# Café ERP — database schema v1

**Status:** Proposed schema for review, not a migration or an implemented database. Scope: one location, about 12 tables, at most two workers at a time, simple POS, customer QR ordering, inventory, supplier purchases and basic access control. Detailed accounting and payroll are later modules.

## 1. Design rules

- MySQL 8, Laravel 12 convention: `id BIGINT UNSIGNED` primary keys, `created_at`/`updated_at`, `deleted_at` only for editable catalog records. InnoDB foreign keys for referential integrity; never cascade-delete financial or stock history.
- Money: integer minor units, e.g. `price_minor BIGINT`; `currency_code CHAR(3)` in settings and snapshots on orders/purchases if multi-currency is later required. Confirm local currency precision before migrations.
- Stock: one base unit per item (`g`, `ml`, `piece`); `DECIMAL(16,3)` quantities. Convert 1 kg to 1000 g, 1 litre to 1000 ml on receipt. Packaging may be tracked as pieces.
- Maintain `inventory_items.on_hand_qty` as a locked, transactionally updated balance for fast POS checks; append an immutable `stock_movements` row for every change. Never change balance directly without a movement.
- Payment status and preparation status are independent. **Recording payment alone does not consume stock.** Stock moves once when each made-to-order item is marked prepared, each ready-to-sell item is handed over, or a prepared portion is handed over. A batch consumes its ingredients when produced; its sale consumes a finished portion only.
- Order prices, recipes used, and stock movements must remain understandable after menu prices or recipes change.
- One open order per table is a **proposal**, not yet confirmed. The database can support several orders per table; apply an application rule only after the team decides.

## 2. Tables and important columns

### People, permissions and tables

| Table | Important columns | Purpose / rules |
| --- | --- | --- |
| `users` | `id, name, email NULL, phone NULL, password, is_active, last_login_at, timestamps` | Staff accounts; one unique non-null login identifier required. |
| `roles` | `id, code UNIQUE, name` | Seed `manager`, `staff`. |
| `permissions` | `id, code UNIQUE, description` | Action codes such as `orders.create`, `orders.cancel`, `payments.refund`, `stock.adjust`, `purchases.receive`. |
| `role_permissions` | `role_id, permission_id` composite PK | Defines role access. Buttons follow these permissions, but the server checks them too. |
| `user_roles` | `user_id, role_id` composite PK | Allows a manager to also perform staff actions. |
| `cafe_tables` | `id, label UNIQUE, qr_token_hash UNIQUE, is_active, sort_order` | Table identity; occupancy is derived from open orders, not independently edited. |
| `audit_events` | `id, actor_user_id NULL, action, entity_type, entity_id, details_json, created_at` | Reasons and actors for void, refund, stock adjustment, price and permission changes. Do not store secrets. |

Recommended permissions: `catalog.manage`, `recipes.manage`, `orders.create`, `orders.prepare`, `orders.cancel`, `payments.record`, `payments.refund`, `orders.close_unpaid_loss`, `stock.receive`, `stock.adjust`, `batches.produce`, `batches.waste`, `reports.view`, `users.manage`, `roles.manage`. Seed two roles with a clear matrix before UI design.

### Catalog, recipes and inventory

