Compare commits

...
38 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 e55157fa86 feat(menu-app): the QR menu on the customer apps' look, two languages, allergens (platform-v2 step 6.5)
- connect_frontend/menu-app rebuilt like the order app: the same tokens (index.css,
  tailwind.config.js), texts in i18n.js (en, el; the old 'ot_lang' choice carries over), pure
  logic in src/logic.js with tests (menuFor in the guest's language, QR prices, search in either
  language, cart, order body, refusals). MenuPage (menu, search, dish sheet, cart, checkout at
  the table) and ConfirmPage; App.jsx, components/primitives and OrderConfirm removed;
  react-hot-toast dropped.
- Allergens on every dish (contains on the card; contains / may contain on the dish sheet) and
  in the order app's cards too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:27:05 +02:00
bonaminandClaude Opus 5.5 9f9b882806 feat(menu-app): the QR menu and the order app in the guest's language (contract C-2 names, platform-v2 step 6.4)
The site now sends names / descriptions {el, en} per product, quick option and category
(falling back to the text as typed). The menu app maps them onto its en / gr switch (byLang);
the order app localises its menu by the guest's language (localizeMenu, tested). The menu app
also reads 6.3's allergens object (what a product contains).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:46:59 +02:00
bonaminandClaude Opus 5.5 e0158b2c72 test(cloud): the public menu carries each product's allergens (contract C-2, platform-v2 step 6.3)
The snapshot is stored as the site sends it, so `allergens` {key: contains | may_contain}
reaches GET /api/menu/{site} for the QR menu and the order app without a cloud change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:04:20 +02:00
bonaminandClaude Opus 5.5 7ee059d834 feat(sysadmin): the venue's menu and ordering links from PUBLIC_APPS_URL; 3S pack notes
Plan phase 3S, step S.99.
- SiteOut.apps_url (the cloud's PUBLIC_APPS_URL; a Site property, not stored per site).
- Sysadmin site page: the QR menu and online ordering links/QR codes are built from it
  (were a hard-coded IP and a "/menu/<site>/order" route that never existed); a note when
  PUBLIC_APPS_URL isn't set, and that table codes are printed by the venue.
- Pack README: connect_frontend and /api/menu rows for phase 3S, CL-9 (rate limits are per
  process), CL-10 (table QR tokens: hashes only).
- Test: the sysadmin gets the apps address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 01:35:50 +02:00
bonaminandClaude Opus 5.5 2835b5dc68 feat(cloud): the QR menu at the table, ordering only with a table's QR code
Plan phase 3S, step S.7.
- services/qr.py: the snapshot's `qr` {ordering, tables: [{id, label, token_hash}]} (sha256
  of each table's token; the cloud never holds the tokens). A table order (dine_in) needs
  the venue's ordering on, the site's menu_mode "order" and a valid table token: otherwise
  order.service_unavailable / 403 order.table_invalid (a forged, old or typed-in table is
  refused). The order keeps the table's id and label (online_orders.table_id, migration 0006).
- Public menu: ?t=<token> → `table` {id, label} or `table_invalid`; `table_ordering`; `qr`
  never leaves the cloud.
- Heartbeat returns `apps_url` (new setting PUBLIC_APPS_URL: where /menu/ and /order/ are
  served) so sites can print table QR codes that open the right address.
- Menu app: the table from its QR code (kept for the visit), a "Table 5" banner, ordering
  only at a real table (otherwise read-only, with a notice for an invalid code); checkout
  without a typed table number; prices are the QR menu's (sales point qr_table — it showed
  in-store prices since S.1 removed digital_price) and only products sold there; the
  confirmation page for table orders (in the kitchen); the delivery/takeaway leftovers
  removed (they have their own app since S.4); test ids for e2e.
- Tests: tests/test_qr.py (3); test_checkout's typed-table case moved there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 01:26:33 +02:00
bonaminandClaude Opus 5.5 3459c80611 feat(cloud): table bookings online, with food ordered ahead
Plan phase 3S, step S.6.
- New order types "reservation" (a table only, no items) and "preorder" (a table with food,
  priced at the online_preorder sales point); online_orders.party_size (migration 0005).
- services/ordering.py: the venue's booking settings (ordering.reservations in the snapshot):
  hours (none = any time), time grid, notice, days ahead (≤ 90), party size; res_slots per
  venue day, res_days, res_check (order.service_unavailable, order.party_invalid,
  order.time_invalid). The public menu's ordering summary gains `reservations`
  {enabled, with_food, party_max, days}; GET /api/orders/{site}/reservation-slots?day=.
- Bookings need a phone; a plain booking refuses items (order.items_not_allowed).
- Status steps for bookings: pending_acceptance → accepted | rejected; accepted → delivered
  (arrived) | cancelled (by the venue); ordinary orders unchanged.
- Order app: "Book a table" (people, day, time, optional food at the pre-order prices),
  booking summary at checkout, a booking tracking page (waiting, confirmed, welcome;
  declined / cancelled with the reason). en/el.
- Tests: tests/test_reservations.py (3), order-app logic test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:31:21 +02:00
bonaminandClaude Opus 5.5 9ccb47cfd1 feat(cloud): online orders keep the delivery area's id for the site's fee check
The site checks the cloud's delivery fee with its own engine when it pulls an order (plan
phase 3S, step S.5) and needs the area by id: a name can change between a menu push and
the order. New column online_orders.delivery_area_id (migration 0004), set from the priced
cart, and in the pending-orders payload (C-4, additive).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:38:00 +02:00
bonaminandClaude Opus 5.5 b25bfcda3e feat(cloud): the online ordering app (takeaway, delivery) with hours, time slots and rate limits (platform-v2 3S, S.4)
- connect_frontend/order-app at /order/{site}: menu per service at that service's prices,
  extras, basket (kept per tab), checkout priced by the cloud (fee, area by list or
  postcode, minimum), name/phone/address/notes (remembered), as soon as possible or a time
  slot, tracking page with steps, lines and totals; en/el; tokens in index.css. Logic in
  src/logic.js, unit-tested; built and served by the connect image (npm test in the build).
- services/ordering.py: the venue's services, hours (past midnight), preparation, slot grid,
  days ahead, ASAP; takeaway/delivery orders checked (order.service_unavailable,
  order.closed, order.time_invalid) and need a phone; GET /api/orders/{site}/slots; the
  public menu carries the ordering summary.
- services/ratelimit.py: per-caller limits on quote, order and track (429 rate.limited).
- online_orders.requested_for (0003, unreleased) stored as UTC; every datetime sent with its
  offset (the database keeps no zone: a 12:00 Athens slot came back as 12:00 unzoned).
- Tracking returns what was ordered, the totals, the type and the time.
- Tests: test_ordering.py (5), checkout/fees updated; order-app unit (4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:39:00 +02:00
bonaminandClaude Opus 5.5 9e8ec4c4e6 docs: CL-8 the fee engine has two copies (pack README)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:29:43 +02:00
bonaminandClaude Opus 5.5 96f16e948d feat(cloud): delivery fees and minimum orders at checkout (platform-v2 3S, S.3)
- services/fees.py: the site's fee engine, byte-identical (the site's tests check it);
  tests/fixtures/fee_cases.json: the shared cases, run here too.
- checkout: the snapshot's fees (areas, rules) at the venue's time zone; refused
  order.area_not_served / order.minimum_not_met {minimum, subtotal}; quote and order take
  area_id / postcode and return area_name, fee_rules; the order stores delivery_area.
- GET /api/menu/{site}: delivery_areas [{id, name}] for the customer; the rules and
  postcodes are never sent to the browser.
- Alembic 0003 (unreleased) gains online_orders.delivery_area.
- Tests: test_fees.py (22 shared cases + checkout fees, refusals, public menu, clock).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:28:15 +02:00
bonaminandClaude Opus 5.5 5bdd19d9fb feat(cloud): the cloud prices online orders itself; sites only touch their own data (platform-v2 3S, S.2)
- services/checkout.py: orders and quotes priced from the site's snapshot per sales point
  (prices map; older snapshots: digital_price less discount); refused: unavailable or
  not sold there, bad quantity/option/type, empty, order.price_changed when the browser's
  unit price or total differs. Nothing the browser says about money is stored.
