diff --git a/local_backend/modules/connect_orders/manifest.py b/local_backend/modules/connect_orders/manifest.py index 311e138..d3876a9 100644 --- a/local_backend/modules/connect_orders/manifest.py +++ b/local_backend/modules/connect_orders/manifest.py @@ -1,5 +1,5 @@ """Module manifest — see core/modules/model.py and APPS_PLATFORM §4.""" -from core.modules.model import Module, Mount, Perm +from core.modules.model import Module, Mount, Perm, SettingDef MODULE = Module( key='connect_orders', @@ -11,6 +11,9 @@ MODULE = Module( Perm('connect_orders.manage', 'Accept and manage online orders', roles=('owner', 'store_manager', 'staff_manager', 'barista', 'barman')), Perm('connect_orders.fees', 'Set delivery areas and fees', roles=('owner', 'store_manager')), ), + settings=( + SettingDef('connect_orders.ordering', '{}', 'Online ordering (phase 3S): services offered, ordering hours, preparation and slot minutes, days ahead, as soon as possible. Edited on the Online ordering page.', type='json'), + ), routers=( Mount('routers.fees', '/api/connect/fees'), Mount('routers.connect_orders', '/api/connect'), diff --git a/local_backend/routers/fees.py b/local_backend/routers/fees.py index 12926dd..0828057 100644 --- a/local_backend/routers/fees.py +++ b/local_backend/routers/fees.py @@ -1,6 +1,7 @@ """Delivery areas and fee rules (plan phase 3S, step S.3). Key: connect_orders.fees. -GET /api/connect/fees {areas, rules} +GET /api/connect/fees {areas, rules, ordering} +GET /api/connect/fees/ordering the online ordering settings PUT: save them POST /api/connect/fees/areas add an area PUT/DELETE /areas/{id} POST /api/connect/fees/rules add a rule PUT/DELETE /rules/{id} PUT /api/connect/fees/rules/order [rule ids] in their new order @@ -47,6 +48,24 @@ def rule_out(r) -> dict: "time_from": r.time_from, "time_to": r.time_to, "action": r.action, "value": r.value, "stop": bool(r.stop)} +ORDERING_KEY = "connect_orders.ordering" +SERVICES = ("takeaway", "delivery") + + +def ordering_settings(db) -> dict: + """Online ordering (S.4), with defaults: no services until the venue turns them on.""" + from models.settings import PosSettings + row = db.query(PosSettings).filter(PosSettings.key == ORDERING_KEY).first() + try: + raw = json.loads(row.value) if row and row.value else {} + except ValueError: + raw = {} + try: + return OrderingBody(**{k: v for k, v in raw.items() if k in OrderingBody.model_fields}).model_dump() + except Exception: + return OrderingBody().model_dump() + + def fees_payload(db) -> dict: """What the engine needs (and the cloud gets): active and inactive alike, in order.""" from models.fees import DeliveryArea, FeeRule @@ -55,6 +74,42 @@ def fees_payload(db) -> dict: return {"areas": [area_out(a) for a in areas], "rules": [rule_out(r) for r in rules]} +class OrderingBody(BaseModel): + """What the online ordering app offers and when (plan phase 3S, S.4). The cloud enforces + it at checkout. hours: {"0".."6" (Mon..Sun): [["HH:MM", "HH:MM"], ...]}; no hours at all = + any time; once any day has hours, a day without them is closed. An end before its start + runs past midnight.""" + services: List[Literal["takeaway", "delivery"]] = Field(default_factory=list) + hours: dict = Field(default_factory=dict) + prep_minutes: int = Field(default=20, ge=0, le=24 * 60) # earliest collection/delivery after ordering + slot_minutes: int = Field(default=15, ge=5, le=120) # the times offered, every N minutes + days_ahead: int = Field(default=0, ge=0, le=7) # 0 = today only + asap: bool = True # "as soon as possible" offered while open + + @field_validator("services") + @classmethod + def _services(cls, v): + return [s for s in SERVICES if s in v] + + @field_validator("hours") + @classmethod + def _hours(cls, v): + out = {} + for day, ranges in (v or {}).items(): + if str(day) not in {str(d) for d in range(7)}: + raise ValueError("hours are keyed 0 (Monday) to 6 (Sunday)") + if not isinstance(ranges, list) or len(ranges) > 4: + raise ValueError("at most 4 time ranges a day") + clean = [] + for r in ranges: + if not (isinstance(r, (list, tuple)) and len(r) == 2 and all(isinstance(x, str) and HHMM.match(x) for x in r)) or r[0] == r[1]: + raise ValueError("a time range is [\"HH:MM\", \"HH:MM\"], start and end different") + clean.append([r[0], r[1]]) + if clean: + out[str(day)] = sorted(clean) + return out + + class AreaBody(BaseModel): name: str = Field(min_length=1, max_length=80) postcodes: List[str] = Field(default_factory=list, max_length=100) @@ -164,7 +219,27 @@ def _changed(): @router.get("") def list_fees(db: Session = Depends(get_db), user=Depends(require(KEY))): - return fees_payload(db) + return {**fees_payload(db), "ordering": ordering_settings(db)} + + +@router.get("/ordering") +def get_ordering(db: Session = Depends(get_db), user=Depends(require(KEY))): + return ordering_settings(db) + + +@router.put("/ordering") +def put_ordering(body: OrderingBody, db: Session = Depends(get_db), user=Depends(require(KEY))): + """Save the online ordering settings (they reach the cloud with the menu, within seconds).""" + from models.settings import PosSettings + row = db.query(PosSettings).filter(PosSettings.key == ORDERING_KEY).first() + value = json.dumps(body.model_dump()) + if row is None: + db.add(PosSettings(key=ORDERING_KEY, value=value)) + else: + row.value = value + db.commit() + _changed() + return body.model_dump() @router.post("/areas", status_code=201) diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index e3b26c1..09557c9 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -295,8 +295,9 @@ def menu_snapshot(db) -> tuple[dict, list]: # delivery areas and fee rules (S.3): the cloud applies them at checkout with the same # engine (services/fees.py); the venue's time zone says what "22:00" and "Saturday" mean from core.timeutil import venue_tz - from routers.fees import fees_payload - return {"categories": payload_categories, "fees": fees_payload(db), "timezone": venue_tz().key}, all_products + from routers.fees import fees_payload, ordering_settings + return {"categories": payload_categories, "fees": fees_payload(db), "ordering": ordering_settings(db), + "timezone": venue_tz().key}, all_products async def _push_menu_snapshot(): diff --git a/local_backend/tests/test_fees.py b/local_backend/tests/test_fees.py index 016ee30..44054b7 100644 --- a/local_backend/tests/test_fees.py +++ b/local_backend/tests/test_fees.py @@ -133,3 +133,21 @@ def test_changes_push_the_menu_soon(): assert not menu_changed("GET", "/api/products/", 200) assert not menu_changed("POST", "/api/pricing/modifiers", 422) assert not menu_changed("POST", "/api/orders/1/items", 200) + + +def test_online_ordering_settings(client, db, owner_h): + """S.4: the services, hours and timing the online ordering app follows (the cloud + enforces them); off until the venue turns a service on.""" + from services.cloud_sync import menu_snapshot + assert client.get("/api/connect/fees/ordering", headers=owner_h).json()["services"] == [] + body = {"services": ["delivery", "takeaway"], "hours": {"5": [["20:00", "02:00"]], "6": [["12:00", "16:00"], ["18:00", "23:00"]]}, + "prep_minutes": 30, "slot_minutes": 15, "days_ahead": 1, "asap": False} + r = client.put("/api/connect/fees/ordering", headers=owner_h, json=body) + assert r.status_code == 200, r.text + assert r.json()["services"] == ["takeaway", "delivery"] # fixed order + assert client.get("/api/connect/fees", headers=owner_h).json()["ordering"]["days_ahead"] == 1 + snap, _ = menu_snapshot(db) + assert snap["ordering"]["hours"]["6"] == [["12:00", "16:00"], ["18:00", "23:00"]] and snap["ordering"]["asap"] is False + for bad in ({"services": ["teleport"]}, {"hours": {"7": [["10:00", "11:00"]]}}, {"hours": {"1": [["10:00", "10:00"]]}}, + {"hours": {"1": [["25:00", "11:00"]]}}, {"slot_minutes": 1}, {"days_ahead": 30}, {"prep_minutes": -5}): + assert client.put("/api/connect/fees/ordering", headers=owner_h, json=bad).status_code == 422, bad diff --git a/manager_dashboard/src/pages/online/FeesPage.jsx b/manager_dashboard/src/pages/online/FeesPage.jsx index b3b8859..4e1ff1f 100644 --- a/manager_dashboard/src/pages/online/FeesPage.jsx +++ b/manager_dashboard/src/pages/online/FeesPage.jsx @@ -1,4 +1,5 @@ -// Delivery areas and fees (plan phase 3S, step S.3). Backend: /api/connect/fees +// Online ordering (plan phase 3S, steps S.3–S.4): the ordering settings (OrderingSettings), +// delivery areas and fees. Backend: /api/connect/fees // (connect_orders.fees). The venue lists the areas it delivers to and the fee rules, looked // at from the top: a rule whose conditions hold changes the fee (set, add, % of the // products, free) or refuses the order below a minimum; "stop here" makes the first match @@ -12,6 +13,7 @@ import { useFormat, useTranslation } from '@xenia/i18n' import { SALES_POINTS } from '@xenia/access' import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui' import client from '../../api/client' +import OrderingSettings from './OrderingSettings' import { ACTIONS, DAYS, describeRule, emptyRule, moveRule, parsePostcodes, previewBody, ruleBody, ruleProblems, ruleToForm } from './feesLogic' const chip = on => `px-3 min-h-[var(--x-control-sm)] rounded-full text-label font-medium transition-colors duration-fast @@ -51,10 +53,16 @@ export default function FeesPage() { return (
-

{t('fees.title')}

-

{t('fees.intro')}

+

{t('ordering.pageTitle')}

+ + +
+

{t('fees.title')}

+

{t('fees.intro')}

+
+
diff --git a/manager_dashboard/src/pages/online/OrderingSettings.jsx b/manager_dashboard/src/pages/online/OrderingSettings.jsx new file mode 100644 index 0000000..820b541 --- /dev/null +++ b/manager_dashboard/src/pages/online/OrderingSettings.jsx @@ -0,0 +1,98 @@ +// Online ordering settings (plan phase 3S, step S.4): which services the online ordering app +// offers (takeaway, delivery), when (ordering hours per day, or any time), how long before +// an order can be ready (preparation), the times offered (every N minutes, days ahead) and +// "as soon as possible". The cloud enforces them at checkout. PUT /api/connect/fees/ordering. +import { useState } from 'react' +import toast from 'react-hot-toast' +import { Plus, X } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Field, IconButton, Input, Select, Switch } from '@xenia/ui' +import client from '../../api/client' +import { DAYS, orderingBody, orderingToForm } from './feesLogic' + +export default function OrderingSettings({ ordering, onSaved }) { + const { t } = useTranslation('manager') + const [form, setForm] = useState(() => orderingToForm(ordering)) + const [busy, setBusy] = useState(false) + const set = (k, v) => setForm(f => ({ ...f, [k]: v })) + const setDay = (d, ranges) => setForm(f => ({ ...f, days: f.days.map((r, i) => (i === d ? ranges : r)) })) + const toggleService = s => set('services', form.services.includes(s) ? form.services.filter(x => x !== s) : ['takeaway', 'delivery'].filter(x => x === s || form.services.includes(x))) + + const save = async () => { + setBusy(true) + try { + const { data } = await client.put('/api/connect/fees/ordering', orderingBody(form)) + setForm(orderingToForm(data)) + toast.success(t('fees.saved')) + onSaved?.() + } catch (err) { toast.error(errorMessage(err, t)) } + setBusy(false) + } + + return ( +
+
+

{t('ordering.title')}

+

{t('ordering.intro')}

+
+ +
+ {['takeaway', 'delivery'].map(s => ( + toggleService(s)} + label={t(`ordering.service.${s}`)} description={t(`ordering.serviceHint.${s}`)} data-testid={`ordering-${s}`} /> + ))} +
+ +
+ set('anyTime', v)} label={t('ordering.anyTime')} description={t('ordering.anyTimeHint')} /> + {!form.anyTime && ( +
    + {DAYS.map(d => ( +
  • + {t(`fees.dayLong.${d}`)} +
    + {form.days[d].length === 0 && {t('ordering.closedDay')}} + {form.days[d].map((r, i) => ( +
    + setDay(d, form.days[d].map((x, j) => (j === i ? { ...x, from: e.target.value } : x)))} /> + – + setDay(d, form.days[d].map((x, j) => (j === i ? { ...x, to: e.target.value } : x)))} /> + setDay(d, form.days[d].filter((_, j) => j !== i))}> +
    + ))} + {form.days[d].length < 4 && ( + + )} +
    +
  • + ))} +
+ )} +
+ +
+ + set('prep_minutes', e.target.value)} /> + + + + + + + +
+ set('asap', v)} label={t('ordering.asap')} description={t('ordering.asapHint')} /> +
+
+ ) +} diff --git a/manager_dashboard/src/pages/online/feesLogic.js b/manager_dashboard/src/pages/online/feesLogic.js index a98664c..0eadb64 100644 --- a/manager_dashboard/src/pages/online/feesLogic.js +++ b/manager_dashboard/src/pages/online/feesLogic.js @@ -102,3 +102,30 @@ export function previewBody(form) { time: form.day === 'now' ? null : (form.time || null), } } + +/** Online ordering settings (S.4) → the form: hours as editable rows per day. */ +export function orderingToForm(o) { + const hours = o?.hours ?? {} + return { + services: o?.services ?? [], anyTime: Object.keys(hours).length === 0, + days: DAYS.map(d => (hours[String(d)] ?? []).map(([from, to]) => ({ from, to }))), + prep_minutes: String(o?.prep_minutes ?? 20), slot_minutes: String(o?.slot_minutes ?? 15), + days_ahead: String(o?.days_ahead ?? 0), asap: o?.asap ?? true, + } +} + +/** The form → PUT /api/connect/fees/ordering. A day without ranges is closed (unless any time). */ +export function orderingBody(form) { + const hours = {} + if (!form.anyTime) { + form.days.forEach((ranges, d) => { + const clean = ranges.filter(r => r.from && r.to && r.from !== r.to).map(r => [r.from, r.to]) + if (clean.length) hours[String(d)] = clean + }) + } + const int = (v, dflt) => (Number.isFinite(Number(v)) && String(v).trim() !== '' ? Math.round(Number(v)) : dflt) + return { + services: form.services, hours, prep_minutes: int(form.prep_minutes, 20), slot_minutes: int(form.slot_minutes, 15), + days_ahead: int(form.days_ahead, 0), asap: !!form.asap, + } +} diff --git a/manager_dashboard/tests/fees.test.mjs b/manager_dashboard/tests/fees.test.mjs index 45a5f42..5fa2b48 100644 --- a/manager_dashboard/tests/fees.test.mjs +++ b/manager_dashboard/tests/fees.test.mjs @@ -49,3 +49,17 @@ test('moving rules and the test form', () => { assert.deepEqual(previewBody({ sales_point: 'online_delivery', where: 'area', area_id: '2', postcode: '', subtotal: '', items: '', day: '5', time: '23:30' }), { sales_point: 'online_delivery', area_id: 2, postcode: null, subtotal: 0, items: 0, weekday: 5, time: '23:30' }) }) + +test('online ordering settings: hours per day, any time, numbers', async () => { + const { orderingBody, orderingToForm } = await import('../src/pages/online/feesLogic.js') + const saved = { services: ['delivery'], hours: { 5: [['20:00', '02:00']] }, prep_minutes: 30, slot_minutes: 15, days_ahead: 1, asap: false } + const form = orderingToForm(saved) + assert.equal(form.anyTime, false) + assert.deepEqual(form.days[5], [{ from: '20:00', to: '02:00' }]) + assert.deepEqual(orderingBody(form), saved) + assert.deepEqual(orderingBody({ ...form, anyTime: true }).hours, {}) + const blank = orderingToForm(null) + assert.deepEqual(orderingBody({ ...blank, prep_minutes: '' }), { services: [], hours: {}, prep_minutes: 20, slot_minutes: 15, days_ahead: 0, asap: true }) + form.days[0] = [{ from: '12:00', to: '12:00' }, { from: '', to: '15:00' }] + assert.equal(orderingBody(form).hours['0'], undefined) +}) diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 9ef8ced..daccc6b 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -45,7 +45,7 @@ "devices": "Συσκευές", "sessions": "Συνδεδεμένοι τώρα", "approvals": "Εγκρίσεις υπευθύνου", - "deliveryFees": "Χρεώσεις διανομής" + "deliveryFees": "Online παραγγελίες (ρύθμιση)" }, "profile": { "edit": "Επεξεργασία προφίλ", @@ -509,5 +509,37 @@ "minimum_not_met": "Απορρίπτεται: η ελάχιστη παραγγελία είναι {{minimum}}.", "area_not_served": "Απορρίπτεται: δεν γίνεται διανομή σε αυτή τη διεύθυνση." } + }, + "ordering": { + "pageTitle": "Online παραγγελίες", + "title": "Υπηρεσίες και ωράριο", + "intro": "Τι μπορούν να παραγγείλουν οι πελάτες online και πότε. Παραγγελίες γίνονται μόνο για τις ενεργές υπηρεσίες, μέσα στο ωράριο, για ώρα που αφήνει αρκετό χρόνο προετοιμασίας.", + "service": { + "takeaway": "Παραλαβή", + "delivery": "Διανομή" + }, + "serviceHint": { + "takeaway": "Οι πελάτες παραγγέλνουν online και παραλαμβάνουν από το κατάστημα.", + "delivery": "Οι πελάτες παραγγέλνουν online και εσείς παραδίδετε (περιοχές και χρεώσεις παρακάτω)." + }, + "anyTime": "Οποιαδήποτε ώρα", + "anyTimeHint": "Απενεργοποιήστε για ωράριο παραγγελιών ανά ημέρα.", + "closedDay": "Κλειστά", + "addHours": "Προσθήκη ωραρίου", + "prep": "Προετοιμασία (λεπτά)", + "prepHint": "Η νωρίτερη ώρα που προσφέρεται είναι τόσο μετά την παραγγελία.", + "slot": "Ώρες κάθε", + "slotHint": "Ο πελάτης επιλέγει μία από αυτές τις ώρες.", + "minutes": "{{n}} λεπτά", + "ahead": "Παραγγελία από πριν", + "aheadN": { + "0": "Μόνο σήμερα", + "1": "Έως αύριο", + "2": "Έως 2 ημέρες", + "3": "Έως 3 ημέρες", + "7": "Έως μία εβδομάδα" + }, + "asap": "«Το συντομότερο»", + "asapHint": "Όσο είναι ανοιχτά, οι πελάτες μπορούν να παραγγείλουν και για το συντομότερο." } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index b467565..b0f4893 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -45,7 +45,7 @@ "devices": "Devices", "sessions": "Signed in now", "approvals": "Manager approvals", - "deliveryFees": "Delivery fees" + "deliveryFees": "Online ordering" }, "profile": { "edit": "Edit profile", @@ -509,5 +509,37 @@ "minimum_not_met": "Refused: the minimum order is {{minimum}}.", "area_not_served": "Refused: no delivery to this address." } + }, + "ordering": { + "pageTitle": "Online ordering", + "title": "Services and hours", + "intro": "What customers can order online and when. Orders are taken only for the services turned on, within the hours, for a time that leaves enough preparation.", + "service": { + "takeaway": "Takeaway", + "delivery": "Delivery" + }, + "serviceHint": { + "takeaway": "Customers order online and collect at the venue.", + "delivery": "Customers order online and you deliver (areas and fees below)." + }, + "anyTime": "Any time", + "anyTimeHint": "Turn off to set ordering hours for each day.", + "closedDay": "Closed", + "addHours": "Add hours", + "prep": "Preparation (minutes)", + "prepHint": "The earliest time offered is this long after ordering.", + "slot": "Times offered every", + "slotHint": "The customer picks one of these times.", + "minutes": "{{n}} minutes", + "ahead": "Order ahead", + "aheadN": { + "0": "Today only", + "1": "Up to tomorrow", + "2": "Up to 2 days", + "3": "Up to 3 days", + "7": "Up to a week" + }, + "asap": "\"As soon as possible\"", + "asapHint": "While open, customers can also order for as soon as possible." } } diff --git a/tests/e2e/order_app.mjs b/tests/e2e/order_app.mjs new file mode 100644 index 0000000..c3bf11c --- /dev/null +++ b/tests/e2e/order_app.mjs @@ -0,0 +1,185 @@ +// End-to-end: the online ordering app (plan phase 3S, step S.4), in a phone-sized browser +// against a real cloud backend (a temp database). Done when: a delivery order with a fee and a +// takeaway order are placed in the browser, priced by the cloud, and tracked to the end. +// - the cloud starts empty; a site is registered and pushes a menu as the venue's server +// does (prices per sales point, delivery areas and fee rules, ordering settings) +// - the app is built with the cloud's address and served by `vite preview` at /order/ +// - takeaway: two colas at the takeaway price → placed → tracking page +// - delivery: below the minimum → refused with the minimum; more → the fee for the area +// → placed → the site moves it on (accepted → … → delivered) → the page follows +// node order_app.mjs +import { spawn } from 'node:child_process' +import { openSync, rmSync, mkdirSync } from 'node:fs' +import crypto from 'node:crypto' +import path from 'node:path' +import { chromium } from 'playwright' +import { BROWSER_CHANNEL, CLOUD, OUT, PYTHON, REPO, reporter, sleep } from './lib/env.mjs' +import { killTree, waitHttp } from './lib/proc.mjs' + +const CLOUD_PORT = 8113 +const APP_PORT = 5211 +const CLOUD_URL = `http://127.0.0.1:${CLOUD_PORT}` +const APP_DIR = path.join(REPO, 'cloud-service', 'connect_frontend', 'order-app') +const r = reporter('order app: takeaway + delivery, priced by the cloud, tracked') +const procs = [] + +function start(cmd, args, opts, logName) { + const log = openSync(path.join(OUT, logName), 'w') + const p = spawn(cmd, args, { ...opts, shell: process.platform === 'win32', detached: process.platform !== 'win32', stdio: ['ignore', log, log] }) + procs.push(p) + return p +} + +async function call(method, url, { body, headers = {} } = {}) { + const res = await fetch(`${CLOUD_URL}${url}`, { method, headers: { 'content-type': 'application/json', ...headers }, body: body ? JSON.stringify(body) : undefined }) + const text = await res.text() + let data = null + try { data = text ? JSON.parse(text) : null } catch { data = text } + if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 300)}`) + return data +} + +let browser +try { + // ── the cloud, empty ────────────────────────────────────────────────────── + const tmp = path.join(OUT, 'order-app-cloud') + rmSync(tmp, { recursive: true, force: true }) + mkdirSync(tmp, { recursive: true }) + const key = crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'der', type: 'pkcs8' }).subarray(-32).toString('base64') + start(PYTHON, ['-m', 'uvicorn', 'main:app', '--port', String(CLOUD_PORT)], { + cwd: CLOUD, env: { ...process.env, DATABASE_URL: `sqlite:///${path.join(tmp, 'cloud.db').replace(/\\/g, '/')}`, ADMIN_USERNAME: 'e2eadmin', + ADMIN_PASSWORD: 'e2e-admin-pass', SECRET_KEY: 'e2e', LICENSE_SIGNING_KEY: key, PYTHONIOENCODING: 'utf-8' }, + }, 'order-app-cloud.log') + await waitHttp(`${CLOUD_URL}/docs`, true, 60_000) + + // ── a venue, as the site would set it up ───────────────────────────────── + const admin = await call('POST', '/api/auth/login', { body: { username: 'e2eadmin', password: 'e2e-admin-pass' } }) + const site = await call('POST', '/api/sites/', { headers: { authorization: `Bearer ${admin.access_token}` }, + body: { name: 'Taverna', owner_name: 'O', contact_email: 'o@example.com', license_expires_at: '2030-01-01T00:00:00+00:00' } }) + const siteH = { 'X-Site-ID': site.site_id, 'X-Site-Key': site.secret_key } + const hb = await call('POST', '/api/heartbeat/', { headers: siteH, body: { version: '2.0.0', local_ip: '10.0.0.2', module_catalog: [] } }) + const numeric = hb.site_numeric_id + const snapshot = { + timezone: 'Europe/Athens', + categories: [ + { id: 1, name: 'Drinks', products: [ + { id: 11, name: 'Cola 1.5L', base_price: 3.5, digital_price: 3.5, digital_available: true, sold_at: ['qr_table', 'online_takeaway', 'online_delivery'], + prices: { qr_table: 3.5, online_takeaway: 2.5, online_delivery: 2.8 }, quick_options: [{ id: 7, name: 'Ice', price: 0.2 }] }, + ] }, + { id: 2, name: 'Food', products: [ + { id: 12, name: 'Souvlaki', digital_description: 'Pork, pita, tzatziki', base_price: 4, digital_price: 4, digital_available: true, + sold_at: ['online_takeaway', 'online_delivery'], prices: { online_takeaway: 4, online_delivery: 4.2 }, quick_options: [] }, + { id: 13, name: 'Soup of the day', base_price: 6, digital_available: false, sold_at: ['online_delivery'], prices: { online_delivery: 6 }, quick_options: [] }, + ] }, + ], + fees: { + areas: [{ id: 1, name: 'Centre', postcodes: ['24100'], is_active: true }, { id: 2, name: 'Hills', 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: 'Hills', area_ids: [2], action: 'add', value: 1, sales_points: ['online_delivery'] }, + ], + }, + ordering: { services: ['takeaway', 'delivery'], hours: {}, prep_minutes: 20, slot_minutes: 15, days_ahead: 0, asap: true }, + } + await call('POST', '/api/menu/sync', { headers: siteH, body: { site_id: numeric, snapshot_json: JSON.stringify(snapshot) } }) + + // ── the app, built for this cloud ───────────────────────────────────────── + const build = spawn('npx', ['vite', 'build'], { cwd: APP_DIR, shell: process.platform === 'win32', env: { ...process.env, VITE_CLOUD_URL: CLOUD_URL }, stdio: 'ignore' }) + const built = await new Promise(res => build.on('exit', code => res(code === 0))) + r.check('the order app builds with the cloud address', built) + start('npx', ['vite', 'preview', '--port', String(APP_PORT), '--strictPort'], { cwd: APP_DIR }, 'order-app-preview.log') + await waitHttp(`http://localhost:${APP_PORT}/order/`, true, 60_000) + + browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) + const page = await browser.newPage({ viewport: { width: 390, height: 844 }, locale: 'en-GB' }) + const errors = [] + page.on('pageerror', e => errors.push(e.message)) + const product = id => page.locator(`[data-testid="product"][data-product="${id}"]`).first() + + await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`) + r.check('the venue and its services show (takeaway first, open now)', await page.getByTestId('venue-name').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false) + && await page.getByTestId('service-takeaway').getAttribute('aria-checked') === 'true' && (await page.getByTestId('open-state').textContent()).includes('Open')) + r.check('takeaway prices; the soup (delivery only) is not on the takeaway menu', + (await product(11).getByTestId('price').textContent()).includes('2.50') && await product(13).count() === 0) + await page.getByTestId('service-delivery').click() + r.check('delivery prices; the soup shows as sold out', (await product(11).getByTestId('price').textContent()).includes('2.80') + && (await product(13).textContent()).includes('Sold out')) + await page.screenshot({ path: path.join(OUT, 'order-app-menu.png'), fullPage: true }) + + // ── takeaway ───────────────────────────────────────────────────────────── + await page.getByTestId('service-takeaway').click() + await product(12).getByTestId('add').click() + await product(12).getByRole('button', { name: '+' }).click() + await page.getByTestId('view-order').click() + await page.getByTestId('checkout').waitFor({ timeout: 5000 }) + await page.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.total === '8', null, { timeout: 8000 }).catch(() => {}) + r.check('takeaway: the cloud prices it (2 × €4.00, no fee)', await page.getByTestId('totals').getAttribute('data-total') === '8' + && await page.getByTestId('fee').count() === 0) + await page.getByTestId('place-order').click() + r.check('takeaway: name and phone are asked for first', await page.getByText('Enter your name.').count() === 1 && await page.getByText('Enter a phone number we can call.').count() === 1) + await page.getByTestId('f-name').fill('Maria') + await page.getByTestId('f-phone').fill('6900000001') + await page.getByTestId('place-order').click() + await page.getByTestId('track').waitFor({ timeout: 10_000 }).catch(() => {}) + r.check('takeaway: placed → the tracking page with the order number and total', (await page.getByTestId('track-ref').textContent().catch(() => '')).includes('ORD-0001') + && (await page.getByTestId('track-total').textContent()).includes('8.00') && await page.getByTestId('track').getAttribute('data-status') === 'pending_acceptance') + const takeawayUrl = page.url() + + // ── delivery ───────────────────────────────────────────────────────────── + await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`) + await page.getByTestId('service-delivery').click() + await product(11).getByTestId('add').click() + await page.getByTestId('extras-add').click() // a cola, no extras: €2.80 + await page.getByTestId('view-order').click() + await page.getByTestId('f-area').selectOption('1') + await page.waitForFunction(() => document.querySelector('[data-testid="quote-problem"]'), null, { timeout: 8000 }).catch(() => {}) + r.check('delivery: below the minimum → refused with the minimum shown', await page.getByTestId('quote-problem').getAttribute('data-code').catch(() => '') === 'minimum_not_met' + && (await page.getByTestId('quote-problem').textContent()).includes('5.00')) + await page.getByRole('button', { name: 'Back' }).click() + await product(12).getByTestId('add').click() // + souvlaki €4.20 = €7.00 + await page.getByTestId('view-order').click() + await page.getByTestId('f-area').selectOption('2') // the hills: €2 + €1 + await page.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.total === '10', null, { timeout: 8000 }).catch(() => {}) + r.check('delivery: the area\'s fee comes from the cloud (products €7.00 + fee €3.00)', await page.getByTestId('totals').getAttribute('data-fee') === '3' + && await page.getByTestId('totals').getAttribute('data-total') === '10', await page.getByTestId('totals').textContent()) + await page.getByTestId('f-area').selectOption('1') + await page.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.total === '9', null, { timeout: 8000 }).catch(() => {}) + r.check('delivery: another area, another fee (€2.00)', await page.getByTestId('totals').getAttribute('data-fee') === '2') + await page.getByTestId('f-address').fill('Main square 3') + await page.screenshot({ path: path.join(OUT, 'order-app-checkout.png'), fullPage: true }) + await page.getByTestId('place-order').click() + await page.getByTestId('track').waitFor({ timeout: 10_000 }).catch(() => {}) + r.check('delivery: placed (the details were remembered) → tracking ORD-0002, €9.00 with the fee', + (await page.getByTestId('track-ref').textContent().catch(() => '')).includes('ORD-0002') && (await page.getByTestId('track-total').textContent()).includes('9.00')) + + // ── the venue moves it on; the page follows to the end ─────────────────── + const pending = await call('GET', `/api/orders/pending/${numeric}`, { headers: siteH }) + const delivery = pending.find(o => o.public_ref === 'ORD-0002') + r.check('the site receives it at the cloud\'s prices with the area', delivery && delivery.total === 9 && delivery.delivery_fee === 2 + && delivery.delivery_area === 'Centre' && delivery.sales_point === 'online_delivery', JSON.stringify(delivery)) + for (const status of ['accepted', 'preparing', 'out_for_delivery', 'delivered']) { + await call('PATCH', `/api/orders/${delivery.id}/status`, { headers: siteH, body: { status } }) + const seen = await page.waitForFunction(st => document.querySelector('[data-testid="track"]')?.dataset.status === st, status, { timeout: 15_000 }).then(() => true).catch(() => false) + r.check(`tracking follows: ${status}`, seen) + } + await page.screenshot({ path: path.join(OUT, 'order-app-track.png'), fullPage: true }) + // and the takeaway one is rejected with a reason + const takeaway = pending.find(o => o.public_ref === 'ORD-0001') + await call('PATCH', `/api/orders/${takeaway.id}/status`, { headers: siteH, body: { status: 'rejected', rejection_reason: 'Closing early' } }) + await page.goto(takeawayUrl) + r.check('a rejected order says so, with the reason', await page.waitForFunction(() => document.querySelector('[data-testid="track"]')?.dataset.status === 'rejected', null, { timeout: 15_000 }) + .then(() => true).catch(() => false) && await page.getByText('Closing early').count() === 1) + + // ── Greek ──────────────────────────────────────────────────────────────── + await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`) + await page.getByRole('button', { name: 'EL' }).click() + r.check('the app switches to Greek', await page.getByTestId('service-delivery').textContent() === 'Διανομή') + r.check('no page errors', errors.length === 0, errors.join(' | ')) +} catch (err) { + r.check(`unexpected error: ${err.message}`, false) +} finally { + await browser?.close() + for (const p of procs) killTree(p) +} +process.exit(r.done() ? 1 : 0) diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index 54a31bf..209b12e 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -2,7 +2,8 @@ // node run-all.mjs everything (Android included) // node run-all.mjs --no-android skip the emulator suite import { spawnSync } from 'node:child_process' -import { BACKEND, CS, E2E, PYTHON, WAITER } from './lib/env.mjs' +import path from 'node:path' +import { BACKEND, CS, E2E, PYTHON, REPO, WAITER } from './lib/env.mjs' const shell = process.platform === 'win32' const suites = [ @@ -16,12 +17,14 @@ const suites = [ ['lint: manager_dashboard (v2 code)', 'npm', ['run', 'lint', '--silent', '-w', 'manager-dashboard'], CS], ['unit: terminal (node --test)', 'npm', ['test', '--silent', '-w', 'terminal'], CS], ['lint: terminal', 'npm', ['run', 'lint', '--silent', '-w', 'terminal'], CS], + ['unit: order-app (node --test)', 'npm', ['test', '--silent'], path.join(REPO, 'cloud-service', 'connect_frontend', 'order-app')], ['install.sh', 'node', ['install.mjs'], E2E], ['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E], ['browser', 'node', ['browser.mjs'], E2E], ['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E], ['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E], ['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E], + ['order app (cloud: takeaway + delivery)', 'node', ['order_app.mjs'], E2E], ['stack (compose: terminal :8082, LAN only)', 'node', ['stack.mjs'], E2E], ] if (!process.argv.includes('--no-android')) suites.push(['android (emulator)', 'node', ['android.mjs'], E2E])