import uuid from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from app.audit.service import AuditService from app.auth.dependencies import assert_can_view_hq, visible_hq_ids from app.common import master_approval from app.common.enums import FIELD_ROLES, AuditAction, EntityType, MasterApproval from app.common.exceptions import ConflictError, NotFoundError from app.common.master_edit import commit_unique, move_headquarters from app.common.utils import snapshot from app.stockists.models import Stockist from app.stockists.schemas import StockistCreate, StockistUpdate from app.users.models import User, UserExtraHeadquarters _AUDIT_FIELDS = ["headquarters_id", "name", "address", "contact_number", "is_active"] class StockistService: def __init__(self, db: AsyncSession) -> None: self.db = db self.audit = AuditService(db) async def create(self, data: StockistCreate, actor: User, ip: str | None = None) -> Stockist: await assert_can_view_hq(self.db, actor, data.headquarters_id) values = data.model_dump(exclude_unset=True) if "address" not in values and "shop_address" in values: values["address"] = values.pop("shop_address") else: values.pop("shop_address", None) # Added by an MR: it waits for the Area Business Manager. One they were refused is sent again. if actor.role in FIELD_ROLES: twin = await master_approval.rejected_twin( self.db, Stockist, {k: values[k] for k in ("headquarters_id", "name", "address")} ) if twin is not None: await master_approval.resubmit(self.db, twin, values, actor) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.STOCKIST, entity_id=twin.id, action=AuditAction.SUBMIT, after=snapshot(twin, _AUDIT_FIELDS), ip_address=ip, ) await self.db.commit() await self.db.refresh(twin) return twin stockist = Stockist( **values, approval_status=master_approval.initial_status(actor), requested_by_user_id=actor.id if actor.role in FIELD_ROLES else None, ) self.db.add(stockist) try: await self.db.flush() except IntegrityError as exc: await self.db.rollback() raise ConflictError( "A stockist with this name already exists at this address in this headquarters", {"cause": "uq_stockist_hq_name_address"}, ) from exc await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.STOCKIST, entity_id=stockist.id, action=AuditAction.CREATE, after=snapshot(stockist, _AUDIT_FIELDS), ip_address=ip, ) await self.db.commit() await self.db.refresh(stockist) return stockist async def update( self, stockist_id: uuid.UUID, data: StockistUpdate, actor: User, ip: str | None = None ) -> Stockist: stockist = await self.db.get(Stockist, stockist_id) if stockist is None: raise NotFoundError("Stockist not found") await assert_can_view_hq(self.db, actor, stockist.headquarters_id) before = snapshot(stockist, _AUDIT_FIELDS) update_data = data.model_dump(exclude_unset=True) new_hq = update_data.pop("headquarters_id", None) if new_hq is not None: await move_headquarters(self.db, actor, stockist, new_hq) if "shop_address" in update_data and "address" not in update_data: update_data["address"] = update_data.pop("shop_address") else: update_data.pop("shop_address", None) for field, value in update_data.items(): setattr(stockist, field, value) await self.audit.log( actor_user_id=actor.id, entity_type=EntityType.STOCKIST, entity_id=stockist.id, action=AuditAction.UPDATE, before=before, after=snapshot(stockist, _AUDIT_FIELDS), ip_address=ip, ) await commit_unique(self.db, "A stockist with this name already exists at this address in this headquarters") return stockist async def mr_names_by_hq(self, hq_ids: set[uuid.UUID]) -> dict[uuid.UUID, str]: """Stockists are not assigned to one MR: the active MRs / SFEs working each headquarters (their own headquarters or an extra one), comma-joined, by headquarters id.""" if not hq_ids: return {} field = (User.is_active.is_(True), User.role.in_(list(FIELD_ROLES))) primary = select(User.headquarters_id, User.full_name).where(User.headquarters_id.in_(hq_ids), *field) extra = ( select(UserExtraHeadquarters.headquarters_id, User.full_name) .join(User, User.id == UserExtraHeadquarters.user_id) .where(UserExtraHeadquarters.headquarters_id.in_(hq_ids), *field) ) names: dict[uuid.UUID, set[str]] = {} for stmt in (primary, extra): for hq_id, name in (await self.db.execute(stmt)).all(): names.setdefault(hq_id, set()).add(name) return {hq_id: ", ".join(sorted(n)) for hq_id, n in names.items()} async def list_for(self, actor: User) -> list[Stockist]: allowed = await visible_hq_ids(self.db, actor) stmt = ( select(Stockist) .where(Stockist.approval_status == MasterApproval.APPROVED) .order_by(Stockist.name) ) if actor.role in FIELD_ROLES: stmt = stmt.where(Stockist.is_active.is_(True)) if allowed is not None: stmt = stmt.where(Stockist.headquarters_id.in_(allowed or [None])) return list((await self.db.execute(stmt)).scalars().all()) async def requests_for(self, actor: User) -> list[Stockist]: return await master_approval.requests_for(self.db, Stockist, actor) async def review( self, stockist_id: uuid.UUID, approve: bool, reason: str | None, actor: User, ip: str | None = None ) -> Stockist: return await master_approval.review( self.db, Stockist, EntityType.STOCKIST, stockist_id, approve, reason, actor, ip )