X

GBGX-ERP

Frontend Code Documentation

Next.js App Router React + TypeScript BFF Security Gateway 7 Modules

GBGX-ERP
FRONTEND

Structured technical documentation for the Next.js App Router frontend — covering architecture, authentication, BFF security, shared infrastructure, operational modules, and end-to-end business workflows.

Version

Consolidated Frontend Documentation

Platform

GBGX-ERP / WMS / EV Ecosystem

Frontend Architecture

Next.js App Router + React + TypeScript

Documentation Scope

Frontend Documentation Modules 1–7, consolidated into a single developer-oriented reference

Key Patterns

HttpOnly JWT Cookie BFF Gateway TanStack Query Role-Aware UI

Document Scope

This document consolidates Frontend Documentation Modules 1–7 into a single developer-oriented reference. It describes the frontend behavior and architecture based on the supplied module documentation.

Boundary: it does not claim implementation details that were not provided.
Contents
01

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.

LayerPrimary ResponsibilityKey Technologies / Patterns
Application shellGlobal layout, providers, styling, role-based shellsNext.js App Router, Tailwind CSS v4, React providers
IdentityLogin, session state, logout, password resetHttpOnly JWT cookie, AuthContext, BFF
Data accessAPI requests, caching, mutations, invalidationAxios, TanStack Query, TypeScript interfaces
Security gatewayAuthentication injection, routing, CSRF checks, rate limitingNext.js Route Handler / BFF
OperationsInventory, warehouse, transfers, putaway, picking, packingInventory module + shared query hooks
Supply chainVendors, RFQs, POs, GRNs, productsProcurement / Vendor / Product modules
CommercialSales, delivery, invoices, payments, credit notesSales + Finance
After-salesService tickets, warranties, part swapsService module
EV lifecycleVIN, batteries, digital twin, genealogyAssets / Batteries
CompatibilityVehicle-to-product compatibilityFitment registry + cascading search
02

Frontend Architecture

2.1 High-Level Request Architecture

React UI TanStack Query / API hooks Axios client /api/v1 BFF Backend microservice Database / transactional domain logic

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

Global Application Foundation

3.1 Root Layout & Providers
  • 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.
3.2 Design System
  • 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.
3.3 Global Styling & Interaction

The design system is intentionally consistent across the ERP, while module-specific pages compose the shared primitives rather than creating independent visual systems.

04

Authentication, Authorization & Session Security

4.1 Authentication Flow

  1. 1User submits credentials through the login page.
  2. 2Credentials are sent through the BFF rather than directly to the backend.
  3. 3The BFF intercepts a successful login response, extracts the access token, and stores it in an HttpOnly session cookie.
  4. 4The browser receives a sanitized response without the raw access token.
  5. 5AuthContext calls the session endpoint to hydrate UI-visible identity state.
  6. 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

The documented session cookie is __Host-gbgx_session. The token is intended to remain inaccessible to browser JavaScript, reducing exposure to token theft through XSS.

4.3 Role-Based Routing

Persona / RoleFrontend Behavior
Unauthenticated userRedirected to /login when attempting protected areas.
CUSTOMERDirected toward /customer-portal rather than the main ERP dashboard.
VENDORDirected toward /vendor-portal.
WAREHOUSE_MANAGERReceives warehouse-oriented dashboard and operational tools.
DEALERReceives sales/inventory-oriented capabilities appropriate to the role.
COMPANY_ADMINReceives 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.

05

API Client & Shared Data Layer

5.1 Axios Client — lib/api/client.ts
  • 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.
5.2 TanStack Query
  • 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.
5.3 Typed Domain Interfaces

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.

06

Shared UI Components & Utilities

Component / UtilityResponsibility
Sidebar.tsxRole-aware navigation, navigation search, desktop collapse, mobile drawer.
FilterBar.tsxStandardized search and date-range filtering for data-heavy screens.
ActionMenu.tsxRow-level Edit, status toggle, and Delete actions with outside-click dismissal.
formatCurrencyIndian locale currency formatting using Intl.NumberFormat and INR conventions.
Sonner ToasterGlobal user notifications.
AuthProviderClient-visible authentication/session state.
QueryProviderTanStack Query client and server-state lifecycle.
The shared layer is important for consistency: feature modules should reuse these primitives instead of duplicating navigation, filtering, action menus, authentication state, and notification behavior.
07

BFF Gateway Architecture

