# C3S Smart Beverage Vending — System Architecture

This document is the design reference that precedes the implementation. It covers:

1. System architecture and responsibilities
2. Database relationships (ER diagram)
3. Operational state machine (state-transition diagram)
4. API communication flow (sequence diagrams)
5. Project directory structure
6. Key design decisions — including the **"no access to the Gifty server"** constraint

All diagrams are Mermaid (render in GitHub, GitLab, VS Code, Obsidian…).

---

## 1. System architecture

```mermaid
flowchart LR
    subgraph CLOUD["C3S Server (PHP 8.1+ / MySQL, HTTPS)"]
        API["REST API<br/>public/index.php"]
        SVC["Services<br/>State machine · QR sessions · Orders<br/>Payments · Dispensing"]
        ADM["Admin dashboard<br/>public/admin/"]
        CRON["Housekeeping cron<br/>(offline detection, expiry)"]
        DB[("MySQL<br/>c3s_vending")]
        API --> SVC --> DB
        ADM --> SVC
        CRON --> SVC
    end

    subgraph PI["Raspberry Pi 2 (inside the machine)"]
        PY["c3s_vending (Python, systemd)<br/>heartbeat · command poll · executor"]
        JRN[("Local journal<br/>/var/lib/c3s-vending")]
        LDS["Local display server<br/>127.0.0.1:8080"]
        KIOSK["Chromium kiosk<br/>display/index.html"]
        GPIO["GPIO driver"]
        PY --- JRN
        PY --> LDS --> KIOSK
        PY --> GPIO
    end

    CTRL["Vending machine<br/>electronic controller"]
    GIFTY["Gifty platform<br/>(external, not modified by us)"]
    CUST(("Customer<br/>phone"))

    PY -- "HMAC-signed HTTPS<br/>/api/raspberry/* /api/machine/session/*" --> API
    GPIO -- "selection pulse ↓ / busy+error ↑" --> CTRL
    KIOSK -. "shows QR" .-> CUST
    CUST -- "scans QR" --> GIFTY
    GIFTY -- "HMAC-signed HTTPS<br/>validate · products · orders · payment-confirmation" --> API
```

### Responsibilities (strict separation)

| Component | Owns | Never does |
|---|---|---|
| **C3S server** (PHP/MySQL) | Machines, products, menus, QR tokens, orders, payment *verification*, machine state machine, dispensing commands, audit | Process card payments; talk to GPIO |
| **Gifty** (external) | QR scanning, menu display to the customer, product selection, **payment processing** | Decide whether a machine dispenses; generate tokens |
| **Raspberry Pi** (Python) | Heartbeat, rendering QR, executing dispense commands on the controller, reporting *real* controller status, local journal against duplicates | Decide prices, validate payments, create sessions |
| **HTML display** | Showing the current state to the customer | Hold any credential (it only talks to `127.0.0.1`) |

### Trust boundaries

* Raspberry Pi ↔ C3S: per-machine secret, every request HMAC-SHA256 signed with timestamp + nonce (replay protection). Secret stored encrypted (AES-256-GCM) in MySQL.
* Gifty ↔ C3S: partner key + secret, same HMAC scheme. Payment notifications carry an additional **payload signature** (separate webhook secret) checked by a pluggable verifier.
* Display ↔ Pi: loopback only. The display never sees the machine secret. The QR token is only displayed as a QR (that is its purpose); it is single-use and short-lived.

---

## 2. Database relationships