| Table | Important columns | Purpose / rules |
| --- | --- | --- |
| `menu_categories` | `id, name, sort_order, is_active` | Customer menu and POS grouping. |
| `inventory_items` | `id, sku UNIQUE, name, kind ENUM('ingredient','retail','supply','prepared'), base_unit ENUM('g','ml','piece'), on_hand_qty DECIMAL(16,3), low_stock_qty DECIMAL(16,3), is_active, timestamps` | Physical stock. A reusable ceramic cup may be counted here for breakage, but is not consumed on ordinary use. |
| `menu_items` | `id, category_id, name, description, image_path NULL, price_minor, stock_mode ENUM('recipe','direct','prepared_portion'), direct_inventory_item_id NULL, is_active, manually_unavailable, sort_order, timestamps` | What customers buy. `direct` points to a bottled product, `prepared_portion` to a cake slice, `recipe` to a made-to-order drink/meal. Unavailable items remain visible but disabled on customer menu. |
| `recipes` | `id, menu_item_id UNIQUE, version, is_active, updated_by_user_id, timestamps` | Current manager-defined recipe for each made-to-order item. Version is an aid to audit; recipe lines are copied to consumption records at preparation. |
| `recipe_lines` | `id, recipe_id, inventory_item_id, qty_per_menu_unit DECIMAL(16,3), UNIQUE(recipe_id,inventory_item_id)` | Example latte: 18 g beans + 250 ml milk. |
| `serving_options` | `id, code UNIQUE, label, is_active` | E.g. ceramic, disposable. Relevant when the item uses a serving container. |
| `serving_option_supplies` | `serving_option_id, inventory_item_id, qty_per_unit, PRIMARY KEY(serving_option_id,inventory_item_id)` | Disposable option may consume cup + lid. Ceramic has no normal consumption. |
| `batch_recipes` | `id, output_inventory_item_id, standard_output_qty, version, is_active` | Recipe for advance preparation of cake/sandwich portions; separate from menu item recipe. |
| `batch_recipe_lines` | `id, batch_recipe_id, ingredient_item_id, qty_for_standard_output` | Ingredient amounts for a standard output amount. |
| `production_batches` | `id, batch_recipe_id, batch_recipe_version, output_item_id, actual_output_qty, produced_by_user_id, produced_at, note NULL` | Worker enters actual portions made. Scale ingredient use according to agreed recipe and yield rule; see open questions. |
| `stock_movements` | `id, inventory_item_id, qty_delta DECIMAL(16,3), movement_type, source_type, source_id, source_line_id NULL, unit_cost_minor NULL, reason NULL, actor_user_id NULL, occurred_at, created_at` | Immutable stock ledger; positive receipt/production/return, negative consumption/sale/waste/adjustment. Unique event identity below prevents duplicates. |
| `stock_counts` | `id, counted_by_user_id, counted_at, note NULL` | Physical count session. |
| `stock_count_lines` | `id, stock_count_id, inventory_item_id, system_qty, counted_qty, difference_qty, reason, movement_id UNIQUE NULL` | Manager adjusts quantity to real count; movement records the difference. |

**Important:** A batch recipe consumes ingredients once during production. The `prepared` stock item gains portions then loses one on each sale or waste entry. A made-to-order menu recipe is consumed at preparation, not at order creation or payment. Serving supplies follow the actual serving option selected on that order line, regardless of dine-in/takeaway.

### Suppliers and purchasing

| Table | Important columns | Purpose / rules |
| --- | --- | --- |
| `suppliers` | `id, name, phone NULL, email NULL, is_active, timestamps` | Supplier directory and delivery history. |
| `purchase_orders` | `id, number UNIQUE, supplier_id, ordered_at, expected_at NULL, status ENUM('draft','ordered','partially_received','received','closed_short','cancelled'), created_by_user_id, note NULL, timestamps` | Placing an order does not increase stock or automatically create payable. |
| `purchase_order_lines` | `id, purchase_order_id, inventory_item_id, ordered_qty, unit_cost_minor, qty_closed_short DEFAULT 0, short_reason NULL` | Ordered amount and agreed estimate. Received quantity is summed from receipt lines; outstanding = ordered − received − closed short. |
| `goods_receipts` | `id, purchase_order_id, received_at, received_by_user_id, supplier_document_no NULL, note NULL` | An order can have several partial receipts. |
| `goods_receipt_lines` | `id, goods_receipt_id, purchase_order_line_id, received_qty, actual_unit_cost_minor, stock_movement_id UNIQUE` | Only actual accepted quantity increases stock and creates the amount owed. Validate cumulative receipt ≤ remaining order unless manager explicitly amends order. |
| `supplier_payments` | `id, purchase_order_id, amount_minor, method, reference NULL, paid_at, recorded_by_user_id` | Pay for received stock now or later. For v1, do not accept payment greater than received value minus prior payments; supplier advances are later scope. |

`amount_owed = SUM(received_qty × actual_unit_cost_minor) − SUM(supplier_payments.amount_minor)`. This v1 rule assumes no tax, delivery charge, return or supplier credit note yet; add explicit document lines if those are required. Supplier on-time/short delivery reports derive from expected, actual receipt and closed-short data. A delivery marked partially received is not automatically a supplier failure.

### POS, customer ordering and money

