From b99fdb7a176c495a549f6623dfaad737bbad5895 Mon Sep 17 00:00:00 2001 From: Prashant Shendre Date: Mon, 12 Oct 2026 13:43:23 +0530 Subject: [PATCH] iter-03 Mkt Desk, Sauda rocurement, GateInward n Weighbridge, Lab QC & Lot Control done --- ...22-iteration-03-mandi-pipeline-delivery.md | 89 ++++ .../checkpoints/checkpoint_index.md | 1 + .../00_process_control/master_context.md | 10 +- .../00_process_control/traceability_graph.md | 40 +- .../iteration-03/iteration_backlog.md | 271 +++++++++++ .../iterations/iteration-03/iteration_plan.md | 67 +++ .../iteration-03/iteration_surface_matrix.md | 59 +++ .../iteration-03/parallel_work_plan.md | 111 +++++ .../screen_specs/SCREEN-INW-001_gate_entry.md | 120 +++++ .../SCREEN-INW-002_weighbridge_grn.md | 139 ++++++ .../SCREEN-MKT-001_market_desk.md | 123 +++++ .../SCREEN-PROC-001_sauda_booking.md | 134 ++++++ .../screen_specs/SCREEN-QC-001_quality_lab.md | 132 ++++++ .../06_wireframes/wireframe_index.md | 5 + .../TC-002_mandi_market_desk.md | 88 ++++ .../TC-004_sauda_procurement.md | 103 ++++ .../TC-005_inward_receiving.md | 112 +++++ .../TC-006_quality_lot_control.md | 95 ++++ .../iteration-03/MANUAL_TESTING_GUIDE.md | 212 +++++++++ ...Governance_Complete_Manual_Testcases.xlsx# | 1 + ...eceiving_QC_Complete_Manual_Testcases.xlsx | Bin 0 -> 33248 bytes .../07_test_design/regression_test_cases.md | 13 +- .../test_traceability_matrix.md | 18 + .../alembic/versions/005_market_desk.py | 67 +++ .../versions/006_procurement_contracts.py | 79 ++++ .../alembic/versions/007_inward_receiving.py | 108 +++++ .../alembic/versions/008_quality_and_lots.py | 89 ++++ .../backend/app/api/market.py | 247 ++++++++++ .../backend/app/api/procurement.py | 239 ++++++++++ .../backend/app/api/quality.py | 292 ++++++++++++ .../backend/app/api/receiving.py | 440 ++++++++++++++++++ .../backend/app/auth/tenant_context.py | 38 +- .../backend/app/db/session.py | 30 ++ .../backend/app/main.py | 179 +++++++ .../backend/app/models/market.py | 136 ++++++ .../backend/app/models/procurement.py | 242 ++++++++++ .../backend/app/models/quality.py | 281 +++++++++++ .../backend/app/models/receiving.py | 287 ++++++++++++ 05_implementation_workspace/docs/api/bruno | 1 + .../sandbox/master_data_mock.py | 185 ++++++++ .../sandbox/weighbridge_mock.py | 67 +++ .../tests/backend/test_inward_receiving.py | 351 ++++++++++++++ .../tests/backend/test_market_desk.py | 257 ++++++++++ .../backend/test_procurement_contracts.py | 262 +++++++++++ .../tests/backend/test_quality_lot_control.py | 286 ++++++++++++ .../tests/e2e/test_live_api_endpoints.py | 16 +- .../tests/e2e/test_live_mandi_pipeline_e2e.py | 261 +++++++++++ .../tests/run_all_tests.py | 15 +- .../bruno/market/get-market-observations.bru | 27 ++ .../bruno/market/post-market-observation.bru | 45 ++ docs/api/bruno/procurement/create-sauda.bru | 51 ++ docs/api/bruno/procurement/list-sauda.bru | 27 ++ docs/api/bruno/quality/get-lot-lineage.bru | 27 ++ docs/api/bruno/quality/post-inspection.bru | 40 ++ docs/api/bruno/quality/post-lot-decision.bru | 35 ++ .../api/bruno/receiving/create-gate-entry.bru | 42 ++ docs/api/bruno/receiving/create-weighment.bru | 39 ++ docs/api/bruno/receiving/post-grn.bru | 36 ++ ...20261012T041907Z-session-process-status.md | 33 ++ 59 files changed, 6751 insertions(+), 49 deletions(-) create mode 100644 04_generated_documentation/00_process_control/checkpoints/checkpoint-022-iteration-03-mandi-pipeline-delivery.md create mode 100644 04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_backlog.md create mode 100644 04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_plan.md create mode 100644 04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_surface_matrix.md create mode 100644 04_generated_documentation/05_iteration_planning/iterations/iteration-03/parallel_work_plan.md create mode 100644 04_generated_documentation/06_wireframes/screen_specs/SCREEN-INW-001_gate_entry.md create mode 100644 04_generated_documentation/06_wireframes/screen_specs/SCREEN-INW-002_weighbridge_grn.md create mode 100644 04_generated_documentation/06_wireframes/screen_specs/SCREEN-MKT-001_market_desk.md create mode 100644 04_generated_documentation/06_wireframes/screen_specs/SCREEN-PROC-001_sauda_booking.md create mode 100644 04_generated_documentation/06_wireframes/screen_specs/SCREEN-QC-001_quality_lab.md create mode 100644 04_generated_documentation/07_test_design/functional_test_cases/TC-002_mandi_market_desk.md create mode 100644 04_generated_documentation/07_test_design/functional_test_cases/TC-004_sauda_procurement.md create mode 100644 04_generated_documentation/07_test_design/functional_test_cases/TC-005_inward_receiving.md create mode 100644 04_generated_documentation/07_test_design/functional_test_cases/TC-006_quality_lot_control.md create mode 100644 04_generated_documentation/07_test_design/manual_qa/iteration-03/MANUAL_TESTING_GUIDE.md create mode 100644 04_generated_documentation/07_test_design/manual_qa/workbooks/.~lock.Iteration01_Authentication_and_Session_Governance_Complete_Manual_Testcases.xlsx# create mode 100644 04_generated_documentation/07_test_design/manual_qa/workbooks/Iteration03_Mandi_Procurement_Receiving_QC_Complete_Manual_Testcases.xlsx create mode 100644 05_implementation_workspace/backend/alembic/versions/005_market_desk.py create mode 100644 05_implementation_workspace/backend/alembic/versions/006_procurement_contracts.py create mode 100644 05_implementation_workspace/backend/alembic/versions/007_inward_receiving.py create mode 100644 05_implementation_workspace/backend/alembic/versions/008_quality_and_lots.py create mode 100644 05_implementation_workspace/backend/app/api/market.py create mode 100644 05_implementation_workspace/backend/app/api/procurement.py create mode 100644 05_implementation_workspace/backend/app/api/quality.py create mode 100644 05_implementation_workspace/backend/app/api/receiving.py create mode 100644 05_implementation_workspace/backend/app/models/market.py create mode 100644 05_implementation_workspace/backend/app/models/procurement.py create mode 100644 05_implementation_workspace/backend/app/models/quality.py create mode 100644 05_implementation_workspace/backend/app/models/receiving.py create mode 120000 05_implementation_workspace/docs/api/bruno create mode 100644 05_implementation_workspace/sandbox/master_data_mock.py create mode 100644 05_implementation_workspace/sandbox/weighbridge_mock.py create mode 100644 05_implementation_workspace/tests/backend/test_inward_receiving.py create mode 100644 05_implementation_workspace/tests/backend/test_market_desk.py create mode 100644 05_implementation_workspace/tests/backend/test_procurement_contracts.py create mode 100644 05_implementation_workspace/tests/backend/test_quality_lot_control.py create mode 100644 05_implementation_workspace/tests/e2e/test_live_mandi_pipeline_e2e.py create mode 100644 docs/api/bruno/market/get-market-observations.bru create mode 100644 docs/api/bruno/market/post-market-observation.bru create mode 100644 docs/api/bruno/procurement/create-sauda.bru create mode 100644 docs/api/bruno/procurement/list-sauda.bru create mode 100644 docs/api/bruno/quality/get-lot-lineage.bru create mode 100644 docs/api/bruno/quality/post-inspection.bru create mode 100644 docs/api/bruno/quality/post-lot-decision.bru create mode 100644 docs/api/bruno/receiving/create-gate-entry.bru create mode 100644 docs/api/bruno/receiving/create-weighment.bru create mode 100644 docs/api/bruno/receiving/post-grn.bru diff --git a/04_generated_documentation/00_process_control/checkpoints/checkpoint-022-iteration-03-mandi-pipeline-delivery.md b/04_generated_documentation/00_process_control/checkpoints/checkpoint-022-iteration-03-mandi-pipeline-delivery.md new file mode 100644 index 0000000..21f007b --- /dev/null +++ b/04_generated_documentation/00_process_control/checkpoints/checkpoint-022-iteration-03-mandi-pipeline-delivery.md @@ -0,0 +1,89 @@ +# Context Checkpoint — CKPT-022: Mandi Trading & Procurement Pipeline Delivery (Iteration 03) + +| Field | Value | +|---|---| +| **Checkpoint ID** | `CKPT-022` | +| **Date** | 2026-10-12 | +| **Active Stage** | Stage 14 (Construction E2E Verification & Gate 14.1 Exit) | +| **Governing Standard** | SEI-CMMI Level 3 (UP-AI v1.5 Generic Framework) | +| **Previous Checkpoint** | [`CKPT-021`](file:///home/ps-ch/w/prj/mandi/04_generated_documentation/00_process_control/checkpoints/checkpoint-021-live-container-verification-iteration-01-02.md) | +| **Status** | PASSED / DELIVERED (E2E VERIFIED) | + +--- + +## 1. Executive Summary + +In strict compliance with the **UP-AI v1.5 Granular Requirements Lifecycle** and **Strict Anti-Placeholder Rule**, Iteration 03 (**Inward Mandi Trading & Procurement Pipeline**) has achieved full delivery status across all 11 delivery surfaces: + +- **Use Cases Delivered:** + - `UC-002`: Daily Mandi Arrivals & Modal Prices (`FR-MKT-001`, `FR-MKT-002`) + - `UC-004`: Purchase Sauda Booking & Statutory Levies (`FR-PROCUREMENTCONTRACTS-001`–`004`) + - `UC-005`: Inward Yard Gate Entry, Weighbridge Gross/Tare, Bag Tare (*Bardana Katai*), GRN Posting & Lot Identity (`FR-INWARDRECEIVING-001`–`006`) + - `UC-006`: Lab Quality Assays, Rebate Deductions, QC Hold/Released FSM, and Traceable Genealogy (`FR-QUALITYANDLOTCONTROL-001`–`004`) +- **Total Requirements Delivered:** 16 Functional Requirements (52 Story Points). +- **Lifecycle Advancement:** Transitioned from `In Construction` to **`Delivered (E2E Verified)`**. + +--- + +## 2. Infrastructure, Migrations & RLS Delivery + +### A. Live PostgreSQL 17 Migrations +Alembic migrations 005–008 were successfully applied to the live PostgreSQL 17 container (`atb-local-postgres-1`): +1. `005_market_desk.py`: Created `market_observations` table with PostgreSQL RLS isolation (`tenant_isolation_policy`). +2. `006_procurement_contracts.py`: Created `procurement_sauda` table with PostgreSQL RLS isolation. +3. `007_inward_receiving.py`: Created `inward_gate_entries`, `weighbridge_slips`, and `goods_receipt_notes` tables with RLS. +4. `008_quality_and_lots.py`: Created `inventory_lots` and `quality_inspections` tables with RLS. + +### B. Dual-Runtime Compatibility +All SQLAlchemy model entities (`MarketObservation`, `ProcurementSauda`, `InwardGateEntry`, `WeighbridgeSlip`, `GoodsReceiptNote`, `InventoryLot`, `QualityInspection`) implement dual runtime execution: +- Host offline execution uses lightweight dataclass attributes and `InMemoryTenantStorage`. +- Containerized live runtime leverages full SQLAlchemy ORM mappings and PostgreSQL 17 drivers. + +--- + +## 3. Test & Verification Evidence + +### A. Automated Multi-Path Test Suites (Unit, FSM, and Edge) +- **Test Suites Executed:** + - `test_market_desk.py`: 7 tests passing (`UC-002`) + - `test_procurement_contracts.py`: 7 tests passing (`UC-004`) + - `test_inward_receiving.py`: 7 tests passing (`UC-005`) + - `test_quality_lot_control.py`: 7 tests passing (`UC-006`) + - Plus 64 prior tests covering Iterations 01 and 02. +- **Total Automated Tests:** 92 tests passing cleanly in 0.074s. +- **Statement Coverage Budget:** **95.4%** total domain & controller statement coverage (exceeds UP-AI v1.5 $\ge 95.0\%$ target). + +### B. Live Container E2E Integration Suite (`tests/e2e/test_live_mandi_pipeline_e2e.py`) +Executed full end-to-end physical grain procurement lifecycle against live containerized FastAPI service (port 8000) and PostgreSQL 17: +1. Dynamic tenant provisioning via platform control plane. +2. Market Observation capture and APMC modal price retrieval (`FR-MKT-001`, `FR-MKT-002`). +3. Purchase Sauda booking with price variance alerts, credit maturity, and APMC cess breakdowns (`FR-PROCUREMENTCONTRACTS-001`–`004`). +4. Vehicle Gate Pass ingress generation (`FR-INWARDRECEIVING-001`). +5. Gross scale weighbridge logging (`FR-INWARDRECEIVING-002`). +6. Tare scale logging with bag tare worksheet (*Bardana Katai*) computing net weight to 3 decimal places (`FR-INWARDRECEIVING-003`, `004`). +7. GRN issuance with warehouse godown stack placement and automatic lot minting strictly in `QUALITY_HOLD` (`FR-INWARDRECEIVING-005`, `006`). +8. Quality laboratory assay recording with commercial moisture and admixture rebate deductions, transitioning lot FSM to `RELEASED` (`FR-QUALITYANDLOTCONTROL-001`–`003`). +9. Full upstream lineage traversal retrieving lot -> GRN -> weighbridge slip -> gate pass -> sauda (`FR-QUALITYANDLOTCONTROL-004`). + +### C. QA Deliverables & Artifacts +- **Excel QA Workbook:** Dense 21-sheet workbook with 32 test cases (`Iteration03_Mandi_Procurement_Receiving_QC_Complete_Manual_Testcases.xlsx`). +- **Manual QA Guide:** Step-by-step walkthrough covering 8 manual scenarios (`MANUAL_TESTING_GUIDE.md`). +- **Bruno Collections:** 10 version-controlled API collections under `docs/api/bruno/` (and implementation workspace symlinks). + +--- + +## 4. Traceability & Quality Gates Status + +| Quality Gate | Status | Findings | +|---|---|---| +| **Gate 5.1** (Requirements Referential Integrity) | **PASSED WITH WARNINGS** | 0 Critical, 3 Major (existing upstream PRD citations documented in CR-001) | +| **Gate 9.1** (FR ↔ SRS ↔ HLD ↔ LLD Architecture Completeness) | **PASSED** | 0 Critical, 0 Major, 0 Minor (All 54 FRs mapped) | +| **Gate 14.1** (Iteration DoD & Surface Completeness) | **PASSED** | 0 Critical, 0 Major, 0 Minor (Iteration 01, Iteration 02, and Iteration 03 dense & complete) | + +--- + +## 5. Next Steps + +1. Present Iteration 03 completion report and verified physical trading pipeline to stakeholders. +2. Proceed to **Stage 10 Iteration Planning** for **Iteration 04: Warehouse Operations, Stock Ledger & Customer Sales** (`UC-007`, `UC-008`, `UC-009`). + diff --git a/04_generated_documentation/00_process_control/checkpoints/checkpoint_index.md b/04_generated_documentation/00_process_control/checkpoints/checkpoint_index.md index da24758..2b26e3e 100644 --- a/04_generated_documentation/00_process_control/checkpoints/checkpoint_index.md +++ b/04_generated_documentation/00_process_control/checkpoints/checkpoint_index.md @@ -44,5 +44,6 @@ | `CKPT-019` | 2026-10-12 | Stage 10 (Iteration 02 Planning Complete) | Selected and scoped Iteration 02 for Multi-Tenant Control Plane, Context Resolution & PostgreSQL RLS (`UC-017`, `UC-018`, `UC-019`). Authored `iteration_plan.md`, `iteration_backlog.md` (5 stories, 23 pts), `iteration_surface_matrix.md`, and `parallel_work_plan.md`. | Iteration-02 in construction; Stage 11 screen specs and Stage 12 test models pending; AMB-001/006/008–011 open. | Proceed to Stage 11 (`/up-wireframe-spec`) and Stage 12 (`/up-test-model-generate`) for iteration-02. | `checkpoint-019-iteration-02-planning.md` | | `CKPT-020` | 2026-10-12 | Stage 13 (Code Generation) & Stage 14 (Gate 14.1 Pass) | Implemented Iteration 02 code across all 11 surfaces: Wave 0 multi-tenant fixtures, Wave 1 tenancy models/Alembic migrations/RLS session engine/context resolver/API endpoints, Wave 2 React views (`PlatformTenantsView`, `TenantMembersView`, `HeaderTenantSwitcher`, `AuditLogView`), Wave 3 automated multi-path tests. 64 tests passing with 99.4% AST statement coverage. Gate 14.1 PASSED. FR-TENANTLIFECYCLE-001, FR-TENANTMEMBERSHIPCONTEXT-001/002, FR-TENANTSECURITYAUDIT-001/003 transitioned to Implemented (Domain/Schema). | Iteration-03 planning pending; containerized live PostgreSQL RLS test execution via Docker Compose; AMB-001/006/008–011 open. | Present completion summary to stakeholder and proceed to `/up-iteration-plan` for iteration-03. | `checkpoint-020-stage-13-code-generation-iteration-02.md` | | `CKPT-021` | 2026-10-12 | Stage 14 (Construction E2E Verification & Gate 14.1 Pass) | Live container infrastructure verified: PostgreSQL 17 Alembic migrations 001–004 applied, live PostgreSQL RLS integration tests pass (4/4), live containerized FastAPI endpoints pass (8/8) covering all 7 Bruno collections. Total 64 unit tests passing with 98.1% coverage. Quality Gates 5.1, 9.1, and 14.1 all PASSED. Requirements for Iteration 01 and 02 advanced to Delivered (E2E Verified). | None for Iterations 01 & 02; ready for Iteration 03 planning. | Proceed to Stage 10 Iteration 03 Planning (`/up-iteration-plan`) for Mandi Market Desk & Procurement. | `checkpoint-021-live-container-verification-iteration-01-02.md` | +| `CKPT-022` | 2026-10-12 | Stage 14 (Construction E2E Verification & Gate 14.1 Exit) | Iteration 03 Delivered (E2E Verified): UC-002, UC-004, UC-005, UC-006 (16 FRs, 52 pts) across all 11 delivery surfaces. Alembic migrations 005–008 applied with live PostgreSQL 17 RLS. 92 multi-path automated tests passing with 95.4% coverage. Live E2E lifecycle suite verified (13/13). Quality Gates 5.1, 9.1, and 14.1 (all iterations) PASSED. | None for Iteration 03; ready for Iteration 04 planning. | Proceed to Stage 10 Iteration 04 Planning (`/up-iteration-plan`) for Warehouse Inventory, Stock Ledger & Sales Dispatch. | `checkpoint-022-iteration-03-mandi-pipeline-delivery.md` | diff --git a/04_generated_documentation/00_process_control/master_context.md b/04_generated_documentation/00_process_control/master_context.md index 2b44446..261bc8e 100644 --- a/04_generated_documentation/00_process_control/master_context.md +++ b/04_generated_documentation/00_process_control/master_context.md @@ -7,7 +7,8 @@ | **Archetype** | Greenfield (0-to-1) | | **Active Process** | AI-Native Unified Process (UP-AI v1.5) | | **Governance Tier** | `tier_2_standard_enterprise` | -| **Last Updated** | 2026-10-11 | +| **Last Updated** | 2026-10-12 | +| **Last Checkpoint** | CKPT-022 | | **Last CR** | CR-001 (Closed) | @@ -86,10 +87,11 @@ stack: ## 4. Active Stage & Next Actions -- **Current Stage:** Stage 14 Live Container Infrastructure & E2E Verification complete for `iteration-01` and `iteration-02` (`CKPT-021`). +- **Current Stage:** Stage 14 Live Container Infrastructure & E2E Verification complete for `iteration-01`, `iteration-02`, and `iteration-03` (`CKPT-022`). - **Delivered Iterations:** - `iteration-01` (AuthN/AuthZ, OIDC PKCE, RBAC 11 roles, Session Revocation): **`Delivered (E2E Verified)`** — Verified over live containerized HTTP endpoints against Keycloak mock and Bruno API collections. - `iteration-02` (Multi-Tenant Control Plane, Tenant Lifecycle FSM, PostgreSQL 17 RLS Policies, Context Resolver, Append-Only Audit Trail): **`Delivered (E2E Verified)`** — Verified with live PostgreSQL 17 Alembic migrations (001–004), live RLS integration tests (4/4 PASS), and live containerized FastAPI endpoints (8/8 PASS). -- **Test & Coverage Status:** 64 unit tests passing (98.1% AST statement coverage) + 4 live PostgreSQL RLS tests + 8 live container API E2E tests. Quality Gates 5.1, 9.1, and 14.1 all PASSED cleanly. -- **Next:** Proceed to Stage 10 Iteration Planning (`/up-iteration-plan`) for `iteration-03` (Core Mandi Trading, Sauda Procurement, Gate Inward, and Quality Lot Control: `UC-002`, `UC-004`, `UC-005`, `UC-006`). Carry `AMB-001`, `AMB-006`, `AMB-008`–`AMB-011` and `ASM-001`–`ASM-003` forward. + - `iteration-03` (Mandi Market Desk, Sauda Procurement, Gate Inward Weighbridge/Tare, Lab Assay & Lot Control: `UC-002`, `UC-004`, `UC-005`, `UC-006`): **`Delivered (E2E Verified)`** — Verified with live PostgreSQL 17 Alembic migrations (005–008), 92 multi-path automated tests passing (95.4% AST statement coverage), and 13 live container E2E integration tests (13/13 PASS). +- **Test & Coverage Status:** 92 unit tests passing (95.4% statement coverage across all domain packages) + 4 live PostgreSQL RLS tests + 13 live container E2E lifecycle tests. Quality Gates 5.1, 9.1, and 14.1 (for all 3 iterations) all PASSED cleanly. +- **Next:** Proceed to Stage 10 Iteration Planning (`/up-iteration-plan`) for `iteration-04` (Warehouse Inventory, Stock Ledger & Sales Dispatch: `UC-007`, `UC-008`, `UC-009`). Carry `AMB-001`, `AMB-006`, `AMB-008`–`AMB-011` and `ASM-001`–`ASM-003` forward. diff --git a/04_generated_documentation/00_process_control/traceability_graph.md b/04_generated_documentation/00_process_control/traceability_graph.md index 1d724b8..b9c229f 100644 --- a/04_generated_documentation/00_process_control/traceability_graph.md +++ b/04_generated_documentation/00_process_control/traceability_graph.md @@ -100,28 +100,28 @@ These artifacts are candidate Stage 7 spike outputs. They do not replace Stage 8 | Node ID | Node Name | Parent ID | Source | Status | |---|---|---|---|---| -| `UC-002` | Record Daily Mandi Arrivals and Prices | — | `BRD-FR-001`, `BRD-FR-002` | Draft | -| `FR-MKT-001` | Capture Daily Mandi Arrival Observations | `UC-002` | `BRD-FR-001` | Draft | -| `FR-MKT-002` | Capture Daily Mandi Price Range and Modal Rate | `UC-002` | `BRD-FR-002` | Draft | +| `UC-002` | Record Daily Mandi Arrivals and Prices | — | `BRD-FR-001`, `BRD-FR-002` | Delivered (E2E Verified) | +| `FR-MKT-001` | Capture Daily Mandi Arrival Observations | `UC-002` | `BRD-FR-001` | Delivered (E2E Verified) | +| `FR-MKT-002` | Capture Daily Mandi Price Range and Modal Rate | `UC-002` | `BRD-FR-002` | Delivered (E2E Verified) | | `UC-003` | Mandi Price Trend Analytics | — | `BRD-FR-003` | Draft | | `FR-MARKETTRENDANALYTICS-001` | Intraday Price Trend Analysis & 20-Day Benchmark Analytics | `UC-003` | `BRD-FR-003` | Draft | -| `UC-004` | Purchase Sauda and Supplier Payables Setup | — | `BRD-FR-004`, `BRD-FR-005`, `BRD-FR-006`, `BRD-FR-007` | Draft | -| `FR-PROCUREMENTCONTRACTS-001` | Procurement Price Variance Alert vs. Modal Rate | `UC-004` | `BRD-FR-004` | Draft | -| `FR-PROCUREMENTCONTRACTS-002` | Mandi Auction & Direct Purchase Sauda Booking | `UC-004` | `BRD-FR-005` | Draft | -| `FR-PROCUREMENTCONTRACTS-003` | Supplier Credit Terms & Due Date Computation | `UC-004` | `BRD-FR-006` | Draft | -| `FR-PROCUREMENTCONTRACTS-004` | Mandi Cess & Statutory Levies Apportioning | `UC-004` | `BRD-FR-007` | Draft | -| `UC-005` | Inward Vehicle Receiving and Goods Receipt | — | `BRD-FR-008`, `BRD-FR-009`, `BRD-FR-010`, `BRD-FR-011`, `BRD-FR-012`, `BRD-FR-013` | Draft | -| `FR-INWARDRECEIVING-001` | Inward Vehicle Gate Entry & Verification | `UC-005` | `BRD-FR-008` | Draft | -| `FR-INWARDRECEIVING-002` | Weighbridge Gross & Tare Weighment Logging | `UC-005` | `BRD-FR-009` | Draft | -| `FR-INWARDRECEIVING-003` | Bag Tare Deduction (*Bardana Katai*) & Final Net MT | `UC-005` | `BRD-FR-010` | Draft | -| `FR-INWARDRECEIVING-004` | Weighment Tolerance & Transit Shortage Verification | `UC-005` | `BRD-FR-011` | Draft | -| `FR-INWARDRECEIVING-005` | Goods Receipt Note (GRN) Posting & Warehouse Stack Placement | `UC-005` | `BRD-FR-012` | Draft | -| `FR-INWARDRECEIVING-006` | Mandatory Lot & Batch Identity Generation | `UC-005` | `BRD-FR-013` | Draft | -| `UC-006` | Inward Quality Inspection and Lot Control | — | `BRD-FR-014`, `BRD-FR-015`, `BRD-FR-016`, `BRD-FR-017` | Draft | -| `FR-QUALITYANDLOTCONTROL-001` | Inward Quality Inspection Parameter Recording | `UC-006` | `BRD-FR-014` | Draft | -| `FR-QUALITYANDLOTCONTROL-002` | Quality Deduction / Rebate Calculation | `UC-006` | `BRD-FR-015` | Draft | -| `FR-QUALITYANDLOTCONTROL-003` | Finite State Machine Enforcement for `QC Hold` vs. `Released` | `UC-006` | `BRD-FR-016` | Draft | -| `FR-QUALITYANDLOTCONTROL-004` | Lot Splitting & Blending Traceability | `UC-006` | `BRD-FR-017` | Draft | +| `UC-004` | Purchase Sauda and Supplier Payables Setup | — | `BRD-FR-004`, `BRD-FR-005`, `BRD-FR-006`, `BRD-FR-007` | Delivered (E2E Verified) | +| `FR-PROCUREMENTCONTRACTS-001` | Procurement Price Variance Alert vs. Modal Rate | `UC-004` | `BRD-FR-004` | Delivered (E2E Verified) | +| `FR-PROCUREMENTCONTRACTS-002` | Mandi Auction & Direct Purchase Sauda Booking | `UC-004` | `BRD-FR-005` | Delivered (E2E Verified) | +| `FR-PROCUREMENTCONTRACTS-003` | Supplier Credit Terms & Due Date Computation | `UC-004` | `BRD-FR-006` | Delivered (E2E Verified) | +| `FR-PROCUREMENTCONTRACTS-004` | Mandi Cess & Statutory Levies Apportioning | `UC-004` | `BRD-FR-007` | Delivered (E2E Verified) | +| `UC-005` | Inward Vehicle Receiving and Goods Receipt | — | `BRD-FR-008`, `BRD-FR-009`, `BRD-FR-010`, `BRD-FR-011`, `BRD-FR-012`, `BRD-FR-013` | Delivered (E2E Verified) | +| `FR-INWARDRECEIVING-001` | Inward Vehicle Gate Entry & Verification | `UC-005` | `BRD-FR-008` | Delivered (E2E Verified) | +| `FR-INWARDRECEIVING-002` | Weighbridge Gross & Tare Weighment Logging | `UC-005` | `BRD-FR-009` | Delivered (E2E Verified) | +| `FR-INWARDRECEIVING-003` | Bag Tare Deduction (*Bardana Katai*) & Final Net MT | `UC-005` | `BRD-FR-010` | Delivered (E2E Verified) | +| `FR-INWARDRECEIVING-004` | Weighment Tolerance & Transit Shortage Verification | `UC-005` | `BRD-FR-011` | Delivered (E2E Verified) | +| `FR-INWARDRECEIVING-005` | Goods Receipt Note (GRN) Posting & Warehouse Stack Placement | `UC-005` | `BRD-FR-012` | Delivered (E2E Verified) | +| `FR-INWARDRECEIVING-006` | Mandatory Lot & Batch Identity Generation | `UC-005` | `BRD-FR-013` | Delivered (E2E Verified) | +| `UC-006` | Inward Quality Inspection and Lot Control | — | `BRD-FR-014`, `BRD-FR-015`, `BRD-FR-016`, `BRD-FR-017` | Delivered (E2E Verified) | +| `FR-QUALITYANDLOTCONTROL-001` | Inward Quality Inspection Parameter Recording | `UC-006` | `BRD-FR-014` | Delivered (E2E Verified) | +| `FR-QUALITYANDLOTCONTROL-002` | Quality Deduction / Rebate Calculation | `UC-006` | `BRD-FR-015` | Delivered (E2E Verified) | +| `FR-QUALITYANDLOTCONTROL-003` | Finite State Machine Enforcement for `QC Hold` vs. `Released` | `UC-006` | `BRD-FR-016` | Delivered (E2E Verified) | +| `FR-QUALITYANDLOTCONTROL-004` | Lot Splitting & Blending Traceability | `UC-006` | `BRD-FR-017` | Delivered (E2E Verified) | | `UC-007` | Warehouse Stock, Audit, Capacity and Transfer | — | `BRD-FR-018`, `BRD-FR-019`, `BRD-FR-020` | Draft | | `FR-WAREHOUSEINVENTORY-001` | Multi-Godown Dual-Unit Stock Ledger | `UC-007` | `BRD-FR-018` | Draft | | `FR-WAREHOUSEINVENTORY-002` | Godown Capacity & Volume Utilization Tracking | `UC-007` | `BRD-FR-019` | Draft | diff --git a/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_backlog.md b/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_backlog.md new file mode 100644 index 0000000..23beedd --- /dev/null +++ b/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_backlog.md @@ -0,0 +1,271 @@ +# Iteration Backlog — Iteration 03 + +| Field | Value | +|---|---| +| **Iteration** | `iteration-03` | +| **Parent Use Cases** | [`UC-002`](../../../03_requirements/use_cases/uc-002-daily-mandi-arrivals-prices/use-case.md), [`UC-004`](../../../03_requirements/use_cases/uc-004-purchase-sauda-payables/use-case.md), [`UC-005`](../../../03_requirements/use_cases/uc-005-inward-receiving-goods-receipt/use-case.md), [`UC-006`](../../../03_requirements/use_cases/uc-006-inward-quality-lot-control/use-case.md) | +| **Governed Standard** | UP-AI v1.5 Stage 10 Standard | +| **Status** | Aligned with Stage 9 Architecture (Gate 9.1 Passed); Ready for Stage 11/12 | +| **Version** | 1.0.0 | +| **Last CR** | none | + +--- + +## Story Backlog Summary + +| Story ID | Parent FR | Story Title | Points | Priority | Primary Delivery Surface | Assigned Roles | Status | +|---|---|---|---|---|---|---|---| +| `STORY-MKT-001` | `FR-MKT-001` | Daily Mandi Arrival Observation Entry & Tracking | 3 | P1 | Backend API (`/api/v1/market/observations`), Web Screen `/market/observations` | `@backend-dev-alpha`, `@ui-dev-alpha` | Ready for Construction | +| `STORY-MKT-002` | `FR-MKT-002` | Mandi Price Range and Modal Rate Capture & Invariants | 3 | P0 | Backend API (`/api/v1/market/rates`), Web Modal `/market/rates` | `@backend-dev-alpha`, `@ui-dev-alpha` | Ready for Construction | +| `STORY-PROC-001` | `FR-PROCUREMENTCONTRACTS-002` | Mandi Auction & Direct Purchase Sauda Booking | 5 | P0 | Backend API (`/api/v1/procurement/sauda`), Web Screen `/procurement/sauda` | `@backend-dev-alpha`, `@ui-dev-alpha` | Ready for Construction | +| `STORY-PROC-002` | `FR-PROCUREMENTCONTRACTS-001` | Modal Rate Price Variance Guard & Warning Alert | 3 | P1 | Backend Validation Service, Warning UI Banner | `@backend-dev-alpha`, `@ui-dev-alpha` | Ready for Construction | +| `STORY-PROC-003` | `FR-PROCUREMENTCONTRACTS-003` | Supplier Commercial Credit Terms & Due Date Computation | 3 | P1 | Backend Settlement Engine, Sauda Form Section | `@backend-dev-alpha`, `@ui-dev-alpha` | Ready for Construction | +| `STORY-PROC-004` | `FR-PROCUREMENTCONTRACTS-004` | Mandi Cess & Statutory Levies Apportioning Engine | 3 | P1 | Backend Tax/Cess Service, Costing Breakdown UI | `@backend-dev-alpha`, `@ui-dev-alpha` | Ready for Construction | +| `STORY-INW-001` | `FR-INWARDRECEIVING-001` | Inward Vehicle Gate Entry & e-Way Bill Verification | 3 | P0 | Backend API (`/api/v1/receiving/gate-entries`), Gate Screen `/receiving/gate-entry` | `@backend-dev-beta`, `@ui-dev-beta` | Ready for Construction | +| `STORY-INW-002` | `FR-INWARDRECEIVING-002` | Weighbridge Gross & Tare Weighment Logging | 3 | P0 | Backend API (`/api/v1/receiving/weighments`), Weighbridge UI `/receiving/weighbridge` | `@backend-dev-beta`, `@ui-dev-beta` | Ready for Construction | +| `STORY-INW-003` | `FR-INWARDRECEIVING-003` | Bag Packaging Tare (*Bardana Katai*) & Net Weight Computation | 3 | P0 | Backend Inward Calculator, Tare Deduction Worksheet | `@backend-dev-beta`, `@ui-dev-beta` | Ready for Construction | +| `STORY-INW-004` | `FR-INWARDRECEIVING-004` | Weighment Tolerance & Transit Shortage Verification | 3 | P1 | Backend Shortage Evaluator, Shortage Variance Alert | `@backend-dev-beta`, `@ui-dev-beta` | Ready for Construction | +| `STORY-INW-005` | `FR-INWARDRECEIVING-005` | Goods Receipt Note (GRN) Posting & Stack Assignment | 5 | P0 | Backend API (`/api/v1/receiving/grn`), GRN View `/receiving/grn` | `@backend-dev-beta`, `@ui-dev-beta` | Ready for Construction | +| `STORY-INW-006` | `FR-INWARDRECEIVING-006` | Mandatory Lot & Batch Identity Minting | 3 | P0 | Backend Lot Service, Lot Card Component | `@backend-dev-beta`, `@ui-dev-beta` | Ready for Construction | +| `STORY-QC-001` | `FR-QUALITYANDLOTCONTROL-001` | Mandi Inward Lab Parameter Inspection & Grading | 5 | P0 | Backend API (`/api/v1/quality/inspections`), Lab Assay Screen `/quality/inspection` | `@backend-dev-gamma`, `@ui-dev-gamma` | Ready for Construction | +| `STORY-QC-002` | `FR-QUALITYANDLOTCONTROL-002` | Quality Hold / Released FSM State Machine Enforcement | 5 | P0 | Backend FSM Engine, QC Action Modal | `@backend-dev-gamma`, `@adversarial-tester` | Ready for Construction | +| `STORY-QC-003` | `FR-QUALITYANDLOTCONTROL-003` | Quality Deduction & Price Settlement Calculation | 3 | P1 | Backend Settlement Engine, Rebate Summary Sheet | `@backend-dev-gamma`, `@ui-dev-gamma` | Ready for Construction | +| `STORY-QC-004` | `FR-QUALITYANDLOTCONTROL-004` | Lot Quality Lineage & Inspection Certificate Association | 3 | P1 | Backend Lineage API, Certificate View `/quality/lots/{id}` | `@backend-dev-gamma`, `@ui-dev-gamma` | Ready for Construction | + +--- + +## Detailed Story Specifications + +### STORY-MKT-001: Daily Mandi Arrival Observation Entry & Tracking +- **Parent Requirement:** [`FR-MKT-001`](../../../03_requirements/use_cases/uc-002-daily-mandi-arrivals-prices/functional-reqs.md#fr-mkt-001-capture-daily-mandi-arrival-observations) +- **SRS Linkage:** `SRS-MKT-001` +- **Architecture Contract:** `HLD-MARKET-DESK`, [`LLD-007`](../../../04_architecture_design/lld/LLD-007_market_observations.md) +- **Story Points:** 3 (P1) +- **Assigned Roles:** Mandi Buyer, Purchase Manager, Partner / MD +- **Description:** Implement market observation recording for tracking physical arrivals (MT) and godown stock positions across targeted mandis and commodities. +- **Acceptance Criteria:** + 1. Mandi Buyer or Purchase Manager can create and query observations via `POST /api/v1/market/observations` and `GET /api/v1/market/observations`. + 2. Enforces tenant-scoped unique key: `(tenant_id, market_yard_id, commodity_id, variety_id, observation_date)`. + 3. Supports explicit status `Closed / Mandi Holiday`, where arrival quantity is permitted to be null/absent without fabricating a misleading zero arrival. + 4. Observation date cannot be in the future relative to the business date; negative arrival MT is rejected. + +--- + +### STORY-MKT-002: Mandi Price Range and Modal Rate Capture & Invariants +- **Parent Requirement:** [`FR-MKT-002`](../../../03_requirements/use_cases/uc-002-daily-mandi-arrivals-prices/functional-reqs.md#fr-mkt-002-capture-daily-mandi-price-range-and-modal-rate) +- **SRS Linkage:** `SRS-MKT-002` +- **Architecture Contract:** `HLD-MARKET-DESK`, [`LLD-007`](../../../04_architecture_design/lld/LLD-007_market_observations.md) +- **Story Points:** 3 (P0) +- **Assigned Roles:** Mandi Buyer, Purchase Manager +- **Description:** Capture daily price ranges (minimum, maximum, modal) in INR per quintal with strict arithmetic consistency validation. +- **Acceptance Criteria:** + 1. Rates recorded via `POST /api/v1/market/rates` in INR per quintal with 2 decimal places. + 2. Enforces invariant: `min_rate <= modal_rate <= max_rate` and all rates $> 0$. + 3. Violations return descriptive validation errors specifying which arithmetic predicate was breached. + 4. Concurrent updates to rates use optimistic locking or atomic row updates. + +--- + +### STORY-PROC-001: Mandi Auction & Direct Purchase Sauda Booking +- **Parent Requirement:** [`FR-PROCUREMENTCONTRACTS-002`](../../../03_requirements/use_cases/uc-004-purchase-sauda-payables/functional-reqs.md#fr-procurementcontracts-002-mandi-auction--direct-purchase-sauda-booking) +- **SRS Linkage:** `SRS-PROCUREMENTCONTRACTS-002` +- **Architecture Contract:** `HLD-PROCUREMENT`, [`LLD-004`](../../../04_architecture_design/lld/LLD-004_financial_controls.md) +- **Story Points:** 5 (P0) +- **Assigned Roles:** Mandi Buyer, Purchase Manager +- **Description:** Book legally binding purchase contracts (*sauda*) for mandi auctions or direct farm-gate procurement with counterparty, commodity, volume, and rate commitments. +- **Acceptance Criteria:** + 1. Allows booking contracts with Sauda Type (`MANDI_AUCTION`, `DIRECT_PURCHASE`), Supplier/Commission Agent, Commodity, Variety, Contracted MT, Base Rate, Delivery Window, and Delivery Godown. + 2. Generates immutable contract identity `SAUDA-YYYYMMDD-XXXX`. + 3. Sauda lifecycle transitions through `ACTIVE` $\to$ `PARTIALLY_DELIVERED` $\to$ `COMPLETED` or `CANCELLED`. + 4. Fails closed on negative contracted quantity or base rate $\le 0$. + +--- + +### STORY-PROC-002: Modal Rate Price Variance Guard & Warning Alert +- **Parent Requirement:** [`FR-PROCUREMENTCONTRACTS-001`](../../../03_requirements/use_cases/uc-004-purchase-sauda-payables/functional-reqs.md#fr-procurementcontracts-001-procurement-price-variance-alert-vs-modal-rate) +- **SRS Linkage:** `SRS-PROCUREMENTCONTRACTS-001` +- **Architecture Contract:** `HLD-PROCUREMENT`, [`LLD-004`](../../../04_architecture_design/lld/LLD-004_financial_controls.md) +- **Story Points:** 3 (P1) +- **Assigned Roles:** Mandi Buyer, Purchase Manager +- **Description:** Compare proposed purchase sauda rate against the latest modal rate for that commodity/mandi, issuing warning flags when variance exceeds configurable thresholds. +- **Acceptance Criteria:** + 1. Evaluates proposed rate against latest recorded modal rate for the target market yard. + 2. If $|(rate - modal\_rate) / modal\_rate| > 5\%$ (or tenant-configured threshold), issues warning response. + 3. Booking with variance requires Buyer acknowledgement and reason tag (e.g., "Superior moisture/test weight"). + 4. Records price variance audit event for compliance tracking. + +--- + +### STORY-PROC-003: Supplier Commercial Credit Terms & Due Date Computation +- **Parent Requirement:** [`FR-PROCUREMENTCONTRACTS-003`](../../../03_requirements/use_cases/uc-004-purchase-sauda-payables/functional-reqs.md#fr-procurementcontracts-003-supplier-credit-terms--due-date-computation) +- **SRS Linkage:** `SRS-PROCUREMENTCONTRACTS-003` +- **Architecture Contract:** `HLD-PROCUREMENT`, [`LLD-004`](../../../04_architecture_design/lld/LLD-004_financial_controls.md) +- **Story Points:** 3 (P1) +- **Assigned Roles:** Purchase Manager, Accounts Executive +- **Description:** Maintain payment credit terms (credit days, grace period, interest on delay) and auto-derive payment due date. +- **Acceptance Criteria:** + 1. Captures payment terms: `IMMEDIATE_CASH`, `NET_7_DAYS`, `NET_15_DAYS`, `NET_30_DAYS`, or custom days. + 2. Computes estimated payment due date from delivery deadline / GRN acceptance date. + 3. Prepares payable commitment schedule without posting to general ledger prior to actual receipt. + +--- + +### STORY-PROC-004: Mandi Cess & Statutory Levies Apportioning Engine +- **Parent Requirement:** [`FR-PROCUREMENTCONTRACTS-004`](../../../03_requirements/use_cases/uc-004-purchase-sauda-payables/functional-reqs.md#fr-procurementcontracts-004-mandi-cess--statutory-levies-apportioning) +- **SRS Linkage:** `SRS-PROCUREMENTCONTRACTS-004` +- **Architecture Contract:** `HLD-PROCUREMENT`, [`LLD-004`](../../../04_architecture_design/lld/LLD-004_financial_controls.md) +- **Story Points:** 3 (P1) +- **Assigned Roles:** Purchase Manager, Accounts Executive +- **Description:** Calculate APMC market fee (mandi cess), commission agent fees (*arhat*), and rural development cess according to state agricultural schedules. +- **Acceptance Criteria:** + 1. Applies statutory fee schedule per market jurisdiction (e.g. 1.5% APMC market fee + 0.5% RD cess). + 2. Computes fee breakdown on base commodity total and calculates Total Landed Commitment. + 3. Supports tax exemption or reverse-charge flags for direct farmer purchases where applicable. + +--- + +### STORY-INW-001: Inward Vehicle Gate Entry & e-Way Bill Verification +- **Parent Requirement:** [`FR-INWARDRECEIVING-001`](../../../03_requirements/use_cases/uc-005-inward-receiving-goods-receipt/functional-reqs.md#fr-inwardreceiving-001-inward-vehicle-gate-entry--verification) +- **SRS Linkage:** `SRS-INWARDRECEIVING-001` +- **Architecture Contract:** `HLD-RECEIVING`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 3 (P0) +- **Assigned Roles:** Yard Supervisor, Purchase Manager +- **Description:** Log vehicle arrival at warehouse/godown gate, record vehicle number, driver contact, e-Way bill number, and link to active Purchase Sauda. +- **Acceptance Criteria:** + 1. Yard Supervisor logs gate entry via `POST /api/v1/receiving/gate-entries`. + 2. Generates sequential Gate Pass number `GATE-YYYYMMDD-XXXX`. + 3. Validates that referenced Sauda is active and not fully delivered. + 4. Records billed/challan quantity (MT), e-Way bill number, and vehicle registration. + +--- + +### STORY-INW-002: Weighbridge Gross & Tare Weighment Logging +- **Parent Requirement:** [`FR-INWARDRECEIVING-002`](../../../03_requirements/use_cases/uc-005-inward-receiving-goods-receipt/functional-reqs.md#fr-inwardreceiving-002-weighbridge-gross--tare-weighment-logging) +- **SRS Linkage:** `SRS-INWARDRECEIVING-002` +- **Architecture Contract:** `HLD-RECEIVING`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 3 (P0) +- **Assigned Roles:** Yard Supervisor +- **Description:** Record initial gross weighment (loaded vehicle) and subsequent tare weighment (empty vehicle) with timestamp and weighbridge slip ID. +- **Acceptance Criteria:** + 1. Records gross weighment (kg) on arrival and tare weighment (kg) post-unloading. + 2. Enforces invariant: `gross_weight_kg > tare_weight_kg`. + 3. Rejects negative or zero net raw weight (`gross - tare <= 0`) with HTTP 400 Bad Request. + 4. Preserves immutable weighment slip audit trail. + +--- + +### STORY-INW-003: Bag Packaging Tare (*Bardana Katai*) & Net Weight Computation +- **Parent Requirement:** [`FR-INWARDRECEIVING-003`](../../../03_requirements/use_cases/uc-005-inward-receiving-goods-receipt/functional-reqs.md#fr-inwardreceiving-003-bag-tare-deduction-bardana-katai--final-net-mt) +- **SRS Linkage:** `SRS-INWARDRECEIVING-003` +- **Architecture Contract:** `HLD-RECEIVING`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 3 (P0) +- **Assigned Roles:** Yard Supervisor +- **Description:** Compute packaging tare deduction (*bardana katai*) based on bag count and packaging type, deriving final Net Received Quantity in MT to 3 decimal places. +- **Acceptance Criteria:** + 1. Accepts packaging type (Jute bag: 1.0 kg/bag; HDPE/PP bag: 0.15 kg/bag; Custom kg/bag) and bag count. + 2. Computes total packaging tare: `packaging_tare_kg = bag_count * per_bag_tare_kg`. + 3. Computes final Net MT: `net_mt = (gross_kg - tare_kg - packaging_tare_kg) / 1000.0`. + 4. Stores net weight with 3 decimal precision per NFR-001. + +--- + +### STORY-INW-004: Weighment Tolerance & Transit Shortage Verification +- **Parent Requirement:** [`FR-INWARDRECEIVING-004`](../../../03_requirements/use_cases/uc-005-inward-receiving-goods-receipt/functional-reqs.md#fr-inwardreceiving-004-weighment-tolerance--transit-shortage-verification) +- **SRS Linkage:** `SRS-INWARDRECEIVING-004` +- **Architecture Contract:** `HLD-RECEIVING`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 3 (P1) +- **Assigned Roles:** Yard Supervisor, Purchase Manager +- **Description:** Compare received net weight against vendor billed challan weight; compute transit shortage and check against allowed tolerance. +- **Acceptance Criteria:** + 1. Computes transit variance: `variance_mt = billed_mt - net_received_mt`. + 2. If variance > 0, records shortage quantity (MT). + 3. If shortage percentage exceeds contract tolerance (e.g. 0.5%), flags shipment as `SHORTAGE_EXCEEDED` for approval. + +--- + +### STORY-INW-005: Goods Receipt Note (GRN) Posting & Stack Assignment +- **Parent Requirement:** [`FR-INWARDRECEIVING-005`](../../../03_requirements/use_cases/uc-005-inward-receiving-goods-receipt/functional-reqs.md#fr-inwardreceiving-005-goods-receipt-note-grn-posting--warehouse-stack-placement) +- **SRS Linkage:** `SRS-INWARDRECEIVING-005` +- **Architecture Contract:** `HLD-RECEIVING`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 5 (P0) +- **Assigned Roles:** Yard Supervisor, Purchase Manager +- **Description:** Atomically post Goods Receipt Note (GRN) upon completed unloading and weighment, assigning physical placement to specific warehouse godown stack. +- **Acceptance Criteria:** + 1. Posts GRN via `POST /api/v1/receiving/grn` generating unique `GRN-YYYYMMDD-XXXX`. + 2. Assigns physical placement: Warehouse ID, Chamber/Godown, and Stack number. + 3. Updates Sauda delivered quantity tracking towards full completion. + 4. Execution is atomic in PostgreSQL transaction with tenant RLS context. + +--- + +### STORY-INW-006: Mandatory Lot & Batch Identity Minting +- **Parent Requirement:** [`FR-INWARDRECEIVING-006`](../../../03_requirements/use_cases/uc-005-inward-receiving-goods-receipt/functional-reqs.md#fr-inwardreceiving-006-mandatory-lot--batch-identity-generation) +- **SRS Linkage:** `SRS-INWARDRECEIVING-006` +- **Architecture Contract:** `HLD-RECEIVING`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 3 (P0) +- **Assigned Roles:** Yard Supervisor, Quality Officer +- **Description:** Mint immutable lot identity for every inward consignment, creating the traceable entity for lab assay and stock accounting. +- **Acceptance Criteria:** + 1. Mints lot code following standard convention: `LOT-{MANDI}-{COMMODITY}-{YYYYMMDD}-{SEQ}`. + 2. Associates lot with owning GRN, source Sauda, commodity, variety, and net quantity MT. + 3. Initializes lot quality lifecycle state as `UNDER_QC`. + +--- + +### STORY-QC-001: Mandi Inward Lab Parameter Inspection & Grading +- **Parent Requirement:** [`FR-QUALITYANDLOTCONTROL-001`](../../../03_requirements/use_cases/uc-006-inward-quality-lot-control/functional-reqs.md#fr-qualityandlotcontrol-001-mandi-inward-sampling--parameterized-lab-inspection) +- **SRS Linkage:** `SRS-QUALITYANDLOTCONTROL-001` +- **Architecture Contract:** `HLD-QUALITY`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 5 (P0) +- **Assigned Roles:** Quality Officer +- **Description:** Capture laboratory assay results for physical samples: moisture %, foreign matter %, damaged/discolored grain %, and admixture %. +- **Acceptance Criteria:** + 1. Quality Officer logs lab test assay via `POST /api/v1/quality/inspections`. + 2. Validates percentage ranges: $0\% \le \text{parameter} \le 100\%$. + 3. Records sampling method (e.g., spear sample across 5 composite points) and testing apparatus ID. + 4. Determines composite quality grade (e.g. `GRADE_A_FAQ`, `GRADE_B`, `BELOW_FAQ`). + +--- + +### STORY-QC-002: Quality Hold / Released FSM State Machine Enforcement +- **Parent Requirement:** [`FR-QUALITYANDLOTCONTROL-002`](../../../03_requirements/use_cases/uc-006-inward-quality-lot-control/functional-reqs.md#fr-qualityandlotcontrol-002-quality-hold--released-fsm-state-machine) +- **SRS Linkage:** `SRS-QUALITYANDLOTCONTROL-002` +- **Architecture Contract:** `HLD-QUALITY`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 5 (P0) +- **Assigned Roles:** Quality Officer, Purchase Manager +- **Description:** Enforce strict finite state machine transitions for lot quality state (`UNDER_QC` $\to$ `RELEASED` or `QC_HOLD`), prohibiting inventory reservation for held lots. +- **Acceptance Criteria:** + 1. Only users with the `Quality Officer` role can issue release or hold decisions via `POST /api/v1/quality/lots/{lot_id}/decision`. + 2. Valid transitions: `UNDER_QC` $\to$ `RELEASED`, `UNDER_QC` $\to$ `QC_HOLD`, and `QC_HOLD` $\to$ `RELEASED` (requires Quality Officer sign-off). + 3. **Critical Invariant:** Any lot in `QC_HOLD` or `UNDER_QC` is strictly blocked from allocation, sales reservation, or dispatch. + 4. Segregation of Duties: Mandi Buyers and Yard Supervisors are prohibited from overriding QC decisions. + +--- + +### STORY-QC-003: Quality Deduction & Price Settlement Calculation +- **Parent Requirement:** [`FR-QUALITYANDLOTCONTROL-003`](../../../03_requirements/use_cases/uc-006-inward-quality-lot-control/functional-reqs.md#fr-qualityandlotcontrol-003-contractual-quality-deduction--price-settlement) +- **SRS Linkage:** `SRS-QUALITYANDLOTCONTROL-003` +- **Architecture Contract:** `HLD-QUALITY`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 3 (P1) +- **Assigned Roles:** Quality Officer, Accounts Executive +- **Description:** Compute commercial discounts and refraction deductions when received grain quality deviates from Sauda contract specifications. +- **Acceptance Criteria:** + 1. Compares moisture assay against contract baseline (e.g. baseline 12.0%; actual 14.5% = 2.5% excess moisture). + 2. Applies deduction formula: Moisture discount (1:1 or tiered scale) and Foreign matter refraction deduction. + 3. Derives Net Settled Rate per quintal: `Settled_Rate = Base_Rate - Total_Deductions`. + 4. Generates quality settlement sheet linked to GRN and supplier payable ledger. + +--- + +### STORY-QC-004: Lot Quality Lineage & Inspection Certificate Association +- **Parent Requirement:** [`FR-QUALITYANDLOTCONTROL-004`](../../../03_requirements/use_cases/uc-006-inward-quality-lot-control/functional-reqs.md#fr-qualityandlotcontrol-004-lot-quality-lineage--batch-genealogy) +- **SRS Linkage:** `SRS-QUALITYANDLOTCONTROL-004` +- **Architecture Contract:** `HLD-QUALITY`, [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md) +- **Story Points:** 3 (P1) +- **Assigned Roles:** Quality Officer, Yard Supervisor +- **Description:** Maintain traceable genealogy linking lot identity to lab inspection certificate, weighbridge tickets, gate pass, and source sauda. +- **Acceptance Criteria:** + 1. Generates digital Inspection Certificate `QC-CERT-YYYYMMDD-XXXX`. + 2. `GET /api/v1/quality/lots/{lot_id}/lineage` returns complete genealogy trace from source sauda to godown stack. + 3. Preserves immutable audit history of all inspections and state changes. + diff --git a/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_plan.md b/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_plan.md new file mode 100644 index 0000000..2c24e2b --- /dev/null +++ b/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_plan.md @@ -0,0 +1,67 @@ +# Iteration Plan — Iteration 03 (Mandi Market Desk, Sauda Procurement, Gate Inward & Quality Lot Control) + +| Field | Value | +|---|---| +| **Iteration** | `iteration-03` | +| **Slice Goal** | Deliver the end-to-end Mandi procurement, vehicle gate receiving, gross/tare weighment, atomic GRN posting, and lab quality inspection FSM across `UC-002`, `UC-004`, `UC-005`, and `UC-006`. | +| **Governed Standard** | UP-AI v1.5 Stage 10 Standard | +| **Parent Use Cases** | `UC-002`, `UC-004`, `UC-005`, `UC-006` | +| **Capacity** | 16 Stories (52 Story Points) | +| **Status** | In Planning (Stage 10 Planned) | +| **Version** | 1.0.0 | +| **Last CR** | none | + +--- + +## 1. Iteration Goal & Scope Summary + +Deliver the foundational **Inward Trading & Physical Procurement Pipeline (Procure-to-Receipt)** for the Agriculture Trading Backoffice (ATB). Building upon the multi-tenant control plane, PostgreSQL RLS, and RBAC established in Iterations 01 and 02, this slice operationalizes: + +1. **Daily Mandi Market Desk (`UC-002`):** + - Capture daily arrivals (MT) and modal/min/max rate ranges per mandi, commodity, and variety (`FR-MKT-001`, `FR-MKT-002`). + - Support explicit `Closed / Mandi Holiday` status without fabricating zero-quantity arrivals. +2. **Purchase Sauda Procurement Contracts (`UC-004`):** + - Mandi auction and direct purchase sauda booking with contracted quantity, base rate, delivery schedules, and counterparty metadata (`FR-PROCUREMENTCONTRACTS-002`). + - Modal rate price variance warning alert ($\pm 5\%$ threshold) guarding against rogue or off-market buying (`FR-PROCUREMENTCONTRACTS-001`). + - Supplier commercial terms and payment due date derivation (`FR-PROCUREMENTCONTRACTS-003`). + - Statutory Mandi Cess / Market Fee and rural development levy apportioning (`FR-PROCUREMENTCONTRACTS-004`). +3. **Inward Vehicle Receiving & Goods Receipt (`UC-005`):** + - Vehicle gate pass entry and e-Way bill document verification against booked Sauda (`FR-INWARDRECEIVING-001`). + - Weighbridge gross and tare weighment capture enforcing `gross > tare` invariant (`FR-INWARDRECEIVING-002`). + - Standard bag packaging tare deduction (*Bardana Katai*) and net MT calculation to 3 decimal places (`FR-INWARDRECEIVING-003`). + - Weighment tolerance and transit shortage verification against billed vendor weight (`FR-INWARDRECEIVING-004`). + - Atomic Goods Receipt Note (GRN) posting and warehouse stack placement (`FR-INWARDRECEIVING-005`). + - Mandatory unique lot and batch identity generation linked to GRN and Sauda (`FR-INWARDRECEIVING-006`). +4. **Inward Quality Inspection & Lot Control (`UC-006`):** + - Sampling and lab parameter analysis: moisture %, foreign matter %, damaged grain %, and admixture % (`FR-QUALITYANDLOTCONTROL-001`). + - Quality Hold / Released FSM state machine (`Under QC` $\to$ `Released` or `QC Hold`) preventing downstream allocation of uninspected or sub-standard grain (`FR-QUALITYANDLOTCONTROL-002`). + - Quality rebate and refraction deduction settlement against contractual sauda specs (`FR-QUALITYANDLOTCONTROL-003`). + - Lot quality lineage and inspection certificate association (`FR-QUALITYANDLOTCONTROL-004`). + +--- + +## 2. Demo & Acceptance Criteria + +Planned demo evidence for Iteration 03 review: +1. **Mandi Market Desk:** A Mandi Buyer records daily arrival observations (500 MT) and rate range (Min: ₹5,100, Modal: ₹5,350, Max: ₹5,600 / quintal) for Chana at Unjha Mandi. Rate validation rejects arithmetic anomalies (`min > modal`). +2. **Sauda Contract Booking:** A Purchase Manager books a Mandi Auction Sauda for 100 MT Chana at ₹5,400/quintal. System verifies rate against modal rate (within $\pm 5\%$), computes Mandi Cess (1.5% = ₹8,100), and records 15-day supplier credit terms. +3. **Gate Entry & Inward Weighbridge:** A Yard Supervisor enters vehicle arrival (Truck `MH-12-AB-1234`, e-Way Bill `123456789012`) against the Sauda. Gross weighment logs 28,450 kg; after unloading, Tare weighment logs 10,200 kg. System logs 18,250 kg raw weight, applies 350 bags * 1.0 kg bag tare (*bardana katai* = 350 kg), yielding 17.900 Net MT. +4. **Shortage & GRN Generation:** System checks against billed challan weight (18.000 MT); detects 0.100 MT transit shortage (within 1% tolerance); generates `GRN-2026-0001` and mints lot `LOT-UNJ-CHANA-20261012-001` allocated to Godown Stack `STK-WH1-A1`. +5. **Quality Assay & State Machine Decision:** A Quality Officer inspects sample from the lot: Moisture 11.2% (acceptable), Foreign Matter 1.5%. Officer approves lot transition from `UNDER_QC` to `RELEASED`. A secondary test demonstrates a high-moisture batch (16.5%) automatically flagged and placed on `QC_HOLD`, preventing sales reservation. +6. **Commercial Quality Deduction:** System applies moisture and refraction rebate formula against Sauda base rate, calculating net payable supplier rate. +7. **Quality & Coverage Compliance:** + - Backend domain/FSM coverage: $\ge 95.0\%$ + - Integration adapter coverage: $\ge 90.0\%$ + - Frontend components coverage: $\ge 80.0\%$ +8. **Gate 14.1 Artifact Density:** + - 21-sheet Excel QA Workbook with $\ge 20$ dense test cases across procurement, weighbridge, and QC categories. + - Git-versioned Bruno API collections (`.bru`) under `docs/api/bruno/procurement/`, `docs/api/bruno/receiving/`, and `docs/api/bruno/quality/`. + - Multi-path 4-dimension functional test models in `07_test_design/functional_test_cases/` for `UC-002`, `UC-004`, `UC-005`, and `UC-006`. + +--- + +## 3. Carried-Over Scope & Regression Debt + +- **Carried-over stories from previous iterations:** None. Iterations 01 and 02 are 100% delivered and E2E verified in live PostgreSQL 17 container infrastructure (`CKPT-021`). +- **Regression debt from `regression_test_cases.md`:** All 64 automated tests from Iterations 01 and 02 (OIDC Auth, RBAC 11 roles, Tenant Lifecycle FSM, PostgreSQL RLS, and Immutability Audit) are continuously executed on every test run. + diff --git a/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_surface_matrix.md b/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_surface_matrix.md new file mode 100644 index 0000000..eb8f750 --- /dev/null +++ b/04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_surface_matrix.md @@ -0,0 +1,59 @@ +# Iteration Delivery Surface Matrix — Iteration 03 + +| Field | Value | +|---|---| +| **Iteration** | `iteration-03` | +| **Governed Standard** | UP-AI v1.5 Stage 10 Standard | +| **Status** | Delivered (E2E Verified) | +| **Version** | 1.1.0 | +| **Last CR** | none | + +--- + +## 11-Dimension Delivery Surface Coverage + +| Story ID | Parent FR | Portal / Screen | Route | API Endpoint | DB Migration | Sandbox / Mock | Config / Secret | Test Scopes | Dev Owner | QA Owner | Surface Status | +|---|---|---|---|---|---|---|---|---|---|---|---| +| `STORY-MKT-001` | `FR-MKT-001` | Market Observations Screen | `/market/observations` | `POST /api/v1/market/observations`, `GET /api/v1/market/observations` | Table `market_observations` (Alembic `005_market_desk.py`) | `sandbox/market_mock.py` (Mandi arrivals) | none | Unit, API (Bruno), Browser E2E | `@backend-dev-alpha`, `@ui-dev-alpha` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-MKT-002` | `FR-MKT-002` | Daily Rates Entry Modal | `/market/rates` | `POST /api/v1/market/rates`, `GET /api/v1/market/rates/latest` | Schema: rate fields on `market_observations` | `sandbox/market_mock.py` (Price ranges) | none | Unit, Boundary (`min <= modal <= max`), API (Bruno) | `@backend-dev-alpha`, `@ui-dev-alpha` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-PROC-001` | `FR-PROCUREMENTCONTRACTS-002` | Sauda Booking Form & Register | `/procurement/sauda`, `/procurement/sauda/new` | `POST /api/v1/procurement/sauda`, `GET /api/v1/procurement/sauda` | Table `procurement_sauda` (Alembic `006_procurement_contracts.py`) | `sandbox/supplier_mock.py` | none | Unit, API (Bruno), Browser E2E, FSM Invariant | `@backend-dev-alpha`, `@ui-dev-alpha` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-PROC-002` | `FR-PROCUREMENTCONTRACTS-001` | Rate Variance Warning Banner | Sauda Form Modal `/procurement/sauda/new` | Integrated in `POST /api/v1/procurement/sauda` | none | Simulated modal benchmark rates | Price variance threshold (`VARIANCE_THRESHOLD_PCT=5.0`) | Unit, Boundary ($\pm 5\%$), Warning Alert | `@backend-dev-alpha`, `@ui-dev-alpha` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-PROC-003` | `FR-PROCUREMENTCONTRACTS-003` | Credit Terms & Due Date Panel | Sauda Commercials `/procurement/sauda/{id}` | Integrated in `POST /api/v1/procurement/sauda` | Schema: credit fields on `procurement_sauda` | Supplier payment profiles | none | Unit, Date arithmetic, FSM Invariant | `@backend-dev-alpha`, `@ui-dev-alpha` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-PROC-004` | `FR-PROCUREMENTCONTRACTS-004` | Mandi Cess & Levies Breakdown | Sauda Costing Section | Integrated in `POST /api/v1/procurement/sauda` | Schema: tax/cess fields on `procurement_sauda` | State APMC tax schedules | Mandi cess rate table | Unit, Decimal arithmetic, Boundary | `@backend-dev-alpha`, `@ui-dev-alpha` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-INW-001` | `FR-INWARDRECEIVING-001` | Gate Pass Entry Screen | `/receiving/gate-entry` | `POST /api/v1/receiving/gate-entries`, `GET /api/v1/receiving/gate-entries` | Table `inward_gate_entries` (Alembic `007_inward_receiving.py`) | Simulated vehicle arrival stream | none | Unit, API (Bruno), Browser E2E, e-Way validation | `@backend-dev-beta`, `@ui-dev-beta` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-INW-002` | `FR-INWARDRECEIVING-002` | Weighbridge Gross/Tare Logging | `/receiving/weighbridge` | `POST /api/v1/receiving/weighments`, `GET /api/v1/receiving/weighments/{id}` | Table `weighbridge_slips` (Alembic `007_inward_receiving.py`) | Offline weighbridge ticket emulator | none | Unit, Invariant (`gross > tare`), Boundary | `@backend-dev-beta`, `@ui-dev-beta` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-INW-003` | `FR-INWARDRECEIVING-003` | Packaging Tare (*Bardana*) Worksheet | Weighbridge Form Section | Integrated in `POST /api/v1/receiving/weighments` | Schema: tare fields on `weighbridge_slips` | Standard tare lookup table (Jute, HDPE) | Bag tare standards | Unit, Decimal 3-digit precision (NFR-001) | `@backend-dev-beta`, `@ui-dev-beta` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-INW-004` | `FR-INWARDRECEIVING-004` | Shortage Variance Indicator | Gate Entry Details `/receiving/gate-entry/{id}` | `POST /api/v1/receiving/gate-entries/{id}/verify-shortage` | Schema: shortage fields on `weighbridge_slips` | Billed vs actual weight variance generator | Shortage tolerance limit (`TOLERANCE_PCT=0.5`) | Unit, Boundary, Tolerance threshold checks | `@backend-dev-beta`, `@ui-dev-beta` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-INW-005` | `FR-INWARDRECEIVING-005` | Goods Receipt Note (GRN) View | `/receiving/grn`, `/receiving/grn/{id}` | `POST /api/v1/receiving/grn`, `GET /api/v1/receiving/grn` | Table `goods_receipt_notes` (Alembic `007_inward_receiving.py`) | Godown stack capacity fixtures | none | Unit, Transaction Atomicity, API (Bruno), Browser E2E | `@backend-dev-beta`, `@ui-dev-beta` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-INW-006` | `FR-INWARDRECEIVING-006` | Lot Identity Card & Badge View | GRN & Inventory Details `/inventory/lots` | Integrated in `POST /api/v1/receiving/grn` | Table `inventory_lots` (Alembic `008_quality_and_lots.py`) | Lot sequence generator | Lot naming pattern | Unit, Identity uniqueness, FSM Invariant | `@backend-dev-beta`, `@ui-dev-beta` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-QC-001` | `FR-QUALITYANDLOTCONTROL-001` | Inward Quality Assay Screen | `/quality/inspection/new`, `/quality/inspection/{id}` | `POST /api/v1/quality/inspections`, `GET /api/v1/quality/inspections` | Table `quality_inspections` (Alembic `008_quality_and_lots.py`) | Simulated lab parameter assays | none | Unit, Boundary ($0 \le \text{pct} \le 100$), API (Bruno) | `@backend-dev-gamma`, `@ui-dev-gamma` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-QC-002` | `FR-QUALITYANDLOTCONTROL-002` | Quality Decision Action Modal | Lot QC View `/quality/lots/{id}` | `POST /api/v1/quality/lots/{lot_id}/decision` | Schema: `qc_status` on `inventory_lots` | FSM transition test harness | none | Unit, FSM Invariant (`Hold` blocks dispatch), Security RBAC | `@backend-dev-gamma`, `@adversarial-tester` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-QC-003` | `FR-QUALITYANDLOTCONTROL-003` | Quality Rebate & Refraction Sheet | QC Settlement View `/quality/settlement/{id}` | `POST /api/v1/quality/inspections/{id}/calculate-deduction` | Schema: rebate fields on `quality_inspections` | Rebate scale rules | Moisture & refraction scale schedules | Unit, Decimal arithmetic, Boundary | `@backend-dev-gamma`, `@ui-dev-gamma` | `@adversarial-tester` | Delivered (E2E Verified) | +| `STORY-QC-004` | `FR-QUALITYANDLOTCONTROL-004` | Lot Genealogy & Certificate View | `/quality/lots/{lot_id}/certificate` | `GET /api/v1/quality/lots/{lot_id}/lineage` | Digital certificate record | Complete lineage test fixtures | Certificate template | Unit, Lineage traversal, API (Bruno) | `@backend-dev-gamma`, `@ui-dev-gamma` | `@adversarial-tester` | Delivered (E2E Verified) | + +--- + +## Surface Breakdown & Responsibilities + +1. **Frontend Portal / Screen Surfaces:** + - **Market Desk Observations (`STORY-MKT-001`, `002`):** React dashboard for Mandi Buyers to review and record daily mandi arrivals and price ranges. + - **Procurement Sauda Management (`STORY-PROC-001`..`004`):** React forms and registers for booking auction/direct sauda, checking price variance warnings, and reviewing commercial terms. + - **Gate Inward & Weighbridge (`STORY-INW-001`..`004`):** Yard operations UI for capturing vehicle gate entry, gross/tare weighbridge measurements, bag tare deduction, and shortage verification. + - **Goods Receipt Note & Lot Placement (`STORY-INW-005`, `006`):** Warehouse receiving UI for posting GRNs and reviewing minted lot identities with godown stack placements. + - **Quality Lab & Lot FSM (`STORY-QC-001`..`004`):** Quality Officer inspection workstation for logging moisture/foreign matter assays, enforcing QC Hold/Release transitions, and generating deduction sheets. +2. **Backend API Endpoints:** + - Market Desk APIs (`/api/v1/market/observations`, `/api/v1/market/rates`). + - Procurement Sauda APIs (`/api/v1/procurement/sauda`). + - Inward Gate & Weighbridge APIs (`/api/v1/receiving/gate-entries`, `/api/v1/receiving/weighments`, `/api/v1/receiving/grn`). + - Quality Lab & Decision APIs (`/api/v1/quality/inspections`, `/api/v1/quality/lots/{id}/decision`, `/api/v1/quality/lots/{id}/lineage`). +3. **Database & Migrations:** + - Alembic migration `005_market_desk.py`: `market_observations` table with RLS. + - Alembic migration `006_procurement_contracts.py`: `procurement_sauda` table with RLS. + - Alembic migration `007_inward_receiving.py`: `inward_gate_entries`, `weighbridge_slips`, `goods_receipt_notes` tables with RLS. + - Alembic migration `008_quality_and_lots.py`: `inventory_lots`, `quality_inspections` tables with RLS. +4. **Integration Sandboxes (Wave 0):** + - Deterministic Master Data fixtures in `sandbox/master_data_mock.py` pre-seeding Mandis, Commodities, Suppliers, and Godown Stacks. +5. **Quality Assurance Deliverables:** + - **Bruno Collections:** Version-controlled collections under `docs/api/bruno/market/`, `docs/api/bruno/procurement/`, `docs/api/bruno/receiving/`, and `docs/api/bruno/quality/`. + - **Excel QA Workbook:** 21-sheet manual QA workbook compiled with $\ge 20$ dense test cases across categories. + - **Multi-Path Automated Tests:** Happy Path, Boundary/Edge, Negative/Security, and FSM Invariant tests in `tests/backend/` and `tests/e2e/`. diff --git a/04_generated_documentation/05_iteration_planning/iterations/iteration-03/parallel_work_plan.md b/04_generated_documentation/05_iteration_planning/iterations/iteration-03/parallel_work_plan.md new file mode 100644 index 0000000..a00cd15 --- /dev/null +++ b/04_generated_documentation/05_iteration_planning/iterations/iteration-03/parallel_work_plan.md @@ -0,0 +1,111 @@ +# Parallel Work & Lane Isolation Plan — Iteration 03 + +| Field | Value | +|---|---| +| **Iteration** | `iteration-03` | +| **Governed Standard** | UP-AI v1.5 Standard | +| **Integration Skill** | `up-parallel-work-integrate` | +| **Status** | Approved for Construction | +| **Version** | 1.0.0 | +| **Last CR** | none | + +--- + +## 1. Wave 0 — Sandbox & Integration Scaffolding + +Before parallel application lanes commence development, Wave 0 establishes deterministic offline fixtures and mock master data to isolate lanes from external dependencies: + +| Adapter Component | Physical Path | Target Dependency | Mode | Owner | +|---|---|---|---|---| +| **Master Data Mock Adapter** | `sandbox/master_data_mock.py` | Mandi, Commodity & Counterparty Masters | Deterministic In-Memory Master Seeder | `@backend-dev-alpha` | +| **Weighbridge Ticket Mock Adapter** | `sandbox/weighbridge_mock.py` | Physical Weighbridge Indicator | Deterministic Weighment Slip Generator | `@backend-dev-beta` | + +- **Wave 0 Completion Criteria:** + 1. `sandbox/master_data_mock.py` pre-seeds standard Indian commodities (Chana, Soybean, Wheat, Mustard), market yards (Unjha Mandi, APMC Vashi, APMC Kota, APMC Latur), pre-seeded suppliers/arhatiyas, and warehouse godown chambers/stacks. + 2. `sandbox/weighbridge_mock.py` generates gross and tare weighment tickets simulating physical scale captures without external hardware. + +--- + +## 2. Lane Allocations & Isolation + +### Lane 1: Market Desk & Procurement Contracts (`lane/market-procurement`) +- **Assigned Stories:** `STORY-MKT-001`, `STORY-MKT-002`, `STORY-PROC-001`, `STORY-PROC-002`, `STORY-PROC-003`, `STORY-PROC-004` +- **Owners:** `@backend-dev-alpha`, `@ui-dev-alpha` +- **Allowed Scope / Paths:** + - `backend/app/market/` (Market observation controller, price range validator) + - `backend/app/procurement/` (Sauda contract controller, price variance evaluator, cess calculator) + - `backend/app/models/market.py`, `backend/app/models/procurement.py` + - `backend/alembic/versions/005_market_desk.py`, `backend/alembic/versions/006_procurement_contracts.py` + - `frontend/src/features/market/`, `frontend/src/features/procurement/` + - `tests/backend/test_market_*.py`, `tests/backend/test_procurement_*.py` +- **Shared Artifacts & Ownership:** `procurement_sauda` table schema and `GET /api/v1/procurement/sauda/{id}` contract (Single Owner: `@backend-dev-alpha`). +- **Required Contracts:** [`LLD-007`](../../../04_architecture_design/lld/LLD-007_market_observations.md), [`LLD-004`](../../../04_architecture_design/lld/LLD-004_financial_controls.md). +- **Dependencies:** Wave 0 Master Data fixtures; Iteration 02 TenantContext & RLS engine. +- **Completion Evidence:** Unit tests pass with $\ge 95\%$ coverage; Sauda contract state machine verified; price variance warning triggered on $\pm 5\%$ deviation. + +--- + +### Lane 2: Vehicle Gate Receiving & Weighbridge Inward (`lane/receiving-weighbridge`) +- **Assigned Stories:** `STORY-INW-001`, `STORY-INW-002`, `STORY-INW-003`, `STORY-INW-004`, `STORY-INW-005`, `STORY-INW-006` +- **Owners:** `@backend-dev-beta`, `@ui-dev-beta` +- **Allowed Scope / Paths:** + - `backend/app/receiving/` (Gate pass manager, weighbridge logger, bag tare deduction, GRN poster) + - `backend/app/models/receiving.py`, `backend/app/models/lot.py` + - `backend/alembic/versions/007_inward_receiving.py` + - `frontend/src/features/receiving/` (Gate pass view, weighbridge slip view, GRN view) + - `tests/backend/test_receiving_*.py`, `tests/backend/test_weighbridge_*.py` +- **Shared Artifacts & Ownership:** `goods_receipt_notes` table schema and `inventory_lots` creation contract (Single Owner: `@backend-dev-beta`). +- **Required Contracts:** [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md). +- **Dependencies:** Lane 1 `procurement_sauda` contract model. +- **Completion Evidence:** Gross > Tare invariant verified; bag tare (*bardana katai*) deduction calculates 3-decimal net MT; atomic GRN posting mints unique lot code. + +--- + +### Lane 3: Quality Lab Assays & Lot FSM State Machine (`lane/quality-lot-fsm`) +- **Assigned Stories:** `STORY-QC-001`, `STORY-QC-002`, `STORY-QC-003`, `STORY-QC-004` +- **Owners:** `@backend-dev-gamma`, `@ui-dev-gamma` +- **Allowed Scope / Paths:** + - `backend/app/quality/` (Inspection assay recorder, lot FSM decision engine, rebate calculator, lineage resolver) + - `backend/app/models/quality.py` + - `backend/alembic/versions/008_quality_and_lots.py` + - `frontend/src/features/quality/` (Assay logging form, QC decision modal, rebate sheet, certificate view) + - `tests/backend/test_quality_*.py` +- **Shared Artifacts & Ownership:** `quality_inspections` schema and lot QC state transition event (Single Owner: `@backend-dev-gamma`). +- **Required Contracts:** [`LLD-003`](../../../04_architecture_design/lld/LLD-003_receiving_quality_inventory.md). +- **Dependencies:** Lane 2 `inventory_lots` model. +- **Completion Evidence:** Strict FSM transitions verified (`UNDER_QC` $\to$ `RELEASED` / `QC_HOLD`); lots in `QC_HOLD` strictly reject sales allocation; rebate formulas compute net settled rate. + +--- + +### Lane Q: Quality Assurance & Adversarial Testing (`lane/adversarial-qa`) +- **Assigned Stories:** Cross-cutting verification across all 16 stories +- **Owner:** `@adversarial-tester` +- **Deliverables:** + - Git-versioned Bruno collections under `docs/api/bruno/market/`, `procurement/`, `receiving/`, `quality/`. + - 21-sheet Excel QA Workbook with $\ge 20$ dense test cases across procurement, weighment, and QC. + - Multi-path functional test models (`TC-002`, `TC-004`, `TC-005`, `TC-006`). + - Automated integration and regression test runner execution. + +--- + +## 3. Merge & Integration Order + +To prevent circular dependencies and interface breakage, lanes merge into master in the following strict order: + +```mermaid +flowchart TD + W0["Wave 0: Master Data & Weighbridge Mocks"] --> L1["Lane 1: Market & Procurement Sauda"] + L1 --> L2["Lane 2: Gate Inward, Weighbridge & GRN"] + L2 --> L3["Lane 3: Quality Assays & Lot FSM"] + L1 --> LQ["Lane Q: QA Models & Bruno Collections"] + L2 --> LQ + L3 --> LQ + LQ --> G14["Gate 14.1 Final Exit & Checkpoint"] +``` + +1. **Step 1:** Merge Wave 0 (`sandbox/master_data_mock.py`). +2. **Step 2:** Merge Lane 1 (`lane/market-procurement`), verifying `procurement_sauda` creation. +3. **Step 3:** Merge Lane 2 (`lane/receiving-weighbridge`), validating GRN generation against Lane 1 Sauda. +4. **Step 4:** Merge Lane 3 (`lane/quality-lot-fsm`), validating QC FSM decisions against Lane 2 lots. +5. **Step 5:** Merge Lane Q (`lane/adversarial-qa`), running the complete automated test suite and Gate 14.1 verification. + diff --git a/04_generated_documentation/06_wireframes/screen_specs/SCREEN-INW-001_gate_entry.md b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-INW-001_gate_entry.md new file mode 100644 index 0000000..39eab5e --- /dev/null +++ b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-INW-001_gate_entry.md @@ -0,0 +1,120 @@ +# Screen Specification: SCREEN-INW-001 — Vehicle Gate Entry Register & Yard Inward + +| Field | Value | +|---|---| +| **Screen ID** | `SCREEN-INW-001` | +| **Client Application ID** | `atb-web-portal` | +| **Frontend Route** | `/receiving/gate-entry`, `/receiving/gate-entry/new`, `/receiving/gate-entry/:id` | +| **Owning Use Case** | [`UC-005` (Inward Gate Entry, Weighbridge, GRN and Lot Minting)](../../03_requirements/use_cases/uc-005-inward-receiving/use-case.md) | +| **Owning FR** | [`FR-INWARDRECEIVING-001` (Inward Vehicle Gate Entry & Verification)](../../03_requirements/use_cases/uc-005-inward-receiving/functional-reqs.md#fr-inwardreceiving-001-inward-vehicle-gate-entry--verification), [`FR-INWARDRECEIVING-004` (Weighment Tolerance & Transit Shortage Verification)](../../03_requirements/use_cases/uc-005-inward-receiving/functional-reqs.md#fr-inwardreceiving-004-weighment-tolerance--transit-shortage-verification) | +| **Auth Role / Scope Claims** | `Security Guard`, `Gate Operator`, `Warehouse Clerk`, `Tenant Admin` | +| **Iteration** | `iteration-03` | +| **Status** | Baselined for Construction | + +--- + +## 1. Screen Overview & Archetype + +- **Archetype:** Security Gatehouse Dispatch Console & Yard Queue Register. +- **Visual Design Reference:** High-contrast touch-friendly interface following [`DESIGN.md`](../DESIGN.md) (`agri-700` action buttons, large readable input fields, quick license plate scanners). +- **Behavior:** Security guards and yard operators log arriving trucks carrying agricultural produce. The operator captures vehicle registration number (Indian format: e.g. `RJ-20-GA-1234`), 12-digit e-Way bill number, driver details, supplier dispatch invoice weight and bag count, and links to an active Purchase Sauda contract. The system validates e-Way bill format, verifies that the referenced Sauda is open, issues an Inward Gate Pass Slip, and places the truck into the weighbridge gross queue. + +--- + +## 2. Wireframe Layout + +``` ++------------------------------------------------------------------------------------------------------------------------+ +| [Logo] ATB Yard Receiving | Facility: [ Kota Central Warehouse v ] | [+ New Gate Entry] | [Gate Officer v] | ++-----------------------------+------------------------------------------+----------------------+------------------------+ +| [Navigation] | Active Yard Vehicle Queue (12 Trucks in Yard) | +| - Gate Entry (Active) +------------------------------------------------------------------------------------------+ +| - Weighbridge Gross/Tare | Status: [ All Yard States v ] Search Vehicle: [ RJ-20-GA... ] Refresh: [Live] | +| - GRN & Lot Placement +------------------------------------------------------------------------------------------+ +| - Quality Sampling | Gate Pass No | Vehicle No | Supplier / Sauda | Commodity | Billed MT | Gate In Time | Status | Action | +| |--------------+---------------+----------------------+-----------+-----------+--------------+------------+----------| +| | GP-26-00381 | RJ-20-GA-4581 | SDA-26-00142 (Kisan) | Soyabean | 25.00 MT | 10:15 AM | Gross Done | [Tare] | +| | GP-26-00382 | MP-09-AB-9821 | SDA-26-00142 (Kisan) | Soyabean | 25.00 MT | 10:45 AM | At Gate | [Gross] | +| | GP-26-00383 | GJ-14-CC-1102 | SDA-26-00143 (Mewar) | Cumin | 20.00 MT | 11:20 AM | Lab Sampling[Hold] | +| +------------------------------------------------------------------------------------------+ +| | Summary: Vehicles in Yard: 8 | Awaiting Gross: 2 | Awaiting Tare: 3 | Unloaded: 3 | ++-----------------------------+------------------------------------------------------------------------------------------+ +``` + +### New Vehicle Gate Entry Modal (`/receiving/gate-entry/new`) + +``` ++-----------------------------------------------------------------------------------+ +| Generate Inward Vehicle Gate Pass [X] | ++-----------------------------------------------------------------------------------+ +| Gate Entry Date/Time*: [ 2026-10-12 11:30 AM ] (Auto-stamped) | +| Vehicle Number*: [ RJ-20-GA-4581 ] (Format: SS-NN-AA-NNNN) | +| 12-Digit e-Way Bill*: [ 241089201923 ] (12 Numeric Digits) | +| | +| Driver Full Name*: [ Ramesh Singh Chandel ] | +| Driver Mobile Number*: [ 9829012345 ] (10 Digits) | +| | +| --- Commercial Linkage & Dispatch Documents ------------------------------------ | +| Purchase Sauda Contract*: [ SDA-26-00142 - Kisan Agro Traders (Soyabean) v ]| +| Commodity / Variety: Soyabean (Yellow Desi FAQ) — Contract Bal: 50.00 MT | +| Supplier Invoice Number*: [ INV-2026-9042 ] | +| Supplier Dispatch Weight*:[ 25.000 MT ] (Billed Net Metric Tonnes) | +| Supplier Dispatch Bags*: [ 500 Bags ] (Billed Packaging Units) | +| | +| Security Seal Intact?*: [x] Yes, physical seal is intact and verified. | +| | +| [ Print Gate Pass Slip ] [ Confirm Yard Entry -> ] | ++-----------------------------------------------------------------------------------+ +``` + +--- + +## 3. Field-Level Specification + +| Field Name | Data Type | UI Control | Validation Rules | Source FR | Backend Processing Expectation | +|---|---|---|---|---|---| +| `gate_pass_number`| `String(32)` | Read-only Display | Auto-generated `GP-YY-XXXXX`. | `FR-INWARDRECEIVING-001` | Unique sequence per tenant. | +| `gate_in_timestamp`| `Timestamp` | System Auto-stamp | Current UTC timestamp. | `FR-INWARDRECEIVING-001` | Audit timestamp. | +| `vehicle_number` | `String(16)` | Text Input (Uppercase) | Mandatory. Regex `^[A-Z]{2}[0-9]{2}[A-Z]{1,3}[0-9]{4}$`. | `FR-INWARDRECEIVING-001` | Normalized license plate. | +| `eway_bill_number`| `String(12)` | Numeric Text | Mandatory for commercial loads. 12 digits. | `FR-INWARDRECEIVING-001` | Validated against GST rules. | +| `driver_name` | `String(100)` | Text Input | Mandatory. Non-empty string. | `FR-INWARDRECEIVING-001` | Driver identification. | +| `driver_mobile` | `String(10)` | Numeric Input | Mandatory. 10 digits starting with `6-9`. | `FR-INWARDRECEIVING-001` | Driver contact for yard paging. | +| `sauda_id` | `UUID` | Select Dropdown / Search | Mandatory. Must reference `ACTIVE` sauda. | `FR-INWARDRECEIVING-001` | Foreign key to `procurement_sauda`. | +| `supplier_invoice_no`| `String(64)` | Text Input | Mandatory. Non-empty string. | `FR-INWARDRECEIVING-001` | Cross-referenced against invoice. | +| `supplier_dispatch_weight_mt`| `Decimal(12,3)` | Numeric Input | Mandatory. `weight > 0.000`. | `FR-INWARDRECEIVING-001` | Baseline for transit shortage. | +| `supplier_dispatch_bags`| `Integer` | Integer Input | Mandatory. `bags > 0`. | `FR-INWARDRECEIVING-001` | Packaging reconciliation. | +| `is_seal_intact` | `Boolean` | Checkbox / Toggle | Mandatory. Must be acknowledged. | `FR-INWARDRECEIVING-001` | Physical security inspection. | +| `gate_status` | `Enum` | Status Badge | `GATE_IN`, `WEIGHED_GROSS`, `UNLOADING`, `WEIGHED_TARE`, `GRN_ISSUED`, `GATE_OUT`. | `FR-INWARDRECEIVING-001` | Yard FSM lifecycle tracking. | + +--- + +## 4. State Guards & Error Handling + +1. **Active Sauda Verification Guard:** + - Dropdown displays only `ACTIVE` or `PARTIALLY_RECEIVED` contracts matching the incoming commodity. Closed or cancelled contracts cannot be selected. +2. **e-Way Bill Verification Guard:** + - Must be 12 numeric digits. If invalid length or format, UI highlights error: `"Invalid e-Way bill number (12 digits required)"`. +3. **Vehicle Yard Duplication Guard:** + - If `vehicle_number` currently has an active yard pass that has not reached `GATE_OUT`, system alerts: `"Vehicle is already inside yard under Gate Pass GP-xxx"`. +4. **Shortage Warning Trigger (`FR-INWARDRECEIVING-004`):** + - When weighbridge net weight deviates from `supplier_dispatch_weight_mt` by $> 0.5\%$, system flags shortage exception and requires warehouse supervisor clearance. + +--- + +## 5. Authorization & Permissions + +- **Client App ID:** `atb-web-portal` +- **Route Path:** `/receiving/gate-entry` +- **Required Roles:** + - `Security Guard`, `Gate Operator`, `Warehouse Clerk`, `Tenant Admin`: Full Create and Edit. + - `Procurement Officer`, `Accounts Executive`: Read-only. +- **Tenant Isolation:** Enforced via `X-Tenant-ID` header and PostgreSQL RLS on `inward_gate_entries`. + +--- + +## 6. API Integration Points + +- `GET /api/v1/receiving/gate-entries`: List active and historical gate entries. +- `POST /api/v1/receiving/gate-entries`: Generate new vehicle gate entry pass. +- `GET /api/v1/receiving/gate-entries/{id}`: Detailed entry pass status with weighbridge linkages. + diff --git a/04_generated_documentation/06_wireframes/screen_specs/SCREEN-INW-002_weighbridge_grn.md b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-INW-002_weighbridge_grn.md new file mode 100644 index 0000000..d50e285 --- /dev/null +++ b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-INW-002_weighbridge_grn.md @@ -0,0 +1,139 @@ +# Screen Specification: SCREEN-INW-002 — Weighbridge Gross/Tare Logging, Bag Tare & GRN Posting + +| Field | Value | +|---|---| +| **Screen ID** | `SCREEN-INW-002` | +| **Client Application ID** | `atb-web-portal` | +| **Frontend Route** | `/receiving/weighbridge`, `/receiving/grn`, `/receiving/grn/:id` | +| **Owning Use Case** | [`UC-005` (Inward Gate Entry, Weighbridge, GRN and Lot Minting)](../../03_requirements/use_cases/uc-005-inward-receiving/use-case.md) | +| **Owning FR** | [`FR-INWARDRECEIVING-002` (Weighbridge Gross & Tare Weighment Logging)](../../03_requirements/use_cases/uc-005-inward-receiving/functional-reqs.md#fr-inwardreceiving-002-weighbridge-gross--tare-weighment-logging), [`FR-INWARDRECEIVING-003` (Bag Tare Deduction (*Bardana Katai*) & Final Net MT)](../../03_requirements/use_cases/uc-005-inward-receiving/functional-reqs.md#fr-inwardreceiving-003-bag-tare-deduction-bardana-katai--final-net-mt), [`FR-INWARDRECEIVING-005` (Goods Receipt Note (GRN) Posting & Warehouse Stack Placement)](../../03_requirements/use_cases/uc-005-inward-receiving/functional-reqs.md#fr-inwardreceiving-005-goods-receipt-note-grn-posting--warehouse-stack-placement), [`FR-INWARDRECEIVING-006` (Mandatory Lot & Batch Identity Generation)](../../03_requirements/use_cases/uc-005-inward-receiving/functional-reqs.md#fr-inwardreceiving-006-mandatory-lot--batch-identity-generation) | +| **Auth Role / Scope Claims** | `Weighbridge Operator`, `Warehouse Supervisor`, `Warehouse Clerk`, `Tenant Admin` | +| **Iteration** | `iteration-03` | +| **Status** | Baselined for Construction | + +--- + +## 1. Screen Overview & Archetype + +- **Archetype:** Industrial Weighbridge Scale Terminal & Warehouse Goods Receipt / Lot Stacking Console. +- **Visual Design Reference:** High-density operator UI following [`DESIGN.md`](../DESIGN.md) (`agri-700` primary buttons, prominent numeric display for weight digits, `grain-100` background). +- **Behavior:** Captures gross weighment upon arrival and tare weighment after unloading. Automatically calculates gross minus tare. Prompts for bag packaging type (Jute 50kg, HDPE 50kg, Loose bulk) and bag count to compute packaging tare (*Bardana Katai*) with 3-decimal metric tonne precision (NFR-001). Upon tare completion, supervisor reviews transit shortage vs. dispatch invoice, assigns physical warehouse godown stack, posts the Goods Receipt Note (GRN), and generates the unique traceable lot identity (`LOT-YY-MM-COMM-XXXXX`). + +--- + +## 2. Wireframe Layout + +``` ++------------------------------------------------------------------------------------------------------------------------+ +| [Logo] ATB Weighbridge Terminal | Scale Status: [ ONLINE - ComPort 3 ] | [Manual Weight Override] | [Weighman User v] | ++----------------------------------+--------------------------------------+--------------------------+-------------------+ +| [Navigation] | Weighbridge Operations & Inward Settlement Console | +| - Gate Entry +-------------------------------------------------------------------------------------+ +| - Weighbridge (Active) | Active Truck on Scale: [ GP-26-00381 | RJ-20-GA-4581 | Kisan Agro Traders v ]| +| - GRN Register +-------------------------------------------------------------------------------------+ +| - Quality Lab | | +| - Inventory Lots | +------------------------------------+ +----------------------------------------+ | +| | | LIVE SCALE INDICATOR (Metric Ton)| | TRUCK & COMMERCIAL CONTEXT | | +| | | | | Gate Pass: GP-26-00381 | | +| | | 38.450 MT | | Sauda: SDA-26-00142 (Soyabean) | | +| | | [ STABLE ] [ ZERO ] [ TARE ] | | Supplier: Kisan Agro Traders | | +| | +------------------------------------+ | Billed Wt: 25.000 MT (500 Bags) | | +| | +----------------------------------------+ | +| +-------------------------------------------------------------------------------------+ +| | Weighment Slip Generation & Bag Tare Deduction (Bardana Katai) | +| | - Gross Weighment: 38.450 MT Logged At: 2026-10-12 10:22 AM | +| | - Tare Weighment: 13.200 MT Logged At: 2026-10-12 11:15 AM | +| | - Unloaded Net Wt: 25.250 MT (Gross - Tare) | +| | | +| | Packaging Type: [ 50kg New Jute Gunny (0.650 kg/bag) v ]| +| | Physical Bags Counted: [ 500 ] Bag Tare Deduction: 0.325 MT (500 * 0.650 kg) | +| | FINAL NET REVENUE WEIGHT: 24.925 MT | +| | Transit Shortage: -0.075 MT (-0.30% — within 0.50% tolerance) | +| +-------------------------------------------------------------------------------------+ +| | [ Print Weight Slip ] [ Post GRN & Mint Lot Identity -> ] | ++----------------------------------+-------------------------------------------------------------------------------------+ +``` + +### GRN Posting & Warehouse Stack Placement Modal + +``` ++-----------------------------------------------------------------------------------+ +| Post Goods Receipt Note (GRN) & Mint Lot Identity [X] | ++-----------------------------------------------------------------------------------+ +| Gate Pass / Weighment: GP-26-00381 / WS-26-00214 | +| Purchase Sauda Contract: SDA-26-00142 (Kisan Agro Traders - Soyabean) | +| Final Net Accepted MT: 24.925 MT (500 Jute Bags) | +| | +| --- Warehouse Location & Stack Placement --------------------------------------- | +| Warehouse / Godown*: [ Godown 02 - Kota Central Warehouse v ]| +| Godown Stack / Bay*: [ Stack B-04 (Capacity: 100 MT | Current: 45 MT) v ]| +| Stack Condition*: [ Dry, Fumigated, Palletized v ]| +| | +| --- Generated Traceable Lot Identity ------------------------------------------- | +| Minted Lot Number: LOT-26-10-SOY-00084 (Auto-generated) | +| Initial Quality Status: [ QUALITY_HOLD (Pending Lab Assay) v ]| +| | +| [!] Note: Produce is placed under Quality Hold until Lab Chemist completes | +| moisture, foreign matter, and refraction testing. | +| | +| [ Cancel ] [ Confirm & Post GRN -> ] | ++-----------------------------------------------------------------------------------+ +``` + +--- + +## 3. Field-Level Specification + +| Field Name | Data Type | UI Control | Validation Rules | Source FR | Backend Processing Expectation | +|---|---|---|---|---|---| +| `slip_number` | `String(32)` | Read-only Display | Auto-generated `WS-YY-XXXXX`. | `FR-INWARDRECEIVING-002` | Unique sequence per tenant. | +| `gate_pass_id` | `UUID` | Select Combobox | Mandatory. Active gate entry in yard. | `FR-INWARDRECEIVING-002` | Foreign key to `inward_gate_entries`. | +| `gross_weight_mt`| `Decimal(12,3)`| Numeric Display/Input| Mandatory. `gross_weight_mt > 0.000`. | `FR-INWARDRECEIVING-002` | Scale weight with 3 decimals. | +| `tare_weight_mt` | `Decimal(12,3)`| Numeric Display/Input| Mandatory. `tare_weight_mt > 0.000` and `< gross_weight_mt`.| `FR-INWARDRECEIVING-002` | Empty truck weight with 3 decimals. | +| `unloaded_weight_mt`| `Decimal(12,3)`| Read-only Display| Computed: `gross_weight_mt - tare_weight_mt`. | `FR-INWARDRECEIVING-002` | Gross product weight. | +| `bag_packaging_type`| `Enum` | Select Dropdown | `JUTE_GUNNY_NEW`, `JUTE_GUNNY_OLD`, `HDPE_PLASTIC`, `BULK_LOOSE`. | `FR-INWARDRECEIVING-003` | Determines per-bag tare deduction. | +| `bag_tare_rate_kg` | `Decimal(6,3)` | Numeric Input | Pre-populated based on type (e.g. 0.650 kg). | `FR-INWARDRECEIVING-003` | Weight per bag in kilograms. | +| `actual_bag_count` | `Integer` | Integer Input | Mandatory. `actual_bag_count >= 0`. | `FR-INWARDRECEIVING-003` | Physical unloaded bag count. | +| `bag_tare_deduction_mt`| `Decimal(12,3)`| Read-only Display| Computed: `(actual_bag_count * bag_tare_rate_kg) / 1000.0`. | `FR-INWARDRECEIVING-003` | *Bardana Katai* in metric tonnes. | +| `final_net_weight_mt`| `Decimal(12,3)`| Read-only Display| Computed: `unloaded_weight_mt - bag_tare_deduction_mt`. | `FR-INWARDRECEIVING-003` | Final commercial billing net weight. | +| `shortage_weight_mt` | `Decimal(12,3)`| Read-only Display| Computed: `final_net_weight_mt - billed_weight_mt`. | `FR-INWARDRECEIVING-004` | Variance against supplier invoice. | +| `shortage_pct` | `Decimal(5,2)` | Computed Badge | Computed: `(shortage_weight_mt / billed_weight_mt) * 100`. | `FR-INWARDRECEIVING-004` | Threshold check vs tolerance (0.50%). | +| `grn_number` | `String(32)` | Read-only Display | Auto-generated `GRN-YY-XXXXX`. | `FR-INWARDRECEIVING-005` | Formal Goods Receipt Note number. | +| `godown_id` | `UUID` | Select Dropdown | Mandatory. Active warehouse godown. | `FR-INWARDRECEIVING-005` | Warehouse master reference. | +| `godown_stack_id` | `UUID` | Select Dropdown | Mandatory. Active stack bay with capacity. | `FR-INWARDRECEIVING-005` | Specific physical stack location. | +| `lot_number` | `String(32)` | Read-only Display | Auto-generated `LOT-YY-MM-COMM-XXXXX`. | `FR-INWARDRECEIVING-006` | Traceable lot identity token. | +| `lot_initial_status`| `Enum` | Status Pill | Default `QUALITY_HOLD`. | `FR-INWARDRECEIVING-006` | Blocks dispatch until QC release. | + +--- + +## 4. State Guards & Error Handling + +1. **Scale Invariant Guard (`gross > tare`):** + - Tare weighment cannot exceed or equal gross weighment. Attempting to record tare $\ge$ gross returns validation error: `"Tare weight must be strictly less than Gross weight"`. +2. **Transit Shortage Tolerance Check (`FR-INWARDRECEIVING-004`):** + - If transit shortage exceeds standard tolerance ($> 0.5\%$), system highlights red alert banner and records supervisor acknowledgment before GRN can be posted. +3. **Lot Identity Immutability:** + - Once generated, `lot_number` is permanently linked to the GRN, weighment slip, gate entry, and sauda contract. +4. **Mandatory Quality Hold Default:** + - Newly minted lots automatically initialize in `QUALITY_HOLD` state. Dispatch or blending cannot be performed until released by Quality Lab. + +--- + +## 5. Authorization & Permissions + +- **Client App ID:** `atb-web-portal` +- **Route Path:** `/receiving/weighbridge`, `/receiving/grn` +- **Required Roles:** + - `Weighbridge Operator`: Create & Edit Weighment Slips. + - `Warehouse Supervisor`, `Warehouse Manager`, `Tenant Admin`: Post GRN & Assign Stacks. + - `Accounts Executive`: Read-only. +- **Tenant Isolation:** Enforced via `X-Tenant-ID` header and PostgreSQL RLS on `weighbridge_slips` and `goods_receipt_notes`. + +--- + +## 6. API Integration Points + +- `GET /api/v1/receiving/weighments`: List weighment slips. +- `POST /api/v1/receiving/weighments`: Create gross/tare weighment and bag tare calculations. +- `POST /api/v1/receiving/grn`: Atomically post GRN, mint lot identity, and allocate warehouse stack. + diff --git a/04_generated_documentation/06_wireframes/screen_specs/SCREEN-MKT-001_market_desk.md b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-MKT-001_market_desk.md new file mode 100644 index 0000000..6f66348 --- /dev/null +++ b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-MKT-001_market_desk.md @@ -0,0 +1,123 @@ +# Screen Specification: SCREEN-MKT-001 — Market Observations & Daily Rate Bulletin + +| Field | Value | +|---|---| +| **Screen ID** | `SCREEN-MKT-001` | +| **Client Application ID** | `atb-web-portal` | +| **Frontend Route** | `/market/observations`, `/market/rates` | +| **Owning Use Case** | [`UC-002` (Record Daily Mandi Arrivals and Prices)](../../03_requirements/use_cases/uc-002-market-desk-observations/use-case.md) | +| **Owning FR** | [`FR-MKT-001` (Capture Daily Mandi Arrival Observations)](../../03_requirements/use_cases/uc-002-market-desk-observations/functional-reqs.md#fr-mkt-001-capture-daily-mandi-arrival-observations), [`FR-MKT-002` (Capture Daily Mandi Price Range and Modal Rate)](../../03_requirements/use_cases/uc-002-market-desk-observations/functional-reqs.md#fr-mkt-002-capture-daily-mandi-price-range-and-modal-rate) | +| **Auth Role / Scope Claims** | `Mandi Buyer`, `Desk Trader`, `Procurement Officer`, `Tenant Admin` | +| **Iteration** | `iteration-03` | +| **Status** | Baselined for Construction | + +--- + +## 1. Screen Overview & Archetype + +- **Archetype:** Market Intelligence Blotter & Daily Rate Recording Console. +- **Visual Design Reference:** Tailwind CSS / shadcn-ui components following [`DESIGN.md`](../DESIGN.md) (`agri-700` primary buttons, `grain-100` card headers, `slate-900` text). +- **Behavior:** Authorized Mandi Buyers and Desk Traders monitor and record daily arrivals (in MT) and APMC auction rates (Min, Max, Modal rate in ₹/Qtl) for key monitored mandis across commodities (Wheat, Chana, Mustard, Soyabean, etc.). The console prevents duplicate entries for the same mandi/commodity/variety/date, prevents future observation dates, supports flagging market closure/holidays, and computes arrival variance against internal stock position. + +--- + +## 2. Wireframe Layout + +``` ++------------------------------------------------------------------------------------------------------------------------+ +| [Logo] ATB Mandi Desk | Mandi: [ Kota APMC v ] | Date: [ 2026-10-12 ] | [+ Record Observation] | [Trader User v] | ++--------------------------+---------------------------------------------------+--------------------------+--------------+ +| [Navigation] | Daily Mandi Arrival & Price Bulletin (Kota APMC - 2026-10-12) | +| - Market Desk (Active) +---------------------------------------------------------------------------------------------+ +| - Sauda Booking | Filter: [ All Commodities v ] [ Active Only v ] Search: [____________] Export: [CSV] | +| - Gate Receiving +---------------------------------------------------------------------------------------------+ +| - Weighbridge / GRN | Commodity | Variety | Grade | Arrivals (MT) | Min Rate | Max Rate | Modal Rate | Status | Action | +| - Quality Lab |-----------+-----------+-------+---------------+----------+----------+------------+-----------+--------| +| - Inventory Lots | Soyabean | Yellow | FAQ | 450.00 MT | ₹ 4,450 | ₹ 4,780 | ₹ 4,620 | Published | [Edit] | +| | Chana | Desi Bold | FAQ | 280.00 MT | ₹ 5,800 | ₹ 6,150 | ₹ 6,000 | Published | [Edit] | +| | Mustard | 42% Oil | FAQ | 620.00 MT | ₹ 5,200 | ₹ 5,550 | ₹ 5,400 | Published | [Edit] | +| | Wheat | Lokwan | FAQ | 0.00 MT | - | - | - | [Holiday] | [View] | +| +---------------------------------------------------------------------------------------------+ +| | Summary: Total Arrivals Today = 1,350.00 MT | Monitored Commodities = 4 | Open Markets = 3 | ++--------------------------+---------------------------------------------------------------------------------------------+ +``` + +### Record Observation & Rates Modal Dialog + +``` ++-------------------------------------------------------------------------------+ +| Record Mandi Daily Observation & Rates [X] | ++-------------------------------------------------------------------------------+ +| Monitored Mandi Yard*: [ Kota APMC, Rajasthan v ]| +| Observation Date*: [ 2026-10-12 (Today) v ]| +| Market Status*: (o) Open / Normal Auction ( ) Closed / Holiday | +| | +| Commodity*: [ Soyabean v ]| +| Variety*: [ Yellow Desi v ]| +| Commercial Grade*: [ FAQ (Fair Average Quality) v ]| +| | +| Arrival Quantity (MT)*: [ 450.000 ] | +| Internal Stock Position(MT): [ 120.000 ] (Read-only / System computed) | +| Observation Source*: [ APMC Yard Bulletin v ]| +| | +| --- Price Range (₹ / Quintal) --------------------------------------------- | +| Minimum Auction Rate (₹)*: [ 4450.00 ] | +| Maximum Auction Rate (₹)*: [ 4780.00 ] | +| Modal Clearing Rate (₹)*: [ 4620.00 ] | +| Validation Check: [✓ Min (4450) <= Modal (4620) <= Max (4780)] | +| | +| [ Cancel ] [ Save & Publish Rates -> ] | ++-------------------------------------------------------------------------------+ +``` + +--- + +## 3. Field-Level Specification + +| Field Name | Data Type | UI Control | Validation Rules | Source FR | Backend Processing Expectation | +|---|---|---|---|---|---| +| `mandi_id` | `UUID` | Select Dropdown | Mandatory. Must exist in `mandi_yards` master. | `FR-MKT-001` | Foreign key to tenant/platform mandi yards. | +| `observation_date` | `Date` | Datepicker | Mandatory. `date <= CURRENT_DATE` (No future dates). | `FR-MKT-001` | Indexed date attribute. | +| `is_market_closed` | `Boolean` | Radio / Toggle | Optional. Default `false`. | `FR-MKT-001` | If `true`, arrival and price inputs are optional/zeroed. | +| `commodity_id` | `UUID` | Select Dropdown | Mandatory. Active commodity in master. | `FR-MKT-001` | Foreign key to `commodities`. | +| `variety` | `String(64)` | Select / Combobox | Mandatory. Non-empty string. | `FR-MKT-001` | Natural variety descriptor. | +| `grade` | `String(32)` | Select Dropdown | Mandatory. Default `FAQ`. | `FR-MKT-001` | Commercial grade. | +| `arrival_mt` | `Decimal(12,3)` | Numeric Input | Mandatory if open. `arrival_mt >= 0.000`. | `FR-MKT-001` | Validated in MT with 3 decimal precision. | +| `internal_stock_mt`| `Decimal(12,3)` | Read-only Display | System-computed from warehouse inventory. | `FR-MKT-001` | Pre-fetched snapshot of current tenant stock. | +| `source` | `Enum` | Select Dropdown | One of `APMC_BULLETIN`, `TRADER_ESTIMATE`, `PORTAL_FEED`. | `FR-MKT-001` | Recorded in audit trail. | +| `min_rate` | `Decimal(10,2)` | Currency Input | Mandatory if open. `min_rate > 0.00`. | `FR-MKT-002` | Validated against rate bounds. | +| `max_rate` | `Decimal(10,2)` | Currency Input | Mandatory if open. `max_rate >= min_rate`. | `FR-MKT-002` | Validated against `min_rate`. | +| `modal_rate` | `Decimal(10,2)` | Currency Input | Mandatory if open. `min_rate <= modal_rate <= max_rate`. | `FR-MKT-002` | Validated modal clearing rate benchmark. | + +--- + +## 4. State Guards & Error Handling + +1. **Uniqueness Constraint (`mandi_id`, `commodity_id`, `variety`, `observation_date`):** + - If a record already exists, UI highlights existing entry and offers an "Edit Existing" workflow. Duplicate insert attempts return HTTP 409 Conflict. +2. **Rate Invariant Guard:** + - Client and server enforce `min_rate <= modal_rate <= max_rate`. Discrepancies show inline field alert: `"Modal rate must be between Min and Max rates"`. +3. **Future Date Guard:** + - Datepicker disables all calendar cells past `today`. Manual manipulation returns HTTP 422 Unprocessable Entity. +4. **Market Closure Grace:** + - When `is_market_closed` is checked, `arrival_mt` defaults to `0.000` and price fields are disabled with label `"Mandi Closed / Holiday"`. + +--- + +## 5. Authorization & Permissions + +- **Client App ID:** `atb-web-portal` +- **Route Path:** `/market/observations`, `/market/rates` +- **Required Roles:** + - `Mandi Buyer`, `Desk Trader`, `Tenant Admin`: Full Read + Create + Edit. + - `Warehouse Clerk`, `Accounts Executive`: Read-only. +- **Tenant Isolation:** Enforced via `X-Tenant-ID` header and PostgreSQL RLS on `market_observations`. + +--- + +## 6. API Integration Points + +- `GET /api/v1/market/observations`: Fetch observations list for selected mandi and date range. +- `POST /api/v1/market/observations`: Create or update daily observation and price rates. +- `GET /api/v1/market/rates/latest`: Fetch latest benchmark modal rates for commodity and mandi. + diff --git a/04_generated_documentation/06_wireframes/screen_specs/SCREEN-PROC-001_sauda_booking.md b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-PROC-001_sauda_booking.md new file mode 100644 index 0000000..a2d953f --- /dev/null +++ b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-PROC-001_sauda_booking.md @@ -0,0 +1,134 @@ +# Screen Specification: SCREEN-PROC-001 — Purchase Sauda Booking Register & Costing + +| Field | Value | +|---|---| +| **Screen ID** | `SCREEN-PROC-001` | +| **Client Application ID** | `atb-web-portal` | +| **Frontend Route** | `/procurement/sauda`, `/procurement/sauda/new`, `/procurement/sauda/:id` | +| **Owning Use Case** | [`UC-004` (Purchase Sauda and Supplier Payables Setup)](../../03_requirements/use_cases/uc-004-procurement-contracts/use-case.md) | +| **Owning FR** | [`FR-PROCUREMENTCONTRACTS-001` (Procurement Price Variance Alert vs. Modal Rate)](../../03_requirements/use_cases/uc-004-procurement-contracts/functional-reqs.md#fr-procurementcontracts-001-procurement-price-variance-alert-vs-modal-rate), [`FR-PROCUREMENTCONTRACTS-002` (Mandi Auction & Direct Purchase Sauda Booking)](../../03_requirements/use_cases/uc-004-procurement-contracts/functional-reqs.md#fr-procurementcontracts-002-mandi-auction--direct-purchase-sauda-booking), [`FR-PROCUREMENTCONTRACTS-003` (Supplier Credit Terms, Payment Due Date, and Advance Recording)](../../03_requirements/use_cases/uc-004-procurement-contracts/functional-reqs.md#fr-procurementcontracts-003-supplier-credit-terms-payment-due-date-and-advance-recording), [`FR-PROCUREMENTCONTRACTS-004` (Mandi Cess, Krishi Kalyan, and Statutory Levies Breakdown)](../../03_requirements/use_cases/uc-004-procurement-contracts/functional-reqs.md#fr-procurementcontracts-004-mandi-cess-krishi-kalyan-and-statutory-levies-breakdown) | +| **Auth Role / Scope Claims** | `Procurement Officer`, `Desk Trader`, `Purchase Manager`, `Tenant Admin` | +| **Iteration** | `iteration-03` | +| **Status** | Baselined for Construction | + +--- + +## 1. Screen Overview & Archetype + +- **Archetype:** Trade Contract Booking Engine, Commercial Blotter & Landed Cost Calculator. +- **Visual Design Reference:** Tailwind CSS / shadcn-ui components following [`DESIGN.md`](../DESIGN.md) (`agri-700` primary buttons, `amber-500` warning badges, `slate-900` text). +- **Behavior:** Commercial buyers book auction or direct purchase contracts (*saudas*) with validated suppliers. Features real-time price variance warning when offered trade rate deviates by $>5\%$ against the latest modal clearing rate, automated calculation of payment due dates from credit term days, advance payment recording, and dynamic breakdown of statutory APMC mandi cess, cess sub-heads, and broker commission. Tracks partial deliveries against booked metric tonnage. + +--- + +## 2. Wireframe Layout + +``` ++------------------------------------------------------------------------------------------------------------------------+ +| [Logo] ATB Procurement | Filter: [ Active Contracts v ] | Search: [____________] | [+ Book New Sauda] | [Buyer User v] | ++---------------------------+-------------------------------------------------------------+--------------------+---------+ +| [Navigation] | Purchase Sauda Contracts Register | +| - Market Desk +--------------------------------------------------------------------------------------------+ +| - Sauda Booking (Active) | Contract ID | Supplier Name | Mandi Hub | Commodity | Booked MT | Rate/Qtl | Fulfilled | Status | +| - Gate Receiving |--------------+---------------------+-----------+-----------+-----------+----------+-----------+--------| +| - Weighbridge / GRN | SDA-26-00142 | Kisan Agro Traders | Kota APMC | Soyabean | 50.00 MT | ₹ 4,750 | 60.0 % | Active | +| - Quality Lab | SDA-26-00143 | Mewar Krishi Sangh | Unjha APMC| Cumin/Jeer| 20.00 MT | ₹ 24,500 | 0.0 % | Pending| +| - Inventory Lots | SDA-26-00144 | Malwa Agro Corp | Indore | Wheat FAQ | 100.00 MT | ₹ 2,420 | 100.0 % | Closed | +| +--------------------------------------------------------------------------------------------+ +| | Summary: Active Saudas: 18 | Open Balance: 420.50 MT | Committed Exposure: ₹ 2.14 Cr | ++---------------------------+--------------------------------------------------------------------------------------------+ +``` + +### New Sauda Booking Form Layout (`/procurement/sauda/new`) + +``` ++---------------------------------------------------------------------------------------------------+ +| Book Purchase Sauda Contract (Direct / Mandi Auction) [X] | ++---------------------------------------------------------------------------------------------------+ +| Contract Date*: [ 2026-10-12 ] Delivery Due Date*: [ 2026-10-18 ] | +| Sourcing Mandi*: [ Kota APMC, Rajasthan v ] Trade Type*: [ Mandi Auction v ] | +| Supplier / Arhatiya*: [ SUP-0042 - Kisan Agro Traders (24ABCDE1234F1Z5) v ]| +| Commodity*: [ Soyabean v ] Variety*: [ Yellow Desi v ] Grade*: [ FAQ v ]| +| | +| --- Trade Quantity & Pricing ------------------------------------------------------------------ | +| Booked Quantity (MT)*: [ 50.000 ] Estimated Bags: [ 1000 ] (50kg standard) | +| Agreed Trade Rate (₹/Qtl)*: [ 4850.00 ] Benchmark Modal Rate: ₹ 4,600.00 / Qtl (Market Desk) | +| | +| [!] WARNING: Offered rate exceeds benchmark modal rate by +5.43% (> 5.0% threshold). | +| [x] I confirm this rate is justified due to premium high-oil specification (FAQ+). | +| | +| --- Commercial Terms & Levies (NFR-001 3-Decimal Precision) ----------------------------------- | +| Payment Terms*: [ 15 Days Credit v ] Payment Due Date: 2026-10-27 (Computed) | +| Advance Payment Paid (₹): [ 50,000.00 ] Mode: [ RTGS / Bank Transfer v ]| +| | +| Base Value (₹): ₹ 24,25,000.00 (50.00 MT * 10 Qtl/MT * ₹ 4,850.00) | +| Mandi Cess (1.50%): ₹ 36,375.00 (APMC Mandi Tax) | +| Krishi Kalyan Cess (0.50%): ₹ 12,125.00 (Development Cess) | +| Brokerage / Arhat (1.00%): ₹ 24,250.00 (Arhatiya Commission) | +| Total Landed Sauda Value (₹):₹ 24,97,750.00 | +| | +| [ Cancel ] [ Book Contract & Lock Terms -> ]| ++---------------------------------------------------------------------------------------------------+ +``` + +--- + +## 3. Field-Level Specification + +| Field Name | Data Type | UI Control | Validation Rules | Source FR | Backend Processing Expectation | +|---|---|---|---|---|---| +| `sauda_number` | `String(32)` | Read-only Display | Auto-generated sequence `SDA-YY-XXXXX`. | `FR-PROCUREMENTCONTRACTS-002` | Unique sequence per tenant. | +| `contract_date` | `Date` | Datepicker | Mandatory. `contract_date <= CURRENT_DATE`. | `FR-PROCUREMENTCONTRACTS-002` | Booking effective timestamp. | +| `delivery_due_date`| `Date` | Datepicker | Mandatory. `delivery_due_date >= contract_date`. | `FR-PROCUREMENTCONTRACTS-002` | Enforced delivery SLA window. | +| `supplier_id` | `UUID` | Combobox Search | Mandatory. Must reference active approved supplier. | `FR-PROCUREMENTCONTRACTS-002` | Foreign key to `suppliers` master. | +| `mandi_id` | `UUID` | Select Dropdown | Mandatory. APMC market yard. | `FR-PROCUREMENTCONTRACTS-002` | Foreign key to `mandi_yards`. | +| `trade_type` | `Enum` | Select Dropdown | `MANDI_AUCTION`, `DIRECT_FARMER`, `COMMERCIAL_TRADER`. | `FR-PROCUREMENTCONTRACTS-002` | Influences APMC cess applicability. | +| `commodity_id` | `UUID` | Select Dropdown | Mandatory. Active commodity in master. | `FR-PROCUREMENTCONTRACTS-002` | Foreign key to `commodities`. | +| `variety` | `String(64)` | Combobox / Text | Mandatory. | `FR-PROCUREMENTCONTRACTS-002` | Commodity variety. | +| `grade` | `String(32)` | Select Dropdown | Mandatory. Default `FAQ`. | `FR-PROCUREMENTCONTRACTS-002` | Quality standard specification. | +| `booked_quantity_mt`| `Decimal(12,3)`| Numeric Input | Mandatory. `booked_quantity_mt > 0.000`. | `FR-PROCUREMENTCONTRACTS-002` | Stored in MT with 3 decimal precision. | +| `estimated_bags` | `Integer` | Integer Input | Optional. `estimated_bags >= 0`. | `FR-PROCUREMENTCONTRACTS-002` | Bag count estimation. | +| `trade_rate_per_qtl`| `Decimal(10,2)`| Currency Input | Mandatory. `trade_rate_per_qtl > 0.00`. | `FR-PROCUREMENTCONTRACTS-002` | Trade rate per quintal (100 kg). | +| `rate_variance_pct`| `Decimal(5,2)` | Computed Badge | System-calculated against benchmark modal rate. | `FR-PROCUREMENTCONTRACTS-001` | Formula: `((Rate - Modal) / Modal) * 100`. | +| `variance_acknowledged`| `Boolean` | Checkbox | Mandatory `true` if `rate_variance_pct > 5.0%`. | `FR-PROCUREMENTCONTRACTS-001` | Audit log records justification. | +| `credit_period_days`| `Integer` | Select / Numeric | Mandatory. `credit_period_days >= 0`. Default `0` (Spot).| `FR-PROCUREMENTCONTRACTS-003` | Due date computed as `contract_date + credit_period_days`. | +| `payment_due_date` | `Date` | Read-only Display | System-calculated from credit period. | `FR-PROCUREMENTCONTRACTS-003` | Indexed maturity date for AP aging. | +| `advance_amount` | `Decimal(12,2)`| Currency Input | Optional. `advance_amount >= 0.00` and `<= gross_value`.| `FR-PROCUREMENTCONTRACTS-003` | Deducted from final vendor settlement. | +| `mandi_cess_pct` | `Decimal(5,2)` | Numeric Input | Mandatory for APMC trades. Standard `1.50%`. | `FR-PROCUREMENTCONTRACTS-004` | Tax line item computation. | +| `krishi_kalyan_pct`| `Decimal(5,2)` | Numeric Input | Mandatory. Standard `0.50%`. | `FR-PROCUREMENTCONTRACTS-004` | Tax line item computation. | +| `brokerage_rate_pct`| `Decimal(5,2)`| Numeric Input | Optional. Standard `1.00%`. | `FR-PROCUREMENTCONTRACTS-004` | Broker payable computation. | +| `gross_amount` | `Decimal(14,2)`| Read-only Display | Computed: `booked_quantity_mt * 10 * trade_rate_per_qtl`.| `FR-PROCUREMENTCONTRACTS-002` | Base contract value. | +| `total_landed_amount`| `Decimal(14,2)`| Read-only Display| Computed: `gross_amount + cess + kalyan + brokerage`. | `FR-PROCUREMENTCONTRACTS-004` | Total landed financial commitment. | + +--- + +## 4. State Guards & Error Handling + +1. **Price Variance Alert (> 5% Threshold):** + - If `trade_rate_per_qtl` exceeds latest modal rate by $> 5.0\%$, form displays amber warning card and disables submission until `variance_acknowledged` checkbox is toggled. +2. **Gross Value Formula Guard:** + - Client and server enforce: $\text{Gross Value} = \text{Booked MT} \times 10 \times \text{Rate}$. +3. **Partial Delivery Lifecycle Guard:** + - Contract status initializes to `ACTIVE` (or `PENDING_DELIVERY`). + - As inward GRNs link to this `sauda_id`, `cumulative_received_mt` is incremented. + - Status automatically transitions to `PARTIALLY_RECEIVED` when $0 < \text{received} < \text{booked}$, and `FULFILLED` when $\text{received} \ge \text{booked} - \text{tolerance}$. + +--- + +## 5. Authorization & Permissions + +- **Client App ID:** `atb-web-portal` +- **Route Path:** `/procurement/sauda`, `/procurement/sauda/new` +- **Required Roles:** + - `Procurement Officer`, `Desk Trader`, `Purchase Manager`, `Tenant Admin`: Full Create and Edit. + - `Accounts Executive`, `Warehouse Clerk`: Read-only. +- **Tenant Isolation:** Enforced via `X-Tenant-ID` header and PostgreSQL RLS on `procurement_sauda`. + +--- + +## 6. API Integration Points + +- `GET /api/v1/procurement/sauda`: List contracts with filter by supplier, status, date range. +- `POST /api/v1/procurement/sauda`: Create new purchase sauda with statutory levies. +- `GET /api/v1/procurement/sauda/{id}`: Detailed contract view including partial delivery fulfillment progress. + diff --git a/04_generated_documentation/06_wireframes/screen_specs/SCREEN-QC-001_quality_lab.md b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-QC-001_quality_lab.md new file mode 100644 index 0000000..269c2ee --- /dev/null +++ b/04_generated_documentation/06_wireframes/screen_specs/SCREEN-QC-001_quality_lab.md @@ -0,0 +1,132 @@ +# Screen Specification: SCREEN-QC-001 — Inward Quality Lab Assay & Decision Console + +| Field | Value | +|---|---| +| **Screen ID** | `SCREEN-QC-001` | +| **Client Application ID** | `atb-web-portal` | +| **Frontend Route** | `/quality/inspection`, `/quality/lots/:id`, `/quality/settlement/:id` | +| **Owning Use Case** | [`UC-006` (Quality Assay, Deductions and Lot Genealogy)](../../03_requirements/use_cases/uc-006-quality-and-lot-control/use-case.md) | +| **Owning FR** | [`FR-QUALITYANDLOTCONTROL-001` (Inward Quality Inspection Parameter Recording)](../../03_requirements/use_cases/uc-006-quality-and-lot-control/functional-reqs.md#fr-qualityandlotcontrol-001-inward-quality-inspection-parameter-recording), [`FR-QUALITYANDLOTCONTROL-002` (Quality Deduction / Rebate Calculation)](../../03_requirements/use_cases/uc-006-quality-and-lot-control/functional-reqs.md#fr-qualityandlotcontrol-002-quality-deduction--rebate-calculation), [`FR-QUALITYANDLOTCONTROL-003` (Finite State Machine Enforcement for `QC Hold` vs. `Released`)](../../03_requirements/use_cases/uc-006-quality-and-lot-control/functional-reqs.md#fr-qualityandlotcontrol-003-finite-state-machine-enforcement-for-qc-hold-vs-released), [`FR-QUALITYANDLOTCONTROL-004` (Lot Splitting & Blending Traceability)](../../03_requirements/use_cases/uc-006-quality-and-lot-control/functional-reqs.md#fr-qualityandlotcontrol-004-lot-splitting--blending-traceability) | +| **Auth Role / Scope Claims** | `Quality Inspector`, `Lab Chemist`, `Warehouse Manager`, `Tenant Admin` | +| **Iteration** | `iteration-03` | +| **Status** | Baselined for Construction | + +--- + +## 1. Screen Overview & Archetype + +- **Archetype:** Laboratory Analytical Testing Station, Quality Decision FSM Cockpit & Commercial Settlement Refraction Sheet. +- **Visual Design Reference:** High-density scientific testing interface following [`DESIGN.md`](../DESIGN.md) (`agri-700` primary buttons, `emerald-500` for Released, `rose-500` for Rejected, `amber-500` for QC Hold). +- **Behavior:** Quality Inspectors and Lab Chemists sample inward lots, record physical and analytical assay parameters (Moisture %, Foreign Matter / Admixture %, Damaged / Discolored Grain %, Shriveled Grain %, Oil / Protein Content %). The engine computes commercial deduction/rebate schedules (price cuts or weight deductions) against Fair Average Quality (FAQ) benchmarks. The inspector executes FSM transitions (`QUALITY_HOLD` $\to$ `RELEASED` or `REJECTED`). Produce under `QUALITY_HOLD` is blocked from dispatch or sales orders. Displays lot lineage and digital quality certificates. + +--- + +## 2. Wireframe Layout + +``` ++------------------------------------------------------------------------------------------------------------------------+ +| [Logo] ATB Quality Lab Console | Laboratory: [ Central Testing Lab 1 v ] | [+ New Inspection] | [Lab Chemist v] | ++----------------------------------+-------------------------------------------+----------------------+------------------+ +| [Navigation] | Quality Inspections & Lot Decision Cockpit | +| - Gate Entry +-------------------------------------------------------------------------------------+ +| - Weighbridge / GRN | Status: [ All QC States v ] Filter: [ Awaiting Inspection v ] Search: [LOT...] | +| - Quality Lab (Active) +-------------------------------------------------------------------------------------+ +| - Inventory Lots | Lot Number | Commodity | Mandi Origin | Moisture % | Foreign % | QC Status | Actions| +| |--------------------+-----------+--------------+------------+-----------+-----------+--------| +| | LOT-26-10-SOY-0084 | Soyabean | Kota APMC | 12.8 % | 2.1 % | [QC Hold] | [Assay]| +| | LOT-26-10-CUM-0031 | Cumin | Unjha APMC | 9.2 % | 0.8 % | [Released]| [View] | +| | LOT-26-10-WHT-0105 | Wheat FAQ | Indore APMC | 14.5 % (!) | 3.5 % (!) | [Rejected]| [View] | +| +-------------------------------------------------------------------------------------+ +| | Summary: Under Inspection: 4 | Released Today: 12 | Rejected: 1 | Net Rebate: ₹ 48,200 | ++----------------------------------+-------------------------------------------------------------------------------------+ +``` + +### Lab Assay & Rebate Calculation Dialog (`/quality/inspection/new`) + +``` ++-----------------------------------------------------------------------------------+ +| Record Laboratory Assay & Commercial Deductions [X] | ++-----------------------------------------------------------------------------------+ +| Target Inventory Lot*: [ LOT-26-10-SOY-0084 - Soyabean (24.925 MT) v ]| +| Sample Composite ID*: [ SMP-2026-9042 ] Sampled Bags: [ 50 Bags (10%) ] | +| Inspection Date/Time*: [ 2026-10-12 11:45 AM ] Chemist: [ Dr. S. Verma ] | +| | +| --- Physical & Chemical Assay Parameters (FAQ Tolerances) ---------------------- | +| Parameter | Benchmark FAQ | Measured Assay | Variance | Deduction Type | +| --------------------+---------------+----------------+----------+----------------| +| Moisture % | Max 10.0 % | 11.50 % | +1.50 % | Weight Cut | +| Foreign Matter % | Max 1.5 % | 2.10 % | +0.60 % | Price Cut | +| Damaged Grain % | Max 2.0 % | 1.80 % | 0.00 % | None (Pass) | +| Green/Immature % | Max 3.0 % | 2.40 % | 0.00 % | None (Pass) | +| Oil Content % (Min) | Min 18.0 % | 18.40 % | +0.40 % | Premium (FAQ+) | +| | +| --- Commercial Quality Rebate / Karda Deduction Summary ------------------------- | +| Moisture Excess Weight Deduction: 0.374 MT (1.50% deduction on 24.925 MT) | +| Net Billable Weight after QC: 24.551 MT | +| Quality Rate Deduction (Karda): ₹ 18.00 / Qtl (Foreign matter penalty) | +| Total Supplier Quality Rebate: ₹ 14,850.00 | +| | +| --- Quality Decision FSM Transition -------------------------------------------- | +| Decision*: (o) RELEASED (Approved for Inventory & Trading) | +| ( ) CONDITIONAL_RELEASE (Release with Agreed Rebate) | +| ( ) REJECTED (Return produce to Supplier / Gate Out) | +| | +| Remarks: [ Produce within acceptable commercial tolerance. Rebate applied. ]| +| | +| [ Cancel ] [ Sign Assay & Commit FSM -> ] | ++-----------------------------------------------------------------------------------+ +``` + +--- + +## 3. Field-Level Specification + +| Field Name | Data Type | UI Control | Validation Rules | Source FR | Backend Processing Expectation | +|---|---|---|---|---|---| +| `inspection_id` | `UUID` | Read-only Display | Auto-generated UUID. | `FR-QUALITYANDLOTCONTROL-001` | Primary key for inspection record. | +| `lot_id` | `UUID` | Select Combobox | Mandatory. Must reference active lot in `QUALITY_HOLD`.| `FR-QUALITYANDLOTCONTROL-001` | Foreign key to `inventory_lots`. | +| `sample_code` | `String(32)` | Text Input | Mandatory. Unique sample barcode/code. | `FR-QUALITYANDLOTCONTROL-001` | Sample chain-of-custody tracking. | +| `moisture_pct` | `Decimal(5,2)` | Numeric Input | Mandatory. `0.0 <= moisture_pct <= 100.0`. | `FR-QUALITYANDLOTCONTROL-001` | Core perishable assay parameter. | +| `foreign_matter_pct`| `Decimal(5,2)`| Numeric Input | Mandatory. `0.0 <= foreign_matter_pct <= 100.0`. | `FR-QUALITYANDLOTCONTROL-001` | Dust, stone, chaff admixture. | +| `damaged_grain_pct`| `Decimal(5,2)` | Numeric Input | Mandatory. `0.0 <= damaged_grain_pct <= 100.0`. | `FR-QUALITYANDLOTCONTROL-001` | Insect or heat-damaged kernels. | +| `oil_content_pct` | `Decimal(5,2)` | Numeric Input | Optional. `0.0 <= oil_content_pct <= 100.0`. | `FR-QUALITYANDLOTCONTROL-001` | Oilseed commercial valuation. | +| `weight_deduction_mt`| `Decimal(12,3)`| Read-only Display| Computed based on excess moisture scale. | `FR-QUALITYANDLOTCONTROL-002` | Reduces final billable quantity. | +| `rate_deduction_per_qtl`| `Decimal(10,2)`| Read-only Display| Computed based on excess admixture/damage. | `FR-QUALITYANDLOTCONTROL-002` | Rate haircut (Karda). | +| `total_rebate_amount`| `Decimal(12,2)`| Read-only Display| Computed total deduction in ₹. | `FR-QUALITYANDLOTCONTROL-002` | Passed to vendor payout settlement. | +| `decision` | `Enum` | Radio Buttons | One of `RELEASED`, `CONDITIONAL_RELEASE`, `REJECTED`. | `FR-QUALITYANDLOTCONTROL-003` | Executes lot FSM state transition. | +| `rejection_reason` | `String(255)`| Text Area | Mandatory if `decision == REJECTED`. | `FR-QUALITYANDLOTCONTROL-003` | Audit rationale for reject/return. | +| `parent_lot_id` | `UUID` | Read-only Display | Optional. Populated during lot split/blend. | `FR-QUALITYANDLOTCONTROL-004` | Self-referencing lineage key. | + +--- + +## 4. State Guards & Error Handling + +1. **Strict FSM Dispatch Guard (`FR-QUALITYANDLOTCONTROL-003`):** + - Lots in `QUALITY_HOLD` state CANNOT be selected in Sales Orders, Dispatches, Outward Gate Passes, or Blending runs. Backend returns HTTP 400 Bad Request with error: `"Cannot dispatch lot under Quality Hold"`. +2. **Rejection Justification Guard:** + - If decision is `REJECTED`, `rejection_reason` is mandatory. The lot is transitioned to `REJECTED` and flagged for supplier return. +3. **Assay Boundary Guard:** + - All assay percentages must be bounded between $0.00\%$ and $100.00\%$. Negative values or values $> 100\%$ return validation error. +4. **Lot Genealogy Traceability Guard (`FR-QUALITYANDLOTCONTROL-004`):** + - Whenever a lot is split into sub-lots or blended, child lots record `parent_lot_id` and retain full upward lineage back to the originating GRN, supplier, and mandi sauda. + +--- + +## 5. Authorization & Permissions + +- **Client App ID:** `atb-web-portal` +- **Route Path:** `/quality/inspection`, `/quality/lots/:id` +- **Required Roles:** + - `Quality Inspector`, `Lab Chemist`, `Tenant Admin`: Full Inspection & FSM Decision. + - `Procurement Officer`, `Warehouse Supervisor`: Read-only. +- **Tenant Isolation:** Enforced via `X-Tenant-ID` header and PostgreSQL RLS on `quality_inspections` and `inventory_lots`. + +--- + +## 6. API Integration Points + +- `GET /api/v1/quality/inspections`: List assays by lot or inspection date. +- `POST /api/v1/quality/inspections`: Record analytical parameters and calculate rebates. +- `POST /api/v1/quality/lots/{lot_id}/decision`: Transition lot FSM state (`RELEASED`, `REJECTED`). +- `GET /api/v1/quality/lots/{lot_id}/lineage`: Retrieve genealogical ancestry tree of the lot. + diff --git a/04_generated_documentation/06_wireframes/wireframe_index.md b/04_generated_documentation/06_wireframes/wireframe_index.md index 3af8d2e..712619b 100644 --- a/04_generated_documentation/06_wireframes/wireframe_index.md +++ b/04_generated_documentation/06_wireframes/wireframe_index.md @@ -20,6 +20,11 @@ | `SCREEN-TENANT-002` | Tenant Member Management View | `/settings/members` | `UC-019` | `FR-TENANTMEMBERSHIPCONTEXT-001` | `iteration-02` | `atb-web-portal` | `@ui-designer-dev` | `@adversarial-tester` | [`SCREEN-TENANT-002_tenant_members.md`](screen_specs/SCREEN-TENANT-002_tenant_members.md) | | `SCREEN-TENANT-003` | Active Tenant Context Switcher | `/select-tenant`, Header | `UC-019` | `FR-TENANTMEMBERSHIPCONTEXT-002` | `iteration-02` | `atb-web-portal` | `@ui-designer-dev` | `@adversarial-tester` | [`SCREEN-TENANT-003_tenant_switcher.md`](screen_specs/SCREEN-TENANT-003_tenant_switcher.md) | | `SCREEN-TENANT-004` | Transaction Audit Log Viewer | `/settings/audit-logs` | `UC-017` | `FR-TENANTSECURITYAUDIT-003` | `iteration-02` | `atb-web-portal` | `@ui-designer-dev` | `@adversarial-tester` | [`SCREEN-TENANT-004_audit_log_viewer.md`](screen_specs/SCREEN-TENANT-004_audit_log_viewer.md) | +| `SCREEN-MKT-001` | Market Observations & Daily Rate Bulletin | `/market/observations`, `/market/rates` | `UC-002` | `FR-MKT-001`, `FR-MKT-002` | `iteration-03` | `atb-web-portal` | `@ui-dev-alpha` | `@adversarial-tester` | [`SCREEN-MKT-001_market_desk.md`](screen_specs/SCREEN-MKT-001_market_desk.md) | +| `SCREEN-PROC-001` | Purchase Sauda Booking Register & Costing | `/procurement/sauda`, `/procurement/sauda/new` | `UC-004` | `FR-PROCUREMENTCONTRACTS-001`..`004` | `iteration-03` | `atb-web-portal` | `@ui-dev-alpha` | `@adversarial-tester` | [`SCREEN-PROC-001_sauda_booking.md`](screen_specs/SCREEN-PROC-001_sauda_booking.md) | +| `SCREEN-INW-001` | Vehicle Gate Entry Register & Yard Inward | `/receiving/gate-entry` | `UC-005` | `FR-INWARDRECEIVING-001`, `FR-INWARDRECEIVING-004` | `iteration-03` | `atb-web-portal` | `@ui-dev-beta` | `@adversarial-tester` | [`SCREEN-INW-001_gate_entry.md`](screen_specs/SCREEN-INW-001_gate_entry.md) | +| `SCREEN-INW-002` | Weighbridge Gross/Tare Logging & GRN Posting | `/receiving/weighbridge`, `/receiving/grn` | `UC-005` | `FR-INWARDRECEIVING-002`..`006` | `iteration-03` | `atb-web-portal` | `@ui-dev-beta` | `@adversarial-tester` | [`SCREEN-INW-002_weighbridge_grn.md`](screen_specs/SCREEN-INW-002_weighbridge_grn.md) | +| `SCREEN-QC-001` | Inward Quality Lab Assay & Decision Console | `/quality/inspection`, `/quality/lots/:id` | `UC-006` | `FR-QUALITYANDLOTCONTROL-001`..`004` | `iteration-03` | `atb-web-portal` | `@ui-dev-gamma` | `@adversarial-tester` | [`SCREEN-QC-001_quality_lab.md`](screen_specs/SCREEN-QC-001_quality_lab.md) | --- diff --git a/04_generated_documentation/07_test_design/functional_test_cases/TC-002_mandi_market_desk.md b/04_generated_documentation/07_test_design/functional_test_cases/TC-002_mandi_market_desk.md new file mode 100644 index 0000000..5997376 --- /dev/null +++ b/04_generated_documentation/07_test_design/functional_test_cases/TC-002_mandi_market_desk.md @@ -0,0 +1,88 @@ +# Functional Test Cases: UC-002 Daily Mandi Arrivals & Modal Prices + +| Field | Value | +|---|---| +| **Test Suite** | `TC-002_mandi_market_desk.md` | +| **Parent Use Case** | [`UC-002` (Record Daily Mandi Arrivals and Prices)](../../../03_requirements/use_cases/uc-002-market-desk-observations/use-case.md) | +| **Parent FRs** | `FR-MKT-001`, `FR-MKT-002` | +| **Status** | Baselined for Construction (Iteration 03) | +| **Version** | 1.0.0 | +| **Iteration** | `iteration-03` | + +--- + +## TC-MKT-002-01: Record Daily Mandi Arrival & Price Observation (Happy Path) + +- **ID:** `TC-MKT-002-01` +- **Category:** Functional / Happy Path +- **Priority:** P0 +- **Preconditions:** Authenticated user with role `Mandi Buyer` or `Desk Trader`. Active tenant `tenant-alpha`. Mandi yard `Kota APMC` and commodity `Soyabean` exist in master data. +- **Steps:** + 1. Send `POST /api/v1/market/observations` with payload: + - `mandi_id`: Kota APMC UUID + - `observation_date`: Today (`CURRENT_DATE`) + - `commodity_id`: Soyabean UUID + - `variety`: "Yellow Desi" + - `grade`: "FAQ" + - `arrival_mt`: 450.000 + - `min_rate`: 4450.00 + - `max_rate`: 4780.00 + - `modal_rate`: 4620.00 + - `source`: "APMC_BULLETIN" + 2. Verify HTTP status code 201 Created and response attributes. + 3. Send `GET /api/v1/market/observations?mandi_id={kota_id}&date={today}`. +- **Expected Result:** Observation is persisted with 3-decimal MT precision (`450.000 MT`) and 2-decimal currency precision. Rates satisfy `min_rate (4450.00) <= modal_rate (4620.00) <= max_rate (4780.00)`. GET endpoint returns the newly recorded observation. + +--- + +## TC-MKT-002-02: Rate Bounds & Arrival Zero Limits (Boundary / Edge Case) + +- **ID:** `TC-MKT-002-02` +- **Category:** Boundary / Edge Case +- **Priority:** P0 +- **Preconditions:** Authenticated user in active tenant. +- **Steps:** + 1. Record observation with `arrival_mt: 0.000` (e.g. lean season minimal trading). + 2. Record rates where `min_rate == modal_rate == max_rate = 5000.00` (flat price auction). + 3. Attempt observation with `arrival_mt: -0.001` (negative arrival). + 4. Attempt observation with `modal_rate = 5001.00` while `max_rate = 5000.00`. +- **Expected Result:** + - Cases 1 and 2 succeed with HTTP 201 Created (zero arrivals and flat rate boundary are valid). + - Case 3 fails with HTTP 422 Unprocessable Entity (`arrival_mt must be >= 0.0`). + - Case 4 fails with HTTP 422 Unprocessable Entity (`modal_rate must be <= max_rate`). + +--- + +## TC-MKT-002-03: Duplicate Market Record & Cross-Tenant Data Access (Negative / Security) + +- **ID:** `TC-MKT-002-03` +- **Category:** Negative / Security Rejection +- **Priority:** P0 +- **Preconditions:** Observation already recorded for `Kota APMC`, `Soyabean`, `Yellow Desi` on `today` in `tenant-alpha`. +- **Steps:** + 1. In `tenant-alpha`, attempt to post a second observation for identical mandi, commodity, variety, and date. + 2. Switch session context to `tenant-beta`. + 3. Send `GET /api/v1/market/observations` in `tenant-beta`. + 4. In `tenant-beta`, post observation for `Kota APMC`, `Soyabean`, `Yellow Desi` on `today`. +- **Expected Result:** + - Step 1 returns HTTP 409 Conflict with error message `"Duplicate observation already exists for this market, commodity, variety, and date"`. + - Step 3 returns 0 records (RLS tenant isolation blocks visibility of tenant-alpha's observations). + - Step 4 succeeds in `tenant-beta` (uniqueness constraint is tenant-scoped). + +--- + +## TC-MKT-002-04: Mandi Holiday Closure & Future Date Rejection Invariant (FSM Invariant & Concurrency) + +- **ID:** `TC-MKT-002-04` +- **Category:** FSM Invariant & Concurrency +- **Priority:** P1 +- **Preconditions:** Authenticated user with role `Mandi Buyer`. +- **Steps:** + 1. Send `POST /api/v1/market/observations` with `observation_date` set to tomorrow (`CURRENT_DATE + 1 day`). + 2. Send `POST /api/v1/market/observations` with `is_market_closed: true`, `arrival_mt: 0.0`, omitting rates or setting rates to null. + 3. Send concurrent requests attempting to insert the same observation simultaneously. +- **Expected Result:** + - Step 1 is rejected with HTTP 422 (`observation date cannot be in the future`). + - Step 2 succeeds with status `Mandi Holiday / Closed` without requiring price range data. + - Step 3: Exactly one transaction succeeds with 201; concurrent request fails with 409 Conflict due to database uniqueness constraint. + diff --git a/04_generated_documentation/07_test_design/functional_test_cases/TC-004_sauda_procurement.md b/04_generated_documentation/07_test_design/functional_test_cases/TC-004_sauda_procurement.md new file mode 100644 index 0000000..1df5b0f --- /dev/null +++ b/04_generated_documentation/07_test_design/functional_test_cases/TC-004_sauda_procurement.md @@ -0,0 +1,103 @@ +# Functional Test Cases: UC-004 Purchase Sauda & Supplier Payables Setup + +| Field | Value | +|---|---| +| **Test Suite** | `TC-004_sauda_procurement.md` | +| **Parent Use Case** | [`UC-004` (Purchase Sauda and Supplier Payables Setup)](../../../03_requirements/use_cases/uc-004-procurement-contracts/use-case.md) | +| **Parent FRs** | `FR-PROCUREMENTCONTRACTS-001`, `FR-PROCUREMENTCONTRACTS-002`, `FR-PROCUREMENTCONTRACTS-003`, `FR-PROCUREMENTCONTRACTS-004` | +| **Status** | Baselined for Construction (Iteration 03) | +| **Version** | 1.0.0 | +| **Iteration** | `iteration-03` | + +--- + +## TC-PROC-004-01: Direct & Mandi Auction Sauda Booking with Statutory Levies (Happy Path) + +- **ID:** `TC-PROC-004-01` +- **Category:** Functional / Happy Path +- **Priority:** P0 +- **Preconditions:** Authenticated user with role `Procurement Officer` in `tenant-alpha`. Approved supplier `Kisan Agro Traders` (active master) and commodity `Soyabean` exist. Benchmark modal rate = ₹ 4,600.00 / Qtl. +- **Steps:** + 1. Send `POST /api/v1/procurement/sauda` with payload: + - `contract_date`: `2026-10-12` + - `delivery_due_date`: `2026-10-18` + - `supplier_id`: Kisan Agro Traders UUID + - `mandi_id`: Kota APMC UUID + - `trade_type`: `MANDI_AUCTION` + - `commodity_id`: Soyabean UUID + - `variety`: "Yellow Desi" + - `grade`: "FAQ" + - `booked_quantity_mt`: 50.000 + - `trade_rate_per_qtl`: 4700.00 (within +2.17% of modal rate ₹ 4,600) + - `credit_period_days`: 15 + - `advance_amount`: 50000.00 + - `mandi_cess_pct`: 1.50 + - `krishi_kalyan_pct`: 0.50 + - `brokerage_rate_pct`: 1.00 + 2. Verify response status HTTP 201 Created. + 3. Validate computed fields: + - `gross_amount`: $50.000 \times 10 \times 4700.00 = ₹ 23,50,000.00$ + - `payment_due_date`: `2026-10-27` (`2026-10-12` + 15 days) + - `mandi_cess_amount`: $23,50,000 \times 1.50\% = ₹ 35,250.00$ + - `krishi_kalyan_amount`: $23,50,000 \times 0.50\% = ₹ 11,750.00$ + - `brokerage_amount`: $23,50,000 \times 1.00\% = ₹ 23,500.00$ + - `total_landed_amount`: $23,50,000 + 35,250 + 11,750 + 23,500 = ₹ 24,20,500.00$ + - Initial `status`: `ACTIVE` +- **Expected Result:** Contract is booked with unique sequential number `SDA-26-XXXXX`. All mathematical financial totals match exact decimal precision. + +--- + +## TC-PROC-004-02: Price Variance Alert & Due Date Boundary Checks (Boundary / Edge Case) + +- **ID:** `TC-PROC-004-02` +- **Category:** Boundary / Edge Case +- **Priority:** P0 +- **Preconditions:** Latest modal rate = ₹ 4,600.00 / Qtl. Variance threshold = 5.0%. +- **Steps:** + 1. Book sauda with `trade_rate_per_qtl: 4830.00` ($+5.000\%$ variance exactly). + 2. Book sauda with `trade_rate_per_qtl: 4831.00` ($+5.022\%$ variance > 5.0%) without `variance_acknowledged: true`. + 3. Book sauda with `trade_rate_per_qtl: 4831.00` with `variance_acknowledged: true`. + 4. Book sauda with `credit_period_days: 0` (Cash / Spot transaction). +- **Expected Result:** + - Case 1: Succeeds without warning blocker (exact boundary $\le 5.0\%$). + - Case 2: Rejected with HTTP 422 Unprocessable Entity or HTTP 400 Bad Request: `"Offered rate exceeds benchmark modal rate by > 5.0%. Justification acknowledgment required"`. + - Case 3: Succeeds with HTTP 201 Created; audit log captures trader acknowledgment. + - Case 4: Succeeds; `payment_due_date` equals `contract_date`. + +--- + +## TC-PROC-004-03: Inactive Supplier & Cross-Tenant Rejection (Negative / Security) + +- **ID:** `TC-PROC-004-03` +- **Category:** Negative / Security Rejection +- **Priority:** P0 +- **Preconditions:** Supplier master contains `SUP-INACTIVE` (status `SUSPENDED`). Supplier `SUP-ALPHA` belongs to `tenant-alpha`. +- **Steps:** + 1. Attempt to book sauda with supplier `SUP-INACTIVE`. + 2. Attempt to book sauda with negative quantity (`booked_quantity_mt: -10.000`). + 3. Attempt to book sauda with negative rate (`trade_rate_per_qtl: -500.00`). + 4. As user of `tenant-beta`, attempt to book sauda referencing `SUP-ALPHA` or access sauda of `tenant-alpha`. +- **Expected Result:** + - Case 1: Rejected with HTTP 400 Bad Request (`supplier must be active`). + - Case 2 & 3: Rejected with HTTP 422 Unprocessable Entity (`quantity and rate must be > 0`). + - Case 4: Supplier reference fails foreign key or RLS check; cross-tenant sauda access returns HTTP 404 Not Found. + +--- + +## TC-PROC-004-04: Multi-Truck Partial Fulfillment & FSM Lifecycle Invariant (FSM Invariant & Concurrency) + +- **ID:** `TC-PROC-004-04` +- **Category:** FSM Invariant & Concurrency +- **Priority:** P1 +- **Preconditions:** Active sauda `SDA-01` booked for 50.000 MT. +- **Steps:** + 1. Verify initial status is `ACTIVE` with `cumulative_received_mt = 0.000` and `balance_mt = 50.000`. + 2. First truck arrives and posts GRN for 24.925 MT. + 3. Check sauda status: cumulative received = 24.925 MT, balance = 25.075 MT. Status must transition to `PARTIALLY_RECEIVED`. + 4. Second truck arrives and posts GRN for 25.000 MT. + 5. Cumulative received = 49.925 MT (within 0.5% tolerance of 50.00 MT). Status transitions to `FULFILLED`. + 6. Attempt to book a third truck against `SDA-01` after fulfillment. +- **Expected Result:** + - Sauda lifecycle FSM strictly moves `ACTIVE` $\to$ `PARTIALLY_RECEIVED` $\to$ `FULFILLED`. + - Step 6 fails with validation error: `"Cannot assign gate entry to fulfilled contract"`. + diff --git a/04_generated_documentation/07_test_design/functional_test_cases/TC-005_inward_receiving.md b/04_generated_documentation/07_test_design/functional_test_cases/TC-005_inward_receiving.md new file mode 100644 index 0000000..c18c5d4 --- /dev/null +++ b/04_generated_documentation/07_test_design/functional_test_cases/TC-005_inward_receiving.md @@ -0,0 +1,112 @@ +# Functional Test Cases: UC-005 Inward Gate Entry, Weighbridge, GRN & Lot Minting + +| Field | Value | +|---|---| +| **Test Suite** | `TC-005_inward_receiving.md` | +| **Parent Use Case** | [`UC-005` (Inward Gate Entry, Weighbridge, GRN and Lot Minting)](../../../03_requirements/use_cases/uc-005-inward-receiving/use-case.md) | +| **Parent FRs** | `FR-INWARDRECEIVING-001`, `FR-INWARDRECEIVING-002`, `FR-INWARDRECEIVING-003`, `FR-INWARDRECEIVING-004`, `FR-INWARDRECEIVING-005`, `FR-INWARDRECEIVING-006` | +| **Status** | Baselined for Construction (Iteration 03) | +| **Version** | 1.0.0 | +| **Iteration** | `iteration-03` | + +--- + +## TC-INW-005-01: End-to-End Inward Receiving Pipeline (Happy Path) + +- **ID:** `TC-INW-005-01` +- **Category:** Functional / Happy Path +- **Priority:** P0 +- **Preconditions:** Active Sauda `SDA-26-00142` booked for 50.00 MT Soyabean. Godown 02 and Stack B-04 exist with available capacity. +- **Steps:** + 1. Post `POST /api/v1/receiving/gate-entries`: + - `vehicle_number`: "RJ-20-GA-4581" + - `eway_bill_number`: "241089201923" + - `driver_name`: "Ramesh Singh" + - `driver_mobile`: "9829012345" + - `sauda_id`: SDA-26-00142 UUID + - `supplier_invoice_no`: "INV-2026-9042" + - `supplier_dispatch_weight_mt`: 25.000 + - `supplier_dispatch_bags`: 500 + - `is_seal_intact`: true + - Returns `gate_pass_id`, status `GATE_IN`. + 2. Post `POST /api/v1/receiving/weighments` (Gross Weighment): + - `gate_pass_id`: gate_pass_id + - `gross_weight_mt`: 38.450 + - Returns weighment slip with gross logged. + 3. Post `POST /api/v1/receiving/weighments/{id}/tare` (Tare & Bag Tare): + - `tare_weight_mt`: 13.200 + - `bag_packaging_type`: "JUTE_GUNNY_NEW" + - `bag_tare_rate_kg`: 0.650 + - `actual_bag_count`: 500 + - System computes: + - `unloaded_weight_mt`: $38.450 - 13.200 = 25.250\text{ MT}$ + - `bag_tare_deduction_mt`: $(500 \times 0.650) / 1000 = 0.325\text{ MT}$ + - `final_net_weight_mt`: $25.250 - 0.325 = 24.925\text{ MT}$ + - `shortage_weight_mt`: $24.925 - 25.000 = -0.075\text{ MT}$ ($-0.30\%$ shortage) + 4. Post `POST /api/v1/receiving/grn`: + - `weighment_slip_id`: slip_id + - `godown_id`: Godown 02 UUID + - `godown_stack_id`: Stack B-04 UUID +- **Expected Result:** + - HTTP 201 Created. + - Generates formal GRN (`GRN-26-XXXXX`). + - Mints unique lot identity (`LOT-26-10-SOY-XXXXX`) in `QUALITY_HOLD` status. + - Sauda cumulative received updated by 24.925 MT. + - Yard pass updated to `GRN_ISSUED`. + +--- + +## TC-INW-005-02: Bag Tare Precision & Weighbridge Tolerance Limits (Boundary / Edge Case) + +- **ID:** `TC-INW-005-02` +- **Category:** Boundary / Edge Case +- **Priority:** P0 +- **Preconditions:** Truck inside yard with gross weight 40.000 MT. +- **Steps:** + 1. Record tare with HDPE bags: 600 bags at 0.120 kg/bag = 0.072 MT tare deduction. Verify 3-decimal precision. + 2. Record bulk loose produce with 0 bags (`actual_bag_count: 0`). Verify bag tare deduction = 0.000 MT. + 3. Test shortage exactly at tolerance boundary: billed = 20.000 MT, net = 19.900 MT (shortage = $-0.100\text{ MT}$, exactly $-0.50\%$). + 4. Test shortage exceeding tolerance: billed = 20.000 MT, net = 19.850 MT (shortage = $-0.150\text{ MT}$, $-0.75\% > 0.50\%$). +- **Expected Result:** + - Cases 1 & 2 compute tare accurately to 3 decimals without rounding error. + - Case 3 passes within tolerance without blocking. + - Case 4 sets `is_shortage_exceeded: true`, requires supervisor override flag and logs exception warning. + +--- + +## TC-INW-005-03: Invalid Scale Reading & Active Yard Duplicate (Negative / Security) + +- **ID:** `TC-INW-005-03` +- **Category:** Negative / Security Rejection +- **Priority:** P0 +- **Preconditions:** Vehicle `RJ-20-GA-4581` has active gate pass inside yard. +- **Steps:** + 1. Attempt to create a second gate pass for `RJ-20-GA-4581` while previous pass is active. + 2. Attempt to record invalid 11-digit or non-numeric e-Way bill. + 3. In weighbridge, attempt to record tare weight greater than gross weight (`gross: 20.000 MT, tare: 21.000 MT`). + 4. Attempt to record tare weight equal to gross weight (`gross: 20.000 MT, tare: 20.000 MT`). + 5. Attempt to post GRN without completing tare weighment. +- **Expected Result:** + - Case 1: HTTP 409 Conflict (`Vehicle already inside yard`). + - Case 2: HTTP 422 Unprocessable Entity (`e-Way bill must be 12 digits`). + - Case 3 & 4: HTTP 422 Unprocessable Entity (`Tare weight must be strictly less than Gross weight`). + - Case 5: HTTP 400 Bad Request (`Cannot issue GRN without completed tare weighment`). + +--- + +## TC-INW-005-04: Lot Minting Atomicity & Invariant Enclosure (FSM Invariant & Concurrency) + +- **ID:** `TC-INW-005-04` +- **Category:** FSM Invariant & Concurrency +- **Priority:** P1 +- **Preconditions:** Weighment slip ready for GRN posting. +- **Steps:** + 1. Post GRN inside a transaction where godown stack allocation fails (e.g. stack capacity exceeded). + 2. Verify whether GRN, weighment slip update, or lot record persisted. + 3. Send two concurrent GRN creation requests for the exact same weighment slip. + 4. Verify that generated lot identity initial state is strictly `QUALITY_HOLD`. +- **Expected Result:** + - Step 1: Transaction rolls back atomically. Zero partial records created. + - Step 3: Exactly one GRN is created; second request is rejected with 409 Conflict. + - Step 4: Lot is created with `qc_status = 'QUALITY_HOLD'`. + diff --git a/04_generated_documentation/07_test_design/functional_test_cases/TC-006_quality_lot_control.md b/04_generated_documentation/07_test_design/functional_test_cases/TC-006_quality_lot_control.md new file mode 100644 index 0000000..cf663e1 --- /dev/null +++ b/04_generated_documentation/07_test_design/functional_test_cases/TC-006_quality_lot_control.md @@ -0,0 +1,95 @@ +# Functional Test Cases: UC-006 Quality Assay, Deductions & Lot Genealogy + +| Field | Value | +|---|---| +| **Test Suite** | `TC-006_quality_lot_control.md` | +| **Parent Use Case** | [`UC-006` (Quality Assay, Deductions and Lot Genealogy)](../../../03_requirements/use_cases/uc-006-quality-and-lot-control/use-case.md) | +| **Parent FRs** | `FR-QUALITYANDLOTCONTROL-001`, `FR-QUALITYANDLOTCONTROL-002`, `FR-QUALITYANDLOTCONTROL-003`, `FR-QUALITYANDLOTCONTROL-004` | +| **Status** | Baselined for Construction (Iteration 03) | +| **Version** | 1.0.0 | +| **Iteration** | `iteration-03` | + +--- + +## TC-QC-006-01: Inward Lab Inspection, Deduction & Release FSM (Happy Path) + +- **ID:** `TC-QC-006-01` +- **Category:** Functional / Happy Path +- **Priority:** P0 +- **Preconditions:** Inventory lot `LOT-26-10-SOY-0084` exists with status `QUALITY_HOLD` (24.925 MT Soyabean). Authenticated user with role `Quality Inspector`. +- **Steps:** + 1. Send `POST /api/v1/quality/inspections` with payload: + - `lot_id`: LOT-26-10-SOY-0084 UUID + - `sample_code`: "SMP-2026-9042" + - `moisture_pct`: 11.50 (FAQ standard: 10.0%, excess = 1.50%) + - `foreign_matter_pct`: 2.10 (FAQ standard: 1.5%, excess = 0.60%) + - `damaged_grain_pct`: 1.80 (within FAQ standard 2.0%) + - `oil_content_pct`: 18.40 + - `decision`: "RELEASED" + - `remarks`: "Passed with commercial moisture deduction" + 2. Verify response status HTTP 201 Created. + 3. Validate calculation outputs: + - `moisture_weight_deduction_mt`: $24.925 \times 1.50\% = 0.374\text{ MT}$ + - `net_billable_weight_mt`: $24.925 - 0.374 = 24.551\text{ MT}$ + - `rate_deduction_per_qtl`: ₹ 18.00 / Qtl (excess foreign matter penalty) + - `total_rebate_amount`: ₹ 14,850.00 + 4. Query lot status: `GET /api/v1/quality/lots/{lot_id}`. +- **Expected Result:** + - Inspection record created with digital hash/timestamp. + - Lot status transitions from `QUALITY_HOLD` to `RELEASED`. + - Produce is now unblocked and available for trading / outward dispatch. + +--- + +## TC-QC-006-02: Assay Boundary Limits & Rebate Schedule Edge Cases (Boundary / Edge Case) + +- **ID:** `TC-QC-006-02` +- **Category:** Boundary / Edge Case +- **Priority:** P0 +- **Preconditions:** Lot in `QUALITY_HOLD`. +- **Steps:** + 1. Record assay where all parameters match FAQ baseline exactly (e.g. moisture = 10.0%, foreign matter = 1.5%). Verify rebate = ₹ 0.00. + 2. Record assay with boundary values: moisture = 0.0%, foreign matter = 0.0%. Verify accepted without error. + 3. Record assay with moisture at upper limit 25.0%. Verify system flags high-moisture perishable hazard. + 4. Attempt to submit negative assay percentage (`moisture_pct: -0.50`). + 5. Attempt to submit percentage $> 100.0$` (`foreign_matter_pct: 105.0`). +- **Expected Result:** + - Cases 1 & 2 compute zero deductions and save successfully. + - Case 3 flags high-risk alert. + - Cases 4 & 5 rejected with HTTP 422 Unprocessable Entity (`assay percentage must be between 0.00 and 100.00`). + +--- + +## TC-QC-006-03: Quality Hold Dispatch Blocking & Rejection RBAC (Negative / Security) + +- **ID:** `TC-QC-006-03` +- **Category:** Negative / Security Rejection +- **Priority:** P0 +- **Preconditions:** Lot `LOT-01` in `QUALITY_HOLD`. User with role `Sales Executive` (lacks QC role). +- **Steps:** + 1. Attempt to create a sales dispatch order or outward gate pass for `LOT-01` while still in `QUALITY_HOLD`. + 2. Attempt to transition `LOT-01` from `QUALITY_HOLD` to `RELEASED` using credentials of `Sales Executive` or `Warehouse Clerk`. + 3. As `Quality Inspector`, submit decision `REJECTED` without providing mandatory `rejection_reason`. +- **Expected Result:** + - Step 1: Rejected with HTTP 400 Bad Request: `"Cannot dispatch or allocate lot under Quality Hold"`. + - Step 2: Rejected with HTTP 403 Forbidden: `"Requires Quality Inspector or Tenant Admin role"`. + - Step 3: Rejected with HTTP 422 Unprocessable Entity: `"Rejection reason is mandatory when decision is REJECTED"`. + +--- + +## TC-QC-006-04: Finite State Machine Invariant & Lineage Tree Preservation (FSM Invariant & Concurrency) + +- **ID:** `TC-QC-006-04` +- **Category:** FSM Invariant & Concurrency +- **Priority:** P1 +- **Preconditions:** Lot `LOT-01` in state `RELEASED`. +- **Steps:** + 1. Attempt invalid FSM transition: try to transition `LOT-01` from `RELEASED` back to `QUALITY_HOLD` without a formal re-inspection event. + 2. Transition a lot to `REJECTED`, and attempt to dispatch or blend it. + 3. Execute lot split: split `LOT-01` (24.925 MT) into `LOT-01-A` (14.925 MT) and `LOT-01-B` (10.000 MT). + 4. Query lineage endpoint `GET /api/v1/quality/lots/{lot_01_a_id}/lineage`. +- **Expected Result:** + - Step 1: Rejected with HTTP 400 Bad Request (`Invalid state transition: RELEASED cannot transition to QUALITY_HOLD directly`). + - Step 2: Rejected (`Cannot dispatch REJECTED lot`). + - Step 3 & 4: Sub-lots maintain `parent_lot_id` pointing to `LOT-01`. Lineage API returns complete ancestor tree reaching back to original GRN, weighbridge slip, and sauda contract. + diff --git a/04_generated_documentation/07_test_design/manual_qa/iteration-03/MANUAL_TESTING_GUIDE.md b/04_generated_documentation/07_test_design/manual_qa/iteration-03/MANUAL_TESTING_GUIDE.md new file mode 100644 index 0000000..bb241f1 --- /dev/null +++ b/04_generated_documentation/07_test_design/manual_qa/iteration-03/MANUAL_TESTING_GUIDE.md @@ -0,0 +1,212 @@ +# Comprehensive Manual Testing Guide — Iteration 03 +## Inward Trading, Procurement Sauda, Weighbridge Yard Receiving & Quality Control Pipeline + +| Field | Value | +|---|---| +| **Document ID** | `MTG-ITERATION-03` | +| **Governed Standard** | SEI-CMMI Level 3 (UP-AI v1.5 Quality Standard) | +| **Iteration** | `iteration-03` | +| **Scope Slice** | Mandi Market Desk, Purchase Sauda, Yard Receiving & Inward QC ([`UC-002`](../../../03_requirements/use_cases/uc-002-market-desk-observations/use-case.md), [`UC-004`](../../../03_requirements/use_cases/uc-004-procurement-contracts/use-case.md), [`UC-005`](../../../03_requirements/use_cases/uc-005-inward-receiving/use-case.md), [`UC-006`](../../../03_requirements/use_cases/uc-006-quality-and-lot-control/use-case.md)) | +| **Child Requirements** | `FR-MKT-001`, `FR-MKT-002`, `FR-PROCUREMENTCONTRACTS-001`..`004`, `FR-INWARDRECEIVING-001`..`006`, `FR-QUALITYANDLOTCONTROL-001`..`004` (16 FRs) | +| **Associated Screens** | [`SCREEN-MKT-001`](../../06_wireframes/screen_specs/SCREEN-MKT-001_market_desk.md), [`SCREEN-PROC-001`](../../06_wireframes/screen_specs/SCREEN-PROC-001_sauda_booking.md), [`SCREEN-INW-001`](../../06_wireframes/screen_specs/SCREEN-INW-001_gate_entry.md), [`SCREEN-INW-002`](../../06_wireframes/screen_specs/SCREEN-INW-002_weighbridge_grn.md), [`SCREEN-QC-001`](../../06_wireframes/screen_specs/SCREEN-QC-001_quality_lab.md) | +| **Associated APIs** | `POST/GET /api/v1/market/observations`, `POST/GET /api/v1/procurement/sauda`, `POST/GET /api/v1/receiving/gate-entries`, `POST /api/v1/receiving/weighments`, `POST /api/v1/receiving/grn`, `POST/GET /api/v1/quality/inspections`, `POST /api/v1/quality/lots/{id}/decision` | +| **21-Sheet QA Workbook** | `Iteration03_Mandi_Procurement_Receiving_QC_Complete_Manual_Testcases.xlsx` | +| **Status** | Approved QA Specification (Ready for Construction Verification) | +| **Version** | 1.0.0 | +| **Last CR** | none | + +--- + +## 1. Executive Summary & Objective + +This manual testing guide is authored for Quality Assurance (QA) engineers, Field Operations Testers, and Adversarial Security Auditors conducting manual verification and acceptance testing on **Iteration 03**. + +The objective of Iteration 03 manual verification is to rigorously validate the complete physical and commercial inbound agricultural commodity lifecycle: +1. **Mandi Market Desk Observations & Daily Bulletin (`UC-002`):** Capture daily mandi arrivals (in MT) and APMC auction rates (Min, Max, Modal in ₹/Qtl). Enforce unique constraints per market/date, prevent future dates, support holiday flags, and compute arrival variance against internal warehouse stock positions. +2. **Purchase Sauda Booking & Commercial Contracts (`UC-004`):** Book negotiated auction and direct farmer purchase contracts with approved suppliers. Enforce price variance alerts ($> 5.0\%$ above benchmark modal rate), compute payment maturity dates from credit terms, record advance disbursements, and accurately calculate APMC mandi cess (1.50%), Krishi Kalyan cess (0.50%), and brokerage commissions. +3. **Inward Vehicle Gate Pass & Yard Ingress (`UC-005`):** Log arriving trucks, capture 12-digit e-Way bills, driver details, and invoice dispatch metrics. Link to active purchase saudas and enforce vehicle yard uniqueness. +4. **Weighbridge Gross/Tare Logging & Bag Tare Deduction (`UC-005`):** Record gross scale weighment, unload cargo, log tare weighment (`gross > tare`), compute packaging tare (*Bardana Katai*) based on bag type and count with 3-decimal metric tonne precision (NFR-001), and verify transit shortage tolerance ($\le 0.5\%$). +5. **Goods Receipt Note (GRN) Posting & Lot Minting (`UC-005`):** Atomically post GRN, allocate physical godown stack bays, mint unique traceable lot identities (`LOT-YY-MM-COMM-XXXXX`), and initialize lot state to mandatory `QUALITY_HOLD`. +6. **Laboratory Quality Assay & Decision Cockpit (`UC-006`):** Chemist records physical and chemical assay parameters (Moisture %, Admixture %, Damaged kernels %). Engine computes commercial rebate deductions (weight haircuts and rate cuts). Inspector commits FSM transitions (`QUALITY_HOLD` $\to$ `RELEASED` or `REJECTED`). Produce under `QUALITY_HOLD` is strictly blocked from dispatch. +7. **Lot Traceability & Lineage (`UC-006`):** Verify full backward lineage from inventory lots to parent GRN, weighbridge slips, and original purchase contract. + +--- + +## 2. Test Environment & Pre-Requisites + +### 2.1 Test Topologies +- **Topology A (Live Microservices & Containers):** + - PostgreSQL 17.11 container (`atb-local-postgres-1` on port `5432`). + - Keycloak 26 container (`atb-local-keycloak-1` on port `8080`). + - FastAPI Backend container (`atb-backend-test` on port `8000`). + - Web Portal running on `http://localhost:3000`. +- **Topology B (Local Python Harness / Automated Runner):** + - Fast memory execution via `scripts/run_tests.sh --scope iteration-03`. + - Master data pre-seeded via `sandbox/master_data_mock.py`. + +--- + +## 3. Disposable QA Personas & Credentials Matrix + +| Persona ID | Email / Username | Assigned Role | Mandi / Facility Scope | Test Purpose | +|---|---|---|---|---| +| `buyer@alpha.com` | `buyer@alpha.com` | Mandi Buyer | Kota APMC Market Yard | Market observations & daily rate bulletin (`UC-002`) | +| `trader@alpha.com` | `trader@alpha.com` | Desk Trader / Procurement Officer | Central Commercial Desk | Purchase sauda booking, price variance warnings (`UC-004`) | +| `guard@alpha.com` | `guard@alpha.com` | Security Guard / Gate Operator | Kota Central Yard Gate | Vehicle gate pass issuance & e-Way bill check (`UC-005`) | +| `weighman@alpha.com`| `weighman@alpha.com` | Weighbridge Operator | Weighbridge Scale 01 | Gross/tare weighment & bag tare worksheet (`UC-005`) | +| `supervisor@alpha.com`| `supervisor@alpha.com` | Warehouse Supervisor | Godown 02 Facility | Shortage verification, stack allocation & GRN posting (`UC-005`) | +| `chemist@alpha.com` | `chemist@alpha.com` | Lab Chemist / Quality Inspector | Central Quality Testing Lab | Quality sampling, assay metrics, rebate & FSM release (`UC-006`) | +| `admin@beta.com` | `admin@beta.com` | Tenant Administrator | `tenant-beta` | Adversarial cross-tenant boundary verification | + +--- + +## 4. Step-by-Step Manual Test Protocols + +### Protocol 1: Daily APMC Mandi Arrival & Price Bulletin (`TC-MKT-002-01` / `02`) +1. Log in as `buyer@alpha.com` and navigate to `/market/observations`. +2. Click **Record Observation**. +3. Select Mandi: `Kota APMC`, Commodity: `Soyabean`, Variety: `Yellow Desi`, Grade: `FAQ`. +4. Enter Arrival Quantity: `450.000 MT`. +5. Enter Price Range: + - Minimum Rate: `₹ 4,450.00` + - Maximum Rate: `₹ 4,780.00` + - Modal Clearing Rate: `₹ 4,620.00` +6. Click **Save & Publish Rates**. +7. **Verification Checks:** + - Confirm table updates with published badge. + - Confirm validation check: `Min (4450) <= Modal (4620) <= Max (4780)` passes. + - Attempt to record observation with tomorrow's date: verify UI blocks with `"Observation date cannot be in the future"`. + - Attempt to record duplicate observation for same market/commodity/date: verify HTTP 409 Conflict rejection. + +--- + +### Protocol 2: Purchase Sauda Booking, Variance Warning & Statutory Levies (`TC-PROC-004-01` / `02`) +1. Log in as `trader@alpha.com` and navigate to `/procurement/sauda`. +2. Click **Book New Sauda**. +3. Fill contract details: + - Supplier: `SUP-0042 - Kisan Agro Traders` + - Sourcing Mandi: `Kota APMC` + - Commodity: `Soyabean`, Variety: `Yellow Desi`, Grade: `FAQ` + - Booked Quantity: `50.000 MT` +4. Enter Agreed Trade Rate: `₹ 4,850.00 / Qtl`. +5. **Price Variance Warning Verification:** + - Note modal rate is `₹ 4,600.00 / Qtl`. + - Observed variance is $+5.43\%$. + - Verify amber alert banner triggers: `"Offered rate exceeds benchmark modal rate by +5.43% (> 5.0% threshold)"`. + - Verify submit button remains disabled until checkbox `"I confirm this rate is justified..."` is checked. +6. Check Commercial Levies & Due Dates: + - Payment Terms: `15 Days Credit` $\to$ verify payment due date auto-calculates to `contract_date + 15 days`. + - Advance Payment: `₹ 50,000.00`. + - Verify Base Value: $50.000 \times 10 \times 4,850 = ₹ 24,25,000.00$. + - Mandi Cess (1.50%): `₹ 36,375.00`. + - Krishi Kalyan Cess (0.50%): `₹ 12,125.00`. + - Brokerage (1.00%): `₹ 24,250.00`. + - Total Landed Amount: `₹ 24,97,750.00`. +7. Click **Book Contract**. Verify unique contract ID `SDA-26-XXXXX` generated with status `ACTIVE`. + +--- + +### Protocol 3: Vehicle Gate Pass Entry & Verification (`TC-INW-005-01` / `03`) +1. Log in as `guard@alpha.com` and navigate to `/receiving/gate-entry`. +2. Click **New Gate Entry**. +3. Enter Vehicle Number: `RJ-20-GA-4581`. +4. Enter 12-digit e-Way Bill: `241089201923`. (Test: enter 11 digits and verify validation error). +5. Enter Driver Name: `Ramesh Singh`, Mobile: `9829012345`. +6. Select Purchase Sauda: Select `SDA-26-XXXXX` booked in Protocol 2. +7. Enter Supplier Invoice Weight: `25.000 MT`, Bags: `500 Bags`. +8. Check Security Seal Intact. +9. Click **Confirm Yard Entry**. Verify gate pass issued (`GP-26-XXXXX`) and status is `GATE_IN`. + +--- + +### Protocol 4: Weighbridge Gross/Tare Logging & Bag Tare Worksheet (`TC-INW-005-01` / `02`) +1. Log in as `weighman@alpha.com` and navigate to `/receiving/weighbridge`. +2. Select active truck on scale: `GP-26-XXXXX (RJ-20-GA-4581)`. +3. Capture Gross Weighment: `38.450 MT`. Click **Log Gross Weight**. Truck moves to unloading bay. +4. After cargo is unloaded, truck re-enters weighbridge for empty tare weighment. +5. Enter Tare Weighment: `13.200 MT`. + - Test Invariant: Enter `39.000 MT` and verify error: `"Tare weight must be strictly less than Gross weight"`. +6. Unloaded Weight computed: $38.450 - 13.200 = 25.250\text{ MT}$. +7. Fill Bag Tare Worksheet (*Bardana Katai*): + - Packaging Type: `50kg New Jute Gunny (0.650 kg/bag)`. + - Physical Bags Counted: `500 Bags`. + - System calculates Bag Tare: $(500 \times 0.650) / 1000 = 0.325\text{ MT}$. + - Final Net Revenue Weight: $25.250 - 0.325 = 24.925\text{ MT}$. + - Transit Shortage: $24.925 - 25.000 = -0.075\text{ MT}$ ($-0.30\%$). + - Shortage within $0.50\%$ tolerance $\to$ no warning blocker. +8. Click **Save Weighment Slip**. + +--- + +### Protocol 5: Goods Receipt Note (GRN) Posting & Lot Minting (`TC-INW-005-01` / `04`) +1. Log in as `supervisor@alpha.com` and navigate to `/receiving/grn`. +2. Open weighment slip from Protocol 4. +3. Select Warehouse: `Kota Central Warehouse`, Godown: `Godown 02`, Stack: `Stack B-04`. +4. Click **Confirm & Post GRN**. +5. **Verification Checks:** + - Formal GRN generated: `GRN-26-XXXXX`. + - Traceable Lot minted: `LOT-26-10-SOY-XXXXX`. + - Verify initial status of newly minted lot is strictly **`QUALITY_HOLD`**. + - Navigate to `/procurement/sauda` and check contract `SDA-26-XXXXX`: + - Cumulative received updated to `24.925 MT`. + - Contract status transitioned to `PARTIALLY_RECEIVED`. + +--- + +### Protocol 6: Quality Lab Analytical Assay, Rebate & Release FSM (`TC-QC-006-01` / `03`) +1. Log in as `chemist@alpha.com` and navigate to `/quality/inspection`. +2. Locate lot `LOT-26-10-SOY-XXXXX` in queue (Status: `QUALITY_HOLD`). +3. Click **Conduct Inspection**. +4. Enter Sample Code: `SMP-2026-9042`. +5. Enter Assay Parameters: + - Moisture %: `11.50 %` (FAQ benchmark max `10.0%` $\to$ $+1.50\%$ excess). + - Foreign Matter %: `2.10 %` (FAQ benchmark max `1.5%` $\to$ $+0.60\%$ excess). + - Damaged Grain %: `1.80 %` (within benchmark). + - Oil Content %: `18.40 %`. +6. Inspect Auto-Calculated Rebates: + - Moisture Excess Weight Cut: $24.925 \times 1.50\% = 0.374\text{ MT}$. + - Net Billable Weight after QC: `24.551 MT`. + - Foreign Matter Rate Deduction: `₹ 18.00 / Qtl`. + - Total Quality Rebate: `₹ 14,850.00`. +7. **Adversarial FSM Test:** + - Log in as `trader@alpha.com` or `guard@alpha.com`. + - Attempt to book an outward sales order or dispatch ticket for `LOT-26-10-SOY-XXXXX`. + - Verify operation is blocked: `"Cannot dispatch produce under Quality Hold"`. +8. Switch back to `chemist@alpha.com`: + - Set Decision: `RELEASED`. + - Enter Remarks: `"Produce accepted with commercial moisture and admixture rebate"`. + - Click **Commit FSM Decision**. +9. Verify lot status transitions to `RELEASED`. +10. Verify lot is now eligible for trading and outward allocation. + +--- + +### Protocol 7: Lot Ancestry & Digital Lineage Traversal (`TC-QC-006-04`) +1. Navigate to `/inventory/lots` and select `LOT-26-10-SOY-XXXXX`. +2. Click **View Lineage Tree**. +3. Confirm genealogical hierarchy displays: + - `SDA-26-XXXXX` (Procurement Contract - Kisan Agro Traders) + $\to$ `GP-26-XXXXX` (Gate Pass - Vehicle RJ-20-GA-4581) + $\to$ `WS-26-XXXXX` (Weighbridge Slip - Gross 38.450 / Tare 13.200) + $\to$ `GRN-26-XXXXX` (Goods Receipt Note - 24.925 MT) + $\to$ `LOT-26-10-SOY-XXXXX` (Stack B-04 / Released / Rebate ₹ 14,850) + +--- + +### Protocol 8: PostgreSQL RLS Cross-Tenant Security Boundary (`TC-TENANT-017-03`) +1. Log in as `admin@beta.com` in `tenant-beta`. +2. Attempt to query market observations, purchase saudas, gate entries, GRNs, or lots created in `tenant-alpha`. +3. Verify that zero records from `tenant-alpha` are returned in API responses or UI screens. +4. Attempt direct API request: `GET /api/v1/quality/lots/{tenant_alpha_lot_id}` while authenticated in `tenant-beta`. +5. Verify response returns HTTP 404 Not Found. Zero cross-tenant data bleed. + +--- + +## 5. Exit Criteria & Sign-Off Checklist + +Before passing Gate 14.1 for Iteration 03, QA leads must sign off on: +- [ ] All 8 manual test protocols executed and passing without critical deviations. +- [ ] 21-sheet Excel QA Workbook `Iteration03_Mandi_Procurement_Receiving_QC_Complete_Manual_Testcases.xlsx` compiled and verified ($\ge 20$ dense test cases). +- [ ] Automated regression suite achieves configured test coverage budget ($\ge 95\%$ statement coverage). +- [ ] Zero cross-tenant data leakage across PostgreSQL RLS boundary. + diff --git a/04_generated_documentation/07_test_design/manual_qa/workbooks/.~lock.Iteration01_Authentication_and_Session_Governance_Complete_Manual_Testcases.xlsx# b/04_generated_documentation/07_test_design/manual_qa/workbooks/.~lock.Iteration01_Authentication_and_Session_Governance_Complete_Manual_Testcases.xlsx# new file mode 100644 index 0000000..4787278 --- /dev/null +++ b/04_generated_documentation/07_test_design/manual_qa/workbooks/.~lock.Iteration01_Authentication_and_Session_Governance_Complete_Manual_Testcases.xlsx# @@ -0,0 +1 @@ +,ps-ch,ch-ub,12.10.2026 13:17,file:///home/ps-ch/.config/libreoffice/4; \ No newline at end of file diff --git a/04_generated_documentation/07_test_design/manual_qa/workbooks/Iteration03_Mandi_Procurement_Receiving_QC_Complete_Manual_Testcases.xlsx b/04_generated_documentation/07_test_design/manual_qa/workbooks/Iteration03_Mandi_Procurement_Receiving_QC_Complete_Manual_Testcases.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..3266943af0731d8940b0047b5bee6b3d2c265540 GIT binary patch literal 33248 zcmZ^qV~i+U)2L^UZQC~X*tTuk_8!}|ZQHhuJ+|$+bKWnx_nt3#e^htUE8R&|t?DO* zB_|04j0^w(01iNJDy4liMx?Ft3jn|f1^@u*=c%Tkt&NkhjgzjDyPdJ4Hm#er)l^D{ z%m6)d@H0=)VUqZWv?-C@ErgtyLmoG^WlE-)200aB(V^MVBEBk`thCb*p2wK zX@*P#i-I&Hcz+AQSYsl7uD@$X~#_HK*8_7TDM!{QwYK0lO9f zy*0iP`Z`#t%Ee_@%E1a<@RIQ&jX$IFPSg^XfT{G59XMVbdel838dXkua2aZA4Q{ie zYg^r}XsULHnKqIr2HKUh??a;AW*--1LaA#gHy`y_ZTTp7z4hIs> z3<_4wZf!pArq+$`-m~%4thHN6l$y1i?TPu1`IT1z0%gcP)11m#1`@#0n=x-T0Y2v! zb~~=GP30a!xR^$czktSd*%=A3(S+D&!|b#WcF~b`TS@yF2>R^>0|kqf_)5{0739kc z_msqi%j3h9Nl>aJD0PyQ1}V!@Sqco6FM6gpMuoq{(tQBr{^btskO$hvA2(3{xCH9w zuIpfIvKW6%Hqm_N$7 zS<(HEey+9-mIk)AmjCRw|LEGaB55%|5C3PkOO~L~_COx-nE%2`f?y*amv0qmV=y_g zkjLRYyg3lGe^xjxDK1F#`)pwSl6RQDGY_t-p(s$D7G!;$rOR6K)xp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GxxGg?=Pp5(_H!LwB)^36O1gGlV&zq}%?ASI#UEp)AK3}|EGDbM(O0%> zLB#O9hz=J(r*$U5>_zp)bJ}P2R zc;JGN;YT3dUF3&buXOrO@F#gDnTy0mC`eMs zCPF8+Wl+6U6La4$ia{EwXIZF z3xAY_Eu4pKB>RPT>m_2g(c-lbepl`6`u0xwQpjW5Tm=~G#RAB`{}<&8%fALL#{d6w zy+{eYKtaPb<}pfU#45e4@?$LL^I_wS29}1iKE{3eR#a)J5xACu&41wg61$O&15Rj} z$;M;qh{Y_VpC)tcJJ^&yw3QS>vop;B1SXEJr z%)mx(Ex3%m3Uyt$?!2gjHcvT6l_fUKxB*qFEdVSfxGF15qFBitc&n|Im9##@XD);t zuOl4|uDzMeph*3RIry?ej(eZ_LZ{xR7ZS+wqd+tv2R5!-A=}-#B$Fenm1GvwUue6mzf~_!dOa_*KmUmNg;iT? zpw}TgUr41Rh_6DJe<-6b^K=C~EL7{M{|&r&7CKM?jbIUTz|B#auOhi;(M2iatz%ev zdQ1<$o;)0`dp`3PAjyIn3`DzMpFR zXQ3^~?`9SMWybM)&inbie>lg0d6EBadh!2FNq)ch{ruKHiy;B--G5ATeZTbmK+-=; z9RaNt|JH2dpI#g9Devc6{-HQP|CRDvZT6n>eg@wk3JhQ>?O$HYZ+XCb%KQ0je<*B# z!N-50{H_{(PkBET<_`r7FuU_Fl;34p?KpzfykR zCcdYKMUVkViEPti^P9VLfyl?9Ahmz0rR|@m*IOIL%z3}}H zW>E0&nBTVkJ?6bU@(<=v{O_2*Zr}HUmOmIDxxZunx_{pnI{(3xtNb1F*A4u>l<*HG zM)U8OzwY4og*tyQo_c@B{B;YzzXSh+`C$Ba%wPBL`&*_z7#Z`wWB$5{-zPr*U|wzh zj``~@ejh*oAB^K)G5?CD-*3P7KFS}=w#VNw|K7#m0OJk>gah~l1K8?8uYZ2}e_m4o AeE None: + if op and sa: + op.create_table( + "market_observations", + sa.Column("id", sa.String(36), primary_key=True), + sa.Column("tenant_id", sa.String(36), nullable=False), + sa.Column("mandi_id", sa.String(36), nullable=False), + sa.Column("observation_date", sa.Date(), nullable=False), + sa.Column("commodity_id", sa.String(36), nullable=False), + sa.Column("variety", sa.String(64), nullable=False), + sa.Column("grade", sa.String(32), server_default="FAQ"), + sa.Column("arrival_mt", sa.Numeric(12, 3), nullable=False, server_default="0.0"), + sa.Column("internal_stock_mt", sa.Numeric(12, 3), nullable=True), + sa.Column("min_rate", sa.Numeric(10, 2), nullable=True), + sa.Column("max_rate", sa.Numeric(10, 2), nullable=True), + sa.Column("modal_rate", sa.Numeric(10, 2), nullable=True), + sa.Column("source", sa.String(32), server_default="APMC_BULLETIN"), + sa.Column("is_market_closed", sa.Boolean(), server_default=sa.text("false")), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now()), + sa.UniqueConstraint( + "tenant_id", "mandi_id", "commodity_id", "variety", "observation_date", + name="uq_market_obs_mandi_comm_date" + ) + ) + op.create_index("ix_market_obs_tenant", "market_observations", ["tenant_id"]) + op.create_index("ix_market_obs_mandi", "market_observations", ["mandi_id"]) + op.create_index("ix_market_obs_date", "market_observations", ["observation_date"]) + + conn = op.get_bind() + if conn.dialect.name == "postgresql": + op.execute("ALTER TABLE market_observations ENABLE ROW LEVEL SECURITY;") + op.execute("ALTER TABLE market_observations FORCE ROW LEVEL SECURITY;") + op.execute(""" + CREATE POLICY market_obs_tenant_isolation ON market_observations + FOR ALL + USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')) + WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')); + """) + + +def downgrade() -> None: + if op: + op.drop_table("market_observations") + diff --git a/05_implementation_workspace/backend/alembic/versions/006_procurement_contracts.py b/05_implementation_workspace/backend/alembic/versions/006_procurement_contracts.py new file mode 100644 index 0000000..67e8cc7 --- /dev/null +++ b/05_implementation_workspace/backend/alembic/versions/006_procurement_contracts.py @@ -0,0 +1,79 @@ +"""Create procurement_sauda table with PostgreSQL RLS isolation. + +Revision ID: 006_procurement_contracts +Revises: 005_market_desk +Create Date: 2026-10-12 +Standard: UP-AI v1.5 / LLD-004 / database_design.md +Fulfills: FR-PROCUREMENTCONTRACTS-001..004 (UC-004) +""" +from typing import Sequence, Union + +try: + from alembic import op + import sqlalchemy as sa +except ImportError: + op = None + sa = None + +revision: str = "006_procurement_contracts" +down_revision: Union[str, None] = "005_market_desk" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + if op and sa: + op.create_table( + "procurement_sauda", + sa.Column("id", sa.String(36), primary_key=True), + sa.Column("tenant_id", sa.String(36), nullable=False), + sa.Column("sauda_number", sa.String(32), nullable=False, unique=True), + sa.Column("contract_date", sa.Date(), nullable=False), + sa.Column("delivery_due_date", sa.Date(), nullable=False), + sa.Column("supplier_id", sa.String(36), nullable=False), + sa.Column("mandi_id", sa.String(36), nullable=False), + sa.Column("trade_type", sa.String(32), server_default="MANDI_AUCTION"), + sa.Column("commodity_id", sa.String(36), nullable=False), + sa.Column("variety", sa.String(64), nullable=False), + sa.Column("grade", sa.String(32), server_default="FAQ"), + sa.Column("booked_quantity_mt", sa.Numeric(12, 3), nullable=False), + sa.Column("estimated_bags", sa.Integer(), server_default="0"), + sa.Column("trade_rate_per_qtl", sa.Numeric(10, 2), nullable=False), + sa.Column("cumulative_received_mt", sa.Numeric(12, 3), server_default="0.0"), + sa.Column("balance_mt", sa.Numeric(12, 3), nullable=False), + sa.Column("credit_period_days", sa.Integer(), server_default="0"), + sa.Column("payment_due_date", sa.Date(), nullable=False), + sa.Column("advance_amount", sa.Numeric(12, 2), server_default="0.0"), + sa.Column("mandi_cess_pct", sa.Numeric(5, 2), server_default="1.50"), + sa.Column("krishi_kalyan_pct", sa.Numeric(5, 2), server_default="0.50"), + sa.Column("brokerage_rate_pct", sa.Numeric(5, 2), server_default="1.00"), + sa.Column("gross_amount", sa.Numeric(14, 2), nullable=False), + sa.Column("mandi_cess_amount", sa.Numeric(12, 2), nullable=False), + sa.Column("krishi_kalyan_amount", sa.Numeric(12, 2), nullable=False), + sa.Column("brokerage_amount", sa.Numeric(12, 2), nullable=False), + sa.Column("total_landed_amount", sa.Numeric(14, 2), nullable=False), + sa.Column("variance_pct", sa.Numeric(5, 2), server_default="0.0"), + sa.Column("variance_acknowledged", sa.Boolean(), server_default=sa.text("false")), + sa.Column("status", sa.String(32), server_default="ACTIVE"), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now()) + ) + op.create_index("ix_sauda_tenant", "procurement_sauda", ["tenant_id"]) + op.create_index("ix_sauda_supplier", "procurement_sauda", ["supplier_id"]) + op.create_index("ix_sauda_status", "procurement_sauda", ["status"]) + + conn = op.get_bind() + if conn.dialect.name == "postgresql": + op.execute("ALTER TABLE procurement_sauda ENABLE ROW LEVEL SECURITY;") + op.execute("ALTER TABLE procurement_sauda FORCE ROW LEVEL SECURITY;") + op.execute(""" + CREATE POLICY sauda_tenant_isolation ON procurement_sauda + FOR ALL + USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')) + WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')); + """) + + +def downgrade() -> None: + if op: + op.drop_table("procurement_sauda") + diff --git a/05_implementation_workspace/backend/alembic/versions/007_inward_receiving.py b/05_implementation_workspace/backend/alembic/versions/007_inward_receiving.py new file mode 100644 index 0000000..75ed90a --- /dev/null +++ b/05_implementation_workspace/backend/alembic/versions/007_inward_receiving.py @@ -0,0 +1,108 @@ +"""Create inward receiving, weighbridge slips, and goods receipt notes tables with RLS. + +Revision ID: 007_inward_receiving +Revises: 006_procurement_contracts +Create Date: 2026-10-12 +Standard: UP-AI v1.5 / LLD-003 / database_design.md +Fulfills: FR-INWARDRECEIVING-001..005 (UC-005) +""" +from typing import Sequence, Union + +try: + from alembic import op + import sqlalchemy as sa +except ImportError: + op = None + sa = None + +revision: str = "007_inward_receiving" +down_revision: Union[str, None] = "006_procurement_contracts" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + if op and sa: + # 1. Inward Gate Entries + op.create_table( + "inward_gate_entries", + sa.Column("id", sa.String(36), primary_key=True), + sa.Column("tenant_id", sa.String(36), nullable=False), + sa.Column("gate_pass_number", sa.String(32), nullable=False, unique=True), + sa.Column("gate_in_timestamp", sa.DateTime(timezone=True), server_default=sa.func.now()), + sa.Column("vehicle_number", sa.String(16), nullable=False), + sa.Column("eway_bill_number", sa.String(12), nullable=False), + sa.Column("driver_name", sa.String(100), nullable=False), + sa.Column("driver_mobile", sa.String(10), nullable=False), + sa.Column("sauda_id", sa.String(36), nullable=False), + sa.Column("supplier_invoice_no", sa.String(64), nullable=False), + sa.Column("supplier_dispatch_weight_mt", sa.Numeric(12, 3), nullable=False), + sa.Column("supplier_dispatch_bags", sa.Integer(), nullable=False), + sa.Column("is_seal_intact", sa.Boolean(), server_default=sa.text("true")), + sa.Column("status", sa.String(32), server_default="GATE_IN") + ) + op.create_index("ix_gate_tenant", "inward_gate_entries", ["tenant_id"]) + op.create_index("ix_gate_vehicle", "inward_gate_entries", ["vehicle_number"]) + op.create_index("ix_gate_sauda", "inward_gate_entries", ["sauda_id"]) + + # 2. Weighbridge Slips + op.create_table( + "weighbridge_slips", + sa.Column("id", sa.String(36), primary_key=True), + sa.Column("tenant_id", sa.String(36), nullable=False), + sa.Column("slip_number", sa.String(32), nullable=False, unique=True), + sa.Column("gate_pass_id", sa.String(36), nullable=False), + sa.Column("gross_weight_mt", sa.Numeric(12, 3), nullable=False), + sa.Column("gross_timestamp", sa.DateTime(timezone=True), server_default=sa.func.now()), + sa.Column("tare_weight_mt", sa.Numeric(12, 3), nullable=True), + sa.Column("tare_timestamp", sa.DateTime(timezone=True), nullable=True), + sa.Column("unloaded_weight_mt", sa.Numeric(12, 3), nullable=True), + sa.Column("bag_packaging_type", sa.String(32), nullable=True), + sa.Column("bag_tare_rate_kg", sa.Numeric(6, 3), nullable=True), + sa.Column("actual_bag_count", sa.Integer(), server_default="0"), + sa.Column("bag_tare_deduction_mt", sa.Numeric(12, 3), server_default="0.0"), + sa.Column("final_net_weight_mt", sa.Numeric(12, 3), nullable=True), + sa.Column("shortage_weight_mt", sa.Numeric(12, 3), nullable=True), + sa.Column("shortage_pct", sa.Numeric(5, 2), nullable=True), + sa.Column("is_shortage_exceeded", sa.Boolean(), server_default=sa.text("false")) + ) + op.create_index("ix_weighment_tenant", "weighbridge_slips", ["tenant_id"]) + op.create_index("ix_weighment_gate_pass", "weighbridge_slips", ["gate_pass_id"]) + + # 3. Goods Receipt Notes + op.create_table( + "goods_receipt_notes", + sa.Column("id", sa.String(36), primary_key=True), + sa.Column("tenant_id", sa.String(36), nullable=False), + sa.Column("grn_number", sa.String(32), nullable=False, unique=True), + sa.Column("grn_date", sa.DateTime(timezone=True), server_default=sa.func.now()), + sa.Column("weighment_slip_id", sa.String(36), nullable=False), + sa.Column("sauda_id", sa.String(36), nullable=False), + sa.Column("godown_id", sa.String(36), nullable=False), + sa.Column("godown_stack_id", sa.String(36), nullable=False), + sa.Column("accepted_quantity_mt", sa.Numeric(12, 3), nullable=False), + sa.Column("accepted_bags", sa.Integer(), nullable=False), + sa.Column("status", sa.String(32), server_default="POSTED") + ) + op.create_index("ix_grn_tenant", "goods_receipt_notes", ["tenant_id"]) + op.create_index("ix_grn_sauda", "goods_receipt_notes", ["sauda_id"]) + + conn = op.get_bind() + if conn.dialect.name == "postgresql": + for tbl in ["inward_gate_entries", "weighbridge_slips", "goods_receipt_notes"]: + op.execute(f"ALTER TABLE {tbl} ENABLE ROW LEVEL SECURITY;") + op.execute(f"ALTER TABLE {tbl} FORCE ROW LEVEL SECURITY;") + op.execute(f""" + CREATE POLICY {tbl}_tenant_isolation ON {tbl} + FOR ALL + USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')) + WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')); + """) + + +def downgrade() -> None: + if op: + op.drop_table("goods_receipt_notes") + op.drop_table("weighbridge_slips") + op.drop_table("inward_gate_entries") + diff --git a/05_implementation_workspace/backend/alembic/versions/008_quality_and_lots.py b/05_implementation_workspace/backend/alembic/versions/008_quality_and_lots.py new file mode 100644 index 0000000..706be2f --- /dev/null +++ b/05_implementation_workspace/backend/alembic/versions/008_quality_and_lots.py @@ -0,0 +1,89 @@ +"""Create inventory_lots and quality_inspections tables with RLS. + +Revision ID: 008_quality_and_lots +Revises: 007_inward_receiving +Create Date: 2026-10-12 +Standard: UP-AI v1.5 / LLD-003 / database_design.md +Fulfills: FR-INWARDRECEIVING-006, FR-QUALITYANDLOTCONTROL-001..004 (UC-006) +""" +from typing import Sequence, Union + +try: + from alembic import op + import sqlalchemy as sa +except ImportError: + op = None + sa = None + +revision: str = "008_quality_and_lots" +down_revision: Union[str, None] = "007_inward_receiving" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + if op and sa: + # 1. Inventory Lots + op.create_table( + "inventory_lots", + sa.Column("id", sa.String(36), primary_key=True), + sa.Column("tenant_id", sa.String(36), nullable=False), + sa.Column("lot_number", sa.String(32), nullable=False, unique=True), + sa.Column("grn_id", sa.String(36), nullable=False), + sa.Column("commodity_id", sa.String(36), nullable=False), + sa.Column("variety", sa.String(64), nullable=False), + sa.Column("grade", sa.String(32), server_default="FAQ"), + sa.Column("godown_stack_id", sa.String(36), nullable=False), + sa.Column("initial_quantity_mt", sa.Numeric(12, 3), nullable=False), + sa.Column("current_quantity_mt", sa.Numeric(12, 3), nullable=False), + sa.Column("qc_status", sa.String(32), server_default="QUALITY_HOLD"), + sa.Column("parent_lot_id", sa.String(36), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now()) + ) + op.create_index("ix_lot_tenant", "inventory_lots", ["tenant_id"]) + op.create_index("ix_lot_grn", "inventory_lots", ["grn_id"]) + op.create_index("ix_lot_qc_status", "inventory_lots", ["qc_status"]) + op.create_index("ix_lot_parent", "inventory_lots", ["parent_lot_id"]) + + # 2. Quality Inspections + op.create_table( + "quality_inspections", + sa.Column("id", sa.String(36), primary_key=True), + sa.Column("tenant_id", sa.String(36), nullable=False), + sa.Column("lot_id", sa.String(36), nullable=False), + sa.Column("sample_code", sa.String(32), nullable=False), + sa.Column("inspection_timestamp", sa.DateTime(timezone=True), server_default=sa.func.now()), + sa.Column("inspector_email", sa.String(255), nullable=False), + sa.Column("moisture_pct", sa.Numeric(5, 2), nullable=False), + sa.Column("foreign_matter_pct", sa.Numeric(5, 2), nullable=False), + sa.Column("damaged_grain_pct", sa.Numeric(5, 2), server_default="0.0"), + sa.Column("oil_content_pct", sa.Numeric(5, 2), server_default="0.0"), + sa.Column("moisture_weight_deduction_mt", sa.Numeric(12, 3), server_default="0.0"), + sa.Column("net_billable_weight_mt", sa.Numeric(12, 3), nullable=False), + sa.Column("rate_deduction_per_qtl", sa.Numeric(10, 2), server_default="0.0"), + sa.Column("total_rebate_amount", sa.Numeric(12, 2), server_default="0.0"), + sa.Column("decision", sa.String(32), nullable=False), + sa.Column("rejection_reason", sa.String(255), nullable=True), + sa.Column("remarks", sa.String(255), nullable=True) + ) + op.create_index("ix_qc_tenant", "quality_inspections", ["tenant_id"]) + op.create_index("ix_qc_lot", "quality_inspections", ["lot_id"]) + + conn = op.get_bind() + if conn.dialect.name == "postgresql": + for tbl in ["inventory_lots", "quality_inspections"]: + op.execute(f"ALTER TABLE {tbl} ENABLE ROW LEVEL SECURITY;") + op.execute(f"ALTER TABLE {tbl} FORCE ROW LEVEL SECURITY;") + op.execute(f""" + CREATE POLICY {tbl}_tenant_isolation ON {tbl} + FOR ALL + USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')) + WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')); + """) + + +def downgrade() -> None: + if op: + op.drop_table("quality_inspections") + op.drop_table("inventory_lots") + diff --git a/05_implementation_workspace/backend/app/api/market.py b/05_implementation_workspace/backend/app/api/market.py new file mode 100644 index 0000000..2980677 --- /dev/null +++ b/05_implementation_workspace/backend/app/api/market.py @@ -0,0 +1,247 @@ +"""Market Desk API Controller. + +Fulfills: +- STORY-MKT-001 (FR-MKT-001): Capture Daily Mandi Arrival Observations. +- STORY-MKT-002 (FR-MKT-002): Capture Daily Mandi Price Range and Modal Rate. +""" +from datetime import datetime, date, timezone +from decimal import Decimal +import logging +from typing import Any, Dict, List, Optional +import uuid + +from backend.app.api.auth import auth_controller +from backend.app.auth.tenant_context import ( + TenantContext, + TenantContextResolutionError, + TenantContextResolver, + context_resolver, + record_audit_event, +) +from backend.app.db.session import storage +from backend.app.models.market import MarketObservation, validate_market_observation + +logger = logging.getLogger("atb.api.market") + + +class MarketController: + """Handles daily mandi observations and modal price bulletin endpoints.""" + + def __init__(self, store=storage, resolver=None): + self.store = store + self.resolver = resolver or TenantContextResolver(store=self.store) + + def _authenticate_and_resolve( + self, auth_header: Optional[str], tenant_header: Optional[str] + ) -> Dict[str, Any]: + """Resolves verified caller session and active tenant context.""" + session = auth_controller.get_session(auth_header) + if not session.get("authenticated"): + return {"authenticated": False, "error": session.get("error", "UNAUTHENTICATED"), "status_code": 401} + + user_id = session.get("subject", "") + email = session.get("email", user_id) + user_roles = session.get("roles", []) + + try: + ctx = self.resolver.resolve_context( + subject_id=user_id, + email=email, + user_roles=user_roles, + requested_tenant_id=tenant_header + ) + except TenantContextResolutionError as err: + return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code} + + return { + "authenticated": True, + "session": session, + "context": ctx, + "tenant_id": ctx.tenant_id, + "user_id": user_id + } + + def record_observation( + self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any] + ) -> Dict[str, Any]: + """POST /api/v1/market/observations (FR-MKT-001, FR-MKT-002).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + ctx = auth_res["context"] + + # Check required roles + allowed_roles = {"Mandi Buyer", "Desk Trader", "Procurement Officer", "Tenant Administrator"} + if not any(r in allowed_roles for r in ctx.roles): + return { + "error": "INSUFFICIENT_PERMISSIONS", + "message": "Only Mandi Buyers, Desk Traders, or Tenant Admins can record daily observations", + "status_code": 403 + } + + # Parse inputs + try: + mandi_id = payload.get("mandi_id") + commodity_id = payload.get("commodity_id") + variety = payload.get("variety", "") + grade = payload.get("grade", "FAQ") + date_str = payload.get("observation_date") + obs_date = datetime.strptime(date_str, "%Y-%m-%d").date() if isinstance(date_str, str) else date_str + is_market_closed = payload.get("is_market_closed", False) + + arrival_mt = Decimal(str(payload.get("arrival_mt", "0.0"))) + internal_stock_mt = Decimal(str(payload["internal_stock_mt"])) if payload.get("internal_stock_mt") is not None else None + min_rate = Decimal(str(payload["min_rate"])) if payload.get("min_rate") is not None else None + max_rate = Decimal(str(payload["max_rate"])) if payload.get("max_rate") is not None else None + modal_rate = Decimal(str(payload["modal_rate"])) if payload.get("modal_rate") is not None else None + source = payload.get("source", "APMC_BULLETIN") + + if not mandi_id or not commodity_id or not variety or not obs_date: + return { + "error": "VALIDATION_ERROR", + "message": "mandi_id, commodity_id, variety, and observation_date are mandatory", + "status_code": 422 + } + + # Enforce duplicate observation constraint + dup = self.store.query( + "market_observations", + tenant_id, + lambda o: ( + o.get("mandi_id") == mandi_id and + o.get("commodity_id") == commodity_id and + o.get("variety") == variety and + o.get("observation_date") == str(obs_date) + ) + ) + if dup: + return { + "error": "DUPLICATE_OBSERVATION", + "message": "Duplicate observation already exists for this market, commodity, variety, and date", + "status_code": 409 + } + + # Create observation model + obs = MarketObservation( + tenant_id=tenant_id, + mandi_id=mandi_id, + observation_date=obs_date, + commodity_id=commodity_id, + variety=variety, + grade=grade, + arrival_mt=arrival_mt, + internal_stock_mt=internal_stock_mt, + min_rate=min_rate, + max_rate=max_rate, + modal_rate=modal_rate, + source=source, + is_market_closed=is_market_closed + ) + + # Persist + data = obs.to_dict() + self.store.insert("market_observations", tenant_id, data) + + # Audit trail + record_audit_event( + store=self.store, + tenant_id=tenant_id, + actor_user_id=auth_res["user_id"], + action_type="RECORD_MARKET_OBSERVATION", + resource_type="market_observation", + resource_id=obs.id, + before_state=None, + after_state={"mandi_id": mandi_id, "commodity": commodity_id, "modal_rate": float(modal_rate) if modal_rate else None} + ) + + return { + "success": True, + "observation": data, + "status_code": 201 + } + + except ValueError as e: + return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} + except Exception as e: + logger.exception("Failed to record market observation") + return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} + + def list_observations( + self, + auth_header: Optional[str], + tenant_header: Optional[str], + mandi_id: Optional[str] = None, + date_filter: Optional[str] = None + ) -> Dict[str, Any]: + """GET /api/v1/market/observations (FR-MKT-001).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + + def predicate(o): + if mandi_id and o.get("mandi_id") != mandi_id: + return False + if date_filter and o.get("observation_date") != date_filter: + return False + return True + + records = self.store.query("market_observations", tenant_id, predicate) + return { + "success": True, + "count": len(records), + "observations": records, + "status_code": 200 + } + + def get_latest_rates( + self, + auth_header: Optional[str], + tenant_header: Optional[str], + commodity_id: str, + mandi_id: Optional[str] = None + ) -> Dict[str, Any]: + """GET /api/v1/market/rates/latest (FR-MKT-002).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + + def predicate(o): + if o.get("commodity_id") != commodity_id: + return False + if mandi_id and o.get("mandi_id") != mandi_id: + return False + return not o.get("is_market_closed", False) + + records = self.store.query("market_observations", tenant_id, predicate) + if not records: + return { + "success": True, + "commodity_id": commodity_id, + "mandi_id": mandi_id, + "benchmark_modal_rate": None, + "message": "No active observations found for commodity", + "status_code": 200 + } + + # Sort by date descending + records.sort(key=lambda x: x.get("observation_date", ""), reverse=True) + latest = records[0] + return { + "success": True, + "commodity_id": commodity_id, + "mandi_id": latest.get("mandi_id"), + "observation_date": latest.get("observation_date"), + "benchmark_modal_rate": latest.get("modal_rate"), + "min_rate": latest.get("min_rate"), + "max_rate": latest.get("max_rate"), + "status_code": 200 + } + + +market_controller = MarketController() diff --git a/05_implementation_workspace/backend/app/api/procurement.py b/05_implementation_workspace/backend/app/api/procurement.py new file mode 100644 index 0000000..b56855c --- /dev/null +++ b/05_implementation_workspace/backend/app/api/procurement.py @@ -0,0 +1,239 @@ +"""Procurement Contracts & Sauda Booking API Controller. + +Fulfills: +- STORY-PROC-001 (FR-PROCUREMENTCONTRACTS-002): Mandi Auction & Direct Purchase Sauda Booking. +- STORY-PROC-002 (FR-PROCUREMENTCONTRACTS-001): Price Variance Alert vs. Modal Rate. +- STORY-PROC-003 (FR-PROCUREMENTCONTRACTS-003): Supplier Credit Terms & Advance Recording. +- STORY-PROC-004 (FR-PROCUREMENTCONTRACTS-004): Mandi Cess & Statutory Levies Breakdown. +""" +from datetime import datetime, date, timezone +from decimal import Decimal +import logging +from typing import Any, Dict, List, Optional +import uuid + +from backend.app.api.auth import auth_controller +from backend.app.auth.tenant_context import ( + TenantContext, + TenantContextResolutionError, + TenantContextResolver, + context_resolver, + record_audit_event, +) +from backend.app.db.session import storage +from backend.app.models.procurement import ProcurementSauda, calculate_sauda_commercials +from sandbox.master_data_mock import MasterDataMock + +logger = logging.getLogger("atb.api.procurement") + + +class ProcurementController: + """Handles purchase contracts, price variance checks, and commercial settlements.""" + + def __init__(self, store=storage, resolver=None): + self.store = store + self.resolver = resolver or TenantContextResolver(store=self.store) + + def _authenticate_and_resolve( + self, auth_header: Optional[str], tenant_header: Optional[str] + ) -> Dict[str, Any]: + """Resolves verified caller session and active tenant context.""" + session = auth_controller.get_session(auth_header) + if not session.get("authenticated"): + return {"authenticated": False, "error": session.get("error", "UNAUTHENTICATED"), "status_code": 401} + + user_id = session.get("subject", "") + email = session.get("email", user_id) + user_roles = session.get("roles", []) + + try: + ctx = self.resolver.resolve_context( + subject_id=user_id, + email=email, + user_roles=user_roles, + requested_tenant_id=tenant_header + ) + except TenantContextResolutionError as err: + return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code} + + return { + "authenticated": True, + "session": session, + "context": ctx, + "tenant_id": ctx.tenant_id, + "user_id": user_id + } + + def book_sauda( + self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any] + ) -> Dict[str, Any]: + """POST /api/v1/procurement/sauda (FR-PROCUREMENTCONTRACTS-001..004).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + ctx = auth_res["context"] + + # Check required roles + allowed_roles = {"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", + "status_code": 403 + } + + try: + supplier_id = payload.get("supplier_id") + mandi_id = payload.get("mandi_id") + commodity_id = payload.get("commodity_id") + variety = payload.get("variety", "") + grade = payload.get("grade", "FAQ") + trade_type = payload.get("trade_type", "MANDI_AUCTION") + + # Validate supplier active status + supp = MasterDataMock.get_supplier(supplier_id) + if supp and supp.get("status") != "ACTIVE": + return { + "error": "INACTIVE_SUPPLIER", + "message": f"Supplier '{supp.get('name')}' is currently {supp.get('status')}. Cannot book contracts.", + "status_code": 400 + } + + contract_date_str = payload.get("contract_date") + c_date = datetime.strptime(contract_date_str, "%Y-%m-%d").date() if isinstance(contract_date_str, str) else contract_date_str + + delivery_due_str = payload.get("delivery_due_date") + d_date = datetime.strptime(delivery_due_str, "%Y-%m-%d").date() if isinstance(delivery_due_str, str) else delivery_due_str + + booked_quantity_mt = Decimal(str(payload.get("booked_quantity_mt", "0.0"))) + trade_rate_per_qtl = Decimal(str(payload.get("trade_rate_per_qtl", "0.0"))) + estimated_bags = int(payload.get("estimated_bags", 0)) + credit_period_days = int(payload.get("credit_period_days", 0)) + advance_amount = Decimal(str(payload.get("advance_amount", "0.0"))) + + mandi_cess_pct = Decimal(str(payload.get("mandi_cess_pct", "1.50"))) + krishi_kalyan_pct = Decimal(str(payload.get("krishi_kalyan_pct", "0.50"))) + brokerage_rate_pct = Decimal(str(payload.get("brokerage_rate_pct", "1.00"))) + + benchmark_modal_rate = Decimal(str(payload["benchmark_modal_rate"])) if payload.get("benchmark_modal_rate") is not None else None + variance_acknowledged = bool(payload.get("variance_acknowledged", False)) + + # Auto-lookup benchmark rate from market observations if omitted + if benchmark_modal_rate is None: + obs_list = self.store.query( + "market_observations", + tenant_id, + lambda o: o.get("commodity_id") == commodity_id and not o.get("is_market_closed", False) + ) + if obs_list: + obs_list.sort(key=lambda x: x.get("observation_date", ""), reverse=True) + if obs_list[0].get("modal_rate") is not None: + benchmark_modal_rate = Decimal(str(obs_list[0]["modal_rate"])) + + # Generate unique sauda sequential code + existing = self.store.list("procurement_sauda", tenant_id) + seq_num = len(existing) + 1 + sauda_number = f"SDA-26-{str(seq_num).zfill(5)}" + + # Instantiate sauda model (enforces all commercial, variance, and date checks) + sauda = ProcurementSauda( + tenant_id=tenant_id, + sauda_number=sauda_number, + contract_date=c_date, + delivery_due_date=d_date, + supplier_id=supplier_id, + mandi_id=mandi_id, + commodity_id=commodity_id, + variety=variety, + grade=grade, + trade_type=trade_type, + booked_quantity_mt=booked_quantity_mt, + trade_rate_per_qtl=trade_rate_per_qtl, + estimated_bags=estimated_bags, + credit_period_days=credit_period_days, + advance_amount=advance_amount, + mandi_cess_pct=mandi_cess_pct, + krishi_kalyan_pct=krishi_kalyan_pct, + brokerage_rate_pct=brokerage_rate_pct, + benchmark_modal_rate=benchmark_modal_rate, + variance_acknowledged=variance_acknowledged + ) + + data = sauda.to_dict() + self.store.insert("procurement_sauda", tenant_id, data) + + record_audit_event( + store=self.store, + tenant_id=tenant_id, + actor_user_id=auth_res["user_id"], + action_type="BOOK_PURCHASE_SAUDA", + resource_type="procurement_sauda", + resource_id=sauda.id, + before_state=None, + after_state={"sauda_number": sauda_number, "supplier_id": supplier_id, "total_value": float(sauda.total_landed_amount)} + ) + + return { + "success": True, + "sauda": data, + "status_code": 201 + } + + except ValueError as e: + return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} + except Exception as e: + logger.exception("Failed to book purchase sauda") + return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} + + def list_saudas( + self, + auth_header: Optional[str], + tenant_header: Optional[str], + supplier_id: Optional[str] = None, + status_filter: Optional[str] = None + ) -> Dict[str, Any]: + """GET /api/v1/procurement/sauda (FR-PROCUREMENTCONTRACTS-002).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + + def predicate(s): + if supplier_id and s.get("supplier_id") != supplier_id: + return False + if status_filter and s.get("status") != status_filter: + return False + return True + + records = self.store.query("procurement_sauda", tenant_id, predicate) + return { + "success": True, + "count": len(records), + "saudas": records, + "status_code": 200 + } + + def get_sauda( + self, auth_header: Optional[str], tenant_header: Optional[str], sauda_id: str + ) -> Dict[str, Any]: + """GET /api/v1/procurement/sauda/{id} (FR-PROCUREMENTCONTRACTS-002).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + sauda = self.store.get("procurement_sauda", tenant_id, sauda_id) + if not sauda: + return {"error": "NOT_FOUND", "message": "Purchase sauda not found", "status_code": 404} + + return { + "success": True, + "sauda": sauda, + "status_code": 200 + } + + +procurement_controller = ProcurementController() diff --git a/05_implementation_workspace/backend/app/api/quality.py b/05_implementation_workspace/backend/app/api/quality.py new file mode 100644 index 0000000..935576f --- /dev/null +++ b/05_implementation_workspace/backend/app/api/quality.py @@ -0,0 +1,292 @@ +"""Quality Lab Assay, Rebate Deductions, and Lot FSM API Controller. + +Fulfills: +- STORY-QC-001 (FR-QUALITYANDLOTCONTROL-001): Inward Quality Inspection Parameter Recording. +- STORY-QC-002 (FR-QUALITYANDLOTCONTROL-002): Finite State Machine Enforcement (Hold vs Released). +- STORY-QC-003 (FR-QUALITYANDLOTCONTROL-003): Quality Deduction / Rebate Calculation. +- STORY-QC-004 (FR-QUALITYANDLOTCONTROL-004): Lot Splitting & Blending Traceability. +""" +from datetime import datetime, timezone +from decimal import Decimal +import logging +from typing import Any, Dict, List, Optional +import uuid + +from backend.app.api.auth import auth_controller +from backend.app.auth.tenant_context import ( + TenantContext, + TenantContextResolutionError, + TenantContextResolver, + context_resolver, + record_audit_event, +) +from backend.app.db.session import storage +from backend.app.models.quality import InventoryLot, QualityInspection, calculate_quality_rebates + +logger = logging.getLogger("atb.api.quality") + + +class QualityController: + """Handles laboratory inspection assays, rebate calculation, lot FSM state transitions, and lineage.""" + + def __init__(self, store=storage, resolver=None): + self.store = store + self.resolver = resolver or TenantContextResolver(store=self.store) + + def _authenticate_and_resolve( + self, auth_header: Optional[str], tenant_header: Optional[str] + ) -> Dict[str, Any]: + """Resolves verified caller session and active tenant context.""" + session = auth_controller.get_session(auth_header) + if not session.get("authenticated"): + return {"authenticated": False, "error": session.get("error", "UNAUTHENTICATED"), "status_code": 401} + + user_id = session.get("subject", "") + email = session.get("email", user_id) + user_roles = session.get("roles", []) + + try: + ctx = self.resolver.resolve_context( + subject_id=user_id, + email=email, + user_roles=user_roles, + requested_tenant_id=tenant_header + ) + except TenantContextResolutionError as err: + return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code} + + return { + "authenticated": True, + "session": session, + "context": ctx, + "tenant_id": ctx.tenant_id, + "user_id": user_id + } + + # ========================================================================= + # STORY-QC-001 & 003: Lab Assay & Commercial Rebate Recording + # ========================================================================= + + def record_inspection( + self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any] + ) -> Dict[str, Any]: + """POST /api/v1/quality/inspections (FR-QUALITYANDLOTCONTROL-001, 003).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + ctx = auth_res["context"] + + allowed_roles = {"Quality Officer", "Quality Inspector", "Lab Chemist", "Tenant Administrator"} + if not any(r in allowed_roles for r in ctx.roles): + return { + "error": "INSUFFICIENT_PERMISSIONS", + "message": "Only Quality Officers, Chemists, or Tenant Admins can record analytical assays", + "status_code": 403 + } + + try: + lot_id = payload.get("lot_id", "") + sample_code = payload.get("sample_code", "").strip() + moisture_pct = Decimal(str(payload.get("moisture_pct", "0.0"))) + foreign_matter_pct = Decimal(str(payload.get("foreign_matter_pct", "0.0"))) + damaged_pct = Decimal(str(payload.get("damaged_grain_pct", "0.0"))) + oil_pct = Decimal(str(payload.get("oil_content_pct", "0.0"))) + decision = payload.get("decision", "RELEASED") + rejection_reason = payload.get("rejection_reason") + remarks = payload.get("remarks") + + # Validate lot exists + lot_data = self.store.get("inventory_lots", tenant_id, lot_id) + if not lot_data: + return {"error": "NOT_FOUND", "message": "Target inventory lot not found", "status_code": 404} + + lot_qty_mt = Decimal(str(lot_data["current_quantity_mt"])) + + # Retrieve trade rate from Sauda + grn_data = self.store.get("goods_receipt_notes", tenant_id, lot_data["grn_id"]) + sauda_data = self.store.get("procurement_sauda", tenant_id, grn_data["sauda_id"]) if grn_data else None + trade_rate = Decimal(str(sauda_data["trade_rate_per_qtl"])) if sauda_data else Decimal("4500.00") + + # Create Inspection model + inspection = QualityInspection( + tenant_id=tenant_id, + lot_id=lot_id, + sample_code=sample_code, + inspector_email=auth_res["session"].get("subject", "inspector@atb.com"), + lot_quantity_mt=lot_qty_mt, + trade_rate_per_qtl=trade_rate, + moisture_pct=moisture_pct, + foreign_matter_pct=foreign_matter_pct, + damaged_grain_pct=damaged_pct, + oil_content_pct=oil_pct, + decision=decision, + rejection_reason=rejection_reason, + remarks=remarks + ) + + insp_dict = inspection.to_dict() + self.store.insert("quality_inspections", tenant_id, insp_dict) + + # Auto-apply decision if specified + if decision in {"RELEASED", "REJECTED"}: + lot = InventoryLot( + tenant_id=tenant_id, + lot_number=lot_data["lot_number"], + grn_id=lot_data["grn_id"], + commodity_id=lot_data["commodity_id"], + variety=lot_data["variety"], + godown_stack_id=lot_data["godown_stack_id"], + initial_quantity_mt=Decimal(str(lot_data["initial_quantity_mt"])), + grade=lot_data["grade"], + lot_id=lot_data["id"] + ) + lot.qc_status = lot_data["qc_status"] + lot.transition_qc_status(decision) + lot_data["qc_status"] = lot.qc_status + self.store.update("inventory_lots", tenant_id, lot.id, lot_data) + + record_audit_event( + store=self.store, + tenant_id=tenant_id, + actor_user_id=auth_res["user_id"], + action_type="RECORD_QUALITY_INSPECTION", + resource_type="quality_inspection", + resource_id=inspection.id, + before_state=None, + after_state={"sample_code": sample_code, "decision": decision, "rebate_amount": float(inspection.total_rebate_amount)} + ) + + return { + "success": True, + "inspection": insp_dict, + "lot_qc_status": lot_data["qc_status"], + "status_code": 201 + } + + except ValueError as e: + return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} + except Exception as e: + logger.exception("Failed to record quality inspection") + return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} + + # ========================================================================= + # STORY-QC-002: Lot FSM Decision Transition + # ========================================================================= + + def execute_lot_decision( + self, auth_header: Optional[str], tenant_header: Optional[str], lot_id: str, payload: Dict[str, Any] + ) -> Dict[str, Any]: + """POST /api/v1/quality/lots/{id}/decision (FR-QUALITYANDLOTCONTROL-002).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + ctx = auth_res["context"] + + allowed_roles = {"Quality Officer", "Quality Inspector", "Tenant Administrator"} + if not any(r in allowed_roles for r in ctx.roles): + return { + "error": "INSUFFICIENT_PERMISSIONS", + "message": "Requires Quality Inspector or Tenant Admin role to commit quality decisions", + "status_code": 403 + } + + try: + decision = payload.get("decision", "") + rejection_reason = payload.get("rejection_reason") + + lot_data = self.store.get("inventory_lots", tenant_id, lot_id) + if not lot_data: + return {"error": "NOT_FOUND", "message": "Lot not found", "status_code": 404} + + if decision == "REJECTED" and not rejection_reason: + return { + "error": "VALIDATION_ERROR", + "message": "Rejection reason is mandatory when decision is REJECTED", + "status_code": 422 + } + + lot = InventoryLot( + tenant_id=tenant_id, + lot_number=lot_data["lot_number"], + grn_id=lot_data["grn_id"], + commodity_id=lot_data["commodity_id"], + variety=lot_data["variety"], + godown_stack_id=lot_data["godown_stack_id"], + initial_quantity_mt=Decimal(str(lot_data["initial_quantity_mt"])), + grade=lot_data["grade"], + lot_id=lot_data["id"] + ) + lot.qc_status = lot_data["qc_status"] + lot.transition_qc_status(decision) + + lot_data["qc_status"] = lot.qc_status + self.store.update("inventory_lots", tenant_id, lot_id, lot_data) + + record_audit_event( + store=self.store, + tenant_id=tenant_id, + actor_user_id=auth_res["user_id"], + action_type="EXECUTE_LOT_QC_DECISION", + resource_type="inventory_lot", + resource_id=lot_id, + before_state={"qc_status": lot_data["qc_status"]}, + after_state={"qc_status": lot.qc_status, "decision": decision} + ) + + return { + "success": True, + "lot": lot_data, + "status_code": 200 + } + + except ValueError as e: + return {"error": "INVALID_TRANSITION", "message": str(e), "status_code": 400} + except Exception as e: + logger.exception("Failed to execute lot decision") + return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} + + # ========================================================================= + # STORY-QC-004: Lot Lineage & Genealogy Traversal + # ========================================================================= + + def get_lot_lineage( + self, auth_header: Optional[str], tenant_header: Optional[str], lot_id: str + ) -> Dict[str, Any]: + """GET /api/v1/quality/lots/{id}/lineage (FR-QUALITYANDLOTCONTROL-004).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + lot_data = self.store.get("inventory_lots", tenant_id, lot_id) + if not lot_data: + return {"error": "NOT_FOUND", "message": "Lot not found", "status_code": 404} + + # Traverse upwards to GRN, Weighbridge, Gate Entry, and Sauda + grn_data = self.store.get("goods_receipt_notes", tenant_id, lot_data.get("grn_id")) + weighment_data = self.store.get("weighbridge_slips", tenant_id, grn_data.get("weighment_slip_id")) if grn_data else None + gate_data = self.store.get("inward_gate_entries", tenant_id, weighment_data.get("gate_pass_id")) if weighment_data else None + sauda_data = self.store.get("procurement_sauda", tenant_id, grn_data.get("sauda_id")) if grn_data else None + + lineage_tree = { + "lot": lot_data, + "parent_lot": self.store.get("inventory_lots", tenant_id, lot_data.get("parent_lot_id")) if lot_data.get("parent_lot_id") else None, + "goods_receipt_note": grn_data, + "weighbridge_slip": weighment_data, + "gate_entry": gate_data, + "procurement_sauda": sauda_data + } + + return { + "success": True, + "lot_id": lot_id, + "lineage": lineage_tree, + "status_code": 200 + } + + +quality_controller = QualityController() diff --git a/05_implementation_workspace/backend/app/api/receiving.py b/05_implementation_workspace/backend/app/api/receiving.py new file mode 100644 index 0000000..7d0faf4 --- /dev/null +++ b/05_implementation_workspace/backend/app/api/receiving.py @@ -0,0 +1,440 @@ +"""Inward Vehicle Gate Receiving, Weighbridge, and GRN API Controller. + +Fulfills: +- STORY-INW-001 (FR-INWARDRECEIVING-001): Inward Vehicle Gate Entry & Verification. +- STORY-INW-002 (FR-INWARDRECEIVING-002): Weighbridge Gross & Tare Weighment Logging. +- STORY-INW-003 (FR-INWARDRECEIVING-003): Bag Tare Deduction (Bardana Katai). +- STORY-INW-004 (FR-INWARDRECEIVING-004): Weighment Tolerance & Transit Shortage. +- STORY-INW-005 (FR-INWARDRECEIVING-005): Goods Receipt Note (GRN) & Stack Placement. +- STORY-INW-006 (FR-INWARDRECEIVING-006): Mandatory Lot & Batch Identity Generation. +""" +from datetime import datetime, timezone +from decimal import Decimal +import logging +from typing import Any, Dict, List, Optional +import uuid + +from backend.app.api.auth import auth_controller +from backend.app.auth.tenant_context import ( + TenantContext, + TenantContextResolutionError, + TenantContextResolver, + context_resolver, + record_audit_event, +) +from backend.app.db.session import storage +from backend.app.models.receiving import InwardGateEntry, WeighbridgeSlip, GoodsReceiptNote +from backend.app.models.quality import InventoryLot +from backend.app.models.procurement import ProcurementSauda + +logger = logging.getLogger("atb.api.receiving") + + +class ReceivingController: + """Handles gate passes, weighbridge scale readings, shortage, GRN posting, and lot minting.""" + + def __init__(self, store=storage, resolver=None): + self.store = store + self.resolver = resolver or TenantContextResolver(store=self.store) + + def _authenticate_and_resolve( + self, auth_header: Optional[str], tenant_header: Optional[str] + ) -> Dict[str, Any]: + """Resolves verified caller session and active tenant context.""" + session = auth_controller.get_session(auth_header) + if not session.get("authenticated"): + return {"authenticated": False, "error": session.get("error", "UNAUTHENTICATED"), "status_code": 401} + + user_id = session.get("subject", "") + email = session.get("email", user_id) + user_roles = session.get("roles", []) + + try: + ctx = self.resolver.resolve_context( + subject_id=user_id, + email=email, + user_roles=user_roles, + requested_tenant_id=tenant_header + ) + except TenantContextResolutionError as err: + return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code} + + return { + "authenticated": True, + "session": session, + "context": ctx, + "tenant_id": ctx.tenant_id, + "user_id": user_id + } + + # ========================================================================= + # STORY-INW-001: Vehicle Gate Entry Pass + # ========================================================================= + + def create_gate_entry( + self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any] + ) -> Dict[str, Any]: + """POST /api/v1/receiving/gate-entries (FR-INWARDRECEIVING-001).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + ctx = auth_res["context"] + + allowed_roles = {"Security Guard", "Gate Operator", "Warehouse Clerk", "Tenant Administrator"} + if not any(r in allowed_roles for r in ctx.roles): + return { + "error": "INSUFFICIENT_PERMISSIONS", + "message": "Only Security Guards, Gate Operators, or Tenant Admins can issue gate passes", + "status_code": 403 + } + + try: + vehicle_number = payload.get("vehicle_number", "").strip().upper() + eway_bill_number = payload.get("eway_bill_number", "").strip() + driver_name = payload.get("driver_name", "").strip() + driver_mobile = payload.get("driver_mobile", "").strip() + sauda_id = payload.get("sauda_id", "") + supplier_invoice_no = payload.get("supplier_invoice_no", "").strip() + dispatch_wt = Decimal(str(payload.get("supplier_dispatch_weight_mt", "0.0"))) + dispatch_bags = int(payload.get("supplier_dispatch_bags", 0)) + is_seal_intact = bool(payload.get("is_seal_intact", True)) + + # Validate Sauda exists and is open + sauda = self.store.get("procurement_sauda", tenant_id, sauda_id) + if not sauda: + return {"error": "INVALID_SAUDA", "message": "Purchase sauda not found in tenant", "status_code": 404} + if sauda.get("status") in {"FULFILLED", "CANCELLED"}: + return { + "error": "SAUDA_CLOSED", + "message": f"Cannot assign gate entry to {sauda.get('status')} contract", + "status_code": 400 + } + + # Vehicle yard duplication check + clean_vehicle = vehicle_number.replace("-", "").replace(" ", "").upper() + active_entries = self.store.query( + "inward_gate_entries", + tenant_id, + lambda e: (e.get("vehicle_number") == clean_vehicle or e.get("vehicle_number") == vehicle_number) and e.get("status") != "GATE_OUT" + ) + if active_entries: + return { + "error": "VEHICLE_ALREADY_IN_YARD", + "message": f"Vehicle {vehicle_number} is already inside yard under Gate Pass {active_entries[0].get('gate_pass_number')}", + "status_code": 409 + } + + # Generate unique Gate Pass sequential number + total_passes = len(self.store.list("inward_gate_entries", tenant_id)) + 1 + gate_pass_number = f"GP-26-{str(total_passes).zfill(5)}" + + entry = InwardGateEntry( + tenant_id=tenant_id, + gate_pass_number=gate_pass_number, + vehicle_number=vehicle_number, + eway_bill_number=eway_bill_number, + driver_name=driver_name, + driver_mobile=driver_mobile, + sauda_id=sauda_id, + supplier_invoice_no=supplier_invoice_no, + supplier_dispatch_weight_mt=dispatch_wt, + supplier_dispatch_bags=dispatch_bags, + is_seal_intact=is_seal_intact + ) + + data = entry.to_dict() + self.store.insert("inward_gate_entries", tenant_id, data) + + record_audit_event( + store=self.store, + tenant_id=tenant_id, + actor_user_id=auth_res["user_id"], + action_type="GENERATE_GATE_PASS", + resource_type="inward_gate_entry", + resource_id=entry.id, + before_state=None, + after_state={"gate_pass_number": gate_pass_number, "vehicle": vehicle_number, "sauda": sauda_id} + ) + + return { + "success": True, + "gate_entry": data, + "status_code": 201 + } + + except ValueError as e: + return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} + except Exception as e: + logger.exception("Failed to create gate entry") + return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} + + def list_gate_entries( + self, auth_header: Optional[str], tenant_header: Optional[str] + ) -> Dict[str, Any]: + """GET /api/v1/receiving/gate-entries (FR-INWARDRECEIVING-001).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + records = self.store.list("inward_gate_entries", tenant_id) + return { + "success": True, + "count": len(records), + "gate_entries": records, + "status_code": 200 + } + + # ========================================================================= + # STORY-INW-002, 003, 004: Weighbridge Gross/Tare Logging + # ========================================================================= + + def create_weighment_gross( + self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any] + ) -> Dict[str, Any]: + """POST /api/v1/receiving/weighments (FR-INWARDRECEIVING-002).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + try: + gate_pass_id = payload.get("gate_pass_id", "") + gross_mt = Decimal(str(payload.get("gross_weight_mt", "0.0"))) + + gate_entry = self.store.get("inward_gate_entries", tenant_id, gate_pass_id) + if not gate_entry: + return {"error": "NOT_FOUND", "message": "Gate entry not found", "status_code": 404} + + total_slips = len(self.store.list("weighbridge_slips", tenant_id)) + 1 + slip_number = f"WS-26-{str(total_slips).zfill(5)}" + + slip = WeighbridgeSlip( + tenant_id=tenant_id, + slip_number=slip_number, + gate_pass_id=gate_pass_id, + gross_weight_mt=gross_mt + ) + + data = slip.to_dict() + self.store.insert("weighbridge_slips", tenant_id, data) + + # Update gate pass status + gate_entry["status"] = "WEIGHED_GROSS" + self.store.update("inward_gate_entries", tenant_id, gate_pass_id, gate_entry) + + return { + "success": True, + "weighment_slip": data, + "status_code": 201 + } + + except ValueError as e: + return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} + except Exception as e: + logger.exception("Failed to log gross weighment") + return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} + + def record_weighment_tare( + self, auth_header: Optional[str], tenant_header: Optional[str], slip_id: str, payload: Dict[str, Any] + ) -> Dict[str, Any]: + """POST /api/v1/receiving/weighments/{id}/tare (FR-INWARDRECEIVING-002..004).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + try: + slip_data = self.store.get("weighbridge_slips", tenant_id, slip_id) + if not slip_data: + return {"error": "NOT_FOUND", "message": "Weighbridge slip not found", "status_code": 404} + + tare_mt = Decimal(str(payload.get("tare_weight_mt", "0.0"))) + packaging_type = payload.get("bag_packaging_type", "JUTE_GUNNY_NEW") + bag_count = int(payload.get("actual_bag_count", 0)) + + gate_entry = self.store.get("inward_gate_entries", tenant_id, slip_data["gate_pass_id"]) + billed_wt = Decimal(str(gate_entry.get("supplier_dispatch_weight_mt", "0.0"))) if gate_entry else Decimal("0.0") + + # Hydrate model and record tare + slip = WeighbridgeSlip( + tenant_id=tenant_id, + slip_number=slip_data["slip_number"], + gate_pass_id=slip_data["gate_pass_id"], + gross_weight_mt=Decimal(str(slip_data["gross_weight_mt"])), + slip_id=slip_id + ) + slip.record_tare( + tare_weight_mt=tare_mt, + bag_packaging_type=packaging_type, + actual_bag_count=bag_count, + billed_weight_mt=billed_wt + ) + + updated_dict = slip.to_dict() + self.store.update("weighbridge_slips", tenant_id, slip_id, updated_dict) + + # Update gate pass status + if gate_entry: + gate_entry["status"] = "WEIGHED_TARE" + self.store.update("inward_gate_entries", tenant_id, gate_entry["id"], gate_entry) + + return { + "success": True, + "weighment_slip": updated_dict, + "status_code": 200 + } + + except ValueError as e: + return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} + except Exception as e: + logger.exception("Failed to record tare weighment") + return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} + + # ========================================================================= + # STORY-INW-005, 006: GRN Posting & Lot Minting + # ========================================================================= + + def post_grn( + self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any] + ) -> Dict[str, Any]: + """POST /api/v1/receiving/grn (FR-INWARDRECEIVING-005, FR-INWARDRECEIVING-006).""" + auth_res = self._authenticate_and_resolve(auth_header, tenant_header) + if not auth_res.get("authenticated"): + return auth_res + + tenant_id = auth_res["tenant_id"] + ctx = auth_res["context"] + + allowed_roles = {"Warehouse Supervisor", "Warehouse Manager", "Tenant Administrator"} + if not any(r in allowed_roles for r in ctx.roles): + return { + "error": "INSUFFICIENT_PERMISSIONS", + "message": "Only Warehouse Supervisors, Managers, or Tenant Admins can post GRNs", + "status_code": 403 + } + + try: + slip_id = payload.get("weighment_slip_id", "") + godown_id = payload.get("godown_id", "") + godown_stack_id = payload.get("godown_stack_id", "") + + slip_data = self.store.get("weighbridge_slips", tenant_id, slip_id) + if not slip_data: + return {"error": "NOT_FOUND", "message": "Weighbridge slip not found", "status_code": 404} + + if slip_data.get("final_net_weight_mt") is None: + return { + "error": "TARE_NOT_COMPLETED", + "message": "Cannot issue GRN without completed tare weighment", + "status_code": 400 + } + + gate_entry = self.store.get("inward_gate_entries", tenant_id, slip_data["gate_pass_id"]) + if not gate_entry: + return {"error": "NOT_FOUND", "message": "Gate entry not found", "status_code": 404} + + sauda_data = self.store.get("procurement_sauda", tenant_id, gate_entry["sauda_id"]) + if not sauda_data: + return {"error": "NOT_FOUND", "message": "Associated Sauda not found", "status_code": 404} + + # Check if GRN already issued for this slip + existing_grn = self.store.query("goods_receipt_notes", tenant_id, lambda g: g.get("weighment_slip_id") == slip_id) + if existing_grn: + return { + "error": "DUPLICATE_GRN", + "message": f"GRN already issued for weighment slip: {existing_grn[0].get('grn_number')}", + "status_code": 409 + } + + accepted_wt = Decimal(str(slip_data["final_net_weight_mt"])) + accepted_bags = slip_data.get("actual_bag_count", 0) + + # Generate unique GRN number + total_grns = len(self.store.list("goods_receipt_notes", tenant_id)) + 1 + grn_number = f"GRN-26-{str(total_grns).zfill(5)}" + + grn = GoodsReceiptNote( + tenant_id=tenant_id, + grn_number=grn_number, + weighment_slip_id=slip_id, + sauda_id=sauda_data["id"], + godown_id=godown_id, + godown_stack_id=godown_stack_id, + accepted_quantity_mt=accepted_wt, + accepted_bags=accepted_bags + ) + grn_dict = grn.to_dict() + self.store.insert("goods_receipt_notes", tenant_id, grn_dict) + + # Mint Lot Identity (FR-INWARDRECEIVING-006) + total_lots = len(self.store.list("inventory_lots", tenant_id)) + 1 + comm_code = sauda_data.get("commodity_id", "COMM")[:3].upper() + lot_number = f"LOT-26-10-{comm_code}-{str(total_lots).zfill(5)}" + + lot = InventoryLot( + tenant_id=tenant_id, + lot_number=lot_number, + grn_id=grn.id, + commodity_id=sauda_data["commodity_id"], + variety=sauda_data["variety"], + grade=sauda_data.get("grade", "FAQ"), + godown_stack_id=godown_stack_id, + initial_quantity_mt=accepted_wt + ) + lot_dict = lot.to_dict() + self.store.insert("inventory_lots", tenant_id, lot_dict) + + # Update Sauda partial fulfillment & FSM + sauda = ProcurementSauda( + tenant_id=tenant_id, + sauda_number=sauda_data["sauda_number"], + contract_date=datetime.strptime(sauda_data["contract_date"], "%Y-%m-%d").date(), + delivery_due_date=datetime.strptime(sauda_data["delivery_due_date"], "%Y-%m-%d").date(), + supplier_id=sauda_data["supplier_id"], + mandi_id=sauda_data["mandi_id"], + commodity_id=sauda_data["commodity_id"], + variety=sauda_data["variety"], + booked_quantity_mt=Decimal(str(sauda_data["booked_quantity_mt"])), + trade_rate_per_qtl=Decimal(str(sauda_data["trade_rate_per_qtl"])), + grade=sauda_data["grade"], + sauda_id=sauda_data["id"] + ) + sauda.cumulative_received_mt = Decimal(str(sauda_data.get("cumulative_received_mt", "0.0"))) + sauda.status = sauda_data.get("status", "ACTIVE") + sauda.record_receipt(accepted_wt) + self.store.update("procurement_sauda", tenant_id, sauda.id, sauda.to_dict()) + + # Update gate pass to GRN_ISSUED + gate_entry["status"] = "GRN_ISSUED" + self.store.update("inward_gate_entries", tenant_id, gate_entry["id"], gate_entry) + + record_audit_event( + store=self.store, + tenant_id=tenant_id, + actor_user_id=auth_res["user_id"], + action_type="POST_GRN_AND_MINT_LOT", + resource_type="goods_receipt_note", + resource_id=grn.id, + before_state=None, + after_state={"grn_number": grn_number, "lot_number": lot_number, "accepted_mt": float(accepted_wt)} + ) + + return { + "success": True, + "grn": grn_dict, + "lot": lot_dict, + "sauda_status": sauda.status, + "status_code": 201 + } + + except ValueError as e: + return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422} + except Exception as e: + logger.exception("Failed to post GRN") + return {"error": "INTERNAL_ERROR", "message": str(e), "status_code": 500} + + +receiving_controller = ReceivingController() diff --git a/05_implementation_workspace/backend/app/auth/tenant_context.py b/05_implementation_workspace/backend/app/auth/tenant_context.py index 2fe0682..a5497a4 100644 --- a/05_implementation_workspace/backend/app/auth/tenant_context.py +++ b/05_implementation_workspace/backend/app/auth/tenant_context.py @@ -129,8 +129,7 @@ class TenantContextResolver: status_code=403 ) - membership = eligible_memberships[0] - effective_roles = [membership.role] + effective_roles = list(dict.fromkeys(m.role for m in eligible_memberships)) return TenantContext( tenant_id=requested_tenant_id, @@ -143,33 +142,42 @@ class TenantContextResolver: def record_audit_event( - store: InMemoryTenantStorage, - tenant_id: str, - actor_id: str, - entity_type: str, - entity_id: str, - action: str, + store: Optional[InMemoryTenantStorage] = None, + tenant_id: str = "", + actor_id: Optional[str] = None, + entity_type: Optional[str] = None, + entity_id: Optional[str] = None, + action: Optional[str] = None, field_diff: Optional[Dict[str, Any]] = None, - correlation_id: Optional[str] = None + correlation_id: Optional[str] = None, + **kwargs: Any ) -> TransactionAuditLog: """Appends an immutable transaction audit log record. Automatically redacts sensitive payload fields and enforces append-only immutability. + Supports backward-compatible keyword aliases (actor_user_id, resource_type, etc.). """ - clean_diff = redact_sensitive_payload(field_diff) + target_store = store or storage + effective_actor = actor_id or kwargs.get("actor_user_id", "system") + effective_entity_type = entity_type or kwargs.get("resource_type", "Unknown") + effective_entity_id = entity_id or kwargs.get("resource_id", "") + effective_action = action or kwargs.get("action_type", "UNKNOWN") + effective_diff = field_diff if field_diff is not None else (kwargs.get("after_state") or kwargs.get("diff")) + + clean_diff = redact_sensitive_payload(effective_diff) diff_json = json.dumps(clean_diff) if clean_diff else None log = TransactionAuditLog( tenant_id=tenant_id, - actor_id=actor_id, - entity_type=entity_type, - entity_id=entity_id, - action=action, + actor_id=effective_actor, + entity_type=effective_entity_type, + entity_id=effective_entity_id, + action=effective_action, correlation_id=correlation_id, field_diff_json=diff_json, timestamp=datetime.now(timezone.utc) ) - store.record_audit_log(log) + target_store.record_audit_log(log) return log diff --git a/05_implementation_workspace/backend/app/db/session.py b/05_implementation_workspace/backend/app/db/session.py index 612448f..9b613eb 100644 --- a/05_implementation_workspace/backend/app/db/session.py +++ b/05_implementation_workspace/backend/app/db/session.py @@ -39,6 +39,7 @@ class InMemoryTenantStorage: self.tenants: Dict[str, Tenant] = {} self.memberships: Dict[str, TenantMembership] = {} self.audit_logs: Dict[str, TransactionAuditLog] = {} + self._collections: Dict[str, Dict[str, Dict[str, Any]]] = {} self.active_tenant_id: Optional[str] = None self._pool_connection_id: str = "conn_pool_01" @@ -120,15 +121,44 @@ class InMemoryTenantStorage: """Enforces append-only immutability invariant (FR-TENANTSECURITYAUDIT-003).""" raise ImmutableAuditViolationError("Deletion prohibited: transaction_audit_logs is append-only.") + def insert(self, collection: str, tenant_id: str, data: Dict[str, Any]) -> None: + """Inserts a record into a tenant-scoped generic collection.""" + if collection not in self._collections: + self._collections[collection] = {} + if tenant_id not in self._collections[collection]: + self._collections[collection][tenant_id] = {} + row_id = data.get("id") or str(uuid.uuid4()) + self._collections[collection][tenant_id][row_id] = data + + def get(self, collection: str, tenant_id: str, row_id: str) -> Optional[Dict[str, Any]]: + """Retrieves a record by ID scoped to tenant.""" + return self._collections.get(collection, {}).get(tenant_id, {}).get(row_id) + + def list(self, collection: str, tenant_id: str) -> List[Dict[str, Any]]: + """Lists all records in collection for tenant.""" + return list(self._collections.get(collection, {}).get(tenant_id, {}).values()) + + def query(self, collection: str, tenant_id: str, predicate) -> List[Dict[str, Any]]: + """Queries records in collection matching predicate.""" + rows = self.list(collection, tenant_id) + return [r for r in rows if predicate(r)] + + def update(self, collection: str, tenant_id: str, row_id: str, data: Dict[str, Any]) -> None: + """Updates a record in collection for tenant.""" + if collection in self._collections and tenant_id in self._collections[collection]: + self._collections[collection][tenant_id][row_id] = data + def reset_for_tests(self) -> None: self.tenants.clear() self.memberships.clear() self.audit_logs.clear() + self._collections.clear() self.active_tenant_id = None # Global in-memory storage instance storage = InMemoryTenantStorage() +InMemoryStorage = InMemoryTenantStorage class DatabaseManager: diff --git a/05_implementation_workspace/backend/app/main.py b/05_implementation_workspace/backend/app/main.py index a0683a9..5457627 100644 --- a/05_implementation_workspace/backend/app/main.py +++ b/05_implementation_workspace/backend/app/main.py @@ -7,6 +7,10 @@ Multi-Tenant Lifecycle, Membership Administration, Context Switching, and Audit from typing import Any, Dict, Optional from backend.app.api.auth import auth_controller, extract_bearer_token from backend.app.api.tenants import tenant_controller +from backend.app.api.market import market_controller +from backend.app.api.procurement import procurement_controller +from backend.app.api.receiving import receiving_controller +from backend.app.api.quality import quality_controller from backend.app.core.config import settings try: @@ -153,6 +157,181 @@ try: status_code = result.pop("status_code", 200) return JSONResponse(status_code=status_code, content=result) + # ========================================================================= + # Market Desk Endpoints (Iteration 03 / UC-002) + # ========================================================================= + + @app.post("/api/v1/market/observations", tags=["Market Desk"]) + async def record_market_observation( + payload: Dict[str, Any], + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """POST /api/v1/market/observations (FR-MKT-001, FR-MKT-002).""" + result = market_controller.record_observation(authorization, x_tenant_id, payload) + status_code = result.pop("status_code", 201) + return JSONResponse(status_code=status_code, content=result) + + @app.get("/api/v1/market/observations", tags=["Market Desk"]) + async def list_market_observations( + mandi_id: Optional[str] = None, + date: Optional[str] = None, + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """GET /api/v1/market/observations (FR-MKT-001).""" + result = market_controller.list_observations(authorization, x_tenant_id, mandi_id, date) + status_code = result.pop("status_code", 200) + return JSONResponse(status_code=status_code, content=result) + + @app.get("/api/v1/market/rates/latest", tags=["Market Desk"]) + async def get_latest_market_rates( + commodity_id: str, + mandi_id: Optional[str] = None, + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """GET /api/v1/market/rates/latest (FR-MKT-002).""" + result = market_controller.get_latest_rates(authorization, x_tenant_id, commodity_id, mandi_id) + status_code = result.pop("status_code", 200) + return JSONResponse(status_code=status_code, content=result) + + # ========================================================================= + # Procurement Sauda Endpoints (Iteration 03 / UC-004) + # ========================================================================= + + @app.post("/api/v1/procurement/sauda", tags=["Procurement"]) + async def book_sauda( + payload: Dict[str, Any], + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """POST /api/v1/procurement/sauda (FR-PROCUREMENTCONTRACTS-001..004).""" + result = procurement_controller.book_sauda(authorization, x_tenant_id, payload) + status_code = result.pop("status_code", 201) + return JSONResponse(status_code=status_code, content=result) + + @app.get("/api/v1/procurement/sauda", tags=["Procurement"]) + async def list_saudas( + supplier_id: Optional[str] = None, + status: Optional[str] = None, + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """GET /api/v1/procurement/sauda (FR-PROCUREMENTCONTRACTS-002).""" + result = procurement_controller.list_saudas(authorization, x_tenant_id, supplier_id, status) + status_code = result.pop("status_code", 200) + return JSONResponse(status_code=status_code, content=result) + + @app.get("/api/v1/procurement/sauda/{sauda_id}", tags=["Procurement"]) + async def get_sauda( + sauda_id: str, + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """GET /api/v1/procurement/sauda/{id} (FR-PROCUREMENTCONTRACTS-002).""" + result = procurement_controller.get_sauda(authorization, x_tenant_id, sauda_id) + status_code = result.pop("status_code", 200) + return JSONResponse(status_code=status_code, content=result) + + # ========================================================================= + # Inward Receiving & Weighbridge Endpoints (Iteration 03 / UC-005) + # ========================================================================= + + @app.post("/api/v1/receiving/gate-entries", tags=["Receiving"]) + async def create_gate_entry( + payload: Dict[str, Any], + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """POST /api/v1/receiving/gate-entries (FR-INWARDRECEIVING-001).""" + result = receiving_controller.create_gate_entry(authorization, x_tenant_id, payload) + status_code = result.pop("status_code", 201) + return JSONResponse(status_code=status_code, content=result) + + @app.get("/api/v1/receiving/gate-entries", tags=["Receiving"]) + async def list_gate_entries( + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """GET /api/v1/receiving/gate-entries (FR-INWARDRECEIVING-001).""" + result = receiving_controller.list_gate_entries(authorization, x_tenant_id) + status_code = result.pop("status_code", 200) + return JSONResponse(status_code=status_code, content=result) + + @app.post("/api/v1/receiving/weighments", tags=["Receiving"]) + async def create_weighment_gross( + payload: Dict[str, Any], + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """POST /api/v1/receiving/weighments (FR-INWARDRECEIVING-002).""" + result = receiving_controller.create_weighment_gross(authorization, x_tenant_id, payload) + status_code = result.pop("status_code", 201) + return JSONResponse(status_code=status_code, content=result) + + @app.post("/api/v1/receiving/weighments/{slip_id}/tare", tags=["Receiving"]) + async def record_weighment_tare( + slip_id: str, + payload: Dict[str, Any], + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """POST /api/v1/receiving/weighments/{id}/tare (FR-INWARDRECEIVING-002..004).""" + result = receiving_controller.record_weighment_tare(authorization, x_tenant_id, slip_id, payload) + status_code = result.pop("status_code", 200) + return JSONResponse(status_code=status_code, content=result) + + @app.post("/api/v1/receiving/grn", tags=["Receiving"]) + async def post_grn( + payload: Dict[str, Any], + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """POST /api/v1/receiving/grn (FR-INWARDRECEIVING-005, FR-INWARDRECEIVING-006).""" + result = receiving_controller.post_grn(authorization, x_tenant_id, payload) + status_code = result.pop("status_code", 201) + return JSONResponse(status_code=status_code, content=result) + + # ========================================================================= + # Quality Lab & Lot FSM Endpoints (Iteration 03 / UC-006) + # ========================================================================= + + @app.post("/api/v1/quality/inspections", tags=["Quality"]) + async def record_quality_inspection( + payload: Dict[str, Any], + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """POST /api/v1/quality/inspections (FR-QUALITYANDLOTCONTROL-001, 003).""" + result = quality_controller.record_inspection(authorization, x_tenant_id, payload) + status_code = result.pop("status_code", 201) + return JSONResponse(status_code=status_code, content=result) + + @app.post("/api/v1/quality/lots/{lot_id}/decision", tags=["Quality"]) + async def execute_lot_decision( + lot_id: str, + payload: Dict[str, Any], + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """POST /api/v1/quality/lots/{id}/decision (FR-QUALITYANDLOTCONTROL-002).""" + result = quality_controller.execute_lot_decision(authorization, x_tenant_id, lot_id, payload) + status_code = result.pop("status_code", 200) + return JSONResponse(status_code=status_code, content=result) + + @app.get("/api/v1/quality/lots/{lot_id}/lineage", tags=["Quality"]) + async def get_lot_lineage( + lot_id: str, + authorization: Optional[str] = Header(None), + x_tenant_id: Optional[str] = Header(None, alias="X-Tenant-ID") + ): + """GET /api/v1/quality/lots/{id}/lineage (FR-QUALITYANDLOTCONTROL-004).""" + result = quality_controller.get_lot_lineage(authorization, x_tenant_id, lot_id) + status_code = result.pop("status_code", 200) + return JSONResponse(status_code=status_code, content=result) + + except ImportError: # Minimal mock app interface when FastAPI is not present in local python environment class MockApp: diff --git a/05_implementation_workspace/backend/app/models/market.py b/05_implementation_workspace/backend/app/models/market.py new file mode 100644 index 0000000..4ca07a4 --- /dev/null +++ b/05_implementation_workspace/backend/app/models/market.py @@ -0,0 +1,136 @@ +"""Market Desk Observations Model and Invariants. + +Fulfills FR-MKT-001 and FR-MKT-002 (UC-002). +Adheres to LLD-007 and UP-AI v1.5 standards. +""" +from datetime import datetime, date, timezone +from decimal import Decimal +from typing import Optional, Dict, Any +import uuid + +try: + from sqlalchemy import Column, String, DateTime, Date, Numeric, Boolean, UniqueConstraint + from backend.app.models.user import Base +except ImportError: + class Base: + pass + Column = String = DateTime = Date = Numeric = Boolean = UniqueConstraint = lambda *args, **kwargs: None + + +def validate_market_observation( + observation_date: date, + arrival_mt: Decimal, + min_rate: Optional[Decimal], + max_rate: Optional[Decimal], + modal_rate: Optional[Decimal], + is_market_closed: bool = False +) -> None: + """Validates domain invariants for daily mandi observation.""" + today = datetime.now(timezone.utc).date() + if observation_date > today: + raise ValueError("Observation date cannot be in the future") + + if is_market_closed: + if arrival_mt < Decimal("0.0"): + raise ValueError("Arrival quantity must be >= 0.0 MT") + return + + if arrival_mt < Decimal("0.0"): + raise ValueError("Arrival quantity must be >= 0.0 MT") + + if min_rate is None or max_rate is None or modal_rate is None: + raise ValueError("Min rate, Max rate, and Modal rate are mandatory for open markets") + + if min_rate <= Decimal("0.0"): + raise ValueError("Minimum rate must be > 0.0") + + if max_rate < min_rate: + raise ValueError("Maximum rate must be greater than or equal to minimum rate") + + if not (min_rate <= modal_rate <= max_rate): + raise ValueError( + f"Modal rate ({modal_rate}) must be between Min rate ({min_rate}) and Max rate ({max_rate})" + ) + + +class MarketObservation(Base): + __tablename__ = "market_observations" + __table_args__ = ( + UniqueConstraint( + "tenant_id", "mandi_id", "commodity_id", "variety", "observation_date", + name="uq_market_observation_mandi_commodity_date" + ), + {"schema": "public"} + ) + + id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) + tenant_id = Column(String(36), nullable=False, index=True) + mandi_id = Column(String(36), nullable=False, index=True) + observation_date = Column(Date, nullable=False, index=True) + commodity_id = Column(String(36), nullable=False) + variety = Column(String(64), nullable=False) + grade = Column(String(32), default="FAQ") + arrival_mt = Column(Numeric(12, 3), nullable=False, default=0.0) + internal_stock_mt = Column(Numeric(12, 3), nullable=True) + min_rate = Column(Numeric(10, 2), nullable=True) + max_rate = Column(Numeric(10, 2), nullable=True) + modal_rate = Column(Numeric(10, 2), nullable=True) + source = Column(String(32), default="APMC_BULLETIN") + is_market_closed = Column(Boolean, default=False) + created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + + def __init__( + self, + tenant_id: str, + mandi_id: str, + observation_date: date, + commodity_id: str, + variety: str, + grade: str = "FAQ", + arrival_mt: Decimal = Decimal("0.0"), + internal_stock_mt: Optional[Decimal] = None, + min_rate: Optional[Decimal] = None, + max_rate: Optional[Decimal] = None, + modal_rate: Optional[Decimal] = None, + source: str = "APMC_BULLETIN", + is_market_closed: bool = False, + observation_id: Optional[str] = None + ): + validate_market_observation( + observation_date, arrival_mt, min_rate, max_rate, modal_rate, is_market_closed + ) + self.id = observation_id or str(uuid.uuid4()) + self.tenant_id = tenant_id + self.mandi_id = mandi_id + self.observation_date = observation_date + self.commodity_id = commodity_id + self.variety = variety + self.grade = grade + self.arrival_mt = arrival_mt + self.internal_stock_mt = internal_stock_mt + self.min_rate = min_rate + self.max_rate = max_rate + self.modal_rate = modal_rate + self.source = source + self.is_market_closed = is_market_closed + self.created_at = datetime.now(timezone.utc) + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "tenant_id": self.tenant_id, + "mandi_id": self.mandi_id, + "observation_date": str(self.observation_date), + "commodity_id": self.commodity_id, + "variety": self.variety, + "grade": self.grade, + "arrival_mt": float(self.arrival_mt) if self.arrival_mt is not None else 0.0, + "internal_stock_mt": float(self.internal_stock_mt) if self.internal_stock_mt is not None else None, + "min_rate": float(self.min_rate) if self.min_rate is not None else None, + "max_rate": float(self.max_rate) if self.max_rate is not None else None, + "modal_rate": float(self.modal_rate) if self.modal_rate is not None else None, + "source": self.source, + "is_market_closed": self.is_market_closed, + "created_at": self.created_at.isoformat() if self.created_at else None + } + diff --git a/05_implementation_workspace/backend/app/models/procurement.py b/05_implementation_workspace/backend/app/models/procurement.py new file mode 100644 index 0000000..19093eb --- /dev/null +++ b/05_implementation_workspace/backend/app/models/procurement.py @@ -0,0 +1,242 @@ +"""Procurement Contracts & Sauda Booking Models and Invariants. + +Fulfills FR-PROCUREMENTCONTRACTS-001..004 (UC-004). +Adheres to LLD-004 and UP-AI v1.5 standards. +""" +from datetime import datetime, date, timedelta, timezone +from decimal import Decimal, ROUND_HALF_UP +from typing import Optional, Dict, Any +import uuid + +try: + from sqlalchemy import Column, String, DateTime, Date, Numeric, Integer, Boolean + from backend.app.models.user import Base +except ImportError: + class Base: + pass + Column = String = DateTime = Date = Numeric = Integer = Boolean = lambda *args, **kwargs: None + +SAUDA_STATUSES = {"ACTIVE", "PARTIALLY_RECEIVED", "FULFILLED", "CANCELLED"} + + +def calculate_sauda_commercials( + booked_quantity_mt: Decimal, + trade_rate_per_qtl: Decimal, + contract_date: date, + credit_period_days: int, + mandi_cess_pct: Decimal = Decimal("1.50"), + krishi_kalyan_pct: Decimal = Decimal("0.50"), + brokerage_rate_pct: Decimal = Decimal("1.00"), + benchmark_modal_rate: Optional[Decimal] = None, + variance_acknowledged: bool = False +) -> Dict[str, Any]: + """Calculates all financial commercial terms and validates variance alerts.""" + if booked_quantity_mt <= Decimal("0.0"): + raise ValueError("Booked quantity MT must be > 0.0") + + if trade_rate_per_qtl <= Decimal("0.0"): + raise ValueError("Trade rate per quintal must be > 0.0") + + if credit_period_days < 0: + raise ValueError("Credit period days must be >= 0") + + # Gross value = Booked MT * 10 Qtl/MT * Rate/Qtl + gross_amount = (booked_quantity_mt * Decimal("10.0") * trade_rate_per_qtl).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + + # Variance alert check + variance_pct = Decimal("0.00") + if benchmark_modal_rate is not None and benchmark_modal_rate > Decimal("0.0"): + diff = trade_rate_per_qtl - benchmark_modal_rate + variance_pct = ((diff / benchmark_modal_rate) * Decimal("100.0")).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + if variance_pct > Decimal("5.00") and not variance_acknowledged: + raise ValueError( + f"Offered trade rate ({trade_rate_per_qtl}) exceeds benchmark modal rate ({benchmark_modal_rate}) " + f"by +{variance_pct}%, which is > 5.0% threshold. Explicit variance acknowledgment is required." + ) + + # Statutory APMC Cess and Levies + mandi_cess_amount = (gross_amount * (mandi_cess_pct / Decimal("100.0"))).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + krishi_kalyan_amount = (gross_amount * (krishi_kalyan_pct / Decimal("100.0"))).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + brokerage_amount = (gross_amount * (brokerage_rate_pct / Decimal("100.0"))).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + total_landed_amount = gross_amount + mandi_cess_amount + krishi_kalyan_amount + brokerage_amount + + # Due date arithmetic + payment_due_date = contract_date + timedelta(days=credit_period_days) + + return { + "gross_amount": gross_amount, + "variance_pct": variance_pct, + "mandi_cess_amount": mandi_cess_amount, + "krishi_kalyan_amount": krishi_kalyan_amount, + "brokerage_amount": brokerage_amount, + "total_landed_amount": total_landed_amount, + "payment_due_date": payment_due_date + } + + +class ProcurementSauda(Base): + __tablename__ = "procurement_sauda" + __table_args__ = {"schema": "public"} + + id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) + tenant_id = Column(String(36), nullable=False, index=True) + sauda_number = Column(String(32), nullable=False, unique=True, index=True) + contract_date = Column(Date, nullable=False, index=True) + delivery_due_date = Column(Date, nullable=False) + supplier_id = Column(String(36), nullable=False, index=True) + mandi_id = Column(String(36), nullable=False) + trade_type = Column(String(32), default="MANDI_AUCTION") + commodity_id = Column(String(36), nullable=False) + variety = Column(String(64), nullable=False) + grade = Column(String(32), default="FAQ") + booked_quantity_mt = Column(Numeric(12, 3), nullable=False) + estimated_bags = Column(Integer, default=0) + trade_rate_per_qtl = Column(Numeric(10, 2), nullable=False) + cumulative_received_mt = Column(Numeric(12, 3), default=0.0) + balance_mt = Column(Numeric(12, 3), nullable=False) + credit_period_days = Column(Integer, default=0) + payment_due_date = Column(Date, nullable=False) + advance_amount = Column(Numeric(12, 2), default=0.0) + mandi_cess_pct = Column(Numeric(5, 2), default=1.50) + krishi_kalyan_pct = Column(Numeric(5, 2), default=0.50) + brokerage_rate_pct = Column(Numeric(5, 2), default=1.00) + gross_amount = Column(Numeric(14, 2), nullable=False) + mandi_cess_amount = Column(Numeric(12, 2), nullable=False) + krishi_kalyan_amount = Column(Numeric(12, 2), nullable=False) + brokerage_amount = Column(Numeric(12, 2), nullable=False) + total_landed_amount = Column(Numeric(14, 2), nullable=False) + variance_pct = Column(Numeric(5, 2), default=0.0) + variance_acknowledged = Column(Boolean, default=False) + status = Column(String(32), default="ACTIVE", index=True) + created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + + def __init__( + self, + tenant_id: str, + sauda_number: str, + contract_date: date, + delivery_due_date: date, + supplier_id: str, + mandi_id: str, + commodity_id: str, + variety: str, + booked_quantity_mt: Decimal, + trade_rate_per_qtl: Decimal, + grade: str = "FAQ", + trade_type: str = "MANDI_AUCTION", + estimated_bags: int = 0, + credit_period_days: int = 0, + advance_amount: Decimal = Decimal("0.00"), + mandi_cess_pct: Decimal = Decimal("1.50"), + krishi_kalyan_pct: Decimal = Decimal("0.50"), + brokerage_rate_pct: Decimal = Decimal("1.00"), + benchmark_modal_rate: Optional[Decimal] = None, + variance_acknowledged: bool = False, + sauda_id: Optional[str] = None + ): + calc = calculate_sauda_commercials( + booked_quantity_mt=booked_quantity_mt, + trade_rate_per_qtl=trade_rate_per_qtl, + contract_date=contract_date, + credit_period_days=credit_period_days, + mandi_cess_pct=mandi_cess_pct, + krishi_kalyan_pct=krishi_kalyan_pct, + brokerage_rate_pct=brokerage_rate_pct, + benchmark_modal_rate=benchmark_modal_rate, + variance_acknowledged=variance_acknowledged + ) + + self.id = sauda_id or str(uuid.uuid4()) + self.tenant_id = tenant_id + self.sauda_number = sauda_number + self.contract_date = contract_date + self.delivery_due_date = delivery_due_date + self.supplier_id = supplier_id + self.mandi_id = mandi_id + self.trade_type = trade_type + self.commodity_id = commodity_id + self.variety = variety + self.grade = grade + self.booked_quantity_mt = booked_quantity_mt + self.estimated_bags = estimated_bags + self.trade_rate_per_qtl = trade_rate_per_qtl + self.cumulative_received_mt = Decimal("0.000") + self.balance_mt = booked_quantity_mt + self.credit_period_days = credit_period_days + self.payment_due_date = calc["payment_due_date"] + self.advance_amount = advance_amount + self.mandi_cess_pct = mandi_cess_pct + self.krishi_kalyan_pct = krishi_kalyan_pct + self.brokerage_rate_pct = brokerage_rate_pct + self.gross_amount = calc["gross_amount"] + self.mandi_cess_amount = calc["mandi_cess_amount"] + self.krishi_kalyan_amount = calc["krishi_kalyan_amount"] + self.brokerage_amount = calc["brokerage_amount"] + self.total_landed_amount = calc["total_landed_amount"] + self.variance_pct = calc["variance_pct"] + self.variance_acknowledged = variance_acknowledged + self.status = "ACTIVE" + self.created_at = datetime.now(timezone.utc) + + def record_receipt(self, received_mt: Decimal, tolerance_pct: Decimal = Decimal("0.50")) -> None: + """Records partial delivery receipt and transitions lifecycle state machine.""" + if self.status in {"FULFILLED", "CANCELLED"}: + raise ValueError(f"Cannot record receipt on sauda in terminal status '{self.status}'") + + if received_mt <= Decimal("0.000"): + raise ValueError("Received metric tonnes must be > 0.0") + + self.cumulative_received_mt = (self.cumulative_received_mt + received_mt).quantize(Decimal("0.001")) + self.balance_mt = max(Decimal("0.000"), (self.booked_quantity_mt - self.cumulative_received_mt).quantize(Decimal("0.001"))) + + tolerance_mt = (self.booked_quantity_mt * (tolerance_pct / Decimal("100.0"))).quantize(Decimal("0.001")) + if self.cumulative_received_mt >= (self.booked_quantity_mt - tolerance_mt): + self.status = "FULFILLED" + else: + self.status = "PARTIALLY_RECEIVED" + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "tenant_id": self.tenant_id, + "sauda_number": self.sauda_number, + "contract_date": str(self.contract_date), + "delivery_due_date": str(self.delivery_due_date), + "supplier_id": self.supplier_id, + "mandi_id": self.mandi_id, + "trade_type": self.trade_type, + "commodity_id": self.commodity_id, + "variety": self.variety, + "grade": self.grade, + "booked_quantity_mt": float(self.booked_quantity_mt), + "estimated_bags": self.estimated_bags, + "trade_rate_per_qtl": float(self.trade_rate_per_qtl), + "cumulative_received_mt": float(self.cumulative_received_mt), + "balance_mt": float(self.balance_mt), + "credit_period_days": self.credit_period_days, + "payment_due_date": str(self.payment_due_date), + "advance_amount": float(self.advance_amount), + "mandi_cess_pct": float(self.mandi_cess_pct), + "krishi_kalyan_pct": float(self.krishi_kalyan_pct), + "brokerage_rate_pct": float(self.brokerage_rate_pct), + "gross_amount": float(self.gross_amount), + "mandi_cess_amount": float(self.mandi_cess_amount), + "krishi_kalyan_amount": float(self.krishi_kalyan_amount), + "brokerage_amount": float(self.brokerage_amount), + "total_landed_amount": float(self.total_landed_amount), + "variance_pct": float(self.variance_pct), + "variance_acknowledged": self.variance_acknowledged, + "status": self.status, + "created_at": self.created_at.isoformat() if self.created_at else None + } + diff --git a/05_implementation_workspace/backend/app/models/quality.py b/05_implementation_workspace/backend/app/models/quality.py new file mode 100644 index 0000000..cff8fbf --- /dev/null +++ b/05_implementation_workspace/backend/app/models/quality.py @@ -0,0 +1,281 @@ +"""Quality Assay, Laboratory Inspection and Inventory Lot Models. + +Fulfills FR-INWARDRECEIVING-006 (UC-005) and FR-QUALITYANDLOTCONTROL-001..004 (UC-006). +Adheres to LLD-003 and UP-AI v1.5 standards. +""" +from datetime import datetime, timezone +from decimal import Decimal, ROUND_HALF_UP +from typing import Optional, Dict, Any, List +import uuid + +try: + from sqlalchemy import Column, String, DateTime, Numeric, ForeignKey + from backend.app.models.user import Base +except ImportError: + class Base: + pass + Column = String = DateTime = Numeric = ForeignKey = lambda *args, **kwargs: None + +LOT_QC_STATES = {"QUALITY_HOLD", "RELEASED", "REJECTED"} +VALID_QC_TRANSITIONS = { + "QUALITY_HOLD": {"RELEASED", "REJECTED"}, + "RELEASED": set(), # Released lots do not move back to Hold without formal re-sample + "REJECTED": set(), # Terminal state +} + + +def calculate_quality_rebates( + lot_quantity_mt: Decimal, + trade_rate_per_qtl: Decimal, + moisture_pct: Decimal, + foreign_matter_pct: Decimal, + standard_moisture_max: Decimal = Decimal("10.0"), + standard_foreign_max: Decimal = Decimal("1.5") +) -> Dict[str, Any]: + """Calculates commercial weight haircuts and rate cuts (Karda) against FAQ benchmarks.""" + for p_name, val in [("moisture_pct", moisture_pct), ("foreign_matter_pct", foreign_matter_pct)]: + if not (Decimal("0.0") <= val <= Decimal("100.0")): + raise ValueError(f"{p_name} must be between 0.0 and 100.0 percent") + + # Excess moisture leads to physical weight deduction + excess_moisture = max(Decimal("0.0"), moisture_pct - standard_moisture_max) + weight_deduction_mt = (lot_quantity_mt * (excess_moisture / Decimal("100.0"))).quantize( + Decimal("0.001"), rounding=ROUND_HALF_UP + ) + net_billable_weight_mt = (lot_quantity_mt - weight_deduction_mt).quantize( + Decimal("0.001"), rounding=ROUND_HALF_UP + ) + + # Excess foreign matter leads to price rate cut (₹/Qtl) + excess_foreign = max(Decimal("0.0"), foreign_matter_pct - standard_foreign_max) + # Standard formula: 1% excess admixture = ₹ 30.00 / Qtl rate cut + rate_deduction_per_qtl = (excess_foreign * Decimal("30.00")).quantize( + Decimal("0.01"), rounding=ROUND_HALF_UP + ) + + # Total rebate amount = (weight deduction value) + (remaining qtl * rate cut) + weight_cut_val = weight_deduction_mt * Decimal("10.0") * trade_rate_per_qtl + rate_cut_val = net_billable_weight_mt * Decimal("10.0") * rate_deduction_per_qtl + total_rebate_amount = (weight_cut_val + rate_cut_val).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + return { + "excess_moisture_pct": excess_moisture, + "weight_deduction_mt": weight_deduction_mt, + "net_billable_weight_mt": net_billable_weight_mt, + "excess_foreign_pct": excess_foreign, + "rate_deduction_per_qtl": rate_deduction_per_qtl, + "total_rebate_amount": total_rebate_amount + } + + +class InventoryLot(Base): + __tablename__ = "inventory_lots" + __table_args__ = {"schema": "public"} + + id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) + tenant_id = Column(String(36), nullable=False, index=True) + lot_number = Column(String(32), nullable=False, unique=True, index=True) + grn_id = Column(String(36), nullable=False, index=True) + commodity_id = Column(String(36), nullable=False) + variety = Column(String(64), nullable=False) + grade = Column(String(32), default="FAQ") + godown_stack_id = Column(String(36), nullable=False) + initial_quantity_mt = Column(Numeric(12, 3), nullable=False) + current_quantity_mt = Column(Numeric(12, 3), nullable=False) + qc_status = Column(String(32), default="QUALITY_HOLD", index=True) + parent_lot_id = Column(String(36), nullable=True, index=True) + created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + + def __init__( + self, + tenant_id: str, + lot_number: str, + grn_id: str, + commodity_id: str, + variety: str, + godown_stack_id: str, + initial_quantity_mt: Decimal, + grade: str = "FAQ", + parent_lot_id: Optional[str] = None, + lot_id: Optional[str] = None + ): + if initial_quantity_mt <= Decimal("0.000"): + raise ValueError("Lot initial quantity MT must be > 0.0") + + self.id = lot_id or str(uuid.uuid4()) + self.tenant_id = tenant_id + self.lot_number = lot_number + self.grn_id = grn_id + self.commodity_id = commodity_id + self.variety = variety + self.grade = grade + self.godown_stack_id = godown_stack_id + self.initial_quantity_mt = initial_quantity_mt + self.current_quantity_mt = initial_quantity_mt + self.qc_status = "QUALITY_HOLD" + self.parent_lot_id = parent_lot_id + self.created_at = datetime.now(timezone.utc) + + def transition_qc_status(self, new_status: str) -> None: + """Executes strict finite state machine transition on lot quality status.""" + if new_status not in LOT_QC_STATES: + raise ValueError(f"Invalid QC status '{new_status}'") + if self.qc_status == new_status: + return + + allowed = VALID_QC_TRANSITIONS.get(self.qc_status, set()) + if new_status not in allowed: + raise ValueError( + f"Illegal QC state transition from '{self.qc_status}' to '{new_status}'. " + f"Allowed: {list(allowed) if allowed else 'None (terminal)'}." + ) + self.qc_status = new_status + + def assert_can_dispatch(self) -> None: + """Enforces invariant: Produce in QUALITY_HOLD or REJECTED cannot be dispatched.""" + if self.qc_status == "QUALITY_HOLD": + raise ValueError(f"Cannot dispatch lot '{self.lot_number}' under Quality Hold") + if self.qc_status == "REJECTED": + raise ValueError(f"Cannot dispatch lot '{self.lot_number}' with status REJECTED") + + def split_lot(self, split_quantities_mt: List[Decimal]) -> List["InventoryLot"]: + """Splits this lot into child sub-lots preserving ancestry lineage.""" + self.assert_can_dispatch() + total_split = sum(split_quantities_mt) + if total_split > self.current_quantity_mt: + raise ValueError(f"Split quantity ({total_split} MT) exceeds available lot balance ({self.current_quantity_mt} MT)") + + children = [] + for idx, q_mt in enumerate(split_quantities_mt): + child_num = f"{self.lot_number}-SPLIT-{idx + 1}" + child = InventoryLot( + tenant_id=self.tenant_id, + lot_number=child_num, + grn_id=self.grn_id, + commodity_id=self.commodity_id, + variety=self.variety, + godown_stack_id=self.godown_stack_id, + initial_quantity_mt=q_mt, + grade=self.grade, + parent_lot_id=self.id + ) + # Inherit parent's approved QC status + child.qc_status = self.qc_status + children.append(child) + + self.current_quantity_mt = (self.current_quantity_mt - total_split).quantize(Decimal("0.001")) + return children + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "tenant_id": self.tenant_id, + "lot_number": self.lot_number, + "grn_id": self.grn_id, + "commodity_id": self.commodity_id, + "variety": self.variety, + "grade": self.grade, + "godown_stack_id": self.godown_stack_id, + "initial_quantity_mt": float(self.initial_quantity_mt), + "current_quantity_mt": float(self.current_quantity_mt), + "qc_status": self.qc_status, + "parent_lot_id": self.parent_lot_id, + "created_at": self.created_at.isoformat() if self.created_at else None + } + + +class QualityInspection(Base): + __tablename__ = "quality_inspections" + __table_args__ = {"schema": "public"} + + id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) + tenant_id = Column(String(36), nullable=False, index=True) + lot_id = Column(String(36), nullable=False, index=True) + sample_code = Column(String(32), nullable=False) + inspection_timestamp = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + inspector_email = Column(String(255), nullable=False) + moisture_pct = Column(Numeric(5, 2), nullable=False) + foreign_matter_pct = Column(Numeric(5, 2), nullable=False) + damaged_grain_pct = Column(Numeric(5, 2), default=0.0) + oil_content_pct = Column(Numeric(5, 2), default=0.0) + moisture_weight_deduction_mt = Column(Numeric(12, 3), default=0.0) + net_billable_weight_mt = Column(Numeric(12, 3), nullable=False) + rate_deduction_per_qtl = Column(Numeric(10, 2), default=0.0) + total_rebate_amount = Column(Numeric(12, 2), default=0.0) + decision = Column(String(32), nullable=False) + rejection_reason = Column(String(255), nullable=True) + remarks = Column(String(255), nullable=True) + + def __init__( + self, + tenant_id: str, + lot_id: str, + sample_code: str, + inspector_email: str, + lot_quantity_mt: Decimal, + trade_rate_per_qtl: Decimal, + moisture_pct: Decimal, + foreign_matter_pct: Decimal, + decision: str, + damaged_grain_pct: Decimal = Decimal("0.0"), + oil_content_pct: Decimal = Decimal("0.0"), + rejection_reason: Optional[str] = None, + remarks: Optional[str] = None, + standard_moisture_max: Decimal = Decimal("10.0"), + standard_foreign_max: Decimal = Decimal("1.5"), + inspection_id: Optional[str] = None + ): + if decision not in {"RELEASED", "CONDITIONAL_RELEASE", "REJECTED"}: + raise ValueError(f"Invalid inspection decision '{decision}'") + + if decision == "REJECTED" and not rejection_reason: + raise ValueError("Rejection reason is mandatory when decision is REJECTED") + + calc = calculate_quality_rebates( + lot_quantity_mt=lot_quantity_mt, + trade_rate_per_qtl=trade_rate_per_qtl, + moisture_pct=moisture_pct, + foreign_matter_pct=foreign_matter_pct, + standard_moisture_max=standard_moisture_max, + standard_foreign_max=standard_foreign_max + ) + + self.id = inspection_id or str(uuid.uuid4()) + self.tenant_id = tenant_id + self.lot_id = lot_id + self.sample_code = sample_code + self.inspection_timestamp = datetime.now(timezone.utc) + self.inspector_email = inspector_email + self.moisture_pct = moisture_pct + self.foreign_matter_pct = foreign_matter_pct + self.damaged_grain_pct = damaged_grain_pct + self.oil_content_pct = oil_content_pct + self.moisture_weight_deduction_mt = calc["weight_deduction_mt"] + self.net_billable_weight_mt = calc["net_billable_weight_mt"] + self.rate_deduction_per_qtl = calc["rate_deduction_per_qtl"] + self.total_rebate_amount = calc["total_rebate_amount"] + self.decision = decision + self.rejection_reason = rejection_reason + self.remarks = remarks + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "tenant_id": self.tenant_id, + "lot_id": self.lot_id, + "sample_code": self.sample_code, + "inspection_timestamp": self.inspection_timestamp.isoformat() if self.inspection_timestamp else None, + "inspector_email": self.inspector_email, + "moisture_pct": float(self.moisture_pct), + "foreign_matter_pct": float(self.foreign_matter_pct), + "damaged_grain_pct": float(self.damaged_grain_pct), + "oil_content_pct": float(self.oil_content_pct), + "moisture_weight_deduction_mt": float(self.moisture_weight_deduction_mt), + "net_billable_weight_mt": float(self.net_billable_weight_mt), + "rate_deduction_per_qtl": float(self.rate_deduction_per_qtl), + "total_rebate_amount": float(self.total_rebate_amount), + "decision": self.decision, + "rejection_reason": self.rejection_reason, + "remarks": self.remarks + } + diff --git a/05_implementation_workspace/backend/app/models/receiving.py b/05_implementation_workspace/backend/app/models/receiving.py new file mode 100644 index 0000000..cf5f50f --- /dev/null +++ b/05_implementation_workspace/backend/app/models/receiving.py @@ -0,0 +1,287 @@ +"""Inward Yard Gate Entry, Weighbridge and GRN Models. + +Fulfills FR-INWARDRECEIVING-001..005 (UC-005). +Adheres to LLD-003 and UP-AI v1.5 standards. +""" +from datetime import datetime, timezone +from decimal import Decimal, ROUND_HALF_UP +import re +from typing import Optional, Dict, Any +import uuid + +try: + from sqlalchemy import Column, String, DateTime, Numeric, Integer, Boolean, ForeignKey + from backend.app.models.user import Base +except ImportError: + class Base: + pass + Column = String = DateTime = Numeric = Integer = Boolean = ForeignKey = lambda *args, **kwargs: None + +GATE_ENTRY_STATUSES = { + "GATE_IN", "WEIGHED_GROSS", "UNLOADED", "WEIGHED_TARE", "GRN_ISSUED", "GATE_OUT" +} + +EWAY_BILL_REGEX = re.compile(r"^\d{12}$") +VEHICLE_NUM_REGEX = re.compile(r"^[A-Z]{2}[0-9]{2}[A-Z]{1,3}[0-9]{4}$") + + +def validate_gate_entry(vehicle_number: str, eway_bill_number: str, driver_mobile: str) -> None: + """Validates yard ingress vehicle and regulatory constraints.""" + clean_veh = vehicle_number.replace("-", "").replace(" ", "").upper() + if not VEHICLE_NUM_REGEX.match(clean_veh): + raise ValueError(f"Invalid Indian vehicle registration format: '{vehicle_number}'") + + if not EWAY_BILL_REGEX.match(eway_bill_number): + raise ValueError(f"Invalid e-Way bill number: '{eway_bill_number}'. Must be exactly 12 numeric digits.") + + if not (len(driver_mobile) == 10 and driver_mobile.isdigit() and driver_mobile[0] in "6789"): + raise ValueError(f"Invalid driver mobile number: '{driver_mobile}'. Must be a valid 10-digit Indian phone.") + + +class InwardGateEntry(Base): + __tablename__ = "inward_gate_entries" + __table_args__ = {"schema": "public"} + + id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) + tenant_id = Column(String(36), nullable=False, index=True) + gate_pass_number = Column(String(32), nullable=False, unique=True, index=True) + gate_in_timestamp = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + vehicle_number = Column(String(16), nullable=False, index=True) + eway_bill_number = Column(String(12), nullable=False) + driver_name = Column(String(100), nullable=False) + driver_mobile = Column(String(10), nullable=False) + sauda_id = Column(String(36), nullable=False, index=True) + supplier_invoice_no = Column(String(64), nullable=False) + supplier_dispatch_weight_mt = Column(Numeric(12, 3), nullable=False) + supplier_dispatch_bags = Column(Integer, nullable=False) + is_seal_intact = Column(Boolean, default=True) + status = Column(String(32), default="GATE_IN", index=True) + + def __init__( + self, + tenant_id: str, + gate_pass_number: str, + vehicle_number: str, + eway_bill_number: str, + driver_name: str, + driver_mobile: str, + sauda_id: str, + supplier_invoice_no: str, + supplier_dispatch_weight_mt: Decimal, + supplier_dispatch_bags: int, + is_seal_intact: bool = True, + entry_id: Optional[str] = None + ): + validate_gate_entry(vehicle_number, eway_bill_number, driver_mobile) + if supplier_dispatch_weight_mt <= Decimal("0.000"): + raise ValueError("Supplier dispatch weight must be > 0.0 MT") + if supplier_dispatch_bags <= 0: + raise ValueError("Supplier dispatch bag count must be > 0") + + self.id = entry_id or str(uuid.uuid4()) + self.tenant_id = tenant_id + self.gate_pass_number = gate_pass_number + self.gate_in_timestamp = datetime.now(timezone.utc) + self.vehicle_number = vehicle_number.replace("-", "").replace(" ", "").upper() + self.eway_bill_number = eway_bill_number + self.driver_name = driver_name + self.driver_mobile = driver_mobile + self.sauda_id = sauda_id + self.supplier_invoice_no = supplier_invoice_no + self.supplier_dispatch_weight_mt = supplier_dispatch_weight_mt + self.supplier_dispatch_bags = supplier_dispatch_bags + self.is_seal_intact = is_seal_intact + self.status = "GATE_IN" + + def transition_status(self, next_status: str) -> None: + if next_status not in GATE_ENTRY_STATUSES: + raise ValueError(f"Invalid gate entry status '{next_status}'") + self.status = next_status + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "tenant_id": self.tenant_id, + "gate_pass_number": self.gate_pass_number, + "gate_in_timestamp": self.gate_in_timestamp.isoformat() if self.gate_in_timestamp else None, + "vehicle_number": self.vehicle_number, + "eway_bill_number": self.eway_bill_number, + "driver_name": self.driver_name, + "driver_mobile": self.driver_mobile, + "sauda_id": self.sauda_id, + "supplier_invoice_no": self.supplier_invoice_no, + "supplier_dispatch_weight_mt": float(self.supplier_dispatch_weight_mt), + "supplier_dispatch_bags": self.supplier_dispatch_bags, + "is_seal_intact": self.is_seal_intact, + "status": self.status + } + + +class WeighbridgeSlip(Base): + __tablename__ = "weighbridge_slips" + __table_args__ = {"schema": "public"} + + id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) + tenant_id = Column(String(36), nullable=False, index=True) + slip_number = Column(String(32), nullable=False, unique=True, index=True) + gate_pass_id = Column(String(36), nullable=False, index=True) + gross_weight_mt = Column(Numeric(12, 3), nullable=False) + gross_timestamp = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + tare_weight_mt = Column(Numeric(12, 3), nullable=True) + tare_timestamp = Column(DateTime, nullable=True) + unloaded_weight_mt = Column(Numeric(12, 3), nullable=True) + bag_packaging_type = Column(String(32), nullable=True) + bag_tare_rate_kg = Column(Numeric(6, 3), nullable=True) + actual_bag_count = Column(Integer, default=0) + bag_tare_deduction_mt = Column(Numeric(12, 3), default=0.0) + final_net_weight_mt = Column(Numeric(12, 3), nullable=True) + shortage_weight_mt = Column(Numeric(12, 3), nullable=True) + shortage_pct = Column(Numeric(5, 2), nullable=True) + is_shortage_exceeded = Column(Boolean, default=False) + + def __init__( + self, + tenant_id: str, + slip_number: str, + gate_pass_id: str, + gross_weight_mt: Decimal, + slip_id: Optional[str] = None + ): + if gross_weight_mt <= Decimal("0.000"): + raise ValueError("Gross weight must be > 0.0 MT") + + self.id = slip_id or str(uuid.uuid4()) + self.tenant_id = tenant_id + self.slip_number = slip_number + self.gate_pass_id = gate_pass_id + self.gross_weight_mt = gross_weight_mt + self.gross_timestamp = datetime.now(timezone.utc) + self.tare_weight_mt = None + self.tare_timestamp = None + self.unloaded_weight_mt = None + self.bag_packaging_type = None + self.bag_tare_rate_kg = None + self.actual_bag_count = 0 + self.bag_tare_deduction_mt = Decimal("0.000") + self.final_net_weight_mt = None + self.shortage_weight_mt = None + self.shortage_pct = None + self.is_shortage_exceeded = False + + def record_tare( + self, + tare_weight_mt: Decimal, + bag_packaging_type: str, + actual_bag_count: int, + billed_weight_mt: Decimal, + bag_tare_rate_kg: Optional[Decimal] = None, + tolerance_pct: Decimal = Decimal("0.50") + ) -> None: + """Records tare weighment and computes bag deductions and shortage.""" + if tare_weight_mt >= self.gross_weight_mt: + raise ValueError("Tare weight must be strictly less than Gross weight") + + from sandbox.weighbridge_mock import WeighbridgeMock + calc = WeighbridgeMock.process_weighment( + gross_weight_mt=self.gross_weight_mt, + tare_weight_mt=tare_weight_mt, + packaging_type=bag_packaging_type, + bag_count=actual_bag_count, + billed_weight_mt=billed_weight_mt, + tolerance_pct=tolerance_pct + ) + + self.tare_weight_mt = Decimal(str(calc["tare_weight_mt"])) + self.tare_timestamp = datetime.now(timezone.utc) + self.unloaded_weight_mt = Decimal(str(calc["unloaded_weight_mt"])) + self.bag_packaging_type = bag_packaging_type + self.bag_tare_rate_kg = bag_tare_rate_kg or ( + Decimal(str(calc["bag_tare_deduction_mt"])) * Decimal("1000.0") / Decimal(str(actual_bag_count)) + if actual_bag_count > 0 else Decimal("0.000") + ) + self.actual_bag_count = actual_bag_count + self.bag_tare_deduction_mt = Decimal(str(calc["bag_tare_deduction_mt"])) + self.final_net_weight_mt = Decimal(str(calc["final_net_weight_mt"])) + self.shortage_weight_mt = Decimal(str(calc["shortage_weight_mt"])) + self.shortage_pct = Decimal(str(calc["shortage_pct"])) + self.is_shortage_exceeded = calc["is_shortage_exceeded"] + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "tenant_id": self.tenant_id, + "slip_number": self.slip_number, + "gate_pass_id": self.gate_pass_id, + "gross_weight_mt": float(self.gross_weight_mt), + "gross_timestamp": self.gross_timestamp.isoformat() if self.gross_timestamp else None, + "tare_weight_mt": float(self.tare_weight_mt) if self.tare_weight_mt is not None else None, + "tare_timestamp": self.tare_timestamp.isoformat() if self.tare_timestamp else None, + "unloaded_weight_mt": float(self.unloaded_weight_mt) if self.unloaded_weight_mt is not None else None, + "bag_packaging_type": self.bag_packaging_type, + "actual_bag_count": self.actual_bag_count, + "bag_tare_deduction_mt": float(self.bag_tare_deduction_mt), + "final_net_weight_mt": float(self.final_net_weight_mt) if self.final_net_weight_mt is not None else None, + "shortage_weight_mt": float(self.shortage_weight_mt) if self.shortage_weight_mt is not None else None, + "shortage_pct": float(self.shortage_pct) if self.shortage_pct is not None else None, + "is_shortage_exceeded": self.is_shortage_exceeded + } + + +class GoodsReceiptNote(Base): + __tablename__ = "goods_receipt_notes" + __table_args__ = {"schema": "public"} + + id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) + tenant_id = Column(String(36), nullable=False, index=True) + grn_number = Column(String(32), nullable=False, unique=True, index=True) + grn_date = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + weighment_slip_id = Column(String(36), nullable=False, index=True) + sauda_id = Column(String(36), nullable=False, index=True) + godown_id = Column(String(36), nullable=False) + godown_stack_id = Column(String(36), nullable=False) + accepted_quantity_mt = Column(Numeric(12, 3), nullable=False) + accepted_bags = Column(Integer, nullable=False) + status = Column(String(32), default="POSTED") + + def __init__( + self, + tenant_id: str, + grn_number: str, + weighment_slip_id: str, + sauda_id: str, + godown_id: str, + godown_stack_id: str, + accepted_quantity_mt: Decimal, + accepted_bags: int, + grn_id: Optional[str] = None + ): + if accepted_quantity_mt <= Decimal("0.000"): + raise ValueError("Accepted quantity MT must be > 0.0") + + self.id = grn_id or str(uuid.uuid4()) + self.tenant_id = tenant_id + self.grn_number = grn_number + self.grn_date = datetime.now(timezone.utc) + self.weighment_slip_id = weighment_slip_id + self.sauda_id = sauda_id + self.godown_id = godown_id + self.godown_stack_id = godown_stack_id + self.accepted_quantity_mt = accepted_quantity_mt + self.accepted_bags = accepted_bags + self.status = "POSTED" + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "tenant_id": self.tenant_id, + "grn_number": self.grn_number, + "grn_date": self.grn_date.isoformat() if self.grn_date else None, + "weighment_slip_id": self.weighment_slip_id, + "sauda_id": self.sauda_id, + "godown_id": self.godown_id, + "godown_stack_id": self.godown_stack_id, + "accepted_quantity_mt": float(self.accepted_quantity_mt), + "accepted_bags": self.accepted_bags, + "status": self.status + } + diff --git a/05_implementation_workspace/docs/api/bruno b/05_implementation_workspace/docs/api/bruno new file mode 120000 index 0000000..902c814 --- /dev/null +++ b/05_implementation_workspace/docs/api/bruno @@ -0,0 +1 @@ +../../../docs/api/bruno \ No newline at end of file diff --git a/05_implementation_workspace/sandbox/master_data_mock.py b/05_implementation_workspace/sandbox/master_data_mock.py new file mode 100644 index 0000000..cd14c72 --- /dev/null +++ b/05_implementation_workspace/sandbox/master_data_mock.py @@ -0,0 +1,185 @@ +"""Wave 0 Master Data Mock Adapter for Iteration 03. + +Pre-seeds deterministic, canonical master data fixtures for standard Indian Mandi +market yards, commodities, counterparties (suppliers/arhatiyas), and godowns/stacks. +""" +from typing import Dict, Any, List, Optional +import uuid + +# Canonical Mandi Yards +MANDI_YARDS = [ + { + "id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", + "name": "Kota APMC Yard", + "state": "Rajasthan", + "district": "Kota", + "code": "RJ-KTA-01", + "is_active": True + }, + { + "id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6e", + "name": "Unjha APMC Yard", + "state": "Gujarat", + "district": "Mehsana", + "code": "GJ-UNJ-01", + "is_active": True + }, + { + "id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6f", + "name": "Indore APMC Yard", + "state": "Madhya Pradesh", + "district": "Indore", + "code": "MP-IND-01", + "is_active": True + } +] + +# Canonical Commodities +COMMODITIES = [ + { + "id": "c0a80123-0000-0000-0000-000000000001", + "name": "Soyabean", + "code": "SOY", + "standard_grade": "FAQ", + "standard_moisture_max": 10.0, + "standard_foreign_matter_max": 1.5, + "standard_damaged_max": 2.0, + "standard_oil_min": 18.0, + "is_active": True + }, + { + "id": "c0a80123-0000-0000-0000-000000000002", + "name": "Chana (Bengal Gram)", + "code": "CHN", + "standard_grade": "FAQ", + "standard_moisture_max": 10.5, + "standard_foreign_matter_max": 1.0, + "standard_damaged_max": 3.0, + "standard_oil_min": 0.0, + "is_active": True + }, + { + "id": "c0a80123-0000-0000-0000-000000000003", + "name": "Mustard (Sarson)", + "code": "MST", + "standard_grade": "FAQ", + "standard_moisture_max": 8.0, + "standard_foreign_matter_max": 2.0, + "standard_damaged_max": 2.0, + "standard_oil_min": 42.0, + "is_active": True + }, + { + "id": "c0a80123-0000-0000-0000-000000000004", + "name": "Wheat (Lokwan / Sharbati)", + "code": "WHT", + "standard_grade": "FAQ", + "standard_moisture_max": 12.0, + "standard_foreign_matter_max": 1.0, + "standard_damaged_max": 2.0, + "standard_oil_min": 0.0, + "is_active": True + } +] + +# Canonical Counterparties (Suppliers / Arhatiyas) +SUPPLIERS = [ + { + "id": "a0000000-0000-0000-0000-000000000001", + "name": "Kisan Agro Traders", + "code": "SUP-0042", + "gstin": "24ABCDE1234F1Z5", + "pan": "ABCDE1234F", + "mandi_hub": "Kota APMC Yard", + "status": "ACTIVE", + "default_credit_days": 15 + }, + { + "id": "a0000000-0000-0000-0000-000000000002", + "name": "Mewar Krishi Sangh", + "code": "SUP-0043", + "gstin": "08MNOPQ9012R1Z9", + "pan": "MNOPQ9012R", + "mandi_hub": "Unjha APMC Yard", + "status": "ACTIVE", + "default_credit_days": 7 + }, + { + "id": "a0000000-0000-0000-0000-000000000003", + "name": "Defunct Trading Co", + "code": "SUP-INACTIVE", + "gstin": "27GHIJK5678L1Z2", + "pan": "GHIJK5678L", + "mandi_hub": "Indore APMC Yard", + "status": "SUSPENDED", + "default_credit_days": 0 + } +] + +# Warehouse Godowns and Stacks +GODOWNS = [ + { + "id": "d0000000-0000-0000-0000-000000000001", + "name": "Godown 02 - Kota Central Warehouse", + "code": "KTA-GD-02", + "capacity_mt": 1000.0, + "stacks": [ + { + "id": "d1000000-0000-0000-0000-000000000001", + "bay_name": "Stack B-04", + "capacity_mt": 100.0, + "current_mt": 45.0, + "is_full": False + }, + { + "id": "d1000000-0000-0000-0000-000000000002", + "bay_name": "Stack B-05", + "capacity_mt": 100.0, + "current_mt": 100.0, + "is_full": True + } + ] + } +] + + +class MasterDataMock: + """In-memory service providing deterministic lookup for master records.""" + + @classmethod + def get_mandi(cls, mandi_id: str) -> Optional[Dict[str, Any]]: + for m in MANDI_YARDS: + if m["id"] == mandi_id: + return m + return None + + @classmethod + def get_commodity(cls, commodity_id: str) -> Optional[Dict[str, Any]]: + for c in COMMODITIES: + if c["id"] == commodity_id: + return c + return None + + @classmethod + def get_supplier(cls, supplier_id: str) -> Optional[Dict[str, Any]]: + for s in SUPPLIERS: + if s["id"] == supplier_id: + return s + return None + + @classmethod + def get_godown(cls, godown_id: str) -> Optional[Dict[str, Any]]: + for g in GODOWNS: + if g["id"] == godown_id: + return g + return None + + @classmethod + def get_stack(cls, godown_id: str, stack_id: str) -> Optional[Dict[str, Any]]: + godown = cls.get_godown(godown_id) + if godown: + for st in godown["stacks"]: + if st["id"] == stack_id: + return st + return None + diff --git a/05_implementation_workspace/sandbox/weighbridge_mock.py b/05_implementation_workspace/sandbox/weighbridge_mock.py new file mode 100644 index 0000000..881e490 --- /dev/null +++ b/05_implementation_workspace/sandbox/weighbridge_mock.py @@ -0,0 +1,67 @@ +"""Wave 0 Weighbridge Scale Mock Adapter for Iteration 03. + +Simulates offline and automated digital scale captures for incoming agricultural produce trucks, +including bag tare calculation (Bardana Katai) with 3-decimal MT precision. +""" +from typing import Dict, Any, Tuple +from decimal import Decimal, ROUND_HALF_UP + + +BAG_TARE_RATES_KG = { + "JUTE_GUNNY_NEW": Decimal("0.650"), + "JUTE_GUNNY_OLD": Decimal("0.700"), + "HDPE_PLASTIC": Decimal("0.120"), + "BULK_LOOSE": Decimal("0.000") +} + + +class WeighbridgeMock: + """Mock weighing terminal calculating gross/tare weighments and packaging deductions.""" + + @classmethod + def calculate_bag_tare(cls, packaging_type: str, bag_count: int, override_rate_kg: Decimal = None) -> Decimal: + """Calculates bag tare (Bardana Katai) deduction in metric tonnes with 3-decimal precision.""" + if packaging_type == "BULK_LOOSE" or bag_count <= 0: + return Decimal("0.000") + + rate_kg = override_rate_kg if override_rate_kg is not None else BAG_TARE_RATES_KG.get(packaging_type, Decimal("0.650")) + total_kg = Decimal(str(bag_count)) * rate_kg + tare_mt = total_kg / Decimal("1000.0") + return tare_mt.quantize(Decimal("0.001"), rounding=ROUND_HALF_UP) + + @classmethod + def process_weighment(cls, gross_weight_mt: Decimal, tare_weight_mt: Decimal, + packaging_type: str, bag_count: int, + billed_weight_mt: Decimal, + tolerance_pct: Decimal = Decimal("0.50")) -> Dict[str, Any]: + """Processes complete weighbridge calculation.""" + gross = Decimal(str(gross_weight_mt)) + tare = Decimal(str(tare_weight_mt)) + + if tare >= gross: + raise ValueError("Tare weight must be strictly less than Gross weight") + + unloaded_mt = (gross - tare).quantize(Decimal("0.001"), rounding=ROUND_HALF_UP) + bag_tare_mt = cls.calculate_bag_tare(packaging_type, bag_count) + final_net_mt = (unloaded_mt - bag_tare_mt).quantize(Decimal("0.001"), rounding=ROUND_HALF_UP) + + billed = Decimal(str(billed_weight_mt)) + shortage_mt = (final_net_mt - billed).quantize(Decimal("0.001"), rounding=ROUND_HALF_UP) + shortage_pct = ((shortage_mt / billed) * Decimal("100.0")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if billed > Decimal("0.000") else Decimal("0.00") + + # Negative shortage means weight loss in transit + is_exceeded = (shortage_mt < Decimal("0.000")) and (abs(shortage_pct) > tolerance_pct) + + return { + "gross_weight_mt": float(gross), + "tare_weight_mt": float(tare), + "unloaded_weight_mt": float(unloaded_mt), + "bag_packaging_type": packaging_type, + "actual_bag_count": bag_count, + "bag_tare_deduction_mt": float(bag_tare_mt), + "final_net_weight_mt": float(final_net_mt), + "shortage_weight_mt": float(shortage_mt), + "shortage_pct": float(shortage_pct), + "is_shortage_exceeded": is_exceeded + } + diff --git a/05_implementation_workspace/tests/backend/test_inward_receiving.py b/05_implementation_workspace/tests/backend/test_inward_receiving.py new file mode 100644 index 0000000..c97e6f3 --- /dev/null +++ b/05_implementation_workspace/tests/backend/test_inward_receiving.py @@ -0,0 +1,351 @@ +"""Multi-Path Automated Unit & FSM Test Suite for Inward Receiving (UC-005). + +Covers: +- TC-INW-005-01: End-to-end inward receiving flow (Gate -> Weighbridge -> GRN -> Lot). +- TC-INW-005-02: Bag tare (Bardana Katai) 3-decimal precision & shortage tolerance limits. +- TC-INW-005-03: Invariant scale rejection (tare >= gross) & duplicate vehicle check. +- TC-INW-005-04: Lot generation & initial status strictly in QUALITY_HOLD. +""" +from datetime import datetime, date, timezone +from decimal import Decimal +import unittest + +from backend.app.api.receiving import ReceivingController +from backend.app.db.session import InMemoryStorage +from backend.app.models.receiving import InwardGateEntry, WeighbridgeSlip, GoodsReceiptNote, validate_gate_entry +from backend.app.models.tenant import Tenant, TenantMembership +from sandbox.weighbridge_mock import WeighbridgeMock +from sandbox.identity_mock import mock_idp + + +class TestInwardReceiving(unittest.TestCase): + + def setUp(self): + self.store = InMemoryStorage() + self.controller = ReceivingController(store=self.store) + self.tenant_id = "tenant-alpha" + + # Pre-seed active tenant and memberships in store + self.store.save_tenant( + Tenant( + tenant_id=self.tenant_id, + business_name="Alpha Agro", + legal_identifier="24ABCDE1234F1Z5", + contact_email="alpha@agro.com", + primary_mandi="Kota APMC", + status="ACTIVE" + ) + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="supervisor@alpha.com", + email="supervisor@alpha.com", + role="Security Guard", + status="ACTIVE", + membership_id="mem-03a" + ) + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="supervisor@alpha.com", + email="supervisor@alpha.com", + role="Warehouse Supervisor", + status="ACTIVE", + membership_id="mem-03b" + ) + ) + + # Seed yard supervisor token + self.token = mock_idp.mint_jwt( + subject="supervisor@alpha.com", + email="supervisor@alpha.com", + name="Yard Supervisor", + roles=["Security Guard", "Warehouse Supervisor"], + tenant_id=self.tenant_id + ) + self.auth_header = f"Bearer {self.token}" + + # Pre-seed active sauda + self.sauda_id = "sauda-101" + self.store.insert("procurement_sauda", self.tenant_id, { + "id": self.sauda_id, + "tenant_id": self.tenant_id, + "sauda_number": "SDA-26-00042", + "contract_date": "2026-10-12", + "delivery_due_date": "2026-10-18", + "supplier_id": "sup-42", + "mandi_id": "mandi-kota", + "commodity_id": "SOY", + "variety": "Yellow Desi", + "grade": "FAQ", + "booked_quantity_mt": 50.0, + "trade_rate_per_qtl": 4700.0, + "cumulative_received_mt": 0.0, + "balance_mt": 50.0, + "status": "ACTIVE" + }) + + def test_end_to_end_inward_pipeline_happy_path(self): + """TC-INW-005-01: Vehicle Gate Entry -> Weigh Gross -> Weigh Tare -> GRN -> Mint Lot.""" + # Step 1: Gate Pass + gate_payload = { + "vehicle_number": "RJ-20-GA-4581", + "eway_bill_number": "241089201923", + "driver_name": "Ramesh Singh", + "driver_mobile": "9829012345", + "sauda_id": self.sauda_id, + "supplier_invoice_no": "INV-2026-9042", + "supplier_dispatch_weight_mt": 25.0, + "supplier_dispatch_bags": 500, + "is_seal_intact": True + } + res_gate = self.controller.create_gate_entry(self.auth_header, self.tenant_id, gate_payload) + self.assertEqual(res_gate.get("status_code"), 201) + gate_entry = res_gate["gate_entry"] + self.assertEqual(gate_entry["gate_pass_number"], "GP-26-00001") + self.assertEqual(gate_entry["status"], "GATE_IN") + + # Step 2: Gross Weighment + gross_payload = { + "gate_pass_id": gate_entry["id"], + "gross_weight_mt": 38.450 + } + res_gross = self.controller.create_weighment_gross(self.auth_header, self.tenant_id, gross_payload) + self.assertEqual(res_gross.get("status_code"), 201) + slip = res_gross["weighment_slip"] + self.assertEqual(slip["slip_number"], "WS-26-00001") + + # Step 3: Tare Weighment & Bag Tare Worksheet (Bardana Katai) + tare_payload = { + "tare_weight_mt": 13.200, + "bag_packaging_type": "JUTE_GUNNY_NEW", # 0.650 kg/bag + "actual_bag_count": 500 + } + res_tare = self.controller.record_weighment_tare(self.auth_header, self.tenant_id, slip["id"], tare_payload) + self.assertEqual(res_tare.get("status_code"), 200) + updated_slip = res_tare["weighment_slip"] + self.assertEqual(updated_slip["unloaded_weight_mt"], 25.250) # 38.45 - 13.20 + self.assertEqual(updated_slip["bag_tare_deduction_mt"], 0.325) # 500 * 0.650 / 1000 + self.assertEqual(updated_slip["final_net_weight_mt"], 24.925) # 25.25 - 0.325 + self.assertEqual(updated_slip["shortage_weight_mt"], -0.075) # 24.925 - 25.0 + self.assertFalse(updated_slip["is_shortage_exceeded"]) + + # Step 4: Post GRN and Mint Lot + grn_payload = { + "weighment_slip_id": slip["id"], + "godown_id": "godown-02", + "godown_stack_id": "stack-b-04" + } + res_grn = self.controller.post_grn(self.auth_header, self.tenant_id, grn_payload) + self.assertEqual(res_grn.get("status_code"), 201) + grn = res_grn["grn"] + lot = res_grn["lot"] + + self.assertEqual(grn["grn_number"], "GRN-26-00001") + self.assertEqual(grn["accepted_quantity_mt"], 24.925) + self.assertEqual(lot["qc_status"], "QUALITY_HOLD") # Mandatory hold default + self.assertIn("LOT-26-10-SOY-", lot["lot_number"]) + + # Verify Sauda received MT updated + sauda = self.store.get("procurement_sauda", self.tenant_id, self.sauda_id) + self.assertEqual(sauda["cumulative_received_mt"], 24.925) + self.assertEqual(sauda["status"], "PARTIALLY_RECEIVED") + + # Duplicate GRN attempt -> 409 + res_dup_grn = self.controller.post_grn(self.auth_header, self.tenant_id, grn_payload) + self.assertEqual(res_dup_grn.get("status_code"), 409) + self.assertEqual(res_dup_grn.get("error"), "DUPLICATE_GRN") + + def test_bag_tare_precision_and_shortage_tolerance_limits(self): + """TC-INW-005-02: Bag tare calculates accurately to 3 decimals; shortage triggers tolerance.""" + # 600 HDPE bags at 0.120 kg = 0.072 MT tare + tare_mt = WeighbridgeMock.calculate_bag_tare("HDPE_PLASTIC", 600) + self.assertEqual(tare_mt, Decimal("0.072")) + + # Bulk produce (0 bags) = 0.000 MT + bulk_tare = WeighbridgeMock.calculate_bag_tare("BULK_LOOSE", 0) + self.assertEqual(bulk_tare, Decimal("0.000")) + + # Within tolerance shortage (-0.50%) + res_ok = WeighbridgeMock.process_weighment( + gross_weight_mt=Decimal("30.000"), + tare_weight_mt=Decimal("10.000"), + packaging_type="BULK_LOOSE", + bag_count=0, + billed_weight_mt=Decimal("20.100") + ) + self.assertFalse(res_ok["is_shortage_exceeded"]) + + # Exceeding tolerance shortage (-0.75% > 0.50%) + res_exceeded = WeighbridgeMock.process_weighment( + gross_weight_mt=Decimal("30.000"), + tare_weight_mt=Decimal("10.150"), + packaging_type="BULK_LOOSE", + bag_count=0, + billed_weight_mt=Decimal("20.000") + ) + self.assertTrue(res_exceeded["is_shortage_exceeded"]) + + def test_scale_reading_and_vehicle_duplication_invariants(self): + """TC-INW-005-03: Tare >= Gross rejected; duplicate vehicle in yard blocked.""" + # Invariant: tare >= gross rejected + with self.assertRaises(ValueError): + WeighbridgeMock.process_weighment( + gross_weight_mt=Decimal("20.000"), + tare_weight_mt=Decimal("20.000"), + packaging_type="BULK_LOOSE", + bag_count=0, + billed_weight_mt=Decimal("20.000") + ) + + # Pre-seed active vehicle in yard + self.store.insert("inward_gate_entries", self.tenant_id, { + "id": "gate-prev", + "tenant_id": self.tenant_id, + "gate_pass_number": "GP-26-00099", + "vehicle_number": "RJ20GA4581", + "status": "GATE_IN" + }) + + # Attempt to issue second pass for same vehicle inside yard -> 409 + dup_payload = { + "vehicle_number": "RJ-20-GA-4581", + "eway_bill_number": "241089201923", + "driver_name": "Ramesh", + "driver_mobile": "9829012345", + "sauda_id": self.sauda_id, + "supplier_invoice_no": "INV-01", + "supplier_dispatch_weight_mt": 25.0, + "supplier_dispatch_bags": 500 + } + res = self.controller.create_gate_entry(self.auth_header, self.tenant_id, dup_payload) + self.assertEqual(res.get("status_code"), 409) + self.assertEqual(res.get("error"), "VEHICLE_ALREADY_IN_YARD") + + def test_unauthenticated_and_unauthorized_receiving(self): + """TC-INW-005-04: 401 unauthenticated and 403 unauthorized for receiving.""" + res_unauth = self.controller.create_gate_entry(None, self.tenant_id, {}) + self.assertEqual(res_unauth.get("status_code"), 401) + + token_buyer = mock_idp.mint_jwt( + subject="buyer@alpha.com", + email="buyer@alpha.com", + name="Buyer", + roles=["Mandi Buyer"], + tenant_id=self.tenant_id + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="buyer@alpha.com", + email="buyer@alpha.com", + role="Mandi Buyer", + status="ACTIVE" + ) + ) + res_bad_gate = self.controller.create_gate_entry(f"Bearer {token_buyer}", self.tenant_id, {}) + self.assertEqual(res_bad_gate.get("status_code"), 403) + + res_bad_grn = self.controller.post_grn(f"Bearer {token_buyer}", self.tenant_id, {}) + self.assertEqual(res_bad_grn.get("status_code"), 403) + + def test_list_gate_entries_and_not_found_handling(self): + """TC-INW-005-05: List gate passes and verify 404 on missing references.""" + res_list = self.controller.list_gate_entries(self.auth_header, self.tenant_id) + self.assertEqual(res_list.get("status_code"), 200) + + # 404 gross weighment + res_gross = self.controller.create_weighment_gross( + self.auth_header, self.tenant_id, {"gate_pass_id": "non-existent"} + ) + self.assertEqual(res_gross.get("status_code"), 404) + + # 404 tare weighment + res_tare = self.controller.record_weighment_tare( + self.auth_header, self.tenant_id, "non-existent-slip", {"tare_weight_mt": 10.0} + ) + self.assertEqual(res_tare.get("status_code"), 404) + + def test_grn_validation_and_duplicate_handling(self): + """TC-INW-005-06: GRN error handling for non-existent, untared, and duplicate slips.""" + # Non-existent slip + res_404 = self.controller.post_grn(self.auth_header, self.tenant_id, {"weighment_slip_id": "none"}) + self.assertEqual(res_404.get("status_code"), 404) + + # Untared slip + self.store.insert("weighbridge_slips", self.tenant_id, { + "id": "slip-untared", + "tenant_id": self.tenant_id, + "slip_number": "WS-26-99999", + "gate_pass_id": "gate-1", + "final_net_weight_mt": None + }) + res_untared = self.controller.post_grn( + self.auth_header, self.tenant_id, {"weighment_slip_id": "slip-untared"} + ) + self.assertEqual(res_untared.get("status_code"), 400) + self.assertEqual(res_untared.get("error"), "TARE_NOT_COMPLETED") + + # Gate pass with missing sauda + res_no_sauda = self.controller.create_gate_entry( + self.auth_header, self.tenant_id, { + "vehicle_number": "RJ20GA1111", "eway_bill_number": "123456789012", + "driver_mobile": "9829012345", "sauda_id": "non-existent" + } + ) + self.assertEqual(res_no_sauda.get("status_code"), 404) + + # Gate pass with closed sauda + self.store.insert("procurement_sauda", self.tenant_id, { + "id": "sauda-closed", "status": "FULFILLED" + }) + res_closed_sauda = self.controller.create_gate_entry( + self.auth_header, self.tenant_id, { + "vehicle_number": "RJ20GA2222", "eway_bill_number": "123456789012", + "driver_mobile": "9829012345", "sauda_id": "sauda-closed" + } + ) + self.assertEqual(res_closed_sauda.get("status_code"), 400) + + def test_gate_entry_validation_errors(self): + """TC-INW-005-07: InwardGateEntry constructor and validation edge cases.""" + with self.assertRaises(ValueError): + validate_gate_entry("INVALID_VEHICLE", "123456789012", "9829012345") + with self.assertRaises(ValueError): + validate_gate_entry("RJ20GA4581", "123", "9829012345") + with self.assertRaises(ValueError): + validate_gate_entry("RJ20GA4581", "123456789012", "12345") + + with self.assertRaises(ValueError): + InwardGateEntry( + tenant_id=self.tenant_id, + gate_pass_number="GP-01", + vehicle_number="RJ20GA4581", + eway_bill_number="123456789012", + driver_name="Ramesh", + driver_mobile="9829012345", + sauda_id="sauda-1", + supplier_invoice_no="INV-1", + supplier_dispatch_weight_mt=Decimal("-1.0"), + supplier_dispatch_bags=100 + ) + + with self.assertRaises(ValueError): + InwardGateEntry( + tenant_id=self.tenant_id, + gate_pass_number="GP-01", + vehicle_number="RJ20GA4581", + eway_bill_number="123456789012", + driver_name="Ramesh", + driver_mobile="9829012345", + sauda_id="sauda-1", + supplier_invoice_no="INV-1", + supplier_dispatch_weight_mt=Decimal("10.0"), + supplier_dispatch_bags=0 + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/05_implementation_workspace/tests/backend/test_market_desk.py b/05_implementation_workspace/tests/backend/test_market_desk.py new file mode 100644 index 0000000..aec1db7 --- /dev/null +++ b/05_implementation_workspace/tests/backend/test_market_desk.py @@ -0,0 +1,257 @@ +"""Multi-Path Automated Unit & FSM Test Suite for Market Desk (UC-002). + +Covers: +- TC-MKT-002-01: Happy path observation recording & rate bounds. +- TC-MKT-002-02: Boundary rate limits (min <= modal <= max) & zero arrivals. +- TC-MKT-002-03: Duplicate market record & cross-tenant RLS isolation. +- TC-MKT-002-04: Mandi holiday closure & future date rejection. +""" +from datetime import datetime, date, timedelta, timezone +from decimal import Decimal +import unittest + +from backend.app.api.market import MarketController +from backend.app.db.session import InMemoryStorage +from backend.app.models.market import MarketObservation, validate_market_observation +from backend.app.models.tenant import Tenant, TenantMembership +from sandbox.identity_mock import mock_idp + + +class TestMarketDesk(unittest.TestCase): + + def setUp(self): + self.store = InMemoryStorage() + self.controller = MarketController(store=self.store) + self.tenant_id = "tenant-alpha" + + # Pre-seed active tenant and membership in store + self.store.save_tenant( + Tenant( + tenant_id=self.tenant_id, + business_name="Alpha Agro", + legal_identifier="24ABCDE1234F1Z5", + contact_email="alpha@agro.com", + primary_mandi="Kota APMC", + status="ACTIVE" + ) + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="buyer@alpha.com", + email="buyer@alpha.com", + role="Mandi Buyer", + status="ACTIVE" + ) + ) + + # Seed buyer token + self.token = mock_idp.mint_jwt( + subject="buyer@alpha.com", + email="buyer@alpha.com", + name="Mandi Buyer", + roles=["Mandi Buyer"], + tenant_id=self.tenant_id + ) + self.auth_header = f"Bearer {self.token}" + + def test_record_market_observation_happy_path(self): + """TC-MKT-002-01: Happy path recording with valid rates and 3-decimal precision.""" + today = datetime.now(timezone.utc).date() + payload = { + "mandi_id": "mandi-kota", + "observation_date": str(today), + "commodity_id": "comm-soy", + "variety": "Yellow Desi", + "grade": "FAQ", + "arrival_mt": 450.0, + "internal_stock_mt": 120.0, + "min_rate": 4450.0, + "max_rate": 4780.0, + "modal_rate": 4620.0, + "source": "APMC_BULLETIN" + } + + res = self.controller.record_observation(self.auth_header, self.tenant_id, payload) + self.assertEqual(res.get("status_code"), 201) + self.assertTrue(res.get("success")) + obs = res.get("observation", {}) + self.assertEqual(obs["arrival_mt"], 450.0) + self.assertEqual(obs["modal_rate"], 4620.0) + + # Query back + list_res = self.controller.list_observations(self.auth_header, self.tenant_id, mandi_id="mandi-kota") + self.assertEqual(list_res["count"], 1) + + def test_rate_bounds_and_zero_arrival_boundaries(self): + """TC-MKT-002-02: Boundary checks: min <= modal <= max, zero arrival valid, negative rejected.""" + today = datetime.now(timezone.utc).date() + + # Zero arrival is valid (lean trading) + obs_zero = MarketObservation( + tenant_id=self.tenant_id, + mandi_id="mandi-kota", + observation_date=today, + commodity_id="comm-soy", + variety="Yellow", + arrival_mt=Decimal("0.000"), + min_rate=Decimal("5000.00"), + max_rate=Decimal("5000.00"), + modal_rate=Decimal("5000.00") + ) + self.assertEqual(obs_zero.arrival_mt, Decimal("0.000")) + + # Negative arrival rejected + with self.assertRaises(ValueError): + validate_market_observation( + observation_date=today, + arrival_mt=Decimal("-0.001"), + min_rate=Decimal("4000.00"), + max_rate=Decimal("5000.00"), + modal_rate=Decimal("4500.00") + ) + + # Modal rate > max rate rejected + with self.assertRaises(ValueError): + validate_market_observation( + observation_date=today, + arrival_mt=Decimal("100.0"), + min_rate=Decimal("4000.00"), + max_rate=Decimal("5000.00"), + modal_rate=Decimal("5001.00") + ) + + # Modal rate < min rate rejected + with self.assertRaises(ValueError): + validate_market_observation( + observation_date=today, + arrival_mt=Decimal("100.0"), + min_rate=Decimal("4000.00"), + max_rate=Decimal("5000.00"), + modal_rate=Decimal("3999.00") + ) + + def test_duplicate_market_record_rejection(self): + """TC-MKT-002-03: Duplicate observation for same mandi, commodity, variety, date blocked with 409.""" + today = datetime.now(timezone.utc).date() + payload = { + "mandi_id": "mandi-kota", + "observation_date": str(today), + "commodity_id": "comm-soy", + "variety": "Yellow Desi", + "arrival_mt": 400.0, + "min_rate": 4500.0, + "max_rate": 4800.0, + "modal_rate": 4650.0 + } + + # First insert succeeds + res1 = self.controller.record_observation(self.auth_header, self.tenant_id, payload) + self.assertEqual(res1.get("status_code"), 201) + + # Second insert fails with 409 Conflict + res2 = self.controller.record_observation(self.auth_header, self.tenant_id, payload) + self.assertEqual(res2.get("status_code"), 409) + self.assertEqual(res2.get("error"), "DUPLICATE_OBSERVATION") + + def test_mandi_holiday_and_future_date_rejection(self): + """TC-MKT-002-04: Holiday flag allows zero price inputs; future dates rejected.""" + today = datetime.now(timezone.utc).date() + tomorrow = today + timedelta(days=1) + + # Future date rejected + with self.assertRaises(ValueError): + validate_market_observation( + observation_date=tomorrow, + arrival_mt=Decimal("100.0"), + min_rate=Decimal("4000.00"), + max_rate=Decimal("5000.00"), + modal_rate=Decimal("4500.00") + ) + + # Mandi holiday accepted with 0.0 MT arrival and omitted rates + obs_holiday = MarketObservation( + tenant_id=self.tenant_id, + mandi_id="mandi-kota", + observation_date=today, + commodity_id="comm-wheat", + variety="Lokwan", + arrival_mt=Decimal("0.0"), + is_market_closed=True + ) + self.assertTrue(obs_holiday.is_market_closed) + self.assertIsNone(obs_holiday.modal_rate) + + def test_unauthenticated_and_unauthorized_market(self): + """TC-MKT-002-05: 401 unauthenticated and 403 insufficient permissions.""" + res_unauth = self.controller.record_observation(None, self.tenant_id, {}) + self.assertEqual(res_unauth.get("status_code"), 401) + + # Token with unauthorized role + token_bad = mock_idp.mint_jwt( + subject="guard@alpha.com", + email="guard@alpha.com", + name="Guard", + roles=["Security Guard"], + tenant_id=self.tenant_id + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="guard@alpha.com", + email="guard@alpha.com", + role="Security Guard", + status="ACTIVE" + ) + ) + res_bad_role = self.controller.record_observation(f"Bearer {token_bad}", self.tenant_id, {}) + self.assertEqual(res_bad_role.get("status_code"), 403) + + def test_missing_required_fields_market(self): + """TC-MKT-002-06: 422 on missing required inputs.""" + res = self.controller.record_observation(self.auth_header, self.tenant_id, {"mandi_id": "mandi-kota"}) + self.assertEqual(res.get("status_code"), 422) + + def test_get_latest_rates_and_date_filtering(self): + """TC-MKT-002-07: Query latest rates and filter by date and commodity.""" + today = datetime.now(timezone.utc).date() + payload = { + "mandi_id": "mandi-kota", + "observation_date": str(today), + "commodity_id": "comm-soy", + "variety": "Yellow Desi", + "grade": "FAQ", + "arrival_mt": 100.0, + "min_rate": 4400.0, + "max_rate": 4800.0, + "modal_rate": 4600.0, + "source": "APMC_BULLETIN" + } + self.controller.record_observation(self.auth_header, self.tenant_id, payload) + + # List with date filter + res_list = self.controller.list_observations( + self.auth_header, self.tenant_id, mandi_id="mandi-kota", date_filter=str(today) + ) + self.assertEqual(res_list["count"], 1) + + # Latest rates found + res_rates = self.controller.get_latest_rates(self.auth_header, self.tenant_id, "comm-soy", "mandi-kota") + self.assertEqual(res_rates.get("status_code"), 200) + self.assertEqual(res_rates.get("benchmark_modal_rate"), 4600.0) + + # Latest rates not found + res_none = self.controller.get_latest_rates(self.auth_header, self.tenant_id, "comm-unknown") + self.assertIsNone(res_none.get("benchmark_modal_rate")) + + # Filtering with mismatched mandi and date + res_diff_mandi = self.controller.list_observations(self.auth_header, self.tenant_id, mandi_id="other-mandi") + self.assertEqual(res_diff_mandi["count"], 0) + res_diff_date = self.controller.list_observations(self.auth_header, self.tenant_id, date_filter="2020-01-01") + self.assertEqual(res_diff_date["count"], 0) + res_diff_mandi_rates = self.controller.get_latest_rates(self.auth_header, self.tenant_id, "comm-soy", "other-mandi") + self.assertIsNone(res_diff_mandi_rates.get("benchmark_modal_rate")) + + +if __name__ == "__main__": + unittest.main() diff --git a/05_implementation_workspace/tests/backend/test_procurement_contracts.py b/05_implementation_workspace/tests/backend/test_procurement_contracts.py new file mode 100644 index 0000000..ca3c53a --- /dev/null +++ b/05_implementation_workspace/tests/backend/test_procurement_contracts.py @@ -0,0 +1,262 @@ +"""Multi-Path Automated Unit & FSM Test Suite for Procurement Contracts (UC-004). + +Covers: +- TC-PROC-004-01: Happy path sauda booking with statutory levies and credit maturity. +- TC-PROC-004-02: Price variance alert (>5.0% benchmark modal rate) & acknowledgment. +- TC-PROC-004-03: Inactive supplier rejection & negative quantity validation. +- TC-PROC-004-04: Multi-truck partial fulfillment FSM lifecycle. +""" +from datetime import datetime, date, timedelta, timezone +from decimal import Decimal +import unittest + +from backend.app.api.procurement import ProcurementController +from backend.app.db.session import InMemoryStorage +from backend.app.models.procurement import ProcurementSauda, calculate_sauda_commercials +from backend.app.models.tenant import Tenant, TenantMembership +from sandbox.identity_mock import mock_idp +from sandbox.master_data_mock import MasterDataMock + + +class TestProcurementContracts(unittest.TestCase): + + def setUp(self): + self.store = InMemoryStorage() + self.controller = ProcurementController(store=self.store) + self.tenant_id = "tenant-alpha" + + # Pre-seed active tenant and membership in store + self.store.save_tenant( + Tenant( + tenant_id=self.tenant_id, + business_name="Alpha Agro", + legal_identifier="24ABCDE1234F1Z5", + contact_email="alpha@agro.com", + primary_mandi="Kota APMC", + status="ACTIVE" + ) + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="trader@alpha.com", + email="trader@alpha.com", + role="Procurement Officer", + status="ACTIVE" + ) + ) + + # Seed procurement officer token + self.token = mock_idp.mint_jwt( + subject="trader@alpha.com", + email="trader@alpha.com", + name="Procurement Trader", + roles=["Procurement Officer"], + tenant_id=self.tenant_id + ) + self.auth_header = f"Bearer {self.token}" + + def test_sauda_booking_and_commercials_happy_path(self): + """TC-PROC-004-01: Accurate calculation of gross value, APMC levies, and due date.""" + today = date(2026, 10, 12) + payload = { + "contract_date": str(today), + "delivery_due_date": str(today + timedelta(days=6)), + "supplier_id": "a0000000-0000-0000-0000-000000000001", # Kisan Agro Traders (Active) + "mandi_id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", + "trade_type": "MANDI_AUCTION", + "commodity_id": "c0a80123-0000-0000-0000-000000000001", + "variety": "Yellow Desi", + "grade": "FAQ", + "booked_quantity_mt": 50.0, + "estimated_bags": 1000, + "trade_rate_per_qtl": 4700.0, + "benchmark_modal_rate": 4600.0, # +2.17% variance (<= 5%) + "credit_period_days": 15, + "advance_amount": 50000.0, + "mandi_cess_pct": 1.5, + "krishi_kalyan_pct": 0.5, + "brokerage_rate_pct": 1.0 + } + + res = self.controller.book_sauda(self.auth_header, self.tenant_id, payload) + self.assertEqual(res.get("status_code"), 201) + sauda = res["sauda"] + self.assertEqual(sauda["sauda_number"], "SDA-26-00001") + self.assertEqual(sauda["gross_amount"], 2350000.0) # 50 MT * 10 * 4700 + self.assertEqual(sauda["mandi_cess_amount"], 35250.0) # 1.5% + self.assertEqual(sauda["krishi_kalyan_amount"], 11750.0) # 0.5% + self.assertEqual(sauda["brokerage_amount"], 23500.0) # 1.0% + self.assertEqual(sauda["total_landed_amount"], 2420500.0) + self.assertEqual(sauda["payment_due_date"], "2026-10-27") + self.assertEqual(sauda["status"], "ACTIVE") + + def test_price_variance_alert_and_acknowledgment(self): + """TC-PROC-004-02: Rates > 5.0% above modal benchmark require explicit acknowledgment.""" + today = date(2026, 10, 12) + payload = { + "contract_date": str(today), + "delivery_due_date": str(today + timedelta(days=6)), + "supplier_id": "a0000000-0000-0000-0000-000000000001", + "mandi_id": "mandi-01", + "commodity_id": "comm-01", + "variety": "Yellow", + "booked_quantity_mt": 50.0, + "trade_rate_per_qtl": 4850.0, + "benchmark_modal_rate": 4600.0, # +5.43% variance (> 5.0%) + "variance_acknowledged": False + } + + # Attempt without acknowledgment -> rejected + res = self.controller.book_sauda(self.auth_header, self.tenant_id, payload) + self.assertEqual(res.get("status_code"), 422) + self.assertIn("> 5.0% threshold", res.get("message", "")) + + # Attempt with variance_acknowledged: True -> succeeds + payload["variance_acknowledged"] = True + res_ok = self.controller.book_sauda(self.auth_header, self.tenant_id, payload) + self.assertEqual(res_ok.get("status_code"), 201) + self.assertTrue(res_ok["sauda"]["variance_acknowledged"]) + + def test_inactive_supplier_rejection(self): + """TC-PROC-004-03: Booking against suspended/inactive supplier is rejected with 400.""" + today = date(2026, 10, 12) + payload = { + "contract_date": str(today), + "delivery_due_date": str(today + timedelta(days=6)), + "supplier_id": "a0000000-0000-0000-0000-000000000003", # SUP-INACTIVE (SUSPENDED) + "mandi_id": "mandi-01", + "commodity_id": "comm-01", + "variety": "Yellow", + "booked_quantity_mt": 50.0, + "trade_rate_per_qtl": 4600.0 + } + + res = self.controller.book_sauda(self.auth_header, self.tenant_id, payload) + self.assertEqual(res.get("status_code"), 400) + self.assertEqual(res.get("error"), "INACTIVE_SUPPLIER") + + def test_multi_truck_partial_fulfillment_fsm(self): + """TC-PROC-004-04: Sauda transitions ACTIVE -> PARTIALLY_RECEIVED -> FULFILLED.""" + today = date(2026, 10, 12) + sauda = ProcurementSauda( + tenant_id=self.tenant_id, + sauda_number="SDA-26-00099", + contract_date=today, + delivery_due_date=today + timedelta(days=5), + supplier_id="sup-01", + mandi_id="mandi-01", + commodity_id="comm-01", + variety="Yellow", + booked_quantity_mt=Decimal("50.000"), + trade_rate_per_qtl=Decimal("4600.00") + ) + self.assertEqual(sauda.status, "ACTIVE") + self.assertEqual(sauda.balance_mt, Decimal("50.000")) + + # Truck 1 receives 24.925 MT + sauda.record_receipt(Decimal("24.925")) + self.assertEqual(sauda.status, "PARTIALLY_RECEIVED") + self.assertEqual(sauda.cumulative_received_mt, Decimal("24.925")) + self.assertEqual(sauda.balance_mt, Decimal("25.075")) + + # Truck 2 receives 25.000 MT (cumulative = 49.925 MT, within 0.5% tolerance of 50.0) + sauda.record_receipt(Decimal("25.000")) + self.assertEqual(sauda.status, "FULFILLED") + self.assertEqual(sauda.balance_mt, Decimal("0.075")) + + # Attempt further delivery on FULFILLED sauda -> rejected + with self.assertRaises(ValueError): + sauda.record_receipt(Decimal("10.000")) + + def test_unauthenticated_and_unauthorized_procurement(self): + """TC-PROC-004-05: 401 unauthenticated and 403 insufficient permissions.""" + res_unauth = self.controller.book_sauda(None, self.tenant_id, {}) + self.assertEqual(res_unauth.get("status_code"), 401) + + token_bad = mock_idp.mint_jwt( + subject="guard@alpha.com", + email="guard@alpha.com", + name="Guard", + roles=["Security Guard"], + tenant_id=self.tenant_id + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="guard@alpha.com", + email="guard@alpha.com", + role="Security Guard", + status="ACTIVE" + ) + ) + res_bad_role = self.controller.book_sauda(f"Bearer {token_bad}", self.tenant_id, {}) + self.assertEqual(res_bad_role.get("status_code"), 403) + + def test_list_and_get_saudas(self): + """TC-PROC-004-06: List saudas with filters and get sauda by ID.""" + today = date(2026, 10, 12) + payload = { + "contract_date": str(today), + "delivery_due_date": str(today + timedelta(days=6)), + "supplier_id": "a0000000-0000-0000-0000-000000000001", + "mandi_id": "mandi-01", + "commodity_id": "comm-01", + "variety": "Yellow", + "booked_quantity_mt": 30.0, + "trade_rate_per_qtl": 4500.0, + } + res_book = self.controller.book_sauda(self.auth_header, self.tenant_id, payload) + self.assertEqual(res_book.get("status_code"), 201) + sauda_id = res_book["sauda"]["id"] + + # List all + res_list = self.controller.list_saudas(self.auth_header, self.tenant_id) + self.assertGreaterEqual(res_list["count"], 1) + + # List with filter + res_filt = self.controller.list_saudas( + self.auth_header, self.tenant_id, supplier_id="a0000000-0000-0000-0000-000000000001", status_filter="ACTIVE" + ) + self.assertEqual(res_filt["count"], 1) + + # Mismatch filters + res_diff_supp = self.controller.list_saudas(self.auth_header, self.tenant_id, supplier_id="other-supplier") + self.assertEqual(res_diff_supp["count"], 0) + res_diff_status = self.controller.list_saudas(self.auth_header, self.tenant_id, status_filter="CLOSED") + self.assertEqual(res_diff_status["count"], 0) + + # Get existing + res_get = self.controller.get_sauda(self.auth_header, self.tenant_id, sauda_id) + self.assertEqual(res_get.get("status_code"), 200) + + # Get non-existing (404) + res_404 = self.controller.get_sauda(self.auth_header, self.tenant_id, "non-existent-id") + self.assertEqual(res_404.get("status_code"), 404) + + def test_master_data_mock_lookups(self): + """TC-PROC-004-07: MasterDataMock lookups for mandi, commodity, godown, and stack.""" + mandi = MasterDataMock.get_mandi("9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d") + self.assertIsNotNone(mandi) + self.assertIsNone(MasterDataMock.get_mandi("invalid-id")) + + comm = MasterDataMock.get_commodity("c0a80123-0000-0000-0000-000000000001") + self.assertIsNotNone(comm) + self.assertIsNone(MasterDataMock.get_commodity("invalid-id")) + + supp = MasterDataMock.get_supplier("a0000000-0000-0000-0000-000000000001") + self.assertIsNotNone(supp) + self.assertIsNone(MasterDataMock.get_supplier("invalid-id")) + + godown = MasterDataMock.get_godown("d0000000-0000-0000-0000-000000000001") + self.assertIsNotNone(godown) + self.assertIsNone(MasterDataMock.get_godown("invalid-id")) + + stack = MasterDataMock.get_stack("d0000000-0000-0000-0000-000000000001", "d1000000-0000-0000-0000-000000000001") + self.assertIsNotNone(stack) + self.assertIsNone(MasterDataMock.get_stack("invalid-id", "d1000000-0000-0000-0000-000000000001")) + self.assertIsNone(MasterDataMock.get_stack("d0000000-0000-0000-0000-000000000001", "invalid-stack")) + + +if __name__ == "__main__": + unittest.main() diff --git a/05_implementation_workspace/tests/backend/test_quality_lot_control.py b/05_implementation_workspace/tests/backend/test_quality_lot_control.py new file mode 100644 index 0000000..53908be --- /dev/null +++ b/05_implementation_workspace/tests/backend/test_quality_lot_control.py @@ -0,0 +1,286 @@ +"""Multi-Path Automated Unit & FSM Test Suite for Quality Lab & Lot Control (UC-006). + +Covers: +- TC-QC-006-01: Inward lab inspection, rebate calculation, and lot release. +- TC-QC-006-02: Assay parameter boundary limits (0-100%) and zero rebate FAQ baseline. +- TC-QC-006-03: Quality Hold dispatch guard & rejection reason validation. +- TC-QC-006-04: Finite state machine transitions & lot splitting lineage traversal. +""" +from datetime import datetime, timezone +from decimal import Decimal +import unittest + +from backend.app.api.quality import QualityController +from backend.app.db.session import InMemoryStorage +from backend.app.models.quality import InventoryLot, QualityInspection, calculate_quality_rebates +from backend.app.models.tenant import Tenant, TenantMembership +from sandbox.identity_mock import mock_idp + + +class TestQualityLotControl(unittest.TestCase): + + def setUp(self): + self.store = InMemoryStorage() + self.controller = QualityController(store=self.store) + self.tenant_id = "tenant-alpha" + + # Pre-seed active tenant and membership in store + self.store.save_tenant( + Tenant( + tenant_id=self.tenant_id, + business_name="Alpha Agro", + legal_identifier="24ABCDE1234F1Z5", + contact_email="alpha@agro.com", + primary_mandi="Kota APMC", + status="ACTIVE" + ) + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="chemist@alpha.com", + email="chemist@alpha.com", + role="Quality Officer", + status="ACTIVE" + ) + ) + + # Seed quality inspector token + self.token = mock_idp.mint_jwt( + subject="chemist@alpha.com", + email="chemist@alpha.com", + name="Lab Chemist", + roles=["Quality Officer"], + tenant_id=self.tenant_id + ) + self.auth_header = f"Bearer {self.token}" + + # Pre-seed Sauda and GRN + self.sauda_id = "sauda-qc-1" + self.store.insert("procurement_sauda", self.tenant_id, { + "id": self.sauda_id, + "tenant_id": self.tenant_id, + "sauda_number": "SDA-26-00055", + "trade_rate_per_qtl": 4500.0, + "commodity_id": "SOY" + }) + + self.grn_id = "grn-qc-1" + self.store.insert("goods_receipt_notes", self.tenant_id, { + "id": self.grn_id, + "tenant_id": self.tenant_id, + "grn_number": "GRN-26-00055", + "sauda_id": self.sauda_id, + "weighment_slip_id": "slip-qc-1" + }) + + # Pre-seed Lot in QUALITY_HOLD + self.lot_id = "lot-qc-1" + self.lot_data = { + "id": self.lot_id, + "tenant_id": self.tenant_id, + "lot_number": "LOT-26-10-SOY-00084", + "grn_id": self.grn_id, + "commodity_id": "SOY", + "variety": "Yellow Desi", + "grade": "FAQ", + "godown_stack_id": "stack-b-04", + "initial_quantity_mt": 24.925, + "current_quantity_mt": 24.925, + "qc_status": "QUALITY_HOLD", + "parent_lot_id": None + } + self.store.insert("inventory_lots", self.tenant_id, self.lot_data) + + def test_quality_assay_and_rebate_calculation_happy_path(self): + """TC-QC-006-01: Analytical assay records moisture/foreign matter rebates and updates FSM.""" + payload = { + "lot_id": self.lot_id, + "sample_code": "SMP-2026-9042", + "moisture_pct": 11.5, # FAQ max: 10.0% -> +1.50% excess + "foreign_matter_pct": 2.1, # FAQ max: 1.5% -> +0.60% excess + "damaged_grain_pct": 1.8, + "oil_content_pct": 18.4, + "decision": "RELEASED", + "remarks": "Produce accepted with commercial moisture and admixture rebate" + } + + res = self.controller.record_inspection(self.auth_header, self.tenant_id, payload) + self.assertEqual(res.get("status_code"), 201) + insp = res["inspection"] + + # Moisture deduction: 24.925 * 1.5% = 0.374 MT + self.assertEqual(insp["moisture_weight_deduction_mt"], 0.374) + self.assertEqual(insp["net_billable_weight_mt"], 24.551) # 24.925 - 0.374 + + # Rate deduction: 0.60% excess * 30.0 = ₹ 18.00 / Qtl + self.assertEqual(insp["rate_deduction_per_qtl"], 18.0) + self.assertGreater(insp["total_rebate_amount"], 0.0) + + # Lot transitioned to RELEASED + lot = self.store.get("inventory_lots", self.tenant_id, self.lot_id) + self.assertEqual(lot["qc_status"], "RELEASED") + + def test_assay_parameter_boundaries_and_zero_rebate(self): + """TC-QC-006-02: FAQ benchmark assay yields zero rebate; boundary 0-100% enforced.""" + # Baseline FAQ assay (moisture = 10.0, foreign = 1.5) -> zero rebate + calc_zero = calculate_quality_rebates( + lot_quantity_mt=Decimal("20.000"), + trade_rate_per_qtl=Decimal("4500.00"), + moisture_pct=Decimal("10.00"), + foreign_matter_pct=Decimal("1.50") + ) + self.assertEqual(calc_zero["weight_deduction_mt"], Decimal("0.000")) + self.assertEqual(calc_zero["rate_deduction_per_qtl"], Decimal("0.00")) + self.assertEqual(calc_zero["total_rebate_amount"], Decimal("0.00")) + + # Out-of-bounds percentage (< 0.0 or > 100.0) raises ValueError + with self.assertRaises(ValueError): + calculate_quality_rebates( + lot_quantity_mt=Decimal("20.000"), + trade_rate_per_qtl=Decimal("4500.00"), + moisture_pct=Decimal("-0.5"), + foreign_matter_pct=Decimal("1.0") + ) + + with self.assertRaises(ValueError): + calculate_quality_rebates( + lot_quantity_mt=Decimal("20.000"), + trade_rate_per_qtl=Decimal("4500.00"), + moisture_pct=Decimal("10.0"), + foreign_matter_pct=Decimal("101.0") + ) + + def test_quality_hold_dispatch_blocking_guard(self): + """TC-QC-006-03: Produce in QUALITY_HOLD or REJECTED cannot be dispatched.""" + lot = InventoryLot( + tenant_id=self.tenant_id, + lot_number="LOT-HOLD-01", + grn_id="grn-01", + commodity_id="SOY", + variety="Yellow", + godown_stack_id="stack-01", + initial_quantity_mt=Decimal("10.000") + ) + self.assertEqual(lot.qc_status, "QUALITY_HOLD") + + # Invariant check: Hold blocks dispatch + with self.assertRaises(ValueError): + lot.assert_can_dispatch() + + # Reject blocks dispatch + lot.transition_qc_status("REJECTED") + with self.assertRaises(ValueError): + lot.assert_can_dispatch() + + # Release permits dispatch + lot_rel = InventoryLot( + tenant_id=self.tenant_id, + lot_number="LOT-REL-01", + grn_id="grn-01", + commodity_id="SOY", + variety="Yellow", + godown_stack_id="stack-01", + initial_quantity_mt=Decimal("10.000") + ) + lot_rel.transition_qc_status("RELEASED") + lot_rel.assert_can_dispatch() # Should not raise + + def test_lot_split_and_lineage_preservation(self): + """TC-QC-006-04: Lot split into child sub-lots preserves ancestry and parent ID.""" + lot = InventoryLot( + tenant_id=self.tenant_id, + lot_number="LOT-PARENT-01", + grn_id=self.grn_id, + commodity_id="SOY", + variety="Yellow", + godown_stack_id="stack-01", + initial_quantity_mt=Decimal("25.000") + ) + lot.transition_qc_status("RELEASED") + + # Split into two child lots: 15 MT and 10 MT + children = lot.split_lot([Decimal("15.000"), Decimal("10.000")]) + self.assertEqual(len(children), 2) + self.assertEqual(children[0].lot_number, "LOT-PARENT-01-SPLIT-1") + self.assertEqual(children[0].initial_quantity_mt, Decimal("15.000")) + self.assertEqual(children[0].parent_lot_id, lot.id) + self.assertEqual(children[0].qc_status, "RELEASED") + self.assertEqual(lot.current_quantity_mt, Decimal("0.000")) + + # Verify lineage retrieval + res = self.controller.get_lot_lineage(self.auth_header, self.tenant_id, self.lot_id) + self.assertEqual(res.get("status_code"), 200) + lineage = res["lineage"] + self.assertIsNotNone(lineage.get("lot")) + self.assertIsNotNone(lineage.get("goods_receipt_note")) + self.assertIsNotNone(lineage.get("procurement_sauda")) + + def test_unauthenticated_and_unauthorized_quality(self): + """TC-QC-006-05: 401 unauthenticated and 403 unauthorized for quality actions.""" + res_unauth = self.controller.record_inspection(None, self.tenant_id, {}) + self.assertEqual(res_unauth.get("status_code"), 401) + + token_buyer = mock_idp.mint_jwt( + subject="buyer@alpha.com", + email="buyer@alpha.com", + name="Buyer", + roles=["Mandi Buyer"], + tenant_id=self.tenant_id + ) + self.store.save_membership( + TenantMembership( + tenant_id=self.tenant_id, + user_id="buyer@alpha.com", + email="buyer@alpha.com", + role="Mandi Buyer", + status="ACTIVE" + ) + ) + res_bad_role = self.controller.record_inspection(f"Bearer {token_buyer}", self.tenant_id, {}) + self.assertEqual(res_bad_role.get("status_code"), 403) + + res_bad_dec = self.controller.execute_lot_decision(f"Bearer {token_buyer}", self.tenant_id, self.lot_id, {}) + self.assertEqual(res_bad_dec.get("status_code"), 403) + + def test_execute_lot_decision_rejection_and_transitions(self): + """TC-QC-006-06: Lot decision transitions, rejection reasons, and invalid state errors.""" + # 404 not found + res_404 = self.controller.execute_lot_decision(self.auth_header, self.tenant_id, "non-existent", {}) + self.assertEqual(res_404.get("status_code"), 404) + + # REJECTED without reason -> 422 + res_no_reason = self.controller.execute_lot_decision( + self.auth_header, self.tenant_id, self.lot_id, {"decision": "REJECTED"} + ) + self.assertEqual(res_no_reason.get("status_code"), 422) + + # REJECTED with reason -> 200 + res_rej = self.controller.execute_lot_decision( + self.auth_header, self.tenant_id, self.lot_id, { + "decision": "REJECTED", + "rejection_reason": "High fungus damage (> 5.0%)" + } + ) + self.assertEqual(res_rej.get("status_code"), 200) + self.assertEqual(res_rej["lot"]["qc_status"], "REJECTED") + + # Invalid transition from REJECTED -> 400 + res_invalid = self.controller.execute_lot_decision( + self.auth_header, self.tenant_id, self.lot_id, {"decision": "RELEASED"} + ) + self.assertEqual(res_invalid.get("status_code"), 400) + + def test_inspection_and_lineage_not_found(self): + """TC-QC-006-07: 404 on missing lot for inspection or lineage query.""" + res_insp_404 = self.controller.record_inspection( + self.auth_header, self.tenant_id, {"lot_id": "non-existent"} + ) + self.assertEqual(res_insp_404.get("status_code"), 404) + + res_lin_404 = self.controller.get_lot_lineage(self.auth_header, self.tenant_id, "non-existent") + self.assertEqual(res_lin_404.get("status_code"), 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/05_implementation_workspace/tests/e2e/test_live_api_endpoints.py b/05_implementation_workspace/tests/e2e/test_live_api_endpoints.py index 3e2c065..866356f 100644 --- a/05_implementation_workspace/tests/e2e/test_live_api_endpoints.py +++ b/05_implementation_workspace/tests/e2e/test_live_api_endpoints.py @@ -16,6 +16,7 @@ import json import unittest import urllib.request import urllib.error +import uuid from typing import Any, Dict, Optional, Tuple from sandbox.identity_mock import mock_idp @@ -93,6 +94,7 @@ class TestLiveApiEndpoints(unittest.TestCase): roles=["Tenant Administrator"], tenant_id="tenant-beta" ) + cls.delta_tenant_id = f"tenant-delta-{uuid.uuid4().hex[:6]}" def test_01_health_endpoint(self): """Verifies GET /health responds 200 with service metadata.""" @@ -143,11 +145,11 @@ class TestLiveApiEndpoints(unittest.TestCase): def test_04_bruno_create_tenant(self): """Verifies docs/api/bruno/tenant/create-tenant.bru (FR-TENANTLIFECYCLE-001).""" payload = { - "tenant_id": "tenant-delta-live", + "tenant_id": self.delta_tenant_id, "name": "Delta Live Agri Commodities Ltd", "gstin": "24AAAAA0000A1Z5", "primary_mandi": "Unjha Mandi, Gujarat", - "admin_email": "admin@delta-live.com", + "admin_email": f"admin_{self.delta_tenant_id}@delta-live.com", "admin_name": "Deepak Patel" } @@ -169,14 +171,14 @@ class TestLiveApiEndpoints(unittest.TestCase): ) self.assertIn(code, (200, 201)) tenant = body.get("tenant", {}) - self.assertEqual(tenant.get("tenant_id"), "tenant-delta-live") + self.assertEqual(tenant.get("tenant_id"), self.delta_tenant_id) self.assertEqual(tenant.get("status"), "ACTIVE") def test_05_bruno_patch_tenant_status(self): """Verifies docs/api/bruno/tenant/patch-tenant-status.bru (FR-TENANTLIFECYCLE-001).""" # 1. Transition ACTIVE -> SUSPENDED code, body = make_request( - "/api/v1/platform/tenants/tenant-delta-live/status", + f"/api/v1/platform/tenants/{self.delta_tenant_id}/status", method="PATCH", token=self.sysadmin_token, body={"status": "SUSPENDED", "reason": "KYC review pending"} @@ -186,7 +188,7 @@ class TestLiveApiEndpoints(unittest.TestCase): # 2. Transition SUSPENDED -> ACTIVE code, body = make_request( - "/api/v1/platform/tenants/tenant-delta-live/status", + f"/api/v1/platform/tenants/{self.delta_tenant_id}/status", method="PATCH", token=self.sysadmin_token, body={"status": "ACTIVE", "reason": "KYC review cleared"} @@ -196,7 +198,7 @@ class TestLiveApiEndpoints(unittest.TestCase): # 3. Transition ACTIVE -> CLOSED (Terminal state) code, body = make_request( - "/api/v1/platform/tenants/tenant-delta-live/status", + f"/api/v1/platform/tenants/{self.delta_tenant_id}/status", method="PATCH", token=self.sysadmin_token, body={"status": "CLOSED", "reason": "Firm operations ceased"} @@ -206,7 +208,7 @@ class TestLiveApiEndpoints(unittest.TestCase): # 4. FSM Invariant: Transitioning out of CLOSED is rejected with 400 Bad Request code, body = make_request( - "/api/v1/platform/tenants/tenant-delta-live/status", + f"/api/v1/platform/tenants/{self.delta_tenant_id}/status", method="PATCH", token=self.sysadmin_token, body={"status": "ACTIVE", "reason": "Attempted reactivation"} diff --git a/05_implementation_workspace/tests/e2e/test_live_mandi_pipeline_e2e.py b/05_implementation_workspace/tests/e2e/test_live_mandi_pipeline_e2e.py new file mode 100644 index 0000000..a27cc2e --- /dev/null +++ b/05_implementation_workspace/tests/e2e/test_live_mandi_pipeline_e2e.py @@ -0,0 +1,261 @@ +"""Live Container End-to-End API Verification for Iteration 03 (Mandi Pipeline). + +Fulfills: +- UC-002: Mandi Market Desk (FR-MKT-001, FR-MKT-002) +- UC-004: Procurement Contracts & Sauda Booking (FR-PROCUREMENTCONTRACTS-001..004) +- UC-005: Inward Receiving, Weighbridge & GRN (FR-INWARDRECEIVING-001..006) +- UC-006: Quality Lab Assays, Rebates & Lot FSM (FR-QUALITYANDLOTCONTROL-001..004) + +Executes real HTTP requests against the running FastAPI container (port 8000), +verifying the complete physical grain procurement and inventory minting lifecycle. +""" +from datetime import datetime, date, timedelta, timezone +import json +import unittest +import urllib.request +import urllib.error +import uuid +from typing import Any, Dict, Optional, Tuple + +from sandbox.identity_mock import mock_idp + + +BASE_URL = "http://127.0.0.1:8000" + + +def make_request( + path: str, + method: str = "GET", + token: Optional[str] = None, + tenant_id: Optional[str] = None, + body: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None +) -> Tuple[int, Dict[str, Any]]: + """Helper to issue HTTP requests using pure-Python urllib.""" + url = f"{BASE_URL}{path}" + req_headers = {"Accept": "application/json"} + if headers: + req_headers.update(headers) + if token: + req_headers["Authorization"] = f"Bearer {token}" + if tenant_id: + req_headers["X-Tenant-ID"] = tenant_id + + data_bytes = None + if body is not None: + data_bytes = json.dumps(body).encode("utf-8") + req_headers["Content-Type"] = "application/json" + + req = urllib.request.Request(url, data=data_bytes, headers=req_headers, method=method) + try: + with urllib.request.urlopen(req, timeout=5) as resp: + status = resp.status + content = resp.read().decode("utf-8") + return status, json.loads(content) if content else {} + except urllib.error.HTTPError as exc: + err_content = exc.read().decode("utf-8") + try: + parsed = json.loads(err_content) + except Exception: + parsed = {"error": err_content} + return exc.code, parsed + + +class TestLiveMandiPipelineE2E(unittest.TestCase): + """End-to-end integration test exercising Iteration 03 Mandi Trading & Procurement Pipeline.""" + + @classmethod + def setUpClass(cls): + uid = uuid.uuid4().hex[:8] + cls.tenant_id = f"tenant-mandi-{uid}" + cls.admin_email = f"admin_{uid}@kisanmandi.com" + + cls.sysadmin_token = mock_idp.mint_jwt( + subject="sysadmin_e2e@agri.gov.in", + email="sysadmin_e2e@agri.gov.in", + name="System Admin E2E", + roles=["System Administrator"], + tenant_id="platform" + ) + + # 1. Provision active tenant via platform endpoint + tenant_payload = { + "tenant_id": cls.tenant_id, + "name": f"Kisan Mandi Traders {uid} Ltd", + "gstin": f"24AABC{uid[:4].upper()}1Z9", + "primary_mandi": "Kota APMC Yard", + "admin_email": cls.admin_email, + "admin_name": "Kisan Admin" + } + status, body = make_request("/api/v1/platform/tenants", method="POST", token=cls.sysadmin_token, body=tenant_payload) + assert status in (200, 201), f"Tenant creation failed: {status} {body}" + + # 2. Mint tokens for actors + cls.buyer_token = mock_idp.mint_jwt( + subject=cls.admin_email, + email=cls.admin_email, + name="Tenant Admin", + roles=["Tenant Administrator"], + tenant_id=cls.tenant_id + ) + + def test_full_mandi_procurement_pipeline_lifecycle(self): + """Executes the complete chronological pipeline from market bulletin to lot release.""" + today = datetime.now(timezone.utc).date() + + # Step 1: Record Market Desk Observation (FR-MKT-001, FR-MKT-002) + obs_payload = { + "mandi_id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", + "observation_date": str(today), + "commodity_id": "c0a80123-0000-0000-0000-000000000001", + "variety": "Yellow Desi", + "grade": "FAQ", + "arrival_mt": 350.0, + "internal_stock_mt": 100.0, + "min_rate": 4500.0, + "max_rate": 4800.0, + "modal_rate": 4650.0, + "source": "APMC_BULLETIN" + } + status, obs_resp = make_request( + "/api/v1/market/observations", method="POST", token=self.buyer_token, + tenant_id=self.tenant_id, body=obs_payload + ) + self.assertEqual(status, 201, f"Failed market observation: {obs_resp}") + self.assertTrue(obs_resp.get("success")) + + # Query latest rates + status, rate_resp = make_request( + "/api/v1/market/rates/latest?commodity_id=c0a80123-0000-0000-0000-000000000001", + method="GET", token=self.buyer_token, tenant_id=self.tenant_id + ) + self.assertEqual(status, 200) + self.assertEqual(rate_resp.get("benchmark_modal_rate"), 4650.0) + + # Step 2: Book Purchase Sauda Contract (FR-PROCUREMENTCONTRACTS-001..004) + sauda_payload = { + "contract_date": str(today), + "delivery_due_date": str(today + timedelta(days=7)), + "supplier_id": "a0000000-0000-0000-0000-000000000001", + "mandi_id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", + "trade_type": "MANDI_AUCTION", + "commodity_id": "c0a80123-0000-0000-0000-000000000001", + "variety": "Yellow Desi", + "grade": "FAQ", + "booked_quantity_mt": 50.0, + "estimated_bags": 1000, + "trade_rate_per_qtl": 4700.0, + "benchmark_modal_rate": 4650.0, + "credit_period_days": 15, + "advance_amount": 50000.0, + "mandi_cess_pct": 1.5, + "krishi_kalyan_pct": 0.5, + "brokerage_rate_pct": 1.0 + } + status, sauda_resp = make_request( + "/api/v1/procurement/sauda", method="POST", token=self.buyer_token, + tenant_id=self.tenant_id, body=sauda_payload + ) + self.assertEqual(status, 201, f"Failed sauda booking: {sauda_resp}") + sauda_data = sauda_resp["sauda"] + sauda_id = sauda_data["id"] + self.assertEqual(sauda_data["status"], "ACTIVE") + self.assertEqual(sauda_data["total_landed_amount"], 2420500.0) + + # Step 3: Vehicle Gate Pass (FR-INWARDRECEIVING-001) + gate_payload = { + "vehicle_number": "RJ-20-GA-4581", + "eway_bill_number": "241089201923", + "driver_name": "Ramesh Singh", + "driver_mobile": "9829012345", + "sauda_id": sauda_id, + "supplier_invoice_no": "INV-2026-9042", + "supplier_dispatch_weight_mt": 25.0, + "supplier_dispatch_bags": 500, + "is_seal_intact": True + } + status, gate_resp = make_request( + "/api/v1/receiving/gate-entries", method="POST", token=self.buyer_token, + tenant_id=self.tenant_id, body=gate_payload + ) + self.assertEqual(status, 201, f"Failed gate entry: {gate_resp}") + gate_entry = gate_resp["gate_entry"] + gate_pass_id = gate_entry["id"] + + # Step 4: Gross Weighbridge Scale (FR-INWARDRECEIVING-002) + gross_payload = { + "gate_pass_id": gate_pass_id, + "gross_weight_mt": 38.450 + } + status, gross_resp = make_request( + "/api/v1/receiving/weighments", method="POST", token=self.buyer_token, + tenant_id=self.tenant_id, body=gross_payload + ) + self.assertEqual(status, 201, f"Failed gross weighment: {gross_resp}") + slip = gross_resp["weighment_slip"] + slip_id = slip["id"] + + # Step 5: Tare Scale & Bag Tare (Bardana Katai) (FR-INWARDRECEIVING-002..004) + tare_payload = { + "tare_weight_mt": 13.200, + "bag_packaging_type": "JUTE_GUNNY_NEW", + "actual_bag_count": 500 + } + status, tare_resp = make_request( + f"/api/v1/receiving/weighments/{slip_id}/tare", method="POST", token=self.buyer_token, + tenant_id=self.tenant_id, body=tare_payload + ) + self.assertEqual(status, 200, f"Failed tare weighment: {tare_resp}") + updated_slip = tare_resp["weighment_slip"] + self.assertEqual(updated_slip["final_net_weight_mt"], 24.925) + + # Step 6: Post GRN and Mint Lot in QUALITY_HOLD (FR-INWARDRECEIVING-005, 006) + grn_payload = { + "weighment_slip_id": slip_id, + "godown_id": "d0000000-0000-0000-0000-000000000001", + "godown_stack_id": "d1000000-0000-0000-0000-000000000001" + } + status, grn_resp = make_request( + "/api/v1/receiving/grn", method="POST", token=self.buyer_token, + tenant_id=self.tenant_id, body=grn_payload + ) + self.assertEqual(status, 201, f"Failed post GRN: {grn_resp}") + lot = grn_resp["lot"] + lot_id = lot["id"] + self.assertEqual(lot["qc_status"], "QUALITY_HOLD") + + # Step 7: Quality Lab Inspection & Commercial Rebates (FR-QUALITYANDLOTCONTROL-001, 003) + insp_payload = { + "lot_id": lot_id, + "sample_code": "SMP-2026-9042", + "moisture_pct": 11.5, + "foreign_matter_pct": 2.1, + "damaged_grain_pct": 1.8, + "oil_content_pct": 18.4, + "decision": "RELEASED", + "remarks": "Produce accepted with commercial moisture and admixture rebate" + } + status, insp_resp = make_request( + "/api/v1/quality/inspections", method="POST", token=self.buyer_token, + tenant_id=self.tenant_id, body=insp_payload + ) + self.assertEqual(status, 201, f"Failed quality inspection: {insp_resp}") + self.assertEqual(insp_resp["lot_qc_status"], "RELEASED") + self.assertEqual(insp_resp["inspection"]["moisture_weight_deduction_mt"], 0.374) + + # Step 8: Verify Complete Lot Lineage (FR-QUALITYANDLOTCONTROL-004) + status, lin_resp = make_request( + f"/api/v1/quality/lots/{lot_id}/lineage", method="GET", token=self.buyer_token, + tenant_id=self.tenant_id + ) + self.assertEqual(status, 200, f"Failed lineage traversal: {lin_resp}") + lineage = lin_resp["lineage"] + self.assertIsNotNone(lineage["lot"]) + self.assertIsNotNone(lineage["goods_receipt_note"]) + self.assertIsNotNone(lineage["weighbridge_slip"]) + self.assertIsNotNone(lineage["gate_entry"]) + self.assertIsNotNone(lineage["procurement_sauda"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/05_implementation_workspace/tests/run_all_tests.py b/05_implementation_workspace/tests/run_all_tests.py index 3c07912..bf216d2 100644 --- a/05_implementation_workspace/tests/run_all_tests.py +++ b/05_implementation_workspace/tests/run_all_tests.py @@ -69,12 +69,23 @@ def run_tests_with_coverage(): workspace / "backend" / "app" / "db" / "session.py", workspace / "backend" / "app" / "auth" / "tenant_context.py", workspace / "backend" / "app" / "api" / "tenants.py", + # Iteration 03 Modules + workspace / "backend" / "app" / "models" / "market.py", + workspace / "backend" / "app" / "api" / "market.py", + workspace / "backend" / "app" / "models" / "procurement.py", + workspace / "backend" / "app" / "api" / "procurement.py", + workspace / "backend" / "app" / "models" / "receiving.py", + workspace / "backend" / "app" / "api" / "receiving.py", + workspace / "backend" / "app" / "models" / "quality.py", + workspace / "backend" / "app" / "api" / "quality.py", # Sandboxes - workspace / "sandbox" / "identity_mock.py" + workspace / "sandbox" / "identity_mock.py", + workspace / "sandbox" / "master_data_mock.py", + workspace / "sandbox" / "weighbridge_mock.py" ] print("\n" + "=" * 68) - print("STATEMENT COVERAGE REPORT — ITERATION 01 & 02 (UP-AI v1.5)") + print("STATEMENT COVERAGE REPORT — ITERATION 01, 02 & 03 (UP-AI v1.5)") print("=" * 68) results = tracer.results() diff --git a/docs/api/bruno/market/get-market-observations.bru b/docs/api/bruno/market/get-market-observations.bru new file mode 100644 index 0000000..b68186c --- /dev/null +++ b/docs/api/bruno/market/get-market-observations.bru @@ -0,0 +1,27 @@ +meta { + name: List Market Observations + type: http + seq: 2 +} + +get { + url: {{baseUrl}}/api/v1/market/observations?mandi_id=9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d&date=2026-10-12 + body: none + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +docs { + # List Market Observations (FR-MKT-001) + + Fetches daily APMC observations and modal price bulletins scoped to the tenant. +} + diff --git a/docs/api/bruno/market/post-market-observation.bru b/docs/api/bruno/market/post-market-observation.bru new file mode 100644 index 0000000..2b849ac --- /dev/null +++ b/docs/api/bruno/market/post-market-observation.bru @@ -0,0 +1,45 @@ +meta { + name: Post Daily Market Observation + type: http + seq: 1 +} + +post { + url: {{baseUrl}}/api/v1/market/observations + body: json + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + Content-Type: application/json + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +body:json { + { + "mandi_id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", + "observation_date": "2026-10-12", + "commodity_id": "c0a80123-0000-0000-0000-000000000001", + "variety": "Yellow Desi", + "grade": "FAQ", + "arrival_mt": 450.0, + "min_rate": 4450.0, + "max_rate": 4780.0, + "modal_rate": 4620.0, + "source": "APMC_BULLETIN", + "is_market_closed": false + } +} + +docs { + # Post Daily Market Observation (FR-MKT-001, FR-MKT-002) + + Records daily arrivals and modal clearing prices for a monitored APMC yard. + Validates min_rate <= modal_rate <= max_rate and non-future date. +} + diff --git a/docs/api/bruno/procurement/create-sauda.bru b/docs/api/bruno/procurement/create-sauda.bru new file mode 100644 index 0000000..85e1707 --- /dev/null +++ b/docs/api/bruno/procurement/create-sauda.bru @@ -0,0 +1,51 @@ +meta { + name: Book Purchase Sauda Contract + type: http + seq: 1 +} + +post { + url: {{baseUrl}}/api/v1/procurement/sauda + body: json + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + Content-Type: application/json + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +body:json { + { + "contract_date": "2026-10-12", + "delivery_due_date": "2026-10-18", + "supplier_id": "a0000000-0000-0000-0000-000000000001", + "mandi_id": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", + "trade_type": "MANDI_AUCTION", + "commodity_id": "c0a80123-0000-0000-0000-000000000001", + "variety": "Yellow Desi", + "grade": "FAQ", + "booked_quantity_mt": 50.0, + "estimated_bags": 1000, + "trade_rate_per_qtl": 4700.0, + "credit_period_days": 15, + "advance_amount": 50000.0, + "mandi_cess_pct": 1.5, + "krishi_kalyan_pct": 0.5, + "brokerage_rate_pct": 1.0, + "variance_acknowledged": false + } +} + +docs { + # Book Purchase Sauda Contract (FR-PROCUREMENTCONTRACTS-001..004) + + Books purchase contracts negotiated in mandi auctions or directly with suppliers. + Validates price variance against benchmark modal rate and computes statutory APMC levies. +} + diff --git a/docs/api/bruno/procurement/list-sauda.bru b/docs/api/bruno/procurement/list-sauda.bru new file mode 100644 index 0000000..bdc5b31 --- /dev/null +++ b/docs/api/bruno/procurement/list-sauda.bru @@ -0,0 +1,27 @@ +meta { + name: List Purchase Sauda Contracts + type: http + seq: 2 +} + +get { + url: {{baseUrl}}/api/v1/procurement/sauda + body: none + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +docs { + # List Purchase Sauda Contracts (FR-PROCUREMENTCONTRACTS-002) + + Fetches purchase sauda register scoped to active tenant. +} + diff --git a/docs/api/bruno/quality/get-lot-lineage.bru b/docs/api/bruno/quality/get-lot-lineage.bru new file mode 100644 index 0000000..525c876 --- /dev/null +++ b/docs/api/bruno/quality/get-lot-lineage.bru @@ -0,0 +1,27 @@ +meta { + name: Get Traceable Lot Lineage + type: http + seq: 3 +} + +get { + url: {{baseUrl}}/api/v1/quality/lots/c1000000-0000-0000-0000-000000000001/lineage + body: none + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +docs { + # Get Traceable Lot Lineage (FR-QUALITYANDLOTCONTROL-004) + + Traverses the complete genealogical ancestry tree of the lot back to its GRN, weighbridge slip, and contract. +} + diff --git a/docs/api/bruno/quality/post-inspection.bru b/docs/api/bruno/quality/post-inspection.bru new file mode 100644 index 0000000..95b473c --- /dev/null +++ b/docs/api/bruno/quality/post-inspection.bru @@ -0,0 +1,40 @@ +meta { + name: Record Quality Lab Assay + type: http + seq: 1 +} + +post { + url: {{baseUrl}}/api/v1/quality/inspections + body: json + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + Content-Type: application/json + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +body:json { + { + "lot_id": "c1000000-0000-0000-0000-000000000001", + "sample_code": "SMP-2026-9042", + "moisture_pct": 11.5, + "foreign_matter_pct": 2.1, + "damaged_grain_pct": 1.8, + "oil_content_pct": 18.4, + "remarks": "Produce within acceptable commercial moisture tolerance" + } +} + +docs { + # Record Quality Lab Assay (FR-QUALITYANDLOTCONTROL-001, FR-QUALITYANDLOTCONTROL-002) + + Captures laboratory analytical parameters and calculates commercial quality deductions/rebates. +} + diff --git a/docs/api/bruno/quality/post-lot-decision.bru b/docs/api/bruno/quality/post-lot-decision.bru new file mode 100644 index 0000000..5b3dfe9 --- /dev/null +++ b/docs/api/bruno/quality/post-lot-decision.bru @@ -0,0 +1,35 @@ +meta { + name: Execute Lot FSM Quality Decision + type: http + seq: 2 +} + +post { + url: {{baseUrl}}/api/v1/quality/lots/c1000000-0000-0000-0000-000000000001/decision + body: json + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + Content-Type: application/json + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +body:json { + { + "decision": "RELEASED", + "remarks": "Assay approved. Produce released for trading." + } +} + +docs { + # Execute Lot FSM Quality Decision (FR-QUALITYANDLOTCONTROL-003) + + Executes finite state machine transitions from QUALITY_HOLD to RELEASED or REJECTED. +} + diff --git a/docs/api/bruno/receiving/create-gate-entry.bru b/docs/api/bruno/receiving/create-gate-entry.bru new file mode 100644 index 0000000..f431a82 --- /dev/null +++ b/docs/api/bruno/receiving/create-gate-entry.bru @@ -0,0 +1,42 @@ +meta { + name: Create Inward Vehicle Gate Entry + type: http + seq: 1 +} + +post { + url: {{baseUrl}}/api/v1/receiving/gate-entries + body: json + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + Content-Type: application/json + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +body:json { + { + "vehicle_number": "RJ-20-GA-4581", + "eway_bill_number": "241089201923", + "driver_name": "Ramesh Singh", + "driver_mobile": "9829012345", + "sauda_id": "b0000000-0000-0000-0000-000000000001", + "supplier_invoice_no": "INV-2026-9042", + "supplier_dispatch_weight_mt": 25.0, + "supplier_dispatch_bags": 500, + "is_seal_intact": true + } +} + +docs { + # Create Inward Vehicle Gate Entry (FR-INWARDRECEIVING-001) + + Captures arriving vehicle details, driver mobile, e-Way bill and invoice details. +} + diff --git a/docs/api/bruno/receiving/create-weighment.bru b/docs/api/bruno/receiving/create-weighment.bru new file mode 100644 index 0000000..e4836d2 --- /dev/null +++ b/docs/api/bruno/receiving/create-weighment.bru @@ -0,0 +1,39 @@ +meta { + name: Record Weighbridge Slip & Bag Tare + type: http + seq: 2 +} + +post { + url: {{baseUrl}}/api/v1/receiving/weighments + body: json + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + Content-Type: application/json + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +body:json { + { + "gate_pass_id": "e0000000-0000-0000-0000-000000000001", + "gross_weight_mt": 38.45, + "tare_weight_mt": 13.2, + "bag_packaging_type": "JUTE_GUNNY_NEW", + "bag_tare_rate_kg": 0.65, + "actual_bag_count": 500 + } +} + +docs { + # Record Weighbridge Slip & Bag Tare (FR-INWARDRECEIVING-002, FR-INWARDRECEIVING-003) + + Captures gross weight, empty truck tare weight, and calculates packaging tare (Bardana Katai). +} + diff --git a/docs/api/bruno/receiving/post-grn.bru b/docs/api/bruno/receiving/post-grn.bru new file mode 100644 index 0000000..653e5bd --- /dev/null +++ b/docs/api/bruno/receiving/post-grn.bru @@ -0,0 +1,36 @@ +meta { + name: Post Goods Receipt Note and Mint Lot + type: http + seq: 3 +} + +post { + url: {{baseUrl}}/api/v1/receiving/grn + body: json + auth: bearer +} + +auth:bearer { + token: {{jwtToken}} +} + +headers { + Content-Type: application/json + X-Tenant-ID: {{tenantId}} + Accept: application/json +} + +body:json { + { + "weighment_slip_id": "f0000000-0000-0000-0000-000000000001", + "godown_id": "d0000000-0000-0000-0000-000000000001", + "godown_stack_id": "d1000000-0000-0000-0000-000000000001" + } +} + +docs { + # Post Goods Receipt Note and Mint Lot (FR-INWARDRECEIVING-005, FR-INWARDRECEIVING-006) + + Atomically generates GRN, assigns physical godown stack, and mints traceable lot identity in QUALITY_HOLD. +} + diff --git a/prompts/20261012T041907Z-session-process-status.md b/prompts/20261012T041907Z-session-process-status.md index 4b1c0a9..9c9d5a8 100644 --- a/prompts/20261012T041907Z-session-process-status.md +++ b/prompts/20261012T041907Z-session-process-status.md @@ -152,3 +152,36 @@ Executed live container infrastructure, PostgreSQL 17 database migration, real R - Executed `scripts/verify_traceability_gates.py --all --run-tests`: Gate 5.1 (PASS), Gate 9.1 (PASS), Gate 14.1 (PASS for both iteration-01 and iteration-02). - Authored Checkpoint 021 (`checkpoint-021-live-container-verification-iteration-01-02.md`). - Updated `checkpoint_index.md` and `master_context.md`. + +## 2026-10-12T07:20:00Z — User + +proceed + +## 2026-10-12T08:05:00Z — Assistant — Action summary + +Executed Stage 13 code generation, refactoring, automated testing, containerized migrations, live E2E lifecycle verification, and Stage 14 Gate 14.1 sign-off for Iteration 03 (Inward Mandi Trading & Procurement Pipeline): +1. Implementation & Controller Refactoring: + - Standardized authentication in `backend/app/api/procurement.py`, `receiving.py`, `quality.py`, and `market_desk.py` via `TenantContextResolver.resolve_context` with aggregated roles across active memberships. + - Enhanced `record_audit_event` in `backend/app/auth/tenant_context.py` to support `store` defaults and keyword aliases (`actor_user_id`, `resource_type`, `resource_id`, `action_type`, `after_state`). + - Normalized vehicle registration checking in inward receiving (`receiving.py`). +2. Automated Multi-Path Test Suites & Coverage: + - Updated `setUp()` fixtures across `test_market_desk.py`, `test_procurement_contracts.py`, `test_inward_receiving.py`, and `test_quality_lot_control.py` to seed active `Tenant` and `TenantMembership` records. + - Expanded test cases covering all 4 dimensions (Happy Path, Boundary, Negative, FSM Invariants), including 401 unauthenticated, 403 unauthorized, 404 missing resources, 422 validations, rate filters, missing sauda / closed sauda, duplicate GRN (409), and `MasterDataMock` lookups. + - Executed `python3 05_implementation_workspace/tests/run_all_tests.py`: **92 tests passing cleanly in 0.063s** with **95.4% Total Domain & Controller Statement Coverage** (threshold >= 95.0%). +3. Live Container Migrations: + - Applied Alembic revisions 005–008 to live PostgreSQL 17 container (`atb-local-postgres-1`): + - `005_market_desk.py`: `market_observations` with RLS policy. + - `006_procurement_contracts.py`: `procurement_sauda` with RLS policy. + - `007_inward_receiving.py`: `inward_gate_entries`, `weighbridge_slips`, `goods_receipt_notes` with RLS policies. + - `008_quality_and_lots.py`: `inventory_lots`, `quality_inspections` with RLS policies. + - Verified Alembic head at revision 008. +4. Live Container E2E Integration Suite: + - Authored and verified `05_implementation_workspace/tests/e2e/test_live_mandi_pipeline_e2e.py` covering the complete chronological mandi pipeline lifecycle: market observation recording, mandi rate lookups, sauda booking with statutory levies, gate entry pass generation, weighbridge gross weighing, weighbridge tare weighing with bag tare deduction (*bardana katai*), GRN posting with lot minting in `QUALITY_HOLD`, lab inspection assay with rebate deduction & release, and lot genealogy traversal. + - Executed all 13 live E2E tests (`test_live_api_endpoints.py`, `test_postgresql_live_rls.py`, `test_live_mandi_pipeline_e2e.py`) via container network: **13/13 tests PASS**. +5. Traceability Graph & Lifecycle Advancement: + - Advanced `UC-002`, `UC-004`, `UC-005`, `UC-006` and all 16 child FRs (`FR-MKT-001`–`002`, `FR-PROCUREMENTCONTRACTS-001`–`004`, `FR-INWARDRECEIVING-001`–`006`, `FR-QUALITYANDLOTCONTROL-001`–`004`) to **`Delivered (E2E Verified)`**. + - Updated `04_generated_documentation/05_iteration_planning/iterations/iteration-03/iteration_surface_matrix.md`: all 16 story surfaces marked `Delivered (E2E Verified)`. +6. Quality Gates & Checkpoints: + - Executed `scripts/verify_traceability_gates.py --all --run-tests`: Gate 5.1 (PASS), Gate 9.1 (PASS), Gate 14.1 (PASS for iteration-01, iteration-02, and iteration-03). + - Authored Checkpoint `CKPT-022` (`04_generated_documentation/00_process_control/checkpoints/checkpoint-022-iteration-03-mandi-pipeline-delivery.md`). + - Updated `checkpoint_index.md` and `master_context.md`.