| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- # app/services/agency_service.py
- import uuid
- from typing import List, Optional
- from sqlalchemy.ext.asyncio import AsyncSession
- from sqlalchemy import select
- from app.models.agency import VasAgency
- from app.schemas.agency import VasAgencyCreate, VasAgencyUpdate
- from app.core.biz_exception import NotFoundError, BizLogicError
- from app.utils.pagination import paginate
- class AgencyService:
- @staticmethod
- async def create(db: AsyncSession, data: VasAgencyCreate) -> VasAgency:
- # 检查重名
- stmt = select(VasAgency).where(VasAgency.name == data.name)
- existing = (await db.execute(stmt)).scalar_one_or_none()
- if existing:
- raise BizLogicError(f"中介名称 '{data.name}' 已存在")
- agency_id = data.id or f"AG-{uuid.uuid4().hex[:8].upper()}"
- agency = VasAgency(
- id=agency_id,
- name=data.name,
- contact_name=data.contact_name,
- contact_phone=data.contact_phone,
- owner_id=data.owner_id,
- min_floor_price=data.min_floor_price,
- notes=data.notes,
- )
- db.add(agency)
- await db.commit()
- await db.refresh(agency)
- return agency
- @staticmethod
- async def get(db: AsyncSession, agency_id: str) -> Optional[VasAgency]:
- stmt = select(VasAgency).where(VasAgency.id == agency_id)
- return (await db.execute(stmt)).scalar_one_or_none()
- @staticmethod
- async def update(db: AsyncSession, agency_id: str, data: VasAgencyUpdate) -> VasAgency:
- agency = await AgencyService.get(db, agency_id)
- if not agency:
- raise NotFoundError("合作中介机构不存在")
- update_dict = data.dict(exclude_unset=True)
- for key, value in update_dict.items():
- setattr(agency, key, value)
- await db.commit()
- await db.refresh(agency)
- return agency
- @staticmethod
- async def list_all(db: AsyncSession, page: int = 0, size: int = 20, active_only: bool = False):
- stmt = select(VasAgency)
- if active_only:
- stmt = stmt.where(VasAgency.status == 1)
- stmt = stmt.order_by(VasAgency.created_at.desc())
- return await paginate(db, stmt, page, size)
|