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

router = APIRouter(tags=['Home'])


@router.post("/home/add", response_model=HomeSchemaDetail)
async def add_home(
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)],
        cadastral_number: str = Form(...),
        name: str = Form(...),
        image: Optional[UploadFile] = File(None),
):
    base64_image = None

    if image:
        image_object_content = await image.read()
        base64_image = base64.b64encode(image_object_content).decode('utf-8')

    # Check if a home with this cadastral number already exists
    existing_home = env['home'].sudo().search([('cadastral_number', '=', cadastral_number)], limit=1)

    if existing_home:
        # Use the existing home record
        home = existing_home
        # Check ownership based on the current partner
        is_owner = home.partner_id.id == partner.id
    else:
        # Fetch data from external API if creating a new Home record
        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 len(api_data.get('response', [])) == 0:
            raise HTTPException(status_code=404, detail="Home not found")

        if api_data.get("success") and api_data.get("response"):
            external_home_data = api_data["response"][0]

            # Retrieve or create Region, District, and Mahalla records
            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
                })

            # Create the home record
            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
            })

            # Check ownership
            is_owner = external_home_data["owner_pinfl"] == partner.pnfl
        else:
            # Create a minimal home record if external data is not found
            home = env['home'].sudo().create({
                "partner_id": partner.id,
                "name": name,
                "street": "Sakkokiy ko'chasi 15 uy",
                "home_info": "15 Uy 3 qavatli",
                "cadastral_number": cadastral_number,
                "area": 15.5,
                "living_space": 16.5,
                "image": base64_image,
            })
            is_owner = (
                True if external_home_data["owner_pinfl"] == partner.pnfl else False
            )

    # Add the user home session details
    user_home = env['user.home.session'].sudo().search([
        ('partner_id', '=', partner.id),
        ('home_id', '=', home.id),
    ], limit=1)


    if not user_home:
        user_home = env['user.home.session'].sudo().search([
            ('partner_id', '=', partner.id),
            ('home_id', '=', home.id),
            ('active', '=', False)
        ], limit=1)
        main_home_count = env['user.home.session'].sudo().search_count([
            ('partner_id', '=', partner.id),
            ('is_main_home', '=', True)
        ])
        if not user_home:
            user_home = env['user.home.session'].sudo().create({
                'home_name': name,
                'partner_id': partner.id,
                'home_id': home.id,
                'is_owner': is_owner,
                'is_main_home': False if main_home_count > 0 else True
            })
        else:
            user_home.sudo().write({
                'active': True,
                'home_name': name,
                'is_main_home': False if main_home_count > 0 else 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

    return HomeSchemaDetail(
        id=home.id,
        name=user_home.home_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: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)],
        request: Request
):
    domain = [('partner_id', '=', partner.id)]
    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=f"{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: 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")

    sessions_count = env['user.home.session'].sudo().search_count([
        ('home_id', '=', home_id),
        ('active', '=', True)
    ])

    # Get owner
    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=user_home.home_id.id,
        name=user_home.home_name,
        street=user_home.home_id.street,
        home_info=user_home.home_id.home_info if user_home.home_id.home_info else None,
        cadastral_number=user_home.home_id.cadastral_number if user_home.home_id.cadastral_number else None,
        area=user_home.home_id.area if user_home.home_id.area else None,
        living_space=user_home.home_id.living_space if user_home.home_id.living_space else None,
        image=get_media_url(user_home.home_id._name, user_home.home_id.id, 'image') if user_home.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: 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")

    env['user.home.session'].sudo().search([
        ('partner_id', '=', partner.id),
        ('is_main_home', '=', True)
    ]).write({'is_main_home': False})

    user_home.sudo().write({'is_main_home': True})
    sessions_count = env['user.home.session'].sudo().search_count([
        ('home_id', '=', home_id),
        ('active', '=', True)
    ])

    # Get owner
    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=user_home.home_id.id,
        name=user_home.home_name,
        street=user_home.home_id.street,
        home_info=user_home.home_id.home_info if user_home.home_id.home_info else None,
        cadastral_number=user_home.home_id.cadastral_number if user_home.home_id.cadastral_number else None,
        area=user_home.home_id.area if user_home.home_id.area else None,
        living_space=user_home.home_id.living_space if user_home.home_id.living_space else None,
        image=get_media_url(user_home.home_id._name, user_home.home_id.id, 'image') if user_home.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: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[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_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")

    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


@router.delete("/home/{home_id}/session/{user_id}", status_code=204)
async def delete_user_session(
        home_id: int,
        user_id: int,
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)]
):
    UserHomeSession = env['user.home.session'].sudo()

    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})

        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

router = APIRouter(tags=['User Session'])


@router.websocket("/ws/{session_id}")
async def websocket_endpoint(
        websocket: WebSocket,
        session_id: str,
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)]
):
    await websocket.accept()
    websocket_id = str(uuid.uuid4())
    redis_session_manager.register_websocket(session_id, websocket_id)

    try:
        while True:
            await websocket.receive_text()
            redis_session_manager.update_last_activity(session_id)

    except WebSocketDisconnect:
        redis_session_manager.unregister_websocket(session_id, websocket_id)
    except Exception as e:
        redis_session_manager.unregister_websocket(session_id, websocket_id)
        await websocket.close()


@router.get("/sessions", response_model=SessionResponse)
async def get_sessions(
    env: Annotated[Environment, Depends(odoo_env)],
    partner: Annotated[Partner, Depends(get_partner_with_session)],
    current_session_id: str = Depends(get_partner_with_session_id)
):
    user_id = partner.id
    session_ids = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")

    current_session_data = redis_session_manager.get_session(current_session_id)
    if not current_session_data:
        raise HTTPException(status_code=404, detail="Current session not found")

    response = SessionResponse(
        current_session=SessionSchema(
            session_id=current_session_id,
            app_version=current_session_data.get('app_version'),
            device_name=current_session_data['device_name'],
            location=current_session_data.get('location'),
            last_activity=current_session_data.get('last_activity'),
            is_ios=current_session_data.get('is_ios') or False,
            status=current_session_data.get('status', UserStatus.OFFLINE)
        ),
        other_sessions=[]
    )

    for session_id in session_ids:
        if session_id != current_session_id:
            session_data = redis_session_manager.get_session(session_id)
            if session_data:
                session_info = 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)
                )
                response.other_sessions.append(session_info)

    return response


@router.get("/session/{session_id}", response_model=SessionSchema)
async def get_session_detail(
        session_id: str,
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)]
):
    user_id = partner.id
    user_sessions = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")

    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



@router.delete("/logout/all-except-current", status_code=204)
async def logout_all_except_current(
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)],
        current_session_id: str = Depends(get_partner_with_session_id)
):
    user_id = partner.id
    user_sessions = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")

    for session_id in user_sessions:
        if session_id != current_session_id:
            redis_session_manager.end_session(session_id)

    return None


@router.delete("/logout/current", status_code=204)
async def logout_current_session(
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)],
        current_session_id: str = Depends(get_partner_with_session_id)
):
    redis_session_manager.end_session(current_session_id)
    return None


@router.delete("/logout/{session_id}", status_code=204)
async def logout_from_session(
        session_id: str,
        env: Annotated[Environment, Depends(odoo_env)],
        partner: Annotated[Partner, Depends(get_partner_with_session)],
        current_session_id: str = Depends(get_partner_with_session_id)
):
    user_id = partner.id
    user_sessions = redis_session_manager.redis.smembers(f"user_sessions:{user_id}")

    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