```mermaid
erDiagram
    machines ||--o{ machine_products : "menu"
    products ||--o{ machine_products : "offered on"
    machines ||--o{ qr_sessions : "issues"
    qr_sessions ||--o| orders : "at most one order"
    machines ||--o{ orders : ""
    products ||--o{ orders : ""
    orders ||--o{ payments : "notifications (≤1 VERIFIED)"
    orders ||--o| dispense_commands : "exactly one when paid"
    machines ||--o{ dispense_commands : ""
    dispense_commands ||--o{ dispensing_logs : "events"
    orders ||--o{ dispensing_logs : ""
    machines ||--o{ machine_logs : ""
    admin_users ||--o{ audit_logs : "actor (admin)"

    machines {
        int id PK
        varchar machine_code UK "public id e.g. VM-001"
        enum state "11-state machine"
        varchar api_secret_enc "AES-256-GCM"
        datetime last_heartbeat_at
    }
    products {
        int id PK
        varchar sku UK
        decimal base_price
        char currency
        smallint prep_time_seconds "default 60"
    }
    machine_products {
        int id PK
        int machine_id FK
        int product_id FK
        varchar selection_code "controller channel"
        decimal price_override
    }
    qr_sessions {
        bigint id PK
        char session_uuid UK
        char token_hash UK "HMAC-SHA256 of token"
        varchar token_enc "encrypted token"
        enum status "ACTIVE RESERVED CONSUMED EXPIRED CANCELLED"
        tinyint open_flag "UNIQUE(machine_id, open_flag)"
    }
    orders {
        bigint id PK
        char order_uuid UK
        bigint qr_session_id FK,UK
        enum status
        tinyint active_flag "UNIQUE(machine_id, active_flag)"
    }
    payments {
        bigint id PK
        varchar gifty_transaction_id UK "idempotency key"
        bigint order_id FK
        enum verification_result
        enum refund_status
    }
    dispense_commands {
        bigint id PK
        char command_uuid UK
        bigint order_id FK,UK
        enum status
    }
```

Integrity guarantees enforced **by the database itself** (not just code):

| Rule | Mechanism |
|---|---|
| One open QR session per machine | generated column `open_flag` + `UNIQUE(machine_id, open_flag)` |
| One active dispensing operation per machine | generated column `active_flag` + `UNIQUE(machine_id, active_flag)` on `orders` |
| One order per QR session | `UNIQUE(qr_session_id)` |
| One command per order (no duplicate dispensing) | `UNIQUE(order_id)` on `dispense_commands` |
| Payment notification idempotency | `UNIQUE(gifty_transaction_id)` |
| An order can be paid (VERIFIED) only once | generated column `verified_order_id` + UNIQUE |
| API replay protection | `PRIMARY KEY(key_id, nonce)` on `api_nonces` |

Extra tables beyond the brief: `machine_products` (normalised per-machine menu & price), `dispense_commands` (command delivery tracking), `audit_logs`, `api_nonces`, `admin_users`.

---

## 3. Operational state machine

All transitions are validated centrally in `server/src/Services/StateMachine.php`, always under a `SELECT … FOR UPDATE` lock on the machine row.

```mermaid
stateDiagram-v2
    [*] --> OFFLINE
    OFFLINE --> INITIALIZING : first heartbeat
    OFFLINE --> MAINTENANCE : admin

    INITIALIZING --> AVAILABLE : controller OK
    INITIALIZING --> ERROR : controller fault
    INITIALIZING --> OFFLINE : heartbeat lost
    INITIALIZING --> MAINTENANCE : admin

    AVAILABLE --> QR_ACTIVE : new token generated
    AVAILABLE --> OFFLINE
    AVAILABLE --> ERROR
    AVAILABLE --> MAINTENANCE

    QR_ACTIVE --> ORDER_PENDING : Gifty validated token (session RESERVED)
    QR_ACTIVE --> AVAILABLE : unscanned QR expired (rotate)
    QR_ACTIVE --> OFFLINE
    QR_ACTIVE --> ERROR
    QR_ACTIVE --> MAINTENANCE

    ORDER_PENDING --> PAYMENT_CONFIRMED : verified payment notification
    ORDER_PENDING --> AVAILABLE : abandoned / timeout / cancelled
    ORDER_PENDING --> OFFLINE
    ORDER_PENDING --> ERROR

    PAYMENT_CONFIRMED --> PREPARING : Pi reports STARTED (controller busy)
    PAYMENT_CONFIRMED --> ERROR : FAILED / UNKNOWN / stale

    PREPARING --> DISPENSING : controller dispensing signal
    PREPARING --> COMPLETED : controller confirms completion
    PREPARING --> ERROR
    DISPENSING --> COMPLETED : controller confirms completion
    DISPENSING --> ERROR

    COMPLETED --> AVAILABLE : after completed_display_seconds
    COMPLETED --> OFFLINE
    COMPLETED --> ERROR
    COMPLETED --> MAINTENANCE

    ERROR --> INITIALIZING : admin reset (no unresolved UNKNOWN order)
    ERROR --> MAINTENANCE
    MAINTENANCE --> INITIALIZING : admin ends maintenance
```

