# iFixKart Platform: Deep-Dive Technical Implementation Architecture & Suggestions This document details the high-level implementation designs, processing flows, database schemas, code blueprints, and performance suggestions for the **iFixKart Unified Platform**. --- ## 1. System Processing Flow Diagrams ### 1.1 Storefront Product Checkout & Stock Soft-Lock Flow This sequence illustrates how storefront purchases are processed, using distributed soft-locks to prevent race conditions or overselling before a payment completes. ```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 ``` --- ### 1.2 Service Booking & Technician Assignment Flow This workflow outlines the service lifecycle from a customer slot booking up to technician checkout and billing. ```mermaid graph TD %% Nodes 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] %% Styling 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; ``` --- ### 1.3 Daily Automated Reconciliation Data Flow This details the cron utility that compares daily Razorpay transaction logs against internal sales invoices. ```mermaid flowchart LR cron[Scheduled Daily Cron Job] --> fetch_rp[Fetch Razorpay Settlement API] cron --> fetch_db[Fetch Local DB Payment Transactions] fetch_rp --> merge[Data Reconciliation Engine] fetch_db --> merge merge --> check{Discrepancy Detected?} check -- Yes --> flag[Log reconciliation_mismatch & Alert Admin via Bailey] check -- No --> reconcile[Mark Transaction Ledger as Reconciled] flag --> report[Generate PDF/Excel Finance Report] reconcile --> report style check fill:#fef3c7,stroke:#d97706,stroke-width:2px; style flag fill:#fee2e2,stroke:#b91c1c,stroke-width:2px; ``` --- ## 2. Core Database Schema Recommendations (MySQL) To ensure data integrity, sequential safety, and compliance (e.g., GST), we recommend the following relational model layout: ``` ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ customers │ │ products │ │ device_models │ ├──────────────────┤ ├──────────────────┤ ├──────────────────┤ │ id (PK) │◄──┐ │ id (PK) │◄──┐ │ id (PK) │ │ email │ │ │ sku (Unique) │ │ │ brand │ │ phone │ │ │ price │ │ │ series │ │ name │ │ │ stock_qty │ │ │ model_name │ └──────────────────┘ │ │ device_model_id │─┐ │ └──────────────────┘ │ └──────────────────┘ │ │ │ │ │ ┌──────────────────┐ │ ┌──────────────────┐ │ │ ┌──────────────────┐ │ orders │ │ │ order_items │ │ │ │ inventory_locks │ ├──────────────────┤ │ ├──────────────────┤ │ │ ├──────────────────┤ │ id (PK) │◄──┼───│ order_id (FK) │ │ │ │ id (PK) │ │ customer_id (FK) │───┘ │ product_id (FK) ─┼─┘ │ │ product_id (FK) ─┘ │ order_number │ │ price │ │ │ lock_uuid │ │ status │ │ quantity │ │ │ expires_at │ │ total_amount │ └──────────────────┘ │ └──────────────────┘ └──────────────────┘ │ │ ┌──────────────────┐ ┌──────────────────┐ │ │ service_bookings │ │ repair_services │ │ ├──────────────────┤ ├──────────────────┤ │ │ id (PK) │ │ id (PK) │◄──┘ │ customer_id (FK) │ │ service_name │ │ device_model_id │ │ base_price │ │ booking_date │ └──────────────────┘ │ advance_paid │ └──────────────────┘ ``` ### 2.1 Inventory & Locks Database DDL ```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) ); ``` ### 2.2 Invoicing & Audit Logging DDL ```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, FOREIGN KEY (order_id) REFERENCES orders(id), 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) ); ``` --- ## 3. Core Implementation Blueprints (FastAPI/Python) ### 3.1 Distributed Inventory Locking Service Uses Redis to execute transactional locks before confirming a slot or checking out. ```python import uuid import datetime from fastapi import FastAPI, HTTPException, Depends from sqlalchemy.orm import Session import redis r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) app = FastAPI() def get_redis_lock(product_id: int, quantity: int) -> str: """Attempts to lock item in redis for 10 minutes to prevent double-booking.""" lock_id = str(uuid.uuid4()) lock_key = f"lock:product:{product_id}" # Set NX (set if not exists) with 600 seconds expiration acquired = r.set(lock_key, lock_id, ex=600, nx=True) if not acquired: raise HTTPException(status_code=409, detail="Item is currently soft-locked in another checkout session.") return lock_id def release_redis_lock(product_id: int, lock_id: str): """Safely release the lock only if the token matches.""" lock_key = f"lock:product:{product_id}" # Use Lua script to ensure atomicity during checking and deleting 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_id) ``` --- ### 3.2 Idempotent Payment Webhook Handler (Razorpay) Ensures webhook events are executed exactly once to prevent double-invoicing or duplicate notifications. ```python import hmac import hashlib from fastapi import Request, Header, APIRouter from sqlalchemy.orm import Session router = APIRouter() @router.post("/api/v1/payments/webhook") async def handle_razorpay_webhook( request: Request, signature: str = Header(..., alias="X-Razorpay-Signature"), db: Session = Depends(get_db) ): body = await request.body() # 1. Verify Razorpay Signature expected_signature = hmac.new( key=bytes("YOUR_WEBHOOK_SECRET", "utf-8"), msg=body, digestmod=hashlib.sha256 ).hexdigest() if not hmac.compare_digest(expected_signature, signature): raise HTTPException(status_code=400, detail="Invalid signature verification.") payload = await request.json() event_id = payload.get("id") # 2. Check Idempotency Table is_processed = db.query(ProcessedWebhook).filter_by(event_id=event_id).first() if is_processed: return {"status": "already_processed"} # 3. Process Transaction event_type = payload.get("event") if event_type == "order.paid": order_details = payload["payload"]["payment"]["entity"] razorpay_order_id = order_details["order_id"] # Trigger DB State update and deduct inventory confirm_payment(db, razorpay_order_id, order_details["id"]) # 4. Record event processing completion db.add(ProcessedWebhook(event_id=event_id, processed_at=datetime.datetime.utcnow())) db.commit() return {"status": "success"} ``` --- ### 3.3 Bailey Internal WhatsApp Notification Service Minimalist, reliable helper class that sends platform events and escalations directly to the technician/admin groups. ```python import httpx import logging class BaileyNotificationService: def __init__(self, endpoint_url: str, token: str): self.endpoint_url = endpoint_url self.token = token self.client = httpx.Client(timeout=5.0) def send_team_notification(self, message: str) -> bool: """Pushes a message string to the iFixKart internal notifications channel.""" headers = { "Authorization": f"Bearer {self.token}", "Content-Type": "application/json" } payload = {"message": message} try: response = self.client.post(self.endpoint_url, json=payload, headers=headers) if response.status_code == 200: return True logging.error(f"Bailey notification dispatch failed: {response.text}") except Exception as e: logging.error(f"Failed connection to Bailey: {str(e)}") return False # Usage: # notifier = BaileyNotificationService("http://127.0.0.1:9000/api/send", "secure_token_abc") # notifier.send_team_notification("🚨 ALERT: Booking #1290 has stalled in 'Proposal' for 3 days.") ``` --- ## 4. Key Architectural Suggestions & Best Practices ### 4.1 Database Indexing Strategy To maintain low latency (< 500ms checkouts) under volume, enforce these indexes on your database: * **Composite Indexes**: Use `INDEX idx_model_repair (device_model_id, status)` for fast catalog filters. * **Tracking Lookups**: Create `INDEX idx_device_imei (imei_serial)` to enable lightning-fast service checks by technicians. * **Reconciliation Indexing**: Ensure `created_at` fields on payments and bookings are indexed to keep the daily cron execution speed high. ### 4.2 Graceful Degradation using Circuit Breakers For integrations like `ShippingRocket` and `Razorpay`, wrap your HTTP client methods in a circuit breaker configuration: * If the API fails 5 consecutive times, open the circuit for 60 seconds. * Failures should fall back to saving requests inside a local queue/database (DLQ) to be reprocessed automatically when the API returns. ### 4.3 Schema.org Structured Data Example (AEO) To capture local voice and search queries (AEO), inject JSON-LD markup on product and booking details dynamically: ```html ```