- Fix NameError in link_media_groups_to_catalog: raw_mk/raw_pmk were used before assignment in Priority 0 comma-split block; moved fetches to top of variant loop so all priority levels share the same resolved values - Expand variant_attributes.attribute_value to String(2000) for comma-separated multi-image media keys - Expand products, device_models, device_series, media_library, migration_media_items URL/path/name columns to String(2000) - Update Pydantic VariantAttributeCreate.attribute_value max_length=2000 - Add rollback cache eviction for new series/model keys (fixes MySQL 1452) - Add comma-separated media key splitting in upsert_executor for multi-image variant image attachment - Add Priority 0 comma-separated MEDIA_LINK support in migration_worker - Update docs/12-ai session summary and current state
90 KiB
90 KiB
Session Summary
Master Architectural Implementation — iFixKart Unified Suite (Phases 0 - 15)
Phase 15: Migration Engine 2000-Character Capacity & Comma-Separated Multi-Image Pipeline
- Root Cause Diagnostics:
variant_attributes.attribute_valuewas limited toVARCHAR(255), causing MySQL Error 1406 (Data too long for column 'attribute_value') on rows with concatenated media keys (e.g. Motorola E32s at 494–719 characters).- Row rollback desynchronization: When a row failed on size overflow,
sp.rollback()deleted newly inserted series/models from MySQL, but Python'sseries_cacheretained phantom IDs, triggering cascading foreign key constraint failures (MySQL Error 1452) across 79 subsequent rows. - Comma-separated media keys in CSV were not parsed into individual images.
- Implemented Changes & Deployments:
- Database Migration: Ran
ALTER TABLEacross local and remoteifixkartecommercemodifyingvariant_attributes.attribute_value,products.name,products.full_path,products.warranty_summary,product_images.image_url,variant_images.image_url,device_models.name,device_models.full_path,device_series.name,media_library.original_filename,media_library.cdn_url, andmigration_media_items.file_nametoVARCHAR(2000). - SQLAlchemy & Pydantic Parity: Updated ProductModel.py, DeviceCatalogModel.py, MigrationModel.py, and Catalog.py to support 2000 characters.
- Comma-Separated Media Key Splitting: Enhanced upsert_executor.py and migration_worker.py to split comma-separated keys, resolve each
MediaGroup, and sequentially attach all images toVariantImage(sort_order = 0, 1, 2, ...). - Cache Eviction on Rollback: In upsert_executor.py, uncommitted cache entries are automatically evicted upon
sp.rollback(), preventing cascade foreign key errors permanently. - Deployed & Verified: SFTP synced to
/var/www/fastapi/ifixkart/, compiled cleanly, and restartedifixkart.serviceand local backend daemon.
- Database Migration: Ran
Phase 14: Storefront Image Rendering & Variant Selection Diagnostics & Fixes
- Root Cause 1 (Images 404 / Placeholders):
- Database product/variant image paths were referencing an older purged batch UUID (
a1dd8ca5-ad5c-4151-96e5-4c764ffdecab) rather than the active upload UUID (96adda77-5689-46bc-9e96-71a0d9975d68). - Storefront Nginx configuration (
/etc/nginx/sites-available/ifixkart-ecommerce) did not have a staticlocation /uploads/block routing directly to/var/www/fastapi/ifixkart/uploads/. - Next.js storefront PM2 process (
ifixkart-ecommerce) had not been rebuilt or restarted after earlier migrations.
- Database product/variant image paths were referencing an older purged batch UUID (
- Root Cause 2 (Variants Not Showing on PDP):
- The source catalog CSV had empty values in the dedicated
colorcolumn; colors (Forest Blue,Hot Pink,Marshmallow Blue) were embedded inside variant names or media keys. - As a result, all imported variants were assigned identical single-value attributes (
material: Original Grade), causing the PDP dimension selector in ProductInteractiveGrid.tsx to collapse into a single button and hide variant switches.
- The source catalog CSV had empty values in the dedicated
- Implemented Fixes & Deployments:
- Database & Media Path Realignment: Updated
product_images,variant_images, andmedia_libraryrecords to reference active upload media files and added fallback symlink copies on disk. - Nginx Static Asset Proxy: Added
/uploads/alias in/etc/nginx/sites-available/ifixkart-ecommerceand reloaded Nginx. - Migration Engine Auto-Inference: Updated upsert_executor.py to automatically extract color from variant name suffixes or media keys for all future catalog imports. Pushed commit
7c7c474and restartedifixkart.service. - PDP Fallback Variant Selector: Enhanced ProductInteractiveGrid.tsx so that if variants exist without multi-valued dimensions, a dedicated variant pill selector is rendered.
- Category Thumbnails Fallback: Updated CategoriesSection.tsx to fall back to the first product image in a category when no dedicated category image is assigned.
- Rebuilt & Restarted: Successfully compiled Next.js storefront (
npm run build) and restarted PM2 processifixkart-ecommerce. - Browser Validation: Verified via Chrome subagent that images render on the homepage and PDP, and color variant switches (e.g. Forest Blue -> Hot Pink) dynamically change the product image.
- Database & Media Path Realignment: Updated
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.
Phase 35: Dedicated Multi-Dashboard Routes & Account Lockout Fix
- Current Feature:
- Deconstruction of the monolithic dashboard into dedicated modular routes with top shared navigation header and sidebar links.
- Resolution of Super Admin account lockout and credential synchronization.
- Architectural & Business Logic:
- Modular Dashboard Routes:
- Created DashboardHeaderNav.tsx: Shared navigation tab bar with route highlighting and quick switching across all 6 dashboards.
- Created DashboardShared.tsx: Standardized card styling, stage progress charts, badges, and currency formatters.
- Created useDashboardData.ts: Centralized data fetching hook.
- Implemented dedicated route pages:
/dashboard: Main Overview Dashboard/dashboard/executive: Executive C-Suite Dashboard/dashboard/store-manager: Store Manager Dashboard/dashboard/technician: Technician Workshop Dashboard/dashboard/b2b: B2B Wholesale Dashboard/products/dashboard: Product Analytics Dashboard
- Updated Sidebar.tsx to list all 6 distinct dashboard links under the Dashboard group.
- Account Lockout & Credentials:
- Account:
admin@ifixkart.com. - Password:
Admin$2026Setup. - Resolved shell argument expansion issue that caused corruption of the argon2id hash on the remote server.
- Clean hash generated and parameterized directly via SQLAlchemy across local databases (
ifixkart_core,ifixkart_commerce) and remote databases (ifixkartecommerceadmin,ifixkartecommerce). - Verified
is_locked = False,failed_login_attempts = 0, and successful JWT issuance on both local port 8000 and remote production backendhttps://ifixkartbe.trionixsolution.com. - Successfully logged in via browser test on
http://localhost:3022/login.
- Account:
- Remote Deployment:
- Synced all newly created dashboard files to
/var/www/html/ifixkartdev. - Executed clean
npm run buildand restarted PM2 processifixkart-admin(id: 2). - Verified
https://ifixkartdev.trionixsolution.com/loginreturns HTTP 200.
- Synced all newly created dashboard files to
- Modular Dashboard Routes:
Phase 36: Cross-System Intelligence, Marketing Feeds, Multi-Format Reports & Security Auto-Logout
- User Directives & Requirements:
- Integration of high-value capabilities from CRM and Sassynest into iFixKart.
- Addition of Google Merchant Center product feed, Google Analytics 4 (GA4) dashboard, Razorpay audit dashboard, Shiprocket logistics dashboard, and Social Media publisher.
- Multi-format enterprise reports (Sales, Inventory, Repairs, Logistics, Employee Operational Activity) supporting Excel (.xlsx), CSV, and PDF downloads.
- 30-minute inactivity auto-logout with advance warning modal and real-time countdown timer.
- Strict constraints: Permanently omit targets and incentives; keep OpenWA internal-only; keep Shiprocket and WATI credentials safely disabled.
- Backend Implementations:
- Google Analytics 4: google_analytics_service.py & GoogleAnalyticsRouter.py (Property ID
521198579, service account credentials, realtime active visitor ticker). - Google Merchant Center: google_merchant_feed.py & GoogleMerchantRouter.py (RSS 2.0 XML generator at
/api/v1/storefront/feed/google-merchant.xmland/api/v1/merchant/status). - Razorpay Ledger: RazorpayDashboardRouter.py (Net captured revenue, provider split, transaction audit ledger).
- Social Media Hub: meta_graph_service.py & SocialMediaRouter.py (Meta Graph API v22.0, Instagram ID
17841478415652122, Page ID994740483728923). - Shiprocket Logistics: ShiprocketRouter.py (Courier rate simulator, SLA matrices, wallet preview in sandbox preview mode).
- Reporting Engine: ReportExportRouter.py (Streaming generation of
.xlsx,.csv,.pdffor Sales, Inventory, Repairs, Logistics, and Employee operational activity).
- Google Analytics 4: google_analytics_service.py & GoogleAnalyticsRouter.py (Property ID
- Admin Panel UI Implementations:
- Session Security: IdleSessionManager.tsx (30-min idle timeout, 28-min advance warning modal with countdown timer and cross-tab synchronization; mounted in layout.tsx).
- Google Merchant Center: merchant-center/page.tsx (
/merchant-center): Live feed copy, 1000 product compliance stats, manual regeneration. - Razorpay Dashboard: razorpay-dashboard/page.tsx (
/razorpay-dashboard): Captured volume cards, transactions ledger table with search, filters, and CSV export. - Google Analytics 4: analytics/google/page.tsx (
/analytics/google): Realtime active users, 30-day traffic metrics, acquisition sources. - Social Media Hub: social-media/page.tsx (
/social-media): Multi-channel publisher, 17 Instagram filters with live CSS transform preview, mobile phone mockup. - Shiprocket Logistics: logistics/page.tsx (
/logistics): Courier comparative SLAs, pincode serviceability calculator, prepaid wallet balance. - Reporting Hub: reports/page.tsx (
/reports): Unified downloads hub for Excel, CSV, and PDF files. - Navigation: Sidebar.tsx expanded with Marketing entries, Sales and Billings entries, and a dedicated
Reports & Intelligencegroup.
- Storefront Customer-Facing UI Implementations:
- Google Analytics 4 Client Tracking: GoogleAnalytics.tsx & analytics.ts (Injected into layout.tsx with route change listeners and e-commerce event hooks
view_item,add_to_cart,begin_checkout,purchase). - Google Shopping JSON-LD Schema: app/products/[slug]/page.tsx (Generates schema.org
ProductJSON-LD with price, INR currency, stock availability, brand, and reviews). - Delivery Pincode & SLA Verification Widget: ProductInteractiveGrid.tsx (Live 6-digit pincode validator, 2-3 business day express delivery feedback, and courier SLA indicator).
- Social Media Community Showcase: SocialCommunitySection.tsx (Mounted in app/page.tsx with genuine workshop repair showcases,
@ifixkart_officialhandles, and community follow links).
- Google Analytics 4 Client Tracking: GoogleAnalytics.tsx & analytics.ts (Injected into layout.tsx with route change listeners and e-commerce event hooks
- Verification:
- Backend API tests: 100% PASSED (Merchant status 200, GA4 status 200, Meta status 200, Razorpay metrics 200, Shiprocket 200, RSS XML feed 200, All report formats 200).
- Admin Panel TypeScript compilation (
npx tsc --noEmit): PASSED (0 errors). - Storefront TypeScript compilation (
npx tsc --noEmit): PASSED (0 errors). - Live HTTP curl checks across all new routes and PDPs: 200 OK.
- All 4 background processes (:8000, :3021, :3022, OpenWA) active and healthy.
Phase 18: User Management, Roles & Permissions Engine & RBAC Enforcement
- Login UI Sanitization (login/page.tsx):
- Permanently removed mock test persona quick-fill chips (
SELECT TEST PERSONA (RBAC)). - Restored clean, production-grade enterprise authentication interface (Email, Password, Sign In).
- Permanently removed mock test persona quick-fill chips (
- Backend Serialization & User Listing Bugfix:
- Fixed FastAPI Pydantic
UserResponseschema in schemas/User.py by makingemail_verified: Optional[bool] = Falseandphone_verified: Optional[bool] = False. - Resolved
ResponseValidationErrorthat previously causedGET /api/v1/users/allto crash with HTTP 500 and trigger the frontend toast"Network issue — please refresh page or check connection". - Populated verified flags in
ifixkart_core.users.
- Fixed FastAPI Pydantic
- Master Data Parity (users/page.tsx):
- Synchronized static lookup arrays (
ROLES,DEPARTMENTS,DESIGNATIONS) with real database ULIDs. - Enabled seamless user addition, role assignment, and department mapping.
- Synchronized static lookup arrays (
- Roles & Permissions Management (roles/page.tsx):
- Tested "+ Add role" slideover modal end-to-end: created custom role
Workshop Lead(PrefixWLD). - Successfully assigned granular permissions (
inventory.general.manage,catalog.general.read) and verified database persistence inrole_permissions. - Seeded 33 platform permissions to
Super AdminandAdmin.
- Tested "+ Add role" slideover modal end-to-end: created custom role
- RBAC Route Guard & Navigation Shielding:
- Injected role authorization guard in AdminLayout.tsx via
isRouteAllowed()andparseJwt(). - Non-authorized route access attempts display a clean "Access Restricted" alert and "Return to My Workspace" quick-action.
- Verified role restriction with Technician persona (
tech.lead@ifixkart.com).
- Injected role authorization guard in AdminLayout.tsx via
Phase 38: Dynamic Role-Based UI Filtering & Technician Walk-In Intake Fix
- Dynamic Role-Based UI Filtering (Resolving Images 1 & 2):
- Issue: Store Manager saw
[Executive C-Suite]tab in the top navigation bar of/dashboard. Clicking it threw an "Access Restricted" error screen. - Requirement: If a section, route, or tab is restricted for a role, hide it completely. Do not render entry points that lead to access restriction screens across any role.
- Implementation:
- DashboardHeaderNav.tsx: Initialized
userRolesynchronously and filteredDASHBOARD_TABSviaisRouteAllowed(tab.href, effectiveRole). Removed fallback that exposed all tabs when role was resolving. - Sidebar.tsx: Updated logo link from hardcoded
/dashboardtogetDefaultDashboardForRole(userRole)so clicking the logo redirects users to their authorized workspace. Synchronized role initialization. - Header.tsx: Conditionally gated
/settingsin profile dropdown and/activity-logsin the notification slide-over behindisRouteAllowed(). - dashboard/page.tsx: Gated
"Manage Security ->"link behindisRouteAllowed('/security', userRole). - lib/rbac.ts: Enabled
/settingsaccess foradminrole so company administrators can manage delivery, credits, store locations, and devices.
- DashboardHeaderNav.tsx: Initialized
- Issue: Store Manager saw
- Technician Walk-In Service Order Fix (Resolving Image 3):
- Issue: Technician visiting
/services/intakeencountered toast"You do not have permission to access this resource"upon submitting a walk-in intake. - Root Cause:
POST /api/v1/service/jobs/{job_id}/intakein ServiceJobRouter.py line 190 was restricted toRoleChecker(["Super Admin", "Admin", "Manager"])—"Technician" was completely missing!get_current_actorinServiceJobRouter.pyline 64 had only["Super Admin", "Admin", "Manager", "Technician"]and omitted other operational roles.
- Fixes Applied:
- Added
"Technician"and"Store Manager"toRoleCheckeron/services/jobs/{job_id}/intake. - Added alias matching in RoleChecker.py so
"store manager"satisfies"manager"and vice versa.
- Added
- Issue: Technician visiting
- Verification Across All Roles:
- Store Manager (
manager.store@ifixkart.com): Dashboard tab bar renders strictly[Main Overview],[Store Manager], and[Product Analytics].[Executive C-Suite],[Technician Workshop],[B2B Wholesale]and"Manage Security ->"are completely hidden. - Technician (
tech.lead@ifixkart.com): Dashboard tab bar renders strictly[Technician Workshop]. Form submission on/services/intakecreates walk-in job (SRV-1792390487-9CC6) and smoothly redirects to/technician?job_id=...without permission errors. - Sales (
sales.rep@ifixkart.com): Tab bar renders strictly[Main Overview]and[B2B Wholesale]. Sidebar shows only CRM and Sales Billings. - Customer Support (
support.agent@ifixkart.com): Lands directly on/customers. Sidebar shows only CRM customer management, review moderation, and service queues. - Super Admin (
admin@ifixkart.com): Full platform access across all 6 dashboard tabs, all sidebar modules, and security management.
- Store Manager (
Phase 39: Dynamic Footer Router APIs, Admin CMS Layout Manager & Storefront Integration
- Context & Requirement:
- The user requested dynamic APIs and separate storefront pages for the footer links: About Us (
/about), Terms & Policy (/terms&/privacy), Help Center (/help), Feedback (/feedback), FAQs (/faqs), and Payments (/payments). - Added full visual content customization under the Admin Panel's "Homepage Layout" manager (
http://localhost:3022/storefront-sections) so admins can edit copy, cards, story paragraphs, Q&As, payment methods, and contact info, and publish updates live to the storefront.
- The user requested dynamic APIs and separate storefront pages for the footer links: About Us (
- Backend Architecture & Endpoints:
- SQLAlchemy Customer Feedback Model: Created CustomerFeedbackModel.py (
customer_feedbackstable) for storing customer ratings, messages, topics, and order numbers. Registered in init_db.py. - Customer Feedback Submission API: Added
POST /api/v1/storefront/feedbackin storefront.py with Pydantic payload validation (name,email,topic,rating,order_no,message). - Admin Feedback Moderation Endpoints: Added
GET /api/v1/admin/storefront/feedbacksandPUT /api/v1/admin/storefront/feedbacks/{feedback_id}/statusin admin_storefront.py. - Bulk-Save Partitioning Bugfix: Enhanced
POST /api/v1/admin/storefront/content/bulk-savein admin_storefront.py to match existing records by(page, region)ifcontent_idis missing, and scoped deletion strictly per-page to prevent cross-page section deletions.
- SQLAlchemy Customer Feedback Model: Created CustomerFeedbackModel.py (
- Admin Panel "Homepage Layout" Manager (storefront-sections/page.tsx):
- Expanded
LayoutPageunion to:'home' | 'services' | 'about' | 'terms' | 'help' | 'feedback' | 'faqs' | 'payments'. - Added modern horizontal tab bar with live section counts:
Homepage (10),Repair Services (6),About Us (3),Terms & Policy (3),Help Center (2),Feedback (1),FAQs (3),Payments (3). - Added universal section header editor allowing admins to customize the top-level Title and Subtitle/Description for any section across all 8 pages.
- Implemented tailored field editors for:
about_hero: Brand story paragraphs list with dynamic add/delete/edit.about_features: Feature highlight cards grid (title, desc, link, icon).about_contact: Workshop address, support phone, support email, operating hours.terms_clauses&privacy_clauses: Legal clause list (title, full markdown body).help_hero&help_topics: Search bar placeholder & topic cards (title, desc, link).feedback_hero: Incentive promo banner title & subtitle.faq_general&faq_orders: Question & Answer accordion items.payments_methods&payments_security: Payment method cards & security guarantee/refund SLA notes.
- Expanded
- Storefront Client & Separate Dynamic Pages:
- API Client Service (storefrontService.ts): Added
getPageLayout(page: string)andsubmitFeedback(payload). - About Us Page (about/page.tsx): Dynamically renders
about_hero(title, subtitle, story paragraphs),about_features(cards grid), andabout_contact(address, phone, email, hours) with zero-downtime fallbacks. - Customer Feedback Page (feedback/page.tsx): Connects form submission directly to
POST /api/v1/storefront/feedbackwith responsive success modal and dynamic promo headers. - Legal Documents (LegalPage.tsx): Renders dynamic policy clauses for
/termsand/privacywith fallback defaults. - Help Center (help/page.tsx): Dynamically renders help topics and hero search configuration.
- Payments Page (payments/page.tsx): Dynamically renders payment methods, security assurances, and refund SLAs.
- FAQs Page (faqs/page.tsx): Dynamically fetches and renders Q&A categories from
/api/v1/storefront/layout/faqs.
- API Client Service (storefrontService.ts): Added
- Verification & Parity:
- Admin TypeScript typecheck (
npx tsc --noEmitinNew admin panel/ikixkart-dashboard): PASSED (0 errors). - Storefront TypeScript typecheck (
npx tsc --noEmitinEcommerce/File 2/storefront): PASSED (0 errors). - Storefront HTTP checks:
/terms(200),/privacy(200),/help(200),/feedback(200),/faqs(200),/payments(200). - Admin Console HTTP check:
/storefront-sections(200). - Headless Browser Verification: Verified all 8 tabs switch cleanly, section expanders open with editable inputs, and no console errors occur.
- Live API submission test:
POST /api/v1/storefront/feedbackreturned200 OKwith createdfeedback_id.
- Admin TypeScript typecheck (
Phase 40: Comprehensive Platform Security Hardening & Remediation
- Context & Scope:
- Remediated critical and high-priority vulnerabilities identified in the penetration test report, strictly preserving existing hardcoded application credentials/secrets.
- Key Remediations Implemented:
- CORS Wildcard Regex Elimination (main.py):
- Removed
allow_origin_regex=r"https?://.*", restoring strict origin domain checking based on explicit whitelist (allow_origins).
- Removed
- Rate Limiting & SlowAPI Integration (limiter.py, main.py):
- Initialized global
Limiterwith default 120 req/min and exception handler forRateLimitExceeded. - Throttled critical auth routes: Customer Login (5/min), Register (5/min), Google OAuth (10/min), Admin Login (5/min), Token endpoint (10/min), and Token Refresh (20/min).
- Initialized global
- Customer Account Lockout Mechanism (EcomCustomerModel.py, CustomerAuthRouter.py):
- Migrated
ecom_customersdatabase schema across bothcoreandcommercedatabases to addfailed_login_attempts,is_locked, andlocked_until. - Enforced account lockout after 5 failed attempts for 15 minutes.
- Migrated
- Data Migration Router Protection (MigrationRouter.py):
- Secured all 30+ migration engine endpoints with
RoleChecker(["Super Admin", "Admin"]).
- Secured all 30+ migration engine endpoints with
- Cron Scheduled Tasks Router Protection (CronRouter.py):
- Added
verify_cron_accessdependency requiring either an authenticated Admin Bearer token or a validX-Cron-Keyheader matching backend secrets using constant-time comparison (hmac.compare_digest).
- Added
- MCP API Key Bypass Hardening (RoleChecker.py):
- Restricted
X-API-KEYinternal bypass strictly to loopback/local IPs (127.0.0.1,::1,localhost,testclient). Rejects external IPs with HTTP 403 Forbidden.
- Restricted
- Cookie & Session Hardening:
- Changed admin refresh token cookie from
SameSite=NonetoSameSite=Laxin AuthenticationRouter.py. - Reduced default access token expiry from 24h to 30 minutes and refresh token expiry from 120 days to 30 days in Config.py.
- Changed admin refresh token cookie from
- DOS & Information Disclosure Prevention:
- Reduced global request body size ceiling from 3GB to 50MB in main.py.
- Sanitized
/healthin HealthRouter.py to return only{"status": "healthy"}for unauthenticated probes; detailed diagnostics moved behind Admin authentication. - Enforced real magic byte header validation for video uploads in FileRouter.py.
- Excluded
credentials/,jwt_public.pem,*.pem, and*.keyin .gitignore. - Added
sanitize_htmlin html_utils.py to strip XSS vectors.
- CORS Wildcard Regex Elimination (main.py):
Phase 41: Multi-Repository Git Synchronization & Release Push
-
Repositories Synchronized & Pushed:
- Backend (ifixkart-backend):
- Remote:
https://git.trionixsolution.com/adithiyan/ifixkart-backend.git(branchmain). - Commit:
ae8162afeat(backend): add integrations for Google Analytics, Merchant Center, Shiprocket, Razorpay, Meta Graph & rate limiter. - Key Modules: Google Analytics GA4 reporting router, Google Merchant Center product XML feed, Shiprocket logistics integration, Razorpay dashboard router, Meta Graph social media hub, SlowAPI rate limiter, customer lockout security enhancements, sanitized health probe, and customer feedback router. Excluded credentials and sensitive keys in
.gitignore.
- Remote:
- Admin Dashboard (ikixkart-dashboard):
- Remote:
https://git.trionixsolution.com/adithiyan/ifixkart-admin.git(branchmain). - Commit:
ae5dc76feat(admin): add role-based dashboards, analytics, logistics, merchant center & social media management. - Key Modules: Role-based dashboards (B2B, Executive, Store Manager, Technician), dynamic CMS Homepage Layout editor for 8 storefront pages, Google Analytics GA4 live chart cards, Shiprocket courier tracking, IdleSessionManager session timeout, RBAC permission guards, and Razorpay dashboard.
- Remote:
- Storefront (storefront):
- Remote:
https://git.trionixsolution.com/adithiyan/ifixkart-storefront.git(branchmain). - Commit:
f9797fefeat(storefront): add Google Analytics integration, PDP interactive gallery, feedback & storefront CMS pages. - Key Modules: Google Analytics tag provider (
GoogleAnalytics.tsx&analytics.ts), enhanced product PDP interactive image gallery and spec switcher, dynamic footer pages (/about,/faqs,/help,/feedback,/payments,/terms,/privacy) fetching live from CMS backend layout API.
- Remote:
- Backend (ifixkart-backend):
-
Verification:
git push origin mainverified and in sync across all 3 git repositories.
-
Repository Hygiene Cleanup:
- Removed 33 legacy scratch, DB migration, test runner scripts, screenshots, and keys (
add_location*.py,alter_*.py,test_*.py,warranties_*.png,jwt_public.pem,cleanup_*.py, etc.) from git tracking inBackend. - Added strict exclusion rules to
Backend/.gitignore. - Pushed cleanup commit
5b40b38toadithiyan/ifixkart-backendonmain. Root repository structure now exposes strictly core application code (app/,requirements.txt,.gitignore,OpenWA).
- Removed 33 legacy scratch, DB migration, test runner scripts, screenshots, and keys (
Phase 42: Native Swarm Intelligence & Predictive Digital Twin Engine (swarm/)
- Architectural Scope:
- Implemented an air-gapped, multi-agent behavioral simulation sandbox in
/mnt/fam/SERVER/IfixKartEcommerce/swarmto model customer price elasticity, WhatsApp campaign deliverability/spam risk, workshop repair intake surges, and B2B corporate fleet procurement.
- Implemented an air-gapped, multi-agent behavioral simulation sandbox in
- Core Directives & Corrections Implemented:
- Confidence Intervals vs Dispersion: Distinguishes AI persona dispersion from statistical sampling error. Projections mathematically calibrated against 2,819 real historical orders and catalog records with empirical 95% confidence intervals and explicit epistemic notice disclaimers.
- Durable Queue & Crash Recovery: Built atomic state machine with row-level locks, heartbeats, cancellation tokens, hard timeouts (120s), and automatic zombie-reaping on FastAPI backend startup.
- Database Multi-Engine Integrity: Integrated with
RoutingSessionandengine_coreforsimulation_jobsinifixkartecommerceadmin. - Air-Gapped Sandbox Enforcement: Enforces
SET SESSION TRANSACTION READ ONLYon operational database queries; zero live payment/messaging gateway imports. - LLM Abstraction Layer: Modular provider layer supporting Mock offline provider, Gemini Flash, and OpenAI GPT-4o with deterministic fallbacks and micro-cost tracking.
- Backend API Integration (SimulationRouter.py):
- Mounted
/api/v1/simulationwith routes/scenarios,/scenarios/run(HTTP 202),/jobs/{id},/jobs,/jobs/{id}/cancel, and/jobs/{id}/interview. - Enforced RBAC (
Super Admin,Admin,Store Manager) and SlowAPI rate limiting (5 req/min).
- Mounted
- Next.js Admin UI (simulation/page.tsx):
- Executive Swarm Prediction Lab dashboard with 4 scenario cards, dynamic parameter sliders, live execution polling stepper, Recharts visualizer, Markdown synthesis viewer, and an interactive 50-persona deep-dive interview console.
- Sidebar and RBAC routing updated to permit access for Admin and Store Manager roles.
- Verification & Parity:
- All 15 Swarm unit tests passing (
python3 -m unittest discover -s swarm/tests/ -v). - Empirical benchmarks verified across concurrency levels 1, 2, and 4 (
reports/test-results/swarm_benchmark_results.json). - All 4 business scenarios verified against live FastAPI backend (
reports/test_swarm_api.py). - Next.js Admin TypeScript compile: 0 errors (
npx tsc -p tsconfig.json --noEmit). - Master Platform E2E Regression: 100% PASSED (40/40 APIs, 15/15 DB checks, real-time sync verified).
- All 15 Swarm unit tests passing (
Phase 43: Enterprise Integrations Hub & Multi-Gateway Control
- Architectural Scope:
- Implemented the production Integrations Hub module across backend and admin dashboard matching the reference CRM style.
- Zero placeholder cards or static mocks. Strictly mirrors live services and honors
Config.pyas primary with databasesettingsfallback.
- Microservices & Gateways Implemented:
- Internal Staff WhatsApp (OpenWA Gateway):
- Real-time embedded QR code renderer right inside
/integrations/whatsappconnecting to local OpenWA gateway on port 8088 (/api/sessions/{id}/qr). - Auto-refresh polling every 4.5 seconds for QR code rotation.
- Session status indicator, Force Restart Session trigger, and live direct test message sender.
- Real-time embedded QR code renderer right inside
- External Customer WhatsApp (WATI Cloud API):
- Purely dedicated to customer notifications, Meta template delivery, and marketing broadcasts.
- Endpoint (
https://live-mt-server.wati.io) and Bearer token management with locked badge when set inConfig.py. - Template discovery viewer and live customer template test sender (
/api/v1/integrations/wati/send-template).
- Transactional Email Gateway:
- Zoho ZeptoMail CPaaS primary integration (
info@trionixsolution.com/ZEPTOMAIL_API_KEY) with fallback custom SMTP configuration. - Live test email dispatcher modal (
/api/v1/integrations/email/test).
- Zoho ZeptoMail CPaaS primary integration (
- Google Analytics 4 (GA4):
- Live telemetry board integration with Property ID
521198579. - Real-time active users (last 30m), 30-day active users, page views, and direct link to deep telemetry dashboard (
/analytics/google).
- Live telemetry board integration with Property ID
- Meta Ads & Graph API (v22.0):
- App ID
1208251298791396, Ad Account1307493795455160, Page ID, and Instagram Business ID. - Live access token validation inspecting token user profile, currency, and ad spend status.
- App ID
- Knowlarity Cloud Telephony:
- SuperReceptionist virtual number (
KNOWLARITY_SR_NUMBER), API key, and authorization tokens. - Agent Click-to-Call bridge dialer (
/api/v1/integrations/call/make-call) ringing the agent first before connecting customer. - Real-time call logs audit table with call duration, status, and recording playback audio links.
- SuperReceptionist virtual number (
- Shiprocket Logistics & Courier Partner:
- Shiprocket API credentials, warehouse pickup hub, and pincode configuration.
- Real-time Pincode Serviceability & Freight Rate Calculator checking courier availability (Bluedart, Delhivery, Ekart, DTDC) with COD toggle.
- Internal Staff WhatsApp (OpenWA Gateway):
- Backend Components:
Backend/app/services/IntegrationService.py: Central integration service handling all 7 providers.Backend/app/api/v1/routers/IntegrationRouter.py: 18 REST endpoints mounted at/api/v1/integrationsinBackend/app/main.py.
- Frontend Components:
services/api/integrationService.ts: TypeScript API client.components/integrations/IntegrationsHeaderNav.tsx: Shared responsive sub-navigation.app/(admin)/integrations/page.tsx: Central overview dashboard with status badges and source indicators.app/(admin)/integrations/whatsapp/page.tsx: Dual-tab WhatsApp page (OpenWA Live QR + WATI Customer Broadcasts).app/(admin)/integrations/email/page.tsx: ZeptoMail & SMTP email dispatcher.app/(admin)/integrations/google-analytics/page.tsx: GA4 status & telemetry hub.app/(admin)/integrations/meta-ads/page.tsx: Meta Graph v22.0 credentials & token inspector.app/(admin)/integrations/call/page.tsx: Knowlarity click-to-call & call logs table.app/(admin)/integrations/shipping/page.tsx: Shiprocket logistics & courier serviceability checker.components/layouts/Sidebar.tsx: AddedIntegrations Hubtop-level group with sub-links.
- Verification:
- TypeScript compilation: 0 errors (
npx tsc --noEmit). - Next.js HTTP verification: All 6 routes return HTTP 200 OK.
- Browser DevTools verification: Live screenshots confirm UI styling, live embedded OpenWA QR code, WATI tab, Knowlarity dialer, and Shiprocket calculator.
- TypeScript compilation: 0 errors (
Phase 44: Workspace Cleanup & Legacy Test File Removal
- Scope: Cleaned up ad-hoc development artifacts, logs, redundant zip files, and legacy testing scripts across the repository.
- Preserved Files (Explicit User Approval):
test_locs.py: Location testing utility in root.test_ssh.py: SSH diagnostic utility in root.query_locations.py: Location query helper in root.deploy_full_updates.py: Server deployment automation script in root.
- Purged Files:
- Logs & Dumps:
admin_panel.log,storefront_ecomm.log,nohup.out,diff_output.txt,Backend/backend.log,Backend/uvicorn_server.log,Backend/uvicorn_test.log. - Redundant Archives:
ifixkart_server_deployment.zip,new_admin_panel_dashboard.zip,New admin panel/ikixkart-dashboard (2).zip,New admin panel/ikixkart-dashboard/adminpanel.zip,New admin panel/ikixkart-dashboard/Archive.zip,Backend/app.zip,Backend/Archive.zip. - Backend Test/Scratch Scripts (29 files):
Backend/test_*.py(test_convert,test_credit_flow,test_credit_storefront_flow,test_db,test_db_sync,test_delivery_cod_rules,test_get_terminals,test_notifications,test_query,test_quote,test_sync,test_warranty_db,test_warranty_flow,test_zeptomail,setup_api_test),alter_*.py,add_location*.py,drop_db.py,fix_db.py,cleanup_catalog_showcase.py,populate_cashify_products.py,reset_admin.py,unlock.py,migrate_wallet_db.py, etc. - SQLite Test DBs & Screenshots:
Backend/ifixkart_crm.db,Backend/local_ifixkart.db,Backend/warranties_page.png,Backend/warranties_success.png. - Duplicate Directory: Root
swarm/duplicate removed (canonical code preserved underBackend/swarm/). - Reports Test Scripts:
run_all_audits.sh,reports/audit_*.py,reports/test_swarm_api.py. - Python Caches: Untracked ~100+
.pycfiles inBackend/app/**/__pycache__/from git index; removed.pytest_cache/.
- Logs & Dumps:
- Verification:
- Verified
test_locs.py,test_ssh.py,query_locations.py, anddeploy_full_updates.pyexist and intact. - Verified FastAPI backend boots and imports cleanly (
venv/bin/python -c 'from app.main import app').
- Verified