# iFixKart Platform: Unified Master Specification & Architectural Blueprint This document serves as the **Ultimate Master Specification** for the **iFixKart Unified Commerce, Service & Operations Platform**. It merges all business requirements, high-level enterprise capabilities, deployment layouts, database schemas, code blueprints, and implementation roadmaps into a single source of truth. --- ## Document Control & Project Overview | Attribute | Details | | :--- | :--- | | **Project Name** | iFixKart — Unified Commerce, Service & Operations Platform | | **Business Scope** | Electronics retail (parts, mobiles, tablets, laptops) and device repair service | | **Geographic Target** | Chennai, Tamil Nadu, India | | **Document Version** | 1.0 (Master Integration Specification) | | **Prepared By** | Trionix Solution | | **Prepared For** | iFixKart Stakeholders, Development Team, Investors | | **Classification** | Confidential — Internal & Client Use | ### Version History * **v1.0 (July 2026)**: Final consolidation of Storefront Architecture Plans, Business Requirements Documents (BRD), Ecosystem Topologies, database DDL designs, backend Python/FastAPI helper scripts, and operational roadmaps. --- ## 1. Executive Summary & Business Case Historically, iFixKart's commerce operations (selling spare parts and devices) and service operations (booking device repairs) have functioned in silos. This fragmentation creates operational bottlenecks, inventory mismatches, and missed revenue opportunities. The iFixKart Unified Platform bridges this gap with: * **Two Front-Ends**: A Next.js customer-facing storefront and an internal Next.js admin management board. * **Three Backend Components**: An E-commerce backend (FastAPI), an Admin/CRM backend (FastAPI), and a private internal notification app (Bailey). * **Two Database Schemas**: Dedicated MySQL databases for storefront actions and internal CRM/Billing data. ### Key Performance Benefits 1. **Zero Data Silos**: Inventory, customers, invoicing, and repair histories share data pipelines. 2. **Minimized Revenue Leakage**: Implemented through automated Razorpay reconciliation, real-time inventory locking, and audit logs. 3. **Operational Scalability**: Streamlining slot bookings, shipping labeling, and follow-up notifications. --- ## 2. Business Capability & Ecosystem Map ### 2.1 Capability Architecture This capability tree shows the distinct business divisions enabled by the platform: ```mermaid mindmap root((iFixKart Platform)) Demand Generation Website SEO & AEO Google Merchant Center Sync Meta Ads Lead Capture Social Media Content Calendar Channel & Sales Management Customer Storefront (Next.js) Walk-In In-Store POS (Billing) Order Management (OMS) Inventory Allocation Ledger Service Delivery Device Lookup wizard Slot Booking Calendar Advance Deposit Collection Technician Job Portal Finance & Operations Sequential GST Invoicing Automated Payout Reconciliation RMA & Product Returns Warranty Tracker Security & Reliability Role-Based Access (RBAC) Audit Logs Redis Lock Concurrency Bailey Whatsapp Alerts ``` --- ### 2.2 System Ecosystem Flow Diagram This shows how the front-end interfaces, backend services, databases, and third-party APIs communicate: ```mermaid graph TD %% Users customer((Customers)) admin_staff((Staff & Admins)) tech_staff((Technicians)) %% Channels subgraph Channels ["Channels (Front-Ends)"] storefront[Customer Storefront & Repair Portal] admin_dashboard[Admin & Management CRM Dashboard] tech_portal[Mobile-Friendly Technician Portal] end %% Core Services subgraph Core ["Platform Services (Modular Monoliths)"] ecomm_api[E-commerce API Service] admin_api[Admin Operations API Service] bailey_bot[Bailey WhatsApp Dispatcher] end %% Data Store subgraph Storage ["Storage Layer"] ecomm_db[(E-commerce DB)] admin_db[(Admin DB)] cache[(Redis Session & Cache)] end %% External Systems subgraph External ["External Services"] razorpay[Razorpay Payment Gateway] shipping_rocket[ShippingRocket Logistics] meta[Meta Marketing API] gmc[Google Merchant Center] end %% Interconnections customer -->|Accesses| storefront admin_staff -->|Accesses| admin_dashboard tech_staff -->|Accesses| tech_portal storefront -->|REST APIs| ecomm_api admin_dashboard -->|REST APIs| admin_api tech_portal -->|REST APIs| admin_api ecomm_api <-->|Sync Engine| admin_api ecomm_api -->|Cache & Locks| cache ecomm_api -->|Write/Read| ecomm_db admin_api -->|Write/Read| admin_db ecomm_api -.->|Triggers Alerts| bailey_bot admin_api -.->|Triggers Alerts| bailey_bot ecomm_api <-->|Collect Payments| razorpay admin_api <-->|Generate Labels| shipping_rocket admin_api <-->|Sync Feeds| gmc admin_api <-->|Sync Leads| meta classDef channel fill:#eff6ff,stroke:#2563eb,stroke-width:2px; classDef core fill:#f5f3ff,stroke:#7c3aed,stroke-width:2px; classDef storage fill:#ecfdf5,stroke:#059669,stroke-width:2px; classDef ext fill:#fffbeb,stroke:#d97706,stroke-width:1px; class storefront,admin_dashboard,tech_portal channel; class ecomm_api,admin_api,bailey_bot core; class ecomm_db,admin_db,cache storage; class razorpay,shipping_rocket,meta,gmc ext; ``` --- ## 3. Customer Storefront & Portal Architecture * **Reference UI Design**: `https://demo.templatemonster.com/demo/501755.html` (`TechShop` theme context). * **Target Codebase Location**: `/run/media/sonu/FAM/SERVER/IfixKartEcommerce/Ecommerce Page` * **Documentation Location**: `/run/media/sonu/FAM/SERVER/IfixKartEcommerce/Documentation` ### 3.1 Architectural Decision Records (ADRs) * **ADR-1**: The customer storefront & repair wizard is constructed as a dedicated Next.js app inside `Ecommerce Page`. * **ADR-2**: `Admin Ecommerce` remains the primary ERP management dashboard. * **ADR-3**: Both storefront and admin share the identical FastAPI backend (`http://127.0.0.1:8000`), JWT authentication schemas, and design token classes. * **ADR-4**: Catalog records are dynamic; zero duplicate business logic or hardcoded inventory data is permitted. * **ADR-5**: Newly added modules must remain modular, decoupled, and reusable. ### 3.2 Design Token Classes (`app/globals.css`) * **Primary Accent**: `var(--primary)` (`#e4382f`) * **Foreground Text**: `var(--foreground)` (`#1b2559`) * **Background Surface**: `var(--background)` (`#f4f7fe`) * **Card Surface**: `var(--card)` (`#ffffff`) * **Border Radii**: `--radius-sm` (6px), `--radius-md` (8px), `--radius-lg` (12px) --- ### 3.3 Component Inventory & Status | Category | Component Name | Action / Status | Source / Asset Path | | :--- | :--- | :--- | :--- | | **Existing UI Primitives** | Button, Input, Dialog, Card, Data Table | **REUSE** | Tailwind design tokens in `app/globals.css` | | **Layout System** | App Container, Grid System, Flex Utilities | **REUSE** | Tailwind CSS layout engine | | **State Management** | Storefront Cart & Wishlist Store | **CREATE** | `store/cartStore.ts` | | **API Client** | `apiFetch` HTTP Client with Auth | **REUSE** | `services/api/client.ts` | | **API Endpoint Registry** | API Endpoints Constants (Versioned `/api/v1/...`) | **EXTEND** | `services/api/config.ts` | | **Catalog Services** | Brands, Categories, Parts, Devices, Products APIs | **REUSE** | `services/api/catalogService.ts` | | **Icons System** | Lucide React Icons | **REUSE** | `lucide-react` | | **Store Header & Search** | `StoreHeader`, `LiveSearch` (Debounced Autocomplete) | **CREATE** | `components/store/StoreHeader.tsx`, `LiveSearch.tsx` | | **Dynamic Mega Menu** | `MegaMenu` (Database Categories Tree) | **CREATE** | `components/store/MegaMenu.tsx` | | **Hero Slider** | `HeroBanner` (FastAPI Dynamic Banners) | **CREATE** | `components/store/HeroBanner.tsx` | | **Product Card & Grid** | `ProductCard`, `ProductGrid` (Native Schema & Stock) | **CREATE** | `components/store/ProductCard.tsx`, `ProductGrid.tsx` | | **Cart Drawer** | `CartDrawer` (Slide-over Cart Preview) | **CREATE** | `components/store/CartDrawer.tsx` | | **Quick View** | `QuickViewModal` (Product Detail Preview) | **CREATE** | `components/store/QuickViewModal.tsx` | | **Repair Booking** | `RepairBookingWizard` (Device Repair Flow) | **CREATE** | `components/store/RepairBookingWizard.tsx` | --- ## 4. Deep-Dive Process Flows ### 4.1 Product Checkout with Distributed Stock Soft-Lock Prevents race conditions by locking stock items during cart checkout before final payment confirmation. ```mermaid sequenceDiagram autonumber actor Customer as Storefront Client participant API as FastAPI E-comm Backend participant Redis as Redis Cache (Locks) participant DB as MySQL DB participant PG as Razorpay Gateway Customer->>API: POST /api/v1/checkout (Items, Cart Info) rect rgb(240, 248, 255) note right of API: Step 1: Distributed Lock Evaluation API->>Redis: SETNX lock:product_id:uuid "locked" EX 600 Redis-->>API: Lock Acquired (Success) end API->>DB: Check stock quantity & status DB-->>API: Available (In Stock) API->>DB: CREATE Order in state "New Order" (Soft-Locked) API->>PG: Initialize Razorpay Order (Amount, Currency, Receipt ID) PG-->>API: return razorpay_order_id API->>Customer: return order details + razorpay_order_id Customer->>PG: Complete checkout payment in UI PG->>API: POST /api/v1/payments/webhook (Signature, razorpay_payment_id) rect rgb(244, 247, 254) note right of API: Step 2: Idempotency & Hard Deduction API->>DB: Check webhook idempotency table for payment_id DB-->>API: Not processed yet (Unique) API->>DB: Update Order state to "Paid" API->>DB: Deduct physical stock (Hard-Deducted) API->>Redis: DEL lock:product_id:uuid end API-->>PG: HTTP 200 OK API->>Customer: Push payment confirmation notification ``` --- ### 4.2 End-to-End Service Booking Lifecycle Integrates slot availability checks, advance deposit collections, technician management, and balance closure. ```mermaid graph TD A[Customer selects Device & Issue] --> B[Browse Calendar Slots] B --> C[Select Time Slot & Pay 30% Advance] C --> D{Payment Successful?} D -- No --> E[Release Slot & Send Recovery Alert via Bailey] D -- Yes --> F[Booking Confirmed: State = New] F --> G[System assigns Technician based on skills/availability] G --> H[Technician accepts job on Tech Portal] H --> I[Technician starts repair: State = Processing] I --> J[Technician logs parts used & completes job] J --> K[Invoice Manager computes outstanding 70% balance] K --> L[Customer pays balance: State = Completed] L --> M[System issues sequential GST Invoice & updates CRM] style D fill:#fef3c7,stroke:#d97706,stroke-width:2px; style F fill:#dcfce7,stroke:#15803d,stroke-width:2px; style M fill:#dbeafe,stroke:#1d4ed8,stroke-width:2px; ``` --- ## 5. Relational Database Specifications (MySQL DDL) To maintain consistent data schemas across both domains, implement these key database layouts: ### 5.1 Catalog & Concurrency Tables ```sql CREATE TABLE IF NOT EXISTS products ( id INT AUTO_INCREMENT PRIMARY KEY, sku VARCHAR(50) UNIQUE NOT NULL, name VARCHAR(255) NOT NULL, price DECIMAL(10, 2) NOT NULL, stock_qty INT DEFAULT 0, status ENUM('Available', 'Unavailable', 'Archived') DEFAULT 'Available', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, INDEX idx_sku (sku) ); CREATE TABLE IF NOT EXISTS inventory_locks ( id INT AUTO_INCREMENT PRIMARY KEY, product_id INT NOT NULL, lock_uuid VARCHAR(64) UNIQUE NOT NULL, quantity INT DEFAULT 1, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE, INDEX idx_expiration (expires_at) ); ``` ### 5.2 Billing, Compliance & Auditing ```sql CREATE TABLE IF NOT EXISTS invoices ( id INT AUTO_INCREMENT PRIMARY KEY, invoice_number VARCHAR(100) UNIQUE NOT NULL, -- Sequential & Immutable (GST requirement) order_id INT NULL, booking_id INT NULL, customer_name VARCHAR(255) NOT NULL, gst_number VARCHAR(15) NULL, cgst DECIMAL(8, 2) DEFAULT 0.00, sgst DECIMAL(8, 2) DEFAULT 0.00, igst DECIMAL(8, 2) DEFAULT 0.00, subtotal DECIMAL(10, 2) NOT NULL, total DECIMAL(10, 2) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_invoice_num (invoice_number) ); CREATE TABLE IF NOT EXISTS audit_logs ( id INT AUTO_INCREMENT PRIMARY KEY, actor_id INT NOT NULL, actor_name VARCHAR(255) NOT NULL, action_type VARCHAR(100) NOT NULL, -- e.g., "PRICE_CHANGE", "REFUND_APPROVED" target_table VARCHAR(100) NOT NULL, target_id INT NOT NULL, before_state JSON NOT NULL, after_state JSON NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_audit_lookup (action_type, target_table, target_id) ); ``` --- ## 6. Code Implementation Blueprints (FastAPI / Python) ### 6.1 Distributed Locking Service (Redis + Python) ```python import uuid import redis from fastapi import FastAPI, HTTPException r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) app = FastAPI() def acquire_soft_lock(product_id: int) -> str: """Attempts to lock item in redis for 10 minutes (600s) to prevent double-booking.""" lock_uuid = str(uuid.uuid4()) lock_key = f"lock:product:{product_id}" # Set NX (set if not exists) with expiry acquired = r.set(lock_key, lock_uuid, ex=600, nx=True) if not acquired: raise HTTPException(status_code=409, detail="Inventory is locked in another checkout session.") return lock_uuid def release_soft_lock(product_id: int, lock_uuid: str): """Safely release the lock only if the token matches.""" lock_key = f"lock:product:{product_id}" lua_release = """ if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end """ r.eval(lua_release, 1, lock_key, lock_uuid) ``` ### 6.2 Idempotent Webhook Receiver (Razorpay + SQLAlchemy) ```python import hmac import hashlib from fastapi import Request, Header, APIRouter, HTTPException from sqlalchemy.orm import Session router = APIRouter() @router.post("/api/v1/payments/webhook") async def handle_payment_webhook( request: Request, signature: str = Header(..., alias="X-Razorpay-Signature"), db: Session = Depends(get_db) ): body = await request.body() # Verify Secret Signature expected = hmac.new( key=bytes("YOUR_RAZORPAY_SECRET", "utf-8"), msg=body, digestmod=hashlib.sha256 ).hexdigest() if not hmac.compare_digest(expected, signature): raise HTTPException(status_code=400, detail="Signature verification failed.") payload = await request.json() event_id = payload.get("id") # Check if webhook event was processed previously duplicate = db.query(ProcessedWebhook).filter_by(event_id=event_id).first() if duplicate: return {"status": "already_processed"} # Execute Business Mutation if payload.get("event") == "order.paid": order_entity = payload["payload"]["payment"]["entity"] finalize_paid_order(db, order_entity["order_id"], order_entity["id"]) # Mark event as resolved db.add(ProcessedWebhook(event_id=event_id)) db.commit() return {"status": "success"} ``` --- ## 7. Cloud Deployment & Network Infrastructure A typical architecture deployment pattern running containerized micro-services inside a Virtual Private Cloud (VPC): ```mermaid graph TD user_traffic[Storefront Users & API Requests] --> DNS[Route 53 DNS] DNS --> LB[Nginx Load Balancer / Reverse Proxy] subgraph Containers ["Container Cluster (Docker Swarm or ECS)"] LB -->|Route: / | container_sf[Next.js Customer Storefront] LB -->|Route: /admin | container_admin[Next.js Admin Dashboard] LB -->|Route: /api/v1/storefront | container_api_ecomm[FastAPI E-commerce Service] LB -->|Route: /api/v1/admin | container_api_admin[FastAPI Admin Service] end subgraph DataServices ["Managed Data Services"] container_api_ecomm & container_api_admin --> db_rds[(Amazon RDS MySQL Master)] container_api_ecomm --> cache_redis[(Amazon ElastiCache Redis)] end subgraph VPC ["Private Network Subnet"] container_api_ecomm container_api_admin db_rds cache_redis end ``` --- ## 8. Five Concrete Mechanisms to Increase Sales & LTV The platform is designed to drive revenue at each point of contact: 1. **Abandoned Checkout Recovery**: Identifies incomplete carts or unconfirmed service slots. It triggers alerts to the sales team via Bailey so reps can call customers directly. 2. **30% Booking Deposit**: Splitting the service fee into a deposit reduces payment friction and increases initial slot bookings. 3. **Structured Warranty Lifecycles**: Tied directly to device serial numbers (IMEI). Triggers automated reminders for renewals when warranties approach expiration. 4. **Organic Search Visibility (AEO/SEO)**: Embeds Product and LocalBusiness JSON-LD markup schema. This optimizes visibility in AI-driven search models for phrases like *"device screen repair Chennai"*. 5. **Consolidated Customer Profiles**: Syncs storefront checkouts, walks-ins, and Meta social ads into a unified CRM contact record for cross-selling. --- ## 9. Implementation Gantt Roadmap & Timeline A phased, dependency-aware rollout separates database modeling from customer-facing services and automation: ```mermaid gantt title iFixKart Phased Implementation Roadmap dateFormat YYYY-MM-DD section Phase 1: Foundation Next.js Storefront & Admin :active, p1_1, 2026-07-01, 30d OMS & Basic Invoices :active, p1_2, after p1_1, 20d Razorpay Slot Bookings :p1_3, after p1_2, 15d section Phase 2: CRM & Shipping CRM Pipeline & Contacts :p2_1, after p1_3, 20d ShippingRocket Integration :p2_2, after p2_1, 15d Walk-in POS Invoicing :p2_3, after p2_2, 15d section Phase 3: Automation Inventory Lock / Distributed :p3_1, after p2_3, 15d Bailey Whatsapp Engine :p3_2, after p3_1, 10d Daily Payment Reconciliation :p3_3, after p3_2, 15d section Phase 4: Scaling Warranties & RMAs :p4_1, after p3_3, 20d Technician Calendar & Apps :p4_2, after p4_1, 20d Loyalty & GMC SEO :p4_3, after p4_2, 15d ``` --- ## 10. Non-Functional Requirements & Performance Targets * **Availability**: Target **99.5%+ uptime** for storefront and checkout. Integrates circuit breakers to ensure external API outages (e.g., ShippingRocket) degrade gracefully. * **Performance**: Storefront page loading times below **2.5 seconds** over standard mobile connections. * **Security & Regulatory Compliance**: Enforces strict RBAC. Complies with the **Indian Digital Personal Data Protection (DPDP) Act** (consent collection, database deletion APIs, and records processing limits). * **Auditability**: Records all sensitive actions (price updates, refunds, inventory edits) with target IDs, user IDs, and before/after states. --- ## 11. Appendix — Glossary * **BRD**: *Business Requirements Document* — Defines system capabilities and business value. * **OMS**: *Order Management System* — Manages order/booking states. * **CRM**: *Client Resource Management* — System of record for contacts, proposals, and leads. * **RBAC**: *Role-Based Access Control* — Endpoint access permissions based on employee roles. * **RMA**: *Return Merchandise Authorization* — Workflow for inspecting and writing off returned items. * **DLQ**: *Dead Letter Queue* — Replay queue for failed message event executions. * **Idempotency**: Guarantee that an operation produces the same result when executed multiple times. * **Circuit Breaker**: System wrapper to prevent system hangs when third-party APIs are down. * **AEO**: *Answer Engine Optimization* — Adjusting schema to optimize surfacing in AI-driven search models. * **Bailey**: Private internal team notification app pushing updates to team WhatsApp groups.