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 (
+
+