from sqlalchemy.orm import Session, joinedload from sqlalchemy import select, func from typing import List, Optional, Dict, Any import ulid import random from app.models.RepairErpModel import CrmCustomerDevice, CrmRepairTicket from app.models.CrmModel import CrmCustomer from app.schemas.RepairErp import ( CrmCustomerDeviceCreate, CrmRepairTicketCreate, CrmRepairTicketUpdateStage, CrmRepairTicketUpdateChecklist, CrmRepairTicketUpdateEstimate, CrmRepairTicketAssignTechnician ) from app.core.events.event_publisher import publish_business_event class RepairErpService: def __init__(self, db: Session, tenant_id: str = "tenant_default"): self.db = db self.tenant_id = tenant_id # --- DEVICE REGISTRATION & IMEI LOOKUP --- def register_device(self, data: CrmCustomerDeviceCreate) -> CrmCustomerDevice: device = CrmCustomerDevice( device_id=str(ulid.ULID()), tenant_id=self.tenant_id, customer_id=data.customer_id, brand=data.brand, model_name=data.model_name, color=data.color, imei_serial=data.imei_serial, cosmetic_condition=data.cosmetic_condition, notes=data.notes ) self.db.add(device) self.db.commit() self.db.refresh(device) return device def lookup_by_imei(self, imei_serial: str) -> Optional[CrmCustomerDevice]: stmt = select(CrmCustomerDevice).where( CrmCustomerDevice.imei_serial == imei_serial, CrmCustomerDevice.tenant_id == self.tenant_id, CrmCustomerDevice.deleted_at.is_(None) ) return self.db.execute(stmt).scalar_one_or_none() def list_customer_devices(self, customer_id: str) -> List[CrmCustomerDevice]: stmt = select(CrmCustomerDevice).where( CrmCustomerDevice.customer_id == customer_id, CrmCustomerDevice.tenant_id == self.tenant_id, CrmCustomerDevice.deleted_at.is_(None) ) return list(self.db.execute(stmt).scalars().all()) # --- REPAIR TICKET LIFECYCLE --- def create_ticket(self, data: CrmRepairTicketCreate) -> CrmRepairTicket: random_num = random.randint(1000, 9999) ticket_number = f"IFK-REP-{random_num}" ticket = CrmRepairTicket( ticket_id=str(ulid.ULID()), ticket_number=ticket_number, tenant_id=self.tenant_id, customer_id=data.customer_id, device_id=data.device_id, assigned_technician_id=data.assigned_technician_id, stage="RECEIVED", issue_description=data.issue_description, is_warranty_claim=data.is_warranty_claim or False, notes=data.notes ) self.db.add(ticket) # Increment customer repair count stmt_cust = select(CrmCustomer).where(CrmCustomer.customer_id == data.customer_id, CrmCustomer.tenant_id == self.tenant_id) cust = self.db.execute(stmt_cust).scalar_one_or_none() if cust: cust.total_repairs_count += 1 if cust.total_orders_count > 0: cust.is_dual_customer = True if cust.total_repairs_count >= 5 or cust.is_dual_customer: cust.service_tier = "VIP" self.db.commit() self.db.refresh(ticket) publish_business_event( event_type="REPAIR_TICKET_CREATED", payload={"ticket_id": ticket.ticket_id, "ticket_number": ticket.ticket_number, "stage": ticket.stage}, tenant_id=self.tenant_id, aggregate_id=ticket.ticket_id ) return ticket def _enrich_ticket(self, t: Optional[CrmRepairTicket]) -> Optional[CrmRepairTicket]: if not t: return None t.status = t.stage t.problem_description = t.issue_description t.priority = "NORMAL" if getattr(t, "customer", None): t.customer_name = getattr(t.customer, "name", None) or getattr(t.customer, "first_name", "") or "Customer" t.customer_phone = getattr(t.customer, "phone", "") or "" if getattr(t, "device", None): t.brand_name = getattr(t.device, "brand", "") or "" t.model_name = getattr(t.device, "model_name", "") or "" t.imei_serial = getattr(t.device, "imei_serial", "") or "" return t def get_ticket(self, ticket_id: str) -> Optional[CrmRepairTicket]: stmt = ( select(CrmRepairTicket) .options(joinedload(CrmRepairTicket.customer), joinedload(CrmRepairTicket.device)) .where( CrmRepairTicket.ticket_id == ticket_id, CrmRepairTicket.tenant_id == self.tenant_id, CrmRepairTicket.deleted_at.is_(None) ) ) ticket = self.db.execute(stmt).scalar_one_or_none() if ticket and ticket.assigned_technician_id: from app.models.UserModel import User tech_user = self.db.query(User).filter(User.user_id == ticket.assigned_technician_id).first() if tech_user: ticket.assigned_technician_name = (tech_user.display_name or f"{tech_user.first_name} {tech_user.last_name}").strip() return self._enrich_ticket(ticket) def list_tickets(self, skip: int = 0, limit: int = 50, stage: Optional[str] = None, technician_id: Optional[str] = None) -> List[CrmRepairTicket]: stmt = ( select(CrmRepairTicket) .options(joinedload(CrmRepairTicket.customer), joinedload(CrmRepairTicket.device)) .where( CrmRepairTicket.tenant_id == self.tenant_id, CrmRepairTicket.deleted_at.is_(None) ) ) if stage: stmt = stmt.where(CrmRepairTicket.stage == stage) if technician_id: stmt = stmt.where(CrmRepairTicket.assigned_technician_id == technician_id) stmt = stmt.offset(skip).limit(limit).order_by(CrmRepairTicket.created_at.desc()) tickets = list(self.db.execute(stmt).scalars().all()) tech_ids = {t.assigned_technician_id for t in tickets if t.assigned_technician_id} tech_map = {} if tech_ids: from app.models.UserModel import User tech_users = self.db.query(User).filter(User.user_id.in_(tech_ids)).all() tech_map = { u.user_id: (u.display_name or f"{u.first_name} {u.last_name}").strip() for u in tech_users } for t in tickets: self._enrich_ticket(t) if t.assigned_technician_id: t.assigned_technician_name = tech_map.get(t.assigned_technician_id) return tickets def update_stage(self, ticket_id: str, data: CrmRepairTicketUpdateStage) -> Optional[CrmRepairTicket]: ticket = self.get_ticket(ticket_id) if not ticket: return None old_stage = ticket.stage ticket.stage = data.stage if data.notes: ticket.notes = data.notes self.db.commit() self.db.refresh(ticket) publish_business_event( event_type="REPAIR_STAGE_CHANGED", payload={"ticket_id": ticket.ticket_id, "old_stage": old_stage, "new_stage": ticket.stage}, tenant_id=self.tenant_id, aggregate_id=ticket.ticket_id ) return ticket def update_checklists(self, ticket_id: str, data: CrmRepairTicketUpdateChecklist) -> Optional[CrmRepairTicket]: ticket = self.get_ticket(ticket_id) if not ticket: return None if data.diagnostic_checklist_json is not None: ticket.diagnostic_checklist_json = data.diagnostic_checklist_json if data.qc_checklist_json is not None: ticket.qc_checklist_json = data.qc_checklist_json self.db.commit() self.db.refresh(ticket) return ticket def assign_technician(self, ticket_id: str, data: CrmRepairTicketAssignTechnician) -> Optional[CrmRepairTicket]: ticket = self.get_ticket(ticket_id) if not ticket: return None ticket.assigned_technician_id = data.assigned_technician_id self.db.commit() self.db.refresh(ticket) return ticket