7.1 Gateway Route — app/api/v1/[...path]/route.ts

The BFF is the security and routing boundary between browser code and backend services.

7.2 Request Processing
  1. 1Receive the browser request at /api/v1/[...path].
  2. 2Determine the target microservice from the first URL path segment.
  3. 3Remove browser-supplied Authorization and Cookie headers to prevent client-side spoofing.
  4. 4Read the JWT from the trusted HttpOnly session cookie.
  5. 5Inject the backend Bearer token.
  6. 6Inject X-GBGX-S2S so the backend can verify the request originated from the trusted BFF.
  7. 7For state-changing requests, require X-Requested-With: XMLHttpRequest.
  8. 8Apply the in-memory IP rate limiter of 100 requests per minute.
  9. 9Forward the request to the selected backend service.
7.3 Login Special Case

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.

7.4 Security Boundary

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.

08

Main Dashboard & Administrative Capabilities

8.1 Dynamic Command Center

The main dashboard uses /analytics/dashboard-summary to retrieve dashboard data through a consolidated endpoint rather than issuing many independent KPI calls.

RoleDashboard Focus
WAREHOUSE_MANAGERPending Picks, Pending Putaways, Total Movements, and assignment tasks.
DEALER7-Day Revenue, Open Orders, and daily earnings visualization.
COMPANY_ADMINSales 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.
8.2 Master Data
  • 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.
8.3 System / Finance / Admin Tools
  • 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.
09

Inventory & Warehouse Management

9.1 Inventory Overview
AreaFrontend Capability
Live StockInfinite-query inventory quants, client aggregation, bin/serial/manufacturing detail.
LedgerHistorical immutable stock_moves with server-side filters.
AgingWarehouse age analysis and dead-stock visual highlighting.
CSV ExportClient-generated CSV from aggregated inventory data.
9.2 Warehouse Setup
  • 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
9.3 Outbound Operations
  • 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.
9.4 Transfers & Putaway
  • 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.
9.5 Reverse Logistics
  • 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.
9.6 Locators
  • Local Locator is restricted to the current facility/tenant.
  • Global Locator searches the complete branch network and resolves tenant identifiers into readable entity names.
10

Procurement, Vendors & Product Master

10.1 RFQ & Purchase Orders
  • 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

10.2 Goods Receipt
Serialization TypeGRN UI
SerializedIndividual serial number and manufacturing-date inputs.
BatchQuantity and manufacturing date, with multiple batch rows.
QuantitySingle 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.
10.3 Low Stock

Low-stock detection cross-references inventory quants against tenant-scoped threshold rules. Administrators can move toward RFQ creation, while dealers can request stock.

10.4 Vendor Management
  • 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.
10.5 Product Catalog
  • 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.
11

Sales, Service & Finance

11.1 Sales Order Creation
  1. 1Search customer by phone.
  2. 2Resolve multiple matches through a selection dropdown.
  3. 3Filter product variants to items with available stock in the current warehouse.
  4. 4For serialized products, require a specific available serial.
  5. 5Calculate base amount, SKU-specific GST, discounts, and final total in real time.
  6. 6Submit the resulting sales order payload to the backend.
11.2 Fulfillment

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.
11.3 Service Center
  • 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.
11.4 Finance
  • 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.
12

EV Assets, Batteries & Fitment

12.1 Digital Twin
  • 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.
12.2 Vehicle Workbench
  • 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.
12.3 Warranty Management

Statuses: Active Expired Claimed Voided

  • Warranty status is derived from backend flags and date logic.
  • Voiding requires a reason.
12.4 Battery Intelligence
  • 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.
12.5 Fitment Finder
Make Model Year Variant
  • 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.
13

Cross-Module Business Flows

13.1 Inbound Supply Chain

Vendor RFQ Quote Comparison PO In Transit GRN Inventory Putaway

13.2 Warehouse Fulfillment

Inventory Reservation Pick Assignment Picked/Transit Pack Delivery

13.3 Order to Cash

Customer Sales Order Stock/Serial Validation Payment Pack Deliver Invoice/Warranty Balance Collection

13.4 After-Sales Service

Customer EV Asset Service Ticket Warranty Check Parts/Labor Close Invoice Payment

13.5 EV Component Genealogy

Vehicle/VIN Battery/Motor Components Install/Uninstall History Component Swap Warranty/RMA State

13.6 Reverse Logistics

