Pharmacy Management and ERP Platform
Software Requirements Specification (SRS) and System Architecture
Document version: 1.0
Date: 2026-04-27
Target stack: Laravel 13.x, PHP 8.3+, MySQL 8.0+ or MariaDB 10.6+
Deployment profile: Shared hosting first, cloud-ready later
Assumptions and Design Constraints
- The platform will be built as a modular monolith in Laravel so it can run efficiently on shared hosting while preserving clear domain boundaries.
- The application must work without Redis, Supervisor, Docker, websockets, or any always-on Node server.
- Frontend delivery will use Laravel Blade + Alpine.js with prebuilt CSS/JS assets, so no Node runtime is required on the hosting server.
- Laravel 13.x is the current stable target for this blueprint. If a selected shared host does not support PHP 8.3+, the hosting vendor must be upgraded or changed before implementation proceeds.
- Regulatory controls will be configurable because pharmacy rules differ by country and product category.
1. Executive Summary
This document defines a robust, scalable pharmacy management and ERP platform designed for retail pharmacies, multi-branch pharmacy groups, wholesale distributors, and pharmacy-linked manufacturing operations. The solution is engineered as a Laravel-based modular monolith that can run on low-cost shared hosting today and scale to VPS or cloud environments later without requiring a full rewrite.
The platform combines pharmacy operations, finance, inventory, procurement, HR, analytics, and enterprise workflows in one unified system. It supports prescription handling, dispensing, batch and expiry control, procurement, accounting, reporting, customer and supplier management, multi-location control, and optional manufacturing workflows such as BOM, MRP, and MES.
The architecture prioritizes low resource usage, secure processing, clear auditability, and operational resilience in environments with limited hosting permissions.
2. Product Vision and Objectives
Product Vision
Build a pharmacy-first ERP platform that starts as a practical operational system for a single pharmacy and grows into a full enterprise platform for chains, wholesalers, distributors, and light manufacturing environments.
Strategic Objectives
- Centralize all pharmacy and back-office operations in one application.
- Reduce stock-outs, expiries, leakages, and manual reconciliation work.
- Provide auditable dispensing and inventory traceability.
- Support growth from a single outlet to multi-company and multi-warehouse operations.
- Keep deployment simple enough for cPanel/shared hosting while preserving enterprise-grade structure.
- Deliver mobile-friendly access without depending on heavy real-time infrastructure.
- Enable staged adoption so clients can start with an MVP and add modules over time.
Measurable Business Outcomes
- Lower expired stock write-offs through FEFO and alerting.
- Improve order fulfillment speed and accuracy.
- Reduce manual accounting and reconciliation delays.
- Increase visibility through near real-time operational dashboards.
- Create a reliable audit trail for prescriptions, inventory, finance, and approvals.
3. Target Users and Roles
Primary Users
- Pharmacists: prescription review, dispensing, clinical notes, stock substitution review, patient counseling history.
- Pharmacy Technicians: prescription preparation, picking, packing, stock checks, label printing.
- Cashiers / POS Staff: OTC sales, invoice settlement, receipt printing, returns, customer lookup.
- Store Managers / Branch Managers: branch performance, stock approvals, pricing controls, staff oversight.
- Warehouse Staff: receiving, put-away, picking, transfer, cycle counting, batch handling.
- Procurement Officers: supplier management, RFQs, purchase orders, GRNs, returns to vendor.
- Accountants / Finance Team: GL, AP, AR, bank and cash reconciliation, tax, budgeting, period close.
- HR / Payroll Officers: employee records, attendance imports, payroll runs, statutory deductions.
- Quality Assurance Staff: batch release, quarantine, CAPA, recall management, document control.
- Manufacturing / Production Staff: formulation, BOM execution, work orders, material issue, batch production records.
- Executives / Owners / Management: dashboards, KPI tracking, branch comparison, profitability, cash position.
- System Administrators / IT: user provisioning, RBAC, configuration, backups, integrations, audit review.
Cross-Cutting Role Model
- Roles are assigned by company, branch, warehouse, and function.
- Users may hold multiple roles, for example Pharmacist + Branch Manager.
- Sensitive permissions require both functional permission and data-scope permission.
4. Full Modular System Architecture (Laravel-Based)
Architectural Style
The recommended architecture is a modular monolith with strong bounded contexts. This approach offers:
- lower operational overhead than microservices,
- simpler deployment on shared hosting,
- single database transaction support where needed,
- easier reporting across domains,
- a clean migration path to services later if scale demands it.
High-Level Layers
-
Presentation Layer
- Blade views
- Alpine.js for small interactive components
- REST API controllers for mobile and third-party integrations
-
Application Layer
- Use-case services / action classes
- Form requests for validation
- Policies and authorization gates
- Workflow orchestration services
-
Domain Layer
- Eloquent models
- Domain services
- Value objects / enums
- Business rules
- Domain events
-
Infrastructure Layer
- MySQL/MariaDB persistence
- File storage
- Email/SMS adapters
- Payment gateway adapters
- Barcode and hardware integration adapters
Recommended Laravel Module Structure
app/
Domains/
Shared/
Pharmacy/
Inventory/
Sales/
Purchasing/
CRM/
SRM/
Finance/
Accounting/
HR/
Warehouse/
Quality/
Manufacturing/
Analytics/
routes/
web.php
api.php
database/
migrations/
seeders/
resources/
views/
lang/
Each domain should expose:
ModelsActionsorServicesPoliciesDTOsor data mappers where usefulObserversEventsandListenersReports
Shared Kernel
The following services should live in a shared kernel and be reused by all modules:
- authentication and session handling,
- RBAC and policy engine,
- company/branch/location context resolver,
- settings and feature flags,
- workflow engine,
- notification engine,
- audit logging,
- numbering/sequencing service,
- currency and tax engine,
- document attachment service.
Integration Pattern
- Synchronous in-process service calls for core business actions.
- Laravel events/listeners for decoupled post-transaction reactions.
- Database-backed jobs for deferred work where available.
- REST APIs and webhooks for external systems.
Deployment Pattern
- Single Laravel codebase
- Single MySQL/MariaDB database per environment
- Optional multiple databases later for reporting or tenant isolation
- No mandatory persistent daemons
Architecture Diagram
flowchart TB
U["Users (Web, Tablet, Mobile Browser, API Clients)"] --> W["Blade UI / REST API"]
W --> M["Laravel Middleware, Auth, RBAC, Tenant Context"]
M --> A["Application Services / Actions"]
A --> D1["Pharmacy Domain"]
A --> D2["ERP Domains"]
A --> D3["Workflow / Notifications / Audit"]
D1 --> DB["MySQL / MariaDB"]
D2 --> DB
D3 --> DB
A --> FS["File Storage"]
A --> X["Payment / SMS / Email / Barcode / Third-Party APIs"]
5. Detailed Module-by-Module Feature Breakdown
Canonical Module List (Kept Unchanged)
Financial Management, Inventory Management, Sales Order Management, Purchase Order Management, CRM, SRM, Manufacturing, HR, BI, Warehouse, Quality Control, Fixed Assets, Document Management, Mobile Access, Multi Currency, Multi Language, E-Commerce, Workflow Automation, Dashboards, Accounting, Budgeting, Payroll, BOM, MRP, ERP, MES, Logistics, Analytics, etc.
Module Breakdown
| Module | Scope | Key Features | Key Integrations |
|---|---|---|---|
| Financial Management | Cash and financial oversight | cashbooks, bank accounts, treasury, expense controls, margin analysis, branch P&L | Accounting, Budgeting, Payroll, Dashboards |
| Inventory Management | Stock control | item master, batch/lot tracking, FEFO, serial/batch support, adjustments, stock counts, reorder levels | Warehouse, Sales, Purchasing, Quality Control |
| Sales Order Management | Retail and B2B sales | quotations, POS, invoices, sales orders, returns, discounts, promotions, credit sales | CRM, Accounting, Logistics |
| Purchase Order Management | Procurement | requisitions, RFQs, approvals, purchase orders, GRNs, purchase returns, landed cost | SRM, Inventory, Accounting |
| CRM | Customer and patient relationship management | customer profiles, patient history, loyalty, communication logs, pricing tiers, follow-up reminders | Sales, Mobile Access, E-Commerce |
| SRM | Supplier relationship management | supplier onboarding, scorecards, contracts, lead times, compliance documents, dispute tracking | Purchasing, Quality Control, Financial Management |
| Manufacturing | Internal production and compounding | formulations, work orders, batch records, yields, material issue, output posting | BOM, MRP, MES, Quality Control |
| HR | Workforce administration | employee master, positions, leave, shift templates, performance records, onboarding | Payroll, Workflow Automation |
| BI | Decision support | management reports, data marts, KPI snapshots, drill-down summaries | Dashboards, Analytics |
| Warehouse | Physical stock movement | warehouse/bin setup, put-away, picking, transfers, cycle count, staging areas | Inventory, Logistics, Purchase Orders |
| Quality Control | Product and process quality | quarantine, sampling, inspection, non-conformance, CAPA, release/hold, recall support | Inventory, Manufacturing, Document Management |
| Fixed Assets | Asset lifecycle | asset register, depreciation, transfers, maintenance history, disposal | Accounting, Financial Management |
| Document Management | Controlled documents and attachments | prescription scans, invoices, HR docs, SOPs, certificates, retention rules, versioning | Quality Control, HR, CRM |
| Mobile Access | Lightweight mobile use | responsive screens, task dashboards, approvals, stock checks, delivery confirmation | API, Workflow Automation |
| Multi Currency | Currency handling | exchange rates, base currency, transactional currency, realized/unrealized FX, branch rate policy | Sales, Purchasing, Accounting |
| Multi Language | Localization | translated labels, multilingual masters, printable templates by locale | UI, Documents, E-Commerce |
| E-Commerce | Online commerce | catalog, stock visibility, prescription upload, click-and-collect, order tracking | CRM, Inventory, Logistics |
| Workflow Automation | Rule-driven process automation | approvals, escalations, reminders, routing rules, status transitions | All modules |
| Dashboards | Operational monitoring | role-based widgets, KPIs, branch comparison, exception panels, alerts | BI, Analytics |
| Accounting | Book of records | chart of accounts, journals, GL, AP, AR, tax, trial balance, close periods | Financial Management, Sales, Purchasing |
| Budgeting | Planning and variance | annual budgets, departmental budgets, budget revisions, actual vs budget | Accounting, Dashboards |
| Payroll | Compensation processing | earnings, deductions, taxes, payslips, approvals, disbursement files | HR, Accounting |
| BOM | Product formulation structures | formulas, recipe versions, packaging BOMs, substitution controls | Manufacturing, MRP |
| MRP | Material planning | demand calculation, replenishment proposals, shortage analysis, production planning | Inventory, Purchasing, BOM |
| ERP | Enterprise orchestration | master data governance, cross-module workflows, approval routing, intercompany controls | All modules |
| MES | Shop-floor execution | work center tracking, task execution, batch status, material consumption capture | Manufacturing, Quality Control |
| Logistics | Outbound and inbound movement | delivery planning, route batches, proof of delivery, shipment status, transfer tracking | Sales, Warehouse, E-Commerce |
| Analytics | Insights and forecasting | trend analysis, demand forecasting, ABC/FSN analysis, expiry risk analysis | BI, Dashboards |
| etc. | Extensibility bucket | future modules such as insurance billing, laboratory links, clinic integration, franchise portal | Shared APIs and feature flags |
6. Pharmacy-Specific Workflows
6.1 Prescription Intake
- Patient or caregiver presents prescription physically or digitally.
- Staff searches or creates patient profile.
- System records prescriber, prescription date, medication lines, dosage, and attachments.
- Pharmacist validates prescription completeness and checks for expiry, duplicates, or refill limits.
- If stock is unavailable, system suggests alternatives or creates a backorder/procurement request.
6.2 Dispensing Workflow
- Approved prescription creates a dispensing task.
- System allocates stock using FEFO and batch controls.
- Staff picks stock and records quantities.
- Pharmacist verifies picked items against the prescription.
- System prints label and patient instructions.
- Sale/invoice is posted and inventory is deducted.
- Audit log captures who entered, checked, and dispensed.
6.3 OTC Sales Workflow
- Cashier scans barcode or searches product.
- System validates price, stock, and discount policy.
- Cashier completes payment or credit capture.
- Stock movement and accounting journal are posted automatically.
6.4 Stock Alert Workflow
- Nightly or on-transaction stock checks compare available quantity to reorder thresholds.
- Low stock items create alerts and optional replenishment suggestions.
- Managers review and approve purchase requisitions.
6.5 Expiry Tracking Workflow
- Each receipt stores batch number, manufacture date, and expiry date.
- FEFO allocation prioritizes earliest valid expiry.
- Configurable alerts warn at 180/90/30/7 days.
- Near-expiry items can be marked for promotion, transfer, quarantine, or return to vendor.
6.6 Recall and Quarantine Workflow
- Manager or QA marks affected batch as recalled or quarantined.
- System immediately blocks sale, transfer, or issue of the batch.
- On-hand quantities by branch are listed.
- Prior customers and invoices tied to the batch are traceable for notification.
6.7 Controlled Medication Workflow
If local regulations require extra controls, the system should support:
- stricter permissions,
- witness or dual sign-off,
- reason codes for adjustments,
- restricted voiding,
- serialized register exports,
- regulator-ready audit trails.
7. ERP-Wide Workflows
Procure-to-Pay
Requisition -> approval -> RFQ/quotation -> purchase order -> goods receipt -> invoice match -> supplier payment -> GL posting
Order-to-Cash
Quotation or prescription -> sales order/POS -> fulfillment -> invoice -> receipt/payment -> revenue recognition -> customer statement
Forecast-to-Replenish
Demand analysis -> reorder recommendation -> approval -> PO or production order -> receipt -> put-away -> availability update
Manufacture-to-Release
Formula/BOM approval -> production order -> material issue -> batch execution -> QC inspection -> release -> inventory posting
Hire-to-Retire
Recruit/onboard -> employee master -> attendance/leave -> payroll -> appraisal -> transfer or exit
Budget-to-Actual
Budget preparation -> approval -> period locking -> actual postings -> variance review -> management action
8. Database Architecture
Database Strategy
- Use MySQL 8.0+ or MariaDB 10.6+ with InnoDB.
- Use utf8mb4 charset throughout.
- Prefer single database, multi-company row-level isolation in the first version.
- Use BIGINT unsigned primary keys or UUIDs for externally exposed resources where needed.
- Use DECIMAL(18,2/4/6) for monetary and quantity fields; avoid floating-point math for finance and stock.
Normalization Strategy
- Normalize master data to 3NF for maintainability.
- Keep transactional detail tables separate from headers.
- Use lookup tables for controlled vocabularies and statuses where it improves consistency.
- Introduce denormalized reporting tables only for BI/performance layers, not as the operational source of truth.
Multi-Tenant Scoping
Most transactional tables should include:
company_idbranch_idwhere relevantlocation_idorwarehouse_idwhere relevantcreated_byupdated_by
Ledger Pattern
Use append-only ledgers for sensitive domains:
- stock ledger
- GL journal lines
- payment ledger
- audit log
This improves traceability and reduces hidden data mutation risk.
Indexing Strategy
Create composite indexes around common filters:
(company_id, status)(company_id, branch_id, created_at)(company_id, item_id, batch_number)(company_id, expiry_date)(company_id, document_number)(company_id, patient_id, prescription_date)(company_id, account_id, posting_date)
Archiving Strategy
- Keep current operational data in primary tables.
- Archive very old audit rows, notifications, and generated reports into archive tables or export packages when data volume grows.
- Avoid deleting financial and inventory history; instead reverse, void, or mark inactive.
9. Role-Based Access Control (RBAC) and Permissions
RBAC Model
Use a layered permission model:
- Role-based permissions: cashier, pharmacist, warehouse clerk, accountant, HR officer, admin, executive.
- Data-scope permissions: company, branch, warehouse, department, cost center.
- Action-level permissions: create, approve, void, dispense, adjust stock, post journal, export report.
Permission Design
- Start with
spatie/laravel-permissionor an equivalent internal implementation. - Use Laravel policies for record-level enforcement.
- Enforce approval limits by amount, branch, module, and transaction type.
- Separate configuration permissions from operational permissions.
Example Role Mapping
| Role | Core Permissions |
|---|---|
| Pharmacist | review prescription, approve dispensing, substitute item, access patient medication history |
| Cashier | create sale, collect payment, print receipt, limited return processing |
| Warehouse Clerk | receive goods, transfer stock, cycle count, no price override |
| Procurement Officer | create requisition/PO, compare suppliers, submit for approval |
| Accountant | post journals, reconcile cash/bank, close periods, tax reports |
| HR Officer | manage employee data, leave, payroll preparation |
| Branch Manager | approve discounts, stock adjustments, branch purchases within limits |
| System Admin | user setup, permission assignment, settings, integration config |
10. Security
Authentication
- Laravel authentication with password hashing via Argon2id or bcrypt depending server support.
- Optional 2FA for administrators, finance users, and pharmacists.
- Email verification for privileged users.
- Session timeout and device/session revocation.
Authorization
- Policies and gates per module.
- Branch and company scoping enforced at query level and policy level.
- Sensitive actions require re-authentication or PIN confirmation where appropriate.
Data Protection
- Encrypt sensitive fields at rest where justified, such as API keys and certain patient identifiers.
- Force HTTPS in production.
- Use CSRF protection, rate limiting, secure cookies, and strict validation.
- Limit document upload types and sizes.
Auditability
Audit the following:
- login attempts,
- permission changes,
- prescription lifecycle events,
- stock adjustments,
- price changes,
- accounting postings and reversals,
- payroll approvals,
- document downloads of sensitive files.
Compliance Posture
The platform should be compliance-ready, with final compliance mapping configured for jurisdiction-specific obligations such as privacy laws, pharmacy handling rules, tax rules, and controlled-substance regulations.
11. API Architecture (RESTful APIs Using Laravel)
API Principles
- Versioned REST API under
/api/v1 - JSON responses with consistent resource formatting
- Token authentication using Laravel Sanctum
- Idempotency keys for payment and external callback endpoints
- Pagination, filtering, sorting, and include parameters
API Categories
- Authentication and profile
- Master data
- Sales and prescription operations
- Inventory and warehouse transactions
- Purchasing
- Finance and accounting
- Reports and dashboard widgets
- Mobile task endpoints
- Third-party integration endpoints
Response Standards
- Use API Resources for response transformation.
- Standardize success, validation error, authorization error, and business rule error formats.
- Return traceable reference numbers on all write endpoints.
12. Integration Strategy
Payment Gateways
- Card payments
- bank transfer reconciliation imports
- mobile money where relevant
- cash and POS settlement
Communication
- SMTP email
- SMS gateway integrations through adapter classes
- optional WhatsApp or messaging connectors if permitted locally
Barcode and RFID
- Support keyboard-emulation barcode scanners out of the box.
- Support label printers for product and shelf labels.
- RFID should be adapter-based and optional, using vendor SDK/API integrations where supported.
Third-Party APIs
- e-commerce marketplace sync
- accounting export/import if required
- insurance or benefit scheme connectors
- regulator or tax invoice connectors where legally required
- external lab or clinic systems if later added
Integration Design Rules
- Encapsulate each integration behind an interface and adapter.
- Log requests and responses with masking of secrets and personal data.
- Support retry and dead-letter handling using database-backed jobs or manual retry screens.
13. Mobile App Strategy
Phase 1: Lightweight Mobile Access
- Responsive web application optimized for tablets and smartphones.
- Mobile-first task flows for approvals, stock checks, delivery confirmation, and dashboards.
- Offline-like resilience through draft saving and retryable form submissions where possible.
Phase 2: API-Driven Mobile Apps
- Build native or cross-platform apps only after mobile usage patterns are proven.
- Reuse the Laravel REST API.
- Focus on warehouse scanning, manager approvals, field delivery, and sales rep functions.
Recommended Mobile Scope
- view tasks,
- approve requests,
- check stock,
- scan barcodes,
- confirm deliveries,
- review branch KPIs.
14. Dashboard and Reporting System (BI + KPIs)
Dashboard Principles
- Role-based dashboards
- branch-specific and group-wide filters
- fast-loading widgets using cached or summarized data
- exception-driven alerts rather than noisy information overload
Example KPIs
- daily sales
- gross margin
- top-moving items
- low-stock items
- near-expiry stock value
- stock adjustment variance
- purchase lead time
- receivables aging
- payables aging
- branch profitability
- payroll cost ratio
- production yield variance
Reporting Types
- operational reports
- financial statements
- regulatory and audit reports
- inventory valuation
- customer and supplier statements
- management analytics
Real-Time Reporting Strategy
- Use efficient polling every 30 to 120 seconds where needed.
- Expose lightweight JSON widget endpoints.
- Refresh only changed widgets using timestamps or ETags.
- Avoid websockets unless later infrastructure can support them.
15. Workflow Automation and Notification System
Workflow Engine
Use configurable workflow tables for:
- approval chains,
- escalation rules,
- status transitions,
- SLA timers,
- reminder schedules.
Notification Channels
- in-app notifications,
- email,
- SMS,
- digest reports.
Trigger Examples
- low-stock alert,
- prescription ready for pharmacist approval,
- PO awaiting approval,
- supplier delivery overdue,
- item batch nearing expiry,
- pending payroll approval,
- negative margin sale attempt,
- failed integration callback.
Shared Hosting Fallback
- Primary mode: database queue driver.
- Fallback mode: synchronous dispatch for critical low-volume notifications.
- Optional cron mode:
queue:work --stop-when-emptyandschedule:runvia cPanel cron every 1-5 minutes. - No-cron fallback: a guarded application heartbeat endpoint or admin-triggered maintenance runner for low-volume environments.
16. Multi-Company, Multi-Location, Multi-Currency, Multi-Language Design
Organization Hierarchy
- Group / Holding Company
- Company / Legal Entity
- Branch / Outlet
- Warehouse / Store
- Bin / Shelf / Zone
Multi-Company Rules
- Shared users may access multiple companies if permitted.
- Each transaction belongs to one legal entity.
- Intercompany transactions should create mirrored accounting records.
Multi-Location Rules
- Inventory is stored per warehouse and optionally per bin.
- Transfers require source and destination authorization.
- Branch dashboards default to local data but allow authorized roll-up.
Multi-Currency Rules
- Base currency per company
- transaction currency per document
- exchange rate table by date
- realized and unrealized FX treatment in accounting
Multi-Language Rules
- UI labels stored in Laravel language files
- print templates localized
- customer-facing documents support locale selection
17. Laravel-Specific Architecture Decisions
Backend Pattern
- Controllers stay thin.
- Business logic lives in application services or action classes.
- Eloquent remains the default ORM and query layer.
- Repositories are used only where they add real abstraction value, such as complex externalized read models or interchangeable data sources.
Events and Listeners
Use events for decoupled side effects, for example:
PrescriptionDispensedStockAdjustedPurchaseOrderApprovedGoodsReceivedInvoicePaid
Listeners can then update ledgers, notifications, dashboards, or analytics snapshots.
Jobs and Fallback Strategy
- Default queue driver:
database - Fallback queue driver:
sync - Keep job payloads small and retry-safe
- Provide admin screens to re-run failed jobs
Configuration Strategy
.envfor environment secrets- database-backed settings for business configuration
- feature flags to enable modules per tenant or edition
File Handling
- Use Laravel filesystem with local/public disks on shared hosting.
- Store documents outside the public web root where possible.
- Expose downloads through authenticated controllers or signed URLs.
18. UI/UX Design Principles
Design Goals
- pharmacy-friendly,
- fast to learn,
- keyboard-efficient,
- mobile-responsive,
- low-clutter,
- error-resistant.
UX Principles
- Prioritize fast search and barcode entry.
- Use large, readable typography for dispensing and POS screens.
- Clearly distinguish warning states: expiry, low stock, controlled item, insufficient rights.
- Minimize modal overload and reduce click depth.
- Provide contextual actions from list views.
- Keep dashboard widgets actionable.
Layout Strategy
- Desktop: dense operational tables with filters and quick actions.
- Tablet: approval, picking, and receiving optimized layouts.
- Mobile: task-first cards and simplified forms.
19. Development Roadmap (Phases: MVP -> Full ERP)
Phase 0: Foundation
- Laravel project setup
- authentication, RBAC, settings
- company/branch/warehouse master data
- audit log foundation
- item master and barcode model
Phase 1: MVP Retail Pharmacy
- Inventory Management
- Sales Order Management
- Purchase Order Management
- basic CRM
- Dashboards
- Accounting lite
- prescription intake and dispensing
Phase 2: Multi-Branch Operations
- branch transfers
- multi-location stock
- Financial Management
- full Accounting
- Budgeting
- Document Management
- Mobile Access
Phase 3: Distribution and Enterprise
- SRM
- Warehouse
- Logistics
- BI
- Analytics
- E-Commerce
- advanced Workflow Automation
Phase 4: Manufacturing and Advanced ERP
- Manufacturing
- BOM
- MRP
- MES
- Quality Control
- Fixed Assets
- Payroll
- HR expansion
20. MVP Feature Set (What to Build First)
The MVP should focus on operational fit for a single or small multi-branch retail pharmacy.
MVP Scope
- user authentication and RBAC
- company, branch, warehouse, item, category, and supplier masters
- barcode-enabled stock receipt and issue
- batch/expiry tracking
- OTC sales and receipt printing
- prescription capture and dispensing
- purchase orders and goods receipt
- low-stock and expiry alerts
- basic customer/patient records
- cashbook and core sales/purchase accounting
- dashboard with daily sales, stock alerts, and expiry alerts
- printable invoices, receipts, and labels
MVP Exclusions
- manufacturing,
- advanced payroll,
- full BI warehouse,
- deep e-commerce,
- RFID-specific flows,
- intercompany automation.
21. Advanced Enterprise Feature Set
- full double-entry accounting and period close
- consolidated multi-company reporting
- supplier scorecards and contract lifecycle
- customer loyalty, promotions, and segmentation
- automated replenishment and demand forecasting
- wholesale order portal and sales rep workflows
- production planning, MES, and quality release
- fixed asset depreciation and maintenance
- budgeting and variance workflows
- payroll and HR self-service
- advanced analytics and forecasting
- configurable API ecosystem and partner portal
22. Testing Strategy (Unit, Feature, Integration)
Unit Tests
- pricing calculations
- tax calculations
- FEFO allocation
- payroll formulas
- ledger posting services
- exchange rate logic
Feature Tests
- login and permission enforcement
- prescription creation and dispensing
- stock receipt and transfer
- sales posting and return handling
- purchase approval flow
- journal posting and reversal
Integration Tests
- payment gateway callbacks
- SMS/email adapters
- barcode workflows
- import/export jobs
- queue fallback behavior
Test Environment Strategy
- use dedicated testing database,
- seed reference data,
- fake notifications and queues,
- test both queue-enabled and sync fallback modes.
23. Deployment Strategy for Shared Hosting
Hosting Requirements
- PHP 8.3+
- MySQL/MariaDB access
- SSH access preferred, but not mandatory
- cPanel cron support preferred
- writable
storageandbootstrap/cache
Recommended cPanel Deployment
- Upload project outside
public_htmlif possible. - Point the domain or subdomain document root to Laravel
public/. - Configure
.envwith database, mail, app URL, session, cache, and queue settings. - Run migrations.
- Run
php artisan storage:linkif symlinks are permitted; otherwise use a controlled public storage fallback. - Run
php artisan config:cache,route:cache, andview:cache. - Use database queue driver by default.
- Add lightweight cron entries if available:
php artisan schedule:runphp artisan queue:work --stop-when-empty --tries=1
Shared Hosting Fallback Profile
If symlinks, long-running workers, or frequent cron jobs are not allowed:
- use local/public disk strategy,
- use
syncqueue for critical notifications, - use database queue with manual admin-triggered runner for non-critical work,
- use efficient polling instead of websockets.
24. Performance Optimization
Application Performance
- Keep pages server-rendered where possible.
- Use pagination everywhere for large lists.
- Use eager loading to avoid N+1 queries.
- Use request-level caching for settings and reference data.
- Cache stable lookup data using file or database cache drivers.
Database Performance
- composite indexes on scoping and status fields,
- summarize high-volume analytics into daily snapshot tables,
- use chunked processing for imports and reclassification jobs,
- avoid unbounded
LIKEsearches on large tables without search strategy.
Asset Performance
- prebuild CSS/JS before deployment,
- compress images and documents,
- use lazy loading for heavy dashboard widgets,
- generate PDFs on demand or cache them after first generation.
No-Redis Optimization Profile
- cache driver: file or database
- queue driver: database or sync
- session driver: database for multi-server future readiness, file for smallest setups
25. Backup and Disaster Recovery Strategy
Backup Scope
- database backups
- uploaded documents
- generated reports if business critical
- environment configuration backup copy stored securely
Recommended Schedule
- daily full database backup
- hourly incremental or transaction export if available
- daily document backup
- weekly restore test
Recovery Targets
- Small shared-hosting deployment target RPO: 24 hours
- Small shared-hosting deployment target RTO: 4 to 8 hours
- Improve targets as infrastructure matures
Operational Safeguards
- downloadable manual backup option for admins,
- off-server backup storage where feasible,
- clear restore runbook,
- backup success/failure notification.
26. Scalability Plan (Shared Hosting -> VPS -> Cloud)
Stage 1: Shared Hosting
- single app instance
- single database
- file or database cache
- database queue or sync
Stage 2: VPS / Dedicated Server
- dedicated PHP-FPM and web server tuning
- scheduled workers
- Redis optional
- object storage optional
- stronger monitoring
Stage 3: Cloud / Managed Platform
- load balancer
- managed database
- Redis/cache layer
- object storage
- background workers
- read replicas or reporting database
Migration Principle
Because the application is built as a modular monolith with clean domain boundaries, the same codebase can move infrastructure tiers without rewriting the business system.
27. Example Database Schema (Tables and Relationships)
Core Master Tables
companiesbrancheswarehousesbinsusersrolespermissionscustomerspatientssuppliersemployeesitemsitem_categoriesitem_uomscurrenciesexchange_ratestax_codes
Pharmacy Tables
prescriptionsprescription_itemsdispense_ordersdispense_order_itemsclinical_notes
Inventory and Warehouse Tables
stock_batchesstock_balancesstock_movementsstock_adjustmentsstock_countsstock_transfersstock_transfer_itemsgoods_receiptsgoods_receipt_items
Sales Tables
sales_orderssales_order_itemsinvoicesinvoice_itemspaymentspayment_allocationssales_returns
Purchasing Tables
purchase_requisitionspurchase_orderspurchase_order_itemspurchase_returns
Finance and Accounting Tables
chart_of_accountsjournal_entriesjournal_entry_linesbudgetsbudget_linesbank_accountscash_transactions
HR and Payroll Tables
departmentspositionsattendancesleavespayroll_runspayroll_lines
Manufacturing and Quality Tables
bomsbom_itemsproduction_ordersproduction_order_itemsmaterial_issuesproduction_outputsquality_inspectionsquality_nonconformances
System Tables
audit_logsdocumentsnotificationsworkflow_definitionsworkflow_stepsapproval_requestsfailed_jobssettings
Key Relationships
- one
companyhas manybranches - one
branchhas manywarehouses - one
itemhas manystock_batches - one
prescriptionhas manyprescription_items - one
dispense_orderbelongs to oneprescription - one
invoicehas manyinvoice_items - one
purchase_orderhas manypurchase_order_items - one
journal_entryhas manyjournal_entry_lines - one
production_orderhas many material issues and outputs - one
documentmay belong morphically to prescriptions, suppliers, employees, or quality records
28. Example API Endpoints
Authentication
POST /api/v1/auth/loginPOST /api/v1/auth/logoutGET /api/v1/me
Master Data
GET /api/v1/itemsPOST /api/v1/itemsGET /api/v1/suppliersGET /api/v1/customers
Pharmacy
POST /api/v1/prescriptionsGET /api/v1/prescriptions/{id}POST /api/v1/prescriptions/{id}/approvePOST /api/v1/dispense-ordersPOST /api/v1/dispense-orders/{id}/complete
Inventory
GET /api/v1/inventory/stock-balancesPOST /api/v1/inventory/adjustmentsPOST /api/v1/inventory/transfersGET /api/v1/inventory/expiry-alerts
Sales
POST /api/v1/sales/ordersPOST /api/v1/invoicesPOST /api/v1/paymentsPOST /api/v1/sales/returns
Purchasing
POST /api/v1/purchase-ordersPOST /api/v1/goods-receiptsPOST /api/v1/purchase-returns
Finance
GET /api/v1/accounting/trial-balanceGET /api/v1/accounting/general-ledgerPOST /api/v1/accounting/journal-entries
Reporting
GET /api/v1/dashboards/branch-summaryGET /api/v1/reports/near-expiry-stockGET /api/v1/reports/sales-daily
29. Example User Stories and Acceptance Criteria
User Story 1: Pharmacist Dispensing
As a pharmacist, I want to approve and dispense a prescription so that the correct medication is issued safely and recorded accurately.
Acceptance criteria
- prescription cannot be dispensed without pharmacist approval,
- system allocates valid stock by FEFO,
- dispense action posts stock movement and invoice,
- audit log records approving and dispensing users.
User Story 2: Cashier OTC Sale
As a cashier, I want to scan a barcode and complete a sale quickly so that checkout remains fast and accurate.
Acceptance criteria
- barcode scan retrieves item within acceptable response time,
- out-of-stock items cannot be sold without override rights,
- receipt is printable immediately after payment,
- stock and cash postings occur automatically.
User Story 3: Procurement Replenishment
As a procurement officer, I want to see low-stock alerts and generate purchase orders so that stock-outs are reduced.
Acceptance criteria
- reorder suggestion shows current stock, pending POs, and reorder level,
- approval workflow is triggered for purchases above threshold,
- approved PO can be converted to GRN on receipt.
User Story 4: Warehouse Transfer
As a warehouse clerk, I want to transfer stock between branches so that demand can be balanced.
Acceptance criteria
- transfer requires source and destination selection,
- batch quantities move with traceability,
- receiving branch confirms receipt before stock becomes available.
User Story 5: Accountant Period Close
As an accountant, I want to close a financial period so that historical postings remain controlled.
Acceptance criteria
- unauthorized users cannot close periods,
- closed periods block direct posting unless reopened by authorized users,
- all close/open actions are audited.
User Story 6: Management Dashboard
As a branch manager, I want a dashboard showing sales, low stock, and near-expiry items so that I can act quickly.
Acceptance criteria
- dashboard loads branch-scoped data by default,
- widgets refresh without full page reload,
- alerts link directly to actionable screens.
30. Risks and Mitigation Strategies
| Risk | Impact | Mitigation |
|---|---|---|
| Shared hosting lacks PHP 8.3+ or proper permissions | project blocked or unstable | choose a host that supports Laravel 13 prerequisites before kickoff |
| Over-customization during MVP | delivery delays | enforce phased scope and feature flags |
| High transaction volume on weak hosting | slow response times | use server-side pagination, indexes, summary tables, and upgrade path to VPS |
| Weak operational discipline around master data | inaccurate reports and stock | implement approval workflows, validations, and audit trails |
| Country-specific pharmacy regulation changes | compliance exposure | design configurable compliance rules and localize before go-live |
| Queue/cron limitations | delayed notifications and automations | use database queue, sync fallback, and manual runner tools |
| Data loss from poor backup discipline | business interruption | automate backups and test restores regularly |
| Unclear branch-level ownership | permission leakage | enforce branch/company scope in RBAC and policies |
31. Final Implementation Checklist
Foundation
- confirm hosting supports PHP 8.3+, MySQL/MariaDB, and Laravel 13
- define target edition: retail, multi-branch, wholesale, manufacturing
- finalize jurisdiction-specific compliance checklist
- approve core master data model
Technical Setup
- initialize Laravel 13 project
- configure authentication and RBAC
- establish domain folder structure
- create migration and seeding standards
- implement audit logging and settings framework
MVP Build
- implement item, supplier, customer, patient, branch, warehouse masters
- build stock receipt, transfer, adjustment, and balance flows
- build OTC sales and prescription dispensing
- implement purchase order and goods receipt
- implement low-stock and expiry alerts
- implement dashboard widgets and core reports
Enterprise Expansion
- add accounting depth and financial statements
- add SRM, warehouse, logistics, BI, and analytics
- add HR, payroll, fixed assets, budgeting
- add manufacturing, BOM, MRP, MES, and quality modules as required
Operational Readiness
- configure backups and restore procedure
- configure mail/SMS/payment integrations
- prepare training manuals and SOPs
- run UAT with pharmacists, cashiers, warehouse, and finance users
- perform security hardening and performance testing
- prepare phased go-live and support plan
Recommended Implementation Position
The strongest delivery strategy is to build this product as a Laravel 13 modular monolith with Blade-first UI, database-backed queues, file/database caching, and strict domain boundaries. That gives the project the right balance of enterprise capability, low hosting overhead, clean extensibility, and a safe migration path from shared hosting to more capable infrastructure.
Reference
- Laravel release notes: https://laravel.com/docs/13.x/releases