from abc import ABC, abstractmethod from typing import Optional, Tuple from sqlalchemy import and_, delete, func, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import place_channels, place_facts, place_photos, places, place_units, sites from common.enums import ErrorType from common.logger import LOG from common.utils.gtime import GTime # 사업장 CRUD. class IPlaceCRUD(ABC): @abstractmethod async def add_place(self, cdb: AsyncSession, place: places) -> ErrorType: pass @abstractmethod async def get_place(self, cdb: AsyncSession, owner_user_id, place_id) -> Tuple[ErrorType, places]: pass @abstractmethod async def list_places(self, cdb: AsyncSession, owner_user_id, search, category, status, skip, limit) -> Tuple[ErrorType, list, int]: pass @abstractmethod async def update_place(self, cdb: AsyncSession, owner_user_id, place_id, data: dict) -> Tuple[ErrorType, int]: pass @abstractmethod async def delete_place(self, cdb: AsyncSession, owner_user_id, place_id) -> Tuple[ErrorType, int]: pass @abstractmethod async def list_units(self, cdb: AsyncSession, place_id) -> Tuple[ErrorType, list]: pass @abstractmethod async def get_unit(self, cdb: AsyncSession, place_id, unit_id) -> Tuple[ErrorType, place_units]: pass @abstractmethod async def add_unit(self, cdb: AsyncSession, unit: place_units) -> ErrorType: pass @abstractmethod async def list_links(self, cdb: AsyncSession, place_id, confirmed_only: bool) -> Tuple[ErrorType, list]: pass @abstractmethod async def add_link(self, cdb: AsyncSession, link: place_channels) -> ErrorType: pass @abstractmethod async def confirm_link(self, cdb: AsyncSession, place_id, link_id, user_id, ts) -> Tuple[ErrorType, int]: pass async def confirm_link_by_url(self, cdb: AsyncSession, place_id, url, user_id, ts) -> Tuple[ErrorType, int]: pass @abstractmethod async def set_link_raw(self, cdb: AsyncSession, place_id, url, raw) -> Tuple[ErrorType, int]: pass @abstractmethod async def find_by_external(self, cdb: AsyncSession, owner_user_id, source, external_place_id) -> Tuple[ErrorType, list]: pass class PlaceCRUD(IPlaceCRUD): async def add_place(self, cdb: AsyncSession, place: places) -> ErrorType: try: return await DB_SESSION_MNG.insert(cdb, place) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED async def get_place(self, cdb: AsyncSession, owner_user_id, place_id) -> Tuple[ErrorType, places]: try: query = ( select(places) .where(places.place_id == place_id, places.owner_user_id == owner_user_id, places.deleted == False) # noqa: E712 .limit(1) ) err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) if err_type != ErrorType.SUCCESS: return err_type, None if len(row_list) != 1: return ErrorType.DB_INVALID_KEY, None return ErrorType.SUCCESS, row_list[0] except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, None async def find_by_external(self, cdb: AsyncSession, owner_user_id, source, external_place_id) -> Tuple[ErrorType, list]: """같은 사장님이 **이미 갖고 있는** 같은 외부 업소.""" try: def _count(model): return ( select(func.count()) .select_from(model) .where(model.place_id == places.place_id, model.deleted == False) # noqa: E712 .scalar_subquery() ) weight = _count(place_facts) + _count(place_units) + _count(place_photos) + _count(sites) query = ( select(places) .where( places.owner_user_id == owner_user_id, places.external_source == source, places.external_place_id == str(external_place_id), places.deleted == False, # noqa: E712 ) .order_by(weight.desc(), places.created_at.asc()) ) return await DB_SESSION_MNG.execute(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, [] async def list_places( self, cdb: AsyncSession, owner_user_id, search: Optional[str], category: Optional[int], status: Optional[int], skip: int, limit: int, ) -> Tuple[ErrorType, list, int]: try: conditions = [places.deleted == False, places.owner_user_id == owner_user_id] # noqa: E712 if category is not None: conditions.append(places.category == category) if status is not None: conditions.append(places.status == status) if search: conditions.append( or_( places.name.ilike(f"%{search}%"), places.road_address.ilike(f"%{search}%"), places.address.ilike(f"%{search}%"), ) ) where = and_(*conditions) cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(places).where(where)) if cnt_err != ErrorType.SUCCESS: return cnt_err, [], 0 total = int(cnt_rows[0] or 0) if cnt_rows else 0 list_err, rows = await DB_SESSION_MNG.execute( cdb, select(places).where(where).order_by(places.created_at.desc()).offset(skip).limit(limit), ) if list_err != ErrorType.SUCCESS: return list_err, [], 0 return ErrorType.SUCCESS, list(rows), total except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, [], 0 async def update_place(self, cdb: AsyncSession, owner_user_id, place_id, data: dict) -> Tuple[ErrorType, int]: """회사 스코프를 WHERE 에 걸어 남의 회사 사업장을 못 건드리게 한다.""" try: if not data: return ErrorType.SUCCESS, 0 query = ( update(places) .where(places.place_id == place_id, places.owner_user_id == owner_user_id, places.deleted == False) # noqa: E712 .values(**data, updated_at=GTime.UTC()) ) return await DB_SESSION_MNG.add_with_rowcount(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, 0 async def delete_place(self, cdb: AsyncSession, owner_user_id, place_id) -> Tuple[ErrorType, int]: """사업장을 실제 삭제한다.""" try: query = ( delete(places) .where(places.place_id == place_id, places.owner_user_id == owner_user_id, places.deleted == False) # noqa: E712 ) return await DB_SESSION_MNG.add_with_rowcount(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, 0 async def list_units(self, cdb: AsyncSession, place_id) -> Tuple[ErrorType, list]: try: query = ( select(place_units) .where(place_units.place_id == place_id, place_units.deleted == False) # noqa: E712 .order_by(place_units.sort_order.asc(), place_units.created_at.asc()) ) err_type, rows = await DB_SESSION_MNG.execute(cdb, query) return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, [] async def get_unit(self, cdb: AsyncSession, place_id, unit_id) -> Tuple[ErrorType, place_units]: try: query = ( select(place_units) .where(place_units.unit_id == unit_id, place_units.place_id == place_id, place_units.deleted == False) # noqa: E712 .limit(1) ) err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) if err_type != ErrorType.SUCCESS: return err_type, None if len(row_list) != 1: return ErrorType.DB_INVALID_KEY, None return ErrorType.SUCCESS, row_list[0] except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, None async def add_unit(self, cdb: AsyncSession, unit: place_units) -> ErrorType: try: return await DB_SESSION_MNG.insert(cdb, unit) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED async def list_links(self, cdb: AsyncSession, place_id, confirmed_only: bool = False) -> Tuple[ErrorType, list]: """채널 URL 목록.""" try: conditions = [place_channels.place_id == place_id, place_channels.deleted == False] # noqa: E712 if confirmed_only: conditions.append(place_channels.confirmed_at.is_not(None)) query = select(place_channels).where(and_(*conditions)).order_by(place_channels.discovered_at.asc()) err_type, rows = await DB_SESSION_MNG.execute(cdb, query) return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, [] async def add_link(self, cdb: AsyncSession, link: place_channels) -> ErrorType: try: return await DB_SESSION_MNG.insert(cdb, link) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED async def confirm_link_by_url(self, cdb: AsyncSession, place_id, url, user_id, ts) -> Tuple[ErrorType, int]: """URL 로 확정한다 — 방금 넣은 링크의 link_id 를 다시 조회하지 않기 위해서다.""" try: query = ( update(place_channels) .where( place_channels.place_id == place_id, place_channels.url == url, place_channels.confirmed_at.is_(None), place_channels.deleted == False, # noqa: E712 ) .values(confirmed_at=ts, confirmed_by=user_id, updated_at=ts) ) return await DB_SESSION_MNG.add_with_rowcount(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, 0 async def set_link_raw(self, cdb: AsyncSession, place_id, url, raw) -> Tuple[ErrorType, int]: """수집한 원문을 링크에 박제한다.""" try: query = ( update(place_channels) .where( place_channels.place_id == place_id, place_channels.url == url, place_channels.deleted == False, # noqa: E712 ) .values(raw=raw, updated_at=GTime.UTC()) ) return await DB_SESSION_MNG.add_with_rowcount(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, 0 async def confirm_link(self, cdb: AsyncSession, place_id, link_id, user_id, ts) -> Tuple[ErrorType, int]: """미확정 링크만 확정한다(이미 확정된 건 rowcount 0 — 동시 처리 가드).""" try: query = ( update(place_channels) .where( place_channels.link_id == link_id, place_channels.place_id == place_id, place_channels.confirmed_at.is_(None), place_channels.deleted == False, # noqa: E712 ) .values(confirmed_at=ts, confirmed_by=user_id, updated_at=ts) ) return await DB_SESSION_MNG.add_with_rowcount(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, 0