# Café ERP — Codex implementation handoff

## 1. Your task

Build a working, simple Café ERP using **CodeIgniter 4 and MySQL**, following this brief, the supplied database schema, the backend scaffold and the supplied UI designs.

The café has **one location, around 12 tables and up to two workers at a time**. Keep everyday work fast: choose items in the POS, record payment, mark items prepared or handed over, and finish the order. Inventory calculations happen in the background.

Implement the admin panel, staff POS and responsive customer ordering website. This is a small café operation; separate waiter, cashier and kitchen teams are not required. The same worker can take an order, take payment and prepare it.

Use clear English labels, small functions and brief comments explaining important business rules. Implement real persistence and validation, not demonstration screens with fake success messages.

## 2. Materials and source priority

The owner will provide:

| Material | How to use it |
| --- | --- |
| This handoff | Business scope, latest decisions and implementation expectations |
| `Cafe-ERP-Database-Schema-v1.md` | Proposed entities, relationships, stock triggers and indexes |
| `Cafe-ERP-CI4-Backend-Scaffold.zip` | Starting folders, class names, models and responsibility boundaries |
| `Cafe-ERP-CI4-Backend-Structure.md` | Folder guide |
| `Cafe-ERP-UI-Screens.zip` / `Cafe-ERP-Screen-Gallery.html` | Admin, POS and customer screen layouts |
| `POS-UI-01.png`, `POS-UI-02.png` | Original POS visual references |

**Resolve conflicts in this order:** latest owner instructions → this handoff → schema → UI → scaffold placeholders.

The original schema mentions Laravel 12 in its introduction. That stack choice is obsolete: **use CI4**. Older example plans mention 24 tables and five staff; use approximately **12 tables and two workers**, with editable table/user records.

The schema is a review draft, not tested SQL. The scaffold contains placeholder controllers, empty service shells and model mappings. It has no working login, migrations or business actions. Business controller placeholders return HTTP 501, and placeholder filters deny access. Replace them with real implementations before enabling their routes.

The UI is a visual draft. Its currency, prices, report numbers, staff names and payment methods are examples. SVG import behavior varies; the SVGs do not provide native Figma Auto Layout or a working application. Recreate their layout in real HTML/CSS.

## 3. First-release scope

| Module | Required behavior |
| --- | --- |
| Access | Individual staff accounts, Manager/Staff roles and action permissions |
| Catalog | Categories, menu items, photos, prices, recipes, serving options and availability |
| Inventory | Ingredients, retail products, supplies and prepared portions; stock history, low-stock warnings and adjustments |
| Purchasing | Suppliers, order date, expected delivery, actual receipts, partial delivery, missing remainder and supplier payments |
| Production | Record portions made, consume batch ingredients and record waste |
| POS | Dine-in/takeaway, item quantities, notes, ceramic/disposable option, pay-first/pay-later, preparation, refunds and unpaid loss |
| Tables | Editable table records and QR links; display open orders and occupancy |
| Customer website | Mobile menu, unavailable labels, cart, QR order request, staff approval and scoped status page |
| Reporting | Sales, payment receipts/refunds, unpaid losses, stock activity/waste, low stock and supplier balances/delivery history |

**Later updates:** full Chart of Accounts, journals, payroll, staff advances, supplier advance payments/credits/refunds, multiple branches, reservations, delivery logistics, online payment gateways, split bills and partial refunds. Do not build these without a new owner instruction.

## 4. The central rule: payment and preparation are separate

**Payment never reduces stock by itself.** Stock reduces only when an item reaches the appropriate preparation/handover stage. Every stock action must happen exactly once.

| Event | Payment result | Stock result |
| --- | --- | --- |
| Create an order | Unpaid | No change |
| Customer pays before preparation | Paid | No change; preparation remains pending |
| Made-to-order drink marked prepared | Unchanged | Deduct its ingredients and used serving supplies once |
| Bottled product handed over | Unchanged | Deduct the product quantity once |
| Prepared cake slice handed over | Unchanged | Deduct one finished slice; do not deduct ingredients again |
| Customer pays after preparation | Paid | No second deduction |
| Cancel before preparation/handover | Cancel unpaid bill or refund paid bill | No stock was used |
| Prepared order not paid | Record unpaid loss after manager action | Used stock stays used |

