# Pavitram Agroz ERP – Project Changelog

All notable changes and milestones across the four development phases of the centralized multi-store manufacturing and billing management system are documented herein.

---

## [Phase 4] - Point of Sale (POS) Billing, Invoices, Returns & Reporting Analytics
### Added
- **High-Speed Cashier POS Terminal**:
  - Auto-focus scanner input station supporting USB 2D hardware barcode scanners (keyboard-wedge input with enter key interception).
  - Integrated HTML5 camera barcode/QR scanner (`Html5QrcodeScanner`) with automatic video stream teardown.
  - Quick fallback product search modal for manual lookup.
  - Real-time cart calculation engine with subtotal, configurable line-item discounts, GST tax breakup (CGST, SGST, IGST), and final totals.
- **Strict Concurrency & Anti-Double-Sale Defense**:
  - Implemented `lockForUpdate()` database row locks and atomic DB transactions in `PosCheckoutService`.
  - Re-validates every individual physical unit immediately prior to invoice commit: ensures unit exists, is verified, belongs to active store, has status `In Store`, is not damaged, quarantined, in transit, or sold.
- **Invoicing System**:
  - Sequential format generator: `PA-INV-{STORE_CODE}-{YYYYMMDD}-{XXXXX}`.
  - Complete line item recording with unit serial numbers, unit price, discounts, and GST tax percentages.
  - Multi-tender payment recording: Cash, UPI, Card, Net Banking with transaction references.
  - Dual print views: 80mm/58mm ESC/POS thermal receipt view (`/pos/invoices/{id}/thermal`) and A4 Tax Invoice (`/pos/invoices/{id}/print`).
  - Invoice cancellation workflow requiring mandatory explanation; automatically reverses physical units back to store inventory and logs reversing movement in `stock_movements`.
- **Customer Sales Returns & Refunds**:
  - Invoice lookup by invoice number or unit serial number.
  - Unit-level quality inspection with four actionable resolutions:
    - `Restock`: returns unit lifecycle state to `In Store` with reversing stock movement.
    - `Damaged / Quarantine`: transitions unit to `Damaged` / `Quarantine`, ensuring it can never be sold.
    - `Dispose`: transitions unit to `Disposed`.
    - `Rejected`: rejects return and leaves invoice untouched.
  - Two-stage authorization: Cashier initiates return request; Store Admin or Super Admin approves refund settlement.
- **Enterprise Reporting & Analytics Suite**:
  - Comprehensive business analytics: sales velocity, store-to-store revenue comparison (Super Admin only), product sales turnover, batch turnover, cashier revenue performance, payment method distribution, customer return metrics, and damaged inventory tracking.
  - Automated 90-day expiry risk alerting.
  - Streaming CSV export endpoint for all analytical views.
  - Strict Anti-IDOR security: Cashiers are blocked with HTTP 403 Forbidden; Store Admins are restricted to their assigned store data.
- **Master Documentation**:
  - Created `PROJECT_DOCUMENTATION.md`, `CHANGELOG.md`, and `TEST_REPORT.md`.

---

## [Phase 3] - Central Warehouse, Multi-Store Inventory & Stock Transfers
### Added
- **Central Warehouse Management**:
  - Multi-warehouse directory (`PA-WH-001`, `PA-WH-002`) with contact info, geolocation data, and capacity status.
  - Location-scoped inventory cockpit with product-wise, batch-wise, and unit-level visibility.
- **Pre-Storage Warehouse Inbound Intake**:
  - Rapid scanner intake terminal (`/warehouse-receiving`).
  - Re-validates that physical units have `verification_status == 'verified'` before transitioning to `In Warehouse`.