- POST /api/orders/{site}/quote; delivery needs phone + address.
- Fixes: pending orders, menu sync and stats snapshot acted on the site_id given, not the
  authenticated site (a site could read another's orders or overwrite its menu/stats).
- Order refs are unique per site (a second site's first order failed); tracking by a
  random token GET /api/orders/track/{token}; old /status/{ref} only while unambiguous.
- Alembic 0003: online_orders sales_point, table_label, tracking_token; table rebuilt.
- menu-app: tracking link uses the token, shows the order number; tells the customer when
  the menu changed or the order failed.
- Tests: test_checkout.py (6), 0003 data migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:38:37 +02:00
bonaminandClaude Opus 5.5 2541a5782e fix(menu-app): show a product once in search when it's listed in several categories
Platform v2 step 1.13 (D-23): the site's menu snapshot can list the same product under several categories. Search flattened all categories, so such a product appeared twice (and with a duplicate React key). Category sections still show it in each category; cart lookups already used the first match. npm run build passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:38:54 +02:00
bonaminandClaude Opus 5.5 48fd10df77 feat(cloud): Alembic, license token v2 with modules, plan presets, module editor
Platform v2 step 1.7 (APPS_PLATFORM D-3, D-20, D-21, D-22, §5.2).
- Alembic replaces create_all + _run_migrations. 0001_cloud_baseline is
  exactly the v1 production schema (incl. the dead menu_hours_en/_gr), checked
  against a frozen fixture; schema.py refuses an unstamped v1 DB, so prod is
  stamped once at cutover (DEPLOYMENT_GUIDE Part 6)
- 0002_v2_licensing: sites.modules (JSON), sites.module_catalog(_at),
  plan_presets; existing sites get every module v1 had (KDS unlimited); the
  same map is seeded as preset "Everything (v1 sites)"; dead columns dropped
- license token v: 2 with a normalized `modules` map
- heartbeat v2: request {version, local_ip, module_catalog} (catalogue stored
  per site); response {license_token, latest_version, waiter_domain,
  site_numeric_id} - the unsigned v1 license fields are gone
- sites API: create with a preset, PUT /{id}/modules (validated),
  POST /{id}/apply-preset/{preset}; /api/presets CRUD
- sysadmin panel: Licensed modules card per site (built from the reported
  catalogue, fallback list), preset picker on register, Presets page
- .dockerignore: local *.db, .env and tests no longer baked into the image
- tests (new): baseline = v1, unstamped refused, stamp+upgrade of a v1 DB,
  drift, token v2 shape/signature, module edits, presets; CL-2/CL-7 rules

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:27:47 +02:00
bonaminandClaude Opus 5.5 048b46af41 docs: CL-6 - the license signing key is permanent (back up, never rotate casually)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 22:17:29 +03:00
bonaminandClaude Opus 5.5 96a014ecbe feat(cloud): heartbeat returns a signed license token (Ed25519)
Sites now enforce their license offline (client-services KI-006): the
cloud is needed to renew a license, not to run it. Each heartbeat carries
license_token = base64url(payload).base64url(signature), payload
{v:1, site_id, active, locked, lock_reason, expires_at, issued_at}, signed
with LICENSE_SIGNING_KEY (base64 raw Ed25519 private key, cloud .env). The
matching public key is built into the site code, so a stored token can't be
edited and a clock can't be set before issued_at unnoticed.

Additive field only (old sites ignore it). Without the key the field is
null and a warning is logged. Pins cryptography==46.0.4 (was transitive).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 22:16:32 +03:00
bonaminandClaude Opus 5.5 15331cdccf chore: label waiter domain as legacy in sysadmin; document bonamin.net hosts
Per-client domains are retired (client-services plan step 9); the field
and column stay for sites not yet migrated (never drop columns).
Documents xenia-api / xenia-admin / registry .bonamin.net.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 19:06:32 +03:00
bonaminandClaude Opus 5.5 d323be1088 docs: add pack README with VPS rules, router/auth map and commands
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 17:52:55 +03:00
bonaminandClaude Sonnet 5 7a53cc3d66 feat: receive and serve product images pushed from local sites
New POST /api/menu/sync-image (site-authenticated) accepts a product's
image file, stores it under /app/data/product_images keyed by
(site, product_id), and skips the write entirely if the uploaded
content hash matches what's already stored. GET /api/menu/{site_slug}
now injects the cloud-hosted image URL into each product that has no
manual digital_image_url override — replacing the local-only image_url
from the snapshot, which was never reachable from the public internet.

Also fixes the menu-app resolving product image URLs as bare relative
paths instead of prefixing them with the cloud API origin (same class
of bug as the earlier header-image fix).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19 20:57:00 +03:00
bonaminandClaude Sonnet 5 6c7df8d011 fix(menu-app): replace EN|ΕΛ pill with a compact globe icon + dropdown
The two-segment language pill sat over the header image/logo area and
clipped it. Swapped for a small globe icon button tucked closer to the
corner, opening a lightweight dropdown with full language names on tap.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19 11:16:18 +03:00
bonaminandClaude Sonnet 5 a73f081ca1 fix: QR menu branding fields — display name, header image, empty-to-hide
- menu_display_name is now separate from the site's internal name (was
  incorrectly showing the sysadmin-only site name on the public menu).
- Header image now resolves against the cloud API origin instead of
  the menu-app's own origin, fixing the broken-image icon.
- Tagline/blurb/hours now genuinely hide when cleared: the sysadmin
  save handler was converting empty fields to null, which the PUT
  endpoint's exclude_none silently drops instead of clearing.
- Added a settable blurb (EN/GR) below the tagline, previously
  hardcoded ("Fresh seasonal plates, served with care.").
- Collapsed hours from two fields (EN/GR) to one — opening hours don't
  vary by language.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19 10:44:28 +03:00
bonaminandClaude Sonnet 5 f5736b85cb fix(menu-app): crash when tagline/hours fields are null
The API now always sends restaurant.tagline/blurb as {en, gr} objects,
including when a site hasn't set them yet (both null). The old
`?? r.tagline` fallback rendered the whole object as a React child in
that case (React error #31) instead of falling back to a display
string. Fall back to the localized fallback string instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19 10:22:43 +03:00
bonaminandClaude Sonnet 5 d87540e08f feat: per-site QR menu mode (order vs view-only) + editable branding
Adds a sysadmin-configurable toggle so sites can disable online ordering
on the public QR menu until it's fully supported, plus editable
tagline/hours and a header image (replacing the hardcoded "Our Menu"
placeholder) — all previously hardcoded frontend strings.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19 09:59:35 +03:00
bonamin 0cad6a76d3 change the QR Code URl. Just a quick fix 2026-06-01 20:06:46 +03:00
bonaminandClaude Sonnet 4.6 a6f759bf49 fix(menu-app): 6 UI adjustments
1. Font consistency: add Noto Sans as fallback for both display and body
   fonts so Greek characters render in the same visual weight as Latin
2. Category panel gradients: reduce top opacity 0.85 → 0.65 (20% less)
3. Mobile full-width: remove max-w cap on mobile; sm:max-w-[960px] on
   desktop (2× wider than before); shadow only on sm+ breakpoint
4. Smaller Add button (h-9→h-8, text-13→12) and price (22px→18px)
5. More spacing between description and footer hairline (pt-3 mt-3)
6. Square hero image in product detail sheet (aspect-square instead of h-44)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 16:23:40 +03:00
bonaminandClaude Sonnet 4.6 ffaeab136d feat(menu-app): full redesign to Olive & Thyme design spec
Rebuild the public-facing digital menu from the design handoff bundle.
Matches high-fidelity spec: Bricolage Grotesque + Hanken Grotesk fonts,
cream/green/gold palette, per-category tinted panels, product cards with
gradient art, tag icon badges, bottom-sheet product detail, search overlay,
cart → checkout bottom-sheet flow posting to real API, floating cart button
with bump animation, and restyled order-confirm page.

- New: src/components/primitives.jsx (DishArt, Badge, DietChip, TagIcons,
  Price, DiscountFlag, Stepper, price helpers)
- Rewrite: MenuPage.jsx — all screens in one component tree, API-driven,
  lang toggle (EN/GR) persisted to localStorage, scroll-spy category bar
- Rewrite: OrderConfirm.jsx — design-system styling, brand colors
- Update: App.jsx — remove /order route (cart flow is now a bottom sheet)
- Update: tailwind.config.js — font families, brand tokens, animations
- Update: index.html — Google Fonts for Bricolage Grotesque + Hanken Grotesk
- Delete: CartPage, ProductModal, ProductCard, CategoryNav, CartButton

Cart checkout POSTs to real submitOrder API and redirects to /confirm/:ref
for live order status polling. Restaurant info falls back to hardcoded
placeholder until backend includes it in the fetchMenu response (see
REWORK_REVISIT.md).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 15:55:52 +03:00
bonaminandClaude Sonnet 4.6 17fb3a2589 fix(sysadmin): use site_id UUID string instead of integer PK throughout manager endpoints
The sysadmin panel URL uses site.site_id (UUID string) not site.id (int PK).
All manager account endpoints were querying/expecting the integer PK — none matched.

- GET /by-site/{site_id}: param type str, filter by Site.site_id
- POST /register: site_ids type list[str], query Site.site_id.in_()
- DELETE /site-access: site_id type str, query Site.site_id
- schemas/manager.py: ManagerRegisterRequest.site_ids list[int] → list[str]
- SiteDetailPage.jsx: remove Number() casts on siteId in add/remove calls

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 10:45:10 +03:00
bonaminandClaude Sonnet 4.6 70c7b9564b feat(manager-app): Part 5 — show snapshot_taken_at freshness in DashboardPage
Adds a "Site data: X min ago" line derived from snapshot.snapshot_taken_at
so managers can see how fresh the stats snapshot is.

All other Part 5 items (menu-app api.js, OrderConfirm polling, manager-app
api.js, IncomingOrdersPage 15s poll + OrderCard actions) were already fully
implemented in the existing scaffolding.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 10:10:08 +03:00
bonaminandClaude Sonnet 4.6 82b853369b feat(sysadmin): Part 4 — QR code section in SiteDetailPage
- Install qrcode.react in sysadmin_panel
- Add QR Codes section above Remote Managers with two codes side by side:
  Menu QR (https://yourdomain.com/menu/{site_id}) and
  Order QR (https://yourdomain.com/menu/{site_id}/order)
- Each card shows the URL as copyable text and a Download PNG button
- Uses site.site_id as the slug (no slug field exists on the Site model)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 10:07:28 +03:00
bonaminandClaude Sonnet 4.6 ac58d150ea feat(sysadmin): Part 3 — Remote Managers section in SiteDetailPage
Backend (manager_auth.py):
- register: upsert instead of 409 — if email exists, just add site access
- GET /api/manager/by-site/{site_id}: list managers linked to a site (admin auth)
- DELETE /api/manager/site-access: remove a manager's access to a site (admin auth)

Sysadmin API client:
- getManagersBySite, addManagerToSite, removeManagerSiteAccess

SiteDetailPage.jsx:
- Remote Managers section: lists all linked managers with email, name, active badge
- Add Manager modal: email + full name + password form (password ignored if account exists)
- Remove access button with optimistic removal from list

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 10:04:28 +03:00
bonaminandClaude Sonnet 4.6 b45a93a559 feat(connect): Phase 7 — Docker & nginx for connect_frontend
connect_frontend/Dockerfile
  Multi-stage build: node:20-alpine builds both menu-app and
  manager-app in parallel stages, then nginx:alpine serves both
  dist folders under /menu and /manage respectively.
  VITE_CLOUD_URL passed as build arg so the API URL is baked
  in at build time (standard Vite pattern).

connect_frontend/nginx-connect.conf
  Single nginx server block:
    /menu/   → /usr/share/nginx/html/menu  (SPA fallback)
    /manage/ → /usr/share/nginx/html/manage (SPA fallback)
    /health  → 200 ok

nginx-connect.conf
  Kept at cloud-service root for reference / standalone use.

docker-compose.yml
  connect_frontend service added:
    - build context: ./connect_frontend
    - VITE_CLOUD_URL passed from root .env
    - port 3100:80
    - depends_on cloud_backend

Individual Dockerfiles also added to menu-app/ and manager-app/
for standalone builds if needed.

To deploy:
  docker compose build connect_frontend
  docker compose up -d connect_frontend

  Public menu:    http://<host>:3100/menu/<site_slug>
  Manager app:    http://<host>:3100/manage/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 01:00:56 +03:00
bonaminandClaude Sonnet 4.6 7d75ef44f7 fix: explicitly import Site in manager_account to resolve relationship
SQLAlchemy couldn't resolve the string 'Site' in ManagerAccount's
relationship() at query time because Site wasn't guaranteed to be
imported first. Adding the explicit import ensures the mapper is
configured correctly regardless of import order.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 00:57:02 +03:00
bonaminandClaude Sonnet 4.6 3598a929e0 fix: switch admin auth to HTTPBearer for consistent Swagger UI
Same fix as manager_auth — OAuth2PasswordBearer was showing an OAuth2
form in Swagger instead of a plain Bearer token input, causing
'Not authenticated' when testing via the docs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 00:54:30 +03:00
bonaminandClaude Sonnet 4.6 f291234c14 fix: switch manager auth from OAuth2PasswordBearer to HTTPBearer
OAuth2PasswordBearer caused Swagger UI to show a username/password/
client_id form instead of a simple token input, making the docs
unusable for testing. HTTPBearer shows a plain 'Bearer token' field,
consistent with how the local_backend handles auth.

No runtime behaviour change — token extraction is identical.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 00:49:09 +03:00
bonaminandClaude Sonnet 4.6 6c5e35d537 fix: use AppData path for SQLite DB on Windows, absolute path on Linux
The default sqlite:////app/data/cloud.db path only works inside Docker.
On Windows, Controlled Folder Access blocks writes to arbitrary paths.

Now mirrors the same pattern as local_backend/config.py:
  - Windows: %LOCALAPPDATA%/xenia_cloud/cloud.db (always writable)
  - Linux/Docker: next to main.py (overridden by DATABASE_URL in .env)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 00:38:50 +03:00
bonaminandClaude Sonnet 4.6 12bd589bb7 feat(connect): Phase 6 — menu-app and manager-app frontend SPAs
Two Vite + React 18 + Tailwind apps under connect_frontend/.
Both use React Router v6, Axios, react-hot-toast, and Lucide icons.
Neither uses localStorage — tokens live in sessionStorage (manager-app)
or component state (menu-app cart).

── menu-app (public menu + ordering) ──────────────────────────────

Routing (basename /menu):
  /:siteSlug              → MenuPage
  /:siteSlug/order        → CartPage
  /:siteSlug/confirm/:ref → OrderConfirm

Pages:
  MenuPage      — fetches menu snapshot, category nav tabs, product
                  cards; floating CartButton; opens ProductModal
  ProductModal  — quantity picker, quick-option toggles, price/discount
                  display, "Add to order" with line total
  CartPage      — order type selector (dine_in/delivery), customer
                  details form, cart summary, submits to cloud API
  OrderConfirm  — polls GET /api/orders/status/:ref every 10s;
                  renders status icon + label; stops polling on
                  terminal states (delivered/rejected)

Components:
  CategoryNav   — horizontal scrollable pill tabs
  ProductCard   — image, name, description, price with discount badge;
                  greyed + "Out of stock" badge when unavailable
  CartButton    — fixed bottom bar with item count + total

── manager-app (remote dashboard) ─────────────────────────────────

Routing (basename /manage):
  /login              → LoginPage
  /                   → SiteSelectorPage (auto-navigates if one site)
  /:siteId            → DashboardPage
  /:siteId/orders     → IncomingOrdersPage
  /:siteId/orders/history → OrderHistoryPage
  /:siteId/orders/:id → OrderDetailPage
  RequireAuth wrapper redirects to /login if no sessionStorage token

Pages:
  LoginPage          — email/password → POST /api/manager/login;
                       stores JWT in sessionStorage
  SiteSelectorPage   — lists accessible venues; auto-selects if one
  DashboardPage      — polls snapshot + pending orders every 15s;
                       2×2 stat grid + pending order list
  IncomingOrdersPage — polls pending orders every 15s; order cards
  OrderDetailPage    — full order detail; Accept/Reject with optional
                       rejection reason; lifecycle progression buttons
                       (Preparing → Ready → Delivered etc.)
  OrderHistoryPage   — all orders with status filter tabs

Components:
  RequireAuth   — route guard using sessionStorage token
  StatCard      — labelled metric tile
  StatusBadge   — colour-coded status pill
  OrderCard     — summary card linking to OrderDetailPage
  (no OrderCard uses useParams to get siteId for nav — wired correctly)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 00:25:28 +03:00
bonaminandClaude Sonnet 4.6 abe7f4ff0d feat(connect): return site_numeric_id in heartbeat response
Local backend needs the cloud DB integer PK to call Connect API
endpoints (menu sync, order pending poll). Heartbeat is the only
authenticated channel available at startup, so we piggyback the id
there rather than adding a new endpoint.

Changes:
  - schemas/site.py: site_numeric_id: int | None added to HeartbeatResponse
  - routers/heartbeat.py: site_numeric_id=site.id included in response

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 00:11:48 +03:00
bonaminandClaude Sonnet 4.6 cd8a6c53cf feat(connect): Phase 3 — cloud API routes for Xenia Connect
Adds four new routers, three schema files, and one new model.
All new endpoints use new URL prefixes — no existing routes touched.

routers/menu.py
  GET  /api/menu/{site_slug}     — public menu snapshot (no auth)
  POST /api/menu/sync            — upsert snapshot (site API key)

routers/orders.py
  POST /api/orders/{site_slug}         — customer places order (public)
  GET  /api/orders/status/{public_ref} — customer tracks order (public)
  GET  /api/orders/pending/{site_id}   — local backend polls (site key)
  POST /api/orders/{id}/synced         — mark synced (site key)
  PATCH /api/orders/{id}/status        — update status with transition
                                         validation (site key)

routers/manager_auth.py
  POST /api/manager/register  — create manager account (admin JWT)
  POST /api/manager/login     — returns manager JWT
  POST /api/manager/refresh   — refreshes manager JWT
  Shared _get_current_manager dependency used by remote_dashboard

routers/remote_dashboard.py
  GET  /api/remote/sites                           — manager JWT
  GET  /api/remote/sites/{id}/snapshot             — manager JWT
  GET  /api/remote/sites/{id}/orders               — manager JWT
  GET  /api/remote/sites/{id}/orders/pending       — manager JWT
  PATCH /api/remote/sites/{id}/orders/{oid}/status — manager JWT
  POST /api/remote/snapshot                        — site API key
                                                     (stats push)

models/stats_snapshot.py (NEW)
  stats_snapshots table — one row per site, holds serialized
  operational stats; created by create_all on startup

config.py / .env.example
  MANAGER_JWT_SECRET and MANAGER_JWT_EXPIRE_HOURS (default 72h)
  added as separate settings from the admin SECRET_KEY

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 00:05:48 +03:00
bonaminandClaude Sonnet 4.6 835806f92d feat(connect): Phase 2 — cloud DB models for Xenia Connect
Adds three new tables created automatically by create_all on next
startup, plus an additive migration for an existing table:

models/menu_snapshot.py (NEW)
  - menu_snapshots: one row per site, holds the full serialized
    category+product JSON; upserted on each sync from local_backend

models/online_order.py (NEW)
  - online_orders: full order lifecycle from customer submission
    through delivery; tracks sync state so local_backend can poll
    for unprocessed orders (synced_to_local=0)

models/manager_account.py (NEW)
  - manager_accounts + manager_site_access (M2M join table): remote
    manager login accounts with per-site access control

models/site.py (MODIFIED)
  - order_counter column added; incremented atomically when each
    online order is created to generate "ORD-XXXX" public_ref values

main.py (MODIFIED)
  - imports all three new models so create_all registers their tables
  - _run_migrations() added (same pattern as local_backend) for the
    additive order_counter column on the existing sites table

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 00:01:02 +03:00
120 changed files with 13664 additions and 35 deletions
+4
View File
@@ -0,0 +1,4 @@
# cloud-service
Read [docs/README.md](docs/README.md) (pack rules) and the global [../docs/README.md](../docs/README.md) (Working Rules) before making changes.
This is its own git repo. Commit here first, then bump the pointer in the parent `xenia-pos` repo.
+6
View File
@@ -0,0 +1,6 @@
# Never bake local data, secrets or tests into the image
*.db
*.db-*
.env
__pycache__/
tests/
+10
View File
@@ -15,3 +15,13 @@ ADMIN_PASSWORD=changeme
# The current latest release version — clients compare against this to detect updates # The current latest release version — clients compare against this to detect updates
LATEST_VERSION=0.0.0 LATEST_VERSION=0.0.0
# Xenia Connect — manager JWT (use a different secret from SECRET_KEY)
# Generate with: python -c "import secrets; print(secrets.token_hex(32))"
MANAGER_JWT_SECRET=change-me-manager-secret
MANAGER_JWT_EXPIRE_HOURS=72
# Where customers open the apps (connect_frontend: /menu/ QR menu, /order/ online ordering),
# e.g. https://menu.example.com. Sent to sites with the heartbeat: their table QR codes and
# ordering link point here. Empty = sites use their CLOUD_URL.
PUBLIC_APPS_URL=
+8
View File
@@ -0,0 +1,8 @@
# Alembic CLI config for cloud_backend (APPS_PLATFORM D-22). The app calls schema.py itself.
# cd cloud_backend
# alembic revision --autogenerate --rev-id 0003_short_name -m "what changed" # then REVIEW it
# alembic upgrade head
# Production cutover (once): alembic stamp 0001_cloud_baseline && alembic upgrade head
[alembic]
script_location = migrations
file_template = %%(rev)s
+4 -4
View File
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta, timezone
from jose import jwt, JWTError from jose import jwt, JWTError
from passlib.context import CryptContext from passlib.context import CryptContext
from fastapi import Depends, HTTPException, status from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from config import settings from config import settings
@@ -10,7 +10,7 @@ from database import get_db
from models.admin import Admin from models.admin import Admin
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login") _bearer = HTTPBearer()
ALGORITHM = "HS256" ALGORITHM = "HS256"
@@ -29,9 +29,9 @@ def create_access_token(data: dict) -> str:
return jwt.encode(payload, settings.SECRET_KEY, algorithm=ALGORITHM) return jwt.encode(payload, settings.SECRET_KEY, algorithm=ALGORITHM)
def get_current_admin(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> Admin: def get_current_admin(credentials: HTTPAuthorizationCredentials = Depends(_bearer), db: Session = Depends(get_db)) -> Admin:
try: try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[ALGORITHM]) payload = jwt.decode(credentials.credentials, settings.SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub") username: str = payload.get("sub")
if not username: if not username:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
+20 -1
View File
@@ -1,16 +1,35 @@
import os
from pathlib import Path from pathlib import Path
from pydantic_settings import BaseSettings from pydantic_settings import BaseSettings
_HERE = Path(__file__).parent _HERE = Path(__file__).parent
if os.name == "nt":
_DB_DIR = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / "xenia_cloud"
_DB_DIR.mkdir(parents=True, exist_ok=True)
_DEFAULT_DB = _DB_DIR / "cloud.db"
else:
_DEFAULT_DB = _HERE / "cloud.db"
class Settings(BaseSettings): class Settings(BaseSettings):
SECRET_KEY: str = "change-me-generate-a-long-random-string" SECRET_KEY: str = "change-me-generate-a-long-random-string"
DATABASE_URL: str = "sqlite:////app/data/cloud.db" DATABASE_URL: str = f"sqlite:///{_DEFAULT_DB.as_posix()}"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 ACCESS_TOKEN_EXPIRE_MINUTES: int = 60
ADMIN_USERNAME: str = "sysadmin" ADMIN_USERNAME: str = "sysadmin"
ADMIN_PASSWORD: str = "changeme" ADMIN_PASSWORD: str = "changeme"
LATEST_VERSION: str = "0.0.0" LATEST_VERSION: str = "0.0.0"
# Ed25519 private key (base64, raw 32 bytes) that signs sites' license tokens.
# Generated once; the matching public key is built into client-services
# (local_backend/services/license.py). Keep secret, back up.
LICENSE_SIGNING_KEY: str = ""
# Manager JWT (separate secret from admin JWT)
MANAGER_JWT_SECRET: str = "change-me-manager-secret"
MANAGER_JWT_EXPIRE_HOURS: int = 72
# Where customers open the apps (connect_frontend: /menu/, /order/), e.g. https://menu.example.com.
# Sent to sites with the heartbeat so they can print table QR codes and show their ordering
# link (phase 3S, S.7). Empty = the sites use their CLOUD_URL.
PUBLIC_APPS_URL: str = ""
model_config = {"env_file": str(_HERE / ".env")} model_config = {"env_file": str(_HERE / ".env")}
+27 -8
View File
@@ -1,14 +1,20 @@
"""Cloud backend entry point. Schema: Alembic only (schema.py, APPS_PLATFORM D-22)."""
import os
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from config import settings from config import settings
from database import engine, Base from database import engine
from auth_utils import hash_password from auth_utils import hash_password
import models.admin # noqa: F401 import models.all # noqa: F401 every model (Alembic + routers)
import models.site # noqa: F401
from routers import auth, sites, heartbeat from routers import auth, sites, heartbeat, presets
from routers import menu as menu_router
from routers import orders as orders_router
from routers import manager_auth as manager_auth_router
from routers import remote_dashboard as remote_dashboard_router
def _seed_default_admin(): def _seed_default_admin():
@@ -27,7 +33,9 @@ def _seed_default_admin():
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
Base.metadata.create_all(bind=engine) # Schema = Alembic revisions only (schema.py, D-22). Refuses an unstamped v1 database.
from schema import upgrade_to_head
upgrade_to_head()
_seed_default_admin() _seed_default_admin()
yield yield
@@ -41,9 +49,20 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
app.include_router(auth.router, prefix="/api/auth", tags=["auth"]) app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(sites.router, prefix="/api/sites", tags=["sites"]) app.include_router(sites.router, prefix="/api/sites", tags=["sites"])
app.include_router(heartbeat.router, prefix="/api/heartbeat", tags=["heartbeat"]) app.include_router(heartbeat.router, prefix="/api/heartbeat", tags=["heartbeat"])
app.include_router(presets.router, prefix="/api/presets", tags=["presets"])
app.include_router(menu_router.router, prefix="/api/menu", tags=["menu"])
app.include_router(orders_router.router, prefix="/api/orders", tags=["orders"])
app.include_router(manager_auth_router.router, prefix="/api/manager", tags=["manager"])
app.include_router(remote_dashboard_router.router,prefix="/api/remote", tags=["remote"])
os.makedirs("/app/data/site_headers", exist_ok=True)
app.mount("/static/site_headers", StaticFiles(directory="/app/data/site_headers"), name="site_headers")
os.makedirs("/app/data/product_images", exist_ok=True)
app.mount("/static/product_images", StaticFiles(directory="/app/data/product_images"), name="product_images")
@app.get("/health") @app.get("/health")
+42
View File
@@ -0,0 +1,42 @@
"""Alembic environment for cloud_backend (APPS_PLATFORM D-22).
Agent notes: target metadata = models/all.py; render_as_batch for SQLite; a caller may
pass a connection in config.attributes["connection"] (schema.py, tests); otherwise
config.settings.DATABASE_URL is used.
"""
import sys
from pathlib import Path
from alembic import context
from sqlalchemy import create_engine
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from database import Base # noqa: E402
import models.all # noqa: E402,F401
target_metadata = Base.metadata
def _run(connection):
context.configure(connection=connection, target_metadata=target_metadata,
render_as_batch=True, compare_type=True)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connection = context.config.attributes.get("connection")
if connection is not None:
_run(connection)
return
from config import settings
engine = create_engine(settings.DATABASE_URL)
with engine.connect() as conn:
_run(conn)
engine.dispose()
if context.is_offline_mode():
raise SystemExit("Offline (--sql) mode is not supported.")
run_migrations_online()
+22
View File
@@ -0,0 +1,22 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
@@ -0,0 +1,191 @@
"""cloud v1 baseline: exactly the schema the v1 production cloud has (D-22)
Autogenerated from the models, then hand-edited so it equals what v1's create_all +
_run_migrations() produce: sites also has menu_hours_en / menu_hours_gr (v1 superseded
them by menu_hours but never dropped them; 0002 drops them).
The production DB is never upgraded THROUGH this revision: it is stamped to it at
cutover, so this file must describe production, not an ideal schema.
tests/test_schema.py compares it with a database built by v1's code.
Revision ID: 0001_cloud_baseline
Revises:
Create Date: 2026-11-12 19:18:38.281895
"""
from alembic import op
import sqlalchemy as sa
revision = '0001_cloud_baseline'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('admins',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(), nullable=False),
sa.Column('password_hash', sa.String(), nullable=False),
sa.Column('role', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('username')
)
with op.batch_alter_table('admins', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_admins_id'), ['id'], unique=False)
op.create_table('manager_accounts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(), nullable=False),
sa.Column('password_hash', sa.String(), nullable=False),
sa.Column('full_name', sa.String(), nullable=True),
sa.Column('is_active', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('manager_accounts', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_manager_accounts_email'), ['email'], unique=True)
batch_op.create_index(batch_op.f('ix_manager_accounts_id'), ['id'], unique=False)
op.create_table('sites',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('owner_name', sa.String(), nullable=False),
sa.Column('contact_email', sa.String(), nullable=False),
sa.Column('secret_key_hash', sa.String(), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_locked', sa.Boolean(), nullable=True),
sa.Column('lock_reason', sa.String(), nullable=True),
sa.Column('license_expires_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('last_seen_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('last_seen_ip', sa.String(), nullable=True),
sa.Column('last_seen_local_ip', sa.String(), nullable=True),
sa.Column('waiter_domain', sa.String(), nullable=True),
sa.Column('order_counter', sa.Integer(), nullable=False),
sa.Column('menu_mode', sa.String(), nullable=False),
sa.Column('menu_display_name', sa.String(), nullable=True),
sa.Column('menu_tagline_en', sa.String(), nullable=True),
sa.Column('menu_tagline_gr', sa.String(), nullable=True),
sa.Column('menu_blurb_en', sa.String(), nullable=True),
sa.Column('menu_blurb_gr', sa.String(), nullable=True),
sa.Column('menu_hours', sa.String(), nullable=True),
sa.Column('menu_hours_en', sa.String(), nullable=True),
sa.Column('menu_hours_gr', sa.String(), nullable=True),
sa.Column('menu_header_image_url', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('sites', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_sites_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_sites_site_id'), ['site_id'], unique=True)
op.create_table('manager_site_access',
sa.Column('manager_id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['manager_id'], ['manager_accounts.id'], ),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('manager_id', 'site_id')
)
op.create_table('menu_snapshots',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('snapshot_json', sa.Text(), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('menu_snapshots', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_menu_snapshots_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_menu_snapshots_site_id'), ['site_id'], unique=True)
op.create_table('online_orders',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('public_ref', sa.String(), nullable=False),
sa.Column('order_type', sa.String(), nullable=False),
sa.Column('customer_name', sa.String(), nullable=False),
sa.Column('customer_phone', sa.String(), nullable=True),
sa.Column('customer_address', sa.Text(), nullable=True),
sa.Column('customer_notes', sa.Text(), nullable=True),
sa.Column('items_json', sa.Text(), nullable=False),
sa.Column('subtotal', sa.Float(), nullable=False),
sa.Column('delivery_fee', sa.Float(), nullable=False),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('status', sa.String(), nullable=False),
sa.Column('rejection_reason', sa.String(), nullable=True),
sa.Column('synced_to_local', sa.Integer(), nullable=False),
sa.Column('local_order_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('public_ref')
)
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_online_orders_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_online_orders_site_id'), ['site_id'], unique=False)
batch_op.create_index(batch_op.f('ix_online_orders_status'), ['status'], unique=False)
op.create_table('product_images',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('product_id', sa.Integer(), nullable=False),
sa.Column('image_url', sa.String(), nullable=False),
sa.Column('image_hash', sa.String(), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('site_id', 'product_id', name='uq_product_images_site_product')
)
with op.batch_alter_table('product_images', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_product_images_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_product_images_site_id'), ['site_id'], unique=False)
op.create_table('stats_snapshots',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('snapshot_json', sa.Text(), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('site_id')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('stats_snapshots')
with op.batch_alter_table('product_images', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_product_images_site_id'))
batch_op.drop_index(batch_op.f('ix_product_images_id'))
op.drop_table('product_images')
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_online_orders_status'))
batch_op.drop_index(batch_op.f('ix_online_orders_site_id'))
batch_op.drop_index(batch_op.f('ix_online_orders_id'))
op.drop_table('online_orders')
with op.batch_alter_table('menu_snapshots', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_menu_snapshots_site_id'))
batch_op.drop_index(batch_op.f('ix_menu_snapshots_id'))
op.drop_table('menu_snapshots')
op.drop_table('manager_site_access')
with op.batch_alter_table('sites', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_sites_site_id'))
batch_op.drop_index(batch_op.f('ix_sites_id'))
op.drop_table('sites')
with op.batch_alter_table('manager_accounts', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_manager_accounts_id'))
batch_op.drop_index(batch_op.f('ix_manager_accounts_email'))
op.drop_table('manager_accounts')
with op.batch_alter_table('admins', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_admins_id'))
op.drop_table('admins')
# ### end Alembic commands ###
@@ -0,0 +1,70 @@
"""v2 licensing: site modules, catalogue, plan presets (D-3, D-20, D-21, §5.2)
Hand-edited:
- existing sites get V1_SITE_MODULES: every module a v1 site already had, with no
limits tighter than v1 (KDS screens unlimited). At cutover each site keeps doing what
it did; the owner can then change sites in the sysadmin panel. Frozen here on purpose.
- the same map is seeded as the preset "Everything (v1 sites)".
- menu_hours_en / menu_hours_gr (superseded in v1) are dropped.
Revision ID: 0002_v2_licensing
Revises: 0001_cloud_baseline
Create Date: 2026-11-12 19:19:08.073899
"""
import json
from alembic import op
import sqlalchemy as sa
V1_SITE_MODULES = {
"ordering": {}, "waiter_app": {}, "history": {}, "reports": {}, "pricing": {}, "tabs": {},
"crm": {}, "expenses": {}, "inventory": {}, "staff_planning": {}, "notes": {}, "chat": {},
"reservations": {}, "kds": {"limits": {"devices": None}}, "connect_menu": {},
"connect_orders": {}, "connect_remote": {}, "caller_id": {}, "fiscal": {},
}
revision = '0002_v2_licensing'
down_revision = '0001_cloud_baseline'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('plan_presets',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('modules', sa.JSON(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
with op.batch_alter_table('sites', schema=None) as batch_op:
batch_op.add_column(sa.Column('modules', sa.JSON(), nullable=False, server_default=sa.text("'{}'")))
batch_op.add_column(sa.Column('module_catalog', sa.JSON(), nullable=True))
batch_op.add_column(sa.Column('module_catalog_at', sa.DateTime(timezone=True), nullable=True))
batch_op.drop_column('menu_hours_en')
batch_op.drop_column('menu_hours_gr')
# ### end Alembic commands ###
conn = op.get_bind()
conn.execute(sa.text("update sites set modules = :m"), {"m": json.dumps(V1_SITE_MODULES)})
conn.execute(sa.text("insert into plan_presets (name, description, modules) values (:n, :d, :m)"),
{"n": "Everything (v1 sites)", "d": "Every module v1 sites had, no extra limits",
"m": json.dumps(V1_SITE_MODULES)})
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('sites', schema=None) as batch_op:
batch_op.add_column(sa.Column('menu_hours_gr', sa.VARCHAR(), nullable=True))
batch_op.add_column(sa.Column('menu_hours_en', sa.VARCHAR(), nullable=True))
batch_op.drop_column('module_catalog_at')
batch_op.drop_column('module_catalog')
batch_op.drop_column('modules')
op.drop_table('plan_presets')
# ### end Alembic commands ###
@@ -0,0 +1,86 @@
"""online orders: sales_point, table_label, delivery_area, requested_for, tracking_token; public_ref unique per site (plan phase 3S, S.2/S.3)
- sales_point / table_label: the cloud prices orders per sales point; the QR menu's table
- public_ref ("ORD-0001") counts per site but was unique across all sites, so a second
site's first online order failed → unique per (site_id, public_ref)
- tracking_token: the customer's tracking page used the public ref alone (ambiguous across
sites and guessable) → a random token per order (existing orders get one)
The table is rebuilt from an explicit definition (SQLite can't drop the unnamed
UNIQUE(public_ref) in place; copy_from leaves it out, the indexes are kept).
Revision ID: 0003_order_sales_point
Revises: 0002_v2_licensing
Create Date: 2026-11-15 23:00:00
"""
import secrets
from alembic import op
import sqlalchemy as sa
revision = '0003_order_sales_point'
down_revision = '0002_v2_licensing'
branch_labels = None
depends_on = None
def _base(*extra):
"""online_orders as 0001 created it, without UNIQUE(public_ref), plus `extra`."""
return sa.Table(
'online_orders', sa.MetaData(),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('public_ref', sa.String(), nullable=False),
sa.Column('order_type', sa.String(), nullable=False),
sa.Column('customer_name', sa.String(), nullable=False),
sa.Column('customer_phone', sa.String(), nullable=True),
sa.Column('customer_address', sa.Text(), nullable=True),
sa.Column('customer_notes', sa.Text(), nullable=True),
sa.Column('items_json', sa.Text(), nullable=False),
sa.Column('subtotal', sa.Float(), nullable=False),
sa.Column('delivery_fee', sa.Float(), nullable=False),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('status', sa.String(), nullable=False),
sa.Column('rejection_reason', sa.String(), nullable=True),
sa.Column('synced_to_local', sa.Integer(), nullable=False),
sa.Column('local_order_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
*extra,
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.Index('ix_online_orders_id', 'id'),
sa.Index('ix_online_orders_site_id', 'site_id'),
sa.Index('ix_online_orders_status', 'status'),
)
def upgrade() -> None:
with op.batch_alter_table('online_orders', copy_from=_base(), recreate='always') as batch_op:
batch_op.add_column(sa.Column('table_label', sa.String(), nullable=True))
batch_op.add_column(sa.Column('delivery_area', sa.String(), nullable=True))
batch_op.add_column(sa.Column('requested_for', sa.DateTime(timezone=True), nullable=True))
batch_op.add_column(sa.Column('sales_point', sa.String(), nullable=True))
batch_op.add_column(sa.Column('tracking_token', sa.String(), nullable=True))
batch_op.create_unique_constraint('uq_online_orders_site_ref', ['site_id', 'public_ref'])
batch_op.create_unique_constraint('uq_online_orders_tracking_token', ['tracking_token'])
conn = op.get_bind()
for (oid,) in conn.execute(sa.text("select id from online_orders where tracking_token is null")).fetchall():
conn.execute(sa.text("update online_orders set tracking_token = :t where id = :i"),
{"t": secrets.token_urlsafe(12), "i": oid})
def downgrade() -> None:
current = _base(sa.Column('table_label', sa.String(), nullable=True),
sa.Column('delivery_area', sa.String(), nullable=True),
sa.Column('requested_for', sa.DateTime(timezone=True), nullable=True),
sa.Column('sales_point', sa.String(), nullable=True),
sa.Column('tracking_token', sa.String(), nullable=True))
with op.batch_alter_table('online_orders', copy_from=current, recreate='always') as batch_op:
batch_op.drop_column('tracking_token')
batch_op.drop_column('sales_point')
batch_op.drop_column('requested_for')
batch_op.drop_column('delivery_area')
batch_op.drop_column('table_label')
batch_op.create_unique_constraint('uq_online_orders_public_ref', ['public_ref'])
@@ -0,0 +1,27 @@
"""online orders: delivery_area_id (plan phase 3S, S.5)
The site checks the cloud's delivery fee with its own engine when it pulls an order, and
needs the area by id (a name can change between a menu push and the order).
Revision ID: 0004_order_area_id
Revises: 0003_order_sales_point
Create Date: 2026-11-16 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0004_order_area_id'
down_revision = '0003_order_sales_point'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.add_column(sa.Column('delivery_area_id', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_column('delivery_area_id')
@@ -0,0 +1,24 @@
"""online orders: party_size (reservations online, plan phase 3S, S.6)
Revision ID: 0005_order_party_size
Revises: 0004_order_area_id
Create Date: 2026-11-16 21:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0005_order_party_size'
down_revision = '0004_order_area_id'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.add_column(sa.Column('party_size', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_column('party_size')
@@ -0,0 +1,24 @@
"""online orders: table_id (the QR menu at the table, plan phase 3S, S.7)
Revision ID: 0006_order_table_id
Revises: 0005_order_party_size
Create Date: 2026-11-16 23:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0006_order_table_id'
down_revision = '0005_order_party_size'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.add_column(sa.Column('table_id', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_column('table_id')
+9
View File
@@ -0,0 +1,9 @@
"""Every cloud model, for Alembic autogenerate and the drift guard. Add new model modules here."""
import models.admin # noqa: F401
import models.site # noqa: F401
import models.menu_snapshot # noqa: F401
import models.online_order # noqa: F401
import models.manager_account # noqa: F401
import models.stats_snapshot # noqa: F401
import models.product_image # noqa: F401
import models.plan_preset # noqa: F401
+27
View File
@@ -0,0 +1,27 @@
from sqlalchemy import Column, Integer, String, DateTime, Table, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base
from models.site import Site # noqa: F401 — needed so SQLAlchemy resolves "Site" in relationship
# Many-to-many: one manager can access multiple sites, one site can have multiple managers
manager_site_access = Table(
"manager_site_access",
Base.metadata,
Column("manager_id", Integer, ForeignKey("manager_accounts.id"), primary_key=True),
Column("site_id", Integer, ForeignKey("sites.id"), primary_key=True),
)
class ManagerAccount(Base):
__tablename__ = "manager_accounts"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, nullable=False, index=True)
password_hash = Column(String, nullable=False)
full_name = Column(String, nullable=True)
is_active = Column(Integer, default=1, nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
sites = relationship("Site", secondary=manager_site_access, backref="manager_accounts")
+12
View File
@@ -0,0 +1,12 @@
from sqlalchemy import Column, Integer, Text, DateTime, ForeignKey
from sqlalchemy.sql import func
from database import Base
class MenuSnapshot(Base):
__tablename__ = "menu_snapshots"
id = Column(Integer, primary_key=True, index=True)
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True, unique=True)
snapshot_json = Column(Text, nullable=False)
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
+56
View File
@@ -0,0 +1,56 @@
from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.sql import func
from database import Base
class OnlineOrder(Base):
__tablename__ = "online_orders"
__table_args__ = (
UniqueConstraint("site_id", "public_ref", name="uq_online_orders_site_ref"), # S.2: per site
UniqueConstraint("tracking_token", name="uq_online_orders_tracking_token"),
)
id = Column(Integer, primary_key=True, index=True)
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True)
# Human-readable reference, unique per site (e.g. "ORD-0042")
public_ref = Column(String, nullable=False)
# the customer's tracking page: random, unguessable (S.2; the ref alone was ambiguous across sites)
tracking_token = Column(String, nullable=True)
order_type = Column(String, nullable=False) # dine_in | takeaway | delivery | reservation | preorder (S.6)
# Customer info
customer_name = Column(String, nullable=False)
customer_phone = Column(String, nullable=True)
customer_address = Column(Text, nullable=True) # required for delivery
customer_notes = Column(Text, nullable=True)
table_label = Column(String, nullable=True) # the QR menu's table (S.7: from the table's QR token)
table_id = Column(Integer, nullable=True) # the site's table id, from a valid QR token (S.7)
delivery_area = Column(String, nullable=True) # the delivery area's name (S.3)
delivery_area_id = Column(Integer, nullable=True) # the site's area id (S.5: the site checks the fee)
requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap
party_size = Column(Integer, nullable=True) # reservations (S.6): how many guests
sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2)
# Order content — JSON array of ordered items
items_json = Column(Text, nullable=False)
# Financials
subtotal = Column(Float, nullable=False)
delivery_fee = Column(Float, default=0.0, nullable=False)
total = Column(Float, nullable=False)
# Status lifecycle:
# pending_acceptance → accepted | rejected
# accepted → preparing → ready | out_for_delivery → delivered
# reservations (S.6): pending_acceptance → accepted (confirmed) | rejected;
# accepted → delivered (the guests arrived) | cancelled (by the venue)
status = Column(String, default="pending_acceptance", nullable=False, index=True)
rejection_reason = Column(String, nullable=True)
# Sync state — local backend polls for these
synced_to_local = Column(Integer, default=0, nullable=False) # 0=no, 1=yes
local_order_id = Column(Integer, nullable=True) # set after local creates it
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
+20
View File
@@ -0,0 +1,20 @@
"""Plan presets (APPS_PLATFORM D-3, §5.2): named module maps the sysadmin applies to a site.
A preset only fills in a site's `modules` map; after applying, the site's map can be
edited freely. Plans are not a concept the sites know about.
"""
from sqlalchemy import JSON, Column, DateTime, Integer, String
from sqlalchemy.sql import func
from database import Base
class PlanPreset(Base):
__tablename__ = "plan_presets"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False, unique=True)
description = Column(String, nullable=True)
modules = Column(JSON, nullable=False, default=dict)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
+19
View File
@@ -0,0 +1,19 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.sql import func
from database import Base
class ProductImage(Base):
"""Cloud-hosted copy of a local product's image, pushed by local_backend
during menu sync. Used as a fallback on the public QR menu when the
product has no digital_image_url override set."""
__tablename__ = "product_images"
id = Column(Integer, primary_key=True, index=True)
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True)
product_id = Column(Integer, nullable=False)
image_url = Column(String, nullable=False)
image_hash = Column(String, nullable=False)
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
__table_args__ = (UniqueConstraint("site_id", "product_id", name="uq_product_images_site_product"),)
+28 -1
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime from sqlalchemy import JSON, Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func from sqlalchemy.sql import func
from database import Base from database import Base
@@ -21,3 +21,30 @@ class Site(Base):
last_seen_ip = Column(String, nullable=True) last_seen_ip = Column(String, nullable=True)
last_seen_local_ip = Column(String, nullable=True) last_seen_local_ip = Column(String, nullable=True)
waiter_domain = Column(String, nullable=True) waiter_domain = Column(String, nullable=True)
# Monotonically incrementing counter used to generate public_ref for online orders
order_counter = Column(Integer, default=0, nullable=False)
# QR menu branding/config
menu_mode = Column(String, nullable=False, default="order") # "order" | "view_only"
menu_display_name = Column(String, nullable=True)
menu_tagline_en = Column(String, nullable=True)
menu_tagline_gr = Column(String, nullable=True)
menu_blurb_en = Column(String, nullable=True)
menu_blurb_gr = Column(String, nullable=True)
menu_hours = Column(String, nullable=True)
menu_header_image_url = Column(String, nullable=True)
# Licensed modules (APPS_PLATFORM D-3, §5.2): the `modules` map of the site's v2 license
# token, e.g. {"ordering": {}, "kds": {"limits": {"devices": 2}}, "caller_id": {"exp": "..."}}.
# Edited in the sysadmin panel, usually by applying a plan preset first.
modules = Column(JSON, nullable=False, default=dict)
# What the site reported it can run (heartbeat `module_catalog`, D-20): drives the editor.
module_catalog = Column(JSON, nullable=True)
module_catalog_at = Column(DateTime(timezone=True), nullable=True)
@property
def apps_url(self) -> str | None:
"""Where customers open this cloud's apps (PUBLIC_APPS_URL; phase 3S): the sysadmin's
menu and ordering links are built from it. Not stored per site."""
from config import settings
return settings.PUBLIC_APPS_URL.rstrip("/") or None
+12
View File
@@ -0,0 +1,12 @@
from sqlalchemy import Column, Integer, Text, DateTime, ForeignKey
from sqlalchemy.sql import func
from database import Base
class StatsSnapshot(Base):
__tablename__ = "stats_snapshots"
id = Column(Integer, primary_key=True)
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, unique=True)
snapshot_json = Column(Text, nullable=False)
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
+2
View File
@@ -0,0 +1,2 @@
-r requirements.txt
pytest==8.3.3
+2
View File
@@ -8,3 +8,5 @@ passlib[bcrypt]==1.7.4
bcrypt==4.0.1 bcrypt==4.0.1
python-multipart==0.0.9 python-multipart==0.0.9
httpx==0.27.2 httpx==0.27.2
cryptography==46.0.4
alembic==1.14.0
+7 -5
View File
@@ -7,6 +7,7 @@ from config import settings
from database import get_db from database import get_db
from models.site import Site from models.site import Site
from schemas.site import HeartbeatRequest, HeartbeatResponse from schemas.site import HeartbeatRequest, HeartbeatResponse
from services.license_token import issue_license_token
router = APIRouter() router = APIRouter()
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto") _pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
@@ -29,14 +30,15 @@ def heartbeat(
site.last_seen_ip = request.client.host if request.client else None site.last_seen_ip = request.client.host if request.client else None
if body.local_ip: if body.local_ip:
site.last_seen_local_ip = body.local_ip site.last_seen_local_ip = body.local_ip
if body.module_catalog:
site.module_catalog = body.module_catalog
site.module_catalog_at = now
db.commit() db.commit()
licensed = site.is_active and (site.license_expires_at.replace(tzinfo=timezone.utc) > now)
return HeartbeatResponse( return HeartbeatResponse(
licensed=licensed,
locked=site.is_locked,
lock_reason=site.lock_reason,
expires_at=site.license_expires_at,
latest_version=settings.LATEST_VERSION, latest_version=settings.LATEST_VERSION,
waiter_domain=site.waiter_domain, waiter_domain=site.waiter_domain,
site_numeric_id=site.id,
license_token=issue_license_token(site, now),
apps_url=settings.PUBLIC_APPS_URL.rstrip("/") or None,
) )
+150
View File
@@ -0,0 +1,150 @@
from datetime import datetime, timedelta, timezone
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jose import jwt, JWTError
from passlib.context import CryptContext
from pydantic import BaseModel
from sqlalchemy.orm import Session
from config import settings
from database import get_db
from models.manager_account import ManagerAccount, manager_site_access
from models.site import Site
from auth_utils import get_current_admin
from schemas.manager import (
ManagerRegisterRequest, ManagerLoginRequest,
ManagerTokenOut, ManagerOut,
)
router = APIRouter()
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
_bearer = HTTPBearer()
ALGORITHM = "HS256"
# ── Shared dependency: decode manager JWT ─────────────────────────────────────
def _get_current_manager(credentials: HTTPAuthorizationCredentials = Depends(_bearer), db: Session = Depends(get_db)) -> ManagerAccount:
try:
payload = jwt.decode(credentials.credentials, settings.MANAGER_JWT_SECRET, algorithms=[ALGORITHM])
manager_id = int(payload.get("sub", 0))
except (JWTError, ValueError):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
manager = db.query(ManagerAccount).filter(ManagerAccount.id == manager_id).first()
if not manager or not manager.is_active:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Manager not found or inactive")
return manager
def _create_manager_token(manager: ManagerAccount) -> str:
site_ids = [s.id for s in manager.sites]
payload = {
"sub": str(manager.id),
"email": manager.email,
"site_ids": site_ids,
"exp": datetime.now(timezone.utc) + timedelta(hours=settings.MANAGER_JWT_EXPIRE_HOURS),
}
return jwt.encode(payload, settings.MANAGER_JWT_SECRET, algorithm=ALGORITHM)
# ── Admin-only: register a manager ───────────────────────────────────────────
@router.post("/register", response_model=ManagerOut, status_code=status.HTTP_201_CREATED)
def register_manager(
body: ManagerRegisterRequest,
db: Session = Depends(get_db),
_admin=Depends(get_current_admin),
):
existing = db.query(ManagerAccount).filter(ManagerAccount.email == body.email).first()
sites = db.query(Site).filter(Site.site_id.in_(body.site_ids)).all()
if existing:
# Email already exists — just add the new site access links, don't recreate the account
for site in sites:
if site not in existing.sites:
existing.sites.append(site)
db.commit()
db.refresh(existing)
return existing
manager = ManagerAccount(
email=body.email,
password_hash=_pwd.hash(body.password),
full_name=body.full_name,
sites=sites,
)
db.add(manager)
db.commit()
db.refresh(manager)
return manager
# ── Public: manager login ─────────────────────────────────────────────────────
@router.post("/login", response_model=ManagerTokenOut)
def login_manager(body: ManagerLoginRequest, db: Session = Depends(get_db)):
manager = db.query(ManagerAccount).filter(ManagerAccount.email == body.email).first()
if not manager or not _pwd.verify(body.password, manager.password_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
if not manager.is_active:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account disabled")
return ManagerTokenOut(access_token=_create_manager_token(manager))
# ── Public: refresh ───────────────────────────────────────────────────────────
@router.post("/refresh", response_model=ManagerTokenOut)
def refresh_manager_token(manager: ManagerAccount = Depends(_get_current_manager)):
return ManagerTokenOut(access_token=_create_manager_token(manager))
# ── Admin-only: list managers for a site ─────────────────────────────────────
class ManagerBySiteOut(BaseModel):
id: int
email: str
full_name: Optional[str] = None
is_active: int
model_config = {"from_attributes": True}
@router.get("/by-site/{site_id}", response_model=list[ManagerBySiteOut])
def get_managers_by_site(
site_id: str,
db: Session = Depends(get_db),
_admin=Depends(get_current_admin),
):
site = db.query(Site).filter(Site.site_id == site_id).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
return site.manager_accounts
# ── Admin-only: remove a manager's access to a site ──────────────────────────
class SiteAccessRemoveRequest(BaseModel):
manager_id: int
site_id: str # site_id UUID string, not integer PK
@router.delete("/site-access", status_code=status.HTTP_204_NO_CONTENT)
def remove_manager_site_access(
body: SiteAccessRemoveRequest,
db: Session = Depends(get_db),
_admin=Depends(get_current_admin),
):
manager = db.query(ManagerAccount).filter(ManagerAccount.id == body.manager_id).first()
if not manager:
raise HTTPException(status_code=404, detail="Manager not found")
site = db.query(Site).filter(Site.site_id == body.site_id).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
if site in manager.sites:
manager.sites.remove(site)
db.commit()
+155
View File
@@ -0,0 +1,155 @@
import os
import uuid
from fastapi import APIRouter, Depends, HTTPException, Header, UploadFile, File, Form, status
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from database import get_db
from models.site import Site
from models.menu_snapshot import MenuSnapshot
from models.product_image import ProductImage
from schemas.menu import MenuSyncRequest, MenuSyncResponse
router = APIRouter()
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
PRODUCT_IMAGE_DIR = "/app/data/product_images"
def _require_site(
x_site_id: str = Header(..., alias="X-Site-ID"),
x_site_key: str = Header(..., alias="X-Site-Key"),
db: Session = Depends(get_db),
) -> Site:
site = db.query(Site).filter(Site.site_id == x_site_id).first()
if not site or not _pwd.verify(x_site_key, site.secret_key_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid site credentials")
return site
# ── Public ────────────────────────────────────────────────────────────────────
@router.get("/{site_slug}")
def get_menu(site_slug: str, t: str | None = None, db: Session = Depends(get_db)):
"""Return the latest menu snapshot for a site. Used by the public menu SPA. `t`: a table's
QR token (S.7) → `table` {id, label}, or `table_invalid` when it isn't one of the venue's."""
site = db.query(Site).filter(Site.site_id == site_slug).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
snapshot = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
if not snapshot:
raise HTTPException(status_code=404, detail="No menu published yet")
import json
data = json.loads(snapshot.snapshot_json)
from services.checkout import delivery_areas
data["delivery_areas"] = delivery_areas(data) # S.3: what the customer picks from
data.pop("fees", None) # the rules and postcodes stay on the cloud
from services.ordering import summary
data["ordering"] = summary(data) # S.4: services, open now, slots
data["menu_mode"] = site.menu_mode
from services import qr
data["table_ordering"] = qr.ordering_on(data, site) # S.7: ordering at the table (with a table's QR)
if t is not None:
table = qr.table_for(data, t)
data["table"] = table
data["table_invalid"] = table is None
data.pop("qr", None) # the tables' token hashes stay on the cloud
data["restaurant"] = {
"name": site.menu_display_name,
"tagline": {"en": site.menu_tagline_en, "gr": site.menu_tagline_gr},
"blurb": {"en": site.menu_blurb_en, "gr": site.menu_blurb_gr},
"hours": site.menu_hours,
"headerImageUrl": site.menu_header_image_url,
}
cloud_images = {
img.product_id: img.image_url
for img in db.query(ProductImage).filter(ProductImage.site_id == site.id).all()
}
for cat in data.get("categories", []):
for product in cat.get("products", []):
# image_url as pushed by local_backend points at the restaurant's own
# LAN/local server and isn't reachable from the internet — always
# replace it with the cloud-hosted copy (or None) unless a manual
# digital_image_url override is set.
if not product.get("digital_image_url"):
product["image_url"] = cloud_images.get(product.get("id"))
return data
# ── Internal (site API key) ───────────────────────────────────────────────────
@router.post("/sync", response_model=MenuSyncResponse)
def sync_menu(body: MenuSyncRequest, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
"""Upsert the menu snapshot for this site. Called by local_backend on each sync. Only the
authenticated site's own (before S.2 the body's site_id was trusted: one site could
overwrite another's menu)."""
if body.site_id != site.id:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's menu")
import json
try:
json.loads(body.snapshot_json)
except ValueError:
raise HTTPException(status_code=422, detail="snapshot_json is not JSON")
snapshot = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
if snapshot:
snapshot.snapshot_json = body.snapshot_json
else:
snapshot = MenuSnapshot(site_id=site.id, snapshot_json=body.snapshot_json)
db.add(snapshot)
db.commit()
return MenuSyncResponse(ok=True)
@router.post("/sync-image")
async def sync_product_image(
product_id: int = Form(...),
file: UploadFile = File(...),
site: Site = Depends(_require_site),
db: Session = Depends(get_db),
):
"""Upload/replace the cloud-hosted copy of a product's image. Called by
local_backend during menu sync for products whose image changed."""
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image")
contents = await file.read()
import hashlib
image_hash = hashlib.sha256(contents).hexdigest()
record = (
db.query(ProductImage)
.filter(ProductImage.site_id == site.id, ProductImage.product_id == product_id)
.first()
)
os.makedirs(PRODUCT_IMAGE_DIR, exist_ok=True)
if record and record.image_hash == image_hash:
return {"ok": True, "image_url": record.image_url, "unchanged": True}
if record:
old_path = os.path.join(PRODUCT_IMAGE_DIR, os.path.basename(record.image_url))
if os.path.exists(old_path):
os.remove(old_path)
ext = file.filename.rsplit(".", 1)[-1].lower() if file.filename and "." in file.filename else "jpg"
filename = f"{site.id}_{product_id}_{uuid.uuid4().hex[:8]}.{ext}"
filepath = os.path.join(PRODUCT_IMAGE_DIR, filename)
with open(filepath, "wb") as f:
f.write(contents)
image_url = f"/static/product_images/{filename}"
if record:
record.image_url = image_url
record.image_hash = image_hash
else:
record = ProductImage(site_id=site.id, product_id=product_id, image_url=image_url, image_hash=image_hash)
db.add(record)
db.commit()
return {"ok": True, "image_url": image_url, "unchanged": False}
+278
View File
@@ -0,0 +1,278 @@
import json
import secrets
from datetime import date, timezone
from fastapi import APIRouter, Depends, HTTPException, Header, Request, status
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from database import get_db
from models.site import Site
from models.online_order import OnlineOrder
from models.menu_snapshot import MenuSnapshot
from schemas.online_order import (
OnlineOrderCreate, OnlineOrderCreated, OrderStatusOut,
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest, QuoteRequest,
)
from services.checkout import CheckoutError, check_sent, price_cart
from services import ordering, qr, ratelimit
# public endpoints, per caller address (CL-4)
QUOTE_LIMIT = (120, 60) # 120 quotes a minute
ORDER_LIMIT = (10, 600) # 10 orders in 10 minutes
TRACK_LIMIT = (240, 60)
def _limit(request, bucket, rule):
if not ratelimit.hit(bucket, ratelimit.client_ip(request), *rule):
raise HTTPException(status_code=429, detail={"code": "rate.limited", "params": {"seconds": rule[1]}})
from auth_utils import get_current_admin # manager JWT checked separately in manager_auth
router = APIRouter()
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Valid status transitions
_TRANSITIONS: dict[str, set[str]] = {
"pending_acceptance": {"accepted", "rejected"},
"accepted": {"preparing"},
"preparing": {"ready", "out_for_delivery"},
"ready": {"delivered"},
"out_for_delivery": {"delivered"},
}
# reservations (S.6): confirmed or declined; then the guests arrive, or the venue cancels
_RES_TRANSITIONS: dict[str, set[str]] = {
"pending_acceptance": {"accepted", "rejected"},
"accepted": {"delivered", "cancelled"},
}
def _transitions(order_type: str) -> dict[str, set[str]]:
return _RES_TRANSITIONS if order_type in ordering.RES_TYPES else _TRANSITIONS
def _require_site(
x_site_id: str = Header(..., alias="X-Site-ID"),
x_site_key: str = Header(..., alias="X-Site-Key"),
db: Session = Depends(get_db),
) -> Site:
site = db.query(Site).filter(Site.site_id == x_site_id).first()
if not site or not _pwd.verify(x_site_key, site.secret_key_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid site credentials")
return site
# ── Public endpoints ──────────────────────────────────────────────────────────
def _site_and_menu(db, site_slug):
site = db.query(Site).filter(Site.site_id == site_slug).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
snap = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
if snap is None:
raise HTTPException(status_code=409, detail={"code": "order.no_menu", "params": {}})
return site, json.loads(snap.snapshot_json)
def _priced(menu, order_type, items, area_id=None, postcode=None):
try:
return price_cart(menu, order_type, items, area_id=area_id, postcode=postcode)
except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail())
@router.get("/{site_slug}/slots")
def order_slots(site_slug: str, db: Session = Depends(get_db)):
"""When online orders can be placed (S.4): services, open now, ASAP offered, time slots."""
_site, menu = _site_and_menu(db, site_slug)
return ordering.summary(menu)
@router.get("/{site_slug}/reservation-slots")
def reservation_slots(site_slug: str, day: str, db: Session = Depends(get_db)):
"""The reservation times of one venue day (S.6): ?day=YYYY-MM-DD → {day, slots: [iso]}."""
_site, menu = _site_and_menu(db, site_slug)
try:
wanted = date.fromisoformat(day)
except ValueError:
raise HTTPException(status_code=422, detail={"code": "order.time_invalid", "params": {}})
return {"day": wanted.isoformat(), "slots": [t.isoformat() for t in ordering.res_slots(menu, wanted)]}
@router.post("/{site_slug}/quote")
def quote_order(site_slug: str, body: QuoteRequest, request: Request, db: Session = Depends(get_db)):
"""The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S)."""
_limit(request, "quote", QUOTE_LIMIT)
_site, menu = _site_and_menu(db, site_slug)
return _priced(menu, body.order_type, [i.model_dump() for i in body.items], body.area_id, body.postcode).out()
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db: Session = Depends(get_db)):
"""Customer submits an order from a customer app. The cloud prices it from the venue's menu
for the order's sales point (services/checkout.py); a price or total the app sent that
differs → 409 order.price_changed with the current prices; nothing the browser says about
money is stored (phase 3S, S.2)."""
_limit(request, "order", ORDER_LIMIT)
site, menu = _site_and_menu(db, site_slug)
items = [i.model_dump() for i in body.items]
reservation = body.order_type in ordering.RES_TYPES # S.6: a table, maybe with food
table = None
if body.order_type == "dine_in": # S.7: only from a table's QR code
if not qr.ordering_on(menu, site):
raise HTTPException(status_code=409, detail={"code": "order.service_unavailable", "params": {"service": "dine_in"}})
table = qr.table_for(menu, body.table_token)
if table is None:
raise HTTPException(status_code=403, detail={"code": "order.table_invalid", "params": {}})
if body.order_type == "reservation":
if items:
raise HTTPException(status_code=422, detail={"code": "order.items_not_allowed", "params": {}})
priced = None
else:
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode)
if reservation:
problem = ordering.res_check(menu, body.order_type, body.requested_for, body.party_size)
elif body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
problem = ordering.check(menu, body.order_type, body.requested_for)
else:
problem = None
if problem:
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
if (reservation or body.order_type in ("takeaway", "delivery")) and not (body.customer_phone or "").strip():
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
if priced is not None:
try:
check_sent(priced, items, body.total)
except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail())
if body.order_type == "delivery" and not ((body.customer_address or "").strip() and (body.customer_phone or "").strip()):
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone", "customer_address"]}})
# Atomically increment counter and generate public_ref
site.order_counter = (site.order_counter or 0) + 1
public_ref = f"ORD-{site.order_counter:04d}"
order = OnlineOrder(
site_id=site.id,
public_ref=public_ref,
order_type=body.order_type,
customer_name=body.customer_name,
customer_phone=body.customer_phone,
customer_address=body.customer_address,
customer_notes=body.customer_notes,
table_label=table["label"] if table else None,
table_id=table["id"] if table else None,
delivery_area=priced.area_name if priced else None,
delivery_area_id=priced.area_id if priced else None,
# stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it)
requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None)
if (reservation or body.order_type in ("takeaway", "delivery")) and body.requested_for else None),
party_size=body.party_size if reservation else None,
sales_point=priced.sales_point if priced else None,
items_json=json.dumps([line.out() for line in priced.lines] if priced else []),
subtotal=priced.subtotal if priced else 0.0,
delivery_fee=priced.delivery_fee if priced else 0.0,
total=priced.total if priced else 0.0,
status="pending_acceptance",
)
order.tracking_token = secrets.token_urlsafe(12)
db.add(order)
db.commit()
db.refresh(order)
return OnlineOrderCreated(order_id=order.id, public_ref=order.public_ref, status=order.status,
tracking_token=order.tracking_token, total=order.total)
@router.get("/track/{token}", response_model=OrderStatusOut)
def track_order(token: str, request: Request, db: Session = Depends(get_db)):
"""The customer's tracking page (S.2): by the order's random token. Since S.4 also what
was ordered and when it's wanted (the token is the customer's own secret)."""
_limit(request, "track", TRACK_LIMIT)
order = db.query(OnlineOrder).filter(OnlineOrder.tracking_token == token).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
try:
lines = json.loads(order.items_json or "[]")
except ValueError:
lines = []
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason,
order_type=order.order_type, requested_for=order.requested_for, created_at=order.created_at,
party_size=order.party_size,
lines=[{"name": x.get("name"), "quantity": x.get("quantity"), "unit_price": x.get("unit_price"),
"options": [o.get("name") for o in x.get("options") or []]} for x in lines],
subtotal=order.subtotal, delivery_fee=order.delivery_fee, total=order.total)
@router.get("/status/{public_ref}", response_model=OrderStatusOut)
def get_order_status(public_ref: str, db: Session = Depends(get_db)):
"""Old tracking by the public ref (menu-app links before S.2): only while the ref is unique
across sites; otherwise 404 (the new link is /track/{token})."""
orders = db.query(OnlineOrder).filter(OnlineOrder.public_ref == public_ref).limit(2).all()
if len(orders) != 1:
raise HTTPException(status_code=404, detail="Order not found")
order = orders[0]
return OrderStatusOut(
public_ref=order.public_ref,
status=order.status,
rejection_reason=order.rejection_reason,
)
# ── Internal endpoints (site API key) ─────────────────────────────────────────
@router.get("/pending/{site_id}", response_model=list[PendingOrderOut])
def get_pending_orders(site_id: int, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
"""Return all orders not yet synced to the local backend. Only the authenticated site's own
(before S.2 any site with a valid key could read another site's by its number)."""
if site_id != site.id:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's orders")
orders = (
db.query(OnlineOrder)
.filter(OnlineOrder.site_id == site_id, OnlineOrder.synced_to_local == 0)
.order_by(OnlineOrder.created_at)
.all()
)
return orders
@router.post("/{order_id}/synced", status_code=status.HTTP_204_NO_CONTENT)
def mark_order_synced(
order_id: int,
body: OrderSyncedRequest,
site: Site = Depends(_require_site),
db: Session = Depends(get_db),
):
"""Local backend calls this after it has created the order locally."""
order = db.query(OnlineOrder).filter(
OnlineOrder.id == order_id, OnlineOrder.site_id == site.id
).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
order.synced_to_local = 1
order.local_order_id = body.local_order_id
db.commit()
@router.patch("/{order_id}/status", status_code=status.HTTP_204_NO_CONTENT)
def update_order_status(
order_id: int,
body: OrderStatusUpdateRequest,
site: Site = Depends(_require_site),
db: Session = Depends(get_db),
):
"""Update order status. Called by local_backend after staff accept/reject/progress."""
order = db.query(OnlineOrder).filter(
OnlineOrder.id == order_id, OnlineOrder.site_id == site.id
).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
allowed = _transitions(order.order_type).get(order.status, set())
if body.status not in allowed:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Cannot transition from '{order.status}' to '{body.status}'",
)
order.status = body.status
if body.rejection_reason:
order.rejection_reason = body.rejection_reason
db.commit()
+56
View File
@@ -0,0 +1,56 @@
"""Plan presets CRUD (sysadmin): named module maps applied to sites (APPS_PLATFORM D-3, §5.2)."""
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from auth_utils import get_current_admin
from database import get_db
from models.plan_preset import PlanPreset
from routers.sites import _validate_modules
router = APIRouter()
class PresetIn(BaseModel):
name: str
description: str | None = None
modules: dict
def _out(p: PlanPreset) -> dict:
return {"id": p.id, "name": p.name, "description": p.description, "modules": p.modules or {}}
@router.get("/")
def list_presets(db: Session = Depends(get_db), _=Depends(get_current_admin)):
return [_out(p) for p in db.query(PlanPreset).order_by(PlanPreset.name).all()]
@router.post("/", status_code=status.HTTP_201_CREATED)
def create_preset(body: PresetIn, db: Session = Depends(get_db), _=Depends(get_current_admin)):
if db.query(PlanPreset).filter(PlanPreset.name == body.name).first():
raise HTTPException(status_code=409, detail="A preset with that name exists")
p = PlanPreset(name=body.name, description=body.description, modules=_validate_modules(body.modules))
db.add(p)
db.commit()
db.refresh(p)
return _out(p)
@router.put("/{preset_id}")
def update_preset(preset_id: int, body: PresetIn, db: Session = Depends(get_db), _=Depends(get_current_admin)):
p = db.get(PlanPreset, preset_id)
if not p:
raise HTTPException(status_code=404, detail="Preset not found")
p.name, p.description, p.modules = body.name, body.description, _validate_modules(body.modules)
db.commit()
db.refresh(p)
return _out(p)
@router.delete("/{preset_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_preset(preset_id: int, db: Session = Depends(get_db), _=Depends(get_current_admin)):
p = db.get(PlanPreset, preset_id)
if p:
db.delete(p)
db.commit()
+173
View File
@@ -0,0 +1,173 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from database import get_db
from models.manager_account import ManagerAccount
from models.online_order import OnlineOrder
from models.stats_snapshot import StatsSnapshot
from schemas.manager import StatsSnapshotOut, StatsSnapshotRequest
from routers.manager_auth import _get_current_manager
router = APIRouter()
# ── Sites the manager can access ──────────────────────────────────────────────
@router.get("/sites")
def list_sites(manager: ManagerAccount = Depends(_get_current_manager)):
return [{"id": s.id, "site_id": s.site_id, "name": s.name} for s in manager.sites]
# ── Stats snapshot ────────────────────────────────────────────────────────────
@router.get("/sites/{site_id}/snapshot", response_model=StatsSnapshotOut)
def get_stats_snapshot(
site_id: int,
manager: ManagerAccount = Depends(_get_current_manager),
db: Session = Depends(get_db),
):
_check_site_access(manager, site_id)
snap = db.query(StatsSnapshot).filter(StatsSnapshot.site_id == site_id).first()
if not snap:
raise HTTPException(status_code=404, detail="No snapshot available yet")
return snap
# ── Orders ────────────────────────────────────────────────────────────────────
@router.get("/sites/{site_id}/orders")
def list_orders(
site_id: int,
order_status: str | None = None,
limit: int = 50,
offset: int = 0,
manager: ManagerAccount = Depends(_get_current_manager),
db: Session = Depends(get_db),
):
_check_site_access(manager, site_id)
q = db.query(OnlineOrder).filter(OnlineOrder.site_id == site_id)
if order_status:
q = q.filter(OnlineOrder.status == order_status)
orders = q.order_by(OnlineOrder.created_at.desc()).offset(offset).limit(limit).all()
return _serialize_orders(orders)
@router.get("/sites/{site_id}/orders/pending")
def list_pending_orders(
site_id: int,
manager: ManagerAccount = Depends(_get_current_manager),
db: Session = Depends(get_db),
):
_check_site_access(manager, site_id)
orders = (
db.query(OnlineOrder)
.filter(OnlineOrder.site_id == site_id, OnlineOrder.status == "pending_acceptance")
.order_by(OnlineOrder.created_at)
.all()
)
return _serialize_orders(orders)
# ── Stats snapshot push (site API key — called by local_backend) ──────────────
# Imported and registered from main.py under a site-key-protected sub-path.
# Defined here as a plain function so remote_dashboard router stays manager-JWT only.
from fastapi import Header
from passlib.context import CryptContext
from models.site import Site
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
@router.post("/snapshot", status_code=status.HTTP_204_NO_CONTENT)
def push_stats_snapshot(
body: StatsSnapshotRequest,
x_site_id: str = Header(..., alias="X-Site-ID"),
x_site_key: str = Header(..., alias="X-Site-Key"),
db: Session = Depends(get_db),
):
"""Local backend pushes stats every 5 minutes. Auth: site API key."""
site = db.query(Site).filter(Site.site_id == x_site_id).first()
if not site or not _pwd.verify(x_site_key, site.secret_key_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid site credentials")
if body.site_id != site.id: # S.2: only its own (the body's site_id was trusted before)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's stats")
snap = db.query(StatsSnapshot).filter(StatsSnapshot.site_id == site.id).first()
if snap:
snap.snapshot_json = body.snapshot_json
else:
snap = StatsSnapshot(site_id=site.id, snapshot_json=body.snapshot_json)
db.add(snap)
db.commit()
# ── Manager can also update order status (goes via cloud, local polls) ─────────
from schemas.online_order import OrderStatusUpdateRequest
_TRANSITIONS: dict[str, set[str]] = {
"pending_acceptance": {"accepted", "rejected"},
"accepted": {"preparing"},
"preparing": {"ready", "out_for_delivery"},
"ready": {"delivered"},
"out_for_delivery": {"delivered"},
}
@router.patch("/sites/{site_id}/orders/{order_id}/status", status_code=status.HTTP_204_NO_CONTENT)
def manager_update_order_status(
site_id: int,
order_id: int,
body: OrderStatusUpdateRequest,
manager: ManagerAccount = Depends(_get_current_manager),
db: Session = Depends(get_db),
):
_check_site_access(manager, site_id)
order = db.query(OnlineOrder).filter(
OnlineOrder.id == order_id, OnlineOrder.site_id == site_id
).first()
if not order:
raise HTTPException(status_code=404, detail="Order not found")
allowed = _TRANSITIONS.get(order.status, set())
if body.status not in allowed:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Cannot transition from '{order.status}' to '{body.status}'",
)
order.status = body.status
if body.rejection_reason:
order.rejection_reason = body.rejection_reason
db.commit()
# ── Helpers ───────────────────────────────────────────────────────────────────
def _check_site_access(manager: ManagerAccount, site_id: int):
if not any(s.id == site_id for s in manager.sites):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No access to this site")
def _serialize_orders(orders):
return [
{
"id": o.id,
"public_ref": o.public_ref,
"order_type": o.order_type,
"customer_name": o.customer_name,
"customer_phone": o.customer_phone,
"customer_address": o.customer_address,
"customer_notes": o.customer_notes,
"subtotal": o.subtotal,
"delivery_fee": o.delivery_fee,
"total": o.total,
"status": o.status,
"rejection_reason": o.rejection_reason,
"synced_to_local": o.synced_to_local,
"local_order_id": o.local_order_id,
"created_at": o.created_at.isoformat() if o.created_at else None,
"updated_at": o.updated_at.isoformat() if o.updated_at else None,
}
for o in orders
]
+111 -2
View File
@@ -1,17 +1,50 @@
import os
import secrets import secrets
import uuid import uuid
from passlib.context import CryptContext from passlib.context import CryptContext
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from auth_utils import get_current_admin from auth_utils import get_current_admin
from database import get_db from database import get_db
from models.site import Site from models.site import Site
from schemas.site import SiteCreate, SiteUpdate, SiteOut, SiteCreatedOut, LockRequest from schemas.site import SiteModulesUpdate, SiteCreate, SiteUpdate, SiteOut, SiteCreatedOut, LockRequest
router = APIRouter() router = APIRouter()
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto") _pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
HEADER_IMAGE_DIR = "/app/data/site_headers"
def _preset_modules(db: Session, name: str | None) -> dict:
if not name:
return {}
from models.plan_preset import PlanPreset
preset = db.query(PlanPreset).filter(PlanPreset.name == name).first()
if preset is None:
raise HTTPException(status_code=400, detail=f"Unknown preset: {name}")
return dict(preset.modules or {})
def _validate_modules(modules: dict) -> dict:
"""Shape check of a module map; the site ignores keys it doesn't know (newer catalogue)."""
from services.license_token import normalize_modules
from datetime import datetime as _dt
if not isinstance(modules, dict):
raise HTTPException(status_code=422, detail="modules must be an object")
for key, spec in modules.items():
if not isinstance(key, str) or not key or not isinstance(spec or {}, dict):
raise HTTPException(status_code=422, detail=f"bad module entry {key!r}")
for lk, lv in ((spec or {}).get("limits") or {}).items():
if lv is not None and (not isinstance(lv, int) or lv < 0):
raise HTTPException(status_code=422, detail=f"{key}.{lk}: limit must be a whole number >= 0 or null")
if (spec or {}).get("exp"):
try:
_dt.fromisoformat(str(spec["exp"]).replace("Z", "+00:00"))
except ValueError:
raise HTTPException(status_code=422, detail=f"{key}: exp must be an ISO date-time")
return normalize_modules(modules)
@router.get("/", response_model=list[SiteOut]) @router.get("/", response_model=list[SiteOut])
def list_sites(db: Session = Depends(get_db), _=Depends(get_current_admin)): def list_sites(db: Session = Depends(get_db), _=Depends(get_current_admin)):
@@ -28,6 +61,7 @@ def create_site(body: SiteCreate, db: Session = Depends(get_db), _=Depends(get_c
contact_email=body.contact_email, contact_email=body.contact_email,
secret_key_hash=_pwd.hash(raw_key), secret_key_hash=_pwd.hash(raw_key),
license_expires_at=body.license_expires_at, license_expires_at=body.license_expires_at,
modules=_preset_modules(db, body.preset),
) )
db.add(site) db.add(site)
db.commit() db.commit()
@@ -50,6 +84,8 @@ def update_site(site_id: str, body: SiteUpdate, db: Session = Depends(get_db), _
site = db.query(Site).filter(Site.site_id == site_id).first() site = db.query(Site).filter(Site.site_id == site_id).first()
if not site: if not site:
raise HTTPException(status_code=404, detail="Site not found") raise HTTPException(status_code=404, detail="Site not found")
if body.menu_mode is not None and body.menu_mode not in ("order", "view_only"):
raise HTTPException(status_code=400, detail="menu_mode must be 'order' or 'view_only'")
for field, value in body.model_dump(exclude_none=True).items(): for field, value in body.model_dump(exclude_none=True).items():
setattr(site, field, value) setattr(site, field, value)
db.commit() db.commit()
@@ -57,6 +93,51 @@ def update_site(site_id: str, body: SiteUpdate, db: Session = Depends(get_db), _
return site return site
@router.post("/{site_id}/header-image", response_model=SiteOut)
async def upload_header_image(site_id: str, file: UploadFile = File(...), db: Session = Depends(get_db), _=Depends(get_current_admin)):
site = db.query(Site).filter(Site.site_id == site_id).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image")
os.makedirs(HEADER_IMAGE_DIR, exist_ok=True)
if site.menu_header_image_url:
old_path = os.path.join(HEADER_IMAGE_DIR, os.path.basename(site.menu_header_image_url))
if os.path.exists(old_path):
os.remove(old_path)
filename = f"{site.site_id}_{uuid.uuid4().hex[:8]}.png"
filepath = os.path.join(HEADER_IMAGE_DIR, filename)
contents = await file.read()
with open(filepath, "wb") as f:
f.write(contents)
site.menu_header_image_url = f"/static/site_headers/{filename}"
db.commit()
db.refresh(site)
return site
@router.delete("/{site_id}/header-image", response_model=SiteOut)
def delete_header_image(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)):
site = db.query(Site).filter(Site.site_id == site_id).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
if site.menu_header_image_url:
old_path = os.path.join(HEADER_IMAGE_DIR, os.path.basename(site.menu_header_image_url))
if os.path.exists(old_path):
os.remove(old_path)
site.menu_header_image_url = None
db.commit()
db.refresh(site)
return site
@router.post("/{site_id}/lock", response_model=SiteOut) @router.post("/{site_id}/lock", response_model=SiteOut)
def lock_site(site_id: str, body: LockRequest, db: Session = Depends(get_db), _=Depends(get_current_admin)): def lock_site(site_id: str, body: LockRequest, db: Session = Depends(get_db), _=Depends(get_current_admin)):
site = db.query(Site).filter(Site.site_id == site_id).first() site = db.query(Site).filter(Site.site_id == site_id).first()
@@ -88,3 +169,31 @@ def delete_site(site_id: str, db: Session = Depends(get_db), _=Depends(get_curre
raise HTTPException(status_code=404, detail="Site not found") raise HTTPException(status_code=404, detail="Site not found")
db.delete(site) db.delete(site)
db.commit() db.commit()
# ── Licensed modules (APPS_PLATFORM D-3, §5.2) ─────────────────────────────────
@router.put("/{site_id}/modules", response_model=SiteOut)
def set_site_modules(site_id: str, body: SiteModulesUpdate, db: Session = Depends(get_db), _=Depends(get_current_admin)):
"""Replace the site's module map. The site gets it in its next heartbeat (signed token)."""
site = db.query(Site).filter(Site.site_id == site_id).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
site.modules = _validate_modules(body.modules)
db.commit()
db.refresh(site)
return site
@router.post("/{site_id}/apply-preset/{preset_id}", response_model=SiteOut)
def apply_preset(site_id: str, preset_id: int, db: Session = Depends(get_db), _=Depends(get_current_admin)):
"""Copy a preset's module map into the site (then editable per site)."""
from models.plan_preset import PlanPreset
site = db.query(Site).filter(Site.site_id == site_id).first()
preset = db.get(PlanPreset, preset_id)
if not site or not preset:
raise HTTPException(status_code=404, detail="Site or preset not found")
site.modules = dict(preset.modules or {})
db.commit()
db.refresh(site)
return site
+53
View File
@@ -0,0 +1,53 @@
"""The one way the cloud schema is created and upgraded: Alembic (APPS_PLATFORM D-22).
v1 used create_all + an ALTER list in main.py (_run_migrations); both are gone on
platform-v2. The production database predates Alembic: at cutover it is STAMPED to
0001_cloud_baseline (the exact v1 schema) and then upgraded (DEPLOYMENT_GUIDE.md,
"Platform v2 cutover"). Until it is stamped, startup refuses it, so the v2 cloud can
never half-migrate production by accident.
"""
from __future__ import annotations
import logging
from pathlib import Path
from alembic import command
from alembic.config import Config
from sqlalchemy import inspect
logger = logging.getLogger("cloud.schema")
MIGRATIONS_DIR = Path(__file__).resolve().parent / "migrations"
BASELINE = "0001_cloud_baseline"
class UnstampedDatabaseError(RuntimeError):
pass
def alembic_config(connection=None) -> Config:
cfg = Config()
cfg.set_main_option("script_location", str(MIGRATIONS_DIR))
cfg.set_main_option("file_template", "%%(rev)s")
if connection is not None:
cfg.attributes["connection"] = connection
return cfg
def upgrade_to_head(engine=None) -> None:
if engine is None:
from database import engine as app_engine
engine = app_engine
with engine.begin() as conn:
tables = set(inspect(conn).get_table_names())
if tables and "alembic_version" not in tables:
raise UnstampedDatabaseError(
"This cloud database predates Alembic (v1). Back it up, then run "
f"`alembic stamp {BASELINE}` once (DEPLOYMENT_GUIDE.md, Platform v2 cutover).")
command.upgrade(alembic_config(conn), "head")
logger.info("schema upgraded to head")
def stamp_baseline(engine) -> None:
"""Cutover helper: mark a v1 production DB as being at the baseline revision."""
with engine.begin() as conn:
command.stamp(alembic_config(conn), BASELINE)
+53
View File
@@ -0,0 +1,53 @@
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
class ManagerRegisterRequest(BaseModel):
email: str
password: str
full_name: Optional[str] = None
site_ids: list[str] = [] # site_id UUID strings, not integer PKs
class ManagerLoginRequest(BaseModel):
email: str
password: str
class ManagerTokenOut(BaseModel):
access_token: str
token_type: str = "bearer"
class ManagerSiteOut(BaseModel):
id: int
site_id: str
name: str
model_config = {"from_attributes": True}
class ManagerOut(BaseModel):
id: int
email: str
full_name: Optional[str] = None
is_active: int
created_at: datetime
sites: list[ManagerSiteOut] = []
model_config = {"from_attributes": True}
class StatsSnapshotOut(BaseModel):
site_id: int
snapshot_json: str
updated_at: datetime
model_config = {"from_attributes": True}
class StatsSnapshotRequest(BaseModel):
site_id: int
snapshot_json: str
+10
View File
@@ -0,0 +1,10 @@
from pydantic import BaseModel
class MenuSyncRequest(BaseModel):
site_id: int
snapshot_json: str
class MenuSyncResponse(BaseModel):
ok: bool
+114
View File
@@ -0,0 +1,114 @@
from __future__ import annotations
from datetime import datetime
from typing import Optional
from datetime import timezone
from pydantic import BaseModel, Field, field_serializer
def _utc(value):
"""The cloud's database keeps no time zone: a naive datetime is UTC. Sent with its offset."""
if value is None:
return None
return (value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value).isoformat()
class OrderItemIn(BaseModel):
"""What the customer wants. Prices come from the venue's menu (services/checkout.py);
name and unit_price, if sent, are only compared (phase 3S, S.2)."""
product_id: int
quantity: int
name: Optional[str] = None
unit_price: Optional[float] = None
options: list = [] # quick option ids (or {id})
class QuoteRequest(BaseModel):
order_type: str # dine_in | takeaway | delivery | preorder
items: list[OrderItemIn] = Field(max_length=100)
area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20)
class OnlineOrderCreate(BaseModel):
order_type: str # dine_in | takeaway | delivery | reservation | preorder
customer_name: str = Field(min_length=1, max_length=100)
party_size: Optional[int] = None # reservations (S.6)
customer_phone: Optional[str] = Field(default=None, max_length=40)
customer_address: Optional[str] = Field(default=None, max_length=500)
customer_notes: Optional[str] = Field(default=None, max_length=1000)
customer_table: Optional[str] = Field(default=None, max_length=40) # ignored since S.7 (the token says)
table_token: Optional[str] = Field(default=None, max_length=100) # the table's QR token (S.7)
area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20)
requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible
items: list[OrderItemIn] = Field(default_factory=list, max_length=100)
# what the customer was shown: compared, never stored as sent
subtotal: Optional[float] = None
delivery_fee: Optional[float] = None
total: Optional[float] = None
class OnlineOrderCreated(BaseModel):
order_id: int
public_ref: str
status: str
tracking_token: Optional[str] = None # the tracking page: GET /api/orders/track/{token} (S.2)
total: Optional[float] = None
class OrderStatusOut(BaseModel):
public_ref: str
status: str
rejection_reason: Optional[str] = None
# S.4: what the tracking page shows (all optional: older clients ignore them)
order_type: Optional[str] = None
requested_for: Optional[datetime] = None
party_size: Optional[int] = None # reservations (S.6)
created_at: Optional[datetime] = None
lines: Optional[list] = None
subtotal: Optional[float] = None
delivery_fee: Optional[float] = None
total: Optional[float] = None
@field_serializer('requested_for', 'created_at')
def _times(self, value):
return _utc(value)
class PendingOrderOut(BaseModel):
id: int
public_ref: str
order_type: str
customer_name: str
customer_phone: Optional[str] = None
customer_address: Optional[str] = None
customer_notes: Optional[str] = None
table_label: Optional[str] = None # the QR menu's table (S.2)
table_id: Optional[int] = None # the site's table, from a valid QR token (S.7)
delivery_area: Optional[str] = None # the delivery area's name (S.3)
delivery_area_id: Optional[int] = None # the site's area id (S.5)
requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible
party_size: Optional[int] = None # reservations (S.6)
sales_point: Optional[str] = None # the site's sales point (S.2)
items_json: str
subtotal: float
delivery_fee: float
total: float
status: str
created_at: datetime
model_config = {"from_attributes": True}
@field_serializer('requested_for', 'created_at')
def _times(self, value):
return _utc(value)
class OrderSyncedRequest(BaseModel):
local_order_id: int
class OrderStatusUpdateRequest(BaseModel):
status: str
rejection_reason: Optional[str] = None
+34 -6
View File
@@ -7,6 +7,12 @@ class SiteCreate(BaseModel):
owner_name: str owner_name: str
contact_email: str contact_email: str
license_expires_at: datetime license_expires_at: datetime
preset: str | None = "Everything (v1 sites)" # plan preset to fill `modules`; None = nothing licensed
class SiteModulesUpdate(BaseModel):
"""The whole module map: {key: {limits?: {name: int|null}, exp?: ISO datetime}}."""
modules: dict
class SiteUpdate(BaseModel): class SiteUpdate(BaseModel):
@@ -15,6 +21,13 @@ class SiteUpdate(BaseModel):
contact_email: str | None = None contact_email: str | None = None
license_expires_at: datetime | None = None license_expires_at: datetime | None = None
waiter_domain: str | None = None waiter_domain: str | None = None
menu_mode: str | None = None
menu_display_name: str | None = None
menu_tagline_en: str | None = None
menu_tagline_gr: str | None = None
menu_blurb_en: str | None = None
menu_blurb_gr: str | None = None
menu_hours: str | None = None
class SiteOut(BaseModel): class SiteOut(BaseModel):
@@ -28,10 +41,22 @@ class SiteOut(BaseModel):
lock_reason: str | None lock_reason: str | None
license_expires_at: datetime license_expires_at: datetime
created_at: datetime created_at: datetime
modules: dict = {}
module_catalog: list | None = None
module_catalog_at: datetime | None = None
last_seen_at: datetime | None last_seen_at: datetime | None
last_seen_ip: str | None last_seen_ip: str | None
last_seen_local_ip: str | None last_seen_local_ip: str | None
waiter_domain: str | None waiter_domain: str | None
menu_mode: str
menu_display_name: str | None
menu_tagline_en: str | None
menu_tagline_gr: str | None
menu_blurb_en: str | None
menu_blurb_gr: str | None
menu_hours: str | None
menu_header_image_url: str | None
apps_url: str | None = None # PUBLIC_APPS_URL: the customer apps' address (phase 3S)
model_config = {"from_attributes": True} model_config = {"from_attributes": True}
@@ -45,15 +70,18 @@ class LockRequest(BaseModel):
class HeartbeatRequest(BaseModel): class HeartbeatRequest(BaseModel):
version: str = "1.0.0" """C-1 v2 (docs/reference/cloud-contract.md)."""
uptime_seconds: int = 0 version: str
local_ip: str | None = None local_ip: str | None = None
# The modules this site's code knows (D-20): [{key, kind, name, depends, limits: [{key, ...}]}]
module_catalog: list[dict] = []
class HeartbeatResponse(BaseModel): class HeartbeatResponse(BaseModel):
licensed: bool # Signed v2 license the site stores and enforces offline (services/license_token.py).
locked: bool # Everything about licensing is inside it; there are no unsigned license fields.
lock_reason: str | None license_token: str | None
expires_at: datetime
latest_version: str | None = None latest_version: str | None = None
waiter_domain: str | None = None waiter_domain: str | None = None
site_numeric_id: int # cloud DB pk — needed by the Connect workers
apps_url: str | None = None # the customer apps' public address (S.7; table QR codes)
View File
+194
View File
@@ -0,0 +1,194 @@
"""The cloud prices online orders itself (plan phase 3S, step S.2).
The customer's browser sends what it wants (product ids, quantities, chosen quick options);
the price of everything comes from the venue's menu snapshot (pushed by the site), for the
order's sales point. A total the browser sends is only compared: a difference means the
customer saw old prices (or edited them) and the order is refused with the current ones.
price_cart(snapshot, order_type, items) -> Priced
CheckoutError(status, code, **params) the router turns it into {"detail": {code, params}}
Snapshot product (site services/cloud_sync._push_menu_snapshot):
{id, name, digital_name, base_price, digital_price, digital_discount, digital_available,
sold_at: [sales point], prices: {sales point: price}, quick_options: [{id, name, price}]}
Snapshots from before S.2 have no `prices` / `sold_at`: every customer-app sales point, at
digital_price (or base_price) less digital_discount %.
The fee (S.3): the snapshot's `fees` {areas, rules} through services/fees.py (the same file
as the site's) at the venue's time (`timezone`). A delivery outside the venue's areas ->
order.area_not_served; below a minimum -> order.minimum_not_met {minimum, subtotal}.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
from services import fees as fee_engine
# the cloud order's type → the site's sales point (core/sales_points.py)
POINT_FOR_TYPE = {
"dine_in": "qr_table",
"takeaway": "online_takeaway",
"delivery": "online_delivery",
"preorder": "online_preorder",
}
DIGITAL = tuple(POINT_FOR_TYPE.values())
MAX_QTY = 99
MAX_LINES = 100
EPS = 0.005
class CheckoutError(Exception):
def __init__(self, status: int, code: str, **params):
super().__init__(code)
self.status, self.code, self.params = status, code, params
def detail(self) -> dict:
return {"code": self.code, "params": self.params}
@dataclass
class Line:
product_id: int
name: str
quantity: int
unit_price: float
options: list = field(default_factory=list) # [{id, name, price}]
def out(self) -> dict:
return {"product_id": self.product_id, "name": self.name, "quantity": self.quantity,
"unit_price": self.unit_price, "options": self.options}
@dataclass
class Priced:
sales_point: str
lines: list
subtotal: float
delivery_fee: float
total: float
area_id: int | None = None
area_name: str | None = None
fee_rules: list = field(default_factory=list) # names of the rules that applied
def out(self) -> dict:
return {"sales_point": self.sales_point, "lines": [x.out() for x in self.lines],
"subtotal": self.subtotal, "delivery_fee": self.delivery_fee, "total": self.total,
"area_id": self.area_id, "area_name": self.area_name, "fee_rules": self.fee_rules}
def venue_clock(snapshot: dict, now: datetime | None = None) -> tuple[int, str]:
"""(weekday Mon=0, "HH:MM") at the venue, from the snapshot's time zone."""
try:
tz = ZoneInfo(snapshot.get("timezone") or "Europe/Athens")
except Exception:
tz = ZoneInfo("Europe/Athens")
local = (now or datetime.now(timezone.utc)).astimezone(tz)
return local.weekday(), local.strftime("%H:%M")
def delivery_areas(snapshot: dict) -> list:
"""The active areas a customer picks from: [{id, name}] (no postcodes, no rules)."""
return [{"id": a.get("id"), "name": a.get("name")} for a in (snapshot.get("fees") or {}).get("areas") or []
if a.get("is_active", True)]
def products_of(snapshot: dict) -> dict[int, dict]:
out: dict[int, dict] = {}
for cat in snapshot.get("categories", []):
for p in cat.get("products", []):
if isinstance(p.get("id"), int):
out.setdefault(p["id"], p) # a product listed in several categories: once
return out
def price_at(product: dict, point: str) -> float | None:
"""The product's price at a sales point; None = not sold there."""
sold = product.get("sold_at")
if sold is not None and point not in sold:
return None
prices = product.get("prices")
if prices is not None:
value = prices.get(point)
return None if value is None else round(float(value), 2)
base = product.get("digital_price")
if base is None:
base = product.get("base_price") or 0.0
pct = product.get("digital_discount") or 0.0
return round(float(base) * (1 - float(pct) / 100.0), 2)
def _display_name(product: dict) -> str:
name = product.get("digital_name") or product.get("name") or f"#{product.get('id')}"
return name if isinstance(name, str) else str(name)
def _option_ids(raw) -> list:
out = []
for o in raw or []:
oid = o.get("id") if isinstance(o, dict) else o
if not isinstance(oid, int) or isinstance(oid, bool):
raise CheckoutError(422, "order.option_unavailable", option_id=oid)
out.append(oid)
return out
def price_cart(snapshot: dict, order_type: str, items: list[dict], area_id=None, postcode=None,
now: datetime | None = None) -> Priced:
"""Price the cart from the snapshot. items: [{product_id, quantity, options?}]; the
customer's area (picked, or by postcode) for the fee."""
point = POINT_FOR_TYPE.get(order_type)
if point is None:
raise CheckoutError(422, "order.type_invalid", order_type=order_type)
if not items:
raise CheckoutError(422, "order.empty")
if len(items) > MAX_LINES:
raise CheckoutError(422, "order.too_many_lines", max=MAX_LINES)
products = products_of(snapshot)
lines = []
for it in items:
pid, qty = it.get("product_id"), it.get("quantity")
if isinstance(qty, bool) or not isinstance(qty, int) or not 1 <= qty <= MAX_QTY:
raise CheckoutError(422, "order.quantity_invalid", product_id=pid, max=MAX_QTY)
product = products.get(pid) if isinstance(pid, int) else None
unit = price_at(product, point) if product is not None else None
if product is None or unit is None or product.get("digital_available") is False:
raise CheckoutError(409, "order.item_unavailable", product_id=pid,
name=_display_name(product) if product else None)
quick = {q.get("id"): q for q in product.get("quick_options") or [] if isinstance(q, dict)}
options = []
for oid in _option_ids(it.get("options")):
q = quick.get(oid)
if q is None:
raise CheckoutError(409, "order.option_unavailable", product_id=pid, option_id=oid)
options.append({"id": oid, "name": q.get("name"), "price": round(float(q.get("price") or 0.0), 2)})
unit = round(unit + sum(o["price"] for o in options), 2)
lines.append(Line(product_id=pid, name=_display_name(product), quantity=qty, unit_price=unit, options=options))
subtotal = round(sum(x.unit_price * x.quantity for x in lines), 2)
rules = snapshot.get("fees") or {}
weekday, hhmm = venue_clock(snapshot, now)
result = fee_engine.compute(rules.get("rules") or [], rules.get("areas") or [], sales_point=point,
subtotal=subtotal, items=sum(x.quantity for x in lines),
area_id=area_id, postcode=postcode, weekday=weekday, hhmm=hhmm)
if result["refused"] == "area_not_served":
raise CheckoutError(409, "order.area_not_served", postcode=postcode, area_id=area_id)
if result["refused"] == "minimum_not_met":
raise CheckoutError(409, "order.minimum_not_met", minimum=result["minimum"], subtotal=subtotal)
fee = result["fee"]
area = next((a for a in rules.get("areas") or [] if a.get("id") == result["area_id"]), None)
return Priced(sales_point=point, lines=lines, subtotal=subtotal, delivery_fee=fee, total=round(subtotal + fee, 2),
area_id=result["area_id"], area_name=area.get("name") if area else None,
fee_rules=[a["name"] for a in result["applied"] if a["action"] != "minimum"])
def check_sent(priced: Priced, items: list[dict], total: float | None) -> None:
"""What the browser showed must be what we charge: each line's unit price (if sent) and
the total (if sent). Otherwise order.price_changed with the current prices."""
changed = total is not None and abs(float(total) - priced.total) > EPS
for sent, line in zip(items, priced.lines):
up = sent.get("unit_price")
if up is not None and abs(float(up) - line.unit_price) > EPS:
changed = True
if changed:
raise CheckoutError(409, "order.price_changed", **priced.out())
+128
View File
@@ -0,0 +1,128 @@
"""Delivery fees and minimum orders (plan phase 3S, step S.3).
ONE engine, two copies: client-services/local_backend/services/fees.py (the manager's "test
an order", the site's check of pulled orders) and cloud-service/cloud_backend/services/fees.py
(checkout). The files are identical and both repos run the same cases
(tests/fixtures/fee_cases.json); a site test fails if the copies differ. Pure Python: plain
dicts in, a dict out, no database, no clock (the caller gives the venue's weekday and time).
compute(rules, areas, *, sales_point, subtotal, items, area_id=None, postcode=None,
weekday=None, hhmm=None) -> {"fee", "refused", "minimum", "area_id", "applied"}
Areas: {id, name, postcodes: [str], is_active}. The customer's area is the one picked (by id)
or the one whose postcodes contain theirs (spaces ignored). When the venue has active areas,
a delivery to none of them is refused ("area_not_served"); with no areas, anywhere is fine.
Rules: {id, name, is_active, sort_order, sales_points: [..], area_ids: [..], subtotal_min,
subtotal_max, items_min, items_max, days: [0-6], time_from, time_to, action, value, stop}.
Inactive rules are skipped; the rest are looked at in (sort_order, id) order. A rule applies
when every condition it sets holds (empty lists / nulls = any):
sales point in sales_points · area in area_ids · subtotal_min <= subtotal < subtotal_max ·
items_min <= items <= items_max · weekday in days · time_from <= time < time_to (crosses
midnight when time_from > time_to)
What an applying rule does to the fee (which starts at 0):
set fee = value add fee += value
percent fee += subtotal × value / 100
free fee = 0 minimum refuse the order when subtotal < value
`stop`: once this rule applies, no later rule is looked at (first match wins). The fee is
never negative and is rounded to cents.
"""
from __future__ import annotations
EPS = 0.0005
ACTIONS = ("set", "add", "percent", "free", "minimum")
def _norm_postcode(value) -> str:
return "".join(str(value or "").split()).upper()
def resolve_area(areas: list, area_id=None, postcode=None):
"""The customer's active area: by id, else by postcode; None when neither matches."""
active = [a for a in areas or [] if a.get("is_active", True)]
if area_id is not None:
for a in active:
if a.get("id") == area_id:
return a
code = _norm_postcode(postcode)
if code:
for a in active:
if code in {_norm_postcode(p) for p in a.get("postcodes") or []}:
return a
return None
def _minutes(hhmm):
try:
h, m = str(hhmm).split(":")
h, m = int(h), int(m)
except (ValueError, TypeError):
return None
return h * 60 + m if 0 <= h <= 23 and 0 <= m <= 59 else None
def _in_time(rule, hhmm) -> bool:
start, end = _minutes(rule.get("time_from")), _minutes(rule.get("time_to"))
if start is None and end is None:
return True
now = _minutes(hhmm)
if now is None:
return False
start = 0 if start is None else start
end = 24 * 60 if end is None else end
return start <= now < end if start <= end else (now >= start or now < end)
def applies(rule, *, sales_point, subtotal, items, area, weekday, hhmm) -> bool:
if rule.get("sales_points") and sales_point not in rule["sales_points"]:
return False
if rule.get("area_ids") and (area is None or area.get("id") not in rule["area_ids"]):
return False
if rule.get("subtotal_min") is not None and subtotal + EPS < rule["subtotal_min"]:
return False
if rule.get("subtotal_max") is not None and subtotal + EPS >= rule["subtotal_max"]:
return False
if rule.get("items_min") is not None and items < rule["items_min"]:
return False
if rule.get("items_max") is not None and items > rule["items_max"]:
return False
if rule.get("days") and weekday not in rule["days"]:
return False
return _in_time(rule, hhmm)
def compute(rules, areas, *, sales_point, subtotal, items, area_id=None, postcode=None,
weekday=None, hhmm=None) -> dict:
area = resolve_area(areas, area_id, postcode)
result = {"fee": 0.0, "refused": None, "minimum": None, "area_id": area.get("id") if area else None, "applied": []}
if sales_point == "online_delivery" and area is None and any(a.get("is_active", True) for a in areas or []):
result["refused"] = "area_not_served"
return result
fee = 0.0
ordered = sorted((r for r in rules or [] if r.get("is_active", True) and r.get("action") in ACTIONS),
key=lambda r: (r.get("sort_order") or 0, r.get("id") or 0))
for rule in ordered:
if not applies(rule, sales_point=sales_point, subtotal=subtotal, items=items, area=area,
weekday=weekday, hhmm=hhmm):
continue
action, value = rule["action"], float(rule.get("value") or 0.0)
if action == "minimum":
if subtotal + EPS < value:
result.update(refused="minimum_not_met", minimum=round(value, 2), fee=round(max(fee, 0.0), 2))
result["applied"].append({"rule_id": rule.get("id"), "name": rule.get("name"), "action": action,
"value": value, "fee": round(max(fee, 0.0), 2)})
return result
elif action == "set":
fee = value
elif action == "add":
fee += value
elif action == "percent":
fee += subtotal * value / 100.0
elif action == "free":
fee = 0.0
result["applied"].append({"rule_id": rule.get("id"), "name": rule.get("name"), "action": action,
"value": value, "fee": round(max(fee, 0.0), 2)})
if rule.get("stop"):
break
result["fee"] = round(max(fee, 0.0), 2)
return result
+83
View File
@@ -0,0 +1,83 @@
"""
Signed license tokens for on-site servers (client-services KI-006).
Every heartbeat answer carries a token the site stores and verifies with the
public key built into its code. The site then enforces the license OFFLINE:
it keeps running until `expires_at` (+ its grace), however long it is without
internet, and nobody can extend it by editing the stored copy.
Format: <base64url(payload JSON)>.<base64url(Ed25519 signature of the first part)>
Payload v2 (platform v2, D-3, D-21; v2 sites accept nothing else):
{ v: 2, site_id, active, locked, lock_reason, expires_at, issued_at,
modules: { <module key>: { limits?: {name: int|null}, exp?: ISO } } }
`modules` comes from sites.modules (sysadmin panel). A module missing from the map is
not licensed (the site's free tier still applies). null limit = unlimited.
issued_at = the cloud's clock — the site uses it as a floor against clock rollback.
Key: LICENSE_SIGNING_KEY in the cloud .env (base64 raw Ed25519 private key,
generated once; see docs). Without it, heartbeats carry no token — old-style
behaviour — and a warning is logged.
"""
import base64
import json
import logging
from datetime import datetime, timezone
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from config import settings
logger = logging.getLogger(__name__)
_key: Ed25519PrivateKey | None = None
_warned = False
def _b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def _signing_key() -> Ed25519PrivateKey | None:
global _key, _warned
if _key is None and settings.LICENSE_SIGNING_KEY:
_key = Ed25519PrivateKey.from_private_bytes(base64.b64decode(settings.LICENSE_SIGNING_KEY))
if _key is None and not _warned:
logger.warning("LICENSE_SIGNING_KEY not set — heartbeats carry no signed license token")
_warned = True
return _key
def _iso(dt: datetime) -> str:
return (dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)).astimezone(timezone.utc).isoformat()
def normalize_modules(raw: dict) -> dict:
"""Clean a module map for the token: only `limits` and `exp`, limits int or None."""
out = {}
for key, spec in (raw or {}).items():
spec = spec or {}
entry = {}
limits = {k: (None if v is None else int(v)) for k, v in (spec.get("limits") or {}).items()}
if limits:
entry["limits"] = limits
if spec.get("exp"):
entry["exp"] = spec["exp"]
out[key] = entry
return out
def issue_license_token(site, now: datetime) -> str | None:
key = _signing_key()
if key is None:
return None
payload = {
"v": 2,
"site_id": site.site_id,
"active": bool(site.is_active),
"locked": bool(site.is_locked),
"lock_reason": site.lock_reason,
"expires_at": _iso(site.license_expires_at),
"issued_at": _iso(now),
"modules": normalize_modules(site.modules or {}),
}
body = _b64url(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
return f"{body}.{_b64url(key.sign(body.encode()))}"
+185
View File
@@ -0,0 +1,185 @@
"""When online orders are taken (plan phase 3S, step S.4).
The venue's settings travel with the menu snapshot (`ordering`, site routers/fees.py
OrderingBody) and are enforced here at checkout:
{services: ["takeaway", "delivery"], hours: {"0".."6": [["HH:MM", "HH:MM"], ...]},
prep_minutes, slot_minutes, days_ahead, asap}
- a service not in `services` → order.service_unavailable
- hours: none at all = any time; otherwise a day without ranges is closed; a range whose end
is before its start runs past midnight into the next day
- "as soon as possible" (no requested time): only while open now, and only if `asap`
- a requested time: one of slots() — on the slot grid (every slot_minutes from local
midnight), at least prep_minutes from now, within today + days_ahead, while open
Times are the venue's local time (the snapshot's `timezone`).
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
DEFAULTS = {"services": [], "hours": {}, "prep_minutes": 20, "slot_minutes": 15, "days_ahead": 0, "asap": True}
MAX_SLOTS = 300
def config(snapshot: dict) -> dict:
cfg = {**DEFAULTS, **(snapshot.get("ordering") or {})}
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 15))
cfg["prep_minutes"] = max(0, int(cfg.get("prep_minutes") or 0))
cfg["days_ahead"] = max(0, min(7, int(cfg.get("days_ahead") or 0)))
return cfg
def venue_tz(snapshot: dict) -> ZoneInfo:
try:
return ZoneInfo(snapshot.get("timezone") or "Europe/Athens")
except Exception:
return ZoneInfo("Europe/Athens")
def _mins(hhmm: str) -> int:
h, m = hhmm.split(":")
return int(h) * 60 + int(m)
def is_open(cfg: dict, local: datetime) -> bool:
hours = cfg.get("hours") or {}
if not hours:
return True
t = local.hour * 60 + local.minute
today, yesterday = str(local.weekday()), str((local.weekday() - 1) % 7)
for start, end in hours.get(today, []):
s, e = _mins(start), _mins(end)
if (s < e and s <= t < e) or (s > e and t >= s):
return True
for start, end in hours.get(yesterday, []):
s, e = _mins(start), _mins(end)
if s > e and t < e: # yesterday's range running past midnight
return True
return False
def _first_slot(cfg: dict, local_now: datetime) -> datetime:
earliest = local_now + timedelta(minutes=cfg["prep_minutes"])
step = cfg["slot_minutes"]
midnight = earliest.replace(hour=0, minute=0, second=0, microsecond=0)
mins = (earliest - midnight).total_seconds() / 60
n = int(-(-mins // step)) # round up to the grid
return midnight + timedelta(minutes=n * step)
def slots(snapshot: dict, now: datetime | None = None) -> list[datetime]:
"""The times a customer can pick (aware, venue local), in order."""
cfg, tz = config(snapshot), venue_tz(snapshot)
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
last_day = (local_now + timedelta(days=cfg["days_ahead"])).date()
out, t = [], _first_slot(cfg, local_now)
while t.date() <= last_day and len(out) < MAX_SLOTS:
if is_open(cfg, t):
out.append(t)
t = (t + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
return out
def summary(snapshot: dict, now: datetime | None = None) -> dict:
"""What the ordering app needs: services, open now, ASAP offered, the slots."""
cfg, tz = config(snapshot), venue_tz(snapshot)
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
open_now = is_open(cfg, local_now)
return {"services": cfg["services"], "open_now": open_now, "asap": bool(cfg["asap"]) and open_now,
"prep_minutes": cfg["prep_minutes"], "timezone": tz.key,
"slots": [t.isoformat() for t in slots(snapshot, now)],
"reservations": res_summary(snapshot, now)} # S.6
def check(snapshot: dict, service: str, requested_for: datetime | None, now: datetime | None = None):
"""None if the order may be placed for that time, else (code, params)."""
cfg = config(snapshot)
if service not in cfg["services"]:
return "order.service_unavailable", {"service": service}
tz = venue_tz(snapshot)
now = now or datetime.now(timezone.utc)
if requested_for is None:
if cfg["asap"] and is_open(cfg, now.astimezone(tz)):
return None
return "order.closed", {}
if requested_for.tzinfo is None:
return "order.time_invalid", {}
wanted = requested_for.astimezone(tz)
if any(abs((wanted - t).total_seconds()) < 1 for t in slots(snapshot, now)):
return None
return "order.time_invalid", {}
# ── Reservations online (plan phase 3S, step S.6) ─────────────────────────────
# The snapshot's `ordering.reservations` (site routers/fees.py ReservationsBody):
# {enabled, with_food, hours: {"0".."6": [[from, to], ...]}, slot_minutes, days_ahead,
# notice_minutes, party_max, fire_minutes}
# "reservation" = a table only; "preorder" = a table with food ready on arrival (with_food).
# Times: on the slot grid of the venue's day, at least notice_minutes from now, within today +
# days_ahead, inside the hours (none = any time). fire_minutes is the site's (the kitchen).
RES_DEFAULTS = {"enabled": False, "with_food": False, "hours": {}, "slot_minutes": 30, "days_ahead": 30,
"notice_minutes": 60, "party_max": 10}
RES_TYPES = ("reservation", "preorder")
def res_config(snapshot: dict) -> dict:
cfg = {**RES_DEFAULTS, **((snapshot.get("ordering") or {}).get("reservations") or {})}
cfg["enabled"] = bool(cfg.get("enabled"))
cfg["with_food"] = cfg["enabled"] and bool(cfg.get("with_food"))
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 30))
cfg["days_ahead"] = max(0, min(90, int(cfg.get("days_ahead") or 0)))
cfg["notice_minutes"] = max(0, int(cfg.get("notice_minutes") or 0))
cfg["party_max"] = max(1, min(100, int(cfg.get("party_max") or 1)))
return cfg
def res_slots(snapshot: dict, day, now: datetime | None = None) -> list[datetime]:
"""The reservation times on one venue day (a date), aware venue local, in order."""
cfg, tz = res_config(snapshot), venue_tz(snapshot)
if not cfg["enabled"]:
return []
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
if day < local_now.date() or day > (local_now + timedelta(days=cfg["days_ahead"])).date():
return []
earliest = local_now + timedelta(minutes=cfg["notice_minutes"])
t = datetime(day.year, day.month, day.day, tzinfo=tz)
out = []
while t.date() == day:
if t >= earliest and is_open(cfg, t):
out.append(t)
t = (t.astimezone(timezone.utc) + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
return out
def res_days(snapshot: dict, now: datetime | None = None) -> list[str]:
"""The venue days (ISO dates) with at least one reservation time."""
cfg, tz = res_config(snapshot), venue_tz(snapshot)
if not cfg["enabled"]:
return []
today = (now or datetime.now(timezone.utc)).astimezone(tz).date()
days = (today + timedelta(days=n) for n in range(cfg["days_ahead"] + 1))
return [d.isoformat() for d in days if res_slots(snapshot, d, now)]
def res_summary(snapshot: dict, now: datetime | None = None) -> dict:
cfg = res_config(snapshot)
return {"enabled": cfg["enabled"], "with_food": cfg["with_food"], "party_max": cfg["party_max"],
"days": res_days(snapshot, now)}
def res_check(snapshot: dict, order_type: str, requested_for: datetime | None, party_size, now: datetime | None = None):
"""None if the reservation may be requested, else (code, params)."""
cfg = res_config(snapshot)
if not cfg["enabled"] or (order_type == "preorder" and not cfg["with_food"]):
return "order.service_unavailable", {"service": order_type}
if isinstance(party_size, bool) or not isinstance(party_size, int) or not 1 <= party_size <= cfg["party_max"]:
return "order.party_invalid", {"max": cfg["party_max"]}
if requested_for is None or requested_for.tzinfo is None:
return "order.time_invalid", {}
wanted = requested_for.astimezone(venue_tz(snapshot))
if any(abs((wanted - t).total_seconds()) < 1 for t in res_slots(snapshot, wanted.date(), now)):
return None
return "order.time_invalid", {}
+35
View File
@@ -0,0 +1,35 @@
"""The QR menu at the table (plan phase 3S, step S.7).
Each table's QR code carries a random token the venue's server made for that table
(client-services services/table_qr.py). The menu snapshot brings, under `qr`:
{ordering: bool, tables: [{id, label, token_hash}]} token_hash = sha256(token) hex
so the cloud never holds the tokens themselves, and a token is checked by its hash. A new
QR code for a table (the venue "rotates" it) makes the old one useless at the next menu push.
Ordering at the table needs the venue's `ordering`, the site's menu_mode "order" (sysadmin)
and a valid token; otherwise the QR menu is read-only. The public menu never shows `qr`.
"""
from __future__ import annotations
import hashlib
import hmac
def token_hash(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def table_for(snapshot: dict, token: str | None) -> dict | None:
"""{id, label} of the table this token belongs to, or None."""
if not token or not isinstance(token, str) or len(token) > 100:
return None
wanted = token_hash(token)
for t in (snapshot.get("qr") or {}).get("tables") or []:
if isinstance(t, dict) and hmac.compare_digest(str(t.get("token_hash") or ""), wanted):
return {"id": t.get("id"), "label": t.get("label")}
return None
def ordering_on(snapshot: dict, site) -> bool:
return site.menu_mode == "order" and bool((snapshot.get("qr") or {}).get("ordering"))
+44
View File
@@ -0,0 +1,44 @@
"""A small in-memory rate limit for the public endpoints (CL-4, plan phase 3S S.4).
hit(bucket, key, limit, per_seconds) -> bool True = allowed (and counted)
client_ip(request) the caller's address behind the proxy
Per process (the cloud runs one); a restart forgets. Enough to stop a script hammering the
order endpoint; not a defence against a distributed attack (that's the proxy's job).
"""
from __future__ import annotations
import threading
import time
from collections import deque
_lock = threading.Lock()
_hits: dict[tuple[str, str], deque] = {}
_MAX_KEYS = 50_000
def hit(bucket: str, key: str, limit: int, per_seconds: float, now: float | None = None) -> bool:
now = time.monotonic() if now is None else now
with _lock:
if len(_hits) > _MAX_KEYS: # never grow without bound
_hits.clear()
q = _hits.setdefault((bucket, key), deque())
while q and now - q[0] >= per_seconds:
q.popleft()
if len(q) >= limit:
return False
q.append(now)
return True
def reset() -> None:
with _lock:
_hits.clear()
def client_ip(request) -> str:
"""The first X-Forwarded-For address (the VPS proxy sets it), else the socket's."""
fwd = request.headers.get("x-forwarded-for", "")
if fwd:
return fwd.split(",")[0].strip() or "?"
return getattr(request.client, "host", None) or "?"
+51
View File
@@ -0,0 +1,51 @@
"""Cloud backend tests. Run from cloud_backend/: python -m pytest tests -q
Before anything imports config/database, DATABASE_URL points at a fresh temp file and a
throwaway LICENSE_SIGNING_KEY is set, so tests never touch a real cloud DB or key.
"""
import base64
import os
import sys
import tempfile
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
_TMP = Path(tempfile.mkdtemp(prefix="xenia-cloud-tests-"))
os.environ["DATABASE_URL"] = f"sqlite:///{(_TMP / 'cloud.db').as_posix()}"
TEST_KEY = Ed25519PrivateKey.generate()
os.environ["LICENSE_SIGNING_KEY"] = base64.b64encode(
TEST_KEY.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw,
serialization.NoEncryption())).decode()
TEST_PUB = base64.b64encode(TEST_KEY.public_key().public_bytes(
serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode()
os.environ["ADMIN_USERNAME"] = "sysadmin"
os.environ["ADMIN_PASSWORD"] = "test-admin-pw"
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import pytest # noqa: E402
@pytest.fixture(scope="session")
def client():
from fastapi.testclient import TestClient
import main
with TestClient(main.app) as c: # runs the lifespan: Alembic upgrade + default admin
yield c
@pytest.fixture(scope="session")
def admin_h(client):
r = client.post("/api/auth/login", json={"username": "sysadmin", "password": "test-admin-pw"})
assert r.status_code == 200, r.text
return {"Authorization": f"Bearer {r.json()['access_token']}"}
@pytest.fixture(autouse=True)
def _fresh_rate_limits():
"""Every test starts with empty rate-limit counters (services/ratelimit.py, S.4)."""
from services import ratelimit
ratelimit.reset()
yield
+108
View File
@@ -0,0 +1,108 @@
{
"_about": "Delivery fee cases (plan phase 3S, S.3). The SAME file in client-services/local_backend/tests/fixtures and cloud-service/cloud_backend/tests/fixtures; both repos run every case through their copy of services/fees.py.",
"areas": [
{"id": 1, "name": "Village centre", "postcodes": ["241 00"], "is_active": true},
{"id": 2, "name": "Kalamata", "postcodes": ["24100", "24131"], "is_active": true},
{"id": 3, "name": "Old area", "postcodes": ["99999"], "is_active": false}
],
"cases": [
{"name": "no rules: free",
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "fixed fee",
"rules": [{"id": 1, "name": "Delivery", "sales_points": ["online_delivery"], "action": "set", "value": 2.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 1},
"expect": {"fee": 2.5, "refused": null, "area_id": 1}},
{"name": "fixed fee does not touch takeaway",
"rules": [{"id": 1, "name": "Delivery", "sales_points": ["online_delivery"], "action": "set", "value": 2.5}],
"ctx": {"sales_point": "online_takeaway", "subtotal": 12, "items": 2},
"expect": {"fee": 0.0, "refused": null, "area_id": null}},
{"name": "by area: the far area costs more (area by postcode, spaces ignored)",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5},
{"id": 2, "name": "Kalamata", "area_ids": [2], "action": "set", "value": 3.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "postcode": "241 31"},
"expect": {"fee": 3.5, "refused": null, "area_id": 2}},
{"name": "by area: the near area keeps the base",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5},
{"id": 2, "name": "Kalamata", "area_ids": [2], "action": "set", "value": 3.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "area_id": 1},
"expect": {"fee": 1.5, "refused": null, "area_id": 1}},
{"name": "area not served (unknown postcode)",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 1.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "postcode": "11111"},
"expect": {"fee": 0.0, "refused": "area_not_served", "area_id": null}},
{"name": "an inactive area is not served",
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 3, "area_id": 3},
"expect": {"fee": 0.0, "refused": "area_not_served", "area_id": null}},
{"name": "free above 25 (first match wins)",
"rules": [{"id": 1, "name": "Free over 25", "subtotal_min": 25, "action": "free", "stop": true, "sort_order": 0},
{"id": 2, "name": "Base", "action": "set", "value": 2.0, "sort_order": 1}],
"ctx": {"sales_point": "online_delivery", "subtotal": 30, "items": 4, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "free above 25: below it pays",
"rules": [{"id": 1, "name": "Free over 25", "subtotal_min": 25, "action": "free", "stop": true, "sort_order": 0},
{"id": 2, "name": "Base", "action": "set", "value": 2.0, "sort_order": 1}],
"ctx": {"sales_point": "online_delivery", "subtotal": 24.99, "items": 4, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "lower above 15 (subtotal range)",
"rules": [{"id": 1, "name": "Under 15", "subtotal_max": 15, "action": "set", "value": 3.0},
{"id": 2, "name": "15 and up", "subtotal_min": 15, "action": "set", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 15, "items": 2, "area_id": 1},
"expect": {"fee": 1.0, "refused": null, "area_id": 1}},
{"name": "item-count tier: a big order adds 1",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Big order", "items_min": 10, "action": "add", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 40, "items": 12, "area_id": 1},
"expect": {"fee": 3.0, "refused": null, "area_id": 1}},
{"name": "item-count tier: a small order pays the base only",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Big order", "items_min": 10, "action": "add", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 40, "items": 9, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "percent of the products",
"rules": [{"id": 1, "name": "5 %", "action": "percent", "value": 5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 33, "items": 3, "area_id": 1},
"expect": {"fee": 1.65, "refused": null, "area_id": 1}},
{"name": "minimum order refused",
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 10},
{"id": 2, "name": "Base", "action": "set", "value": 2.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 8.5, "items": 1, "area_id": 1},
"expect": {"fee": 0.0, "refused": "minimum_not_met", "minimum": 10.0, "area_id": 1}},
{"name": "minimum met: the fee rules go on",
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 10},
{"id": 2, "name": "Base", "action": "set", "value": 2.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 10, "items": 1, "area_id": 1},
"expect": {"fee": 2.0, "refused": null, "area_id": 1}},
{"name": "a higher minimum for the far area",
"rules": [{"id": 1, "name": "Far minimum", "area_ids": [2], "action": "minimum", "value": 15},
{"id": 2, "name": "Minimum", "action": "minimum", "value": 10}],
"ctx": {"sales_point": "online_delivery", "subtotal": 12, "items": 2, "area_id": 2},
"expect": {"fee": 0.0, "refused": "minimum_not_met", "minimum": 15.0, "area_id": 2}},
{"name": "stacking: base + late-night surcharge",
"rules": [{"id": 1, "name": "Base", "action": "set", "value": 2.0},
{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 4, "hhmm": "23:30"},
"expect": {"fee": 2.5, "refused": null, "area_id": 1}},
{"name": "time window crossing midnight, after midnight",
"rules": [{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 5, "hhmm": "01:15"},
"expect": {"fee": 0.5, "refused": null, "area_id": 1}},
{"name": "time window, outside",
"rules": [{"id": 2, "name": "Late", "time_from": "22:00", "time_to": "02:00", "action": "add", "value": 0.5}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 5, "hhmm": "12:00"},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "weekend only",
"rules": [{"id": 1, "name": "Weekend", "days": [5, 6], "action": "set", "value": 1.0}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1, "weekday": 2, "hhmm": "12:00"},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "an inactive rule is skipped; the fee is never negative",
"rules": [{"id": 1, "name": "Off", "is_active": false, "action": "set", "value": 9},
{"id": 2, "name": "Discount", "action": "add", "value": -2}],
"ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 1},
"expect": {"fee": 0.0, "refused": null, "area_id": 1}},
{"name": "a takeaway packaging fee (areas only matter for delivery)",
"rules": [{"id": 1, "name": "Packaging", "sales_points": ["online_takeaway"], "action": "set", "value": 0.3}],
"ctx": {"sales_point": "online_takeaway", "subtotal": 9, "items": 3, "postcode": "nowhere"},
"expect": {"fee": 0.3, "refused": null, "area_id": null}}
]
}
+118
View File
@@ -0,0 +1,118 @@
-- The v1 production cloud schema (create_all + _run_migrations on main, 2026-11-12).
-- Frozen fixture for tests/test_schema.py: the v2 baseline must equal it, and a DB
-- in this shape must stamp + upgrade cleanly (APPS_PLATFORM D-22). Never edit.
CREATE TABLE admins (
id INTEGER NOT NULL,
username VARCHAR NOT NULL,
password_hash VARCHAR NOT NULL,
role VARCHAR,
PRIMARY KEY (id),
UNIQUE (username)
);
CREATE TABLE manager_accounts (
id INTEGER NOT NULL,
email VARCHAR NOT NULL,
password_hash VARCHAR NOT NULL,
full_name VARCHAR,
is_active INTEGER NOT NULL,
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id)
);
CREATE TABLE manager_site_access (
manager_id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
PRIMARY KEY (manager_id, site_id),
FOREIGN KEY(manager_id) REFERENCES manager_accounts (id),
FOREIGN KEY(site_id) REFERENCES sites (id)
);
CREATE TABLE menu_snapshots (
id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
snapshot_json TEXT NOT NULL,
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id),
FOREIGN KEY(site_id) REFERENCES sites (id)
);
CREATE TABLE online_orders (
id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
public_ref VARCHAR NOT NULL,
order_type VARCHAR NOT NULL,
customer_name VARCHAR NOT NULL,
customer_phone VARCHAR,
customer_address TEXT,
customer_notes TEXT,
items_json TEXT NOT NULL,
subtotal FLOAT NOT NULL,
delivery_fee FLOAT NOT NULL,
total FLOAT NOT NULL,
status VARCHAR NOT NULL,
rejection_reason VARCHAR,
synced_to_local INTEGER NOT NULL,
local_order_id INTEGER,
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id),
FOREIGN KEY(site_id) REFERENCES sites (id),
UNIQUE (public_ref)
);
CREATE TABLE product_images (
id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
image_url VARCHAR NOT NULL,
image_hash VARCHAR NOT NULL,
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id),
CONSTRAINT uq_product_images_site_product UNIQUE (site_id, product_id),
FOREIGN KEY(site_id) REFERENCES sites (id)
);
CREATE TABLE sites (
id INTEGER NOT NULL,
site_id VARCHAR NOT NULL,
name VARCHAR NOT NULL,
owner_name VARCHAR NOT NULL,
contact_email VARCHAR NOT NULL,
secret_key_hash VARCHAR NOT NULL,
is_active BOOLEAN,
is_locked BOOLEAN,
lock_reason VARCHAR,
license_expires_at DATETIME NOT NULL,
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
last_seen_at DATETIME,
last_seen_ip VARCHAR,
last_seen_local_ip VARCHAR,
waiter_domain VARCHAR,
order_counter INTEGER NOT NULL,
menu_mode VARCHAR NOT NULL,
menu_display_name VARCHAR,
menu_tagline_en VARCHAR,
menu_tagline_gr VARCHAR,
menu_blurb_en VARCHAR,
menu_blurb_gr VARCHAR,
menu_hours VARCHAR,
menu_header_image_url VARCHAR, menu_hours_en VARCHAR, menu_hours_gr VARCHAR,
PRIMARY KEY (id)
);
CREATE TABLE stats_snapshots (
id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
snapshot_json TEXT NOT NULL,
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id),
UNIQUE (site_id),
FOREIGN KEY(site_id) REFERENCES sites (id)
);
CREATE INDEX ix_admins_id ON admins (id);
CREATE UNIQUE INDEX ix_manager_accounts_email ON manager_accounts (email);
CREATE INDEX ix_manager_accounts_id ON manager_accounts (id);
CREATE INDEX ix_menu_snapshots_id ON menu_snapshots (id);
CREATE UNIQUE INDEX ix_menu_snapshots_site_id ON menu_snapshots (site_id);
CREATE INDEX ix_online_orders_id ON online_orders (id);
CREATE INDEX ix_online_orders_site_id ON online_orders (site_id);
CREATE INDEX ix_online_orders_status ON online_orders (status);
CREATE INDEX ix_product_images_id ON product_images (id);
CREATE INDEX ix_product_images_site_id ON product_images (site_id);
CREATE INDEX ix_sites_id ON sites (id);
CREATE UNIQUE INDEX ix_sites_site_id ON sites (site_id);
+142
View File
@@ -0,0 +1,142 @@
"""The cloud prices online orders itself; sites only touch their own data (plan phase 3S, S.2).
Done when: a tampered price or total is refused, a correct order is stored with the cloud's
prices, and one site can't read or overwrite another's data."""
import json
from test_licensing_v2 import _heartbeat, _new_site
COLA, PIE, SOUP = 11, 12, 13
# online ordering on, any time (no hours), as soon as possible (S.4)
ORDERING = {"services": ["takeaway", "delivery"], "hours": {}, "prep_minutes": 20, "slot_minutes": 15, "days_ahead": 0, "asap": True}
def _h(site):
return {"X-Site-ID": site["site_id"], "X-Site-Key": site["secret_key"]}
def _menu(client, site, numeric):
"""A snapshot as the site pushes it after S.2: prices per sales point, where it's sold."""
snap = {"categories": [{"id": 1, "name": "All", "products": [
{"id": COLA, "name": "Cola 1.5L", "base_price": 3.5, "digital_price": 3.0, "digital_available": True,
"sold_at": ["qr_table", "online_takeaway", "online_delivery"],
"prices": {"qr_table": 3.0, "online_takeaway": 2.5, "online_delivery": 2.8},
"quick_options": [{"id": 7, "name": "Ice", "price": 0.2}]},
{"id": PIE, "name": "Pie", "base_price": 5.0, "digital_price": 5.0, "digital_available": True,
"sold_at": ["qr_table"], "prices": {"qr_table": 5.0}, "quick_options": []},
{"id": SOUP, "name": "Soup", "base_price": 6.0, "digital_price": 6.0, "digital_available": False,
"sold_at": ["qr_table", "online_delivery"], "prices": {"qr_table": 6.0, "online_delivery": 6.0}, "quick_options": []},
]}], "ordering": ORDERING, "timezone": "Europe/Athens"}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
assert r.status_code == 200, r.text
def _venue(client, admin_h):
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
_menu(client, site, numeric)
return site, numeric
def _order(client, site, order_type="takeaway", **extra):
body = {"order_type": order_type, "customer_name": "Maria", "customer_phone": "6900000000",
"items": [{"product_id": COLA, "quantity": 2}], **extra}
return client.post(f"/api/orders/{site['site_id']}", json=body)
def _code(r):
return r.json()["detail"]["code"]
def test_the_cloud_prices_by_sales_point(client, admin_h):
site, _ = _venue(client, admin_h)
q = lambda t, items: client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": t, "items": items}) # noqa: E731
take = q("takeaway", [{"product_id": COLA, "quantity": 2, "options": [7]}]).json()
assert (take["sales_point"], take["lines"][0]["unit_price"], take["total"]) == ("online_takeaway", 2.7, 5.4)
assert q("dine_in", [{"product_id": COLA, "quantity": 1}]).json()["total"] == 3.0
assert q("delivery", [{"product_id": COLA, "quantity": 1}]).json()["total"] == 2.8
assert _code(q("takeaway", [{"product_id": PIE, "quantity": 1}])) == "order.item_unavailable" # QR menu only
assert _code(q("delivery", [{"product_id": SOUP, "quantity": 1}])) == "order.item_unavailable" # out of stock now
assert _code(q("takeaway", [{"product_id": 999, "quantity": 1}])) == "order.item_unavailable"
assert _code(q("takeaway", [{"product_id": COLA, "quantity": 0}])) == "order.quantity_invalid"
assert _code(q("takeaway", [{"product_id": COLA, "quantity": 1, "options": [8]}])) == "order.option_unavailable"
assert _code(q("teleport", [{"product_id": COLA, "quantity": 1}])) == "order.type_invalid"
assert _code(q("takeaway", [])) == "order.empty"
def test_a_tampered_order_is_refused_and_a_correct_one_stored_at_the_clouds_prices(client, admin_h):
"""The done-when, first part."""
site, numeric = _venue(client, admin_h)
r = _order(client, site, items=[{"product_id": COLA, "quantity": 2, "unit_price": 0.01}], subtotal=0.02, total=0.02)
assert r.status_code == 409 and _code(r) == "order.price_changed"
assert r.json()["detail"]["params"]["total"] == 5.0 # the current prices come back
assert _code(_order(client, site, total=1.0)) == "order.price_changed"
ok = _order(client, site, total=5.0, delivery_fee=-3, customer_table=" ")
assert ok.status_code == 201, ok.text
pending = client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()
stored = next(o for o in pending if o["public_ref"] == ok.json()["public_ref"])
assert (stored["subtotal"], stored["delivery_fee"], stored["total"], stored["sales_point"]) == (5.0, 0.0, 5.0, "online_takeaway")
assert json.loads(stored["items_json"]) == [{"product_id": COLA, "name": "Cola 1.5L", "quantity": 2, "unit_price": 2.5, "options": []}]
# no total sent at all: priced by the cloud anyway (the old menu app's fields are optional)
assert _order(client, site).status_code == 201
def test_delivery_details(client, admin_h):
site, numeric = _venue(client, admin_h) # table orders: tests/test_qr.py (S.7)
assert _code(_order(client, site, "delivery")) == "order.details_missing"
assert _order(client, site, "delivery", customer_address="Main square 3").status_code == 201
def test_a_site_only_touches_its_own_data(client, admin_h):
"""The done-when, second part: a site's key can't read or overwrite another site's data."""
a, a_num = _venue(client, admin_h)
b, b_num = _venue(client, admin_h)
assert _order(client, a).status_code == 201
assert client.get(f"/api/orders/pending/{a_num}", headers=_h(b)).status_code == 403
assert client.post("/api/menu/sync", headers=_h(b), json={"site_id": a_num, "snapshot_json": "{}"}).status_code == 403
assert client.post("/api/remote/snapshot", headers=_h(b), json={"site_id": a_num, "snapshot_json": "{}"}).status_code == 403
# a's menu is intact
assert _order(client, a, total=5.0).status_code == 201
assert client.post("/api/menu/sync", headers=_h(a), json={"site_id": a_num, "snapshot_json": "not json"}).status_code == 422
def test_a_snapshot_from_before_s2_still_prices(client, admin_h):
"""A site that hasn't updated yet pushes digital_price / digital_discount only."""
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
old = {"categories": [{"id": 1, "name": "All", "products": [
{"id": COLA, "name": "Cola", "base_price": 4.0, "digital_price": None, "digital_discount": 25, "digital_available": True,
"quick_options": []}]}]}
client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(old)})
r = client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "dine_in", "items": [{"product_id": COLA, "quantity": 1}]})
assert r.json()["total"] == 3.0
def test_order_numbers_per_site_and_tracking_by_token(client, admin_h):
"""Two venues both have an ORD-0001 (the second used to fail); the customer tracks their
order by its random token, and the bare number no longer identifies it."""
a, _ = _venue(client, admin_h)
b, _ = _venue(client, admin_h)
ra, rb = _order(client, a).json(), _order(client, b).json()
assert ra["public_ref"] == rb["public_ref"] == "ORD-0001"
assert ra["tracking_token"] != rb["tracking_token"] and ra["total"] == 5.0
t = client.get(f"/api/orders/track/{ra['tracking_token']}")
tj = t.json()
assert t.status_code == 200 and (tj["public_ref"], tj["status"], tj["rejection_reason"], tj["total"]) == ("ORD-0001", "pending_acceptance", None, 5.0)
assert tj["lines"] == [{"name": "Cola 1.5L", "quantity": 2, "unit_price": 2.5, "options": []}] and tj["order_type"] == "takeaway"
assert client.get("/api/orders/status/ORD-0001").status_code == 404 # ambiguous now
assert client.get("/api/orders/track/nope").status_code == 404
def test_the_public_menu_carries_each_products_allergens(client, admin_h):
"""Plan step 6.3 (contract C-2): the site sends `allergens` {key: contains | may_contain} per
product; the public menu passes them to the QR menu and the order app as they are."""
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
snap = {"categories": [{"id": 1, "name": "All", "products": [
{"id": PIE, "name": "Pie", "base_price": 5.0, "digital_price": 5.0, "digital_available": True,
"sold_at": ["qr_table"], "prices": {"qr_table": 5.0}, "quick_options": [],
"allergens": {"gluten": "contains", "sesame": "may_contain"}}]}], "ordering": ORDERING, "timezone": "Europe/Athens"}
assert client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)}).status_code == 200
menu = client.get(f"/api/menu/{site['site_id']}").json()
assert menu["categories"][0]["products"][0]["allergens"] == {"gluten": "contains", "sesame": "may_contain"}
+86
View File
@@ -0,0 +1,86 @@
"""Delivery fees at checkout (plan phase 3S, step S.3).
The engine (services/fees.py) is the site's file; both repos run the same cases
(tests/fixtures/fee_cases.json, identical in both; the site's tests check the copies match).
Done when (cloud half): the cloud charges the venue's fee and refuses an order below the minimum."""
import json
from datetime import datetime, timezone
from pathlib import Path
import pytest
from test_checkout import COLA, ORDERING, _code, _h, _menu, _order
from test_licensing_v2 import _heartbeat, _new_site
CASES = json.loads((Path(__file__).resolve().parent / "fixtures" / "fee_cases.json").read_text(encoding="utf-8"))
@pytest.mark.parametrize("case", CASES["cases"], ids=[c["name"] for c in CASES["cases"]])
def test_shared_fee_cases(case):
from services.fees import compute
got = compute(case["rules"], CASES["areas"], **case["ctx"])
for key, value in case["expect"].items():
assert got[key] == value, (key, got)
FEES = {"areas": [{"id": 1, "name": "Centre", "postcodes": ["24100"], "is_active": True},
{"id": 2, "name": "Far", "postcodes": ["24131"], "is_active": True}],
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 5, "sales_points": ["online_delivery"]},
{"id": 2, "name": "Base", "action": "set", "value": 2, "sales_points": ["online_delivery"]},
{"id": 3, "name": "Far", "area_ids": [2], "action": "add", "value": 1.5, "sales_points": ["online_delivery"]}]}
def _venue_with_fees(client, admin_h):
site = _new_site(client, admin_h)
numeric = _heartbeat(client, site)["site_numeric_id"]
_menu(client, site, numeric)
# the same menu plus the venue's fees, as the site pushes them since S.3
menu = client.get(f"/api/menu/{site['site_id']}").json()
snap = {"categories": menu["categories"], "fees": FEES, "ordering": ORDERING, "timezone": "Europe/Athens"}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
assert r.status_code == 200
return site, numeric
def _quote(client, site, **body):
return client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "delivery", **body})
def test_the_cloud_charges_the_venues_fee(client, admin_h):
site, numeric = _venue_with_fees(client, admin_h)
q = _quote(client, site, items=[{"product_id": COLA, "quantity": 2}], area_id=1).json() # 2 × 2.8 delivery price
assert (q["subtotal"], q["delivery_fee"], q["total"], q["area_name"], q["fee_rules"]) == (5.6, 2.0, 7.6, "Centre", ["Base"])
q = _quote(client, site, items=[{"product_id": COLA, "quantity": 2}], postcode="241 31").json()
assert (q["delivery_fee"], q["area_name"]) == (3.5, "Far")
# the order: the fee is the cloud's, whatever the page sends; the area is stored
assert _code(_order(client, site, "delivery", customer_address="Main sq. 3", area_id=1, delivery_fee=0, total=5.6)) == "order.price_changed"
ok = _order(client, site, "delivery", customer_address="Main sq. 3", area_id=1, total=7.6)
assert ok.status_code == 201, ok.text
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == ok.json()["public_ref"])
assert (stored["delivery_fee"], stored["total"], stored["delivery_area"], stored["delivery_area_id"]) == (2.0, 7.6, "Centre", 1)
# takeaway: the delivery rules don't apply
assert client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "takeaway", "items": [{"product_id": COLA, "quantity": 1}]}).json()["delivery_fee"] == 0
def test_minimum_and_area_are_refused(client, admin_h):
site, _ = _venue_with_fees(client, admin_h)
r = _quote(client, site, items=[{"product_id": COLA, "quantity": 1}], area_id=1)
assert r.status_code == 409 and _code(r) == "order.minimum_not_met"
assert r.json()["detail"]["params"] == {"minimum": 5.0, "subtotal": 2.8}
assert _code(_order(client, site, "delivery", customer_address="x", area_id=1, items=[{"product_id": COLA, "quantity": 1}])) == "order.minimum_not_met"
assert _code(_quote(client, site, items=[{"product_id": COLA, "quantity": 2}], postcode="10431")) == "order.area_not_served"
assert _code(_quote(client, site, items=[{"product_id": COLA, "quantity": 2}])) == "order.area_not_served"
def test_the_public_menu_lists_areas_but_not_the_rules(client, admin_h):
site, _ = _venue_with_fees(client, admin_h)
menu = client.get(f"/api/menu/{site['site_id']}").json()
assert menu["delivery_areas"] == [{"id": 1, "name": "Centre"}, {"id": 2, "name": "Far"}]
assert "fees" not in menu
def test_the_venue_clock():
from services.checkout import venue_clock
at = datetime(2026, 11, 15, 21, 30, tzinfo=timezone.utc) # Sunday 23:30 in Athens (UTC+2)
assert venue_clock({"timezone": "Europe/Athens"}, at) == (6, "23:30")
assert venue_clock({"timezone": "Nowhere/Bad"}, at) == (6, "23:30")
+101
View File
@@ -0,0 +1,101 @@
"""License token v2, site modules, presets, heartbeat catalogue (plan step 1.7, D-3, D-20, D-21)."""
import base64
import json
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from conftest import TEST_PUB
def _decode(token):
body, sig = token.split(".")
pad = lambda s: s + "=" * (-len(s) % 4) # noqa: E731
Ed25519PublicKey.from_public_bytes(base64.b64decode(TEST_PUB)).verify(
base64.urlsafe_b64decode(pad(sig)), body.encode()) # raises if the signature is wrong
return json.loads(base64.urlsafe_b64decode(pad(body)))
def _new_site(client, admin_h, **extra):
r = client.post("/api/sites/", headers=admin_h, json={
"name": "Test", "owner_name": "O", "contact_email": "o@example.com",
"license_expires_at": "2027-06-01T00:00:00+00:00", **extra})
assert r.status_code == 201, r.text
return r.json()
def _heartbeat(client, site, catalog=()):
r = client.post("/api/heartbeat/", headers={"X-Site-ID": site["site_id"], "X-Site-Key": site["secret_key"]},
json={"version": "2.0.0", "local_ip": "192.168.1.10", "module_catalog": list(catalog)})
assert r.status_code == 200, r.text
return r.json()
def test_normalize_modules():
from services.license_token import normalize_modules
assert normalize_modules({"kds": {"limits": {"devices": "2"}, "junk": 1}, "tabs": None}) == \
{"kds": {"limits": {"devices": 2}}, "tabs": {}}
def test_new_site_gets_default_preset_and_v2_token(client, admin_h):
site = _new_site(client, admin_h)
assert "ordering" in site["modules"]
hb = _heartbeat(client, site)
assert set(hb) == {"license_token", "latest_version", "waiter_domain", "site_numeric_id", "apps_url"}
p = _decode(hb["license_token"])
assert p["v"] == 2 and p["site_id"] == site["site_id"] and p["modules"]["kds"] == {"limits": {"devices": None}}
assert {"active", "locked", "expires_at", "issued_at"} <= set(p)
def test_site_without_preset_licenses_nothing(client, admin_h):
site = _new_site(client, admin_h, preset=None)
assert _decode(_heartbeat(client, site)["license_token"])["modules"] == {}
def test_editing_modules_changes_the_next_token(client, admin_h):
site = _new_site(client, admin_h)
r = client.put(f"/api/sites/{site['site_id']}/modules", headers=admin_h,
json={"modules": {"ordering": {}, "kds": {"limits": {"devices": 2}},
"caller_id": {"exp": "2027-01-31T00:00:00+00:00"}}})
assert r.status_code == 200, r.text
mods = _decode(_heartbeat(client, site)["license_token"])["modules"]
assert mods == {"ordering": {}, "kds": {"limits": {"devices": 2}},
"caller_id": {"exp": "2027-01-31T00:00:00+00:00"}}
def test_bad_module_maps_are_refused(client, admin_h):
site = _new_site(client, admin_h)
for bad in ({"kds": {"limits": {"devices": -1}}}, {"kds": {"limits": {"devices": "x"}}},
{"caller_id": {"exp": "tomorrow"}}):
assert client.put(f"/api/sites/{site['site_id']}/modules", headers=admin_h, json={"modules": bad}).status_code == 422
def test_heartbeat_stores_the_module_catalogue(client, admin_h):
site = _new_site(client, admin_h)
catalog = [{"key": "kds", "kind": "app", "name": "Kitchen display", "depends": ["ordering"],
"limits": [{"key": "devices", "free": 0, "licensed_default": 1}]}]
_heartbeat(client, site, catalog)
got = client.get(f"/api/sites/{site['site_id']}", headers=admin_h).json()
assert got["module_catalog"] == catalog and got["module_catalog_at"]
def test_presets_crud_and_apply(client, admin_h):
r = client.post("/api/presets/", headers=admin_h, json={"name": "Cafe basic", "description": "POS + KDS",
"modules": {"ordering": {}, "kds": {"limits": {"devices": 1}}}})
assert r.status_code == 201, r.text
preset = r.json()
names = [p["name"] for p in client.get("/api/presets/", headers=admin_h).json()]
assert "Cafe basic" in names and "Everything (v1 sites)" in names
site = _new_site(client, admin_h, preset="Cafe basic")
assert set(site["modules"]) == {"ordering", "kds"}
site2 = _new_site(client, admin_h)
applied = client.post(f"/api/sites/{site2['site_id']}/apply-preset/{preset['id']}", headers=admin_h).json()
assert applied["modules"] == {"ordering": {}, "kds": {"limits": {"devices": 1}}}
assert client.post("/api/presets/", headers=admin_h, json={"name": "Cafe basic", "modules": {}}).status_code == 409
assert client.delete(f"/api/presets/{preset['id']}", headers=admin_h).status_code == 204
def test_unknown_preset_on_create(client, admin_h):
r = client.post("/api/sites/", headers=admin_h, json={
"name": "T", "owner_name": "O", "contact_email": "o@x", "license_expires_at": "2027-06-01T00:00:00+00:00",
"preset": "Nope"})
assert r.status_code == 400
+95
View File
@@ -0,0 +1,95 @@
"""When online orders are taken: services, hours, time slots, rate limits (plan phase 3S, S.4)."""
import json
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
from services import ordering
from test_checkout import COLA, _code, _h, _menu, _order, _venue
ATH = ZoneInfo("Europe/Athens")
def snap(**cfg):
return {"timezone": "Europe/Athens", "ordering": {"services": ["takeaway", "delivery"], "hours": {}, "prep_minutes": 20,
"slot_minutes": 15, "days_ahead": 0, "asap": True, **cfg}}
def at(y, mo, d, h, mi):
return datetime(y, mo, d, h, mi, tzinfo=ATH).astimezone(timezone.utc)
# Sunday 15 Nov 2026 is weekday 6; Monday 16 Nov is 0
EVENINGS = {"6": [["18:00", "23:00"]], "5": [["20:00", "02:00"]]}
def test_open_hours_including_past_midnight():
cfg = ordering.config(snap(hours=EVENINGS))
local = lambda *a: datetime(*a, tzinfo=ATH) # noqa: E731
assert ordering.is_open(cfg, local(2026, 11, 15, 18, 0))
assert not ordering.is_open(cfg, local(2026, 11, 15, 23, 0))
assert not ordering.is_open(cfg, local(2026, 11, 15, 12, 0))
assert ordering.is_open(cfg, local(2026, 11, 15, 1, 30)) # Saturday's 20:00–02:00, after midnight
assert not ordering.is_open(cfg, local(2026, 11, 16, 19, 0)) # Monday has no hours: closed
assert ordering.is_open(ordering.config(snap()), local(2026, 11, 16, 4, 0)) # no hours = any time
def test_slots_start_after_preparation_on_the_grid_and_stay_in_hours():
s = snap(hours=EVENINGS)
got = [t.strftime("%H:%M") for t in ordering.slots(s, at(2026, 11, 15, 21, 7))]
assert got == ["21:30", "21:45", "22:00", "22:15", "22:30", "22:45"] # 21:07 + 20 → 21:27 → 21:30
assert ordering.slots(s, at(2026, 11, 15, 22, 50)) == [] # nothing left today
ahead = ordering.slots(snap(hours=EVENINGS, days_ahead=1, slot_minutes=30), at(2026, 11, 15, 22, 50))
assert ahead == [] # Monday closed
morning = [t.strftime("%H:%M") for t in ordering.slots(s, at(2026, 11, 15, 10, 0))]
assert morning[0] == "18:00" and morning[-1] == "22:45"
def test_check_asap_and_requested_times():
s = snap(hours=EVENINGS)
evening, noon = at(2026, 11, 15, 21, 7), at(2026, 11, 15, 12, 0)
assert ordering.check(s, "delivery", None, evening) is None
assert ordering.check(s, "delivery", None, noon) == ("order.closed", {}) # closed now: no ASAP
assert ordering.check(s, "takeaway", at(2026, 11, 15, 18, 30), noon) is None # but a later slot is fine
assert ordering.check(s, "takeaway", at(2026, 11, 15, 18, 31), noon)[0] == "order.time_invalid" # off the grid
assert ordering.check(s, "takeaway", at(2026, 11, 15, 21, 15), evening)[0] == "order.time_invalid" # too soon
assert ordering.check(snap(asap=False), "delivery", None, evening) == ("order.closed", {})
assert ordering.check(snap(services=["takeaway"]), "delivery", None, evening) == ("order.service_unavailable", {"service": "delivery"})
assert ordering.check(s, "takeaway", datetime(2026, 11, 15, 18, 30), noon)[0] == "order.time_invalid" # no zone
def test_the_endpoints_enforce_it(client, admin_h):
site, numeric = _venue(client, admin_h)
# the venue turns delivery off and opens only on Mondays 12:00–13:00
menu = client.get(f"/api/menu/{site['site_id']}").json()
snapshot = {"categories": menu["categories"], "timezone": "Europe/Athens",
"ordering": {"services": ["takeaway"], "hours": {"0": [["12:00", "13:00"]]}, "prep_minutes": 0,
"slot_minutes": 15, "days_ahead": 7, "asap": True}}
client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snapshot)})
s = client.get(f"/api/orders/{site['site_id']}/slots").json()
assert s["services"] == ["takeaway"] and len(s["slots"]) >= 4
first = datetime.fromisoformat(s["slots"][0])
assert first.astimezone(ATH).weekday() == 0 and first.astimezone(ATH).strftime("%H:%M") >= "12:00"
assert client.get(f"/api/menu/{site['site_id']}").json()["ordering"]["services"] == ["takeaway"]
assert _code(_order(client, site, "delivery", customer_address="x")) == "order.service_unavailable"
r = _order(client, site, "takeaway", requested_for=s["slots"][0])
assert r.status_code == 201, r.text
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == r.json()["public_ref"])
assert datetime.fromisoformat(stored["requested_for"].replace("Z", "+00:00")) == first
track = client.get(f"/api/orders/track/{r.json()['tracking_token']}").json()
assert track["requested_for"] and track["order_type"] == "takeaway"
# a takeaway or delivery order needs a phone number
assert _code(_order(client, site, "takeaway", customer_phone="", requested_for=s["slots"][0])) == "order.details_missing"
def test_rate_limits(client, admin_h):
from services import ratelimit
site, _ = _venue(client, admin_h)
statuses = [_order(client, site).status_code for _ in range(11)]
assert statuses[:10] == [201] * 10 and statuses[10] == 429
assert _code(_order(client, site)) == "rate.limited"
# another address is counted apart (behind the proxy)
ok = client.post(f"/api/orders/{site['site_id']}", headers={"X-Forwarded-For": "203.0.113.9"},
json={"order_type": "takeaway", "customer_name": "A", "customer_phone": "1", "items": [{"product_id": COLA, "quantity": 1}]})
assert ok.status_code == 201
assert ratelimit.hit("t", "k", 2, 60, now=0) and ratelimit.hit("t", "k", 2, 60, now=1) and not ratelimit.hit("t", "k", 2, 60, now=2)
assert ratelimit.hit("t", "k", 2, 60, now=61) # the window moves on
+70
View File
@@ -0,0 +1,70 @@
"""The QR menu at the table (plan phase 3S, step S.7): ordering only with a table's QR token
(checked by its hash from the snapshot), only when the venue allows it; the public menu says
which table the token is and never shows the hashes; a forged token is refused."""
import json
from services import qr
from test_checkout import ORDERING, PIE, _code, _h, _order, _venue
def _push_qr(client, site, numeric, ordering=True, tables=None):
menu = client.get(f"/api/menu/{site['site_id']}").json()
tables = tables if tables is not None else [{"id": 5, "label": "T5", "token_hash": qr.token_hash("tok-five")},
{"id": 6, "label": "Garden 6", "token_hash": qr.token_hash("tok-six")}]
snap = {"categories": menu["categories"], "ordering": ORDERING, "timezone": "Europe/Athens",
"qr": {"ordering": ordering, "tables": tables}}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
assert r.status_code == 200, r.text
def test_a_table_token_finds_its_table():
snap = {"qr": {"tables": [{"id": 5, "label": "T5", "token_hash": qr.token_hash("abc")}]}}
assert qr.table_for(snap, "abc") == {"id": 5, "label": "T5"}
assert qr.table_for(snap, "abd") is None
assert qr.table_for(snap, "") is None and qr.table_for(snap, None) is None
assert qr.table_for({}, "abc") is None
def test_ordering_at_the_table_needs_a_real_table_token(client, admin_h):
site, numeric = _venue(client, admin_h)
_push_qr(client, site, numeric)
menu = client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-five"}).json()
assert menu["table_ordering"] is True and menu["table"] == {"id": 5, "label": "T5"} and menu["table_invalid"] is False
assert "qr" not in menu # the hashes stay on the cloud
forged = client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-seven"}).json()
assert forged["table"] is None and forged["table_invalid"] is True
assert "table" not in client.get(f"/api/menu/{site['site_id']}").json()
r = _order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 2}])
assert r.status_code == 201, r.text
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == r.json()["public_ref"])
assert (stored["table_id"], stored["table_label"], stored["sales_point"], stored["total"]) == (5, "T5", "qr_table", 10.0)
# a forged token, none, or a table name typed in by hand: refused
assert _code(_order(client, site, "dine_in", table_token="tok-seven", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
assert _code(_order(client, site, "dine_in", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
r = _order(client, site, "dine_in", customer_table="5", items=[{"product_id": PIE, "quantity": 1}])
assert r.status_code == 403 and _code(r) == "order.table_invalid"
# a new QR code for table 5: the old one stops working at the next push
_push_qr(client, site, numeric, tables=[{"id": 5, "label": "T5", "token_hash": qr.token_hash("tok-five-new")}])
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
assert _order(client, site, "dine_in", table_token="tok-five-new", items=[{"product_id": PIE, "quantity": 1}]).status_code == 201
def test_read_only_menus_take_no_table_orders(client, admin_h):
site, numeric = _venue(client, admin_h)
_push_qr(client, site, numeric, ordering=False)
assert client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-five"}).json()["table_ordering"] is False
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.service_unavailable"
# the venue allows it, but the sysadmin set the site's menu to view only
_push_qr(client, site, numeric, ordering=True)
r = client.put(f"/api/sites/{site['site_id']}", headers=admin_h, json={"menu_mode": "view_only"})
assert r.status_code == 200, r.text
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.service_unavailable"
def test_the_sysadmin_gets_the_apps_address(client, admin_h, monkeypatch):
from config import settings
site, _ = _venue(client, admin_h)
monkeypatch.setattr(settings, "PUBLIC_APPS_URL", "https://menu.example.com/")
got = client.get(f"/api/sites/{site['site_id']}", headers=admin_h).json()
assert got["apps_url"] == "https://menu.example.com"
+114
View File
@@ -0,0 +1,114 @@
"""Reservations online (plan phase 3S, step S.6): a table only, or a table with food ready on
arrival; times on the venue's grid, inside its hours, with notice, up to N days ahead; party
size; the venue confirms or declines, then the guests arrive or the venue cancels."""
import json
from datetime import date, datetime, timezone
from zoneinfo import ZoneInfo
from services import ordering
from test_checkout import COLA, ORDERING, _code, _h, _venue
ATH = ZoneInfo("Europe/Athens")
DINNER = {"0": [["19:00", "23:00"]], "6": [["13:00", "16:00"], ["19:00", "23:00"]]} # Mon, Sun
def snap(**res):
return {"timezone": "Europe/Athens", "ordering": {**ORDERING, "reservations": {
"enabled": True, "with_food": True, "hours": DINNER, "slot_minutes": 30, "days_ahead": 14,
"notice_minutes": 120, "party_max": 8, **res}}}
def at(y, mo, d, h, mi):
return datetime(y, mo, d, h, mi, tzinfo=ATH).astimezone(timezone.utc)
def test_times_days_and_checks():
s, now = snap(), at(2026, 11, 15, 18, 10) # Sunday 18:10
sunday = [t.strftime("%H:%M") for t in ordering.res_slots(s, date(2026, 11, 15), now)]
assert sunday == ["20:30", "21:00", "21:30", "22:00", "22:30"] # 2 h notice; lunch is over
monday = [t.strftime("%H:%M") for t in ordering.res_slots(s, date(2026, 11, 16), now)]
assert monday[0] == "19:00" and monday[-1] == "22:30"
assert ordering.res_slots(s, date(2026, 11, 17), now) == [] # Tuesday: no hours = closed
assert ordering.res_slots(s, date(2026, 11, 30), now) == [] # beyond 14 days
days = ordering.res_days(s, now)
assert days[:3] == ["2026-11-15", "2026-11-16", "2026-11-22"] and "2026-11-17" not in days
ok = at(2026, 11, 16, 20, 0)
assert ordering.res_check(s, "reservation", ok, 4, now) is None
assert ordering.res_check(s, "preorder", ok, 4, now) is None
assert ordering.res_check(s, "reservation", ok, 9, now) == ("order.party_invalid", {"max": 8})
assert ordering.res_check(s, "reservation", ok, 0, now)[0] == "order.party_invalid"
assert ordering.res_check(s, "reservation", ok, None, now)[0] == "order.party_invalid"
assert ordering.res_check(s, "reservation", at(2026, 11, 16, 20, 10), 2, now)[0] == "order.time_invalid" # off grid
assert ordering.res_check(s, "reservation", at(2026, 11, 15, 19, 0), 2, now)[0] == "order.time_invalid" # too soon
assert ordering.res_check(s, "reservation", None, 2, now)[0] == "order.time_invalid"
assert ordering.res_check(snap(with_food=False), "preorder", ok, 2, now) == ("order.service_unavailable", {"service": "preorder"})
assert ordering.res_check(snap(enabled=False), "reservation", ok, 2, now)[0] == "order.service_unavailable"
assert ordering.res_summary(snap(enabled=False), now) == {"enabled": False, "with_food": False, "party_max": 8, "days": []}
def _push(client, site, numeric, **res):
menu = client.get(f"/api/menu/{site['site_id']}").json()
hours = {str(d): [["00:00", "23:59"]] for d in range(7)}
snapshot = {"categories": menu["categories"], "timezone": "Europe/Athens",
"ordering": {**ORDERING, "reservations": {"enabled": True, "with_food": True, "hours": hours, "slot_minutes": 30,
"days_ahead": 3, "notice_minutes": 0, "party_max": 6, **res}}}
for cat in snapshot["categories"]:
for p in cat["products"]:
if p["id"] == COLA:
p["sold_at"] = [*p["sold_at"], "online_preorder"]
p["prices"] = {**p["prices"], "online_preorder": 2.6}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snapshot)})
assert r.status_code in (200, 204), r.text
def test_book_a_table_with_and_without_food(client, admin_h):
site, numeric = _venue(client, admin_h)
_push(client, site, numeric)
menu = client.get(f"/api/menu/{site['site_id']}").json()
res = menu["ordering"]["reservations"]
assert res["enabled"] and res["with_food"] and res["party_max"] == 6 and len(res["days"]) == 4
day = res["days"][1]
slots = client.get(f"/api/orders/{site['site_id']}/reservation-slots", params={"day": day}).json()["slots"]
assert len(slots) == 48
when = slots[40] # 20:00 tomorrow
book = lambda **x: client.post(f"/api/orders/{site['site_id']}", json={ # noqa: E731
"order_type": "reservation", "customer_name": "Eleni", "customer_phone": "6977777777", "party_size": 4,
"requested_for": when, "customer_notes": "By the window", **x})
plain = book()
assert plain.status_code == 201, plain.text
assert _code(book(party_size=7)) == "order.party_invalid"
assert _code(book(customer_phone="")) == "order.details_missing"
assert _code(book(items=[{"product_id": COLA, "quantity": 1}])) == "order.items_not_allowed"
assert _code(book(requested_for=None)) == "order.time_invalid"
food = book(order_type="preorder", items=[{"product_id": COLA, "quantity": 2}], total=5.2)
assert food.status_code == 201, food.text
assert food.json()["total"] == 5.2 # the preorder price
assert _code(book(order_type="preorder", items=[])) == "order.empty"
pending = {o["public_ref"]: o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()}
p = pending[plain.json()["public_ref"]]
assert (p["order_type"], p["party_size"], p["total"], json.loads(p["items_json"]), p["sales_point"]) == ("reservation", 4, 0.0, [], None)
assert datetime.fromisoformat(p["requested_for"].replace("Z", "+00:00")) == datetime.fromisoformat(when)
f = pending[food.json()["public_ref"]]
assert (f["order_type"], f["sales_point"], f["party_size"]) == ("preorder", "online_preorder", 4)
# the venue confirms, then the guests arrive (or it cancels); the customer's page follows
st = lambda oid, s: client.patch(f"/api/orders/{oid}/status", headers=_h(site), json={"status": s}) # noqa: E731
assert st(p["id"], "preparing").status_code == 422
assert st(p["id"], "accepted").status_code == 204
assert st(p["id"], "delivered").status_code == 204
assert st(f["id"], "accepted").status_code == 204 and st(f["id"], "cancelled").status_code == 204
track = client.get(f"/api/orders/track/{food.json()['tracking_token']}").json()
assert (track["status"], track["order_type"], track["party_size"], track["total"]) == ("cancelled", "preorder", 4, 5.2)
# an ordinary order can't be "cancelled" this way
order = client.post(f"/api/orders/{site['site_id']}", json={"order_type": "takeaway", "customer_name": "M",
"customer_phone": "6900000000", "items": [{"product_id": COLA, "quantity": 1}]})
oid = next(o["id"] for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == order.json()["public_ref"])
st(oid, "accepted")
assert st(oid, "cancelled").status_code == 422
def test_reservations_off_by_default(client, admin_h):
site, _ = _venue(client, admin_h)
assert client.get(f"/api/menu/{site['site_id']}").json()["ordering"]["reservations"]["enabled"] is False
r = client.post(f"/api/orders/{site['site_id']}", json={"order_type": "reservation", "customer_name": "E", "customer_phone": "690000000",
"party_size": 2, "requested_for": datetime.now(timezone.utc).isoformat()})
assert _code(r) == "order.service_unavailable"
+121
View File
@@ -0,0 +1,121 @@
"""Cloud schema guard (APPS_PLATFORM D-22): Alembic only, baseline = v1 production, no drift."""
import json
import re
import sqlite3
from pathlib import Path
import pytest
from alembic.autogenerate import compare_metadata
from alembic.migration import MigrationContext
from sqlalchemy import create_engine, text
from schema import BASELINE, UnstampedDatabaseError, stamp_baseline, upgrade_to_head
HERE = Path(__file__).resolve().parent
V1_SQL = (HERE / "fixtures" / "v1_cloud_schema.sql").read_text(encoding="utf-8")
def _v1_db(path: Path):
con = sqlite3.connect(path)
con.executescript(V1_SQL)
con.execute("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, "
"is_locked, license_expires_at, order_counter, menu_mode, menu_hours_en) values "
"(1, 'site-1', 'Kopse', 'O', 'o@x', 'h', 1, 0, '2027-05-01 00:00:00', 7, 'order', 'old')")
con.commit()
con.close()
return create_engine(f"sqlite:///{path.as_posix()}")
def _shape(path):
con = sqlite3.connect(path)
tables = {t: sorted((r[1], r[2].upper(), r[3]) for r in con.execute(f'pragma table_info("{t}")'))
for (t,) in con.execute("select name from sqlite_master where type='table' "
"and name not in ('alembic_version', 'sqlite_sequence')")}
idx = sorted(r[0] for r in con.execute("select name from sqlite_master where type='index' and name not like 'sqlite_%'"))
con.close()
return tables, idx
def test_baseline_equals_v1_production_schema(tmp_path):
from schema import alembic_config
from alembic import command
eng = create_engine(f"sqlite:///{(tmp_path / 'b.db').as_posix()}")
with eng.begin() as conn:
command.upgrade(alembic_config(conn), BASELINE)
eng.dispose()
con = sqlite3.connect(tmp_path / "v1.db")
con.executescript(V1_SQL)
con.close()
assert _shape(tmp_path / "b.db") == _shape(tmp_path / "v1.db")
def test_unstamped_v1_db_is_refused(tmp_path):
eng = _v1_db(tmp_path / "prod.db")
with pytest.raises(UnstampedDatabaseError):
upgrade_to_head(eng)
def test_stamp_then_upgrade_a_v1_db(tmp_path): # the cutover procedure
eng = _v1_db(tmp_path / "prod.db")
stamp_baseline(eng)
upgrade_to_head(eng)
with eng.connect() as conn:
site = conn.execute(text("select site_id, order_counter, modules from sites")).one()
presets = conn.execute(text("select name from plan_presets")).scalars().all()
cols = [r[1] for r in conn.execute(text("pragma table_info(sites)"))]
eng.dispose()
assert site[0] == "site-1" and site[1] == 7 # data kept
mods = json.loads(site[2])
assert {"ordering", "waiter_app", "kds", "connect_menu"} <= set(mods)
assert mods["kds"] == {"limits": {"devices": None}} # v1 had no KDS limit
assert presets == ["Everything (v1 sites)"]
assert "menu_hours_en" not in cols
def test_no_drift_between_models_and_migrations(tmp_path):
from database import Base
import models.all # noqa: F401
eng = create_engine(f"sqlite:///{(tmp_path / 'd.db').as_posix()}")
upgrade_to_head(eng)
with eng.connect() as conn:
diff = compare_metadata(MigrationContext.configure(conn, opts={"compare_type": True}), Base.metadata)
eng.dispose()
assert diff == [], "\n".join(map(str, diff))
def test_nothing_calls_create_all():
root = HERE.parent
bad = [p.relative_to(root).as_posix() for p in root.rglob("*.py")
if not p.relative_to(root).as_posix().startswith(("tests/", "migrations/"))
and re.search(r"\.create_all\(", p.read_text(encoding="utf-8", errors="ignore"))]
assert bad == []
def test_0003_keeps_orders_gives_tokens_and_refs_per_site(tmp_path):
"""Existing online orders survive the table rebuild, get a tracking token, and two sites
may now both have ORD-0001 (plan phase 3S, S.2)."""
from schema import alembic_config
from alembic import command
import sqlalchemy as sa
eng = create_engine(f"sqlite:///{(tmp_path / 'c.db').as_posix()}")
with eng.begin() as conn:
command.upgrade(alembic_config(conn), "0002_v2_licensing")
for sid in (1, 2):
conn.execute(text("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, "
"license_expires_at, created_at, order_counter, menu_mode) "
"values (:i, :s, 'S', 'O', 'o@x', 'x', 1, '2027-01-01', '2026-01-01', 1, 'order')"), {"i": sid, "s": f"site-{sid}"})
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (1, 'ORD-0001', 'dine_in', 'A', '[]', 1, 0, 1, 'delivered', 1)"))
upgrade_to_head(eng)
with eng.begin() as conn:
row = conn.execute(text("select public_ref, tracking_token from online_orders")).one()
assert row[0] == "ORD-0001" and row[1]
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'B', '[]', 1, 0, 1, 'delivered', 0)"))
with pytest.raises(sa.exc.IntegrityError):
with conn.begin_nested():
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
"delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'C', '[]', 1, 0, 1, 'delivered', 0)"))
idx = {i["name"] for i in sa.inspect(conn).get_indexes("online_orders")}
eng.dispose()
assert {"ix_online_orders_site_id", "ix_online_orders_status"} <= idx
+36
View File
@@ -0,0 +1,36 @@
# Build menu-app
FROM node:20-alpine AS menu-builder
WORKDIR /app/menu-app
COPY menu-app/package.json .
RUN npm install
COPY menu-app/ .
ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm run build
# Build order-app (online ordering: takeaway and delivery, plan phase 3S S.4)
FROM node:20-alpine AS order-builder
WORKDIR /app/order-app
COPY order-app/package.json order-app/package-lock.json ./
RUN npm ci
COPY order-app/ .
ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm test && npm run build
# Build manager-app
FROM node:20-alpine AS manager-builder
WORKDIR /app/manager-app
COPY manager-app/package.json .
RUN npm install
COPY manager-app/ .
ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm run build
# Serve them with nginx
FROM nginx:alpine
COPY --from=menu-builder /app/menu-app/dist /usr/share/nginx/html/menu
COPY --from=manager-builder /app/manager-app/dist /usr/share/nginx/html/manage
COPY --from=order-builder /app/order-app/dist /usr/share/nginx/html/order
COPY nginx-connect.conf /etc/nginx/conf.d/default.conf
+11
View File
@@ -0,0 +1,11 @@
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html/manage
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="el">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Xenia Connect — Manager</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+26
View File
@@ -0,0 +1,26 @@
{
"name": "manager-app",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.7.9",
"lucide-react": "^1.14.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hot-toast": "^2.4.1",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.16",
"vite": "^6.0.5"
}
}
@@ -0,0 +1 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
+24
View File
@@ -0,0 +1,24 @@
import { Routes, Route, Navigate } from 'react-router-dom'
import LoginPage from './pages/LoginPage'
import SiteSelectorPage from './pages/SiteSelectorPage'
import DashboardPage from './pages/DashboardPage'
import IncomingOrdersPage from './pages/IncomingOrdersPage'
import OrderDetailPage from './pages/OrderDetailPage'
import OrderHistoryPage from './pages/OrderHistoryPage'
import RequireAuth from './components/RequireAuth'
export default function App() {
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<RequireAuth />}>
<Route path="/" element={<SiteSelectorPage />} />
<Route path="/:siteId" element={<DashboardPage />} />
<Route path="/:siteId/orders" element={<IncomingOrdersPage />} />
<Route path="/:siteId/orders/history" element={<OrderHistoryPage />} />
<Route path="/:siteId/orders/:orderId" element={<OrderDetailPage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
)
}
+58
View File
@@ -0,0 +1,58 @@
import axios from 'axios'
const BASE = import.meta.env.VITE_CLOUD_URL || ''
const api = axios.create({ baseURL: BASE })
// Attach manager JWT from sessionStorage on every request
api.interceptors.request.use(config => {
const token = sessionStorage.getItem('manager_token')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
})
// Force logout on 401
api.interceptors.response.use(
res => res,
err => {
if (err.response?.status === 401) {
sessionStorage.removeItem('manager_token')
window.location.href = '/manage/login'
}
return Promise.reject(err)
}
)
export default api
export async function managerLogin(email, password) {
const { data } = await api.post('/api/manager/login', { email, password })
return data // { access_token, token_type }
}
export async function fetchSites() {
const { data } = await api.get('/api/remote/sites')
return data
}
export async function fetchSnapshot(siteId) {
const { data } = await api.get(`/api/remote/sites/${siteId}/snapshot`)
return data
}
export async function fetchPendingOrders(siteId) {
const { data } = await api.get(`/api/remote/sites/${siteId}/orders/pending`)
return data
}
export async function fetchOrders(siteId, params = {}) {
const { data } = await api.get(`/api/remote/sites/${siteId}/orders`, { params })
return data
}
export async function updateOrderStatus(siteId, orderId, status, rejectionReason = null) {
await api.patch(`/api/remote/sites/${siteId}/orders/${orderId}/status`, {
status,
rejection_reason: rejectionReason,
})
}
@@ -0,0 +1,41 @@
import { useNavigate, useParams } from 'react-router-dom'
import { Truck, UtensilsCrossed, Clock } from 'lucide-react'
import StatusBadge from './StatusBadge'
function timeAgo(iso) {
const diff = Math.floor((Date.now() - new Date(iso)) / 1000)
if (diff < 60) return `${diff}s ago`
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`
return `${Math.floor(diff / 3600)}h ago`
}
export default function OrderCard({ order }) {
const { siteId } = useParams()
const navigate = useNavigate()
return (
<button
onClick={() => navigate(`/${siteId}/orders/${order.id}`)}
className="w-full bg-white rounded-2xl shadow-sm p-4 text-left hover:shadow-md transition-shadow space-y-2"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{order.order_type === 'delivery'
? <Truck size={16} className="text-indigo-500" />
: <UtensilsCrossed size={16} className="text-emerald-500" />}
<span className="font-bold text-slate-800 font-mono">{order.public_ref}</span>
</div>
<StatusBadge status={order.status} />
</div>
<p className="text-sm text-slate-600">{order.customer_name}</p>
<div className="flex items-center justify-between">
<span className="text-sm font-bold text-slate-800">€{order.total?.toFixed(2)}</span>
<span className="text-xs text-slate-400 flex items-center gap-1">
<Clock size={12} /> {timeAgo(order.created_at)}
</span>
</div>
</button>
)
}
@@ -0,0 +1,6 @@
import { Navigate, Outlet } from 'react-router-dom'
export default function RequireAuth() {
const token = sessionStorage.getItem('manager_token')
return token ? <Outlet /> : <Navigate to="/login" replace />
}
@@ -0,0 +1,9 @@
export default function StatCard({ label, value, sub, color = 'text-slate-800' }) {
return (
<div className="bg-white rounded-2xl p-4 shadow-sm space-y-1">
<p className="text-xs text-slate-400 font-medium uppercase tracking-wide">{label}</p>
<p className={`text-2xl font-bold ${color}`}>{value ?? '—'}</p>
{sub && <p className="text-xs text-slate-400">{sub}</p>}
</div>
)
}
@@ -0,0 +1,27 @@
const STYLES = {
pending_acceptance: 'bg-amber-100 text-amber-700',
accepted: 'bg-emerald-100 text-emerald-700',
rejected: 'bg-red-100 text-red-600',
preparing: 'bg-blue-100 text-blue-700',
ready: 'bg-teal-100 text-teal-700',
out_for_delivery: 'bg-indigo-100 text-indigo-700',
delivered: 'bg-slate-100 text-slate-500',
}
const LABELS = {
pending_acceptance: 'Pending',
accepted: 'Accepted',
rejected: 'Rejected',
preparing: 'Preparing',
ready: 'Ready',
out_for_delivery: 'Out for delivery',
delivered: 'Delivered',
}
export default function StatusBadge({ status }) {
return (
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold ${STYLES[status] || 'bg-slate-100 text-slate-500'}`}>
{LABELS[status] || status}
</span>
)
}
@@ -0,0 +1,6 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
* { box-sizing: border-box; }
body { margin: 0; font-family: 'Geist', system-ui, sans-serif; background: #f8fafc; }
+15
View File
@@ -0,0 +1,15 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { Toaster } from 'react-hot-toast'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<BrowserRouter basename="/manage">
<App />
<Toaster position="top-center" />
</BrowserRouter>
</React.StrictMode>
)
@@ -0,0 +1,116 @@
import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ArrowLeft, RefreshCw, Bell } from 'lucide-react'
import { fetchSnapshot, fetchPendingOrders } from '../api'
import StatCard from '../components/StatCard'
import OrderCard from '../components/OrderCard'
const POLL_MS = 15_000
export default function DashboardPage() {
const { siteId } = useParams()
const navigate = useNavigate()
const [snapshot, setSnapshot] = useState(null)
const [pending, setPending] = useState([])
const [lastUpdated, setLastUpdated] = useState(null)
const [loading, setLoading] = useState(true)
async function load() {
try {
const [snap, orders] = await Promise.all([
fetchSnapshot(siteId).catch(() => null),
fetchPendingOrders(siteId).catch(() => []),
])
setSnapshot(snap ? JSON.parse(snap.snapshot_json) : null)
setPending(orders)
setLastUpdated(new Date())
} finally {
setLoading(false)
}
}
useEffect(() => {
load()
const timer = setInterval(load, POLL_MS)
return () => clearInterval(timer)
}, [siteId])
const stats = snapshot || {}
return (
<div className="min-h-screen bg-slate-50 pb-10">
{/* Header */}
<div className="bg-white border-b border-slate-100 shadow-sm sticky top-0 z-10">
<div className="max-w-2xl mx-auto px-4 py-3 flex items-center justify-between">
<button onClick={() => navigate('/')} className="text-slate-400 hover:text-slate-700">
<ArrowLeft size={20} />
</button>
<h1 className="font-bold text-slate-800">Dashboard</h1>
<button onClick={load} className="text-slate-400 hover:text-slate-700">
<RefreshCw size={18} />
</button>
</div>
</div>
<div className="max-w-2xl mx-auto px-4 py-5 space-y-5">
{/* Stats grid */}
<div className="grid grid-cols-2 gap-3">
<StatCard label="Open tables" value={stats.open_tables} />
<StatCard label="Revenue today" value={stats.today_revenue != null ? `€${stats.today_revenue.toFixed(2)}` : null} color="text-emerald-600" />
<StatCard label="Orders today" value={stats.today_orders} />
<StatCard label="Online pending" value={stats.online_orders_pending} color={stats.online_orders_pending > 0 ? 'text-amber-600' : 'text-slate-800'} />
</div>
{lastUpdated && (
<p className="text-xs text-slate-400 text-right">
Refreshed {lastUpdated.toLocaleTimeString()}
</p>
)}
{stats.snapshot_taken_at && (() => {
const diffMin = Math.round((Date.now() - new Date(stats.snapshot_taken_at).getTime()) / 60_000)
const label = diffMin < 1 ? 'just now' : `${diffMin} min ago`
return (
<p className="text-xs text-slate-400 text-right -mt-3">
Site data: {label}
</p>
)
})()}
{/* Pending orders */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="font-bold text-slate-700 flex items-center gap-2">
<Bell size={16} className={pending.length ? 'text-amber-500' : 'text-slate-300'} />
Pending orders
{pending.length > 0 && (
<span className="bg-amber-100 text-amber-700 text-xs font-bold px-2 py-0.5 rounded-full">
{pending.length}
</span>
)}
</h2>
<button
onClick={() => navigate(`/${siteId}/orders`)}
className="text-sky-500 text-sm font-medium hover:underline"
>
View all
</button>
</div>
{loading ? (
<div className="flex justify-center py-8">
<div className="w-6 h-6 rounded-full border-2 border-sky-400 border-t-transparent animate-spin" />
</div>
) : pending.length === 0 ? (
<div className="bg-white rounded-2xl p-8 text-center text-slate-400 text-sm shadow-sm">
No pending orders
</div>
) : (
pending.map(o => <OrderCard key={o.id} order={o} />)
)}
</div>
</div>
</div>
)
}
@@ -0,0 +1,60 @@
import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ArrowLeft, RefreshCw } from 'lucide-react'
import { fetchPendingOrders } from '../api'
import OrderCard from '../components/OrderCard'
const POLL_MS = 15_000
export default function IncomingOrdersPage() {
const { siteId } = useParams()
const navigate = useNavigate()
const [orders, setOrders] = useState([])
const [loading, setLoading] = useState(true)
async function load() {
try {
const data = await fetchPendingOrders(siteId)
setOrders(data)
} finally {
setLoading(false)
}
}
useEffect(() => {
load()
const timer = setInterval(load, POLL_MS)
return () => clearInterval(timer)
}, [siteId])
return (
<div className="min-h-screen bg-slate-50 pb-10">
<div className="bg-white border-b border-slate-100 shadow-sm sticky top-0 z-10">
<div className="max-w-2xl mx-auto px-4 py-3 flex items-center justify-between">
<button onClick={() => navigate(-1)} className="text-slate-400 hover:text-slate-700">
<ArrowLeft size={20} />
</button>
<h1 className="font-bold text-slate-800">Incoming Orders</h1>
<button onClick={load} className="text-slate-400 hover:text-slate-700">
<RefreshCw size={18} />
</button>
</div>
</div>
<div className="max-w-2xl mx-auto px-4 py-5 space-y-3">
{loading ? (
<div className="flex justify-center py-16">
<div className="w-8 h-8 rounded-full border-2 border-sky-400 border-t-transparent animate-spin" />
</div>
) : orders.length === 0 ? (
<div className="bg-white rounded-2xl p-12 text-center text-slate-400 shadow-sm">
<p className="font-medium">No pending orders</p>
<p className="text-sm mt-1">New orders will appear here automatically.</p>
</div>
) : (
orders.map(o => <OrderCard key={o.id} order={o} />)
)}
</div>
</div>
)
}
@@ -0,0 +1,77 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { KeyRound } from 'lucide-react'
import { managerLogin } from '../api'
import toast from 'react-hot-toast'
export default function LoginPage() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
async function handleSubmit(e) {
e.preventDefault()
if (!email || !password) return
setLoading(true)
try {
const data = await managerLogin(email, password)
sessionStorage.setItem('manager_token', data.access_token)
navigate('/', { replace: true })
} catch (err) {
toast.error(err.response?.data?.detail || 'Invalid credentials')
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-sky-50 flex items-center justify-center p-4">
<div className="w-full max-w-sm">
<div className="bg-white rounded-2xl shadow-xl border border-slate-100 p-8">
<form onSubmit={handleSubmit} className="space-y-5">
<div className="text-center space-y-2">
<div className="flex justify-center mb-3">
<div className="w-12 h-12 bg-sky-500 rounded-xl flex items-center justify-center">
<KeyRound className="text-white" size={22} />
</div>
</div>
<h1 className="text-xl font-bold text-slate-800">Xenia Connect</h1>
<p className="text-sm text-slate-500">Manager Dashboard</p>
</div>
<div className="space-y-3">
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="Email"
autoComplete="email"
required
className="w-full border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-sky-400 focus:ring-1 focus:ring-sky-100"
/>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="Password"
autoComplete="current-password"
required
className="w-full border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-sky-400 focus:ring-1 focus:ring-sky-100"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-sky-500 hover:bg-sky-600 disabled:opacity-60 text-white py-3 rounded-xl font-semibold transition-colors"
>
{loading ? 'Signing in…' : 'Sign In'}
</button>
</form>
</div>
<p className="text-center text-xs text-slate-400 mt-4">Xenia POS · Remote Manager</p>
</div>
</div>
)
}
@@ -0,0 +1,175 @@
import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ArrowLeft, Truck, UtensilsCrossed } from 'lucide-react'
import { fetchOrders, updateOrderStatus } from '../api'
import StatusBadge from '../components/StatusBadge'
import toast from 'react-hot-toast'
const NEXT_STATUSES = {
accepted: [{ value: 'preparing', label: 'Mark Preparing' }],
preparing: [
{ value: 'ready', label: 'Mark Ready' },
{ value: 'out_for_delivery', label: 'Out for Delivery' },
],
ready: [{ value: 'delivered', label: 'Mark Delivered' }],
out_for_delivery: [{ value: 'delivered', label: 'Mark Delivered' }],
}
export default function OrderDetailPage() {
const { siteId, orderId } = useParams()
const navigate = useNavigate()
const [order, setOrder] = useState(null)
const [loading, setLoading] = useState(true)
const [acting, setActing] = useState(false)
const [rejectReason, setRejectReason] = useState('')
const [showReject, setShowReject] = useState(false)
useEffect(() => {
fetchOrders(siteId)
.then(list => setOrder(list.find(o => String(o.id) === orderId) || null))
.finally(() => setLoading(false))
}, [siteId, orderId])
async function act(status, reason = null) {
setActing(true)
try {
await updateOrderStatus(siteId, orderId, status, reason)
toast.success(`Order ${status.replace('_', ' ')}`)
navigate(-1)
} catch (err) {
toast.error(err.response?.data?.detail || 'Action failed')
} finally {
setActing(false)
}
}
if (loading) return (
<div className="min-h-screen flex items-center justify-center">
<div className="w-8 h-8 rounded-full border-2 border-sky-400 border-t-transparent animate-spin" />
</div>
)
if (!order) return (
<div className="min-h-screen flex items-center justify-center text-slate-400">
Order not found.
</div>
)
const items = (() => { try { return JSON.parse(order.items_json || '[]') } catch { return [] } })()
const nextActions = NEXT_STATUSES[order.status] || []
return (
<div className="min-h-screen bg-slate-50 pb-10">
<div className="bg-white border-b border-slate-100 shadow-sm sticky top-0 z-10">
<div className="max-w-lg mx-auto px-4 py-3 flex items-center gap-3">
<button onClick={() => navigate(-1)} className="text-slate-400 hover:text-slate-700">
<ArrowLeft size={20} />
</button>
<h1 className="font-bold text-slate-800 font-mono">{order.public_ref}</h1>
<div className="ml-auto"><StatusBadge status={order.status} /></div>
</div>
</div>
<div className="max-w-lg mx-auto px-4 py-5 space-y-4">
{/* Customer info */}
<div className="bg-white rounded-2xl p-4 shadow-sm space-y-2">
<div className="flex items-center gap-2 text-sm font-semibold text-slate-700">
{order.order_type === 'delivery'
? <Truck size={15} className="text-indigo-500" />
: <UtensilsCrossed size={15} className="text-emerald-500" />}
{order.order_type === 'delivery' ? 'Delivery' : 'Dine In'}
</div>
<p className="font-bold text-slate-800">{order.customer_name}</p>
{order.customer_phone && <p className="text-sm text-slate-500">{order.customer_phone}</p>}
{order.customer_address && (
<p className="text-sm text-slate-500">{order.customer_address}</p>
)}
{order.customer_notes && (
<p className="text-sm text-slate-500 italic">"{order.customer_notes}"</p>
)}
</div>
{/* Items */}
<div className="bg-white rounded-2xl p-4 shadow-sm space-y-2">
<p className="text-sm font-semibold text-slate-700 mb-3">Items</p>
{items.map((item, idx) => (
<div key={idx} className="flex justify-between text-sm">
<span className="text-slate-700">{item.quantity}× {item.name}</span>
<span className="text-slate-600 font-medium">€{(item.unit_price * item.quantity).toFixed(2)}</span>
</div>
))}
<div className="border-t border-slate-100 pt-2 mt-2 space-y-1">
<div className="flex justify-between text-sm text-slate-500">
<span>Subtotal</span><span>€{order.subtotal?.toFixed(2)}</span>
</div>
{order.delivery_fee > 0 && (
<div className="flex justify-between text-sm text-slate-500">
<span>Delivery fee</span><span>€{order.delivery_fee?.toFixed(2)}</span>
</div>
)}
<div className="flex justify-between font-bold text-slate-800">
<span>Total</span><span>€{order.total?.toFixed(2)}</span>
</div>
</div>
</div>
{/* Actions */}
{order.status === 'pending_acceptance' && !showReject && (
<div className="flex gap-3">
<button
onClick={() => act('accepted')}
disabled={acting}
className="flex-1 bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white py-3.5 rounded-xl font-semibold transition-colors"
>
Accept
</button>
<button
onClick={() => setShowReject(true)}
disabled={acting}
className="flex-1 bg-red-50 hover:bg-red-100 text-red-600 py-3.5 rounded-xl font-semibold transition-colors"
>
Reject
</button>
</div>
)}
{showReject && (
<div className="bg-white rounded-2xl p-4 shadow-sm space-y-3">
<p className="text-sm font-semibold text-slate-700">Rejection reason (optional)</p>
<input
type="text"
value={rejectReason}
onChange={e => setRejectReason(e.target.value)}
placeholder="e.g. Kitchen closed, item unavailable…"
className="w-full border border-slate-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-red-300"
/>
<div className="flex gap-3">
<button
onClick={() => act('rejected', rejectReason || null)}
disabled={acting}
className="flex-1 bg-red-500 hover:bg-red-600 disabled:opacity-60 text-white py-3 rounded-xl font-semibold"
>
Confirm Rejection
</button>
<button onClick={() => setShowReject(false)} className="px-4 py-3 rounded-xl text-slate-500 hover:bg-slate-100">
Cancel
</button>
</div>
</div>
)}
{nextActions.map(({ value, label }) => (
<button
key={value}
onClick={() => act(value)}
disabled={acting}
className="w-full bg-sky-500 hover:bg-sky-600 disabled:opacity-60 text-white py-3.5 rounded-xl font-semibold transition-colors"
>
{label}
</button>
))}
</div>
</div>
)
}
@@ -0,0 +1,74 @@
import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ArrowLeft } from 'lucide-react'
import { fetchOrders } from '../api'
import OrderCard from '../components/OrderCard'
const STATUSES = [
{ value: '', label: 'All' },
{ value: 'pending_acceptance', label: 'Pending' },
{ value: 'accepted', label: 'Accepted' },
{ value: 'preparing', label: 'Preparing' },
{ value: 'ready', label: 'Ready' },
{ value: 'out_for_delivery', label: 'Delivery' },
{ value: 'delivered', label: 'Delivered' },
{ value: 'rejected', label: 'Rejected' },
]
export default function OrderHistoryPage() {
const { siteId } = useParams()
const navigate = useNavigate()
const [orders, setOrders] = useState([])
const [filter, setFilter] = useState('')
const [loading, setLoading] = useState(true)
useEffect(() => {
setLoading(true)
fetchOrders(siteId, filter ? { order_status: filter } : {})
.then(setOrders)
.finally(() => setLoading(false))
}, [siteId, filter])
return (
<div className="min-h-screen bg-slate-50 pb-10">
<div className="bg-white border-b border-slate-100 shadow-sm sticky top-0 z-10">
<div className="max-w-2xl mx-auto px-4 py-3 flex items-center gap-3">
<button onClick={() => navigate(-1)} className="text-slate-400 hover:text-slate-700">
<ArrowLeft size={20} />
</button>
<h1 className="font-bold text-slate-800">Order History</h1>
</div>
{/* Status filter tabs */}
<div className="flex gap-1 overflow-x-auto px-4 pb-2 pt-1">
{STATUSES.map(s => (
<button
key={s.value}
onClick={() => setFilter(s.value)}
className={`flex-shrink-0 px-3 py-1 rounded-full text-xs font-medium transition-colors ${
filter === s.value
? 'bg-sky-500 text-white'
: 'bg-slate-100 text-slate-600 hover:bg-slate-200'
}`}
>
{s.label}
</button>
))}
</div>
</div>
<div className="max-w-2xl mx-auto px-4 py-5 space-y-3">
{loading ? (
<div className="flex justify-center py-16">
<div className="w-8 h-8 rounded-full border-2 border-sky-400 border-t-transparent animate-spin" />
</div>
) : orders.length === 0 ? (
<div className="bg-white rounded-2xl p-12 text-center text-slate-400 shadow-sm">
No orders found.
</div>
) : (
orders.map(o => <OrderCard key={o.id} order={o} />)
)}
</div>
</div>
)
}
@@ -0,0 +1,66 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Store, LogOut } from 'lucide-react'
import { fetchSites } from '../api'
export default function SiteSelectorPage() {
const [sites, setSites] = useState([])
const [loading, setLoading] = useState(true)
const navigate = useNavigate()
useEffect(() => {
fetchSites()
.then(data => {
setSites(data)
// Auto-navigate if only one site
if (data.length === 1) navigate(`/${data[0].id}`, { replace: true })
})
.finally(() => setLoading(false))
}, [])
function logout() {
sessionStorage.removeItem('manager_token')
navigate('/login', { replace: true })
}
if (loading) return (
<div className="min-h-screen flex items-center justify-center">
<div className="w-8 h-8 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
</div>
)
return (
<div className="min-h-screen bg-slate-50 p-6">
<div className="max-w-md mx-auto space-y-5">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-slate-800">Select Venue</h1>
<button onClick={logout} className="text-slate-400 hover:text-slate-600 flex items-center gap-1 text-sm">
<LogOut size={16} /> Log out
</button>
</div>
{sites.length === 0 ? (
<p className="text-slate-500 text-center py-12">No venues assigned to your account.</p>
) : (
<div className="space-y-3">
{sites.map(site => (
<button
key={site.id}
onClick={() => navigate(`/${site.id}`)}
className="w-full bg-white rounded-2xl p-5 shadow-sm hover:shadow-md transition-shadow text-left flex items-center gap-4"
>
<div className="w-12 h-12 bg-sky-100 rounded-xl flex items-center justify-center flex-shrink-0">
<Store className="text-sky-600" size={22} />
</div>
<div>
<p className="font-bold text-slate-800">{site.name}</p>
<p className="text-xs text-slate-400 font-mono">{site.site_id}</p>
</div>
</button>
))}
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,10 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ['./index.html', './src/**/*.{js,jsx}'],
theme: {
extend: {
fontFamily: { sans: ['Geist', 'system-ui', 'sans-serif'] },
},
},
plugins: [],
}
@@ -0,0 +1,9 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: '/manage/',
server: { host: '0.0.0.0', port: 5201 },
build: { outDir: 'dist' },
})
+11
View File
@@ -0,0 +1,11 @@
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
ARG VITE_CLOUD_URL=
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html/menu
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#1f3a34" />
<title>Menu</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,400;12..96,500;12..96,600;12..96,700&family=Hanken+Grotesk:wght@400;500;600;700&family=Noto+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "menu-app",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "node --test \"tests/*.test.mjs\""
},
"dependencies": {
"axios": "^1.7.9",
"lucide-react": "^1.14.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.16",
"vite": "^6.0.5"
}
}
@@ -0,0 +1 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
+21
View File
@@ -0,0 +1,21 @@
// The cloud's public endpoints for the QR menu (cloud_backend/routers/menu.py, orders.py).
import axios from 'axios'
export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || ''
const api = axios.create({ baseURL: CLOUD_URL, timeout: 15000 })
/** The menu; with a table's QR token (phase 3S, S.7) also which table it is (`table`, or
* `table_invalid`) and whether ordering at the table is on (`table_ordering`). */
export const fetchMenu = async (site, tableToken) =>
(await api.get(`/api/menu/${encodeURIComponent(site)}`, { params: tableToken ? { t: tableToken } : {} })).data
export const placeOrder = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}`, body)).data
/** The tracking link carries the order's random token (S.2); older links carry the public ref. */
export async function track(ref) {
try {
return (await api.get(`/api/orders/track/${encodeURIComponent(ref)}`)).data
} catch (err) {
if (err?.response?.status !== 404 || !/^ORD-\d+$/.test(ref)) throw err
return (await api.get(`/api/orders/status/${encodeURIComponent(ref)}`)).data
}
}
export const imageUrl = url => (!url ? null : /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}`)
+97
View File
@@ -0,0 +1,97 @@
// The QR menu's texts (en, el; plan step 6.5, same shape as the order app's). The guest's choice
// is remembered on this device; the first visit follows the browser's language.
import { createContext, useContext } from 'react'
const STORE = 'xenia-menu-lang'
const OLD_STORE = 'ot_lang' // the menu app before 6.5 kept 'en' / 'gr' here
export const TEXTS = {
en: {
menu: 'Menu', loading: 'Loading the menu…', notFound: 'This menu was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.',
retry: 'Try again', language: 'Language', categories: 'Categories', search: 'Search the menu…', searchOpen: 'Search', close: 'Close',
noResults: 'No dishes found', noResultsBody: 'Try a different word.',
add: 'Add', soldOut: 'Sold out', more: 'More', less: 'Less',
allergens: 'Allergens', contains: 'Contains', mayContain: 'May contain', noAllergens: 'No allergens declared. Ask the staff if you have an allergy.',
allergenNote: 'Ask the staff if you have an allergy.',
atTable: 'Table {{table}}: order from your phone', tableInvalid: 'This QR code is no longer valid. Please ask the staff.',
orderingOff: 'Ordering from the table is not available right now. Please ask the staff.',
viewOrder: 'Your order', items_one: '{{count}} item', items_other: '{{count}} items',
yourOrder: 'Your order', empty: 'Your order is empty.', emptyBody: 'Add a few dishes to get started.', total: 'Total', continue: 'Continue', back: 'Back',
table: 'Table', checkout: 'Send to the kitchen', name: 'Your name (optional)', namePlaceholder: 'e.g. Alex', summary: 'Your order',
placeOrder: 'Place order · {{total}}', sending: 'Sending…', payNote: 'You pay at the table.',
refused: {
changed: 'Something on the menu changed since you opened it. Please reload the page and check your order.',
rate: 'Too many attempts. Please wait a few minutes.', failed: 'The order could not be sent. Please try again.',
},
track: {
pending_acceptance: 'Sending your order to the kitchen…', accepted: 'Your order is in the kitchen', rejected: 'Order not taken',
acceptedBody: 'Thank you! Your waiter will bring it to your table. Enjoy your meal.',
rejectedBody: 'We\'re sorry we couldn\'t take your order this time. Please speak to the staff.',
waiting: 'This page updates by itself. Keep it open.', reason: 'Reason: {{reason}}', failed: 'Could not load the order\'s status.', back: 'Back to the menu',
},
allergen: {
gluten: 'Gluten', crustaceans: 'Crustaceans', eggs: 'Eggs', fish: 'Fish', peanuts: 'Peanuts', soybeans: 'Soya', milk: 'Milk',
nuts: 'Nuts', celery: 'Celery', mustard: 'Mustard', sesame: 'Sesame', sulphites: 'Sulphites', lupin: 'Lupin', molluscs: 'Molluscs',
},
},
el: {
menu: 'Μενού', loading: 'Φόρτωση μενού…', notFound: 'Το μενού δεν βρέθηκε.', loadFailed: 'Το μενού δεν φορτώθηκε. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά.',
retry: 'Δοκιμάστε ξανά', language: 'Γλώσσα', categories: 'Κατηγορίες', search: 'Αναζήτηση στο μενού…', searchOpen: 'Αναζήτηση', close: 'Κλείσιμο',
noResults: 'Δεν βρέθηκαν πιάτα', noResultsBody: 'Δοκιμάστε άλλη λέξη.',
add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', more: 'Περισσότερο', less: 'Λιγότερο',
allergens: 'Αλλεργιογόνα', contains: 'Περιέχει', mayContain: 'Μπορεί να περιέχει', noAllergens: 'Δεν έχουν δηλωθεί αλλεργιογόνα. Ρωτήστε το προσωπικό αν έχετε αλλεργία.',
allergenNote: 'Ρωτήστε το προσωπικό αν έχετε αλλεργία.',
atTable: 'Τραπέζι {{table}}: παραγγείλτε από το κινητό σας', tableInvalid: 'Αυτό το QR δεν ισχύει πλέον. Ρωτήστε το προσωπικό.',
orderingOff: 'Η παραγγελία από το τραπέζι δεν είναι διαθέσιμη τώρα. Ρωτήστε το προσωπικό.',
viewOrder: 'Η παραγγελία σας', items_one: '{{count}} πιάτο', items_other: '{{count}} πιάτα',
yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', emptyBody: 'Προσθέστε μερικά πιάτα για να ξεκινήσετε.', total: 'Σύνολο', continue: 'Συνέχεια', back: 'Πίσω',
table: 'Τραπέζι', checkout: 'Αποστολή στην κουζίνα', name: 'Το όνομά σας (προαιρετικά)', namePlaceholder: 'π.χ. Αλέξης', summary: 'Η παραγγελία σας',
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', payNote: 'Πληρώνετε στο τραπέζι.',
refused: {
changed: 'Κάτι άλλαξε στο μενού από τότε που το ανοίξατε. Ανανεώστε τη σελίδα και ελέγξτε την παραγγελία σας.',
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', failed: 'Η παραγγελία δεν στάλθηκε. Δοκιμάστε ξανά.',
},
track: {
pending_acceptance: 'Η παραγγελία σας στέλνεται στην κουζίνα…', accepted: 'Η παραγγελία σας είναι στην κουζίνα', rejected: 'Η παραγγελία δεν έγινε δεκτή',
acceptedBody: 'Ευχαριστούμε! Ο σερβιτόρος θα τη φέρει στο τραπέζι σας. Καλή όρεξη.',
rejectedBody: 'Λυπούμαστε, δεν μπορέσαμε να δεχτούμε την παραγγελία. Μιλήστε με το προσωπικό.',
waiting: 'Η σελίδα ενημερώνεται μόνη της. Κρατήστε την ανοιχτή.', reason: 'Λόγος: {{reason}}', failed: 'Δεν φορτώθηκε η κατάσταση της παραγγελίας.', back: 'Πίσω στο μενού',
},
allergen: {
gluten: 'Γλουτένη', crustaceans: 'Καρκινοειδή', eggs: 'Αυγά', fish: 'Ψάρια', peanuts: 'Αράπικα φιστίκια', soybeans: 'Σόγια', milk: 'Γάλα',
nuts: 'Ξηροί καρποί', celery: 'Σέλινο', mustard: 'Μουστάρδα', sesame: 'Σουσάμι', sulphites: 'Θειώδη', lupin: 'Λούπινο', molluscs: 'Μαλάκια',
},
},
}
export function initialLang() {
try {
const saved = localStorage.getItem(STORE)
if (saved && TEXTS[saved]) return saved
const old = localStorage.getItem(OLD_STORE)
if (old) return old === 'gr' ? 'el' : 'en'
} catch { /* private mode */ }
return (navigator.language || 'en').toLowerCase().startsWith('el') ? 'el' : 'en'
}
export function saveLang(lang) {
try { localStorage.setItem(STORE, lang) } catch { /* private mode */ }
}
/** t('a.b', {x}) with {{x}} and _one/_other plurals by `count`. */
export function translate(lang, key, params = {}) {
const dict = TEXTS[lang] ?? TEXTS.en
const find = k => k.split('.').reduce((o, p) => (o == null ? undefined : o[p]), dict)
let s = params.count != null ? find(`${key}_${params.count === 1 ? 'one' : 'other'}`) : undefined
if (s === undefined) s = find(key)
if (typeof s !== 'string') return key
return s.replace(/\{\{(\w+)\}\}/g, (_, k) => (params[k] ?? ''))
}
export const LangContext = createContext({ lang: 'en', setLang: () => {} })
export function useT() {
const { lang, setLang } = useContext(LangContext)
const money = n => new Intl.NumberFormat(lang === 'el' ? 'el-GR' : 'en-IE', { style: 'currency', currency: 'EUR' }).format(n ?? 0)
return { lang, setLang, t: (key, params) => translate(lang, key, params), money }
}
+35
View File
@@ -0,0 +1,35 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* The app's tokens (RGB triples, used through tailwind.config.js). Light only for now. */
:root {
--o-canvas: 246 244 239;
--o-surface: 255 255 255;
--o-surface-2: 239 236 228;
--o-line: 226 221 209;
--o-ink: 28 36 33;
--o-ink-2: 88 96 92;
--o-ink-3: 140 145 140;
--o-accent: 31 58 52;
--o-accent-fg: 247 244 236;
--o-accent-soft: 222 234 228;
--o-accent-ink: 24 66 56;
--o-success: 48 120 78;
--o-success-soft: 225 242 231;
--o-success-ink: 30 92 56;
--o-warning-soft: 252 240 214;
--o-warning-ink: 124 82 10;
--o-danger-soft: 251 228 222;
--o-danger-ink: 160 50 30;
--o-shadow: 28 36 33;
color-scheme: light;
}
html, body { background: rgb(var(--o-canvas)); color: rgb(var(--o-ink)); }
body { font-family: theme('fontFamily.sans'); -webkit-font-smoothing: antialiased; }
button { -webkit-tap-highlight-color: transparent; }
:focus-visible { outline: 3px solid rgb(var(--o-accent) / 0.45); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}
+107
View File
@@ -0,0 +1,107 @@
// The QR menu's logic (plan step 6.5). Pure: unit-tested in Node (tests/logic.test.mjs).
//
// The venue's menu comes from GET /api/menu/{site}: categories with products, each with the
// prices per sales point (this app sells at `qr_table`), its texts per language (`names`,
// `descriptions`, 6.4) and allergens (6.3). The cloud prices the order itself; the numbers here
// are what the guest sees before sending.
export const QR_POINT = 'qr_table'
export const LANGS = ['el', 'en']
/** The 14 EU allergens, in the order the venue's apps list them (the site's core/allergens.py). */
export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs']
const round2 = n => Math.round(n * 100) / 100
/** A product's allergens to show: what it contains, then what it may contain (traces). */
export function allergenList(map) {
const m = map && typeof map === 'object' && !Array.isArray(map) ? map : {}
const list = Array.isArray(map) ? map.filter(k => ALLERGENS.includes(k)).map(key => ({ key, level: 'contains' })) : []
for (const level of ['contains', 'may_contain']) for (const key of ALLERGENS) if (m[key] === level) list.push({ key, level })
return list
}
/** A text in the guest's language: `texts` {el, en} from the venue (already falling back), else the base. */
const pick = (texts, lang, base) => (texts && texts[lang]) || base || ''
/**
* The menu as this app shows it: the categories with the products sold on the QR menu, each
* product's text in `lang`, its price, availability and allergens. A product listed in several
* categories shows in each (`repeat` marks the later ones, so search shows it once).
*/
export function menuFor(data, lang) {
const seen = new Set()
return (data?.categories ?? []).map(c => ({
id: String(c.id),
name: pick(c.names, lang, c.name),
products: (c.products ?? [])
.filter(p => !p.sold_at || p.sold_at.includes(QR_POINT))
.map(p => ({
id: String(p.id),
name: pick(p.names, lang, p.digital_name || p.name),
names: p.names ?? null,
baseName: p.digital_name || p.name || '',
description: pick(p.descriptions, lang, p.digital_description || p.description || ''),
price: p.prices ? (p.prices[QR_POINT] ?? 0) : (p.digital_price ?? p.base_price ?? 0),
available: p.digital_available !== false,
image: p.digital_image_url || p.image_url || null,
tags: p.tags ?? [],
allergens: allergenList(p.allergens),
repeat: seen.has(String(p.id)) || !seen.add(String(p.id)),
})),
})).filter(c => c.products.length > 0)
}
/** Lowercase, no accents: "Σουβλάκι" and "σουβλακι" match. */
export function fold(text) {
return String(text ?? '').normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim()
}
/** What a search finds, once each: by its name in either language (or as typed) or description. */
export function search(categories, query) {
const q = fold(query)
if (!q) return []
return categories.flatMap(c => c.products.filter(p => !p.repeat))
.filter(p => [p.name, p.baseName, ...Object.values(p.names ?? {}), p.description].some(s => fold(s).includes(q)))
}
/** The cart is {productId: quantity}. */
export function setQty(cart, id, qty) {
const next = { ...cart }
if (qty <= 0) delete next[id]
else next[id] = Math.min(99, qty)
return next
}
/** The cart's lines priced from the menu; products no longer on it (or sold out) are left out. */
export function cartLines(cart, categories) {
const byId = new Map(categories.flatMap(c => c.products).map(p => [p.id, p]))
return Object.entries(cart ?? {}).flatMap(([id, qty]) => {
const p = byId.get(id)
if (!p || !p.available || qty <= 0) return []
return [{ product: p, qty, total: round2(p.price * qty) }]
})
}
export const cartTotal = lines => round2(lines.reduce((s, l) => s + l.total, 0))
export const cartCount = lines => lines.reduce((s, l) => s + l.qty, 0)
/** The order as the cloud takes it: at the table its QR code names (the cloud checks the token). */
export function orderBody(lines, { tableToken, name, tableLabel, tableWord }) {
return {
order_type: 'dine_in',
table_token: tableToken,
customer_name: (name ?? '').trim() || `${tableWord} ${tableLabel ?? ''}`.trim(),
items: lines.map(l => ({ product_id: Number(l.product.id), quantity: l.qty, unit_price: l.product.price })),
total: cartTotal(lines),
}
}
/** The text key for a refused order (the cloud's error code). */
export function refusalKey(code) {
if (['order.price_changed', 'order.item_unavailable', 'order.option_unavailable'].includes(code)) return 'refused.changed'
if (code === 'order.table_invalid') return 'tableInvalid'
if (code === 'order.service_unavailable') return 'orderingOff'
if (code === 'rate.limited') return 'refused.rate'
return 'refused.failed'
}
+27
View File
@@ -0,0 +1,27 @@
// The QR menu (plan step 6.5): read the venue's menu, or order at a table with its QR code.
import { StrictMode, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter, Route, Routes } from 'react-router-dom'
import './index.css'
import { initialLang, LangContext, saveLang } from './i18n'
import ConfirmPage from './pages/ConfirmPage'
import MenuPage from './pages/MenuPage'
function App() {
const [lang, setLangState] = useState(initialLang)
const setLang = l => { setLangState(l); saveLang(l); document.documentElement.lang = l }
document.documentElement.lang = lang
return (
<LangContext.Provider value={{ lang, setLang }}>
<BrowserRouter basename="/menu">
<Routes>
<Route path="/:site" element={<MenuPage />} />
<Route path="/:site/confirm/:ref" element={<ConfirmPage />} />
<Route path="*" element={<p className="p-6 text-ink-2">Xenia</p>} />
</Routes>
</BrowserRouter>
</LangContext.Provider>
)
}
createRoot(document.getElementById('root')).render(<StrictMode><App /></StrictMode>)
@@ -0,0 +1,55 @@
// After a table order (plan step 6.5): sending → in the kitchen, or not taken (with the
// venue's reason). Polls every 10 s until it's settled.
import { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { Check, Clock, X } from 'lucide-react'
import { track } from '../api'
import { useT } from '../i18n'
const SETTLED = new Set(['accepted', 'rejected', 'delivered', 'preparing', 'ready'])
const POLL_MS = 10_000
export default function ConfirmPage() {
const { site, ref } = useParams()
const { t } = useT()
const [order, setOrder] = useState(null)
const [failed, setFailed] = useState(false)
useEffect(() => {
let timer
let stop = false
const poll = async () => {
try {
const data = await track(ref)
if (stop) return
setOrder(data)
if (!SETTLED.has(data.status)) timer = setTimeout(poll, POLL_MS)
} catch { if (!stop) setFailed(true) }
}
poll()
return () => { stop = true; clearTimeout(timer) }
}, [ref])
const status = order?.status
const state = status === 'rejected' ? 'rejected' : SETTLED.has(status) ? 'accepted' : 'pending_acceptance'
const Icon = { pending_acceptance: Clock, accepted: Check, rejected: X }[state]
const tone = { pending_acceptance: 'bg-warning-soft text-warning-ink', accepted: 'bg-success-soft text-success-ink', rejected: 'bg-danger-soft text-danger-ink' }[state]
return (
<div className="mx-auto max-w-lg min-h-dvh bg-canvas flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
<div className={`w-20 h-20 rounded-full flex items-center justify-center ${tone}`}><Icon size={38} strokeWidth={2.2} aria-hidden="true" /></div>
{order?.public_ref && <p className="text-xs font-semibold uppercase tracking-[0.2em] text-ink-3">{order.public_ref}</p>}
<h1 data-testid="confirm-status" data-status={status ?? ''} className="font-display text-2xl font-semibold text-ink leading-tight">
{failed ? t('track.failed') : t(`track.${state}`)}
</h1>
{order?.rejection_reason && <p className="text-ink-2">{t('track.reason', { reason: order.rejection_reason })}</p>}
{state === 'accepted' && <p className="max-w-xs text-ink-2">{t('track.acceptedBody')}</p>}
{state === 'rejected' && <p className="max-w-xs text-ink-2">{t('track.rejectedBody')}</p>}
{state === 'pending_acceptance' && !failed && (<>
<p className="text-sm text-ink-3">{t('track.waiting')}</p>
<div className="w-5 h-5 rounded-full border-2 border-accent border-t-transparent animate-spin" role="status" aria-label={t('track.waiting')} />
</>)}
<Link to={`/${site}`} className="mt-4 px-5 h-11 rounded-full bg-surface border border-line text-ink font-semibold flex items-center">{t('track.back')}</Link>
</div>
)
}
@@ -0,0 +1,337 @@
// The QR menu (plan step 6.5, rebuilt on the customer apps' look). Without a table it's a menu to
// read; scanned at a table whose venue allows it (phase 3S, S.7) the guest orders from their
// phone: the order goes to the table's order and the kitchen, and the cloud prices it itself.
// Texts in the guest's language (the venue's translations, 6.4), each dish's allergens (6.3).
import { useEffect, useMemo, useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { Armchair, ChevronLeft, Minus, Plus, Search, Send, ShoppingBag, TriangleAlert, X } from 'lucide-react'
import { fetchMenu, imageUrl, placeOrder } from '../api'
import { useT } from '../i18n'
import { cartCount, cartLines, cartTotal, menuFor, orderBody, refusalKey, search, setQty } from '../logic'
const TABLE_KEY = site => `xenia-qr-table:${site}`
const CART_KEY = site => `xenia-qr-cart:${site}`
export default function MenuPage() {
const { site } = useParams()
const navigate = useNavigate()
const [params] = useSearchParams()
const { t, lang } = useT()
// the table's QR code carries its token (?t=…); kept for this visit so a reload keeps the table
const [tableToken] = useState(() => {
const fromUrl = params.get('t')
try {
if (fromUrl) sessionStorage.setItem(TABLE_KEY(site), fromUrl)
return fromUrl || sessionStorage.getItem(TABLE_KEY(site)) || null
} catch { return fromUrl }
})
const [data, setData] = useState(null)
const [error, setError] = useState(null)
const [cart, setCart] = useState(() => { try { return JSON.parse(sessionStorage.getItem(CART_KEY(site))) || {} } catch { return {} } })
const [open, setOpen] = useState(null) // a product shown big
const [searching, setSearching] = useState(false)
const [stage, setStage] = useState(null) // 'cart' | 'checkout'
const load = () => {
setError(null)
fetchMenu(site, tableToken).then(setData).catch(err => setError(err?.response?.status === 404 ? 'notFound' : 'loadFailed'))
}
useEffect(load, [site, tableToken]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { try { sessionStorage.setItem(CART_KEY(site), JSON.stringify(cart)) } catch { /* private mode */ } }, [cart, site])
const categories = useMemo(() => menuFor(data, lang), [data, lang])
const lines = useMemo(() => cartLines(cart, categories), [cart, categories])
const count = cartCount(lines)
const canOrder = !!(data?.table_ordering && data?.table)
const add = p => setCart(c => setQty(c, p.id, (c[p.id] || 0) + 1))
const remove = p => setCart(c => setQty(c, p.id, (c[p.id] || 0) - 1))
if (error) {
return (
<Shell>
<div className="p-6 grid gap-4 text-center">
<p className="text-ink-2">{t(error)}</p>
{error === 'loadFailed' && <button type="button" className="mx-auto px-5 h-11 rounded-full bg-accent text-accent-fg font-semibold" onClick={load}>{t('retry')}</button>}
</div>
</Shell>
)
}
if (!data) return <Shell><p className="p-6 text-center text-ink-2" role="status">{t('loading')}</p></Shell>
const r = data.restaurant ?? {}
const tagline = r.tagline?.[lang === 'el' ? 'gr' : 'en']
const visible = categories.filter(c => c.products.some(p => !p.repeat))
return (
<Shell>
<header className="px-4 pt-5 pb-3 grid gap-3 bg-surface border-b border-line">
<div className="flex items-start gap-3">
<div className="flex-1 min-w-0">
<h1 className="font-display text-2xl font-semibold text-ink leading-tight" data-testid="venue-name">{r.name || t('menu')}</h1>
{tagline && <p className="text-sm text-ink-2 mt-0.5">{tagline}</p>}
</div>
<LangSwitch />
</div>
{(data.table && canOrder) || data.table_invalid ? (
<p data-testid={data.table_invalid ? 'table-invalid' : 'table-banner'}
className={`p-3 rounded-control text-sm font-medium flex items-center gap-2 ${data.table_invalid ? 'bg-danger-soft text-danger-ink' : 'bg-accent-soft text-accent-ink'}`}>
{data.table_invalid ? <TriangleAlert size={16} aria-hidden="true" /> : <Armchair size={16} aria-hidden="true" />}
{data.table_invalid ? t('tableInvalid') : t('atTable', { table: data.table.label })}
</p>
) : null}
</header>
<nav className="sticky top-0 z-10 bg-canvas/95 backdrop-blur px-4 py-2 flex gap-2 overflow-x-auto border-b border-line" aria-label={t('categories')}>
<button type="button" onClick={() => setSearching(true)} aria-label={t('searchOpen')} data-testid="search-open"
className="shrink-0 w-9 h-9 rounded-full bg-surface border border-line flex items-center justify-center text-ink-2"><Search size={16} /></button>
{visible.map(c => (
<a key={c.id} href={`#cat-${c.id}`} className="shrink-0 px-3.5 h-9 rounded-full flex items-center text-sm font-medium bg-surface text-ink-2 border border-line">{c.name}</a>
))}
</nav>
<main className="px-4 pb-32 pt-3 grid gap-6">
{categories.map(c => (
<section key={c.id} id={`cat-${c.id}`} className="grid gap-2 scroll-mt-16" aria-labelledby={`h-${c.id}`} data-testid="menu-section">
<h2 id={`h-${c.id}`} className="font-display text-lg font-semibold text-ink">{c.name}</h2>
{c.products.map(p => (
<ProductCard key={`${c.id}-${p.id}`} product={p} qty={cart[p.id] || 0} canOrder={canOrder}
onOpen={() => setOpen(p)} onAdd={() => add(p)} onRemove={() => remove(p)} />
))}
</section>
))}
<p className="text-xs text-ink-3 text-center">{t('allergenNote')}</p>
</main>
{canOrder && count > 0 && (
<div className="fixed inset-x-0 bottom-0 p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<button type="button" onClick={() => setStage('cart')} data-testid="cart-button"
className="mx-auto max-w-lg w-full h-14 px-5 rounded-full bg-accent text-accent-fg shadow-bar flex items-center gap-3 font-semibold">
<ShoppingBag size={20} aria-hidden="true" />
<span className="flex-1 text-left">{t('viewOrder')} · {t('items', { count })}</span>
<Money value={cartTotal(lines)} />
</button>
</div>
)}
{open && <ProductSheet product={open} canOrder={canOrder} qty={cart[open.id] || 0} onClose={() => setOpen(null)} onAdd={() => add(open)} onRemove={() => remove(open)} />}
{searching && <SearchSheet categories={categories} cart={cart} canOrder={canOrder} onClose={() => setSearching(false)}
onOpen={p => { setSearching(false); setOpen(p) }} onAdd={add} onRemove={remove} />}
{stage && canOrder && (
<CartSheet stage={stage} setStage={setStage} lines={lines} table={data.table}
onAdd={add} onRemove={remove}
onSend={async name => {
const result = await placeOrder(site, orderBody(lines, { tableToken, name, tableLabel: data.table.label, tableWord: t('table') }))
setCart({})
try { sessionStorage.removeItem(CART_KEY(site)) } catch { /* private mode */ }
navigate(`/${site}/confirm/${result.tracking_token ?? result.public_ref}`)
}} />
)}
</Shell>
)
}
function Shell({ children }) {
return <div className="mx-auto max-w-lg min-h-dvh bg-canvas">{children}</div>
}
function LangSwitch() {
const { lang, setLang, t } = useT()
return (
<div className="flex rounded-full bg-surface-2 p-0.5 text-sm font-semibold shrink-0" role="group" aria-label={t('language')}>
{['el', 'en'].map(l => (
<button key={l} type="button" onClick={() => setLang(l)} aria-pressed={lang === l} data-testid={`lang-${l}`}
className={`px-2.5 h-8 rounded-full ${lang === l ? 'bg-surface text-ink shadow-card' : 'text-ink-2'}`}>{l.toUpperCase()}</button>
))}
</div>
)
}
function Money({ value }) {
const { money } = useT()
return <span className="tabular-nums">{money(value)}</span>
}
function Qty({ qty, onAdd, onRemove }) {
const { t } = useT()
return (
<div className="flex items-center gap-1">
<button type="button" onClick={onRemove} aria-label={t('less')} className="w-9 h-9 rounded-full bg-surface-2 text-ink flex items-center justify-center"><Minus size={16} /></button>
<span className="w-7 text-center font-semibold" data-testid="qty">{qty}</span>
<button type="button" onClick={onAdd} aria-label={t('more')} className="w-9 h-9 rounded-full bg-accent text-accent-fg flex items-center justify-center"><Plus size={16} /></button>
</div>
)
}
function AddButton({ product, qty, canOrder, onAdd, onRemove }) {
const { t } = useT()
if (!product.available) return <span className="text-sm font-medium text-ink-3">{t('soldOut')}</span>
if (!canOrder) return null
if (qty > 0) return <Qty qty={qty} onAdd={onAdd} onRemove={onRemove} />
return (
<button type="button" onClick={onAdd} data-testid="menu-add"
className="h-9 px-4 rounded-full bg-accent text-accent-fg text-sm font-semibold flex items-center gap-1"><Plus size={15} aria-hidden="true" />{t('add')}</button>
)
}
function ProductCard({ product, qty, canOrder, onOpen, onAdd, onRemove }) {
const { t } = useT()
const img = imageUrl(product.image)
const contains = product.allergens.filter(a => a.level === 'contains')
return (
<article className="p-3 rounded-card bg-surface border border-line shadow-card flex gap-3" data-testid="menu-product" data-product={product.id}>
{img && <button type="button" onClick={onOpen} className="shrink-0" aria-label={product.name}><img src={img} alt="" loading="lazy" className="w-20 h-20 rounded-control object-cover bg-surface-2" /></button>}
<div className="flex-1 min-w-0 grid gap-1 content-start">
<button type="button" onClick={onOpen} className="text-left font-semibold text-ink leading-snug" data-testid="menu-name">{product.name}</button>
{product.description && <p className="text-sm text-ink-2 line-clamp-2">{product.description}</p>}
{contains.length > 0 && (
<p className="text-xs text-warning-ink" data-testid="card-allergens">{t('contains')}: {contains.map(a => t(`allergen.${a.key}`)).join(', ')}</p>
)}
<div className="flex items-center justify-between gap-2 mt-1">
<span className="font-semibold text-ink" data-testid="price"><Money value={product.price} /></span>
<AddButton product={product} qty={qty} canOrder={canOrder} onAdd={onAdd} onRemove={onRemove} />
</div>
</div>
</article>
)
}
/** The dish's allergens: what it contains, then what it may contain. */
function AllergenBlock({ allergens }) {
const { t } = useT()
const contains = allergens.filter(a => a.level === 'contains')
const traces = allergens.filter(a => a.level === 'may_contain')
return (
<div className="grid gap-2 p-3 rounded-control bg-surface-2" data-testid="allergens" data-count={allergens.length}>
<p className="text-xs font-semibold uppercase tracking-wide text-ink-3">{t('allergens')}</p>
{allergens.length === 0 && <p className="text-sm text-ink-2">{t('noAllergens')}</p>}
{[['contains', contains], ['mayContain', traces]].filter(([, list]) => list.length).map(([label, list]) => (
<div key={label} className="flex flex-wrap items-center gap-1.5">
<span className="text-sm text-ink-2">{t(label)}:</span>
{list.map(a => (
<span key={a.key} data-allergen={a.key} data-level={a.level}
className={`px-2 py-0.5 rounded-full text-xs font-semibold ${a.level === 'contains' ? 'bg-warning-soft text-warning-ink' : 'border border-dashed border-line text-ink-2'}`}>
{t(`allergen.${a.key}`)}
</span>
))}
</div>
))}
</div>
)
}
function Sheet({ onClose, labelledBy, children }) {
useEffect(() => {
const esc = e => { if (e.key === 'Escape') onClose() }
document.addEventListener('keydown', esc)
return () => document.removeEventListener('keydown', esc)
}, [onClose])
return (
<div className="fixed inset-0 z-20 flex items-end justify-center bg-ink/40" role="dialog" aria-modal="true" aria-labelledby={labelledBy} onClick={onClose}>
<div className="w-full max-w-lg max-h-[90dvh] overflow-y-auto bg-surface rounded-t-[22px] p-4 pb-[max(1rem,env(safe-area-inset-bottom))] grid gap-3" onClick={e => e.stopPropagation()}>
{children}
</div>
</div>
)
}
function ProductSheet({ product, canOrder, qty, onClose, onAdd, onRemove }) {
const { t } = useT()
const img = imageUrl(product.image)
return (
<Sheet onClose={onClose} labelledBy="product-title">
<div data-testid="product-sheet" className="grid gap-3">
{img && <img src={img} alt="" className="w-full max-h-64 rounded-card object-cover bg-surface-2" />}
<div className="flex items-start gap-2">
<h2 id="product-title" className="flex-1 font-display text-xl font-semibold text-ink">{product.name}</h2>
<button type="button" onClick={onClose} aria-label={t('close')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center shrink-0"><X size={18} /></button>
</div>
{product.description && <p className="text-ink-2 whitespace-pre-line">{product.description}</p>}
<AllergenBlock allergens={product.allergens} />
<div className="flex items-center justify-between gap-2">
<span className="text-lg font-semibold text-ink"><Money value={product.price} /></span>
<AddButton product={product} qty={qty} canOrder={canOrder} onAdd={onAdd} onRemove={onRemove} />
</div>
</div>
</Sheet>
)
}
function SearchSheet({ categories, cart, canOrder, onClose, onOpen, onAdd, onRemove }) {
const { t } = useT()
const [q, setQ] = useState('')
const found = useMemo(() => search(categories, q), [categories, q])
return (
<div className="fixed inset-0 z-20 bg-canvas flex flex-col" role="dialog" aria-modal="true" aria-label={t('searchOpen')}>
<div className="mx-auto w-full max-w-lg flex items-center gap-2 p-3">
<div className="flex-1 flex items-center gap-2 h-11 px-3.5 rounded-full bg-surface border border-line">
<Search size={18} className="text-ink-3" aria-hidden="true" />
<input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder={t('search')} aria-label={t('search')} data-testid="search-input"
className="flex-1 bg-transparent outline-none text-ink placeholder:text-ink-3" />
</div>
<button type="button" onClick={onClose} className="px-2 h-11 text-sm font-medium text-ink-2">{t('back')}</button>
</div>
<div className="mx-auto w-full max-w-lg flex-1 overflow-y-auto px-4 pb-6 grid gap-2 content-start">
{q.trim() && found.length === 0 && (
<div className="mt-16 text-center grid gap-1"><p className="font-display text-lg text-ink">{t('noResults')}</p><p className="text-sm text-ink-3">{t('noResultsBody')}</p></div>
)}
{found.map(p => <ProductCard key={p.id} product={p} qty={cart[p.id] || 0} canOrder={canOrder} onOpen={() => onOpen(p)} onAdd={() => onAdd(p)} onRemove={() => onRemove(p)} />)}
</div>
</div>
)
}
function CartSheet({ stage, setStage, lines, table, onAdd, onRemove, onSend }) {
const { t, money } = useT()
const [name, setName] = useState('')
const [sending, setSending] = useState(false)
const [problem, setProblem] = useState(null)
const total = cartTotal(lines)
const close = () => setStage(null)
const send = async () => {
setSending(true)
setProblem(null)
try { await onSend(name) } catch (err) { setProblem(refusalKey(err?.response?.data?.detail?.code ?? err?.response?.data?.error?.code)); setSending(false) }
}
return (
<Sheet onClose={close} labelledBy="cart-title">
<div className="flex items-center gap-2">
{stage === 'checkout' && <button type="button" onClick={() => setStage('cart')} aria-label={t('back')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><ChevronLeft size={18} /></button>}
<h2 id="cart-title" className="flex-1 font-display text-xl font-semibold text-ink">{stage === 'cart' ? t('yourOrder') : t('checkout')}</h2>
<button type="button" onClick={close} aria-label={t('close')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><X size={18} /></button>
</div>
{lines.length === 0 ? (
<div className="py-10 text-center grid gap-1"><p className="font-display text-lg text-ink">{t('empty')}</p><p className="text-sm text-ink-3">{t('emptyBody')}</p></div>
) : stage === 'cart' ? (<>
<ul className="grid gap-2">
{lines.map(l => (
<li key={l.product.id} className="flex items-center gap-3 p-2.5 rounded-control bg-surface-2" data-testid="cart-line">
<span className="flex-1 min-w-0 grid"><span className="font-medium text-ink truncate">{l.product.name}</span><span className="text-sm text-ink-2"><Money value={l.product.price} /></span></span>
<Qty qty={l.qty} onAdd={() => onAdd(l.product)} onRemove={() => onRemove(l.product)} />
</li>
))}
</ul>
<div className="flex items-baseline justify-between"><span className="text-sm text-ink-2">{t('total')}</span><span className="text-xl font-semibold text-ink"><Money value={total} /></span></div>
<button type="button" onClick={() => setStage('checkout')} data-testid="cart-continue" className="h-12 rounded-full bg-accent text-accent-fg font-semibold">{t('continue')}</button>
</>) : (<>
<p className="font-semibold text-ink" data-testid="checkout-table">{t('table')} {table?.label}</p>
<label className="grid gap-1.5">
<span className="text-sm font-medium text-ink-2">{t('name')}</span>
<input value={name} onChange={e => setName(e.target.value)} placeholder={t('namePlaceholder')} maxLength={100} autoComplete="given-name"
className="h-12 px-3.5 rounded-control bg-surface border border-line text-ink outline-none focus:border-accent" />
</label>
<div className="grid gap-1 p-3 rounded-control bg-surface-2">
<p className="text-xs font-semibold uppercase tracking-wide text-ink-3">{t('summary')}</p>
{lines.map(l => (
<div key={l.product.id} className="flex justify-between gap-2 text-sm"><span className="text-ink-2"><b className="text-ink">{l.qty}×</b> {l.product.name}</span><Money value={l.total} /></div>
))}
</div>
<p className="text-xs text-ink-3">{t('payNote')}</p>
{problem && <p role="alert" className="p-3 rounded-control bg-danger-soft text-danger-ink text-sm">{t(problem)}</p>}
<button type="button" disabled={sending} onClick={send} data-testid="place-order"
className="h-12 rounded-full bg-accent text-accent-fg font-semibold flex items-center justify-center gap-2 disabled:opacity-60">
<Send size={16} aria-hidden="true" />{sending ? t('sending') : t('placeOrder', { total: money(total) })}
</button>
</>)}
</Sheet>
)
}
@@ -0,0 +1,30 @@
// The QR menu (plan step 6.5) on the customer apps' look: the same tokens as the order app.
/** @type {import('tailwindcss').Config} */
// Colours are tokens (CSS variables in src/index.css), never literals in components: one
// place to restyle the app, the same token names as the venue apps' @xenia/ui.
const c = name => `rgb(var(--o-${name}) / <alpha-value>)`
export default {
content: ['./index.html', './src/**/*.{js,jsx}'],
theme: {
extend: {
fontFamily: {
sans: ['Hanken Grotesk', 'Noto Sans', 'system-ui', 'sans-serif'],
display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'],
},
colors: {
canvas: c('canvas'),
surface: { DEFAULT: c('surface'), 2: c('surface-2') },
line: c('line'),
ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') },
accent: { DEFAULT: c('accent'), fg: c('accent-fg'), soft: c('accent-soft'), ink: c('accent-ink') },
success: { DEFAULT: c('success'), soft: c('success-soft'), ink: c('success-ink') },
warning: { soft: c('warning-soft'), ink: c('warning-ink') },
danger: { soft: c('danger-soft'), ink: c('danger-ink') },
},
borderRadius: { card: '18px', control: '12px' },
boxShadow: { card: '0 6px 18px -12px rgb(var(--o-shadow) / 0.45)', bar: '0 12px 28px -10px rgb(var(--o-shadow) / 0.6)' },
},
},
plugins: [],
}
@@ -0,0 +1,61 @@
// The QR menu's logic (plan step 6.5).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { allergenList, cartCount, cartLines, cartTotal, fold, menuFor, orderBody, refusalKey, search, setQty } from '../src/logic.js'
const data = { categories: [
{ id: 1, name: 'Ψητά', names: { el: 'Ψητά', en: 'Grill' }, products: [
{ id: 5, name: 'Σουβλάκι', names: { el: 'Σουβλάκι', en: 'Pork skewer' }, descriptions: { el: 'Με πίτα', en: 'With pitta' },
prices: { qr_table: 3.5, online_delivery: 4 }, sold_at: ['qr_table', 'online_delivery'], allergens: { gluten: 'contains', sesame: 'may_contain' } },
{ id: 6, name: 'Μπριζόλα', prices: { qr_table: 12 }, sold_at: ['qr_table'], digital_available: false },
{ id: 7, name: 'Delivery only', prices: { online_delivery: 9 }, sold_at: ['online_delivery'] },
] },
{ id: 2, name: 'Ορεκτικά', products: [{ id: 5, name: 'Σουβλάκι', names: { el: 'Σουβλάκι', en: 'Pork skewer' }, prices: { qr_table: 3.5 }, sold_at: ['qr_table'] }] },
{ id: 3, name: 'Empty', products: [{ id: 7, name: 'x', prices: {}, sold_at: ['online_takeaway'] }] },
] }
test('the menu in the guest\'s language, the QR menu\'s prices, only what it sells', () => {
const en = menuFor(data, 'en')
assert.deepEqual(en.map(c => c.name), ['Grill', 'Ορεκτικά']) // a category without a translation: as typed
const souv = en[0].products[0]
assert.equal(souv.name, 'Pork skewer')
assert.equal(souv.description, 'With pitta')
assert.equal(souv.price, 3.5)
assert.equal(en[0].products.length, 2) // the delivery-only dish isn't here
assert.equal(en[0].products[1].available, false)
assert.equal(en[1].products[0].repeat, true) // listed twice: search shows it once
assert.equal(menuFor(data, 'el')[0].products[0].name, 'Σουβλάκι')
})
test('allergens: contains first, then may contain; older array data still read', () => {
assert.deepEqual(allergenList({ sesame: 'may_contain', milk: 'contains', pollen: 'contains' }), [{ key: 'milk', level: 'contains' }, { key: 'sesame', level: 'may_contain' }])
assert.deepEqual(allergenList(['gluten', 'dairy']), [{ key: 'gluten', level: 'contains' }])
assert.deepEqual(allergenList(null), [])
})
test('search: either language, no accents, each dish once', () => {
const en = menuFor(data, 'en')
assert.deepEqual(search(en, 'σουβλακι').map(p => p.id), ['5'])
assert.deepEqual(search(en, 'pork').map(p => p.id), ['5'])
assert.deepEqual(search(en, 'pitta').map(p => p.id), ['5'])
assert.deepEqual(search(en, ''), [])
assert.equal(fold('Σουβλάκι'), 'σουβλακι')
})
test('the cart, its total and the order the cloud takes', () => {
const en = menuFor(data, 'en')
let cart = setQty({}, '5', 2)
cart = setQty(cart, '6', 1) // sold out: left out
cart = setQty(cart, '99', 1) // not on the menu any more
const lines = cartLines(cart, en)
assert.deepEqual(lines.map(l => [l.product.id, l.qty, l.total]), [['5', 2, 7]])
assert.equal(cartTotal(lines), 7)
assert.equal(cartCount(lines), 2)
assert.deepEqual(setQty({ 5: 1 }, '5', 0), {})
assert.deepEqual(orderBody(lines, { tableToken: 'tok', name: ' ', tableLabel: '5', tableWord: 'Table' }), {
order_type: 'dine_in', table_token: 'tok', customer_name: 'Table 5', items: [{ product_id: 5, quantity: 2, unit_price: 3.5 }], total: 7,
})
assert.equal(refusalKey('order.price_changed'), 'refused.changed')
assert.equal(refusalKey('order.table_invalid'), 'tableInvalid')
assert.equal(refusalKey('nope'), 'refused.failed')
})
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: '/menu/',
server: { host: '0.0.0.0', port: 5200 },
build: { outDir: 'dist' },
})
+27
View File
@@ -0,0 +1,27 @@
server {
listen 80;
# Public menu SPA
location /menu/ {
alias /usr/share/nginx/html/menu/;
try_files $uri $uri/ /menu/index.html;
}
# Online ordering SPA (takeaway, delivery)
location /order/ {
alias /usr/share/nginx/html/order/;
try_files $uri $uri/ /order/index.html;
}
# Remote manager SPA
location /manage/ {
alias /usr/share/nginx/html/manage/;
try_files $uri $uri/ /manage/index.html;
}
# Health check
location /health {
return 200 'ok';
add_header Content-Type text/plain;
}
}
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#1f3a34" />
<title>Order online</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Hanken+Grotesk:wght@400;500;600;700&family=Noto+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "order-app",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "node --test \"tests/*.test.mjs\""
},
"dependencies": {
"axios": "^1.7.9",
"lucide-react": "^1.14.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.16",
"vite": "^6.0.5"
}
}
@@ -0,0 +1 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
+15
View File
@@ -0,0 +1,15 @@
// The cloud's public endpoints for online ordering (cloud_backend/routers/orders.py, menu.py).
import axios from 'axios'
export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || ''
const api = axios.create({ baseURL: CLOUD_URL, timeout: 15000 })
/** The venue's menu, areas and ordering summary (services, open now, slots). */
export const fetchMenu = async site => (await api.get(`/api/menu/${encodeURIComponent(site)}`)).data
export const fetchSlots = async site => (await api.get(`/api/orders/${encodeURIComponent(site)}/slots`)).data
export const quote = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}/quote`, body)).data
export const placeOrder = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}`, body)).data
export const track = async token => (await api.get(`/api/orders/track/${encodeURIComponent(token)}`)).data
export const imageUrl = url => (!url ? null : /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}`)
/** One venue day's table booking times (S.6): {day, slots: [iso]}. */
export const fetchBookingSlots = async (site, day) => (await api.get(`/api/orders/${encodeURIComponent(site)}/reservation-slots`, { params: { day } })).data
+146
View File
@@ -0,0 +1,146 @@
// The ordering app's texts (en, el). The customer's choice is remembered on this device; the
// first visit follows the browser's language.
import { createContext, useContext } from 'react'
const STORE = 'xenia-order-lang'
export const TEXTS = {
en: {
service: 'How', bookTable: 'Book a table',
book: {
party: 'People', day: 'Day', time: 'Time', none: 'No tables can be booked online right now.', noTimes: 'No free times this day. Try another day.',
food: 'Order food for when you arrive', foodHint: 'Pick dishes now: the kitchen prepares them for your arrival. You pay at the venue.',
continue: 'Continue', title: 'Book a table', tableFor_one: 'Table for {{count}}', tableFor_other: 'Table for {{count}}',
send: 'Request booking', note: 'The venue confirms your booking. You pay at the venue.', foodReady: 'Ready for when you arrive.',
},
takeaway: 'Takeaway', delivery: 'Delivery', open: 'Open now', closed: 'Closed now',
closedBody: 'You can still order for a later time.', noOrdering: 'Online ordering is not available right now.',
loading: 'Loading the menu…', notFound: 'This venue was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.',
contains: 'Contains', mayContain: 'May contain',
allergen: {
gluten: 'Gluten', crustaceans: 'Crustaceans', eggs: 'Eggs', fish: 'Fish', peanuts: 'Peanuts', soybeans: 'Soya', milk: 'Milk',
nuts: 'Nuts', celery: 'Celery', mustard: 'Mustard', sesame: 'Sesame', sulphites: 'Sulphites', lupin: 'Lupin', molluscs: 'Molluscs',
},
retry: 'Try again', add: 'Add', soldOut: 'Sold out', options: 'Extras', addToOrder: 'Add to order', cancel: 'Cancel',
viewOrder: 'View order', items_one: '{{count}} item', items_other: '{{count}} items',
yourOrder: 'Your order', empty: 'Your order is empty.', products: 'Products', fee: 'Delivery fee', total: 'Total',
pricing: 'Working out the price…', details: 'Your details', name: 'Name', phone: 'Phone',
address: 'Street and number', area: 'Area', areaPick: 'Pick your area', byPostcode: 'Or enter your postcode',
byArea: 'Pick from the list', postcode: 'Postcode', notes: 'Notes for the venue (optional)',
when: 'When', asap: 'As soon as possible', pickTime: 'Pick a time', today: 'Today', tomorrow: 'Tomorrow',
placeOrder: 'Place order · {{total}}', sending: 'Sending…', back: 'Back',
payNote: 'You pay at the venue or on delivery.',
problem: {
party: 'Pick how many people.',
name: 'Enter your name.', phone: 'Enter a phone number we can call.', address: 'Enter the delivery address.',
area: 'Pick your area.', postcode: 'Enter your postcode.', when: 'Pick a time.',
},
refused: {
minimum_not_met: 'The minimum order for delivery is {{minimum}}.', area_not_served: 'Sorry, we don\'t deliver to this address.',
price_changed: 'Prices changed since you opened the menu. Check your order: it now shows the current prices.',
item_unavailable: 'Something in your order is no longer available. Please remove it.', option_unavailable: 'An extra you chose is no longer available.',
service_unavailable: 'This service is not available right now.', closed: 'We\'re closed right now. Pick a later time.',
time_invalid: 'That time is no longer available. Pick another.', details_missing: 'Please fill in your details.',
party_invalid: 'We take online bookings for up to {{max}} people. Call us for larger groups.',
rate: 'Too many attempts. Please wait a few minutes.', no_menu: 'The menu is not available right now.', failed: 'Something went wrong. Please try again.',
},
track: {
booking: {
title: 'Booking {{ref}}', placed: 'Thank you! We got your booking request.',
pending_acceptance: 'Waiting for the venue to confirm', accepted: 'Confirmed', delivered: 'Welcome, you\'re here',
rejected: 'The venue could not take this booking', cancelled: 'Cancelled by the venue',
},
title: 'Order {{ref}}', placed: 'Thank you! We got your order.', for: 'For {{when}}', asap: 'As soon as possible',
keep: 'Keep this page open, or save its address, to follow your order.',
status: {
pending_acceptance: 'Waiting for the venue to confirm', accepted: 'Confirmed', preparing: 'Being prepared',
ready: 'Ready to collect', out_for_delivery: 'On its way', delivered: 'Done', rejected: 'Not accepted',
},
rejected: 'The venue could not take this order.', reason: 'Reason: {{reason}}', newOrder: 'Order again', notFound: 'This order was not found.',
},
},
el: {
service: 'Τρόπος', bookTable: 'Κράτηση τραπεζιού',
book: {
party: 'Άτομα', day: 'Ημέρα', time: 'Ώρα', none: 'Δεν γίνονται online κρατήσεις αυτή τη στιγμή.', noTimes: 'Δεν υπάρχουν ελεύθερες ώρες αυτή τη μέρα. Δοκιμάστε άλλη.',
food: 'Παραγγείλετε φαγητό για την άφιξή σας', foodHint: 'Διαλέξτε πιάτα τώρα: η κουζίνα τα ετοιμάζει για την ώρα που έρχεστε. Πληρώνετε στο κατάστημα.',
continue: 'Συνέχεια', title: 'Κράτηση τραπεζιού', tableFor_one: 'Τραπέζι για {{count}}', tableFor_other: 'Τραπέζι για {{count}}',
send: 'Αίτημα κράτησης', note: 'Το κατάστημα επιβεβαιώνει την κράτηση. Πληρώνετε στο κατάστημα.', foodReady: 'Έτοιμα για την άφιξή σας.',
},
takeaway: 'Παραλαβή', delivery: 'Διανομή', open: 'Ανοιχτά τώρα', closed: 'Κλειστά τώρα',
closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.',
loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.',
contains: 'Περιέχει', mayContain: 'Μπορεί να περιέχει',
allergen: {
gluten: 'Γλουτένη', crustaceans: 'Καρκινοειδή', eggs: 'Αυγά', fish: 'Ψάρια', peanuts: 'Αράπικα φιστίκια', soybeans: 'Σόγια', milk: 'Γάλα',
nuts: 'Ξηροί καρποί', celery: 'Σέλινο', mustard: 'Μουστάρδα', sesame: 'Σουσάμι', sulphites: 'Θειώδη', lupin: 'Λούπινο', molluscs: 'Μαλάκια',
},
retry: 'Δοκιμάστε ξανά', add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', options: 'Έξτρα', addToOrder: 'Στην παραγγελία', cancel: 'Ακύρωση',
viewOrder: 'Η παραγγελία', items_one: '{{count}} τεμάχιο', items_other: '{{count}} τεμάχια',
yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', products: 'Προϊόντα', fee: 'Χρέωση διανομής', total: 'Σύνολο',
pricing: 'Υπολογισμός τιμής…', details: 'Τα στοιχεία σας', name: 'Όνομα', phone: 'Τηλέφωνο',
address: 'Οδός και αριθμός', area: 'Περιοχή', areaPick: 'Επιλέξτε περιοχή', byPostcode: 'Ή γράψτε τον Τ.Κ.',
byArea: 'Επιλογή από τη λίστα', postcode: 'Τ.Κ.', notes: 'Σημειώσεις για το κατάστημα (προαιρετικά)',
when: 'Πότε', asap: 'Το συντομότερο', pickTime: 'Επιλέξτε ώρα', today: 'Σήμερα', tomorrow: 'Αύριο',
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω',
payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.',
problem: {
party: 'Επιλέξτε πόσα άτομα.',
name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.',
area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.',
},
refused: {
minimum_not_met: 'Η ελάχιστη παραγγελία για διανομή είναι {{minimum}}.', area_not_served: 'Δυστυχώς δεν κάνουμε διανομή σε αυτή τη διεύθυνση.',
price_changed: 'Οι τιμές άλλαξαν από τότε που ανοίξατε το μενού. Ελέγξτε την παραγγελία: δείχνει πλέον τις τρέχουσες τιμές.',
item_unavailable: 'Κάτι στην παραγγελία σας δεν είναι πλέον διαθέσιμο. Αφαιρέστε το.', option_unavailable: 'Ένα έξτρα που επιλέξατε δεν είναι πλέον διαθέσιμο.',
service_unavailable: 'Αυτή η υπηρεσία δεν είναι διαθέσιμη τώρα.', closed: 'Είμαστε κλειστά τώρα. Επιλέξτε αργότερη ώρα.',
time_invalid: 'Η ώρα αυτή δεν είναι πλέον διαθέσιμη. Επιλέξτε άλλη.', details_missing: 'Συμπληρώστε τα στοιχεία σας.',
party_invalid: 'Online κρατήσεις έως {{max}} άτομα. Για μεγαλύτερες παρέες τηλεφωνήστε μας.',
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', no_menu: 'Το μενού δεν είναι διαθέσιμο αυτή τη στιγμή.', failed: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά.',
},
track: {
booking: {
title: 'Κράτηση {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε το αίτημα κράτησης.',
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', delivered: 'Καλώς ήρθατε',
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την κράτηση', cancelled: 'Ακυρώθηκε από το κατάστημα',
},
title: 'Παραγγελία {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε την παραγγελία σας.', for: 'Για {{when}}', asap: 'Το συντομότερο',
keep: 'Κρατήστε αυτή τη σελίδα ανοιχτή, ή αποθηκεύστε τη διεύθυνσή της, για να παρακολουθείτε την παραγγελία.',
status: {
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', preparing: 'Ετοιμάζεται',
ready: 'Έτοιμη για παραλαβή', out_for_delivery: 'Καθ\' οδόν', delivered: 'Ολοκληρώθηκε', rejected: 'Δεν έγινε δεκτή',
},
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την παραγγελία.', reason: 'Λόγος: {{reason}}', newOrder: 'Νέα παραγγελία', notFound: 'Η παραγγελία δεν βρέθηκε.',
},
},
}
export function initialLang() {
try {
const saved = localStorage.getItem(STORE)
if (saved && TEXTS[saved]) return saved
} catch { /* private mode */ }
return (navigator.language || 'en').toLowerCase().startsWith('el') ? 'el' : 'en'
}
export function saveLang(lang) {
try { localStorage.setItem(STORE, lang) } catch { /* private mode */ }
}
/** t('a.b', {x}) with {{x}} and _one/_other plurals by `count`. */
export function translate(lang, key, params = {}) {
const dict = TEXTS[lang] ?? TEXTS.en
const find = k => k.split('.').reduce((o, p) => (o == null ? undefined : o[p]), dict)
let s = params.count != null ? find(`${key}_${params.count === 1 ? 'one' : 'other'}`) : undefined
if (s === undefined) s = find(key)
if (typeof s !== 'string') return key
return s.replace(/\{\{(\w+)\}\}/g, (_, k) => (params[k] ?? ''))
}
export const LangContext = createContext({ lang: 'en', setLang: () => {} })
export function useT() {
const { lang, setLang } = useContext(LangContext)
const money = n => new Intl.NumberFormat(lang === 'el' ? 'el-GR' : 'en-IE', { style: 'currency', currency: 'EUR' }).format(n ?? 0)
return { lang, setLang, t: (key, params) => translate(lang, key, params), money }
}
+35
View File
@@ -0,0 +1,35 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* The app's tokens (RGB triples, used through tailwind.config.js). Light only for now. */
:root {
--o-canvas: 246 244 239;
--o-surface: 255 255 255;
--o-surface-2: 239 236 228;
--o-line: 226 221 209;
--o-ink: 28 36 33;
--o-ink-2: 88 96 92;
--o-ink-3: 140 145 140;
--o-accent: 31 58 52;
--o-accent-fg: 247 244 236;
--o-accent-soft: 222 234 228;
--o-accent-ink: 24 66 56;
--o-success: 48 120 78;
--o-success-soft: 225 242 231;
--o-success-ink: 30 92 56;
--o-warning-soft: 252 240 214;
--o-warning-ink: 124 82 10;
--o-danger-soft: 251 228 222;
--o-danger-ink: 160 50 30;
--o-shadow: 28 36 33;
color-scheme: light;
}
html, body { background: rgb(var(--o-canvas)); color: rgb(var(--o-ink)); }
body { font-family: theme('fontFamily.sans'); -webkit-font-smoothing: antialiased; }
button { -webkit-tap-highlight-color: transparent; }
:focus-visible { outline: 3px solid rgb(var(--o-accent) / 0.45); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}
+187
View File
@@ -0,0 +1,187 @@
// The online ordering app's logic (plan phase 3S, step S.4). Pure: unit-tested in Node
// (tests/logic.test.mjs). Prices shown come from the venue's menu for the chosen service;
// what is charged is the cloud's answer (POST /api/orders/{site}/quote and the order itself).
export const SERVICES = ['takeaway', 'delivery']
// 'preorder': food ordered with a table booking, ready on arrival (S.6)
export const POINT = { takeaway: 'online_takeaway', delivery: 'online_delivery', preorder: 'online_preorder' }
export const BOOKING_TYPES = ['reservation', 'preorder']
const round2 = n => Math.round(n * 100) / 100
/** A product's price for a service, or null when it isn't sold that way. */
export function priceFor(product, service) {
const point = POINT[service]
if (product.sold_at && !product.sold_at.includes(point)) return null
if (product.prices) return product.prices[point] ?? null
return product.digital_price ?? product.base_price ?? null // menus from before S.2
}
/** The menu for a service: categories with the products sold that way (once each, priced). */
export function menuFor(categories, service) {
const seen = new Set()
return (categories ?? []).map(c => ({
...c,
products: (c.products ?? []).filter(p => {
const price = priceFor(p, service)
return price != null
}).map(p => ({ ...p, price: priceFor(p, service), available: p.digital_available !== false, repeat: seen.has(p.id) || !seen.add(p.id) })),
})).filter(c => c.products.length > 0)
}
export const productName = p => p.digital_name || p.name
/** The 14 EU allergens (plan step 6.3), in the venue's order. */
export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs']
/** A product's allergens by level: {contains: [keys], may_contain: [keys]}. */
export function allergensOf(p) {
const m = p?.allergens && typeof p.allergens === 'object' && !Array.isArray(p.allergens) ? p.allergens : {}
return { contains: ALLERGENS.filter(k => m[k] === 'contains'), may_contain: ALLERGENS.filter(k => m[k] === 'may_contain') }
}
/**
* The menu in the guest's language (plan step 6.4): the venue sends each product's, quick option's
* and category's `names` (and `descriptions`) per menu language, already falling back to the text
* as typed; menus from older sites have none and stay as they are.
*/
export function localizeMenu(categories, lang) {
const pick = (texts, base) => (texts && texts[lang]) || base
return (categories ?? []).map(c => ({
...c,
name: pick(c.names, c.name),
products: (c.products ?? []).map(p => (p.names ? {
...p,
name: pick(p.names, p.digital_name || p.name),
digital_name: null,
digital_description: pick(p.descriptions, p.digital_description || '') || null,
quick_options: (p.quick_options ?? []).map(o => ({ ...o, name: pick(o.names, o.name) })),
} : p)),
}))
}
export const productText = p => p.digital_description || ''
/** A cart line's key: the product and its chosen options. */
export const lineKey = (productId, options = []) => [productId, ...[...options].sort((a, b) => a - b)].join(':')
/** Add one (or `qty`) of a product with options. */
export function addToCart(cart, product, options = [], qty = 1) {
const key = lineKey(product.id, options)
const found = cart.find(l => l.key === key)
if (found) return cart.map(l => (l.key === key ? { ...l, qty: Math.min(99, l.qty + qty) } : l))
return [...cart, { key, productId: product.id, options: [...options].sort((a, b) => a - b), qty }]
}
export function setQty(cart, key, qty) {
return qty <= 0 ? cart.filter(l => l.key !== key) : cart.map(l => (l.key === key ? { ...l, qty: Math.min(99, qty) } : l))
}
export const cartCount = cart => cart.reduce((s, l) => s + l.qty, 0)
/** The cart priced from the menu (what's shown before the cloud answers); lines whose product
* isn't sold for this service any more are dropped. */
export function cartLines(cart, products, service) {
const byId = new Map(products.map(p => [p.id, p]))
return cart.flatMap(l => {
const p = byId.get(l.productId)
const price = p ? priceFor(p, service) : null
if (price == null) return []
const opts = (p.quick_options ?? []).filter(o => l.options.includes(o.id))
const unit = round2(price + opts.reduce((s, o) => s + (o.price || 0), 0))
return [{ ...l, name: productName(p), unit, total: round2(unit * l.qty), optionNames: opts.map(o => o.name) }]
})
}
/** Items as the cloud takes them. */
export const itemsBody = lines => lines.map(l => ({ product_id: l.productId, quantity: l.qty, options: l.options, unit_price: l.unit }))
/** What checkout still needs: a list of field keys (empty = can order). */
export function checkoutProblems(form, service, { areas = [], asap = true, slots = [] } = {}) {
const out = []
if (!form.name.trim()) out.push('name')
if (!/^[+\d][\d\s-]{5,}$/.test(form.phone.trim())) out.push('phone')
if (service === 'delivery') {
if (!form.address.trim()) out.push('address')
if (areas.length && form.where === 'area' && !form.areaId) out.push('area')
if (form.where === 'postcode' && !form.postcode.trim()) out.push('postcode')
}
if (form.when === 'asap' ? !asap : !slots.includes(form.when)) out.push('when')
return out
}
/** The order request (POST /api/orders/{site}). `quote` is the cloud's last answer. */
export function orderBody(form, service, lines, quote) {
return {
order_type: service,
customer_name: form.name.trim(),
customer_phone: form.phone.trim(),
customer_address: service === 'delivery' ? form.address.trim() : null,
customer_notes: form.notes.trim() || null,
area_id: service === 'delivery' && form.where === 'area' && form.areaId ? Number(form.areaId) : null,
postcode: service === 'delivery' && form.where === 'postcode' ? form.postcode.trim() || null : null,
requested_for: form.when === 'asap' ? null : form.when,
items: itemsBody(lines),
total: quote?.total ?? undefined,
}
}
/** Slots grouped by local day for the picker: [{ day: 'YYYY-MM-DD', times: [{ iso, label }] }]. */
export function slotDays(slots, timeZone) {
const dayFmt = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })
const timeFmt = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', hour12: false })
const out = []
for (const iso of slots ?? []) {
const d = new Date(iso)
const day = dayFmt.format(d)
let g = out.find(x => x.day === day)
if (!g) out.push(g = { day, times: [] })
g.times.push({ iso, label: timeFmt.format(d) })
}
return out
}
/** What a table booking still needs (S.6): field keys (empty = can send). */
export function bookingProblems(form, booking, partyMax = 99) {
const out = []
if (!form.name.trim()) out.push('name')
if (!/^[+\d][\d\s-]{5,}$/.test(form.phone.trim())) out.push('phone')
if (!(booking.party >= 1 && booking.party <= partyMax)) out.push('party')
if (!booking.when) out.push('when')
return out
}
/** The booking request (POST /api/orders/{site}): a table only, or with food (a preorder). */
export function bookingBody(form, booking, lines, quote) {
const food = lines.length > 0
return {
order_type: food ? 'preorder' : 'reservation',
customer_name: form.name.trim(),
customer_phone: form.phone.trim(),
customer_notes: form.notes.trim() || null,
party_size: booking.party,
requested_for: booking.when,
items: food ? itemsBody(lines) : [],
total: food ? (quote?.total ?? undefined) : undefined,
}
}
/** The tracking page's steps for an order type, and how far it got. */
export function trackSteps(orderType, status) {
if (BOOKING_TYPES.includes(orderType)) {
const steps = ['pending_acceptance', 'accepted', 'delivered']
const over = ['rejected', 'cancelled'].includes(status)
return { steps, at: over ? -1 : steps.indexOf(status), done: status === 'delivered' || over }
}
const steps = orderType === 'delivery'
? ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered']
: ['pending_acceptance', 'accepted', 'preparing', 'ready', 'delivered']
return { steps, at: status === 'rejected' ? -1 : steps.indexOf(status), done: status === 'delivered' || status === 'rejected' }
}
/** A refusal from the cloud → a message key and its params. */
export function refusal(err) {
const d = err?.response?.data?.detail
if (err?.response?.status === 429) return ['rate', {}]
if (d && typeof d === 'object' && d.code) return [d.code.replace(/^order\./, ''), d.params ?? {}]
return ['failed', {}]
}
+26
View File
@@ -0,0 +1,26 @@
import { StrictMode, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter, Route, Routes } from 'react-router-dom'
import './index.css'
import { initialLang, LangContext, saveLang } from './i18n'
import OrderPage from './pages/OrderPage'
import TrackPage from './pages/TrackPage'
function App() {
const [lang, setLangState] = useState(initialLang)
const setLang = l => { setLangState(l); saveLang(l); document.documentElement.lang = l }
document.documentElement.lang = lang
return (
<LangContext.Provider value={{ lang, setLang }}>
<BrowserRouter basename="/order">
<Routes>
<Route path="/:site" element={<OrderPage />} />
<Route path="/:site/track/:token" element={<TrackPage />} />
<Route path="*" element={<p className="p-6 text-ink-2">Xenia</p>} />
</Routes>
</BrowserRouter>
</LangContext.Provider>
)
}
createRoot(document.getElementById('root')).render(<StrictMode><App /></StrictMode>)

Some files were not shown because too many files have changed in this diff Show More