The POS must visibly show **Payment** and **Preparation** separately. A single button may mark all selected pending items prepared/handed over, while the backend handles each stock type correctly.

Do not mark a paid order fully completed or release its table while preparation/handover is still pending. Normal completion requires fulfillment and full payment. Cancellation or authorized unpaid-loss closure is a separate final outcome.

### Pay first — the normal flow

1. Worker opens POS, selects table or takeaway and adds menu items.
2. POS displays the server-calculated total.
3. Worker records payment using a configured method.
4. Order becomes paid; preparation remains pending; stock does not change.
5. Worker prepares/serves items and marks them accordingly.
6. System consumes the appropriate stock once and completes the order when all items are fulfilled.

### Pay later

1. Worker creates an order and saves it unpaid.
2. Worker prepares/serves items and marks them accordingly.
3. System consumes stock once; payment remains unpaid.
4. Worker records payment later. The system completes the order without consuming stock again.
5. If the customer never pays, an authorized manager can close the remaining balance as **Unpaid loss**, with a reason.

### Refunds, cancellations and waste

- The owner currently permits a **full cancellation/refund before preparation or handover**, and no refund after that stage.
- **No partial refund in version one.** If any order item has reached its stock-use stage, the full order refund is blocked under this policy.
- An unpaid unprepared cancellation creates no food waste and no stock use.
- A customer receiving food but failing to pay creates **unpaid loss**, not automatically food waste.
- If prepared food is actually discarded, record waste. Already-consumed ingredients must not be deducted again.
- Discarding an unsold prepared cake slice reduces finished-slice stock once.
- Keep history and reasons. Do not delete paid orders or erase transactions.
- Manager corrections for mistaken preparation/payment actions remain an open decision; do not create a hidden bypass.

## 5. Inventory and recipes

### Four inventory types

1. **Ingredients:** coffee, milk, sugar, flour, syrup.
2. **Ready-to-sell products:** water bottles, cans, packaged snacks.
3. **Supplies:** disposable cups, lids, napkins and bags.
4. **Prepared portions:** cake slices or sandwiches made in advance.

Keep stock items separate from menu items. A latte is a sellable menu item with an ingredient recipe. A water bottle is a menu item pointing to a directly stocked product.

The manager enters each recipe once. Example: one latte uses 18 g coffee and 250 ml milk. Staff never type these amounts for each sale. Preserve the actual consumed quantities so later recipe edits do not change old transactions.

For a prepared batch, the worker records portions made. The system consumes that batch's ingredient inputs and adds finished portions in one transaction. Selling a portion reduces the finished stock only. The actual batch-yield rule must be confirmed before implementing it.

### Serving container

Staff can choose ceramic or disposable for a drink, whether dine-in or takeaway.

- Ceramic: reusable; ordinary use does not reduce its count.
- Disposable: consume the configured cup/lid quantities with the prepared drink.
- Broken reusable items may be recorded as damage or a stock adjustment.

The manager sets low-stock warning levels per item. Show a low-stock list. Allow the manager to enter a physical count and mandatory reason to adjust quantity; record actor, time and difference.

Use consistent base units and exact decimal quantities. Converting litres to millilitres must not change the value of a purchase. A cost per litre is not an integer cost per millilitre: preserve purchase units/conversion factors and a correctly rounded received-line amount, or use another exact representation. Audit and refine the draft pricing fields before migrations rather than silently rounding away costs.

## 6. Purchasing and supplier balance

Ordering, receiving and paying happen on different dates.

1. Manager creates a purchase with supplier, quantities, costs and expected delivery.
2. The order itself adds no stock.
3. On arrival, manager records actual accepted quantities and receipt date.
4. Stock increases only by the quantities actually received.
5. Manager can record supplier payment immediately or later.

For an order of 20 litres with 12 received, show **Partly received**, with 8 still expected. Accept later deliveries without recreating the original order.

If the supplier will not deliver the remaining 8, the manager closes that remainder as **Not delivered**, with a reason. No stock or amount owed is added for the missing goods.

