From fb1ec060fcf1e4bb0684fad19d37f71e13a83658 Mon Sep 17 00:00:00 2001 From: iFixKart Dev Date: Mon, 9 Nov 2026 15:22:00 +0530 Subject: [PATCH] feat(catalog-service): exclude media keys from attributes, split comma values, sync preset values, and add technician calendar invites --- .gitignore | 1 + app/api/v1/routers/CronRouter.py | 26 + app/api/v1/routers/ServiceJobRouter.py | 189 +++++ app/api/v1/routers/SimulationPaymentRouter.py | 4 +- app/core/database/db_session.py | 16 +- app/models/ServiceModel.py | 2 + app/services/CalendarInviteService.py | 673 ++++++++++++++++++ app/services/NotificationGatewayService.py | 91 ++- app/services/OrderService.py | 71 +- app/services/ServiceJobService.py | 7 + app/services/ServicePaymentService.py | 11 +- app/services/TemplateService.py | 17 +- .../migration_engine/upsert_executor.py | 77 +- scripts/sim/reconcile.py | 216 ++++++ scripts/sim/reset_sim_data.py | 114 +++ scripts/sim/teardown.py | 130 ++++ swarm/agents/__init__.py | 5 + swarm/agents/customer.py | 326 +++++++++ swarm/agents/orchestrator.py | 201 ++++++ swarm/agents/personas.py | 279 ++++++++ swarm/agents/runner.py | 127 ++++ 21 files changed, 2512 insertions(+), 71 deletions(-) create mode 100644 app/services/CalendarInviteService.py create mode 100644 scripts/sim/reconcile.py create mode 100644 scripts/sim/reset_sim_data.py create mode 100644 scripts/sim/teardown.py create mode 100644 swarm/agents/__init__.py create mode 100644 swarm/agents/customer.py create mode 100644 swarm/agents/orchestrator.py create mode 100644 swarm/agents/personas.py create mode 100644 swarm/agents/runner.py diff --git a/.gitignore b/.gitignore index a69d358..393f8f4 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,7 @@ Thumbs.db *.mp4 # Root Scratch, Alter, Test & One-off DB Scripts +ssh_tunnel.py add_location.py add_location_raw.py alter_db.py diff --git a/app/api/v1/routers/CronRouter.py b/app/api/v1/routers/CronRouter.py index 13f793f..4b558ea 100644 --- a/app/api/v1/routers/CronRouter.py +++ b/app/api/v1/routers/CronRouter.py @@ -193,3 +193,29 @@ def trigger_credit_maturity_sweep(db: Session = Depends(get_db)): "message": "Store credit maturity sweep completed", "result": result } + +@router.post("/send-appointment-reminders") +def trigger_appointment_reminders(db: Session = Depends(get_db)): + """ + Sends 2-hour pre-appointment WhatsApp reminders with location & directions + to both walk-in customers and their assigned technicians. + """ + from app.services.CalendarInviteService import CalendarInviteService + result = CalendarInviteService.send_appointment_reminders(db) + return { + "message": "Appointment reminder sweep completed", + "result": result + } + +@router.post("/pending-walkin-tasks-eod") +def trigger_pending_walkin_tasks_eod(db: Session = Depends(get_db)): + """ + Closing time (8:00 PM) audit: checks for pending walk-in repair tasks + and dispatches internal WhatsApp summary to Admin. + """ + from app.services.CalendarInviteService import CalendarInviteService + result = CalendarInviteService.audit_pending_walkin_tasks_eod(db) + return { + "message": "Pending walk-in tasks EOD audit completed", + "result": result + } diff --git a/app/api/v1/routers/ServiceJobRouter.py b/app/api/v1/routers/ServiceJobRouter.py index 3081e0d..8da98bf 100644 --- a/app/api/v1/routers/ServiceJobRouter.py +++ b/app/api/v1/routers/ServiceJobRouter.py @@ -311,11 +311,27 @@ def get_service_job_details( # Fetch job media items media_list = inspection_service.get_job_media(db, job.job_id) + # Fetch latest assignment + from app.models.ServiceModel import ServiceJobAssignment + assignment = ( + db.query(ServiceJobAssignment) + .filter(ServiceJobAssignment.service_job_id == job.job_id) + .order_by(ServiceJobAssignment.assigned_at.desc()) + .first() + ) + assigned_tech_name = None + if assignment: + tech_user = db.query(User).filter(User.user_id == assignment.technician_id).first() + if tech_user: + assigned_tech_name = tech_user.display_name or f"{tech_user.first_name or ''} {tech_user.last_name or ''}".strip() + # Build response payload return { "job_id": job.job_id, "job_no": job.job_no, "status": job.status, + "assigned_technician_id": assignment.technician_id if assignment else None, + "assigned_technician_name": assigned_tech_name, "customer": { "customer_id": job.customer_id, "name": f"{cust.first_name} {cust.last_name}".strip() if cust else "Guest Customer", @@ -390,6 +406,27 @@ def list_service_jobs_admin( "phone": c.phone or "N/A" } + from app.models.ServiceModel import ServiceJobAssignment + job_ids = [j.job_id for j in jobs] + assign_map = {} + if job_ids: + assignments = ( + db.query(ServiceJobAssignment) + .filter(ServiceJobAssignment.service_job_id.in_(job_ids)) + .order_by(ServiceJobAssignment.assigned_at.asc()) + .all() + ) + tech_ids = {a.technician_id for a in assignments} + tech_users = { + u.user_id: (u.display_name or f"{u.first_name or ''} {u.last_name or ''}".strip()) + for u in db.query(User).filter(User.user_id.in_(tech_ids)).all() + } if tech_ids else {} + for a in assignments: + assign_map[a.service_job_id] = { + "technician_id": a.technician_id, + "technician_name": tech_users.get(a.technician_id, "Technician") + } + return [ { "job_id": j.job_id, @@ -399,6 +436,8 @@ def list_service_jobs_admin( "customer_email": cust_map.get(j.customer_id, {}).get("email") or "N/A", "customer_phone": cust_map.get(j.customer_id, {}).get("phone") or "N/A", "status": j.status, + "assigned_technician_id": assign_map.get(j.job_id, {}).get("technician_id"), + "assigned_technician_name": assign_map.get(j.job_id, {}).get("technician_name"), "service_name": j.service_name_snapshot or (j.custom_service_name if j.custom_service_name else (j.service.name if j.service else "Custom Repair")), "base_price": float(j.base_price_snapshot if j.base_price_snapshot is not None else (j.service.base_price if j.service else 0.0)), "device_brand": j.device.brand if j.device else (j.brand_id or "Generic"), @@ -525,6 +564,11 @@ def update_service_job_status_admin( if status == "DELIVERED": WarrantyService.generate_warranty_for_service(db, job.job_id) CreditService.create_pending_credit_for_service(db, job.job_id) + from app.services.CalendarInviteService import CalendarInviteService + try: + CalendarInviteService.complete_walkin_crm_task(db, job.job_id) + except Exception as crm_ex: + print(f"[ServiceJobRouter] Error completing CRM task on repair delivery: {crm_ex}") elif status == "CANCELLED": CreditService.void_pending_credit(db, "SERVICE_JOB", job.job_id, reason="Service job cancelled") @@ -641,3 +685,148 @@ def stream_private_condition_video( raise HTTPException(status_code=404, detail="Video media file missing on server disk") return FileResponse(file_path, media_type=file_record.mime_type or "video/mp4") + + +from pydantic import BaseModel + +class TechnicianAssignPayload(BaseModel): + technician_id: str + reason: Optional[str] = None + + +@router.get("/technicians/active", response_model=List[Dict[str, Any]]) +def list_active_technicians( + current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Store Manager", "Technician"])), + db: Session = Depends(get_db) +): + """Retrieve list of active technicians for assignment.""" + from app.services.CalendarInviteService import CalendarInviteService + return CalendarInviteService.get_active_technicians(db) + + +@router.post("/jobs/{job_id}/assign-technician") +def assign_technician_to_job( + job_id: str, + payload: TechnicianAssignPayload, + current_user: User = Depends(RoleChecker(["Super Admin", "Admin", "Manager", "Store Manager", "Technician"])), + db: Session = Depends(get_db) +): + """Assigns an active technician to a service job and syncs CRM tasks/calendar.""" + from app.services.CalendarInviteService import CalendarInviteService + try: + return CalendarInviteService.assign_technician_to_service_job( + db=db, + job_id=job_id, + technician_id=payload.technician_id, + assigned_by=current_user.user_id, + reason=payload.reason + ) + except ValueError as ve: + raise HTTPException(status_code=404, detail=str(ve)) + except Exception as e: + raise HTTPException(status_code=500, detail=f"Failed to assign technician: {str(e)}") + + +@router.get("/jobs/{job_id}/calendar-invite") +def get_job_calendar_invite(job_id: str, db: Session = Depends(get_db)): + """Generates Google Calendar URL and slot details for a service appointment.""" + from app.services.CalendarInviteService import CalendarInviteService + from app.models.ServiceModel import ServiceAppointment + from app.models.CustomerDeviceModel import CustomerDevice + from app.models.EcomCustomerModel import EcomCustomer + + job = db.query(ServiceJob).filter( + (ServiceJob.job_id == job_id) | (ServiceJob.job_no == job_id) + ).first() + if not job: + raise HTTPException(status_code=404, detail="Service job not found") + + appt = ( + db.query(ServiceAppointment) + .filter(ServiceAppointment.service_job_id == job.job_id) + .order_by(ServiceAppointment.created_at.desc()) + .first() + ) + if not appt: + raise HTTPException(status_code=404, detail="No appointment found for this service job") + + customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == job.customer_id).first() + customer_name = f"{customer.first_name or ''} {customer.last_name or ''}".strip() if customer else "Valued Customer" + + device = db.query(CustomerDevice).filter(CustomerDevice.device_id == job.device_id).first() + device_label = f"{device.brand or ''} {device.model or ''}".strip() if device else (job.service_name_snapshot or "Device") + + gcal_url = CalendarInviteService.generate_google_calendar_url( + job_no=job.job_no, + start_time=appt.scheduled_start, + end_time=appt.scheduled_end, + device_name=device_label, + customer_name=customer_name, + store_address=CalendarInviteService.DEFAULT_STORE_ADDRESS, + problem_summary=job.custom_service_name or job.service_name_snapshot, + ) + + return { + "job_id": job.job_id, + "job_no": job.job_no, + "appointment_id": appt.appointment_id, + "scheduled_start": appt.scheduled_start.isoformat(), + "scheduled_end": appt.scheduled_end.isoformat(), + "device_name": device_label, + "google_calendar_url": gcal_url, + "store_name": CalendarInviteService.DEFAULT_STORE_NAME, + "store_address": CalendarInviteService.DEFAULT_STORE_ADDRESS, + "ics_download_url": f"/api/v1/service/jobs/{job.job_id}/calendar.ics", + } + + +@router.get("/jobs/{job_id}/calendar.ics") +def download_job_calendar_ics(job_id: str, db: Session = Depends(get_db)): + """Downloads an RFC 5545 .ics calendar invite for the service appointment.""" + from fastapi.responses import Response + from app.services.CalendarInviteService import CalendarInviteService + from app.models.ServiceModel import ServiceAppointment + from app.models.CustomerDeviceModel import CustomerDevice + from app.models.EcomCustomerModel import EcomCustomer + + job = db.query(ServiceJob).filter( + (ServiceJob.job_id == job_id) | (ServiceJob.job_no == job_id) + ).first() + if not job: + raise HTTPException(status_code=404, detail="Service job not found") + + appt = ( + db.query(ServiceAppointment) + .filter(ServiceAppointment.service_job_id == job.job_id) + .order_by(ServiceAppointment.created_at.desc()) + .first() + ) + if not appt: + raise HTTPException(status_code=404, detail="No appointment found for this service job") + + customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == job.customer_id).first() + customer_name = f"{customer.first_name or ''} {customer.last_name or ''}".strip() if customer else "Valued Customer" + + device = db.query(CustomerDevice).filter(CustomerDevice.device_id == job.device_id).first() + device_label = f"{device.brand or ''} {device.model or ''}".strip() if device else (job.service_name_snapshot or "Device") + + ics_bytes = CalendarInviteService.generate_ics_bytes( + job_no=job.job_no, + appointment_id=appt.appointment_id, + start_time=appt.scheduled_start, + end_time=appt.scheduled_end, + device_name=device_label, + customer_name=customer_name, + store_address=CalendarInviteService.DEFAULT_STORE_ADDRESS, + problem_summary=job.custom_service_name or job.service_name_snapshot, + ) + + return Response( + content=ics_bytes, + media_type="text/calendar", + headers={ + "Content-Disposition": f'attachment; filename="iFixKart-Service-{job.job_no}.ics"' + } + ) + + diff --git a/app/api/v1/routers/SimulationPaymentRouter.py b/app/api/v1/routers/SimulationPaymentRouter.py index 263a236..dd4cbf5 100644 --- a/app/api/v1/routers/SimulationPaymentRouter.py +++ b/app/api/v1/routers/SimulationPaymentRouter.py @@ -87,7 +87,7 @@ def simulate_payment( "message": "Payment already captured", "order_id": order.order_id, "order_no": order.order_no, - "status": order.status, + "order_status": order.status, "payment_status": order.payment_status, "invoice_id": existing_invoice.invoice_id if existing_invoice else None, "invoice_no": existing_invoice.invoice_no if existing_invoice else None, @@ -139,7 +139,7 @@ def simulate_payment( "message": "Simulated payment captured and order confirmed", "order_id": order.order_id, "order_no": order.order_no, - "status": order.status, + "order_status": order.status, "payment_status": order.payment_status, "payment_id": ledger.payment_id, "transaction_ref": ledger.transaction_ref, diff --git a/app/core/database/db_session.py b/app/core/database/db_session.py index d65406f..22b26b1 100644 --- a/app/core/database/db_session.py +++ b/app/core/database/db_session.py @@ -1,6 +1,7 @@ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, declarative_base, Session from app.core.config.Config import settings +import os Base = declarative_base() @@ -9,11 +10,18 @@ core_url = settings.CORE_DATABASE_URL or settings.DATABASE_URL crm_url = settings.CRM_DATABASE_URL or settings.DATABASE_URL commerce_url = settings.COMMERCE_DATABASE_URL or settings.DATABASE_URL +# Pool sizing is environment-configurable so the simulation backend can raise +# it (DB_POOL_SIZE / DB_MAX_OVERFLOW in .env.sim); production keeps defaults. +_pool_size = int(os.getenv("DB_POOL_SIZE", "5")) +_max_overflow = int(os.getenv("DB_MAX_OVERFLOW", "10")) + # 2. Engines configuration with connection pooling engine_core = create_engine( core_url, future=True, pool_pre_ping=True, + pool_size=_pool_size, + max_overflow=_max_overflow, connect_args={"init_command": "SET time_zone='+00:00'"} ) @@ -21,6 +29,8 @@ engine_crm = create_engine( crm_url, future=True, pool_pre_ping=True, + pool_size=_pool_size, + max_overflow=_max_overflow, connect_args={"init_command": "SET time_zone='+00:00'"} ) @@ -28,6 +38,8 @@ engine_commerce = create_engine( commerce_url, future=True, pool_pre_ping=True, + pool_size=_pool_size, + max_overflow=_max_overflow, connect_args={"init_command": "SET time_zone='+00:00'"} ) @@ -61,7 +73,9 @@ class RoutingSession(Session): "departments", "designations", "roles", "permissions", "users", "user_sessions", "audit_logs", "countries", "states", "cities", "settings", "file_uploads", - "role_permissions", "simulation_jobs" + "role_permissions", "simulation_jobs", + "notification_templates", "notifications", "notification_attempts", + "dead_letter_notifications", "whatsapp_sessions", "user_location_mappings" ]: return engine_core diff --git a/app/models/ServiceModel.py b/app/models/ServiceModel.py index 5024155..d366266 100644 --- a/app/models/ServiceModel.py +++ b/app/models/ServiceModel.py @@ -89,6 +89,8 @@ class ServiceAppointment(Base): created_at = Column(DateTime, server_default=func.now()) confirmed_at = Column(DateTime, nullable=True) cancelled_at = Column(DateTime, nullable=True) + reminder_sent = Column(Boolean, default=False, nullable=False, index=True) + reminder_sent_at = Column(DateTime, nullable=True) job = relationship("ServiceJob") diff --git a/app/services/CalendarInviteService.py b/app/services/CalendarInviteService.py new file mode 100644 index 0000000..03a1bb4 --- /dev/null +++ b/app/services/CalendarInviteService.py @@ -0,0 +1,673 @@ +import os +import urllib.parse +from datetime import datetime, timedelta, timezone +from typing import Optional, List, Dict, Any +from sqlalchemy.orm import Session +from sqlalchemy import select, or_, func +import ulid + +import app.models.db_base # Ensure all SQLAlchemy relations are loaded +from app.models.ServiceModel import ( + ServiceJob, + ServiceAppointment, + ServiceJobAssignment, + ServiceJobEvent, +) +from app.models.CrmModel import CrmTask, CrmCalendarEvent +from app.models.CustomerDeviceModel import CustomerDevice +from app.models.EcomCustomerModel import EcomCustomer +from app.models.TechnicianModel import TechnicianProfile +from app.models.UserModel import User, Role +from app.core.config.Config import settings + + +class CalendarInviteService: + DEFAULT_STORE_NAME = "iFixKart Service Hub" + DEFAULT_STORE_ADDRESS = "Chennai Central Service Branch, Tamil Nadu, India" + DEFAULT_MAPS_URL = "https://maps.google.com/?q=iFixKart+Chennai" + + @classmethod + def _to_utc_compact(cls, dt: datetime) -> str: + """Convert datetime to iCalendar UTC compact format: YYYYMMDDTHHMMSSZ.""" + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + else: + dt = dt.astimezone(timezone.utc) + return dt.strftime("%Y%m%dT%H%M%SZ") + + @classmethod + def generate_ics_content( + cls, + job_no: str, + appointment_id: str, + start_time: datetime, + end_time: datetime, + device_name: str, + customer_name: str, + store_address: Optional[str] = None, + problem_summary: Optional[str] = None, + ) -> str: + """ + Generate RFC 5545 compliant .ics VCALENDAR content. + """ + now_compact = cls._to_utc_compact(datetime.now(timezone.utc)) + start_compact = cls._to_utc_compact(start_time) + end_compact = cls._to_utc_compact(end_time) + + uid = f"srv-{job_no}-{appointment_id}@ifixkart.com" + location = store_address or cls.DEFAULT_STORE_ADDRESS + summary = f"iFixKart Repair: {device_name} (#{job_no})" + + desc_lines = [ + f"Dear {customer_name},", + f"Your walk-in repair appointment for {device_name} is confirmed.", + f"Job Reference: {job_no}", + f"Service Center: {location}", + "", + "Pre-Visit Checklist:", + "β€’ Please backup your personal device data if possible.", + "β€’ Bring your device along with any relevant accessories/chargers.", + "β€’ Keep your screen lock passcode handy for post-repair testing.", + "", + "Contact Support: support@ifixkart.com | +91 90803 23589", + "Thank you for choosing iFixKart!", + ] + if problem_summary: + desc_lines.insert(4, f"Reported Issue: {problem_summary}") + + description = "\\n".join(desc_lines) + + ics_lines = [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//iFixKart//Service Appointments//EN", + "CALSCALE:GREGORIAN", + "METHOD:REQUEST", + "BEGIN:VEVENT", + f"UID:{uid}", + f"DTSTAMP:{now_compact}", + f"DTSTART:{start_compact}", + f"DTEND:{end_compact}", + f"SUMMARY:{summary}", + f"DESCRIPTION:{description}", + f"LOCATION:{location}", + "STATUS:CONFIRMED", + "SEQUENCE:0", + 'ORGANIZER;CN="iFixKart Support":mailto:support@ifixkart.com', + "BEGIN:VALARM", + "TRIGGER:-PT2H", + "ACTION:DISPLAY", + "DESCRIPTION:Reminder: Your iFixKart appointment is in 2 hours", + "END:VALARM", + "END:VEVENT", + "END:VCALENDAR", + ] + return "\r\n".join(ics_lines) + "\r\n" + + @classmethod + def generate_ics_bytes( + cls, + job_no: str, + appointment_id: str, + start_time: datetime, + end_time: datetime, + device_name: str, + customer_name: str, + store_address: Optional[str] = None, + problem_summary: Optional[str] = None, + ) -> bytes: + content = cls.generate_ics_content( + job_no=job_no, + appointment_id=appointment_id, + start_time=start_time, + end_time=end_time, + device_name=device_name, + customer_name=customer_name, + store_address=store_address, + problem_summary=problem_summary, + ) + return content.encode("utf-8") + + @classmethod + def generate_google_calendar_url( + cls, + job_no: str, + start_time: datetime, + end_time: datetime, + device_name: str, + customer_name: str, + store_address: Optional[str] = None, + problem_summary: Optional[str] = None, + ) -> str: + """ + Generate 1-tap Google Calendar web addition link. + """ + start_compact = cls._to_utc_compact(start_time) + end_compact = cls._to_utc_compact(end_time) + dates_param = f"{start_compact}/{end_compact}" + + title = f"iFixKart Repair: {device_name} (#{job_no})" + location = store_address or cls.DEFAULT_STORE_ADDRESS + + details = ( + f"Hi {customer_name}! Your walk-in service is scheduled at iFixKart.\n" + f"Job #{job_no}\n" + f"Device: {device_name}\n" + f"Store: {location}\n" + f"Helpline: +91 90803 23589" + ) + if problem_summary: + details += f"\nIssue: {problem_summary}" + + params = { + "action": "TEMPLATE", + "text": title, + "dates": dates_param, + "details": details, + "location": location, + } + return f"https://calendar.google.com/calendar/render?{urllib.parse.urlencode(params)}" + + @classmethod + def sync_walkin_to_crm(cls, db: Session, job_id: str) -> Dict[str, Any]: + """ + Automatically creates CrmTask and CrmCalendarEvent for confirmed walk-in jobs. + Idempotent: will not duplicate if already synced. + """ + job = db.get(ServiceJob, job_id) + if not job: + return {"status": "SKIPPED", "reason": "Job not found"} + + appt = ( + db.query(ServiceAppointment) + .filter( + ServiceAppointment.service_job_id == job_id, + ServiceAppointment.status.in_(["CONFIRMED", "HELD", "COMPLETED"]), + ) + .order_by(ServiceAppointment.created_at.desc()) + .first() + ) + + customer = ( + db.query(EcomCustomer) + .filter(EcomCustomer.customer_id == job.customer_id) + .first() + ) + customer_name = ( + f"{customer.first_name or ''} {customer.last_name or ''}".strip() + if customer + else "Walk-In Customer" + ) + customer_phone = customer.phone if customer else (job.alt_phone or "") + + device = ( + db.query(CustomerDevice) + .filter(CustomerDevice.device_id == job.device_id) + .first() + ) + device_name = ( + f"{device.brand or ''} {device.model or ''}".strip() + if device + else (job.service_name_snapshot or "Device Repair") + ) + + issue_summary = job.custom_service_name or job.service_name_snapshot or "Hardware Diagnosis" + + slot_str = "" + if appt: + start_fmt = appt.scheduled_start.strftime("%d %b %Y, %I:%M %p") + end_fmt = appt.scheduled_end.strftime("%I:%M %p") + slot_str = f"{start_fmt} - {end_fmt}" + + # 1. Idempotent CrmTask Creation + task = ( + db.query(CrmTask) + .filter( + CrmTask.entity_type == "REPAIR_TICKET", + CrmTask.entity_id == job.job_id, + ) + .first() + ) + if not task: + task = CrmTask( + tenant_id="tenant_default", + title=f"Walk-in Repair: {job.job_no} - {device_name}", + description=f"Customer: {customer_name} ({customer_phone})\nSlot: {slot_str}\nIssue: {issue_summary}", + entity_type="REPAIR_TICKET", + entity_id=job.job_id, + priority=job.priority or "MEDIUM", + status="PENDING", + due_at=appt.scheduled_end if appt else None, + assignee_id=None, + ) + db.add(task) + db.flush() + + # 2. Idempotent CrmCalendarEvent Creation + event = ( + db.query(CrmCalendarEvent) + .filter( + CrmCalendarEvent.source_type == "REPAIR_TICKET", + CrmCalendarEvent.source_id == job.job_id, + ) + .first() + ) + if not event and appt: + event = CrmCalendarEvent( + tenant_id="tenant_default", + task_id=task.task_id if task else None, + title=f"Walk-in: {device_name} ({job.job_no})", + description=f"Customer: {customer_name} ({customer_phone})\nIssue: {issue_summary}\nLocation: {cls.DEFAULT_STORE_NAME}", + source_type="REPAIR_TICKET", + source_id=job.job_id, + start_time=appt.scheduled_start, + end_time=appt.scheduled_end, + is_all_day=False, + status="SCHEDULED", + ) + db.add(event) + db.flush() + + db.commit() + return { + "status": "SYNCED", + "job_id": job.job_id, + "task_id": task.task_id if task else None, + "event_id": event.event_id if event else None, + } + + @classmethod + def get_active_technicians(cls, db: Session) -> List[Dict[str, Any]]: + """ + Returns all active technicians configured in the system. + """ + # Query technician profiles joined with users + profiles = ( + db.query(TechnicianProfile) + .filter(TechnicianProfile.active == True) + .all() + ) + tech_list = [] + user_ids_seen = set() + + for prof in profiles: + user = db.query(User).filter(User.user_id == prof.user_id).first() + if user and user.is_active: + user_ids_seen.add(user.user_id) + tech_list.append({ + "technician_id": prof.technician_id, + "user_id": user.user_id, + "name": user.display_name or f"{user.first_name or ''} {user.last_name or ''}".strip(), + "email": user.email, + "phone": user.phone or "", + "role": user.role.role_name if user.role else "Technician", + }) + + # Fallback: also include any staff user with Technician or Manager role if not already in profile + staff_users = ( + db.query(User) + .join(Role, User.role_id == Role.role_id) + .filter( + User.is_active == True, + Role.role_name.in_(["Technician", "Store Manager", "Super Admin"]), + ) + .all() + ) + for u in staff_users: + if u.user_id not in user_ids_seen: + tech_list.append({ + "technician_id": u.user_id, + "user_id": u.user_id, + "name": u.display_name or f"{u.first_name or ''} {u.last_name or ''}".strip(), + "email": u.email, + "phone": u.phone or "", + "role": u.role.role_name if u.role else "Staff", + }) + + return tech_list + + @classmethod + def assign_technician_to_service_job( + cls, + db: Session, + job_id: str, + technician_id: str, + assigned_by: str, + reason: Optional[str] = None, + ) -> Dict[str, Any]: + """ + Assigns a technician to a service job: + 1. Logs into service_job_assignments + 2. Updates CrmTask.assignee_id + 3. Updates CrmCalendarEvent description + 4. Dispatches timeline event + 5. Sends WhatsApp alert to assigned technician + """ + job = db.get(ServiceJob, job_id) + if not job: + raise ValueError(f"Service job '{job_id}' not found.") + + # Resolve technician profile/user + tech_prof = ( + db.query(TechnicianProfile) + .filter( + or_( + TechnicianProfile.technician_id == technician_id, + TechnicianProfile.user_id == technician_id, + ) + ) + .first() + ) + user_id = tech_prof.user_id if tech_prof else technician_id + tech_user = db.query(User).filter(User.user_id == user_id).first() + tech_name = ( + tech_user.display_name + or f"{tech_user.first_name or ''} {tech_user.last_name or ''}".strip() + if tech_user + else "Technician" + ) + tech_phone = tech_user.phone if tech_user else "" + + # Locate appointment + appt = ( + db.query(ServiceAppointment) + .filter(ServiceAppointment.service_job_id == job_id) + .order_by(ServiceAppointment.created_at.desc()) + .first() + ) + appointment_id = appt.appointment_id if appt else str(ulid.ULID()) + + # 1. Create ServiceJobAssignment entry + assignment = ServiceJobAssignment( + assignment_id=str(ulid.ULID()), + service_job_id=job.job_id, + appointment_id=appointment_id, + technician_id=technician_id, + assigned_by=assigned_by, + reason=reason or "Assigned via Service Management", + ) + db.add(assignment) + + # 2. Update CrmTask assignee + task = ( + db.query(CrmTask) + .filter( + CrmTask.entity_type == "REPAIR_TICKET", + CrmTask.entity_id == job.job_id, + ) + .first() + ) + if task: + task.assignee_id = technician_id + db.add(task) + + # 3. Update CrmCalendarEvent note + event = ( + db.query(CrmCalendarEvent) + .filter( + CrmCalendarEvent.source_type == "REPAIR_TICKET", + CrmCalendarEvent.source_id == job.job_id, + ) + .first() + ) + if event: + event.description = f"{event.description or ''}\nAssigned Tech: {tech_name}" + db.add(event) + + # 4. Timeline Event + timeline_event = ServiceJobEvent( + event_id=str(ulid.ULID()), + job_id=job.job_id, + event_type="TECHNICIAN_ASSIGNED", + performed_by=assigned_by, + notes=f"Assigned to {tech_name} ({technician_id}). Reason: {reason or 'N/A'}", + ) + db.add(timeline_event) + db.commit() + + # 5. WhatsApp notification to technician + if tech_phone: + try: + from app.services.NotificationGatewayService import NotificationGatewayService + from app.schemas.NotificationGateway import NotificationDispatchCreate + + admin_base = getattr(settings, "ADMIN_BASE_URL", "https://admin.ifixkart.com") + job_url = f"{admin_base}/technician?job_id={job.job_id}" + slot_info = ( + f"{appt.scheduled_start.strftime('%d %b, %I:%M %p')}" + if appt + else "Walk-In Queue" + ) + + wa_text = ( + f"πŸ”§ *[iFixKart Workshop Assignment]*\n" + f"Hi {tech_name}, you have been assigned to Service Job *#{job.job_no}*.\n" + f"*Device:* {job.service_name_snapshot or 'Customer Hardware'}\n" + f"*Slot:* {slot_info}\n" + f"*Priority:* {job.priority or 'NORMAL'}\n\n" + f"πŸ‘‰ *Open Workshop Ticket:* {job_url}" + ) + + NotificationGatewayService.dispatch_notification( + db=db, + tenant_id="tenant_default", + payload=NotificationDispatchCreate( + channel="WHATSAPP", + recipient_phone=tech_phone, + body=wa_text, + title=f"New Job Assigned #{job.job_no}", + idempotency_key=f"TECH_ASSIGN:{job.job_id}:{technician_id}", + ), + ) + except Exception as e: + print(f"[CalendarInviteService] Failed to notify technician on WhatsApp: {e}") + + return { + "status": "ASSIGNED", + "job_id": job.job_id, + "technician_id": technician_id, + "technician_name": tech_name, + "assignment_id": assignment.assignment_id, + } + + @classmethod + def complete_walkin_crm_task(cls, db: Session, job_id: str) -> None: + """ + Auto-completes corresponding CrmTask and CrmCalendarEvent when repair finishes. + """ + now = datetime.now(timezone.utc) + tasks = ( + db.query(CrmTask) + .filter( + CrmTask.entity_type == "REPAIR_TICKET", + CrmTask.entity_id == job_id, + ) + .all() + ) + for t in tasks: + t.status = "COMPLETED" + t.completed_at = now + db.add(t) + + events = ( + db.query(CrmCalendarEvent) + .filter( + CrmCalendarEvent.source_type == "REPAIR_TICKET", + CrmCalendarEvent.source_id == job_id, + ) + .all() + ) + for ev in events: + ev.status = "COMPLETED" + db.add(ev) + + db.commit() + + @classmethod + def send_appointment_reminders(cls, db: Session) -> Dict[str, Any]: + """ + Checks for confirmed walk-in appointments starting in ~2 hours (between 1h 45m and 2h 15m), + and sends reminders to both customer and assigned technician. + """ + now = datetime.utcnow() + window_start = now + timedelta(hours=1, minutes=45) + window_end = now + timedelta(hours=2, minutes=15) + + remind_stmt = ( + select(ServiceAppointment) + .join(ServiceJob, ServiceAppointment.service_job_id == ServiceJob.job_id) + .where( + ServiceAppointment.status == "CONFIRMED", + ServiceAppointment.scheduled_start >= window_start, + ServiceAppointment.scheduled_start <= window_end, + ServiceAppointment.reminder_sent == False, + ) + ) + appointments = db.execute(remind_stmt).scalars().all() + + reminders_sent = 0 + from app.services.NotificationGatewayService import NotificationGatewayService + from app.schemas.NotificationGateway import NotificationDispatchCreate + + for appt in appointments: + job = db.get(ServiceJob, appt.service_job_id) + if not job: + continue + + customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == job.customer_id).first() + customer_name = ( + f"{customer.first_name or ''} {customer.last_name or ''}".strip() + if customer + else "Valued Customer" + ) + customer_phone = (customer.phone if customer and customer.phone else (job.alt_phone or "")) + if customer and not customer.phone and job.alt_phone: + try: + customer.phone = job.alt_phone.strip() + db.commit() + except Exception: + pass + + device = db.query(CustomerDevice).filter(CustomerDevice.device_id == job.device_id).first() + device_str = f"{device.brand or ''} {device.model or ''}".strip() if device else (job.service_name_snapshot or "Device") + + slot_start_fmt = appt.scheduled_start.strftime("%I:%M %p") + slot_end_fmt = appt.scheduled_end.strftime("%I:%M %p") + + # 1. Customer WhatsApp Reminder + if customer_phone: + cust_msg = ( + f"πŸ‘‹ *Hello {customer_name}! Friendly Appointment Reminder*\n\n" + f"Your walk-in service appointment for *{device_str}* is scheduled today in *2 hours*:\n" + f"⏰ *Time Slot:* {slot_start_fmt} - {slot_end_fmt}\n" + f"πŸ“ *Store:* {cls.DEFAULT_STORE_NAME}\n" + f"πŸ—ΊοΈ *Directions:* {cls.DEFAULT_MAPS_URL}\n\n" + f"Please remember to bring your device passcode. See you soon!\n" + f"– Team iFixKart" + ) + try: + NotificationGatewayService.dispatch_notification( + db=db, + tenant_id="tenant_default", + payload=NotificationDispatchCreate( + channel="WHATSAPP", + recipient_phone=customer_phone, + body=cust_msg, + title=f"Walk-in Reminder #{job.job_no}", + idempotency_key=f"REMINDER_CUST:{appt.appointment_id}", + ), + ) + except Exception as ex: + print(f"Error sending customer reminder: {ex}") + + # 2. Technician WhatsApp Reminder + assignment = ( + db.query(ServiceJobAssignment) + .filter(ServiceJobAssignment.service_job_id == job.job_id) + .order_by(ServiceJobAssignment.assigned_at.desc()) + .first() + ) + if assignment: + tech_user = db.query(User).filter(User.user_id == assignment.technician_id).first() + if tech_user and tech_user.phone: + tech_msg = ( + f"⏰ *[Upcoming Walk-In in 2 Hours]*\n" + f"Customer *{customer_name}* is scheduled to arrive at *{slot_start_fmt}* for Job *#{job.job_no}* ({device_str}).\n" + f"Please ensure workspace readiness." + ) + try: + NotificationGatewayService.dispatch_notification( + db=db, + tenant_id="tenant_default", + payload=NotificationDispatchCreate( + channel="WHATSAPP", + recipient_phone=tech_user.phone, + body=tech_msg, + title=f"Technician Slot Reminder #{job.job_no}", + idempotency_key=f"REMINDER_TECH:{appt.appointment_id}", + ), + ) + except Exception as ex: + print(f"Error sending technician reminder: {ex}") + + appt.reminder_sent = True + appt.reminder_sent_at = datetime.utcnow() + reminders_sent += 1 + + db.commit() + return {"status": "SUCCESS", "reminders_sent": reminders_sent} + + @classmethod + def audit_pending_walkin_tasks_eod(cls, db: Session) -> Dict[str, Any]: + """ + Queries all walk-in tasks for today that remain PENDING and triggers Admin internal WhatsApp summary. + """ + today = datetime.utcnow().date() + start_of_day = datetime(today.year, today.month, today.day) + end_of_day = start_of_day + timedelta(days=1) + + pending_tasks = ( + db.query(CrmTask) + .filter( + CrmTask.entity_type == "REPAIR_TICKET", + CrmTask.status == "PENDING", + CrmTask.due_at >= start_of_day, + CrmTask.due_at < end_of_day, + ) + .all() + ) + + admin_base = getattr(settings, "ADMIN_BASE_URL", "https://admin.ifixkart.com") + summary_lines = [] + + for idx, t in enumerate(pending_tasks, start=1): + tech_name = "⚠️ UNASSIGNED" + if t.assignee_id: + tech_user = db.query(User).filter(User.user_id == t.assignee_id).first() + if tech_user: + tech_name = tech_user.display_name or f"{tech_user.first_name} {tech_user.last_name}" + + summary_lines.append(f"{idx}. {t.title} (Tech: {tech_name})") + + from app.core.events.notification_events import dispatch_internal_notification + + message = ( + f"⚠️ *[iFixKart EOD Alert] {len(pending_tasks)} Walk-In Repair Tasks Pending Today ({today.strftime('%d %b %Y')}):*\n\n" + + ("\n".join(summary_lines) if summary_lines else "All clear! Zero pending tasks.") + + f"\n\nπŸ‘‰ *Review CRM Todos:* {admin_base}/crm-todos" + ) + + dispatch_internal_notification( + event_type="PENDING_WALKIN_TASKS_EOD", + message=message, + context={ + "pending_count": len(pending_tasks), + "date": today.strftime("%Y-%m-%d"), + }, + ) + + return { + "status": "AUDIT_COMPLETE", + "date": today.strftime("%Y-%m-%d"), + "pending_count": len(pending_tasks), + } diff --git a/app/services/NotificationGatewayService.py b/app/services/NotificationGatewayService.py index 0545338..3dbf850 100644 --- a/app/services/NotificationGatewayService.py +++ b/app/services/NotificationGatewayService.py @@ -460,8 +460,16 @@ class NotificationGatewayService: customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == job.customer_id).first() if customer: customer_name = f"{customer.first_name or ''} {customer.last_name or ''}".strip() - customer_phone = customer.phone or "" + customer_phone = customer.phone or job.alt_phone or "" customer_email = customer.email if customer.email and not customer.email.endswith("@store.local") else "" + if not customer.phone and job.alt_phone: + try: + customer.phone = job.alt_phone.strip() + db.commit() + except Exception: + pass + else: + customer_phone = job.alt_phone or "" device = db.query(CustomerDevice).filter(CustomerDevice.device_id == job.device_id).first() device_str = f"{device.brand} {device.model} - " if device else "" @@ -533,17 +541,76 @@ class NotificationGatewayService: email_html = EmailTemplateService.service_invoice_email(service_dict) - wa_message = ( - f"πŸ”§ *iFixKart Service {'Booking' if is_advance else 'Ready'} Confirmation*\n" - f"*Job Ref:* {job.job_no}\n" - f"*Invoice Ref:* {invoice_no}\n" - f"*Customer:* {customer_name}\n" - f"*Service:* {device_str}{job.service_name_snapshot or 'Repair Service'}\n" - f"*Total Paid:* β‚Ή{paid_total:,.2f}\n" - f"*Balance Due:* β‚Ή{balance:,.2f}\n\n" - f"πŸ“„ *Download Service Receipt / Invoice:*\n{pdf_url}\n\n" - f"Thank you for choosing iFixKart!" - ) + if is_advance: + from app.models.ServiceModel import ServiceAppointment + from app.services.CalendarInviteService import CalendarInviteService + + appt = ( + db.query(ServiceAppointment) + .filter(ServiceAppointment.service_job_id == job.job_id) + .order_by(ServiceAppointment.created_at.desc()) + .first() + ) + if appt: + slot_start_fmt = appt.scheduled_start.strftime("%d %b %Y, %I:%M %p") + slot_end_fmt = appt.scheduled_end.strftime("%I:%M %p") + device_label = device_str.strip() or "Device" + + gcal_url = CalendarInviteService.generate_google_calendar_url( + job_no=job.job_no, + start_time=appt.scheduled_start, + end_time=appt.scheduled_end, + device_name=device_label, + customer_name=customer_name, + store_address=CalendarInviteService.DEFAULT_STORE_ADDRESS, + problem_summary=job.custom_service_name or job.service_name_snapshot, + ) + + wa_message = ( + f"πŸ”§ *iFixKart Walk-In Service Booking Confirmed*\n" + f"*Job Ref:* {job.job_no}\n" + f"*Invoice Ref:* {invoice_no}\n" + f"*Customer:* {customer_name}\n" + f"*Service:* {device_str}{job.service_name_snapshot or 'Repair Service'}\n" + f"πŸ“… *Confirmed Slot:* {slot_start_fmt} - {slot_end_fmt}\n" + f"πŸ“ *Store:* {CalendarInviteService.DEFAULT_STORE_NAME}\n" + f"*Total Paid:* β‚Ή{paid_total:,.2f}\n" + f"*Balance Due:* β‚Ή{balance:,.2f}\n\n" + f"πŸ‘‰ *1-Tap Add to Calendar:*\n{gcal_url}\n\n" + f"πŸ“„ *Download Service Receipt / Invoice:*\n{pdf_url}\n\n" + f"Thank you for choosing iFixKart!" + ) + + if not attachments: + attachments = [] + import base64 + ics_bytes = CalendarInviteService.generate_ics_bytes( + job_no=job.job_no, + appointment_id=appt.appointment_id, + start_time=appt.scheduled_start, + end_time=appt.scheduled_end, + device_name=device_label, + customer_name=customer_name, + store_address=CalendarInviteService.DEFAULT_STORE_ADDRESS, + problem_summary=job.custom_service_name or job.service_name_snapshot, + ) + attachments.append({ + "content": base64.b64encode(ics_bytes).decode("utf-8"), + "mime_type": "text/calendar", + "name": f"iFixKart-Service-{job.job_no}.ics" + }) + else: + wa_message = ( + f"πŸ”§ *iFixKart Service Ready for Delivery*\n" + f"*Job Ref:* {job.job_no}\n" + f"*Invoice Ref:* {invoice_no}\n" + f"*Customer:* {customer_name}\n" + f"*Service:* {device_str}{job.service_name_snapshot or 'Repair Service'}\n" + f"*Total Paid:* β‚Ή{paid_total:,.2f}\n" + f"*Balance Due:* β‚Ή{balance:,.2f}\n\n" + f"πŸ“„ *Download Service Receipt / Invoice:*\n{pdf_url}\n\n" + f"Thank you for choosing iFixKart!" + ) if pdf_bytes: import base64 diff --git a/app/services/OrderService.py b/app/services/OrderService.py index d56e2a9..8b96606 100644 --- a/app/services/OrderService.py +++ b/app/services/OrderService.py @@ -7,6 +7,7 @@ import ulid import json from datetime import datetime, timezone from typing import List, Optional, Dict, Any +from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from fastapi import HTTPException, status @@ -57,8 +58,30 @@ def create_invoice_for_order(order: Order, db: Session) -> Invoice: if existing: return existing + # Invoice numbers are generated by reading the last invoice, so concurrent + # confirmations can race for the same C1P1-YY-NNNNNN. Retry inside a + # SAVEPOINT: a duplicate-number collision only rolls back the invoice. + for attempt in range(3): + invoice = None + try: + with db.begin_nested(): + invoice = _build_invoice_row(order, db) + db.add(invoice) + db.flush() + return invoice + except IntegrityError: + if attempt == 2: + raise + db.rollback() + existing = db.query(Invoice).filter(Invoice.order_id == order.order_id).first() + if existing: + return existing + return _build_invoice_row(order, db) + + +def _build_invoice_row(order: Order, db: Session) -> Invoice: tax_amount = float(order.tax_amount or 0) - invoice = Invoice( + return Invoice( invoice_id=str(ulid.ULID()), invoice_no=generate_invoice_number(db), order_id=order.order_id, @@ -72,9 +95,7 @@ def create_invoice_for_order(order: Order, db: Session) -> Invoice: pdf_path=None, # Enforce dynamic on-the-fly PDF rendering status="GENERATED", ) - db.add(invoice) - db.flush() - return invoice + def _dispatch_order_notifications(db: Session, order_id: str, channel: str = "BOTH"): # Simulation must never send real email / WhatsApp / admin alerts. if settings.SIMULATION_MODE: @@ -130,6 +151,48 @@ class OrderService: payment_method: str = "RAZORPAY", use_wallet_credits: bool = False, coupon_code: Optional[str] = None + ) -> Dict[str, Any]: + """ + Concurrency-safe wrapper: order numbers are generated by scanning the + latest order_no, so two simultaneous checkouts can race for the same + ORD-YYYYMMDD-NNNN. On that unique-key collision the whole (transactional) + creation is retried with a fresh number. + """ + attempts = 3 + for attempt in range(attempts): + try: + return OrderService._create_ecommerce_order_inner( + db, + customer, + address_id, + payment_method=payment_method, + use_wallet_credits=use_wallet_credits, + coupon_code=coupon_code, + ) + except HTTPException: + raise + except IntegrityError as exc: + db.rollback() + message = str(getattr(exc, "orig", None) or exc) + duplicate = "Duplicate entry 'ORD-" in message + if duplicate and attempt < attempts - 1: + continue + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=( + "Order could not be created due to a duplicate order number." + if duplicate else "Internal error during order creation." + ) + ) from exc + + @staticmethod + def _create_ecommerce_order_inner( + db: Session, + customer: EcomCustomer, + address_id: str, + payment_method: str = "RAZORPAY", + use_wallet_credits: bool = False, + coupon_code: Optional[str] = None ) -> Dict[str, Any]: """ Processes cart validation, stock reservation, order creation with dynamic delivery calculations. diff --git a/app/services/ServiceJobService.py b/app/services/ServiceJobService.py index 69bf3f2..4410fae 100644 --- a/app/services/ServiceJobService.py +++ b/app/services/ServiceJobService.py @@ -236,6 +236,13 @@ class ServiceJobService: db.commit() db.refresh(job) + if fulfillment_type == "WALK_IN": + try: + from app.services.CalendarInviteService import CalendarInviteService + CalendarInviteService.sync_walkin_to_crm(db, job.job_id) + except Exception as sync_ex: + print(f"[ServiceJobService] Error auto-syncing walk-in to CRM: {sync_ex}") + return { "job_id": job.job_id, "job_no": job.job_no, diff --git a/app/services/ServicePaymentService.py b/app/services/ServicePaymentService.py index 147a728..b23e38e 100644 --- a/app/services/ServicePaymentService.py +++ b/app/services/ServicePaymentService.py @@ -271,14 +271,21 @@ class ServicePaymentService: if payment.payment_type == "ADVANCE": from fastapi import BackgroundTasks from app.core.events.notification_events import dispatch_internal_notification - _dispatch_service_notifications(db, job.job_id, "SERVICE_BOOKED", "EMAIL") + from app.services.CalendarInviteService import CalendarInviteService + + try: + CalendarInviteService.sync_walkin_to_crm(db, job.job_id) + except Exception as sync_ex: + print(f"Error syncing walk-in to CRM: {sync_ex}") + + _dispatch_service_notifications(db, job.job_id, "SERVICE_BOOKED", "BOTH") dispatch_internal_notification( event_type="SERVICE_BOOKED_INTERNAL", message=f"New Service Job booked: {job.job_no}", context={"job_no": job.job_no} ) elif payment.payment_type == "FINAL": - _dispatch_service_notifications(db, job.job_id, "SERVICE_READY", "EMAIL") + _dispatch_service_notifications(db, job.job_id, "SERVICE_READY", "BOTH") return {"message": "Payment verified successfully", "job_id": payment.service_job_id} diff --git a/app/services/TemplateService.py b/app/services/TemplateService.py index 7a414ed..181f742 100644 --- a/app/services/TemplateService.py +++ b/app/services/TemplateService.py @@ -163,12 +163,17 @@ class TemplateService: @staticmethod def render_template(db: Session, event_key: str, channel: str, context: dict, tenant_id: str = "tenant_default") -> Optional[Tuple[str, str]]: - template = db.query(NotificationTemplate).filter( - NotificationTemplate.tenant_id == tenant_id, - NotificationTemplate.event_key == event_key, - NotificationTemplate.channel == channel, - NotificationTemplate.is_active == True - ).first() + try: + template = db.query(NotificationTemplate).filter( + NotificationTemplate.tenant_id == tenant_id, + NotificationTemplate.event_key == event_key, + NotificationTemplate.channel == channel, + NotificationTemplate.is_active == True + ).first() + except Exception as query_ex: + import logging + logging.getLogger(__name__).warning(f"Error querying notification template: {query_ex}") + return None if not template: return None diff --git a/app/services/migration_engine/upsert_executor.py b/app/services/migration_engine/upsert_executor.py index c7635b6..2441549 100644 --- a/app/services/migration_engine/upsert_executor.py +++ b/app/services/migration_engine/upsert_executor.py @@ -515,6 +515,8 @@ class UpsertExecutor: } if all_attributes: + from sqlalchemy.orm.attributes import flag_modified + # Clear previous variant_attributes links for this variant db_session.query(VariantAttribute).filter(VariantAttribute.variant_id == variant.variant_id).delete() @@ -536,58 +538,45 @@ class UpsertExecutor: attribute_id=at_id, name=attr_name, code=attr_code, - status="active" + status="active", + preset_values=[] ) db_session.add(attr_type) if attr_type_cache is not None: attr_type_cache[attr_code] = attr_type - va_id = str(ulid.ULID()) - var_attr = VariantAttribute( - id=va_id, - variant_id=variant.variant_id, - attribute_id=attr_type.attribute_id, - attribute_value=str(attr_val) - ) - db_session.add(var_attr) + # Split on comma for multi-value attributes + sub_values = [s.strip() for s in str(attr_val).split(",") if s.strip()] + valid_sub_values = [sv for sv in sub_values if sv.lower() not in PLACEHOLDER_VALUES] - # CRITICAL: Always save media_key and parent_media_key separately. - # Supports comma-separated keys as well as single keys. - for mk_code, mk_name in (("media_key", "media_key"), ("parent_media_key", "parent_media_key")): - raw_mk_val = all_attributes.get(mk_code) - if raw_mk_val: - # Split on commas for multi-image references - sub_keys = [k.strip() for k in str(raw_mk_val).split(",") if k.strip()] - if not sub_keys and str(raw_mk_val).strip(): - sub_keys = [str(raw_mk_val).strip()] + seen_variant_values = set() + for sub_v in valid_sub_values: + if sub_v.lower() in seen_variant_values: + continue + seen_variant_values.add(sub_v.lower()) - mk_attr_type = None - if attr_type_cache is not None and mk_code in attr_type_cache: - mk_attr_type = attr_type_cache[mk_code] - else: - mk_attr_type = db_session.query(AttributeType).filter(AttributeType.code == mk_code).first() - if not mk_attr_type: - mk_at_id = str(ulid.ULID()) - mk_attr_type = AttributeType( - attribute_id=mk_at_id, - name=mk_name, - code=mk_code, - status="active" - ) - db_session.add(mk_attr_type) - if attr_type_cache is not None: - attr_type_cache[mk_code] = mk_attr_type + va_id = str(ulid.ULID()) + var_attr = VariantAttribute( + id=va_id, + variant_id=variant.variant_id, + attribute_id=attr_type.attribute_id, + attribute_value=sub_v[:2000] + ) + db_session.add(var_attr) - for sk in sub_keys: - canonical_val = MediaResolver.canonicalize_media_key(sk) or sk - if canonical_val: - canonical_val = canonical_val[:2000] - db_session.add(VariantAttribute( - id=str(ulid.ULID()), - variant_id=variant.variant_id, - attribute_id=mk_attr_type.attribute_id, - attribute_value=canonical_val - )) + # Auto-sync distinct values to Master Attribute preset_values (case-insensitive deduplication) + current_presets = list(attr_type.preset_values or []) + existing_lower = {str(p).strip().lower() for p in current_presets} + modified_presets = False + for sub_v in valid_sub_values: + if sub_v.lower() not in existing_lower: + current_presets.append(sub_v) + existing_lower.add(sub_v.lower()) + modified_presets = True + + if modified_presets: + attr_type.preset_values = current_presets + flag_modified(attr_type, "preset_values") # 6. Attach Variant Images via Smart Canonical Media Key Resolver (Supporting Comma-Separated Keys) raw_media_key = mapped_row.get("media_key") or mapped_row.get("parent_media_key") diff --git a/scripts/sim/reconcile.py b/scripts/sim/reconcile.py new file mode 100644 index 0000000..239690d --- /dev/null +++ b/scripts/sim/reconcile.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +""" +Reconcile the simulation database after a swarm run. + +Checks that the HTTP journey produced a coherent database state: +orders <-> items <-> invoices <-> payment ledger <-> inventory ledger <-> history. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +from datetime import datetime, timezone +from pathlib import Path + +from dotenv import load_dotenv +from sqlalchemy import create_engine, text + +BACKEND_DIR = Path(__file__).resolve().parents[2] +SIM_ENV = BACKEND_DIR / ".env.sim" +ARTIFACT_DIR = BACKEND_DIR / "sim-artifacts" + + +def scalar(conn, sql: str, **params): + return conn.execute(text(sql), params).scalar() + + +def main() -> int: + parser = argparse.ArgumentParser(description="Validate simulation DB consistency") + parser.add_argument("--output", default="") + args = parser.parse_args() + + if not SIM_ENV.exists(): + raise SystemExit(f"Missing {SIM_ENV}") + load_dotenv(SIM_ENV, override=True) + engine = create_engine(os.getenv("COMMERCE_DATABASE_URL"), future=True) + checks: dict[str, object] = {} + failures: list[str] = [] + + with engine.connect() as conn: + checks["customers"] = scalar(conn, "SELECT COUNT(*) FROM ecom_customers") + checks["carts"] = scalar(conn, "SELECT COUNT(*) FROM carts") + checks["orders_total"] = scalar(conn, "SELECT COUNT(*) FROM orders") + checks["order_items"] = scalar(conn, "SELECT COUNT(*) FROM order_items") + checks["invoices"] = scalar(conn, "SELECT COUNT(*) FROM invoices") + checks["payment_ledger"] = scalar(conn, "SELECT COUNT(*) FROM payment_ledger") + checks["history_rows"] = scalar(conn, "SELECT COUNT(*) FROM order_status_history") + + checks["orders_by_status"] = { + r[0]: r[1] + for r in conn.execute(text("SELECT status, COUNT(*) FROM orders GROUP BY status")) + } + checks["orders_by_payment"] = { + r[0]: r[1] + for r in conn.execute(text("SELECT payment_status, COUNT(*) FROM orders GROUP BY payment_status")) + } + checks["ledger_by_provider"] = { + f"{r[0]}/{r[1]}": r[2] + for r in conn.execute( + text("SELECT provider, status, COUNT(*) FROM payment_ledger GROUP BY provider, status") + ) + } + + checks["revenue_confirmed"] = float( + scalar(conn, "SELECT COALESCE(SUM(final_amount),0) FROM orders WHERE status='ORDER_CONFIRMED'") or 0 + ) + checks["duplicate_order_numbers"] = [ + r[0] for r in conn.execute( + text("SELECT order_no FROM orders GROUP BY order_no HAVING COUNT(*) > 1") + ) + ] + if checks["duplicate_order_numbers"]: + failures.append("duplicate order numbers") + + checks["paid_without_invoice"] = [ + r[0] for r in conn.execute( + text( + "SELECT o.order_id FROM orders o " + "LEFT JOIN invoices i ON i.order_id=o.order_id " + "WHERE o.payment_status='PAYMENT_CAPTURED' AND i.invoice_id IS NULL" + ) + ) + ] + if checks["paid_without_invoice"]: + failures.append("paid orders without invoice") + + checks["orphan_invoices"] = [ + r[0] for r in conn.execute( + text( + "SELECT i.invoice_id FROM invoices i " + "LEFT JOIN orders o ON o.order_id=i.order_id WHERE o.order_id IS NULL" + ) + ) + ] + if checks["orphan_invoices"]: + failures.append("invoices without orders") + + checks["paid_without_captured_ledger"] = [ + r[0] for r in conn.execute( + text( + "SELECT o.order_id FROM orders o " + "LEFT JOIN payment_ledger p ON p.order_id=o.order_id AND p.status='CAPTURED' " + "WHERE o.payment_status='PAYMENT_CAPTURED' AND p.payment_id IS NULL" + ) + ) + ] + if checks["paid_without_captured_ledger"]: + failures.append("paid orders without captured payment ledger") + + checks["orders_without_history"] = [ + r[0] for r in conn.execute( + text( + "SELECT o.order_id FROM orders o " + "LEFT JOIN order_status_history h ON h.order_id=o.order_id " + "WHERE h.history_id IS NULL" + ) + ) + ] + if checks["orders_without_history"]: + failures.append("orders without status history") + + checks["order_total_mismatches"] = [ + r[0] for r in conn.execute( + text( + "SELECT o.order_id FROM orders o " + "JOIN (SELECT order_id, ROUND(SUM(total_price),2) AS items_total FROM order_items GROUP BY order_id) x " + "ON x.order_id=o.order_id " + "WHERE ABS(o.total_amount - x.items_total) > 0.01" + ) + ) + ] + if checks["order_total_mismatches"]: + failures.append("order total != sum(order_items)") + + checks["invoice_total_mismatches"] = [ + r[0] for r in conn.execute( + text( + "SELECT i.invoice_id FROM invoices i JOIN orders o ON o.order_id=i.order_id " + "WHERE ABS(i.total_amount - o.final_amount) > 0.01" + ) + ) + ] + if checks["invoice_total_mismatches"]: + failures.append("invoice total != order final amount") + + checks["confirmed_without_sale_ledger"] = [ + r[0] for r in conn.execute( + text( + "SELECT o.order_id FROM orders o " + "WHERE o.status='ORDER_CONFIRMED' AND NOT EXISTS (" + " SELECT 1 FROM inventory_ledger l " + " WHERE l.reference_id=o.order_id AND l.event_type='ONLINE_SALE_FROM_RESERVATION'" + ")" + ) + ) + ] + if checks["confirmed_without_sale_ledger"]: + failures.append("confirmed orders without sale ledger") + + checks["negative_stock_variants"] = [ + r[0] for r in conn.execute( + text( + "SELECT variant_id FROM inventory_ledger GROUP BY variant_id HAVING SUM(qty) < 0" + ) + ) + ] + if checks["negative_stock_variants"]: + failures.append("negative stock") + + checks["opening_stock"] = scalar( + conn, "SELECT COALESCE(SUM(qty),0) FROM inventory_ledger WHERE reference_id='SIM_SEED'" + ) + checks["sold_units"] = scalar( + conn, "SELECT COALESCE(SUM(-qty),0) FROM inventory_ledger " + "WHERE event_type='ONLINE_SALE_FROM_RESERVATION'" + ) + checks["current_stock"] = scalar(conn, "SELECT COALESCE(SUM(qty),0) FROM inventory_ledger") + checks["stock_delta"] = int(checks["current_stock"]) - int(checks["opening_stock"]) + int(checks["sold_units"]) + if checks["stock_delta"] != 0: + failures.append("inventory ledger does not balance") + + checks["carts_with_items"] = scalar( + conn, "SELECT COUNT(*) FROM carts WHERE items_json IS NOT NULL" + ) + + report = { + "checked_at": datetime.now(timezone.utc).isoformat(), + "database": os.getenv("COMMERCE_DATABASE_URL", "").rsplit("/", 1)[-1], + "checks": checks, + "failures": failures, + "ok": not failures, + } + ARTIFACT_DIR.mkdir(parents=True, exist_ok=True) + output = Path(args.output) if args.output else ARTIFACT_DIR / "reconciliation.json" + output.write_text(json.dumps(report, indent=2, default=str)) + + print(f"=== RECONCILIATION ({'OK' if report['ok'] else 'FAILED'}) ===") + for key in ( + "customers", "orders_total", "order_items", "invoices", "payment_ledger", + "history_rows", "revenue_confirmed", "opening_stock", "sold_units", "current_stock", + ): + print(f"{key:22}: {checks[key]}") + print(f"{'orders_by_status':22}: {checks['orders_by_status']}") + print(f"{'orders_by_payment':22}: {checks['orders_by_payment']}") + print(f"{'ledger_by_provider':22}: {checks['ledger_by_provider']}") + if failures: + print("\nFAILURES:") + for failure in failures: + print(f" - {failure}") + print(f"\nreport: {output}") + return 0 if report["ok"] else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/sim/reset_sim_data.py b/scripts/sim/reset_sim_data.py new file mode 100644 index 0000000..8ac2a8c --- /dev/null +++ b/scripts/sim/reset_sim_data.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +""" +Reset the *simulation* transactional state without touching reference data. + +This removes orders, carts, invoices, ledgers and status history from the sim +commerce schema and re-creates the opening-stock ledger rows. Reference data +(products, variants, categories, CRM tables) and customers are preserved unless +--drop-customers is passed. + +Usage: + cd Backend + ./venv/bin/python scripts/sim/reset_sim_data.py --yes + ./venv/bin/python scripts/sim/reset_sim_data.py --yes --drop-customers +""" +from __future__ import annotations + +import argparse +import os +import sys +from datetime import datetime, timezone +from pathlib import Path + +import ulid +from dotenv import load_dotenv +from sqlalchemy import create_engine, text + +BACKEND_DIR = Path(__file__).resolve().parents[2] +SIM_ENV = BACKEND_DIR / ".env.sim" + +TRANSACTIONAL_TABLES = [ + "payment_ledger", + "invoices", + "order_status_history", + "order_items", + "orders", + "carts", + "inventory_ledger", +] + +OPENING_STOCK = 5000 + + +def log(msg: str) -> None: + print(f"[reset] {msg}", flush=True) + + +def assert_sim_database(url: str) -> str: + db_name = url.rsplit("/", 1)[-1].split("?")[0] + if not db_name.endswith("_sim"): + raise SystemExit(f"Refusing to reset non-simulation database {db_name!r}") + return db_name + + +def main() -> int: + parser = argparse.ArgumentParser(description="Reset simulation transactional data") + parser.add_argument("--yes", action="store_true", help="Required confirmation flag") + parser.add_argument("--opening-stock", type=int, default=OPENING_STOCK) + parser.add_argument("--drop-customers", action="store_true", help="Also delete sim customers/addresses") + args = parser.parse_args() + if not args.yes: + raise SystemExit("Refusing to reset without --yes") + + if not SIM_ENV.exists(): + raise SystemExit(f"Missing {SIM_ENV}; run provision_sim_db.py first") + load_dotenv(SIM_ENV, override=True) + if os.getenv("SIMULATION_MODE", "").lower() not in ("1", "true", "yes"): + raise SystemExit("Refusing to reset: SIMULATION_MODE is not true in .env.sim") + + url = os.getenv("COMMERCE_DATABASE_URL", "") + db_name = assert_sim_database(url) + engine = create_engine(url, future=True) + now = datetime.now(timezone.utc).replace(tzinfo=None) + + with engine.begin() as conn: + for table in TRANSACTIONAL_TABLES: + conn.execute(text(f"DELETE FROM {table}")) + log(f"cleared {table}") + + variants = [ + r[0] + for r in conn.execute(text("SELECT variant_id FROM product_variants WHERE status='ACTIVE'")) + ] + conn.execute( + text( + "INSERT INTO inventory_ledger " + "(ledger_id, variant_id, event_type, qty, reference_id, notes, created_at) " + "VALUES (:ledger_id, :variant_id, 'RECEIPT', :qty, 'SIM_SEED', " + "'Simulation opening stock', :created_at)" + ), + [ + { + "ledger_id": str(ulid.ULID()), + "variant_id": variant_id, + "qty": args.opening_stock, + "created_at": now, + } + for variant_id in variants + ], + ) + log(f"seeded {len(variants)} variants x {args.opening_stock} units opening stock") + + if args.drop_customers: + conn.execute(text("DELETE FROM customer_addresses")) + deleted = conn.execute( + text("DELETE FROM ecom_customers WHERE email LIKE '%@sim.example.com'") + ).rowcount + log(f"deleted {deleted} simulation customers and their addresses") + + print(f"\nReset complete: {db_name}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/sim/teardown.py b/scripts/sim/teardown.py new file mode 100644 index 0000000..fc87226 --- /dev/null +++ b/scripts/sim/teardown.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +""" +Tear down the IfixKart simulation environment. + +1. Stop the simulation backend (port 8001, `scripts/sim/run_sim_backend.py`). +2. Optionally --drop-dbs: drop the three *_sim databases on the remote MySQL. + +Production services (backend on :8000, the MySQL tunnel) are left running. + +Usage: + cd Backend + ./venv/bin/python scripts/sim/teardown.py # stop sim backend only + ./venv/bin/python scripts/sim/teardown.py --drop-dbs # also drop sim DBs +""" +from __future__ import annotations + +import argparse +import os +import re +import signal +import subprocess +import sys +from datetime import datetime, timezone +from pathlib import Path + +from dotenv import load_dotenv +from sqlalchemy import create_engine, text + +BACKEND_DIR = Path(__file__).resolve().parents[2] +SIM_ENV = BACKEND_DIR / ".env.sim" +ARTIFACT_DIR = BACKEND_DIR / "sim-artifacts" + +SIM_DBS = ["ifixkartecommerce_sim", "ifixkartecommerceadmin_sim", "ifixkartcrm_sim"] + + +def log(msg: str) -> None: + print(f"[teardown] {msg}", flush=True) + + +def stop_sim_backend() -> None: + result = subprocess.run( + ["pgrep", "-f", "scripts/sim/run_sim_backend.py"], + capture_output=True, text=True, + ) + pids = [int(p) for p in result.stdout.split()] + if not pids: + log("sim backend: not running") + return + for pid in pids: + try: + os.kill(pid, signal.SIGTERM) + log(f"sim backend: sent SIGTERM to pid {pid}") + except ProcessLookupError: + pass + for _ in range(10): + alive = subprocess.run(["pgrep", "-f", "scripts/sim/run_sim_backend.py"], capture_output=True) + if alive.returncode != 0: + break + time_module_sleep(0.5) + leftovers = subprocess.run(["pgrep", "-f", "scripts/sim/run_sim_backend.py"], capture_output=True, text=True) + for pid in [int(p) for p in leftovers.stdout.split()]: + try: + os.kill(pid, signal.SIGKILL) + log(f"sim backend: SIGKILL stubborn pid {pid}") + except ProcessLookupError: + pass + log("sim backend: stopped") + + +def time_module_sleep(seconds: float) -> None: + import time + time.sleep(seconds) + + +def parse_creds(url: str) -> tuple[str, str, str, str]: + m = re.match(r"mysql\+pymysql://([^:]+):([^@]+)@([^:/?]+):(\d+)/", url) + if not m: + raise SystemExit("Could not parse DB credentials from COMMERCE_DATABASE_URL") + return m.group(1), m.group(2), m.group(3), m.group(4) + + +def drop_sim_dbs() -> None: + if not SIM_ENV.exists(): + raise SystemExit(f"Missing {SIM_ENV}") + load_dotenv(SIM_ENV, override=True) + + # Rebuild each sim URL with the same credentials WITHOUT its database name. + user, password, host, port = parse_creds(os.getenv("COMMERCE_DATABASE_URL", "")) + base = f"mysql+pymysql://{user}:{password}@{host}:{port}/" + engine = create_engine(base, future=True) + with engine.begin() as conn: + # Safety: only drop databases whose name ends with _sim. + for db_name in SIM_DBS: + exists = conn.execute( + text("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME=:n"), + {"n": db_name}, + ).scalar() + if not exists: + log(f"{db_name}: not present, skipped") + continue + if not db_name.endswith("_sim"): + raise SystemExit(f"Refusing to drop non-simulation database {db_name}") + conn.execute(text(f"DROP DATABASE `{db_name}`")) + log(f"{db_name}: dropped") + log("simulation databases dropped") + + +def main() -> int: + parser = argparse.ArgumentParser(description="Stop simulation services and optionally drop sim DBs") + parser.add_argument("--drop-dbs", action="store_true", help="Also DROP the three *_sim databases") + args = parser.parse_args() + + stop_sim_backend() + if args.drop_dbs: + drop_sim_dbs() + else: + log("databases left intact (pass --drop-dbs to drop them)") + + stamp = datetime.now(timezone.utc).isoformat() + (ARTIFACT_DIR / "teardown.json").write_text( + f'{{"torn_down_at": "{stamp}", "dropped_dbs": {args.drop_dbs}}}\n' + ) + log("production backend (:8000) and the MySQL tunnel were left untouched") + return 0 + + +if __name__ == "__main__": + if sys.platform != "linux": + raise SystemExit("Linux only") + raise SystemExit(main()) diff --git a/swarm/agents/__init__.py b/swarm/agents/__init__.py new file mode 100644 index 0000000..6094de6 --- /dev/null +++ b/swarm/agents/__init__.py @@ -0,0 +1,5 @@ +"""LLM-planned, HTTP-driven customer agents for the IfixKart simulation.""" +from swarm.agents.customer import CustomerAgent, JourneyResult +from swarm.agents.personas import Persona, build_personas + +__all__ = ["CustomerAgent", "JourneyResult", "Persona", "build_personas"] diff --git a/swarm/agents/customer.py b/swarm/agents/customer.py new file mode 100644 index 0000000..14dcafb --- /dev/null +++ b/swarm/agents/customer.py @@ -0,0 +1,326 @@ +""" +One simulated customer = one identity + one authenticated HTTP session + one +real journey through the IfixKart API. + +The agent does not insert rows directly. It registers a session through the +normal login endpoint, browses the public catalog, adds real cart items, checks +out, pays through the simulation-only gateway and verifies the resulting order. +""" +from __future__ import annotations + +import asyncio +import random +import time +from dataclasses import asdict, dataclass, field +from typing import Any, Optional + +import httpx + +from swarm.agents.personas import Persona + + +class JourneyError(RuntimeError): + pass + + +@dataclass +class JourneyResult: + agent_index: int + email: str + persona_id: str + outcome: str + order_id: Optional[str] = None + order_no: Optional[str] = None + amount: float = 0.0 + steps: list[str] = field(default_factory=list) + error: str = "" + duration_ms: int = 0 + status_code: int = 0 + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +class CustomerAgent: + def __init__( + self, + *, + client: httpx.AsyncClient, + agent_index: int, + account: dict[str, Any], + persona: Persona, + rng: random.Random, + think_time_scale: float = 0.05, + request_timeout: float = 45.0, + metrics=None, + ) -> None: + self.client = client + self.index = agent_index + self.account = account + self.persona = persona + self.rng = rng + self.think_scale = think_time_scale + self.request_timeout = request_timeout + self.metrics = metrics + self.token: Optional[str] = None + self.steps: list[str] = [] + self.products: list[dict[str, Any]] = [] + + # ---------- low-level helpers ---------- + + async def _think(self, low: float, high: float) -> None: + delay = self.rng.uniform(low, high) * self.think_scale + if delay > 0: + await asyncio.sleep(delay) + + async def _request( + self, + method: str, + path: str, + *, + expected: tuple[int, ...] = (200,), + **kwargs, + ) -> httpx.Response: + headers = kwargs.pop("headers", {}) + headers.setdefault("user-agent", f"IfixKartSwarm/{self.persona.device}") + if self.token: + headers.setdefault("authorization", f"Bearer {self.token}") + started = time.perf_counter() + try: + response = await self.client.request( + method, + path, + headers=headers, + timeout=self.request_timeout, + **kwargs, + ) + except Exception as exc: + if self.metrics: + await self.metrics.record_request(path, 0, time.perf_counter() - started, error=type(exc).__name__) + raise JourneyError(f"{method} {path} failed: {type(exc).__name__}: {exc}") from exc + elapsed = time.perf_counter() - started + if self.metrics: + await self.metrics.record_request(path, response.status_code, elapsed) + if response.status_code not in expected: + text = response.text[:500].replace("\n", " ") + raise JourneyError(f"{method} {path} -> {response.status_code}: {text}") + return response + + # ---------- journey steps ---------- + + async def _login(self) -> None: + response = await self._request( + "POST", + "/api/v1/customer/auth/login", + expected=(200,), + json={"email": self.account["email"], "password": self.account["password"]}, + ) + self.token = response.json()["access_token"] + self.steps.append("login") + + async def _get_address(self) -> str: + response = await self._request("GET", "/api/v1/customer/profile/addresses", expected=(200,)) + addresses = response.json() + if addresses: + self.steps.append("load_address") + return addresses[0]["address_id"] + + payload = { + "address_type": "SHIPPING", + "full_name": f"{self.account['first_name']} {self.account['last_name']}", + "phone": f"9{self.rng.randint(100000000, 999999999)}"[:10], + "street_address": f"{self.rng.randint(1, 200)}, {self.rng.choice(['MG Road', 'Anna Nagar', 'Banjara Hills', 'Park Street'])}", + "city": self.persona.city, + "state": self.persona.state, + "pincode": self.persona.pincode, + "is_default": True, + } + response = await self._request("POST", "/api/v1/customer/profile/addresses", expected=(200,), json=payload) + self.steps.append("create_address") + return response.json()["address_id"] + + async def _catalog(self) -> None: + page = 1 + products: list[dict[str, Any]] = [] + while True: + response = await self._request( + "GET", + "/api/v1/catalog/products", + expected=(200,), + params={"page": page, "limit": 100}, + ) + body = response.json() + batch = body.get("products") or [] + products.extend(batch) + if not batch or len(products) >= int(body.get("total") or 0) or page >= 3: + break + page += 1 + self.products = [p for p in products if p.get("first_variant_id")] + if not self.products: + raise JourneyError("catalog returned no purchasable variants") + self.steps.append(f"catalog:{len(self.products)}") + + def _choose_products(self) -> list[dict[str, Any]]: + def score(product: dict[str, Any]) -> tuple[float, float]: + name = (product.get("name") or "").lower() + price = float(product.get("price") or 0) + affinity = 0.0 + for keyword in self.persona.preferred_keywords: + if keyword in name: + affinity += 2.0 + if price <= self.persona.budget_max: + affinity += 1.0 + else: + affinity -= 2.0 + return (affinity, self.rng.random()) + + ranked = sorted(self.products, key=score, reverse=True) + in_budget = [p for p in ranked if float(p.get("price") or 0) <= self.persona.budget_max] + chosen = in_budget or sorted(self.products, key=lambda p: float(p.get("price") or 0)) + return chosen[: max(4, self.persona.browse_depth + 2)] + + async def _browse(self) -> bool: + candidates = self._choose_products() + depth = min(self.persona.browse_depth, len(candidates)) + for product in candidates[:depth]: + slug = product.get("slug") + if not slug: + continue + try: + await self._request("GET", f"/api/v1/catalog/products/detail/{slug}", expected=(200,)) + except JourneyError: + # A detail page 404 should not kill the whole journey. + pass + await self._think(1.0, 4.0) + self.steps.append(f"browse:{depth}") + return self.rng.random() < self.persona.conversion_prob + + async def _add_to_cart(self, candidates: list[dict[str, Any]]) -> float: + added = 0 + total_qty = 0 + desired = 1 + if self.rng.random() < 0.25: + desired = 2 + + for product in candidates: + if added >= 2: + break + qty = self.persona.quantity_pref if added == 0 else 1 + if desired == 1: + qty = 1 + try: + response = await self._request( + "POST", + "/api/v1/cart/items", + expected=(200,), + json={"variant_id": product["first_variant_id"], "qty": qty}, + ) + added += 1 + total_qty += qty + self.steps.append(f"cart_add:{product.get('slug', '')[:40]}:{qty}") + await self._think(1.0, 3.0) + if response.json().get("total_amount") is not None: + continue + except JourneyError: + continue + + if added == 0: + raise JourneyError("could not add any item to cart") + self.steps.append(f"cart_items:{total_qty}") + return total_qty + + async def run(self) -> JourneyResult: + started = time.perf_counter() + result = JourneyResult( + agent_index=self.index, + email=self.account["email"], + persona_id=self.persona.persona_id, + outcome="ERROR", + ) + try: + await self._login() + await self._think(0.5, 2.0) + + address_id = await self._get_address() + await self._think(0.5, 2.0) + + await self._catalog() + await self._think(1.0, 3.0) + + candidates = self._choose_products() + wants_to_buy = await self._browse() + if not wants_to_buy: + result.outcome = "BROWSE_ABANDON" + result.steps = self.steps + result.duration_ms = int((time.perf_counter() - started) * 1000) + return result + + await self._add_to_cart(candidates) + await self._think(1.0, 4.0) + + if self.rng.random() < self.persona.cart_abandon_prob: + result.outcome = "CART_ABANDON" + result.steps = self.steps + result.duration_ms = int((time.perf_counter() - started) * 1000) + return result + + checkout = await self._request( + "POST", + "/api/v1/checkout/create", + expected=(200,), + json={"address_id": address_id, "payment_method": "RAZORPAY"}, + ) + order = checkout.json() + result.order_id = order.get("order_id") + result.order_no = order.get("order_no") + result.amount = float(order.get("final_amount") or 0) + self.steps.append("checkout") + await self._think(1.0, 4.0) + + if self.rng.random() < self.persona.payment_fail_prob: + try: + await self._request( + "POST", + "/api/v1/payment/cancel", + expected=(200,), + json={"order_id": result.order_id, "reason": "Simulated payment failure/abandonment"}, + ) + except JourneyError: + pass + result.outcome = "PAYMENT_FAILED" + result.steps = self.steps + result.duration_ms = int((time.perf_counter() - started) * 1000) + return result + + paid = await self._request( + "POST", + "/api/v1/payment/simulate", + expected=(200,), + json={"order_id": result.order_id, "note": "IfixKart swarm simulated payment"}, + ) + self.steps.append("payment_simulated") + body = paid.json() + if body.get("status") != "SUCCESS": + raise JourneyError(f"simulated payment did not succeed: {body}") + + verified = await self._request( + "GET", + f"/api/v1/orders/{result.order_id}", + expected=(200,), + ) + final = verified.json() + result.outcome = "ORDER_CONFIRMED" + result.amount = float(final.get("final_amount") or result.amount) + self.steps.append("order_verified") + return result + except JourneyError as exc: + result.outcome = "ERROR" + result.error = str(exc) + result.status_code = 0 + except Exception as exc: # defensive: never let one agent kill the fleet + result.outcome = "ERROR" + result.error = f"{type(exc).__name__}: {exc}" + finally: + result.steps = self.steps + result.duration_ms = int((time.perf_counter() - started) * 1000) + return result diff --git a/swarm/agents/orchestrator.py b/swarm/agents/orchestrator.py new file mode 100644 index 0000000..acef8b5 --- /dev/null +++ b/swarm/agents/orchestrator.py @@ -0,0 +1,201 @@ +""" +Async fleet orchestrator: run N customer agents with bounded concurrency, +realistic staggered arrival and per-endpoint telemetry. +""" +from __future__ import annotations + +import asyncio +import json +import math +import random +import time +from collections import Counter, defaultdict +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import httpx + +from swarm.agents.customer import CustomerAgent, JourneyResult +from swarm.agents.personas import Persona, persona_for_agent + + +def _percentile(values: list[float], pct: float) -> float: + if not values: + return 0.0 + ordered = sorted(values) + idx = min(len(ordered) - 1, max(0, int(math.ceil(pct / 100.0 * len(ordered))) - 1)) + return ordered[idx] + + +class Metrics: + def __init__(self) -> None: + self.lock = asyncio.Lock() + self.requests: Counter[tuple[str, int]] = Counter() + self.latencies: dict[str, list[float]] = defaultdict(list) + self.request_errors: Counter[str] = Counter() + self.outcomes: Counter[str] = Counter() + self.orders: list[dict[str, Any]] = [] + self.errors: Counter[str] = Counter() + self.completed = 0 + + async def record_request(self, path: str, status: int, seconds: float, error: str = "") -> None: + # Normalise dynamic IDs so latency buckets stay stable. + key = path.split("?")[0] + if key.startswith("/api/v1/orders/"): + key = "/api/v1/orders/{id}" + if key.startswith("/api/v1/catalog/products/detail/"): + key = "/api/v1/catalog/products/detail/{slug}" + async with self.lock: + self.requests[(key, status)] += 1 + self.latencies[key].append(seconds) + if error: + self.request_errors[error] += 1 + + async def record_result(self, result: JourneyResult) -> None: + async with self.lock: + self.completed += 1 + self.outcomes[result.outcome] += 1 + if result.outcome == "ORDER_CONFIRMED": + self.orders.append( + { + "order_id": result.order_id, + "order_no": result.order_no, + "amount": result.amount, + "email": result.email, + "persona_id": result.persona_id, + } + ) + elif result.outcome == "ERROR": + message = result.error[:180] + self.errors[message] += 1 + + def summary(self, started_at: datetime, duration_s: float, count: int) -> dict[str, Any]: + total_requests = sum(self.requests.values()) + statuses: Counter[int] = Counter() + for (_path, status), n in self.requests.items(): + statuses[status] += n + latency = {} + for path, values in self.latencies.items(): + latency[path] = { + "count": len(values), + "p50_ms": round(_percentile(values, 50) * 1000, 1), + "p95_ms": round(_percentile(values, 95) * 1000, 1), + "p99_ms": round(_percentile(values, 99) * 1000, 1), + "max_ms": round(max(values) * 1000, 1), + } + revenue = round(sum(o["amount"] for o in self.orders), 2) + return { + "started_at": started_at.isoformat(), + "duration_seconds": round(duration_s, 1), + "agents_requested": count, + "agents_completed": self.completed, + "outcomes": dict(self.outcomes), + "orders_confirmed": len(self.orders), + "revenue": revenue, + "aov": round(revenue / len(self.orders), 2) if self.orders else 0.0, + "total_http_requests": total_requests, + "http_statuses": {str(k): v for k, v in sorted(statuses.items())}, + "request_errors": dict(self.request_errors), + "endpoint_latency": latency, + "top_errors": [{"error": k, "count": v} for k, v in self.errors.most_common(15)], + "orders_sample": self.orders[:20], + } + + +async def run_fleet( + *, + base_url: str, + accounts: list[dict[str, Any]], + base_personas: list[Persona], + count: int, + concurrency: int, + think_time_scale: float, + ramp_seconds: float, + seed: int, + request_timeout: float, + progress_every: int = 100, +) -> dict[str, Any]: + count = min(count, len(accounts)) + if count <= 0: + raise ValueError("no agent accounts supplied") + if not base_personas: + raise ValueError("empty persona bank") + + metrics = Metrics() + rng = random.Random(seed) + plans = [ + (accounts[i], persona_for_agent(base_personas, i, rng)) + for i in range(count) + ] + + limits = httpx.Limits( + max_connections=max(50, concurrency * 2), + max_keepalive_connections=max(20, concurrency), + keepalive_expiry=30.0, + ) + semaphore = asyncio.Semaphore(concurrency) + started_wall = datetime.now(timezone.utc) + started = time.perf_counter() + + async with httpx.AsyncClient( + base_url=base_url, + timeout=request_timeout, + limits=limits, + follow_redirects=False, + ) as client: + + async def one(index: int, account: dict[str, Any], persona: Persona) -> JourneyResult: + if ramp_seconds > 0 and count > 1: + await asyncio.sleep(ramp_seconds * index / (count - 1)) + agent = CustomerAgent( + client=client, + agent_index=index, + account=account, + persona=persona, + rng=random.Random(seed + index * 7919), + think_time_scale=think_time_scale, + request_timeout=request_timeout, + metrics=metrics, + ) + async with semaphore: + result = await agent.run() + await metrics.record_result(result) + async with metrics.lock: + done = metrics.completed + if done % max(1, progress_every) == 0 or done == count: + elapsed = time.perf_counter() - started + rate = done / elapsed if elapsed else 0 + print( + f"[fleet] {done}/{count} agents | {rate:.1f}/s | " + f"orders={len(metrics.orders)} | outcomes={dict(metrics.outcomes)}", + flush=True, + ) + return result + + tasks = [ + asyncio.create_task(one(i, account, persona)) + for i, (account, persona) in enumerate(plans) + ] + results = await asyncio.gather(*tasks, return_exceptions=True) + + for result in results: + if isinstance(result, Exception): + await metrics.record_result( + JourneyResult( + agent_index=-1, + email="", + persona_id="", + outcome="ERROR", + error=f"orchestrator: {type(result).__name__}: {result}", + ) + ) + + duration = time.perf_counter() - started + return metrics.summary(started_wall, duration, count) + + +def write_report(report: dict[str, Any], output: Path) -> None: + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(json.dumps(report, indent=2)) + print(f"[fleet] report written to {output}") diff --git a/swarm/agents/personas.py b/swarm/agents/personas.py new file mode 100644 index 0000000..93461ac --- /dev/null +++ b/swarm/agents/personas.py @@ -0,0 +1,279 @@ +""" +Persona bank for the IfixKart customer swarm. + +The local LLM is used offline to create a diverse bank of shopper personas. +Each of the 10k agents then gets a persona sampled (with jitter) from that bank, +so the LLM is never in the per-request hot path. +""" +from __future__ import annotations + +import json +import random +import re +from dataclasses import asdict, dataclass, field +from typing import Any + +import httpx + +DEFAULT_OLLAMA = "http://127.0.0.1:11434" +DEFAULT_MODEL = "qwen3.5:4b" + +CATEGORY_KEYWORDS = [ + "display", + "touch screen", + "battery", + "back panel", + "screen guard", + "charger", + "camera", + "speaker", + "motorola", + "samsung", + "redmi", + "realme", + "vivo", + "oppo", + "iphone", +] + +INDIAN_CITIES = [ + ("Bengaluru", "Karnataka", "560001"), + ("Mysuru", "Karnataka", "570001"), + ("Hyderabad", "Telangana", "500001"), + ("Chennai", "Tamil Nadu", "600001"), + ("Coimbatore", "Tamil Nadu", "641001"), + ("Mumbai", "Maharashtra", "400001"), + ("Pune", "Maharashtra", "411001"), + ("Delhi", "Delhi", "110001"), + ("Noida", "Uttar Pradesh", "201301"), + ("Jaipur", "Rajasthan", "302001"), + ("Ahmedabad", "Gujarat", "380001"), + ("Kochi", "Kerala", "682001"), + ("Kolkata", "West Bengal", "700001"), + ("Visakhapatnam", "Andhra Pradesh", "530001"), + ("Indore", "Madhya Pradesh", "452001"), + ("Chandigarh", "Chandigarh", "160001"), +] + + +@dataclass +class Persona: + persona_id: str + name: str + age: int + city: str + state: str + pincode: str + budget_max: float + browse_depth: int + conversion_prob: float + cart_abandon_prob: float + payment_fail_prob: float + preferred_keywords: list[str] = field(default_factory=list) + quantity_pref: int = 1 + device: str = "mobile" + notes: str = "" + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> "Persona": + def num(key: str, default: float) -> float: + # Use an explicit None check: a legitimate 0.0 must not fall back + # to the default (e.g. zero cart-abandonment for verification runs). + value = data.get(key) + return default if value is None else float(value) + + return cls( + persona_id=str(data.get("persona_id") or "p"), + name=str(data.get("name") or "Shopper"), + age=int(num("age", 30)), + city=str(data.get("city") or "Bengaluru"), + state=str(data.get("state") or "Karnataka"), + pincode=str(data.get("pincode") or "560001"), + budget_max=num("budget_max", 15000), + browse_depth=max(1, min(8, int(num("browse_depth", 3)))), + conversion_prob=max(0.005, min(0.6, num("conversion_prob", 0.06))), + cart_abandon_prob=max(0.0, min(0.95, num("cart_abandon_prob", 0.55))), + payment_fail_prob=max(0.0, min(0.5, num("payment_fail_prob", 0.05))), + preferred_keywords=[ + str(k).lower() for k in (data.get("preferred_keywords") or []) + if str(k).strip() + ][:5], + quantity_pref=max(1, min(3, int(num("quantity_pref", 1)))), + device=str(data.get("device") or "mobile"), + notes=str(data.get("notes") or "")[:400], + ) + + +def _extract_json(text: str) -> Any: + text = text.strip() + text = re.sub(r"^```(?:json)?\s*", "", text) + text = re.sub(r"\s*```$", "", text) + start = text.find("[") + end = text.rfind("]") + if start >= 0 and end > start: + candidate = text[start:end + 1] + try: + return json.loads(candidate) + except json.JSONDecodeError: + # Small local models emit slightly malformed JSON; salvage objects + # one by one and keep whatever parses cleanly. + objects = [] + for m in re.finditer(r"\{", candidate): + depth = 0 + in_str = False + esc = False + for idx in range(m.start(), len(candidate)): + ch = candidate[idx] + if in_str: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == '"': + in_str = False + continue + if ch == '"': + in_str = True + elif ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + try: + objects.append(json.loads(candidate[m.start():idx + 1])) + except json.JSONDecodeError: + pass + break + if objects: + return objects + start = text.find("{") + end = text.rfind("}") + if start >= 0 and end > start: + return json.loads(text[start:end + 1]) + raise ValueError("no JSON found") + + +def llm_personas( + count: int = 30, + model: str = DEFAULT_MODEL, + ollama_url: str = DEFAULT_OLLAMA, + timeout: int = 180, + seed: int = 42, +) -> list[Persona]: + """Ask the local Ollama model for a diverse bank of shopper personas.""" + prompt = f"""You are generating synthetic but realistic Indian e-commerce shoppers for a mobile-parts store (displays, batteries, back panels, screen guards). + +Return ONLY a JSON array of {count} objects. No markdown, no commentary. +Each object must have exactly these fields: +persona_id (string p01...), name (Indian name), age (18-55), city, state, pincode (valid 6 digits), +budget_max (number between 1500 and 30000), browse_depth (1-6), +conversion_prob (0.01-0.20), cart_abandon_prob (0.35-0.85), payment_fail_prob (0.01-0.15), +preferred_keywords (array of 1-3 from: display, touch screen, battery, back panel, screen guard, motorola, samsung, redmi, realme, vivo, oppo, iphone), +quantity_pref (1-2), device (mobile/tablet/laptop), notes (short sentence about their shopping style). + +Make the personas diverse in age, city, budget, patience, device type and intent. Vary conversion_prob realistically (low for browsers, higher for repair-shop owners).""" + payload = { + "model": model, + "prompt": prompt, + "stream": False, + "options": {"temperature": 0.9, "num_predict": 4096, "seed": seed}, + } + with httpx.Client(timeout=timeout) as client: + r = client.post(f"{ollama_url.rstrip('/')}/api/generate", json=payload) + r.raise_for_status() + body = r.json() + raw = body.get("response", "") + data = _extract_json(raw) + if isinstance(data, dict): + data = data.get("personas") or [data] + personas = [Persona.from_dict(item) for item in data if isinstance(item, dict)] + if not personas: + raise ValueError("LLM returned no personas") + return personas[:count] + + +def fallback_personas(seed: int = 42) -> list[Persona]: + """Deterministic diverse bank used when Ollama is unavailable.""" + rng = random.Random(seed) + templates = [ + ("repair-shop owner", 0.18, 0.35, ["display", "touch screen", "battery"], 2, 26000), + ("budget student", 0.05, 0.70, ["battery", "screen guard"], 1, 4500), + ("working professional", 0.08, 0.55, ["display", "back panel"], 1, 18000), + ("small reseller", 0.22, 0.30, ["display", "battery", "motorola"], 2, 30000), + ("careful comparer", 0.04, 0.78, ["screen guard", "battery"], 1, 9000), + ("urgent repair", 0.25, 0.20, ["display", "touch screen"], 1, 15000), + ("gift buyer", 0.06, 0.65, ["screen guard", "back panel"], 1, 7000), + ("loyal Samsung user", 0.10, 0.50, ["samsung", "display"], 1, 22000), + ("Xiaomi enthusiast", 0.09, 0.52, ["redmi", "battery"], 1, 12000), + ("tablet owner", 0.07, 0.60, ["display", "touch screen"], 1, 20000), + ("laptop gamer", 0.05, 0.72, ["battery", "screen guard"], 1, 10000), + ("impulse buyer", 0.16, 0.40, ["screen guard", "back panel"], 2, 6000), + ] + out: list[Persona] = [] + for i in range(40): + label, conv, abandon, keys, qty, budget = templates[i % len(templates)] + city, state, pin = rng.choice(INDIAN_CITIES) + out.append( + Persona( + persona_id=f"p{i + 1:03d}", + name=f"Shopper {i + 1}", + age=rng.randint(18, 55), + city=city, + state=state, + pincode=pin, + budget_max=round(budget * rng.uniform(0.75, 1.2), 2), + browse_depth=rng.randint(1, 6), + conversion_prob=max(0.01, conv * rng.uniform(0.7, 1.35)), + cart_abandon_prob=min(0.9, abandon * rng.uniform(0.85, 1.15)), + payment_fail_prob=rng.uniform(0.01, 0.10), + preferred_keywords=keys, + quantity_pref=qty, + device=rng.choice(["mobile", "mobile", "mobile", "tablet", "laptop"]), + notes=label, + ) + ) + return out + + +def build_personas( + count: int, + *, + model: str | None = DEFAULT_MODEL, + ollama_url: str = DEFAULT_OLLAMA, + seed: int = 42, +) -> list[Persona]: + """Create a base bank, using the local LLM when possible and falling back.""" + if model: + try: + base = llm_personas(count=count, model=model, ollama_url=ollama_url, seed=seed) + print(f"[personas] generated {len(base)} personas with {model}") + return base + except Exception as exc: + print(f"[personas] LLM unavailable ({exc}); using deterministic bank") + return fallback_personas(seed=seed) + + +def persona_for_agent(base: list[Persona], index: int, rng: random.Random) -> Persona: + """Sample one base persona and jitter it so 10k agents are not clones.""" + p = rng.choice(base) + city, state, pin = rng.choice(INDIAN_CITIES) + return Persona( + persona_id=f"{p.persona_id}-{index:06d}", + name=p.name, + age=max(18, min(60, p.age + rng.randint(-4, 4))), + city=city, + state=state, + pincode=pin, + budget_max=round(p.budget_max * rng.uniform(0.85, 1.15), 2), + browse_depth=max(1, min(7, p.browse_depth + rng.choice([-1, 0, 0, 1]))), + conversion_prob=max(0.005, min(0.5, p.conversion_prob * rng.uniform(0.7, 1.4))), + cart_abandon_prob=max(0.0, min(0.95, p.cart_abandon_prob * rng.uniform(0.85, 1.15))), + payment_fail_prob=max(0.0, min(0.4, p.payment_fail_prob * rng.uniform(0.7, 1.3))), + preferred_keywords=list(p.preferred_keywords), + quantity_pref=p.quantity_pref, + device=p.device, + notes=p.notes, + ) diff --git a/swarm/agents/runner.py b/swarm/agents/runner.py new file mode 100644 index 0000000..08814b1 --- /dev/null +++ b/swarm/agents/runner.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +""" +Run the IfixKart customer swarm. + +Example: + cd Backend + ./venv/bin/python -m swarm.agents.runner \ + --agents-file sim-artifacts/agents-smoke.json \ + --count 20 --concurrency 20 --think-time-scale 0.02 + +For 10k: + ./venv/bin/python -m swarm.agents.runner \ + --agents-file sim-artifacts/agents-.json \ + --count 10000 --concurrency 250 --ramp-seconds 120 --think-time-scale 0.01 +""" +from __future__ import annotations + +import argparse +import asyncio +import json +import sys +from datetime import datetime, timezone +from pathlib import Path + +BACKEND_DIR = Path(__file__).resolve().parents[2] +if str(BACKEND_DIR) not in sys.path: + sys.path.insert(0, str(BACKEND_DIR)) + +from swarm.agents.orchestrator import run_fleet, write_report # noqa: E402 +from swarm.agents.personas import Persona, build_personas # noqa: E402 + +DEFAULT_AGENTS = BACKEND_DIR / "sim-artifacts" / "agents-smoke.json" +DEFAULT_OUT = BACKEND_DIR / "sim-artifacts" + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run the IfixKart simulated customer swarm") + parser.add_argument("--base-url", default="http://127.0.0.1:8001") + parser.add_argument("--agents-file", default=str(DEFAULT_AGENTS)) + parser.add_argument("--count", type=int, default=20) + parser.add_argument("--concurrency", type=int, default=50) + parser.add_argument("--think-time-scale", type=float, default=0.02) + parser.add_argument("--ramp-seconds", type=float, default=5.0) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--request-timeout", type=float, default=45.0) + parser.add_argument("--llm-model", default="qwen3.5:4b", help="Ollama model for persona bank; empty disables") + parser.add_argument("--ollama-url", default="http://127.0.0.1:11434") + parser.add_argument("--persona-count", type=int, default=24) + parser.add_argument("--persona-file", default="", help="Reuse an existing persona bank JSON") + parser.add_argument("--output", default="") + args = parser.parse_args() + + agents_path = Path(args.agents_file) + if not agents_path.exists(): + raise SystemExit(f"Agents file not found: {agents_path}; run seed_customers.py first") + data = json.loads(agents_path.read_text()) + accounts = data.get("agents") or [] + run_id = data.get("run_id") or datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S") + + if args.persona_file: + persona_data = json.loads(Path(args.persona_file).read_text()) + base_personas = [Persona.from_dict(p) for p in persona_data.get("personas", persona_data)] + print(f"[runner] loaded {len(base_personas)} personas from {args.persona_file}") + else: + base_personas = build_personas( + args.persona_count, + model=args.llm_model or None, + ollama_url=args.ollama_url, + seed=args.seed, + ) + persona_out = DEFAULT_OUT / f"personas-{run_id}.json" + persona_out.parent.mkdir(parents=True, exist_ok=True) + persona_out.write_text( + json.dumps( + { + "run_id": run_id, + "model": args.llm_model or "deterministic", + "personas": [p.to_dict() for p in base_personas], + }, + indent=2, + ) + ) + print(f"[runner] persona bank saved to {persona_out}") + + print( + f"[runner] base_url={args.base_url} agents={min(args.count, len(accounts))} " + f"concurrency={args.concurrency} think_scale={args.think_time_scale}" + ) + report = asyncio.run( + run_fleet( + base_url=args.base_url, + accounts=accounts, + base_personas=base_personas, + count=args.count, + concurrency=args.concurrency, + think_time_scale=args.think_time_scale, + ramp_seconds=args.ramp_seconds, + seed=args.seed, + request_timeout=args.request_timeout, + progress_every=10 if args.count <= 100 else max(50, args.count // 20), + ) + ) + report["run_id"] = run_id + report["base_url"] = args.base_url + report["persona_model"] = args.llm_model or "deterministic" + report["concurrency"] = args.concurrency + output = Path(args.output) if args.output else DEFAULT_OUT / f"report-{run_id}-{int(report['agents_requested'])}.json" + write_report(report, output) + + print("\n=== SWARM SUMMARY ===") + print(f"agents completed : {report['agents_completed']}/{report['agents_requested']}") + print(f"duration : {report['duration_seconds']}s") + print(f"outcomes : {report['outcomes']}") + print(f"orders confirmed : {report['orders_confirmed']}") + print(f"revenue : β‚Ή{report['revenue']:,}") + print(f"AOV : β‚Ή{report['aov']:,}") + print(f"HTTP requests : {report['total_http_requests']}") + print(f"HTTP statuses : {report['http_statuses']}") + if report["top_errors"]: + print("top errors :") + for err in report["top_errors"][:8]: + print(f" {err['count']}x {err['error']}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())