Rules that follow from the diagram:

* **A QR token is generated only in AVAILABLE** → so never during PAYMENT_CONFIRMED / PREPARING / DISPENSING / ERROR.
* The QR is **stable** during ORDER_PENDING (session RESERVED, same token, no rotation).
* Once paid, the session becomes **CONSUMED** — the token can never be reused. After COMPLETED → AVAILABLE a brand-new token is generated.
* Network loss during PAYMENT_CONFIRMED/PREPARING/DISPENSING does **not** change the state (the Pi keeps executing and reports when it reconnects). If no report arrives within `dispense_stale_seconds`, the order becomes **UNKNOWN** and the machine **ERROR** — a timeout is never treated as success.
* ERROR blocks new sessions until an administrator resolves every UNKNOWN order (physically checked: dispensed / not dispensed) and resets the machine.

### Display states (HTML) vs machine states

| Display screen | Machine state(s) / Pi local state |
|---|---|
| 1 AVAILABLE (QR shown) | `QR_ACTIVE` with an ACTIVE session |
| 2 SESSION ACTIVE | `ORDER_PENDING` |
| 3 PAYMENT CONFIRMED | `PAYMENT_CONFIRMED` (command queued, controller not yet busy) |
| 4 PREPARING (progress) | `PREPARING`, `DISPENSING`, or Pi executor running — progress comes from the executor; never shows 100 % until the controller confirms |
| 5 COMPLETED | `COMPLETED` (controller-confirmed) |
| 6 ERROR | `ERROR`, `OFFLINE`, connection lost, executor FAILED/UNKNOWN |
| (extra) STARTING / MAINTENANCE | `INITIALIZING`, `AVAILABLE` (token being issued), `MAINTENANCE` |

### Order status lifecycle

`PENDING_PAYMENT → PAYMENT_CONFIRMED → QUEUED → PREPARATION_STARTED → IN_PROGRESS → COMPLETED`
Side exits: `FAILED`, `UNKNOWN` (admin must resolve), `CANCELLED`, `EXPIRED`, `REFUND_REQUIRED`.

---

## 4. API communication flow

### 4.1 Normal purchase cycle