Keep supplier delivery history, including expected date, actual receipt dates, ordered/received quantities and closed shortages. A partial delivery is not automatically failure if the remainder arrives as agreed.

In v1, the amount owed is based on accepted received goods minus recorded supplier payments. Block payments above the current received balance; supplier advances are deferred. Confirm any delivery charges or taxes before implementing purchase totals.

## 7. Customer ordering and table handling

Customers scan a table QR code and browse the menu without a customer account.

- Unavailable items **remain visible** with an Unavailable label and disabled Add control.
- Customer submits a request and sees Waiting for staff approval.
- Staff checks availability and accepts or rejects.
- Accepted requests use the same order, payment and inventory rules as POS orders.
- Recheck availability on the server at submission, acceptance and stock use.
- Public table/order tokens must not expose other orders or grant staff access.
- Repeated submit or network retry must not create duplicate orders.

The customer website records an order request; it does not process an online payment in v1. Payment is recorded by staff at the café.

Table occupancy follows open orders. Table count is editable. Whether one table can have multiple open bills or additional QR requests is still open.

## 8. Users and permissions

Use individual accounts with **Manager** and **Staff** roles initially. Provide actions such as view, add, edit, receive, adjust, prepare, refund and close unpaid loss. Hiding a button alone does not protect an action: enforce the same permission on its backend route.

**Proposed initial access:** staff can create orders, record payments and mark items prepared; managers additionally manage catalog, purchasing, adjustments, users, reports, refunds and unpaid-loss closure. The final matrix should be confirmed with the owner.

The scaffold and schema use different example permission names (`orders.add` versus `orders.create`). Normalize them into one documented permission catalog and use it consistently in seeds, filters, controllers and buttons. Do not seed both names accidentally.

Use CI4 session-based staff authentication for this browser application unless the existing repository already has a suitable auth solution. Validate active accounts, regenerate session IDs on login, hash passwords, protect state-changing requests from CSRF, throttle login/public requests and keep secrets outside Git.

## 9. CI4 structure and implementation standards

Follow the supplied CI4 folder guide. Preserve a working repository if one already exists; inspect it before copying the overlay or creating another appstarter.

| Layer | Responsibility |
| --- | --- |
| Controllers/Auth | Login/logout |
| Controllers/Admin | Manager requests |
| Controllers/Pos | Orders, payment and preparation |
| Controllers/Customer | Public QR menu and requests |
| Services | Small business actions and transaction boundaries |
| Models | Table mappings and focused database queries |
| Filters | Staff authentication and action permissions |
| Validation | Request rules |
| Database/Migrations | Reproducible tables, constraints and indexes |
| Database/Seeds | Permission/role/table initialization |
| Views and public assets | Admin, POS and customer UI |

Use one shared backend for all three interfaces. Do not duplicate stock calculations in JavaScript or separate them into another kitchen application.

- Keep controllers small and services focused; avoid a generic repository layer unless it solves a real need.
- Calculate prices, totals and actor identity on the server.
- Use integer minor units for money and exact decimals for quantities; no binary float stock arithmetic.
- Use transactions and locked rows for stock, receipts, fulfillment and payment changes.
- Check database transaction failure explicitly; do not assume CI4 throws for every failed query.
- Enforce unique event/request identifiers so repeated preparation, receipt or payment requests are safe.
- Keep an immutable stock history and update its cached balance in the same transaction.
- Do not hard-delete financial/stock history or expose unvalidated request bodies to model writes.
- Handle composite-key junction tables with both keys rather than assuming they have an id.
- Add missing supporting fields/indexes when justified, document the change and preserve the agreed rules.

## 10. UI requirements

Match the supplied screen hierarchy and original POS references: narrow navigation rail, category controls, photo menu grid, right-hand order details and clear primary actions.

Use the shared palette: coral `#F95630`, pale peach `#FFEFE9`, white `#FFFFFF`, off-white `#FCFBFC`, ink `#222321`. Supporting green/amber/red states should also include text labels. Inter is the proposed font.

Implement real Add/Edit/Save/Receive/Pay/Prepare/Cancel actions, validation errors, loading states, empty states and failed-request recovery. Disable repeat clicks while submitting, with server protection as well. Keep customer screens mobile friendly and POS controls easy to tap.

