Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jan 10, 2026

Overview

Implements foundation layers (Phases 1-2) for a pharmaceutical inventory and accounting ERP with integrated Point of Sale system. Adds 31 database models with regulatory compliance controls (lot tracking, FEFO allocation, immutable ledgers) and 7 service classes for inventory, procurement, sales, accounting, and POS operations.

Database Schema (Phase 1)

31 new models across 6 domains:

  • Master Data: ErpItem (pharma attributes: dosage, strength, storage conditions, shelf-life), ErpSupplier, ErpWarehouse, ErpLocation, ErpChartOfAccount
  • Inventory: ErpLot (lot/expiry tracking), ErpInventoryLedger (append-only), ErpStockBalance (materialized view)
  • Procurement: ErpPurchaseOrder, ErpGRN (goods receipt with lot capture), ErpSupplierBill
  • Sales: ErpSalesOrder, ErpAllocation (FEFO-based), ErpShipment, ErpReturn (with QA disposition)
  • Accounting: ErpGLJournal (immutable), ErpPostingRule (auto-posting), ErpARInvoice, ErpAPInvoice, ErpPayment
  • POS: PosCashierShift, PosPrescription, PosTransaction, PosSyncQueue (offline support)

SQL enforcement:

-- Prevent tampering with posted ledgers and journals
CREATE TRIGGER prevent_inventory_ledger_updates
  BEFORE UPDATE ON "ErpInventoryLedger"
  EXECUTE FUNCTION reject_inventory_ledger_modification();

CREATE TRIGGER prevent_gl_journal_updates  
  BEFORE UPDATE ON "ErpGLJournal"
  EXECUTE FUNCTION reject_gl_journal_modification();

-- Ensure balanced double-entry bookkeeping
CREATE TRIGGER validate_journal_balance
  BEFORE UPDATE ON "ErpGLJournal"
  EXECUTE FUNCTION validate_balanced_journal();

-- Materialized view for O(1) stock queries
CREATE MATERIALIZED VIEW erp_stock_balance_mv AS
  SELECT item_id, lot_id, warehouse_id, status,
         SUM(quantity_delta) as quantity
  FROM "ErpInventoryLedger"
  GROUP BY item_id, lot_id, warehouse_id, status;

All tables scoped by organizationId/storeId for multi-tenant isolation.

Core Services (Phase 2)

7 service classes with transactional integrity:

  1. ErpBaseService - Transaction wrapper with configurable isolation (RepeatableRead/Serializable)
  2. InventoryLedgerService - Append-only ledger operations, reversal entries for corrections
  3. FEFOAllocationService - First-Expire-First-Out allocation with shelf-life validation and row-level locking
  4. PostingService - Atomic GL posting:
    • postGRN(): Dr Inventory / Cr GRNI
    • postShipment(): Dr COGS / Cr Inventory + AR invoice
    • postAdjustment(): With maker-checker threshold checks
    • postReturn(): QA disposition to GL
  5. ApprovalService - Maker-checker workflows for adjustments, payments, journal postings
  6. POSService - Transaction processing with immediate inventory deduction, shift reconciliation
  7. PrescriptionService - Pharmacist verification, drug interaction checks
// Example: Atomic GRN posting with automatic GL entries
await postingService.postGRN(grnId, userId);
// Creates: inventory ledger + GL journal (Dr Inventory / Cr GRNI) + updates GRN status
// All in single Serializable transaction

// Example: FEFO allocation respecting shelf-life constraints
const allocations = await fefoService.allocateStock({
  itemId, quantity, warehouseId,
  minShelfLifeDays: 90  // Customer requirement
});
// Returns: [{ lotId, quantity }, ...] sorted by earliest expiry

Key Features

  • Regulatory Compliance: Lot traceability, controlled substance tracking, quarantine/release workflows
  • Financial Controls: Double-entry accounting, immutable ledgers, period close enforcement
  • FEFO Allocation: Pharmaceutical best practice to minimize expiry waste
  • Offline POS: Sync queue for resilient retail operations
  • Multi-Tenant: Complete isolation at database and service layers

Remaining Work

This completes ~30% of the full implementation. Remaining phases:

  • Phase 3: REST API layer (100+ endpoints)
  • Phase 4: ERP UI (30+ screens)
  • Phase 5: POS UI with offline support
  • Phase 6: Testing (unit, integration, E2E)
  • Phase 7: Production deployment

See docs/pharma-erp/IMPLEMENTATION_STATUS.md for complete status and next steps.

Original prompt

This section details on the original issue you should resolve

<issue_title>Implement Pharma ERP + POS System (Full Feature Buildout)</issue_title>
<issue_description>## Summary

Implement the Pharma ERP + POS system as described in the project documentation. This comprehensive task covers database, backend (API/services), frontend (UI), and all required compliance, audit, and reporting features necessary for a multi-tenant pharmaceutical ERP with integrated Point of Sale (POS), following the specifications and phased plan documented in:


