feat: delivery areas and fee rules with "test an order" (platform-v2 3S, S.3)
- models/fees.py + Alembic 0018: delivery_areas, fee_rules; key connect_orders.fees (owner, store manager; existing ones get it). - services/fees.py: the pure engine (set / add / % / free / minimum, conditions: sales points, areas, products total, item count, days, time incl. past midnight, stop), the same file as the cloud's; tests/fixtures/fee_cases.json shared, plus a test that the cloud copy is identical. - routers/fees.py at /api/connect/fees: areas and rules CRUD (validated), order, preview. - Snapshot carries fees + the venue's time zone; a change to products, pricing or fees pushes the menu within ~5 s (middleware -> cloud_sync.request_menu_push). - Manager: Online -> Delivery fees page (@xenia/ui): rules in order with words for each, areas with postcodes, "Test an order"; en/el texts; feesLogic.js unit-tested. - Tests: test_fees.py (39), manager unit +5, manager.mjs +7 on the real page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -75,6 +75,10 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."),
|
||||
"pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."),
|
||||
"order.not_sold_here": (422, "{name} isn't sold for this kind of order."),
|
||||
"fees.area_not_found": (404, "Delivery area {area_id} not found."),
|
||||
"fees.rule_not_found": (404, "Fee rule {rule_id} not found."),
|
||||
"fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."),
|
||||
"fees.order_invalid": (422, "The new order must list every rule once."),
|
||||
"refund.invalid": (422, "This refund doesn't add up ({reason})."),
|
||||
"refund.too_old": (409, "Only payments from today's business day can be refunded at the counter."),
|
||||
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
|
||||
|
||||
@@ -93,6 +93,19 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
# (v1's LicenseCheckMiddleware is gone: an unlicensed site gets the free tier, module by module, D-5.)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def _menu_change_push(request, call_next):
|
||||
"""A successful change to products, price rules or fees pushes the customer apps' menu
|
||||
soon (phase 3S; services/cloud_sync.request_menu_push)."""
|
||||
response = await call_next(request)
|
||||
from services.cloud_sync import menu_changed, request_menu_push
|
||||
if menu_changed(request.method, request.url.path, response.status_code):
|
||||
request_menu_push()
|
||||
return response
|
||||
|
||||
|
||||
# Added last = outermost: the request id exists before any other middleware runs.
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""delivery_areas + fee_rules; key connect_orders.fees for owners and managers (plan phase 3S, S.3)
|
||||
|
||||
Revision ID: 0018_fee_rules
|
||||
Revises: 0017_sales_points
|
||||
Create Date: 2026-11-16 10:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.timeutil import UTCDateTime
|
||||
|
||||
|
||||
revision = '0018_fee_rules'
|
||||
down_revision = '0017_sales_points'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('delivery_areas',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('postcodes', sa.Text(), nullable=False),
|
||||
sa.Column('is_active', sa.Integer(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', UTCDateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
with op.batch_alter_table('delivery_areas', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_delivery_areas_id'), ['id'], unique=False)
|
||||
|
||||
op.create_table('fee_rules',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('is_active', sa.Integer(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.Column('sales_points', sa.Text(), nullable=False),
|
||||
sa.Column('area_ids', sa.Text(), nullable=False),
|
||||
sa.Column('subtotal_min', sa.Float(), nullable=True),
|
||||
sa.Column('subtotal_max', sa.Float(), nullable=True),
|
||||
sa.Column('items_min', sa.Integer(), nullable=True),
|
||||
sa.Column('items_max', sa.Integer(), nullable=True),
|
||||
sa.Column('days', sa.Text(), nullable=False),
|
||||
sa.Column('time_from', sa.String(), nullable=True),
|
||||
sa.Column('time_to', sa.String(), nullable=True),
|
||||
sa.Column('action', sa.String(), nullable=False),
|
||||
sa.Column('value', sa.Float(), nullable=False),
|
||||
sa.Column('stop', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', UTCDateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
with op.batch_alter_table('fee_rules', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_fee_rules_id'), ['id'], unique=False)
|
||||
|
||||
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||
"select id, 'connect_orders.fees' from users where role in ('owner', 'store_manager')"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(sa.text("delete from user_permissions where key = 'connect_orders.fees'"))
|
||||
op.drop_table('fee_rules')
|
||||
op.drop_table('delivery_areas')
|
||||
@@ -34,4 +34,5 @@ import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
|
||||
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
|
||||
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
|
||||
import models.notification # noqa: F401 Notification, NotificationRead (step 1.11)
|
||||
import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3)
|
||||
import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Delivery areas and fee rules (plan phase 3S, step S.3).
|
||||
|
||||
The venue lists the areas it delivers to (by name, with postcodes when it wants the customer's
|
||||
postcode matched) and fee rules evaluated in order by services/fees.py — the same engine the
|
||||
cloud runs at checkout (the rules travel with the menu snapshot). See that module for the
|
||||
rule semantics.
|
||||
"""
|
||||
from sqlalchemy import Column, Float, Integer, String, Text
|
||||
|
||||
from core.timeutil import UTCDateTime, utcnow
|
||||
from database import Base
|
||||
|
||||
|
||||
class DeliveryArea(Base):
|
||||
__tablename__ = "delivery_areas"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
postcodes = Column(Text, nullable=False, default="[]") # JSON list of strings
|
||||
is_active = Column(Integer, nullable=False, default=1)
|
||||
sort_order = Column(Integer, nullable=False, default=0)
|
||||
created_at = Column(UTCDateTime, default=utcnow)
|
||||
|
||||
|
||||
class FeeRule(Base):
|
||||
__tablename__ = "fee_rules"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
is_active = Column(Integer, nullable=False, default=1)
|
||||
sort_order = Column(Integer, nullable=False, default=0)
|
||||
# conditions (empty / null = any)
|
||||
sales_points = Column(Text, nullable=False, default='["online_delivery"]') # JSON list
|
||||
area_ids = Column(Text, nullable=False, default="[]") # JSON list of ints
|
||||
subtotal_min = Column(Float, nullable=True) # products total >= this
|
||||
subtotal_max = Column(Float, nullable=True) # products total < this
|
||||
items_min = Column(Integer, nullable=True) # number of items >= this
|
||||
items_max = Column(Integer, nullable=True) # number of items <= this
|
||||
days = Column(Text, nullable=False, default="[]") # JSON list, Mon=0 … Sun=6
|
||||
time_from = Column(String, nullable=True) # "HH:MM", venue time
|
||||
time_to = Column(String, nullable=True) # "HH:MM"; before time_from = crosses midnight
|
||||
# what it does: set | add | percent | free | minimum
|
||||
action = Column(String, nullable=False, default="set")
|
||||
value = Column(Float, nullable=False, default=0.0)
|
||||
stop = Column(Integer, nullable=False, default=0) # no later rule is looked at once this one applies
|
||||
created_at = Column(UTCDateTime, default=utcnow)
|
||||
@@ -9,8 +9,10 @@ MODULE = Module(
|
||||
depends=('ordering', 'connect_menu'),
|
||||
permissions=(
|
||||
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')),
|
||||
),
|
||||
routers=(
|
||||
Mount('routers.fees', '/api/connect/fees'),
|
||||
Mount('routers.connect_orders', '/api/connect'),
|
||||
),
|
||||
workers=('services.cloud_sync:order_pull_worker',),
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Delivery areas and fee rules (plan phase 3S, step S.3). Key: connect_orders.fees.
|
||||
|
||||
GET /api/connect/fees {areas, rules}
|
||||
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
|
||||
POST /api/connect/fees/preview "test an order": the engine's answer and why
|
||||
|
||||
The rules and areas travel to the cloud with the menu snapshot (services/cloud_sync.py,
|
||||
contract C-2) and are applied there at checkout by the same engine (services/fees.py). Each
|
||||
change pushes the menu soon (main.py middleware). Rule semantics: services/fees.py.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import List, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core import sales_points
|
||||
from core.access.deps import require
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
|
||||
router = APIRouter()
|
||||
KEY = "connect_orders.fees"
|
||||
HHMM = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$")
|
||||
|
||||
SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"]
|
||||
|
||||
|
||||
# ── shapes ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
def area_out(a) -> dict:
|
||||
return {"id": a.id, "name": a.name, "postcodes": json.loads(a.postcodes or "[]"),
|
||||
"is_active": bool(a.is_active), "sort_order": a.sort_order}
|
||||
|
||||
|
||||
def rule_out(r) -> dict:
|
||||
return {"id": r.id, "name": r.name, "is_active": bool(r.is_active), "sort_order": r.sort_order,
|
||||
"sales_points": json.loads(r.sales_points or "[]"), "area_ids": json.loads(r.area_ids or "[]"),
|
||||
"subtotal_min": r.subtotal_min, "subtotal_max": r.subtotal_max,
|
||||
"items_min": r.items_min, "items_max": r.items_max, "days": json.loads(r.days or "[]"),
|
||||
"time_from": r.time_from, "time_to": r.time_to, "action": r.action, "value": r.value, "stop": bool(r.stop)}
|
||||
|
||||
|
||||
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
|
||||
areas = db.query(DeliveryArea).order_by(DeliveryArea.sort_order, DeliveryArea.id).all()
|
||||
rules = db.query(FeeRule).order_by(FeeRule.sort_order, FeeRule.id).all()
|
||||
return {"areas": [area_out(a) for a in areas], "rules": [rule_out(r) for r in rules]}
|
||||
|
||||
|
||||
class AreaBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
postcodes: List[str] = Field(default_factory=list, max_length=100)
|
||||
is_active: bool = True
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _name(cls, v):
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("name is empty")
|
||||
return v
|
||||
|
||||
@field_validator("postcodes")
|
||||
@classmethod
|
||||
def _codes(cls, v):
|
||||
out = []
|
||||
for code in v:
|
||||
code = " ".join(str(code).split())
|
||||
if not code or len(code) > 20:
|
||||
raise ValueError("a postcode is empty or longer than 20 characters")
|
||||
if code not in out:
|
||||
out.append(code)
|
||||
return out
|
||||
|
||||
|
||||
class RuleBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
is_active: bool = True
|
||||
sales_points: List[SalesPoint] = Field(default_factory=lambda: ["online_delivery"])
|
||||
area_ids: List[int] = Field(default_factory=list, max_length=200)
|
||||
subtotal_min: Optional[float] = Field(default=None, ge=0, le=100000)
|
||||
subtotal_max: Optional[float] = Field(default=None, gt=0, le=100000)
|
||||
items_min: Optional[int] = Field(default=None, ge=0, le=10000)
|
||||
items_max: Optional[int] = Field(default=None, ge=0, le=10000)
|
||||
days: List[int] = Field(default_factory=list, max_length=7)
|
||||
time_from: Optional[str] = None
|
||||
time_to: Optional[str] = None
|
||||
action: Literal["set", "add", "percent", "free", "minimum"] = "set"
|
||||
value: float = Field(default=0.0, ge=-1000, le=100000)
|
||||
stop: bool = False
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _name(cls, v):
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("name is empty")
|
||||
return v
|
||||
|
||||
@field_validator("days")
|
||||
@classmethod
|
||||
def _days(cls, v):
|
||||
if any(d < 0 or d > 6 for d in v):
|
||||
raise ValueError("days are 0 (Monday) to 6 (Sunday)")
|
||||
return sorted(set(v))
|
||||
|
||||
@field_validator("time_from", "time_to")
|
||||
@classmethod
|
||||
def _time(cls, v):
|
||||
if v in (None, ""):
|
||||
return None
|
||||
if not HHMM.match(v):
|
||||
raise ValueError("times are HH:MM")
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _ranges(self):
|
||||
if self.subtotal_min is not None and self.subtotal_max is not None and self.subtotal_min >= self.subtotal_max:
|
||||
raise ValueError("the lower amount must be below the upper one")
|
||||
if self.items_min is not None and self.items_max is not None and self.items_min > self.items_max:
|
||||
raise ValueError("the lower item count must not be above the upper one")
|
||||
if (self.time_from is None) != (self.time_to is None):
|
||||
raise ValueError("give both times or neither")
|
||||
if self.action != "add" and self.value < 0:
|
||||
raise ValueError("only 'add' takes a negative amount")
|
||||
if self.action == "percent" and self.value > 100:
|
||||
raise ValueError("a percentage is at most 100")
|
||||
self.sales_points = sales_points.normalize(self.sales_points)
|
||||
self.area_ids = sorted(set(self.area_ids))
|
||||
return self
|
||||
|
||||
|
||||
def _check_areas(db, ids):
|
||||
from models.fees import DeliveryArea
|
||||
if ids:
|
||||
known = {a.id for a in db.query(DeliveryArea).filter(DeliveryArea.id.in_(ids)).all()}
|
||||
missing = [i for i in ids if i not in known]
|
||||
if missing:
|
||||
raise XeniaError("fees.area_not_found", area_id=missing[0])
|
||||
|
||||
|
||||
def _apply_rule(rule, body: RuleBody):
|
||||
rule.name, rule.is_active, rule.action, rule.value, rule.stop = body.name, int(body.is_active), body.action, body.value, int(body.stop)
|
||||
rule.sales_points, rule.area_ids, rule.days = json.dumps(body.sales_points), json.dumps(body.area_ids), json.dumps(body.days)
|
||||
rule.subtotal_min, rule.subtotal_max = body.subtotal_min, body.subtotal_max
|
||||
rule.items_min, rule.items_max = body.items_min, body.items_max
|
||||
rule.time_from, rule.time_to = body.time_from, body.time_to
|
||||
|
||||
|
||||
def _changed():
|
||||
from services.sse_bus import broadcast_sync
|
||||
broadcast_sync("fees_changed", {})
|
||||
|
||||
|
||||
# ── endpoints ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("")
|
||||
def list_fees(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
return fees_payload(db)
|
||||
|
||||
|
||||
@router.post("/areas", status_code=201)
|
||||
def add_area(body: AreaBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from models.fees import DeliveryArea
|
||||
count = db.query(DeliveryArea).count()
|
||||
area = DeliveryArea(name=body.name, postcodes=json.dumps(body.postcodes), is_active=int(body.is_active), sort_order=count)
|
||||
db.add(area)
|
||||
db.commit()
|
||||
_changed()
|
||||
return area_out(area)
|
||||
|
||||
|
||||
@router.put("/areas/{area_id}")
|
||||
def edit_area(area_id: int, body: AreaBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from models.fees import DeliveryArea
|
||||
area = db.get(DeliveryArea, area_id)
|
||||
if area is None:
|
||||
raise XeniaError("fees.area_not_found", area_id=area_id)
|
||||
area.name, area.postcodes, area.is_active = body.name, json.dumps(body.postcodes), int(body.is_active)
|
||||
db.commit()
|
||||
_changed()
|
||||
return area_out(area)
|
||||
|
||||
|
||||
@router.delete("/areas/{area_id}", status_code=204)
|
||||
def delete_area(area_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""Refused while a rule names the area (fees.area_in_use {rules}): change those rules first."""
|
||||
from models.fees import DeliveryArea, FeeRule
|
||||
area = db.get(DeliveryArea, area_id)
|
||||
if area is None:
|
||||
raise XeniaError("fees.area_not_found", area_id=area_id)
|
||||
users = [r.name for r in db.query(FeeRule).all() if area_id in json.loads(r.area_ids or "[]")]
|
||||
if users:
|
||||
raise XeniaError("fees.area_in_use", rules=", ".join(users))
|
||||
db.delete(area)
|
||||
db.commit()
|
||||
_changed()
|
||||
|
||||
|
||||
@router.post("/rules", status_code=201)
|
||||
def add_rule(body: RuleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from models.fees import FeeRule
|
||||
_check_areas(db, body.area_ids)
|
||||
rule = FeeRule(sort_order=db.query(FeeRule).count())
|
||||
_apply_rule(rule, body)
|
||||
db.add(rule)
|
||||
db.commit()
|
||||
_changed()
|
||||
return rule_out(rule)
|
||||
|
||||
|
||||
@router.put("/rules/order")
|
||||
def order_rules(ids: List[int], db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""The rules in their new order: every rule id once."""
|
||||
from models.fees import FeeRule
|
||||
rules = {r.id: r for r in db.query(FeeRule).all()}
|
||||
if sorted(ids) != sorted(rules):
|
||||
raise XeniaError("fees.order_invalid")
|
||||
for n, rid in enumerate(ids):
|
||||
rules[rid].sort_order = n
|
||||
db.commit()
|
||||
_changed()
|
||||
return fees_payload(db)
|
||||
|
||||
|
||||
@router.put("/rules/{rule_id}")
|
||||
def edit_rule(rule_id: int, body: RuleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from models.fees import FeeRule
|
||||
rule = db.get(FeeRule, rule_id)
|
||||
if rule is None:
|
||||
raise XeniaError("fees.rule_not_found", rule_id=rule_id)
|
||||
_check_areas(db, body.area_ids)
|
||||
_apply_rule(rule, body)
|
||||
db.commit()
|
||||
_changed()
|
||||
return rule_out(rule)
|
||||
|
||||
|
||||
@router.delete("/rules/{rule_id}", status_code=204)
|
||||
def delete_rule(rule_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from models.fees import FeeRule
|
||||
rule = db.get(FeeRule, rule_id)
|
||||
if rule is None:
|
||||
raise XeniaError("fees.rule_not_found", rule_id=rule_id)
|
||||
db.delete(rule)
|
||||
db.commit()
|
||||
_changed()
|
||||
|
||||
|
||||
class PreviewBody(BaseModel):
|
||||
sales_point: SalesPoint = "online_delivery"
|
||||
area_id: Optional[int] = None
|
||||
postcode: Optional[str] = Field(default=None, max_length=20)
|
||||
subtotal: float = Field(ge=0, le=100000)
|
||||
items: int = Field(ge=0, le=10000)
|
||||
weekday: Optional[int] = Field(default=None, ge=0, le=6) # venue's now when omitted
|
||||
time: Optional[str] = None # "HH:MM", venue's now when omitted
|
||||
|
||||
@field_validator("time")
|
||||
@classmethod
|
||||
def _time(cls, v):
|
||||
if v in (None, ""):
|
||||
return None
|
||||
if not HHMM.match(v):
|
||||
raise ValueError("times are HH:MM")
|
||||
return v
|
||||
|
||||
|
||||
@router.post("/preview")
|
||||
def preview(body: PreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""Test an order: the fee (or why it's refused) and the rules that applied, exactly as the
|
||||
cloud will compute it at checkout."""
|
||||
from core.timeutil import venue_now
|
||||
from services import fees
|
||||
data = fees_payload(db)
|
||||
now = venue_now()
|
||||
weekday = body.weekday if body.weekday is not None else now.weekday()
|
||||
hhmm = body.time or now.strftime("%H:%M")
|
||||
result = fees.compute(data["rules"], data["areas"], sales_point=body.sales_point, subtotal=body.subtotal,
|
||||
items=body.items, area_id=body.area_id, postcode=body.postcode, weekday=weekday, hhmm=hhmm)
|
||||
area = next((a for a in data["areas"] if a["id"] == result["area_id"]), None)
|
||||
return {**result, "area_name": area["name"] if area else None, "weekday": weekday, "time": hhmm,
|
||||
"total": round(body.subtotal + result["fee"], 2) if not result["refused"] else None}
|
||||
@@ -292,7 +292,11 @@ def menu_snapshot(db) -> tuple[dict, list]:
|
||||
if product_list:
|
||||
payload_categories.append({"id": cat.id, "name": cat.name, "sort_order": cat.sort_order,
|
||||
"products": product_list})
|
||||
return {"categories": payload_categories}, all_products
|
||||
# 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
|
||||
|
||||
|
||||
async def _push_menu_snapshot():
|
||||
@@ -307,7 +311,7 @@ async def _push_menu_snapshot():
|
||||
try:
|
||||
snapshot, all_products = menu_snapshot(db)
|
||||
payload_categories = snapshot["categories"]
|
||||
snapshot_json = json.dumps({"categories": payload_categories})
|
||||
snapshot_json = json.dumps(snapshot)
|
||||
|
||||
# Resolve numeric site_id from license state (set by heartbeat response)
|
||||
site_numeric_id = license_state.get("site_numeric_id")
|
||||
@@ -576,11 +580,42 @@ async def _wait_for_site_id(max_seconds: int = 30) -> None:
|
||||
await asyncio.sleep(1)
|
||||
|
||||
|
||||
# A change to what the customer apps sell (products, price rules, fees) pushes the menu soon,
|
||||
# not at the next 5-minute tick (phase 3S): request_menu_push() from any thread wakes the
|
||||
# worker; edits in a row within MENU_SETTLE_SECONDS become one push.
|
||||
MENU_SETTLE_SECONDS = 5
|
||||
MENU_PATHS = ("/api/products", "/api/pricing", "/api/connect/fees", "/api/data-transfer/import")
|
||||
_menu_wake: "asyncio.Event | None" = None
|
||||
_menu_loop = None
|
||||
|
||||
|
||||
def request_menu_push() -> None:
|
||||
"""Ask the menu worker to push soon. Thread-safe; nothing happens while it isn't running."""
|
||||
loop, wake = _menu_loop, _menu_wake
|
||||
if loop is not None and wake is not None:
|
||||
try:
|
||||
loop.call_soon_threadsafe(wake.set)
|
||||
except RuntimeError: # the loop has closed
|
||||
pass
|
||||
|
||||
|
||||
def menu_changed(method: str, path: str, status_code: int) -> bool:
|
||||
"""Whether a finished request changed what the customer apps sell."""
|
||||
return method not in ("GET", "HEAD", "OPTIONS") and status_code < 400 and path.startswith(MENU_PATHS)
|
||||
|
||||
|
||||
async def menu_push_worker():
|
||||
global _menu_wake, _menu_loop
|
||||
_menu_loop, _menu_wake = asyncio.get_running_loop(), asyncio.Event()
|
||||
await _wait_for_site_id()
|
||||
while True:
|
||||
_menu_wake.clear()
|
||||
await _push_menu_snapshot()
|
||||
await asyncio.sleep(PUSH_INTERVAL_SECONDS)
|
||||
try:
|
||||
await asyncio.wait_for(_menu_wake.wait(), PUSH_INTERVAL_SECONDS)
|
||||
await asyncio.sleep(MENU_SETTLE_SECONDS)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
|
||||
async def stats_push_worker():
|
||||
|
||||
@@ -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
|
||||
+108
@@ -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}}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Delivery areas and fee rules (plan phase 3S, step S.3).
|
||||
|
||||
Done when: the four rule kinds (fixed, area, free above €X, item-count tier) and the minimum
|
||||
give the right answer on both sides from the same cases, and the cloud refuses an order below
|
||||
the minimum (that half: cloud-service tests/test_checkout.py)."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_live import err, owner_h # noqa: F401 (fixtures)
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
CASES = json.loads((HERE / "fixtures" / "fee_cases.json").read_text(encoding="utf-8"))
|
||||
SITE_ENGINE = HERE.parent / "services" / "fees.py"
|
||||
CLOUD = HERE.parents[2] / "cloud-service" / "cloud_backend"
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
|
||||
def test_the_cloud_runs_the_same_engine_and_cases():
|
||||
"""The two copies must not drift (the cloud sits next to this repo in the parent checkout)."""
|
||||
if not CLOUD.exists():
|
||||
pytest.skip("cloud-service isn't checked out next to client-services")
|
||||
assert (CLOUD / "services" / "fees.py").read_text(encoding="utf-8") == SITE_ENGINE.read_text(encoding="utf-8")
|
||||
assert json.loads((CLOUD / "tests" / "fixtures" / "fee_cases.json").read_text(encoding="utf-8")) == CASES
|
||||
|
||||
|
||||
def _area(client, h, name, codes=(), **extra):
|
||||
r = client.post("/api/connect/fees/areas", headers=h, json={"name": name, "postcodes": list(codes), **extra})
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def _rule(client, h, **body):
|
||||
r = client.post("/api/connect/fees/rules", headers=h, json={"name": body.pop("name", "Rule"), **body})
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def _preview(client, h, **body):
|
||||
r = client.post("/api/connect/fees/preview", headers=h, json={"sales_point": "online_delivery", **body})
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_set_up_and_test_an_order(client, owner_h):
|
||||
"""The manager's flow: areas, rules of every kind, "test an order"."""
|
||||
h = owner_h
|
||||
centre = _area(client, h, "Village centre", ["241 00"])
|
||||
far = _area(client, h, "Kalamata", ["24131", " 24131 ", "24100"])
|
||||
assert far["postcodes"] == ["24131", "24100"] # tidied, no duplicates
|
||||
_rule(client, h, name="Minimum", action="minimum", value=10)
|
||||
_rule(client, h, name="Free over 25", subtotal_min=25, action="free", stop=True)
|
||||
_rule(client, h, name="Base", action="set", value=2)
|
||||
_rule(client, h, name="Far", area_ids=[far["id"]], action="add", value=1.5)
|
||||
_rule(client, h, name="Big order", items_min=10, action="add", value=1)
|
||||
p = _preview(client, h, area_id=centre["id"], subtotal=12, items=2)
|
||||
assert (p["fee"], p["total"], p["area_name"], [a["name"] for a in p["applied"]]) == (2.0, 14.0, "Village centre", ["Minimum", "Base"])
|
||||
assert _preview(client, h, postcode="241 31", subtotal=12, items=2)["fee"] == 3.5 # far, by postcode
|
||||
assert _preview(client, h, area_id=centre["id"], subtotal=12, items=11)["fee"] == 3.0 # big order
|
||||
assert _preview(client, h, area_id=far["id"], subtotal=30, items=11)["fee"] == 0.0 # free over 25 stops
|
||||
low = _preview(client, h, area_id=centre["id"], subtotal=8, items=1)
|
||||
assert (low["refused"], low["minimum"], low["total"]) == ("minimum_not_met", 10.0, None)
|
||||
assert _preview(client, h, postcode="10431", subtotal=12, items=2)["refused"] == "area_not_served"
|
||||
assert _preview(client, h, sales_point="online_takeaway", subtotal=12, items=2)["fee"] == 0.0 # delivery rules only
|
||||
listed = client.get("/api/connect/fees", headers=h).json()
|
||||
assert [r["name"] for r in listed["rules"]] == ["Minimum", "Free over 25", "Base", "Far", "Big order"]
|
||||
|
||||
|
||||
def test_order_edit_and_delete(client, owner_h):
|
||||
h = owner_h
|
||||
area = _area(client, h, "A")
|
||||
a = _rule(client, h, name="First", action="set", value=1)
|
||||
b = _rule(client, h, name="Second", area_ids=[area["id"]], action="set", value=2)
|
||||
assert client.put("/api/connect/fees/rules/order", headers=h, json=[a["id"]]).json()["error"]["code"] == "fees.order_invalid"
|
||||
r = client.put("/api/connect/fees/rules/order", headers=h, json=[b["id"], a["id"]])
|
||||
assert [x["name"] for x in r.json()["rules"]] == ["Second", "First"]
|
||||
assert err(client.delete(f"/api/connect/fees/areas/{area['id']}", headers=h)) == "fees.area_in_use"
|
||||
r = client.put(f"/api/connect/fees/rules/{b['id']}", headers=h, json={"name": "Second", "action": "set", "value": 2.5})
|
||||
assert r.status_code == 200 and r.json()["area_ids"] == [] and r.json()["value"] == 2.5
|
||||
assert client.delete(f"/api/connect/fees/areas/{area['id']}", headers=h).status_code == 204
|
||||
assert client.delete(f"/api/connect/fees/rules/{a['id']}", headers=h).status_code == 204
|
||||
assert err(client.delete(f"/api/connect/fees/rules/{a['id']}", headers=h)) == "fees.rule_not_found"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [
|
||||
{"name": " "},
|
||||
{"name": "x", "subtotal_min": 20, "subtotal_max": 10},
|
||||
{"name": "x", "items_min": 5, "items_max": 2},
|
||||
{"name": "x", "time_from": "22:00"},
|
||||
{"name": "x", "time_from": "25:00", "time_to": "02:00"},
|
||||
{"name": "x", "days": [7]},
|
||||
{"name": "x", "action": "set", "value": -1},
|
||||
{"name": "x", "action": "percent", "value": 150},
|
||||
{"name": "x", "action": "teleport"},
|
||||
{"name": "x", "sales_points": ["moon"]},
|
||||
])
|
||||
def test_bad_rules_are_refused(client, owner_h, body):
|
||||
assert client.post("/api/connect/fees/rules", headers=owner_h, json=body).status_code == 422
|
||||
|
||||
|
||||
def test_unknown_area_in_a_rule(client, owner_h):
|
||||
assert err(client.post("/api/connect/fees/rules", headers=owner_h, json={"name": "x", "area_ids": [999]})) == "fees.area_not_found"
|
||||
|
||||
|
||||
def test_only_the_key_holders(client, make_user, login):
|
||||
barista = make_user(role="barista")
|
||||
r = client.get("/api/connect/fees", headers=login(barista))
|
||||
assert r.status_code == 403 and r.json()["error"]["code"] == "access.denied"
|
||||
|
||||
|
||||
def test_the_cloud_gets_the_rules_with_the_menu(db, client, owner_h):
|
||||
from services.cloud_sync import menu_snapshot
|
||||
_area(client, owner_h, "Centre", ["24100"])
|
||||
_rule(client, owner_h, name="Base", action="set", value=2)
|
||||
snap, _ = menu_snapshot(db)
|
||||
assert [a["name"] for a in snap["fees"]["areas"]] == ["Centre"]
|
||||
assert snap["fees"]["rules"][0]["action"] == "set" and snap["timezone"]
|
||||
|
||||
|
||||
def test_changes_push_the_menu_soon():
|
||||
from services.cloud_sync import menu_changed
|
||||
assert menu_changed("POST", "/api/connect/fees/rules", 201)
|
||||
assert menu_changed("PUT", "/api/products/5", 200)
|
||||
assert menu_changed("PATCH", "/api/pricing/modifiers/3/toggle", 200)
|
||||
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)
|
||||
@@ -8,7 +8,7 @@
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test \"tests/*.test.mjs\"",
|
||||
"lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx"
|
||||
"lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/online src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.107.1",
|
||||
|
||||
@@ -17,6 +17,7 @@ import DashboardPage from './pages/DashboardPage'
|
||||
import TablesPage from './pages/TablesPage'
|
||||
import OrderDetailPage from './pages/OrderDetailPage'
|
||||
import OnlineOrdersPage from './pages/OnlineOrdersPage'
|
||||
import FeesPage from './pages/online/FeesPage'
|
||||
|
||||
// CRM
|
||||
import ContactsPage from './pages/crm/ContactsPage'
|
||||
@@ -145,6 +146,7 @@ export default function App() {
|
||||
<Route path="dashboard" element={<DashboardPage />} />
|
||||
<Route path="tables" element={<TablesPage />} />
|
||||
<Route path="online-orders" element={<OnlineOrdersPage />} />
|
||||
<Route path="online/fees" element={<FeesPage />} />
|
||||
<Route path="orders/:orderId" element={<OrderDetailPage />} />
|
||||
|
||||
{/* ── CRM ── */}
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
// Delivery areas and fees (plan phase 3S, step S.3). 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
|
||||
// win. The cloud applies the same rules at checkout (the same engine), so "Test an order"
|
||||
// shows exactly what a customer will be charged. No rules = no fee.
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import { ArrowDown, ArrowUp, MapPin, Pencil, Plus, Trash2, Truck } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
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 { 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
|
||||
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
|
||||
|
||||
export default function FeesPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
const [data, setData] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
const [dialog, setDialog] = useState(null) // { kind: 'area' | 'rule', item? } | { kind: 'delete', what, item }
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setData((await client.get('/api/connect/fees')).data)
|
||||
setError(null)
|
||||
} catch (err) { setError(errorMessage(err, t)) }
|
||||
}, [t])
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const areaNames = useMemo(() => Object.fromEntries((data?.areas ?? []).map(a => [a.id, a.name])), [data])
|
||||
|
||||
const act = async (fn, done) => {
|
||||
try {
|
||||
await fn()
|
||||
if (done) toast.success(done)
|
||||
await load()
|
||||
return true
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t))
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if (error) return <div className="p-6"><EmptyState title={error} /></div>
|
||||
if (!data) return <div className="p-6 flex justify-center"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6 grid gap-6 max-w-6xl" data-testid="fees-page">
|
||||
<header className="grid gap-1">
|
||||
<h1 className="text-heading font-semibold text-ink">{t('fees.title')}</h1>
|
||||
<p className="text-body text-ink-2 max-w-3xl">{t('fees.intro')}</p>
|
||||
</header>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_22rem] items-start">
|
||||
<section className="grid gap-3" aria-labelledby="fee-rules">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 id="fee-rules" className="flex-1 text-title font-semibold text-ink">{t('fees.rules')}</h2>
|
||||
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'rule' })} data-testid="rule-add">{t('fees.addRule')}</Button>
|
||||
</div>
|
||||
{data.rules.length === 0 ? (
|
||||
<EmptyState icon={<Truck size={28} />} title={t('fees.noRules')} description={t('fees.noRulesBody')} />
|
||||
) : (
|
||||
<ol className="grid gap-2" data-testid="rules">
|
||||
{data.rules.map((r, i) => (
|
||||
<RuleRow key={r.id} rule={r} n={i + 1} areaNames={areaNames} first={i === 0} last={i === data.rules.length - 1}
|
||||
onMove={step => act(() => client.put('/api/connect/fees/rules/order', moveRule(data.rules, r.id, step)))}
|
||||
onToggle={on => act(() => client.put(`/api/connect/fees/rules/${r.id}`, { ...ruleBody(ruleToForm(r)), is_active: on }))}
|
||||
onEdit={() => setDialog({ kind: 'rule', item: r })}
|
||||
onDelete={() => setDialog({ kind: 'delete', what: 'rule', item: r })} />
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="grid gap-6">
|
||||
<section className="grid gap-3" aria-labelledby="fee-areas">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 id="fee-areas" className="flex-1 text-title font-semibold text-ink">{t('fees.areas')}</h2>
|
||||
<Button variant="secondary" icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'area' })} data-testid="area-add">{t('fees.addArea')}</Button>
|
||||
</div>
|
||||
{data.areas.length === 0 ? (
|
||||
<p className="text-label text-ink-2">{t('fees.noAreas')}</p>
|
||||
) : (
|
||||
<ul className="grid gap-2" data-testid="areas">
|
||||
{data.areas.map(a => (
|
||||
<li key={a.id} className="p-3 rounded-card border border-line bg-surface flex items-start gap-2" data-testid="area">
|
||||
<MapPin size={16} className="mt-0.5 text-ink-3 shrink-0" aria-hidden="true" />
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className={`block text-body font-medium ${a.is_active ? 'text-ink' : 'text-ink-3 line-through'}`}>{a.name}</span>
|
||||
<span className="block text-caption text-ink-2 truncate">{a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}</span>
|
||||
</span>
|
||||
<IconButton size="sm" variant="ghost" label={t('fees.edit')} onClick={() => setDialog({ kind: 'area', item: a })}><Pencil size={16} /></IconButton>
|
||||
<IconButton size="sm" variant="ghost" label={t('fees.delete')} onClick={() => setDialog({ kind: 'delete', what: 'area', item: a })}><Trash2 size={16} /></IconButton>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
<TestOrder areas={data.areas} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{dialog?.kind === 'area' && (
|
||||
<AreaDialog area={dialog.item} onClose={() => setDialog(null)}
|
||||
onSave={body => act(() => (dialog.item ? client.put(`/api/connect/fees/areas/${dialog.item.id}`, body) : client.post('/api/connect/fees/areas', body)),
|
||||
t('fees.saved')).then(ok => ok && setDialog(null))} />
|
||||
)}
|
||||
{dialog?.kind === 'rule' && (
|
||||
<RuleDialog rule={dialog.item} areas={data.areas} onClose={() => setDialog(null)}
|
||||
onSave={body => act(() => (dialog.item ? client.put(`/api/connect/fees/rules/${dialog.item.id}`, body) : client.post('/api/connect/fees/rules', body)),
|
||||
t('fees.saved')).then(ok => ok && setDialog(null))} />
|
||||
)}
|
||||
{dialog?.kind === 'delete' && (
|
||||
<Dialog open size="sm" title={t(`fees.delete${dialog.what === 'area' ? 'Area' : 'Rule'}`, { name: dialog.item.name })} onClose={() => setDialog(null)}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={() => setDialog(null)}>{t('fees.cancel')}</Button>
|
||||
<Button variant="danger" icon={<Trash2 size={16} />} data-testid="confirm-delete"
|
||||
onClick={() => act(() => client.delete(`/api/connect/fees/${dialog.what}s/${dialog.item.id}`), t('fees.deleted')).then(() => setDialog(null))}>
|
||||
{t('fees.delete')}
|
||||
</Button>
|
||||
</>}>
|
||||
<p className="text-body text-ink-2">{t('fees.deleteBody')}</p>
|
||||
</Dialog>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RuleRow({ rule, n, areaNames, first, last, onMove, onToggle, onEdit, onDelete }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { t: tc } = useTranslation('common')
|
||||
const { formatMoney } = useFormat()
|
||||
const d = describeRule(rule, areaNames)
|
||||
const params = p => ({ ...p, min: p.min, max: p.max, minMoney: p.min != null ? formatMoney(p.min) : '', maxMoney: p.max != null ? formatMoney(p.max) : '',
|
||||
days: (p.days ?? []).map(x => t(`fees.dayShort.${x}`)).join(', ') })
|
||||
return (
|
||||
<li className={`p-3 rounded-card border border-line bg-surface grid gap-1.5 ${rule.is_active ? '' : 'opacity-60'}`} data-testid="rule" data-rule={rule.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-caption font-semibold text-ink-3 w-5">{n}</span>
|
||||
<span className="flex-1 min-w-0 text-body font-semibold text-ink truncate">{rule.name}</span>
|
||||
<IconButton size="sm" variant="ghost" label={t('fees.up')} disabled={first} onClick={() => onMove(-1)}><ArrowUp size={16} /></IconButton>
|
||||
<IconButton size="sm" variant="ghost" label={t('fees.down')} disabled={last} onClick={() => onMove(1)}><ArrowDown size={16} /></IconButton>
|
||||
<Switch checked={rule.is_active} onChange={onToggle} aria-label={t('fees.active')} />
|
||||
<IconButton size="sm" variant="ghost" label={t('fees.edit')} onClick={onEdit}><Pencil size={16} /></IconButton>
|
||||
<IconButton size="sm" variant="ghost" label={t('fees.delete')} onClick={onDelete}><Trash2 size={16} /></IconButton>
|
||||
</div>
|
||||
<div className="pl-7 text-label text-ink-2 grid gap-0.5">
|
||||
<span>
|
||||
<span className="font-medium text-ink">{t('fees.when')}</span>{' '}
|
||||
{rule.sales_points.map(sp => tc(`salesPoints.${sp}.name`)).join(', ')}
|
||||
{d.when.map(([k, p]) => ` · ${t(`fees.cond.${k}`, params(p))}`).join('')}
|
||||
</span>
|
||||
<span>
|
||||
<span className="font-medium text-ink">{t('fees.then')}</span>{' '}
|
||||
{t(`fees.do.${d.action[0]}`, { value: d.action[0] === 'percent' ? d.action[1].value : formatMoney(d.action[1].value) })}
|
||||
{rule.stop ? ` · ${t('fees.stopShort')}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function AreaDialog({ area, onClose, onSave }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [name, setName] = useState(area?.name ?? '')
|
||||
const [codes, setCodes] = useState((area?.postcodes ?? []).join(', '))
|
||||
const [active, setActive] = useState(area?.is_active ?? true)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const save = async () => { setBusy(true); await onSave({ name: name.trim(), postcodes: parsePostcodes(codes), is_active: active }); setBusy(false) }
|
||||
return (
|
||||
<Dialog open size="sm" title={area ? t('fees.editArea') : t('fees.addArea')} onClose={busy ? undefined : onClose}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('fees.cancel')}</Button>
|
||||
<Button onClick={save} loading={busy} disabled={!name.trim()} data-testid="area-save">{t('fees.save')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-3">
|
||||
<Field label={t('fees.areaName')} hint={t('fees.areaNameHint')} required>
|
||||
<Input value={name} onChange={e => setName(e.target.value)} maxLength={80} autoFocus data-testid="area-name" />
|
||||
</Field>
|
||||
<Field label={t('fees.postcodes')} hint={t('fees.postcodesHint')}>
|
||||
<Input value={codes} onChange={e => setCodes(e.target.value)} data-testid="area-postcodes" />
|
||||
</Field>
|
||||
<Switch checked={active} onChange={setActive} label={t('fees.areaActive')} />
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function RuleDialog({ rule, areas, onClose, onSave }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { t: tc } = useTranslation('common')
|
||||
const [form, setForm] = useState(() => (rule ? ruleToForm(rule) : emptyRule()))
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [tried, setTried] = useState(false)
|
||||
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
|
||||
const toggle = (k, v) => setForm(f => ({ ...f, [k]: f[k].includes(v) ? f[k].filter(x => x !== v) : [...f[k], v] }))
|
||||
const problems = ruleProblems(form)
|
||||
const save = async () => {
|
||||
setTried(true)
|
||||
if (problems.length) return
|
||||
setBusy(true)
|
||||
await onSave(ruleBody(form))
|
||||
setBusy(false)
|
||||
}
|
||||
const showProblem = k => (tried && problems.includes(k) ? t(`fees.problem.${k}`) : undefined)
|
||||
return (
|
||||
<Dialog open size="lg" title={rule ? t('fees.editRule') : t('fees.addRule')} onClose={busy ? undefined : onClose}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('fees.cancel')}</Button>
|
||||
<Button onClick={save} loading={busy} data-testid="rule-save">{t('fees.save')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-4" data-testid="rule-dialog">
|
||||
<Field label={t('fees.ruleName')} hint={t('fees.ruleNameHint')} error={showProblem('name')} required>
|
||||
<Input value={form.name} onChange={e => set('name', e.target.value)} maxLength={80} autoFocus data-testid="rule-name" />
|
||||
</Field>
|
||||
|
||||
<fieldset className="grid gap-2">
|
||||
<legend className="text-label font-semibold text-ink mb-1">{t('fees.what')}</legend>
|
||||
<div className="grid gap-2 sm:grid-cols-[1fr_10rem]">
|
||||
<Select value={form.action} onChange={e => set('action', e.target.value)} aria-label={t('fees.what')} data-testid="rule-action">
|
||||
{ACTIONS.map(a => <option key={a} value={a}>{t(`fees.action.${a}`)}</option>)}
|
||||
</Select>
|
||||
{form.action !== 'free' && (
|
||||
<Input inputMode="decimal" value={form.value} onChange={e => set('value', e.target.value)} aria-label={t(`fees.valueLabel.${form.action}`)}
|
||||
placeholder={form.action === 'percent' ? '%' : '€'} data-testid="rule-value" />
|
||||
)}
|
||||
</div>
|
||||
<p className="text-caption text-ink-2">{t(`fees.actionHint.${form.action}`)}</p>
|
||||
{['value', 'negative', 'percent'].map(k => showProblem(k) && <p key={k} role="alert" className="text-label text-danger-ink">{showProblem(k)}</p>)}
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="grid gap-2">
|
||||
<legend className="text-label font-semibold text-ink mb-1">{t('fees.salesPoints')}</legend>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{SALES_POINTS.filter(sp => sp !== 'in_store').map(sp => (
|
||||
<button key={sp} type="button" className={chip(form.sales_points.includes(sp))} aria-pressed={form.sales_points.includes(sp)}
|
||||
onClick={() => toggle('sales_points', sp)} data-testid={`rule-sp-${sp}`}>{tc(`salesPoints.${sp}.name`)}</button>
|
||||
))}
|
||||
</div>
|
||||
{showProblem('salesPoints') && <p role="alert" className="text-label text-danger-ink">{showProblem('salesPoints')}</p>}
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="grid gap-3">
|
||||
<legend className="text-label font-semibold text-ink mb-1">{t('fees.conditions')}</legend>
|
||||
<p className="text-caption text-ink-2 -mt-1">{t('fees.conditionsHint')}</p>
|
||||
{areas.length > 0 && (
|
||||
<div className="grid gap-1.5">
|
||||
<span className="text-label text-ink-2">{t('fees.onlyAreas')}</span>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{areas.map(a => (
|
||||
<button key={a.id} type="button" className={chip(form.area_ids.includes(a.id))} aria-pressed={form.area_ids.includes(a.id)}
|
||||
onClick={() => toggle('area_ids', a.id)} data-testid={`rule-area-${a.id}`}>{a.name}</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label={t('fees.subtotalMin')} error={showProblem('subtotalRange')}>
|
||||
<Input inputMode="decimal" value={form.subtotal_min} onChange={e => set('subtotal_min', e.target.value)} placeholder="€" data-testid="rule-subtotal-min" />
|
||||
</Field>
|
||||
<Field label={t('fees.subtotalMax')}>
|
||||
<Input inputMode="decimal" value={form.subtotal_max} onChange={e => set('subtotal_max', e.target.value)} placeholder="€" />
|
||||
</Field>
|
||||
<Field label={t('fees.itemsMin')} error={showProblem('itemsRange')}>
|
||||
<Input inputMode="numeric" value={form.items_min} onChange={e => set('items_min', e.target.value)} data-testid="rule-items-min" />
|
||||
</Field>
|
||||
<Field label={t('fees.itemsMax')}>
|
||||
<Input inputMode="numeric" value={form.items_max} onChange={e => set('items_max', e.target.value)} />
|
||||
</Field>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<span className="text-label text-ink-2">{t('fees.onlyDays')}</span>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{DAYS.map(d => (
|
||||
<button key={d} type="button" className={chip(form.days.includes(d))} aria-pressed={form.days.includes(d)}
|
||||
onClick={() => toggle('days', d)}>{t(`fees.dayShort.${d}`)}</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label={t('fees.timeFrom')} error={showProblem('times')}>
|
||||
<Input type="time" value={form.time_from} onChange={e => set('time_from', e.target.value)} />
|
||||
</Field>
|
||||
<Field label={t('fees.timeTo')} hint={t('fees.timeHint')}>
|
||||
<Input type="time" value={form.time_to} onChange={e => set('time_to', e.target.value)} />
|
||||
</Field>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<Switch checked={form.stop} onChange={v => set('stop', v)} label={t('fees.stop')} description={t('fees.stopHint')} />
|
||||
<Switch checked={form.is_active} onChange={v => set('is_active', v)} label={t('fees.active')} />
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function TestOrder({ areas }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { t: tc } = useTranslation('common')
|
||||
const { formatMoney } = useFormat()
|
||||
// where / area_id stay null until picked: they follow the areas as they're added or removed
|
||||
const [picked, setForm] = useState({ sales_point: 'online_delivery', where: null, area_id: null,
|
||||
postcode: '', subtotal: '15', items: '2', day: 'now', time: '' })
|
||||
const form = {
|
||||
...picked,
|
||||
where: picked.where ?? (areas.length ? 'area' : 'postcode'),
|
||||
area_id: picked.area_id ?? (areas.some(a => a.id === Number(picked.area_id)) ? picked.area_id : (areas[0]?.id ?? '')),
|
||||
}
|
||||
const [result, setResult] = useState(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
|
||||
const run = async () => {
|
||||
setBusy(true)
|
||||
try { setResult((await client.post('/api/connect/fees/preview', previewBody(form))).data) } catch (err) { toast.error(errorMessage(err, t)) }
|
||||
setBusy(false)
|
||||
}
|
||||
return (
|
||||
<section className="p-4 rounded-card border border-line bg-surface-2 grid gap-3" aria-labelledby="fee-test" data-testid="fee-test">
|
||||
<h2 id="fee-test" className="text-title font-semibold text-ink">{t('fees.test')}</h2>
|
||||
<Field label={t('fees.testSalesPoint')}>
|
||||
<Select value={form.sales_point} onChange={e => set('sales_point', e.target.value)}>
|
||||
{SALES_POINTS.filter(sp => sp !== 'in_store').map(sp => <option key={sp} value={sp}>{tc(`salesPoints.${sp}.name`)}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
{form.sales_point === 'online_delivery' && (
|
||||
<div className="grid gap-2">
|
||||
<Select value={form.where} onChange={e => set('where', e.target.value)} aria-label={t('fees.testWhere')}>
|
||||
<option value="area">{t('fees.testByArea')}</option>
|
||||
<option value="postcode">{t('fees.testByPostcode')}</option>
|
||||
</Select>
|
||||
{form.where === 'area' ? (
|
||||
<Select value={form.area_id} onChange={e => set('area_id', e.target.value)} aria-label={t('fees.areas')} data-testid="test-area">
|
||||
<option value="">{t('fees.testNoArea')}</option>
|
||||
{areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
|
||||
</Select>
|
||||
) : (
|
||||
<Input value={form.postcode} onChange={e => set('postcode', e.target.value)} placeholder={t('fees.postcode')} aria-label={t('fees.postcode')} data-testid="test-postcode" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Field label={t('fees.testSubtotal')}>
|
||||
<Input inputMode="decimal" value={form.subtotal} onChange={e => set('subtotal', e.target.value)} data-testid="test-subtotal" />
|
||||
</Field>
|
||||
<Field label={t('fees.testItems')}>
|
||||
<Input inputMode="numeric" value={form.items} onChange={e => set('items', e.target.value)} data-testid="test-items" />
|
||||
</Field>
|
||||
<Field label={t('fees.testDay')}>
|
||||
<Select value={form.day} onChange={e => set('day', e.target.value)}>
|
||||
<option value="now">{t('fees.now')}</option>
|
||||
{DAYS.map(d => <option key={d} value={String(d)}>{t(`fees.dayLong.${d}`)}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
{form.day !== 'now' && (
|
||||
<Field label={t('fees.testTime')}>
|
||||
<Input type="time" value={form.time} onChange={e => set('time', e.target.value)} />
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
<Button onClick={run} loading={busy} data-testid="test-run">{t('fees.testRun')}</Button>
|
||||
{result && (
|
||||
<div className="p-3 rounded-control bg-surface border border-line grid gap-1" role="status" data-testid="test-result"
|
||||
data-fee={result.fee} data-refused={result.refused ?? ''}>
|
||||
{result.refused ? (
|
||||
<p className="text-body font-semibold text-danger-ink">
|
||||
{t(`fees.refused.${result.refused}`, { minimum: result.minimum != null ? formatMoney(result.minimum) : '' })}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-body text-ink">{t('fees.testFee')} <span className="font-semibold">{formatMoney(result.fee)}</span></p>
|
||||
<p className="text-label text-ink-2">{t('fees.testTotal', { total: formatMoney(result.total) })}</p>
|
||||
</>
|
||||
)}
|
||||
{result.area_name && <p className="text-caption text-ink-2">{t('fees.testArea', { name: result.area_name })}</p>}
|
||||
<p className="text-caption text-ink-2">
|
||||
{result.applied.length ? t('fees.testApplied', { names: result.applied.map(a => a.name).join(' → ') }) : t('fees.testNone')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Delivery areas and fee rules, the manager's side (plan phase 3S, step S.3). The rules are
|
||||
// evaluated by the backend's engine (local_backend/services/fees.py, the same file the cloud
|
||||
// runs); this file only turns forms into request bodies and rules into readable lines.
|
||||
// Pure: unit-tested in Node (tests/fees.test.mjs).
|
||||
|
||||
export const ACTIONS = ['set', 'add', 'percent', 'free', 'minimum']
|
||||
export const DAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0
|
||||
|
||||
const num = v => (v === '' || v == null ? null : Number(String(v).replace(',', '.')))
|
||||
|
||||
/** Postcodes typed with commas, semicolons or new lines → a tidy list without duplicates. */
|
||||
export function parsePostcodes(text) {
|
||||
const out = []
|
||||
for (const raw of String(text ?? '').split(/[,;\n]/)) {
|
||||
const code = raw.trim().replace(/\s+/g, ' ')
|
||||
if (code && !out.includes(code)) out.push(code)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** An empty rule form (a delivery fee by default). */
|
||||
export function emptyRule() {
|
||||
return {
|
||||
name: '', is_active: true, sales_points: ['online_delivery'], area_ids: [],
|
||||
subtotal_min: '', subtotal_max: '', items_min: '', items_max: '', days: [],
|
||||
time_from: '', time_to: '', action: 'set', value: '', stop: false,
|
||||
}
|
||||
}
|
||||
|
||||
/** A saved rule → the form (numbers as text, nulls as empty). */
|
||||
export function ruleToForm(rule) {
|
||||
const f = emptyRule()
|
||||
for (const k of Object.keys(f)) {
|
||||
const v = rule[k]
|
||||
f[k] = v == null ? f[k] : (typeof f[k] === 'string' && typeof v === 'number' ? String(v) : v)
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
/** The form → the request body (POST/PUT /api/connect/fees/rules). */
|
||||
export function ruleBody(form) {
|
||||
const int = v => (num(v) == null ? null : Math.round(num(v)))
|
||||
return {
|
||||
name: form.name.trim(), is_active: !!form.is_active, sales_points: form.sales_points, area_ids: form.area_ids,
|
||||
subtotal_min: num(form.subtotal_min), subtotal_max: num(form.subtotal_max),
|
||||
items_min: int(form.items_min), items_max: int(form.items_max), days: [...form.days].sort((a, b) => a - b),
|
||||
time_from: form.time_from || null, time_to: form.time_to || null,
|
||||
action: form.action, value: form.action === 'free' ? 0 : (num(form.value) ?? 0), stop: !!form.stop,
|
||||
}
|
||||
}
|
||||
|
||||
/** What the form still needs before it can be saved: a list of message keys (empty = ok). */
|
||||
export function ruleProblems(form) {
|
||||
const out = []
|
||||
if (!form.name.trim()) out.push('name')
|
||||
const v = num(form.value)
|
||||
if (form.action !== 'free' && (v == null || Number.isNaN(v))) out.push('value')
|
||||
if (form.action !== 'add' && v != null && v < 0) out.push('negative')
|
||||
if (form.action === 'percent' && v > 100) out.push('percent')
|
||||
const lo = num(form.subtotal_min); const hi = num(form.subtotal_max)
|
||||
if (lo != null && hi != null && lo >= hi) out.push('subtotalRange')
|
||||
const il = num(form.items_min); const ih = num(form.items_max)
|
||||
if (il != null && ih != null && il > ih) out.push('itemsRange')
|
||||
if (!!form.time_from !== !!form.time_to) out.push('times')
|
||||
if (!form.sales_points.length) out.push('salesPoints')
|
||||
return out
|
||||
}
|
||||
|
||||
/** One rule as readable parts: { when: [[key, params]], action: [key, params] }, for t(). */
|
||||
export function describeRule(rule, areaNames = {}) {
|
||||
const when = []
|
||||
if (rule.area_ids?.length) when.push(['areas', { names: rule.area_ids.map(id => areaNames[id] ?? `#${id}`).join(', ') }])
|
||||
if (rule.subtotal_min != null && rule.subtotal_max != null) when.push(['subtotalBetween', { min: rule.subtotal_min, max: rule.subtotal_max }])
|
||||
else if (rule.subtotal_min != null) when.push(['subtotalFrom', { min: rule.subtotal_min }])
|
||||
else if (rule.subtotal_max != null) when.push(['subtotalBelow', { max: rule.subtotal_max }])
|
||||
if (rule.items_min != null && rule.items_max != null) when.push(['itemsBetween', { min: rule.items_min, max: rule.items_max }])
|
||||
else if (rule.items_min != null) when.push(['itemsFrom', { min: rule.items_min }])
|
||||
else if (rule.items_max != null) when.push(['itemsUpTo', { max: rule.items_max }])
|
||||
if (rule.days?.length && rule.days.length < 7) when.push(['days', { days: rule.days }])
|
||||
if (rule.time_from && rule.time_to) when.push(['time', { from: rule.time_from, to: rule.time_to }])
|
||||
return { when, action: [rule.action, { value: rule.value }] }
|
||||
}
|
||||
|
||||
/** The rules in a new order after moving one up (-1) or down (+1): their ids. */
|
||||
export function moveRule(rules, id, step) {
|
||||
const ids = rules.map(r => r.id)
|
||||
const i = ids.indexOf(id)
|
||||
const j = i + step
|
||||
if (i < 0 || j < 0 || j >= ids.length) return ids
|
||||
;[ids[i], ids[j]] = [ids[j], ids[i]]
|
||||
return ids
|
||||
}
|
||||
|
||||
/** "Test an order" form → the preview body. */
|
||||
export function previewBody(form) {
|
||||
return {
|
||||
sales_point: form.sales_point,
|
||||
area_id: form.where === 'area' && form.area_id !== '' ? Number(form.area_id) : null,
|
||||
postcode: form.where === 'postcode' ? form.postcode.trim() || null : null,
|
||||
subtotal: num(form.subtotal) ?? 0, items: Math.max(0, Math.round(num(form.items) ?? 0)),
|
||||
weekday: form.day === 'now' ? null : Number(form.day),
|
||||
time: form.day === 'now' ? null : (form.time || null),
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
BookUser, Users, Receipt, CreditCard,
|
||||
Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes,
|
||||
BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText,
|
||||
AppWindow, Settings, CookingPot, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck,
|
||||
AppWindow, Settings, CookingPot, Truck, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck,
|
||||
} from 'lucide-react'
|
||||
|
||||
const DASH = 'core.dashboard.access'
|
||||
@@ -28,6 +28,7 @@ export const NAV = [
|
||||
{ to: '/dashboard', icon: LayoutDashboard, label: 'nav.dashboard', module: 'core', perm: DASH },
|
||||
{ to: '/tables', icon: LayoutGrid, label: 'nav.tables', module: 'ordering', perm: DASH },
|
||||
{ to: '/online-orders', icon: ShoppingBag, label: 'nav.onlineOrders', module: 'connect_orders', perm: DASH, badge: 'onlineOrders' },
|
||||
{ to: '/online/fees', icon: Truck, label: 'nav.deliveryFees', module: 'connect_orders', perm: 'connect_orders.fees' },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// Delivery areas and fee rules, the manager's forms (plan phase 3S, step S.3).
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { describeRule, emptyRule, moveRule, parsePostcodes, previewBody, ruleBody, ruleProblems, ruleToForm } from '../src/pages/online/feesLogic.js'
|
||||
|
||||
test('postcodes typed freely become a tidy list', () => {
|
||||
assert.deepEqual(parsePostcodes('241 00, 24131;24131\n 241 31 '), ['241 00', '24131', '241 31'])
|
||||
assert.deepEqual(parsePostcodes(''), [])
|
||||
})
|
||||
|
||||
test('a rule form round-trips and becomes the request body', () => {
|
||||
const form = { ...emptyRule(), name: ' Far ', area_ids: [2], subtotal_min: '15,5', items_max: '9', days: [6, 5], time_from: '22:00', time_to: '02:00', value: '1,5', action: 'add' }
|
||||
assert.deepEqual(ruleBody(form), {
|
||||
name: 'Far', is_active: true, sales_points: ['online_delivery'], area_ids: [2], subtotal_min: 15.5, subtotal_max: null,
|
||||
items_min: null, items_max: 9, days: [5, 6], time_from: '22:00', time_to: '02:00', action: 'add', value: 1.5, stop: false,
|
||||
})
|
||||
const saved = { id: 7, ...ruleBody(form) }
|
||||
assert.equal(ruleToForm(saved).subtotal_min, '15.5')
|
||||
assert.equal(ruleToForm(saved).subtotal_max, '')
|
||||
assert.equal(ruleBody({ ...emptyRule(), name: 'Free', action: 'free', value: '' }).value, 0)
|
||||
})
|
||||
|
||||
test('what a rule form still needs', () => {
|
||||
assert.deepEqual(ruleProblems(emptyRule()), ['name', 'value'])
|
||||
const ok = { ...emptyRule(), name: 'Base', value: '2' }
|
||||
assert.deepEqual(ruleProblems(ok), [])
|
||||
assert.deepEqual(ruleProblems({ ...ok, value: '-1' }), ['negative'])
|
||||
assert.deepEqual(ruleProblems({ ...ok, action: 'add', value: '-1' }), [])
|
||||
assert.deepEqual(ruleProblems({ ...ok, action: 'percent', value: '120' }), ['percent'])
|
||||
assert.deepEqual(ruleProblems({ ...ok, subtotal_min: '20', subtotal_max: '10', items_min: '5', items_max: '2', time_from: '22:00' }),
|
||||
['subtotalRange', 'itemsRange', 'times'])
|
||||
assert.deepEqual(ruleProblems({ ...ok, sales_points: [] }), ['salesPoints'])
|
||||
})
|
||||
|
||||
test('a rule in words', () => {
|
||||
const d = describeRule({ area_ids: [2], subtotal_min: 25, subtotal_max: null, items_min: 10, items_max: null, days: [5, 6], time_from: '22:00', time_to: '02:00', action: 'free', value: 0 }, { 2: 'Kalamata' })
|
||||
assert.deepEqual(d.when.map(w => w[0]), ['areas', 'subtotalFrom', 'itemsFrom', 'days', 'time'])
|
||||
assert.equal(d.when[0][1].names, 'Kalamata')
|
||||
assert.deepEqual(d.action, ['free', { value: 0 }])
|
||||
assert.deepEqual(describeRule({ days: [0, 1, 2, 3, 4, 5, 6], action: 'set', value: 2 }).when, [])
|
||||
})
|
||||
|
||||
test('moving rules and the test form', () => {
|
||||
const rules = [{ id: 1 }, { id: 2 }, { id: 3 }]
|
||||
assert.deepEqual(moveRule(rules, 2, -1), [2, 1, 3])
|
||||
assert.deepEqual(moveRule(rules, 3, 1), [1, 2, 3])
|
||||
assert.deepEqual(previewBody({ sales_point: 'online_delivery', where: 'postcode', area_id: '1', postcode: ' 24131 ', subtotal: '12,5', items: '3', day: 'now', time: '' }),
|
||||
{ sales_point: 'online_delivery', area_id: null, postcode: '24131', subtotal: 12.5, items: 3, weekday: null, time: null })
|
||||
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' })
|
||||
})
|
||||
@@ -97,5 +97,11 @@
|
||||
"invalid": "Αυτή η επιστροφή δεν βγαίνει ({{reason}}).",
|
||||
"too_old": "Στο ταμείο επιστρέφονται μόνο πληρωμές της σημερινής εργάσιμης ημέρας.",
|
||||
"items_changed": "Κάποια από αυτά τα είδη επιστράφηκαν στο μεταξύ. Ελέγξτε την παραγγελία και δοκιμάστε ξανά."
|
||||
},
|
||||
"fees": {
|
||||
"area_not_found": "Η περιοχή διανομής {{area_id}} δεν βρέθηκε.",
|
||||
"rule_not_found": "Ο κανόνας χρέωσης {{rule_id}} δεν βρέθηκε.",
|
||||
"area_in_use": "Αυτή η περιοχή χρησιμοποιείται από κανόνες χρέωσης: {{rules}}. Αλλάξτε πρώτα αυτούς τους κανόνες.",
|
||||
"order_invalid": "Η νέα σειρά πρέπει να περιέχει κάθε κανόνα μία φορά."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"license": "Άδεια",
|
||||
"devices": "Συσκευές",
|
||||
"sessions": "Συνδεδεμένοι τώρα",
|
||||
"approvals": "Εγκρίσεις υπευθύνου"
|
||||
"approvals": "Εγκρίσεις υπευθύνου",
|
||||
"deliveryFees": "Χρεώσεις διανομής"
|
||||
},
|
||||
"profile": {
|
||||
"edit": "Επεξεργασία προφίλ",
|
||||
@@ -369,5 +370,144 @@
|
||||
"language": "Γλώσσα προσωπικού",
|
||||
"timezone": "Ζώνη ώρας",
|
||||
"languageHint": "Η γλώσσα των οθονών του προσωπικού (ο καθένας μπορεί να διαλέξει τη δική του) και των εκτυπωμένων δελτίων και αναφορών."
|
||||
},
|
||||
"fees": {
|
||||
"title": "Περιοχές και χρεώσεις διανομής",
|
||||
"intro": "Χρεώσεις για online παραγγελίες, από πάνω προς τα κάτω: κάθε κανόνας του οποίου οι συνθήκες ισχύουν αλλάζει τη χρέωση ή απορρίπτει την παραγγελία κάτω από ένα ελάχιστο. Ο πελάτης βλέπει τη χρέωση πριν παραγγείλει, και το online ταμείο χρεώνει ακριβώς ό,τι δείχνει η «Δοκιμή παραγγελίας». Χωρίς κανόνες δεν υπάρχει χρέωση.",
|
||||
"rules": "Κανόνες χρέωσης",
|
||||
"addRule": "Νέος κανόνας",
|
||||
"editRule": "Επεξεργασία κανόνα",
|
||||
"noRules": "Κανένας κανόνας χρέωσης",
|
||||
"noRulesBody": "Οι online παραγγελίες δεν χρεώνονται. Προσθέστε κανόνα για χρέωση διανομής, ελάχιστη παραγγελία ή δωρεάν διανομή πάνω από ένα ποσό.",
|
||||
"areas": "Περιοχές διανομής",
|
||||
"addArea": "Νέα περιοχή",
|
||||
"editArea": "Επεξεργασία περιοχής",
|
||||
"noAreas": "Καμία περιοχή: γίνονται δεκτές διανομές σε κάθε διεύθυνση. Προσθέστε περιοχές για διανομή μόνο εκεί και χρέωση ανά περιοχή.",
|
||||
"byNameOnly": "Επιλογή με το όνομα (χωρίς Τ.Κ.)",
|
||||
"areaName": "Όνομα",
|
||||
"areaNameHint": "Αυτό που επιλέγουν οι πελάτες, π.χ. χωριό ή γειτονιά",
|
||||
"postcodes": "Ταχυδρομικοί κώδικες",
|
||||
"postcodesHint": "Προαιρετικά, χωρισμένοι με κόμμα. Πελάτης που γράφει έναν από αυτούς ανήκει σε αυτή την περιοχή.",
|
||||
"postcode": "Τ.Κ.",
|
||||
"areaActive": "Κάνουμε διανομή εδώ",
|
||||
"edit": "Επεξεργασία",
|
||||
"delete": "Διαγραφή",
|
||||
"up": "Πάνω",
|
||||
"down": "Κάτω",
|
||||
"active": "Ενεργός",
|
||||
"save": "Αποθήκευση",
|
||||
"cancel": "Ακύρωση",
|
||||
"saved": "Αποθηκεύτηκε",
|
||||
"deleted": "Διαγράφηκε",
|
||||
"deleteArea": "Διαγραφή της περιοχής «{{name}}»;",
|
||||
"deleteRule": "Διαγραφή του κανόνα «{{name}}»;",
|
||||
"deleteBody": "Οι online παραγγελίες χρησιμοποιούν τους κανόνες όπως θα είναι μετά, μέσα σε λίγα δευτερόλεπτα.",
|
||||
"when": "Όταν:",
|
||||
"then": "Τότε:",
|
||||
"stopShort": "σταματά εδώ",
|
||||
"cond": {
|
||||
"areas": "περιοχή {{names}}",
|
||||
"subtotalBetween": "προϊόντα {{minMoney}} έως κάτω από {{maxMoney}}",
|
||||
"subtotalFrom": "προϊόντα {{minMoney}} και πάνω",
|
||||
"subtotalBelow": "προϊόντα κάτω από {{maxMoney}}",
|
||||
"itemsBetween": "{{min}} έως {{max}} τεμάχια",
|
||||
"itemsFrom": "{{min}} τεμάχια και πάνω",
|
||||
"itemsUpTo": "έως {{max}} τεμάχια",
|
||||
"days": "{{days}}",
|
||||
"time": "{{from}}–{{to}}"
|
||||
},
|
||||
"do": {
|
||||
"set": "η χρέωση είναι {{value}}",
|
||||
"add": "πρόσθεσε {{value}} στη χρέωση",
|
||||
"percent": "πρόσθεσε {{value}} % των προϊόντων",
|
||||
"free": "χωρίς χρέωση",
|
||||
"minimum": "απόρριψη κάτω από {{value}}"
|
||||
},
|
||||
"ruleName": "Όνομα",
|
||||
"ruleNameHint": "Για εσάς, π.χ. «Διανομή», «Δωρεάν πάνω από 25 €»",
|
||||
"what": "Τι κάνει",
|
||||
"action": {
|
||||
"set": "Η χρέωση γίνεται",
|
||||
"add": "Πρόσθεσε στη χρέωση",
|
||||
"percent": "Πρόσθεσε % των προϊόντων",
|
||||
"free": "Χωρίς χρέωση (δωρεάν διανομή)",
|
||||
"minimum": "Ελάχιστη παραγγελία"
|
||||
},
|
||||
"valueLabel": {
|
||||
"set": "Χρέωση σε ευρώ",
|
||||
"add": "Ποσό σε ευρώ",
|
||||
"percent": "Ποσοστό",
|
||||
"minimum": "Ελάχιστο σε ευρώ"
|
||||
},
|
||||
"actionHint": {
|
||||
"set": "Αντικαθιστά τη χρέωση ως εκεί. Για τη βασική χρέωση διανομής.",
|
||||
"add": "Προστίθεται στη χρέωση ως εκεί (αρνητικό ποσό τη μειώνει), π.χ. επιβάρυνση για μακρινή περιοχή ή μεγάλη παραγγελία.",
|
||||
"percent": "Ποσοστό του συνόλου των προϊόντων, που προστίθεται στη χρέωση.",
|
||||
"free": "Η χρέωση γίνεται 0. Συνήθως με «Σταματά εδώ», π.χ. δωρεάν διανομή πάνω από ένα ποσό.",
|
||||
"minimum": "Παραγγελίες με προϊόντα κάτω από το ποσό απορρίπτονται· ο πελάτης βλέπει το ελάχιστο."
|
||||
},
|
||||
"salesPoints": "Για",
|
||||
"conditions": "Μόνο όταν (όσα συμπληρώσετε)",
|
||||
"conditionsHint": "Αφήστε κενό για πάντα.",
|
||||
"onlyAreas": "Περιοχές διανομής",
|
||||
"subtotalMin": "Προϊόντα από (€)",
|
||||
"subtotalMax": "Προϊόντα κάτω από (€)",
|
||||
"itemsMin": "Τεμάχια από",
|
||||
"itemsMax": "Τεμάχια έως",
|
||||
"onlyDays": "Ημέρες",
|
||||
"timeFrom": "Από",
|
||||
"timeTo": "Έως",
|
||||
"timeHint": "Λήξη πριν την έναρξη περνά τα μεσάνυχτα (π.χ. 22:00–02:00).",
|
||||
"stop": "Σταματά εδώ",
|
||||
"stopHint": "Όταν ισχύει αυτός ο κανόνας, οι κανόνες από κάτω δεν εξετάζονται.",
|
||||
"problem": {
|
||||
"name": "Δώστε όνομα στον κανόνα.",
|
||||
"value": "Συμπληρώστε ποσό.",
|
||||
"negative": "Αρνητικό ποσό μόνο στο «Πρόσθεσε στη χρέωση».",
|
||||
"percent": "Το ποσοστό είναι έως 100.",
|
||||
"subtotalRange": "Το κάτω ποσό πρέπει να είναι μικρότερο από το πάνω.",
|
||||
"itemsRange": "Το κάτω πλήθος δεν μπορεί να είναι μεγαλύτερο από το πάνω.",
|
||||
"times": "Δώστε και τις δύο ώρες ή καμία.",
|
||||
"salesPoints": "Επιλέξτε τουλάχιστον ένα."
|
||||
},
|
||||
"dayShort": {
|
||||
"0": "Δευ",
|
||||
"1": "Τρί",
|
||||
"2": "Τετ",
|
||||
"3": "Πέμ",
|
||||
"4": "Παρ",
|
||||
"5": "Σάβ",
|
||||
"6": "Κυρ"
|
||||
},
|
||||
"dayLong": {
|
||||
"0": "Δευτέρα",
|
||||
"1": "Τρίτη",
|
||||
"2": "Τετάρτη",
|
||||
"3": "Πέμπτη",
|
||||
"4": "Παρασκευή",
|
||||
"5": "Σάββατο",
|
||||
"6": "Κυριακή"
|
||||
},
|
||||
"test": "Δοκιμή παραγγελίας",
|
||||
"testSalesPoint": "Παραγγελία ως",
|
||||
"testWhere": "Πού",
|
||||
"testByArea": "Επιλογή περιοχής",
|
||||
"testByPostcode": "Πληκτρολόγηση Τ.Κ.",
|
||||
"testNoArea": "Χωρίς περιοχή",
|
||||
"testSubtotal": "Προϊόντα (€)",
|
||||
"testItems": "Τεμάχια",
|
||||
"testDay": "Ημέρα",
|
||||
"testTime": "Ώρα",
|
||||
"now": "Τώρα",
|
||||
"testRun": "Υπολογισμός χρέωσης",
|
||||
"testFee": "Χρέωση:",
|
||||
"testTotal": "Σύνολο με τα προϊόντα: {{total}}",
|
||||
"testArea": "Περιοχή: {{name}}",
|
||||
"testApplied": "Κανόνες που εφαρμόστηκαν: {{names}}",
|
||||
"testNone": "Δεν εφαρμόστηκε κανένας κανόνας.",
|
||||
"refused": {
|
||||
"minimum_not_met": "Απορρίπτεται: η ελάχιστη παραγγελία είναι {{minimum}}.",
|
||||
"area_not_served": "Απορρίπτεται: δεν γίνεται διανομή σε αυτή τη διεύθυνση."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@
|
||||
"name": "Online παραγγελίες",
|
||||
"description": "Παραγγελίες από το QR μενού, που έρχονται από το cloud.",
|
||||
"permissions": {
|
||||
"manage": "Αποδοχή και διαχείριση online παραγγελιών"
|
||||
"manage": "Αποδοχή και διαχείριση online παραγγελιών",
|
||||
"fees": "Ρύθμιση περιοχών και χρεώσεων διανομής"
|
||||
}
|
||||
},
|
||||
"connect_remote": {
|
||||
|
||||
@@ -97,5 +97,11 @@
|
||||
"invalid": "This refund doesn't add up ({{reason}}).",
|
||||
"too_old": "Only payments from today's business day can be refunded at the counter.",
|
||||
"items_changed": "Some of these items were refunded in the meantime. Check the order and try again."
|
||||
},
|
||||
"fees": {
|
||||
"area_not_found": "Delivery area {{area_id}} not found.",
|
||||
"rule_not_found": "Fee rule {{rule_id}} not found.",
|
||||
"area_in_use": "This area is used by fee rules: {{rules}}. Change those rules first.",
|
||||
"order_invalid": "The new order must list every rule once."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"license": "License",
|
||||
"devices": "Devices",
|
||||
"sessions": "Signed in now",
|
||||
"approvals": "Manager approvals"
|
||||
"approvals": "Manager approvals",
|
||||
"deliveryFees": "Delivery fees"
|
||||
},
|
||||
"profile": {
|
||||
"edit": "Edit profile",
|
||||
@@ -369,5 +370,144 @@
|
||||
"language": "Staff language",
|
||||
"timezone": "Time zone",
|
||||
"languageHint": "The language of staff screens (each person can choose their own) and of printed tickets and reports."
|
||||
},
|
||||
"fees": {
|
||||
"title": "Delivery areas and fees",
|
||||
"intro": "Fees for online orders, looked at from the top: every rule whose conditions hold changes the fee, or refuses the order below a minimum. The customer sees the fee before ordering, and the online checkout charges exactly what \"Test an order\" shows. Without rules there is no fee.",
|
||||
"rules": "Fee rules",
|
||||
"addRule": "Add a rule",
|
||||
"editRule": "Edit rule",
|
||||
"noRules": "No fee rules",
|
||||
"noRulesBody": "Online orders are charged no fee. Add a rule for a delivery fee, a minimum order or free delivery above an amount.",
|
||||
"areas": "Delivery areas",
|
||||
"addArea": "Add an area",
|
||||
"editArea": "Edit area",
|
||||
"noAreas": "No areas: deliveries are accepted to any address. Add areas to deliver only there and to charge by area.",
|
||||
"byNameOnly": "Picked by name (no postcodes)",
|
||||
"areaName": "Name",
|
||||
"areaNameHint": "What customers pick, e.g. a village or a neighbourhood",
|
||||
"postcodes": "Postcodes",
|
||||
"postcodesHint": "Optional, separated by commas. A customer who types one of these is in this area.",
|
||||
"postcode": "Postcode",
|
||||
"areaActive": "We deliver here",
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"up": "Move up",
|
||||
"down": "Move down",
|
||||
"active": "On",
|
||||
"save": "Save",
|
||||
"cancel": "Cancel",
|
||||
"saved": "Saved",
|
||||
"deleted": "Deleted",
|
||||
"deleteArea": "Delete the area \"{{name}}\"?",
|
||||
"deleteRule": "Delete the rule \"{{name}}\"?",
|
||||
"deleteBody": "Online orders use the rules as they are after this, within a few seconds.",
|
||||
"when": "When:",
|
||||
"then": "Then:",
|
||||
"stopShort": "stop here",
|
||||
"cond": {
|
||||
"areas": "area {{names}}",
|
||||
"subtotalBetween": "products {{minMoney}} to under {{maxMoney}}",
|
||||
"subtotalFrom": "products {{minMoney}} or more",
|
||||
"subtotalBelow": "products under {{maxMoney}}",
|
||||
"itemsBetween": "{{min}} to {{max}} items",
|
||||
"itemsFrom": "{{min}} items or more",
|
||||
"itemsUpTo": "up to {{max}} items",
|
||||
"days": "{{days}}",
|
||||
"time": "{{from}}–{{to}}"
|
||||
},
|
||||
"do": {
|
||||
"set": "the fee is {{value}}",
|
||||
"add": "add {{value}} to the fee",
|
||||
"percent": "add {{value}} % of the products",
|
||||
"free": "no fee",
|
||||
"minimum": "refuse orders under {{value}}"
|
||||
},
|
||||
"ruleName": "Name",
|
||||
"ruleNameHint": "For you, e.g. \"Delivery\", \"Free over €25\"",
|
||||
"what": "What it does",
|
||||
"action": {
|
||||
"set": "Set the fee to",
|
||||
"add": "Add to the fee",
|
||||
"percent": "Add a % of the products",
|
||||
"free": "No fee (free delivery)",
|
||||
"minimum": "Minimum order"
|
||||
},
|
||||
"valueLabel": {
|
||||
"set": "Fee in euros",
|
||||
"add": "Amount in euros",
|
||||
"percent": "Percent",
|
||||
"minimum": "Minimum in euros"
|
||||
},
|
||||
"actionHint": {
|
||||
"set": "Replaces the fee so far. Use it for the base delivery fee.",
|
||||
"add": "Added to the fee so far (a negative amount lowers it), e.g. a surcharge for a far area or a big order.",
|
||||
"percent": "A percentage of the products' total, added to the fee.",
|
||||
"free": "The fee becomes 0. Usually with \"stop here\", e.g. free delivery over an amount.",
|
||||
"minimum": "Orders whose products cost less are refused; the customer is told the minimum."
|
||||
},
|
||||
"salesPoints": "For",
|
||||
"conditions": "Only when (all that you fill in)",
|
||||
"conditionsHint": "Leave empty for always.",
|
||||
"onlyAreas": "Delivery areas",
|
||||
"subtotalMin": "Products from (€)",
|
||||
"subtotalMax": "Products under (€)",
|
||||
"itemsMin": "Items from",
|
||||
"itemsMax": "Items up to",
|
||||
"onlyDays": "Days",
|
||||
"timeFrom": "From",
|
||||
"timeTo": "Until",
|
||||
"timeHint": "An end before the start runs past midnight (e.g. 22:00–02:00).",
|
||||
"stop": "Stop here",
|
||||
"stopHint": "When this rule applies, the rules below it are not looked at.",
|
||||
"problem": {
|
||||
"name": "Give the rule a name.",
|
||||
"value": "Enter an amount.",
|
||||
"negative": "Only \"Add to the fee\" takes a negative amount.",
|
||||
"percent": "A percentage is at most 100.",
|
||||
"subtotalRange": "The lower amount must be below the upper one.",
|
||||
"itemsRange": "The lower count must not be above the upper one.",
|
||||
"times": "Give both times, or neither.",
|
||||
"salesPoints": "Pick at least one."
|
||||
},
|
||||
"dayShort": {
|
||||
"0": "Mon",
|
||||
"1": "Tue",
|
||||
"2": "Wed",
|
||||
"3": "Thu",
|
||||
"4": "Fri",
|
||||
"5": "Sat",
|
||||
"6": "Sun"
|
||||
},
|
||||
"dayLong": {
|
||||
"0": "Monday",
|
||||
"1": "Tuesday",
|
||||
"2": "Wednesday",
|
||||
"3": "Thursday",
|
||||
"4": "Friday",
|
||||
"5": "Saturday",
|
||||
"6": "Sunday"
|
||||
},
|
||||
"test": "Test an order",
|
||||
"testSalesPoint": "Ordered as",
|
||||
"testWhere": "Where",
|
||||
"testByArea": "Pick an area",
|
||||
"testByPostcode": "Type a postcode",
|
||||
"testNoArea": "No area",
|
||||
"testSubtotal": "Products (€)",
|
||||
"testItems": "Items",
|
||||
"testDay": "Day",
|
||||
"testTime": "Time",
|
||||
"now": "Now",
|
||||
"testRun": "Work out the fee",
|
||||
"testFee": "Fee:",
|
||||
"testTotal": "Total with products: {{total}}",
|
||||
"testArea": "Area: {{name}}",
|
||||
"testApplied": "Rules applied: {{names}}",
|
||||
"testNone": "No rule applied.",
|
||||
"refused": {
|
||||
"minimum_not_met": "Refused: the minimum order is {{minimum}}.",
|
||||
"area_not_served": "Refused: no delivery to this address."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@
|
||||
"name": "Online orders",
|
||||
"description": "Orders placed from the QR menu, brought in from the cloud.",
|
||||
"permissions": {
|
||||
"manage": "Accept and manage online orders"
|
||||
"manage": "Accept and manage online orders",
|
||||
"fees": "Set delivery areas and fees"
|
||||
}
|
||||
},
|
||||
"connect_remote": {
|
||||
|
||||
@@ -513,6 +513,57 @@ try {
|
||||
r.check('online orders: loads its lists and never asks for the old /api/stream',
|
||||
ooUrls.some(u => u.startsWith('/api/connect/orders')) && !ooUrls.some(u => u.startsWith('/api/stream')), [...new Set(ooUrls)].filter(u => u.startsWith('/api/')).join(' '))
|
||||
|
||||
// ── phase 3S S.3: delivery areas and fees, set up and tested on the real page ──
|
||||
await page.goto(`${APP}/online/fees`)
|
||||
r.check('fees: the page opens from the nav entry, no rules yet', await page.getByTestId('fees-page').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)
|
||||
&& await page.locator('a[href="/online/fees"]').count() >= 1 && await page.getByTestId('rule').count() === 0)
|
||||
await page.getByTestId('area-add').click()
|
||||
await page.getByTestId('area-name').fill('Centre')
|
||||
await page.getByTestId('area-postcodes').fill('24100, 241 31')
|
||||
await page.getByTestId('area-save').click()
|
||||
r.check('fees: an area with postcodes', await page.getByTestId('area').filter({ hasText: 'Centre' }).waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
|
||||
&& (await page.getByTestId('area').first().textContent()).includes('241 31'))
|
||||
const addRule = async (name, fill) => {
|
||||
await page.getByTestId('rule-add').click()
|
||||
await page.getByTestId('rule-name').fill(name)
|
||||
await fill()
|
||||
await page.getByTestId('rule-save').click()
|
||||
await page.getByTestId('rule').filter({ hasText: name }).waitFor({ timeout: 5000 }).catch(() => {})
|
||||
}
|
||||
await addRule('Base', () => page.getByTestId('rule-value').fill('2'))
|
||||
await addRule('Free over 25', async () => {
|
||||
await page.getByTestId('rule-action').selectOption('free')
|
||||
await page.getByTestId('rule-subtotal-min').fill('25')
|
||||
await page.getByRole('switch', { name: 'Stop here' }).click()
|
||||
})
|
||||
await page.getByTestId('rule').filter({ hasText: 'Free over 25' }).getByRole('button', { name: 'Move up' }).click()
|
||||
await page.waitForFunction(() => document.querySelector('[data-testid="rule"]')?.textContent.includes('Free over 25'), null, { timeout: 5000 }).catch(() => {})
|
||||
r.check('fees: rules added and put in order (free over 25 first, it stops)', (await page.getByTestId('rule').first().textContent()).includes('Free over 25')
|
||||
&& (await page.getByTestId('rule').first().textContent()).includes('stop here'))
|
||||
const testFee = async (subtotal) => {
|
||||
await page.getByTestId('test-subtotal').fill(String(subtotal))
|
||||
await page.getByTestId('test-run').click()
|
||||
await page.waitForFunction(st => document.querySelector('[data-testid="test-result"]') && document.querySelector('[data-testid="test-subtotal"]').value === st,
|
||||
String(subtotal), { timeout: 5000 }).catch(() => {})
|
||||
await sleep(300)
|
||||
return page.getByTestId('test-result')
|
||||
}
|
||||
let res = await testFee(15)
|
||||
r.check('fees: "test an order" for €15 in Centre → €2.00', await res.getAttribute('data-fee') === '2' && await res.getAttribute('data-refused') === ''
|
||||
&& (await res.textContent()).includes('Base') && (await res.textContent()).includes('Centre'),
|
||||
await res.textContent())
|
||||
res = await testFee(30)
|
||||
r.check('fees: …for €30 → free, the first rule stopped the rest', await res.getAttribute('data-fee') === '0' && await res.getAttribute('data-refused') === ''
|
||||
&& (await res.textContent()).includes('Free over 25') && !(await res.textContent()).includes('Base'),
|
||||
await res.textContent())
|
||||
await page.getByTestId('test-subtotal').fill('8')
|
||||
await page.getByRole('combobox', { name: 'Where' }).selectOption('postcode')
|
||||
await page.getByTestId('test-postcode').fill('10431')
|
||||
await page.getByTestId('test-run').click()
|
||||
await page.waitForFunction(() => document.querySelector('[data-testid="test-result"]')?.dataset.refused, null, { timeout: 5000 }).catch(() => {})
|
||||
r.check('fees: …a postcode outside the areas is refused', await page.getByTestId('test-result').getAttribute('data-refused') === 'area_not_served')
|
||||
await page.screenshot({ path: path.join(OUT, 'manager-fees.png'), fullPage: true })
|
||||
|
||||
await page.goto(`${APP}/settings`)
|
||||
await page.getByText('Sign-in & security', { exact: true }).click()
|
||||
const waiterMode = page.getByTestId('setting-auth.waiter_login_mode')
|
||||
|
||||
Reference in New Issue
Block a user