X

GBG-X ENTERPRISE ERP

Backend Code Documentation

FastAPI + MongoDB Enterprise ERP / WMS 10 Modules

GBG-X
ENTERPRISE ERP

Backend Code Documentation — a structured technical reference covering the application core, security model, master data, procurement, sales, inventory execution, analytics, and EV digital-twin capabilities.

System

GBG-X Enterprise ERP / WMS

Backend Framework

FastAPI (Python)

Database

MongoDB

Document Type

Code / Architecture Docs

Primary Architecture

Modular service-oriented FastAPI backend

Core Patterns

Transactional Outbox Double-Entry Ledger FEFO RBAC Multi-Tenancy

Documentation Scope

10 backend modules

Document Control & Scope

This document consolidates the ten supplied GBG-X backend documentation modules into a single structured technical reference. It describes the application core, security model, master data, procurement, sales, inventory execution, analytics, and EV digital-twin capabilities.

  • Application bootstrap, configuration, database connectivity, and database maintenance utilities.
  • Cross-cutting logging, auditing, event processing, PDF generation, and AI/ML interfaces.
  • Authentication, authorization, RBAC, JWT sessions, and tenant isolation.
  • Entity provisioning and product/catalog master data.
  • Vendor onboarding, procurement, GRN processing, invoice matching, and service operations.
  • Sales, customer provisioning, returns/RMA, and media uploads.
  • Inventory ledger, quants, locations, warehouse operations, reservations, picking, packing, transfers, QC, refurbishment, and traceability.
  • Analytics, KPI computation, dashboarding, and audit reporting.
  • EV assets, fitment compatibility, battery health, component swaps, warranties, RMA/debit-note flows, and product passports.
Source basis: the ten module documentation batches supplied in this conversation. This document consolidates and structures those descriptions; it does not claim additional implementation details that were not supplied.
Contents
01

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

01

API-driven FastAPI application with a unified /api/v1 routing boundary.

02

MongoDB persistence using asynchronous access through Motor.

03

Transactional Outbox Pattern for reliable asynchronous business events.

04

Double-entry inventory ledger using source and destination locations for every stock movement.

05

Real-time inventory quants as a derived operational projection of the immutable stock-move history.

06

FEFO allocation for batch/serial-aware inventory reservation and warehouse execution.

07

JWT-based authentication and role-based authorization with tenant-aware query filtering.

08

ACID MongoDB transactions for complex multi-document operations such as service closure and delivery.

09

Analytics layer using database-side aggregation and concurrent asynchronous queries.

10

Digital-twin representation of vehicle/component relationships for batteries, motors, and serialized EV assets.

High-Level Logical Architecture

Client / Frontend
FastAPI API Layer (/api/v1)
Authentication / RBAC / Tenant Filtering
Domain / Service Layer
Products · Entities · Vendors Procurement · Sales · Returns · Service Inventory · EV Assets · Fitment · Batteries Analytics
Cross-Cutting Core
AuditOutbox / EventsLoggingPDF Generation
MongoDB
business collections stock_moves (immutable ledger) inventory_quants (projection) event_outbox processed_events audit_logs
AWS S3 (media)
02

Architecture & Cross-Cutting Design

2.1 Layering

LayerResponsibilityExamples
API / RouterHTTP contracts, dependencies, request/response handlingauth/api/v1.py sales/router.py
Domain / ServiceBusiness rules and orchestrationProductService reservation_service
RepositoryPersistence abstraction where usedProductRepository FitmentRepository
CoreCross-cutting infrastructureaudit.py outbox.py logger.py
DatabaseTransactional state and projectionsMongoDB collections
External InfrastructureObject storage and cloud integrationsAWS 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.
03

Module 1 — Application Core & Configuration

Purpose — Bootstraps the FastAPI application, configures security and CORS, manages MongoDB connectivity, registers routers, and provides database maintenance utilities.
main.py
  • 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.
config/settings.py
  • Uses Pydantic BaseSettings for typed environment configuration.
  • Loads development settings from .env.
  • Includes MongoDB, JWT, AWS S3, and token-expiration configuration.
config/database.py
  • 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.
Database Maintenance Scripts
  • 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.
04

Module 2 — Core Utilities & Intelligence

Purpose — Provides structured logging, immutable audit records, reliable event processing, enterprise PDF generation, and AI/ML interface contracts.
core/logger.py
  • Standardizes Python logging with timestamp, level, logger name, and message.
  • Writes to stdout for cloud logging systems.
core/audit.py
  • 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.
core/outbox.py core/events.py
  • 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.
core/pdf_generator.py
  • 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.
intelligence/interfaces.py

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.
05

Module 3 — Authentication & Authorization

Purpose — Provides identity, password security, JWT sessions, RBAC, and tenant-level data isolation.
modules/auth/enums.py

Defines the system role hierarchy:

COMPANY_ADMIN CENTRAL_WH_MANAGER INVENTORY_MANAGER PROCUREMENT_MANAGER SALES_MANAGER WAREHOUSE_STAFF VENDOR CUSTOMER DEALER
modules/auth/security.py
  • 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.
