Executive System Overview
GBG-X is a modular enterprise ERP/WMS backend built around FastAPI and MongoDB. The backend combines transactional business services with an immutable inventory ledger, real-time inventory projections, event-driven processing, strict multi-tenant authorization, procurement and sales workflows, and an EV asset digital-twin layer.
Primary Architectural Characteristics
API-driven FastAPI application with a unified /api/v1 routing boundary.
MongoDB persistence using asynchronous access through Motor.
Transactional Outbox Pattern for reliable asynchronous business events.
Double-entry inventory ledger using source and destination locations for every stock movement.
Real-time inventory quants as a derived operational projection of the immutable stock-move history.
FEFO allocation for batch/serial-aware inventory reservation and warehouse execution.
JWT-based authentication and role-based authorization with tenant-aware query filtering.
ACID MongoDB transactions for complex multi-document operations such as service closure and delivery.
Analytics layer using database-side aggregation and concurrent asynchronous queries.
Digital-twin representation of vehicle/component relationships for batteries, motors, and serialized EV assets.
High-Level Logical Architecture
Architecture & Cross-Cutting Design
2.1 Layering
| Layer | Responsibility | Examples |
|---|---|---|
| API / Router | HTTP contracts, dependencies, request/response handling | auth/api/v1.py sales/router.py |
| Domain / Service | Business rules and orchestration | ProductService reservation_service |
| Repository | Persistence abstraction where used | ProductRepository FitmentRepository |
| Core | Cross-cutting infrastructure | audit.py outbox.py logger.py |
| Database | Transactional state and projections | MongoDB collections |
| External Infrastructure | Object storage and cloud integrations | AWS S3 / boto3 |
2.2 Core Architectural Patterns
- Transactional Outbox: business state and the corresponding event are persisted together so events are not silently lost.
- Idempotent Event Processing: deterministic event hashing and processed-event tracking protect against duplicate execution.
- Double-Entry Inventory: every stock movement has a source and destination location, preserving balanced movement history.
- Projection Model: inventory_quants provides fast current-state reads while stock_moves remains the historical source of truth.
- FEFO: inventory is allocated according to manufacturing/expiry chronology where applicable.
- RBAC + Tenant Isolation: endpoint authorization is combined with database query filtering.
- Clean Architecture: selected domains, especially Products and Fitment, separate API, domain service, and repository responsibilities.
- ACID Orchestration: high-risk workflows combine related writes inside MongoDB transactions.
Module 1 — Application Core & Configuration
- Uses FastAPI lifespan management to connect to MongoDB during startup and close connections during shutdown.
- Runs index creation during application startup.
- Applies global X-GBGX-S2S middleware; /health and OPTIONS bypass the S2S check.
- Loads CORS origins from CORS_ALLOWED_ORIGINS.
- Registers the application routers under /api/v1.
- Uses Pydantic BaseSettings for typed environment configuration.
- Loads development settings from .env.
- Includes MongoDB, JWT, AWS S3, and token-expiration configuration.
- Maintains primary and optional read-replica MongoDB clients.
- Falls back to the primary database when a read replica is not configured.
- Exposes get_db() and get_read_db() as FastAPI dependencies.
- Uses lazy connection behavior to support AWS SnapStart-style serverless execution.
- create_indexes.py defines indexes for high-volume and query-sensitive collections.
- run_indexes.py applies indexes independently from the FastAPI process.
- backfill_quants.py rebuilds inventory_quants by replaying historical DONE and RESERVED stock moves chronologically.
Module 2 — Core Utilities & Intelligence
- Standardizes Python logging with timestamp, level, logger name, and message.
- Writes to stdout for cloud logging systems.
- Writes critical actions to the audit_logs collection.
- Records action, entity type, entity ID, user email, and timestamp.
- Functions as an append-only historical audit mechanism.
- Stores pending business events in event_outbox.
- process_outbox() polls and processes pending events.
- Uses deterministic SHA-256 payload hashing and processed_events to provide idempotency.
- Routes event types through handle_event_by_type().
- Includes structural support for Idempotency-Key middleware.
- Defines EnterprisePDF branding, headers, footers, page numbers, and UTC timestamps.
- Generates purchase orders, sales invoices, GRNs, delivery challans, and packing slips.
- Supports serial-number rows, EV identifiers, payment history, and balance-due presentation.
Defines abstract interfaces for future predictive capabilities:
- StockoutPredictor — stockout probability and demand forecasting.
- VendorRiskRanker — supplier risk and delay prediction.
- BatteryDegradationAnalyzer — battery RUL and anomaly analysis.
Module 3 — Authentication & Authorization
Defines the system role hierarchy:
- bcrypt is used for password hashing and verification.
- create_access_token() signs JWT claims with JWT_SECRET_KEY.
- Access tokens receive an expiration claim based on ACCESS_TOKEN_EXPIRE_MINUTES.
- OAuth2PasswordBearer extracts the Bearer token.
- JWT validation checks the signature and required claims: sub, role, tenant_id.
- require_roles() creates route-specific RBAC dependencies.
- get_entity_filter() constructs tenant-aware MongoDB filters.
- COMPANY_ADMIN may receive an unrestricted filter; tenant-bound roles receive tenant-specific filters.
- authenticate_user() verifies identity and active status.
- login_user() issues a JWT and returns role and tenant information.
- The MongoDB user _id is used as the JWT sub claim.
- Authentication profiling logs can measure bcrypt and MongoDB execution time.
Module 4 — Entities & Products
- Company administrators can provision warehouses, dealers, and vendors.
- Enforces a single CENTRAL_WAREHOUSE rule.
- Generates readable tenant IDs using WH- / DLR- prefixes and UUID-derived suffixes.
- Creates a linked admin user for a newly provisioned entity.
- Staff tenant_id is derived from the manager's JWT rather than trusted request data.
- Suspending an entity cascades is_active=False to users belonging to that tenant.
- Uses API → Domain Service → Repository layering.
- Prevents duplicate parent and variant SKUs.
- Generates variant SKUs when missing.
- Blocks product deletion when stock_moves contain inventory history.
- Cleans fitment_registry when a product is deleted.
- Supports hierarchical categories with level and hierarchy path.
- Uses strict Pydantic validation for warranty months, costs, prices, UOM, serialization type, and compliance type.
- Enforces selling_price >= cost_price.
Module 5 — Vendors, Procurement & Service
- Validates Indian GSTIN format and normalizes phone numbers.
- Provisions vendor record, VENDOR portal account, and entities record.
- Maintains a reliability score from 0 to 100.
- QC results can adjust reliability; low scores can automatically suspend the vendor.
- Server-side PO pricing prevents client-side price tampering.
- Supports RFQs sent to multiple vendors.
- Public quote submission can be performed through a secure link.
- GRN processing supports external vendors and internal transfers.
- Serial validation and batch ID generation preserve FEFO integrity.
- Three-way invoice matching compares PO, GRN, and supplier invoice values.
Invoice states: MATCHED PRICE_DISCREPANCY GRN_MISSING
- Supports service orders, AMCs, warranties, and part swaps.
- Ticket closure uses a MongoDB transaction for coordinated inventory, warranty, defective-asset, and invoice writes.
- Serialized consumed parts require serial-number information.
- Warranty claims can move defective serialized assets to a DAMAGED zone.
- Warranty tickets can generate zero-value paid invoices and close automatically.
- Service execution integrates with EV assets for uninstall/install operations.
Module 6 — Sales, Returns & Media
- Can automatically provision a CUSTOMER portal account for a newly encountered customer email.
- Creates sales orders together with SALES_ORDER_CREATED outbox events inside an ACID transaction.
- Reservation processing can occur asynchronously through the Outbox Worker.
- FEFO bin allocation computes net available stock and creates granular RESERVED moves.
- Order listing uses batch queries to avoid an N+1 stock-move lookup pattern.
- Delivery performs coordinated inventory deduction, vehicle ownership transfer, warranty registration, and invoice generation.
- Validates warranty eligibility from serial history, original receipt timing, and catalog warranty duration.
- Creates RMA records and RETURN stock moves.
- Failed parts can be moved to VIRTUAL-SCRAP-LOC and associated RMAs marked SCRAPPED.
- Return and scrap actions are auditable.
- Uploads media to AWS S3.
- Uses lazy boto3 import inside the upload endpoint.
- Protects uploads through RBAC.
- Uses UUID-based object keys to avoid filename collisions.
Module 7 — Inventory: Base & Core Services
- StockMoveBase models source and destination locations plus serial, batch, manufacturing-date, cost, and tenant data.
Statuses: DRAFT RESERVED DONE CANCELLED
Move types: RECEIPT PICK PACK TRANSFER SCRAP PUTAWAY + related operations
- Defines a Protocol for inventory capabilities such as get_available_inventory, reserve_inventory, and process_qc.
- create_stock_move() prevents identical source and destination locations.
- Tenant IDs can be extracted from location identifiers.
- Writes immutable stock moves and synchronizes inventory_quants.
- DONE movements adjust physical availability; RESERVED movements adjust available/reserved balances.
- inventory_quants provides fast current-state stock reads.
- Uses MongoDB $inc for atomic quantity updates.
- Ignores virtual and transitional locations for active-stock calculations.
- Supports FEFO deduction behavior when manufacturing date is not directly supplied.
- Removes zeroed quant documents.
- Builds warehouse/zone/rack/bin hierarchy paths.
- Validates root locations and provides safe location resolution.
- Cycle counts use snapshot/recheck concurrency control and return 409 Conflict when stock changes during counting.
- Adjustments use virtual gain/loss locations to preserve double-entry accounting.
- Applies tenant-based filters to movement and quant queries.
- Putaway queue identifies transit stock and suitable empty bins.
Module 8 — Inventory: Fulfillment & Operational Services
- Calculates batch-level availability with MongoDB aggregation.
- Sorts batches by manufacturing date for FEFO.
- Creates RESERVED moves until requested quantity is allocated.
- Uses idempotency keys to prevent duplicate reservations.
- Builds a RESERVED pick queue while excluding PUTAWAY work.
- Validates picks and transitions moves to DONE.
- Synchronizes related PO/transfer statuses for transit-bound stock.
- Creates OPEN packages and associates picked stock moves with package IDs.
- DISPATCHED packages receive courier tracking and timestamps.
- Provides a queue of picked but unpackaged customer-bound items.
- Supports inter-location, inter-entity, and Return-to-Vendor movements.
- Uses PENDING_APPROVAL before generating RESERVED pick tasks.
- Routes RTV/RMA-related defective assets through DAMAGED zones.
- Uses bin-level FEFO allocation for standard transfers.
- Runs QC updates inside MongoDB transactions.
- Moves items to QC_PASS or QC_FAIL destinations.
- Adjusts vendor reliability based on pass/fail results.
- Refurbishment can return a recoverable item from scrap to active inventory.
- trace_serial_number() builds a chronological serialized-asset movement history and resolves human-readable locations.
Module 9 — Analytics
- Serializes MongoDB documents for frontend consumption.
- Calculates inventory and backorder valuation using product catalog prices.
- Defaults missing prices to 0.0 for conservative metric behavior.
- Computes QC pass rate and fill rate through database-side aggregation.
- Calculates tenant-scoped inventory valuation while excluding virtual, transit, and damaged locations.
- Calculates vendor lead time and defect rates with defensive datetime checks.
- Provides simplified FIFO valuation from historical receipt and QC-pass moves.
- Uses asyncio.gather for concurrent dashboard queries.
- Provides role-specific summaries for dealers, warehouse managers, and company administrators.
- Scopes audit results for non-admin users to their tenant.
- Defines dashboard areas, risk levels, and KPI types.
- Pydantic response models such as VendorMetric and RecallReportResponse provide stable API contracts.
Module 10 — EV Assets, Fitment & Batteries
- install_part_to_vehicle() and uninstall_part_from_vehicle() create assembly events and update cached vehicle component serials.
- Cached fields such as current_battery_serial reduce repeated historical queries.
- mint_refurbished_part() supports serialized component refurbishment and re-entry to inventory.
- swap_vehicle_component orchestrates uninstall, install, warranty changes, RMA generation, and potential vendor debit notes.
- get_unified_product_passport accepts VIN or serial number and returns consolidated lifecycle information.
- Uses Domain Service + Repository architecture.
- Validates product existence before mapping.
- Prevents invalid VEHICLE-to-VEHICLE mappings.
- Prevents duplicate mappings at the same fitment position.
- Enriches compatibility responses with catalog information.
- Tracks State of Health and cycle count.
- Supports battery transfer between vehicles and stock.
- Synchronizes battery current_vehicle_vin and status.
- Clears the old vehicle's battery reference and sets the new vehicle's reference during transfers.
End-to-End Business Workflows
13.1 Sales Order to Delivery
- 1Customer / order creation
- 2ACID order + SALES_ORDER_CREATED outbox event
- 3Outbox processing
- 4FEFO inventory reservation
- 5Warehouse picking
- 6Packing and dispatch
- 7Delivery transaction
- 8Inventory deduction to customer location
- 9Vehicle ownership transfer when applicable
- 10Warranty registration
- 11Sales invoice generation
13.2 Procure-to-Stock
- 1Vendor onboarding
- 2RFQ creation and vendor quotation
- 3Purchase order creation with server-side catalog pricing
- 4Goods receipt
- 5Serial / batch validation
- 6Stock movement into receiving / transit workflow
- 7QC inspection
- 8Vendor reliability adjustment
- 9Putaway into warehouse stock
13.3 Service & Component Replacement
- 1Service order creation
- 2Part consumption using FEFO
- 3Serialized-part validation
- 4Warranty evaluation
- 5Defective component handling
- 6EV component uninstall / install
- 7Warranty update
- 8Invoice generation
- 9Ticket closure
13.4 Return / RMA / Scrap
- 1RMA initiation
- 2Serial history lookup
- 3Warranty eligibility calculation
- 4RETURN stock movement to QC
- 5QC / refurbishment or scrap decision
- 6Scrap movement and RMA status update
- 7Audit logging
13.5 EV Component Swap
- 1Identify vehicle and old component
- 2Uninstall old component
- 3Install replacement component
- 4Update vehicle cached serial fields
- 5Update old-component warranty
- 6Register replacement warranty where applicable
- 7Generate RMA and vendor debit note when conditions are met
- 8Expose unified product passport / history
Data Integrity, Security & Operational Invariants
| Area | Invariant / Control | Purpose |
|---|---|---|
| Authentication | JWT requires sub, role, tenant_id | Ensures authenticated requests carry identity and tenancy context. |
| RBAC | Route dependencies enforce allowed roles | Prevents unauthorized operations. |
| Tenant Isolation | MongoDB filters derived from JWT tenant context | Prevents cross-tenant data exposure. |
| Entity Provisioning | Only one CENTRAL_WAREHOUSE | Protects organizational topology. |
| Products | SKU uniqueness | Prevents ambiguous catalog identity. |
| Products | Inventory-history deletion barrier | Prevents orphaned inventory history. |
| Pricing | selling_price >= cost_price | Protects product master-data integrity. |
| Inventory | Source ≠ destination | Preserves meaningful double-entry movements. |
| Inventory | stock_moves immutable | Maintains historical truth. |
| Inventory | inventory_quants derived from movements | Enables fast operational reads while preserving history. |
| Cycle Count | Snapshot/recheck before adjustment | Prevents concurrent count corruption. |
| Outbox | Processed-event hash tracking | Prevents duplicate event effects. |
| Procurement | Server-side PO pricing | Prevents client-side price manipulation. |
| Serial Assets | Serialized movement history | Supports traceability, warranty, and compliance. |
| EV Digital Twin | Cached current component serials | Keeps physical and digital assembly state synchronized. |
Performance & Scalability Considerations
- MongoDB indexes are explicitly provisioned for high-volume operational collections and known query patterns.
- inventory_quants avoids repeatedly aggregating historical stock moves for current-stock reads.
- Analytics dashboard queries can execute concurrently using asyncio.gather.
- Sales order listing uses batch querying to avoid N+1 stock-move lookups.
- Read-replica support can route read-heavy workloads away from the primary database.
- Lazy boto3 import reduces baseline application startup overhead for deployments where media endpoints are not used.
- The Outbox pattern decouples critical order creation from downstream inventory reservation work.
- Idempotency protections make retry behavior safer for asynchronous workers.
- UUID-based media keys prevent object-name collision and reduce coordination requirements.
Cross-Module Dependency Map
| From | Depends On / Integrates With | Key Relationship |
|---|---|---|
| Authentication | Entities, all business modules | Provides identity, role, and tenant context. |
| Entities | Authentication, Products | Creates tenants and linked accounts. |
| Products | Inventory, Procurement, Sales, Fitment, Analytics | Provides SKU, price, warranty, and compatibility master data. |
| Vendors | Procurement, QC, Analytics | Supplier lifecycle, scoring, and purchasing eligibility. |
| Procurement | Products, Inventory, Vendors, QC | Turns supplier transactions into controlled stock. |
| Sales | Products, Inventory, Outbox, EV Assets | Turns customer orders into reservations, delivery, warranty, and invoices. |
| Returns | Inventory, Products, Audit | Reverses customer stock flows and manages warranty/scrap. |
| Service | Inventory, Products, EV Assets, Warranty | Consumes parts and updates vehicle component state. |
| Inventory | Products, Procurement, Sales, Service, Returns | Authoritative physical stock movement domain. |
| Analytics | Inventory, Sales, Procurement, QC, Audit | Read / BI layer over operational data. |
| EV Assets | Inventory, Service, Fitment, Batteries, Vendors | Digital genealogy and component lifecycle. |
| Fitment | Products, EV Assets | Compatibility rules for vehicle/component relationships. |
| Batteries | EV Assets, Inventory | Battery-specific lifecycle and vehicle synchronization. |
16.1 Core Data Collections Referenced
| Collection | Primary Role |
|---|---|
| users | User identity, authentication state, roles, tenant association. |
| entities | Business entities / tenants and organizational records. |
| product_catalogs | Products, variants, prices, warranty and master data. |
| vendors | Supplier master and reliability information. |
| stock_moves | Immutable inventory movement ledger. |
| inventory_quants | Current inventory projection. |
| event_outbox | Pending transactional events. |
| processed_events | Idempotency history for processed events. |
| audit_logs | Historical audit events. |
| fitment_registry | Vehicle/product compatibility mappings. |
| ev_assets | Serialized EV components / digital-twin state. |
| sales_orders | Customer sales transactions. |
| purchase_orders | Supplier procurement transactions. |
| RMA / warranty records | Reverse logistics and warranty lifecycle information. |
Technical Reference Summary
The GBG-X backend is organized around a small number of strong invariants: authenticated tenant context, immutable inventory history, derived current inventory, reliable event delivery, controlled master data, and synchronized serialized EV assets. The ten modules collectively form an integrated ERP/WMS rather than ten isolated feature packages.
Core Concepts to Understand Before Modifying the Code
- Understand JWT claims and tenant filtering before changing any protected endpoint.
- Treat stock_moves as historical truth; do not bypass the ledger for inventory-changing behavior.
- Understand how inventory_quants is synchronized and rebuilt before modifying inventory calculations.
- Use the Outbox mechanism for workflows that require reliable asynchronous downstream processing.
- Preserve FEFO behavior in reservation, transfer, and service-part consumption paths.
- Respect product SKU, pricing, warranty, and fitment invariants.
- Use transactions for multi-document business operations where partial writes would corrupt business state.
- Maintain EV digital-twin cached fields together with assembly events and inventory movements.
- Keep analytics calculations tenant-scoped and exclude virtual/transitional locations where appropriate.
- Preserve audit logging for critical state-changing operations.
Appendix A — Module Inventory
| # | Module | Primary Responsibility |
|---|---|---|
| 1 | Application Core & Configuration | Bootstrap, settings, DB, indexes, quant backfill |
| 2 | Core Utilities & Intelligence | Logging, audit, outbox, PDFs, AI interfaces |
| 3 | Authentication & Authorization | Identity, JWT, RBAC, tenant isolation |
| 4 | Entities & Products | Tenants, staff, catalog, categories, fitment cleanup |
| 5 | Vendors, Procurement & Service | Suppliers, POs, GRNs, invoice matching, service |
| 6 | Sales, Returns & Media | Orders, delivery, RMA, scrap, S3 media |
| 7 | Inventory — Base & Core | Ledger, quants, locations, warehouse, cycle count |
| 8 | Inventory — Fulfillment | Reservation, picking, packing, transfers, QC, traceability |
| 9 | Analytics | KPIs, valuation, dashboards, audit analytics |
| 10 | EV Assets, Fitment & Batteries | Digital twin, compatibility, battery lifecycle |
Appendix B — Key Status / State Transitions
| Domain | Representative Transition |
|---|---|
| Outbox | PENDING → PROCESSED / DUPLICATE_SKIPPED |
| Inventory Move | DRAFT / RESERVED → DONE; CANCELLED where applicable |
| Package | OPEN → DISPATCHED |
| Transfer | PENDING_APPROVAL → RESERVED |
| Entity | ACTIVE → SUSPENDED (with user deactivation cascade) |
| Vendor | ACTIVE → SUSPENDED based on reliability threshold |
| RMA | Active lifecycle → SCRAPPED when failed part is written off |
| QC | Item → QC_PASS or QC_FAIL |