| Table | Important columns | Purpose / rules |
| --- | --- | --- |
| `orders` | `id, number UNIQUE, source ENUM('pos','qr'), service_type ENUM('dine_in','takeaway'), table_id NULL, created_by_user_id NULL, public_token_hash NULL, qr_request_key NULL, approval_status ENUM('not_required','pending','accepted','rejected'), order_status ENUM('open','completed','cancelled','closed_unpaid_loss'), payment_status ENUM('unpaid','partially_paid','paid','refunded'), total_minor, paid_minor, created_at, closed_at NULL, timestamps` | Staff POS or QR customer request. Public token gates order status lookup. Reject QR request before sale processing. `qr_request_key` unique per table/request to stop double submission. |
| `order_items` | `id, order_id, menu_item_id, inventory_item_id NULL, name_snapshot, unit_price_minor, quantity INT UNSIGNED, serving_option_id NULL, notes NULL, state ENUM('pending','prepared','handed_over','cancelled','wasted'), recipe_version_snapshot NULL, created_at, prepared_at NULL, handed_over_at NULL, cancelled_at NULL` | For correct partial preparation, either use **one row per physical unit** (v1 recommendation) or add prepared/handed quantity counters; one row/unit makes cancellation and one-time consumption clearer. `quantity=1` for v1; repeat rows for two lattes. |
| `order_item_consumptions` | `id, order_item_id, inventory_item_id, qty_consumed, stock_movement_id UNIQUE, trigger_stage ENUM('prepared','handed_over'), created_at, UNIQUE(order_item_id,inventory_item_id,trigger_stage)` | Frozen actual quantities used. Keeps previous orders correct when manager edits a recipe. If one ingredient appears twice through recipe and serving option, aggregate before inserting. |
| `payments` | `id, order_id, amount_minor, method ENUM('cash','card','mobile_money'), reference NULL, client_request_key UNIQUE NULL, received_by_user_id, received_at` | Receipts, including pay-first. Do not infer preparation from payment. Multiple payment rows can support mixed tender even if split bills are deferred. |
| `refunds` | `id, order_id, payment_id NULL, amount_minor, reason, approved_by_user_id, method, reference NULL, refunded_at` | v1 only **full order cancellation/refund before any order item has reached its stock-use stage**. No partial refund, per user's current decision. Refund records are separate from payments. |
| `unpaid_losses` | `id, order_id UNIQUE, amount_minor, reason, approved_by_user_id, closed_at` | Prepared/handed-over order that will not be paid. It is a financial loss, not automatically food waste. |
| `item_waste_events` | `id, order_item_id NULL, inventory_item_id NULL, qty, reason, actor_user_id, stock_movement_id NULL, created_at` | Unsold production waste or prepared item discarded. For made-to-order items, consumed ingredients are already gone: record waste outcome without deducting recipe again. For unsold batch portions, deduct portions with a movement. |

**QR scope:** Customer opens a signed/opaque table QR link, browses menu, submits a request, and sees pending/accepted/rejected status. Staff accepts before it becomes a normal order. The server rechecks availability at submission and acceptance. QR token is not staff authentication. A table's public token must not reveal other orders or customer data.

## 3. Exact stock triggers

| Action | Stock movement | Payment effect |
| --- | --- | --- |
| Place purchase order | None | None |
| Receive stock | Plus actual accepted quantity | Creates amount owed for received goods |
| Make cake batch | Minus batch ingredients; plus finished slices | None |
| Create POS/QR order | None | None |
| Pay first | None | Record payment, order paid |
| Mark made-to-order item prepared | Minus frozen recipe ingredients and consumable serving supplies, once | None |
| Hand over bottled drink | Minus one retail unit, once | None |
| Hand over prepared cake slice | Minus one finished portion, once | None |
| Pay later | None if items were already prepared/handed over | Record payment; close when settled |
| Cancel/refund entire paid order before any item reaches its stock-use stage | None | Record refund and cancellation |
| Customer leaves without paying after receiving item | No second deduction | Manager records unpaid loss |
| Discard made-to-order prepared item | No second ingredient deduction | Record waste outcome |
| Discard unsold prepared batch portion | Minus finished portion | None |
| Adjust physical count | Signed difference | None |

**Correction to earlier conversation:** In pay-first sales, payment does *not* reduce stock. Preparation or handover does. A full refund before any stock-use stage needs no stock reversal because none was consumed. Once **any** item reaches its stock-use stage, v1 disallows the entire order refund under the agreed no-partial-refund rule. Payment errors and legally required remedies need a separate manager correction workflow, to be decided.