modules/auth/dependencies.py
  • 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.
modules/auth/service.py
  • 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.
modules/auth/api/v1.py
POST /login POST /register GET /me Password reset (request / confirm) Authenticated password change
  • Authentication profiling logs can measure bcrypt and MongoDB execution time.
06

Module 4 — Entities & Products

Purpose — Manages organizational tenants and business entities while providing validated product and category master data.
modules/entities/
  • 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.
modules/products/
  • 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.
07

Module 5 — Vendors, Procurement & Service

Purpose — Handles supplier lifecycle, procure-to-pay operations, receiving and invoice matching, and service-center workflows.
modules/vendors/
  • 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.
modules/procurement/
  • 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

modules/service/
  • 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.
08

Module 6 — Sales, Returns & Media

Purpose — Drives order-to-cash, reverse logistics, and secure media upload workflows.
modules/sales/
  • 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.
modules/returns/
  • 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.
modules/media/
  • 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.
09

Module 7 — Inventory: Base & Core Services

Purpose — Provides the authoritative inventory ledger, real-time stock projection, location hierarchy, warehouse data, and cycle-count controls.
Schemas & Enums
  • 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

Contracts
  • Defines a Protocol for inventory capabilities such as get_available_inventory, reserve_inventory, and process_qc.
Ledger Service
  • 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.
Quant Service
  • 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.
Location, Warehouse & Cycle Count Services
  • 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.
Core Router
  • Applies tenant-based filters to movement and quant queries.
  • Putaway queue identifies transit stock and suitable empty bins.
10

Module 8 — Inventory: Fulfillment & Operational Services

Purpose — Translates reservations into physical warehouse execution and provides transfer, QC, refurbishment, and serial traceability services.
Reservation Service
  • 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.
Picking Service
  • 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.
Packing Service
  • 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.
Transfer Service
  • 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.
QC Service
  • Runs QC updates inside MongoDB transactions.
  • Moves items to QC_PASS or QC_FAIL destinations.
  • Adjusts vendor reliability based on pass/fail results.
Refurbishment & Traceability
  • 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.
11

Module 9 — Analytics

Purpose — Provides the business intelligence and dashboard layer across inventory, procurement, sales, vendor performance, QC, and audit data.
Helpers
  • 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.
Analytics Service
  • 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.
Router
  • 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.
Enums & Schemas
  • Defines dashboard areas, risk levels, and KPI types.
  • Pydantic response models such as VendorMetric and RecallReportResponse provide stable API contracts.
12

Module 10 — EV Assets, Fitment & Batteries

Purpose — Maintains the EV digital twin, serialized component genealogy, fitment compatibility, and battery lifecycle state.
modules/ev_assets/
  • 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.
modules/fitment/
  • 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.
modules/batteries/
  • 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.
13

End-to-End Business Workflows

13.1 Sales Order to Delivery

  1. 1Customer / order creation
  2. 2ACID order + SALES_ORDER_CREATED outbox event
  3. 3Outbox processing
  4. 4FEFO inventory reservation
  5. 5Warehouse picking
  6. 6Packing and dispatch
  7. 7Delivery transaction
  8. 8Inventory deduction to customer location
  9. 9Vehicle ownership transfer when applicable
  10. 10Warranty registration
  11. 11Sales invoice generation

13.2 Procure-to-Stock

  1. 1Vendor onboarding
  2. 2RFQ creation and vendor quotation
  3. 3Purchase order creation with server-side catalog pricing
  4. 4Goods receipt
  5. 5Serial / batch validation
  6. 6Stock movement into receiving / transit workflow
  7. 7QC inspection
  8. 8Vendor reliability adjustment
  9. 9Putaway into warehouse stock

13.3 Service & Component Replacement

  1. 1Service order creation
  2. 2Part consumption using FEFO
  3. 3Serialized-part validation
  4. 4Warranty evaluation
  5. 5Defective component handling
  6. 6EV component uninstall / install
  7. 7Warranty update
  8. 8Invoice generation
  9. 9Ticket closure

13.4 Return / RMA / Scrap

  1. 1RMA initiation
  2. 2Serial history lookup
  3. 3Warranty eligibility calculation
  4. 4RETURN stock movement to QC
  5. 5QC / refurbishment or scrap decision
  6. 6Scrap movement and RMA status update
  7. 7Audit logging

13.5 EV Component Swap

  1. 1Identify vehicle and old component
  2. 2Uninstall old component
  3. 3Install replacement component
  4. 4Update vehicle cached serial fields
  5. 5Update old-component warranty
  6. 6Register replacement warranty where applicable
  7. 7Generate RMA and vendor debit note when conditions are met
  8. 8Expose unified product passport / history
14

Data Integrity, Security & Operational Invariants

