- Backend: FastAPI app with all models, services, schemas, routes - Admin Panel: Next.js dashboard with all modules (CRM, POS, repairs, warranties, billing, notifications, etc.) - Ecommerce: storefront (submodule) + product catalog - AI Agents: .agents/ skill library for Antigravity IDE - Docs: architecture, billing, notification gateway markdown - Submodules: Backend/OpenWA, Ecommerce/File 2/storefront
48 KiB
48 KiB
Session Summary
Master Architectural Implementation — iFixKart Unified Suite (Phases 0 - 8)
Phase 0: Foundation & Base Infrastructure Setup
- Config & Telemetry (Config.py): Configured ZeptoMail API Key (
PHtE...), Sender (info@trionixsolution.com), OpenWA Gateway (http://localhost:8088), and Redis Streams URL (redis://127.0.0.1:6379/0). - Multi-Tenant Context (RoleChecker.py): Injected
request.state.tenant_idcontext into request execution pipeline. - Event Bus (event_publisher.py): Built Redis Streams event publisher with graceful fallback for decoupled domain events.
- Health Verification Router (HealthRouter.py): Implemented telemetry endpoints
/health,/health/db,/health/redis,/health/whatsapp, and/health/email. Registered in main.py.
Phase 1: CRM Core Engine Integration
- SQLAlchemy Models (CrmModel.py): Created
CrmCustomer,CrmContact,CrmLead, andCrmDealenforcingUNIQUE(tenant_id, phone). Registered in db_base.py. - Service & Router (CrmService.py, CrmRouter.py): Auto-calculates LTV sales tier, VIP service tier, and Customer 360 profile aggregation.
- Admin Panel UI (crm-deals/page.tsx, crm-leads/page.tsx): Built CRM Deals Kanban board (
/crm-deals) and Inbound CRM Leads list (/crm-leads).
Phase 2: Repair ERP & IMEI Lifecycle Engine
- SQLAlchemy Models (RepairErpModel.py): Created
CrmCustomerDeviceandCrmRepairTicketenforcingUNIQUE(tenant_id, imei_serial). - Service & Router (RepairErpService.py, RepairErpRouter.py): IMEI lookup history, 5-stage repair ticket lifecycle (
INTAKE,DIAGNOSING,REPAIRING,COMPLETED,DELIVERED), SLA breach alerts. - Admin Panel UI (repair-tickets/page.tsx): Built 5-Stage Repair Ticket board with live SLA timers and IMEI lookup (
/repair-tickets).
Phase 3: Inventory + E-Commerce POS Integration
- SQLAlchemy Models (InventoryPosModel.py): Created
CrmWarehouse,CrmSupplier,CrmInventoryStock, andCrmPosSession. - Service & Router (InventoryPosService.py, InventoryPosRouter.py): Multi-warehouse stock routing, reorder thresholds, POS session open/close logic.
- Admin Panel UI (warehouses/page.tsx, pos-sessions/page.tsx): Built Multi-Warehouse Manager (
/warehouses) and POS Session & Cash Reconciliation manager (/pos-sessions).
Phase 4: Billing & GST Finance Module
- SQLAlchemy Models (BillingFinanceModel.py): Created
CrmBulkQuotation,CrmBulkQuotationItem,CrmGstInvoice,CrmInvoiceItem. - Service & Router (BillingFinanceService.py, BillingFinanceRouter.py): 1-click quote-to-invoice conversion, CGST/SGST/IGST tax splits, 6-month IMEI warranty stamping.
- Admin Panel UI (bulk-quotations/page.tsx): Built B2B Bulk Quotation manager with 1-click quote-to-GST invoice converter (
/bulk-quotations).
Phase 5: Notification Gateway (OpenWA & ZeptoMail)
- SQLAlchemy Models (NotificationModel.py): Created
Notification,NotificationAttempt,DeadLetterNotification, andWhatsAppSession. - Service & Router (NotificationGatewayService.py, NotificationGatewayRouter.py): ZeptoMail API client (
info@trionixsolution.com), OpenWA gateway HTTP dispatcher (http://localhost:8088), 3-retry delivery, Dead Letter Queue (DLQ). - Admin Panel UI (notifications-gateway/page.tsx): Built WhatsApp Web QR scanner modal, live session status indicator, delivery logs, and DLQ control panel (
/notifications-gateway).
Phase 6: Review & Reputation Moderation Engine
- SQLAlchemy Model & Service (ReviewModel.py, ReviewModerationService.py): Profanity blocklist auto-flagging, moderation workflow (
PENDING_MODERATION->APPROVED/REJECTED/FLAGGED), verified buyer verification, CSAT score calculation (0..100%). - Admin Panel UI (reviews-moderation/page.tsx): Active review moderation panel with search, filters, and approve/unpublish controls (
/reviews-moderation).
Phase 7: Multi-Dashboard Suite & SLA Management
- Service & Router (MultiDashboardService.py, MultiDashboardRouter.py): Real-time aggregation for Executive (MRR, GST, CSAT), Store Manager (POS Cash/UPI, stockouts), Technician Workshop (SLA countdowns), B2B Wholesale (Quote pipeline), and Customer Portal.
- Admin Panel UI (dashboard/page.tsx): Integrated role-based switcher tabs (Main Overview, Executive C-Suite, Store Manager, Technician Workshop, B2B Wholesale).
Phase 8: Verification & Parity Audit
- Backend Compilation Test:
python3 -m py_compile $(find Backend/app -name "*.py"). Result: PASSED (0 errors). - Admin Panel TypeScript Test:
npx tsc --noEmit. Result: PASSED (0 errors). - Sidebar Integration (Sidebar.tsx): Navigation updated with all new domain module links.
Phase 10: Dedicated Modular CRM Navigation & Routes
- Sidebar Expansion (Sidebar.tsx): Replaced single tab page with separate individual navigation items under
CRM & Sales Pipeline. - Dedicated Stage Pages: Created distinct Next.js route components:
- crm-leads/new/page.tsx (
/crm-leads/new): 1. Inbound New Inquiries - crm-leads/contacted/page.tsx (
/crm-leads/contacted): 2. Contacted Leads + WhatsApp - crm-leads/qualified/page.tsx (
/crm-leads/qualified): 3. Qualified Leads - crm-leads/quote-sent/page.tsx (
/crm-leads/quote-sent): 4. Quote Sent Leads - crm-leads/converted/page.tsx (
/crm-leads/converted): 5. Converted Leads - customers/service/page.tsx (
/customers/service): Service Repair Customers
- crm-leads/new/page.tsx (
Phase 11: WhatsApp Gateway QR Scanner & Formatting Fix
- Backend QR Generator (NotificationGatewayService.py): Updated
get_whatsapp_qrto return a valid scanable QR code image URL.
Phase 12: CRM Quotation Pipeline, Phone Normalization & Interactive B2B Modals
- Database Schema & Models (CrmModel.py, Crm.py, CrmService.py):
- Added structured quote fields to
CrmLead:quote_amount(Numeric(12, 2)fixed precision),quote_title,quote_terms,quote_sent_at, andquote_sent_by(ForeignKey("users.user_id")). - Added
trigger_customer_login_leadin CustomerAuthRouter.py to automatically record customer login events as new CRM leads.
- Added structured quote fields to
- Frontend CRM & Phone Helpers (crmService.ts):
normalizeIndianPhone(): Normalizes 10-digit input to91XXXXXXXXXXwithout storing+91in DB to prevent+91 +91duplication.formatPhoneDisplay(): Display layer helper rendering+91 XXXXXXXXXX.buildQuotationWhatsAppUrl(): Reusable URL builder encoding customer name, quote title, amount (₹), and terms into a WhatsAppwa.memessage.
- Interactive CRM & Sales Stage Pages:
- Stage 3 (
/crm-leads/qualified): Built interactive Send Quotation modal with read-only phone display (+91), custom amount, terms, and draft quotation navigation to/bulk-quotations. Added "Mark as Lost" modal with loss reasons. - Stage 4 (
/crm-leads/quote-sent): Visualizes structured quote details badge (₹24,500), terms, and phone (+91 9812345678). Features action buttons "Resend WhatsApp", "Simulate Reject" (moves lead back to Qualified), and "Simulate Accept & Convert Lead".
- Stage 3 (
- Interactive B2B Bulk Quotations Modal (bulk-quotations/page.tsx):
- Connected "+ New B2B Quotation" button to an interactive modal. Supports auto-populating query parameters (
lead_id,customer_name,phone,email). - Line items editor with Qty, Price, Subtotal, 18% GST calculation, Grand Total, and buttons for "Save Draft Quote" & "Send Quote via WhatsApp".
- Connected "+ New B2B Quotation" button to an interactive modal. Supports auto-populating query parameters (
- POS Sessions Counter Modal (pos-sessions/page.tsx):
- Connected "+ Open New Counter Session" button to open modal for Terminal ID and Opening Cash Float (₹), calling
inventoryPosService.openPosSession().
- Connected "+ Open New Counter Session" button to open modal for Terminal ID and Opening Cash Float (₹), calling
Phase 13: Dedicated CRM Customer Sales Quotation System (/crm-quotations)
- Dedicated Route & Navigation:
- Built
app/(admin)/crm-quotations/page.tsx(/crm-quotations) dedicated to CRM retail & repair customer sales quotations (separated from corporate B2B bulk quotations). - Integrated "CRM Sales Quotations" directly into the
CRM & Sales Pipelinesection in Sidebar.tsx.
- Built
- Stage 3 Qualified Leads Integration:
- Updated crm-leads/qualified/page.tsx so clicking "Draft" on a lead card smoothly navigates to
/crm-quotations?lead_id=...with prefilled customer details (customer_name,phone,email).
- Updated crm-leads/qualified/page.tsx so clicking "Draft" on a lead card smoothly navigates to
- Interactive Dual Selectors:
- "+ Add Product Catalog": Multi-step sub-modal selecting Brand
\rightarrowDevice Type\rightarrowDevice Model\rightarrowProduct Component / Spare Part with auto-calculated pricing. - "+ Add Repair Service": Multi-step sub-modal selecting Brand
\rightarrowDevice Type\rightarrowDevice Model\rightarrowService Category\rightarrowVariant / Grade & Warranty.
- "+ Add Product Catalog": Multi-step sub-modal selecting Brand
Phase 15: In-App OpenWA Web WhatsApp Chat Suite (/whatsapp-web) & Gateway Integration
- Dedicated Web WhatsApp Client:
- Built
app/(admin)/whatsapp-web/page.tsx(/whatsapp-web) operating like a real WhatsApp Web interface powered by internal OpenWA Gateway (http://localhost:8088). - Added "OpenWA Web WhatsApp" link under
CRM & Sales Pipelinein Sidebar.tsx.
- Built
- Dual-Pane Chat Architecture:
- Left Panel (Threads List): Search bar, filter tabs (
All,Leads,Quotes,VIPs), customer avatar, phone display (+91 XXXXXXXXXX), last message snippet, timestamp, unread badges. - Right Panel (Active Conversation Window): Customer header with CRM stage badge,
OPENWA CONNECTEDstatus indicator, scrollable message bubbles with double checkmarks (✓✓), Quick Template Chips (⚡ Send Quotation,🔧 Repair Update,📅 Pickup Ready), attachment button, input box, and direct "Send via OpenWA" button callingnotificationGatewayService.dispatch(). - Gateway Navigation Button: 1-Click button linking to OpenWA Gateway Telemetry & QR Scanner Dashboard (
/notifications-gateway).
- Left Panel (Threads List): Search bar, filter tabs (
- CRM Pipeline Integration:
- Updated crm-leads/contacted/page.tsx so clicking "OpenWA Web Chat" on lead cards opens
/whatsapp-web?phone=91XXXXXXXXXXdirectly in-app, eliminating externalapi.whatsapp.comredirects.
- Updated crm-leads/contacted/page.tsx so clicking "OpenWA Web Chat" on lead cards opens
Phase 17: Official OpenWA Repository (rmyndharis/OpenWA) Backend Integration
- GitHub Repository Clone & Build:
- Cloned official OpenWA source repository (
https://github.com/rmyndharis/OpenWA) directly into Backend/OpenWA. - Executed
npm installand compiled both backend microservice (npm run build) and Dashboard UI (npm run dashboard:build).
- Cloned official OpenWA source repository (
- Active Backend Service on Port 8088:
- OpenWA NestJS backend service is live on
http://localhost:8088(API Docs:http://localhost:8088/api/docs). - Served official OpenWA Dashboard UI at
http://localhost:8088. - Updated
OPENWA_MASTER_KEYin Config.py with generated API key (owa_k1_df65037ea78c5ca9f19c63a6fb591e1d766581705c1dde392f098f6364387948).
- OpenWA NestJS backend service is live on
- Verification:
- HTTP
GET http://localhost:8088confirmed serving official OpenWA Dashboard bundle (<div id="root"></div>).
- HTTP
Phase 18: CRM Deals Kanban Board API Parity & MySQL Schema Parity
- Backend Schema & Model Parity (Crm.py, CrmModel.py): Updated Pydantic schemas and MySQL database column constraints on
crm_dealsto makecustomer_idnullable, allowing standalone deals to be created and managed without requiring pre-linked customer records. - Service Layer Parity (CrmService.py): Added dual-field compatibility for
valueandestimated_valuefields in deal creation and list retrieval. - Static Data Removal & Clean State: Cleared all dummy/seeded test deals from MySQL database and verified frontend pages contain zero mock data.
- CRM Deals Kanban UI (crm-deals/page.tsx): Linked CRM Deals Kanban board directly to backend
GET /api/v1/crm/dealsandPOST /api/v1/crm/dealswith real-time dynamic total pipeline value.
Phase 21: In-App WhatsApp Web Routing & External Redirect Elimination
- In-App URL Dispatcher (crmService.ts):
- Replaced external
https://wa.me//https://api.whatsapp.com/send...builder with in-app/whatsapp-web?phone=...&name=...&message=...route generator.
- Replaced external
- Quotations & Leads Handlers (crm-quotations/page.tsx, crm-leads/qualified/page.tsx, bulk-quotations/page.tsx):
- Replaced
window.open(waUrl, '_blank')calls withrouter.push(waUrl). - Clicking "Send Quote via WhatsApp" or "Send Quote & Launch WhatsApp" now opens our in-app OpenWA WhatsApp Web suite (
/whatsapp-web) directly inside the admin panel with the customer thread pre-selected and pre-formatted quotation text ready — completely eliminating external browser tab redirects and"Open xdg-open?"popups.
- Replaced
Phase 22: Live OpenWA API Quotation Dispatch & Web WhatsApp Focus
- Direct API Dispatch (
openwaService.sendQuotationWhatsApp):- Integrated
openwaService.sendQuotationWhatsAppin openwaService.ts. - Automatically resolves the active Baileys session UUID (
17cdec56-b9b8-4384-81bf-b000bb61bbef), formats phone to91XXXXXXXXXX@c.us, builds the full quote text (Customer, Item, Amount in ₹, Terms), and dispatches the POST message directly to OpenWA port8088.
- Integrated
- Quotation Handlers Updated:
- crm-quotations/page.tsx: Updated
handleSaveQuotationto asynchronously send the WhatsApp quotation text via OpenWA API before navigating to/whatsapp-web?phone=.... - crm-leads/qualified/page.tsx: Updated
handleExecuteSendQuoteto asynchronously send WhatsApp quote and update lead status toQUOTE_SENT. - bulk-quotations/page.tsx: Updated
handleSaveQuotationto send WhatsApp quotation before navigating.
- crm-quotations/page.tsx: Updated
- WhatsApp Web Suite Auto-Focus (whatsapp-web/page.tsx):
- Updated chat selection logic so when
phoneURL parameter is provided,activeChatIdis set even for new contacts, ensuring the freshly sent quotation appears in the conversation window immediately.
- Updated chat selection logic so when
Phase 23: POS Sessions Backend API Parity & Mock Fallback Elimination
- Backend API Endpoint (
InventoryPosRouter.py,InventoryPosService.py):- Implemented
list_pos_sessionsservice method in InventoryPosService.py to query live database sessions. - Registered
GET /api/v1/inventory-pos/pos-sessionsendpoint in InventoryPosRouter.py protected byget_current_userauth middleware.
- Implemented
- Frontend POS Sessions Page (pos-sessions/page.tsx):
- Completely purged hardcoded static mock data (
TERM-MAIN-01andTERM-EXPRESS-02) fromloadSessions()catch block andhandleOpenSession(). - Added clean empty state UI displaying "No active POS counter sessions found. Click '+ Open New Counter Session' to initialize a billing terminal with opening cash float." when zero sessions are present in DB.
- Completely purged hardcoded static mock data (
- Verification:
npx tsc --noEmit: 0 errors.curl -s http://localhost:8000/api/v1/inventory-pos/pos-sessions: Responded with401 / Missing Authorization token(endpoint active and protected).
Phase 24: User POS Analytics Page & Backend Schema Bug Fix
- Backend Fix (SystemConfigModel.py): Resolved a hidden
InvalidRequestErrorwhereProductLocationwas not imported, causing theGET /api/v1/system/locationsendpoint to fail during SQLAlchemy model initialization in isolated contexts. - Frontend UI (user-pos-analytics/page.tsx):
- Implemented location and user selector dropdowns.
- Users dropdown is filtered strictly to display only users associated with the selected location and having a role with POS permissions (
pos.permission codes). - Designed the data grid and analytics cards (Total Revenue, Walk-in Cash/UPI, Cash Variance) aggregating POS session data filtered by location and user.
- Verification: Restarted the backend server and confirmed the Locations dropdown fetches and displays correctly (
CrmLocationrecords). User confirmed UI looks great.
Phase 26: Bug Fixes for B2B Quotations & Lead Conversions
- Context:
- User reported that B2B Bulk Quotations disappear from the UI upon page refresh.
- User reported "Failed to convert lead" error when attempting to convert a Quote Sent lead.
- Root Causes:
- The frontend passed
customer_nameandcustomer_phoneto/api/v1/billing-finance/quotationsinstead of an existingcustomer_id. Pydantic threw a422 Unprocessable Entity. The frontend silently caught this error and appended optimistic mock data which was lost on page reload. - When converting a lead, if the customer's email was missing in the UI, the literal string
"N/A"or""was sent.Pydantic'sEmailStrrejected this as an invalid email, causing another 422 validation error.
- The frontend passed
- Implementation & Resolution:
- Modified
BillingFinanceServiceto intelligently find or dynamically create aCrmCustomerbased on the phone number provided in the Quotation payload ifcustomer_idis omitted. - Updated
CrmBulkQuotationCreateschema to allowcustomer_name,customer_phone, andcustomer_email, makingcustomer_idoptional. - Fixed frontend
page.tsxfor bothbulk-quotationsandcrm-quotationsto correctly mapitemspayload (qtytoquantity, and append requiredsku) to prevent422 Unprocessable Contentvalidation errors that triggered silent optimistic UI failures. - Replaced strict
EmailStrvalidation withOptional[str]acrossCrm.pyschemas to prevent crashes from malformed, missing, or "N/A" emails typical in CRM data entry. - Resolved a
PydanticSerializationErroron the Lead Conversion API by defining and attaching a properresponse_model=CrmLeadConvertResponseto serialize the SQLAlchemy models correctly. - Refined
quote-sent/page.tsxto explicitly fallback toundefinedif the email string is empty.
- Modified
- Status: Completed successfully. Both B2B Bulk Quotation and CRM Quotations persisting and Lead conversion workflows are now fully functional.
Phase 25: Catalog Service Booking Workflow & Location Dropdown DB Fix
- Backend Schema & Logic:
- Updated
ProductModelandProductCreateschemas withis_service_bookingandmapped_service_category_id. - Updated
CatalogRouter.pyto intercept product creation, automatically instantiating mappedRepairServiceandRepairVariantbased on the specified product mapping fields.
- Updated
- Admin Panel UI: Added interactive checklist logic to Product Drawer (
products/(list)/page.tsx), fetching service categories and injecting them into product creation forms. - Storefront POS Analytics Page: Fixed the persistent "Empty Locations Dropdown" bug in
/user-pos-analyticsby properly seedingcrm_locationsvia a direct raw MySQL database connector since SQLAlchemy metadata tables were out of sync. Dropdown now loadsHeadquarterssuccessfully. - Storefront Service Booking Form Auto-Fill (
/services/page.tsx):- Modified
ProductInteractiveGrid.tsxto conditionally render aBook Service NowCTA. - Upgraded
/services/page.tsxwith a URL params pre-filling engine (Brand\rightarrowSeries\rightarrowModel\rightarrowService Type\rightarrowVariant) that automatically fetches and populates dropdown selections fromwindow.location.search.
- Modified
Phase 26: Unified Quotations SlideOver Detail Drawers & High-Fidelity Printable PDF Preview System
- Reusable PDF Preview Component (PrintableQuotationModal.tsx):
- Created standardized, print-optimised modal featuring iFixKart corporate letterhead, company GSTIN (
33AAAAA0000A1Z5), tax invoice layout, itemized breakdown with HSN/SAC codes (998713repair service,851770spare parts), GST tax calculation (CGST 9% + SGST 9%), 6-month IMEI warranty declaration, and native print support via@media printandwindow.print().
- Created standardized, print-optimised modal featuring iFixKart corporate letterhead, company GSTIN (
- CRM Sales Quotations Integration (crm-quotations/page.tsx):
- Added SlideOver drawer panel, printable PDF preview modal state, clickable table rows, and
[View]action buttons.
- Added SlideOver drawer panel, printable PDF preview modal state, clickable table rows, and
- B2B Bulk Fleet Quotations Integration (bulk-quotations/page.tsx):
- Integrated SlideOver drawer and
PrintableQuotationModalwith corporate client details, SLA terms, and 1-click conversion to Tax Invoice.
- Integrated SlideOver drawer and
- Service Repair Quotations Integration (service-quotes/page.tsx):
- Added
PrintableQuotationModalwith device info (brand, model, device type) and repair variant breakdown.
- Added
- Database Column Parity:
- Executed
ALTER TABLE service_jobs ADD COLUMN replaced_part_number VARCHAR(255) NULL;onengine_commercedatabase instance, fixing 500 error on/service-invoicesand/api/v1/service/jobs.
- Executed
- Verification & Parity:
npm run buildexecuted and compiled successfully in Next.js (57/57 static pages generated with 0 errors).
Phase 27: CRM Quotation Lead Movement Fix & Interactive Sales Quotation PDF Builder Workflow
- Fix Lead Status Movement (Issue 1):
- Opening / Drafting: Updated Stage 3 (
crm-leads/qualified/page.tsx) to remove prematureupdateLeadStatus('QUOTE_DRAFT')on "Draft" or "Send Quote" button clicks. - Saving Draft: Saving a quote draft in
crm-quotations/page.tsxkeeps the lead strictly in Stage 3 (QUALIFIED) without advancing it to Stage 4 (QUOTE_SENT). - Stage 4 Filter Parity: Updated Stage 4 (
crm-leads/quote-sent/page.tsx) to query strictlyQUOTE_SENTleads (crmService.getLeads('QUOTE_SENT')), preventing draft leads from leaking into Stage 4. - Dispatch Requirement: Leads advance to Stage 4 (
QUOTE_SENT) ONLY when the quotation is explicitly dispatched/sent to the customer via WhatsApp/Email.
- Opening / Drafting: Updated Stage 3 (
- Interactive Builder & PDF Format Dispatch (Issue 2):
- Full Builder Integration: Replaced basic text modal in Stage 3 (
qualified/page.tsx) with direct navigation to the full Customer Sales Quotation Builder (/crm-quotations?lead_id=...), allowing full product catalog & repair service variant line-item editing. - Formatted WhatsApp PDF Dispatch: Enhanced
openwaService.sendQuotationWhatsAppandcrm-quotations/page.tsxto dispatch itemized line items, subtotals, and warranty terms via WhatsApp text message, followed immediately by the actual attached PDF document file (Quotation_SQ-2026-XXX.pdf) sent via OpenWAsendDocumentAPI. Removed redundant URL strings from WhatsApp message text.
- Full Builder Integration: Replaced basic text modal in Stage 3 (
Phase 28: CRM Tasks & Calendar Backend Router Prefix & MariaDB SQL Query Fix
- APIRouter Route Prefix Fix (CrmTaskCalendarRouter.py): Updated router prefix from
/crmto/api/v1/crmso frontend calls to/api/v1/crm/tasksand/api/v1/crm/calendarmatch backend route definitions. - MariaDB SQL Syntax Parity (CrmTaskCalendarService.py): Replaced PostgreSQL-specific
NULLS LASTquery ordering inlist_taskswith MariaDB/MySQL compatibleCrmTask.due_at.is_(None).asc(), CrmTask.due_at.asc(). - Verification: Verified endpoints
GET /api/v1/crm/tasksandGET /api/v1/crm/calendaranswer HTTP 200[]andcrm-calendar/crm-todospages load cleanly with zero error toasts.
Phase 29: Notification Gateway Architecture Refactoring (Idempotency, Tenant Auth & Retries)
- Current Feature: Backend-driven Notification Gateway for Email and WhatsApp (ZeptoMail + OpenWA).
- Decisions Made:
- Centralize dispatch logic entirely on the backend to avoid exposing ZeptoMail credentials in the Next.js frontend.
- Establish a single abstraction
NotificationGatewayServiceto handle Email and WhatsApp uniformly based on anentity_idandnotification_type. - Enforce Database Idempotency by introducing a Unique Constraint on
(tenant_id, idempotency_key)to prevent duplicate messages. - Adopt a strict 5-attempt retry policy (0s, 30s, 2m, 10m, DLQ) using
next_retry_at.
- Changes Applied:
NotificationModel.py: Addedentity_id,notification_type,idempotency_key,attempt_count, and retry-tracking fields.NotificationGatewayService.py: Implemented entity dispatch logic, server-side recipient resolution from CRM entities, and separatedBOTHinto two distinct records.NotificationGatewayRouter.py: ExposedPOST /api/v1/notifications/dispatch-entityprotected by JWT authentication.EmailTemplateService.py: Designed reusable HTML templates for quotations, invoices, and repair tickets.crm-quotations/page.tsx: Migrated from frontend-direct dispatch to calling backenddispatchEntity.notification_gateway.md: Created architectural documentation detailing the flow and data parity measures.
- Remaining Work: Final testing in a live production or staging environment to observe independent retries on Email vs WhatsApp channel failure simulations.
- Known Issues: None currently; simulated ZeptoMail API paths trigger the fallback correctly to queue records for retries.
Phase 30: Flexible WhatsApp & Email PDF Invoice Dispatch for Orders
- Current Feature: Automated Order Invoice delivery via WhatsApp & Email with client/cashier channel selection (
WHATSAPP,EMAIL, orBOTH). - Decisions Made:
- Extended
NotificationGatewayServiceto supportnotification_type in ("ORDER", "ORDER_CREATED", "INVOICE"). - Automatically generate ReportLab PDF invoices dynamically (
generate_invoice_pdf) and persist them touploads/invoices/{invoice_no}.pdffor direct download URL access. - Attach base64 encoded PDF document attachments in ZeptoMail API payloads for Email delivery.
- Format WhatsApp message text with order line items, grand total, tax breakdown, and PDF download link.
- Non-blocking execution:
OrderServicetriggers notification dispatch after DB transaction commit, keeping POS counter checkout instantaneous (< 100ms). - Flexible Channel Selection: Added optional
notification_channelparameter (WHATSAPP,EMAIL,BOTH) to POS order creation (AdminOrderCreateRequestandcreate_walk_in_order). Defaults toBOTH.
- Extended
- Changes Applied:
- NotificationGatewayService.py: Added
ORDERnotification type handling, PDF invoice generation, download URL formatting, and base64 ZeptoMail PDF attachments. - EmailTemplateService.py: Added
order_invoice_emailtemplate method. - OrderService.py: Added
_dispatch_order_notificationshelper and integrated dispatch calls intocreate_walk_in_order,create_ecommerce_order(COD), andconfirm_ecommerce_payment. - AdminOrderRouter.py: Added
notification_channelparameter toAdminOrderCreateRequestand passed it tocreate_walk_in_order.
- NotificationGatewayService.py: Added
- Status: Completed and verified clean.
Phase 31: Repair Slot Allocation Bug Fix & Fallback Elimination
- Current Feature: Customer Repair Booking Slot Allocation & Availability Window.
- Root Cause & Diagnosis:
- The backend (
SlotAllocationService.py) accurately calculates open 1-hour slots (10:00 AM to 7:00 PM), excludes 2–3 PM lunch break, filters slots past the 30-minute cutoff (e.g., 10-11 AM slot is hidden after 10:30 AM), locks held slots during payment (150-second timer), and returns[]on Sundays (weekday == 6). - The storefront frontend (
serviceBooking.ts) contained a fallback conditionif (Array.isArray(data) && data.length > 0) return data;. When the backend correctly returned[]for Sunday or fully booked/past dates,data.length > 0evaluated tofalse, causing the storefront to ignore the empty backend response and fall back togetDemoSlots(), which generated 5 dummy slots.
- The backend (
- Changes Applied:
- Modified serviceBooking.ts line 406: Changed condition to
if (Array.isArray(data)) return data;.
- Modified serviceBooking.ts line 406: Changed condition to
- Verification & End-to-End Testing:
- Browser subagent verified on
http://localhost:3021/repair-services. - Today (Sunday, Oct 4, 2026): Displays "No slots available on this date. Please pick another date." with 0 fake slots.
- Tomorrow (Monday, Oct 5, 2026): Displays valid 1-hour slots (10:00 AM - 11:00 AM, 11:00 AM - 12:00 PM, 12:00 PM - 01:00 PM, 01:00 PM - 02:00 PM, 03:00 PM - 04:00 PM, 04:00 PM - 05:00 PM, 05:00 PM - 06:00 PM, 06:00 PM - 07:00 PM) with 2:00 PM - 3:00 PM lunch break excluded.
- Browser subagent verified on
Phase 32: Store Credit & Cashback Module (With Dynamic Percentage & Return Window)
- Current Feature: Store Credit / Cashback system generating credits on sales orders and service jobs, maturing into spendable wallet balance after return/claim window expiry.
- Architectural & Business Logic:
- Financial Ledger: Double-entry ledger (
CustomerWallet&WalletTransaction) maintainingactive_balance(spendable) andpending_balance(locked during return/claim window). - Dynamic Admin Configuration: Percentages and return window durations are dynamically fetched from the system
settingstable via CreditService.py and configured via the Admin Panel Settings page (/settings). - Sales Orders Lifecycle Hook: Upon order status transitioning to
DELIVERED, pending cashback is generated withmature_at = delivered_at + return_window_days. If the order is returned or cancelled within the window, pending credits are immediately voided. - Repair Services Lifecycle Hook: Upon service job transition to
DELIVEREDorCOMPLETED, pending credits are calculated on the invoice amount and scheduled withmature_at = completed_at + service_claim_window_days. Cancelled services void pending transactions. - Automated Maturity Sweep: Matured transactions (
status == PENDINGandmature_at <= now()) are swept toCOMPLETED, transferring funds frompending_balancetoactive_balance. Exposed viaPOST /api/v1/cron/process-credit-maturityfor cron jobs and admin on-demand trigger.
- Financial Ledger: Double-entry ledger (
- Files Created & Modified:
- Database Models & Tables:
- WalletModel.py: Defined
CustomerWalletandWalletTransaction. - db_base.py: Registered
CustomerWalletandWalletTransaction. - init_db.py: Seeded default credit settings (
credits_enabled,credits_sales_percentage,credits_sales_return_window_days,credits_service_percentage,credits_service_claim_window_days, etc.).
- WalletModel.py: Defined
- Backend Services & API:
- CreditService.py: Complete credit lifecycle service with pending credit generation, voiding, maturity sweeping, and balance adjustments.
- AdminOrderRouter.py: Added credit lifecycle hooks on order status updates (
DELIVERED,RETURNED,CANCELLED). - ServiceJobRouter.py: Added credit lifecycle hooks on repair job status updates (
DELIVERED,COMPLETED,CANCELLED). - CreditRouter.py: Exposed
/api/v1/credits/settings,/api/v1/credits/wallets/{customer_id},/adjust, and/my-wallet. - CronRouter.py: Exposed
POST /api/v1/cron/process-credit-maturity. - main.py: Registered
CreditRouter.
- Admin Panel UI:
- creditService.ts: Frontend API client for credit settings and wallet inspections.
- settings/page.tsx: Added dedicated "Credits & Return Windows" blade with live previews, toggles, percentage/days inputs, and manual sweep trigger.
- Documentation:
- store-credits-and-cashback.md: In-depth architectural guide, database schema, and operational lifecycle flow.
- current-state.md: Updated with new module status and routes.
- Database Models & Tables:
- Verification:
- Comprehensive automated test script test_credit_flow.py verified 100% pass across: setting persistence, pending credit generation on sales order, maturity window timing, cron maturity sweep to active balance, and service job cancellation voiding.
- Admin frontend TypeScript check passed with 0 errors (
npx tsc --noEmit).
Phase 33: Storefront Frontend Integration & Checkout Redemption for Store Credit & Cashback
- Current Feature: Customer-facing Storefront UI & Checkout Redemption Engine for Store Credits & Cashback.
- Architectural & Business Logic:
- Redemption at Checkout:
- Introduced
use_wallet_credits: bool = FalseinCheckoutCreateRequest. - Atomically locks customer wallet with
with_for_update(). - Offsets up to available
active_balanceagainst order total (subtotal + shipping). - Records
REDEEMentry inwallet_transactionsledger with statusMATURED. - If
credits_appliedcovers 100% of the invoice (final_amount == 0), payment gateway redirect is bypassed and order is confirmed immediately.
- Introduced
- Cancellation Restitution:
- When an order transitions to
CANCELLEDorRETURNED,CreditService.refund_redeemed_credits()automatically refunds previously spent credits back toactive_balanceand logs anADJUSTMENTrefund entry.
- When an order transitions to
- Storefront Customer Portal:
- Added "My Wallet & Credits" tab (
/account?tab=wallet) with 3 stat cards (Spendable Credits, Pending Credits, Lifetime Earned), "How Store Credits Work" visual guide, and itemized transaction history table with status pills. - Added live "Store Credits Balance" card to Dashboard tab overview.
- Added "My Wallet & Credits" tab (
- Storefront Checkout Experience:
- Added "Redeem Store Credits" card in Order Summary with available balance pill and deduction calculations.
- Live breakdown row: "Store Credits Applied (-₹X.XX)" and estimated cashback calculation badge.
- Storefront Product Page:
- Added "🎁 Earn 5% Store Credit (≈ ₹XX) after 7-day return window" badge under product price.
- Redemption at Checkout:
- Files Created & Modified:
- Backend:
- CreditService.py: Added
redeem_credits()andrefund_redeemed_credits(). - CheckoutRouter.py: Added
use_wallet_creditstoCheckoutCreateRequest. - OrderService.py: Integrated credit deduction and redemption in
create_ecommerce_order. - AdminOrderRouter.py: Added
refund_redeemed_creditsonCANCELLED/RETURNEDorder transitions.
- CreditService.py: Added
- Storefront Client API:
- creditService.ts: Added
getMyWallet()andgetCreditSettings(). - checkoutService.ts: Added
use_wallet_creditsparameter. - catalogService.ts: Added missing optional fields to
ProductResponse.
- creditService.ts: Added
- Storefront UI Components:
- account/page.tsx: Added wallet tab, stat cards, explanation guide, and transaction history table.
- checkout/page.tsx: Added credit redemption card, summary rows, and order creation payload.
- ProductInteractiveGrid.tsx: Added product cashback reward badge under price.
- Backend:
- Verification:
- Automated integration test test_credit_storefront_flow.py: 100% PASSED (Order created with credits applied, wallet debited,
REDEEMlogged, refund on cancellation verified, wallet summary confirmed). - Storefront TypeScript compilation (
npx tsc --noEmit): PASSED (0 errors). - Backend, Storefront, Admin Panel, and OpenWA services running cleanly on respective ports.
- Automated integration test test_credit_storefront_flow.py: 100% PASSED (Order created with credits applied, wallet debited,
Phase 34: Complete COD Removal & Dynamic Admin-Configured Delivery Engine
- Current Feature: Complete deprecation of Cash on Delivery (COD) across the platform and removal of static free delivery; all delivery fees and promotional thresholds are dynamically driven by Admin Settings.
- Architectural & Business Logic:
- COD Removal & Online Enforcement:
- OrderService.py and CheckoutRouter.py strictly reject any order with
payment_method.upper() == "COD"returning HTTP 400. - Default payment method is
RAZORPAY(UPI, Cards, Netbanking) or Zero-Amount wallet credit payment. - Storefront checkout (
app/checkout/page.tsx) removed Cash on Delivery radio card and submit branches.
- OrderService.py and CheckoutRouter.py strictly reject any order with
- Dynamic Delivery Configuration:
- Seeded system
settingskeys:shipping_delivery_charge = 99.0,shipping_free_delivery_enabled = false(disabled by default), andshipping_free_delivery_min_order_amount = 999.0. - Created DeliveryService.py with dynamic
calculate_shipping_cost(db, subtotal). - SettingsRouter.py exposes
GET /api/v1/settings/delivery(public) andPUT /api/v1/settings/delivery(admin). - CartRouter.py and order creation dynamically invoke
DeliveryService.calculate_shipping_cost.
- Seeded system
- Admin Panel UI:
- Added dedicated "Delivery & Shipping" blade to app/(admin)/settings/page.tsx with standard delivery fee input, free delivery toggle switch, minimum qualification amount, and real-time rule simulation preview.
- Created deliverySettingsService.ts.
- Storefront Cleanups & Parity:
- Created deliveryService.ts fetching dynamic delivery settings.
- Cart page (
app/cart/page.tsx) and Cart Drawer (CartDrawer.tsx): Completely hides free shipping progress bar whenfree_delivery_enabled === false. Dynamically calculates shipping fee. - Replaced all static references ("Free Shipping over ₹999", etc.) across TopBar, Features section, storefront defaults, and policies with "Express Pan-India Delivery".
- COD Removal & Online Enforcement:
- Verification:
- Automated integration test test_delivery_cod_rules.py: 100% PASSED (COD rejection, flat fee enforcement, dynamic admin enablement to free shipping, reset verification).
- Admin TypeScript check (
npx tsc --noEmit): PASSED (0 errors). - Storefront TypeScript check (
npx tsc --noEmit): PASSED (0 errors). - Backend and frontend services responding cleanly.