- **Inter-Store & Warehouse Stock Transfers**:
  - Full dispatch and transit lifecycle: `Draft` -> `Pending Dispatch` -> `Dispatched` -> `In Transit` -> `Received` / `Partially Received`.
  - Automatic transfer number generator: `TRF-YYYYMMDD-XXXX`.
  - Dynamic transit state transitions: units transition to `In Transit` with source warehouse/store cleared, preventing double allocation during transport.
  - Receiving discrepancy reporting: supports granular line-item dispositions (`received`, `missing`, `damaged`, `rejected`).
- **Store Inventory Isolation (Anti-IDOR)**:
  - Store Admins are strictly scoped to their assigned retail location.
  - URL query tampering and unauthorized cross-store transfer receiving blocked with HTTP 403.
- **Physical Stock Reconciliation**:
  - Physical audit header creation, discrepancy tracking, and resolution actions (`reconcile`, `quarantine_damaged`, `write_off_missing`).

---

## [Phase 2] - Manufacturing, Batch Management & Individual Unit QR Generation
### Added
- **Manufacturing Batch Management**:
  - Batch tracking: batch number, product link, planned vs actual quantities, manufacturing and expiry dates, operator assignment, and batch notes.
  - Status lifecycle: `Draft`, `In Production`, `Completed`, `Under Verification`, `Closed`.
  - Audit protection: Closed batches cannot be modified without authorization.
- **Machine Connectivity Architecture**:
  - `CountingMachineInterface` abstract contract.
  - Modular hardware connector implementations: `UsbSerialConnector`, `Rs232Connector`, `LanApiConnector`, `PlcGatewayConnector`, `ManualEntryConnector`.
  - Automatic event audit logging in `production_events`.
- **Individual Physical Unit Generation**:
  - Memory-safe chunk generation (500 units per transaction).
  - Format serials: `PA-P001-000001` continuous sequence per product without gaps.
  - Cryptographically secure 128-bit random tokens (`bin2hex(random_bytes(16))`).
  - Initial lifecycle state: `Generated`, `Unverified`.
- **Thermal & Sheet Label Printing**:
  - High-resolution SVG QR code generation embedding public verification URL.
  - Formatted print templates for 50x25mm and 50x30mm thermal rolls and A4 24-up sticker sheets.
  - Controlled reprint tracking requiring min 5-character reason and incrementing reprint count.
- **Pre-Warehouse QA Verification Terminal**:
  - High-speed scan interface (`/manufacturing/qa-verification`) validating physical unit density, seal, and label before warehouse clearance.
- **Public Anti-Counterfeit Verification Portal**:
  - Public route `/scan/{token}` showing digital certificate of authenticity with product specifications, packaging dates, and batch credentials.
  - Security filtering strictly sanitizes sensitive supply chain data (warehouses, stores, purchase prices, suppliers, cashier identities).

---

## [Phase 1] - Core Architecture, Multi-Store Foundation & RBAC
### Added
- **Clean Laravel 11 Project Initialization**:
  - Environment inspection and clean directory bootstrapping.
  - MySQL database architecture with migrations and foreign key constraints.
  - Bootstrap 5 responsive UI layout with navigation sidebar, flash notifications, and modal dialogs.
- **Enterprise Authentication & Security**:
  - Rate-limited login throttling (5 attempts per minute).
  - Secure Bcrypt/Argon2id password hashing.
  - Session regeneration on login, session invalidation on logout.
  - Uninformative password recovery messages preventing user enumeration.
  - Global CSRF protection, secure HTTP-only cookies, and XSS sanitization.
- **Role-Based Access Control (RBAC)**:
  - Three core roles: `Super Admin`, `Store Admin`, `Cashier`.
  - Granular permissions catalog with `permission_role` and `role_user` bindings.
- **Multi-Store Management**:
  - Store entity management with GSTIN, location, and status controls.
  - User store assignment pivot (`store_user`) supporting primary store designations.
- **Product & Category Catalog**:
  - Product categories with nested product items, SKU management, selling prices, and GST tax brackets.
- **System Audit Logging**:
  - `audit_logs` table recording all administrative actions, IP addresses, entity mutations, and timestamps.
