← Part 1: BRD (Sections 1–5)  |  Part 2: BRD Sections 6–8 + Architecture + Database + API + Security

6. Non-Functional Requirements

6.1 Performance Requirements

MetricRequirementMeasurement Method
Page Load Time< 2 seconds (P95) on standard broadbandLighthouse / Web Vitals
API Response Time< 500ms for list queries, < 200ms for single recordServer-side timing headers
Dashboard RefreshKPI data refreshed within 30 seconds of underlying changeReal-time monitoring
Concurrent UsersSupport 50 concurrent users without degradationLoad testing (k6/JMeter)
Database Query< 100ms for indexed queries on orders table (up to 10,000 records)Query EXPLAIN ANALYZE
File ExportPDF/Excel export < 5 seconds for up to 500 recordsEnd-to-end timing
Uptime SLA99.5% monthly uptime (max 3.6 hours downtime/month)Uptime monitoring (Uptime Robot)

6.2 Scalability Requirements

DimensionCurrentYear 1 TargetYear 3 Target
Active Orders2475002,000
Customers89200500
Monthly Revenue₹42.8L₹80L₹2Cr
Concurrent Users5–1050200
Data Volume (Orders)~500 records5,00050,000
Countries Served4610

6.3 Security Requirements

6.4 Usability Requirements

6.5 Compliance Requirements

RegulationRequirementImplementation
GST (India)18% GST on all domestic and export invoices; GSTIN on all documentsAuto-calculation in billing module
FEMA / RBIForeign exchange receipts documented for export ordersPayment method + SWIFT reference tracking
DGFT ExportExport documentation: Shipping Bill, Certificate of Origin, Packing ListDocument generation module
HS CodeHS Code 6802.99 (Worked monumental/building stone) on all export documentsPre-filled in dispatch module
GDPR (EU/Ireland)Customer data protection for Irish customers; right to erasureSoft delete + data export feature
Data RetentionFinancial records retained for 7 years (Indian Companies Act)Archive policy in database

7. Business Rules & Validations

7.1 Order Validations

FieldValidation RuleError Message
Order IDAuto-generated; format AG-XXXX; unique; sequentialSystem-generated, no user input
CustomerRequired; must exist in customer master OR be new prospect"Customer name is required"
CountryRequired; must be one of: USA, Canada, Ireland, India"Please select a valid country"
Product TypeRequired; must be from approved product list (9 types)"Please select a product type"
Stone TypeRequired; must be from approved stone list (6 types)"Please select a stone type"
QuantityRequired; integer; minimum 1; maximum 100"Quantity must be between 1 and 100"
Order ValueRequired; numeric; minimum ₹1,000; maximum ₹50,00,000"Order value must be between ₹1,000 and ₹50,00,000"
Due DateRequired; must be at least 7 days from order date"Due date must be at least 7 days from today"
DimensionsOptional; format: W" × H" × D" (inches)"Use format: 36\" × 12\" × 6\""
Contact EmailRequired; valid email format"Please enter a valid email address"
Payment TermsRequired; must be from approved terms list (5 options)"Please select payment terms"

7.2 Financial Business Rules

7.3 Production Business Rules

7.4 Inventory Business Rules

7.5 Status Transition Rules

EntityFrom StatusAllowed Next StatusCondition
OrderPendingIn ProductionAdvance payment confirmed + worker assigned
OrderIn ProductionCutting Stage, Shaping, Polishing, Engraving, Quality CheckStage updated by supervisor
OrderQuality CheckReady (pass) or back to stage (fail)QC supervisor decision
OrderReadyDispatchedInvoice generated + balance payment received (or terms allow)
OrderDispatchedDeliveredCustomer confirmation or tracking shows delivered
QuotePending ApprovalApproved, RejectedCustomer response
QuoteApprovedConverted to OrderAdvance payment received
InvoicePending ApprovalPaid, OverduePayment received OR due date passed
InvoiceOverduePaidLate payment received

8. Assumptions & Constraints

8.1 Explicit Assumptions

IDAssumptionImpact if Wrong
A-001GST rate is fixed at 18% for all product types and customer locationsBilling module requires reconfiguration if rates vary by HSN code
A-002Production workers do not have ERP login access in Phase 1Mobile worker interface needed if workers need direct stage updates
A-003All financial amounts are stored and displayed in Indian Rupees (INR)Multi-currency module required if customers need USD/EUR invoices
A-004Stone inventory unit is square feet (sq.ft) for all stone typesUnit conversion needed if some stones are sold by cubic feet or weight
A-005HS Code 6802.99 applies to all exported granite productsCustoms documentation errors if different products have different HS codes
A-006Reorder level is 200 sq.ft and critical level is 100 sq.ft for all stone typesAlert thresholds need per-stone configuration if consumption rates vary
A-007Quote validity default is 30 days from creation dateConfigurable per customer if different validity periods are negotiated
A-008Waste factor of 15% is applied to stone consumption estimatesInventory discrepancies if actual waste varies significantly by product type
A-009Email notifications are sent via SMTP/transactional email serviceEmail delivery failures if SMTP not configured; SMS fallback may be needed
A-010The system supports 4 countries (USA, Canada, Ireland, India) in Phase 1Country/timezone/currency additions needed for expansion markets
A-011High-value threshold for Admin approval is ₹5,00,000Configurable threshold needed if business policy changes
A-012Production stage history is tracked but not time-stamped at sub-minute granularityDetailed time-motion studies require higher precision timestamps

