# ARCHITECTURE.md - PHARMATRA System Architecture

## High-Level Architecture
```
Client (Vue 3 + Inertia) <--HTTP/JSON--> Laravel App <--SQL--> MySQL
```

## Directory Structure
```
app/
├── Http/Controllers/     # Web/API controllers
├── Http/Requests/        # Form validation
├── Models/               # Eloquent models (grouped by domain)
├── Policies/             # Authorization
├── Services/             # Business logic
└── Providers/

resources/js/
├── components/           # Shared components
├── layouts/              # App/Auth/POS layouts
├── pages/                # Inertia pages
└── types/                # TypeScript types

routes/web.php            # Web routes
database/migrations/      # Schema
database/seeders/         # Seed data
```

## Request Flow (Inertia)
1. User action → Vue component
2. Inertia.visit/post/put/delete to Laravel route
3. Controller validates/authorizes/processes
4. Returns Inertia::render() or redirect
5. Vue updates without full reload

## Domain Models
- **Organization**: Business, Branch, User, Role, Permission
- **Catalog**: Product, Category, Brand, Manufacturer, Unit
- **Inventory**: StockBatch, StockMovement, StockBalance, StockAdjustment
- **Procurement**: Supplier, PurchaseOrder, GoodsReceivedNote, SupplierInvoice/Payment
- **Sales**: Sale, SaleItem, SaleItemBatch, Payment, Refund, CashierShift
- **Pharmacy**: Patient, Prescription, PrescriptionItem, Dispensing, DispensingItem
- **Finance**: Expense, ExpenseCategory, TaxRate
- **System**: AuditLog, Setting, Notification

## Key Services (to implement)
- `PosService`: cart validation, FEFO allocation, checkout transaction
- `InventoryService`: stock updates, movements, alerts
- `PurchaseService`: GRN processing, batch creation
- `PricingService`: calculations with discounts/tax
- `ReportService`: sales/profit/stock reports

## Transaction Safety
All POS sales, GRN receipts, stock transfers must use `DB::transaction()` with proper locking (`lockForUpdate()`) on stock_batches/stock_balances.

## FEFO Implementation
When allocating stock for sale:
1. Get available batches for product/branch: not expired, not quarantined, not recalled, qty_on_hand > 0
2. Order by expiry_date ASC
3. Allocate from oldest expiring first
4. Track in sale_item_batches

## RBAC
- Roles: System Admin, Pharmacy Owner, Pharmacist, Dispenser, Cashier, Storekeeper, Accountant
- Check via policies/middleware
- Permissions checked server-side

## API Structure
- Web routes for Inertia pages
- JSON endpoints under `/api/` for POS search, quick actions
- Protected by `auth` middleware

## Caching (future)
- Redis optional initially
- Cache product lists, categories if needed

## Security Checklist
- Auth required for app routes
- CSRF tokens
- SQL injection prevented by Eloquent/Query Builder
- XSS protection via Vue/Inertia
- File uploads validated
- Sensitive routes authorized

## Build & Deploy
- `npm run build` for frontend assets
- `php artisan migrate --force`
- Set proper env (APP_ENV, DB_*, APP_KEY)
- Configure backups