```mermaid
sequenceDiagram
    autonumber
    participant PI as Raspberry Pi
    participant C3S as C3S API
    participant DSP as HTML display
    participant G as Gifty
    participant CTRL as Machine controller

    loop every 3 s
        PI->>C3S: POST /api/raspberry/machine/heartbeat (signed)
        C3S-->>PI: state=QR_ACTIVE, session{token, qr_url}
    end
    PI->>PI: build QR SVG from qr_url
    DSP->>PI: GET /api/state (1 s polling, loopback)
    PI-->>DSP: AVAILABLE + qr_version
    Note over DSP: Screen 1: "Scan to order"

    G->>C3S: POST /api/machine/session/validate {token}
    C3S-->>G: 200 session_id + menu  (machine → ORDER_PENDING)
    Note over DSP: Screen 2: "A customer is ordering"
    G->>C3S: POST /api/orders/create {session_id, product_id, quantity:1}
    C3S-->>G: 201 order_id, amount, currency (server-side price)
    G->>G: customer pays inside Gifty
    G->>C3S: POST /api/orders/payment-confirmation (signed request + signed payload)
    C3S->>C3S: verify signatures, amounts, session, idempotency
    C3S-->>G: 200 accepted, order QUEUED (machine → PAYMENT_CONFIRMED, session CONSUMED)
    Note over DSP: Screen 3: "Payment confirmed"

    PI->>C3S: GET /api/raspberry/commands/pending
    C3S-->>PI: DISPENSE command (selection A1)
    PI->>PI: journal RECEIVED → TRIGGERING (fsync)
    PI->>CTRL: pulse selection pin
    CTRL-->>PI: BUSY line asserted
    PI->>C3S: POST commands/result phase=STARTED (machine → PREPARING)
    Note over DSP: Screen 4: progress ring (~60 s)
    loop while BUSY
        PI->>C3S: phase=IN_PROGRESS progress=n
    end
    CTRL-->>PI: BUSY released, no error
    PI->>C3S: phase=COMPLETED confirmed=true (machine → COMPLETED)
    Note over DSP: Screen 5: "Your beverage is ready"
    PI->>C3S: heartbeat (after completed_display_seconds)
    C3S-->>PI: state=QR_ACTIVE, NEW token
    Note over DSP: Screen 1 with a new QR
```

### 4.2 Failure and edge paths

| Situation | Behaviour |
|---|---|
| Token unknown / expired / consumed | 404 `token_invalid` / 410 `token_expired` / 410 `token_consumed` |
| Second customer scans a reserved QR | 409 `session_in_use` |
| Customer abandons | session `reserved_until` passes → session EXPIRED, order EXPIRED, machine AVAILABLE → new QR |
| Payment notification repeated | 200 `duplicate:true`, nothing re-queued |
| Payment arrives after expiry / for an already-paid order | 409 `order_not_payable`, payment stored with `refund_status=REQUIRED` |
| Amount/product mismatch | 422 `payment_mismatch`, stored, refund flagged, nothing dispensed |
| Controller never asserts BUSY | `FAILED NOT_STARTED` → machine ERROR, refund flagged |
| BUSY longer than `max_duration` | `UNKNOWN TIMEOUT` (never success) → ERROR |
| Pi restarted mid-dispense | journal shows TRIGGERING/STARTED without result → reports `UNKNOWN` |
| Network lost mid-dispense | Pi keeps executing; results queued in persistent outbox; flushed on reconnect |
| Pi silent > `dispense_stale_seconds` | C3S marks order UNKNOWN, machine ERROR; a late COMPLETED from the Pi is still accepted and auto-recovers |

---

## 5. Project directory structure

