From 773f62ce07dc003ca0151477c7446a6349106b33 Mon Sep 17 00:00:00 2001 From: Prashant Shendre Date: Thu, 15 Oct 2026 16:37:53 +0530 Subject: [PATCH 1/6] Updated for docker images of FE BE on local --- compose.yaml | 44 +++++++++++++++++++ docs/development/docker-compose.md | 4 +- frontend/src/features/auth/CallbackView.tsx | 2 +- frontend/src/features/auth/LoginView.tsx | 48 +++++++++++++++------ frontend/src/services/api.ts | 4 +- frontend/vite.config.ts | 3 ++ 6 files changed, 90 insertions(+), 15 deletions(-) diff --git a/compose.yaml b/compose.yaml index 25bfabb..9cbbc73 100644 --- a/compose.yaml +++ b/compose.yaml @@ -58,5 +58,49 @@ services: timeout: 3s retries: 10 + backend: + build: + context: . + dockerfile: docker/Dockerfile.backend + environment: + DATABASE_URL: postgresql://${POSTGRES_USER:-atb}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env; see .env.example}@postgres:5432/${POSTGRES_DB:-atb} + VALKEY_URL: valkey://valkey:6379/0 + KEYCLOAK_ISSUER: ${KEYCLOAK_ISSUER:-http://keycloak:8080/auth/realms/atb} + KEYCLOAK_CLIENT_ID: ${KEYCLOAK_CLIENT_ID:-atb-portal} + KEYCLOAK_CLIENT_SECRET: ${KEYCLOAK_CLIENT_SECRET:-} + USE_IDENTITY_MOCK: ${USE_IDENTITY_MOCK:-True} + ENVIRONMENT: ${ENVIRONMENT:-development} + LOG_LEVEL: ${LOG_LEVEL:-INFO} + ports: + - "127.0.0.1:8000:8000" + depends_on: + postgres: + condition: service_healthy + valkey: + condition: service_healthy + healthcheck: + test: ["CMD-SHELL", "curl -f http://127.0.0.1:8000/health || exit 1"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 15s + + frontend: + build: + context: . + dockerfile: docker/Dockerfile.frontend + ports: + - "${PORTAL_PORT:-3000}:80" + depends_on: + backend: + condition: service_healthy + healthcheck: + test: ["CMD-SHELL", "wget --quiet --tries=1 --spider http://127.0.0.1/healthz || exit 1"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 5s + volumes: postgres_data: + diff --git a/docs/development/docker-compose.md b/docs/development/docker-compose.md index 841ebca..878893e 100644 --- a/docs/development/docker-compose.md +++ b/docs/development/docker-compose.md @@ -28,6 +28,8 @@ The services publish ports on loopback only: | PostgreSQL | `127.0.0.1:5432` | `atb` database and user from `.env` | | Keycloak | | Local identity server; admin credentials from `.env` | | Valkey | `127.0.0.1:6379` | Local cache/stream dependency | +| Backend | `127.0.0.1:8000` | FastAPI application API (Swagger docs at `/docs`) | +| Frontend | `http://localhost:3000` | Hardened Nginx reverse proxy & React SPA portal | PostgreSQL also creates a separate `keycloak` database and login for Keycloak. Both databases share one local PostgreSQL container; this is a workstation convenience, not a production isolation recommendation. PostgreSQL data survives `docker compose down` in the named `postgres_data` volume. Valkey is intentionally ephemeral because the durable outbox belongs in PostgreSQL. @@ -48,6 +50,6 @@ To erase the local PostgreSQL data as well, add `--volumes` to the `down` comman The example uses the [PostgreSQL Docker Official Image](https://hub.docker.com/_/postgres), [Keycloak's official container image](https://www.keycloak.org/server/containers) from `quay.io/keycloak/keycloak`, and the [Valkey project's image](https://hub.docker.com/r/valkey/valkey). Release tags are pinned in `project_code/.env.example`; they are not immutable digest pins, and this repository has not configured image signature verification or a vendor certification policy. Review and update the selected tags through normal dependency maintenance. -The current repository has no application API, worker, frontend, migration, or test-runner source to build. Those services should be added to this Compose project as their implementation and test artifacts are authored; this file does not use placeholder build contexts. Mail capture, object-storage emulation, reverse proxy, and observability services are also omitted until their iteration needs and providers are selected. +The Compose project includes the core FastAPI backend API and hardened React SPA frontend services authored during Construction iterations, building directly from `docker/Dockerfile.backend` and `docker/Dockerfile.frontend`. Mail capture, object-storage emulation, and external observability services remain optional overlays until their iteration needs and providers are selected. This Compose configuration does not select a production runtime, change the approved production availability/recovery requirements, or demonstrate production readiness. Production hosting and its evidence gates remain open in the deployment design. diff --git a/frontend/src/features/auth/CallbackView.tsx b/frontend/src/features/auth/CallbackView.tsx index 3315820..62d2b4e 100644 --- a/frontend/src/features/auth/CallbackView.tsx +++ b/frontend/src/features/auth/CallbackView.tsx @@ -58,7 +58,7 @@ export const CallbackView: React.FC = () => { // Verify session with backend API setStatus('Initializing application session...'); - const sessionResp = await fetch('http://localhost:8000/api/v1/auth/session', { + const sessionResp = await fetch('/api/v1/auth/session', { headers: { Authorization: `Bearer ${accessToken}` }, }); diff --git a/frontend/src/features/auth/LoginView.tsx b/frontend/src/features/auth/LoginView.tsx index 8af138a..07cba56 100644 --- a/frontend/src/features/auth/LoginView.tsx +++ b/frontend/src/features/auth/LoginView.tsx @@ -11,7 +11,7 @@ import { Card } from '../../components/ui/Card'; import { ShieldCheck, LogIn, ChevronRight } from 'lucide-react'; export const LoginView: React.FC = () => { - const [selectedPersona, setSelectedPersona] = useState('buyer@alpha.com'); + const [selectedPersona, setSelectedPersona] = useState('buyer@malwa-agri.demo'); const [isLoading, setIsLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(null); @@ -74,15 +74,25 @@ export const LoginView: React.FC = () => { setIsLoading(true); setErrorMessage(null); try { + const isDemo = selectedPersona.endsWith('@malwa-agri.demo'); + const tenantId = isDemo ? 'demo-malwa-agri' : 'tenant-alpha'; + + const role = selectedPersona.includes('buyer') ? 'Mandi Buyer' : + selectedPersona.includes('pmgr') ? 'Purchase Manager' : + selectedPersona.includes('qc') ? 'Quality Officer' : + selectedPersona.includes('yard') || selectedPersona.includes('whmgr') ? 'Yard Supervisor' : + selectedPersona.includes('smgr') ? 'Sales Manager' : + selectedPersona.includes('sales') ? 'Sales Executive' : + selectedPersona.includes('logistics') ? 'Logistics Coordinator' : + selectedPersona.includes('finance') ? 'Accounts Executive' : + selectedPersona.includes('director') ? 'Partner / MD' : 'Tenant Administrator'; + authStore.setSession(`mock_token_${selectedPersona}`, { sub: `usr_${selectedPersona}`, email: selectedPersona, name: selectedPersona.split('@')[0], - roles: selectedPersona.includes('buyer') ? ['Mandi Buyer'] : - selectedPersona.includes('qc') ? ['Quality Officer'] : - selectedPersona.includes('yard') ? ['Yard Supervisor'] : - selectedPersona.includes('sales') ? ['Sales Executive'] : ['Tenant Administrator'], - tenant_id: 'tenant-alpha' + roles: [role], + tenant_id: tenantId }); window.location.href = '/'; } catch (err: any) { @@ -141,12 +151,26 @@ export const LoginView: React.FC = () => { onChange={(e) => setSelectedPersona(e.target.value)} className="w-full py-2 px-3 rounded bg-white border border-card-border text-text-primary text-xs focus:outline-none focus:border-sidebar-surface focus:ring-2 focus:ring-secondary-amber/20 font-mono transition" > - - - - - - + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+
+ + setObservationDate(e.target.value)} + className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre" + /> +
+
+ +
+
+ + +
+ +
+ + setFormVariety(e.target.value)} + className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre" + /> +
+
+ +
+ + setFormArrivalsMt(parseFloat(e.target.value) || 0)} + className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre" + /> + + Equivalent to ~{Math.round(formArrivalsMt * 20).toLocaleString('en-IN')} Bags (50kg standard) + +
+ +
+
+ APMC Auction Rate Spectrum (₹ / Quintal) +
+
+
+ + setFormMinRate(parseFloat(e.target.value) || 0)} + className="w-full py-1 px-2 rounded bg-white border border-card-border text-text-primary text-xs font-mono" + /> +
+
+ + setFormModalRate(parseFloat(e.target.value) || 0)} + className="w-full py-1 px-2 rounded bg-white border border-card-border text-text-primary text-xs font-mono font-bold" + /> +
+
+ + setFormMaxRate(parseFloat(e.target.value) || 0)} + className="w-full py-1 px-2 rounded bg-white border border-card-border text-text-primary text-xs font-mono" + /> +
+
+ + {validationError ? ( +
+ + {validationError} +
+ ) : ( +
+ + Invariant Enforced: Min (₹ {formMinRate}) ≤ Modal (₹ {formModalRate}) ≤ Max (₹ {formMaxRate}) +
+ )} +
+ +
+ + +
+
+ + + + )} + + ); +}; + diff --git a/frontend/src/features/procurement/SaudaProcurementView.tsx b/frontend/src/features/procurement/SaudaProcurementView.tsx new file mode 100644 index 0000000..1a6a937 --- /dev/null +++ b/frontend/src/features/procurement/SaudaProcurementView.tsx @@ -0,0 +1,797 @@ +/** + * SCREEN-PROC-001: Purchase Sauda Booking Register & Costing View. + * + * Fulfills FR-PROCUREMENTCONTRACTS-001..004 & SCREEN-PROC-001.md (Iteration 03 / UC-004). + * Styled per DESIGN.md: AgriTrade Mercantile (Tactile Corporate Minimalism). + */ +import React, { useState } from 'react'; +import { Card } from '../../components/ui/Card'; +import { Button } from '../../components/ui/Button'; +import { StatusPill } from '../../components/ui/StatusPill'; +import { apiClient } from '../../services/api'; +import { + ShoppingCart, + Plus, + AlertTriangle, + CheckCircle2, + Calculator, + Search, + Filter +} from 'lucide-react'; + +export interface SaudaContract { + id: string; + sauda_number: string; + contract_date: string; + delivery_due_date: string; + supplier_name: string; + mandi_hub: string; + commodity_name: string; + variety: string; + grade: string; + booked_quantity_mt: number; + estimated_bags: number; + trade_rate_per_qtl: number; + gross_value: number; + landed_value: number; + mandi_cess: number; + krishi_kalyan: number; + brokerage: number; + credit_days: number; + fulfilled_pct: number; + status: 'ACTIVE' | 'PENDING' | 'CLOSED' | 'REJECTED'; +} + +const DEFAULT_SAUDAS: SaudaContract[] = [ + { + id: 'sda-rec-01', + sauda_number: 'SDA-2026-001', + contract_date: '2026-10-15', + delivery_due_date: '2026-10-22', + supplier_name: 'Rameshwar Patidar (Farmer / Arhatiya - Neemuch)', + mandi_hub: 'Indore APMC', + commodity_name: 'Soyabean', + variety: 'Yellow Desi', + grade: 'FAQ', + booked_quantity_mt: 25.0, + estimated_bags: 500, + trade_rate_per_qtl: 4850.0, + gross_value: 1212500.0, + mandi_cess: 18187.5, + krishi_kalyan: 6062.5, + brokerage: 12125.0, + landed_value: 1248875.0, + credit_days: 7, + fulfilled_pct: 0.0, + status: 'ACTIVE' + }, + { + id: 'sda-rec-02', + sauda_number: 'SDA-26-00142', + contract_date: '2026-10-14', + delivery_due_date: '2026-10-20', + supplier_name: 'Kisan Agro Traders (SUP-0042)', + mandi_hub: 'Kota APMC', + commodity_name: 'Soyabean', + variety: 'Yellow Desi', + grade: 'FAQ', + booked_quantity_mt: 50.0, + estimated_bags: 1000, + trade_rate_per_qtl: 4750.0, + gross_value: 2375000.0, + mandi_cess: 35625.0, + krishi_kalyan: 11875.0, + brokerage: 23750.0, + landed_value: 2446250.0, + credit_days: 15, + fulfilled_pct: 60.0, + status: 'ACTIVE' + }, + { + id: 'sda-rec-03', + sauda_number: 'SDA-26-00143', + contract_date: '2026-10-13', + delivery_due_date: '2026-10-18', + supplier_name: 'Mewar Krishi Sangh', + mandi_hub: 'Unjha APMC', + commodity_name: 'Cumin/Jeera', + variety: 'Special Bold', + grade: 'FAQ', + booked_quantity_mt: 20.0, + estimated_bags: 400, + trade_rate_per_qtl: 24500.0, + gross_value: 4900000.0, + mandi_cess: 73500.0, + krishi_kalyan: 24500.0, + brokerage: 49000.0, + landed_value: 5047000.0, + credit_days: 5, + fulfilled_pct: 0.0, + status: 'PENDING' + }, + { + id: 'sda-rec-04', + sauda_number: 'SDA-26-00144', + contract_date: '2026-10-11', + delivery_due_date: '2026-10-16', + supplier_name: 'Malwa Agro Corp', + mandi_hub: 'Indore APMC', + commodity_name: 'Wheat', + variety: 'Lokwan', + grade: 'FAQ', + booked_quantity_mt: 100.0, + estimated_bags: 2000, + trade_rate_per_qtl: 2420.0, + gross_value: 2420000.0, + mandi_cess: 36300.0, + krishi_kalyan: 12100.0, + brokerage: 24200.0, + landed_value: 2492600.0, + credit_days: 10, + fulfilled_pct: 100.0, + status: 'CLOSED' + } +]; + +const BENCHMARK_MODAL_RATE = 4800.0; // Indore APMC Soybean modal clearing rate benchmark + +export const SaudaProcurementView: React.FC = () => { + const [saudas, setSaudas] = useState(DEFAULT_SAUDAS); + const [searchQuery, setSearchQuery] = useState(''); + const [statusFilter, setStatusFilter] = useState('ALL'); + const [isModalOpen, setIsModalOpen] = useState(false); + const [notification, setNotification] = useState<{ type: 'success' | 'error'; message: string } | null>(null); + + // Form State matching Playbook Journey 1 + const [contractDate, setContractDate] = useState('2026-10-15'); + const [sourcingMandi, setSourcingMandi] = useState('Indore APMC, Madhya Pradesh'); + const [tradeType, setTradeType] = useState('MANDI_AUCTION'); + const [supplierName, setSupplierName] = useState('Rameshwar Patidar (Farmer / Arhatiya - Neemuch)'); + const [commodity, setCommodity] = useState('Soyabean (SOY)'); + const [variety, setVariety] = useState('Yellow FAQ'); + const [bookedMt, setBookedMt] = useState(25.0); + const [tradeRate, setTradeRate] = useState(4850.0); + const [creditDays, setCreditDays] = useState(7); + const [isSubmitting, setIsSubmitting] = useState(false); + const [varianceConfirmed, setVarianceConfirmed] = useState(false); + + // Computed Bags: MT * 1000 / 50kg = MT * 20 + const estimatedBags = Math.round(bookedMt * 20); + + // Computed Payment Due Date + const computeDueDate = (dateStr: string, days: number): string => { + try { + const d = new Date(dateStr); + d.setDate(d.getDate() + days); + return d.toISOString().split('T')[0]; + } catch { + return dateStr; + } + }; + const paymentDueDate = computeDueDate(contractDate, creditDays); + + // Rate Variance calculation: ((tradeRate - benchmark) / benchmark) * 100 + const rateVariancePct = ((tradeRate - BENCHMARK_MODAL_RATE) / BENCHMARK_MODAL_RATE) * 100; + const isVarianceExceeded = rateVariancePct > 5.0; + + // Commercial Math per NFR-001 (Dual UOM, Statutory Rounding) + // Base Value = MT * 10 Qtl/MT * Rate/Qtl + const grossTradeValue = bookedMt * 10 * tradeRate; + const mandiCess = grossTradeValue * 0.015; // 1.50% + const krishiKalyan = grossTradeValue * 0.005; // 0.50% + const brokerage = grossTradeValue * 0.01; // 1.00% + const totalLandedValue = grossTradeValue + mandiCess + krishiKalyan + brokerage; + + const handleBookSauda = async (e: React.FormEvent) => { + e.preventDefault(); + if (isVarianceExceeded && !varianceConfirmed) { + return; + } + + setIsSubmitting(true); + setNotification(null); + + const generatedSaudaNumber = `SDA-2026-${String(saudas.length + 1).padStart(3, '0')}`; + + try { + const payload = { + sauda_number: generatedSaudaNumber, + contract_date: contractDate, + delivery_due_date: paymentDueDate, + supplier_id: 'sup-patidar-01', + mandi_id: 'mandi-indore-01', + trade_type: tradeType, + commodity_id: 'SOY', + variety: variety, + grade: 'FAQ', + booked_quantity_mt: bookedMt, + trade_rate_per_qtl: tradeRate, + rate_variance_pct: rateVariancePct, + variance_acknowledged: isVarianceExceeded ? varianceConfirmed : false, + credit_period_days: creditDays, + payment_due_date: paymentDueDate, + mandi_cess_pct: 1.5, + krishi_kalyan_pct: 0.5, + brokerage_rate_pct: 1.0, + gross_value: grossTradeValue, + landed_value: totalLandedValue + }; + + const resp = await apiClient('/api/v1/procurement/sauda', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + if (resp.error) { + // Log non-blocking backend response while preserving offline mock UI state + console.warn('Backend sauda booking response:', resp.error); + } + + const newContract: SaudaContract = { + id: `sda-${Date.now()}`, + sauda_number: generatedSaudaNumber, + contract_date: contractDate, + delivery_due_date: paymentDueDate, + supplier_name: supplierName, + mandi_hub: sourcingMandi.split(',')[0], + commodity_name: commodity.split(' ')[0], + variety: variety, + grade: 'FAQ', + booked_quantity_mt: bookedMt, + estimated_bags: estimatedBags, + trade_rate_per_qtl: tradeRate, + gross_value: grossTradeValue, + landed_value: totalLandedValue, + mandi_cess: mandiCess, + krishi_kalyan: krishiKalyan, + brokerage: brokerage, + credit_days: creditDays, + fulfilled_pct: 0.0, + status: 'ACTIVE' + }; + + setSaudas([newContract, ...saudas]); + setNotification({ + type: 'success', + message: `Sauda Contract ${generatedSaudaNumber} locked successfully! Landed value ₹ ${totalLandedValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })} booked for ${supplierName}.` + }); + + setIsModalOpen(false); + // Reset form + setBookedMt(25.0); + setTradeRate(4850.0); + setVarianceConfirmed(false); + } catch (err: any) { + setNotification({ + type: 'error', + message: `Failed to book sauda: ${err.message}` + }); + } finally { + setIsSubmitting(false); + } + }; + + // Filtered saudas + const filteredSaudas = saudas.filter(s => { + const matchesSearch = s.sauda_number.toLowerCase().includes(searchQuery.toLowerCase()) || + s.supplier_name.toLowerCase().includes(searchQuery.toLowerCase()) || + s.commodity_name.toLowerCase().includes(searchQuery.toLowerCase()); + const matchesStatus = statusFilter === 'ALL' || s.status === statusFilter; + return matchesSearch && matchesStatus; + }); + + const activeCount = saudas.filter(s => s.status === 'ACTIVE').length; + const totalOpenMt = saudas + .filter(s => s.status === 'ACTIVE') + .reduce((acc, s) => acc + (s.booked_quantity_mt * (1 - s.fulfilled_pct / 100)), 0); + const totalExposure = saudas + .filter(s => s.status === 'ACTIVE') + .reduce((acc, s) => acc + s.landed_value, 0); + + return ( +
+ {/* Top Banner Alert / Notification */} + {notification && ( +
+
+ {notification.type === 'success' ? ( + + ) : ( + + )} + {notification.message} +
+ +
+ )} + + {/* Summary KPI Cards */} +
+
+
+ Active Sauda Contracts +
+
+ {activeCount} + Contracts +
+
+ Indore & Kota Mandis +
+
+ +
+
+ Open Balance Position +
+
+ + {totalOpenMt.toFixed(2)} + + MT Pending Receiving +
+
+ ~{Math.round(totalOpenMt * 20).toLocaleString('en-IN')} Bags Scheduled +
+
+ +
+
+ Committed Procurement Exposure +
+
+ + ₹ {(totalExposure / 100000).toFixed(2)} + + Lakhs +
+
+ Landed including statutory cess +
+
+ +
+
+ Indore Benchmark Modal +
+
+ + ₹ {BENCHMARK_MODAL_RATE.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + + / Qtl +
+
+ Real-time Market Desk Peg +
+
+
+ + {/* Main Register Filter & Action Bar */} +
+
+
+ + setSearchQuery(e.target.value)} + className="w-full pl-9 pr-3 py-1.5 rounded bg-white border border-card-border text-xs text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre" + /> +
+ +
+ + +
+
+ +
+ +
+
+ + {/* Sauda Contracts Table (SCREEN-PROC-001) */} + + SCREEN-PROC-001 • UC-004 + + } + > +
+ + + + + + + + + + + + + + + + + + {filteredSaudas.length === 0 ? ( + + + + ) : ( + filteredSaudas.map((sauda) => ( + + + + + + + + + + + + + + )) + )} + +
Contract IDDateSupplier / ArhatiyaMandi HubCommodityBooked MTAgreed RateBase ValueLanded ValueFulfilledStatus
+ No sauda contracts found matching criteria. +
+ {sauda.sauda_number} + + {sauda.contract_date} + + {sauda.supplier_name} + + {sauda.mandi_hub} + + {sauda.commodity_name}{' '} + ({sauda.variety}) + + {sauda.booked_quantity_mt.toFixed(3)} MT +
{sauda.estimated_bags} bags
+
+ ₹ {sauda.trade_rate_per_qtl.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + + ₹ {sauda.gross_value.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + + ₹ {sauda.landed_value.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + + + {sauda.fulfilled_pct.toFixed(1)} % + + + +
+
+
+ + {/* Book New Sauda Modal Dialog (SCREEN-PROC-001 / Sales Demo Journey 1) */} + {isModalOpen && ( +
+
+
setIsModalOpen(false)} + /> + +
+
+
+ +

+ Book Purchase Sauda Contract (Mandi Auction / Direct Purchase) +

+
+ +
+ +
+ {/* Contract Dates & Sourcing Yard */} +
+
+ + setContractDate(e.target.value)} + className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre" + /> +
+
+ + +
+
+ + {/* Supplier & Trade Type */} +
+
+ + +
+
+ + +
+
+ + {/* Commodity, Variety & Grade */} +
+
+ + +
+
+ + setVariety(e.target.value)} + className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono focus:outline-none focus:ring-1 focus:ring-accent-ochre" + /> +
+
+ + +
+
+ + {/* Trade Quantity & Pricing with Dual-UOM */} +
+
+ Trade Quantity & Pricing Alignment + Benchmark Modal: ₹ {BENCHMARK_MODAL_RATE.toLocaleString('en-IN')}/Qtl +
+ +
+
+ + setBookedMt(parseFloat(e.target.value) || 0)} + className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono font-bold focus:outline-none focus:ring-1 focus:ring-accent-ochre" + /> +
+
+ + +
+
+ + setTradeRate(parseFloat(e.target.value) || 0)} + className="w-full py-1.5 px-2.5 rounded bg-white border border-card-border text-text-primary text-xs font-mono font-bold focus:outline-none focus:ring-1 focus:ring-accent-ochre" + /> +
+
+ + {/* Price Variance Safeguard Banner per Playbook Journey 1 */} + {isVarianceExceeded ? ( +
+
+ + + Price variance (+{rateVariancePct.toFixed(2)}%) exceeds 5.0% benchmark threshold! + +
+

+ Agreed rate (₹ {tradeRate.toFixed(2)}) is higher than Indore APMC clearing rate (₹ {BENCHMARK_MODAL_RATE.toFixed(2)}). Mandatory confirmation required before locking. +

+ +
+ ) : ( +
+ + + Rate Variance: {rateVariancePct >= 0 ? `+${rateVariancePct.toFixed(2)}%` : `${rateVariancePct.toFixed(2)}%`} (Safely within 5.0% benchmark threshold) + +
+ )} +
+ + {/* Commercial Terms & Statutory Levies Calculator */} +
+
+ + + Instant Landed Cost Breakdown (NFR-001 Dual-UOM) + +
+ Terms: + + Due: {paymentDueDate} +
+
+ +
+
+ Base Value ({bookedMt.toFixed(3)} MT • 10 Qtl/MT • ₹ {tradeRate}): + ₹ {grossTradeValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })} +
+
+ APMC Mandi Cess (1.50%): + ₹ {mandiCess.toLocaleString('en-IN', { minimumFractionDigits: 2 })} +
+
+ Krishi Kalyan Cess (0.50%): + ₹ {krishiKalyan.toLocaleString('en-IN', { minimumFractionDigits: 2 })} +
+
+ Brokerage / Arhat (1.00%): + ₹ {brokerage.toLocaleString('en-IN', { minimumFractionDigits: 2 })} +
+
+ Total Landed Sauda Value: + ₹ {totalLandedValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })} +
+
+
+ + {/* Modal Action Buttons */} +
+ + +
+
+
+
+
+ )} +
+ ); +}; -- 2.34.1 From 67d24daac6108529df8ab61d22c8635e0a8e5aff Mon Sep 17 00:00:00 2001 From: Prashant Shendre Date: Thu, 15 Oct 2026 19:51:21 +0530 Subject: [PATCH 5/6] Fixed hardcoded data and ensured seed data would be used. Checkpointing to resume process quality gates update tomorrow --- backend/app/api/procurement.py | 4 +- backend/app/db/demo_seed.py | 798 ++++++++++++++++++ backend/app/db/session.py | 6 + backend/app/main.py | 26 +- .../src/features/market/MarketDeskView.tsx | 362 ++++---- .../procurement/SaudaProcurementView.tsx | 366 ++++---- 6 files changed, 1211 insertions(+), 351 deletions(-) create mode 100644 backend/app/db/demo_seed.py diff --git a/backend/app/api/procurement.py b/backend/app/api/procurement.py index b56855c..70f80b7 100644 --- a/backend/app/api/procurement.py +++ b/backend/app/api/procurement.py @@ -76,11 +76,11 @@ class ProcurementController: ctx = auth_res["context"] # Check required roles - allowed_roles = {"Procurement Officer", "Desk Trader", "Purchase Manager", "Tenant Administrator"} + allowed_roles = {"Mandi Buyer", "Procurement Officer", "Desk Trader", "Purchase Manager", "Tenant Administrator"} if not any(r in allowed_roles for r in ctx.roles): return { "error": "INSUFFICIENT_PERMISSIONS", - "message": "Only Procurement Officers, Desk Traders, or Tenant Admins can book purchase contracts", + "message": "Only Mandi Buyers, Procurement Officers, Desk Traders, or Tenant Admins can book purchase contracts", "status_code": 403 } diff --git a/backend/app/db/demo_seed.py b/backend/app/db/demo_seed.py new file mode 100644 index 0000000..33135bb --- /dev/null +++ b/backend/app/db/demo_seed.py @@ -0,0 +1,798 @@ +"""ATB Demo Dataset Provisioning and Teardown Engine. + +Standardized per UP-AI v1.5 Phase IV Transition Standards. +Fulfills commercial sales demo requirements by provisioning an isolated, realistic, +relational dataset for demo tenant 'demo-malwa-agri' (Malwa Agri Trading Corp). +Can be invoked in-memory inside the running backend process or via CLI scripts. +""" +from datetime import datetime, date, timedelta, timezone +from decimal import Decimal +import logging +from typing import Any, Dict, List, Optional +import uuid + +from backend.app.models.tenant import Tenant, TenantMembership +from backend.app.models.master_data import ( + Commodity, + CommodityVariety, + TradingCounterparty, + Godown, +) +from backend.app.models.policy import TenantOperatingPolicy +from backend.app.models.market import MarketObservation +from backend.app.models.procurement import ProcurementSauda +from backend.app.models.receiving import InwardGateEntry, WeighbridgeSlip, GoodsReceiptNote +from backend.app.models.quality import InventoryLot, QualityInspection +from backend.app.models.sales import CustomerSalesOrder, SalesOrderAllocation +from backend.app.models.logistics import TransportVehicle, OutboundDispatch, OutwardWeighment, DispatchBilty +from backend.app.models.finance import PartySubLedgerEntry, SupplierPayable, MandiExpenseVoucher +from backend.app.models.reporting import DailyTradingSnapshot, OperationalAlert + +logger = logging.getLogger("atb.db.demo_seed") + +DEFAULT_TENANT_ID = "demo-malwa-agri" +DEFAULT_BUSINESS_NAME = "Malwa Agri Trading Corp Pvt Ltd" +DEFAULT_LEGAL_ID = "23AABCM1234F1Z1" +DEFAULT_PRIMARY_MANDI = "Indore APMC Yard (MP-IND-01)" +DEFAULT_ADMIN_EMAIL = "admin@malwa-agri.demo" + +CASCADE_PURGE_ORDER = [ + ("daily_trading_snapshots", "Daily Trading Snapshots"), + ("operational_alerts", "Operational Hazard Alerts"), + ("mandi_expense_vouchers", "Mandi Cess Expense Vouchers"), + ("supplier_payables", "Supplier Accounts Payable"), + ("party_subledger_entries", "Party Double-Entry Subledgers"), + ("dispatch_bilties", "Transport Consignment Bilties"), + ("outward_weighments", "Outward Weighbridge Readings"), + ("outbound_dispatches", "Outbound Dispatch Consignments"), + ("sales_order_allocations", "Sales Lot Allocations"), + ("customer_sales_orders", "Customer Sales Contracts"), + ("quality_inspections", "Laboratory Quality Assays"), + ("inventory_lots", "Warehouse Inventory Lots"), + ("goods_receipt_notes", "Goods Receipt Notes (GRN)"), + ("weighbridge_slips", "Inward Weighbridge Slips"), + ("inward_gate_entries", "Inward Gate Entry Passes"), + ("procurement_sauda", "Procurement Sauda Contracts"), + ("market_observations", "Mandi Market Rate Observations"), + ("transport_fleet", "Transport Fleet Registry"), + ("fleet_vehicles", "Fleet Vehicles"), + ("tenant_operating_policies", "Tenant Operating Risk Policies"), + ("operating_policies", "Operating Policies"), + ("counterparties", "Trading Counterparties Directory"), + ("godowns", "Warehouse Godowns & Stacks"), + ("commodity_varieties", "Commodity Varieties"), + ("commodities", "Commodity Catalog"), +] + + +def purge_demo_dataset(store: Any, tenant_id: str = DEFAULT_TENANT_ID, purge_tenant: bool = False) -> Dict[str, Any]: + """Safely cascades deletion of all demo tenant records with zero residue. + + By default, preserves the tenant shell and operator memberships so the application + can immediately be used in a pristine empty state without requiring re-login. + """ + if not tenant_id.startswith("demo-"): + raise ValueError(f"Safety Rail: Refusing to purge non-demo tenant '{tenant_id}'") + + logger.info("Purging demo tenant '%s' (purge_tenant=%s)...", tenant_id, purge_tenant) + purge_metrics: Dict[str, int] = {} + + for coll_name, _ in CASCADE_PURGE_ORDER: + count = 0 + if coll_name in store._collections and tenant_id in store._collections[coll_name]: + count = len(store._collections[coll_name][tenant_id]) + del store._collections[coll_name][tenant_id] + purge_metrics[coll_name] = count + + if purge_tenant: + # Purge memberships + mem_keys = [k for k, m in store.memberships.items() if m.tenant_id == tenant_id] + for k in mem_keys: + del store.memberships[k] + purge_metrics["memberships"] = len(mem_keys) + + # Purge tenant + tenant_deleted = False + if tenant_id in store.tenants: + del store.tenants[tenant_id] + tenant_deleted = True + purge_metrics["tenant_deleted"] = 1 if tenant_deleted else 0 + else: + # Guarantee tenant and persona memberships remain cleanly active + if tenant_id not in store.tenants: + store.tenants[tenant_id] = Tenant( + tenant_id=tenant_id, + business_name=DEFAULT_BUSINESS_NAME, + legal_identifier=DEFAULT_LEGAL_ID, + primary_mandi=DEFAULT_PRIMARY_MANDI, + contact_email=DEFAULT_ADMIN_EMAIL, + status="ACTIVE" + ) + demo_memberships = [ + ("mem-demo-admin", "user-admin-01", "admin@malwa-agri.demo", "TENANT_ADMIN"), + ("mem-demo-buyer", "user-buyer-01", "buyer@malwa-agri.demo", "MANDI_BUYER"), + ("mem-demo-trader", "user-trader-01", "trader@malwa-agri.demo", "DESK_TRADER"), + ("mem-demo-weigh", "user-weigh-01", "weighbridge@malwa-agri.demo", "WEIGHBRIDGE_OPERATOR"), + ("mem-demo-qc", "user-qc-01", "qc@malwa-agri.demo", "QUALITY_ANALYST"), + ("mem-demo-sales", "user-sales-01", "smgr@malwa-agri.demo", "SALES_MANAGER"), + ("mem-demo-accts", "user-accts-01", "accts@malwa-agri.demo", "ACCOUNTANT"), + ("mem-demo-exec", "user-exec-01", "exec@malwa-agri.demo", "EXECUTIVE_VIEWER"), + ] + for mem_id, user_id, email, role in demo_memberships: + if mem_id not in store.memberships: + store.memberships[mem_id] = TenantMembership( + membership_id=mem_id, + tenant_id=tenant_id, + user_id=user_id, + email=email, + role=role, + status="ACTIVE" + ) + purge_metrics["tenant_active"] = 1 + purge_metrics["memberships_active"] = len(demo_memberships) + + return purge_metrics + + +def seed_demo_dataset(store: Any, tenant_id: str = DEFAULT_TENANT_ID) -> Dict[str, Any]: + """Provisions cohesive, relational sales demo records for tenant_id.""" + if not tenant_id.startswith("demo-"): + raise ValueError(f"Safety Rail: Refusing to seed non-demo tenant '{tenant_id}'") + + # 1. Clean prior demo state + purge_demo_dataset(store, tenant_id) + + # 2. Provision Tenant + tenant = Tenant( + tenant_id=tenant_id, + business_name=DEFAULT_BUSINESS_NAME, + legal_identifier=DEFAULT_LEGAL_ID, + primary_mandi=DEFAULT_PRIMARY_MANDI, + contact_email=DEFAULT_ADMIN_EMAIL, + status="ACTIVE" + ) + store.save_tenant(tenant) + + # 3. Provision RBAC Memberships for all demo personas + demo_memberships = [ + ("mem-demo-admin", "user-admin-01", "admin@malwa-agri.demo", "TENANT_ADMIN"), + ("mem-demo-buyer", "user-buyer-01", "buyer@malwa-agri.demo", "MANDI_BUYER"), + ("mem-demo-trader", "user-trader-01", "trader@malwa-agri.demo", "DESK_TRADER"), + ("mem-demo-weigh", "user-weigh-01", "weighbridge@malwa-agri.demo", "WEIGHBRIDGE_OPERATOR"), + ("mem-demo-qc", "user-qc-01", "qc@malwa-agri.demo", "QUALITY_ANALYST"), + ("mem-demo-sales", "user-sales-01", "smgr@malwa-agri.demo", "SALES_MANAGER"), + ("mem-demo-accts", "user-accts-01", "accts@malwa-agri.demo", "ACCOUNTANT"), + ("mem-demo-exec", "user-exec-01", "exec@malwa-agri.demo", "EXECUTIVE_VIEWER"), + ] + for mem_id, user_id, email, role in demo_memberships: + store.memberships[mem_id] = TenantMembership( + membership_id=mem_id, + tenant_id=tenant_id, + user_id=user_id, + email=email, + role=role, + status="ACTIVE" + ) + + # 4. Provision Master Data + commodities = [ + Commodity( + tenant_id=tenant_id, + code="SOY", + name="Soyabean (Yellow)", + hsn_code="12010090", + standard_bag_weight_kg=50.0, + moisture_baseline_pct=10.0, + foreign_matter_max_pct=1.5, + damaged_grain_max_pct=2.0, + id="c0a80123-demo-0000-0000-000000000001" + ), + Commodity( + tenant_id=tenant_id, + code="CHN", + name="Chana (Bengal Gram)", + hsn_code="07132000", + standard_bag_weight_kg=50.0, + moisture_baseline_pct=10.5, + foreign_matter_max_pct=1.0, + damaged_grain_max_pct=3.0, + id="c0a80123-demo-0000-0000-000000000002" + ), + Commodity( + tenant_id=tenant_id, + code="WHT", + name="Wheat (Sharbati & Lokwan)", + hsn_code="10019910", + standard_bag_weight_kg=50.0, + moisture_baseline_pct=11.0, + foreign_matter_max_pct=1.0, + damaged_grain_max_pct=2.0, + id="c0a80123-demo-0000-0000-000000000003" + ), + Commodity( + tenant_id=tenant_id, + code="MST", + name="Mustard (Sarson / Raida)", + hsn_code="12075010", + standard_bag_weight_kg=50.0, + moisture_baseline_pct=8.0, + foreign_matter_max_pct=1.0, + damaged_grain_max_pct=2.0, + id="c0a80123-demo-0000-0000-000000000004" + ), + ] + for c in commodities: + store.insert("commodities", tenant_id, c.to_dict()) + + varieties = [ + CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[0].id, code="VAR-SOY-01", name="Yellow Desi FAQ", id="var-demo-001"), + CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[0].id, code="VAR-SOY-02", name="JS-335 Grade A", id="var-demo-002"), + CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[1].id, code="VAR-CHN-01", name="Desi Bold FAQ", id="var-demo-003"), + CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[2].id, code="VAR-WHT-01", name="Lokwan FAQ", id="var-demo-004"), + CommodityVariety(tenant_id=tenant_id, commodity_id=commodities[3].id, code="VAR-MST-01", name="42% Oil Conditioned", id="var-demo-005"), + ] + for v in varieties: + store.insert("commodity_varieties", tenant_id, v.to_dict()) + + godowns = [ + Godown( + tenant_id=tenant_id, + code="WH-IND-01", + name="Central Warehouse Indore", + capacity_mt=5000.0, + address="Sanwer Road Industrial Area, Sector C, Indore, MP", + chambers_count=4, + id="godown-demo-indore" + ), + Godown( + tenant_id=tenant_id, + code="WH-NMC-01", + name="Mandi Yard Shed Neemuch", + capacity_mt=2500.0, + address="Mandi Yard Complex, Gate 2, Neemuch, MP", + chambers_count=2, + id="godown-demo-neemuch" + ), + ] + for g in godowns: + store.insert("godowns", tenant_id, g.to_dict()) + + counterparties = [ + TradingCounterparty( + tenant_id=tenant_id, + name="Rameshwar Patidar (Farmer / Arhatiya)", + counterparty_type="FARMER", + pan_number="ABCDE1234F", + bank_account_number="30192837465", + bank_ifsc_code="SBIN0001234", + bank_name="State Bank of India", + phone="9826012345", + credit_terms_days=7, + id="cpty-demo-supplier-01" + ), + TradingCounterparty( + tenant_id=tenant_id, + name="Kisan Agro Traders (SUP-0042)", + counterparty_type="COMMISSION_AGENT", + pan_number="AABCK9912F", + gstin="23AABCK9912F1Z4", + bank_account_number="200911223344", + bank_ifsc_code="HDFC0001234", + bank_name="HDFC Bank", + phone="9826112233", + credit_terms_days=15, + id="cpty-demo-supplier-02" + ), + TradingCounterparty( + tenant_id=tenant_id, + name="Mewar Krishi Sangh", + counterparty_type="COMMISSION_AGENT", + pan_number="AABCM4411F", + gstin="08AABCM4411F1Z2", + bank_account_number="400911223355", + bank_ifsc_code="ICIC0000002", + bank_name="ICICI Bank", + phone="9829011223", + credit_terms_days=7, + id="cpty-demo-supplier-03" + ), + TradingCounterparty( + tenant_id=tenant_id, + name="MP Soya Extraction Industries Ltd", + counterparty_type="PROCESSOR", + pan_number="AABCM8811F", + gstin="23AABCM8811F1Z9", + bank_account_number="501009988776", + bank_ifsc_code="ICIC0000001", + bank_name="ICICI Bank", + phone="9425011223", + credit_limit_inr=5000000.00, + credit_terms_days=15, + id="cpty-demo-customer-01" + ), + TradingCounterparty( + tenant_id=tenant_id, + name="Gujarat Dal & Pulse Millers", + counterparty_type="WHOLESALE_BUYER", + pan_number="AABCG5512F", + gstin="24AABCG5512F1Z8", + bank_account_number="100988776655", + bank_ifsc_code="BARB0UNJHAX", + bank_name="Bank of Baroda", + phone="9898012345", + credit_limit_inr=4000000.00, + credit_terms_days=21, + id="cpty-demo-customer-02" + ), + ] + for cp in counterparties: + store.insert("counterparties", tenant_id, cp.to_dict()) + + fleet = [ + TransportVehicle( + tenant_id=tenant_id, + reg_no="MP09BC8812", + make_model="Tata Signa 2823.K", + payload_capacity_mt=Decimal("28.000"), + ownership_type="Contract", + transporter_name="Malwa Freight Carriers", + status="Available", + fitness_expiry=(date.today() + timedelta(days=180)).isoformat(), + vehicle_id="veh-demo-01" + ), + TransportVehicle( + tenant_id=tenant_id, + reg_no="MP09GH4521", + make_model="Ashok Leyland 1618", + payload_capacity_mt=Decimal("16.000"), + ownership_type="Own", + transporter_name="Malwa Fleet Internal", + status="Available", + fitness_expiry=(date.today() + timedelta(days=90)).isoformat(), + vehicle_id="veh-demo-02" + ), + ] + for f in fleet: + store.insert("transport_fleet", tenant_id, f.to_dict()) + + # 5. Operating Policies + policy = TenantOperatingPolicy( + tenant_id=tenant_id, + created_by="admin@malwa-agri.demo", + change_reason="Baseline commercial trading and credit risk policy", + effective_from=datetime.now(timezone.utc) - timedelta(days=30), + weighbridge_tolerance_pct=0.50, + moisture_deduction_threshold_pct=12.00, + credit_watch_threshold_pct=80.00, + credit_lock_threshold_pct=100.00, + qc_required_default=True, + partner_dispatch_override_ceiling_inr=5000000.00, + id="pol-demo-01" + ) + store.insert("tenant_operating_policies", tenant_id, policy.to_dict()) + + # 6. Daily Mandi Observations (Indore APMC, MP-IND-01 for Today) + today = date.today() + observations = [ + MarketObservation( + tenant_id=tenant_id, + mandi_id="MP-IND-01", + observation_date=today, + commodity_id="SOY", + variety="Yellow Desi", + grade="FAQ", + arrival_mt=Decimal("620.000"), + min_rate=Decimal("4550.00"), + max_rate=Decimal("4900.00"), + modal_rate=Decimal("4800.00"), + source="APMC_BULLETIN", + is_market_closed=False, + observation_id="mkt-demo-obs-01" + ), + MarketObservation( + tenant_id=tenant_id, + mandi_id="MP-IND-01", + observation_date=today, + commodity_id="CHN", + variety="Desi Bold", + grade="FAQ", + arrival_mt=Decimal("280.000"), + min_rate=Decimal("5800.00"), + max_rate=Decimal("6150.00"), + modal_rate=Decimal("6000.00"), + source="APMC_BULLETIN", + is_market_closed=False, + observation_id="mkt-demo-obs-02" + ), + MarketObservation( + tenant_id=tenant_id, + mandi_id="MP-IND-01", + observation_date=today, + commodity_id="WHT", + variety="Lokwan", + grade="FAQ", + arrival_mt=Decimal("450.000"), + min_rate=Decimal("2350.00"), + max_rate=Decimal("2550.00"), + modal_rate=Decimal("2450.00"), + source="APMC_BULLETIN", + is_market_closed=False, + observation_id="mkt-demo-obs-03" + ), + MarketObservation( + tenant_id=tenant_id, + mandi_id="MP-IND-01", + observation_date=today, + commodity_id="MST", + variety="42% Oil", + grade="FAQ", + arrival_mt=Decimal("190.000"), + min_rate=Decimal("5200.00"), + max_rate=Decimal("5550.00"), + modal_rate=Decimal("5400.00"), + source="APMC_BULLETIN", + is_market_closed=False, + observation_id="mkt-demo-obs-04" + ), + ] + for obs in observations: + store.insert("market_observations", tenant_id, obs.to_dict()) + + # 7. Procurement Saudas + saudas = [ + ProcurementSauda( + tenant_id=tenant_id, + sauda_number="SDA-2026-001", + contract_date=today, + delivery_due_date=today + timedelta(days=7), + supplier_id="cpty-demo-supplier-01", + mandi_id="MP-IND-01", + commodity_id="SOY", + variety="Yellow FAQ", + booked_quantity_mt=Decimal("25.000"), + trade_rate_per_qtl=Decimal("4850.00"), + grade="FAQ", + trade_type="MANDI_AUCTION", + estimated_bags=500, + credit_period_days=7, + advance_amount=Decimal("0.00"), + mandi_cess_pct=Decimal("1.50"), + krishi_kalyan_pct=Decimal("0.50"), + brokerage_rate_pct=Decimal("1.00"), + sauda_id="sda-demo-001" + ), + ProcurementSauda( + tenant_id=tenant_id, + sauda_number="SDA-26-00142", + contract_date=today - timedelta(days=1), + delivery_due_date=today + timedelta(days=6), + supplier_id="cpty-demo-supplier-02", + mandi_id="RJ-KOT-01", + commodity_id="SOY", + variety="Yellow Desi", + booked_quantity_mt=Decimal("50.000"), + trade_rate_per_qtl=Decimal("4750.00"), + grade="FAQ", + trade_type="DIRECT_PURCHASE", + estimated_bags=1000, + credit_period_days=15, + advance_amount=Decimal("0.00"), + mandi_cess_pct=Decimal("1.50"), + krishi_kalyan_pct=Decimal("0.50"), + brokerage_rate_pct=Decimal("1.00"), + sauda_id="sda-demo-002" + ), + ProcurementSauda( + tenant_id=tenant_id, + sauda_number="SDA-26-00143", + contract_date=today - timedelta(days=2), + delivery_due_date=today + timedelta(days=4), + supplier_id="cpty-demo-supplier-03", + mandi_id="GJ-UNJ-01", + commodity_id="CHN", + variety="Desi Bold", + booked_quantity_mt=Decimal("20.000"), + trade_rate_per_qtl=Decimal("6000.00"), + grade="FAQ", + trade_type="MANDI_AUCTION", + estimated_bags=400, + credit_period_days=7, + advance_amount=Decimal("0.00"), + mandi_cess_pct=Decimal("1.50"), + krishi_kalyan_pct=Decimal("0.50"), + brokerage_rate_pct=Decimal("1.00"), + sauda_id="sda-demo-003" + ), + ProcurementSauda( + tenant_id=tenant_id, + sauda_number="SDA-26-00144", + contract_date=today - timedelta(days=4), + delivery_due_date=today + timedelta(days=2), + supplier_id="cpty-demo-supplier-01", + mandi_id="MP-IND-01", + commodity_id="WHT", + variety="Lokwan", + booked_quantity_mt=Decimal("100.000"), + trade_rate_per_qtl=Decimal("2420.00"), + grade="FAQ", + trade_type="MANDI_AUCTION", + estimated_bags=2000, + credit_period_days=10, + advance_amount=Decimal("0.00"), + mandi_cess_pct=Decimal("1.50"), + krishi_kalyan_pct=Decimal("0.50"), + brokerage_rate_pct=Decimal("1.00"), + sauda_id="sda-demo-004" + ), + ] + # Update receipt progression + saudas[1].record_receipt(Decimal("30.000")) # 60% fulfilled + saudas[3].record_receipt(Decimal("100.000")) # 100% fulfilled + saudas[3].status = "CLOSED" + + for s in saudas: + store.insert("procurement_sauda", tenant_id, s.to_dict()) + + # 8. Connected Storyboard Transactions (GP -> WB -> GRN -> QC -> SO -> Bilty) + sauda_main = saudas[0] + + gate_entry = InwardGateEntry( + tenant_id=tenant_id, + gate_pass_number="GP-2026-001", + vehicle_number="MP09GH4521", + eway_bill_number="281098765432", + driver_name="Sunil Yadav", + driver_mobile="9826012345", + sauda_id=sauda_main.id, + supplier_invoice_no="INV-RAM-2026-90", + supplier_dispatch_weight_mt=Decimal("25.000"), + supplier_dispatch_bags=500, + entry_id="gate-entry-demo-001" + ) + gate_entry.transition_status("WEIGHED_TARE") + store.insert("inward_gate_entries", tenant_id, gate_entry.to_dict()) + + wb_slip = WeighbridgeSlip( + tenant_id=tenant_id, + slip_number="WB-IND-2026-001", + gate_pass_id=gate_entry.id, + gross_weight_mt=Decimal("35.000"), + slip_id="weigh-slip-demo-001" + ) + wb_slip.record_tare( + tare_weight_mt=Decimal("10.000"), + bag_packaging_type="Jute 50kg", + actual_bag_count=500, + billed_weight_mt=Decimal("25.000") + ) + store.insert("weighbridge_slips", tenant_id, wb_slip.to_dict()) + + grn = GoodsReceiptNote( + tenant_id=tenant_id, + grn_number="GRN-2026-001", + weighment_slip_id=wb_slip.id, + sauda_id=sauda_main.id, + godown_id="godown-demo-indore", + godown_stack_id="Stack A1", + accepted_quantity_mt=Decimal("24.625"), + accepted_bags=500, + grn_id="grn-demo-001" + ) + store.insert("goods_receipt_notes", tenant_id, grn.to_dict()) + + lot = InventoryLot( + tenant_id=tenant_id, + lot_number="LOT-SOY-2026-001", + grn_id=grn.id, + commodity_id="c0a80123-demo-0000-0000-000000000001", + variety="Yellow FAQ", + godown_stack_id="Stack A1", + initial_quantity_mt=Decimal("24.625"), + grade="FAQ", + lot_id="lot-demo-001" + ) + lot.transition_qc_status("RELEASED") + lot.current_quantity_mt = Decimal("0.625") + store.insert("inventory_lots", tenant_id, lot.to_dict()) + + qc_inspection = QualityInspection( + tenant_id=tenant_id, + lot_id=lot.id, + sample_code="SMP-2026-001", + inspector_email="qc@malwa-agri.demo", + lot_quantity_mt=Decimal("25.000"), + trade_rate_per_qtl=Decimal("4850.00"), + moisture_pct=Decimal("11.50"), + foreign_matter_pct=Decimal("2.20"), + decision="RELEASED", + damaged_grain_pct=Decimal("1.80"), + remarks="Approved with FAQ standard moisture deduction", + inspection_id="qc-demo-001" + ) + store.insert("quality_inspections", tenant_id, qc_inspection.to_dict()) + + sales_order = CustomerSalesOrder( + tenant_id=tenant_id, + sales_order_number="SO-2026-089", + customer_id="cpty-demo-customer-01", + destination_city="Pithampur", + customer_segment="Processor", + commodity_id="c0a80123-demo-0000-0000-000000000001", + variety="Yellow FAQ", + contract_qty_mt=Decimal("24.000"), + contract_rate_per_qtl=Decimal("5100.00"), + payment_terms="15 Days", + credit_exposure_ratio=Decimal("107.50"), + credit_override=True, + override_approved_by="smgr@malwa-agri.demo", + grade="FAQ", + order_id="so-demo-001" + ) + sales_order.allocated_qty_mt = Decimal("24.000") + sales_order.status = "FULLY_ALLOCATED" + store.insert("customer_sales_orders", tenant_id, sales_order.to_dict()) + + allocation = SalesOrderAllocation( + tenant_id=tenant_id, + sales_order_id=sales_order.id, + lot_id=lot.id, + warehouse_id="godown-demo-indore", + allocated_qty_mt=Decimal("24.000"), + allocated_bags=480, + lot_qc_status="RELEASED", + available_unreserved_mt=Decimal("24.625"), + allocation_id="alloc-demo-001" + ) + store.insert("sales_order_allocations", tenant_id, allocation.to_dict()) + + dispatch = OutboundDispatch( + tenant_id=tenant_id, + dispatch_number="DSP-2026-089", + sales_order_id=sales_order.id, + allocation_id=allocation.id, + vehicle_id="veh-demo-01", + origin_warehouse_id="godown-demo-indore", + destination_city="Pithampur", + dispatch_id="dispatch-demo-001" + ) + dispatch.transition_status("IN_TRANSIT") + store.insert("outbound_dispatches", tenant_id, dispatch.to_dict()) + + outward_wt = OutwardWeighment( + tenant_id=tenant_id, + dispatch_id=dispatch.id, + tare_weight_kg=Decimal("10200.00"), + gross_weight_kg=Decimal("34200.00"), + allocated_mt=Decimal("24.000"), + loaded_bags=480, + transporter_bilty_no="BLT-2026-089", + eway_bill_no="381044991122", + weighment_id="outward-weigh-demo-001" + ) + store.insert("outward_weighments", tenant_id, outward_wt.to_dict()) + + bilty = DispatchBilty( + tenant_id=tenant_id, + dispatch_id=dispatch.id, + bilty_number="BLT-2026-089", + consignor_name="Malwa Agri Trading Corp Pvt Ltd", + consignee_name="MP Soya Extraction Industries Ltd", + vehicle_reg_no="MP09BC8812", + net_weight_mt=Decimal("24.000"), + bags=480, + eway_bill_no="381044991122", + bilty_id="bilty-demo-001" + ) + store.insert("dispatch_bilties", tenant_id, bilty.to_dict()) + + # 9. Subledgers, Payables, Cess Voucher + customer_invoice = PartySubLedgerEntry( + tenant_id=tenant_id, + party_id="cpty-demo-customer-01", + party_type="CUSTOMER", + voucher_type="SALES_INVOICE", + voucher_number="INV-SALES-2026-089", + debit_amount_inr=Decimal("1224000.00"), + running_balance_inr=Decimal("5374000.00"), + narration="Sales invoice for 24.000 MT Soybean FAQ under Order SO-2026-089 / Bilty BLT-2026-089", + entry_id="subledger-demo-01" + ) + store.insert("party_subledger_entries", tenant_id, customer_invoice.to_dict()) + + supplier_payable = SupplierPayable( + tenant_id=tenant_id, + supplier_id="cpty-demo-supplier-01", + grn_number="GRN-2026-001", + invoice_amount_inr=Decimal("1189141.25"), + grn_date=datetime.now(timezone.utc), + credit_days=7, + sauda_reference="SDA-2026-001", + payable_id="payable-demo-001" + ) + store.insert("supplier_payables", tenant_id, supplier_payable.to_dict()) + + cess_voucher = MandiExpenseVoucher( + tenant_id=tenant_id, + voucher_number="VCH-CESS-2026-001", + expense_category="MANDI_CESS", + amount_inr=Decimal("18187.50"), + payee_name="Indore Mandi Samiti", + payment_mode="BANK_TRANSFER", + debit_account="Mandi Cess Expense", + credit_account="HDFC Bank Current A/C", + linked_sauda_id=sauda_main.id, + narration="1.50% MP Mandi Cess on Sauda SDA-2026-001 gross value ₹12,12,500.00", + voucher_id="voucher-demo-001" + ) + store.insert("mandi_expense_vouchers", tenant_id, cess_voucher.to_dict()) + + # 10. Operational Hazard Alerts + alerts = [ + OperationalAlert( + tenant_id=tenant_id, + category="CREDIT_RISK", + severity="WARNING", + title="Customer Credit Limit Breached: MP Soya", + message="MP Soya Extraction Industries exposure is at 107.5% of approved limit (₹53.74L / ₹50.00L).", + source_entity_type="SALES_ORDER", + source_entity_id=sales_order.id, + alert_id="alert-demo-01" + ), + OperationalAlert( + tenant_id=tenant_id, + category="WAREHOUSE_CAPACITY", + severity="INFO", + title="Indore Godown Capacity at 63%", + message="Central Warehouse Indore is currently holding 3,150 MT out of 5,000 MT capacity.", + source_entity_type="GODOWN", + source_entity_id="godown-demo-indore", + alert_id="alert-demo-02" + ), + ] + for a in alerts: + store.insert("operational_alerts", tenant_id, a.to_dict()) + + # 11. 20-Day Historical Snapshots for Analytics & Dashboard + for day_offset in range(19, -1, -1): + snap_date = today - timedelta(days=day_offset) + # Weekends closed + if snap_date.weekday() >= 5: + continue + + snapshot = DailyTradingSnapshot( + tenant_id=tenant_id, + snapshot_date=str(snap_date), + purchases_mt=Decimal("25.00") if day_offset == 0 else Decimal("0.00"), + sales_mt=Decimal("24.00") if day_offset == 0 else Decimal("0.00"), + closing_stock_mt=Decimal("625.50") + Decimal(str(day_offset * 15)), + total_receivables_inr=Decimal("5374000.00"), + total_payables_inr=Decimal("1189141.25"), + snapshot_id=f"snap-demo-{day_offset}" + ) + store.insert("daily_trading_snapshots", tenant_id, snapshot.to_dict()) + + summary = { + "tenant_id": tenant_id, + "commodities": len(commodities), + "varieties": len(varieties), + "godowns": len(godowns), + "counterparties": len(counterparties), + "fleet": len(fleet), + "policies": 1, + "market_observations": len(observations), + "procurement_sauda": len(saudas), + "gate_entries": 1, + "weighbridge_slips": 1, + "goods_receipt_notes": 1, + "inventory_lots": 1, + "quality_inspections": 1, + "sales_orders": 1, + "dispatches": 1, + "bilties": 1, + "subledger_entries": 1, + "payables": 1, + "cess_vouchers": 1, + "alerts": len(alerts), + } + logger.info("Demo dataset seeded successfully for tenant '%s': %s", tenant_id, summary) + return summary diff --git a/backend/app/db/session.py b/backend/app/db/session.py index a9e0018..fc8e9b4 100644 --- a/backend/app/db/session.py +++ b/backend/app/db/session.py @@ -71,6 +71,12 @@ class InMemoryTenantStorage: except Exception as exc: logger.warning("Could not auto-seed baseline fixtures: %s", exc) + try: + from backend.app.db.demo_seed import seed_demo_dataset + seed_demo_dataset(self, "demo-malwa-agri") + except Exception as exc: + logger.warning("Could not auto-seed demo dataset: %s", exc) + def set_tenant_context(self, tenant_id: Optional[str]) -> None: """Sets transaction-local tenant isolation context (SET LOCAL app.current_tenant_id).""" self.active_tenant_id = tenant_id diff --git a/backend/app/main.py b/backend/app/main.py index 01c2fe9..768f043 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1017,9 +1017,33 @@ try: status_code = result.pop("status_code", 200) return JSONResponse(status_code=status_code, content=result) + # ========================================================================= + # Sales Demo Engine Endpoints (Commercial Seeding & Side-Effect Free Purge) + # ========================================================================= + @app.post("/api/v1/demo/seed", tags=["Sales Demo"]) + async def seed_sales_demo_data(payload: Optional[Dict[str, Any]] = None): + """POST /api/v1/demo/seed - Seeds complete relational dataset for demo-malwa-agri.""" + from backend.app.db.session import storage + from backend.app.db.demo_seed import seed_demo_dataset + tenant_id = (payload or {}).get("tenant_id", "demo-malwa-agri") + try: + summary = seed_demo_dataset(storage, tenant_id=tenant_id) + return JSONResponse(status_code=200, content={"success": True, "message": "Demo data seeded successfully", "summary": summary}) + except Exception as e: + return JSONResponse(status_code=500, content={"success": False, "error": str(e)}) - + @app.post("/api/v1/demo/cleanup", tags=["Sales Demo"]) + async def cleanup_sales_demo_data(payload: Optional[Dict[str, Any]] = None): + """POST /api/v1/demo/cleanup - Purges demo dataset with zero residue.""" + from backend.app.db.session import storage + from backend.app.db.demo_seed import purge_demo_dataset + tenant_id = (payload or {}).get("tenant_id", "demo-malwa-agri") + try: + metrics = purge_demo_dataset(storage, tenant_id=tenant_id) + return JSONResponse(status_code=200, content={"success": True, "message": "Demo data purged successfully with zero residue", "metrics": metrics}) + except Exception as e: + return JSONResponse(status_code=500, content={"success": False, "error": str(e)}) except ImportError: diff --git a/frontend/src/features/market/MarketDeskView.tsx b/frontend/src/features/market/MarketDeskView.tsx index 229ad2f..877adb4 100644 --- a/frontend/src/features/market/MarketDeskView.tsx +++ b/frontend/src/features/market/MarketDeskView.tsx @@ -3,8 +3,9 @@ * * Fulfills FR-MKT-001, FR-MKT-002 & SCREEN-MKT-001.md (Iteration 03 / UC-002). * Styled per DESIGN.md: AgriTrade Mercantile (Tactile Corporate Minimalism). + * Zero Hardcoding: All rates and arrivals flow dynamically from backend API. */ -import React, { useState, useEffect } from 'react'; +import React, { useState, useEffect, useCallback } from 'react'; import { Card } from '../../components/ui/Card'; import { Button } from '../../components/ui/Button'; import { StatusPill } from '../../components/ui/StatusPill'; @@ -17,7 +18,8 @@ import { ArrowUpRight, CheckCircle2, AlertTriangle, - Scale + Scale, + RefreshCw } from 'lucide-react'; export interface MarketCommodityRate { @@ -34,69 +36,34 @@ export interface MarketCommodityRate { status: 'PUBLISHED' | 'HOLIDAY' | 'DRAFT'; } -const DEFAULT_RATES: MarketCommodityRate[] = [ - { - id: 'mkt-001', - commodity_code: 'SOY', - commodity_name: 'Soyabean', - variety: 'Yellow Desi', - grade: 'FAQ', - arrivals_mt: 620.0, - arrivals_bags: 12400, - min_rate: 4550.0, - max_rate: 4900.0, - modal_rate: 4800.0, - status: 'PUBLISHED' - }, - { - id: 'mkt-002', - commodity_code: 'CHN', - commodity_name: 'Chana', - variety: 'Desi Bold', - grade: 'FAQ', - arrivals_mt: 280.0, - arrivals_bags: 5600, - min_rate: 5800.0, - max_rate: 6150.0, - modal_rate: 6000.0, - status: 'PUBLISHED' - }, - { - id: 'mkt-003', - commodity_code: 'WHT', - commodity_name: 'Wheat', - variety: 'Lokwan', - grade: 'FAQ', - arrivals_mt: 450.0, - arrivals_bags: 9000, - min_rate: 2350.0, - max_rate: 2550.0, - modal_rate: 2450.0, - status: 'PUBLISHED' - }, - { - id: 'mkt-004', - commodity_code: 'MST', - commodity_name: 'Mustard', - variety: '42% Oil', - grade: 'FAQ', - arrivals_mt: 190.0, - arrivals_bags: 3800, - min_rate: 5200.0, - max_rate: 5550.0, - modal_rate: 5400.0, - status: 'PUBLISHED' - } +const MANDI_OPTIONS = [ + { id: 'MP-IND-01', name: 'Indore APMC, Madhya Pradesh (Main Auction Yard)' }, + { id: 'RJ-KOT-01', name: 'Kota APMC, Rajasthan (Grain Mandi)' }, + { id: 'GJ-UNJ-01', name: 'Unjha APMC, Gujarat (Spices & Oilseed)' }, ]; +const COMMODITY_NAMES: Record = { + SOY: 'Soyabean', + CHN: 'Chana', + WHT: 'Wheat', + MST: 'Mustard', + 'c0a80123-demo-0000-0000-000000000001': 'Soyabean', + 'c0a80123-demo-0000-0000-000000000002': 'Chana', + 'c0a80123-demo-0000-0000-000000000003': 'Wheat', + 'c0a80123-demo-0000-0000-000000000004': 'Mustard', +}; + interface MarketDeskViewProps { onNavigateToSauda?: () => void; } export const MarketDeskView: React.FC = ({ onNavigateToSauda }) => { - const [selectedMandi, setSelectedMandi] = useState('Indore APMC, Madhya Pradesh'); - const [observationDate, setObservationDate] = useState('2026-10-15'); - const [rates, setRates] = useState(DEFAULT_RATES); + const [selectedMandi, setSelectedMandi] = useState('MP-IND-01'); + const [observationDate, setObservationDate] = useState(() => { + return new Date().toISOString().split('T')[0]; + }); + const [rates, setRates] = useState([]); + const [isLoading, setIsLoading] = useState(true); const [isModalOpen, setIsModalOpen] = useState(false); const [notification, setNotification] = useState<{ type: 'success' | 'error'; message: string } | null>(null); @@ -123,6 +90,53 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud } }, [formMinRate, formMaxRate, formModalRate]); + // Fetch rates dynamically from backend API + const fetchRates = useCallback(async () => { + setIsLoading(true); + try { + let url = `/api/v1/market/observations?mandi_id=${encodeURIComponent(selectedMandi)}`; + if (observationDate) { + url += `&date=${encodeURIComponent(observationDate)}`; + } + const resp = await apiClient(url); + if (resp.status === 200 && resp.data?.observations) { + let obsList = resp.data.observations; + // Fallback: If no observations for exact date, query mandi-wide to display latest bulletin + if (obsList.length === 0 && observationDate) { + const fallbackResp = await apiClient(`/api/v1/market/observations?mandi_id=${encodeURIComponent(selectedMandi)}`); + if (fallbackResp.status === 200 && fallbackResp.data?.observations?.length > 0) { + obsList = fallbackResp.data.observations; + } + } + const mapped: MarketCommodityRate[] = obsList.map((o: any) => ({ + id: o.id || `mkt-${Math.random()}`, + commodity_code: o.commodity_id || 'COMM', + commodity_name: COMMODITY_NAMES[o.commodity_id] || o.commodity_id || 'Commodity', + variety: o.variety || 'FAQ', + grade: o.grade || 'FAQ', + arrivals_mt: Number(o.arrival_mt) || 0, + arrivals_bags: Math.round((Number(o.arrival_mt) || 0) * 20), + min_rate: Number(o.min_rate) || 0, + max_rate: Number(o.max_rate) || 0, + modal_rate: Number(o.modal_rate) || 0, + status: o.is_market_closed ? 'HOLIDAY' : 'PUBLISHED', + })); + setRates(mapped); + } else { + setRates([]); + } + } catch (err: any) { + console.error('Failed to load market observations:', err); + setRates([]); + } finally { + setIsLoading(false); + } + }, [selectedMandi, observationDate]); + + useEffect(() => { + fetchRates(); + }, [fetchRates]); + const handleSaveObservation = async (e: React.FormEvent) => { e.preventDefault(); if (validationError) return; @@ -132,15 +146,15 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud try { const payload = { - mandi_id: 'mandi-indore-01', - commodity_id: formCommodity === 'Soyabean' ? 'SOY' : formCommodity === 'Chana' ? 'CHN' : 'WHT', + mandi_id: selectedMandi, + commodity_id: formCommodity === 'Soyabean' ? 'SOY' : formCommodity === 'Chana' ? 'CHN' : formCommodity === 'Mustard' ? 'MST' : 'WHT', variety: formVariety, grade: 'FAQ', observation_date: observationDate, - arrival_mt: formArrivalsMt, - min_rate: formMinRate, - max_rate: formMaxRate, - modal_rate: formModalRate, + arrival_mt: Number(formArrivalsMt), + min_rate: Number(formMinRate), + max_rate: Number(formMaxRate), + modal_rate: Number(formModalRate), source: 'APMC_BULLETIN' }; @@ -153,34 +167,10 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud if (resp.status === 201 || resp.status === 200 || !resp.error) { setNotification({ type: 'success', - message: `Daily rate observation recorded for ${formCommodity} (${formVariety}) at ₹ ${formModalRate.toLocaleString('en-IN')}/Qtl.` + message: `Daily rate observation recorded for ${formCommodity} (${formVariety}) at ₹ ${Number(formModalRate).toLocaleString('en-IN')}/Qtl.` }); - - // Update local table view - const existingIdx = rates.findIndex(r => r.commodity_name === formCommodity); - const updatedRate: MarketCommodityRate = { - id: `mkt-obs-${Date.now()}`, - commodity_code: payload.commodity_id, - commodity_name: formCommodity, - variety: formVariety, - grade: 'FAQ', - arrivals_mt: formArrivalsMt, - arrivals_bags: Math.round(formArrivalsMt * 20), - min_rate: formMinRate, - max_rate: formMaxRate, - modal_rate: formModalRate, - status: 'PUBLISHED' - }; - - if (existingIdx >= 0) { - const next = [...rates]; - next[existingIdx] = updatedRate; - setRates(next); - } else { - setRates([updatedRate, ...rates]); - } - setIsModalOpen(false); + await fetchRates(); } else { setNotification({ type: 'error', @@ -198,7 +188,8 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud }; const totalArrivalsMt = rates.reduce((acc, r) => acc + r.arrivals_mt, 0); - const soyRate = rates.find(r => r.commodity_name === 'Soyabean') || rates[0]; + const soyRate = rates.find(r => r.commodity_name.toLowerCase().includes('soy') || r.commodity_code === 'SOY'); + const selectedMandiObj = MANDI_OPTIONS.find(m => m.id === selectedMandi) || MANDI_OPTIONS[0]; return (
@@ -239,9 +230,9 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud onChange={(e) => setSelectedMandi(e.target.value)} className="py-1 px-2.5 rounded bg-white border border-card-border text-xs font-medium text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre" > - - - + {MANDI_OPTIONS.map((m) => ( + + ))}
@@ -255,6 +246,17 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud className="py-1 px-2 rounded bg-white border border-card-border text-xs font-mono text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre" />
+ +
@@ -290,13 +292,13 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud
- ₹ {soyRate.modal_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + {soyRate ? `₹ ${soyRate.modal_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })}` : '₹ —'} / Qtl
- Active Mandi Clearing Rate + {soyRate ? 'Active Mandi Clearing Rate' : 'No Active Bulletin'}
@@ -306,9 +308,11 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud
- {soyRate.arrivals_bags.toLocaleString('en-IN')} + {soyRate ? soyRate.arrivals_bags.toLocaleString('en-IN') : '—'} + + + Bags ({soyRate ? soyRate.arrivals_mt.toFixed(1) : '0.0'} MT) - Bags ({soyRate.arrivals_mt.toFixed(1)} MT)
50 kg standard jute bags @@ -326,7 +330,7 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud Metric Tonnes
- Across 4 Monitored Commodities + Across {rates.length} Monitored Commodities
@@ -335,10 +339,10 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud Mandi Samiti Status
- + 0 ? 'normal' : 'watch'} label={rates.length > 0 ? `${rates.length} Active Bulletins` : 'No Rates Seeded'} />
- Indore Yard Floor A Active + {selectedMandiObj.name.split(',')[0]} Yard Active
@@ -346,7 +350,7 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud {/* Commodity Rate Blotter Table (SCREEN-MKT-001) */} FR-MKT-001 • FR-MKT-002 @@ -354,70 +358,90 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud } >
- - - - - - - - - - - - - - - - {rates.map((rate) => ( - - - - - - - - - - + {isLoading ? ( +
+ + Loading real-time market arrivals from backend... +
+ ) : rates.length === 0 ? ( +
+ +
No Market Observations Recorded
+

+ No arrival or price records found for this mandi yard. Use "+ Record Observation" to enter live auction rates or run the sales demo seeder. +

+
+ +
+
+ ) : ( +
CommodityVariety / GradeArrivals (MT)Estimated BagsMin Rate (₹/Qtl)Max Rate (₹/Qtl)Modal Rate (₹/Qtl)StatusAction
-
- - {rate.commodity_name} - - {rate.commodity_code} - -
-
- {rate.variety} • {rate.grade} - - {rate.arrivals_mt.toFixed(3)} MT - - {rate.arrivals_bags.toLocaleString('en-IN')} - - ₹ {rate.min_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })} - - ₹ {rate.max_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })} - - ₹ {rate.modal_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })} - - - - {onNavigateToSauda ? ( - - ) : ( - Locked - )} -
+ + + + + + + + + + + - ))} - -
CommodityVariety / GradeArrivals (MT)Estimated BagsMin Rate (₹/Qtl)Max Rate (₹/Qtl)Modal Rate (₹/Qtl)StatusAction
+ + + {rates.map((rate) => ( + + +
+ + {rate.commodity_name} + + {rate.commodity_code} + +
+ + + {rate.variety} • {rate.grade} + + + {rate.arrivals_mt.toFixed(3)} MT + + + {rate.arrivals_bags.toLocaleString('en-IN')} + + + ₹ {rate.min_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + + + ₹ {rate.max_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + + + ₹ {rate.modal_rate.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + + + + + + {onNavigateToSauda ? ( + + ) : ( + Locked + )} + + + ))} + + + )}
@@ -456,7 +480,7 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud @@ -492,6 +516,11 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud setFormMinRate(5800); setFormMaxRate(6150); setFormModalRate(6000); + } else if (e.target.value === 'Mustard') { + setFormVariety('42% Oil'); + setFormMinRate(5200); + setFormMaxRate(5550); + setFormModalRate(5400); } else { setFormVariety('Lokwan'); setFormMinRate(2350); @@ -616,4 +645,3 @@ export const MarketDeskView: React.FC = ({ onNavigateToSaud ); }; - diff --git a/frontend/src/features/procurement/SaudaProcurementView.tsx b/frontend/src/features/procurement/SaudaProcurementView.tsx index 1a6a937..9bfcc09 100644 --- a/frontend/src/features/procurement/SaudaProcurementView.tsx +++ b/frontend/src/features/procurement/SaudaProcurementView.tsx @@ -3,8 +3,9 @@ * * Fulfills FR-PROCUREMENTCONTRACTS-001..004 & SCREEN-PROC-001.md (Iteration 03 / UC-004). * Styled per DESIGN.md: AgriTrade Mercantile (Tactile Corporate Minimalism). + * Zero Hardcoding: All sauda contracts and commercial positions flow dynamically from backend API. */ -import React, { useState } from 'react'; +import React, { useState, useEffect, useCallback } from 'react'; import { Card } from '../../components/ui/Card'; import { Button } from '../../components/ui/Button'; import { StatusPill } from '../../components/ui/StatusPill'; @@ -16,7 +17,8 @@ import { CheckCircle2, Calculator, Search, - Filter + Filter, + RefreshCw } from 'lucide-react'; export interface SaudaContract { @@ -42,108 +44,18 @@ export interface SaudaContract { status: 'ACTIVE' | 'PENDING' | 'CLOSED' | 'REJECTED'; } -const DEFAULT_SAUDAS: SaudaContract[] = [ - { - id: 'sda-rec-01', - sauda_number: 'SDA-2026-001', - contract_date: '2026-10-15', - delivery_due_date: '2026-10-22', - supplier_name: 'Rameshwar Patidar (Farmer / Arhatiya - Neemuch)', - mandi_hub: 'Indore APMC', - commodity_name: 'Soyabean', - variety: 'Yellow Desi', - grade: 'FAQ', - booked_quantity_mt: 25.0, - estimated_bags: 500, - trade_rate_per_qtl: 4850.0, - gross_value: 1212500.0, - mandi_cess: 18187.5, - krishi_kalyan: 6062.5, - brokerage: 12125.0, - landed_value: 1248875.0, - credit_days: 7, - fulfilled_pct: 0.0, - status: 'ACTIVE' - }, - { - id: 'sda-rec-02', - sauda_number: 'SDA-26-00142', - contract_date: '2026-10-14', - delivery_due_date: '2026-10-20', - supplier_name: 'Kisan Agro Traders (SUP-0042)', - mandi_hub: 'Kota APMC', - commodity_name: 'Soyabean', - variety: 'Yellow Desi', - grade: 'FAQ', - booked_quantity_mt: 50.0, - estimated_bags: 1000, - trade_rate_per_qtl: 4750.0, - gross_value: 2375000.0, - mandi_cess: 35625.0, - krishi_kalyan: 11875.0, - brokerage: 23750.0, - landed_value: 2446250.0, - credit_days: 15, - fulfilled_pct: 60.0, - status: 'ACTIVE' - }, - { - id: 'sda-rec-03', - sauda_number: 'SDA-26-00143', - contract_date: '2026-10-13', - delivery_due_date: '2026-10-18', - supplier_name: 'Mewar Krishi Sangh', - mandi_hub: 'Unjha APMC', - commodity_name: 'Cumin/Jeera', - variety: 'Special Bold', - grade: 'FAQ', - booked_quantity_mt: 20.0, - estimated_bags: 400, - trade_rate_per_qtl: 24500.0, - gross_value: 4900000.0, - mandi_cess: 73500.0, - krishi_kalyan: 24500.0, - brokerage: 49000.0, - landed_value: 5047000.0, - credit_days: 5, - fulfilled_pct: 0.0, - status: 'PENDING' - }, - { - id: 'sda-rec-04', - sauda_number: 'SDA-26-00144', - contract_date: '2026-10-11', - delivery_due_date: '2026-10-16', - supplier_name: 'Malwa Agro Corp', - mandi_hub: 'Indore APMC', - commodity_name: 'Wheat', - variety: 'Lokwan', - grade: 'FAQ', - booked_quantity_mt: 100.0, - estimated_bags: 2000, - trade_rate_per_qtl: 2420.0, - gross_value: 2420000.0, - mandi_cess: 36300.0, - krishi_kalyan: 12100.0, - brokerage: 24200.0, - landed_value: 2492600.0, - credit_days: 10, - fulfilled_pct: 100.0, - status: 'CLOSED' - } -]; - const BENCHMARK_MODAL_RATE = 4800.0; // Indore APMC Soybean modal clearing rate benchmark export const SaudaProcurementView: React.FC = () => { - const [saudas, setSaudas] = useState(DEFAULT_SAUDAS); + const [saudas, setSaudas] = useState([]); + const [isLoading, setIsLoading] = useState(true); const [searchQuery, setSearchQuery] = useState(''); const [statusFilter, setStatusFilter] = useState('ALL'); const [isModalOpen, setIsModalOpen] = useState(false); const [notification, setNotification] = useState<{ type: 'success' | 'error'; message: string } | null>(null); // Form State matching Playbook Journey 1 - const [contractDate, setContractDate] = useState('2026-10-15'); + const [contractDate, setContractDate] = useState(() => new Date().toISOString().split('T')[0]); const [sourcingMandi, setSourcingMandi] = useState('Indore APMC, Madhya Pradesh'); const [tradeType, setTradeType] = useState('MANDI_AUCTION'); const [supplierName, setSupplierName] = useState('Rameshwar Patidar (Farmer / Arhatiya - Neemuch)'); @@ -175,13 +87,99 @@ export const SaudaProcurementView: React.FC = () => { const isVarianceExceeded = rateVariancePct > 5.0; // Commercial Math per NFR-001 (Dual UOM, Statutory Rounding) - // Base Value = MT * 10 Qtl/MT * Rate/Qtl const grossTradeValue = bookedMt * 10 * tradeRate; const mandiCess = grossTradeValue * 0.015; // 1.50% const krishiKalyan = grossTradeValue * 0.005; // 0.50% const brokerage = grossTradeValue * 0.01; // 1.00% const totalLandedValue = grossTradeValue + mandiCess + krishiKalyan + brokerage; + // Fetch Saudas dynamically from backend API + const fetchSaudas = useCallback(async () => { + setIsLoading(true); + try { + let url = '/api/v1/procurement/sauda'; + if (statusFilter !== 'ALL') { + url += `?status_filter=${encodeURIComponent(statusFilter)}`; + } + const resp = await apiClient(url); + if (resp.status === 200 && resp.data?.saudas) { + const rawList = resp.data.saudas; + const mapped: SaudaContract[] = rawList.map((s: any) => { + const bookedQty = Number(s.booked_quantity_mt) || 0; + const cumReceived = Number(s.cumulative_received_mt) || 0; + const rateQtl = Number(s.trade_rate_per_qtl) || 0; + const gross = Number(s.gross_amount) || (bookedQty * 10 * rateQtl); + const landed = Number(s.total_landed_amount) || gross; + const fulfilledPct = bookedQty > 0 ? Math.round((cumReceived / bookedQty) * 100) : 0; + + let uiStatus: 'ACTIVE' | 'PENDING' | 'CLOSED' | 'REJECTED' = 'ACTIVE'; + if (s.status === 'CLOSED' || s.status === 'FULFILLED') { + uiStatus = 'CLOSED'; + } else if (s.status === 'PENDING') { + uiStatus = 'PENDING'; + } else if (s.status === 'REJECTED' || s.status === 'CANCELLED') { + uiStatus = 'REJECTED'; + } + + let supplierDisp = s.supplier_name; + if (!supplierDisp) { + if (s.supplier_id === 'cpty-demo-supplier-01') supplierDisp = 'Rameshwar Patidar (Farmer / Arhatiya)'; + else if (s.supplier_id === 'cpty-demo-supplier-02') supplierDisp = 'Kisan Agro Traders (SUP-0042)'; + else if (s.supplier_id === 'cpty-demo-supplier-03') supplierDisp = 'Mewar Krishi Sangh'; + else if (s.supplier_id === 'cpty-demo-supplier-04') supplierDisp = 'Malwa Agro Corp'; + else supplierDisp = s.supplier_id || 'Counterparty'; + } + + let mandiDisp = s.mandi_id; + if (mandiDisp === 'MP-IND-01') mandiDisp = 'Indore APMC'; + else if (mandiDisp === 'RJ-KOT-01') mandiDisp = 'Kota APMC'; + else if (mandiDisp === 'GJ-UNJ-01') mandiDisp = 'Unjha APMC'; + + let commDisp = s.commodity_id; + if (commDisp === 'SOY' || commDisp === 'c0a80123-demo-0000-0000-000000000001') commDisp = 'Soyabean'; + else if (commDisp === 'CHN' || commDisp === 'c0a80123-demo-0000-0000-000000000002') commDisp = 'Chana'; + else if (commDisp === 'WHT' || commDisp === 'c0a80123-demo-0000-0000-000000000003') commDisp = 'Wheat'; + else if (commDisp === 'MST' || commDisp === 'c0a80123-demo-0000-0000-000000000004') commDisp = 'Mustard'; + + return { + id: s.id || `sda-${Math.random()}`, + sauda_number: s.sauda_number || 'SDA-NEW', + contract_date: s.contract_date || '', + delivery_due_date: s.delivery_due_date || s.contract_date || '', + supplier_name: supplierDisp, + mandi_hub: mandiDisp || 'Indore APMC', + commodity_name: commDisp || 'Commodity', + variety: s.variety || 'FAQ', + grade: s.grade || 'FAQ', + booked_quantity_mt: bookedQty, + estimated_bags: Number(s.estimated_bags) || Math.round(bookedQty * 20), + trade_rate_per_qtl: rateQtl, + gross_value: gross, + landed_value: landed, + mandi_cess: Number(s.mandi_cess_amount) || (gross * 0.015), + krishi_kalyan: Number(s.krishi_kalyan_amount) || (gross * 0.005), + brokerage: Number(s.brokerage_amount) || (gross * 0.01), + credit_days: Number(s.credit_period_days) || 0, + fulfilled_pct: fulfilledPct, + status: uiStatus + }; + }); + setSaudas(mapped); + } else { + setSaudas([]); + } + } catch (err) { + console.error('Failed to load sauda contracts:', err); + setSaudas([]); + } finally { + setIsLoading(false); + } + }, [statusFilter]); + + useEffect(() => { + fetchSaudas(); + }, [fetchSaudas]); + const handleBookSauda = async (e: React.FormEvent) => { e.preventDefault(); if (isVarianceExceeded && !varianceConfirmed) { @@ -198,10 +196,13 @@ export const SaudaProcurementView: React.FC = () => { sauda_number: generatedSaudaNumber, contract_date: contractDate, delivery_due_date: paymentDueDate, - supplier_id: 'sup-patidar-01', - mandi_id: 'mandi-indore-01', + supplier_id: supplierName.includes('Rameshwar') ? 'cpty-demo-supplier-01' : + supplierName.includes('Kisan') ? 'cpty-demo-supplier-02' : + supplierName.includes('Mewar') ? 'cpty-demo-supplier-03' : 'cpty-demo-supplier-01', + mandi_id: sourcingMandi.includes('Indore') ? 'MP-IND-01' : + sourcingMandi.includes('Kota') ? 'RJ-KOT-01' : 'GJ-UNJ-01', trade_type: tradeType, - commodity_id: 'SOY', + commodity_id: commodity.includes('SOY') ? 'SOY' : commodity.includes('CHN') ? 'CHN' : commodity.includes('MST') ? 'MST' : 'WHT', variety: variety, grade: 'FAQ', booked_quantity_mt: bookedMt, @@ -222,45 +223,25 @@ export const SaudaProcurementView: React.FC = () => { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); - if (resp.error) { - // Log non-blocking backend response while preserving offline mock UI state - console.warn('Backend sauda booking response:', resp.error); + + if (resp.status === 201 || resp.status === 200 || !resp.error) { + setNotification({ + type: 'success', + message: `Sauda Contract ${generatedSaudaNumber} locked successfully! Landed value ₹ ${totalLandedValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })} booked for ${supplierName}.` + }); + setIsModalOpen(false); + // Reset form + setBookedMt(25.0); + setTradeRate(4850.0); + setVarianceConfirmed(false); + // Refresh live data from backend! + await fetchSaudas(); + } else { + setNotification({ + type: 'error', + message: resp.error || 'Failed to book sauda on backend.' + }); } - - const newContract: SaudaContract = { - id: `sda-${Date.now()}`, - sauda_number: generatedSaudaNumber, - contract_date: contractDate, - delivery_due_date: paymentDueDate, - supplier_name: supplierName, - mandi_hub: sourcingMandi.split(',')[0], - commodity_name: commodity.split(' ')[0], - variety: variety, - grade: 'FAQ', - booked_quantity_mt: bookedMt, - estimated_bags: estimatedBags, - trade_rate_per_qtl: tradeRate, - gross_value: grossTradeValue, - landed_value: totalLandedValue, - mandi_cess: mandiCess, - krishi_kalyan: krishiKalyan, - brokerage: brokerage, - credit_days: creditDays, - fulfilled_pct: 0.0, - status: 'ACTIVE' - }; - - setSaudas([newContract, ...saudas]); - setNotification({ - type: 'success', - message: `Sauda Contract ${generatedSaudaNumber} locked successfully! Landed value ₹ ${totalLandedValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })} booked for ${supplierName}.` - }); - - setIsModalOpen(false); - // Reset form - setBookedMt(25.0); - setTradeRate(4850.0); - setVarianceConfirmed(false); } catch (err: any) { setNotification({ type: 'error', @@ -327,7 +308,7 @@ export const SaudaProcurementView: React.FC = () => { Contracts
- Indore & Kota Mandis + {activeCount > 0 ? 'Indore & Kota Mandis' : 'No Active Contracts'}
@@ -363,50 +344,61 @@ export const SaudaProcurementView: React.FC = () => {
- Indore Benchmark Modal + Statutory Mandi Cess Levies
- - ₹ {BENCHMARK_MODAL_RATE.toLocaleString('en-IN', { minimumFractionDigits: 2 })} + + ₹ {(saudas.reduce((acc, s) => acc + s.mandi_cess, 0) / 100000).toFixed(2)} - / Qtl + Lakhs
-
- Real-time Market Desk Peg +
+ 1.50% MP APMC Mandi Samiti Cess
- {/* Main Register Filter & Action Bar */} + {/* Control Bar: Filters & Action Button */}
-
+
setSearchQuery(e.target.value)} - className="w-full pl-9 pr-3 py-1.5 rounded bg-white border border-card-border text-xs text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre" + className="w-full pl-9 pr-3 py-1.5 rounded bg-white border border-card-border text-xs font-sans text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-ochre placeholder:text-text-muted" />
-
- +
+
+ +
-
+
{/* Role-Gated Navigation Items */} -