8.2 Technical Constraints

8.3 Business Constraints


PART II — SYSTEM ARCHITECTURE

9. Application Architecture Overview

9.1 Architecture Pattern: Layered Monolith with API-First Design

Recommended Architecture: Next.js Full-Stack (App Router) with Supabase as Backend-as-a-Service. This leverages the existing Next.js 15 codebase while adding a production-grade PostgreSQL backend with built-in auth, real-time subscriptions, and row-level security.
🖥️ Presentation Layer
  • Next.js 15 App Router
  • React 19 Components
  • Tailwind CSS v3
  • Recharts (data viz)
  • Heroicons (icons)
  • Sonner (toasts)
⚙️ Application Layer
  • Next.js API Routes
  • Server Actions
  • Business Logic Services
  • Validation (Zod)
  • PDF Generation
  • Email Service
🗄️ Data Layer
  • Supabase (PostgreSQL)
  • Row-Level Security
  • Real-time Subscriptions
  • Supabase Auth
  • Supabase Storage (docs)
  • Edge Functions (cron)

9.2 Technology Stack

LayerTechnologyVersionPurpose
Frontend FrameworkNext.js15.xSSR/SSG, App Router, API Routes
UI LibraryReact19.xComponent-based UI
LanguageTypeScript5.xType safety across full stack
StylingTailwind CSS3.xUtility-first CSS
DatabasePostgreSQL (via Supabase)15.xPrimary data store
AuthSupabase AuthLatestJWT-based authentication
ORM / QuerySupabase JS Client2.xType-safe database queries
ValidationZod3.xRuntime schema validation
ChartsRecharts2.xRevenue and order charts
PDF Generation@react-pdf/renderer3.xInvoice and packing list PDFs
EmailResendLatestTransactional email notifications
File StorageSupabase StorageLatestDocument storage (invoices, photos)
Cron JobsSupabase Edge FunctionsLatestDaily overdue checks, reminders
HostingVercelLatestNext.js optimized deployment
CDNVercel Edge Network—Global content delivery
MonitoringVercel Analytics + SentryLatestPerformance + error tracking

9.3 Data Flow Architecture

