Initial requirements

This commit is contained in:
Prashant Shendre 2026-10-11 15:10:36 +05:30
parent 24901c550e
commit a5f0f24ea4
24 changed files with 28908 additions and 141 deletions

View File

@ -0,0 +1,24 @@
# RamDayal Deen Dayal & Co. — Back Office
A standalone static back-office demonstration for a fictional major dry-agri wholesale firm in Neemuch, Madhya Pradesh.
## Data volume
- 480 synthetic market observations
- 180 purchase entries
- 180 sales entries
- 180 goods-receipt records
- 180 dispatch records
- 90 payment records
- 60 expense records
- 180 lot records
- 12 customers
- 10 suppliers
- 4 warehouses
- 10 staff records
- 6 vehicles
- 20 management snapshots
- operational alerts and inventory positions
All records are explicitly **FICTITIOUS / ILLUSTRATIVE** and are not claims about the real business, market prices, customers, suppliers, stock or transactions of any actual firm.
Open `index.html` directly. No server is required.

View File

@ -0,0 +1,2 @@
:root{--ink:#24332d;--muted:#718078;--line:#e5e9e5;--paper:#f6f7f4;--card:#fff;--green:#285d46;--gold:#b28a3a;--red:#a64b42;--blue:#3e6882}*{box-sizing:border-box}body{margin:0;font-family:Inter,ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Arial;color:var(--ink);background:var(--paper)}button{font:inherit}.app{display:flex;min-height:100vh}.sidebar{width:240px;background:#1f3029;color:#eaf0eb;padding:22px 14px;display:flex;flex-direction:column}.brand{display:flex;gap:11px;align-items:center;padding:3px 10px 28px}.mark{width:39px;height:39px;border-radius:10px;background:#d5b05b;color:#1f3029;display:grid;place-items:center;font-weight:800}.brand strong{display:block;font-size:15px}.brand span{display:block;color:#aebbb4;font-size:11px;margin-top:2px}.nav{width:100%;border:0;background:transparent;color:#c7d1cc;text-align:left;padding:11px 12px;border-radius:8px;display:flex;gap:12px;align-items:center;cursor:pointer;font-size:13px;margin:2px 0}.nav:hover,.nav.active{background:#30483d;color:#fff}.side-note{margin-top:auto;border-top:1px solid #3b5047;padding:16px 10px;color:#9eada5;font-size:11px;line-height:1.5}.side-note small{color:#d2b466;text-transform:uppercase;letter-spacing:.08em}main{flex:1;min-width:0}.topbar{height:82px;background:#fff;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 30px}.eyebrow{font-size:10px;letter-spacing:.14em;color:#849087}.topbar h1{font-size:22px;margin:3px 0 0}.top-actions{display:flex;gap:18px;align-items:center}.date{font-size:12px;color:var(--muted)}.user{border:1px solid var(--line);background:#fff;border-radius:8px;padding:7px 10px;color:var(--ink);font-size:12px}.user:first-letter{font-weight:800}.user span{margin-left:6px;color:var(--muted)}.wrap{padding:26px 30px 40px;max-width:1500px}.cards{display:grid;grid-template-columns:repeat(4,1fr);gap:14px}.card,.panel{background:var(--card);border:1px solid var(--line);border-radius:10px}.metric{padding:18px}.metric label{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}.metric strong{display:block;font-size:26px;margin:9px 0 4px}.metric small{font-size:11px;color:var(--muted)}.positive{color:var(--green)}.negative{color:var(--red)}.section{margin-top:22px}.section-head{display:flex;justify-content:space-between;align-items:end;margin-bottom:10px}.section h2{font-size:15px;margin:0}.section-head p{margin:3px 0 0;font-size:11px;color:var(--muted)}.grid2{display:grid;grid-template-columns:1.5fr 1fr;gap:14px}.panel{padding:18px}.table-wrap{overflow:auto}.table{width:100%;border-collapse:collapse;font-size:12px}.table th{text-align:left;color:#7d8982;font-size:10px;text-transform:uppercase;letter-spacing:.04em;padding:9px 10px;border-bottom:1px solid var(--line);white-space:nowrap}.table td{padding:11px 10px;border-bottom:1px solid #edf0ed;white-space:nowrap}.table tr:last-child td{border-bottom:0}.pill{display:inline-block;border-radius:999px;padding:4px 7px;font-size:10px;background:#edf3ef;color:var(--green)}.pill.amber{background:#f6f0df;color:#87691f}.pill.red{background:#f8e9e7;color:#9a443c}.toolbar{display:flex;gap:8px;flex-wrap:wrap}.select,.search{border:1px solid var(--line);background:#fff;border-radius:7px;padding:8px 10px;font-size:11px;color:var(--ink)}.search{min-width:190px}.mini-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}.mini{padding:12px;border:1px solid var(--line);border-radius:8px}.mini b{font-size:17px}.mini span{display:block;color:var(--muted);font-size:10px;margin-top:3px}.bar{height:8px;background:#edf0ed;border-radius:5px;overflow:hidden;margin-top:10px}.bar i{display:block;height:100%;background:#49735e;border-radius:5px}.note{font-size:11px;color:var(--muted);line-height:1.6}.hero{background:#e9efe9;border:1px solid #dbe4dc;border-radius:10px;padding:18px 20px;margin-bottom:18px}.hero strong{font-size:16px}.hero p{font-size:12px;color:#66736c;margin:6px 0 0}.kicker{font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:#8a7650}.empty{padding:34px;text-align:center;color:var(--muted);font-size:12px}@media(max-width:900px){.sidebar{width:68px}.brand div:not(.mark),.nav span,.side-note{display:none}.nav{justify-content:center}.topbar{padding:0 16px}.wrap{padding:18px}.cards,.grid2{grid-template-columns:1fr 1fr}}@media(max-width:620px){.cards,.grid2,.mini-grid{grid-template-columns:1fr}.sidebar{display:none}.topbar{height:70px}.date{display:none}}
.hero-badge{font-size:10px;line-height:1.35;max-width:250px;padding:10px 12px;border:1px solid #d9cfbb;border-radius:10px;background:#faf7ef;color:#756d60;text-transform:uppercase;letter-spacing:.05em}.alert{display:flex;gap:12px;padding:12px 0;border-bottom:1px solid #eee7da;flex-direction:column}.alert:last-child{border-bottom:0}.alert.warning{border-left:3px solid #b48a38;padding-left:12px}.alert.info{border-left:3px solid #587b68;padding-left:12px}.alert b{font-size:13px}.alert span{font-size:12px;color:#746f66}.amber{background:#f4ead0!important;color:#7d6223!important}.mini-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}.mini{padding:14px;background:#faf7ef;border-radius:10px}.mini b{display:block;font-size:18px}.mini span{font-size:11px;color:#81796c}.note{font-size:12px;color:#777064;line-height:1.6}@media(max-width:900px){.mini-grid{grid-template-columns:repeat(2,1fr)}}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>RamDayal Deen Dayal & Co. — Back Office</title><link rel="stylesheet" href="css/style.css"></head><body><div class="app"><aside class="sidebar"><div class="brand"><div class="mark">RD</div><div><strong>RamDayal</strong><span>Deen Dayal & Co.</span></div></div><nav id="nav"></nav><div class="side-note"><small>Operational demonstration</small><br>All figures are fictitious and for interface demonstration only.</div></aside><main><header class="topbar"><div><div class="eyebrow">BACK OFFICE</div><h1 id="pageTitle">Dashboard</h1></div><div class="top-actions"><span class="date">20 Sep 2026</span><button class="user">RD <span>Admin</span></button></div></header><div id="content"></div></main></div><script src="js/data.js"></script><script src="js/app.js"></script></body></html>

View File

@ -0,0 +1,21 @@
const D=window.RD_DATA||{}; const money=n=>'₹'+new Intl.NumberFormat('en-IN').format(Math.round(n||0)); const num=n=>new Intl.NumberFormat('en-IN').format(Math.round(n||0)); const mt=n=>num(n)+' MT';
const nav=[['dashboard','▦','Dashboard'],['market','◫','Market Desk'],['inventory','▤','Inventory'],['procurement','⇄','Procurement'],['sales','↗','Sales'],['customers','◎','Customers'],['suppliers','◌','Suppliers'],['logistics','▱','Logistics'],['finance','₹','Finance'],['quality','✓','Quality'],['reports','▥','Reports']];
let view='dashboard';
const el=id=>document.getElementById(id); const rows=(arr,cols)=>`<table class="table"><thead><tr>${cols.map(c=>`<th>${c[0]}</th>`).join('')}</tr></thead><tbody>${arr.map(x=>`<tr>${cols.map(c=>`<td>${c[1](x)}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
const pill=(s,kind='')=>`<span class="pill ${kind}">${s}</span>`;
function totals(a,k){return a.reduce((s,x)=>s+(+x[k]||0),0)}
function dashboard(){let inv=D.inventory||[], purch=D.purchases||[], sales=D.sales||[], rec=D.receipts||[], disp=D.dispatches||[];let stock=totals(inv,'closingStockMT'), pv=totals(purch,'valueINR'), sv=totals(sales,'valueINR'); let due=(D.customers||[]).reduce((s,x)=>s+x.outstandingINR,0); return `<div class="wrap"><div class="hero"><div><span class="kicker">Neemuch · Wholesale dry-agri trade</span><h2>RamDayal Deen Dayal & Co.</h2><p>Operational control centre for procurement, inventory, market intelligence, sales, dispatch and accounts.</p></div><div class="hero-badge">${D.meta.status}</div></div><div class="cards"><div class="card metric"><label>Stock on hand</label><strong>${mt(stock)}</strong><small>${inv.length} active stock lines</small></div><div class="card metric"><label>Purchase value</label><strong>${money(pv)}</strong><small>${purch.length} purchase entries</small></div><div class="card metric"><label>Sales value</label><strong>${money(sv)}</strong><small>${sales.length} sales entries</small></div><div class="card metric"><label>Receivables</label><strong>${money(due)}</strong><small>${D.customers.length} customer accounts</small></div></div><div class="grid2 section"><div class="panel"><div class="section-head"><div><h2>Operational alerts</h2><p>Items requiring attention</p></div></div>${D.alerts.map(a=>`<div class="alert ${a.severity}"><b>${a.title}</b><span>${a.detail}</span></div>`).join('')}</div><div class="panel"><div class="section-head"><div><h2>Warehouse position</h2><p>Current capacity utilisation</p></div></div>${rows(D.warehouses,[['Warehouse',x=>x.name],['Capacity',x=>mt(x.capacityMT)],['Used',x=>x.utilisationPct+'%'],['Status',x=>pill(x.utilisationPct>85?'Watch':'Normal',x.utilisationPct>85?'amber':'')]])}</div></div><div class="grid2 section"><div class="panel"><div class="section-head"><div><h2>Top stock lines</h2><p>Highest closing quantities</p></div></div>${rows([...inv].sort((a,b)=>b.closingStockMT-a.closingStockMT).slice(0,10),[['Commodity',x=>x.commodity],['Warehouse',x=>x.warehouse],['Grade',x=>x.grade],['Stock',x=>mt(x.closingStockMT)]])}</div><div class="panel"><div class="section-head"><div><h2>Recent sales</h2><p>Latest customer orders</p></div></div>${rows([...sales].sort((a,b)=>b.date.localeCompare(a.date)||b.id.localeCompare(a.id)).slice(0,10),[['Date',x=>x.date],['Customer',x=>x.customer],['Commodity',x=>x.commodity],['Qty',x=>mt(x.qtyMT)],['Value',x=>money(x.valueINR)]])}</div></div></div>`}
function market(){let a=[...D.market].sort((x,y)=>y.observationDate.localeCompare(x.observationDate));return `<div class="wrap"><div class="section-head"><div><h2>Market Desk</h2><p>${a.length} synthetic market observations</p></div><div class="toolbar"><select class="select" onchange="filterMarket(this.value)"><option>All commodities</option>${D.commodities.map(c=>`<option>${c}</option>`).join('')}</select></div></div><div id="marketTable" class="panel">${marketRows(a.slice(0,80))}</div></div>`}
function marketRows(a){return rows(a,[['Date',x=>x.observationDate],['Market',x=>x.market],['Commodity',x=>x.commodity],['Grade',x=>x.grade],['Arrivals',x=>mt(x.arrivalQuantityMT)],['Modal',x=>money(x.modalPriceINRPerQtl)],['Desk',x=>pill('Synthetic','')]])}
function filterMarket(v){let a=[...D.market].sort((x,y)=>y.observationDate.localeCompare(x.observationDate));if(v!=='All commodities')a=a.filter(x=>x.commodity===v);el('marketTable').innerHTML=marketRows(a.slice(0,100));}
function inventory(){return `<div class="wrap"><div class="section-head"><div><h2>Inventory</h2><p>${D.inventory.length} stock lines across ${D.warehouses.length} warehouses</p></div></div><div class="cards"><div class="card metric"><label>Stock</label><strong>${mt(totals(D.inventory,'closingStockMT'))}</strong><small>current book position</small></div><div class="card metric"><label>Lots</label><strong>${D.lots.length}</strong><small>lot records</small></div><div class="card metric"><label>QC holds</label><strong>${D.lots.filter(x=>x.status==='QC Hold').length}</strong><small>requiring release</small></div><div class="card metric"><label>Warehouses</label><strong>${D.warehouses.length}</strong><small>operating locations</small></div></div><div class="panel section">${rows([...D.inventory].sort((a,b)=>b.closingStockMT-a.closingStockMT),[['SKU',x=>x.sku],['Commodity',x=>x.commodity],['Variety',x=>x.variety],['Grade',x=>x.grade],['Warehouse',x=>x.warehouse],['Closing',x=>mt(x.closingStockMT)],['Bags',x=>num(x.bags)],['Updated',x=>x.updated]])}</div></div>`}
function procurement(){return `<div class="wrap"><div class="section-head"><div><h2>Procurement</h2><p>${D.purchases.length} fictitious purchase entries</p></div></div><div class="cards"><div class="card metric"><label>Quantity purchased</label><strong>${mt(totals(D.purchases,'qtyMT'))}</strong></div><div class="card metric"><label>Purchase value</label><strong>${money(totals(D.purchases,'valueINR'))}</strong></div><div class="card metric"><label>Suppliers</label><strong>${D.suppliers.length}</strong></div><div class="card metric"><label>Receipts</label><strong>${D.receipts.length}</strong></div></div><div class="panel section">${rows([...D.purchases].sort((a,b)=>b.date.localeCompare(a.date)).slice(0,120),[['ID',x=>x.id],['Date',x=>x.date],['Supplier',x=>x.supplier],['Market',x=>x.market],['Commodity',x=>x.commodity],['Qty',x=>mt(x.qtyMT)],['Rate',x=>money(x.rateINRPerQtl)],['Value',x=>money(x.valueINR)],['Status',x=>pill(x.status,x.status==='Under QC'?'amber':'')]])}</div></div>`}
function salesView(){return `<div class="wrap"><div class="section-head"><div><h2>Sales</h2><p>${D.sales.length} fictitious customer sales entries</p></div></div><div class="cards"><div class="card metric"><label>Quantity sold</label><strong>${mt(totals(D.sales,'qtyMT'))}</strong></div><div class="card metric"><label>Sales value</label><strong>${money(totals(D.sales,'valueINR'))}</strong></div><div class="card metric"><label>Customers</label><strong>${D.customers.length}</strong></div><div class="card metric"><label>Dispatches</label><strong>${D.dispatches.length}</strong></div></div><div class="panel section">${rows([...D.sales].sort((a,b)=>b.date.localeCompare(a.date)).slice(0,120),[['ID',x=>x.id],['Date',x=>x.date],['Customer',x=>x.customer],['Commodity',x=>x.commodity],['Qty',x=>mt(x.qtyMT)],['Rate',x=>money(x.rateINRPerQtl)],['Value',x=>money(x.valueINR)],['Status',x=>pill(x.status)]])}</div></div>`}
function masters(kind){let a=D[kind];return `<div class="wrap"><div class="section-head"><div><h2>${kind[0].toUpperCase()+kind.slice(1)}</h2><p>${a.length} master records</p></div></div><div class="panel">${kind==='customers'?rows(a,[['Code',x=>x.code],['Customer',x=>x.name],['City',x=>x.city],['Segment',x=>x.segment],['Credit limit',x=>money(x.creditLimitINR)],['Outstanding',x=>money(x.outstandingINR)],['Exposure',x=>pill(x.outstandingINR>x.creditLimitINR*.8?'Watch':'Normal',x.outstandingINR>x.creditLimitINR*.8?'amber':'')]]):rows(a,[['Code',x=>x.code],['Supplier',x=>x.name],['City',x=>x.city],['Segment',x=>x.segment],['Credit days',x=>x.creditDays],['Status',x=>pill('Active')]])}</div></div>`}
function logistics(){return `<div class="wrap"><div class="section-head"><div><h2>Logistics</h2><p>${D.dispatches.length} dispatch records · ${D.vehicles.length} vehicles</p></div></div><div class="grid2"><div class="panel"><h2>Dispatch board</h2>${rows([...D.dispatches].sort((a,b)=>b.date.localeCompare(a.date)).slice(0,80),[['Date',x=>x.date],['Dispatch',x=>x.id],['Commodity',x=>x.commodity],['Qty',x=>mt(x.qtyMT)],['Vehicle',x=>x.vehicle],['Destination',x=>x.destination],['Status',x=>pill(x.status,x.status==='In Transit'?'amber':'')]])}</div><div class="panel"><h2>Fleet</h2>${rows(D.vehicles,[['Reg. no.',x=>x.regNo],['Vehicle',x=>x.model],['Ownership',x=>x.ownership],['Status',x=>pill(x.status,x.status==='Maintenance'?'amber':'')]])}</div></div></div>`}
function finance(){return `<div class="wrap"><div class="section-head"><div><h2>Finance</h2><p>Receipts, expenses and customer exposure</p></div></div><div class="cards"><div class="card metric"><label>Receipts posted</label><strong>${money(totals(D.payments,'amountINR'))}</strong></div><div class="card metric"><label>Expenses</label><strong>${money(totals(D.expenses,'amountINR'))}</strong></div><div class="card metric"><label>Receivables</label><strong>${money(D.customers.reduce((s,x)=>s+x.outstandingINR,0))}</strong></div><div class="card metric"><label>Payables snapshot</label><strong>${money(D.snapshots[D.snapshots.length-1].payableINR)}</strong></div></div><div class="grid2 section"><div class="panel"><h2>Receipts</h2>${rows(D.payments.slice(0,80),[['ID',x=>x.id],['Date',x=>x.date],['Party',x=>x.party],['Amount',x=>money(x.amountINR)],['Mode',x=>x.mode],['Status',x=>pill(x.status,x.status==='Pending'?'amber':'')]])}</div><div class="panel"><h2>Expenses</h2>${rows(D.expenses.slice(0,80),[['ID',x=>x.id],['Date',x=>x.date],['Category',x=>x.category],['Amount',x=>money(x.amountINR)],['Status',x=>pill(x.status)]])}</div></div></div>`}
function quality(){return `<div class="wrap"><div class="section-head"><div><h2>Quality & Lots</h2><p>Lot control and release status</p></div></div><div class="panel">${rows(D.lots.slice(0,140),[['Lot',x=>x.lotId],['Commodity',x=>x.commodity],['Warehouse',x=>x.warehouse],['Qty',x=>mt(x.qtyMT)],['Grade',x=>x.grade],['Status',x=>pill(x.status,x.status==='QC Hold'?'amber':'')]])}</div></div>`}
function reports(){let pv=totals(D.purchases,'valueINR'),sv=totals(D.sales,'valueINR');return `<div class="wrap"><div class="section-head"><div><h2>Reports</h2><p>Management summaries from the demonstration dataset</p></div></div><div class="grid2"><div class="panel"><h2>20-day trading trend</h2>${rows(D.snapshots,[['Date',x=>x.date],['Purchases',x=>mt(x.purchasesMT)],['Sales',x=>mt(x.salesMT)],['Stock',x=>mt(x.closingStockMT)],['Receivables',x=>money(x.receivableINR)],['Payables',x=>money(x.payableINR)]])}</div><div class="panel"><h2>Business scale</h2><div class="mini-grid"><div class="mini"><b>${D.purchases.length}</b><span>Purchase entries</span></div><div class="mini"><b>${D.sales.length}</b><span>Sales entries</span></div><div class="mini"><b>${D.receipts.length}</b><span>GRNs</span></div><div class="mini"><b>${D.dispatches.length}</b><span>Dispatches</span></div><div class="mini"><b>${D.lots.length}</b><span>Lots</span></div><div class="mini"><b>${D.market.length}</b><span>Market observations</span></div></div><p class="note">Purchase value ${money(pv)} · Sales value ${money(sv)}. All figures are synthetic.</p></div></div></div>`}
const titles=Object.fromEntries(nav.map(x=>[x[0],x[2]]));
function render(){el('content').innerHTML={dashboard,market,inventory,procurement,sales:salesView,customers:()=>masters('customers'),suppliers:()=>masters('suppliers'),logistics,finance,quality,reports}[view]();el('pageTitle').textContent=titles[view];document.querySelectorAll('.nav').forEach(b=>b.classList.toggle('active',b.dataset.view===view));}
el('nav').innerHTML=nav.map(x=>`<button class="nav ${x[0]==='dashboard'?'active':''}" data-view="${x[0]}">${x[1]} <span>${x[2]}</span></button>`).join('');document.querySelectorAll('.nav').forEach(b=>b.onclick=()=>{view=b.dataset.view;render()});render();

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,601 @@
# Product Requirements Document (PRD) / User Requirements Specification (URS)
# Agricultural Mandi Trader App (AMTP)
| Field | Value |
|---|---|
| **Document** | `PRD_Specification.md` (Comprehensive Production-Grade URS) |
| **Product** | Agricultural Mandi Trader App (`AMTP`) |
| **Version** | 1.1.0 (Detailed Operational Baseline) |
| **Author** | `@requirements-analyst` (`up-requirements-elicit`) |
| **Governance Standard** | SEI-CMMI Level 3 (AI-Native Unified Process UP-AI v1.3) |
| **Status** | Baselined |
| **Last Updated** | 2026-10-09 |
---
## 1. Executive Summary & Problem Statement
### 1.1 The Business Need
Wholesale physical agricultural commodity trading in India's Agricultural Produce Market Committee (APMC) mandis (such as Neemuch, Mandsaur, Ratlam, Kota, and Indore) involves fast-paced daily auctions, high financial exposure, multi-warehouse storage, and strict quality grading.
Wholesale trading firms and licensed commission agents (*arhatiyas*) handle dozens of truckloads daily across dry-agri commodities (pulses, oilseeds, grains, and spices such as chickpea/chana, soybean, mustard seed, coriander seed, cumin seed, fenugreek, turmeric, and wheat). Trading firms currently struggle with:
1. **Disconnected Paper Slips (*Sauda Buhis*):** Auction purchase commitments made in the mandi yard are not reflected in real time at the godowns, causing intake delays, truck detention, and weighbridge disputes.
2. **Dual-Unit Commercial Complexity:** Trading rates are quoted strictly in Indian Rupees per Quintal (₹/Qtl), whereas physical freight, warehouse capacity, and bookkeeping operate in Metric Tonnes (MT) and physical bag counts (*kattha/bora*). Manual math frequently causes billing errors.
3. **Quality & Lot Segregation Risks:** Consignments arriving with high moisture or impurities are accidentally mixed into clean warehouse stacks because quality inspection holds (*QC Hold*) are not enforced by software gates.
4. **Unhedged Customer Credit Exposure:** Customers frequently buy on credit terms (e.g., 7–15 days). Without real-time exposure monitoring, sales desks book orders for customers who have exceeded their sanctioned credit limit, leading to severe bad debt.
5. **Multi-Godown Blind Spots:** Stock balances across multiple transit and buffer godowns are reconciled manually at day-end, preventing real-time commitment of available inventory to buyers.
### 1.2 Target Operating Model
The **Agricultural Mandi Trader App (`AMTP`)** is a dedicated, modular, multi-tenant enterprise back-office and trading operations platform built on the **Frappe Framework**. It establishes an unbroken digital chain across 11 core functional modules:
```
Market Desk (Arrivals & Modal Price)
│
▼
Procurement (Auction Sauda Booking) ──► Inward Weighbridge (Gross/Tare/Bags)
│
▼
Godown Intake & Lot ID Generation
│
▼
Lab QC Inspection (QC Hold / Release)
│
▼
Customer Sales Contract ◄────────────── Available Warehouse Stock (MT & Bags)
│
▼
Credit Limit Check (≤80% / Breach Block)
│
▼
Outbound Dispatch Board ──► Transport Fleet Scheduling ──► Outward Weighbridge
│
▼
Customer Receivables Ledger
```
### 1.3 Key Performance Indicators (KPIs)
- **100% End-to-End Lot Traceability:** Unique lot consignment tracking from supplier auction purchase through weighbridge intake, lab test, godown stack, and outbound customer dispatch.
- **Zero Accidental QC Hold Dispatches:** 100% backend programmatic prevention of allocating or dispatching any lot with `status != 'Released'`.
- **Zero Unapproved Credit Limit Breaches:** 100% programmatic enforcement blocking sales order dispatch when customer receivables exceed sanctioned credit limits without executive override.
- **Sub-Second Inventory & Dual-Unit Reconciliation:** Immediate stock ledger balance updates across Metric Tonnes, Quintals, and Bag counts with mathematical consistency:
$$\text{Value (INR)} = \text{Quantity (MT)} \times 10 \times \text{Rate (₹/Qtl)}$$
---
## 2. Target Personas & User Classes
| Persona | Role / Designation | Core Responsibilities & System Permissions |
|---|---|---|
| **Partner / Managing Director** | Executive Management | Full strategic oversight; reviews daily trading snapshots, net P&L metrics, operational alerts, cash flow, and holds exclusive authority for credit-limit override approvals. |
| **Purchase Manager** | Procurement Lead | Manages supplier relationships, monitors mandi auction windows, negotiates rates, reviews purchase vs. market modal rate variances, and approves purchase saudas. |
| **Procurement Executive** | Mandi Field Buyer | Enters daily mandi auction purchases, tracks arrival volumes, and logs daily market desk price observations directly from mandi yards. |
| **Sales Manager** | Commercial Lead | Evaluates customer inquiries, negotiates sales contracts, monitors customer credit exposure, approves sales contracts, and allocates inventory. |
| **Sales Executive** | Field / Desk Sales | Inputs customer sales orders, tracks order fulfillment stages, and communicates dispatch details to buyers. |
| **Yard Supervisor / Godown Keeper** | Warehouse Operations | Manages godown intake, operates weighbridge gross/tare weighment, verifies physical bag counts (*bardana tally*), manages stack placement, and oversees dispatch loading. |
| **Quality Officer** | Quality Inspection & Lab | Inspects inward lots, performs physical/lab sampling (moisture %, foreign matter %, damaged grains), enters test results, and toggles FSM states (`QC Hold` vs. `Released`). |
| **Logistics Coordinator** | Transport & Fleet | Coordinates carrier fleet (owned and contracted trucks), assigns vehicles to dispatches, generates dispatch bilties/manifests, and monitors transit status. |
| **Accounts Executive** | Finance & Accounting | Records customer payment receipts (NEFT/RTGS/Cheque/Cash), maintains supplier payables aging ledgers, records operational expense vouchers, and reconciles balances. |
| **System Administrator** | Technical Governance | Manages Frappe site tenancy, user accounts, DocType role permissions, master catalogs, system configuration, and audit trails. |
---
## 3. Mathematical & Commercial Calculation Engine Standards
### 3.1 Dual-Unit Conversion Engine
In Indian agricultural markets, rates are quoted in **₹ per Quintal**, while transport and inventory operate in **Metric Tonnes (MT)** and **Bags**:
1. **Metric Unit Definitions:**
- $1\text{ Metric Tonne (MT)} = 1,000\text{ Kilograms (kg)}$
- $1\text{ Quintal (Qtl)} = 100\text{ Kilograms (kg)} = 0.100\text{ MT}$
- $1\text{ Metric Tonne (MT)} = 10.0\text{ Quintals (Qtl)}$
2. **Gross Trade Value Formula:**
$$\text{Value (INR)} = \text{Quantity (MT)} \times 10 \times \text{Rate (₹/Qtl)}$$
*Example: $24.0\text{ MT}$ of Coriander seed at $₹4,486\text{ / Qtl} \implies 24.0 \times 10 \times 4486 = ₹1,076,640$.*
3. **Bag Packing Standard:**
$$\text{Average Bag Weight (kg)} = \frac{\text{Net Weight (MT)} \times 1000}{\text{Bag Count}}$$
Standard nominal packing is 50 kg or 100 kg per bag.
### 3.2 Inward Weighbridge & Bag Tare Deduction (*Bardana Katai*)
1. **Net Truck Weight:**
$$\text{Gross Truck Weight (kg)} - \text{Tare Truck Weight (kg)} = \text{Unloaded Gross Commodity Weight (kg)}$$
2. **Bag Tare Deduction (*Bardana Katai*):**
$$\text{Tare Bag Deduction (kg)} = \text{Bag Count} \times \text{Tare Weight Per Bag (kg)}$$
*(Default standard: 1.0 kg per gunny/jute bag, 0.2 kg per HDPE/plastic bag).*
3. **Net Payable Weight:**
$$\text{Net Weight (MT)} = \frac{\text{Unloaded Gross Commodity Weight (kg)} - \text{Tare Bag Deduction (kg)}}{1000}$$
4. **Weighment Shortage / Variance Calculation:**
$$\text{Variance \%} = \frac{\text{Actual Net Weighbridge MT} - \text{Booked Purchase MT}}{\text{Booked Purchase MT}} \times 100$$
- If $|\text{Variance \%}| \le 0.5\%$: Auto-accepted within normal mandi weighment tolerance.
- If $\text{Variance \%} < -0.5\%$: Shortage flagged; net payable MT adjusted to actual weighbridge receipt.
### 3.3 Customer Credit Exposure & Risk Engine
$$\text{Current Exposure (INR)} = \text{Total Outstanding Unpaid Receivables (INR)} + \text{Unbilled Confirmed Orders (INR)}$$
$$\text{Exposure Ratio \%} = \frac{\text{Current Exposure (INR)}}{\text{Sanctioned Credit Limit (INR)}} \times 100$$
- **Normal Zone ($\le 80\%$):** Sales orders and dispatches proceed without restriction.
- **Watch Warning Zone ($>80\%$ and $\le 100\%$):** System issues an automated Warning Alert; sales entry flags account on **Watch**.
- **Breach Block Zone ($>100\%$):** System enforces a **Hard Block**; order cannot transition to `Confirmed` or `Dispatched` without recorded Partner / MD approval.
---
## 4. Finite State Machines (FSMs) & Lifecycle Contracts
### 4.1 Purchase Sauda FSM
```
[Draft] ──► [Booked] ──► [Gate Inward] ──► [Under QC] ──► [Received / Closed]
│ │
▼ ▼
[Cancelled] [Rejected]
```
- `Draft`: Initial booking entered by Mandi Buyer.
- `Booked`: Sauda confirmed with supplier and market rate locked.
- `Gate Inward`: Truck arrived at godown gate; weighbridge gross weight captured.
- `Under QC`: Commodity unloaded; lot minted; awaiting lab test sign-off.
- `Received / Closed`: QC accepted; net tare calculated; GRN posted; inventory credited.
- `Rejected`: Commodity failed quality thresholds; gate pass issued for return to supplier.
### 4.2 Commodity Lot FSM
```
[Generated] ──► [Under QC] ──┬──► [Released] (Available for Allocation & Dispatch)
│
└──► [QC Hold] ──► [Released] (Post Remediation/Approval)
│
└──► [Rejected / Disposal]
```
- `Under QC`: Initial state upon godown unloading. Cannot be linked to sales orders.
- `QC Hold`: Flagged for excessive moisture, foreign matter, or quality dispute. Hard-locked against sales reservation and loading.
- `Released`: Lab approved. Eligible for sales order allocation and dispatch board loading.
- `Rejected`: Unfit for trade; flagged for return or discounted salvage.
### 4.3 Sales Order & Dispatch Board FSM
```
[Draft] ──► [Confirmed] ──► [Allocated] ──► [Loading] ──► [In Transit] ──► [Delivered]
│ │
▼ ▼
[Cancelled] [Order Hold]
```
- `Draft`: Customer inquiry and pricing quote.
- `Confirmed`: Credit check passed; sales contract ratified.
- `Allocated`: Released inventory lot(s) tagged to order.
- `Loading`: Transport vehicle assigned; bags being loaded onto truck.
- `In Transit`: Outward weighbridge completed; dispatch bilty generated; truck en route.
- `Delivered`: Consignee proof of delivery (POD) acknowledged; sales invoice finalized.
---
## 5. Comprehensive Granular Feature Inventory (`BRD-FR-xxx`)
Every discrete requirement carries a unique `BRD-FR-xxx` root ID, detailed operational statement, input/output data attributes, validation rules, and failure modes.
### 5.1 Module 1: Market Desk & Daily Mandi Intelligence
#### `BRD-FR-001`: Daily APMC Mandi Arrival Ingestion & Tracking
- **Owning Module:** Market Desk
- **Primary Persona:** Procurement Executive / Mandi Buyer
- **Priority:** P0
- **Operational Statement:** The system must record daily physical arrival volumes at APMC mandi yards across target commodities (Chana, Coriander, Cumin, Fenugreek, Groundnut, Isabgol, Jaggery, Maize, Mustard, Soybean, Turmeric, Wheat) across monitored markets (Neemuch, Mandsaur, Ratlam, Kota, Indore, Jaora, Ujjain, Chittorgarh).
- **Data Attributes:** Observation Date, Market Yard, Commodity, Variety, Grade, Arrival Quantity in MT, Internal Stock Position in MT, Observation Source, Timestamp.
- **Validation Rules:** Observation date cannot be in the future. Arrival quantity must be $\ge 0.0\text{ MT}$. Duplicate observation for same market, commodity, variety, and date must be blocked.
- **Failure / Exception Flow:** If arrival data is unavailable for a holiday/strike, system must allow flagging the market as `Closed / Mandi Holiday`.
#### `BRD-FR-002`: Daily Modal & Range Pricing Tracking (₹/Qtl)
- **Owning Module:** Market Desk
- **Primary Persona:** Procurement Executive / Purchase Manager
- **Priority:** P0
- **Operational Statement:** For each daily mandi arrival record, the system must capture the quoted price range (Min Rate ₹/Qtl, Max Rate ₹/Qtl) and the official modal clearing price (Modal Rate ₹/Qtl).
- **Data Attributes:** Quoted Min Rate (₹/Qtl), Quoted Max Rate (₹/Qtl), Modal Clearing Rate (₹/Qtl).
- **Validation Rules:** $\text{Min Rate} \le \text{Modal Rate} \le \text{Max Rate}$. All rates must be $> 0$.
- **Failure / Exception Flow:** If user inputs Modal Rate outside the Min-Max range, validation must reject save with an explicit arithmetic constraint error.
#### `BRD-FR-003`: Intraday Price Trend Analysis & 20-Day Benchmark Analytics
- **Owning Module:** Market Desk
- **Primary Persona:** Purchase Manager / Partner
- **Priority:** P0
- **Operational Statement:** The system must provide interactive visual charts and trend tables comparing the 20-day historical modal rate trend per commodity across markets, computing 20-day moving averages, 20-day highs/lows, and price velocity.
- **Data Attributes:** Historical Date Range, Commodity Filter, Market Filter, 20-Day SMA (Simple Moving Average), Price Spread.
- **Validation Rules:** Calculations must dynamically update upon new observation save. Execution time $\le 500\text{ms}$.
#### `BRD-FR-004`: Procurement Price Variance Alert vs. Modal Rate
- **Owning Module:** Market Desk & Procurement
- **Primary Persona:** Purchase Manager
- **Priority:** P1
- **Operational Statement:** When booking a purchase sauda, the system must compare the offered trade rate against the latest modal clearing rate for that commodity/mandi. If the offered rate exceeds the modal rate by $>5\%$, the system must display an inline warning and require confirmation.
- **Data Attributes:** Offered Rate, Benchmark Modal Rate, Variance \%.
- **Validation Rules:** Informational alert only; does not hard-block procurement unless configured in company policy.
---
### 5.2 Module 2: Mandi Procurement & Auction Purchases (Sauda)
#### `BRD-FR-005`: Mandi Auction & Direct Purchase Sauda Booking
- **Owning Module:** Procurement
- **Primary Persona:** Procurement Executive / Purchase Manager
- **Priority:** P0
- **Operational Statement:** The system must record purchase contracts (*saudas*) negotiated in mandi auctions or directly with suppliers. Each sauda must capture supplier code, sourcing market, commodity, variety, trade rate (₹/Qtl), estimated bag count, and booked quantity in MT. The system must support multi-truck partial delivery: a sauda may be fulfilled across multiple trucks/GRNs over consecutive delivery days, tracking cumulative received MT and remaining balance MT until fully fulfilled.
- **Data Attributes:** Sauda ID (`PUR-YYYYMM-xxx`), Sauda Date, Supplier ID, Sourcing Mandi, Commodity, Variety, Booked Qty MT, Estimated Bags, Trade Rate (₹/Qtl), Gross Value INR, Cumulative Received MT, Remaining Balance MT, Status.
- **Validation Rules:** Supplier must be an active master record. Booked MT must be $> 0$. Trade rate must be $> 0$. Gross value must equal $\text{Booked MT} \times 10 \times \text{Rate}$. Status remains `Partially Received` until cumulative received MT reaches booked MT (within tolerance) or explicitly closed by Purchase Manager.
- **Failure / Exception Flow:** If supplier is deactivated or blacklisted, booking must be blocked.
#### `BRD-FR-006`: Supplier Credit Terms & Due Date Computation
- **Owning Module:** Procurement & Finance
- **Primary Persona:** Purchase Manager / Accounts Executive
- **Priority:** P0
- **Operational Statement:** The system must automatically compute the supplier payment due date by adding the supplier's contractual credit days (e.g., 7, 15, or 21 days) to the sauda or GRN receipt date.
- **Data Attributes:** Supplier Credit Days, Transaction Date, Computed Due Date, Payment Status (`Pending`, `Paid`).
- **Validation Rules:** Default credit days inherited from Supplier master; editable only by Purchase Manager.
#### `BRD-FR-007`: Mandi Cess & Statutory Levies Apportioning
- **Owning Module:** Procurement & Finance
- **Primary Persona:** Accounts Executive
- **Priority:** P1
- **Operational Statement:** The system must calculate statutory mandi cess (e.g., 1.5% APMC market fee + 0.2% Nirashrit fee) based on the gross sauda value and append it to the total procurement cost.
- **Data Attributes:** Mandi Cess Rate %, Cess Amount INR, Total Landed Procurement Cost INR.
- **Validation Rules:** Configurable per commodity and market jurisdiction.
---
### 5.3 Module 3: Inward Weighbridge & Goods Receipt (GRN)
#### `BRD-FR-008`: Inward Vehicle Gate Entry & Verification
- **Owning Module:** Goods Receipt
- **Primary Persona:** Yard Supervisor
- **Priority:** P0
- **Operational Statement:** Upon vehicle arrival at the godown, the Yard Supervisor must log gate entry linking the vehicle registration number and driver details to an active booked sauda.
- **Data Attributes:** Gate Entry ID, Inward Date/Time, Vehicle Reg No, Driver Name, Contact No, Linked Sauda ID, Supplier Name, Gate Pass No.
- **Validation Rules:** Linked sauda must be in state `Booked`.
#### `BRD-FR-009`: Weighbridge Gross & Tare Weighment Logging
- **Owning Module:** Goods Receipt
- **Primary Persona:** Yard Supervisor
- **Priority:** P0
- **Operational Statement:** The system must record dual-phase weighbridge measurements for incoming trucks: (1) Gross Weighment (truck + commodity) upon arrival, and (2) Tare Weighment (empty truck) after unloading.
- **Data Attributes:** Gross Weight kg, Gross Timestamp, Tare Weight kg, Tare Timestamp, Gross Net Weight kg ($Gross - Tare$), Weighbridge Slip No.
- **Validation Rules:** $\text{Gross Weight} > \text{Tare Weight} > 0$. Weighbridge slip number mandatory.
- **Failure / Exception Flow:** If Tare Weight $\ge$ Gross Weight, system must hard-block submission with an error.
#### `BRD-FR-010`: Bag Tare Deduction (*Bardana Katai*) & Final Net MT
- **Owning Module:** Goods Receipt
- **Primary Persona:** Yard Supervisor
- **Priority:** P0
- **Operational Statement:** The system must deduct the weight of packaging bags from the gross commodity weight using the defined tare deduction factor (default 1.0 kg/gunny bag) to calculate true Net Payable MT.
- **Data Attributes:** Physical Bag Count, Packaging Type (`Gunny/Jute`, `HDPE/Plastic`), Bag Tare Deduction Rate kg/bag, Total Bag Tare kg, Final Net Weight MT.
- **Validation Rules:** Formula: $\text{Net MT} = (\text{Gross kg} - \text{Tare kg} - (\text{Bags} \times \text{Bag Tare Rate})) / 1000$. Net MT must be $> 0$.
#### `BRD-FR-011`: Weighment Tolerance & Transit Shortage Verification
- **Owning Module:** Goods Receipt
- **Primary Persona:** Yard Supervisor / Purchase Manager
- **Priority:** P0
- **Operational Statement:** The system must compare the Final Net Weighbridge MT against the Booked Sauda MT. If shortage exceeds $0.5\%$, the system must flag a `Transit Shortage Warning` and adjust the final payable amount to the actual net received weight.
- **Data Attributes:** Shortage MT, Shortage Value INR, Variance \%, Shortage Status (`Normal`, `Disputed`).
- **Validation Rules:** If shortage exceeds $2.0\%$, the GRN requires mandatory Purchase Manager approval before stock posting.
#### `BRD-FR-012`: Goods Receipt Note (GRN) Posting & Warehouse Stack Placement
- **Owning Module:** Goods Receipt & Inventory
- **Primary Persona:** Yard Supervisor
- **Priority:** P0
- **Operational Statement:** Upon weighment completion, the system must generate a formal GRN document, allocate the physical goods to a specific warehouse/godown and stack location, credit the warehouse stock book, and mint an inward Commodity Lot.
- **Data Attributes:** GRN ID (`GRN-YYYYMM-xxx`), Receiving Warehouse ID, Stack/Chamber No, Accepted Bags, Accepted Net MT.
- **Validation Rules:** GRN submission atomically updates inventory and creates Lot record in state `Under QC`.
---
### 5.4 Module 4: Quality Inspection & Lot Control
#### `BRD-FR-013`: Mandatory Lot & Batch Identity Generation
- **Owning Module:** Quality & Inventory
- **Primary Persona:** Yard Supervisor / Quality Officer
- **Priority:** P0
- **Operational Statement:** The system must automatically generate a globally unique, immutable Lot ID (`LOT-YYYYMM-xxx`) for every inward consignment processed through a GRN.
- **Data Attributes:** Lot ID, Inward Date, Origin Market, Supplier ID, Commodity, Variety, Receiving Warehouse, Net MT, Bag Count, Quality Status.
- **Validation Rules:** Initial status must be `Under QC`. Lot ID must be permanent and traceable through all sales and dispatches.
#### `BRD-FR-014`: Inward Quality Inspection Parameter Recording
- **Owning Module:** Quality Control
- **Primary Persona:** Quality Officer
- **Priority:** P0
- **Operational Statement:** The Quality Officer must log laboratory/physical test parameters for the lot: Moisture %, Foreign Matter / Dust %, Admixture (other grains) %, Damaged / Discolored %, and Weevil count.
- **Data Attributes:** Inspection Date, Quality Officer ID, Moisture %, Foreign Matter %, Admixture %, Damaged %, Weevil Infestation (`None`, `Mild`, `Severe`), Assigned Commercial Grade (`FAQ`, `Premium`, `Below FAQ`).
- **Validation Rules:** Percentage values must be between $0.00\%$ and $100.00\%$.
#### `BRD-FR-015`: Quality Deduction / Rebate Calculation
- **Owning Module:** Quality Control & Finance
- **Primary Persona:** Quality Officer / Accounts Executive
- **Priority:** P1
- **Operational Statement:** If moisture or foreign matter exceeds standard contract baselines (e.g., standard moisture baseline 10.0%), the system must automatically compute a quality price deduction (e.g., ₹10 deduction per quintal for each 0.5% moisture above baseline).
- **Data Attributes:** Base Contract Rate ₹/Qtl, Quality Penalty Rate ₹/Qtl, Adjusted Final Rate ₹/Qtl, Net Purchase Adjustment INR.
- **Validation Rules:** Deductions cannot reduce rate below 50% of base rate without partner authorization.
#### `BRD-FR-016`: Finite State Machine Enforcement for `QC Hold` vs. `Released`
- **Owning Module:** Quality Control
- **Primary Persona:** Quality Officer
- **Priority:** P0
- **Operational Statement:** The system must enforce strict FSM transitions on the Lot record. If moisture $>12\%$ or foreign matter $>2\%$, the lot must be transitioned to `QC Hold`. A lot on `QC Hold` is programmatically blocked from sales order allocation and dispatch loading.
- **Data Attributes:** Previous Status, New Status (`QC Hold`, `Released`), Hold Reason, Action Plan (`Drying`, `Cleaning`, `Re-testing`), Release Timestamp.
- **Validation Rules:** Only users with `Quality Officer` or `Partner` roles can transition a lot from `QC Hold` to `Released`. System must hard-block dispatch of unreleased lots.
#### `BRD-FR-017`: Lot Splitting & Blending Traceability
- **Owning Module:** Quality & Inventory
- **Primary Persona:** Yard Supervisor / Quality Officer
- **Priority:** P1
- **Operational Statement:** The system must support splitting a parent lot into sub-lots (e.g., when dividing a consignment across two warehouses) or blending multiple lots, maintaining parent-child lineage in the traceability graph.
- **Data Attributes:** Parent Lot ID, Child Lot ID(s), Split Qty MT, Split Bag Count, Linage Tree.
- **Validation Rules:** Sum of child lot quantities must exactly equal parent quantity deducted.
---
### 5.5 Module 5: Multi-Godown Warehouse Inventory
#### `BRD-FR-018`: Multi-Godown Dual-Unit Stock Ledger
- **Owning Module:** Inventory
- **Primary Persona:** Yard Supervisor / Management
- **Priority:** P0
- **Operational Statement:** The system must maintain a real-time, double-entry stock ledger tracking commodity positions across warehouses (WH-01 Neemuch Main Yard, WH-02 Neemuch North Godown, WH-03 Mandsaur Transit Godown, WH-04 Indore Buffer Depot). For each commodity, variety, and grade, it must maintain Opening Stock MT, Received MT, Dispatched MT, Closing Stock MT, and physical Bag counts. The system must support Periodic Physical Stock Audits: recording physical tally counts against book balances and generating supervisor-authorized Stock Adjustment Vouchers capturing natural storage loss/gain (*ghat / nami* due to moisture evaporation or seasonal humidity) or handling spillage with mandatory reason codes.
- **Data Attributes:** Stock Entry ID, Date, Warehouse ID, Commodity, Variety, Grade, Opening MT, Inward MT, Outward MT, Closing MT, Bag Delta, Closing Bags, Physical Count MT, Adjustment Variance MT, Variance Reason Code (`Moisture Loss / Ghat`, `Handling Spillage`, `Bag Burst`, `Seasonal Humidity Gain`).
- **Validation Rules:** Closing stock MT and bags must never be negative ($\ge 0$). Adjustments exceeding $\pm 1.0\%$ of godown balance require mandatory Partner electronic sign-off.
#### `BRD-FR-019`: Godown Capacity & Volume Utilization Tracking
- **Owning Module:** Inventory
- **Primary Persona:** Yard Supervisor / Partner
- **Priority:** P0
- **Operational Statement:** The system must track the physical storage capacity of each warehouse in Metric Tonnes and calculate real-time percentage utilization:
$$\text{Utilisation \%} = \frac{\text{Current Closing Stock (MT)}}{\text{Storage Capacity (MT)}} \times 100$$
- **Data Attributes:** Warehouse ID, Name, City, Capacity MT, Current Stock MT, Utilisation \%.
- **Validation Rules:** Warning status triggered when Utilisation exceeds 85%.
#### `BRD-FR-020`: Godown-to-Godown Internal Stock Transfer
- **Owning Module:** Inventory & Logistics
- **Primary Persona:** Yard Supervisor / Logistics Coordinator
- **Priority:** P0
- **Operational Statement:** The system must support recording stock transfers between godowns (e.g., from Mandsaur Transit Godown to Neemuch Main Yard), logging origin outward deduction, in-transit state, destination weighment, and destination inward credit.
- **Data Attributes:** Transfer ID, Origin Warehouse, Destination Warehouse, Commodity, Lot ID, Transfer Qty MT, Transfer Bags, Vehicle Reg No, Transit Status.
- **Validation Rules:** Outward and inward entries must reconcile within $\pm 0.2\%$ transfer tolerance.
---
### 5.6 Module 6: Customer Sales Contracts & Orders
#### `BRD-FR-021`: Customer Sales Contract Booking
- **Owning Module:** Sales
- **Primary Persona:** Sales Manager / Sales Executive
- **Priority:** P0
- **Operational Statement:** The system must record customer sales orders/contracts specifying customer code, destination city, customer segment (`Wholesale`, `Processor`, `Institutional`, `Distributor`), commodity, variety, grade, contracted quantity in MT, contract rate in ₹/Qtl, and delivery timeline.
- **Data Attributes:** Sales Order ID (`SAL-YYYYMM-xxx`), Order Date, Customer ID, Destination City, Commodity, Variety, Grade, Contract Qty MT, Contract Rate ₹/Qtl, Total Sales Value INR, Payment Terms, Status.
- **Validation Rules:** Total Sales Value must equal $\text{Contract Qty MT} \times 10 \times \text{Rate ₹/Qtl}$.
#### `BRD-FR-022`: Customer Credit Limit & Pre-Order Exposure Verification
- **Owning Module:** Sales & Finance
- **Primary Persona:** Sales Manager / Accounts Executive
- **Priority:** P0
- **Operational Statement:** Prior to confirming a sales order, the system must evaluate the customer's current outstanding receivables plus the value of the new order against their sanctioned credit limit.
- **Data Attributes:** Sanctioned Credit Limit INR, Current Outstanding INR, New Order Value INR, Projected Exposure INR, Projected Exposure Ratio \%.
- **Validation Rules:** If Projected Exposure Ratio $>80\%$, display inline warning. If Projected Exposure Ratio $>100\%$, system must prevent order confirmation unless authorized by Partner.
#### `BRD-FR-023`: Sales Order Inventory Allocation
- **Owning Module:** Sales & Inventory
- **Primary Persona:** Sales Manager / Yard Supervisor
- **Priority:** P0
- **Operational Statement:** The Sales Manager must allocate specific available inventory lot(s) from a warehouse to a confirmed sales order. The system must verify that selected lots are in `Released` state and have sufficient unreserved balance.
- **Data Attributes:** Sales Order ID, Allocated Lot ID, Allocated Qty MT, Allocated Bags, Warehouse ID.
- **Validation Rules:** Allocation fails if Lot status is `QC Hold` or `Under QC`, or if available lot unreserved MT $<$ allocated MT.
---
### 5.7 Module 7: Outbound Logistics & Dispatch Board
#### `BRD-FR-024`: Outbound Dispatch Board Console
- **Owning Module:** Logistics
- **Primary Persona:** Logistics Coordinator
- **Priority:** P0
- **Operational Statement:** The system must provide a visual dispatch management board displaying scheduled, loading, and in-transit consignments, matching confirmed sales orders to allocated warehouse lots and transport vehicles.
- **Data Attributes:** Dispatch ID (`DISP-YYYYMM-xxx`), Dispatch Date, Linked Sales Order ID, Customer Name, Destination City, Commodity, Dispatch Qty MT, Assigned Vehicle Reg No, Driver Details, Status (`Scheduled`, `Loading`, `In Transit`, `Delivered`).
- **Validation Rules:** Dispatch cannot be created without an approved sales order and assigned vehicle.
#### `BRD-FR-025`: Outbound Weighbridge & Dispatch Bilty/Manifest
- **Owning Module:** Logistics & Weighbridge
- **Primary Persona:** Yard Supervisor / Logistics Coordinator
- **Priority:** P0
- **Operational Statement:** The system must capture outward weighbridge weights for loaded dispatch trucks (Tare truck before loading, Gross truck after loading), verify loaded weight against order MT, and generate a printable transport manifest / Bilty.
- **Data Attributes:** Dispatch ID, Outward Tare kg, Outward Gross kg, Net Loaded MT, Loaded Bag Count, Transporter Bilty No, e-Way Bill No.
- **Validation Rules:** Net loaded MT must match allocated order MT within $\pm 1.0\%$ loading tolerance.
#### `BRD-FR-026`: In-Transit Tracking & Proof of Delivery (POD)
- **Owning Module:** Logistics
- **Primary Persona:** Logistics Coordinator
- **Priority:** P0
- **Operational Statement:** The system must track dispatch states from `In Transit` to `Delivered`. Upon consignee receipt, the Logistics Coordinator logs confirmation date, destination weighment, and uploads POD document reference. If destination weighment or quality parameters reveal a transit shortage or damage acknowledged by the buyer, the system must allow recording a Consignee Shortage Note and automatically generating a compensating Sales Credit Note against the customer ledger without altering the immutable outbound dispatch manifest.
- **Data Attributes:** Transit Status, Departure Date/Time, Expected Delivery Date, Actual Delivery Date, Destination Weighbridge Net MT, Transit Loss MT, Consignee Acknowledgement Note, POD Ref, Credit Note ID (if applicable).
- **Validation Rules:** Setting status to `Delivered` triggers automatic generation of finalized Sales Invoice. Consignee shortage deductions exceeding 2.0% require mandatory Sales Manager approval before issuing Credit Note.
---
### 5.8 Module 8: Fleet & Vehicle Management
#### `BRD-FR-027`: Transport Fleet Registry
- **Owning Module:** Logistics & Fleet
- **Primary Persona:** Logistics Coordinator
- **Priority:** P1
- **Operational Statement:** The system must maintain a registry of transport trucks (owned and contract carriers) including registration number, vehicle model, gross payload capacity in MT, ownership type (`Own` vs `Contract`), insurance/fitness expiry dates, and operational status (`Available`, `On Route`, `Maintenance`).
- **Data Attributes:** Vehicle Reg No, Make/Model, Payload Capacity MT, Ownership Type, Transporter Name, Status, Fitness Expiry Date.
- **Validation Rules:** Vehicles with status `Maintenance` cannot be assigned to dispatches.
---
### 5.9 Module 9: Customer Receivables & Exposure Management
#### `BRD-FR-028`: Customer Ledger & Aging Statement
- **Owning Module:** Finance
- **Primary Persona:** Accounts Executive / Sales Manager
- **Priority:** P0
- **Operational Statement:** The system must maintain an immutable party sub-ledger for each customer, debiting finalized sales invoices, crediting payment receipts, and presenting a real-time outstanding balance and aging schedule (0–7 days, 8–15 days, 16–30 days, >30 days).
- **Data Attributes:** Customer ID, Posting Date, Voucher Type (`Sales Invoice`, `Payment Receipt`), Voucher No, Debit Amount INR, Credit Amount INR, Running Outstanding INR.
- **Validation Rules:** Sub-ledger entries are immutable; corrections require credit/debit adjustment vouchers.
#### `BRD-FR-029`: Automated Customer Credit Exposure Watch & Threshold Alert
- **Owning Module:** Finance & Alerts
- **Primary Persona:** Accounts Executive / Partner
- **Priority:** P0
- **Operational Statement:** The system must continuously recompute the customer exposure ratio ($\text{Outstanding} / \text{Credit Limit}$). If exposure $>80\%$, the account must be automatically tagged with a visual `Watch` badge, and an operational warning alert generated on the Executive Dashboard.
- **Data Attributes:** Customer Code, Customer Name, Sanctioned Credit Limit INR, Outstanding INR, Exposure %, Risk Flag (`Normal`, `Watch`, `Critical`).
- **Validation Rules:** Evaluated in real time upon every sales invoice post and payment receipt post.
#### `BRD-FR-030`: Credit Breach Dispatch Lock & Partner Override
- **Owning Module:** Sales & Finance
- **Primary Persona:** Partner / Managing Director
- **Priority:** P0
- **Operational Statement:** If a customer's outstanding receivables exceed 100% of their sanctioned credit limit, all pending dispatches for that customer must be locked. Only a Partner user can record an explicit electronic approval override with mandatory justification notes to release the lock.
- **Data Attributes:** Lock Status (`Active`, `Overridden`), Override Approved By, Override Reason, Timestamp.
- **Validation Rules:** Override action permanently logged in audit trail.
---
### 5.10 Module 10: Payments, Payables & Expense Vouchers
#### `BRD-FR-031`: Customer Payment Receipt Posting
- **Owning Module:** Finance
- **Primary Persona:** Accounts Executive
- **Priority:** P0
- **Operational Statement:** The system must record customer payments capturing payment date, customer code, received amount in INR, payment instrument mode (`NEFT`, `RTGS`, `Cheque`, `Cash`, `UPI`), bank reference/UTR number, and payment status (`Pending Clearance`, `Cleared`, `Bounced`). The system must enforce automatic reversal upon Cheque/Instrument Bounce: if an instrument status transitions to `Bounced`, the system must immediately reverse the credit entry on the customer sub-ledger, restore the previous outstanding debt, recompute exposure ratio %, reinstate credit locks if exposure $>100\%$, and trigger an urgent financial alert.
- **Data Attributes:** Receipt ID (`PAY-YYYYMM-xxx`), Date, Customer ID, Amount INR, Payment Mode, UTR/Cheque No, Bank Name, Clearance Status, Bounce Reason, Reversal Voucher ID.
- **Validation Rules:** Amount must be $> 0$. Credit applied to customer ledger immediately upon `Cleared` status. Reversal action generates immutable audit trail entry and notifies Accounts Executive and Sales Manager.
#### `BRD-FR-032`: Supplier Payables Aging & Balance Snapshots
- **Owning Module:** Finance
- **Primary Persona:** Accounts Executive / Partner
- **Priority:** P0
- **Operational Statement:** The system must track supplier payables arising from accepted GRNs, applying supplier credit days, generating aging schedules, and providing daily aggregate payables snapshots.
- **Data Attributes:** Supplier ID, GRN No, Invoice Amount INR, Due Date, Days Overdue, Payment Status (`Unpaid`, `Partially Paid`, `Paid`).
- **Validation Rules:** Automated calculation of due date based on GRN date + credit days.
#### `BRD-FR-033`: Mandi Operating Expense Classification & Recording
- **Owning Module:** Finance
- **Primary Persona:** Accounts Executive
- **Priority:** P1
- **Operational Statement:** The system must record operational expenses incurred in mandi and godown operations categorizing entries under: Labor / Hamali (loading/unloading), Freight / Cartage, Weighbridge Fees, Godown Rent, Mandi Cess, Pest Control/Fumigation, and Office Expenses.
- **Data Attributes:** Expense ID (`EXP-YYYYMM-xxx`), Date, Category, Amount INR, Payee / Vendor, Linked Consignment / Sauda (if applicable), Payment Mode, Status.
- **Validation Rules:** Expense vouchers must balance against cash/bank ledger accounts.
---
### 5.11 Module 11: Real-Time Operational Alerts & Executive Analytics
#### `BRD-FR-034`: Real-Time Operational Alerts Engine
- **Owning Module:** Management & Alerts
- **Primary Persona:** Partner / Operations Supervisor
- **Priority:** P0
- **Operational Statement:** The system must evaluate active business data and publish automated proactive alerts across four critical categories:
1. **QC Pending Alert:** Lots in state `Under QC` for $>24$ hours or currently on `QC Hold`.
2. **Warehouse Capacity Alert:** Godowns exceeding 85% storage capacity utilization.
3. **Credit Risk Alert:** Customer accounts exceeding 80% or 100% of sanctioned credit limit.
4. **Active Procurement Window Alert:** Mandis with open buying orders during active trading hours.
- **Data Attributes:** Alert ID, Severity (`Info`, `Warning`, `Critical`), Category, Title, Detail Text, Timestamp, Dismissed Status.
- **Validation Rules:** Evaluated synchronously upon transaction mutations and refreshed periodically.
#### `BRD-FR-035`: Executive Control Centre Dashboard
- **Owning Module:** Management
- **Primary Persona:** Partner / Managing Director
- **Priority:** P0
- **Operational Statement:** The system must provide a unified operational dashboard displaying real-time metrics: Total Stock on Hand (MT), Total Active Stock Lines, Intraday Purchase Value INR, Intraday Sales Revenue INR, Total Customer Receivables INR, Top 10 Stock Lines by Volume, Top Recent Sales, and Warehouse Utilization Barometers.
- **Data Attributes:** KPI Metric Cards, Warehouse Position Table, Top Stock Grid, Recent Sales Feed, Active Alerts Feed.
- **Validation Rules:** Dashboard must load within $\le 1.5\text{s}$.
#### `BRD-FR-036`: 20-Day Consolidated Trading Trend Reporting
- **Owning Module:** Management & Reporting
- **Primary Persona:** Partner / Managing Director
- **Priority:** P0
- **Operational Statement:** The system must compile daily management snapshots across a rolling 20-day trading window, tabulating: Date, Purchases MT, Sales MT, Closing Stock MT, Total Receivables INR, and Total Payables INR.
- **Data Attributes:** Daily Snapshot Array (Date, Purchases MT, Sales MT, Stock MT, Receivables INR, Payables INR).
- **Validation Rules:** Dynamically calculated from transaction ledgers; sub-second query performance.
---
### 5.12 Cross-Cutting & Governance Modules
#### `BRD-FR-037`: Agricultural Commodity Master Data Management
- **Owning Module:** Master Data
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Maintain authoritative master catalogs for: Commodities (Chana, Soybean, Mustard, Wheat, Coriander, Cumin, Fenugreek, Groundnut, Isabgol, Jaggery, Maize, Turmeric), Varieties per commodity (e.g., Lokwan, Pusa, Eagle/Badami), and Commercial Quality Grades (`FAQ`, `Premium`, `Below FAQ`).
- **Data Attributes:** Commodity Code, Commodity Name, Category (`Grains`, `Pulses`, `Oilseeds`, `Spices`), Varieties List, Standard Bag Weight kg.
- **Validation Rules:** Commodity code must be unique; cannot delete commodities with active stock ledger entries.
#### `BRD-FR-038`: Trading Counterparty Masters (Suppliers, Customers & Godowns)
- **Owning Module:** Master Data
- **Primary Persona:** System Administrator / Accounts Executive
- **Priority:** P0
- **Operational Statement:** Maintain registries for: (1) Suppliers (Code, Name, City, Segment, Credit Days: 7/15/21), (2) Customers (Code, Name, City, Segment, Credit Limit INR, Contact), and (3) Godowns/Warehouses (Code, Name, City, Capacity MT).
- **Data Attributes:** Entity Code, Name, Address, GSTIN/PAN, Bank Details, Status (`Active`, `Inactive`).
- **Validation Rules:** Tax IDs validated where applicable.
#### `BRD-FR-039`: Site-Based Multi-Tenancy (`database_per_tenant`)
- **Owning Module:** Architecture & Security
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Multi-tenancy must be enforced via Frappe site architecture (`database_per_tenant`). Each trading enterprise runs on an independent MariaDB database within the shared Frappe Bench environment, ensuring strict cryptographic and database isolation of transactions, ledgers, and master data.
- **Data Attributes:** Frappe Site Name, MariaDB Database Name, Tenant Admin Account.
- **Validation Rules:** No cross-database queries or shared connection pools permitted.
#### `BRD-FR-040`: Role-Based Access Control (RBAC) & Permission Scoping
- **Owning Module:** Security
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Access to custom DocTypes, list views, and actions must be governed by Frappe Role Permission Manager across defined roles: `Mandi Buyer`, `Purchase Manager`, `Yard Supervisor`, `Quality Officer`, `Sales Executive`, `Sales Manager`, `Logistics Coordinator`, `Accounts Executive`, `Partner / MD`, and `System Manager`.
- **Data Attributes:** Role Name, DocType Permission Matrix (`Read`, `Write`, `Create`, `Delete`, `Submit`, `Cancel`, `Amend`).
- **Validation Rules:** Segregation of duties enforced: Quality Officers cannot edit prices; Yard Supervisors cannot confirm sales; Sales Executives cannot override credit locks.
#### `BRD-FR-041`: Immutable Transaction Audit Logging
- **Owning Module:** Governance
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** All submitted business documents (GRNs, Sales Orders, Dispatches, Payment Receipts) must be immutable. Amendments require Frappe document versioning (`amended_from`). The system must record audit logs capturing user ID, timestamp, IP address, and old vs. new values for all mutations.
- **Data Attributes:** Audit Trail Log ID, Document Type, Document Name, Modified By, Modified Timestamp, Field Diff JSON.
- **Validation Rules:** Audit logs cannot be deleted or modified through the user interface.
---
## 6. Non-Functional Requirements & Constraints (`BRD-NFR-xxx`)
| NFR ID | Requirement Area | Statement & Quantitative Metric | Priority |
|---|---|---|---|
| `BRD-NFR-001` | Commercial Calculation Integrity | Dual-unit mathematical conversions ($\text{Value} = \text{MT} \times 10 \times \text{Rate}_{\text{Qtl}}$) and bag tare deductions must maintain decimal precision to 3 decimal places for weight and 2 decimal places for currency without rounding drift. | P0 |
| `BRD-NFR-002` | UI Rendering Performance | Frappe Desk views, forms, and executive dashboards must achieve page load rendering times $\le 1.5\text{ seconds}$ on standard broadband (10 Mbps). | P0 |
| `BRD-NFR-003` | API Latency SLAs | Standard resource CRUD endpoints and list filter queries must achieve response latencies $\le 250\text{ ms}$ (p95) under normal operating load. | P0 |
| `BRD-NFR-004` | High-Volume Reporting SLA | 20-day trading trend snapshots and multi-godown stock position reports must generate in $\le 1.0\text{ second}$ across historical ledgers containing $\ge 50,000$ transaction rows. | P0 |
| `BRD-NFR-005` | Programmatic FSM Invariant Protection | Finite State Machines for Lot Quality (`Under QC` $\rightarrow$ `QC Hold` / `Released`) and Outbound Dispatches must be enforced in Python backend controller hooks (`validate`, `on_submit`), preventing client-side script or API bypass. | P0 |
| `BRD-NFR-006` | Tenant Data Isolation | Each tenant firm must reside in a dedicated MariaDB database via Frappe sites (`database_per_tenant`), guaranteeing zero possibility of cross-tenant leakage. | P0 |
| `BRD-NFR-007` | Offline Sandbox Testability | All third-party integration adapters (Identity, Payment Gateway) must provide deterministic local mock adapters under `sandbox/` capable of 100% offline, reproducible CI/CD execution without external network access. | P0 |
| `BRD-NFR-008` | Automated Test Coverage Budgets | Code must meet UP-AI differentiated coverage budgets: $\ge 95\%$ statement/branch coverage for backend domain services and FSMs, $\ge 90\%$ for sandbox adapters, and $\ge 80\%$ for frontend components. | P0 |
---
## 7. Scope Boundaries & Explicit Anti-Scope
### 7.1 In Scope for Version 1.0 (MVP)
- All 41 functional features (`BRD-FR-001` through `BRD-FR-041`) and 8 NFRs across the 11 operational modules.
- Standalone custom Frappe application architecture (`agri_app`) with dedicated custom DocTypes.
- Complete operational workflows matching the RamDayal prototype demonstration dataset.
- Responsive Frappe Desk UI accessible on desktop and mobile godown tablets.
- Automated multi-path test suites ($\ge 95\%$ domain coverage) and 21-sheet Excel QA Workbook compilation.
### 7.2 Explicit Anti-Scope (Deferred to Future Releases)
- **Direct ERPNext Core Ledger Coupling:** No dependency on standard ERPNext `Stock Ledger Entry` or `GL Entry` in v1.0.
- **Hardware Serial Weighbridge Drivers:** Manual entry and supervisor verification of weighbridge tickets; direct COM port/IP serial driver ingestion deferred.
- **Continuous GPS Vehicle Telematics:** Vehicle transit state managed via Dispatch Board FSM; live satellite map streaming deferred.
- **National e-NAM Bidding API:** Electronic auction bidding with national government portals deferred.
- **Multi-Currency / Forex Settlement:** Transactions strictly denominated in Indian National Rupees (INR / ₹).
- **Lab Spectrometry Hardware Ingestion:** Quality Officer enters physical test parameters manually after inspection.
---
## 8. Requirements Traceability Root Matrix
| Module | Granular Feature IDs | Priority | Target Use Cases (Stage 5) |
|---|---|---|---|
| **Market Desk** | `BRD-FR-001`, `BRD-FR-002`, `BRD-FR-003`, `BRD-FR-004` | P0 / P1 | `UC-001` (Market Intelligence & Price Tracking) |
| **Procurement (Sauda)** | `BRD-FR-005`, `BRD-FR-006`, `BRD-FR-007` | P0 / P1 | `UC-002` (Mandi Auction Purchase Sauda Booking) |
| **Goods Receipt (GRN)** | `BRD-FR-008`, `BRD-FR-009`, `BRD-FR-010`, `BRD-FR-011`, `BRD-FR-012` | P0 | `UC-003` (Weighbridge Inward & Godown Intake) |
| **Quality & Lots** | `BRD-FR-013`, `BRD-FR-014`, `BRD-FR-015`, `BRD-FR-016`, `BRD-FR-017` | P0 / P1 | `UC-004` (Commodity Lot QC Inspection & FSM) |
| **Warehouse Inventory** | `BRD-FR-018`, `BRD-FR-019`, `BRD-FR-020` | P0 | `UC-005` (Multi-Godown Stock Ledger & Transfers) |
| **Sales Orders** | `BRD-FR-021`, `BRD-FR-022`, `BRD-FR-023` | P0 | `UC-006` (Customer Sales Contract & Allocation) |
| **Logistics & Dispatch**| `BRD-FR-024`, `BRD-FR-025`, `BRD-FR-026` | P0 | `UC-007` (Outbound Dispatch Board & Transport) |
| **Fleet Management** | `BRD-FR-027` | P1 | `UC-008` (Transport Fleet & Vehicle Master) |
| **Customer Receivables**| `BRD-FR-028`, `BRD-FR-029`, `BRD-FR-030` | P0 | `UC-009` (Customer Receivables & Credit Limit Watch) |
| **Payments & Expenses** | `BRD-FR-031`, `BRD-FR-032`, `BRD-FR-033` | P0 / P1 | `UC-010` (Payment Receipts & Mandi Expenses) |
| **Alerts & Dashboard** | `BRD-FR-034`, `BRD-FR-035`, `BRD-FR-036` | P0 | `UC-011` (Executive Control Centre & Analytics) |
| **Master Data & Security**| `BRD-FR-037`, `BRD-FR-038`, `BRD-FR-039`, `BRD-FR-040`, `BRD-FR-041` | P0 | `UC-012` (Master Data, Multi-Tenancy & RBAC) |

742
01_BRD/PRD_Specification.md Normal file
View File

@ -0,0 +1,742 @@
# Product Requirements Document (PRD) — Agriculture Trading Backoffice
| Field | Value |
|---|---|
| **Document** | `PRD_Specification.md` |
| **Product** | Agriculture Trading Backoffice (`ATB`) |
| **Version** | 1.0.0 |
| **Author** | Stakeholder elicitation with `up-requirements-elicit` |
| **Process** | UP-AI v1.5 |
| **Status** | Draft — business direction accepted; candidate policies pending domain review and baseline approval |
| **Last Updated** | 2026-10-11 |
---
## 1. Executive Summary & Problem Statement
### 1.1 The Business Need
Wholesale physical agricultural commodity trading in India's Agricultural Produce Market Committee (APMC) mandis (such as Neemuch, Mandsaur, Ratlam, Kota, and Indore) involves fast-paced daily auctions, high financial exposure, multi-warehouse storage, and strict quality grading.
Wholesale trading firms and licensed commission agents (*arhatiyas*) handle dozens of truckloads daily across dry-agri commodities (pulses, oilseeds, grains, and spices such as chickpea/chana, soybean, mustard seed, coriander seed, cumin seed, fenugreek, turmeric, and wheat). Trading firms currently struggle with:
1. **Disconnected Paper Slips (*Sauda Buhis*):** Auction purchase commitments made in the mandi yard are not reflected in real time at the godowns, causing intake delays, truck detention, and weighbridge disputes.
2. **Dual-Unit Commercial Complexity:** Trading rates are quoted strictly in Indian Rupees per Quintal (₹/Qtl), whereas physical freight, warehouse capacity, and bookkeeping operate in Metric Tonnes (MT) and physical bag counts (*kattha/bora*). Manual math frequently causes billing errors.
3. **Quality & Lot Segregation Risks:** Consignments arriving with high moisture or impurities are accidentally mixed into clean warehouse stacks because quality inspection holds (*QC Hold*) are not enforced by software gates.
4. **Unhedged Customer Credit Exposure:** Customers frequently buy on credit terms (e.g., 7–15 days). Without real-time exposure monitoring, sales desks book orders for customers who have exceeded their sanctioned credit limit, leading to severe bad debt.
5. **Multi-Godown Blind Spots:** Stock balances across multiple transit and buffer godowns are reconciled manually at day-end, preventing real-time commitment of available inventory to buyers.
### 1.2 Target Operating Model
The **Agriculture Trading Backoffice (`ATB`)** is a modular, multi-tenant back-office and trading operations platform. Its configured implementation stack is maintained in [`tech-profile.yaml`](../tech-profile.yaml) and is not prescribed by this business requirements document. The product establishes an operational chain across the 11 functional areas represented by the reference mockup and this PRD:
```
Market Desk (Arrivals & Modal Price)
│
▼
Procurement (Auction Sauda Booking) ──► Inward Weighbridge (Gross/Tare/Bags)
│
▼
Godown Intake & Lot ID Generation
│
▼
Lab QC Inspection (QC Hold / Release)
│
▼
Customer Sales Contract ◄────────────── Available Warehouse Stock (MT & Bags)
│
▼
Credit Limit Check (≤80% / Breach Block)
│
▼
Outbound Dispatch Board ──► Transport Fleet Scheduling ──► Outward Weighbridge
│
▼
Customer Receivables Ledger
```
### 1.3 Success Measures and Operational Invariants
The following control outcomes are non-negotiable product invariants, measured across all applicable transactions rather than treated as aspirational averages:
- **Complete lot traceability:** 100% of lots accepted into inventory must retain the required links from purchase/receipt through QC, stock movements, allocation, and dispatch where applicable.
- **QC safety:** Zero allocation or dispatch of a lot that is not in the `Released` state; no user override may bypass this invariant.
- **Credit control:** Zero dispatches above the applicable credit block without a recorded authorized override.
Business-efficiency outcomes must be measured for a representative tenant over 30 operating days before rollout to establish a manual baseline, then for 30 operating days after rollout using the same method. Record manual effort per transaction, gate-in-to-stock-posting time, and stock-reconciliation variance by godown/commodity. The business owner will set numeric improvement targets from the observed pre- and post-rollout results. The protocol is accepted; numeric baseline and target values remain open under `AMB-001` pending pilot evidence.
Commercial dual-unit calculation correctness is governed by the formula below and `BRD-NFR-001`; its performance is addressed separately by the approved service-level targets.
$$\text{Value (INR)} = \text{Quantity (MT)} \times 10 \times \text{Rate (₹/Qtl)}$$
---
## 2. Target Personas & User Classes
| Persona | Role / Designation | Core Responsibilities & System Permissions |
|---|---|---|
| **Partner / Managing Director** | Executive Management | Full strategic oversight; reviews daily trading snapshots, net P&L metrics, operational alerts, cash flow, and holds exclusive authority for credit-limit override approvals. |
| **Purchase Manager** | Procurement Lead | Manages supplier relationships, monitors mandi auction windows, negotiates rates, reviews purchase vs. market modal rate variances, and approves purchase saudas. |
| **Procurement Executive** | Mandi Field Buyer | Enters daily mandi auction purchases, tracks arrival volumes, and logs daily market desk price observations directly from mandi yards. |
| **Sales Manager** | Commercial Lead | Evaluates customer inquiries, negotiates sales contracts, monitors customer credit exposure, approves sales contracts, and allocates inventory. |
| **Sales Executive** | Field / Desk Sales | Inputs customer sales orders, tracks order fulfillment stages, and communicates dispatch details to buyers. |
| **Yard Supervisor / Godown Keeper** | Warehouse Operations | Manages godown intake, operates weighbridge gross/tare weighment, verifies physical bag counts (*bardana tally*), manages stack placement, and oversees dispatch loading. |
| **Quality Officer** | Quality Inspection & Lab | Inspects inward lots, performs physical/lab sampling (moisture %, foreign matter %, damaged grains), enters test results, and toggles FSM states (`QC Hold` vs. `Released`). |
| **Logistics Coordinator** | Transport & Fleet | Coordinates carrier fleet (owned and contracted trucks), assigns vehicles to dispatches, generates dispatch bilties/manifests, and monitors transit status. |
| **Accounts Executive** | Finance & Accounting | Records customer payment receipts (NEFT/RTGS/Cheque/Cash), maintains supplier payables aging ledgers, records operational expense vouchers, and reconciles balances. |
| **System Administrator** | Technical Governance | Manages tenant lifecycle, platform configuration, support access, and audit trails. Routine tenant business-data access is not implied by this role. |
| **Tenant Administrator** | Tenant Operations | Manages the tenant’s users, memberships, and role assignments within that tenant; cannot administer other tenants. |
---
## 3. Mathematical & Commercial Calculation Engine Standards
### 3.1 Dual-Unit Conversion Engine
In Indian agricultural markets, rates are quoted in **₹ per Quintal**, while transport and inventory operate in **Metric Tonnes (MT)** and **Bags**:
1. **Metric Unit Definitions:**
- $1\text{ Metric Tonne (MT)} = 1,000\text{ Kilograms (kg)}$
- $1\text{ Quintal (Qtl)} = 100\text{ Kilograms (kg)} = 0.100\text{ MT}$
- $1\text{ Metric Tonne (MT)} = 10.0\text{ Quintals (Qtl)}$
2. **Gross Trade Value Formula:**
$$\text{Value (INR)} = \text{Quantity (MT)} \times 10 \times \text{Rate (₹/Qtl)}$$
*Example: $24.0\text{ MT}$ of Coriander seed at $₹4,486\text{ / Qtl} \implies 24.0 \times 10 \times 4486 = ₹1,076,640$.*
3. **Bag Packing Standard:**
$$\text{Average Bag Weight (kg)} = \frac{\text{Net Weight (MT)} \times 1000}{\text{Bag Count}}$$
Standard nominal packing is 50 kg or 100 kg per bag.
### 3.2 Inward Weighbridge & Bag Tare Deduction (*Bardana Katai*)
1. **Net Truck Weight:**
$$\text{Gross Truck Weight (kg)} - \text{Tare Truck Weight (kg)} = \text{Unloaded Gross Commodity Weight (kg)}$$
2. **Bag Tare Deduction (*Bardana Katai*):**
$$\text{Tare Bag Deduction (kg)} = \text{Bag Count} \times \text{Tare Weight Per Bag (kg)}$$
*(Default standard: 1.0 kg per gunny/jute bag, 0.2 kg per HDPE/plastic bag).*
3. **Net Payable Weight:**
$$\text{Net Weight (MT)} = \frac{\text{Unloaded Gross Commodity Weight (kg)} - \text{Tare Bag Deduction (kg)}}{1000}$$
4. **Weighment Shortage / Variance Calculation:**
$$\text{Variance \%} = \frac{\text{Actual Net Weighbridge MT} - \text{Booked Purchase MT}}{\text{Booked Purchase MT}} \times 100$$
- If $|\text{Variance \%}| \le 0.5\%$: Auto-accepted within normal mandi weighment tolerance.
- If $\text{Variance \%} < -0.5\%$: Shortage flagged; net payable MT adjusted to actual weighbridge receipt.
### 3.3 Customer Credit Exposure & Risk Engine
$$\text{Current Exposure (INR)} = \text{Total Outstanding Unpaid Receivables (INR)} + \text{Unbilled Confirmed Orders (INR)}$$
$$\text{Exposure Ratio \%} = \frac{\text{Current Exposure (INR)}}{\text{Sanctioned Credit Limit (INR)}} \times 100$$
- **Normal Zone ($\le 80\%$):** Sales orders and dispatches proceed without restriction.
- **Watch Warning Zone ($>80\%$ and $\le 100\%$):** System issues an automated Warning Alert; sales entry flags account on **Watch**.
- **Breach Block Zone ($>100\%$):** System enforces a **Hard Block**; order cannot transition to `Confirmed` or `Dispatched` without recorded Partner / MD approval.
---
## 4. Finite State Machines (FSMs) & Lifecycle Contracts
### 4.1 Purchase Sauda FSM
```
[Draft] ──► [Booked] ──► [Gate Inward] ──► [Under QC] ──► [Received / Closed]
│ │
▼ ▼
[Cancelled] [Rejected]
```
- `Draft`: Initial booking entered by Mandi Buyer.
- `Booked`: Sauda confirmed with supplier and market rate locked.
- `Gate Inward`: Truck arrived at godown gate; weighbridge gross weight captured.
- `Under QC`: Commodity unloaded; lot minted; awaiting lab test sign-off.
- `Received / Closed`: QC accepted; net tare calculated; GRN posted; inventory credited.
- `Rejected`: Commodity failed quality thresholds; gate pass issued for return to supplier.
### 4.2 Commodity Lot FSM
```
[Generated] ──► [Under QC] ──┬──► [Released] (Available for Allocation & Dispatch)
│
└──► [QC Hold] ──► [Released] (Post Remediation/Approval)
│
└──► [Rejected / Disposal]
```
- `Under QC`: Initial state upon godown unloading. Cannot be linked to sales orders.
- `QC Hold`: Flagged for excessive moisture, foreign matter, or quality dispute. Hard-locked against sales reservation and loading.
- `Released`: Lab approved. Eligible for sales order allocation and dispatch board loading.
- `Rejected`: Unfit for trade; flagged for return or discounted salvage.
### 4.3 Sales Order & Dispatch Board FSM
```
[Draft] ──► [Confirmed] ──► [Allocated] ──► [Loading] ──► [In Transit] ──► [Delivered]
│ │
▼ ▼
[Cancelled] [Order Hold]
```
- `Draft`: Customer inquiry and pricing quote.
- `Confirmed`: Credit check passed; sales contract ratified.
- `Allocated`: Released inventory lot(s) tagged to order.
- `Loading`: Transport vehicle assigned; bags being loaded onto truck.
- `In Transit`: Outward weighbridge completed; dispatch bilty generated; truck en route.
- `Delivered`: Consignee proof of delivery (POD) acknowledged; sales invoice finalized.
---
## 5. Comprehensive Granular Feature Inventory (`BRD-FR-xxx`)
Every discrete requirement carries a unique `BRD-FR-xxx` root ID, detailed operational statement, input/output data attributes, validation rules, and failure modes.
Operational thresholds in the feature descriptions are proposed values from the supplied backup PRD; see §6.2. They are not confirmed operating policy until domain review and baseline approval.
### 5.1 Module 1: Market Desk & Daily Mandi Intelligence
#### `BRD-FR-001`: Daily APMC Mandi Arrival Ingestion & Tracking
- **Owning Module:** Market Desk
- **Primary Persona:** Procurement Executive / Mandi Buyer
- **Priority:** P0
- **Operational Statement:** The system must record daily physical arrival volumes at APMC mandi yards across target commodities (Chana, Coriander, Cumin, Fenugreek, Groundnut, Isabgol, Jaggery, Maize, Mustard, Soybean, Turmeric, Wheat) across monitored markets (Neemuch, Mandsaur, Ratlam, Kota, Indore, Jaora, Ujjain, Chittorgarh).
- **Data Attributes:** Observation Date, Market Yard, Commodity, Variety, Grade, Arrival Quantity in MT, Internal Stock Position in MT, Observation Source, Timestamp.
- **Validation Rules:** Observation date cannot be in the future. Arrival quantity must be $\ge 0.0\text{ MT}$. Duplicate observation for same market, commodity, variety, and date must be blocked.
- **Failure / Exception Flow:** If arrival data is unavailable for a holiday/strike, system must allow flagging the market as `Closed / Mandi Holiday`.
#### `BRD-FR-002`: Daily Modal & Range Pricing Tracking (₹/Qtl)
- **Owning Module:** Market Desk
- **Primary Persona:** Procurement Executive / Purchase Manager
- **Priority:** P0
- **Operational Statement:** For each daily mandi arrival record, the system must capture the quoted price range (Min Rate ₹/Qtl, Max Rate ₹/Qtl) and the official modal clearing price (Modal Rate ₹/Qtl).
- **Data Attributes:** Quoted Min Rate (₹/Qtl), Quoted Max Rate (₹/Qtl), Modal Clearing Rate (₹/Qtl).
- **Validation Rules:** $\text{Min Rate} \le \text{Modal Rate} \le \text{Max Rate}$. All rates must be $> 0$.
- **Failure / Exception Flow:** If user inputs Modal Rate outside the Min-Max range, validation must reject save with an explicit arithmetic constraint error.
#### `BRD-FR-003`: Intraday Price Trend Analysis & 20-Day Benchmark Analytics
- **Owning Module:** Market Desk
- **Primary Persona:** Purchase Manager / Partner
- **Priority:** P0
- **Operational Statement:** The system must provide interactive visual charts and trend tables comparing the 20-day historical modal rate trend per commodity across markets, computing 20-day moving averages, 20-day highs/lows, and price velocity.
- **Data Attributes:** Historical Date Range, Commodity Filter, Market Filter, 20-Day SMA (Simple Moving Average), Price Spread.
- **Validation Rules:** Calculations must dynamically update upon new observation save. Execution time $\le 500\text{ms}$.
#### `BRD-FR-004`: Procurement Price Variance Alert vs. Modal Rate
- **Owning Module:** Market Desk & Procurement
- **Primary Persona:** Purchase Manager
- **Priority:** P1
- **Operational Statement:** When booking a purchase sauda, the system must compare the offered trade rate against the latest modal clearing rate for that commodity/mandi. If the offered rate exceeds the modal rate by $>5\%$, the system must display an inline warning and require confirmation.
- **Data Attributes:** Offered Rate, Benchmark Modal Rate, Variance \%.
- **Validation Rules:** Informational alert only; does not hard-block procurement unless configured in company policy.
---
### 5.2 Module 2: Mandi Procurement & Auction Purchases (Sauda)
#### `BRD-FR-005`: Mandi Auction & Direct Purchase Sauda Booking
- **Owning Module:** Procurement
- **Primary Persona:** Procurement Executive / Purchase Manager
- **Priority:** P0
- **Operational Statement:** The system must record purchase contracts (*saudas*) negotiated in mandi auctions or directly with suppliers. Each sauda must capture supplier code, sourcing market, commodity, variety, trade rate (₹/Qtl), estimated bag count, and booked quantity in MT. The system must support multi-truck partial delivery: a sauda may be fulfilled across multiple trucks/GRNs over consecutive delivery days, tracking cumulative received MT and remaining balance MT until fully fulfilled.
- **Data Attributes:** Sauda ID (`PUR-YYYYMM-xxx`), Sauda Date, Supplier ID, Sourcing Mandi, Commodity, Variety, Booked Qty MT, Estimated Bags, Trade Rate (₹/Qtl), Gross Value INR, Cumulative Received MT, Remaining Balance MT, Status.
- **Validation Rules:** Supplier must be an active master record. Booked MT must be $> 0$. Trade rate must be $> 0$. Gross value must equal $\text{Booked MT} \times 10 \times \text{Rate}$. Status remains `Partially Received` until cumulative received MT reaches booked MT (within tolerance) or explicitly closed by Purchase Manager.
- **Failure / Exception Flow:** If supplier is deactivated or blacklisted, booking must be blocked.
#### `BRD-FR-006`: Supplier Credit Terms & Due Date Computation
- **Owning Module:** Procurement & Finance
- **Primary Persona:** Purchase Manager / Accounts Executive
- **Priority:** P0
- **Operational Statement:** The system must automatically compute the supplier payment due date by adding the supplier's contractual credit days (e.g., 7, 15, or 21 days) to the sauda or GRN receipt date.
- **Data Attributes:** Supplier Credit Days, Transaction Date, Computed Due Date, Payment Status (`Pending`, `Paid`).
- **Validation Rules:** Default credit days inherited from Supplier master; editable only by Purchase Manager.
#### `BRD-FR-007`: Mandi Cess & Statutory Levies Apportioning
- **Owning Module:** Procurement & Finance
- **Primary Persona:** Accounts Executive
- **Priority:** P1
- **Operational Statement:** The system must calculate statutory mandi cess (e.g., 1.5% APMC market fee + 0.2% Nirashrit fee) based on the gross sauda value and append it to the total procurement cost.
- **Data Attributes:** Mandi Cess Rate %, Cess Amount INR, Total Landed Procurement Cost INR.
- **Validation Rules:** Configurable per commodity and market jurisdiction.
---
### 5.3 Module 3: Inward Weighbridge & Goods Receipt (GRN)
#### `BRD-FR-008`: Inward Vehicle Gate Entry & Verification
- **Owning Module:** Goods Receipt
- **Primary Persona:** Yard Supervisor
- **Priority:** P0
- **Operational Statement:** Upon vehicle arrival at the godown, the Yard Supervisor must log gate entry linking the vehicle registration number and driver details to an active booked sauda.
- **Data Attributes:** Gate Entry ID, Inward Date/Time, Vehicle Reg No, Driver Name, Contact No, Linked Sauda ID, Supplier Name, Gate Pass No.
- **Validation Rules:** Linked sauda must be in state `Booked`.
#### `BRD-FR-009`: Weighbridge Gross & Tare Weighment Logging
- **Owning Module:** Goods Receipt
- **Primary Persona:** Yard Supervisor
- **Priority:** P0
- **Operational Statement:** The system must record dual-phase weighbridge measurements for incoming trucks: (1) Gross Weighment (truck + commodity) upon arrival, and (2) Tare Weighment (empty truck) after unloading.
- **Data Attributes:** Gross Weight kg, Gross Timestamp, Tare Weight kg, Tare Timestamp, Gross Net Weight kg ($Gross - Tare$), Weighbridge Slip No.
- **Validation Rules:** $\text{Gross Weight} > \text{Tare Weight} > 0$. Weighbridge slip number mandatory.
- **Failure / Exception Flow:** If Tare Weight $\ge$ Gross Weight, system must hard-block submission with an error.
#### `BRD-FR-010`: Bag Tare Deduction (*Bardana Katai*) & Final Net MT
- **Owning Module:** Goods Receipt
- **Primary Persona:** Yard Supervisor
- **Priority:** P0
- **Operational Statement:** The system must deduct the weight of packaging bags from the gross commodity weight using the defined tare deduction factor (default 1.0 kg/gunny bag) to calculate true Net Payable MT.
- **Data Attributes:** Physical Bag Count, Packaging Type (`Gunny/Jute`, `HDPE/Plastic`), Bag Tare Deduction Rate kg/bag, Total Bag Tare kg, Final Net Weight MT.
- **Validation Rules:** Formula: $\text{Net MT} = (\text{Gross kg} - \text{Tare kg} - (\text{Bags} \times \text{Bag Tare Rate})) / 1000$. Net MT must be $> 0$.
#### `BRD-FR-011`: Weighment Tolerance & Transit Shortage Verification
- **Owning Module:** Goods Receipt
- **Primary Persona:** Yard Supervisor / Purchase Manager
- **Priority:** P0
- **Operational Statement:** The system must compare the Final Net Weighbridge MT against the Booked Sauda MT. If shortage exceeds $0.5\%$, the system must flag a `Transit Shortage Warning` and adjust the final payable amount to the actual net received weight.
- **Data Attributes:** Shortage MT, Shortage Value INR, Variance \%, Shortage Status (`Normal`, `Disputed`).
- **Validation Rules:** If shortage exceeds $2.0\%$, the GRN requires mandatory Purchase Manager approval before stock posting.
#### `BRD-FR-012`: Goods Receipt Note (GRN) Posting & Warehouse Stack Placement
- **Owning Module:** Goods Receipt & Inventory
- **Primary Persona:** Yard Supervisor
- **Priority:** P0
- **Operational Statement:** Upon weighment completion, the system must generate a formal GRN document, allocate the physical goods to a specific warehouse/godown and stack location, credit the warehouse stock book, and mint an inward Commodity Lot.
- **Data Attributes:** GRN ID (`GRN-YYYYMM-xxx`), Receiving Warehouse ID, Stack/Chamber No, Accepted Bags, Accepted Net MT.
- **Validation Rules:** GRN submission atomically updates inventory and creates Lot record in state `Under QC`.
---
### 5.4 Module 4: Quality Inspection & Lot Control
#### `BRD-FR-013`: Mandatory Lot & Batch Identity Generation
- **Owning Module:** Quality & Inventory
- **Primary Persona:** Yard Supervisor / Quality Officer
- **Priority:** P0
- **Operational Statement:** The system must automatically generate a globally unique, immutable Lot ID (`LOT-YYYYMM-xxx`) for every inward consignment processed through a GRN.
- **Data Attributes:** Lot ID, Inward Date, Origin Market, Supplier ID, Commodity, Variety, Receiving Warehouse, Net MT, Bag Count, Quality Status.
- **Validation Rules:** Initial status must be `Under QC`. Lot ID must be permanent and traceable through all sales and dispatches.
#### `BRD-FR-014`: Inward Quality Inspection Parameter Recording
- **Owning Module:** Quality Control
- **Primary Persona:** Quality Officer
- **Priority:** P0
- **Operational Statement:** The Quality Officer must log laboratory/physical test parameters for the lot: Moisture %, Foreign Matter / Dust %, Admixture (other grains) %, Damaged / Discolored %, and Weevil count.
- **Data Attributes:** Inspection Date, Quality Officer ID, Moisture %, Foreign Matter %, Admixture %, Damaged %, Weevil Infestation (`None`, `Mild`, `Severe`), Assigned Commercial Grade (`FAQ`, `Premium`, `Below FAQ`).
- **Validation Rules:** Percentage values must be between $0.00\%$ and $100.00\%$.
#### `BRD-FR-015`: Quality Deduction / Rebate Calculation
- **Owning Module:** Quality Control & Finance
- **Primary Persona:** Quality Officer / Accounts Executive
- **Priority:** P1
- **Operational Statement:** If moisture or foreign matter exceeds standard contract baselines (e.g., standard moisture baseline 10.0%), the system must automatically compute a quality price deduction (e.g., ₹10 deduction per quintal for each 0.5% moisture above baseline).
- **Data Attributes:** Base Contract Rate ₹/Qtl, Quality Penalty Rate ₹/Qtl, Adjusted Final Rate ₹/Qtl, Net Purchase Adjustment INR.
- **Validation Rules:** Deductions cannot reduce rate below 50% of base rate without partner authorization.
#### `BRD-FR-016`: Finite State Machine Enforcement for `QC Hold` vs. `Released`
- **Owning Module:** Quality Control
- **Primary Persona:** Quality Officer
- **Priority:** P0
- **Operational Statement:** The system must enforce strict FSM transitions on the Lot record. If moisture $>12\%$ or foreign matter $>2\%$, the lot must be transitioned to `QC Hold`. A lot on `QC Hold` is programmatically blocked from sales order allocation and dispatch loading.
- **Data Attributes:** Previous Status, New Status (`QC Hold`, `Released`), Hold Reason, Action Plan (`Drying`, `Cleaning`, `Re-testing`), Release Timestamp.
- **Validation Rules:** Only users with `Quality Officer` or `Partner` roles can transition a lot from `QC Hold` to `Released`. System must hard-block dispatch of unreleased lots.
#### `BRD-FR-017`: Lot Splitting & Blending Traceability
- **Owning Module:** Quality & Inventory
- **Primary Persona:** Yard Supervisor / Quality Officer
- **Priority:** P1
- **Operational Statement:** The system must support splitting a parent lot into sub-lots (e.g., when dividing a consignment across two warehouses) or blending multiple lots, maintaining parent-child lineage in the traceability graph.
- **Data Attributes:** Parent Lot ID, Child Lot ID(s), Split Qty MT, Split Bag Count, Linage Tree.
- **Validation Rules:** Sum of child lot quantities must exactly equal parent quantity deducted.
---
### 5.5 Module 5: Multi-Godown Warehouse Inventory
#### `BRD-FR-018`: Multi-Godown Dual-Unit Stock Ledger
- **Owning Module:** Inventory
- **Primary Persona:** Yard Supervisor / Management
- **Priority:** P0
- **Operational Statement:** The system must maintain a real-time, double-entry stock ledger tracking commodity positions across warehouses (WH-01 Neemuch Main Yard, WH-02 Neemuch North Godown, WH-03 Mandsaur Transit Godown, WH-04 Indore Buffer Depot). For each commodity, variety, and grade, it must maintain Opening Stock MT, Received MT, Dispatched MT, Closing Stock MT, and physical Bag counts. The system must support Periodic Physical Stock Audits: recording physical tally counts against book balances and generating supervisor-authorized Stock Adjustment Vouchers capturing natural storage loss/gain (*ghat / nami* due to moisture evaporation or seasonal humidity) or handling spillage with mandatory reason codes.
- **Data Attributes:** Stock Entry ID, Date, Warehouse ID, Commodity, Variety, Grade, Opening MT, Inward MT, Outward MT, Closing MT, Bag Delta, Closing Bags, Physical Count MT, Adjustment Variance MT, Variance Reason Code (`Moisture Loss / Ghat`, `Handling Spillage`, `Bag Burst`, `Seasonal Humidity Gain`).
- **Validation Rules:** Closing stock MT and bags must never be negative ($\ge 0$). Adjustments exceeding $\pm 1.0\%$ of godown balance require mandatory Partner electronic sign-off.
#### `BRD-FR-019`: Godown Capacity & Volume Utilization Tracking
- **Owning Module:** Inventory
- **Primary Persona:** Yard Supervisor / Partner
- **Priority:** P0
- **Operational Statement:** The system must track the physical storage capacity of each warehouse in Metric Tonnes and calculate real-time percentage utilization:
$$\text{Utilisation \%} = \frac{\text{Current Closing Stock (MT)}}{\text{Storage Capacity (MT)}} \times 100$$
- **Data Attributes:** Warehouse ID, Name, City, Capacity MT, Current Stock MT, Utilisation \%.
- **Validation Rules:** Warning status triggered when Utilisation exceeds 85%.
#### `BRD-FR-020`: Godown-to-Godown Internal Stock Transfer
- **Owning Module:** Inventory & Logistics
- **Primary Persona:** Yard Supervisor / Logistics Coordinator
- **Priority:** P0
- **Operational Statement:** The system must support recording stock transfers between godowns (e.g., from Mandsaur Transit Godown to Neemuch Main Yard), logging origin outward deduction, in-transit state, destination weighment, and destination inward credit.
- **Data Attributes:** Transfer ID, Origin Warehouse, Destination Warehouse, Commodity, Lot ID, Transfer Qty MT, Transfer Bags, Vehicle Reg No, Transit Status.
- **Validation Rules:** Outward and inward entries must reconcile within $\pm 0.2\%$ transfer tolerance.
---
### 5.6 Module 6: Customer Sales Contracts & Orders
#### `BRD-FR-021`: Customer Sales Contract Booking
- **Owning Module:** Sales
- **Primary Persona:** Sales Manager / Sales Executive
- **Priority:** P0
- **Operational Statement:** The system must record customer sales orders/contracts specifying customer code, destination city, customer segment (`Wholesale`, `Processor`, `Institutional`, `Distributor`), commodity, variety, grade, contracted quantity in MT, contract rate in ₹/Qtl, and delivery timeline.
- **Data Attributes:** Sales Order ID (`SAL-YYYYMM-xxx`), Order Date, Customer ID, Destination City, Commodity, Variety, Grade, Contract Qty MT, Contract Rate ₹/Qtl, Total Sales Value INR, Payment Terms, Status.
- **Validation Rules:** Total Sales Value must equal $\text{Contract Qty MT} \times 10 \times \text{Rate ₹/Qtl}$.
#### `BRD-FR-022`: Customer Credit Limit & Pre-Order Exposure Verification
- **Owning Module:** Sales & Finance
- **Primary Persona:** Sales Manager / Accounts Executive
- **Priority:** P0
- **Operational Statement:** Prior to confirming a sales order, the system must evaluate the customer's current outstanding receivables plus the value of the new order against their sanctioned credit limit.
- **Data Attributes:** Sanctioned Credit Limit INR, Current Outstanding INR, New Order Value INR, Projected Exposure INR, Projected Exposure Ratio \%.
- **Validation Rules:** If Projected Exposure Ratio $>80\%$, display inline warning. If Projected Exposure Ratio $>100\%$, system must prevent order confirmation unless authorized by Partner.
#### `BRD-FR-023`: Sales Order Inventory Allocation
- **Owning Module:** Sales & Inventory
- **Primary Persona:** Sales Manager / Yard Supervisor
- **Priority:** P0
- **Operational Statement:** The Sales Manager must allocate specific available inventory lot(s) from a warehouse to a confirmed sales order. The system must verify that selected lots are in `Released` state and have sufficient unreserved balance.
- **Data Attributes:** Sales Order ID, Allocated Lot ID, Allocated Qty MT, Allocated Bags, Warehouse ID.
- **Validation Rules:** Allocation fails if Lot status is `QC Hold` or `Under QC`, or if available lot unreserved MT $<$ allocated MT.
---
### 5.7 Module 7: Outbound Logistics & Dispatch Board
#### `BRD-FR-024`: Outbound Dispatch Board Console
- **Owning Module:** Logistics
- **Primary Persona:** Logistics Coordinator
- **Priority:** P0
- **Operational Statement:** The system must provide a visual dispatch management board displaying scheduled, loading, and in-transit consignments, matching confirmed sales orders to allocated warehouse lots and transport vehicles.
- **Data Attributes:** Dispatch ID (`DISP-YYYYMM-xxx`), Dispatch Date, Linked Sales Order ID, Customer Name, Destination City, Commodity, Dispatch Qty MT, Assigned Vehicle Reg No, Driver Details, Status (`Scheduled`, `Loading`, `In Transit`, `Delivered`).
- **Validation Rules:** Dispatch cannot be created without an approved sales order and assigned vehicle.
#### `BRD-FR-025`: Outbound Weighbridge & Dispatch Bilty/Manifest
- **Owning Module:** Logistics & Weighbridge
- **Primary Persona:** Yard Supervisor / Logistics Coordinator
- **Priority:** P0
- **Operational Statement:** The system must capture outward weighbridge weights for loaded dispatch trucks (Tare truck before loading, Gross truck after loading), verify loaded weight against order MT, and generate a printable transport manifest / Bilty.
- **Data Attributes:** Dispatch ID, Outward Tare kg, Outward Gross kg, Net Loaded MT, Loaded Bag Count, Transporter Bilty No, e-Way Bill No.
- **Validation Rules:** Net loaded MT must match allocated order MT within $\pm 1.0\%$ loading tolerance.
#### `BRD-FR-026`: In-Transit Tracking & Proof of Delivery (POD)
- **Owning Module:** Logistics
- **Primary Persona:** Logistics Coordinator
- **Priority:** P0
- **Operational Statement:** The system must track dispatch states from `In Transit` to `Delivered`. Upon consignee receipt, the Logistics Coordinator logs confirmation date, destination weighment, and uploads POD document reference. If destination weighment or quality parameters reveal a transit shortage or damage acknowledged by the buyer, the system must allow recording a Consignee Shortage Note and automatically generating a compensating Sales Credit Note against the customer ledger without altering the immutable outbound dispatch manifest.
- **Data Attributes:** Transit Status, Departure Date/Time, Expected Delivery Date, Actual Delivery Date, Destination Weighbridge Net MT, Transit Loss MT, Consignee Acknowledgement Note, POD Ref, Credit Note ID (if applicable).
- **Validation Rules:** Setting status to `Delivered` triggers automatic generation of finalized Sales Invoice. Consignee shortage deductions exceeding 2.0% require mandatory Sales Manager approval before issuing Credit Note.
---
### 5.8 Module 8: Fleet & Vehicle Management
#### `BRD-FR-027`: Transport Fleet Registry
- **Owning Module:** Logistics & Fleet
- **Primary Persona:** Logistics Coordinator
- **Priority:** P1
- **Operational Statement:** The system must maintain a registry of transport trucks (owned and contract carriers) including registration number, vehicle model, gross payload capacity in MT, ownership type (`Own` vs `Contract`), insurance/fitness expiry dates, and operational status (`Available`, `On Route`, `Maintenance`).
- **Data Attributes:** Vehicle Reg No, Make/Model, Payload Capacity MT, Ownership Type, Transporter Name, Status, Fitness Expiry Date.
- **Validation Rules:** Vehicles with status `Maintenance` cannot be assigned to dispatches.
---
### 5.9 Module 9: Customer Receivables & Exposure Management
#### `BRD-FR-028`: Customer Ledger & Aging Statement
- **Owning Module:** Finance
- **Primary Persona:** Accounts Executive / Sales Manager
- **Priority:** P0
- **Operational Statement:** The system must maintain an immutable party sub-ledger for each customer, debiting finalized sales invoices, crediting payment receipts, and presenting a real-time outstanding balance and aging schedule (0–7 days, 8–15 days, 16–30 days, >30 days).
- **Data Attributes:** Customer ID, Posting Date, Voucher Type (`Sales Invoice`, `Payment Receipt`), Voucher No, Debit Amount INR, Credit Amount INR, Running Outstanding INR.
- **Validation Rules:** Sub-ledger entries are immutable; corrections require credit/debit adjustment vouchers.
#### `BRD-FR-029`: Automated Customer Credit Exposure Watch & Threshold Alert
- **Owning Module:** Finance & Alerts
- **Primary Persona:** Accounts Executive / Partner
- **Priority:** P0
- **Operational Statement:** The system must continuously recompute the customer exposure ratio ($\text{Outstanding} / \text{Credit Limit}$). If exposure $>80\%$, the account must be automatically tagged with a visual `Watch` badge, and an operational warning alert generated on the Executive Dashboard.
- **Data Attributes:** Customer Code, Customer Name, Sanctioned Credit Limit INR, Outstanding INR, Exposure %, Risk Flag (`Normal`, `Watch`, `Critical`).
- **Validation Rules:** Evaluated in real time upon every sales invoice post and payment receipt post.
#### `BRD-FR-030`: Credit Breach Dispatch Lock & Partner Override
- **Owning Module:** Sales & Finance
- **Primary Persona:** Partner / Managing Director
- **Priority:** P0
- **Operational Statement:** If a customer's outstanding receivables exceed 100% of their sanctioned credit limit, all pending dispatches for that customer must be locked. Only a Partner user can record an explicit electronic approval override with mandatory justification notes to release the lock.
- **Data Attributes:** Lock Status (`Active`, `Overridden`), Override Approved By, Override Reason, Timestamp.
- **Validation Rules:** Override action permanently logged in audit trail.
---
### 5.10 Module 10: Payments, Payables & Expense Vouchers
#### `BRD-FR-031`: Customer Payment Receipt Posting
- **Owning Module:** Finance
- **Primary Persona:** Accounts Executive
- **Priority:** P0
- **Operational Statement:** The system must record customer payments capturing payment date, customer code, received amount in INR, payment instrument mode (`NEFT`, `RTGS`, `Cheque`, `Cash`, `UPI`), bank reference/UTR number, and payment status (`Pending Clearance`, `Cleared`, `Bounced`). The system must enforce automatic reversal upon Cheque/Instrument Bounce: if an instrument status transitions to `Bounced`, the system must immediately reverse the credit entry on the customer sub-ledger, restore the previous outstanding debt, recompute exposure ratio %, reinstate credit locks if exposure $>100\%$, and trigger an urgent financial alert.
- **Data Attributes:** Receipt ID (`PAY-YYYYMM-xxx`), Date, Customer ID, Amount INR, Payment Mode, UTR/Cheque No, Bank Name, Clearance Status, Bounce Reason, Reversal Voucher ID.
- **Validation Rules:** Amount must be $> 0$. Credit applied to customer ledger immediately upon `Cleared` status. Reversal action generates immutable audit trail entry and notifies Accounts Executive and Sales Manager.
#### `BRD-FR-032`: Supplier Payables Aging & Balance Snapshots
- **Owning Module:** Finance
- **Primary Persona:** Accounts Executive / Partner
- **Priority:** P0
- **Operational Statement:** The system must track supplier payables arising from accepted GRNs, applying supplier credit days, generating aging schedules, and providing daily aggregate payables snapshots.
- **Data Attributes:** Supplier ID, GRN No, Invoice Amount INR, Due Date, Days Overdue, Payment Status (`Unpaid`, `Partially Paid`, `Paid`).
- **Validation Rules:** Automated calculation of due date based on GRN date + credit days.
#### `BRD-FR-033`: Mandi Operating Expense Classification & Recording
- **Owning Module:** Finance
- **Primary Persona:** Accounts Executive
- **Priority:** P1
- **Operational Statement:** The system must record operational expenses incurred in mandi and godown operations categorizing entries under: Labor / Hamali (loading/unloading), Freight / Cartage, Weighbridge Fees, Godown Rent, Mandi Cess, Pest Control/Fumigation, and Office Expenses.
- **Data Attributes:** Expense ID (`EXP-YYYYMM-xxx`), Date, Category, Amount INR, Payee / Vendor, Linked Consignment / Sauda (if applicable), Payment Mode, Status.
- **Validation Rules:** Expense vouchers must balance against cash/bank ledger accounts.
---
### 5.11 Module 11: Real-Time Operational Alerts & Executive Analytics
#### `BRD-FR-034`: Real-Time Operational Alerts Engine
- **Owning Module:** Management & Alerts
- **Primary Persona:** Partner / Operations Supervisor
- **Priority:** P0
- **Operational Statement:** The system must evaluate active business data and publish automated proactive alerts across four critical categories:
1. **QC Pending Alert:** Lots in state `Under QC` for $>24$ hours or currently on `QC Hold`.
2. **Warehouse Capacity Alert:** Godowns exceeding 85% storage capacity utilization.
3. **Credit Risk Alert:** Customer accounts exceeding 80% or 100% of sanctioned credit limit.
4. **Active Procurement Window Alert:** Mandis with open buying orders during active trading hours.
- **Data Attributes:** Alert ID, Severity (`Info`, `Warning`, `Critical`), Category, Title, Detail Text, Timestamp, Dismissed Status.
- **Validation Rules:** Evaluated synchronously upon transaction mutations and refreshed periodically.
#### `BRD-FR-035`: Executive Control Centre Dashboard
- **Owning Module:** Management
- **Primary Persona:** Partner / Managing Director
- **Priority:** P0
- **Operational Statement:** The system must provide a unified operational dashboard displaying real-time metrics: Total Stock on Hand (MT), Total Active Stock Lines, Intraday Purchase Value INR, Intraday Sales Revenue INR, Total Customer Receivables INR, Top 10 Stock Lines by Volume, Top Recent Sales, and Warehouse Utilization Barometers.
- **Data Attributes:** KPI Metric Cards, Warehouse Position Table, Top Stock Grid, Recent Sales Feed, Active Alerts Feed.
- **Validation Rules:** Dashboard must load within $\le 1.5\text{s}$.
#### `BRD-FR-036`: 20-Day Consolidated Trading Trend Reporting
- **Owning Module:** Management & Reporting
- **Primary Persona:** Partner / Managing Director
- **Priority:** P0
- **Operational Statement:** The system must compile daily management snapshots across a rolling 20-day trading window, tabulating: Date, Purchases MT, Sales MT, Closing Stock MT, Total Receivables INR, and Total Payables INR.
- **Data Attributes:** Daily Snapshot Array (Date, Purchases MT, Sales MT, Stock MT, Receivables INR, Payables INR).
- **Validation Rules:** Dynamically calculated from transaction ledgers; sub-second query performance.
---
### 5.12 Cross-Cutting & Governance Modules
#### `BRD-FR-037`: Agricultural Commodity Master Data Management
- **Owning Module:** Master Data
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Maintain authoritative master catalogs for: Commodities (Chana, Soybean, Mustard, Wheat, Coriander, Cumin, Fenugreek, Groundnut, Isabgol, Jaggery, Maize, Turmeric), Varieties per commodity (e.g., Lokwan, Pusa, Eagle/Badami), and Commercial Quality Grades (`FAQ`, `Premium`, `Below FAQ`).
- **Data Attributes:** Commodity Code, Commodity Name, Category (`Grains`, `Pulses`, `Oilseeds`, `Spices`), Varieties List, Standard Bag Weight kg.
- **Validation Rules:** Commodity code must be unique; cannot delete commodities with active stock ledger entries.
#### `BRD-FR-038`: Trading Counterparty Masters (Suppliers, Customers & Godowns)
- **Owning Module:** Master Data
- **Primary Persona:** System Administrator / Accounts Executive
- **Priority:** P0
- **Operational Statement:** Maintain registries for: (1) Suppliers (Code, Name, City, Segment, Credit Days: 7/15/21), (2) Customers (Code, Name, City, Segment, Credit Limit INR, Contact), and (3) Godowns/Warehouses (Code, Name, City, Capacity MT).
- **Data Attributes:** Entity Code, Name, Address, GSTIN/PAN, Bank Details, Status (`Active`, `Inactive`).
- **Validation Rules:** Tax IDs validated where applicable.
#### `BRD-FR-039`: Tenant Data Isolation
- **Owning Module:** Architecture & Security
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Each independent trading enterprise is a tenant; its branches and godowns operate within that tenant boundary. Users and transactions must be associated with the correct tenant, and access to one tenant’s business data must not expose another tenant’s data. The isolation implementation must conform to the active technology profile.
- **Data Attributes:** Tenant ID, Tenant Name, Tenant Status, Tenant Administrator, Branch and Godown IDs.
- **Validation Rules:** Tenant context must be enforced on every applicable business operation and verified for cross-tenant data access.
#### `BRD-FR-040`: Role-Based Access Control (RBAC) & Permission Scoping
- **Owning Module:** Security
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Access to business records and actions must be governed by role-based permissions for the roles defined in this PRD: `Tenant Administrator`, `Mandi Buyer`, `Purchase Manager`, `Yard Supervisor`, `Quality Officer`, `Sales Executive`, `Sales Manager`, `Logistics Coordinator`, `Accounts Executive`, `Partner / MD`, and `System Administrator`.
- **Data Attributes:** Role Name, Resource/Action Permission Matrix (`Read`, `Write`, `Create`, `Delete`, `Submit`, `Cancel`, `Amend`).
- **Validation Rules:** Segregation of duties enforced: Quality Officers cannot edit prices; Yard Supervisors cannot confirm sales; Sales Executives cannot override credit locks.
#### `BRD-FR-041`: Immutable Transaction Audit Logging
- **Owning Module:** Governance
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Submitted business records (GRNs, Sales Orders, Dispatches, Payment Receipts) must preserve an auditable history. Corrections must not silently rewrite the business history. The system must record user ID, timestamp, and the changed values for governed mutations.
- **Data Attributes:** Audit Trail Log ID, Document Type, Document Name, Modified By, Modified Timestamp, Field Diff JSON.
- **Validation Rules:** Audit history cannot be deleted or modified through normal application operations.
#### `BRD-FR-042`: Tenant Provisioning and Lifecycle Management
- **Owning Module:** Platform Administration
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Public self-service tenant signup is out of scope for v1. An authorized platform administrator must create and configure each tenant, assign its initial Tenant Administrator, and activate, suspend, or close the tenant through a controlled lifecycle. Tenant lifecycle changes must not silently delete or expose business records.
- **Data Attributes:** Tenant ID, Tenant Name, Lifecycle Status, Created/Updated Timestamps, Tenant Administrator, Lifecycle Actor and Reason.
- **Acceptance Intent:** Each lifecycle transition is authorized, recorded, and reflected consistently across application access, API requests, and scheduled work. Closed/suspended tenant data handling follows the retention and deletion policy approved for the service.
#### `BRD-FR-043`: Tenant Membership and Role Administration
- **Owning Module:** Identity & Access Management
- **Primary Persona:** Tenant Administrator
- **Priority:** P0
- **Operational Statement:** A person may hold active memberships in multiple tenants. A Tenant Administrator must be able to add, deactivate, and assign approved business roles to users within their own tenant. A tenant administrator must not manage users or roles belonging to another tenant. Platform-level administrators and tenant-level administrators must have distinct permissions.
- **Data Attributes:** User ID, Tenant ID, Membership Status, Role Assignments, Changed By, Changed At.
- **Acceptance Intent:** Users receive no tenant access without an active membership and role assignment; membership changes take effect on subsequent authorized operations and are auditable.
#### `BRD-FR-044`: Verified Tenant Context for Every Operation
- **Owning Module:** Identity & Access Management
- **Primary Persona:** All authenticated users
- **Priority:** P0
- **Operational Statement:** The service must derive the effective tenant context from the authenticated user’s verified tenant membership. A client-supplied tenant identifier alone must never grant or switch tenant access. A user associated with multiple tenants must explicitly select the active tenant after sign-in; the service verifies that membership and its role for every request before permitting action in that tenant.
- **Data Attributes:** Authenticated Subject, Effective Tenant ID, Membership, Role Claims, Request/Correlation ID.
- **Acceptance Intent:** Missing, invalid, or unauthorized tenant context is denied by default; the same checks apply to REST APIs and non-interactive operations.
#### `BRD-FR-045`: End-to-End Tenant Resource Isolation
- **Owning Module:** Platform Security
- **Primary Persona:** All users; System Administrator for platform controls
- **Priority:** P0
- **Operational Statement:** Tenant isolation must apply to all tenant-owned records and derived resources, including database reads and writes, API lookups, search/report results, exports, uploaded files, cache entries, and queued/background work. Cross-tenant access attempts must fail closed and must not reveal whether another tenant’s resource exists.
- **Data Attributes:** Tenant ID on tenant-owned resources; resource owner; access decision; actor; timestamp; correlation ID.
- **Acceptance Intent:** Automated negative tests demonstrate that users, crafted identifiers, concurrent requests, reused database connections, and background jobs cannot read or mutate another tenant’s resources. Database roles and policies must not allow normal application paths to bypass the configured row-level security controls.
#### `BRD-FR-046`: Controlled Privileged Support Access
- **Owning Module:** Platform Security & Operations
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** Platform support must not imply routine unrestricted access to tenant business data. Support staff have no standing access to tenant business data. Ordinary exceptional access requires approval by that tenant’s Tenant Administrator for a specific support case and a limited duration. For an urgent incident, a designated platform security administrator may grant a break-glass access window of at most one hour, with a recorded reason, immediate audit alert, and notice to the tenant administrator within one business day. All access is recorded for tenant and platform security review.
- **Data Attributes:** Support Actor, Tenant ID, Reason/Case Reference, Approval, Start/End Time, Resources Accessed, Audit Event.
- **Acceptance Intent:** Privileged access can be granted and revoked through a controlled workflow; all such access is attributable and reviewable. Ordinary access requires tenant-admin approval; emergency break-glass access follows the one-hour limit and notification controls above.
### 5.5 Module 13: Privacy Operations & DPDP Support
#### `BRD-FR-047`: Personal Data Purpose, Notice & Consent Records
- **Owning Module:** Privacy Operations
- **Primary Persona:** Tenant Administrator; System Administrator for platform-controlled processing
- **Priority:** P0
- **Operational Statement:** The service must allow each responsible Data Fiduciary to determine and approve the processing purpose, applicable lawful basis, and privacy notice for its processing, then document personal-data categories, purpose, basis, notice version, and accountable contact. Tenant firms own these decisions for trading data; the ATB operator records them separately for its own account, security, and service processing. Privacy controls cover every natural person whose personal data is processed in tenant or platform contexts, whether or not that person has an application account. Where consent is the applicable basis, the service must capture evidence of the notice and consent, support withdrawal, and record resulting processing restrictions. Tenant and platform processing contexts must remain distinguishable.
- **Data Attributes:** Processing Purpose ID, Data Category, Responsible Entity/Role, Processing Basis, Notice Version, Consent Status and Timestamp, Withdrawal Timestamp, Contact.
- **Acceptance Intent:** Personal data processing purposes and notices are attributable to the responsible Data Fiduciary; consent-dependent processing can be stopped or adjusted following a verified withdrawal, subject to applicable lawful retention or other legal obligations.
#### `BRD-FR-048`: Data Principal Rights & Grievance Case Management
- **Owning Module:** Privacy Operations
- **Primary Persona:** Tenant Administrator; System Administrator for platform-controlled processing
- **Priority:** P0
- **Operational Statement:** The service must support receipt, identity verification, routing, tracking, response, and evidence retention for Data Principal requests and grievances concerning access to information, correction, erasure, consent withdrawal, grievance redressal, and nomination, as applicable, including for individuals who do not hold application accounts. Requests must be routed to the responsible Data Fiduciary and handled within the applicable statutory or approved contractual time limit. A request channel must be available without requiring a general customer or supplier portal account.
- **Data Attributes:** Request ID, Data Principal Identifier, Tenant/Platform Scope, Request Type, Verification Evidence, Responsible Fiduciary, Received/Due/Resolved Timestamps, Disposition, Response Evidence.
- **Acceptance Intent:** Requests are not silently lost or fulfilled against the wrong tenant; authorized operators can track deadlines, exceptions, approvals, and completion evidence while preserving tenant isolation.
#### `BRD-FR-049`: Personal Data Breach Response Coordination
- **Owning Module:** Privacy Operations & Security Operations
- **Primary Persona:** System Administrator; Tenant Administrator for tenant-scoped incidents
- **Priority:** P0
- **Operational Statement:** The service must support recording, triaging, investigation, impact assessment, remediation, and notification coordination for suspected or confirmed personal-data breaches. The platform operator must be able to identify affected tenants and notify the responsible tenant Data Fiduciary promptly when acting as its Data Processor. The workflow must support applicable notification content and deadlines to affected Data Principals and the Data Protection Board, including phased or subsequently amended statutory requirements.
- **Data Attributes:** Incident ID, Detection Time, Affected Data/Tenants/Principals, Processor/Fiduciary Roles, Severity, Timeline, Evidence, Mitigation, Notifications and Delivery Status.
- **Acceptance Intent:** Each incident has an accountable owner and audit trail; the responsible Data Fiduciary can assemble required facts and evidence for notifications and demonstrate completion within applicable deadlines.
#### `BRD-FR-050`: Purpose-Aware Retention, Erasure & Legal Hold
- **Owning Module:** Privacy Operations & Data Governance
- **Primary Persona:** Tenant Administrator; System Administrator for platform-controlled processing
- **Priority:** P0
- **Operational Statement:** Use four internal sensitivity levels—Public, Internal, Confidential, and Restricted—with a separate personal-data flag and processing-purpose tag; these are product handling labels, not statutory DPDP classifications. The responsible Data Fiduciary must approve retention schedules by personal-data category and processing purpose after legal/accounting review (tenant firms for trading data; ATB operator for its own account, security, and service data). Authorized operators must be able to apply these schedules by tenant/platform responsibility and applicable legal obligation. The service must support correction, erasure or irreversible de-identification when required, legal holds and statutory retention exceptions, and deletion handling for derived copies and processors, including backups according to the approved schedule. Statutory processing-log retention requirements must be represented separately from general business-record retention.
- **Data Attributes:** Data Category, Purpose, Responsible Fiduciary, Retention Rule, Trigger Date, Legal Basis/Exception, Hold Status, Erasure/De-identification Evidence, Processor Completion.
- **Acceptance Intent:** Data is not erased while an applicable hold or mandatory retention obligation applies; once all approved purposes and legal exceptions expire, erasure is trackable across applicable system copies and contracted processors.
#### `BRD-FR-051`: Data Processor & Subprocessor Governance
- **Owning Module:** Platform Governance
- **Primary Persona:** System Administrator
- **Priority:** P0
- **Operational Statement:** The platform operator must maintain an inventory of processors and subprocessors used for tenant personal data, their processing purpose and location, applicable safeguards and contractual obligations, and status of due diligence. The operator must support tenant Data Fiduciaries with information and operational assistance needed for security safeguards, Data Principal requests, breach response, retention, and erasure obligations.
- **Data Attributes:** Processor/Subprocessor, Processing Purpose, Data Categories, Processing Location, Contract/Safeguard Reference, Due-Diligence Status, Incident/Request Assistance Record.
- **Acceptance Intent:** Processor and subprocessor relationships are identifiable and reviewable; support actions are attributable and consistent with documented tenant instructions and applicable contractual safeguards.
#### `BRD-FR-052`: Tenant Operating Policy Configuration & Audit
- **Owning Module:** Tenant Business Administration
- **Primary Persona:** Partner / Managing Director; authorized tenant functional managers
- **Priority:** P0
- **Operational Statement:** The service must provide tenant-scoped configuration for the provisional operating thresholds listed in §6.2, including market-price variance, weighment shortage, bag tare/packing, commodity quality grading/deductions, credit exposure, warehouse capacity/adjustments/transfers, dispatch tolerances, and alert timing. Policies must support commodity, grade, contract, or other applicable scope and effective dates where needed. Only roles authorized in the tenant permission model may change them; changes must record actor, timestamp, reason, prior value, and new value. Seed values remain provisional. Before each affected live workflow is enabled for a tenant, that tenant’s Partner/Managing Director or delegated authorized business owner must review and confirm or edit every applicable threshold. Missing or unreviewed thresholds block only the affected risk-sensitive workflow. Confirmed policies are versioned with an effective date and changes are audited.
- **Data Attributes:** Tenant ID, Policy Type, Scope (Commodity/Grade/Contract), Value, Unit, Effective From/To, Changed By/At, Reason, Prior Value.
- **Acceptance Intent:** One tenant’s policy never changes another tenant’s behavior. Applicable policy versions can be identified for every governed transaction; unauthorized or unaudited changes are rejected. Candidate values are never silently treated as universally validated rules; the affected workflow remains disabled for a tenant until its authorized business owner confirms or edits the applicable values.
---
## 6. Non-Functional Requirements & Constraints (`BRD-NFR-xxx`)
| NFR ID | Requirement Area | Statement & Quantitative Metric | Priority |
|---|---|---|---|
| `BRD-NFR-001` | Commercial Calculation Integrity | Dual-unit mathematical conversions ($\text{Value} = \text{MT} \times 10 \times \text{Rate}_{\text{Qtl}}$) and bag tare deductions must maintain decimal precision to 3 decimal places for weight and 2 decimal places for currency without rounding drift. | P0 |
| `BRD-NFR-002` | UI Rendering Performance | Web views, forms, and executive dashboards must achieve page load rendering times $\le 1.5\text{ seconds}$ on standard broadband (10 Mbps). | P0 |
| `BRD-NFR-003` | API Latency SLAs | Standard resource CRUD endpoints and list filter queries must achieve response latencies $\le 250\text{ ms}$ (p95) under normal operating load. | P0 |
| `BRD-NFR-004` | High-Volume Reporting SLA | 20-day trading trend snapshots and multi-godown stock position reports must generate in $\le 1.0\text{ second}$ for a tenant with historical ledgers containing $\ge 50,000$ transaction rows. | P0 |
| `BRD-NFR-005` | Programmatic FSM Invariant Protection | Finite State Machines for Lot Quality (`Under QC` $\rightarrow$ `QC Hold` / `Released`) and Outbound Dispatches must be enforced in backend domain logic, preventing client-side or API bypass. | P0 |
| `BRD-NFR-006` | Tenant Data Isolation | Tenant data must remain isolated according to the row-level security model configured in `tech-profile.yaml`; unauthorized cross-tenant access must be prevented and tested. | P0 |
| `BRD-NFR-007` | Offline Sandbox Testability | Configured identity, payment, and messaging integration adapters must provide deterministic local mocks capable of offline, reproducible verification without external network access. | P0 |
| `BRD-NFR-008` | Automated Test Coverage Budgets | Code must meet UP-AI differentiated coverage budgets: $\ge 95\%$ statement/branch coverage for backend domain services and FSMs, $\ge 90\%$ for sandbox adapters, and $\ge 80\%$ for frontend components. | P0 |
| `BRD-NFR-009` | Application Security Assurance | The v1 launch is India-first and must support compliance with India’s Digital Personal Data Protection Act, 2023 and the DPDP Rules applicable at production launch. Supporting tenants subject to other jurisdictions requires a separate legal and privacy assessment before onboarding. Application-security verification must target OWASP ASVS v5.0.0 Level 2. Applicable requirements must be mapped to verification evidence; any non-applicable requirement or exception must be documented with rationale and an accountable owner. Authentication, session handling, authorization, input validation, secure configuration, and sensitive-data protections in transit and at rest must be verified before production release. The compliance design must account for phased commencement and be revalidated against current official notifications before release. | P0 |
| `BRD-NFR-010` | Tenant Isolation Assurance | Tenant isolation must fail closed across synchronous and asynchronous paths, including APIs, database connections, exports, files, caches, scheduled jobs, and support tooling. Automated tests must include cross-tenant negative cases and privileged-role bypass cases. | P0 |
| `BRD-NFR-011` | Availability and Recoverability | Production service availability must be at least 99.9% per month, measured 24/7. Recovery time objective (RTO) must be no more than 4 hours and recovery point objective (RPO) no more than 15 minutes. Backups must be encrypted, taken daily, support point-in-time recovery, and be retained for 35 days. Restore exercises must be performed quarterly and their results recorded before production release. | P0 |
| `BRD-NFR-012` | Capacity and Tenant Fairness | The initial production capacity-planning envelope is 50 tenant firms, up to 25 named users per tenant, and 250 concurrent active users across the service. Report performance must be validated with at least 50,000 ledger rows for a tenant. Load-test the platform for 200 core business documents per tenant per operating day and a 5× peak-hour burst, across the approved tenant/user envelope. This is a provisional capacity-planning scenario, not a customer usage cap. No fixed business-document quota is imposed by this planning envelope. Per-tenant resource use must be observable, with configurable early warnings near the tested fair-share budget. Under contention, the service may apply backpressure or temporarily throttle resource-intensive reports and bulk exports to protect service levels, while preserving and safely reporting the outcome of accepted core business transactions. Numeric fair-share budgets and alert thresholds must be set from architecture/load-test evidence. | P0 |
| `BRD-NFR-013` | Operational Observability | Production operations must provide service-level and tenant-scoped health, error, latency, and workload signals with actionable alerts. Logs and telemetry must carry tenant/correlation context where authorized and must exclude secrets and unnecessary sensitive business data. | P0 |
| `BRD-NFR-014` | Data Governance and Retention | The service must define and enforce four internal sensitivity levels (Public, Internal, Confidential, Restricted), with personal-data and processing-purpose tags applied independently, alongside purpose-aware retention, Data Principal request handling, export, correction, erasure, and legal-hold handling, including tenant closure, in support of applicable DPDP obligations and other applicable laws. These internal labels do not represent statutory DPDP categories. Each responsible Data Fiduciary must approve retention durations by category and purpose after legal/accounting review. The system must preserve applicable statutory minimums and legal holds, and support erasure when purposes and retention obligations end. Backup, processing-log, and audit-data retention and access must follow the approved policy and applicable statutory periods. | P0 |
### 6.1 Active Technology Constraints
The business requirements must be implemented using the active [`tech-profile.yaml`](../tech-profile.yaml): modular monolith; Python/FastAPI backend with SQLAlchemy, Alembic, and REST/OpenAPI; React/TypeScript frontend with Zustand and Tailwind/shadcn, using a Node.js frontend toolchain; Keycloak with OIDC/PKCE and JWT bearer tokens; RBAC/ABAC authorization; PostgreSQL with row-level security for tenant isolation; and Valkey for cache/streams. The profile configures deterministic sandboxes for identity, payment, and messaging. Frontend unit/component testing uses Vitest and browser E2E uses Playwright. These implementation constraints supersede conflicting technology references in the supplied backup PRD. The Node.js version is not specified in the profile.
### 6.2 Candidate Values Requiring Domain Review
The stakeholder accepted the reference values below as configurable seed candidates, scoped by tenant and, where applicable, commodity or contract. They are not universal business rules. Each tenant’s Partner/Managing Director or delegated authorized business owner must review and confirm or edit applicable values before the affected workflow is enabled; changes must be effective-dated and audited under `BRD-FR-052`.
| Area | Candidate value from reference | Validation needed |
|---|---|---|
| Mandi price variance | Warn when offered price is more than 5% above modal price. | Confirm benchmark and warning threshold. |
| Inward shortage | Warn above 0.5% variance; require Purchase Manager approval above 2.0%. | Confirm tolerance and approval authority. |
| Bag tare and packing | Default tare: 1.0 kg per gunny/jute bag and 0.2 kg per HDPE/plastic bag; nominal bags 50 kg or 100 kg. | Confirm packaging types, tare policy, and commercial treatment. |
| Quality grading | Example baseline moisture 10%; example deduction ₹10/Qtl per 0.5% excess; hold above 12% moisture or 2% foreign matter. | Confirm per-commodity/contract thresholds, calculation, and release authority. |
| Credit exposure | Warning above 80%; hard block above 100%; Partner/MD override. | Confirm exposure formula, limits, and override policy. |
| Warehouse/inventory | Capacity warning above 85%; partner sign-off for adjustments above 1%; inter-godown transfer tolerance ±0.2%. | Confirm capacity basis, stock-loss controls, and transfer tolerance. |
| Dispatch/delivery | Outward load tolerance ±1%; Sales Manager approval for customer shortage above 2%. | Confirm weighment and claim rules. |
| Alerts and performance | QC pending alert after 24 hours; UI ≤1.5 s; API p95 ≤250 ms; reports ≤1 s at 50,000 rows. | Confirm operating hours, data volume, measurement conditions, and service targets. |
| Platform availability and recovery | 99.9% monthly 24/7 availability; RTO ≤4 hours; RPO ≤15 minutes; encrypted daily backups with point-in-time recovery, 35-day retention, and quarterly restore exercises. | Validate the hosting design and restore evidence against the approved targets before production. |
| Platform scale | Planning envelope: 50 tenants, 25 named users per tenant, 250 concurrent users service-wide; 200 business documents per tenant per operating day with a 5× peak-hour burst; reports at 50,000 ledger rows per tenant. | Validate through load tests; set numeric per-tenant resource limits and refine estimates with pilot/operating data. |
| Security/compliance level | India DPDP Act and the Rules applicable at production launch are in v1 scope; OWASP ASVS v5.0.0 Level 2 is the verification target. | Confirm remaining legal/data-role mappings and validate the target against the current regulatory and threat context before production. |
Coverage budgets, test dimensions, and test levels are governed by the active technology profile and UP-AI process rather than the backup PRD.
### 6.3 Multi-Tenant Platform Security and Operations References
- [OWASP Application Security Verification Standard (ASVS)](https://github.com/OWASP/ASVS) — candidate source for selecting testable application-security controls and verification rigor.
- [PostgreSQL Row Security Policies](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) — behavior and privileged-role considerations for the configured row-level security model.
- [AWS SaaS Lens](https://docs.aws.amazon.com/wellarchitected/latest/saas-lens/definitions.html) — reference concepts for tenant isolation, onboarding, tenant-aware operations, and noisy-neighbor management.
---
## 7. Scope Boundaries & Explicit Anti-Scope
### 7.1 In Scope for Version 1.0 (MVP)
- All 52 functional features (`BRD-FR-001` through `BRD-FR-052`) and 14 NFRs across the 11 reference operational areas plus tenant platform and privacy/security capabilities.
- Application architecture and technology implementation as configured in `tech-profile.yaml`.
- Complete operational workflows matching the RamDayal prototype demonstration dataset.
- Responsive web UI accessible on desktop and mobile godown tablets.
- Automated multi-path test suites ($\ge 95\%$ domain coverage) and 21-sheet Excel QA Workbook compilation.
### 7.2 Explicit Anti-Scope (Deferred to Future Releases)
- **Direct ERP/accounting platform integration:** External ERP or accounting-ledger integrations are deferred unless separately approved.
- **Hardware Serial Weighbridge Drivers:** Manual entry and supervisor verification of weighbridge tickets; direct COM port/IP serial driver ingestion deferred.
- **Continuous GPS Vehicle Telematics:** Vehicle transit state managed via Dispatch Board FSM; live satellite map streaming deferred.
- **National e-NAM Bidding API:** Electronic auction bidding with national government portals deferred.
- **Multi-Currency / Forex Settlement:** Transactions strictly denominated in Indian National Rupees (INR / ₹).
- **Lab Spectrometry Hardware Ingestion:** Quality Officer enters physical test parameters manually after inspection.
- **External customer/supplier self-service access:** Customer and supplier records are managed internally; external logins and portals are deferred. Rights requests must still be accepted through an appropriate published contact/request channel.
- **Non-India jurisdiction onboarding:** Defer onboarding tenants subject to other jurisdictions until a separate legal and privacy assessment is completed.
- **Intentional processing of under-18s’ personal data:** No child-directed or intentional under-18 data processing use case is planned for v1; any such intended processing requires legal/privacy assessment and approved controls before baseline.
---
## 8. Requirements Traceability Root Matrix
| Module | Granular Feature IDs | Priority | Candidate Use-Case Group (ID to be minted at Stage 5) |
|---|---|---|---|
| **Market Desk** | `BRD-FR-001`–`BRD-FR-004` | P0 / P1 | Market intelligence and price tracking |
| **Procurement (Sauda)** | `BRD-FR-005`–`BRD-FR-007` | P0 / P1 | Mandi purchase booking and supplier terms |
| **Goods Receipt (GRN)** | `BRD-FR-008`–`BRD-FR-012` | P0 | Inward weighbridge and godown intake |
| **Quality & Lots** | `BRD-FR-013`–`BRD-FR-017` | P0 / P1 | Lot inspection, disposition, and traceability |
| **Warehouse Inventory** | `BRD-FR-018`–`BRD-FR-020` | P0 | Stock ledger, capacity, and transfers |
| **Sales Orders** | `BRD-FR-021`–`BRD-FR-023` | P0 | Sales contracts, credit check, and allocation |
| **Logistics & Dispatch** | `BRD-FR-024`–`BRD-FR-026` | P0 | Outbound dispatch and delivery confirmation |
| **Fleet Management** | `BRD-FR-027` | P1 | Vehicle registry and availability |
| **Customer Receivables** | `BRD-FR-028`–`BRD-FR-030` | P0 | Customer ledger and credit controls |
| **Payments & Expenses** | `BRD-FR-031`–`BRD-FR-033` | P0 / P1 | Payment receipts, payables, and expenses |
| **Alerts & Dashboard** | `BRD-FR-034`–`BRD-FR-036` | P0 | Operational alerts and management analytics |
| **Master Data & Business Security** | `BRD-FR-037`–`BRD-FR-041` | P0 | Master data, business roles, and transaction audit |
| **Tenant Platform & Isolation** | `BRD-FR-042`–`BRD-FR-046` | P0 | Tenant lifecycle, membership, isolation, and support access |
| **Privacy Operations & DPDP Support** | `BRD-FR-047`–`BRD-FR-051` | P0 | Processing transparency, Data Principal requests, breach response, retention, and processor governance |
| **Tenant Operating Policy Configuration** | `BRD-FR-052` | P0 | Tenant-scoped, authorized, effective-dated configuration and audit of operational thresholds |

View File

@ -2,16 +2,19 @@
| Field | Value |
|---|---|
| **Governed Standard** | SEI-CMMI Level 3 (UP-AI v1.0) |
| **Document Path** | `04_generated_documentation/00_process_control/ambiguity_register.md` |
| **Last Updated** | 2026-09-03 |
| **Project** | Agriculture Trading Backoffice (`ATB`) |
| **Process** | UP-AI v1.5 |
| **Last Updated** | 2026-10-11 |
---
## Ambiguity Lifecycle
Open requirements questions, ambiguous edge cases, and underspecified third-party integration contracts are tracked here (`AMB-xxx`). Unresolved questions MUST NOT be guessed by AI agents.
Open requirements questions are tracked here (`AMB-xxx`). Unresolved business rules will not be inferred from the illustrative mockup.
| ID | Date | Stage | Ambiguity / Question | Context & Impact | Resolution / Decision | Status | Resolved By |
|---|---|---|---|---|---|---|---|
| AMB-001 | 2026-09-03 | Stage 0 | Session timeout duration and refresh token rotation policy for web portals vs. mobile clients. | Impacts session management in LLD-001 Auth Service. | Standardize on 15-minute access token and 7-day refresh token with rotation. | Resolved | `DEC-002` / Security Lead |
| AMB-001 | 2026-10-11 | Stage 0B | What measured baseline and target values define success for the proposed v1 efficiency KPIs? | The accepted business direction identifies paper handoffs, dual-unit errors, QC segregation, credit exposure, and multi-godown reconciliation as problems. Lot traceability, QC dispatch prevention, and credit controls are hard invariants. The accepted protocol measures a representative tenant for 30 operating days before rollout and 30 operating days after rollout, using manual effort per transaction, gate-in-to-stock-posting time, and stock-reconciliation variance by godown/commodity. | Measurement approach resolved in `DEC-019`: establish the manual baseline before rollout, repeat the measurements for 30 operating days after rollout, then have the business owner set numeric improvement targets from the observed results. Numeric values remain open pending pilot evidence and review. | Open | Stakeholder, 2026-10-11 |
| AMB-002 | 2026-10-11 | Stage 0B | Are the proposed internal roles and lack of external customer/supplier logins correct for v1? | A tenant is an independent trading enterprise with its branches and godowns inside the tenant boundary. The stakeholder accepted the proposed business requirements, including internal roles and no external portals for v1. | Accepted in the stakeholder direction for the PRD draft. | Resolved | Stakeholder, 2026-10-11 |
| AMB-003 | 2026-10-11 | Stage 0B | How should the proposed numeric operating values from the reference be applied when their appropriateness varies by tenant, commodity, or contract? | Stakeholder accepted the business scope and all 11 mockup areas, and accepted the reference values as configurable tenant-scoped seed candidates. | Resolved: the values are not universal defaults. Each tenant’s Partner/Managing Director or delegated authorized business owner must confirm or edit applicable thresholds before affected risk-sensitive workflows are enabled; only those affected workflows remain blocked for missing/unreviewed values. Policies are effective-dated and changes audited per `BRD-FR-052`. | Resolved | Stakeholder, 2026-10-11 |
| AMB-004 | 2026-10-11 | Stage 0B | How are tenants onboarded and suspended, and may one user hold memberships in multiple tenant firms? | Tenant lifecycle and membership management affect identity and administration design. | Resolved: v1 has no public self-service signup; an authorized platform administrator provisions and activates tenants. A person may belong to multiple tenants and explicitly selects the active tenant after sign-in; server-side membership and role checks apply on every request. Captured in `BRD-FR-042`–`BRD-FR-044`. | Resolved | Stakeholder, 2026-10-11 |
| AMB-005 | 2026-10-11 | Stage 0B | Who may approve exceptional cross-tenant support access, and what tenant notification/review is required? | Support access to tenant business data must be exceptional, attributable, and reviewable. | Resolved: no standing support access; ordinary case-specific access requires Tenant Administrator approval and is time-limited. A designated platform security administrator may grant break-glass access for at most one hour during an urgent incident, recording the reason, generating an immediate audit alert, and notifying the tenant administrator within one business day. Captured in `BRD-FR-046`. | Resolved | Stakeholder, 2026-10-11 |
| AMB-006 | 2026-10-11 | Stage 0B | What actual retention durations and additional India-specific sectoral/contractual obligations apply to v1? | The stakeholder accepted the SaaS privacy roles, India-first scope, all-natural-person coverage, four internal sensitivity labels with separate personal-data/purpose tags, category/purpose retention governance, OWASP ASVS v5.0.0 Level 2, and the review path: tenant legal/accounting reviewers approve trading-data purposes/retention; the ATB operator’s qualified privacy/legal reviewer approves platform processing, retention, and processor obligations. Exact durations and other legal/contractual duties remain unconfirmed. The Act/Rules have phased commencement. | PRD captures accepted policy in `BRD-FR-047`–`BRD-FR-051` and `BRD-NFR-009`/`BRD-NFR-014`. Record qualified review evidence for actual durations and other obligations before baseline; revalidate current requirements before production. | Open | — |
| AMB-007 | 2026-10-11 | Stage 0B | What production availability, backup retention, RTO, and RPO targets are acceptable? | These targets determine hosting, data protection, recovery design, and support commitments. | Resolved: 99.9% monthly availability measured 24/7; RTO ≤4 hours; RPO ≤15 minutes; encrypted daily backups with point-in-time recovery and 35-day retention; quarterly restore exercises. Captured in `BRD-NFR-011`. | Resolved | Stakeholder, 2026-10-11 |
| AMB-008 | 2026-10-11 | Stage 0B | What tenant count, active-user count, transaction volume, peak concurrency, and per-tenant limits must the platform support? | Stakeholder approved an initial envelope of 50 tenant firms, 25 named users per tenant, and 250 concurrent active users service-wide. The approved provisional planning scenario is 200 core business documents per tenant per operating day with a 5× peak-hour burst. Stakeholder accepted no fixed business-document quota; observe per-tenant use, provide configurable early warnings near the tested fair-share budget, and protect core transactions while using backpressure/temporary throttling for expensive reports or bulk exports under contention. Numeric fair-share budgets and alert thresholds still require architecture/load-test evidence and later pilot refinement. | Partially resolved: approved 50 tenant firms, up to 25 named users per tenant, 250 concurrent active users service-wide, and 50,000 ledger rows per tenant for report validation. The 200 documents/tenant/operating day and 5× peak-hour burst scenario has been accepted for load testing; set numeric fair-share budgets and alert thresholds from architecture/load-test evidence and refine them with pilot telemetry; see `BRD-NFR-004` and `BRD-NFR-012`. | Open | — |

View File

@ -2,16 +2,13 @@
| Field | Value |
|---|---|
| **Governed Standard** | SEI-CMMI Level 3 (UP-AI v1.0) |
| **Document Path** | `04_generated_documentation/00_process_control/assumptions_register.md` |
| **Last Updated** | 2026-09-03 |
---
| **Project** | Agriculture Trading Backoffice (`ATB`) |
| **Process** | UP-AI v1.5 |
| **Last Updated** | 2026-10-11 |
## Active Assumptions
No unapproved business assumptions are being used to complete the PRD draft. Candidate numeric policies are listed in the ambiguity register and marked provisional. Technical choices in `tech-profile.yaml` are known configuration facts, not assumptions.
| ID | Date | Stage | Assumption | Basis | Risk Level | Status | Superseded By |
|---|---|---|---|---|---|---|---|
| ASM-001 | 2026-09-03 | Stage 0 | Target architecture is a modular monolith with Row-Level Security (RLS) tenant isolation per `tech-profile.yaml`. | Standard UP-AI greenfield profile baseline. | Low | Active | — |
| ASM-002 | 2026-09-03 | Stage 0 | Authentication is delegated to an OIDC provider (Keycloak) using Authorization Code Flow with PKCE. | Enterprise identity architecture standard. | Low | Active | — |
| ASM-003 | 2026-09-03 | Stage 0 | All third-party external integrations will provide deterministic Wave 0 mock adapters for 100% offline CI/CD execution. | UP-AI v1.0 deterministic testability standard. | Low | Active | — |

View File

@ -0,0 +1,25 @@
# Checkpoint 006 — ATB Requirements Elicitation
- **Checkpoint ID:** `CKPT-006`
- **Date:** 2026-10-11
- **Active Stage:** Stage 0B — Requirements elicitation
- **Active Track:** Greenfield, India-first, multi-tenant Agriculture Trading Backoffice (ATB)
- **Active Skill:** `up-requirements-elicit`
- **PRD Status:** Draft; stakeholder review/baseline approval not yet given
## Completed in this Session
- Expanded `01_BRD/PRD_Specification.md` to 52 functional requirements and 14 NFRs. Added tenant platform, DPDP privacy operations, configurable policy thresholds, and production operations/security constraints.
- Updated `04_generated_documentation/00_process_control/ambiguity_register.md`, `decision_log.md`, and `master_context.md`. Decisions DEC-002 through DEC-019 capture stakeholder resolutions.
- Maintained conversation transcript at `prompts/20261011T074829Z-session-greenfield-bootstrap.md`.
- Validated 52 unique FR IDs and 14 unique NFR IDs; scoped `git diff --check` passed. No tests or traceability gates run.
- **Latest completed decision:** `DEC-019` — accepted representative-tenant KPI protocol: 30 operating days of manual baseline before rollout and 30 operating days after rollout, then set targets from measured results.
## Mid-flight / Still Open
- `AMB-001`: collect the accepted 30-operating-day pre-rollout manual baseline and 30-operating-day post-rollout results; business owner to set efficiency targets from evidence.
- `AMB-006`: qualified-review path accepted; collect evidence for exact retention schedules and other applicable legal/contractual obligations; revalidate DPDP commencement before release.
- `AMB-008`: set fair-share resource budgets and alert thresholds from architecture/load-test evidence and pilot telemetry.
- Review the Draft PRD with the stakeholder; baseline only after all required decisions and qualified reviews are resolved.
## Exact Next Action
Prepare the Stage 0B Human Review Brief and review the Draft PRD with the stakeholder. The measurement approach for `AMB-001` is resolved, but pilot data is pending; `AMB-006` needs qualified legal/accounting review evidence for retention durations and other applicable obligations; `AMB-008` needs architecture/load-test evidence and pilot telemetry for numeric fair-share budgets. Keep the PRD Draft; do not invoke Stage 1 `up-brd-extract` until required evidence is available and the stakeholder explicitly approves baseline.

View File

@ -5,7 +5,7 @@
| **Governed Standard** | SEI-CMMI Level 3 (UP-AI v1.3) |
| **Document Path** | `04_generated_documentation/00_process_control/checkpoints/checkpoint_index.md` |
| **Gated By** | `up-context-checkpoint` |
| **Last Updated** | 2026-10-03 |
| **Last Updated** | 2026-10-11 |
---
@ -22,3 +22,4 @@
| `CKPT-006` | 2026-10-11 | Stage 0B (Requirements elicitation / Inception) | ATB draft PRD expanded to 52 FRs and 14 NFRs; decisions recorded through DEC-019, including the accepted pre/post pilot KPI measurement protocol. | `AMB-001`, `AMB-006`, and `AMB-008` remain open for pilot results, qualified legal/accounting evidence, and load-test/pilot telemetry; PRD baseline approval pending. | Prepare Stage 0B Human Review Brief and review the Draft PRD; collect evidence for the remaining ambiguities, then obtain explicit baseline approval before Stage 1. | `checkpoint-006-atb-requirements-elicitation.md` |

View File

@ -2,16 +2,34 @@
| Field | Value |
|---|---|
| **Governed Standard** | SEI-CMMI Level 3 (UP-AI v1.0) |
| **Document Path** | `04_generated_documentation/00_process_control/decision_log.md` |
| **Last Updated** | 2026-09-03 |
| **Project** | Agriculture Trading Backoffice (`ATB`) |
| **Process** | UP-AI v1.5 |
| **Last Updated** | 2026-10-11 |
---
## Architectural & Process Decisions
## Decisions
Project decisions made during requirements elicitation and bootstrap are recorded below. The active archetype and technology selections remain in `tech-profile.yaml`.
| ID | Date | Stage | Decision | Rationale | Alternatives Considered | Impact | Made By |
|---|---|---|---|---|---|---|---|
| DEC-001 | 2026-09-03 | Stage 0 | Adopt Modular Monolith with Row-Level Security for Phase 1. | Maximizes initial construction velocity while guaranteeing strict tenant data isolation from day one. | Microservices-from-day-one; separate DB per tenant. | Scopes Phase 1 architecture to internal module boundaries. | Lead Architect |
| DEC-002 | 2026-09-03 | Stage 0 | Standardize on Keycloak OIDC with Authorization Code Flow & PKCE. | Industry standard protocol supporting multi-tenancy, RBAC, and standard JWT claims. | Custom homegrown auth; Auth0 cloud-only. | All frontend portals use standard Keycloak OIDC redirects. | Security Lead |
| DEC-003 | 2026-09-03 | Stage 0 | Enforce ≥95.0% automated multi-path test coverage at Gate 14.1. | Prevents silent regression debt and ensures multi-dimensional test verification across all user stories. | 80% line coverage; manual testing only. | Requires Happy, Alternate, Negative, and FSM tests per story. | QA Lead |
| DEC-001 | 2026-10-11 | Stage 0B | Adopt the accepted agricultural trading business direction and all 11 mockup areas as the v1 PRD draft scope; use the backup PRD for business requirements only and derive implementation technology from `tech-profile.yaml`. | Stakeholder accepted the proposed business requirements and clarified that the backup comes from a different technology stack. | Narrower mockup scope; adopting the backup PRD’s Frappe/MariaDB architecture. | Creates a 52-feature business draft for review; numeric operating thresholds remain provisional, and the active FastAPI/React/PostgreSQL profile remains authoritative. | Stakeholder |
| DEC-002 | 2026-10-11 | Stage 0B | Use administrator-provisioned tenant onboarding in v1, allow users to hold memberships in multiple tenants, and require explicit active-tenant selection with server-side membership/role verification on each request. | Prevents unreviewed tenant creation and makes tenant context explicit while supporting staff or principals who work across firms. | Public signup; single-tenant-only identity. | Updates `BRD-FR-042`–`BRD-FR-044`; public tenant self-registration is out of v1 scope. | Stakeholder |
| DEC-003 | 2026-10-11 | Stage 0B | Deny standing support access to tenant business data; require tenant-admin approval for ordinary case-specific access; allow a designated platform security administrator to use a maximum one-hour break-glass grant for urgent incidents, with reason, immediate alert, and tenant-admin notice within one business day. | Enables necessary support while constraining and exposing privileged access. | Persistent support access; no emergency path. | Updates `BRD-FR-046` and the support-access workflow and audit requirements. | Stakeholder |
| DEC-004 | 2026-10-11 | Stage 0B | Target compliance with India’s Digital Personal Data Protection Act, 2023 and DPDP Rules applicable at production launch; revalidate the phased commencement and current official requirements before release. | Stakeholder identified Indian DPDP compliance as a v1 product requirement. | No DPDP target; treat statute as already fully commenced regardless of official phase-in. | Updates `BRD-NFR-009` and `BRD-NFR-014`; detailed SaaS roles and compliance workflows were subsequently accepted in `DEC-005`; remaining legal mapping and schedules stay open under `AMB-006`. | Stakeholder |
| DEC-005 | 2026-10-11 | Stage 0B | Treat each tenant as Data Fiduciary for its tenant trading data and the ATB operator as Data Processor for that data, while the operator is Data Fiduciary for its own account, security, and service-operations data; include processing transparency/consent where applicable, Data Principal requests and grievances, breach coordination, retention/erasure/legal holds, and processor/subprocessor governance. | Fits a multi-tenant SaaS service where firms determine trading-data purposes while the vendor operates the service; builds product support for DPDP obligations across both roles. | Treat platform vendor as sole Data Fiduciary for every data category; exclude privacy operations from product scope. | Adds `BRD-FR-047`–`BRD-FR-051`; specific lawful-basis mappings, retention values, statutory applicability, and legal validation remain subject to `AMB-006`. | Stakeholder |
| DEC-006 | 2026-10-11 | Stage 0B | Set production availability to at least 99.9% monthly measured 24/7, RTO ≤4 hours, RPO ≤15 minutes, encrypted daily backups with point-in-time recovery retained 35 days, and quarterly restore exercises. | Provides a measurable initial service continuity target with recoverability evidence. | Targets to be decided later; tighter availability/recovery objectives. | Updates `BRD-NFR-011`; hosting and architecture must demonstrate the targets before production. | Stakeholder |
| DEC-007 | 2026-10-11 | Stage 0B | Use an initial production capacity-planning envelope of 50 tenant firms, up to 25 named users per tenant, and 250 concurrent active users service-wide; validate tenant reports with at least 50,000 ledger rows. | Gives initial sizing and performance-test targets for architecture validation without imposing customer seat caps. | Smaller pilot-only capacity; larger initial envelope. | Updates `BRD-NFR-004` and `BRD-NFR-012`; daily transaction volume, peak-hour write rate, and numeric per-tenant limits remain open under `AMB-008`. | Stakeholder |
| DEC-008 | 2026-10-11 | Stage 0B | Use a provisional capacity-planning load of 200 core business documents per tenant per operating day with a 5× peak-hour burst across the approved 50-tenant/user envelope; treat this as a load-test scenario, not a customer usage cap. | Provides an initial stress profile that can be validated and refined with pilot telemetry. | No initial transaction profile; a contractual usage quota. | Updates `BRD-NFR-012`; numeric per-tenant resource limits remain open under `AMB-008`. | Stakeholder |
| DEC-009 | 2026-10-11 | Stage 0B | Do not impose fixed business-document quotas; observe tenant-level resource use, provide configurable early warnings near tested fair-share budgets, protect core transactions, and use backpressure/temporary throttling on expensive reports or bulk exports under contention. Set numeric fair-share budgets and alert thresholds from load-test evidence. | Avoids arbitrary tenant business caps while protecting shared-service quality. | Fixed document quota; no per-tenant controls; indiscriminate throttling of core transactions. | Updates `BRD-NFR-012`; numerical budgets/thresholds remain an architecture/load-test item under `AMB-008`. | Stakeholder |
| DEC-010 | 2026-10-11 | Stage 0B | Treat the §6.2 reference operating thresholds as configurable seed defaults, scoped by tenant and where applicable by commodity/contract; restrict changes through tenant roles and audit effective-dated changes. Keep numeric values provisional until trading-domain validation. | Provides usable configuration starting points while avoiding unsupported universal rules. | Hard-code reference thresholds globally; treat them as verified policy without domain review. | Adds `BRD-FR-052`; numeric validation remains open under `AMB-003`. | Stakeholder |
| DEC-011 | 2026-10-11 | Stage 0B | Treat lot traceability, prevention of QC-hold dispatch, and credit-block enforcement as hard invariants; measure current manual effort, gate-in-to-stock-posting time, and stock-reconciliation variance during a representative 30-day pilot and set improvement targets from observed baselines. | Avoids inventing savings targets while retaining measurable operational outcomes and non-negotiable controls. | Set unsupported percentage improvements before baseline evidence. | Updates PRD §1.3; actual baseline/target values remain open under `AMB-001`. | Stakeholder |
| DEC-012 | 2026-10-11 | Stage 0B | Use OWASP ASVS v5.0.0 Level 2 as the application-security verification target; map applicable requirements to evidence and document non-applicable requirements/exceptions with rationale and an accountable owner. | The product handles sensitive business and personal data and significant B2B transactions; Level 2 is an appropriate baseline. | No selected standard; Level 1 or Level 3 target. | Updates `BRD-NFR-009`; verify against the regulatory/threat context before production. | Stakeholder |
| DEC-013 | 2026-10-11 | Stage 0B | Scope v1 to India-first tenants; assess other jurisdictions before onboarding there. DPDP privacy controls cover every natural person whose data the tenant or platform processes, including contacts without app accounts. No intentional under-18 personal-data use case is planned for v1; any such use requires legal/privacy assessment and approved controls before baseline. | Sets a clear initial legal operating boundary while covering business-contact data and avoiding an unevaluated child-data use case. | International tenant onboarding without jurisdiction review; restrict rights support to account holders. | Updates `BRD-NFR-009`, `BRD-FR-047`–`BRD-FR-048`, and §7.2; remaining legal mapping and retention questions stay under `AMB-006`. | Stakeholder |
| DEC-014 | 2026-10-11 | Stage 0B | Require the responsible Data Fiduciary to approve retention schedules by personal-data category and purpose after legal/accounting review; preserve statutory minimums and legal holds, then support erasure when purposes and retention obligations end. Tenant firms own trading-data schedules; the ATB operator owns schedules for its own processing. | Avoids one ungrounded global duration and aligns retention responsibility with the accepted SaaS role split. | Fixed global retention duration; unrestricted retention; automatic erasure without checking legal obligations. | Updates `BRD-FR-050` and `BRD-NFR-014`; exact durations remain open under `AMB-006` pending qualified review. | Stakeholder |
| DEC-015 | 2026-10-11 | Stage 0B | Require each tenant Data Fiduciary to approve purpose, lawful basis, and notice for its trading-data processing; require the ATB operator to separately determine and document these for its own account, security, and service processing. Record consent and withdrawal evidence only where consent is selected as the applicable basis. | Aligns privacy decisions with the accepted tenant/platform role split and avoids treating consent as a universal basis. | Platform vendor decides all tenant purposes/bases; use consent as a default for every processing purpose. | Updates `BRD-FR-047`; taxonomy, retention durations, and other legal obligations remain open under `AMB-006`. | Stakeholder |
| DEC-016 | 2026-10-11 | Stage 0B | Classify information using internal sensitivity labels Public, Internal, Confidential, and Restricted, with personal-data and processing-purpose tags applied independently. Treat these as product handling labels, not statutory DPDP categories. | Separates handling sensitivity from whether information is personal data or why it is processed. | One exclusive classification axis conflating personal data, purpose, and sensitivity. | Updates `BRD-NFR-014`; exact retention periods and additional legal obligations remain open under `AMB-006`. | Stakeholder |
| DEC-017 | 2026-10-11 | Stage 0B | Require tenant legal/accounting reviewers to approve trading-data purposes and retention schedules; require the ATB operator’s qualified privacy/legal reviewer to approve platform processing, retention, and processor/subprocessor obligations. Record evidence; leave durations unfilled until approved. | Assigns privacy/legal decisions to the party responsible for each processing context and avoids inventing legal retention periods. | One global schedule; agent-selected periods without qualified review. | Adds a review-evidence gate to `AMB-006`, `BRD-FR-050`, `BRD-FR-051`, and `BRD-NFR-014`; exact durations and other duties remain open. | Stakeholder |
| DEC-018 | 2026-10-11 | Stage 0B | Require each tenant’s Partner/Managing Director or delegated authorized business owner to review and confirm or edit applicable reference thresholds before affected workflows go live. Keep only the affected risk-sensitive workflow disabled when a threshold is missing or unreviewed; record effective-dated policy versions and audit changes. | Converts reference values into safe tenant-specific setup candidates without asserting universal domain correctness or blocking unrelated operations. | Silently activate workflows on candidate values; block all tenant operations for any missing threshold. | Updates `BRD-FR-042` and `BRD-FR-052`; resolves the application approach for `AMB-003`. | Stakeholder |
| DEC-019 | 2026-10-11 | Stage 0B | For a representative tenant, measure manual effort per transaction, gate-in-to-stock-posting time, and stock-reconciliation variance by godown/commodity for 30 operating days before rollout, then repeat for 30 operating days after rollout; set numeric improvement targets from the observed results. Keep lot traceability, QC dispatch prevention, and credit controls as hard product invariants. | Establishes an evidence-based pre/post comparison without inventing improvement percentages before pilot data exists. | Choose numeric efficiency targets before collecting baseline evidence; assess only post-rollout values. | Updates PRD §1.3; the protocol is resolved while measured baselines and numeric targets remain open under `AMB-001`. | Stakeholder |

View File

@ -2,23 +2,28 @@
| Field | Value |
|---|---|
| **Governed Standard** | SEI-CMMI Level 3 (UP-AI v1.0) |
| **Document Path** | `04_generated_documentation/00_process_control/folder_discovery_report.md` |
| **Last Updated** | 2026-09-03 |
| **Project** | Agriculture Trading Backoffice (`ATB`) |
| **Archetype** | Greenfield |
| **Process** | UP-AI v1.5 |
| **Last Updated** | 2026-10-11 |
---
## 1. Input Directories & Files
| # | Item Name | Relative Path | Type | Purpose | Target Stage | Processing Notes |
| # | Item Name | Relative Path | Type | Purpose | Target Stage | Processing Notes / Risk |
|---|---|---|---|---|---|---|
| 1 | `PRD_Specification.md` | `01_BRD/PRD_Specification.md` | Markdown | Primary Business Requirements Document (PRD/BRD) | Stage 1: Feature Extraction (`up-brd-extract`) | Extract all functional features to `brd_inventory.md` (`BRD-FR-xxx`). |
| 2 | `tech-profile.yaml` | `tech-profile.yaml` | YAML | Active technology stack configuration & quality thresholds | All Stages | Read by all agent skills for architecture and code generation. |
| 1 | `PRD_Specification.template.md` | `01_BRD/PRD_Specification.template.md` | Markdown template | Example structure for a future requirements document. | Stage 0B / Stage 1 | Template is not authoritative; its sample UEP content must not be extracted as ATB requirements. |
| 2 | `PRD_Specification backup.md` | `01_BRD/PRD_Specification backup.md` | Markdown reference | Business requirements reference for mandi trading workflows. | Stage 0B | User accepted its business direction; its AMTP/Frappe/MariaDB technology choices do not apply to ATB. Numeric policy values remain provisional. |
| 3 | `PRD_Specification.md` | `01_BRD/PRD_Specification.md` | Markdown draft | ATB Stage 0B PRD based on stakeholder-accepted business suggestions and the active technology profile. | Stage 0B / Stage 1 | Draft exists; validate candidate metrics and numeric policies, then obtain baseline approval before Stage 1. |
| 4 | `tech-profile.yaml` | `tech-profile.yaml` | YAML | Project identity, archetype, stack, sandboxes, tailoring tier, and quality targets. | All stages | Present and authoritative for configured technical choices. Sandbox paths are declared, not verified as implemented. |
| 5 | Legacy sources (absent) | `02_legacy_source_code/`, `03_legacy_screen_shots/` | Directories (not present) | Brownfield code, schema, and screenshot inputs. | Stages 2–4 | Not applicable to the selected greenfield archetype. |
| 6 | Prior generated documentation | `04_generated_documentation/` | Generated artifacts | Sample references from previous work. | None | Treated as samples per user direction; use only current ATB control documents as project governance. |
---
## 2. Recommended Processing Sequence
1. **Stage 1 (Feature Extraction):** Read `01_BRD/` inputs and mint `BRD-FR-xxx` items in `04_generated_documentation/01_source_inventories/brd_inventory.md`.
2. **Stage 5 (Use Case Authoring):** Author atomic use cases under `04_generated_documentation/03_requirements/use_cases/` embedding `FR-xxx` children.
3. **Gate 5.1:** Run `up-traceability-gate` to enforce complete UC $\leftrightarrow$ FR linkage before architecture elaboration.
1. Review `01_BRD/PRD_Specification.md` and validate proposed business KPIs and numeric operating policies with a domain owner.
2. Approve and baseline the PRD; then run Stage 1 (`up-brd-extract`) to refine its `BRD-FR-xxx` roots into `04_generated_documentation/01_source_inventories/brd_inventory.md`.
3. Continue with Stage 5 use-case authoring and the applicable traceability gate in prescribed process order. Skip brownfield discovery stages for this greenfield project.

View File

@ -1,26 +1,20 @@
# Universal Enterprise Platform — Master Context
# Agriculture Trading Backoffice — Master Context
| Field | Value |
|---|---|
| **Project** | Universal Enterprise Platform (UEP) |
| **Code** | `UEP` |
| **Project** | Agriculture Trading Backoffice |
| **Code** | `ATB` |
| **Archetype** | Greenfield (0-to-1) |
| **Active Process** | AI-Native Unified Process (UP-AI v1.1) |
| **Governance Standard** | SEI-CMMI Level 3 Equivalent |
| **Last Updated** | 2026-10-03 |
| **Active Process** | AI-Native Unified Process (UP-AI v1.5) |
| **Governance Tier** | `tier_2_standard_enterprise` |
| **Last Updated** | 2026-10-11 |
---
## 1. Project Goal & Overview
Universal Enterprise Platform (UEP) is a modern, modular, multi-tenant enterprise application platform designed to provide secure, high-performance, and extensible business capabilities.
Target capabilities include:
1. **Identity & Access Governance:** Multi-tenant user lifecycle, OIDC/PKCE authentication, and role-based access control (RBAC).
2. **Core Domain Services:** Modular domain business logic with strictly tenant-isolated data persistence.
3. **External Integrations:** Extensible adapter interfaces with deterministic Wave 0 sandboxes for offline CI validation.
4. **Multi-Portal Frontends:** Role-tailored web interfaces built on modern component design tokens (`DESIGN.md`).
Agriculture Trading Backoffice (ATB) is a greenfield, India-first multi-tenant backoffice platform for agricultural trading firms. The stakeholder-reviewed business direction is captured in the Draft PRD at [`01_BRD/PRD_Specification.md`](../../../01_BRD/PRD_Specification.md); requirements are not yet baselined.
---
@ -39,11 +33,16 @@ stack:
framework: "fastapi"
orm: "sqlalchemy"
migrations: "alembic"
api_standard: "rest_openapi"
test_framework: "pytest"
coverage_tool: "pytest-cov"
frontend:
framework: "react"
language: "typescript"
state_management: "zustand"
ui_library: "tailwind_shadcn"
test_framework: "vitest"
e2e_framework: "playwright"
authentication:
provider: "keycloak"
protocol: "oidc_pkce"
@ -52,6 +51,16 @@ stack:
database:
primary: "postgresql"
cache_and_streams: "valkey"
search_engine: "none"
sandboxes:
- identity_provider: deterministic mock at sandbox/identity_mock.py
- payment_gateway: deterministic mock at sandbox/payment_mock.py
- messaging_service: deterministic mock at sandbox/notification_mock.py
quality:
tailoring_tier: "tier_2_standard_enterprise"
backend_domain_fsm_coverage: 95.0
integration_adapter_coverage: 90.0
frontend_component_coverage: 80.0
```
---
@ -76,5 +85,6 @@ stack:
## 4. Active Stage & Next Actions
- **Current Stage:** Stage 0 Completed / Ready for Stage 1 Inception (`up-brd-extract`) & Stage 5 Elaboration (`up-use-case-author`).
- **Active Iteration:** `iteration-01` (Identity & User Management Slice).
- **Current Stage:** Stage 0B — Requirements elicitation; PRD draft prepared from stakeholder-accepted business direction.
- **Active Iteration:** None; no iteration has been planned for this project baseline.
- **Next:** Prepare the Stage 0B Human Review Brief and review `01_BRD/PRD_Specification.md`. The pilot measurement protocol for `AMB-001` is accepted; collect 30-operating-day pre- and post-rollout results to set numeric targets. Obtain qualified review evidence for DPDP retention durations and other applicable obligations (`AMB-006`), and derive fair-share budgets from load testing and pilot telemetry (`AMB-008`). Keep the PRD in Draft until required evidence is available and the stakeholder explicitly approves the baseline; then proceed to Stage 1 extraction.

View File

@ -2,19 +2,22 @@
| Field | Value |
|---|---|
| **Governed Standard** | SEI-CMMI Level 3 (UP-AI v1.0) |
| **Document Path** | `04_generated_documentation/00_process_control/vocabulary_glossary.md` |
| **Last Updated** | 2026-09-03 |
| **Project** | Agriculture Trading Backoffice (`ATB`) |
| **Process** | UP-AI v1.5 |
| **Last Updated** | 2026-10-11 |
---
## Universal Domain & Process Terminology
## Terms Known at Bootstrap
Business terminology is pending an authoritative PRD/BRD. Entries below come only from the project description and configured profile.
| Term | Category | Definition | Source / Reference |
|---|---|---|---|
| **Tenant** | Identity / Architecture | An isolated organizational unit with its own data boundaries, users, roles, and configuration. | `tech-profile.yaml` |
| **Row-Level Security (RLS)** | Database / Security | PostgreSQL security mechanism ensuring queries only return rows belonging to the active tenant session. | `tech-profile.yaml` |
| **Wave 0 Sandbox** | Testing / Integration | Deterministic local mock adapter under `app/integrations/sandbox/` providing 100% offline, reproducible integration tests. | UP-AI v1.0 Standard |
| **Delivery Surface Matrix** | Construction / QA | 11-dimension delivery contract mapping every story across frontend, API, data, integration, and QA surfaces. | `iteration_surface_matrix.md` |
| **Multi-Path Testing** | Quality Assurance | Enforced testing across Happy Path, Alternate/Boundary, Negative/Failure, and FSM Invariant dimensions ($\ge 95\%$ coverage). | UP-AI v1.0 Standard |
| **Change Request (CR)** | Governance / Traceability | Formal entity computing blast-radius impact across the traceability graph before any requirement, design, or code is modified. | `up-change-request-impact` |
| Agriculture trading backoffice | Project | Backoffice platform for agriculture trading; workflows and domain rules are not yet specified. | `tech-profile.yaml` |
| Tenant | Architecture | Organizational boundary used to isolate application data; the profile enables row-level security. | `tech-profile.yaml` |
| Row-level security (RLS) | Database / Security | Database policy approach configured for tenant isolation in PostgreSQL. | `tech-profile.yaml` |
| OIDC with PKCE | Identity / Security | OpenID Connect using PKCE, configured with Keycloak authentication. | `tech-profile.yaml` |
| JWT bearer token | Identity / Security | Bearer-token format configured for API authentication. | `tech-profile.yaml` |
| RBAC / ABAC | Authorization | Role-based and attribute-based access-control model configured in the profile. | `tech-profile.yaml` |
| Wave 0 sandbox | Integration / Testing | Deterministic mock adapter configured for an external dependency during early integration work. | `tech-profile.yaml` |

View File

@ -1,78 +1,526 @@
# Frontend Design Guideline & Component Standard
# Design.md — IndiaAgriTrade (RamDayal Agri Commodities) Wholesale Trading Desk
| Field | Value |
|---|---|
| **Document** | `DESIGN.md` |
| **System** | Universal Enterprise Platform (UEP) |
| **Governed by** | UP-AI v1.0 Stage 11 Design Standard |
| **Status** | Baselined |
| **Scope** | Cross-portal frontend design & component guideline for Stage 11 (`up-wireframe-spec`) and Stage 13 (`up-code-generate`) |
A comprehensive UI/UX, Component Architecture, and Visual Design Specification for building the **IndiaAgriTrade RamDayal BackOffice & Wholesale Trading Desk** using **Vue 3 (Composition API / <script setup>)** and **Tailwind CSS**.
---
## 0. Purpose
## 1. Executive Summary & Domain Architecture
This document establishes the universal design tokens, layout shells, screen archetypes, and component composition rules across all frontend portals in the platform.
### 1.1 Business Context
**IndiaAgriTrade (RamDayal)** represents an enterprise-grade wholesale agricultural commodity trading and back-office desk operating across major Indian Mandis (APMC markets), grain corridors, oilseed hubs, and pulse processing centers.
It eliminates UI drift and guarantees that:
1. All screens compose from standardized design system primitives (Radix UI / shadcn / Tailwind CSS).
2. Wireframe screen shapes map deterministically to component patterns.
3. Common cross-portal behaviors (OIDC redirect, RBAC menu filtering, toast notifications, error handling) are implemented consistently.
Key functional pillars:
1. **Trading Desk / Live Mandi Book**: Real-time bid/ask order book across spot Mandi contracts, futures arbitrage, forward booking (Wheat, Chana, Mustard, Soyabean, Paddy/Basmati, Cotton, Maize, Tur/Arhar).
2. **Trader Blotter & Position Management**: Net physical exposure (metric tons), warehouse stock receipts (WSR/e-NWR), and daily MTM (Mark-to-Market) P&L.
3. **Mandi Settlement & Procurement (APMC)**: Farmer/FPO/Arhatiya settlement, mandi cess, loading/unloading (Hamali), moisture and foreign matter deduction (Karda/Quality Assay).
4. **Logistics & Dispatch Tracking**: Rake movements, fleet truck dispatches, e-Way bills, gate-in/gate-out weighbridge sync.
5. **Quality Assay & Lab Inspection**: Lab certificates, moisture %, admixture %, damaged grain %, protein/oil content, Fair Average Quality (FAQ) standards.
6. **Financial Ledger & Khata (Vyapar Bahi)**: GST compliant invoices, TDS (194Q / 206C), trader advance vouchers, credit aging, payment netting.
---
## 1. Design System Foundation & Tokens
## 2. Brand Identity & Visual Design System
### 1.1 Technology Stack
- **Framework:** React 19 + TypeScript + Vite
- **Styling:** Tailwind CSS v4 with CSS-first custom tokens
- **Component Primitives:** Radix UI / shadcn/ui (`class-variance-authority`)
- **Icons:** `lucide-react`
- **Charts:** `recharts` / shadcn chart wrapper
### 2.1 Color Palette (Tailwind Tokens)
Designed specifically for high-density agricultural trade execution — combining earthy reliability with financial clarity.
### 1.2 Core Color & Semantic Tokens (`index.css`)
| Token | HSL / Value | Semantic Purpose |
|---|---|---|
| `--primary` | `hsl(221, 83%, 53%)` | Primary brand action, active navigation, focus rings |
| `--background` | `hsl(0, 0%, 100%)` / `hsl(222, 47%, 11%)` | Canvas background (Light / Dark mode) |
| `--card` | `hsl(0, 0%, 100%)` / `hsl(217, 33%, 17%)` | Surface container for table/form/metric cards |
| `--success` | `hsl(142, 76%, 36%)` | Active, Confirmed, Delivered, Resolved states |
| `--warning` | `hsl(38, 92%, 50%)` | Pending, In-Progress, Expiring-Soon states |
| `--destructive` | `hsl(0, 84%, 60%)` | Failed, Rejected, Cancelled, Overdue states |
| `--info` | `hsl(199, 89%, 48%)` | Informational, Draft, Awaiting-Approval states |
---
## 2. Universal Layout Shell (`MainLayout.tsx`)
Every authenticated portal route runs under a standard layout shell:
```
+-------------------------------------------------------------------------+
| [Logo] Tenant Name [Search / Quick Actions] [User Avatar] | <-- Header
+-------------------+-----------------------------------------------------+
| Navigation: | |
| - Dashboard | Breadcrumbs / PageHeader(Title, Actions) |
| - Management | |
| - Settings | [Routed Page Content: Table / Form / Dashboard] |
| - Audit Logs | |
| | |
+-------------------+-----------------------------------------------------+
| [Collapse Sidebar]| Global Toaster |
+-------------------+-----------------------------------------------------+
```javascript
// tailwind.config.js theme extension
module.exports = {
theme: {
extend: {
colors: {
// Agri Brand Greens (Growth, Agriculture, APMC Trust)
agri: {
50: '#f0fdf4',
100: '#dcfce7',
200: '#bbf7d0',
500: '#15803d',
600: '#166534',
700: '#14532d',
800: '#0f3f22',
900: '#0a2a17',
},
// Grain / Earth Warm Neutrals (Wheat, Mustard, Mandi)
grain: {
50: '#fffbeb',
100: '#fef3c7',
200: '#fde68a',
400: '#f59e0b',
600: '#d97706',
700: '#b45309',
900: '#78350f',
},
// Trading Finance Semantic Signals
trade: {
bid: '#059669', // Buy / Green
bidBg: '#ecfdf5',
ask: '#dc2626', // Sell / Red
askBg: '#fef2f2',
neutral: '#475569',
hold: '#d97706',
arbitrage: '#6366f1'
},
// High-Density Data Backgrounds & Surfaces
surface: {
base: '#f8fafc',
card: '#ffffff',
subtle: '#f1f5f9',
border: '#e2e8f0',
darkBg: '#0f172a',
darkCard: '#1e293b',
darkBorder: '#334155'
}
}
}
}
}
```
- **Route Guarding:** Unauthenticated state immediately triggers OIDC redirect to Keycloak.
- **RBAC Filtering:** Sidebar items and action buttons evaluate user role claims before rendering.
### 2.2 Typography
- **Primary Interface Font**: `Inter` or `Plus Jakarta Sans` for clean tabular numbers and compact labeling.
- **Numbers & Rates**: Monospaced font family `JetBrains Mono` or tabular numerals (`tabular-nums font-mono`) for rates per quintal (₹/Qtl), weights (MT), and ledger figures.
- **Scale**:
- Micro Badges: `text-[10px] font-semibold tracking-wider uppercase`
- Compact Data Table: `text-xs leading-4 font-normal text-slate-700`
- Table Headers & Metric Labels: `text-[11px] font-bold text-slate-500 uppercase tracking-wide`
- Primary Field Values: `text-sm font-semibold text-slate-900 font-mono tabular-nums`
- Large Trading Figures / P&L: `text-xl md:text-2xl font-bold font-mono tracking-tight`
### 2.3 Layout Structure & Grid
- **Global Frame**:
- Persistent Header: Mandi clock (IST / Market Open/Close countdown), global ticker marquee (Wheat, Chana, Mustard, Soyabean, Paddy rates), quick search (`CMD+K`), active terminal profile ("RamDayal Traders - Indore Hub").
- Left Collapsible Navigation: Categorized into **Trading Desk**, **Procurement & Mandi**, **Warehouse & Logistics**, **Lab & Quality Assay**, **Financials & Ledgers**, and **Reports & Compliance**.
- Responsive Viewport: Fluid responsive container (`max-w-7xl mx-auto px-4 sm:px-6 lg:px-8`) with dense mode toggles for dual-monitor trading screens or mobile responsive drawer.
---
## 3. Seven Screen Archetypes → Component Mapping
## 3. Site Map & Detailed Page Blueprints
1. **List / Table + Filters:** `Card` + `FilterBar` + `Table` + `Pagination` + row action `DropdownMenu`.
2. **Dashboard / Metrics:** `MetricCard` (KPI tiles) + `Chart` (Recharts) + `ActivityFeed`.
3. **Multi-Step Form / Wizard:** `Stepper` + `Form` (React Hook Form + Zod) + `ButtonGroup`.
4. **Detail / Split-Panel View:** `PageHeader` + `Tabs` (Overview, History, Permissions, Audit).
5. **Modal / Action Dialog:** `Dialog` / `AlertDialog` (one dialog per distinct row action).
6. **Live Telemetry / Stream:** Map canvas or event stream + collapsible filter drawer + status legend.
7. **Error / Empty State:** `EmptyStateCard` with descriptive icon, friendly title, and primary recovery action button.
### Page 1: Trading Desk & Live Mandi Terminal (`/trading-desk`)
*The command center for live commodity deals, bids, offers, and broker communications.*
- **Header Metric Strip**:
- Today's Turnover (₹ Cr & MT)
- Open Contract Value
- Net Physical Inventory (MT across Indore, Kota, Bikaner, Akola, Hapur warehouses)
- Realized Day MTM (₹ Lacs)
- **Live Commodity Ticker & APMC Board**:
- Commodity tabs: Chana Desi, Wheat Sharbati/Mill Quality, Mustard Seed (42% Oil), Soyabean Yellow, Tur Maharashtra, Basmati 1121 Pusa.
- Metrics: Spot Mandi Price (₹/Qtl), Day Change (₹ & %), Daily Arrivals (Bags/Boras), Major Mandi comparisons (e.g., Indore vs. Akola vs. Latur).
- **Quick Order Entry (Sauda Slip)**:
- Deal Type: Spot Buy (Kharid) / Spot Sell (Bikri) / Forward Sauda / Delivery Contract.
- Fields: Counterparty (Vyapari/Mill/Arhatiya), Mandi/Location, Commodity & Grade, Quantity (Qtl/MT), Rate (₹/Qtl), Delivery Terms (Ex-Mandi, FOR Mill, Loaded on Truck), Payment Terms (CAD, Advance, 7-day Khata).
- **Active Blotter (Sauda Book)**:
- Real-time list of deals executed today with statuses: `Confirmed`, `Awaiting Gate-In`, `Under Quality Assay`, `Settled`.
### Page 2: APMC Mandi Procurement & Farmer/Arhatiya Settlement (`/procurement-apmc`)
*Back-office management of mandi auction lots, weigh slips, and karda deductions.*
- **Auction Lot Intake**:
- Farmer / Arhatiya Code & Name, APMC Lot ID.
- Weighbridge Gross / Tare / Net Weight (Dharam Kanta Sync).
- **Quality & Deduction Calculation Engine**:
- Moisture Deduction (`Moisture % > 12%` automatic formula trigger).
- Foreign Matter / Admixture (`Dust/Stone %` deduction).
- Damaged/Discolored Seed Deduction (Karda rulebook).
- Net Billable Weight calculation.
- **Mandi Charges & Expense Slip**:
- APMC Mandi Fee / Cess (e.g., 1.5%), Krishi Kalyan Cess, Labour/Hamali Charges (₹/bag), Stitching/Bagging charges (Bardana charges).
- **Settlement Vouchers (J-Form / K-Form Generation)**:
- Instant generation and printing of standardized Mandi J-Form receipt with QR code verification.
### Page 3: Warehouse & Stock Receipts (e-NWR) (`/warehouse-inventory`)
*Physical stock oversight across owned godowns, CWC/SWC warehouses, and cold storages.*
- **Facility Overview Matrix**:
- Total Capacity vs Occupied (Metric Tons & Bags).
- Storage locations: Indore Central Godown, Kota Grain Silo, Bikaner Mustard Depot, Latur Pulse Facility.
- **Batch & Stack Management (Chhatta / Stack Cards)**:
- Commodity, Variety, Crop Year (e.g., Rabi 2024), Fumigation Status, Insurance Expiry.
- Electronic Negotiable Warehouse Receipt (e-NWR / WDRA) tracking for pledged bank credit limits.
- **Stock Movement Log**:
- Gate-In (Inward from Mandi/Farmer), Gate-Out (Outward dispatch to Flour/Oil Mills), Internal Stack Transfers.
### Page 4: Quality Assay & Laboratory Certification (`/quality-assay`)
*Inspection workflows for trade verification and dispute resolution.*
- **Sample Testing Workflow**:
- Sample Barcode ID, Commodity Lot link, Inspector Name, Inspection Date.
- **Parameter Analysis Form & Sliders**:
- Moisture Content (`%`), Oil Content (`%` for Mustard/Soybean), Protein (`%` for Wheat/Chana), Foreign Matter (`%`), Immature/Shriveled Grain (`%`), Weeviled/Damaged (`%`).
- **Grade Classification**:
- Auto-categorization: `Super Premium (Sharbati)`, `Grade A (FAQ)`, `Grade B (Feed Quality)`, `Rejection Criteria Exceeded`.
- **Assay Certificate Export**:
- Direct PDF/Print preview with digital stamp and trade reference.
### Page 5: Logistics, Fleet & E-Way Bill Dispatch (`/logistics-dispatch`)
*Transit execution between warehouses, processing plants, and port rakes.*
- **Dispatch Scheduling**:
- Truck Number, Driver Mobile, Transporter Name, Bilty (LR) Number.
- Rake Allocation (Goods Train wagon dispatch for bulk grain movements).
- **Compliance Integration**:
- E-Way Bill Number, E-Invoice IRN, Validity Countdown, Destination Geo-fencing.
- **Live Transit Status**:
- Route checkpoint tracking: Loaded -> Weighbridge Verified -> In-Transit -> Gate-In at Mill -> Unloaded & Weight Reconciled.
### Page 6: Financial Ledger & Counterparty Khata (Vyapar Bahi) (`/financials-khata`)
*Agricultural mercantile accounting, commission agent balances, and tax compliance.*
- **Counterparty Directory & Aging**:
- Millers, Wholesalers, Arhatiyas, Transporters, Bardana Suppliers.
- Credit Limit, Current Balance (Debit/Credit ₹), Aging Brackets (0-15d, 16-30d, 31-60d, 60d+).
- **Voucher Entry**:
- Payment Advice, Receipt, Commission (Dalali) Note, Interest Calculation for overdue payment terms.
- **Tax & Compliance Sub-Module**:
- Section 194Q TDS on purchase of goods (>₹50 Lakhs threshold monitor).
- TCS under 206C(1H), GST E-Invoicing status.
---
## 4. Vue 3 Architecture & State Management
### 4.1 Component Tree & File Organization
```
src/
├── assets/
│ └── css/
│ └── tailwind.css
├── components/
│ ├── common/
│ │ ├── BaseBadge.vue
│ │ ├── BaseButton.vue
│ │ ├── BaseCard.vue
│ │ ├── BaseInput.vue
│ │ ├── BaseSelect.vue
│ │ ├── BaseModal.vue
│ │ ├── MetricTile.vue
│ │ └── TabularNumber.vue
│ ├── layout/
│ │ ├── AppHeader.vue
│ │ ├── AppSidebar.vue
│ │ ├── MandiTickerMarquee.vue
│ │ └── QuickActionFloatingBar.vue
│ ├── trading/
│ │ ├── SaudaEntryModal.vue
│ │ ├── LiveMandiPriceGrid.vue
│ │ ├── BlotterTable.vue
│ │ └── CommodityRateChart.vue
│ ├── procurement/
│ │ ├── WeighbridgeCalculator.vue
│ │ ├── QualityDeductionPanel.vue
│ │ └── JFormReceiptModal.vue
│ ├── warehouse/
│ │ ├── StackCardGrid.vue
│ │ └── StockTransferDialog.vue
│ └── financials/
│ ├── KhataSummaryCard.vue
│ └── LedgerTransactionTable.vue
├── composables/
│ ├── useMandiTicker.js // Real-time rates & calculations
│ ├── useTradeBlotter.js // Sauda entries, filtering, MTM
│ ├── useAssayCalculator.js // Karda, moisture & deduction math
│ └── useCurrencyFormatter.js // Indian number system (Lakhs/Crores)
├── stores/
│ ├── useAuthStore.js
│ ├── useMarketDataStore.js
│ └── useTradingDeskStore.js
├── router/
│ └── index.js
└── views/
├── TradingDeskView.vue
├── ProcurementView.vue
├── WarehouseView.vue
├── QualityAssayView.vue
├── LogisticsView.vue
└── FinancialsKhataView.vue
```
### 4.2 Reusable Composables Example
#### A. Indian Currency & Agricultural Metric Formatter (`useAgriFormatters.js`)
```javascript
export function useAgriFormatters() {
// Formats to Indian Rupee notation (₹ 1,25,000)
const formatINR = (value) => {
if (value === null || value === undefined) return '₹0';
return new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR',
maximumFractionDigits: 0
}).format(value);
};
// Formats rate per quintal (₹ 2,450 / Qtl)
const formatRatePerQtl = (rate) => {
return `${formatINR(rate)}/Qtl`;
};
// Formats weight in Metric Tons and Bags (50kg std)
const formatWeight = (tons) => {
const bags = Math.round((tons * 1000) / 50);
return `${tons.toLocaleString('en-IN')} MT (${bags.toLocaleString('en-IN')} Bags)`;
};
return { formatINR, formatRatePerQtl, formatWeight };
}
```
#### B. Mandi Deduction & Karda Calculation (`useAssayCalculator.js`)
```javascript
export function useAssayCalculator() {
const calculateNetPayable = ({ grossWeight, tareWeight, ratePerQtl, moisturePct, foreignMatterPct, mandiCessPct = 1.5 }) => {
const rawNetWeightKg = grossWeight - tareWeight;
// Standard tolerances: Moisture 12%, Foreign Matter 1%
const excessMoisture = Math.max(0, moisturePct - 12);
const excessForeign = Math.max(0, foreignMatterPct - 1);
const deductionPct = excessMoisture + excessForeign;
const deductionKg = (rawNetWeightKg * deductionPct) / 100;
const billableWeightKg = rawNetWeightKg - deductionKg;
const billableQtl = billableWeightKg / 100;
const grossCommodityAmount = billableQtl * ratePerQtl;
const mandiCess = (grossCommodityAmount * mandiCessPct) / 100;
const netPayable = grossCommodityAmount - mandiCess;
return {
rawNetWeightKg,
deductionKg,
billableWeightKg,
billableQtl,
grossCommodityAmount,
mandiCess,
netPayable
};
};
return { calculateNetPayable };
}
```
---
## 5. UI Component Specifications & Code Templates (Vue 3 + Tailwind)
### 5.1 Trading Metric Card Component (`MetricTile.vue`)
```vue
<script setup>
defineProps({
title: String,
value: [String, Number],
subtitle: String,
trend: Number, // positive or negative
iconBg: { type: String, default: 'bg-agri-50 text-agri-700' }
});
</script>
<template>
<div class="bg-white rounded-xl border border-slate-200 p-4 shadow-sm hover:shadow transition-shadow">
<div class="flex items-center justify-between">
<span class="text-xs font-semibold uppercase tracking-wider text-slate-500">{{ title }}</span>
<div v-if="trend !== undefined" :class="[
'flex items-center text-xs font-mono font-medium px-2 py-0.5 rounded-full',
trend >= 0 ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700'
]">
<span>{{ trend >= 0 ? '▲ +' : '▼ ' }}{{ trend }}%</span>
</div>
</div>
<div class="mt-2 flex items-baseline gap-2">
<div class="text-2xl font-bold font-mono tracking-tight text-slate-900">{{ value }}</div>
</div>
<div v-if="subtitle" class="mt-1 text-xs text-slate-500 font-medium">{{ subtitle }}</div>
</div>
</template>
```
### 5.2 Live Mandi Commodity Ticker (`MandiTickerMarquee.vue`)
```vue
<script setup>
const tickerItems = [
{ commodity: 'Chana Desi (Indore)', rate: 5850, change: 45, unit: '₹/Qtl' },
{ commodity: 'Wheat Sharbati (Sehore)', rate: 3620, change: -15, unit: '₹/Qtl' },
{ commodity: 'Mustard 42% (Kota)', rate: 5410, change: 80, unit: '₹/Qtl' },
{ commodity: 'Soyabean Yellow (Ujjain)', rate: 4680, change: 10, unit: '₹/Qtl' },
{ commodity: 'Tur Maharashtra (Akola)', rate: 10250, change: -110, unit: '₹/Qtl' },
{ commodity: 'Basmati 1121 Paddy (Karnal)', rate: 4200, change: 25, unit: '₹/Qtl' }
];
</script>
<template>
<div class="bg-slate-900 border-b border-slate-800 text-slate-200 py-1.5 px-4 overflow-hidden">
<div class="flex items-center gap-6 overflow-x-auto no-scrollbar whitespace-nowrap text-xs">
<div class="flex items-center gap-1.5 font-bold text-amber-400 uppercase tracking-wider text-[11px] shrink-0">
<span class="relative flex h-2 w-2">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
</span>
Live Mandi Rates
</div>
<div class="flex items-center gap-6">
<div
v-for="item in tickerItems"
:key="item.commodity"
class="flex items-center gap-2 border-r border-slate-700/80 pr-6"
>
<span class="font-medium text-slate-300">{{ item.commodity }}</span>
<span class="font-mono font-bold text-white tabular-nums">₹{{ item.rate.toLocaleString('en-IN') }}</span>
<span
:class="item.change >= 0 ? 'text-emerald-400' : 'text-rose-400'"
class="font-mono text-[11px] font-semibold tabular-nums"
>
{{ item.change >= 0 ? '+' : '' }}{{ item.change }}
</span>
</div>
</div>
</div>
</div>
</template>
```
### 5.3 Sauda Entry Form Dialog (`SaudaSlipModal.vue`)
```vue
<script setup>
import { reactive } from 'vue';
const props = defineProps({
isOpen: Boolean
});
const emit = defineEmits(['close', 'submit']);
const form = reactive({
dealType: 'BUY',
commodity: 'Chana Desi',
mandi: 'Indore Mandi',
counterparty: '',
quantityMt: 50,
ratePerQtl: 5850,
deliveryTerms: 'EX_MANDI',
paymentDays: 7
});
const calculateTotal = () => {
const qtl = form.quantityMt * 10;
return qtl * form.ratePerQtl;
};
</script>
<template>
<div v-if="isOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
<div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full border border-slate-200 overflow-hidden">
<div class="bg-agri-700 text-white px-6 py-4 flex items-center justify-between">
<div>
<h3 class="font-bold text-lg">New Sauda Slip (Trade Booking)</h3>
<p class="text-xs text-agri-100">RamDayal Wholesale Trading Desk</p>
</div>
<button @click="emit('close')" class="text-agri-200 hover:text-white text-xl leading-none">&times;</button>
</div>
<form @submit.prevent="emit('submit', { ...form, totalAmount: calculateTotal() })" class="p-6 space-y-4">
<!-- Deal Type Toggle -->
<div class="grid grid-cols-2 gap-2 p-1 bg-slate-100 rounded-lg">
<button
type="button"
@click="form.dealType = 'BUY'"
:class="form.dealType === 'BUY' ? 'bg-emerald-600 text-white shadow' : 'text-slate-600'"
class="py-2 text-xs font-bold uppercase rounded-md transition"
>
Kharid (Buy)
</button>
<button
type="button"
@click="form.dealType = 'SELL'"
:class="form.dealType === 'SELL' ? 'bg-rose-600 text-white shadow' : 'text-slate-600'"
class="py-2 text-xs font-bold uppercase rounded-md transition"
>
Bikri (Sell)
</button>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold uppercase text-slate-500 mb-1">Commodity</label>
<select v-model="form.commodity" class="w-full text-sm border-slate-200 rounded-lg focus:ring-agri-600">
<option>Chana Desi</option>
<option>Wheat Sharbati</option>
<option>Mustard Seed</option>
<option>Soyabean Yellow</option>
<option>Tur Whole</option>
</select>
</div>
<div>
<label class="block text-xs font-bold uppercase text-slate-500 mb-1">Mandi / Hub</label>
<select v-model="form.mandi" class="w-full text-sm border-slate-200 rounded-lg">
<option>Indore Mandi</option>
<option>Kota APMC</option>
<option>Bikaner Grain Market</option>
<option>Akola APMC</option>
</select>
</div>
</div>
<div>
<label class="block text-xs font-bold uppercase text-slate-500 mb-1">Counterparty (Vyapari / Mill)</label>
<input
v-model="form.counterparty"
placeholder="e.g. Shrinath Agro Industries, Ujjain"
class="w-full text-sm border-slate-200 rounded-lg"
required
/>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold uppercase text-slate-500 mb-1">Quantity (MT)</label>
<input type="number" v-model.number="form.quantityMt" class="w-full font-mono text-sm border-slate-200 rounded-lg" />
<span class="text-[11px] text-slate-400">{{ form.quantityMt * 10 }} Quintals ({{ form.quantityMt * 20 }} Bags)</span>
</div>
<div>
<label class="block text-xs font-bold uppercase text-slate-500 mb-1">Rate (₹ / Qtl)</label>
<input type="number" v-model.number="form.ratePerQtl" class="w-full font-mono text-sm border-slate-200 rounded-lg" />
</div>
</div>
<!-- Real-time calculation badge -->
<div class="bg-amber-50 border border-amber-200 rounded-xl p-3 flex justify-between items-center">
<span class="text-xs font-semibold text-amber-900">Total Contract Value:</span>
<span class="text-base font-bold font-mono text-amber-950">₹ {{ calculateTotal().toLocaleString('en-IN') }}</span>
</div>
<div class="pt-2 flex justify-end gap-3">
<button type="button" @click="emit('close')" class="px-4 py-2 border border-slate-200 text-xs font-semibold text-slate-600 rounded-lg">Cancel</button>
<button type="submit" class="px-6 py-2 bg-agri-600 hover:bg-agri-700 text-xs font-bold text-white rounded-lg shadow">Confirm Sauda</button>
</div>
</form>
</div>
</div>
</template>
```
---
## 6. Responsive Strategy & Mobile Mandi Trader UX
Agricultural trading operators frequently shift between desktop multi-column screens at the trading desk and smartphone screens while in the field at APMC yards or godowns.
1. **Card-Based Row Collapsing**:
- On desktop, view dense data grids (`table` layout with 10+ columns: Sauda No, Time, Commodity, Counterparty, Qty, Rate, Total, Status, Action).
- On mobile (`< 768px`), automatically collapse tables into high-contrast swipeable cards showing Commodity badge, Net Qtl, Rate in large mono font, and quick call/WhatsApp buttons for counterparties.
2. **Offline Resilience & Touch Targets**:
- Touch targets for trade execution buttons ≥ 44px × 44px.
- PWA ready design with local cache for mandi price sheets when network in rural APMC yards drops.
3. **Hindi / Bilingual Terminology Support**:
- Labels pair formal English with conversational Mandi Hindi terms (e.g., *Kharid/Buy*, *Bikri/Sell*, *Bora/Bag*, *Bardana/Packaging*, *Karda/Deduction*, *Hamali/Labor*).
---
## 7. Implementation Roadmap & Quickstart
```bash
# 1. Initialize Vue 3 project with Vite & Tailwind CSS
npm create vite@latest india-agri-trade -- --template vue
cd india-agri-trade
npm install -D tailwindcss postcss autoprefixer @tailwindcss/forms
npx tailwindcss init -p
# 2. Key recommended libraries
npm install pinia vue-router lucide-vue-next
```
This specification provides the full architectural, functional, and aesthetic blueprint to implement the **IndiaAgriTrade RamDayal BackOffice & Wholesale Trading Desk** in Vue 3 with Tailwind CSS.

View File

@ -1,18 +0,0 @@
# Wireframe & Screen Specification Index
| Field | Value |
|---|---|
| **Document** | `wireframe_index.md` |
| **System** | Universal Enterprise Platform (UEP) |
| **Governed Standard** | UP-AI v1.0 Stage 11 Standard |
| **Last Updated** | 2026-09-03 |
---
## Screen Inventory
| Screen ID | Screen Title | Route Path | Target Actor / Role | Screen Archetype | Owning UC / FR | Iteration |
|---|---|---|---|---|---|---|
| `SCR-AUTH-001` | Enterprise Login & Tenant Selector | `/login` | Public / All | Form / Modal | `UC-001` / `FR-AUTH-001` | `iteration-01` |
| `SCR-AUTH-002` | User Profile & Active Sessions | `/account/sessions` | All Authenticated | Detail / Table | `UC-001` / `FR-AUTH-003` | `iteration-01` |
| `SCR-ADMIN-001` | Tenant Role & Access Governance | `/admin/roles` | Tenant Admin | List / Table + Filters | `UC-001` / `FR-AUTH-002` | `iteration-01` |

View File

@ -0,0 +1,284 @@
# Session Transcript — Greenfield Bootstrap
## 2026-10-11T07:48:29Z — User
`/up-project-bootstrap --archetype greenfield`
## 2026-10-11T07:49:29Z — Assistant
Started the greenfield bootstrap workflow. The canonical skill and repository guide were inspected. `tech-profile.yaml` declares Agriculture Trading Backoffice (`ATB`), greenfield, with Keycloak authentication and a FastAPI/React/PostgreSQL stack. Existing process-control files and checkpoints are present, so they must be preserved and validated before any bootstrap changes.
## 2026-10-11T07:49:29Z — Assistant — Action summary
Inspection of the existing `master_context.md` found it describes a different project (Universal Enterprise Platform / UEP) and stale stack details, so it conflicts with the active tech profile. A broader read request for the other control documents was rejected by automatic approval review; no project artifacts have been changed yet. Bootstrap remains incomplete pending access to inspect and reconcile the existing governance artifacts, input folder names, and Stage 0 requirements.
## 2026-10-11T07:56:00Z — User
Clarified that `04_generated_documentation/` is sample reference material and authorized reinitializing or overwriting documents while rerunning `/up-project-bootstrap --archetype greenfield`.
## 2026-10-11T07:58:09Z — Assistant — Action summary
Reinitialized `master_context.md`, `assumptions_register.md`, `vocabulary_glossary.md`, `decision_log.md`, and `folder_discovery_report.md` for Agriculture Trading Backoffice (`ATB`) from the current `tech-profile.yaml`. Kept Keycloak and the configured FastAPI/React/PostgreSQL stack. Cleared sample UEP assumptions and decisions rather than carrying them forward. Recorded that `01_BRD/PRD_Specification.md` is missing and the only available input is a non-authoritative template, so Stage 0B elicitation or an approved PRD must precede Stage 1. Read back all five files; identities, empty register schemas, glossary, input status, and next-stage guidance are consistent. No tests or traceability gates apply to this bootstrap document reset.
`git diff --check` passed. `git status --short` also reports `tech-profile.yaml` modified; this file was not edited during this bootstrap and its existing modification was left untouched.
## 2026-10-11T08:09:21Z — User
Requested Stage 0B requirements elicitation and identified `01_BRD/IndiaAgriTrade_RamDayal/` plus its local URL as a sample mockup reference.
## 2026-10-11T08:09:21Z — Assistant
Read the canonical `up-requirements-elicit` skill and inspected the mockup README, navigation and page-rendering code, and sample business data. The UI presents Dashboard, Market Desk, Inventory, Procurement, Sales, Customers, Suppliers, Logistics, Finance, Quality, and Reports. The README and dataset explicitly label records as fictitious/illustrative. These are reference screens and example data only; no business requirements are inferred from them. Began Round 1/2 interview and asked the stakeholder to clarify the business need and success measures, intended organization/tenant and personas, and the MVP workflows.
## 2026-10-11T08:13:13Z — User
Answered the elicitation questions: the product replaces a manual process; it is multi-tenant; and the requested scope is all mockup functionality.
## 2026-10-11T08:13:13Z — Assistant
Recorded `AMB-001` (manual processes and measurable success), `AMB-002` (tenant boundary and roles), and `AMB-003` (specific capabilities/lifecycles and MVP acceptance) as open in the ATB ambiguity register, replacing the stale UEP sample entry. The broad intent to cover all mockup areas is captured, but workflows remain unspecified. Follow-up questions are needed before synthesizing a baseline PRD.
## 2026-10-11T08:13:13Z — User
Answered the elicitation questions: the product replaces a manual process; it is multi-tenant; and the requested scope is all mockup functionality.
## 2026-10-11T08:13:13Z — Assistant
Recorded `AMB-001` (manual processes and measurable success), `AMB-002` (tenant boundary and roles), and `AMB-003` (specific capabilities/lifecycles and MVP acceptance) as open in the ATB ambiguity register, replacing the stale UEP sample entry. The broad intent to cover all mockup areas is captured, but workflows remain unspecified. Follow-up questions are needed before synthesizing a baseline PRD.
## 2026-10-11T08:21:56Z — User
Provided `01_BRD/PRD_Specification backup.md` as a reference and invited suggested answers because they are not a domain expert.
## 2026-10-11T08:21:56Z — Assistant
Reviewed the backup PRD’s business problem, KPIs, personas, operational flows, feature inventory, NFRs, MVP scope, and anti-scope. It provides plausible answers for the open Stage 0B questions, but is explicitly treated as reference pending stakeholder confirmation. Its AMTP/Frappe/MariaDB/database-per-tenant technical baseline conflicts with the active ATB/FastAPI/PostgreSQL/row-level-security profile; no architecture or PRD changes were made from the backup document.
## 2026-10-11T08:25:00Z — User
Clarified the backup PRD is from a different technology stack, directed use of the stack in `tech-profile.yaml` (including Python and Node.js), and accepted the other business requirements suggestions.
## 2026-10-11T08:33:47Z — Assistant — Action summary
Created `01_BRD/PRD_Specification.md` using the reference’s accepted business content: 41 `BRD-FR-xxx` features across 11 areas, eight NFRs, roles, purchase-to-delivery workflows, and scope/anti-scope. Replaced Frappe/MariaDB-specific requirements with the active FastAPI/Python, React/TypeScript and Node.js tooling, Keycloak, PostgreSQL/RLS, Valkey, and configured test/sandbox profile. Marked proposed KPIs and numeric operational/performance thresholds provisional pending domain review. Updated the ATB ambiguity register, decision log (`DEC-001`), assumptions register, and master context; retained the PRD as Draft pending review/baseline approval. Scoped `git diff --check` passed on the PRD and these governance files. No tests or traceability gate were run. Existing unrelated changes to `tech-profile.yaml` and wireframe files were left untouched.
## 2026-10-11T08:35:50Z — Assistant — Follow-up
Updated `folder_discovery_report.md` to list the backup PRD as reference, the new ATB PRD as a draft, and the review/baseline-before-Stage-1 sequence. Confirmed 41 `BRD-FR` entries, eight `BRD-NFR` entries, and no remaining Frappe/MariaDB implementation references in the ATB PRD. The PRD remains Draft while numeric business targets await domain review.
## 2026-10-11T08:56:47Z — User
Asked whether the current requirements provide enough scope to form a production-grade multi-tenant platform.
## 2026-10-11T08:56:47Z — Assistant
Reviewed the draft PRD and current technology profile against primary PostgreSQL, OWASP ASVS, and SaaS architecture guidance. Assessment: the PRD establishes broad domain scope and key business invariants, but does not yet specify tenant identity/lifecycle, end-to-end isolation, platform security, reliability/operations, capacity/noisy-neighbor controls, or measurable validated service objectives. The RLS profile choice requires requirements about connection roles and RLS bypass behavior. No PRD changes made; this turn is an assessment only.
## 2026-10-11T09:01:32Z — User
Asked whether the requirements are sufficient for a production-grade multi-tenant platform and then directed: “please go ahead and add those missing requirements.”
## 2026-10-11T09:01:32Z — Assistant — Action summary
Expanded the Draft PRD with `BRD-FR-042`–`BRD-FR-046` for tenant provisioning/lifecycle, tenant memberships and role administration, verified tenant context, end-to-end resource isolation, and controlled privileged support access. Added `BRD-NFR-009`–`BRD-NFR-014` for application security assurance, tenant-isolation assurance, availability/recoverability, capacity and tenant fairness, operational observability, and data governance/retention. Updated the traceability candidate groupings, persona/role descriptions, requirement totals (46 FRs, 14 NFRs), ambiguity register (`AMB-004`–`AMB-008`), and master-context next actions. Open security, privacy, lifecycle, workload, availability, and recovery policy values remain explicitly unresolved before PRD baseline.
Scoped `git diff --check` passed for the PRD and affected governance files. ID validation confirmed contiguous unique sets of 46 functional requirements and 14 NFRs. No tests or process traceability gate were run; this is Stage 0B documentation and is still Draft. No unrelated user changes were altered.
## 2026-10-11T09:06:00Z — User
Asked to resolve the PRD ambiguities interactively and requested recommendations.
## 2026-10-11T09:06:00Z — Assistant
Started a focused Stage 0B interview and proposed resolving one topic at a time. First topic is tenant onboarding and membership (`AMB-004`). Recommendation: no public self-service tenant signup in v1; a platform administrator provisions a tenant, verifies the initial Tenant Administrator, and explicitly activates/suspends/closes it. A person may have memberships in multiple tenants, but must choose an explicit active tenant context after sign-in; tenant membership and role grants are checked server-side on every request. Awaiting stakeholder decision before updating requirements/registers.
## 2026-10-11T09:08:00Z — User
Accepted both recommendations for `AMB-004` (administrator-provisioned tenant onboarding; users may belong to multiple tenants with explicit tenant selection).
## 2026-10-11T09:08:00Z — Assistant — Action summary
Updated `BRD-FR-042`–`BRD-FR-044` with the accepted v1 onboarding and membership behavior; resolved `AMB-004`; recorded `DEC-002`; corrected the earlier decision-log feature count; and updated master-context next actions. Next elicitation topic: `AMB-005`, exceptional cross-tenant support access approvals and tenant notification/review. No tests or gates run.
## 2026-10-11T09:10:00Z — User
Accepted the recommendation for exceptional cross-tenant support access (`AMB-005`).
## 2026-10-11T09:10:00Z — Assistant — Action summary
Updated `BRD-FR-046` with no standing support access, tenant-admin approval for ordinary case-specific access, and a one-hour emergency break-glass flow with recorded reason, immediate audit alert, and tenant-admin notice within one business day. Resolved `AMB-005` and recorded `DEC-003`. Next topic: `AMB-006`, compliance, privacy, data classification/retention, and security verification target. No tests or gates run.
## 2026-10-11T09:12:00Z — User
Specified Indian DPDP Act compliance for the product.
## 2026-10-11T09:12:00Z — Assistant
Checked the official India Code Act and MeitY DPDP Rules 2025/Gazette commencement notification. The notification phases commencement; as of this session date (2026-10-11), the notification schedules many substantive Act provisions and Rules 3, 5–16, 22, and 23 for 18 months after 2025-11-13 (2027-05-13). Updated `BRD-NFR-009` and `BRD-NFR-014` to require support for the Act and Rules applicable at production launch and current revalidation; refined `AMB-006` and recorded `DEC-004`. This does not resolve tenant/platform Data Fiduciary and Data Processor allocation, Data Principal workflows, retention schedules, other obligations, or security verification rigor. Asked stakeholder to decide these remaining product-policy points with a recommended SaaS role model and capability set.
## 2026-10-11T09:13:39Z — User
Accepted the recommended DPDP SaaS responsibility split and privacy-operation capability scope.
## 2026-10-11T09:13:39Z — Assistant — Action summary
Added `BRD-FR-047`–`BRD-FR-051` for purpose/notice/consent records, Data Principal rights and grievance case management, breach response coordination, purpose-aware retention/erasure/legal hold, and processor/subprocessor governance. Updated PRD scope total and traceability grouping; recorded `DEC-005`; narrowed `AMB-006` to remaining legal mapping, data classification and population, retention schedules, other obligations, and application-security verification rigor. Next topic is `AMB-007`, availability and recovery targets. No tests or traceability gate run.
## 2026-10-11T09:13:39Z — User
Accepted the recommended availability, RTO/RPO, and backup/restore policy package.
## 2026-10-11T09:13:39Z — Assistant — Action summary
Updated `BRD-NFR-011` with 99.9% monthly 24/7 availability, RTO ≤4 hours, RPO ≤15 minutes, encrypted daily backups with point-in-time recovery and 35-day retention, and quarterly restore exercises. Resolved `AMB-007`, recorded `DEC-006`, and revised master-context next actions. Next topic is `AMB-008`, initial tenant/user/workload planning envelope. No tests or traceability gate run.
## 2026-10-11T09:13:48Z — Assistant
Proposed `AMB-008` starter performance envelope for stakeholder review: 50 tenant firms, up to 25 named users per tenant (1,250 total), 250 concurrent active users service-wide, and report validation at 50,000 ledger rows per tenant. These are planning/test targets rather than contractual seat caps. Asked stakeholder to accept or adjust the tenant/user/concurrency envelope; detailed daily transaction and peak profile can then be refined from that scale assumption.
## 2026-10-11T09:14:25Z — User
Accepted the initial capacity envelope recommendation for 50 tenants, up to 25 named users per tenant, 250 concurrent users service-wide, and 50,000 ledger rows per tenant for report validation.
## 2026-10-11T09:14:25Z — Assistant — Action summary
Updated `BRD-NFR-004` and `BRD-NFR-012` with the accepted capacity envelope; recorded `DEC-007`; refined `AMB-008` to keep daily transaction volume, peak-hour write rate, and numeric per-tenant limits open. Updated the earlier `DEC-001` feature count to 51. Proposed a provisional transaction load-test scenario for stakeholder review.
## 2026-10-11T09:15:44Z — User
Accepted the provisional load-test scenario of 200 core business documents per tenant per operating day with a 5× peak-hour burst.
## 2026-10-11T09:15:44Z — Assistant — Action summary
Updated `BRD-NFR-012` with the accepted provisional workload scenario, explicitly not a customer usage cap; recorded `DEC-008`; narrowed `AMB-008` to numeric per-tenant resource/throttle limits and refinement via pilot telemetry. Updated the PRD’s candidate-value table to reflect the now-approved availability/recovery and initial capacity targets.
## 2026-10-11T09:16:43Z — User
Accepted the recommended per-tenant fair-use approach: no fixed business-document cap, observable usage, early warnings, protect core transactions, and throttle/backpressure resource-intensive work under contention.
## 2026-10-11T09:16:43Z — Assistant — Action summary
Updated `BRD-NFR-012`, refined `AMB-008` to defer numerical fair-share budgets and alert thresholds to architecture/load-test evidence, and recorded `DEC-009`. Next topic: `AMB-003` business operating thresholds; recommendation will distinguish configurable reference defaults from confirmed domain policy. No tests or traceability gate run.
## 2026-10-11T09:17:00Z — User
Accepted treating the reference operating thresholds as configurable seed defaults, scoped by tenant and, where relevant, commodity/contract, with authorized audited changes.
## 2026-10-11T09:17:00Z — Assistant — Action summary
Added `BRD-FR-052` for tenant-scoped operating-policy configuration and audit; updated the scope total to 52 functional requirements and traceability grouping; marked the handling approach resolved in `AMB-003` while retaining numeric domain validation as open; updated the candidate-policy text and DPDP security/compliance summary; and recorded `DEC-010`. Next: `AMB-001` proposed success KPI measurement/targets or `AMB-006` remaining DPDP specifics. No tests or traceability gate run.
## 2026-10-11T09:19:35Z — User
Accepted treating safety/control KPIs as hard invariants and measuring operational efficiency through a 30-day pilot before setting improvement targets.
## 2026-10-11T09:19:35Z — Assistant — Action summary
Reworked PRD §1.3 to distinguish hard controls (complete lot traceability, no QC-hold dispatch, no unapproved credit-block bypass) from efficiency metrics (manual effort, gate-in-to-stock-posting time, stock-reconciliation variance). Recorded the 30-day pilot baseline and target-setting approach in `AMB-001` and `DEC-011`. Numeric outcomes remain open pending evidence.
## 2026-10-11T09:20:06Z — Assistant
Reviewed the official OWASP ASVS project and current stable v5.0.0. OWASP describes Level 2 as appropriate for sensitive data and significant business-to-business transactions; it also cautions that OWASP does not certify vendors or software. Recommended mapping applicable v5.0.0 Level 2 requirements to verification evidence, documenting exceptions/non-applicable controls, and making no certification claim. Asked stakeholder to accept or adjust this target (`AMB-006`). Source: https://github.com/OWASP/ASVS.
## 2026-10-11T09:21:04Z — User
Accepted OWASP ASVS v5.0.0 Level 2 as the application-security verification target.
## 2026-10-11T09:21:04Z — Assistant — Action summary
Updated `BRD-NFR-009` and the §6.2 summary to specify ASVS v5.0.0 Level 2, evidence mapping, and documented exceptions; narrowed `AMB-006` to remaining DPDP role/data mapping, classification, retention schedule, and other legal/contractual obligations; recorded `DEC-012`. Recommended confirming India-first scope and covering all natural persons whose personal data the tenant or platform processes (including staff and business contacts), not only account holders.
## 2026-10-11T09:21:25Z — Assistant
For the remaining DPDP scope, recommended v1 boundary: India-first tenant firms, with additional jurisdictions assessed before supporting tenants there; treat as Data Principals all natural persons whose personal data is present in tenant or platform processing (including staff and supplier/customer/carrier contacts), whether or not they have application accounts. Do not assume a dedicated child-data workflow; any intended processing of under-18s' personal data must be legally assessed before baseline. Asked stakeholder to accept or adjust these scope recommendations (`AMB-006`).
## 2026-10-11T09:22:03Z — User
Accepted India-first scope and coverage of all natural persons whose data appears in tenant/platform processing; non-India onboarding and intentional under-18 data processing require prior assessment.
## 2026-10-11T09:22:03Z — Assistant — Action summary
Updated `BRD-NFR-009`, `BRD-FR-047`–`BRD-FR-048`, and §7.2 for India-first onboarding, Data Principal coverage independent of app accounts, non-India jurisdiction assessment, and no planned intentional under-18 data use case without prior assessment/controls. Recorded `DEC-013`; refined `AMB-006`, which remains open for per-purpose legal mapping, classification, retention schedules, and other obligations.
## 2026-10-11T09:22:24Z — Assistant
For `AMB-006` retention schedules, recommended policy is to avoid a single global retention duration. The responsible Data Fiduciary (tenant for trading records; ATB operator for its own account/security/service data) should approve a retention schedule by personal-data category and purpose after legal/accounting review. The product should enforce those schedules, preserve any applicable statutory minimums and legal holds, and support erasure after the purpose and applicable retention obligations end. Asked stakeholder to accept or adjust this policy.
## 2026-10-11T09:30:08Z — User
Accepted the recommended category- and purpose-specific retention policy, approved by the responsible Data Fiduciary after legal/accounting review, preserving legal requirements and holds.
## 2026-10-11T09:30:08Z — Assistant — Action summary
Updated `BRD-FR-050` and `BRD-NFR-014` with the accepted retention governance, recorded `DEC-014`, and narrowed `AMB-006`: the policy is set, while actual durations by category/purpose and other legal/contractual obligations remain open for qualified review. Next: determine who supplies lawful-basis and privacy-notice mappings for each processing purpose.
## 2026-10-11T09:30:08Z — Assistant — Follow-up
Cleaned `AMB-006` to remove previously resolved Data Principal scope, retention-governance, and ASVS decisions, leaving per-purpose lawful-basis/notice mapping, classification, actual durations, and other legal/contractual duties for review. Recommended that each tenant Data Fiduciary approve the lawful basis and notice for tenant trading-data purposes, while the ATB operator separately documents its basis/notices for its own service processing; the product records those decisions and captures consent/withdrawal evidence only where consent is selected as the basis. Asked stakeholder to accept this responsibility model.
## 2026-10-11T09:31:36Z — User
Accepted the responsibility model for lawful basis and privacy notices: each tenant Data Fiduciary decides for trading data; the ATB operator separately documents its own purposes; consent evidence applies only when consent is selected as the basis.
## 2026-10-11T09:31:36Z — Assistant — Action summary
Updated `BRD-FR-047`, narrowed `AMB-006` to data classification, exact retention periods, and other legal/contractual obligations, recorded `DEC-015`, and updated master-context next actions. Saved checkpoint `CKPT-006` for Stage 0B elicitation; no tests or traceability gate run.
## 2026-10-11T09:33:15Z — User
Accepted the four-level internal sensitivity classification with separate personal-data and processing-purpose tags.
## 2026-10-11T09:33:15Z — Assistant — Action summary
Updated `BRD-NFR-014`, recorded `DEC-016`, and narrowed `AMB-006` to exact retention durations and other India-specific legal/contractual obligations requiring qualified review. Updated checkpoint `CKPT-006` to reflect this accepted decision and the remaining open items.
## 2026-10-11T09:33:34Z — Assistant
Updated the checkpoint’s exact next action to reflect that `DEC-016` is accepted and classification is resolved. Recommended a qualified review path: each tenant’s legal/accounting reviewer signs off trading-data purposes and retention; the ATB operator’s qualified privacy/legal reviewer approves platform processing, retention, and processor/subprocessor obligations. Do not invent retention values; keep `AMB-006` open until those approvals/evidence are recorded. Asked stakeholder to accept or adjust this review path.
## 2026-10-11T09:34:38Z — User
Accepted the qualified-review path: tenant legal/accounting reviewers approve tenant trading-data purposes/retention; ATB operator’s qualified privacy/legal reviewer approves its own processing, retention, and processor obligations.
## 2026-10-11T09:34:38Z — Assistant — Action summary
Updated `AMB-006` and recorded `DEC-017` for qualified approval and evidence; exact retention durations and additional obligations remain open until reviewed. Updated checkpoint `CKPT-006`. Next topic: `AMB-003`—how a tenant business owner validates provisional operating-policy seed values before go-live.
## 2026-10-11T09:34:52Z — Assistant
For `AMB-003`, recommended onboarding control: show §6.2 seed values as provisional and require each tenant’s Partner/Managing Director or delegated authorized business owner to review and confirm or edit all applicable operating thresholds before enabling the affected live workflows. Store confirmed policy version/effective date and audited changes. Missing or unreviewed thresholds should prevent only the affected risk-sensitive workflow from going live, rather than silently treating candidates as verified policy. Asked stakeholder to accept or adjust this gate.
## 2026-10-11T09:35:42Z — User
Accepted the tenant go-live review gate for provisional operating thresholds: Partner/Managing Director or delegated authorized business owner confirms/edits each applicable value before its affected workflow goes live; missing/unreviewed values block only affected risk-sensitive workflows.
## 2026-10-11T09:35:42Z — Assistant — Action summary
Updated `BRD-FR-052` and the §6.2 value preamble with tenant confirmation/edit, workflow-specific blocking, versioning/effective-date, and audit rules. Resolved `AMB-003`, recorded `DEC-018`, and removed `AMB-003` from next actions/checkpoint open items. `AMB-001`, `AMB-006`, and `AMB-008` remain open for pilot evidence, qualified legal review, and load-test evidence.
## 2026-10-11T09:36:15Z — Assistant
Refreshed checkpoint `CKPT-006` and master-context next actions after `AMB-003` resolved; validated 52 unique FR IDs and 14 unique NFR IDs. Next elicitation item is `AMB-001`. Recommended a pilot protocol: select a representative tenant, record 30 operating days of manual baseline for effort/transaction, gate-in-to-stock-posting time, and stock-reconciliation variance, then measure the same metrics for 30 operating days after rollout before setting improvement targets. Asked stakeholder to accept or adjust.
## 2026-10-11T09:37:28Z — User
Accepted the recommended `AMB-001` pilot protocol: use a representative tenant, measure 30 operating days of manual baseline for effort/transaction, gate-in-to-stock-posting time, and stock-reconciliation variance, then repeat for 30 operating days after rollout before setting improvement targets.
## 2026-10-11T09:37:28Z — Assistant — Action summary
Updated PRD §1.3 to specify the 30-operating-day pre-rollout manual baseline and 30-operating-day post-rollout comparison. Recorded stakeholder decision `DEC-019`; kept `AMB-001` open only for measured baseline/target values. Updated master context and `CKPT-006`/checkpoint index: Stage 0B now proceeds to a Human Review Brief, while `AMB-006` needs qualified legal/accounting evidence and `AMB-008` needs load-test and pilot evidence. The PRD remains Draft pending evidence and explicit baseline approval. Verification: 52 unique FR IDs (`001`–`052`), 14 unique NFR IDs (`001`–`014`), open ambiguities `AMB-001`, `AMB-006`, and `AMB-008`; scoped `git diff --check` passed. No tests or traceability gate run.

View File

@ -10,10 +10,10 @@
# ==============================================================================
project:
name: "Universal Enterprise Platform"
code: "UEP"
name: "Agriculture Trading Backoffice"
code: "ATB"
version: "1.0.0"
description: "Enterprise software modern platform"
description: "A backoffice platform for agriculture trading"
# Archetype: 'greenfield' (0-to-1 development) or 'brownfield' (legacy modernization/migration)
archetype: "greenfield"