```
c3s-vending/
├── README.md                       Installation & configuration guide
├── docs/
│   ├── ARCHITECTURE.md             (this file)
│   ├── API.md                      Endpoint reference with JSON examples
│   ├── GIFTY_INTEGRATION.md        Partner contract + what needs official Gifty docs
│   └── TESTING.md                  Test procedures & troubleshooting
├── database/
│   ├── schema.sql                  Full schema (tables, FKs, unique guards, indexes)
│   └── seed.sql                    Demo products, machine VM-001, menu
├── server/                         ── C3S backend (native PHP, no framework, no Node.js)
│   ├── config/config.example.php   Copy to config.php (outside web root)
│   ├── public/                     ← web server document root
│   │   ├── index.php               API front controller / router
│   │   ├── .htaccess               Apache rewrite + hardening
│   │   └── admin/                  Admin dashboard (index.php, admin.css, admin.js)
│   ├── src/
│   │   ├── bootstrap.php
│   │   ├── Core/                   Config, Database, Request, Response, Validator, Crypto, Clock, Money, Audit, Http, ApiException
│   │   ├── Auth/ApiAuth.php        HMAC request signing, nonce replay protection
│   │   ├── Payment/                PaymentVerifierInterface, HmacPayloadVerifier, factory
│   │   ├── Services/               StateMachine, MachineService, SessionService, ProductService,
│   │   │                           OrderService, PaymentService, DispenseService
│   │   ├── Controllers/            SessionController, ProductController, OrderController, RaspberryController
│   │   └── Admin/AdminApp.php      Dashboard pages & actions
│   ├── cron/housekeeping.php       Run every minute
│   └── tools/
│       ├── c3s.php                 CLI: generate-key, create-admin, create-machine, machine-secret, current-qr
│       └── gifty_simulator.php     Plays Gifty's role end-to-end for testing
└── raspberry/                      ── Raspberry Pi 2 (Python 3, stdlib + python3-qrcode + RPi.GPIO)
    ├── c3s_vending/
    │   ├── __main__.py             Entry point (python3 -m c3s_vending)
    │   ├── config.py               INI loader & validation
    │   ├── api_client.py           Signed HTTPS client
    │   ├── journal.py              Atomic persistent journal + outbox
    │   ├── controller.py           GPIO relay/busy driver + mock driver
    │   ├── executor.py             Dispense execution thread
    │   ├── display_model.py        Machine state → display screen mapping
    │   ├── display_server.py       Loopback HTTP server for the kiosk
    │   ├── qr.py                   QR SVG generation
    │   └── service.py              Main loop, reconnection, recovery
    ├── display/                    index.html, style.css, app.js (no framework)
    ├── config.example.ini
    ├── systemd/                    c3s-vending.service, c3s-kiosk.service
    ├── kiosk/kiosk.sh
    └── install.sh
```

---

## 6. Key design decisions

### 6.1 You do not have access to the Gifty server

This constraint shapes the integration:

* **C3S cannot change, configure or call anything inside Gifty.** Everything C3S needs from Gifty is therefore written as a **partner contract** (`docs/GIFTY_INTEGRATION.md`): the endpoints Gifty must call, the signing scheme, and the payment-notification payload. That document is what you hand to the Gifty team.
* Items that **only Gifty's official documentation or team can settle** are flagged explicitly (QR deep-link format, whether Gifty can sign webhooks with a shared secret, the exact payment status values, the refund API, a server-side transaction verification API). Nothing in the code pretends to know them; they are configuration values or a pluggable verifier.
* Until Gifty implements the contract, `server/tools/gifty_simulator.php` plays Gifty's role with exactly the same signed requests, so the whole chain (C3S ↔ Pi ↔ display ↔ controller) can be built, tested and demonstrated today.
* **Refunds** cannot be executed by C3S without a Gifty refund API. C3S records every case needing a refund (`payments.refund_status = REQUIRED`) and the admin marks it REFUNDED after handling it in Gifty.

### 6.2 Payment trust

Dispensing starts **only** after a server-to-server notification passes: (1) partner request HMAC, (2) timestamp window + one-time nonce, (3) payload signature via the configured verifier, (4) exact match with the server-side order (machine, session, product, quantity, amount, currency), (5) success status from a configurable allow-list, (6) order still payable. Customer-side redirects or "success" screens are never trusted.

### 6.3 Real controller status

The GPIO driver requires a **BUSY feedback line** from the machine's controller. Progress shown on screen is an estimate *while BUSY is asserted*, capped at 95 %; "completed" is only reported when the controller releases BUSY with no error line. If the controller offers no feedback line at all, the driver refuses to start (see README → Controller wiring) rather than guessing from elapsed time.

### 6.4 Lightweight on Raspberry Pi 2

Python 3 standard library only, plus `python3-qrcode` and `python3-rpi.gpio` from apt. Polling over HTTPS (3 s heartbeat, 2 s command poll) — no WebSockets, no MQTT broker, no Node.js.