## 4. Concurrency and consistency

1. Wrap state transition + stock movements + on-hand update + audit event in one DB transaction. Lock the order item and relevant inventory rows in consistent ID order (`SELECT ... FOR UPDATE`). Reject a repeated transition; do not deduct twice.
2. For one-time stock use, enforce a unique source event key on `stock_movements`, e.g. `event_key VARCHAR(120) UNIQUE` derived from `order_item:{id}:prepared:inventory:{id}`, `receipt_line:{id}`, or `batch:{id}:output`. Aggregate repeated ingredient use before issuing the event. The ledger and cached balance commit together.
3. Validate nonnegative stock for items that cannot be oversold; whether manager may override this needs a decision. A `pending` QR request does not reserve stock.
4. The order's `payment_status` and `paid_minor` are cached summaries reconciled from payments minus refunds. Similarly `total_minor` is a snapshot of accepted order items. Lock order on changes. Do not trust amounts submitted by browser.
5. Do not hard-delete paid orders, purchases, receipts, stock movements, payments, refunds, losses or audit entries. Use cancellation/reversal with reasons.
6. Index `orders(table_id,order_status)`, `orders(created_at,source)`, `orders(payment_status,order_status)`, `order_items(order_id,state)`, `goods_receipts(purchase_order_id)`, `stock_movements(inventory_item_id,occurred_at)`, `inventory_items(is_active,on_hand_qty)`, `purchase_orders(supplier_id,expected_at,status)`.

## 5. Worked example

Starting stock: 1000 g coffee, 10,000 ml milk, 12 cake slices, 50 disposable cups and lids.

- POS creates Table 4 order: one latte with disposable cup and one cake slice. Nothing changes yet.
- Customer pays. `payments` records the money; all stock numbers stay the same.
- Worker marks latte prepared. In one transaction: coffee 982 g, milk 9750 ml, cups 49, lids 49; movements point to the latte item. Payment stays paid.
- Worker hands over the cake slice. Slices become 11. No flour, eggs or sugar deducted now; they were used when the cake batch was made.
- If the worker presses the same action twice, the second request makes no new movements.
- Another customer pays later for a latte. Preparing it reduces recipe stock now; recording payment later changes only the money records.

## 6. Deferred modules and open decisions

**Deferred:** Chart of Accounts, journal entries, payroll, staff advances, supplier prepayments/credits/refunds, multi-location, reservations, split bills, partial item refunds, printer integration. These are not silently modeled as working v1 features.

**Confirm before migrations:**

1. Currency, price precision, taxes/service charges, discounts, and accepted payment methods.
2. Whether a pay-first paid order with nothing prepared may be refunded by staff or needs manager approval.
3. If pay-first items may be marked prepared separately, the no-partial-refund rule means one prepared item blocks a full refund; confirm this exact behavior with the team.
4. How to count batch output when actual yield differs from the standard recipe: use fixed recipe input per batch or scale ingredient input to reported output.
5. Whether QR customers can place additional requests on an occupied table, and whether one table can have more than one open bill.
6. Whether website ordering includes takeaway without a table QR; how the café verifies pickup.
7. Whether stock may temporarily go negative and who can override availability.
8. Whether a supplier bill may include tax, delivery fee or price differences beyond accepted goods.
9. Legal refund obligations and how managers correct a mistaken prepared action or payment without deleting history.

**Next planning step:** Approve these schema choices, then design the actual admin panel, POS and customer ordering screens around the two-person workflow.
# Installed implementation additions

The live schema is maintained by CI4 migrations; the original draft above remains reference material. Confirmed owner choices and current behavior are recorded in BUSINESS-RULES.md.

- `production_batch_inputs` stores each actual ingredient quantity and unique stock movement for a batch. Actual output can be zero for a failed batch.
- `cafe_tables.qr_token_encrypted` preserves recoverable printable capabilities; `qr_token_hash` validates public table links.
- `orders.accepted_at` distinguishes QR acceptance from submission; `rejection_reason` is safe scoped customer feedback.
- Purchase/receipt lines preserve purchase units, exact conversion, actual accepted cost and received amount; supplier payments use unique request keys.
- Bills use non-null request keys and one item row per physical unit. Stock/financial histories are append-only.