Browser (Next.js Client Components)
    │
    ├─ Server Components (SSR) ──→ Supabase DB (direct server query)
    │
    ├─ Client Components ──→ Next.js API Routes (/api/*)
    │                              │
    │                              ├─ Zod Validation
    │                              ├─ Auth Middleware (JWT verify)
    │                              ├─ RBAC Check
    │                              └─ Supabase Client Query
    │
    ├─ Real-time Updates ──→ Supabase Realtime Subscriptions
    │                         (WebSocket — order status changes, notifications)
    │
    └─ File Downloads ──→ Supabase Storage (signed URLs)

Supabase Edge Functions (Cron):
    ├─ Daily 00:00 IST: Check overdue invoices → Update status → Send alerts
    ├─ Daily 08:00 IST: Check low stock → Send notifications
    └─ Daily 09:00 IST: Send payment reminders (3 days before due)

10. Module Architecture & Component Map

10.1 File Structure (Recommended)

src/
├── app/
│   ├── (auth)/
│   │   ├── login/page.tsx
│   │   └── register/page.tsx
│   ├── (dashboard)/
│   │   ├── page.tsx                    ← Dashboard
│   │   ├── order-management/page.tsx
│   │   ├── production-tracking/page.tsx
│   │   ├── inventory-stone/page.tsx
│   │   ├── customer-management/page.tsx
│   │   ├── quotation-billing/page.tsx
│   │   ├── dispatch-logistics/page.tsx
│   │   ├── reports/page.tsx
│   │   └── settings/page.tsx           ← Admin only
│   └── api/
│       ├── orders/route.ts             ← GET, POST
│       ├── orders/[id]/route.ts        ← GET, PUT, DELETE
│       ├── quotations/route.ts
│       ├── quotations/[id]/route.ts
│       ├── invoices/route.ts
│       ├── invoices/[id]/route.ts
│       ├── production/[orderId]/route.ts
│       ├── inventory/route.ts
│       ├── customers/route.ts
│       ├── customers/[id]/route.ts
│       ├── dispatch/route.ts
│       ├── reports/route.ts
│       └── notifications/route.ts
├── components/
│   ├── AppLayout.tsx
│   ├── Sidebar.tsx
│   ├── Topbar.tsx
│   └── ui/
│       ├── StatusBadge.tsx
│       ├── MetricCard.tsx
│       ├── Modal.tsx
│       ├── EmptyState.tsx
│       ├── AppIcon.tsx
│       ├── AppLogo.tsx
│       ├── DataTable.tsx               ← Generic sortable/paginated table
│       ├── ConfirmDialog.tsx
│       └── LoadingSpinner.tsx
├── lib/
│   ├── supabase/
│   │   ├── client.ts                   ← Browser client
│   │   ├── server.ts                   ← Server client (cookies)
│   │   └── middleware.ts               ← Auth middleware
│   ├── validations/
│   │   ├── order.schema.ts             ← Zod schemas
│   │   ├── quotation.schema.ts
│   │   └── invoice.schema.ts
│   ├── services/
│   │   ├── orderService.ts
│   │   ├── productionService.ts
│   │   ├── inventoryService.ts
│   │   ├── billingService.ts
│   │   └── notificationService.ts
│   ├── pdf/
│   │   ├── invoicePdf.tsx
│   │   └── packingListPdf.tsx
│   └── email/
│       └── emailTemplates.ts
└── types/
    ├── order.types.ts
    ├── customer.types.ts
    ├── inventory.types.ts
    └── billing.types.ts

11. Integration Architecture

IntegrationTypePurposeImplementation
SupabaseBaaSDatabase, Auth, Storage, Realtime@supabase/supabase-js SDK
Resend / SendGridEmail APITransactional emails (quotes, invoices, alerts)REST API via Next.js API route
DHL APIShippingShipment booking, tracking number retrievalREST API (Phase 2)
FedEx APIShippingFreight booking for USA/CanadaREST API (Phase 2)
Razorpay / StripePayment GatewayOnline advance payment collectionSDK (Phase 2)
Tally / Zoho BooksAccountingGST filing, financial syncCSV export / API (Phase 2)
Google AnalyticsAnalyticsUsage trackingNEXT_PUBLIC_GA_MEASUREMENT_ID (already in .env)
Vercel AnalyticsPerformanceWeb vitals, page performance@vercel/analytics package

PART III — DATABASE DESIGN

12. Entity Relationship Overview

12.1 Core Entities

EntityTable NameDescriptionKey Relationships
UserusersSystem users (Admin, Staff, Customer)→ customers (1:1 for Customer role)
CustomercustomersCustomer company master→ orders (1:N), → quotations (1:N)
OrderordersProduction orders (core entity)→ customers (N:1), → invoices (1:N), → production_logs (1:N)
QuotationquotationsPrice quotes sent to customers→ customers (N:1), → orders (1:1 on conversion)
InvoiceinvoicesGST invoices linked to orders→ orders (N:1), → payments (1:N)
PaymentpaymentsPayment transactions (advance + balance)→ invoices (N:1), → orders (N:1)
Production Logproduction_logsStage-by-stage production history→ orders (N:1), → users (N:1)
Stone Inventorystone_inventoryCurrent stock levels per stone type→ inventory_transactions (1:N)
Inventory Transactioninventory_transactionsStock in/out history→ stone_inventory (N:1), → orders (N:1)
ShipmentshipmentsDispatch and logistics records→ orders (1:1)
NotificationnotificationsIn-app notification records→ users (N:1)
Audit Logaudit_logsAll system actions with actor + timestamp→ users (N:1)

13. Core Table Schemas

13.1 customers

CREATE TABLE customers (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  company_name    VARCHAR(200) NOT NULL,
  country         VARCHAR(50) NOT NULL CHECK (country IN ('USA','Canada','Ireland','India')),
  contact_person  VARCHAR(100),
  email           VARCHAR(150) NOT NULL UNIQUE,
  phone           VARCHAR(30),
  billing_address TEXT,
  shipping_address TEXT,
  default_payment_terms VARCHAR(100) DEFAULT '30% advance, 70% before dispatch',
  customer_since  DATE DEFAULT CURRENT_DATE,
  is_active       BOOLEAN DEFAULT TRUE,
  user_id         UUID REFERENCES auth.users(id),  -- for customer portal login
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_customers_country ON customers(country);
CREATE INDEX idx_customers_email ON customers(email);

13.2 orders

CREATE TABLE orders (
  id                  UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  order_id            VARCHAR(20) NOT NULL UNIQUE,  -- AG-XXXX format
  customer_id         UUID NOT NULL REFERENCES customers(id),
  product_type        VARCHAR(100) NOT NULL,
  stone_type          VARCHAR(100) NOT NULL,
  quantity            INTEGER NOT NULL CHECK (quantity >= 1 AND quantity <= 100),
  dimensions          VARCHAR(100),
  engraving_details   TEXT,
  order_value         NUMERIC(12,2) NOT NULL CHECK (order_value >= 1000),
  gst_amount          NUMERIC(12,2) GENERATED ALWAYS AS (ROUND(order_value * 0.18, 2)) STORED,
  total_amount        NUMERIC(12,2) GENERATED ALWAYS AS (ROUND(order_value * 1.18, 2)) STORED,
  order_date          DATE NOT NULL DEFAULT CURRENT_DATE,
  due_date            DATE NOT NULL,
  status              VARCHAR(50) NOT NULL DEFAULT 'Pending'
                        CHECK (status IN ('Pending','In Production','Cutting Stage','Shaping',
                          'Polishing','Engraving','Quality Check','Ready','Dispatched','Delivered','Cancelled')),
  production_stage    VARCHAR(100) DEFAULT 'Not Started',
  assigned_worker     VARCHAR(100) DEFAULT 'Unassigned',
  payment_status      VARCHAR(100) DEFAULT 'Advance Pending',
  payment_terms       VARCHAR(100) NOT NULL,
  advance_paid_pct    NUMERIC(5,2) DEFAULT 0,
  production_notes    TEXT,
  special_instructions TEXT,
  contact_email       VARCHAR(150),
  contact_phone       VARCHAR(30),
  billing_address     TEXT,
  shipping_address    TEXT,
  days_overdue        INTEGER GENERATED ALWAYS AS (
                        GREATEST(0, EXTRACT(DAY FROM NOW() - due_date)::INTEGER)
                      ) STORED,
  is_deleted          BOOLEAN DEFAULT FALSE,  -- soft delete
  created_by          UUID REFERENCES auth.users(id),
  created_at          TIMESTAMPTZ DEFAULT NOW(),
  updated_at          TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_orders_status ON orders(status);
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
CREATE INDEX idx_orders_due_date ON orders(due_date);
CREATE INDEX idx_orders_order_id ON orders(order_id);
CREATE INDEX idx_orders_is_deleted ON orders(is_deleted) WHERE is_deleted = FALSE;

13.3 quotations

CREATE TABLE quotations (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  quote_id        VARCHAR(20) NOT NULL UNIQUE,  -- QT-XXXX format
  customer_id     UUID NOT NULL REFERENCES customers(id),
  products        TEXT NOT NULL,  -- e.g. "Angel Monument × 2 (Black Galaxy)"
  base_amount     NUMERIC(12,2) NOT NULL CHECK (base_amount > 0),
  gst_amount      NUMERIC(12,2) GENERATED ALWAYS AS (ROUND(base_amount * 0.18, 2)) STORED,
  total_amount    NUMERIC(12,2) GENERATED ALWAYS AS (ROUND(base_amount * 1.18, 2)) STORED,
  created_date    DATE NOT NULL DEFAULT CURRENT_DATE,
  valid_until     DATE NOT NULL DEFAULT (CURRENT_DATE + INTERVAL '30 days'),
  status          VARCHAR(50) NOT NULL DEFAULT 'Pending Approval'
                    CHECK (status IN ('Pending Approval','Approved','Rejected','Converted to Order')),
  payment_terms   VARCHAR(100),
  engraving_notes TEXT,
  internal_notes  TEXT,
  converted_order_id UUID REFERENCES orders(id),  -- set when converted
  created_by      UUID REFERENCES auth.users(id),
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_quotations_customer_id ON quotations(customer_id);
CREATE INDEX idx_quotations_status ON quotations(status);

13.4 invoices

CREATE TABLE invoices (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  invoice_id      VARCHAR(20) NOT NULL UNIQUE,  -- INV-XXXX format
  order_id        UUID NOT NULL REFERENCES orders(id),
  customer_id     UUID NOT NULL REFERENCES customers(id),
  base_amount     NUMERIC(12,2) NOT NULL,
  gst_amount      NUMERIC(12,2) GENERATED ALWAYS AS (ROUND(base_amount * 0.18, 2)) STORED,
  total_amount    NUMERIC(12,2) GENERATED ALWAYS AS (ROUND(base_amount * 1.18, 2)) STORED,
  amount_paid     NUMERIC(12,2) DEFAULT 0,
  balance_due     NUMERIC(12,2) GENERATED ALWAYS AS (
                    ROUND(base_amount * 1.18, 2) - amount_paid
                  ) STORED,
  issue_date      DATE NOT NULL DEFAULT CURRENT_DATE,
  due_date        DATE NOT NULL,
  status          VARCHAR(50) NOT NULL DEFAULT 'Pending Approval'
                    CHECK (status IN ('Pending Approval','Paid','Overdue')),
  payment_method  VARCHAR(50),  -- Wire Transfer, SWIFT, ACH, Full Payment
  payment_ref     VARCHAR(100),  -- SWIFT ref, bank ref, etc.
  payment_date    DATE,
  notes           TEXT,
  pdf_url         TEXT,  -- Supabase Storage URL
  created_by      UUID REFERENCES auth.users(id),
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_invoices_order_id ON invoices(order_id);
CREATE INDEX idx_invoices_customer_id ON invoices(customer_id);
CREATE INDEX idx_invoices_status ON invoices(status);
CREATE INDEX idx_invoices_due_date ON invoices(due_date);

13.5 production_logs

CREATE TABLE production_logs (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  order_id        UUID NOT NULL REFERENCES orders(id),
  stage_from      VARCHAR(100),
  stage_to        VARCHAR(100) NOT NULL,
  worker_assigned VARCHAR(100),
  notes           TEXT,
  qc_result       VARCHAR(20) CHECK (qc_result IN ('Pass','Fail',NULL)),
  qc_notes        TEXT,
  changed_by      UUID REFERENCES auth.users(id),
  changed_at      TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_production_logs_order_id ON production_logs(order_id);

13.6 stone_inventory

CREATE TABLE stone_inventory (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  stone_type      VARCHAR(100) NOT NULL UNIQUE,
  current_stock   NUMERIC(10,2) NOT NULL DEFAULT 0 CHECK (current_stock >= 0),
  reorder_level   NUMERIC(10,2) NOT NULL DEFAULT 200,
  critical_level  NUMERIC(10,2) NOT NULL DEFAULT 100,
  unit            VARCHAR(20) DEFAULT 'sq.ft',
  status          VARCHAR(20) GENERATED ALWAYS AS (
                    CASE
                      WHEN current_stock <= critical_level THEN 'Critical'
                      WHEN current_stock <= reorder_level THEN 'Low Stock'
                      ELSE 'Good Stock'
                    END
                  ) STORED,
  last_updated    TIMESTAMPTZ DEFAULT NOW()
);

-- Seed data
INSERT INTO stone_inventory (stone_type, current_stock) VALUES
  ('Black Galaxy', 320),
  ('Absolute Black', 280),
  ('Imperial Red', 195),
  ('Blue Pearl', 145),
  ('Tan Brown', 235),
  ('Black Pearl', 65);

13.7 shipments

CREATE TABLE shipments (
  id                  UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  order_id            UUID NOT NULL REFERENCES orders(id) UNIQUE,
  carrier             VARCHAR(100),  -- DHL Express, FedEx Freight, etc.
  tracking_number     VARCHAR(100),
  tracking_url        TEXT,
  dispatch_date       DATE,
  estimated_delivery  DATE,
  actual_delivery     DATE,
  hs_code             VARCHAR(20) DEFAULT '6802.99',
  packing_details     TEXT,
  insurance_required  BOOLEAN DEFAULT FALSE,
  insurance_value     NUMERIC(12,2),
  customs_status      VARCHAR(50) DEFAULT 'Not Dispatched'
                        CHECK (customs_status IN ('Not Dispatched','In Transit',
                          'Customs Clearance','Delivered')),
  packing_list_url    TEXT,  -- Supabase Storage URL
  created_by          UUID REFERENCES auth.users(id),
  created_at          TIMESTAMPTZ DEFAULT NOW(),
  updated_at          TIMESTAMPTZ DEFAULT NOW()
);

13.8 notifications

CREATE TABLE notifications (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id     UUID REFERENCES auth.users(id),  -- NULL = broadcast to all admins
  type        VARCHAR(50) NOT NULL,  -- 'order','production','billing','inventory','dispatch'
  title       TEXT NOT NULL,
  message     TEXT NOT NULL,
  is_read     BOOLEAN DEFAULT FALSE,
  link        TEXT,  -- deep link to relevant record
  created_at  TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_notifications_user_id ON notifications(user_id);
CREATE INDEX idx_notifications_is_read ON notifications(is_read) WHERE is_read = FALSE;

13.9 audit_logs

CREATE TABLE audit_logs (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id     UUID REFERENCES auth.users(id),
  user_email  VARCHAR(150),
  action      VARCHAR(100) NOT NULL,  -- 'CREATE_ORDER','UPDATE_STATUS','DELETE_ORDER', etc.
  entity_type VARCHAR(50) NOT NULL,   -- 'order','quotation','invoice', etc.
  entity_id   UUID,
  old_value   JSONB,
  new_value   JSONB,
  ip_address  INET,
  user_agent  TEXT,
  created_at  TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_audit_logs_entity ON audit_logs(entity_type, entity_id);
CREATE INDEX idx_audit_logs_user_id ON audit_logs(user_id);
CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at DESC);

13.10 Row-Level Security (RLS) Policies

-- Enable RLS on all tables
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE quotations ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE customers ENABLE ROW LEVEL SECURITY;

-- Admin: full access
CREATE POLICY "admin_full_access_orders" ON orders
  FOR ALL USING (
    EXISTS (SELECT 1 FROM user_roles WHERE user_id = auth.uid() AND role = 'Admin')
  );

-- Staff: full read + write (no delete)
CREATE POLICY "staff_access_orders" ON orders
  FOR SELECT USING (
    EXISTS (SELECT 1 FROM user_roles WHERE user_id = auth.uid() AND role IN ('Admin','Staff'))
  );

-- Customer: own records only
CREATE POLICY "customer_own_orders" ON orders
  FOR SELECT USING (
    customer_id IN (
      SELECT id FROM customers WHERE user_id = auth.uid()
    )
  );

-- Same pattern applies to quotations, invoices

PART IV — API SPECIFICATIONS

14. REST API Endpoints

14.1 Authentication

MethodEndpointDescriptionAuth Required
POST/api/auth/loginLogin with email + password → returns JWTNo
POST/api/auth/logoutInvalidate sessionYes
GET/api/auth/meGet current user profile + roleYes
POST/api/auth/reset-passwordSend password reset emailNo

14.2 Orders API

MethodEndpointDescriptionRole
GET/api/ordersList orders with filters (status, country, search, page, perPage, sortBy, sortDir)Admin, Staff
POST/api/ordersCreate new orderAdmin, Staff
GET/api/orders/:idGet single order with full detailsAdmin, Staff, Customer (own)
PUT/api/orders/:idUpdate order (status, worker, stage, notes)Admin, Staff
DELETE/api/orders/:idSoft delete order (sets is_deleted=true)Admin only
GET/api/orders/statsOrder counts by status (for dashboard KPIs)Admin, Staff
POST/api/orders/bulkBulk update status or exportAdmin
GET/api/orders/exportExport orders to CSV/ExcelAdmin

14.3 Quotations API

MethodEndpointDescriptionRole
GET/api/quotationsList quotations with filtersAdmin, Staff
POST/api/quotationsCreate new quotationAdmin, Staff
GET/api/quotations/:idGet quotation detailsAdmin, Staff, Customer (own)
PUT/api/quotations/:idUpdate quotation (status, amount)Admin, Staff
POST/api/quotations/:id/convertConvert approved quote to orderAdmin
GET/api/quotations/:id/pdfGenerate and download quote PDFAdmin, Staff

14.4 Invoices API

MethodEndpointDescriptionRole
GET/api/invoicesList invoices with filtersAdmin, Staff
POST/api/invoicesCreate invoice (usually auto-triggered)Admin, Staff
GET/api/invoices/:idGet invoice detailsAdmin, Staff, Customer (own)
PUT/api/invoices/:idUpdate invoice (record payment, mark paid)Admin, Staff
GET/api/invoices/:id/pdfGenerate and download invoice PDFAdmin, Staff, Customer
GET/api/invoices/summaryBilling KPI summary (MTD totals)Admin

14.5 Production API

MethodEndpointDescriptionRole
GET/api/productionList active production ordersAdmin, Staff
PUT/api/production/:orderId/stageUpdate production stageAdmin, Staff
PUT/api/production/:orderId/workerAssign/reassign workerAdmin, Staff
POST/api/production/:orderId/qcSubmit QC result (pass/fail + notes)Admin, Staff
GET/api/production/:orderId/logsGet production stage historyAdmin

14.6 Inventory API

MethodEndpointDescriptionRole
GET/api/inventoryGet all stone inventory levelsAdmin, Staff
PUT/api/inventory/:stoneTypeUpdate stock level (receipt or adjustment)Admin, Staff
GET/api/inventory/transactionsGet inventory transaction historyAdmin
GET/api/inventory/alertsGet low/critical stock alertsAdmin, Staff

14.7 Customers API

MethodEndpointDescriptionRole
GET/api/customersList customers with search/filterAdmin, Staff
POST/api/customersCreate new customerAdmin, Staff
GET/api/customers/:idGet customer with order history + financialsAdmin, Staff
PUT/api/customers/:idUpdate customer detailsAdmin, Staff

14.8 Dashboard / Reports API

MethodEndpointDescriptionRole
GET/api/dashboard/kpisAll dashboard KPI values in single callAdmin, Staff
GET/api/dashboard/revenue-chartMonthly revenue data (last 6 months)Admin
GET/api/dashboard/order-status-chartOrder count by status for donut chartAdmin, Staff
GET/api/dashboard/activity-feedLast 20 activity eventsAdmin, Staff
GET/api/dashboard/deadlinesOrders due within 15 daysAdmin, Staff
GET/api/reports/:typeGenerate report (revenue/orders/production/inventory/gst/export)Admin

15. Request/Response Schemas

15.1 Create Order — POST /api/orders

// Request Body
{
  "customer_id": "uuid",
  "product_type": "Angel Monument",
  "stone_type": "Black Galaxy",
  "quantity": 2,
  "dimensions": "36\" × 12\" × 6\" each",
  "engraving_details": "Custom name + cross motif",
  "order_value": 240000,
  "due_date": "2026-08-20",
  "payment_terms": "30% advance, 70% before dispatch",
  "production_notes": "Customer requested matte finish on base",
  "special_instructions": "Fragile packing with foam corners. No stacking.",
  "contact_email": "orders@johnmemorialco.com",
  "contact_phone": "+1 (617) 555-0192",
  "billing_address": "145 Beacon St, Boston, MA 02116, USA",
  "shipping_address": "145 Beacon St, Boston, MA 02116, USA"
}

// Response 201 Created
{
  "success": true,
  "data": {
    "id": "uuid",
    "order_id": "AG-2848",
    "status": "Pending",
    "gst_amount": 43200,
    "total_amount": 283200,
    "created_at": "2026-08-04T01:42:19Z"
  }
}

// Response 400 Validation Error
{
  "success": false,
  "error": "Validation failed",
  "details": [
    { "field": "due_date", "message": "Due date must be at least 7 days from today" }
  ]
}

15.2 Dashboard KPIs — GET /api/dashboard/kpis

// Response 200
{
  "success": true,
  "data": {
    "revenue_mtd": 4280000,
    "revenue_mtd_formatted": "₹42.8L",
    "revenue_trend_pct": 8.3,
    "total_orders": 247,
    "active_production": 38,
    "pending_dispatch": 14,
    "stone_inventory_sqft": 1240,
    "low_stock_count": 3,
    "active_customers": 89,
    "overdue_orders": 3,
    "export_shipments_mtd": 7,
    "as_of": "2026-08-04T01:42:19Z"
  }
}

15.3 Standard Error Response

// 401 Unauthorized
{ "success": false, "error": "Authentication required" }

// 403 Forbidden
{ "success": false, "error": "Insufficient permissions for this action" }

// 404 Not Found
{ "success": false, "error": "Order AG-9999 not found" }

// 500 Internal Server Error
{ "success": false, "error": "Internal server error", "ref": "ERR-20260804-001" }

PART V — SECURITY, DEPLOYMENT & OPERATIONS

16. Security Architecture

16.1 Authentication Flow

  1. User submits email + password to POST /api/auth/login
  2. Supabase Auth validates credentials → returns JWT access token (8h) + refresh token (7d)
  3. JWT stored in httpOnly cookie (not localStorage — prevents XSS theft)
  4. Every API request: middleware extracts JWT from cookie → verifies signature → attaches user context
  5. Role fetched from user_roles table → attached to request context
  6. API route checks role before executing business logic
  7. Refresh token auto-renews access token before expiry

16.2 Authorization Matrix

ResourceAdminStaffCustomer
Dashboard (full)✅✅❌ (limited)
All Orders✅ CRUD✅ CRU❌
Own Orders✅✅✅ Read only
Production Tracking✅ CRUD✅ CRU❌
Stone Inventory✅ CRUD✅ CRU❌
All Customers✅ CRUD✅ CRU❌
Own Profile✅✅✅
All Quotations✅ CRUD✅ CRU❌
Own Quotations✅✅✅ Read + Create
All Invoices✅ CRUD✅ CRU❌
Own Invoices✅✅✅ Read + Download
Dispatch & Logistics✅ CRUD✅ CRU❌
Reports✅ Full✅ Limited❌
Settings✅❌❌
Audit Logs✅ Read❌❌
Delete Records✅❌❌

16.3 Data Security

17. Deployment Architecture

17.1 Production Environment

ComponentServiceTierNotes
Frontend + APIVercelProNext.js optimized, edge functions, auto-scaling
DatabaseSupabasePro ($25/mo)PostgreSQL 15, 8GB storage, daily backups
AuthSupabase AuthIncludedJWT, email/password, magic link
File StorageSupabase StorageIncluded (100GB)Invoice PDFs, packing lists, order photos
EmailResendPro ($20/mo)Transactional emails, 50k/month
MonitoringSentryTeamError tracking, performance monitoring
UptimeUptime RobotFree5-minute checks, SMS/email alerts
Domainaadhi-granite-erp.com—Already configured (published URL)

17.2 Environment Configuration

# Production .env (Vercel Environment Variables)
NEXT_PUBLIC_SUPABASE_URL=https://[project].supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=[anon-key]
SUPABASE_SERVICE_ROLE_KEY=[service-role-key]  # Server-side only
RESEND_API_KEY=[resend-key]
NEXT_PUBLIC_SITE_URL=https://aadhi-granite-erp.com
NEXT_PUBLIC_GA_MEASUREMENT_ID=[ga-id]
JWT_SECRET=[random-256-bit-secret]

17.3 CI/CD Pipeline

  1. Developer pushes to feature/* branch → GitHub Actions runs: TypeScript check, ESLint, unit tests
  2. PR to develop → Vercel Preview deployment → QA testing on preview URL
  3. PR to main → Requires Admin approval → Vercel Production deployment
  4. Database migrations: Supabase CLI migrations run via GitHub Actions on merge to main
  5. Rollback: Vercel instant rollback to previous deployment if errors detected

17.4 Disaster Recovery

ScenarioRTORPORecovery Method
Application crash5 min0Vercel auto-restart; rollback to last stable
Database corruption2 hours24 hoursSupabase point-in-time recovery
Data center outage4 hours24 hoursSupabase multi-region failover
Accidental data deletion1 hour24 hoursRestore from daily backup

18. Audit Trail & Compliance

18.1 Audit Events Tracked

EventAction CodeData Captured
Order createdCREATE_ORDERFull order JSON, user, IP, timestamp
Order status changedUPDATE_ORDER_STATUSOld status, new status, reason
Order deletedDELETE_ORDEROrder ID, user, reason
Production stage updatedUPDATE_PRODUCTION_STAGEOld stage, new stage, worker, notes
QC result submittedSUBMIT_QC_RESULTPass/Fail, notes, supervisor
Invoice generatedCREATE_INVOICEInvoice ID, order ID, amount
Payment recordedRECORD_PAYMENTAmount, method, reference, date
Quote approved/rejectedUPDATE_QUOTE_STATUSOld status, new status, notes
Inventory updatedUPDATE_INVENTORYStone type, old qty, new qty, reason
User loginUSER_LOGINUser, IP, user agent, timestamp
User login failedUSER_LOGIN_FAILEDEmail attempted, IP, timestamp
Settings changedUPDATE_SETTINGSSetting key, old value, new value

18.2 Compliance Checklist

RequirementStatusImplementation
GST Invoice Format (India)CoveredPDF template with GSTIN, HSN, CGST/SGST/IGST breakdown
7-Year Financial Record RetentionCoveredSoft delete + archive policy; no hard delete on financial records
Export Documentation (DGFT)CoveredPacking list + commercial invoice generation with HS codes
GDPR (Irish Customers)PartialData export + soft delete; cookie consent banner needed
FEMA (Foreign Exchange)PartialPayment method + SWIFT ref tracked; formal FEMA reporting is manual
Audit TrailCoveredaudit_logs table with all CRUD operations

19. Performance & Scalability

19.1 Database Optimization

19.2 Frontend Optimization

19.3 Scalability Strategy

BottleneckCurrent LimitScaling Strategy
Database connectionsSupabase Pro: 60 connectionsConnection pooling via PgBouncer (Supabase built-in)
API throughputVercel: unlimited serverlessAuto-scales; no action needed
File storage100GB (Supabase Pro)Upgrade to Supabase Team ($599/mo) at 80GB usage
Email volumeResend Pro: 50k/monthUpgrade plan at 40k/month usage
Order data growth~500 records/yearArchive orders >3 years old to separate table at 50k records

20. Testing Strategy

20.1 Test Coverage Requirements

Test TypeToolCoverage TargetFocus Areas
Unit TestsJest + React Testing Library80% code coverageBusiness logic, validation schemas, utility functions
Integration TestsJest + Supabase test clientKey workflowsOrder CRUD, payment recording, status transitions
E2E TestsPlaywrightCritical user journeysLogin, create order, update production stage, generate invoice
API TestsPostman / HoppscotchAll endpointsAuth, RBAC, validation errors, edge cases
Load Testsk650 concurrent usersDashboard load, order list, search performance
Security TestsOWASP ZAPOWASP Top 10SQL injection, XSS, CSRF, auth bypass

20.2 Critical Test Scenarios

  1. Order Lifecycle: Create order → assign worker → update through all 7 production stages → QC pass → generate invoice → record payment → dispatch → deliver
  2. Quote-to-Order: Create quote → approve → convert to order → verify order pre-populated correctly
  3. GST Calculation: Verify 18% GST on all amounts; verify CGST/SGST vs IGST split
  4. Overdue Detection: Create invoice with past due date → verify auto-marked Overdue → verify alert generated
  5. RBAC Enforcement: Customer cannot access other customers' orders; Staff cannot delete; Customer cannot access Settings
  6. Inventory Alert: Reduce stock below reorder level → verify notification generated
  7. Bulk Operations: Select 10 orders → bulk update status → verify all updated correctly
  8. Search & Filter: Search by order ID, customer name, product type; filter by status; sort by value
  9. PDF Generation: Generate invoice PDF → verify all fields present, GST breakdown correct
  10. Concurrent Updates: Two users update same order simultaneously → verify no data corruption (optimistic locking)

20.3 UAT Acceptance Criteria

Aadhi Granites ERP — Enterprise Documentation Suite

Document Version 1.0 · August 2026 · Confidential

Prepared by: Enterprise Solution Architect | ERP Consultant | Senior Business Analyst | Technical Architect | UI/UX Analyst | Database Architect | DevOps Architect

← Part 1: BRD Sections 1–5  |  View ERP Prototype →