# RetailOS — Phase 00: Product & System Architecture

**Status:** Draft for review · **Depends on:** none · **Blocks:** Phase 01 (UI Kit) and all later phases
**Stack assumption:** Laravel (PHP) + MySQL backend, Bootstrap 5 frontend (per Tech Stack section)

---

## 1. User Roles

| Role | Scope | Notes |
|---|---|---|
| `super_admin` | Cross-tenant | RetailOS operator team only. Manages shop approval, subscriptions, global settings. |
| `shop_owner` | Single tenant (full) | Created on shop registration. Full access to all modules within their tenant. |
| `manager` | Single tenant (scoped) | Owner-delegated access — configurable per shop (see Permission Matrix). |
| `cashier` | Single tenant (POS only) | POS, returns, basic customer lookup. No settings/reports access by default. |
| `inventory_staff` | Single tenant (stock only) | Product, purchase, stock adjustment. No POS/financial access. |
| `customer` | Online storefront only | Self-service account for the online shop (Phase 04), no dashboard access. |

## 2. Permission Matrix (module × role)

| Module | Owner | Manager | Cashier | Inventory Staff |
|---|---|---|---|---|
| Dashboard/KPIs | Full | View | — | — |
| Products/Inventory | Full | Full | View | Full |
| POS/Sales | Full | Full | Full | — |
| Purchase/Suppliers | Full | Full | — | Full (create only) |
| Customers/CRM | Full | Full | View + Create | — |
| Expenses | Full | Full | — | — |
| Reports | Full | Full (scoped) | — | — |
| Settings/Roles | Full | — | — | — |

*Rule: Manager permissions are further configurable by the owner via a `role_permissions` override table — the matrix above is the default, not a hard limit.*

## 3. Tenant Model (Multi-tenancy)

- **Strategy:** Shared database, shared schema, `tenant_id` (shop_id) column on every tenant-owned table — enforced via a global ORM scope (per ADR-001), not per-query manual filtering.
- **Identification:** Tenant resolved from authenticated user session (dashboard) or subdomain/shop-slug (online storefront).
- **Isolation guarantee:** No query may run without a tenant scope except from `super_admin` context, which is explicitly flagged and audit-logged.
- **New tenant provisioning:** Shop registration → `shops` row created (includes locked `currency_code`, per ADR-016) → default roles/permissions seeded → trial subscription plan attached.

## 4. Database ERD (core entities)

```
shops (tenant root)
 ├─ users (role, shop_id)
 ├─ products ─┬─ categories
 │            ├─ brands
 │            └─ units
 ├─ product_batches (batch_no, expiry_date, qty)
 ├─ customers
 ├─ suppliers
 ├─ purchases ─── purchase_items
 ├─ sales (POS) ─── sale_items ─── payments (split payment support)
 ├─ sale_returns ─── sale_return_items
 ├─ invoices (linked 1:1 to sales)
 ├─ expenses
 ├─ leads (CRM: New→Contacted→Interested→Confirmed→Delivered→Repeat)
 └─ subscriptions (plan_id, status, billing_cycle)

plans (global, not tenant-scoped)
subscription_payments (tenant_id, plan_id, amount, status)
```

*Full column-level ERD to be modeled in a dedicated diagramming tool before migration files are written — this is the entity-relationship skeleton for review.*

## 5. POS Transaction Flow

1. Cashier scans/searches product → added to cart (stock check against `product_batches`, FIFO by expiry)
2. Apply discount (item or cart level, permission-gated)
3. Select payment — supports split payment (cash + card + due/credit in one sale)
4. On confirm: stock decremented, `sales` + `sale_items` + `payments` rows created atomically (DB transaction)
5. Invoice auto-generated and printed/shared
6. If due/credit used → linked to customer ledger for reminders (CRM)

**Return flow:** Return references original `sale_id`, restocks batch, creates `sale_returns` row, adjusts customer ledger if refund is credit.

## 6. Inventory Rules

- Stock tracked at **batch level** (batch number + expiry), not just product level.
- Sale consumption defaults to **FIFO by expiry date** (configurable to FEFO if needed).
- Low-stock and near-expiry thresholds are **per-product configurable**, trigger dashboard alerts.
- Stock adjustments (damage, manual correction) require a reason code and are logged (audit trail), never silent quantity edits.

## 7. Invoice Numbering

- Format: `{SHOP_PREFIX}-{YY}{MM}-{SEQUENCE}` e.g. `RS-2608-000142`
- Sequence resets monthly, **per tenant** (not global) — avoids cross-tenant collision and keeps numbers meaningful per shop.
- Sequence generation must be atomic (DB-level increment or locking) to prevent duplicate numbers under concurrent POS sales.

## 8. Subscription Rules

- Plans are global (not tenant-owned); a tenant holds one active `subscription` at a time.
- Trial → Active → Grace period (on payment failure) → Suspended (read-only access) → Cancelled.
- Downgrade takes effect at next billing cycle; upgrade is immediate with prorated billing.
- Suspended tenants retain data (no deletion) — read-only dashboard access until reactivated or the retention policy period (see Legal & Compliance) expires.

## 9. API Conventions

- REST, versioned from day one: `/api/v1/...`
- Auth: Bearer token (Sanctum/Passport-style), tenant resolved from token claim.
- Response envelope: `{ "success": bool, "data": ..., "message": string, "errors": {} }`
- Pagination: `?page=&per_page=`, max `per_page` capped server-side.
- All list endpoints tenant-scoped by default; no endpoint returns cross-tenant data without explicit `super_admin` middleware.

## 10. Error-Handling Standards

- Standard HTTP status codes; no `200` on failure.
- Validation errors return `422` with field-level `errors` map.
- All exceptions logged with tenant_id + user_id + request_id for traceability.
- User-facing error messages are friendly/localized (বাংলা + English); internal stack traces never exposed to the client in production.

---

## Deliverable Sign-off Checklist
- [ ] User Roles & Permission Matrix reviewed and approved
- [ ] Tenant isolation strategy confirmed (ADR-001 reference)
- [ ] ERD reviewed, migration files can now be started
- [ ] POS transaction flow validated against real cashier workflow
- [ ] Invoice numbering format approved
- [ ] Subscription state machine approved
- [ ] API + error-handling conventions adopted as team standard

**Once every box above is checked, Phase 00 is Done and Phase 01 (UI Kit) may begin.**