Damaged Asset Approval / Transfer RTV / Warranty / Scrap Final Disposition

13.7 Product Compatibility

Vehicle Make/Model/Year/Variant Fitment Registry Compatible Product Product Detail / Purchase
14

Security Architecture

ControlFrontend / BFF BehaviorPurpose
HttpOnly JWT cookieSession token stored server-side from browser JavaScript perspective.Reduce XSS token exposure.
Authorization strippingBFF ignores browser-supplied Authorization header.Prevent client-side token spoofing.
Cookie strippingBFF controls which authentication cookie reaches backend.Prevent arbitrary browser cookie forwarding.
S2S headerBFF injects X-GBGX-S2S.Backend trust boundary.
CSRF headerState-changing requests require X-Requested-With.Reject nonconforming browser mutations.
Rate limiting100 requests/minute in-memory IP limiter.Basic abuse protection.
Role-aware UINavigation and screens vary by role.Reduce unauthorized UI exposure.
Tenant-aware routingTransfers and local searches bind to tenant context.Reduce cross-tenant misuse.
Frontend restrictions should not be treated as the sole security boundary. The documented design appropriately relies on backend transactional and authorization logic for authoritative enforcement, while the frontend provides early validation and safer UX.
15

Data & State Management

15.1 Server State

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.

15.2 Local UI State
  • 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.
15.3 Authoritative State

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.

16

Validation & Error Handling

16.1 Frontend Validation
  • 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.
16.2 API Errors

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.

16.3 Transactional Actions

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.

17

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

Testing & Operational Considerations

The supplied frontend documentation establishes the behaviors that should be covered by automated tests. Exact existing test files were not provided in the seven modules, so the following should be treated as documentation-aligned test targets rather than a claim about current test coverage.
AreaRecommended Test Focus
AuthenticationLogin, session hydration, logout, protected-route redirects, role routing, reset flow.
BFFService routing, cookie handling, header stripping, S2S injection, CSRF rejection, rate limiting.
InventoryPagination, aggregation, serial visibility, transfer tenant binding, pick/pack/putaway state transitions.
ProcurementRFQ comparison, quote approval, GRN serialization modes, CSV import.
ProductsSKU generation, image upload state, fitment queueing, barcode rendering.
SalesStock filtering, serial enforcement, GST calculations, fulfillment transitions, payment balance.
ServiceWarranty detection, billing override, parts serial selection, closure/payment flow.
AssetsVIN/serial lookup, possession-based actions, component swaps, battery transfers.
FitmentCascading selections and compatible-product results.
19

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

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

Module Reference Matrix

ModulePrimary AreasKey Files / RoutesCore Responsibility
1. Core App, Auth & LayoutsApp shell, auth, portalsapp/layout.tsx, app/providers.tsx, app/globals.css, lib/auth.ts, AuthContext.tsx, app/api/auth/*Foundation, identity, role routing
2. API Clients & Shared ComponentsAPI, hooks, shared UIlib/api/client.ts, lib/api/*.ts, lib/utils/format.ts, components/*Data access and reusable UI
3. Dashboard, Admin & BFFDashboard, entities, customers, employees, admin, finance, BFFapp/(dashboard)/page.tsx, app/api/v1/[...path]/route.tsCommand center and secure gateway
4. InventoryStock, ledger, warehouse, outbound, transfers, putaway, damaged, locatorsinventory/*Warehouse operations and inventory lifecycle
5. Procurement, Vendors & ProductsRFQ, PO, GRN, vendors, products, fitmentprocurement/*, vendors/*, products/*Inbound supply chain and item master
6. Sales, Service & FinanceSales, fulfillment, service, invoices, credit notessales/*, service/*, finance/*Order-to-cash and after-sales
7. EV Assets, Batteries & FitmentDigital twin, battery lifecycle, warranties, fitmentassets/*, batteries/*, fitment/*EV genealogy and compatibility
A

Appendix A — End-to-End Architectural Summary

GBGX's frontend can be understood as a layered operational platform:

Global App Shell
Authentication / Role Routing Shared API Client + TanStack Query Next.js BFF Security Gateway
ERP / WMS Operations
InventoryProcurementVendorsProducts
Commercial
SalesServiceFinance
EV Intelligence
Assets / Digital TwinBatteriesFitment
Key architectural invariant: the browser interacts with the application through the Next.js frontend and BFF boundary, while the backend remains the authoritative source for persistent domain state and transactional operations.
B

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.