Scope (High-Level)

  • Extend schema: ERP items, lot/batch, FEFO, ledgers, procurement, sales, accounting, POS tables
  • Backend: Inventory, procurement, sales, accounting, compliance, and POS service layers per provided code patterns
  • API: RESTful endpoints per plan for ERP and POS domains
  • UI: Next.js App Router screens for each ERP module, POS interface with offline support
  • Security: RBAC, NextAuth, audit trails, maker-checker
  • Testing: Service/unit logic and E2E for workflows as planned
  • Reporting: Dashboards and KPI/trace/financial/expiry/stock-out reports
  • Deployment: Staged go-live with user training per roadmap

Acceptance Criteria

  • Follows all critical SRS requirements and implementation plan phases (Phase 1–6)
  • Enforces multi-tenancy, regulatory controls, full traceability, and financial integration
  • Core modules delivered and reviewed against documentation checklists
  • Coverage includes compliance, audit, reporting, support, and training requirements
  • A successful staged rollout to production (see deployment sections)

References

  • Executive Summary: docs/pharma-erp/PHARMA_ERP_EXECUTIVE_SUMMARY.md
  • Full Implementation Plan: docs/pharma-erp/PHARMA_ERP_POS_IMPLEMENTATION_PLAN.md
  • Quick Start: docs/pharma-erp/PHARMA_ERP_QUICK_START.md
  • ReadMe: docs/pharma-erp/PHARMA_ERP_README.md
  • SRS: Software-Requirements-Specification-Pharma-Inventory-and-Accounts-ERP.md
  • SRS Cross-Validation: docs/ERP_SRS_CrossValidation.md

Note: Break this issue into sub-tasks for each major phase/module (database, backend services, API, UI, compliance, testing, reporting, deployment, documentation). Link those sub-issues here for tracking once created.</issue_description>

<agent_instructions>Review all the documentation and the codebase and perform online research for the implementation. Make sure to use all the latest documentation of Next.js 16 and use next.js 16 mcp and shadcn mcp tools for the implementation</agent_instructions>

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@vercel
Copy link

vercel bot commented Jan 10, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
stormcomui Ready Ready Preview, Comment Jan 11, 2026 4:31am

@syed-reza98 syed-reza98 added documentation Improvements or additions to documentation enhancement New feature or request production Changes for Production Environment and Configuration Priority 1 type:story Phase 0 dependencies Pull requests that update a dependency file labels Jan 10, 2026
@syed-reza98 syed-reza98 moved this from Backlog to In progress in StormCom Jan 10, 2026
…schema

- Add 31 new models for ERP and POS modules
- Implement immutability triggers for inventory ledger and GL journals
- Add materialized view for stock balance queries
- Include comprehensive documentation
- Maintain multi-tenant isolation across all tables

Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
…nts-ERP.md to docs/pharma-erp/ Software-Requirements-Specification-Pharma-Inventory-and-Accounts-ERP.md
- Add ErpBaseService with transaction support
- Implement InventoryLedgerService for append-only ledger operations
- Implement FEFOAllocationService for First-Expire-First-Out logic
- Implement PostingService for automated GL posting (GRN, Shipment, Adjustments, Returns)
- Implement ApprovalService for maker-checker workflows
- Implement POSService for transaction processing and shift management
- Implement PrescriptionService for prescription management
- Fix schema mismatches to align with service implementations
- Add missing fields and enums to Prisma schema

Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
- Document completion of Phases 1-2 (database schema and core services)
- Outline remaining work for Phases 3-7
- Provide next steps and recommendations
- Include team staffing and timeline guidance

Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
Copilot AI changed the title [WIP] Implement Pharma ERP and POS system with all features feat(erp): Implement Pharma ERP + POS foundation (database schema and core services) Jan 10, 2026
Copilot AI requested a review from syed-reza98 January 10, 2026 22:08
Copilot AI and others added 5 commits January 11, 2026 02:01
Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
…entation

Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
Copilot AI and others added 2 commits January 11, 2026 02:59
… division by zero, remove unused variables

Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
Copilot AI and others added 10 commits January 11, 2026 03:10
Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
…nitions

Co-authored-by: syed-reza98 <71028588+syed-reza98@users.noreply.github.com>
Refactored API route handlers to use generic type parameters for context, improved type safety, and updated service methods for better API compatibility. Added aliases like listItems, listGRNs, listPurchaseOrders, listSalesOrders, and discontinueItem to service classes. Enhanced validation schemas, improved error messages, and ensured date fields are properly converted. Updated getCurrentUser to include organizationId and isSuperAdmin. Fixed type errors and removed organizationId from service method calls where not needed. All TypeScript errors are now resolved.
Introduces a detailed implementation plan for Phase 4 of the StormCom pharma ERP system, covering UI and API development for 52 screens across 7 ERP modules and POS. The plan includes module breakdowns, reusable UI patterns, security and RBAC guidelines, week-by-week roadmap, file structure recommendations, and success metrics.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file documentation Improvements or additions to documentation enhancement New feature or request pharma-erp Phase 0 Priority 1 production Changes for Production Environment and Configuration type:story

Projects

Status: In progress

Development

Successfully merging this pull request may close these issues.

Implement Pharma ERP + POS System (Full Feature Buildout)

4 participants