Executive Overview
GBGX-ERP is a role-aware enterprise frontend for an EV ecosystem combining ERP, warehouse management, procurement, sales, service, finance, asset genealogy, and reverse logistics. The frontend is structured around the Next.js App Router and uses a Backend-for-Frontend (BFF) layer to keep authentication tokens away from browser-accessible storage and to centralize request security.
The seven documented modules form a connected system rather than seven isolated feature groups. Core application and authentication infrastructure supports the API/client layer; the BFF mediates all backend requests; inventory provides the operational stock foundation; procurement feeds inbound inventory; sales consumes stock and creates financial documents; service and EV asset management extend the lifecycle after sale; and fitment connects products with vehicle compatibility.
| Layer | Primary Responsibility | Key Technologies / Patterns |
|---|---|---|
| Application shell | Global layout, providers, styling, role-based shells | Next.js App Router, Tailwind CSS v4, React providers |
| Identity | Login, session state, logout, password reset | HttpOnly JWT cookie, AuthContext, BFF |
| Data access | API requests, caching, mutations, invalidation | Axios, TanStack Query, TypeScript interfaces |
| Security gateway | Authentication injection, routing, CSRF checks, rate limiting | Next.js Route Handler / BFF |
| Operations | Inventory, warehouse, transfers, putaway, picking, packing | Inventory module + shared query hooks |
| Supply chain | Vendors, RFQs, POs, GRNs, products | Procurement / Vendor / Product modules |
| Commercial | Sales, delivery, invoices, payments, credit notes | Sales + Finance |
| After-sales | Service tickets, warranties, part swaps | Service module |
| EV lifecycle | VIN, batteries, digital twin, genealogy | Assets / Batteries |
| Compatibility | Vehicle-to-product compatibility | Fitment registry + cascading search |
Frontend Architecture
2.1 High-Level Request Architecture
The browser does not directly own the backend JWT. The Next.js BFF reads the HttpOnly session cookie, converts the authenticated browser session into a backend Bearer token, adds the server-to-server secret, and forwards the request to the appropriate backend service.
2.2 Architectural Principles
- Centralized backend access through the BFF rather than direct browser-to-backend calls.
- HttpOnly cookie-based session storage to keep the JWT inaccessible to browser JavaScript.
- Role-aware rendering and routing at layout/page level.
- TanStack Query for server-state caching, background refetching, mutation handling, and invalidation.
- Reusable UI primitives for navigation, filters, row actions, notifications, and data-heavy screens.
- Frontend validation for common business and format constraints, while relying on backend transactions for authoritative state changes.
- Client-side calculations for immediate feedback, with backend transactions remaining authoritative for persistent business state.
Global Application Foundation
- The root layout establishes the HTML structure and loads optimized typography using Next.js font handling.
- Inter is used for body text and Montserrat for headings.
- The provider layer wraps the application with AuthProvider for user/session state, QueryProvider for TanStack Query, and Sonner's Toaster for global notifications.
- Tailwind CSS v4 with a custom @theme configuration.
- Brutalist visual language with sharp edges and zero-radius surfaces.
- Monochromatic surface palette.
- Electric Lime accent for call-to-action elements.
- Reusable .btn-primary and .card-brutalist component classes.
The design system is intentionally consistent across the ERP, while module-specific pages compose the shared primitives rather than creating independent visual systems.
Authentication, Authorization & Session Security
4.1 Authentication Flow
- 1User submits credentials through the login page.
- 2Credentials are sent through the BFF rather than directly to the backend.
- 3The BFF intercepts a successful login response, extracts the access token, and stores it in an HttpOnly session cookie.
- 4The browser receives a sanitized response without the raw access token.
- 5AuthContext calls the session endpoint to hydrate UI-visible identity state.
- 6The frontend securely obtains the user's email through /auth/me rather than trusting email claims solely from the JWT payload.
4.2 Session Cookie
4.3 Role-Based Routing
| Persona / Role | Frontend Behavior |
|---|---|
| Unauthenticated user | Redirected to /login when attempting protected areas. |
| CUSTOMER | Directed toward /customer-portal rather than the main ERP dashboard. |
| VENDOR | Directed toward /vendor-portal. |
| WAREHOUSE_MANAGER | Receives warehouse-oriented dashboard and operational tools. |
| DEALER | Receives sales/inventory-oriented capabilities appropriate to the role. |
| COMPANY_ADMIN | Receives broad administrative, finance, entity, vendor, and analytics capabilities. |
4.4 Password Recovery
Forgot-password and reset-password pages support a time-limited JWT-based reset flow. Administrative tooling can also generate a time-limited one-hour reset link for users who have lost access.
API Client & Shared Data Layer
- Base URL: /api/v1 — requests are routed to the Next.js BFF.
- X-Requested-With: XMLHttpRequest is added to requests for CSRF protection.
- Axios errors are translated into user-facing Sonner notifications.
- 422 responses are parsed to expose field-specific validation messages.
- 401 responses trigger a user notification and redirect toward login.
- API hooks under lib/api wrap backend interactions in reusable query and mutation abstractions.
- useQuery handles standard server-state retrieval.
- useInfiniteQuery supports paginated/infinite data sets such as inventory and sales tables.
- useMutation handles state-changing operations.
- Successful mutations invalidate related query keys so the UI rehydrates from current backend state.
The frontend exposes TypeScript interfaces for important domain objects such as ProductCatalog, StockMove, and SalesOrder. These types create a shared contract for components and API hooks.
Shared UI Components & Utilities
| Component / Utility | Responsibility |
|---|---|
| Sidebar.tsx | Role-aware navigation, navigation search, desktop collapse, mobile drawer. |
| FilterBar.tsx | Standardized search and date-range filtering for data-heavy screens. |
| ActionMenu.tsx | Row-level Edit, status toggle, and Delete actions with outside-click dismissal. |
| formatCurrency | Indian locale currency formatting using Intl.NumberFormat and INR conventions. |
| Sonner Toaster | Global user notifications. |
| AuthProvider | Client-visible authentication/session state. |
| QueryProvider | TanStack Query client and server-state lifecycle. |
BFF Gateway Architecture
The BFF is the security and routing boundary between browser code and backend services.
- 1Receive the browser request at /api/v1/[...path].
- 2Determine the target microservice from the first URL path segment.
- 3Remove browser-supplied Authorization and Cookie headers to prevent client-side spoofing.
- 4Read the JWT from the trusted HttpOnly session cookie.
- 5Inject the backend Bearer token.
- 6Inject X-GBGX-S2S so the backend can verify the request originated from the trusted BFF.
- 7For state-changing requests, require X-Requested-With: XMLHttpRequest.
- 8Apply the in-memory IP rate limiter of 100 requests per minute.
- 9Forward the request to the selected backend service.
POST /auth/login is handled specially. On successful authentication, the BFF extracts access_token from the backend response, stores it in the HttpOnly cookie, and returns a sanitized response to the browser without exposing the token.
The architecture separates browser identity from backend service authentication. The browser proves its session through the cookie; the BFF converts that session into the backend authentication context and adds the server-to-server trust signal.
Main Dashboard & Administrative Capabilities
The main dashboard uses /analytics/dashboard-summary to retrieve dashboard data through a consolidated endpoint rather than issuing many independent KPI calls.
| Role | Dashboard Focus |
|---|---|
| WAREHOUSE_MANAGER | Pending Picks, Pending Putaways, Total Movements, and assignment tasks. |
| DEALER | 7-Day Revenue, Open Orders, and daily earnings visualization. |
| COMPANY_ADMIN | Sales KPIs and administrative/business overview. |
- The seven-day earnings visualization uses a dependency-free CSS calculation based on square-root normalization of revenue to produce more readable bar heights.
- Customers and Employees support strict frontend input patterns, including 10-digit phone validation.
- Successful provisioning can expose an auto-generated portal password in a persistent toast so the administrator can securely transfer it to the user.
- Entities use a multi-step drawer and derive roles from Entity Type.
- The Central Warehouse option is disabled when a Central Warehouse already exists.
- System Logs exposes stock_moves and event_outbox status for operational diagnostics.
- Finance supports invoice listing, invoice-number override, and Credit Note issuance.
- Admin tools support generation of time-limited password reset links.
- Analytics and settings provide supporting administrative capabilities.
Inventory & Warehouse Management
| Area | Frontend Capability |
|---|---|
| Live Stock | Infinite-query inventory quants, client aggregation, bin/serial/manufacturing detail. |
| Ledger | Historical immutable stock_moves with server-side filters. |
| Aging | Warehouse age analysis and dead-stock visual highlighting. |
| CSV Export | Client-generated CSV from aggregated inventory data. |
- The warehouse wizard takes Zones, Aisles, Racks, and Bins as inputs, generates a nested layout model, renders a visual preview, then flattens the model into location records for a bulk POST to /inventory/locations/bulk.
- It also persists the layout configuration for future editing.
- Example hierarchy_path: WH01-Z01-A01-R01-B01
- Reserved stock moves are exposed as pending pick tasks.
- Warehouse managers assign tasks to WAREHOUSE_STAFF.
- Picked items in DONE / TRANSIT state become packing candidates.
- Packing associates a box number with the picked items.
- Transfers expose Pending → In Transit → Received progression.
- Destination routing is bound to the logged-in tenant_id.
- Putaway scans the TRANSIT zone and suggests empty storage bins.
- Dealer workflows can bypass bin selection and route items directly to STOCKYARD.
- Damaged Goods aggregates damaged-zone inventory with pending approvals and active transfers to derive the operational status of each item. The UI then exposes contextual actions such as RTV, Dispose, or Pick & Pack.
- Warranty Approvals allow Central WH users to approve/reject RTV and RMA requests.
- Scrap Register provides an audit-oriented record of scrapped or vendor-returned items.
- Local Locator is restricted to the current facility/tenant.
- Global Locator searches the complete branch network and resolves tenant identifiers into readable entity names.
Procurement, Vendors & Product Master
- Central WH manager creates an RFQ.
- Approved vendors are explicitly invited.
- Vendor quotes are compared by price, lead time, and quote source.
- A selected quote is approved; backend logic generates the Purchase Order.
PO status: Issued → Accepted → In Transit → Received
| Serialization Type | GRN UI |
|---|---|
| Serialized | Individual serial number and manufacturing-date inputs. |
| Batch | Quantity and manufacturing date, with multiple batch rows. |
| Quantity | Single received-quantity input. |
- CSV bulk import accelerates serialized/batch receiving by parsing serial numbers and manufacturing dates client-side and mapping them to the appropriate variant SKUs.
Low-stock detection cross-references inventory quants against tenant-scoped threshold rules. Administrators can move toward RFQ creation, while dealers can request stock.
- GSTIN validation requires a 15-character alphanumeric format.
- Phone validation requires 10 digits.
- Approve/Suspend status changes are exposed through ActionMenu and affect future RFQ eligibility.
- Parent SKUs are generated from brand/product information.
- Variant SKUs append attributes such as color and voltage.
- Parent and variant images are uploaded through /media/upload to S3-backed media storage.
- Fitments can be queued before the product is persisted and submitted after product creation.
- Product detail pages render variant SKU barcodes using react-barcode.
Sales, Service & Finance
- 1Search customer by phone.
- 2Resolve multiple matches through a selection dropdown.
- 3Filter product variants to items with available stock in the current warehouse.
- 4For serialized products, require a specific available serial.
- 5Calculate base amount, SKU-specific GST, discounts, and final total in real time.
- 6Submit the resulting sales order payload to the backend.
Order progression: Awaiting Payment → Ready to Pack → Ready to Deliver → Fulfilled
- Pack triggers a backend transaction and Delivery Challan PDF generation.
- Deliver triggers backend generation of invoices and warranties.
- Payment modal supports partial/full payments and balance calculation.
- Service intake follows a three-step wizard: customer identification, owned EV asset retrieval, and complaint capture.
- The execution workbench checks warranties for the relevant VIN or part serial. When an ACTIVE warranty is applicable, the UI can apply warranty billing logic and zero labor/parts base amounts.
- Serialized parts require serial selection.
- Parts GST is calculated dynamically; Labor GST is calculated at 18% in the documented UI logic.
- After closure and invoice generation, the UI transitions to payment collection.
- Administrators/finance managers can review auto-generated invoices.
- invoice_number can be manually overridden to synchronize ERP numbering with physical GST books.
- Credit Notes link refunds to the originating sales order and represent a negative financial amount.
EV Assets, Batteries & Fitment
- The Asset Lifecycle Portal accepts any supported serial identifier — Battery, Motor, or VIN — and returns movement history, current ownership, and warranty context.
- Action availability is derived from possession and state. Scrap, RTV, and Warranty Claim controls are only exposed when the asset's current location/state makes the action appropriate.
- Vehicle detail shows cached battery/motor relationships.
- AMC status is displayed.
- Install/uninstall genealogy is rendered chronologically.
- Component swaps invoke backend transactional logic that updates vehicle caches, warranty state, and RMA information.
Statuses: Active Expired Claimed Voided
- Warranty status is derived from backend flags and date logic.
- Voiding requires a reason.
- Technicians can update State of Health percentage and cycle count.
- Battery transfers coordinate current_vehicle_vin, the old vehicle's current_battery_serial, and the new vehicle's current_battery_serial.
- Scrap/Dispose routes the battery through the unified scrap endpoint and voids warranty state.
- The compatibility engine uses cascading selections to prevent invalid combinations.
- Compatible products are rendered as visual cards with badges such as OEM Standard and Guaranteed Fit.
Cross-Module Business Flows
13.1 Inbound Supply Chain
13.2 Warehouse Fulfillment
13.3 Order to Cash
13.4 After-Sales Service
13.5 EV Component Genealogy
13.6 Reverse Logistics
13.7 Product Compatibility
Security Architecture
| Control | Frontend / BFF Behavior | Purpose |
|---|---|---|
| HttpOnly JWT cookie | Session token stored server-side from browser JavaScript perspective. | Reduce XSS token exposure. |
| Authorization stripping | BFF ignores browser-supplied Authorization header. | Prevent client-side token spoofing. |
| Cookie stripping | BFF controls which authentication cookie reaches backend. | Prevent arbitrary browser cookie forwarding. |
| S2S header | BFF injects X-GBGX-S2S. | Backend trust boundary. |
| CSRF header | State-changing requests require X-Requested-With. | Reject nonconforming browser mutations. |
| Rate limiting | 100 requests/minute in-memory IP limiter. | Basic abuse protection. |
| Role-aware UI | Navigation and screens vary by role. | Reduce unauthorized UI exposure. |
| Tenant-aware routing | Transfers and local searches bind to tenant context. | Reduce cross-tenant misuse. |
Data & State Management
TanStack Query is the primary server-state abstraction. Queries represent read models; mutations represent state changes; invalidation reconciles cached UI state with backend state after successful operations.
- Form state for complex drawers/modals.
- Queued fitments before product creation.
- Dynamic complaint rows in service tickets.
- Warehouse layout generation before persistence.
- Client-side aggregation and filtering where documented.
- Derived UI state such as warranty, damaged-goods, and PO step states.
Client-side calculations and derived states are for UX and presentation. Backend transactions remain authoritative for stock movement, delivery, invoice generation, warranty changes, component swaps, and other persistent domain transitions.
Validation & Error Handling
- 10-digit phone validation.
- 15-character GSTIN validation.
- Required serial selection for serialized inventory/products.
- Warehouse/tenant-aware stock selection.
- Entity-type-driven role assignment.
- Central Warehouse uniqueness behavior.
- Cascading fitment selections.
Axios interceptors provide a common error UX. Validation responses are parsed into field-specific messages, while authentication failures trigger a login redirect. This prevents each page from reinventing error handling.
Operations such as pack, deliver, component swaps, and inventory changes are documented as backend ACID/transactional actions. The frontend initiates these operations and then refreshes affected query state.
Responsive UI & Interaction Patterns
- Sidebars collapse to icon-only mode on desktop.
- Portal sidebars use slide-in drawers on mobile.
- Data-heavy pages use FilterBar and infinite scrolling where appropriate.
- Slide-over drawers and modals support complex multi-step workflows without leaving context.
- Visual steppers communicate operational lifecycle state.
- Contextual action buttons reduce invalid operations by exposing actions only when state permits them.
- Toasts communicate success, validation, authentication, and provisioning events.
Testing & Operational Considerations
| Area | Recommended Test Focus |
|---|---|
| Authentication | Login, session hydration, logout, protected-route redirects, role routing, reset flow. |
| BFF | Service routing, cookie handling, header stripping, S2S injection, CSRF rejection, rate limiting. |
| Inventory | Pagination, aggregation, serial visibility, transfer tenant binding, pick/pack/putaway state transitions. |
| Procurement | RFQ comparison, quote approval, GRN serialization modes, CSV import. |
| Products | SKU generation, image upload state, fitment queueing, barcode rendering. |
| Sales | Stock filtering, serial enforcement, GST calculations, fulfillment transitions, payment balance. |
| Service | Warranty detection, billing override, parts serial selection, closure/payment flow. |
| Assets | VIN/serial lookup, possession-based actions, component swaps, battery transfers. |
| Fitment | Cascading selections and compatible-product results. |
Technical Design Observations
The following observations are derived from the supplied module documentation and are intended to help maintainers understand design characteristics.
19.1 Strong Architectural Characteristics
- The BFF creates a clear browser-to-backend security boundary.
- TanStack Query centralizes server-state synchronization.
- Role-aware layouts and navigation make the application persona-driven.
- Complex workflows are represented as focused UI workbenches instead of fragmented screens.
- The frontend contains meaningful domain-aware validation and derived state.
- Inventory, asset genealogy, procurement, sales, service, and finance are connected through recognizable business flows.
19.2 Areas Requiring Care During Maintenance
- Client-side business calculations must stay aligned with backend rules; backend results remain authoritative.
- Hardcoded role/navigation mappings require coordinated updates when roles change.
- The in-memory BFF rate limiter is process-local; deployments with multiple instances require consideration of distributed rate limiting.
- Client-derived states that aggregate multiple API sources can become stale unless query invalidation/refetch behavior is maintained carefully.
- The BFF's microservice URL mapping depends on correctly configured environment variables.
- CSV parsing and client-side export/import should be tested against malformed and large inputs.
- Direct S3 media upload workflows require consistent loading, failure, and retry handling.
- Tenant scoping must remain enforced in both frontend requests and backend authorization.
Developer Maintenance Guidelines
- Route new backend access through the centralized API client and BFF instead of creating direct browser-to-backend calls.
- Reuse TanStack Query hooks and invalidate affected query keys after successful mutations.
- Use shared Sidebar, FilterBar, ActionMenu, formatting, and notification primitives where applicable.
- Treat frontend validation as UX protection and backend validation/transactions as authoritative.
- When introducing a new role, update authentication routing, navigation filtering, layouts, and page-level role behavior together.
- When introducing a new microservice route, update the BFF service mapping and verify environment configuration.
- When changing inventory states, review every dependent workflow: picking, packing, transfers, putaway, damaged goods, sales, service, and locators.
- When changing product serialization behavior, review GRN, sales serial selection, inventory views, service parts, and fitment-related workflows.
- When changing asset relationships, review VIN genealogy, battery transfer, warranty, service, and reverse logistics.
- Maintain consistent query keys and invalidation rules to avoid stale operational screens.
- Keep sensitive credentials and tokens out of browser-accessible storage and UI logs.
Module Reference Matrix
| Module | Primary Areas | Key Files / Routes | Core Responsibility |
|---|---|---|---|
| 1. Core App, Auth & Layouts | App shell, auth, portals | app/layout.tsx, app/providers.tsx, app/globals.css, lib/auth.ts, AuthContext.tsx, app/api/auth/* | Foundation, identity, role routing |
| 2. API Clients & Shared Components | API, hooks, shared UI | lib/api/client.ts, lib/api/*.ts, lib/utils/format.ts, components/* | Data access and reusable UI |
| 3. Dashboard, Admin & BFF | Dashboard, entities, customers, employees, admin, finance, BFF | app/(dashboard)/page.tsx, app/api/v1/[...path]/route.ts | Command center and secure gateway |
| 4. Inventory | Stock, ledger, warehouse, outbound, transfers, putaway, damaged, locators | inventory/* | Warehouse operations and inventory lifecycle |
| 5. Procurement, Vendors & Products | RFQ, PO, GRN, vendors, products, fitment | procurement/*, vendors/*, products/* | Inbound supply chain and item master |
| 6. Sales, Service & Finance | Sales, fulfillment, service, invoices, credit notes | sales/*, service/*, finance/* | Order-to-cash and after-sales |
| 7. EV Assets, Batteries & Fitment | Digital twin, battery lifecycle, warranties, fitment | assets/*, batteries/*, fitment/* | EV genealogy and compatibility |
Appendix A — End-to-End Architectural Summary
GBGX's frontend can be understood as a layered operational platform:
Appendix B — Documentation Boundary
This document is a consolidated frontend code-architecture document derived from the seven supplied frontend module documents. It intentionally does not invent exact file names, APIs, environment variables, database schemas, component props, or test implementations that were not included in those source documents. Where a recommended maintenance or testing practice is stated, it is explicitly framed as guidance rather than an assertion that the current code already implements it.