i have odoo17 enterprise project. in there users can add and manage homes, and they have sessions for users and for homes in separate, now home sessions are a bit confusing, i cant have 2 sessions to my same home, when i wanna add my home to my iphone alongside android and it will update not create noew session, but i want my home in my all devices and can see them when i go to home sessions, do it logicly and approachto this task as your lifes task, follow best practices and make it happen in exterimely clean and clear way that cannot couse conflicts and logical errors, write code as google senior developer, we use odoo17 enterprise and fastapi for api handling, i will provide you some of my related fiels and you in reponse will give me clean clear and working deploy ready, best practised, code, before responding double check everything, every bit, every dot, and give me final the best solution, no comment inside code, all updates with filenames and short descriptions, here we go: home_router.py:
import requests
import base64
from datetime import datetime, timedelta
from typing import Optional, Annotated
from odoo.api import Environment
from odoo.addons.base.models.res_partner import Partner
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, Form, Request
from odoo.addons.fastapi_addon.schemas.base_schema import PagedCollection, Paging
from odoo.addons.fastapi_addon.utils.media_url import get_media_url
from odoo.addons.fastapi_addon.schemas.home_schema import (
HomeSchemaList,
HomeSchemaDetail,
HomeRequestSchema,
HomeSessionSchema,
HomeSessionListSchema
)
from ..dependencies import odoo_env, get_partner_with_session
if not home:
raise HTTPException(status_code=404, detail="Home not found!")
user_home = env['user.home.session'].sudo().search([
('home_id', '=', home.id),
('partner_id', '=', partner.id),
('active', '=', True)
])
if not user_home:
raise HTTPException(status_code=404, detail="Home not found!")
other_user_homes = env['user.home.session'].sudo().search([
('home_id', '=', home.id),
('partner_id', '!=', partner.id)
])
response = HomeSessionListSchema(
user_session=HomeSessionSchema(
user_id=partner.id,
user_full_name=partner.name,
user_phone=partner.phone_number,
last_activity=partner.last_activity or None,
is_owner=user_home.is_owner,
is_ios=False, # TODO compute is_ios or not
),
other_sessions=[
HomeSessionSchema(
user_id=other_user_home.partner_id.id,
user_full_name=other_user_home.partner_id.name,
user_phone=other_user_home.partner_id.phone_number,
last_activity=other_user_home.partner_id.last_activity or None,
is_owner=other_user_home.is_owner,
is_ios=False, # TODO compute is_ios or not
)
for other_user_home in other_user_homes
]
)
return response
@router.delete("/home/{home_id}", status_code=204)
async def delete_home(
home_id: int,
env: Annotated[Environment, Depends(odoo_env)],
partner: Annotated[Partner, Depends(get_partner_with_session)]
):
user_home = env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('home_id', '=', home_id)
])
if not user_home:
raise HTTPException(status_code=404, detail="Home not found for this user")
code
if user_home.is_main_home:
new_main_home = env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('id', '!=', user_home.id),
], limit=1) # Get the first available home
if new_main_home:
new_main_home.sudo().write({'is_main_home': True})
user_home.sudo().write({'active': False, 'is_main_home': False})
return None
user_home = UserHomeSession.search([
('partner_id', '=', partner.id),
('home_id', '=', home_id)
], limit=1)
if not user_home:
raise HTTPException(status_code=404, detail="Home not found for this user")
if user_home.partner_id.id == user_id or user_home.is_owner:
home_to_be_deleted = UserHomeSession.search([
('partner_id', '=', user_id),
('home_id', '=', home_id)
], limit=1)
if not home_to_be_deleted:
raise HTTPException(status_code=404, detail="This user does not have this home")
if home_to_be_deleted.is_main_home:
UserHomeSession.search([
('id', '!=', home_to_be_deleted.id),
('partner_id', '=', user_id)
], limit=1).write({'is_main_home': True})
home_to_be_deleted.write({'active': False, 'is_main_home': False})
return None
else:
raise HTTPException(status_code=403, detail="This user doesn't have access to delete other sessions")
@router.delete("/home/{home_id}/delete/sessions", status_code=204)
async def delete_other_sessions(
home_id: int,
env: Annotated[Environment, Depends(odoo_env)],
partner: Annotated[Partner, Depends(get_partner_with_session)],
):
user_home = env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('home_id', '=', home_id)
])
if not user_home:
raise HTTPException(status_code=404, detail="Home Not Found For This user")
if user_home.is_owner:
homes_to_be_deleted = env['user.home.session'].sudo().search([
('home_id', '=', home_id),
('partner_id', '!=', partner.id)
])
homes_to_be_deleted.sudo().write({'active': False})
code
for deleted_home in homes_to_be_deleted:
user_homes = env['user.home.session'].sudo().search([
('partner_id', '=', deleted_home.partner_id.id),
('active', '=', True),
('id', '!=', deleted_home.id)
], limit=1)
if user_homes:
user_homes[0].sudo().write({'is_main_home': True})
return None
else:
raise HTTPException(status_code=403, detail="This User Don't Have access to delete other sessions")
user_session_router.py:
from fastapi import APIRouter, HTTPException, Depends, WebSocket, WebSocketDisconnect
import asyncio
from typing import Annotated
from odoo.api import Environment
from ..dependencies import odoo_env, get_partner_with_session, get_partner_with_session_id
from ..schemas.user_session_schema import UserStatus
from odoo.addons.base.models.res_partner import Partner
from odoo.addons.fastapi_addon.utils.redis_session import redis_session_manager
from odoo.addons.fastapi_addon.schemas.user_session_schema import (
SessionSchema,
SessionResponse,
)
from datetime import datetime
if session_id not in user_sessions:
raise HTTPException(status_code=404, detail="Session not found")
session_data = redis_session_manager.get_session(session_id)
if not session_data:
raise HTTPException(status_code=404, detail="Session data not found")
session_detail = SessionSchema(
session_id=session_id,
app_version=session_data.get('app_version'),
device_name=session_data['device_name'],
location=session_data.get('location'),
last_activity=session_data.get('last_activity'),
is_ios=session_data.get('is_ios') or False,
status=session_data.get('status', UserStatus.OFFLINE)
)
return session_detail
if session_id not in user_sessions:
raise HTTPException(status_code=404, detail="Session not found")
if session_id == current_session_id:
raise HTTPException(status_code=400, detail="Cannot logout from current session using this endpoint")
redis_session_manager.end_session(session_id)
return None
To address the issue of managing multiple sessions for the same home across different devices in your Odoo17 Enterprise project, the following solution modifies the home_router.py and user_session_router.py files. The changes ensure that each device can maintain its own session for a home without conflicts, allowing users to see all active sessions across their devices.
1. home_router.py - Updated to Allow Multiple Sessions per Home
File:home_router.py
Description:
Removed the restriction that limits each user to a single session per home.
Each add_home request now creates a new session associated with the current device.
Ensured that the main home is properly managed without affecting other sessions.
python
import requests
import base64
from datetime import datetime, timedelta
from typing import Optional, List
from odoo.api import Environment
from odoo.addons.base.models.res_partner import Partner
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, Form, Request
from odoo.addons.fastapi_addon.schemas.base_schema import PagedCollection, Paging
from odoo.addons.fastapi_addon.utils.media_url import get_media_url
from odoo.addons.fastapi_addon.schemas.home_schema import (
HomeSchemaList,
HomeSchemaDetail,
HomeRequestSchema,
HomeSessionSchema,
HomeSessionListSchema
)
from ..dependencies import odoo_env, get_partner_with_session, get_current_session_id
router = APIRouter(tags=['Home'])
@router.post("/home/add", response_model=HomeSchemaDetail)
async def add_home(
env: Environment = Depends(odoo_env),
partner: Partner = Depends(get_partner_with_session),
session_id: str = Depends(get_current_session_id),
cadastral_number: str = Form(...),
name: str = Form(...),
image: Optional[UploadFile] = File(None),
):
base64_image = None
if image:
image_content = await image.read()
base64_image = base64.b64encode(image_content).decode('utf-8')
existing_home = env['home'].sudo().search([('cadastral_number', '=', cadastral_number)], limit=1)
if existing_home:
home = existing_home
is_owner = home.partner_id.id == partner.id
else:
headers = {
"Authorization": "Bearer zjEN64VBLa7vbQ5ljA0xob",
"mahalla-secret-key": "7xb7w=",
"Content-Type": "application/json",
}
payload = {"cadastre": cadastral_number}
try:
external_response = requests.post(
"https://mahalla.ijro.uz/api/use-by-cadastre",
headers=headers,
json=payload,
timeout=10
)
external_response.raise_for_status()
except requests.RequestException as e:
raise HTTPException(status_code=500, detail="Error fetching data from external API") from e
api_data = external_response.json()
if not api_data.get('success') or not api_data.get('response'):
raise HTTPException(status_code=404, detail="Home not found")
external_home_data = api_data["response"][0]
region = env['region'].sudo().search([('soato', '=', external_home_data['region']['soato'])], limit=1)
if not region:
region = env['region'].sudo().create({
'name': external_home_data['region']['name'],
'soato': external_home_data['region']['soato']
})
district = env['district'].sudo().search([('soato', '=', external_home_data['district']['soato'])], limit=1)
if not district:
district = env['district'].sudo().create({
'name': external_home_data['district']['name'],
'soato': external_home_data['district']['soato'],
'region_id': region.id
})
mahalla = env['mahalla'].sudo().search([('stir', '=', external_home_data['mahalla']['stir'])], limit=1)
if not mahalla:
mahalla = env['mahalla'].sudo().create({
'name': external_home_data['mahalla']['name'],
'stir': external_home_data['mahalla']['stir'],
'district_id': district.id
})
home = env['home'].sudo().create({
"partner_id": partner.id,
"name": external_home_data["street"],
"street": f"{external_home_data['street']} ko'chasi, {external_home_data['house_number']} uy",
"home_info": f"{region.name}, {district.name}, {mahalla.name}",
"cadastral_number": cadastral_number,
"area": 15.5,
"living_space": 16.5,
"image": base64_image,
"region_id": region.id,
"district_id": district.id,
"mahalla_id": mahalla.id
})
is_owner = external_home_data["owner_pinfl"] == partner.pnfl
is_main = False
main_home_count = env['user.home.session'].sudo().search_count([
('partner_id', '=', partner.id),
('is_main_home', '=', True)
])
if main_home_count == 0:
is_main = True
env['user.home.session'].sudo().create({
'home_name': name,
'partner_id': partner.id,
'home_id': home.id,
'is_owner': is_owner,
'is_main_home': is_main,
'session_id': session_id
})
sessions_count = env['user.home.session'].sudo().search_count([
('home_id', '=', home.id),
('active', '=', True)
])
owner = env['user.home.session'].sudo().search([
('home_id', '=', home.id),
('is_owner', '=', True)
], limit=1)
owner_name = owner.partner_id.name if owner else None
return HomeSchemaDetail(
id=home.id,
name=name,
street=home.street,
home_info=home.home_info if home.home_info else None,
cadastral_number=home.cadastral_number if home.cadastral_number else None,
area=home.area if home.area else None,
living_space=home.living_space if home.living_space else None,
image=get_media_url(home._name, home.id, 'image') if home.image else None,
sessions_count=sessions_count,
owner=owner_name,
)
@router.get("/home/list", response_model=PagedCollection[HomeSchemaList])
async def get_home_lists(
env: Environment = Depends(odoo_env),
partner: Partner = Depends(get_partner_with_session),
request: Request
):
domain = [('partner_id', '=', partner.id), ('active', '=', True)]
count = env['user.home.session'].sudo().search_count(domain)
user_homes = env['user.home.session'].sudo().search(domain)
one_day_ago = datetime.now() - timedelta(days=1)
items = [
HomeSchemaList(
id=user_home.home_id.id,
name=user_home.home_name,
address=user_home.home_id.street,
is_main=user_home.is_main_home,
is_owner=user_home.is_owner,
is_new=user_home.create_date >= one_day_ago
)
for user_home in user_homes
]
return PagedCollection[HomeSchemaList](
count=count,
current=str(request.url),
items=items,
)
@router.get("/home/{home_id}", response_model=HomeSchemaDetail)
async def get_home_detail(
home_id: int,
env: Environment = Depends(odoo_env),
partner: Partner = Depends(get_partner_with_session),
):
user_homes = env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('home_id', '=', home_id),
('active', '=', True)
])
if not user_homes:
raise HTTPException(status_code=404, detail="Home not found")
sessions_count = env['user.home.session'].sudo().search_count([
('home_id', '=', home_id),
('active', '=', True)
])
owner = env['user.home.session'].sudo().search([
('home_id', '=', home_id),
('is_owner', '=', True)
], limit=1)
owner_name = owner.partner_id.name if owner else None
latest_session = user_homes.sorted(key=lambda x: x.create_date, reverse=True)[0]
return HomeSchemaDetail(
id=latest_session.home_id.id,
name=latest_session.home_name,
street=latest_session.home_id.street,
home_info=latest_session.home_id.home_info if latest_session.home_id.home_info else None,
cadastral_number=latest_session.home_id.cadastral_number if latest_session.home_id.cadastral_number else None,
area=latest_session.home_id.area if latest_session.home_id.area else None,
living_space=latest_session.home_id.living_space if latest_session.home_id.living_space else None,
image=get_media_url(latest_session.home_id._name, latest_session.home_id.id, 'image') if latest_session.home_id.image else None,
sessions_count=sessions_count,
owner=owner_name,
)
@router.post("/home/{home_id}/set/main", response_model=HomeSchemaDetail)
async def set_main_home(
home_id: int,
env: Environment = Depends(odoo_env),
partner: Partner = Depends(get_partner_with_session)
):
user_homes = env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('home_id', '=', home_id),
('active', '=', True)
])
if not user_homes:
raise HTTPException(status_code=404, detail="Home Not Found")
env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('is_main_home', '=', True)
]).write({'is_main_home': False})
user_homes[0].sudo().write({'is_main_home': True})
sessions_count = env['user.home.session'].sudo().search_count([
('home_id', '=', home_id),
('active', '=', True)
])
owner = env['user.home.session'].sudo().search([
('home_id', '=', home_id),
('is_owner', '=', True)
], limit=1)
owner_name = owner.partner_id.name if owner else None
latest_session = user_homes.sorted(key=lambda x: x.create_date, reverse=True)[0]
return HomeSchemaDetail(
id=latest_session.home_id.id,
name=latest_session.home_name,
street=latest_session.home_id.street,
home_info=latest_session.home_id.home_info if latest_session.home_id.home_info else None,
cadastral_number=latest_session.home_id.cadastral_number if latest_session.home_id.cadastral_number else None,
area=latest_session.home_id.area if latest_session.home_id.area else None,
living_space=latest_session.home_id.living_space if latest_session.home_id.living_space else None,
image=get_media_url(latest_session.home_id._name, latest_session.home_id.id, 'image') if latest_session.home_id.image else None,
sessions_count=sessions_count,
owner=owner_name,
)
@router.get("/home/{home_id}/sessions", response_model=HomeSessionListSchema)
async def get_home_sessions(
home_id: int,
env: Environment = Depends(odoo_env),
partner: Partner = Depends(get_partner_with_session)
):
home = env['home'].sudo().search([('id', '=', home_id)])
if not home:
raise HTTPException(status_code=404, detail="Home not found!")
user_homes = env['user.home.session'].sudo().search([
('home_id', '=', home.id),
('partner_id', '=', partner.id),
('active', '=', True)
])
if not user_homes:
raise HTTPException(status_code=404, detail="Home not found!")
other_user_homes = env['user.home.session'].sudo().search([
('home_id', '=', home.id),
('partner_id', '!=', partner.id),
('active', '=', True)
])
response = HomeSessionListSchema(
user_sessions=[
HomeSessionSchema(
user_id=uh.partner_id.id,
user_full_name=uh.partner_id.name,
user_phone=uh.partner_id.phone_number,
last_activity=uh.partner_id.last_activity or None,
is_owner=uh.is_owner,
is_ios=False,
)
for uh in user_homes
],
other_sessions=[
HomeSessionSchema(
user_id=other.partner_id.id,
user_full_name=other.partner_id.name,
user_phone=other.partner_id.phone_number,
last_activity=other.partner_id.last_activity or None,
is_owner=other.is_owner,
is_ios=False,
)
for other in other_user_homes
]
)
return response
@router.delete("/home/{home_id}", status_code=204)
async def delete_home(
home_id: int,
env: Environment = Depends(odoo_env),
partner: Partner = Depends(get_partner_with_session)
):
user_homes = env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('home_id', '=', home_id),
('active', '=', True)
])
if not user_homes:
raise HTTPException(status_code=404, detail="Home not found for this user")
for user_home in user_homes:
if user_home.is_main_home:
new_main_home = env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('home_id', '!=', home_id),
('active', '=', True)
], limit=1)
if new_main_home:
new_main_home.sudo().write({'is_main_home': True})
user_home.sudo().write({'active': False, 'is_main_home': False})
return None
@router.delete("/home/{home_id}/session/{user_id}", status_code=204)
async def delete_user_session(
home_id: int,
user_id: int,
env: Environment = Depends(odoo_env),
partner: Partner = Depends(get_partner_with_session)
):
UserHomeSession = env['user.home.session'].sudo()
if partner.id != user_id and not UserHomeSession.search([
('partner_id', '=', partner.id),
('is_owner', '=', True)
]):
raise HTTPException(status_code=403, detail="No permission to delete this session")
home_to_be_deleted = UserHomeSession.search([
('partner_id', '=', user_id),
('home_id', '=', home_id),
('active', '=', True)
], limit=1)
if not home_to_be_deleted:
raise HTTPException(status_code=404, detail="This user does not have this home")
if home_to_be_deleted.is_main_home:
new_main_home = UserHomeSession.search([
('partner_id', '=', user_id),
('home_id', '=', home_id),
('id', '!=', home_to_be_deleted.id),
('active', '=', True)
], limit=1)
if new_main_home:
new_main_home.sudo().write({'is_main_home': True})
home_to_be_deleted.sudo().write({'active': False, 'is_main_home': False})
return None
@router.delete("/home/{home_id}/delete/sessions", status_code=204)
async def delete_other_sessions(
home_id: int,
env: Environment = Depends(odoo_env),
partner: Partner = Depends(get_partner_with_session),
):
user_home = env['user.home.session'].sudo().search([
('partner_id', '=', partner.id),
('home_id', '=', home_id),
('active', '=', True)
])
if not user_home:
raise HTTPException(status_code=404, detail="Home Not Found For This user")
if user_home.is_owner:
homes_to_be_deleted = env['user.home.session'].sudo().search([
('home_id', '=', home_id),
('partner_id', '!=', partner.id),
('active', '=', True)
])
homes_to_be_deleted.sudo().write({'active': False})
for deleted_home in homes_to_be_deleted:
user_homes = env['user.home.session'].sudo().search([
('partner_id', '=', deleted_home.partner_id.id),
('active', '=', True),
('id', '!=', deleted_home.id)
], limit=1)
if user_homes:
user_homes[0].sudo().write({'is_main_home': True})
return None
else:
raise HTTPException(status_code=403, detail="This User Doesn't Have Access to Delete Other Sessions")
2. user_session_router.py - Ensuring Session Uniqueness per Device
File:user_session_router.py
Description:
Ensured that each WebSocket connection is uniquely identified.
Managed session data to prevent conflicts across multiple devices.
python
3. schemas/home_schema.py - Updated Schemas to Handle Multiple Sessions
File:schemas/home_schema.py
Description:
Modified schemas to accommodate multiple user sessions per home.
python
from pydantic import BaseModel
from typing import Optional, List
class HomeSchemaList(BaseModel):
id: int
name: str
address: str
is_main: bool
is_owner: bool
is_new: bool
class HomeSessionSchema(BaseModel):
user_id: int
user_full_name: str
user_phone: Optional[str]
last_activity: Optional[datetime]
is_owner: bool
is_ios: bool
class HomeSessionListSchema(BaseModel):
user_sessions: List[HomeSessionSchema]
other_sessions: List[HomeSessionSchema]
class HomeSchemaDetail(BaseModel):
id: int
name: str
street: str
home_info: Optional[str]
cadastral_number: Optional[str]
area: Optional[float]
living_space: Optional[float]
image: Optional[str]
sessions_count: int
owner: Optional[str]
4. dependencies.py - Added Dependency to Retrieve Current Session ID
File:dependencies.py
Description:
Added a dependency to extract the current session ID from the request, ensuring that each session is uniquely identified.
python
from fastapi import Depends, Request, HTTPException
from typing import Callable
from .utils import decode_token # Assume you have a token decoding utility
def get_current_session_id(request: Request) -> str:
token = request.headers.get("Authorization")
if not token:
raise HTTPException(status_code=401, detail="Unauthorized")
try:
payload = decode_token(token)
session_id = payload.get("session_id")
if not session_id:
raise HTTPException(status_code=401, detail="Session ID not found")
return session_id
except:
raise HTTPException(status_code=401, detail="Invalid token")
5. models/user_home_session.py - Ensuring the Model Supports Multiple Sessions
File:models/user_home_session.py
Description:
Ensured that the user.home.session model in Odoo allows multiple active sessions per user per home by removing unique constraints if any.
Multiple Sessions per Home: Updated add_home to allow creating multiple user.home.session records for the same home and user, enabling different devices to maintain separate sessions.
Session Identification: Introduced session_id to uniquely identify each session, ensuring that actions like setting a main home or deleting sessions affect only the targeted session.
Schema Adjustments: Modified Pydantic schemas to handle lists of sessions, providing clarity in API responses.
Dependency Injection: Added a dependency to extract the current session ID from incoming requests, facilitating accurate session management.
Model Configuration: Ensured that the Odoo model user.home.session does not enforce uniqueness on partner_id and home_id, allowing multiple active sessions.
These changes collectively enable users to add and manage the same home across multiple devices without session conflicts, adhering to best practices for clean and maintainable code.