| Metric | Requirement | Measurement Method |
|---|---|---|
| Page Load Time | < 2 seconds (P95) on standard broadband | Lighthouse / Web Vitals |
| API Response Time | < 500ms for list queries, < 200ms for single record | Server-side timing headers |
| Dashboard Refresh | KPI data refreshed within 30 seconds of underlying change | Real-time monitoring |
| Concurrent Users | Support 50 concurrent users without degradation | Load testing (k6/JMeter) |
| Database Query | < 100ms for indexed queries on orders table (up to 10,000 records) | Query EXPLAIN ANALYZE |
| File Export | PDF/Excel export < 5 seconds for up to 500 records | End-to-end timing |
| Uptime SLA | 99.5% monthly uptime (max 3.6 hours downtime/month) | Uptime monitoring (Uptime Robot) |
| Dimension | Current | Year 1 Target | Year 3 Target |
|---|---|---|---|
| Active Orders | 247 | 500 | 2,000 |
| Customers | 89 | 200 | 500 |
| Monthly Revenue | ₹42.8L | ₹80L | ₹2Cr |
| Concurrent Users | 5–10 | 50 | 200 |
| Data Volume (Orders) | ~500 records | 5,000 | 50,000 |
| Countries Served | 4 | 6 | 10 |
| Regulation | Requirement | Implementation |
|---|---|---|
| GST (India) | 18% GST on all domestic and export invoices; GSTIN on all documents | Auto-calculation in billing module |
| FEMA / RBI | Foreign exchange receipts documented for export orders | Payment method + SWIFT reference tracking |
| DGFT Export | Export documentation: Shipping Bill, Certificate of Origin, Packing List | Document generation module |
| HS Code | HS Code 6802.99 (Worked monumental/building stone) on all export documents | Pre-filled in dispatch module |
| GDPR (EU/Ireland) | Customer data protection for Irish customers; right to erasure | Soft delete + data export feature |
| Data Retention | Financial records retained for 7 years (Indian Companies Act) | Archive policy in database |
| Field | Validation Rule | Error Message |
|---|---|---|
| Order ID | Auto-generated; format AG-XXXX; unique; sequential | System-generated, no user input |
| Customer | Required; must exist in customer master OR be new prospect | "Customer name is required" |
| Country | Required; must be one of: USA, Canada, Ireland, India | "Please select a valid country" |
| Product Type | Required; must be from approved product list (9 types) | "Please select a product type" |
| Stone Type | Required; must be from approved stone list (6 types) | "Please select a stone type" |
| Quantity | Required; integer; minimum 1; maximum 100 | "Quantity must be between 1 and 100" |
| Order Value | Required; numeric; minimum ₹1,000; maximum ₹50,00,000 | "Order value must be between ₹1,000 and ₹50,00,000" |
| Due Date | Required; must be at least 7 days from order date | "Due date must be at least 7 days from today" |
| Dimensions | Optional; format: W" × H" × D" (inches) | "Use format: 36\" × 12\" × 6\"" |
| Contact Email | Required; valid email format | "Please enter a valid email address" |
| Payment Terms | Required; must be from approved terms list (5 options) | "Please select payment terms" |
| Entity | From Status | Allowed Next Status | Condition |
|---|---|---|---|
| Order | Pending | In Production | Advance payment confirmed + worker assigned |
| Order | In Production | Cutting Stage, Shaping, Polishing, Engraving, Quality Check | Stage updated by supervisor |
| Order | Quality Check | Ready (pass) or back to stage (fail) | QC supervisor decision |
| Order | Ready | Dispatched | Invoice generated + balance payment received (or terms allow) |
| Order | Dispatched | Delivered | Customer confirmation or tracking shows delivered |
| Quote | Pending Approval | Approved, Rejected | Customer response |
| Quote | Approved | Converted to Order | Advance payment received |
| Invoice | Pending Approval | Paid, Overdue | Payment received OR due date passed |
| Invoice | Overdue | Paid | Late payment received |
| ID | Assumption | Impact if Wrong |
|---|---|---|
| A-001 | GST rate is fixed at 18% for all product types and customer locations | Billing module requires reconfiguration if rates vary by HSN code |
| A-002 | Production workers do not have ERP login access in Phase 1 | Mobile worker interface needed if workers need direct stage updates |
| A-003 | All financial amounts are stored and displayed in Indian Rupees (INR) | Multi-currency module required if customers need USD/EUR invoices |
| A-004 | Stone inventory unit is square feet (sq.ft) for all stone types | Unit conversion needed if some stones are sold by cubic feet or weight |
| A-005 | HS Code 6802.99 applies to all exported granite products | Customs documentation errors if different products have different HS codes |
| A-006 | Reorder level is 200 sq.ft and critical level is 100 sq.ft for all stone types | Alert thresholds need per-stone configuration if consumption rates vary |
| A-007 | Quote validity default is 30 days from creation date | Configurable per customer if different validity periods are negotiated |
| A-008 | Waste factor of 15% is applied to stone consumption estimates | Inventory discrepancies if actual waste varies significantly by product type |
| A-009 | Email notifications are sent via SMTP/transactional email service | Email delivery failures if SMTP not configured; SMS fallback may be needed |
| A-010 | The system supports 4 countries (USA, Canada, Ireland, India) in Phase 1 | Country/timezone/currency additions needed for expansion markets |
| A-011 | High-value threshold for Admin approval is ₹5,00,000 | Configurable threshold needed if business policy changes |
| A-012 | Production stage history is tracked but not time-stamped at sub-minute granularity | Detailed time-motion studies require higher precision timestamps |
| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Frontend Framework | Next.js | 15.x | SSR/SSG, App Router, API Routes |
| UI Library | React | 19.x | Component-based UI |
| Language | TypeScript | 5.x | Type safety across full stack |
| Styling | Tailwind CSS | 3.x | Utility-first CSS |
| Database | PostgreSQL (via Supabase) | 15.x | Primary data store |
| Auth | Supabase Auth | Latest | JWT-based authentication |
| ORM / Query | Supabase JS Client | 2.x | Type-safe database queries |
| Validation | Zod | 3.x | Runtime schema validation |
| Charts | Recharts | 2.x | Revenue and order charts |
| PDF Generation | @react-pdf/renderer | 3.x | Invoice and packing list PDFs |
| Resend | Latest | Transactional email notifications | |
| File Storage | Supabase Storage | Latest | Document storage (invoices, photos) |
| Cron Jobs | Supabase Edge Functions | Latest | Daily overdue checks, reminders |
| Hosting | Vercel | Latest | Next.js optimized deployment |
| CDN | Vercel Edge Network | — | Global content delivery |
| Monitoring | Vercel Analytics + Sentry | Latest | Performance + error tracking |
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)
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
| Integration | Type | Purpose | Implementation |
|---|---|---|---|
| Supabase | BaaS | Database, Auth, Storage, Realtime | @supabase/supabase-js SDK |
| Resend / SendGrid | Email API | Transactional emails (quotes, invoices, alerts) | REST API via Next.js API route |
| DHL API | Shipping | Shipment booking, tracking number retrieval | REST API (Phase 2) |
| FedEx API | Shipping | Freight booking for USA/Canada | REST API (Phase 2) |
| Razorpay / Stripe | Payment Gateway | Online advance payment collection | SDK (Phase 2) |
| Tally / Zoho Books | Accounting | GST filing, financial sync | CSV export / API (Phase 2) |
| Google Analytics | Analytics | Usage tracking | NEXT_PUBLIC_GA_MEASUREMENT_ID (already in .env) |
| Vercel Analytics | Performance | Web vitals, page performance | @vercel/analytics package |
| Entity | Table Name | Description | Key Relationships |
|---|---|---|---|
| User | users | System users (Admin, Staff, Customer) | → customers (1:1 for Customer role) |
| Customer | customers | Customer company master | → orders (1:N), → quotations (1:N) |
| Order | orders | Production orders (core entity) | → customers (N:1), → invoices (1:N), → production_logs (1:N) |
| Quotation | quotations | Price quotes sent to customers | → customers (N:1), → orders (1:1 on conversion) |
| Invoice | invoices | GST invoices linked to orders | → orders (N:1), → payments (1:N) |
| Payment | payments | Payment transactions (advance + balance) | → invoices (N:1), → orders (N:1) |
| Production Log | production_logs | Stage-by-stage production history | → orders (N:1), → users (N:1) |
| Stone Inventory | stone_inventory | Current stock levels per stone type | → inventory_transactions (1:N) |
| Inventory Transaction | inventory_transactions | Stock in/out history | → stone_inventory (N:1), → orders (N:1) |
| Shipment | shipments | Dispatch and logistics records | → orders (1:1) |
| Notification | notifications | In-app notification records | → users (N:1) |
| Audit Log | audit_logs | All system actions with actor + timestamp | → users (N:1) |
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);
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;
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);
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);
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);
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);
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()
);
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;
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);
-- 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
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /api/auth/login | Login with email + password → returns JWT | No |
| POST | /api/auth/logout | Invalidate session | Yes |
| GET | /api/auth/me | Get current user profile + role | Yes |
| POST | /api/auth/reset-password | Send password reset email | No |
| Method | Endpoint | Description | Role |
|---|---|---|---|
| GET | /api/orders | List orders with filters (status, country, search, page, perPage, sortBy, sortDir) | Admin, Staff |
| POST | /api/orders | Create new order | Admin, Staff |
| GET | /api/orders/:id | Get single order with full details | Admin, Staff, Customer (own) |
| PUT | /api/orders/:id | Update order (status, worker, stage, notes) | Admin, Staff |
| DELETE | /api/orders/:id | Soft delete order (sets is_deleted=true) | Admin only |
| GET | /api/orders/stats | Order counts by status (for dashboard KPIs) | Admin, Staff |
| POST | /api/orders/bulk | Bulk update status or export | Admin |
| GET | /api/orders/export | Export orders to CSV/Excel | Admin |
| Method | Endpoint | Description | Role |
|---|---|---|---|
| GET | /api/quotations | List quotations with filters | Admin, Staff |
| POST | /api/quotations | Create new quotation | Admin, Staff |
| GET | /api/quotations/:id | Get quotation details | Admin, Staff, Customer (own) |
| PUT | /api/quotations/:id | Update quotation (status, amount) | Admin, Staff |
| POST | /api/quotations/:id/convert | Convert approved quote to order | Admin |
| GET | /api/quotations/:id/pdf | Generate and download quote PDF | Admin, Staff |
| Method | Endpoint | Description | Role |
|---|---|---|---|
| GET | /api/invoices | List invoices with filters | Admin, Staff |
| POST | /api/invoices | Create invoice (usually auto-triggered) | Admin, Staff |
| GET | /api/invoices/:id | Get invoice details | Admin, Staff, Customer (own) |
| PUT | /api/invoices/:id | Update invoice (record payment, mark paid) | Admin, Staff |
| GET | /api/invoices/:id/pdf | Generate and download invoice PDF | Admin, Staff, Customer |
| GET | /api/invoices/summary | Billing KPI summary (MTD totals) | Admin |
| Method | Endpoint | Description | Role |
|---|---|---|---|
| GET | /api/production | List active production orders | Admin, Staff |
| PUT | /api/production/:orderId/stage | Update production stage | Admin, Staff |
| PUT | /api/production/:orderId/worker | Assign/reassign worker | Admin, Staff |
| POST | /api/production/:orderId/qc | Submit QC result (pass/fail + notes) | Admin, Staff |
| GET | /api/production/:orderId/logs | Get production stage history | Admin |
| Method | Endpoint | Description | Role |
|---|---|---|---|
| GET | /api/inventory | Get all stone inventory levels | Admin, Staff |
| PUT | /api/inventory/:stoneType | Update stock level (receipt or adjustment) | Admin, Staff |
| GET | /api/inventory/transactions | Get inventory transaction history | Admin |
| GET | /api/inventory/alerts | Get low/critical stock alerts | Admin, Staff |
| Method | Endpoint | Description | Role |
|---|---|---|---|
| GET | /api/customers | List customers with search/filter | Admin, Staff |
| POST | /api/customers | Create new customer | Admin, Staff |
| GET | /api/customers/:id | Get customer with order history + financials | Admin, Staff |
| PUT | /api/customers/:id | Update customer details | Admin, Staff |
| Method | Endpoint | Description | Role |
|---|---|---|---|
| GET | /api/dashboard/kpis | All dashboard KPI values in single call | Admin, Staff |
| GET | /api/dashboard/revenue-chart | Monthly revenue data (last 6 months) | Admin |
| GET | /api/dashboard/order-status-chart | Order count by status for donut chart | Admin, Staff |
| GET | /api/dashboard/activity-feed | Last 20 activity events | Admin, Staff |
| GET | /api/dashboard/deadlines | Orders due within 15 days | Admin, Staff |
| GET | /api/reports/:type | Generate report (revenue/orders/production/inventory/gst/export) | Admin |
// 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" }
]
}
// 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"
}
}
// 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" }
POST /api/auth/loginuser_roles table → attached to request context| Resource | Admin | Staff | Customer |
|---|---|---|---|
| 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 | ✅ | ❌ | ❌ |
| Component | Service | Tier | Notes |
|---|---|---|---|
| Frontend + API | Vercel | Pro | Next.js optimized, edge functions, auto-scaling |
| Database | Supabase | Pro ($25/mo) | PostgreSQL 15, 8GB storage, daily backups |
| Auth | Supabase Auth | Included | JWT, email/password, magic link |
| File Storage | Supabase Storage | Included (100GB) | Invoice PDFs, packing lists, order photos |
| Resend | Pro ($20/mo) | Transactional emails, 50k/month | |
| Monitoring | Sentry | Team | Error tracking, performance monitoring |
| Uptime | Uptime Robot | Free | 5-minute checks, SMS/email alerts |
| Domain | aadhi-granite-erp.com | — | Already configured (published URL) |
# 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]
feature/* branch → GitHub Actions runs: TypeScript check, ESLint, unit testsdevelop → Vercel Preview deployment → QA testing on preview URLmain → Requires Admin approval → Vercel Production deployment| Scenario | RTO | RPO | Recovery Method |
|---|---|---|---|
| Application crash | 5 min | 0 | Vercel auto-restart; rollback to last stable |
| Database corruption | 2 hours | 24 hours | Supabase point-in-time recovery |
| Data center outage | 4 hours | 24 hours | Supabase multi-region failover |
| Accidental data deletion | 1 hour | 24 hours | Restore from daily backup |
| Event | Action Code | Data Captured |
|---|---|---|
| Order created | CREATE_ORDER | Full order JSON, user, IP, timestamp |
| Order status changed | UPDATE_ORDER_STATUS | Old status, new status, reason |
| Order deleted | DELETE_ORDER | Order ID, user, reason |
| Production stage updated | UPDATE_PRODUCTION_STAGE | Old stage, new stage, worker, notes |
| QC result submitted | SUBMIT_QC_RESULT | Pass/Fail, notes, supervisor |
| Invoice generated | CREATE_INVOICE | Invoice ID, order ID, amount |
| Payment recorded | RECORD_PAYMENT | Amount, method, reference, date |
| Quote approved/rejected | UPDATE_QUOTE_STATUS | Old status, new status, notes |
| Inventory updated | UPDATE_INVENTORY | Stone type, old qty, new qty, reason |
| User login | USER_LOGIN | User, IP, user agent, timestamp |
| User login failed | USER_LOGIN_FAILED | Email attempted, IP, timestamp |
| Settings changed | UPDATE_SETTINGS | Setting key, old value, new value |
| Requirement | Status | Implementation |
|---|---|---|
| GST Invoice Format (India) | Covered | PDF template with GSTIN, HSN, CGST/SGST/IGST breakdown |
| 7-Year Financial Record Retention | Covered | Soft delete + archive policy; no hard delete on financial records |
| Export Documentation (DGFT) | Covered | Packing list + commercial invoice generation with HS codes |
| GDPR (Irish Customers) | Partial | Data export + soft delete; cookie consent banner needed |
| FEMA (Foreign Exchange) | Partial | Payment method + SWIFT ref tracked; formal FEMA reporting is manual |
| Audit Trail | Covered | audit_logs table with all CRUD operations |
| Bottleneck | Current Limit | Scaling Strategy |
|---|---|---|
| Database connections | Supabase Pro: 60 connections | Connection pooling via PgBouncer (Supabase built-in) |
| API throughput | Vercel: unlimited serverless | Auto-scales; no action needed |
| File storage | 100GB (Supabase Pro) | Upgrade to Supabase Team ($599/mo) at 80GB usage |
| Email volume | Resend Pro: 50k/month | Upgrade plan at 40k/month usage |
| Order data growth | ~500 records/year | Archive orders >3 years old to separate table at 50k records |
| Test Type | Tool | Coverage Target | Focus Areas |
|---|---|---|---|
| Unit Tests | Jest + React Testing Library | 80% code coverage | Business logic, validation schemas, utility functions |
| Integration Tests | Jest + Supabase test client | Key workflows | Order CRUD, payment recording, status transitions |
| E2E Tests | Playwright | Critical user journeys | Login, create order, update production stage, generate invoice |
| API Tests | Postman / Hoppscotch | All endpoints | Auth, RBAC, validation errors, edge cases |
| Load Tests | k6 | 50 concurrent users | Dashboard load, order list, search performance |
| Security Tests | OWASP ZAP | OWASP Top 10 | SQL injection, XSS, CSRF, auth bypass |
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