AreaInvariant / ControlPurpose
AuthenticationJWT requires sub, role, tenant_idEnsures authenticated requests carry identity and tenancy context.
RBACRoute dependencies enforce allowed rolesPrevents unauthorized operations.
Tenant IsolationMongoDB filters derived from JWT tenant contextPrevents cross-tenant data exposure.
Entity ProvisioningOnly one CENTRAL_WAREHOUSEProtects organizational topology.
ProductsSKU uniquenessPrevents ambiguous catalog identity.
ProductsInventory-history deletion barrierPrevents orphaned inventory history.
Pricingselling_price >= cost_priceProtects product master-data integrity.
InventorySource ≠ destinationPreserves meaningful double-entry movements.
Inventorystock_moves immutableMaintains historical truth.
Inventoryinventory_quants derived from movementsEnables fast operational reads while preserving history.
Cycle CountSnapshot/recheck before adjustmentPrevents concurrent count corruption.
OutboxProcessed-event hash trackingPrevents duplicate event effects.
ProcurementServer-side PO pricingPrevents client-side price manipulation.
Serial AssetsSerialized movement historySupports traceability, warranty, and compliance.
EV Digital TwinCached current component serialsKeeps physical and digital assembly state synchronized.
15

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.
16

Cross-Module Dependency Map

FromDepends On / Integrates WithKey Relationship
AuthenticationEntities, all business modulesProvides identity, role, and tenant context.
EntitiesAuthentication, ProductsCreates tenants and linked accounts.
ProductsInventory, Procurement, Sales, Fitment, AnalyticsProvides SKU, price, warranty, and compatibility master data.
VendorsProcurement, QC, AnalyticsSupplier lifecycle, scoring, and purchasing eligibility.
ProcurementProducts, Inventory, Vendors, QCTurns supplier transactions into controlled stock.
SalesProducts, Inventory, Outbox, EV AssetsTurns customer orders into reservations, delivery, warranty, and invoices.
ReturnsInventory, Products, AuditReverses customer stock flows and manages warranty/scrap.
ServiceInventory, Products, EV Assets, WarrantyConsumes parts and updates vehicle component state.
InventoryProducts, Procurement, Sales, Service, ReturnsAuthoritative physical stock movement domain.
AnalyticsInventory, Sales, Procurement, QC, AuditRead / BI layer over operational data.
EV AssetsInventory, Service, Fitment, Batteries, VendorsDigital genealogy and component lifecycle.
FitmentProducts, EV AssetsCompatibility rules for vehicle/component relationships.
BatteriesEV Assets, InventoryBattery-specific lifecycle and vehicle synchronization.

16.1 Core Data Collections Referenced

CollectionPrimary Role
usersUser identity, authentication state, roles, tenant association.
entitiesBusiness entities / tenants and organizational records.
product_catalogsProducts, variants, prices, warranty and master data.
vendorsSupplier master and reliability information.
stock_movesImmutable inventory movement ledger.
inventory_quantsCurrent inventory projection.
event_outboxPending transactional events.
processed_eventsIdempotency history for processed events.
audit_logsHistorical audit events.
fitment_registryVehicle/product compatibility mappings.
ev_assetsSerialized EV components / digital-twin state.
sales_ordersCustomer sales transactions.
purchase_ordersSupplier procurement transactions.
RMA / warranty recordsReverse logistics and warranty lifecycle information.
17

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.
A

Appendix A — Module Inventory

#ModulePrimary Responsibility
1Application Core & ConfigurationBootstrap, settings, DB, indexes, quant backfill
2Core Utilities & IntelligenceLogging, audit, outbox, PDFs, AI interfaces
3Authentication & AuthorizationIdentity, JWT, RBAC, tenant isolation
4Entities & ProductsTenants, staff, catalog, categories, fitment cleanup
5Vendors, Procurement & ServiceSuppliers, POs, GRNs, invoice matching, service
6Sales, Returns & MediaOrders, delivery, RMA, scrap, S3 media
7Inventory — Base & CoreLedger, quants, locations, warehouse, cycle count
8Inventory — FulfillmentReservation, picking, packing, transfers, QC, traceability
9AnalyticsKPIs, valuation, dashboards, audit analytics
10EV Assets, Fitment & BatteriesDigital twin, compatibility, battery lifecycle
B

Appendix B — Key Status / State Transitions

DomainRepresentative Transition
OutboxPENDING PROCESSED / DUPLICATE_SKIPPED
Inventory MoveDRAFT / RESERVED DONE; CANCELLED where applicable
PackageOPEN DISPATCHED
TransferPENDING_APPROVAL RESERVED
EntityACTIVE SUSPENDED (with user deactivation cascade)
VendorACTIVE SUSPENDED based on reliability threshold
RMAActive lifecycle SCRAPPED when failed part is written off
QCItem QC_PASS or QC_FAIL
C

Appendix C — Final Architectural Picture

GBG-X ERP / WMS
API / Security
RBAC · Tenant
Core Services
Audit · Logs · Outbox · Events
Master DataProcurementSalesInventoryServiceEV
MongoDB State
stock_moves
historical truth
inventory_quants
current projection
Analytics / BI Traceability / Warranty AWS S3 — Media Assets