Currency symbols, methods, figures and photos in the mockups are examples. Use configured business values and owner-supplied content. Do not copy fake report totals into production UI.

## 11. Implementation order

1. Inspect the project and supplied materials. Summarize mismatches and gather only the required missing decisions in one short question set. Continue independent setup work.
2. Install/check CI4 and MySQL, merge the scaffold safely and create a development configuration.
3. Resolve schema arithmetic/state issues, implement migrations and seeds, then validate a fresh database.
4. Implement staff authentication and consistent action permissions.
5. Implement catalog, recipes, stock entry and supplier receipts.
6. Complete one working POS sale: order → pay → stock unchanged → prepare/handover → stock reduced once → completed.
7. Add pay-later, pre-preparation refund, unpaid-loss closure and cancellation.
8. Implement prepared batches, waste, adjustments, partial delivery and supplier payment.
9. Implement QR menu, cart, staff acceptance/rejection and customer status.
10. Connect the complete admin/ POS/customer UI and reports to actual data.
11. Run acceptance checks and leave setup, test and progress documentation.

Keep a short `docs/IMPLEMENTATION-STATUS.md` with completed work, remaining work and unresolved decisions. Do not claim a feature is complete while it still returns placeholder data or HTTP 501.

## 12. Required acceptance checks

Use meaningful automated tests for transaction/access rules and browser checks for critical user paths.

| Scenario | Expected result |
| --- | --- |
| Pay-first latte | Payment records correctly; stock unchanged until prepared |
| Prepare the same latte twice | One ingredient deduction only |
| Pay-later latte | Stock decreases on preparation; later payment does not deduct again |
| Refund paid unprepared order | Full refund, cancellation and no stock movement |
| Refund prepared order | Blocked under current policy |
| Mixed order with one fulfilled item | Partial/full refund blocked under current v1 policy |
| Customer does not pay after receiving order | Manager records unpaid loss; no repeated stock deduction |
| Make 12 cake slices | Ingredients consumed once, finished portions added |
| Sell/waste cake slice | Finished portion reduces once; ingredients not consumed again |
| Disposable cup for dine-in | Cup/lid reduce as configured |
| Ceramic cup used | No normal cup-stock reduction |
| Partial delivery: 12 of 20 | Stock +12, 8 waiting; supplier balance based on 12 |
| Close undelivered remainder | History retained; no added stock/debt |
| Two workers act on same order | Consistent payment, state and stock; no duplicates |
| Staff calls manager-only endpoint directly | Access denied even if UI button is hidden |
| Customer QR double submit | One request only |
| Unavailable item | Visible but disabled; server rejects invalid ordering |
| Quantity adjustment | Correct difference, reason and actor saved |
| Fresh installation | Migrations/seeds and documented setup work without hidden manual steps |

Reports must reconcile with stored records. Distinguish sales from payment receipts, unpaid loss from food waste, and ordered quantity from received stock. Document what each report counts.

## 13. Decisions still open

Ask for these together when they block implementation; do not treat UI samples as answers:

- Currency/decimal precision, actual payment methods, taxes/service charges and discounts.
- Final Manager/Staff permission matrix and who approves refunds.
- Batch input/output rule when actual portions differ from the recipe.
- One or multiple open bills per table; handling additional QR requests.
- Whether takeaway website ordering is needed beyond table QR.
- Whether negative stock is ever permitted, and how paid pending orders affect availability.
- Whether a paid pending order needs allocation/reservation without physical stock reduction.
- Purchase extras such as delivery fees.
- Authorized corrections for mistakes in payment/preparation.

Owner decisions already settled, including separate payment/preparation and no partial refund in v1, should not be reopened unless a real conflict prevents implementation.

## 14. Completion and final handover

Deliver a working application with setup instructions, migrations/seeds, tested core flows, connected screens and a clear list of any unresolved limitations. Document required PHP extensions, local environment configuration and how to provision the first manager without a public default password.

Run available PHP lint, framework checks and appropriate tests. State which checks actually ran. Preserve existing code and data, and avoid unrequested deployment.

Start implementing within this scope. Make routine technical decisions yourself, keep the owner informed at useful milestones and continue until the agreed first-release features work.
