Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d5b8492512 | ||
|
|
e55157fa86 | ||
|
|
9f9b882806 | ||
|
|
e0158b2c72 | ||
|
|
7ee059d834 | ||
|
|
2835b5dc68 | ||
|
|
3459c80611 | ||
|
|
9ccb47cfd1 | ||
|
|
b25bfcda3e | ||
|
|
9e8ec4c4e6 | ||
|
|
96f16e948d | ||
|
|
5bdd19d9fb | ||
|
|
2541a5782e | ||
|
|
48fd10df77 | ||
|
|
048b46af41 | ||
|
|
96a014ecbe | ||
|
|
15331cdccf | ||
|
|
d323be1088 | ||
|
|
7a53cc3d66 | ||
|
|
6c7df8d011 | ||
|
|
a73f081ca1 | ||
|
|
f5736b85cb | ||
|
|
d87540e08f | ||
|
|
0cad6a76d3 | ||
|
|
a6f759bf49 | ||
|
|
ffaeab136d | ||
|
|
17fb3a2589 | ||
|
|
70c7b9564b | ||
|
|
82b853369b | ||
|
|
ac58d150ea |
@@ -0,0 +1,4 @@
|
|||||||
|
# cloud-service
|
||||||
|
|
||||||
|
Read [docs/README.md](docs/README.md) (pack rules) and the global [../docs/README.md](../docs/README.md) (Working Rules) before making changes.
|
||||||
|
This is its own git repo. Commit here first, then bump the pointer in the parent `xenia-pos` repo.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Never bake local data, secrets or tests into the image
|
||||||
|
*.db
|
||||||
|
*.db-*
|
||||||
|
.env
|
||||||
|
__pycache__/
|
||||||
|
tests/
|
||||||
@@ -20,3 +20,8 @@ LATEST_VERSION=0.0.0
|
|||||||
# Generate with: python -c "import secrets; print(secrets.token_hex(32))"
|
# Generate with: python -c "import secrets; print(secrets.token_hex(32))"
|
||||||
MANAGER_JWT_SECRET=change-me-manager-secret
|
MANAGER_JWT_SECRET=change-me-manager-secret
|
||||||
MANAGER_JWT_EXPIRE_HOURS=72
|
MANAGER_JWT_EXPIRE_HOURS=72
|
||||||
|
|
||||||
|
# Where customers open the apps (connect_frontend: /menu/ QR menu, /order/ online ordering),
|
||||||
|
# e.g. https://menu.example.com. Sent to sites with the heartbeat: their table QR codes and
|
||||||
|
# ordering link point here. Empty = sites use their CLOUD_URL.
|
||||||
|
PUBLIC_APPS_URL=
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Alembic CLI config for cloud_backend (APPS_PLATFORM D-22). The app calls schema.py itself.
|
||||||
|
# cd cloud_backend
|
||||||
|
# alembic revision --autogenerate --rev-id 0003_short_name -m "what changed" # then REVIEW it
|
||||||
|
# alembic upgrade head
|
||||||
|
# Production cutover (once): alembic stamp 0001_cloud_baseline && alembic upgrade head
|
||||||
|
[alembic]
|
||||||
|
script_location = migrations
|
||||||
|
file_template = %%(rev)s
|
||||||
@@ -19,9 +19,17 @@ class Settings(BaseSettings):
|
|||||||
ADMIN_USERNAME: str = "sysadmin"
|
ADMIN_USERNAME: str = "sysadmin"
|
||||||
ADMIN_PASSWORD: str = "changeme"
|
ADMIN_PASSWORD: str = "changeme"
|
||||||
LATEST_VERSION: str = "0.0.0"
|
LATEST_VERSION: str = "0.0.0"
|
||||||
|
# Ed25519 private key (base64, raw 32 bytes) that signs sites' license tokens.
|
||||||
|
# Generated once; the matching public key is built into client-services
|
||||||
|
# (local_backend/services/license.py). Keep secret, back up.
|
||||||
|
LICENSE_SIGNING_KEY: str = ""
|
||||||
# Manager JWT (separate secret from admin JWT)
|
# Manager JWT (separate secret from admin JWT)
|
||||||
MANAGER_JWT_SECRET: str = "change-me-manager-secret"
|
MANAGER_JWT_SECRET: str = "change-me-manager-secret"
|
||||||
MANAGER_JWT_EXPIRE_HOURS: int = 72
|
MANAGER_JWT_EXPIRE_HOURS: int = 72
|
||||||
|
# Where customers open the apps (connect_frontend: /menu/, /order/), e.g. https://menu.example.com.
|
||||||
|
# Sent to sites with the heartbeat so they can print table QR codes and show their ordering
|
||||||
|
# link (phase 3S, S.7). Empty = the sites use their CLOUD_URL.
|
||||||
|
PUBLIC_APPS_URL: str = ""
|
||||||
|
|
||||||
model_config = {"env_file": str(_HERE / ".env")}
|
model_config = {"env_file": str(_HERE / ".env")}
|
||||||
|
|
||||||
|
|||||||
+16
-26
@@ -1,18 +1,16 @@
|
|||||||
|
"""Cloud backend entry point. Schema: Alembic only (schema.py, APPS_PLATFORM D-22)."""
|
||||||
|
import os
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from database import engine, Base
|
from database import engine
|
||||||
from auth_utils import hash_password
|
from auth_utils import hash_password
|
||||||
import models.admin # noqa: F401
|
import models.all # noqa: F401 every model (Alembic + routers)
|
||||||
import models.site # noqa: F401
|
|
||||||
import models.menu_snapshot # noqa: F401
|
|
||||||
import models.online_order # noqa: F401
|
|
||||||
import models.manager_account # noqa: F401
|
|
||||||
import models.stats_snapshot # noqa: F401
|
|
||||||
|
|
||||||
from routers import auth, sites, heartbeat
|
from routers import auth, sites, heartbeat, presets
|
||||||
from routers import menu as menu_router
|
from routers import menu as menu_router
|
||||||
from routers import orders as orders_router
|
from routers import orders as orders_router
|
||||||
from routers import manager_auth as manager_auth_router
|
from routers import manager_auth as manager_auth_router
|
||||||
@@ -33,26 +31,11 @@ def _seed_default_admin():
|
|||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
def _run_migrations():
|
|
||||||
"""Apply additive schema changes that create_all won't handle."""
|
|
||||||
from sqlalchemy import text
|
|
||||||
migrations = [
|
|
||||||
# Per-site order counter for public_ref generation (e.g. "ORD-0042")
|
|
||||||
"ALTER TABLE sites ADD COLUMN order_counter INTEGER NOT NULL DEFAULT 0",
|
|
||||||
]
|
|
||||||
for sql in migrations:
|
|
||||||
try:
|
|
||||||
with engine.connect() as conn:
|
|
||||||
conn.execute(text(sql))
|
|
||||||
conn.commit()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
Base.metadata.create_all(bind=engine)
|
# Schema = Alembic revisions only (schema.py, D-22). Refuses an unstamped v1 database.
|
||||||
_run_migrations()
|
from schema import upgrade_to_head
|
||||||
|
upgrade_to_head()
|
||||||
_seed_default_admin()
|
_seed_default_admin()
|
||||||
yield
|
yield
|
||||||
|
|
||||||
@@ -69,11 +52,18 @@ app.add_middleware(
|
|||||||
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
|
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
|
||||||
app.include_router(sites.router, prefix="/api/sites", tags=["sites"])
|
app.include_router(sites.router, prefix="/api/sites", tags=["sites"])
|
||||||
app.include_router(heartbeat.router, prefix="/api/heartbeat", tags=["heartbeat"])
|
app.include_router(heartbeat.router, prefix="/api/heartbeat", tags=["heartbeat"])
|
||||||
|
app.include_router(presets.router, prefix="/api/presets", tags=["presets"])
|
||||||
app.include_router(menu_router.router, prefix="/api/menu", tags=["menu"])
|
app.include_router(menu_router.router, prefix="/api/menu", tags=["menu"])
|
||||||
app.include_router(orders_router.router, prefix="/api/orders", tags=["orders"])
|
app.include_router(orders_router.router, prefix="/api/orders", tags=["orders"])
|
||||||
app.include_router(manager_auth_router.router, prefix="/api/manager", tags=["manager"])
|
app.include_router(manager_auth_router.router, prefix="/api/manager", tags=["manager"])
|
||||||
app.include_router(remote_dashboard_router.router,prefix="/api/remote", tags=["remote"])
|
app.include_router(remote_dashboard_router.router,prefix="/api/remote", tags=["remote"])
|
||||||
|
|
||||||
|
os.makedirs("/app/data/site_headers", exist_ok=True)
|
||||||
|
app.mount("/static/site_headers", StaticFiles(directory="/app/data/site_headers"), name="site_headers")
|
||||||
|
|
||||||
|
os.makedirs("/app/data/product_images", exist_ok=True)
|
||||||
|
app.mount("/static/product_images", StaticFiles(directory="/app/data/product_images"), name="product_images")
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
def health():
|
def health():
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""Alembic environment for cloud_backend (APPS_PLATFORM D-22).
|
||||||
|
|
||||||
|
Agent notes: target metadata = models/all.py; render_as_batch for SQLite; a caller may
|
||||||
|
pass a connection in config.attributes["connection"] (schema.py, tests); otherwise
|
||||||
|
config.settings.DATABASE_URL is used.
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from database import Base # noqa: E402
|
||||||
|
import models.all # noqa: E402,F401
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def _run(connection):
|
||||||
|
context.configure(connection=connection, target_metadata=target_metadata,
|
||||||
|
render_as_batch=True, compare_type=True)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
connection = context.config.attributes.get("connection")
|
||||||
|
if connection is not None:
|
||||||
|
_run(connection)
|
||||||
|
return
|
||||||
|
from config import settings
|
||||||
|
engine = create_engine(settings.DATABASE_URL)
|
||||||
|
with engine.connect() as conn:
|
||||||
|
_run(conn)
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
raise SystemExit("Offline (--sql) mode is not supported.")
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
"""cloud v1 baseline: exactly the schema the v1 production cloud has (D-22)
|
||||||
|
|
||||||
|
Autogenerated from the models, then hand-edited so it equals what v1's create_all +
|
||||||
|
_run_migrations() produce: sites also has menu_hours_en / menu_hours_gr (v1 superseded
|
||||||
|
them by menu_hours but never dropped them; 0002 drops them).
|
||||||
|
The production DB is never upgraded THROUGH this revision: it is stamped to it at
|
||||||
|
cutover, so this file must describe production, not an ideal schema.
|
||||||
|
tests/test_schema.py compares it with a database built by v1's code.
|
||||||
|
|
||||||
|
Revision ID: 0001_cloud_baseline
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-11-12 19:18:38.281895
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0001_cloud_baseline'
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('admins',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('username', sa.String(), nullable=False),
|
||||||
|
sa.Column('password_hash', sa.String(), nullable=False),
|
||||||
|
sa.Column('role', sa.String(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('username')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('admins', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_admins_id'), ['id'], unique=False)
|
||||||
|
|
||||||
|
op.create_table('manager_accounts',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('email', sa.String(), nullable=False),
|
||||||
|
sa.Column('password_hash', sa.String(), nullable=False),
|
||||||
|
sa.Column('full_name', sa.String(), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('manager_accounts', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_manager_accounts_email'), ['email'], unique=True)
|
||||||
|
batch_op.create_index(batch_op.f('ix_manager_accounts_id'), ['id'], unique=False)
|
||||||
|
|
||||||
|
op.create_table('sites',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('site_id', sa.String(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('owner_name', sa.String(), nullable=False),
|
||||||
|
sa.Column('contact_email', sa.String(), nullable=False),
|
||||||
|
sa.Column('secret_key_hash', sa.String(), nullable=False),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||||
|
sa.Column('is_locked', sa.Boolean(), nullable=True),
|
||||||
|
sa.Column('lock_reason', sa.String(), nullable=True),
|
||||||
|
sa.Column('license_expires_at', sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('last_seen_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column('last_seen_ip', sa.String(), nullable=True),
|
||||||
|
sa.Column('last_seen_local_ip', sa.String(), nullable=True),
|
||||||
|
sa.Column('waiter_domain', sa.String(), nullable=True),
|
||||||
|
sa.Column('order_counter', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('menu_mode', sa.String(), nullable=False),
|
||||||
|
sa.Column('menu_display_name', sa.String(), nullable=True),
|
||||||
|
sa.Column('menu_tagline_en', sa.String(), nullable=True),
|
||||||
|
sa.Column('menu_tagline_gr', sa.String(), nullable=True),
|
||||||
|
sa.Column('menu_blurb_en', sa.String(), nullable=True),
|
||||||
|
sa.Column('menu_blurb_gr', sa.String(), nullable=True),
|
||||||
|
sa.Column('menu_hours', sa.String(), nullable=True),
|
||||||
|
sa.Column('menu_hours_en', sa.String(), nullable=True),
|
||||||
|
sa.Column('menu_hours_gr', sa.String(), nullable=True),
|
||||||
|
sa.Column('menu_header_image_url', sa.String(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('sites', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_sites_id'), ['id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_sites_site_id'), ['site_id'], unique=True)
|
||||||
|
|
||||||
|
op.create_table('manager_site_access',
|
||||||
|
sa.Column('manager_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('site_id', sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['manager_id'], ['manager_accounts.id'], ),
|
||||||
|
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('manager_id', 'site_id')
|
||||||
|
)
|
||||||
|
op.create_table('menu_snapshots',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('site_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('snapshot_json', sa.Text(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('menu_snapshots', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_menu_snapshots_id'), ['id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_menu_snapshots_site_id'), ['site_id'], unique=True)
|
||||||
|
|
||||||
|
op.create_table('online_orders',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('site_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('public_ref', sa.String(), nullable=False),
|
||||||
|
sa.Column('order_type', sa.String(), nullable=False),
|
||||||
|
sa.Column('customer_name', sa.String(), nullable=False),
|
||||||
|
sa.Column('customer_phone', sa.String(), nullable=True),
|
||||||
|
sa.Column('customer_address', sa.Text(), nullable=True),
|
||||||
|
sa.Column('customer_notes', sa.Text(), nullable=True),
|
||||||
|
sa.Column('items_json', sa.Text(), nullable=False),
|
||||||
|
sa.Column('subtotal', sa.Float(), nullable=False),
|
||||||
|
sa.Column('delivery_fee', sa.Float(), nullable=False),
|
||||||
|
sa.Column('total', sa.Float(), nullable=False),
|
||||||
|
sa.Column('status', sa.String(), nullable=False),
|
||||||
|
sa.Column('rejection_reason', sa.String(), nullable=True),
|
||||||
|
sa.Column('synced_to_local', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('local_order_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('public_ref')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_online_orders_id'), ['id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_online_orders_site_id'), ['site_id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_online_orders_status'), ['status'], unique=False)
|
||||||
|
|
||||||
|
op.create_table('product_images',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('site_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('product_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('image_url', sa.String(), nullable=False),
|
||||||
|
sa.Column('image_hash', sa.String(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('site_id', 'product_id', name='uq_product_images_site_product')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('product_images', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_product_images_id'), ['id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_product_images_site_id'), ['site_id'], unique=False)
|
||||||
|
|
||||||
|
op.create_table('stats_snapshots',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('site_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('snapshot_json', sa.Text(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('site_id')
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_table('stats_snapshots')
|
||||||
|
with op.batch_alter_table('product_images', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_product_images_site_id'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_product_images_id'))
|
||||||
|
|
||||||
|
op.drop_table('product_images')
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_online_orders_status'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_online_orders_site_id'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_online_orders_id'))
|
||||||
|
|
||||||
|
op.drop_table('online_orders')
|
||||||
|
with op.batch_alter_table('menu_snapshots', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_menu_snapshots_site_id'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_menu_snapshots_id'))
|
||||||
|
|
||||||
|
op.drop_table('menu_snapshots')
|
||||||
|
op.drop_table('manager_site_access')
|
||||||
|
with op.batch_alter_table('sites', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_sites_site_id'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_sites_id'))
|
||||||
|
|
||||||
|
op.drop_table('sites')
|
||||||
|
with op.batch_alter_table('manager_accounts', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_manager_accounts_id'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_manager_accounts_email'))
|
||||||
|
|
||||||
|
op.drop_table('manager_accounts')
|
||||||
|
with op.batch_alter_table('admins', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_admins_id'))
|
||||||
|
|
||||||
|
op.drop_table('admins')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""v2 licensing: site modules, catalogue, plan presets (D-3, D-20, D-21, §5.2)
|
||||||
|
|
||||||
|
Hand-edited:
|
||||||
|
- existing sites get V1_SITE_MODULES: every module a v1 site already had, with no
|
||||||
|
limits tighter than v1 (KDS screens unlimited). At cutover each site keeps doing what
|
||||||
|
it did; the owner can then change sites in the sysadmin panel. Frozen here on purpose.
|
||||||
|
- the same map is seeded as the preset "Everything (v1 sites)".
|
||||||
|
- menu_hours_en / menu_hours_gr (superseded in v1) are dropped.
|
||||||
|
|
||||||
|
Revision ID: 0002_v2_licensing
|
||||||
|
Revises: 0001_cloud_baseline
|
||||||
|
Create Date: 2026-11-12 19:19:08.073899
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
V1_SITE_MODULES = {
|
||||||
|
"ordering": {}, "waiter_app": {}, "history": {}, "reports": {}, "pricing": {}, "tabs": {},
|
||||||
|
"crm": {}, "expenses": {}, "inventory": {}, "staff_planning": {}, "notes": {}, "chat": {},
|
||||||
|
"reservations": {}, "kds": {"limits": {"devices": None}}, "connect_menu": {},
|
||||||
|
"connect_orders": {}, "connect_remote": {}, "caller_id": {}, "fiscal": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0002_v2_licensing'
|
||||||
|
down_revision = '0001_cloud_baseline'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('plan_presets',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('description', sa.String(), nullable=True),
|
||||||
|
sa.Column('modules', sa.JSON(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('name')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('sites', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('modules', sa.JSON(), nullable=False, server_default=sa.text("'{}'")))
|
||||||
|
batch_op.add_column(sa.Column('module_catalog', sa.JSON(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('module_catalog_at', sa.DateTime(timezone=True), nullable=True))
|
||||||
|
batch_op.drop_column('menu_hours_en')
|
||||||
|
batch_op.drop_column('menu_hours_gr')
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
conn = op.get_bind()
|
||||||
|
conn.execute(sa.text("update sites set modules = :m"), {"m": json.dumps(V1_SITE_MODULES)})
|
||||||
|
conn.execute(sa.text("insert into plan_presets (name, description, modules) values (:n, :d, :m)"),
|
||||||
|
{"n": "Everything (v1 sites)", "d": "Every module v1 sites had, no extra limits",
|
||||||
|
"m": json.dumps(V1_SITE_MODULES)})
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('sites', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('menu_hours_gr', sa.VARCHAR(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('menu_hours_en', sa.VARCHAR(), nullable=True))
|
||||||
|
batch_op.drop_column('module_catalog_at')
|
||||||
|
batch_op.drop_column('module_catalog')
|
||||||
|
batch_op.drop_column('modules')
|
||||||
|
|
||||||
|
op.drop_table('plan_presets')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""online orders: sales_point, table_label, delivery_area, requested_for, tracking_token; public_ref unique per site (plan phase 3S, S.2/S.3)
|
||||||
|
|
||||||
|
- sales_point / table_label: the cloud prices orders per sales point; the QR menu's table
|
||||||
|
- public_ref ("ORD-0001") counts per site but was unique across all sites, so a second
|
||||||
|
site's first online order failed → unique per (site_id, public_ref)
|
||||||
|
- tracking_token: the customer's tracking page used the public ref alone (ambiguous across
|
||||||
|
sites and guessable) → a random token per order (existing orders get one)
|
||||||
|
|
||||||
|
The table is rebuilt from an explicit definition (SQLite can't drop the unnamed
|
||||||
|
UNIQUE(public_ref) in place; copy_from leaves it out, the indexes are kept).
|
||||||
|
|
||||||
|
Revision ID: 0003_order_sales_point
|
||||||
|
Revises: 0002_v2_licensing
|
||||||
|
Create Date: 2026-11-15 23:00:00
|
||||||
|
"""
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0003_order_sales_point'
|
||||||
|
down_revision = '0002_v2_licensing'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def _base(*extra):
|
||||||
|
"""online_orders as 0001 created it, without UNIQUE(public_ref), plus `extra`."""
|
||||||
|
return sa.Table(
|
||||||
|
'online_orders', sa.MetaData(),
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('site_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('public_ref', sa.String(), nullable=False),
|
||||||
|
sa.Column('order_type', sa.String(), nullable=False),
|
||||||
|
sa.Column('customer_name', sa.String(), nullable=False),
|
||||||
|
sa.Column('customer_phone', sa.String(), nullable=True),
|
||||||
|
sa.Column('customer_address', sa.Text(), nullable=True),
|
||||||
|
sa.Column('customer_notes', sa.Text(), nullable=True),
|
||||||
|
sa.Column('items_json', sa.Text(), nullable=False),
|
||||||
|
sa.Column('subtotal', sa.Float(), nullable=False),
|
||||||
|
sa.Column('delivery_fee', sa.Float(), nullable=False),
|
||||||
|
sa.Column('total', sa.Float(), nullable=False),
|
||||||
|
sa.Column('status', sa.String(), nullable=False),
|
||||||
|
sa.Column('rejection_reason', sa.String(), nullable=True),
|
||||||
|
sa.Column('synced_to_local', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('local_order_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
*extra,
|
||||||
|
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.Index('ix_online_orders_id', 'id'),
|
||||||
|
sa.Index('ix_online_orders_site_id', 'site_id'),
|
||||||
|
sa.Index('ix_online_orders_status', 'status'),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', copy_from=_base(), recreate='always') as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('table_label', sa.String(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('delivery_area', sa.String(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('requested_for', sa.DateTime(timezone=True), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('sales_point', sa.String(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('tracking_token', sa.String(), nullable=True))
|
||||||
|
batch_op.create_unique_constraint('uq_online_orders_site_ref', ['site_id', 'public_ref'])
|
||||||
|
batch_op.create_unique_constraint('uq_online_orders_tracking_token', ['tracking_token'])
|
||||||
|
conn = op.get_bind()
|
||||||
|
for (oid,) in conn.execute(sa.text("select id from online_orders where tracking_token is null")).fetchall():
|
||||||
|
conn.execute(sa.text("update online_orders set tracking_token = :t where id = :i"),
|
||||||
|
{"t": secrets.token_urlsafe(12), "i": oid})
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
current = _base(sa.Column('table_label', sa.String(), nullable=True),
|
||||||
|
sa.Column('delivery_area', sa.String(), nullable=True),
|
||||||
|
sa.Column('requested_for', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column('sales_point', sa.String(), nullable=True),
|
||||||
|
sa.Column('tracking_token', sa.String(), nullable=True))
|
||||||
|
with op.batch_alter_table('online_orders', copy_from=current, recreate='always') as batch_op:
|
||||||
|
batch_op.drop_column('tracking_token')
|
||||||
|
batch_op.drop_column('sales_point')
|
||||||
|
batch_op.drop_column('requested_for')
|
||||||
|
batch_op.drop_column('delivery_area')
|
||||||
|
batch_op.drop_column('table_label')
|
||||||
|
batch_op.create_unique_constraint('uq_online_orders_public_ref', ['public_ref'])
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""online orders: delivery_area_id (plan phase 3S, S.5)
|
||||||
|
|
||||||
|
The site checks the cloud's delivery fee with its own engine when it pulls an order, and
|
||||||
|
needs the area by id (a name can change between a menu push and the order).
|
||||||
|
|
||||||
|
Revision ID: 0004_order_area_id
|
||||||
|
Revises: 0003_order_sales_point
|
||||||
|
Create Date: 2026-11-16 18:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0004_order_area_id'
|
||||||
|
down_revision = '0003_order_sales_point'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('delivery_area_id', sa.Integer(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('delivery_area_id')
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""online orders: party_size (reservations online, plan phase 3S, S.6)
|
||||||
|
|
||||||
|
Revision ID: 0005_order_party_size
|
||||||
|
Revises: 0004_order_area_id
|
||||||
|
Create Date: 2026-11-16 21:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0005_order_party_size'
|
||||||
|
down_revision = '0004_order_area_id'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('party_size', sa.Integer(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('party_size')
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""online orders: table_id (the QR menu at the table, plan phase 3S, S.7)
|
||||||
|
|
||||||
|
Revision ID: 0006_order_table_id
|
||||||
|
Revises: 0005_order_party_size
|
||||||
|
Create Date: 2026-11-16 23:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0006_order_table_id'
|
||||||
|
down_revision = '0005_order_party_size'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('table_id', sa.Integer(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('table_id')
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""online orders: lat / lng, where the customer pinned the delivery (plan 6R.G: areas drawn on a map)
|
||||||
|
|
||||||
|
Revision ID: 0007_order_pin
|
||||||
|
Revises: 0006_order_table_id
|
||||||
|
Create Date: 2026-11-23 23:55:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0007_order_pin'
|
||||||
|
down_revision = '0006_order_table_id'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('lat', sa.Float(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('lng', sa.Float(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('online_orders', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('lng')
|
||||||
|
batch_op.drop_column('lat')
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""Every cloud model, for Alembic autogenerate and the drift guard. Add new model modules here."""
|
||||||
|
import models.admin # noqa: F401
|
||||||
|
import models.site # noqa: F401
|
||||||
|
import models.menu_snapshot # noqa: F401
|
||||||
|
import models.online_order # noqa: F401
|
||||||
|
import models.manager_account # noqa: F401
|
||||||
|
import models.stats_snapshot # noqa: F401
|
||||||
|
import models.product_image # noqa: F401
|
||||||
|
import models.plan_preset # noqa: F401
|
||||||
@@ -1,23 +1,38 @@
|
|||||||
from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey
|
from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey, UniqueConstraint
|
||||||
from sqlalchemy.sql import func
|
from sqlalchemy.sql import func
|
||||||
from database import Base
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
class OnlineOrder(Base):
|
class OnlineOrder(Base):
|
||||||
__tablename__ = "online_orders"
|
__tablename__ = "online_orders"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("site_id", "public_ref", name="uq_online_orders_site_ref"), # S.2: per site
|
||||||
|
UniqueConstraint("tracking_token", name="uq_online_orders_tracking_token"),
|
||||||
|
)
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True)
|
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True)
|
||||||
|
|
||||||
# Human-readable reference, unique per site (e.g. "ORD-0042")
|
# Human-readable reference, unique per site (e.g. "ORD-0042")
|
||||||
public_ref = Column(String, unique=True, nullable=False)
|
public_ref = Column(String, nullable=False)
|
||||||
order_type = Column(String, nullable=False) # "delivery" | "dine_in"
|
# the customer's tracking page: random, unguessable (S.2; the ref alone was ambiguous across sites)
|
||||||
|
tracking_token = Column(String, nullable=True)
|
||||||
|
order_type = Column(String, nullable=False) # dine_in | takeaway | delivery | reservation | preorder (S.6)
|
||||||
|
|
||||||
# Customer info
|
# Customer info
|
||||||
customer_name = Column(String, nullable=False)
|
customer_name = Column(String, nullable=False)
|
||||||
customer_phone = Column(String, nullable=True)
|
customer_phone = Column(String, nullable=True)
|
||||||
customer_address = Column(Text, nullable=True) # required for delivery
|
customer_address = Column(Text, nullable=True) # required for delivery
|
||||||
customer_notes = Column(Text, nullable=True)
|
customer_notes = Column(Text, nullable=True)
|
||||||
|
table_label = Column(String, nullable=True) # the QR menu's table (S.7: from the table's QR token)
|
||||||
|
table_id = Column(Integer, nullable=True) # the site's table id, from a valid QR token (S.7)
|
||||||
|
delivery_area = Column(String, nullable=True) # the delivery area's name (S.3)
|
||||||
|
delivery_area_id = Column(Integer, nullable=True) # the site's area id (S.5: the site checks the fee)
|
||||||
|
lat = Column(Float, nullable=True) # 6R.G: where the customer pinned the delivery
|
||||||
|
lng = Column(Float, nullable=True)
|
||||||
|
requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap
|
||||||
|
party_size = Column(Integer, nullable=True) # reservations (S.6): how many guests
|
||||||
|
sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2)
|
||||||
|
|
||||||
# Order content — JSON array of ordered items
|
# Order content — JSON array of ordered items
|
||||||
items_json = Column(Text, nullable=False)
|
items_json = Column(Text, nullable=False)
|
||||||
@@ -30,6 +45,8 @@ class OnlineOrder(Base):
|
|||||||
# Status lifecycle:
|
# Status lifecycle:
|
||||||
# pending_acceptance → accepted | rejected
|
# pending_acceptance → accepted | rejected
|
||||||
# accepted → preparing → ready | out_for_delivery → delivered
|
# accepted → preparing → ready | out_for_delivery → delivered
|
||||||
|
# reservations (S.6): pending_acceptance → accepted (confirmed) | rejected;
|
||||||
|
# accepted → delivered (the guests arrived) | cancelled (by the venue)
|
||||||
status = Column(String, default="pending_acceptance", nullable=False, index=True)
|
status = Column(String, default="pending_acceptance", nullable=False, index=True)
|
||||||
rejection_reason = Column(String, nullable=True)
|
rejection_reason = Column(String, nullable=True)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""Plan presets (APPS_PLATFORM D-3, §5.2): named module maps the sysadmin applies to a site.
|
||||||
|
|
||||||
|
A preset only fills in a site's `modules` map; after applying, the site's map can be
|
||||||
|
edited freely. Plans are not a concept the sites know about.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import JSON, Column, DateTime, Integer, String
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class PlanPreset(Base):
|
||||||
|
__tablename__ = "plan_presets"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True)
|
||||||
|
name = Column(String, nullable=False, unique=True)
|
||||||
|
description = Column(String, nullable=True)
|
||||||
|
modules = Column(JSON, nullable=False, default=dict)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, UniqueConstraint
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class ProductImage(Base):
|
||||||
|
"""Cloud-hosted copy of a local product's image, pushed by local_backend
|
||||||
|
during menu sync. Used as a fallback on the public QR menu when the
|
||||||
|
product has no digital_image_url override set."""
|
||||||
|
__tablename__ = "product_images"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True)
|
||||||
|
product_id = Column(Integer, nullable=False)
|
||||||
|
image_url = Column(String, nullable=False)
|
||||||
|
image_hash = Column(String, nullable=False)
|
||||||
|
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||||
|
|
||||||
|
__table_args__ = (UniqueConstraint("site_id", "product_id", name="uq_product_images_site_product"),)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime
|
from sqlalchemy import JSON, Column, Integer, String, Boolean, DateTime
|
||||||
from sqlalchemy.sql import func
|
from sqlalchemy.sql import func
|
||||||
from database import Base
|
from database import Base
|
||||||
|
|
||||||
@@ -23,3 +23,28 @@ class Site(Base):
|
|||||||
waiter_domain = Column(String, nullable=True)
|
waiter_domain = Column(String, nullable=True)
|
||||||
# Monotonically incrementing counter used to generate public_ref for online orders
|
# Monotonically incrementing counter used to generate public_ref for online orders
|
||||||
order_counter = Column(Integer, default=0, nullable=False)
|
order_counter = Column(Integer, default=0, nullable=False)
|
||||||
|
|
||||||
|
# QR menu branding/config
|
||||||
|
menu_mode = Column(String, nullable=False, default="order") # "order" | "view_only"
|
||||||
|
menu_display_name = Column(String, nullable=True)
|
||||||
|
menu_tagline_en = Column(String, nullable=True)
|
||||||
|
menu_tagline_gr = Column(String, nullable=True)
|
||||||
|
menu_blurb_en = Column(String, nullable=True)
|
||||||
|
menu_blurb_gr = Column(String, nullable=True)
|
||||||
|
menu_hours = Column(String, nullable=True)
|
||||||
|
menu_header_image_url = Column(String, nullable=True)
|
||||||
|
|
||||||
|
# Licensed modules (APPS_PLATFORM D-3, §5.2): the `modules` map of the site's v2 license
|
||||||
|
# token, e.g. {"ordering": {}, "kds": {"limits": {"devices": 2}}, "caller_id": {"exp": "..."}}.
|
||||||
|
# Edited in the sysadmin panel, usually by applying a plan preset first.
|
||||||
|
modules = Column(JSON, nullable=False, default=dict)
|
||||||
|
# What the site reported it can run (heartbeat `module_catalog`, D-20): drives the editor.
|
||||||
|
module_catalog = Column(JSON, nullable=True)
|
||||||
|
module_catalog_at = Column(DateTime(timezone=True), nullable=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def apps_url(self) -> str | None:
|
||||||
|
"""Where customers open this cloud's apps (PUBLIC_APPS_URL; phase 3S): the sysadmin's
|
||||||
|
menu and ordering links are built from it. Not stored per site."""
|
||||||
|
from config import settings
|
||||||
|
return settings.PUBLIC_APPS_URL.rstrip("/") or None
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest==8.3.3
|
||||||
@@ -8,3 +8,5 @@ passlib[bcrypt]==1.7.4
|
|||||||
bcrypt==4.0.1
|
bcrypt==4.0.1
|
||||||
python-multipart==0.0.9
|
python-multipart==0.0.9
|
||||||
httpx==0.27.2
|
httpx==0.27.2
|
||||||
|
cryptography==46.0.4
|
||||||
|
alembic==1.14.0
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from config import settings
|
|||||||
from database import get_db
|
from database import get_db
|
||||||
from models.site import Site
|
from models.site import Site
|
||||||
from schemas.site import HeartbeatRequest, HeartbeatResponse
|
from schemas.site import HeartbeatRequest, HeartbeatResponse
|
||||||
|
from services.license_token import issue_license_token
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
@@ -29,15 +30,15 @@ def heartbeat(
|
|||||||
site.last_seen_ip = request.client.host if request.client else None
|
site.last_seen_ip = request.client.host if request.client else None
|
||||||
if body.local_ip:
|
if body.local_ip:
|
||||||
site.last_seen_local_ip = body.local_ip
|
site.last_seen_local_ip = body.local_ip
|
||||||
|
if body.module_catalog:
|
||||||
|
site.module_catalog = body.module_catalog
|
||||||
|
site.module_catalog_at = now
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
licensed = site.is_active and (site.license_expires_at.replace(tzinfo=timezone.utc) > now)
|
|
||||||
return HeartbeatResponse(
|
return HeartbeatResponse(
|
||||||
licensed=licensed,
|
|
||||||
locked=site.is_locked,
|
|
||||||
lock_reason=site.lock_reason,
|
|
||||||
expires_at=site.license_expires_at,
|
|
||||||
latest_version=settings.LATEST_VERSION,
|
latest_version=settings.LATEST_VERSION,
|
||||||
waiter_domain=site.waiter_domain,
|
waiter_domain=site.waiter_domain,
|
||||||
site_numeric_id=site.id,
|
site_numeric_id=site.id,
|
||||||
|
license_token=issue_license_token(site, now),
|
||||||
|
apps_url=settings.PUBLIC_APPS_URL.rstrip("/") or None,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Depends, HTTPException, status
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||||
from jose import jwt, JWTError
|
from jose import jwt, JWTError
|
||||||
from passlib.context import CryptContext
|
from passlib.context import CryptContext
|
||||||
|
from pydantic import BaseModel
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from models.manager_account import ManagerAccount
|
from models.manager_account import ManagerAccount, manager_site_access
|
||||||
from models.site import Site
|
from models.site import Site
|
||||||
from auth_utils import get_current_admin
|
from auth_utils import get_current_admin
|
||||||
from schemas.manager import (
|
from schemas.manager import (
|
||||||
@@ -56,10 +58,18 @@ def register_manager(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
_admin=Depends(get_current_admin),
|
_admin=Depends(get_current_admin),
|
||||||
):
|
):
|
||||||
if db.query(ManagerAccount).filter(ManagerAccount.email == body.email).first():
|
existing = db.query(ManagerAccount).filter(ManagerAccount.email == body.email).first()
|
||||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email already registered")
|
sites = db.query(Site).filter(Site.site_id.in_(body.site_ids)).all()
|
||||||
|
|
||||||
|
if existing:
|
||||||
|
# Email already exists — just add the new site access links, don't recreate the account
|
||||||
|
for site in sites:
|
||||||
|
if site not in existing.sites:
|
||||||
|
existing.sites.append(site)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(existing)
|
||||||
|
return existing
|
||||||
|
|
||||||
sites = db.query(Site).filter(Site.id.in_(body.site_ids)).all()
|
|
||||||
manager = ManagerAccount(
|
manager = ManagerAccount(
|
||||||
email=body.email,
|
email=body.email,
|
||||||
password_hash=_pwd.hash(body.password),
|
password_hash=_pwd.hash(body.password),
|
||||||
@@ -89,3 +99,52 @@ def login_manager(body: ManagerLoginRequest, db: Session = Depends(get_db)):
|
|||||||
@router.post("/refresh", response_model=ManagerTokenOut)
|
@router.post("/refresh", response_model=ManagerTokenOut)
|
||||||
def refresh_manager_token(manager: ManagerAccount = Depends(_get_current_manager)):
|
def refresh_manager_token(manager: ManagerAccount = Depends(_get_current_manager)):
|
||||||
return ManagerTokenOut(access_token=_create_manager_token(manager))
|
return ManagerTokenOut(access_token=_create_manager_token(manager))
|
||||||
|
|
||||||
|
|
||||||
|
# ── Admin-only: list managers for a site ─────────────────────────────────────
|
||||||
|
|
||||||
|
class ManagerBySiteOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
email: str
|
||||||
|
full_name: Optional[str] = None
|
||||||
|
is_active: int
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/by-site/{site_id}", response_model=list[ManagerBySiteOut])
|
||||||
|
def get_managers_by_site(
|
||||||
|
site_id: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
_admin=Depends(get_current_admin),
|
||||||
|
):
|
||||||
|
site = db.query(Site).filter(Site.site_id == site_id).first()
|
||||||
|
if not site:
|
||||||
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
|
return site.manager_accounts
|
||||||
|
|
||||||
|
|
||||||
|
# ── Admin-only: remove a manager's access to a site ──────────────────────────
|
||||||
|
|
||||||
|
class SiteAccessRemoveRequest(BaseModel):
|
||||||
|
manager_id: int
|
||||||
|
site_id: str # site_id UUID string, not integer PK
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/site-access", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
def remove_manager_site_access(
|
||||||
|
body: SiteAccessRemoveRequest,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
_admin=Depends(get_current_admin),
|
||||||
|
):
|
||||||
|
manager = db.query(ManagerAccount).filter(ManagerAccount.id == body.manager_id).first()
|
||||||
|
if not manager:
|
||||||
|
raise HTTPException(status_code=404, detail="Manager not found")
|
||||||
|
|
||||||
|
site = db.query(Site).filter(Site.site_id == body.site_id).first()
|
||||||
|
if not site:
|
||||||
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
|
|
||||||
|
if site in manager.sites:
|
||||||
|
manager.sites.remove(site)
|
||||||
|
db.commit()
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Header, status
|
import os
|
||||||
|
import uuid
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Header, UploadFile, File, Form, status
|
||||||
from passlib.context import CryptContext
|
from passlib.context import CryptContext
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from models.site import Site
|
from models.site import Site
|
||||||
from models.menu_snapshot import MenuSnapshot
|
from models.menu_snapshot import MenuSnapshot
|
||||||
|
from models.product_image import ProductImage
|
||||||
from schemas.menu import MenuSyncRequest, MenuSyncResponse
|
from schemas.menu import MenuSyncRequest, MenuSyncResponse
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
PRODUCT_IMAGE_DIR = "/app/data/product_images"
|
||||||
|
|
||||||
|
|
||||||
def _require_site(
|
def _require_site(
|
||||||
x_site_id: str = Header(..., alias="X-Site-ID"),
|
x_site_id: str = Header(..., alias="X-Site-ID"),
|
||||||
@@ -25,8 +30,9 @@ def _require_site(
|
|||||||
# ── Public ────────────────────────────────────────────────────────────────────
|
# ── Public ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.get("/{site_slug}")
|
@router.get("/{site_slug}")
|
||||||
def get_menu(site_slug: str, db: Session = Depends(get_db)):
|
def get_menu(site_slug: str, t: str | None = None, db: Session = Depends(get_db)):
|
||||||
"""Return the latest menu snapshot for a site. Used by the public menu SPA."""
|
"""Return the latest menu snapshot for a site. Used by the public menu SPA. `t`: a table's
|
||||||
|
QR token (S.7) → `table` {id, label}, or `table_invalid` when it isn't one of the venue's."""
|
||||||
site = db.query(Site).filter(Site.site_id == site_slug).first()
|
site = db.query(Site).filter(Site.site_id == site_slug).first()
|
||||||
if not site:
|
if not site:
|
||||||
raise HTTPException(status_code=404, detail="Site not found")
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
@@ -36,19 +42,115 @@ def get_menu(site_slug: str, db: Session = Depends(get_db)):
|
|||||||
raise HTTPException(status_code=404, detail="No menu published yet")
|
raise HTTPException(status_code=404, detail="No menu published yet")
|
||||||
|
|
||||||
import json
|
import json
|
||||||
return json.loads(snapshot.snapshot_json)
|
data = json.loads(snapshot.snapshot_json)
|
||||||
|
from services.checkout import delivery_areas, venue_point
|
||||||
|
data["delivery_areas"] = delivery_areas(data) # S.3: what the customer picks from (6R.G: shapes drawn)
|
||||||
|
data["venue_point"] = venue_point(data) # 6R.G: where the customer's map starts
|
||||||
|
data.pop("fees", None) # the rules and postcodes stay on the cloud
|
||||||
|
from services.ordering import summary
|
||||||
|
data["ordering"] = summary(data) # S.4: services, open now, slots
|
||||||
|
data["menu_mode"] = site.menu_mode
|
||||||
|
from services import qr
|
||||||
|
data["table_ordering"] = qr.ordering_on(data, site) # S.7: ordering at the table (with a table's QR)
|
||||||
|
if t is not None:
|
||||||
|
table = qr.table_for(data, t)
|
||||||
|
data["table"] = table
|
||||||
|
data["table_invalid"] = table is None
|
||||||
|
data.pop("qr", None) # the tables' token hashes stay on the cloud
|
||||||
|
data["restaurant"] = {
|
||||||
|
"name": site.menu_display_name,
|
||||||
|
"tagline": {"en": site.menu_tagline_en, "gr": site.menu_tagline_gr},
|
||||||
|
"blurb": {"en": site.menu_blurb_en, "gr": site.menu_blurb_gr},
|
||||||
|
"hours": site.menu_hours,
|
||||||
|
"headerImageUrl": site.menu_header_image_url,
|
||||||
|
}
|
||||||
|
|
||||||
|
cloud_images = {
|
||||||
|
img.product_id: img.image_url
|
||||||
|
for img in db.query(ProductImage).filter(ProductImage.site_id == site.id).all()
|
||||||
|
}
|
||||||
|
for cat in data.get("categories", []):
|
||||||
|
for product in cat.get("products", []):
|
||||||
|
# image_url as pushed by local_backend points at the restaurant's own
|
||||||
|
# LAN/local server and isn't reachable from the internet — always
|
||||||
|
# replace it with the cloud-hosted copy (or None) unless a manual
|
||||||
|
# digital_image_url override is set.
|
||||||
|
if not product.get("digital_image_url"):
|
||||||
|
product["image_url"] = cloud_images.get(product.get("id"))
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
# ── Internal (site API key) ───────────────────────────────────────────────────
|
# ── Internal (site API key) ───────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.post("/sync", response_model=MenuSyncResponse)
|
@router.post("/sync", response_model=MenuSyncResponse)
|
||||||
def sync_menu(body: MenuSyncRequest, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
|
def sync_menu(body: MenuSyncRequest, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
|
||||||
"""Upsert the menu snapshot for this site. Called by local_backend on each sync."""
|
"""Upsert the menu snapshot for this site. Called by local_backend on each sync. Only the
|
||||||
snapshot = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == body.site_id).first()
|
authenticated site's own (before S.2 the body's site_id was trusted: one site could
|
||||||
|
overwrite another's menu)."""
|
||||||
|
if body.site_id != site.id:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's menu")
|
||||||
|
import json
|
||||||
|
try:
|
||||||
|
json.loads(body.snapshot_json)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=422, detail="snapshot_json is not JSON")
|
||||||
|
snapshot = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
|
||||||
if snapshot:
|
if snapshot:
|
||||||
snapshot.snapshot_json = body.snapshot_json
|
snapshot.snapshot_json = body.snapshot_json
|
||||||
else:
|
else:
|
||||||
snapshot = MenuSnapshot(site_id=body.site_id, snapshot_json=body.snapshot_json)
|
snapshot = MenuSnapshot(site_id=site.id, snapshot_json=body.snapshot_json)
|
||||||
db.add(snapshot)
|
db.add(snapshot)
|
||||||
db.commit()
|
db.commit()
|
||||||
return MenuSyncResponse(ok=True)
|
return MenuSyncResponse(ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/sync-image")
|
||||||
|
async def sync_product_image(
|
||||||
|
product_id: int = Form(...),
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
site: Site = Depends(_require_site),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Upload/replace the cloud-hosted copy of a product's image. Called by
|
||||||
|
local_backend during menu sync for products whose image changed."""
|
||||||
|
if not file.content_type or not file.content_type.startswith("image/"):
|
||||||
|
raise HTTPException(status_code=400, detail="File must be an image")
|
||||||
|
|
||||||
|
contents = await file.read()
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
image_hash = hashlib.sha256(contents).hexdigest()
|
||||||
|
|
||||||
|
record = (
|
||||||
|
db.query(ProductImage)
|
||||||
|
.filter(ProductImage.site_id == site.id, ProductImage.product_id == product_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
|
||||||
|
os.makedirs(PRODUCT_IMAGE_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
if record and record.image_hash == image_hash:
|
||||||
|
return {"ok": True, "image_url": record.image_url, "unchanged": True}
|
||||||
|
|
||||||
|
if record:
|
||||||
|
old_path = os.path.join(PRODUCT_IMAGE_DIR, os.path.basename(record.image_url))
|
||||||
|
if os.path.exists(old_path):
|
||||||
|
os.remove(old_path)
|
||||||
|
|
||||||
|
ext = file.filename.rsplit(".", 1)[-1].lower() if file.filename and "." in file.filename else "jpg"
|
||||||
|
filename = f"{site.id}_{product_id}_{uuid.uuid4().hex[:8]}.{ext}"
|
||||||
|
filepath = os.path.join(PRODUCT_IMAGE_DIR, filename)
|
||||||
|
with open(filepath, "wb") as f:
|
||||||
|
f.write(contents)
|
||||||
|
|
||||||
|
image_url = f"/static/product_images/{filename}"
|
||||||
|
if record:
|
||||||
|
record.image_url = image_url
|
||||||
|
record.image_hash = image_hash
|
||||||
|
else:
|
||||||
|
record = ProductImage(site_id=site.id, product_id=product_id, image_url=image_url, image_hash=image_hash)
|
||||||
|
db.add(record)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return {"ok": True, "image_url": image_url, "unchanged": False}
|
||||||
|
|||||||
+159
-15
@@ -1,15 +1,30 @@
|
|||||||
import json
|
import json
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Header, status
|
import secrets
|
||||||
|
from datetime import date, timezone
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Header, Request, status
|
||||||
from passlib.context import CryptContext
|
from passlib.context import CryptContext
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from models.site import Site
|
from models.site import Site
|
||||||
from models.online_order import OnlineOrder
|
from models.online_order import OnlineOrder
|
||||||
|
from models.menu_snapshot import MenuSnapshot
|
||||||
from schemas.online_order import (
|
from schemas.online_order import (
|
||||||
OnlineOrderCreate, OnlineOrderCreated, OrderStatusOut,
|
OnlineOrderCreate, OnlineOrderCreated, OrderStatusOut,
|
||||||
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest,
|
PendingOrderOut, OrderSyncedRequest, OrderStatusUpdateRequest, QuoteRequest,
|
||||||
)
|
)
|
||||||
|
from services.checkout import CheckoutError, check_sent, price_cart
|
||||||
|
from services import ordering, qr, ratelimit
|
||||||
|
|
||||||
|
# public endpoints, per caller address (CL-4)
|
||||||
|
QUOTE_LIMIT = (120, 60) # 120 quotes a minute
|
||||||
|
ORDER_LIMIT = (10, 600) # 10 orders in 10 minutes
|
||||||
|
TRACK_LIMIT = (240, 60)
|
||||||
|
|
||||||
|
|
||||||
|
def _limit(request, bucket, rule):
|
||||||
|
if not ratelimit.hit(bucket, ratelimit.client_ip(request), *rule):
|
||||||
|
raise HTTPException(status_code=429, detail={"code": "rate.limited", "params": {"seconds": rule[1]}})
|
||||||
from auth_utils import get_current_admin # manager JWT checked separately in manager_auth
|
from auth_utils import get_current_admin # manager JWT checked separately in manager_auth
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -23,6 +38,15 @@ _TRANSITIONS: dict[str, set[str]] = {
|
|||||||
"ready": {"delivered"},
|
"ready": {"delivered"},
|
||||||
"out_for_delivery": {"delivered"},
|
"out_for_delivery": {"delivered"},
|
||||||
}
|
}
|
||||||
|
# reservations (S.6): confirmed or declined; then the guests arrive, or the venue cancels
|
||||||
|
_RES_TRANSITIONS: dict[str, set[str]] = {
|
||||||
|
"pending_acceptance": {"accepted", "rejected"},
|
||||||
|
"accepted": {"delivered", "cancelled"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _transitions(order_type: str) -> dict[str, set[str]]:
|
||||||
|
return _RES_TRANSITIONS if order_type in ordering.RES_TYPES else _TRANSITIONS
|
||||||
|
|
||||||
|
|
||||||
def _require_site(
|
def _require_site(
|
||||||
@@ -38,12 +62,94 @@ def _require_site(
|
|||||||
|
|
||||||
# ── Public endpoints ──────────────────────────────────────────────────────────
|
# ── Public endpoints ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
|
def _site_and_menu(db, site_slug):
|
||||||
def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(get_db)):
|
|
||||||
"""Customer submits an order from the public menu SPA."""
|
|
||||||
site = db.query(Site).filter(Site.site_id == site_slug).first()
|
site = db.query(Site).filter(Site.site_id == site_slug).first()
|
||||||
if not site:
|
if not site:
|
||||||
raise HTTPException(status_code=404, detail="Site not found")
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
|
snap = db.query(MenuSnapshot).filter(MenuSnapshot.site_id == site.id).first()
|
||||||
|
if snap is None:
|
||||||
|
raise HTTPException(status_code=409, detail={"code": "order.no_menu", "params": {}})
|
||||||
|
return site, json.loads(snap.snapshot_json)
|
||||||
|
|
||||||
|
|
||||||
|
def _pin(body):
|
||||||
|
"""The customer's pin [lat, lng] (6R.G), both or nothing."""
|
||||||
|
return [body.lat, body.lng] if body.lat is not None and body.lng is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def _priced(menu, order_type, items, area_id=None, postcode=None, point=None):
|
||||||
|
try:
|
||||||
|
return price_cart(menu, order_type, items, area_id=area_id, postcode=postcode, pin=point)
|
||||||
|
except CheckoutError as e:
|
||||||
|
raise HTTPException(status_code=e.status, detail=e.detail())
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{site_slug}/slots")
|
||||||
|
def order_slots(site_slug: str, db: Session = Depends(get_db)):
|
||||||
|
"""When online orders can be placed (S.4): services, open now, ASAP offered, time slots."""
|
||||||
|
_site, menu = _site_and_menu(db, site_slug)
|
||||||
|
return ordering.summary(menu)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{site_slug}/reservation-slots")
|
||||||
|
def reservation_slots(site_slug: str, day: str, db: Session = Depends(get_db)):
|
||||||
|
"""The reservation times of one venue day (S.6): ?day=YYYY-MM-DD → {day, slots: [iso]}."""
|
||||||
|
_site, menu = _site_and_menu(db, site_slug)
|
||||||
|
try:
|
||||||
|
wanted = date.fromisoformat(day)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=422, detail={"code": "order.time_invalid", "params": {}})
|
||||||
|
return {"day": wanted.isoformat(), "slots": [t.isoformat() for t in ordering.res_slots(menu, wanted)]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{site_slug}/quote")
|
||||||
|
def quote_order(site_slug: str, body: QuoteRequest, request: Request, db: Session = Depends(get_db)):
|
||||||
|
"""The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S)."""
|
||||||
|
_limit(request, "quote", QUOTE_LIMIT)
|
||||||
|
_site, menu = _site_and_menu(db, site_slug)
|
||||||
|
return _priced(menu, body.order_type, [i.model_dump() for i in body.items], body.area_id, body.postcode, _pin(body)).out()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{site_slug}", response_model=OnlineOrderCreated, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db: Session = Depends(get_db)):
|
||||||
|
"""Customer submits an order from a customer app. The cloud prices it from the venue's menu
|
||||||
|
for the order's sales point (services/checkout.py); a price or total the app sent that
|
||||||
|
differs → 409 order.price_changed with the current prices; nothing the browser says about
|
||||||
|
money is stored (phase 3S, S.2)."""
|
||||||
|
_limit(request, "order", ORDER_LIMIT)
|
||||||
|
site, menu = _site_and_menu(db, site_slug)
|
||||||
|
items = [i.model_dump() for i in body.items]
|
||||||
|
reservation = body.order_type in ordering.RES_TYPES # S.6: a table, maybe with food
|
||||||
|
table = None
|
||||||
|
if body.order_type == "dine_in": # S.7: only from a table's QR code
|
||||||
|
if not qr.ordering_on(menu, site):
|
||||||
|
raise HTTPException(status_code=409, detail={"code": "order.service_unavailable", "params": {"service": "dine_in"}})
|
||||||
|
table = qr.table_for(menu, body.table_token)
|
||||||
|
if table is None:
|
||||||
|
raise HTTPException(status_code=403, detail={"code": "order.table_invalid", "params": {}})
|
||||||
|
if body.order_type == "reservation":
|
||||||
|
if items:
|
||||||
|
raise HTTPException(status_code=422, detail={"code": "order.items_not_allowed", "params": {}})
|
||||||
|
priced = None
|
||||||
|
else:
|
||||||
|
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode, _pin(body))
|
||||||
|
if reservation:
|
||||||
|
problem = ordering.res_check(menu, body.order_type, body.requested_for, body.party_size)
|
||||||
|
elif body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
|
||||||
|
problem = ordering.check(menu, body.order_type, body.requested_for)
|
||||||
|
else:
|
||||||
|
problem = None
|
||||||
|
if problem:
|
||||||
|
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
|
||||||
|
if (reservation or body.order_type in ("takeaway", "delivery")) and not (body.customer_phone or "").strip():
|
||||||
|
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
|
||||||
|
if priced is not None:
|
||||||
|
try:
|
||||||
|
check_sent(priced, items, body.total)
|
||||||
|
except CheckoutError as e:
|
||||||
|
raise HTTPException(status_code=e.status, detail=e.detail())
|
||||||
|
if body.order_type == "delivery" and not ((body.customer_address or "").strip() and (body.customer_phone or "").strip()):
|
||||||
|
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone", "customer_address"]}})
|
||||||
|
|
||||||
# Atomically increment counter and generate public_ref
|
# Atomically increment counter and generate public_ref
|
||||||
site.order_counter = (site.order_counter or 0) + 1
|
site.order_counter = (site.order_counter or 0) + 1
|
||||||
@@ -57,24 +163,59 @@ def create_order(site_slug: str, body: OnlineOrderCreate, db: Session = Depends(
|
|||||||
customer_phone=body.customer_phone,
|
customer_phone=body.customer_phone,
|
||||||
customer_address=body.customer_address,
|
customer_address=body.customer_address,
|
||||||
customer_notes=body.customer_notes,
|
customer_notes=body.customer_notes,
|
||||||
items_json=json.dumps([item.model_dump() for item in body.items]),
|
table_label=table["label"] if table else None,
|
||||||
subtotal=body.subtotal,
|
table_id=table["id"] if table else None,
|
||||||
delivery_fee=body.delivery_fee,
|
delivery_area=priced.area_name if priced else None,
|
||||||
total=body.total,
|
delivery_area_id=priced.area_id if priced else None,
|
||||||
|
lat=body.lat if body.order_type == "delivery" and _pin(body) else None,
|
||||||
|
lng=body.lng if body.order_type == "delivery" and _pin(body) else None,
|
||||||
|
# stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it)
|
||||||
|
requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None)
|
||||||
|
if (reservation or body.order_type in ("takeaway", "delivery")) and body.requested_for else None),
|
||||||
|
party_size=body.party_size if reservation else None,
|
||||||
|
sales_point=priced.sales_point if priced else None,
|
||||||
|
items_json=json.dumps([line.out() for line in priced.lines] if priced else []),
|
||||||
|
subtotal=priced.subtotal if priced else 0.0,
|
||||||
|
delivery_fee=priced.delivery_fee if priced else 0.0,
|
||||||
|
total=priced.total if priced else 0.0,
|
||||||
status="pending_acceptance",
|
status="pending_acceptance",
|
||||||
)
|
)
|
||||||
|
order.tracking_token = secrets.token_urlsafe(12)
|
||||||
db.add(order)
|
db.add(order)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(order)
|
db.refresh(order)
|
||||||
return OnlineOrderCreated(order_id=order.id, public_ref=order.public_ref, status=order.status)
|
return OnlineOrderCreated(order_id=order.id, public_ref=order.public_ref, status=order.status,
|
||||||
|
tracking_token=order.tracking_token, total=order.total)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/track/{token}", response_model=OrderStatusOut)
|
||||||
|
def track_order(token: str, request: Request, db: Session = Depends(get_db)):
|
||||||
|
"""The customer's tracking page (S.2): by the order's random token. Since S.4 also what
|
||||||
|
was ordered and when it's wanted (the token is the customer's own secret)."""
|
||||||
|
_limit(request, "track", TRACK_LIMIT)
|
||||||
|
order = db.query(OnlineOrder).filter(OnlineOrder.tracking_token == token).first()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(status_code=404, detail="Order not found")
|
||||||
|
try:
|
||||||
|
lines = json.loads(order.items_json or "[]")
|
||||||
|
except ValueError:
|
||||||
|
lines = []
|
||||||
|
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason,
|
||||||
|
order_type=order.order_type, requested_for=order.requested_for, created_at=order.created_at,
|
||||||
|
party_size=order.party_size,
|
||||||
|
lines=[{"name": x.get("name"), "quantity": x.get("quantity"), "unit_price": x.get("unit_price"),
|
||||||
|
"options": [o.get("name") for o in x.get("options") or []]} for x in lines],
|
||||||
|
subtotal=order.subtotal, delivery_fee=order.delivery_fee, total=order.total)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/status/{public_ref}", response_model=OrderStatusOut)
|
@router.get("/status/{public_ref}", response_model=OrderStatusOut)
|
||||||
def get_order_status(public_ref: str, db: Session = Depends(get_db)):
|
def get_order_status(public_ref: str, db: Session = Depends(get_db)):
|
||||||
"""Customer polls this to track their order."""
|
"""Old tracking by the public ref (menu-app links before S.2): only while the ref is unique
|
||||||
order = db.query(OnlineOrder).filter(OnlineOrder.public_ref == public_ref).first()
|
across sites; otherwise 404 (the new link is /track/{token})."""
|
||||||
if not order:
|
orders = db.query(OnlineOrder).filter(OnlineOrder.public_ref == public_ref).limit(2).all()
|
||||||
|
if len(orders) != 1:
|
||||||
raise HTTPException(status_code=404, detail="Order not found")
|
raise HTTPException(status_code=404, detail="Order not found")
|
||||||
|
order = orders[0]
|
||||||
return OrderStatusOut(
|
return OrderStatusOut(
|
||||||
public_ref=order.public_ref,
|
public_ref=order.public_ref,
|
||||||
status=order.status,
|
status=order.status,
|
||||||
@@ -86,7 +227,10 @@ def get_order_status(public_ref: str, db: Session = Depends(get_db)):
|
|||||||
|
|
||||||
@router.get("/pending/{site_id}", response_model=list[PendingOrderOut])
|
@router.get("/pending/{site_id}", response_model=list[PendingOrderOut])
|
||||||
def get_pending_orders(site_id: int, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
|
def get_pending_orders(site_id: int, site: Site = Depends(_require_site), db: Session = Depends(get_db)):
|
||||||
"""Return all orders not yet synced to the local backend."""
|
"""Return all orders not yet synced to the local backend. Only the authenticated site's own
|
||||||
|
(before S.2 any site with a valid key could read another site's by its number)."""
|
||||||
|
if site_id != site.id:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's orders")
|
||||||
orders = (
|
orders = (
|
||||||
db.query(OnlineOrder)
|
db.query(OnlineOrder)
|
||||||
.filter(OnlineOrder.site_id == site_id, OnlineOrder.synced_to_local == 0)
|
.filter(OnlineOrder.site_id == site_id, OnlineOrder.synced_to_local == 0)
|
||||||
@@ -128,7 +272,7 @@ def update_order_status(
|
|||||||
if not order:
|
if not order:
|
||||||
raise HTTPException(status_code=404, detail="Order not found")
|
raise HTTPException(status_code=404, detail="Order not found")
|
||||||
|
|
||||||
allowed = _TRANSITIONS.get(order.status, set())
|
allowed = _transitions(order.order_type).get(order.status, set())
|
||||||
if body.status not in allowed:
|
if body.status not in allowed:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""Plan presets CRUD (sysadmin): named module maps applied to sites (APPS_PLATFORM D-3, §5.2)."""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from auth_utils import get_current_admin
|
||||||
|
from database import get_db
|
||||||
|
from models.plan_preset import PlanPreset
|
||||||
|
from routers.sites import _validate_modules
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
class PresetIn(BaseModel):
|
||||||
|
name: str
|
||||||
|
description: str | None = None
|
||||||
|
modules: dict
|
||||||
|
|
||||||
|
|
||||||
|
def _out(p: PlanPreset) -> dict:
|
||||||
|
return {"id": p.id, "name": p.name, "description": p.description, "modules": p.modules or {}}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/")
|
||||||
|
def list_presets(db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
|
return [_out(p) for p in db.query(PlanPreset).order_by(PlanPreset.name).all()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_preset(body: PresetIn, db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
|
if db.query(PlanPreset).filter(PlanPreset.name == body.name).first():
|
||||||
|
raise HTTPException(status_code=409, detail="A preset with that name exists")
|
||||||
|
p = PlanPreset(name=body.name, description=body.description, modules=_validate_modules(body.modules))
|
||||||
|
db.add(p)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(p)
|
||||||
|
return _out(p)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{preset_id}")
|
||||||
|
def update_preset(preset_id: int, body: PresetIn, db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
|
p = db.get(PlanPreset, preset_id)
|
||||||
|
if not p:
|
||||||
|
raise HTTPException(status_code=404, detail="Preset not found")
|
||||||
|
p.name, p.description, p.modules = body.name, body.description, _validate_modules(body.modules)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(p)
|
||||||
|
return _out(p)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{preset_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
def delete_preset(preset_id: int, db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
|
p = db.get(PlanPreset, preset_id)
|
||||||
|
if p:
|
||||||
|
db.delete(p)
|
||||||
|
db.commit()
|
||||||
@@ -91,11 +91,13 @@ def push_stats_snapshot(
|
|||||||
if not site or not _pwd.verify(x_site_key, site.secret_key_hash):
|
if not site or not _pwd.verify(x_site_key, site.secret_key_hash):
|
||||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid site credentials")
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid site credentials")
|
||||||
|
|
||||||
snap = db.query(StatsSnapshot).filter(StatsSnapshot.site_id == body.site_id).first()
|
if body.site_id != site.id: # S.2: only its own (the body's site_id was trusted before)
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not this site's stats")
|
||||||
|
snap = db.query(StatsSnapshot).filter(StatsSnapshot.site_id == site.id).first()
|
||||||
if snap:
|
if snap:
|
||||||
snap.snapshot_json = body.snapshot_json
|
snap.snapshot_json = body.snapshot_json
|
||||||
else:
|
else:
|
||||||
snap = StatsSnapshot(site_id=body.site_id, snapshot_json=body.snapshot_json)
|
snap = StatsSnapshot(site_id=site.id, snapshot_json=body.snapshot_json)
|
||||||
db.add(snap)
|
db.add(snap)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,50 @@
|
|||||||
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
import uuid
|
import uuid
|
||||||
from passlib.context import CryptContext
|
from passlib.context import CryptContext
|
||||||
from fastapi import APIRouter, Depends, HTTPException, status
|
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, status
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from auth_utils import get_current_admin
|
from auth_utils import get_current_admin
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from models.site import Site
|
from models.site import Site
|
||||||
from schemas.site import SiteCreate, SiteUpdate, SiteOut, SiteCreatedOut, LockRequest
|
from schemas.site import SiteModulesUpdate, SiteCreate, SiteUpdate, SiteOut, SiteCreatedOut, LockRequest
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
HEADER_IMAGE_DIR = "/app/data/site_headers"
|
||||||
|
|
||||||
|
|
||||||
|
def _preset_modules(db: Session, name: str | None) -> dict:
|
||||||
|
if not name:
|
||||||
|
return {}
|
||||||
|
from models.plan_preset import PlanPreset
|
||||||
|
preset = db.query(PlanPreset).filter(PlanPreset.name == name).first()
|
||||||
|
if preset is None:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Unknown preset: {name}")
|
||||||
|
return dict(preset.modules or {})
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_modules(modules: dict) -> dict:
|
||||||
|
"""Shape check of a module map; the site ignores keys it doesn't know (newer catalogue)."""
|
||||||
|
from services.license_token import normalize_modules
|
||||||
|
from datetime import datetime as _dt
|
||||||
|
if not isinstance(modules, dict):
|
||||||
|
raise HTTPException(status_code=422, detail="modules must be an object")
|
||||||
|
for key, spec in modules.items():
|
||||||
|
if not isinstance(key, str) or not key or not isinstance(spec or {}, dict):
|
||||||
|
raise HTTPException(status_code=422, detail=f"bad module entry {key!r}")
|
||||||
|
for lk, lv in ((spec or {}).get("limits") or {}).items():
|
||||||
|
if lv is not None and (not isinstance(lv, int) or lv < 0):
|
||||||
|
raise HTTPException(status_code=422, detail=f"{key}.{lk}: limit must be a whole number >= 0 or null")
|
||||||
|
if (spec or {}).get("exp"):
|
||||||
|
try:
|
||||||
|
_dt.fromisoformat(str(spec["exp"]).replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=422, detail=f"{key}: exp must be an ISO date-time")
|
||||||
|
return normalize_modules(modules)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/", response_model=list[SiteOut])
|
@router.get("/", response_model=list[SiteOut])
|
||||||
def list_sites(db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
def list_sites(db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
@@ -28,6 +61,7 @@ def create_site(body: SiteCreate, db: Session = Depends(get_db), _=Depends(get_c
|
|||||||
contact_email=body.contact_email,
|
contact_email=body.contact_email,
|
||||||
secret_key_hash=_pwd.hash(raw_key),
|
secret_key_hash=_pwd.hash(raw_key),
|
||||||
license_expires_at=body.license_expires_at,
|
license_expires_at=body.license_expires_at,
|
||||||
|
modules=_preset_modules(db, body.preset),
|
||||||
)
|
)
|
||||||
db.add(site)
|
db.add(site)
|
||||||
db.commit()
|
db.commit()
|
||||||
@@ -50,6 +84,8 @@ def update_site(site_id: str, body: SiteUpdate, db: Session = Depends(get_db), _
|
|||||||
site = db.query(Site).filter(Site.site_id == site_id).first()
|
site = db.query(Site).filter(Site.site_id == site_id).first()
|
||||||
if not site:
|
if not site:
|
||||||
raise HTTPException(status_code=404, detail="Site not found")
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
|
if body.menu_mode is not None and body.menu_mode not in ("order", "view_only"):
|
||||||
|
raise HTTPException(status_code=400, detail="menu_mode must be 'order' or 'view_only'")
|
||||||
for field, value in body.model_dump(exclude_none=True).items():
|
for field, value in body.model_dump(exclude_none=True).items():
|
||||||
setattr(site, field, value)
|
setattr(site, field, value)
|
||||||
db.commit()
|
db.commit()
|
||||||
@@ -57,6 +93,51 @@ def update_site(site_id: str, body: SiteUpdate, db: Session = Depends(get_db), _
|
|||||||
return site
|
return site
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{site_id}/header-image", response_model=SiteOut)
|
||||||
|
async def upload_header_image(site_id: str, file: UploadFile = File(...), db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
|
site = db.query(Site).filter(Site.site_id == site_id).first()
|
||||||
|
if not site:
|
||||||
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
|
|
||||||
|
if not file.content_type or not file.content_type.startswith("image/"):
|
||||||
|
raise HTTPException(status_code=400, detail="File must be an image")
|
||||||
|
|
||||||
|
os.makedirs(HEADER_IMAGE_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
if site.menu_header_image_url:
|
||||||
|
old_path = os.path.join(HEADER_IMAGE_DIR, os.path.basename(site.menu_header_image_url))
|
||||||
|
if os.path.exists(old_path):
|
||||||
|
os.remove(old_path)
|
||||||
|
|
||||||
|
filename = f"{site.site_id}_{uuid.uuid4().hex[:8]}.png"
|
||||||
|
filepath = os.path.join(HEADER_IMAGE_DIR, filename)
|
||||||
|
|
||||||
|
contents = await file.read()
|
||||||
|
with open(filepath, "wb") as f:
|
||||||
|
f.write(contents)
|
||||||
|
|
||||||
|
site.menu_header_image_url = f"/static/site_headers/{filename}"
|
||||||
|
db.commit()
|
||||||
|
db.refresh(site)
|
||||||
|
return site
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{site_id}/header-image", response_model=SiteOut)
|
||||||
|
def delete_header_image(site_id: str, db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
|
site = db.query(Site).filter(Site.site_id == site_id).first()
|
||||||
|
if not site:
|
||||||
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
|
|
||||||
|
if site.menu_header_image_url:
|
||||||
|
old_path = os.path.join(HEADER_IMAGE_DIR, os.path.basename(site.menu_header_image_url))
|
||||||
|
if os.path.exists(old_path):
|
||||||
|
os.remove(old_path)
|
||||||
|
site.menu_header_image_url = None
|
||||||
|
db.commit()
|
||||||
|
db.refresh(site)
|
||||||
|
return site
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{site_id}/lock", response_model=SiteOut)
|
@router.post("/{site_id}/lock", response_model=SiteOut)
|
||||||
def lock_site(site_id: str, body: LockRequest, db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
def lock_site(site_id: str, body: LockRequest, db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
site = db.query(Site).filter(Site.site_id == site_id).first()
|
site = db.query(Site).filter(Site.site_id == site_id).first()
|
||||||
@@ -88,3 +169,31 @@ def delete_site(site_id: str, db: Session = Depends(get_db), _=Depends(get_curre
|
|||||||
raise HTTPException(status_code=404, detail="Site not found")
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
db.delete(site)
|
db.delete(site)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
# ── Licensed modules (APPS_PLATFORM D-3, §5.2) ─────────────────────────────────
|
||||||
|
|
||||||
|
@router.put("/{site_id}/modules", response_model=SiteOut)
|
||||||
|
def set_site_modules(site_id: str, body: SiteModulesUpdate, db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
|
"""Replace the site's module map. The site gets it in its next heartbeat (signed token)."""
|
||||||
|
site = db.query(Site).filter(Site.site_id == site_id).first()
|
||||||
|
if not site:
|
||||||
|
raise HTTPException(status_code=404, detail="Site not found")
|
||||||
|
site.modules = _validate_modules(body.modules)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(site)
|
||||||
|
return site
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{site_id}/apply-preset/{preset_id}", response_model=SiteOut)
|
||||||
|
def apply_preset(site_id: str, preset_id: int, db: Session = Depends(get_db), _=Depends(get_current_admin)):
|
||||||
|
"""Copy a preset's module map into the site (then editable per site)."""
|
||||||
|
from models.plan_preset import PlanPreset
|
||||||
|
site = db.query(Site).filter(Site.site_id == site_id).first()
|
||||||
|
preset = db.get(PlanPreset, preset_id)
|
||||||
|
if not site or not preset:
|
||||||
|
raise HTTPException(status_code=404, detail="Site or preset not found")
|
||||||
|
site.modules = dict(preset.modules or {})
|
||||||
|
db.commit()
|
||||||
|
db.refresh(site)
|
||||||
|
return site
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""The one way the cloud schema is created and upgraded: Alembic (APPS_PLATFORM D-22).
|
||||||
|
|
||||||
|
v1 used create_all + an ALTER list in main.py (_run_migrations); both are gone on
|
||||||
|
platform-v2. The production database predates Alembic: at cutover it is STAMPED to
|
||||||
|
0001_cloud_baseline (the exact v1 schema) and then upgraded (DEPLOYMENT_GUIDE.md,
|
||||||
|
"Platform v2 cutover"). Until it is stamped, startup refuses it, so the v2 cloud can
|
||||||
|
never half-migrate production by accident.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from alembic import command
|
||||||
|
from alembic.config import Config
|
||||||
|
from sqlalchemy import inspect
|
||||||
|
|
||||||
|
logger = logging.getLogger("cloud.schema")
|
||||||
|
MIGRATIONS_DIR = Path(__file__).resolve().parent / "migrations"
|
||||||
|
BASELINE = "0001_cloud_baseline"
|
||||||
|
|
||||||
|
|
||||||
|
class UnstampedDatabaseError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def alembic_config(connection=None) -> Config:
|
||||||
|
cfg = Config()
|
||||||
|
cfg.set_main_option("script_location", str(MIGRATIONS_DIR))
|
||||||
|
cfg.set_main_option("file_template", "%%(rev)s")
|
||||||
|
if connection is not None:
|
||||||
|
cfg.attributes["connection"] = connection
|
||||||
|
return cfg
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade_to_head(engine=None) -> None:
|
||||||
|
if engine is None:
|
||||||
|
from database import engine as app_engine
|
||||||
|
engine = app_engine
|
||||||
|
with engine.begin() as conn:
|
||||||
|
tables = set(inspect(conn).get_table_names())
|
||||||
|
if tables and "alembic_version" not in tables:
|
||||||
|
raise UnstampedDatabaseError(
|
||||||
|
"This cloud database predates Alembic (v1). Back it up, then run "
|
||||||
|
f"`alembic stamp {BASELINE}` once (DEPLOYMENT_GUIDE.md, Platform v2 cutover).")
|
||||||
|
command.upgrade(alembic_config(conn), "head")
|
||||||
|
logger.info("schema upgraded to head")
|
||||||
|
|
||||||
|
|
||||||
|
def stamp_baseline(engine) -> None:
|
||||||
|
"""Cutover helper: mark a v1 production DB as being at the baseline revision."""
|
||||||
|
with engine.begin() as conn:
|
||||||
|
command.stamp(alembic_config(conn), BASELINE)
|
||||||
@@ -8,7 +8,7 @@ class ManagerRegisterRequest(BaseModel):
|
|||||||
email: str
|
email: str
|
||||||
password: str
|
password: str
|
||||||
full_name: Optional[str] = None
|
full_name: Optional[str] = None
|
||||||
site_ids: list[int] = []
|
site_ids: list[str] = [] # site_id UUID strings, not integer PKs
|
||||||
|
|
||||||
|
|
||||||
class ManagerLoginRequest(BaseModel):
|
class ManagerLoginRequest(BaseModel):
|
||||||
|
|||||||
@@ -1,39 +1,83 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from pydantic import BaseModel
|
from datetime import timezone
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field, field_serializer
|
||||||
|
|
||||||
|
|
||||||
|
def _utc(value):
|
||||||
|
"""The cloud's database keeps no time zone: a naive datetime is UTC. Sent with its offset."""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return (value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value).isoformat()
|
||||||
|
|
||||||
|
|
||||||
class OrderItemIn(BaseModel):
|
class OrderItemIn(BaseModel):
|
||||||
|
"""What the customer wants. Prices come from the venue's menu (services/checkout.py);
|
||||||
|
name and unit_price, if sent, are only compared (phase 3S, S.2)."""
|
||||||
product_id: int
|
product_id: int
|
||||||
name: str
|
|
||||||
quantity: int
|
quantity: int
|
||||||
unit_price: float
|
name: Optional[str] = None
|
||||||
options: list = []
|
unit_price: Optional[float] = None
|
||||||
|
options: list = [] # quick option ids (or {id})
|
||||||
|
|
||||||
|
|
||||||
|
class QuoteRequest(BaseModel):
|
||||||
|
order_type: str # dine_in | takeaway | delivery | preorder
|
||||||
|
items: list[OrderItemIn] = Field(max_length=100)
|
||||||
|
area_id: Optional[int] = None # the delivery area picked (S.3)
|
||||||
|
postcode: Optional[str] = Field(default=None, max_length=20)
|
||||||
|
lat: Optional[float] = Field(default=None, ge=-90, le=90) # 6R.G: the customer's pin on the map
|
||||||
|
lng: Optional[float] = Field(default=None, ge=-180, le=180)
|
||||||
|
|
||||||
|
|
||||||
class OnlineOrderCreate(BaseModel):
|
class OnlineOrderCreate(BaseModel):
|
||||||
order_type: str # "delivery" | "dine_in"
|
order_type: str # dine_in | takeaway | delivery | reservation | preorder
|
||||||
customer_name: str
|
customer_name: str = Field(min_length=1, max_length=100)
|
||||||
customer_phone: Optional[str] = None
|
party_size: Optional[int] = None # reservations (S.6)
|
||||||
customer_address: Optional[str] = None
|
customer_phone: Optional[str] = Field(default=None, max_length=40)
|
||||||
customer_notes: Optional[str] = None
|
customer_address: Optional[str] = Field(default=None, max_length=500)
|
||||||
items: list[OrderItemIn]
|
customer_notes: Optional[str] = Field(default=None, max_length=1000)
|
||||||
subtotal: float
|
customer_table: Optional[str] = Field(default=None, max_length=40) # ignored since S.7 (the token says)
|
||||||
delivery_fee: float = 0.0
|
table_token: Optional[str] = Field(default=None, max_length=100) # the table's QR token (S.7)
|
||||||
total: float
|
area_id: Optional[int] = None # the delivery area picked (S.3)
|
||||||
|
postcode: Optional[str] = Field(default=None, max_length=20)
|
||||||
|
lat: Optional[float] = Field(default=None, ge=-90, le=90) # 6R.G: the customer's pin on the map
|
||||||
|
lng: Optional[float] = Field(default=None, ge=-180, le=180)
|
||||||
|
requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible
|
||||||
|
items: list[OrderItemIn] = Field(default_factory=list, max_length=100)
|
||||||
|
# what the customer was shown: compared, never stored as sent
|
||||||
|
subtotal: Optional[float] = None
|
||||||
|
delivery_fee: Optional[float] = None
|
||||||
|
total: Optional[float] = None
|
||||||
|
|
||||||
|
|
||||||
class OnlineOrderCreated(BaseModel):
|
class OnlineOrderCreated(BaseModel):
|
||||||
order_id: int
|
order_id: int
|
||||||
public_ref: str
|
public_ref: str
|
||||||
status: str
|
status: str
|
||||||
|
tracking_token: Optional[str] = None # the tracking page: GET /api/orders/track/{token} (S.2)
|
||||||
|
total: Optional[float] = None
|
||||||
|
|
||||||
|
|
||||||
class OrderStatusOut(BaseModel):
|
class OrderStatusOut(BaseModel):
|
||||||
public_ref: str
|
public_ref: str
|
||||||
status: str
|
status: str
|
||||||
rejection_reason: Optional[str] = None
|
rejection_reason: Optional[str] = None
|
||||||
|
# S.4: what the tracking page shows (all optional: older clients ignore them)
|
||||||
|
order_type: Optional[str] = None
|
||||||
|
requested_for: Optional[datetime] = None
|
||||||
|
party_size: Optional[int] = None # reservations (S.6)
|
||||||
|
created_at: Optional[datetime] = None
|
||||||
|
lines: Optional[list] = None
|
||||||
|
subtotal: Optional[float] = None
|
||||||
|
delivery_fee: Optional[float] = None
|
||||||
|
total: Optional[float] = None
|
||||||
|
|
||||||
|
@field_serializer('requested_for', 'created_at')
|
||||||
|
def _times(self, value):
|
||||||
|
return _utc(value)
|
||||||
|
|
||||||
|
|
||||||
class PendingOrderOut(BaseModel):
|
class PendingOrderOut(BaseModel):
|
||||||
@@ -44,6 +88,15 @@ class PendingOrderOut(BaseModel):
|
|||||||
customer_phone: Optional[str] = None
|
customer_phone: Optional[str] = None
|
||||||
customer_address: Optional[str] = None
|
customer_address: Optional[str] = None
|
||||||
customer_notes: Optional[str] = None
|
customer_notes: Optional[str] = None
|
||||||
|
table_label: Optional[str] = None # the QR menu's table (S.2)
|
||||||
|
table_id: Optional[int] = None # the site's table, from a valid QR token (S.7)
|
||||||
|
delivery_area: Optional[str] = None # the delivery area's name (S.3)
|
||||||
|
delivery_area_id: Optional[int] = None # the site's area id (S.5)
|
||||||
|
lat: Optional[float] = None # 6R.G: the customer's pin
|
||||||
|
lng: Optional[float] = None
|
||||||
|
requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible
|
||||||
|
party_size: Optional[int] = None # reservations (S.6)
|
||||||
|
sales_point: Optional[str] = None # the site's sales point (S.2)
|
||||||
items_json: str
|
items_json: str
|
||||||
subtotal: float
|
subtotal: float
|
||||||
delivery_fee: float
|
delivery_fee: float
|
||||||
@@ -53,6 +106,10 @@ class PendingOrderOut(BaseModel):
|
|||||||
|
|
||||||
model_config = {"from_attributes": True}
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
@field_serializer('requested_for', 'created_at')
|
||||||
|
def _times(self, value):
|
||||||
|
return _utc(value)
|
||||||
|
|
||||||
|
|
||||||
class OrderSyncedRequest(BaseModel):
|
class OrderSyncedRequest(BaseModel):
|
||||||
local_order_id: int
|
local_order_id: int
|
||||||
|
|||||||
@@ -7,6 +7,12 @@ class SiteCreate(BaseModel):
|
|||||||
owner_name: str
|
owner_name: str
|
||||||
contact_email: str
|
contact_email: str
|
||||||
license_expires_at: datetime
|
license_expires_at: datetime
|
||||||
|
preset: str | None = "Everything (v1 sites)" # plan preset to fill `modules`; None = nothing licensed
|
||||||
|
|
||||||
|
|
||||||
|
class SiteModulesUpdate(BaseModel):
|
||||||
|
"""The whole module map: {key: {limits?: {name: int|null}, exp?: ISO datetime}}."""
|
||||||
|
modules: dict
|
||||||
|
|
||||||
|
|
||||||
class SiteUpdate(BaseModel):
|
class SiteUpdate(BaseModel):
|
||||||
@@ -15,6 +21,13 @@ class SiteUpdate(BaseModel):
|
|||||||
contact_email: str | None = None
|
contact_email: str | None = None
|
||||||
license_expires_at: datetime | None = None
|
license_expires_at: datetime | None = None
|
||||||
waiter_domain: str | None = None
|
waiter_domain: str | None = None
|
||||||
|
menu_mode: str | None = None
|
||||||
|
menu_display_name: str | None = None
|
||||||
|
menu_tagline_en: str | None = None
|
||||||
|
menu_tagline_gr: str | None = None
|
||||||
|
menu_blurb_en: str | None = None
|
||||||
|
menu_blurb_gr: str | None = None
|
||||||
|
menu_hours: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class SiteOut(BaseModel):
|
class SiteOut(BaseModel):
|
||||||
@@ -28,10 +41,22 @@ class SiteOut(BaseModel):
|
|||||||
lock_reason: str | None
|
lock_reason: str | None
|
||||||
license_expires_at: datetime
|
license_expires_at: datetime
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
modules: dict = {}
|
||||||
|
module_catalog: list | None = None
|
||||||
|
module_catalog_at: datetime | None = None
|
||||||
last_seen_at: datetime | None
|
last_seen_at: datetime | None
|
||||||
last_seen_ip: str | None
|
last_seen_ip: str | None
|
||||||
last_seen_local_ip: str | None
|
last_seen_local_ip: str | None
|
||||||
waiter_domain: str | None
|
waiter_domain: str | None
|
||||||
|
menu_mode: str
|
||||||
|
menu_display_name: str | None
|
||||||
|
menu_tagline_en: str | None
|
||||||
|
menu_tagline_gr: str | None
|
||||||
|
menu_blurb_en: str | None
|
||||||
|
menu_blurb_gr: str | None
|
||||||
|
menu_hours: str | None
|
||||||
|
menu_header_image_url: str | None
|
||||||
|
apps_url: str | None = None # PUBLIC_APPS_URL: the customer apps' address (phase 3S)
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
@@ -45,16 +70,18 @@ class LockRequest(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class HeartbeatRequest(BaseModel):
|
class HeartbeatRequest(BaseModel):
|
||||||
version: str = "1.0.0"
|
"""C-1 v2 (docs/reference/cloud-contract.md)."""
|
||||||
uptime_seconds: int = 0
|
version: str
|
||||||
local_ip: str | None = None
|
local_ip: str | None = None
|
||||||
|
# The modules this site's code knows (D-20): [{key, kind, name, depends, limits: [{key, ...}]}]
|
||||||
|
module_catalog: list[dict] = []
|
||||||
|
|
||||||
|
|
||||||
class HeartbeatResponse(BaseModel):
|
class HeartbeatResponse(BaseModel):
|
||||||
licensed: bool
|
# Signed v2 license the site stores and enforces offline (services/license_token.py).
|
||||||
locked: bool
|
# Everything about licensing is inside it; there are no unsigned license fields.
|
||||||
lock_reason: str | None
|
license_token: str | None
|
||||||
expires_at: datetime
|
|
||||||
latest_version: str | None = None
|
latest_version: str | None = None
|
||||||
waiter_domain: str | None = None
|
waiter_domain: str | None = None
|
||||||
site_numeric_id: int | None = None # cloud DB pk — needed by Connect sync loops
|
site_numeric_id: int # cloud DB pk — needed by the Connect workers
|
||||||
|
apps_url: str | None = None # the customer apps' public address (S.7; table QR codes)
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""The cloud prices online orders itself (plan phase 3S, step S.2).
|
||||||
|
|
||||||
|
The customer's browser sends what it wants (product ids, quantities, chosen quick options);
|
||||||
|
the price of everything comes from the venue's menu snapshot (pushed by the site), for the
|
||||||
|
order's sales point. A total the browser sends is only compared: a difference means the
|
||||||
|
customer saw old prices (or edited them) and the order is refused with the current ones.
|
||||||
|
|
||||||
|
price_cart(snapshot, order_type, items) -> Priced
|
||||||
|
CheckoutError(status, code, **params) the router turns it into {"detail": {code, params}}
|
||||||
|
|
||||||
|
Snapshot product (site services/cloud_sync._push_menu_snapshot):
|
||||||
|
{id, name, digital_name, base_price, digital_price, digital_discount, digital_available,
|
||||||
|
sold_at: [sales point], prices: {sales point: price}, quick_options: [{id, name, price}]}
|
||||||
|
Snapshots from before S.2 have no `prices` / `sold_at`: every customer-app sales point, at
|
||||||
|
digital_price (or base_price) less digital_discount %.
|
||||||
|
|
||||||
|
The fee (S.3): the snapshot's `fees` {areas, rules} through services/fees.py (the same file
|
||||||
|
as the site's) at the venue's time (`timezone`). A delivery outside the venue's areas ->
|
||||||
|
order.area_not_served; below a minimum -> order.minimum_not_met {minimum, subtotal}.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from services import fees as fee_engine
|
||||||
|
|
||||||
|
# the cloud order's type → the site's sales point (core/sales_points.py)
|
||||||
|
POINT_FOR_TYPE = {
|
||||||
|
"dine_in": "qr_table",
|
||||||
|
"takeaway": "online_takeaway",
|
||||||
|
"delivery": "online_delivery",
|
||||||
|
"preorder": "online_preorder",
|
||||||
|
}
|
||||||
|
DIGITAL = tuple(POINT_FOR_TYPE.values())
|
||||||
|
MAX_QTY = 99
|
||||||
|
MAX_LINES = 100
|
||||||
|
EPS = 0.005
|
||||||
|
|
||||||
|
|
||||||
|
class CheckoutError(Exception):
|
||||||
|
def __init__(self, status: int, code: str, **params):
|
||||||
|
super().__init__(code)
|
||||||
|
self.status, self.code, self.params = status, code, params
|
||||||
|
|
||||||
|
def detail(self) -> dict:
|
||||||
|
return {"code": self.code, "params": self.params}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Line:
|
||||||
|
product_id: int
|
||||||
|
name: str
|
||||||
|
quantity: int
|
||||||
|
unit_price: float
|
||||||
|
options: list = field(default_factory=list) # [{id, name, price}]
|
||||||
|
|
||||||
|
def out(self) -> dict:
|
||||||
|
return {"product_id": self.product_id, "name": self.name, "quantity": self.quantity,
|
||||||
|
"unit_price": self.unit_price, "options": self.options}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Priced:
|
||||||
|
sales_point: str
|
||||||
|
lines: list
|
||||||
|
subtotal: float
|
||||||
|
delivery_fee: float
|
||||||
|
total: float
|
||||||
|
area_id: int | None = None
|
||||||
|
area_name: str | None = None
|
||||||
|
fee_rules: list = field(default_factory=list) # names of the rules that applied
|
||||||
|
|
||||||
|
def out(self) -> dict:
|
||||||
|
return {"sales_point": self.sales_point, "lines": [x.out() for x in self.lines],
|
||||||
|
"subtotal": self.subtotal, "delivery_fee": self.delivery_fee, "total": self.total,
|
||||||
|
"area_id": self.area_id, "area_name": self.area_name, "fee_rules": self.fee_rules}
|
||||||
|
|
||||||
|
|
||||||
|
def venue_clock(snapshot: dict, now: datetime | None = None) -> tuple[int, str]:
|
||||||
|
"""(weekday Mon=0, "HH:MM") at the venue, from the snapshot's time zone."""
|
||||||
|
try:
|
||||||
|
tz = ZoneInfo(snapshot.get("timezone") or "Europe/Athens")
|
||||||
|
except Exception:
|
||||||
|
tz = ZoneInfo("Europe/Athens")
|
||||||
|
local = (now or datetime.now(timezone.utc)).astimezone(tz)
|
||||||
|
return local.weekday(), local.strftime("%H:%M")
|
||||||
|
|
||||||
|
|
||||||
|
def delivery_areas(snapshot: dict) -> list:
|
||||||
|
"""The active areas: [{id, name, kind}] (no postcodes, no rules). A postcode area is picked
|
||||||
|
from a list; a shape (6R.G: polygon / circle) also gives its geometry, so the customer's map
|
||||||
|
can draw where the venue delivers; the cloud matches it by the customer's pin."""
|
||||||
|
out = []
|
||||||
|
for a in (snapshot.get("fees") or {}).get("areas") or []:
|
||||||
|
if not a.get("is_active", True):
|
||||||
|
continue
|
||||||
|
kind = a.get("kind") or "postcodes"
|
||||||
|
item = {"id": a.get("id"), "name": a.get("name"), "kind": kind}
|
||||||
|
if kind in fee_engine.SHAPES:
|
||||||
|
item["geometry"] = a.get("geometry")
|
||||||
|
out.append(item)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def venue_point(snapshot: dict):
|
||||||
|
"""The venue's place on the map (6R.G): {lat, lng} or None; the customer's map starts there."""
|
||||||
|
return (snapshot.get("fees") or {}).get("venue_point")
|
||||||
|
|
||||||
|
|
||||||
|
def products_of(snapshot: dict) -> dict[int, dict]:
|
||||||
|
out: dict[int, dict] = {}
|
||||||
|
for cat in snapshot.get("categories", []):
|
||||||
|
for p in cat.get("products", []):
|
||||||
|
if isinstance(p.get("id"), int):
|
||||||
|
out.setdefault(p["id"], p) # a product listed in several categories: once
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def price_at(product: dict, point: str) -> float | None:
|
||||||
|
"""The product's price at a sales point; None = not sold there."""
|
||||||
|
sold = product.get("sold_at")
|
||||||
|
if sold is not None and point not in sold:
|
||||||
|
return None
|
||||||
|
prices = product.get("prices")
|
||||||
|
if prices is not None:
|
||||||
|
value = prices.get(point)
|
||||||
|
return None if value is None else round(float(value), 2)
|
||||||
|
base = product.get("digital_price")
|
||||||
|
if base is None:
|
||||||
|
base = product.get("base_price") or 0.0
|
||||||
|
pct = product.get("digital_discount") or 0.0
|
||||||
|
return round(float(base) * (1 - float(pct) / 100.0), 2)
|
||||||
|
|
||||||
|
|
||||||
|
def _display_name(product: dict) -> str:
|
||||||
|
name = product.get("digital_name") or product.get("name") or f"#{product.get('id')}"
|
||||||
|
return name if isinstance(name, str) else str(name)
|
||||||
|
|
||||||
|
|
||||||
|
def _option_ids(raw) -> list:
|
||||||
|
out = []
|
||||||
|
for o in raw or []:
|
||||||
|
oid = o.get("id") if isinstance(o, dict) else o
|
||||||
|
if not isinstance(oid, int) or isinstance(oid, bool):
|
||||||
|
raise CheckoutError(422, "order.option_unavailable", option_id=oid)
|
||||||
|
out.append(oid)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def price_cart(snapshot: dict, order_type: str, items: list[dict], area_id=None, postcode=None,
|
||||||
|
now: datetime | None = None, pin=None) -> Priced:
|
||||||
|
"""Price the cart from the snapshot. items: [{product_id, quantity, options?}]; the
|
||||||
|
customer's area (picked, by their `pin` [lat, lng] on the map (6R.G), or by postcode) for the fee."""
|
||||||
|
point = POINT_FOR_TYPE.get(order_type)
|
||||||
|
if point is None:
|
||||||
|
raise CheckoutError(422, "order.type_invalid", order_type=order_type)
|
||||||
|
if not items:
|
||||||
|
raise CheckoutError(422, "order.empty")
|
||||||
|
if len(items) > MAX_LINES:
|
||||||
|
raise CheckoutError(422, "order.too_many_lines", max=MAX_LINES)
|
||||||
|
products = products_of(snapshot)
|
||||||
|
lines = []
|
||||||
|
for it in items:
|
||||||
|
pid, qty = it.get("product_id"), it.get("quantity")
|
||||||
|
if isinstance(qty, bool) or not isinstance(qty, int) or not 1 <= qty <= MAX_QTY:
|
||||||
|
raise CheckoutError(422, "order.quantity_invalid", product_id=pid, max=MAX_QTY)
|
||||||
|
product = products.get(pid) if isinstance(pid, int) else None
|
||||||
|
unit = price_at(product, point) if product is not None else None
|
||||||
|
if product is None or unit is None or product.get("digital_available") is False:
|
||||||
|
raise CheckoutError(409, "order.item_unavailable", product_id=pid,
|
||||||
|
name=_display_name(product) if product else None)
|
||||||
|
quick = {q.get("id"): q for q in product.get("quick_options") or [] if isinstance(q, dict)}
|
||||||
|
options = []
|
||||||
|
for oid in _option_ids(it.get("options")):
|
||||||
|
q = quick.get(oid)
|
||||||
|
if q is None:
|
||||||
|
raise CheckoutError(409, "order.option_unavailable", product_id=pid, option_id=oid)
|
||||||
|
options.append({"id": oid, "name": q.get("name"), "price": round(float(q.get("price") or 0.0), 2)})
|
||||||
|
unit = round(unit + sum(o["price"] for o in options), 2)
|
||||||
|
lines.append(Line(product_id=pid, name=_display_name(product), quantity=qty, unit_price=unit, options=options))
|
||||||
|
subtotal = round(sum(x.unit_price * x.quantity for x in lines), 2)
|
||||||
|
rules = snapshot.get("fees") or {}
|
||||||
|
weekday, hhmm = venue_clock(snapshot, now)
|
||||||
|
result = fee_engine.compute(rules.get("rules") or [], rules.get("areas") or [], sales_point=point,
|
||||||
|
subtotal=subtotal, items=sum(x.quantity for x in lines),
|
||||||
|
area_id=area_id, postcode=postcode, weekday=weekday, hhmm=hhmm,
|
||||||
|
point=pin)
|
||||||
|
if result["refused"] == "area_not_served":
|
||||||
|
raise CheckoutError(409, "order.area_not_served", postcode=postcode, area_id=area_id)
|
||||||
|
if result["refused"] == "minimum_not_met":
|
||||||
|
raise CheckoutError(409, "order.minimum_not_met", minimum=result["minimum"], subtotal=subtotal)
|
||||||
|
fee = result["fee"]
|
||||||
|
area = next((a for a in rules.get("areas") or [] if a.get("id") == result["area_id"]), None)
|
||||||
|
return Priced(sales_point=point, lines=lines, subtotal=subtotal, delivery_fee=fee, total=round(subtotal + fee, 2),
|
||||||
|
area_id=result["area_id"], area_name=area.get("name") if area else None,
|
||||||
|
fee_rules=[a["name"] for a in result["applied"] if a["action"] != "minimum"])
|
||||||
|
|
||||||
|
|
||||||
|
def check_sent(priced: Priced, items: list[dict], total: float | None) -> None:
|
||||||
|
"""What the browser showed must be what we charge: each line's unit price (if sent) and
|
||||||
|
the total (if sent). Otherwise order.price_changed with the current prices."""
|
||||||
|
changed = total is not None and abs(float(total) - priced.total) > EPS
|
||||||
|
for sent, line in zip(items, priced.lines):
|
||||||
|
up = sent.get("unit_price")
|
||||||
|
if up is not None and abs(float(up) - line.unit_price) > EPS:
|
||||||
|
changed = True
|
||||||
|
if changed:
|
||||||
|
raise CheckoutError(409, "order.price_changed", **priced.out())
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"""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, point=None) -> {"fee", "refused", "minimum", "area_id", "applied"}
|
||||||
|
|
||||||
|
Areas: {id, name, kind, postcodes: [str], geometry, is_active}. `kind` (6R.G; missing =
|
||||||
|
"postcodes"): "postcodes" (a list), "polygon" (geometry [[lat, lng], …], at least 3 corners) or
|
||||||
|
"circle" (geometry {"center": [lat, lng], "radius_m": metres}). The customer's area, in this order:
|
||||||
|
1. the one picked (by id); a shape (polygon / circle) only when the customer's `point`
|
||||||
|
[lat, lng] lies in it (a pin is the only proof of where a shape delivery goes);
|
||||||
|
2. by `point`: the first active shape that holds it (on its edge counts as inside);
|
||||||
|
3. by postcode: the first active postcode area that lists 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. A point is inside a polygon by the even-odd rule on
|
||||||
|
latitude / longitude (fine for a village or a town); inside a circle when the great-circle
|
||||||
|
(haversine) distance to its centre is at most its radius.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
|
EPS = 0.0005
|
||||||
|
ACTIONS = ("set", "add", "percent", "free", "minimum")
|
||||||
|
SHAPES = ("polygon", "circle")
|
||||||
|
EARTH_M = 6371008.8 # mean Earth radius, metres
|
||||||
|
EDGE = 1e-9 # degrees: a point this close to an edge is on it
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_postcode(value) -> str:
|
||||||
|
return "".join(str(value or "").split()).upper()
|
||||||
|
|
||||||
|
|
||||||
|
def _point(value):
|
||||||
|
"""[lat, lng] as two floats, or None when it isn't a usable point."""
|
||||||
|
try:
|
||||||
|
lat, lng = float(value[0]), float(value[1])
|
||||||
|
except (TypeError, ValueError, IndexError, KeyError):
|
||||||
|
return None
|
||||||
|
if not (math.isfinite(lat) and math.isfinite(lng)) or abs(lat) > 90 or abs(lng) > 180:
|
||||||
|
return None
|
||||||
|
return lat, lng
|
||||||
|
|
||||||
|
|
||||||
|
def _on_segment(p, a, b) -> bool:
|
||||||
|
(y, x), (y1, x1), (y2, x2) = p, a, b
|
||||||
|
cross = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)
|
||||||
|
if abs(cross) > EDGE * max(1.0, abs(x2 - x1) + abs(y2 - y1)):
|
||||||
|
return False
|
||||||
|
return min(x1, x2) - EDGE <= x <= max(x1, x2) + EDGE and min(y1, y2) - EDGE <= y <= max(y1, y2) + EDGE
|
||||||
|
|
||||||
|
|
||||||
|
def in_polygon(point, corners) -> bool:
|
||||||
|
"""Even-odd rule on (lat, lng); a point on an edge or a corner is inside."""
|
||||||
|
pts = [c for c in (_point(c) for c in corners or []) if c is not None]
|
||||||
|
p = _point(point)
|
||||||
|
if p is None or len(pts) < 3:
|
||||||
|
return False
|
||||||
|
lat, lng = p
|
||||||
|
inside = False
|
||||||
|
for i in range(len(pts)):
|
||||||
|
a, b = pts[i], pts[i - 1]
|
||||||
|
if _on_segment(p, a, b):
|
||||||
|
return True
|
||||||
|
if (a[0] > lat) != (b[0] > lat):
|
||||||
|
cross_lng = a[1] + (lat - a[0]) * (b[1] - a[1]) / (b[0] - a[0])
|
||||||
|
if lng < cross_lng:
|
||||||
|
inside = not inside
|
||||||
|
return inside
|
||||||
|
|
||||||
|
|
||||||
|
def distance_m(a, b) -> float:
|
||||||
|
"""Great-circle (haversine) distance in metres between two [lat, lng] points."""
|
||||||
|
(lat1, lng1), (lat2, lng2) = _point(a), _point(b)
|
||||||
|
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||||
|
dp, dl = p2 - p1, math.radians(lng2 - lng1)
|
||||||
|
h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
||||||
|
return 2 * EARTH_M * math.asin(min(1.0, math.sqrt(h)))
|
||||||
|
|
||||||
|
|
||||||
|
def holds(area, point) -> bool:
|
||||||
|
"""Does a shape area hold the point? (A postcode area never does.)"""
|
||||||
|
if _point(point) is None:
|
||||||
|
return False
|
||||||
|
kind, geo = area.get("kind") or "postcodes", area.get("geometry")
|
||||||
|
if kind == "polygon":
|
||||||
|
return in_polygon(point, geo)
|
||||||
|
if kind == "circle" and isinstance(geo, dict) and _point(geo.get("center")) is not None:
|
||||||
|
try:
|
||||||
|
radius = float(geo.get("radius_m"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
return radius > 0 and distance_m(point, geo["center"]) <= radius + 0.01
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_area(areas: list, area_id=None, postcode=None, point=None):
|
||||||
|
"""The customer's active area: picked by id (a shape only with a point inside it), else the
|
||||||
|
first shape holding the point, else by postcode; None when nothing 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 and ((a.get("kind") or "postcodes") not in SHAPES or holds(a, point)):
|
||||||
|
return a
|
||||||
|
if _point(point) is not None:
|
||||||
|
for a in active:
|
||||||
|
if (a.get("kind") or "postcodes") in SHAPES and holds(a, point):
|
||||||
|
return a
|
||||||
|
code = _norm_postcode(postcode)
|
||||||
|
if code:
|
||||||
|
for a in active:
|
||||||
|
if (a.get("kind") or "postcodes") not in SHAPES and 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, point=None) -> dict:
|
||||||
|
area = resolve_area(areas, area_id, postcode, point)
|
||||||
|
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
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""
|
||||||
|
Signed license tokens for on-site servers (client-services KI-006).
|
||||||
|
|
||||||
|
Every heartbeat answer carries a token the site stores and verifies with the
|
||||||
|
public key built into its code. The site then enforces the license OFFLINE:
|
||||||
|
it keeps running until `expires_at` (+ its grace), however long it is without
|
||||||
|
internet, and nobody can extend it by editing the stored copy.
|
||||||
|
|
||||||
|
Format: <base64url(payload JSON)>.<base64url(Ed25519 signature of the first part)>
|
||||||
|
Payload v2 (platform v2, D-3, D-21; v2 sites accept nothing else):
|
||||||
|
{ v: 2, site_id, active, locked, lock_reason, expires_at, issued_at,
|
||||||
|
modules: { <module key>: { limits?: {name: int|null}, exp?: ISO } } }
|
||||||
|
`modules` comes from sites.modules (sysadmin panel). A module missing from the map is
|
||||||
|
not licensed (the site's free tier still applies). null limit = unlimited.
|
||||||
|
issued_at = the cloud's clock — the site uses it as a floor against clock rollback.
|
||||||
|
|
||||||
|
Key: LICENSE_SIGNING_KEY in the cloud .env (base64 raw Ed25519 private key,
|
||||||
|
generated once; see docs). Without it, heartbeats carry no token — old-style
|
||||||
|
behaviour — and a warning is logged.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||||
|
|
||||||
|
from config import settings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
_key: Ed25519PrivateKey | None = None
|
||||||
|
_warned = False
|
||||||
|
|
||||||
|
|
||||||
|
def _b64url(data: bytes) -> str:
|
||||||
|
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
|
||||||
|
|
||||||
|
|
||||||
|
def _signing_key() -> Ed25519PrivateKey | None:
|
||||||
|
global _key, _warned
|
||||||
|
if _key is None and settings.LICENSE_SIGNING_KEY:
|
||||||
|
_key = Ed25519PrivateKey.from_private_bytes(base64.b64decode(settings.LICENSE_SIGNING_KEY))
|
||||||
|
if _key is None and not _warned:
|
||||||
|
logger.warning("LICENSE_SIGNING_KEY not set — heartbeats carry no signed license token")
|
||||||
|
_warned = True
|
||||||
|
return _key
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(dt: datetime) -> str:
|
||||||
|
return (dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)).astimezone(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_modules(raw: dict) -> dict:
|
||||||
|
"""Clean a module map for the token: only `limits` and `exp`, limits int or None."""
|
||||||
|
out = {}
|
||||||
|
for key, spec in (raw or {}).items():
|
||||||
|
spec = spec or {}
|
||||||
|
entry = {}
|
||||||
|
limits = {k: (None if v is None else int(v)) for k, v in (spec.get("limits") or {}).items()}
|
||||||
|
if limits:
|
||||||
|
entry["limits"] = limits
|
||||||
|
if spec.get("exp"):
|
||||||
|
entry["exp"] = spec["exp"]
|
||||||
|
out[key] = entry
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def issue_license_token(site, now: datetime) -> str | None:
|
||||||
|
key = _signing_key()
|
||||||
|
if key is None:
|
||||||
|
return None
|
||||||
|
payload = {
|
||||||
|
"v": 2,
|
||||||
|
"site_id": site.site_id,
|
||||||
|
"active": bool(site.is_active),
|
||||||
|
"locked": bool(site.is_locked),
|
||||||
|
"lock_reason": site.lock_reason,
|
||||||
|
"expires_at": _iso(site.license_expires_at),
|
||||||
|
"issued_at": _iso(now),
|
||||||
|
"modules": normalize_modules(site.modules or {}),
|
||||||
|
}
|
||||||
|
body = _b64url(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
|
||||||
|
return f"{body}.{_b64url(key.sign(body.encode()))}"
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
"""When online orders are taken (plan phase 3S, step S.4).
|
||||||
|
|
||||||
|
The venue's settings travel with the menu snapshot (`ordering`, site routers/fees.py
|
||||||
|
OrderingBody) and are enforced here at checkout:
|
||||||
|
|
||||||
|
{services: ["takeaway", "delivery"], hours: {"0".."6": [["HH:MM", "HH:MM"], ...]},
|
||||||
|
prep_minutes, slot_minutes, days_ahead, asap}
|
||||||
|
|
||||||
|
- a service not in `services` → order.service_unavailable
|
||||||
|
- hours: none at all = any time; otherwise a day without ranges is closed; a range whose end
|
||||||
|
is before its start runs past midnight into the next day
|
||||||
|
- "as soon as possible" (no requested time): only while open now, and only if `asap`
|
||||||
|
- a requested time: one of slots() — on the slot grid (every slot_minutes from local
|
||||||
|
midnight), at least prep_minutes from now, within today + days_ahead, while open
|
||||||
|
Times are the venue's local time (the snapshot's `timezone`).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
DEFAULTS = {"services": [], "hours": {}, "prep_minutes": 20, "slot_minutes": 15, "days_ahead": 0, "asap": True}
|
||||||
|
MAX_SLOTS = 300
|
||||||
|
|
||||||
|
|
||||||
|
def config(snapshot: dict) -> dict:
|
||||||
|
cfg = {**DEFAULTS, **(snapshot.get("ordering") or {})}
|
||||||
|
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 15))
|
||||||
|
cfg["prep_minutes"] = max(0, int(cfg.get("prep_minutes") or 0))
|
||||||
|
cfg["days_ahead"] = max(0, min(7, int(cfg.get("days_ahead") or 0)))
|
||||||
|
return cfg
|
||||||
|
|
||||||
|
|
||||||
|
def venue_tz(snapshot: dict) -> ZoneInfo:
|
||||||
|
try:
|
||||||
|
return ZoneInfo(snapshot.get("timezone") or "Europe/Athens")
|
||||||
|
except Exception:
|
||||||
|
return ZoneInfo("Europe/Athens")
|
||||||
|
|
||||||
|
|
||||||
|
def _mins(hhmm: str) -> int:
|
||||||
|
h, m = hhmm.split(":")
|
||||||
|
return int(h) * 60 + int(m)
|
||||||
|
|
||||||
|
|
||||||
|
def is_open(cfg: dict, local: datetime) -> bool:
|
||||||
|
hours = cfg.get("hours") or {}
|
||||||
|
if not hours:
|
||||||
|
return True
|
||||||
|
t = local.hour * 60 + local.minute
|
||||||
|
today, yesterday = str(local.weekday()), str((local.weekday() - 1) % 7)
|
||||||
|
for start, end in hours.get(today, []):
|
||||||
|
s, e = _mins(start), _mins(end)
|
||||||
|
if (s < e and s <= t < e) or (s > e and t >= s):
|
||||||
|
return True
|
||||||
|
for start, end in hours.get(yesterday, []):
|
||||||
|
s, e = _mins(start), _mins(end)
|
||||||
|
if s > e and t < e: # yesterday's range running past midnight
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _first_slot(cfg: dict, local_now: datetime) -> datetime:
|
||||||
|
earliest = local_now + timedelta(minutes=cfg["prep_minutes"])
|
||||||
|
step = cfg["slot_minutes"]
|
||||||
|
midnight = earliest.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||||
|
mins = (earliest - midnight).total_seconds() / 60
|
||||||
|
n = int(-(-mins // step)) # round up to the grid
|
||||||
|
return midnight + timedelta(minutes=n * step)
|
||||||
|
|
||||||
|
|
||||||
|
def slots(snapshot: dict, now: datetime | None = None) -> list[datetime]:
|
||||||
|
"""The times a customer can pick (aware, venue local), in order."""
|
||||||
|
cfg, tz = config(snapshot), venue_tz(snapshot)
|
||||||
|
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
|
||||||
|
last_day = (local_now + timedelta(days=cfg["days_ahead"])).date()
|
||||||
|
out, t = [], _first_slot(cfg, local_now)
|
||||||
|
while t.date() <= last_day and len(out) < MAX_SLOTS:
|
||||||
|
if is_open(cfg, t):
|
||||||
|
out.append(t)
|
||||||
|
t = (t + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def summary(snapshot: dict, now: datetime | None = None) -> dict:
|
||||||
|
"""What the ordering app needs: services, open now, ASAP offered, the slots."""
|
||||||
|
cfg, tz = config(snapshot), venue_tz(snapshot)
|
||||||
|
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
|
||||||
|
open_now = is_open(cfg, local_now)
|
||||||
|
return {"services": cfg["services"], "open_now": open_now, "asap": bool(cfg["asap"]) and open_now,
|
||||||
|
"prep_minutes": cfg["prep_minutes"], "timezone": tz.key,
|
||||||
|
"slots": [t.isoformat() for t in slots(snapshot, now)],
|
||||||
|
"reservations": res_summary(snapshot, now)} # S.6
|
||||||
|
|
||||||
|
|
||||||
|
def check(snapshot: dict, service: str, requested_for: datetime | None, now: datetime | None = None):
|
||||||
|
"""None if the order may be placed for that time, else (code, params)."""
|
||||||
|
cfg = config(snapshot)
|
||||||
|
if service not in cfg["services"]:
|
||||||
|
return "order.service_unavailable", {"service": service}
|
||||||
|
tz = venue_tz(snapshot)
|
||||||
|
now = now or datetime.now(timezone.utc)
|
||||||
|
if requested_for is None:
|
||||||
|
if cfg["asap"] and is_open(cfg, now.astimezone(tz)):
|
||||||
|
return None
|
||||||
|
return "order.closed", {}
|
||||||
|
if requested_for.tzinfo is None:
|
||||||
|
return "order.time_invalid", {}
|
||||||
|
wanted = requested_for.astimezone(tz)
|
||||||
|
if any(abs((wanted - t).total_seconds()) < 1 for t in slots(snapshot, now)):
|
||||||
|
return None
|
||||||
|
return "order.time_invalid", {}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Reservations online (plan phase 3S, step S.6) ─────────────────────────────
|
||||||
|
# The snapshot's `ordering.reservations` (site routers/fees.py ReservationsBody):
|
||||||
|
# {enabled, with_food, hours: {"0".."6": [[from, to], ...]}, slot_minutes, days_ahead,
|
||||||
|
# notice_minutes, party_max, fire_minutes}
|
||||||
|
# "reservation" = a table only; "preorder" = a table with food ready on arrival (with_food).
|
||||||
|
# Times: on the slot grid of the venue's day, at least notice_minutes from now, within today +
|
||||||
|
# days_ahead, inside the hours (none = any time). fire_minutes is the site's (the kitchen).
|
||||||
|
|
||||||
|
RES_DEFAULTS = {"enabled": False, "with_food": False, "hours": {}, "slot_minutes": 30, "days_ahead": 30,
|
||||||
|
"notice_minutes": 60, "party_max": 10}
|
||||||
|
RES_TYPES = ("reservation", "preorder")
|
||||||
|
|
||||||
|
|
||||||
|
def res_config(snapshot: dict) -> dict:
|
||||||
|
cfg = {**RES_DEFAULTS, **((snapshot.get("ordering") or {}).get("reservations") or {})}
|
||||||
|
cfg["enabled"] = bool(cfg.get("enabled"))
|
||||||
|
cfg["with_food"] = cfg["enabled"] and bool(cfg.get("with_food"))
|
||||||
|
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 30))
|
||||||
|
cfg["days_ahead"] = max(0, min(90, int(cfg.get("days_ahead") or 0)))
|
||||||
|
cfg["notice_minutes"] = max(0, int(cfg.get("notice_minutes") or 0))
|
||||||
|
cfg["party_max"] = max(1, min(100, int(cfg.get("party_max") or 1)))
|
||||||
|
return cfg
|
||||||
|
|
||||||
|
|
||||||
|
def res_slots(snapshot: dict, day, now: datetime | None = None) -> list[datetime]:
|
||||||
|
"""The reservation times on one venue day (a date), aware venue local, in order."""
|
||||||
|
cfg, tz = res_config(snapshot), venue_tz(snapshot)
|
||||||
|
if not cfg["enabled"]:
|
||||||
|
return []
|
||||||
|
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
|
||||||
|
if day < local_now.date() or day > (local_now + timedelta(days=cfg["days_ahead"])).date():
|
||||||
|
return []
|
||||||
|
earliest = local_now + timedelta(minutes=cfg["notice_minutes"])
|
||||||
|
t = datetime(day.year, day.month, day.day, tzinfo=tz)
|
||||||
|
out = []
|
||||||
|
while t.date() == day:
|
||||||
|
if t >= earliest and is_open(cfg, t):
|
||||||
|
out.append(t)
|
||||||
|
t = (t.astimezone(timezone.utc) + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def res_days(snapshot: dict, now: datetime | None = None) -> list[str]:
|
||||||
|
"""The venue days (ISO dates) with at least one reservation time."""
|
||||||
|
cfg, tz = res_config(snapshot), venue_tz(snapshot)
|
||||||
|
if not cfg["enabled"]:
|
||||||
|
return []
|
||||||
|
today = (now or datetime.now(timezone.utc)).astimezone(tz).date()
|
||||||
|
days = (today + timedelta(days=n) for n in range(cfg["days_ahead"] + 1))
|
||||||
|
return [d.isoformat() for d in days if res_slots(snapshot, d, now)]
|
||||||
|
|
||||||
|
|
||||||
|
def res_summary(snapshot: dict, now: datetime | None = None) -> dict:
|
||||||
|
cfg = res_config(snapshot)
|
||||||
|
return {"enabled": cfg["enabled"], "with_food": cfg["with_food"], "party_max": cfg["party_max"],
|
||||||
|
"days": res_days(snapshot, now)}
|
||||||
|
|
||||||
|
|
||||||
|
def res_check(snapshot: dict, order_type: str, requested_for: datetime | None, party_size, now: datetime | None = None):
|
||||||
|
"""None if the reservation may be requested, else (code, params)."""
|
||||||
|
cfg = res_config(snapshot)
|
||||||
|
if not cfg["enabled"] or (order_type == "preorder" and not cfg["with_food"]):
|
||||||
|
return "order.service_unavailable", {"service": order_type}
|
||||||
|
if isinstance(party_size, bool) or not isinstance(party_size, int) or not 1 <= party_size <= cfg["party_max"]:
|
||||||
|
return "order.party_invalid", {"max": cfg["party_max"]}
|
||||||
|
if requested_for is None or requested_for.tzinfo is None:
|
||||||
|
return "order.time_invalid", {}
|
||||||
|
wanted = requested_for.astimezone(venue_tz(snapshot))
|
||||||
|
if any(abs((wanted - t).total_seconds()) < 1 for t in res_slots(snapshot, wanted.date(), now)):
|
||||||
|
return None
|
||||||
|
return "order.time_invalid", {}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""The QR menu at the table (plan phase 3S, step S.7).
|
||||||
|
|
||||||
|
Each table's QR code carries a random token the venue's server made for that table
|
||||||
|
(client-services services/table_qr.py). The menu snapshot brings, under `qr`:
|
||||||
|
|
||||||
|
{ordering: bool, tables: [{id, label, token_hash}]} token_hash = sha256(token) hex
|
||||||
|
|
||||||
|
so the cloud never holds the tokens themselves, and a token is checked by its hash. A new
|
||||||
|
QR code for a table (the venue "rotates" it) makes the old one useless at the next menu push.
|
||||||
|
Ordering at the table needs the venue's `ordering`, the site's menu_mode "order" (sysadmin)
|
||||||
|
and a valid token; otherwise the QR menu is read-only. The public menu never shows `qr`.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
|
||||||
|
def token_hash(token: str) -> str:
|
||||||
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def table_for(snapshot: dict, token: str | None) -> dict | None:
|
||||||
|
"""{id, label} of the table this token belongs to, or None."""
|
||||||
|
if not token or not isinstance(token, str) or len(token) > 100:
|
||||||
|
return None
|
||||||
|
wanted = token_hash(token)
|
||||||
|
for t in (snapshot.get("qr") or {}).get("tables") or []:
|
||||||
|
if isinstance(t, dict) and hmac.compare_digest(str(t.get("token_hash") or ""), wanted):
|
||||||
|
return {"id": t.get("id"), "label": t.get("label")}
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def ordering_on(snapshot: dict, site) -> bool:
|
||||||
|
return site.menu_mode == "order" and bool((snapshot.get("qr") or {}).get("ordering"))
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""A small in-memory rate limit for the public endpoints (CL-4, plan phase 3S S.4).
|
||||||
|
|
||||||
|
hit(bucket, key, limit, per_seconds) -> bool True = allowed (and counted)
|
||||||
|
client_ip(request) the caller's address behind the proxy
|
||||||
|
|
||||||
|
Per process (the cloud runs one); a restart forgets. Enough to stop a script hammering the
|
||||||
|
order endpoint; not a defence against a distributed attack (that's the proxy's job).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
_lock = threading.Lock()
|
||||||
|
_hits: dict[tuple[str, str], deque] = {}
|
||||||
|
_MAX_KEYS = 50_000
|
||||||
|
|
||||||
|
|
||||||
|
def hit(bucket: str, key: str, limit: int, per_seconds: float, now: float | None = None) -> bool:
|
||||||
|
now = time.monotonic() if now is None else now
|
||||||
|
with _lock:
|
||||||
|
if len(_hits) > _MAX_KEYS: # never grow without bound
|
||||||
|
_hits.clear()
|
||||||
|
q = _hits.setdefault((bucket, key), deque())
|
||||||
|
while q and now - q[0] >= per_seconds:
|
||||||
|
q.popleft()
|
||||||
|
if len(q) >= limit:
|
||||||
|
return False
|
||||||
|
q.append(now)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def reset() -> None:
|
||||||
|
with _lock:
|
||||||
|
_hits.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def client_ip(request) -> str:
|
||||||
|
"""The first X-Forwarded-For address (the VPS proxy sets it), else the socket's."""
|
||||||
|
fwd = request.headers.get("x-forwarded-for", "")
|
||||||
|
if fwd:
|
||||||
|
return fwd.split(",")[0].strip() or "?"
|
||||||
|
return getattr(request.client, "host", None) or "?"
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Cloud backend tests. Run from cloud_backend/: python -m pytest tests -q
|
||||||
|
|
||||||
|
Before anything imports config/database, DATABASE_URL points at a fresh temp file and a
|
||||||
|
throwaway LICENSE_SIGNING_KEY is set, so tests never touch a real cloud DB or key.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from cryptography.hazmat.primitives import serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||||
|
|
||||||
|
_TMP = Path(tempfile.mkdtemp(prefix="xenia-cloud-tests-"))
|
||||||
|
os.environ["DATABASE_URL"] = f"sqlite:///{(_TMP / 'cloud.db').as_posix()}"
|
||||||
|
TEST_KEY = Ed25519PrivateKey.generate()
|
||||||
|
os.environ["LICENSE_SIGNING_KEY"] = base64.b64encode(
|
||||||
|
TEST_KEY.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw,
|
||||||
|
serialization.NoEncryption())).decode()
|
||||||
|
TEST_PUB = base64.b64encode(TEST_KEY.public_key().public_bytes(
|
||||||
|
serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode()
|
||||||
|
os.environ["ADMIN_USERNAME"] = "sysadmin"
|
||||||
|
os.environ["ADMIN_PASSWORD"] = "test-admin-pw"
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
import pytest # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
def client():
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
import main
|
||||||
|
with TestClient(main.app) as c: # runs the lifespan: Alembic upgrade + default admin
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
def admin_h(client):
|
||||||
|
r = client.post("/api/auth/login", json={"username": "sysadmin", "password": "test-admin-pw"})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
return {"Authorization": f"Bearer {r.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _fresh_rate_limits():
|
||||||
|
"""Every test starts with empty rate-limit counters (services/ratelimit.py, S.4)."""
|
||||||
|
from services import ratelimit
|
||||||
|
ratelimit.reset()
|
||||||
|
yield
|
||||||
+147
@@ -0,0 +1,147 @@
|
|||||||
|
{
|
||||||
|
"_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},
|
||||||
|
{"id": 4, "name": "Drawn square", "kind": "polygon", "postcodes": [], "is_active": true, "geometry": [[37.0, 22.0], [37.0, 22.1], [37.1, 22.1], [37.1, 22.0]]},
|
||||||
|
{"id": 5, "name": "1 km around", "kind": "circle", "postcodes": [], "is_active": true, "geometry": {"center": [37.5, 22.5], "radius_m": 1000}},
|
||||||
|
{"id": 6, "name": "Old shape", "kind": "polygon", "postcodes": [], "is_active": false, "geometry": [[38.0, 23.0], [38.0, 23.1], [38.1, 23.1]]}
|
||||||
|
],
|
||||||
|
"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}},
|
||||||
|
{"name": "6R.G: a pin inside a drawn shape",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.05, 22.05]},
|
||||||
|
"expect": {"refused": null, "area_id": 4}},
|
||||||
|
{"name": "6R.G: a pin on the shape's edge counts as inside",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.0, 22.05]},
|
||||||
|
"expect": {"refused": null, "area_id": 4}},
|
||||||
|
{"name": "6R.G: a pin on a corner counts as inside",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.1, 22.1]},
|
||||||
|
"expect": {"refused": null, "area_id": 4}},
|
||||||
|
{"name": "6R.G: a pin outside every area is refused",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.2, 22.05]},
|
||||||
|
"expect": {"refused": "area_not_served", "area_id": null}},
|
||||||
|
{"name": "6R.G: inside the circle (990 m)",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.5089, 22.5]},
|
||||||
|
"expect": {"refused": null, "area_id": 5}},
|
||||||
|
{"name": "6R.G: past the circle's rim (1.1 km)",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.5099, 22.5]},
|
||||||
|
"expect": {"refused": "area_not_served"}},
|
||||||
|
{"name": "6R.G: a shape picked by id needs a pin inside it",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 4},
|
||||||
|
"expect": {"refused": "area_not_served"}},
|
||||||
|
{"name": "6R.G: a shape picked by id with its pin",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 4, "point": [37.05, 22.05]},
|
||||||
|
"expect": {"area_id": 4}},
|
||||||
|
{"name": "6R.G: a shape picked with a pin outside it falls back to the postcode",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "area_id": 4, "point": [37.2, 22.0], "postcode": "24131"},
|
||||||
|
"expect": {"area_id": 2}},
|
||||||
|
{"name": "6R.G: an inactive shape holds nothing",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [38.02, 23.05]},
|
||||||
|
"expect": {"refused": "area_not_served"}},
|
||||||
|
{"name": "6R.G: a nonsense pin is no pin",
|
||||||
|
"rules": [], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": ["x", 200], "postcode": "241 00"},
|
||||||
|
"expect": {"area_id": 1}},
|
||||||
|
{"name": "6R.G: rules by area work for shapes",
|
||||||
|
"rules": [{"id": 1, "name": "Square fee", "area_ids": [4], "action": "set", "value": 2.5, "sales_points": ["online_delivery"]}, {"id": 2, "name": "Circle fee", "area_ids": [5], "action": "set", "value": 1, "sales_points": ["online_delivery"]}], "ctx": {"sales_point": "online_delivery", "subtotal": 20, "items": 2, "point": [37.05, 22.05]},
|
||||||
|
"expect": {"fee": 2.5, "area_id": 4}}
|
||||||
|
]
|
||||||
|
}
|
||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
-- The v1 production cloud schema (create_all + _run_migrations on main, 2026-11-12).
|
||||||
|
-- Frozen fixture for tests/test_schema.py: the v2 baseline must equal it, and a DB
|
||||||
|
-- in this shape must stamp + upgrade cleanly (APPS_PLATFORM D-22). Never edit.
|
||||||
|
|
||||||
|
CREATE TABLE admins (
|
||||||
|
id INTEGER NOT NULL,
|
||||||
|
username VARCHAR NOT NULL,
|
||||||
|
password_hash VARCHAR NOT NULL,
|
||||||
|
role VARCHAR,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE (username)
|
||||||
|
);
|
||||||
|
CREATE TABLE manager_accounts (
|
||||||
|
id INTEGER NOT NULL,
|
||||||
|
email VARCHAR NOT NULL,
|
||||||
|
password_hash VARCHAR NOT NULL,
|
||||||
|
full_name VARCHAR,
|
||||||
|
is_active INTEGER NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
);
|
||||||
|
CREATE TABLE manager_site_access (
|
||||||
|
manager_id INTEGER NOT NULL,
|
||||||
|
site_id INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (manager_id, site_id),
|
||||||
|
FOREIGN KEY(manager_id) REFERENCES manager_accounts (id),
|
||||||
|
FOREIGN KEY(site_id) REFERENCES sites (id)
|
||||||
|
);
|
||||||
|
CREATE TABLE menu_snapshots (
|
||||||
|
id INTEGER NOT NULL,
|
||||||
|
site_id INTEGER NOT NULL,
|
||||||
|
snapshot_json TEXT NOT NULL,
|
||||||
|
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
FOREIGN KEY(site_id) REFERENCES sites (id)
|
||||||
|
);
|
||||||
|
CREATE TABLE online_orders (
|
||||||
|
id INTEGER NOT NULL,
|
||||||
|
site_id INTEGER NOT NULL,
|
||||||
|
public_ref VARCHAR NOT NULL,
|
||||||
|
order_type VARCHAR NOT NULL,
|
||||||
|
customer_name VARCHAR NOT NULL,
|
||||||
|
customer_phone VARCHAR,
|
||||||
|
customer_address TEXT,
|
||||||
|
customer_notes TEXT,
|
||||||
|
items_json TEXT NOT NULL,
|
||||||
|
subtotal FLOAT NOT NULL,
|
||||||
|
delivery_fee FLOAT NOT NULL,
|
||||||
|
total FLOAT NOT NULL,
|
||||||
|
status VARCHAR NOT NULL,
|
||||||
|
rejection_reason VARCHAR,
|
||||||
|
synced_to_local INTEGER NOT NULL,
|
||||||
|
local_order_id INTEGER,
|
||||||
|
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||||
|
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
FOREIGN KEY(site_id) REFERENCES sites (id),
|
||||||
|
UNIQUE (public_ref)
|
||||||
|
);
|
||||||
|
CREATE TABLE product_images (
|
||||||
|
id INTEGER NOT NULL,
|
||||||
|
site_id INTEGER NOT NULL,
|
||||||
|
product_id INTEGER NOT NULL,
|
||||||
|
image_url VARCHAR NOT NULL,
|
||||||
|
image_hash VARCHAR NOT NULL,
|
||||||
|
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
CONSTRAINT uq_product_images_site_product UNIQUE (site_id, product_id),
|
||||||
|
FOREIGN KEY(site_id) REFERENCES sites (id)
|
||||||
|
);
|
||||||
|
CREATE TABLE sites (
|
||||||
|
id INTEGER NOT NULL,
|
||||||
|
site_id VARCHAR NOT NULL,
|
||||||
|
name VARCHAR NOT NULL,
|
||||||
|
owner_name VARCHAR NOT NULL,
|
||||||
|
contact_email VARCHAR NOT NULL,
|
||||||
|
secret_key_hash VARCHAR NOT NULL,
|
||||||
|
is_active BOOLEAN,
|
||||||
|
is_locked BOOLEAN,
|
||||||
|
lock_reason VARCHAR,
|
||||||
|
license_expires_at DATETIME NOT NULL,
|
||||||
|
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||||
|
last_seen_at DATETIME,
|
||||||
|
last_seen_ip VARCHAR,
|
||||||
|
last_seen_local_ip VARCHAR,
|
||||||
|
waiter_domain VARCHAR,
|
||||||
|
order_counter INTEGER NOT NULL,
|
||||||
|
menu_mode VARCHAR NOT NULL,
|
||||||
|
menu_display_name VARCHAR,
|
||||||
|
menu_tagline_en VARCHAR,
|
||||||
|
menu_tagline_gr VARCHAR,
|
||||||
|
menu_blurb_en VARCHAR,
|
||||||
|
menu_blurb_gr VARCHAR,
|
||||||
|
menu_hours VARCHAR,
|
||||||
|
menu_header_image_url VARCHAR, menu_hours_en VARCHAR, menu_hours_gr VARCHAR,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
);
|
||||||
|
CREATE TABLE stats_snapshots (
|
||||||
|
id INTEGER NOT NULL,
|
||||||
|
site_id INTEGER NOT NULL,
|
||||||
|
snapshot_json TEXT NOT NULL,
|
||||||
|
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE (site_id),
|
||||||
|
FOREIGN KEY(site_id) REFERENCES sites (id)
|
||||||
|
);
|
||||||
|
CREATE INDEX ix_admins_id ON admins (id);
|
||||||
|
CREATE UNIQUE INDEX ix_manager_accounts_email ON manager_accounts (email);
|
||||||
|
CREATE INDEX ix_manager_accounts_id ON manager_accounts (id);
|
||||||
|
CREATE INDEX ix_menu_snapshots_id ON menu_snapshots (id);
|
||||||
|
CREATE UNIQUE INDEX ix_menu_snapshots_site_id ON menu_snapshots (site_id);
|
||||||
|
CREATE INDEX ix_online_orders_id ON online_orders (id);
|
||||||
|
CREATE INDEX ix_online_orders_site_id ON online_orders (site_id);
|
||||||
|
CREATE INDEX ix_online_orders_status ON online_orders (status);
|
||||||
|
CREATE INDEX ix_product_images_id ON product_images (id);
|
||||||
|
CREATE INDEX ix_product_images_site_id ON product_images (site_id);
|
||||||
|
CREATE INDEX ix_sites_id ON sites (id);
|
||||||
|
CREATE UNIQUE INDEX ix_sites_site_id ON sites (site_id);
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
"""The cloud prices online orders itself; sites only touch their own data (plan phase 3S, S.2).
|
||||||
|
|
||||||
|
Done when: a tampered price or total is refused, a correct order is stored with the cloud's
|
||||||
|
prices, and one site can't read or overwrite another's data."""
|
||||||
|
import json
|
||||||
|
|
||||||
|
from test_licensing_v2 import _heartbeat, _new_site
|
||||||
|
|
||||||
|
COLA, PIE, SOUP = 11, 12, 13
|
||||||
|
# online ordering on, any time (no hours), as soon as possible (S.4)
|
||||||
|
ORDERING = {"services": ["takeaway", "delivery"], "hours": {}, "prep_minutes": 20, "slot_minutes": 15, "days_ahead": 0, "asap": True}
|
||||||
|
|
||||||
|
|
||||||
|
def _h(site):
|
||||||
|
return {"X-Site-ID": site["site_id"], "X-Site-Key": site["secret_key"]}
|
||||||
|
|
||||||
|
|
||||||
|
def _menu(client, site, numeric):
|
||||||
|
"""A snapshot as the site pushes it after S.2: prices per sales point, where it's sold."""
|
||||||
|
snap = {"categories": [{"id": 1, "name": "All", "products": [
|
||||||
|
{"id": COLA, "name": "Cola 1.5L", "base_price": 3.5, "digital_price": 3.0, "digital_available": True,
|
||||||
|
"sold_at": ["qr_table", "online_takeaway", "online_delivery"],
|
||||||
|
"prices": {"qr_table": 3.0, "online_takeaway": 2.5, "online_delivery": 2.8},
|
||||||
|
"quick_options": [{"id": 7, "name": "Ice", "price": 0.2}]},
|
||||||
|
{"id": PIE, "name": "Pie", "base_price": 5.0, "digital_price": 5.0, "digital_available": True,
|
||||||
|
"sold_at": ["qr_table"], "prices": {"qr_table": 5.0}, "quick_options": []},
|
||||||
|
{"id": SOUP, "name": "Soup", "base_price": 6.0, "digital_price": 6.0, "digital_available": False,
|
||||||
|
"sold_at": ["qr_table", "online_delivery"], "prices": {"qr_table": 6.0, "online_delivery": 6.0}, "quick_options": []},
|
||||||
|
]}], "ordering": ORDERING, "timezone": "Europe/Athens"}
|
||||||
|
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
|
||||||
|
|
||||||
|
def _venue(client, admin_h):
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
numeric = _heartbeat(client, site)["site_numeric_id"]
|
||||||
|
_menu(client, site, numeric)
|
||||||
|
return site, numeric
|
||||||
|
|
||||||
|
|
||||||
|
def _order(client, site, order_type="takeaway", **extra):
|
||||||
|
body = {"order_type": order_type, "customer_name": "Maria", "customer_phone": "6900000000",
|
||||||
|
"items": [{"product_id": COLA, "quantity": 2}], **extra}
|
||||||
|
return client.post(f"/api/orders/{site['site_id']}", json=body)
|
||||||
|
|
||||||
|
|
||||||
|
def _code(r):
|
||||||
|
return r.json()["detail"]["code"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_cloud_prices_by_sales_point(client, admin_h):
|
||||||
|
site, _ = _venue(client, admin_h)
|
||||||
|
q = lambda t, items: client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": t, "items": items}) # noqa: E731
|
||||||
|
take = q("takeaway", [{"product_id": COLA, "quantity": 2, "options": [7]}]).json()
|
||||||
|
assert (take["sales_point"], take["lines"][0]["unit_price"], take["total"]) == ("online_takeaway", 2.7, 5.4)
|
||||||
|
assert q("dine_in", [{"product_id": COLA, "quantity": 1}]).json()["total"] == 3.0
|
||||||
|
assert q("delivery", [{"product_id": COLA, "quantity": 1}]).json()["total"] == 2.8
|
||||||
|
assert _code(q("takeaway", [{"product_id": PIE, "quantity": 1}])) == "order.item_unavailable" # QR menu only
|
||||||
|
assert _code(q("delivery", [{"product_id": SOUP, "quantity": 1}])) == "order.item_unavailable" # out of stock now
|
||||||
|
assert _code(q("takeaway", [{"product_id": 999, "quantity": 1}])) == "order.item_unavailable"
|
||||||
|
assert _code(q("takeaway", [{"product_id": COLA, "quantity": 0}])) == "order.quantity_invalid"
|
||||||
|
assert _code(q("takeaway", [{"product_id": COLA, "quantity": 1, "options": [8]}])) == "order.option_unavailable"
|
||||||
|
assert _code(q("teleport", [{"product_id": COLA, "quantity": 1}])) == "order.type_invalid"
|
||||||
|
assert _code(q("takeaway", [])) == "order.empty"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_tampered_order_is_refused_and_a_correct_one_stored_at_the_clouds_prices(client, admin_h):
|
||||||
|
"""The done-when, first part."""
|
||||||
|
site, numeric = _venue(client, admin_h)
|
||||||
|
r = _order(client, site, items=[{"product_id": COLA, "quantity": 2, "unit_price": 0.01}], subtotal=0.02, total=0.02)
|
||||||
|
assert r.status_code == 409 and _code(r) == "order.price_changed"
|
||||||
|
assert r.json()["detail"]["params"]["total"] == 5.0 # the current prices come back
|
||||||
|
assert _code(_order(client, site, total=1.0)) == "order.price_changed"
|
||||||
|
ok = _order(client, site, total=5.0, delivery_fee=-3, customer_table=" ")
|
||||||
|
assert ok.status_code == 201, ok.text
|
||||||
|
pending = client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()
|
||||||
|
stored = next(o for o in pending if o["public_ref"] == ok.json()["public_ref"])
|
||||||
|
assert (stored["subtotal"], stored["delivery_fee"], stored["total"], stored["sales_point"]) == (5.0, 0.0, 5.0, "online_takeaway")
|
||||||
|
assert json.loads(stored["items_json"]) == [{"product_id": COLA, "name": "Cola 1.5L", "quantity": 2, "unit_price": 2.5, "options": []}]
|
||||||
|
# no total sent at all: priced by the cloud anyway (the old menu app's fields are optional)
|
||||||
|
assert _order(client, site).status_code == 201
|
||||||
|
|
||||||
|
|
||||||
|
def test_delivery_details(client, admin_h):
|
||||||
|
site, numeric = _venue(client, admin_h) # table orders: tests/test_qr.py (S.7)
|
||||||
|
assert _code(_order(client, site, "delivery")) == "order.details_missing"
|
||||||
|
assert _order(client, site, "delivery", customer_address="Main square 3").status_code == 201
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_site_only_touches_its_own_data(client, admin_h):
|
||||||
|
"""The done-when, second part: a site's key can't read or overwrite another site's data."""
|
||||||
|
a, a_num = _venue(client, admin_h)
|
||||||
|
b, b_num = _venue(client, admin_h)
|
||||||
|
assert _order(client, a).status_code == 201
|
||||||
|
assert client.get(f"/api/orders/pending/{a_num}", headers=_h(b)).status_code == 403
|
||||||
|
assert client.post("/api/menu/sync", headers=_h(b), json={"site_id": a_num, "snapshot_json": "{}"}).status_code == 403
|
||||||
|
assert client.post("/api/remote/snapshot", headers=_h(b), json={"site_id": a_num, "snapshot_json": "{}"}).status_code == 403
|
||||||
|
# a's menu is intact
|
||||||
|
assert _order(client, a, total=5.0).status_code == 201
|
||||||
|
assert client.post("/api/menu/sync", headers=_h(a), json={"site_id": a_num, "snapshot_json": "not json"}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_snapshot_from_before_s2_still_prices(client, admin_h):
|
||||||
|
"""A site that hasn't updated yet pushes digital_price / digital_discount only."""
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
numeric = _heartbeat(client, site)["site_numeric_id"]
|
||||||
|
old = {"categories": [{"id": 1, "name": "All", "products": [
|
||||||
|
{"id": COLA, "name": "Cola", "base_price": 4.0, "digital_price": None, "digital_discount": 25, "digital_available": True,
|
||||||
|
"quick_options": []}]}]}
|
||||||
|
client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(old)})
|
||||||
|
r = client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "dine_in", "items": [{"product_id": COLA, "quantity": 1}]})
|
||||||
|
assert r.json()["total"] == 3.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_order_numbers_per_site_and_tracking_by_token(client, admin_h):
|
||||||
|
"""Two venues both have an ORD-0001 (the second used to fail); the customer tracks their
|
||||||
|
order by its random token, and the bare number no longer identifies it."""
|
||||||
|
a, _ = _venue(client, admin_h)
|
||||||
|
b, _ = _venue(client, admin_h)
|
||||||
|
ra, rb = _order(client, a).json(), _order(client, b).json()
|
||||||
|
assert ra["public_ref"] == rb["public_ref"] == "ORD-0001"
|
||||||
|
assert ra["tracking_token"] != rb["tracking_token"] and ra["total"] == 5.0
|
||||||
|
t = client.get(f"/api/orders/track/{ra['tracking_token']}")
|
||||||
|
tj = t.json()
|
||||||
|
assert t.status_code == 200 and (tj["public_ref"], tj["status"], tj["rejection_reason"], tj["total"]) == ("ORD-0001", "pending_acceptance", None, 5.0)
|
||||||
|
assert tj["lines"] == [{"name": "Cola 1.5L", "quantity": 2, "unit_price": 2.5, "options": []}] and tj["order_type"] == "takeaway"
|
||||||
|
assert client.get("/api/orders/status/ORD-0001").status_code == 404 # ambiguous now
|
||||||
|
assert client.get("/api/orders/track/nope").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_public_menu_carries_each_products_allergens(client, admin_h):
|
||||||
|
"""Plan step 6.3 (contract C-2): the site sends `allergens` {key: contains | may_contain} per
|
||||||
|
product; the public menu passes them to the QR menu and the order app as they are."""
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
numeric = _heartbeat(client, site)["site_numeric_id"]
|
||||||
|
snap = {"categories": [{"id": 1, "name": "All", "products": [
|
||||||
|
{"id": PIE, "name": "Pie", "base_price": 5.0, "digital_price": 5.0, "digital_available": True,
|
||||||
|
"sold_at": ["qr_table"], "prices": {"qr_table": 5.0}, "quick_options": [],
|
||||||
|
"allergens": {"gluten": "contains", "sesame": "may_contain"}}]}], "ordering": ORDERING, "timezone": "Europe/Athens"}
|
||||||
|
assert client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)}).status_code == 200
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
assert menu["categories"][0]["products"][0]["allergens"] == {"gluten": "contains", "sesame": "may_contain"}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""Delivery fees at checkout (plan phase 3S, step S.3).
|
||||||
|
|
||||||
|
The engine (services/fees.py) is the site's file; both repos run the same cases
|
||||||
|
(tests/fixtures/fee_cases.json, identical in both; the site's tests check the copies match).
|
||||||
|
Done when (cloud half): the cloud charges the venue's fee and refuses an order below the minimum."""
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from test_checkout import COLA, ORDERING, _code, _h, _menu, _order
|
||||||
|
from test_licensing_v2 import _heartbeat, _new_site
|
||||||
|
|
||||||
|
CASES = json.loads((Path(__file__).resolve().parent / "fixtures" / "fee_cases.json").read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("case", CASES["cases"], ids=[c["name"] for c in CASES["cases"]])
|
||||||
|
def test_shared_fee_cases(case):
|
||||||
|
from services.fees import compute
|
||||||
|
got = compute(case["rules"], CASES["areas"], **case["ctx"])
|
||||||
|
for key, value in case["expect"].items():
|
||||||
|
assert got[key] == value, (key, got)
|
||||||
|
|
||||||
|
|
||||||
|
FEES = {"areas": [{"id": 1, "name": "Centre", "postcodes": ["24100"], "is_active": True},
|
||||||
|
{"id": 2, "name": "Far", "postcodes": ["24131"], "is_active": True}],
|
||||||
|
"rules": [{"id": 1, "name": "Minimum", "action": "minimum", "value": 5, "sales_points": ["online_delivery"]},
|
||||||
|
{"id": 2, "name": "Base", "action": "set", "value": 2, "sales_points": ["online_delivery"]},
|
||||||
|
{"id": 3, "name": "Far", "area_ids": [2], "action": "add", "value": 1.5, "sales_points": ["online_delivery"]}]}
|
||||||
|
|
||||||
|
|
||||||
|
def _venue_with_fees(client, admin_h):
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
numeric = _heartbeat(client, site)["site_numeric_id"]
|
||||||
|
_menu(client, site, numeric)
|
||||||
|
# the same menu plus the venue's fees, as the site pushes them since S.3
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
snap = {"categories": menu["categories"], "fees": FEES, "ordering": ORDERING, "timezone": "Europe/Athens"}
|
||||||
|
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
|
||||||
|
assert r.status_code == 200
|
||||||
|
return site, numeric
|
||||||
|
|
||||||
|
|
||||||
|
def _quote(client, site, **body):
|
||||||
|
return client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "delivery", **body})
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_cloud_charges_the_venues_fee(client, admin_h):
|
||||||
|
site, numeric = _venue_with_fees(client, admin_h)
|
||||||
|
q = _quote(client, site, items=[{"product_id": COLA, "quantity": 2}], area_id=1).json() # 2 × 2.8 delivery price
|
||||||
|
assert (q["subtotal"], q["delivery_fee"], q["total"], q["area_name"], q["fee_rules"]) == (5.6, 2.0, 7.6, "Centre", ["Base"])
|
||||||
|
q = _quote(client, site, items=[{"product_id": COLA, "quantity": 2}], postcode="241 31").json()
|
||||||
|
assert (q["delivery_fee"], q["area_name"]) == (3.5, "Far")
|
||||||
|
# the order: the fee is the cloud's, whatever the page sends; the area is stored
|
||||||
|
assert _code(_order(client, site, "delivery", customer_address="Main sq. 3", area_id=1, delivery_fee=0, total=5.6)) == "order.price_changed"
|
||||||
|
ok = _order(client, site, "delivery", customer_address="Main sq. 3", area_id=1, total=7.6)
|
||||||
|
assert ok.status_code == 201, ok.text
|
||||||
|
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == ok.json()["public_ref"])
|
||||||
|
assert (stored["delivery_fee"], stored["total"], stored["delivery_area"], stored["delivery_area_id"]) == (2.0, 7.6, "Centre", 1)
|
||||||
|
# takeaway: the delivery rules don't apply
|
||||||
|
assert client.post(f"/api/orders/{site['site_id']}/quote", json={"order_type": "takeaway", "items": [{"product_id": COLA, "quantity": 1}]}).json()["delivery_fee"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_minimum_and_area_are_refused(client, admin_h):
|
||||||
|
site, _ = _venue_with_fees(client, admin_h)
|
||||||
|
r = _quote(client, site, items=[{"product_id": COLA, "quantity": 1}], area_id=1)
|
||||||
|
assert r.status_code == 409 and _code(r) == "order.minimum_not_met"
|
||||||
|
assert r.json()["detail"]["params"] == {"minimum": 5.0, "subtotal": 2.8}
|
||||||
|
assert _code(_order(client, site, "delivery", customer_address="x", area_id=1, items=[{"product_id": COLA, "quantity": 1}])) == "order.minimum_not_met"
|
||||||
|
assert _code(_quote(client, site, items=[{"product_id": COLA, "quantity": 2}], postcode="10431")) == "order.area_not_served"
|
||||||
|
assert _code(_quote(client, site, items=[{"product_id": COLA, "quantity": 2}])) == "order.area_not_served"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_public_menu_lists_areas_but_not_the_rules(client, admin_h):
|
||||||
|
site, _ = _venue_with_fees(client, admin_h)
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
assert menu["delivery_areas"] == [{"id": 1, "name": "Centre", "kind": "postcodes"}, {"id": 2, "name": "Far", "kind": "postcodes"}]
|
||||||
|
assert "fees" not in menu
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_venue_clock():
|
||||||
|
from services.checkout import venue_clock
|
||||||
|
at = datetime(2026, 11, 15, 21, 30, tzinfo=timezone.utc) # Sunday 23:30 in Athens (UTC+2)
|
||||||
|
assert venue_clock({"timezone": "Europe/Athens"}, at) == (6, "23:30")
|
||||||
|
assert venue_clock({"timezone": "Nowhere/Bad"}, at) == (6, "23:30")
|
||||||
|
|
||||||
|
|
||||||
|
SHAPED = {"areas": [{"id": 1, "name": "Centre", "postcodes": ["24100"], "is_active": True},
|
||||||
|
{"id": 7, "name": "Drawn", "kind": "polygon", "postcodes": [], "is_active": True,
|
||||||
|
"geometry": [[37.0, 22.0], [37.0, 22.1], [37.1, 22.1], [37.1, 22.0]]},
|
||||||
|
{"id": 8, "name": "2 km", "kind": "circle", "postcodes": [], "is_active": True,
|
||||||
|
"geometry": {"center": [37.5, 22.5], "radius_m": 2000}}],
|
||||||
|
"rules": [{"id": 1, "name": "Drawn fee", "area_ids": [7], "action": "set", "value": 1.5, "sales_points": ["online_delivery"]},
|
||||||
|
{"id": 2, "name": "Circle fee", "area_ids": [8], "action": "set", "value": 3, "sales_points": ["online_delivery"]}],
|
||||||
|
"venue_point": {"lat": 37.05, "lng": 22.05}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_pin_on_the_map_finds_a_drawn_area_and_reaches_the_site(client, admin_h):
|
||||||
|
"""6R.G: the customer pins the address; the cloud prices it by the area holding the pin and
|
||||||
|
keeps the pin for the site (which checks the fee with the same engine)."""
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
numeric = _heartbeat(client, site)["site_numeric_id"]
|
||||||
|
_menu(client, site, numeric)
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
snap = {"categories": menu["categories"], "fees": SHAPED, "ordering": ORDERING, "timezone": "Europe/Athens"}
|
||||||
|
assert client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)}).status_code == 200
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
assert menu["venue_point"] == {"lat": 37.05, "lng": 22.05}
|
||||||
|
assert menu["delivery_areas"][1] == {"id": 7, "name": "Drawn", "kind": "polygon", "geometry": SHAPED["areas"][1]["geometry"]}
|
||||||
|
assert "24100" not in json.dumps(menu["delivery_areas"]) # the postcodes stay on the cloud
|
||||||
|
items = [{"product_id": COLA, "quantity": 2}]
|
||||||
|
q = _quote(client, site, items=items, lat=37.05, lng=22.05).json()
|
||||||
|
assert (q["delivery_fee"], q["area_name"]) == (1.5, "Drawn")
|
||||||
|
q = _quote(client, site, items=items, lat=37.51, lng=22.5).json()
|
||||||
|
assert (q["delivery_fee"], q["area_name"]) == (3.0, "2 km")
|
||||||
|
assert _code(_quote(client, site, items=items, lat=36.0, lng=22.5)) == "order.area_not_served"
|
||||||
|
assert _code(_quote(client, site, items=items, area_id=7)) == "order.area_not_served" # a shape needs the pin
|
||||||
|
assert _quote(client, site, items=items, lat=37.05).json()["detail"]["code"] == "order.area_not_served" # half a pin is none
|
||||||
|
ok = _order(client, site, "delivery", customer_address="Main sq. 3", lat=37.05, lng=22.05, total=round(5.6 + 1.5, 2))
|
||||||
|
assert ok.status_code == 201, ok.text
|
||||||
|
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == ok.json()["public_ref"])
|
||||||
|
assert (stored["delivery_area"], stored["delivery_area_id"], stored["lat"], stored["lng"]) == ("Drawn", 7, 37.05, 22.05)
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"""License token v2, site modules, presets, heartbeat catalogue (plan step 1.7, D-3, D-20, D-21)."""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
|
||||||
|
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||||
|
|
||||||
|
from conftest import TEST_PUB
|
||||||
|
|
||||||
|
|
||||||
|
def _decode(token):
|
||||||
|
body, sig = token.split(".")
|
||||||
|
pad = lambda s: s + "=" * (-len(s) % 4) # noqa: E731
|
||||||
|
Ed25519PublicKey.from_public_bytes(base64.b64decode(TEST_PUB)).verify(
|
||||||
|
base64.urlsafe_b64decode(pad(sig)), body.encode()) # raises if the signature is wrong
|
||||||
|
return json.loads(base64.urlsafe_b64decode(pad(body)))
|
||||||
|
|
||||||
|
|
||||||
|
def _new_site(client, admin_h, **extra):
|
||||||
|
r = client.post("/api/sites/", headers=admin_h, json={
|
||||||
|
"name": "Test", "owner_name": "O", "contact_email": "o@example.com",
|
||||||
|
"license_expires_at": "2027-06-01T00:00:00+00:00", **extra})
|
||||||
|
assert r.status_code == 201, r.text
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
|
||||||
|
def _heartbeat(client, site, catalog=()):
|
||||||
|
r = client.post("/api/heartbeat/", headers={"X-Site-ID": site["site_id"], "X-Site-Key": site["secret_key"]},
|
||||||
|
json={"version": "2.0.0", "local_ip": "192.168.1.10", "module_catalog": list(catalog)})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_modules():
|
||||||
|
from services.license_token import normalize_modules
|
||||||
|
assert normalize_modules({"kds": {"limits": {"devices": "2"}, "junk": 1}, "tabs": None}) == \
|
||||||
|
{"kds": {"limits": {"devices": 2}}, "tabs": {}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_site_gets_default_preset_and_v2_token(client, admin_h):
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
assert "ordering" in site["modules"]
|
||||||
|
hb = _heartbeat(client, site)
|
||||||
|
assert set(hb) == {"license_token", "latest_version", "waiter_domain", "site_numeric_id", "apps_url"}
|
||||||
|
p = _decode(hb["license_token"])
|
||||||
|
assert p["v"] == 2 and p["site_id"] == site["site_id"] and p["modules"]["kds"] == {"limits": {"devices": None}}
|
||||||
|
assert {"active", "locked", "expires_at", "issued_at"} <= set(p)
|
||||||
|
|
||||||
|
|
||||||
|
def test_site_without_preset_licenses_nothing(client, admin_h):
|
||||||
|
site = _new_site(client, admin_h, preset=None)
|
||||||
|
assert _decode(_heartbeat(client, site)["license_token"])["modules"] == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_editing_modules_changes_the_next_token(client, admin_h):
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
r = client.put(f"/api/sites/{site['site_id']}/modules", headers=admin_h,
|
||||||
|
json={"modules": {"ordering": {}, "kds": {"limits": {"devices": 2}},
|
||||||
|
"caller_id": {"exp": "2027-01-31T00:00:00+00:00"}}})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
mods = _decode(_heartbeat(client, site)["license_token"])["modules"]
|
||||||
|
assert mods == {"ordering": {}, "kds": {"limits": {"devices": 2}},
|
||||||
|
"caller_id": {"exp": "2027-01-31T00:00:00+00:00"}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_module_maps_are_refused(client, admin_h):
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
for bad in ({"kds": {"limits": {"devices": -1}}}, {"kds": {"limits": {"devices": "x"}}},
|
||||||
|
{"caller_id": {"exp": "tomorrow"}}):
|
||||||
|
assert client.put(f"/api/sites/{site['site_id']}/modules", headers=admin_h, json={"modules": bad}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_heartbeat_stores_the_module_catalogue(client, admin_h):
|
||||||
|
site = _new_site(client, admin_h)
|
||||||
|
catalog = [{"key": "kds", "kind": "app", "name": "Kitchen display", "depends": ["ordering"],
|
||||||
|
"limits": [{"key": "devices", "free": 0, "licensed_default": 1}]}]
|
||||||
|
_heartbeat(client, site, catalog)
|
||||||
|
got = client.get(f"/api/sites/{site['site_id']}", headers=admin_h).json()
|
||||||
|
assert got["module_catalog"] == catalog and got["module_catalog_at"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_presets_crud_and_apply(client, admin_h):
|
||||||
|
r = client.post("/api/presets/", headers=admin_h, json={"name": "Cafe basic", "description": "POS + KDS",
|
||||||
|
"modules": {"ordering": {}, "kds": {"limits": {"devices": 1}}}})
|
||||||
|
assert r.status_code == 201, r.text
|
||||||
|
preset = r.json()
|
||||||
|
names = [p["name"] for p in client.get("/api/presets/", headers=admin_h).json()]
|
||||||
|
assert "Cafe basic" in names and "Everything (v1 sites)" in names
|
||||||
|
site = _new_site(client, admin_h, preset="Cafe basic")
|
||||||
|
assert set(site["modules"]) == {"ordering", "kds"}
|
||||||
|
site2 = _new_site(client, admin_h)
|
||||||
|
applied = client.post(f"/api/sites/{site2['site_id']}/apply-preset/{preset['id']}", headers=admin_h).json()
|
||||||
|
assert applied["modules"] == {"ordering": {}, "kds": {"limits": {"devices": 1}}}
|
||||||
|
assert client.post("/api/presets/", headers=admin_h, json={"name": "Cafe basic", "modules": {}}).status_code == 409
|
||||||
|
assert client.delete(f"/api/presets/{preset['id']}", headers=admin_h).status_code == 204
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_preset_on_create(client, admin_h):
|
||||||
|
r = client.post("/api/sites/", headers=admin_h, json={
|
||||||
|
"name": "T", "owner_name": "O", "contact_email": "o@x", "license_expires_at": "2027-06-01T00:00:00+00:00",
|
||||||
|
"preset": "Nope"})
|
||||||
|
assert r.status_code == 400
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
"""When online orders are taken: services, hours, time slots, rate limits (plan phase 3S, S.4)."""
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from services import ordering
|
||||||
|
from test_checkout import COLA, _code, _h, _menu, _order, _venue
|
||||||
|
|
||||||
|
ATH = ZoneInfo("Europe/Athens")
|
||||||
|
|
||||||
|
|
||||||
|
def snap(**cfg):
|
||||||
|
return {"timezone": "Europe/Athens", "ordering": {"services": ["takeaway", "delivery"], "hours": {}, "prep_minutes": 20,
|
||||||
|
"slot_minutes": 15, "days_ahead": 0, "asap": True, **cfg}}
|
||||||
|
|
||||||
|
|
||||||
|
def at(y, mo, d, h, mi):
|
||||||
|
return datetime(y, mo, d, h, mi, tzinfo=ATH).astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
# Sunday 15 Nov 2026 is weekday 6; Monday 16 Nov is 0
|
||||||
|
EVENINGS = {"6": [["18:00", "23:00"]], "5": [["20:00", "02:00"]]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_hours_including_past_midnight():
|
||||||
|
cfg = ordering.config(snap(hours=EVENINGS))
|
||||||
|
local = lambda *a: datetime(*a, tzinfo=ATH) # noqa: E731
|
||||||
|
assert ordering.is_open(cfg, local(2026, 11, 15, 18, 0))
|
||||||
|
assert not ordering.is_open(cfg, local(2026, 11, 15, 23, 0))
|
||||||
|
assert not ordering.is_open(cfg, local(2026, 11, 15, 12, 0))
|
||||||
|
assert ordering.is_open(cfg, local(2026, 11, 15, 1, 30)) # Saturday's 20:00–02:00, after midnight
|
||||||
|
assert not ordering.is_open(cfg, local(2026, 11, 16, 19, 0)) # Monday has no hours: closed
|
||||||
|
assert ordering.is_open(ordering.config(snap()), local(2026, 11, 16, 4, 0)) # no hours = any time
|
||||||
|
|
||||||
|
|
||||||
|
def test_slots_start_after_preparation_on_the_grid_and_stay_in_hours():
|
||||||
|
s = snap(hours=EVENINGS)
|
||||||
|
got = [t.strftime("%H:%M") for t in ordering.slots(s, at(2026, 11, 15, 21, 7))]
|
||||||
|
assert got == ["21:30", "21:45", "22:00", "22:15", "22:30", "22:45"] # 21:07 + 20 → 21:27 → 21:30
|
||||||
|
assert ordering.slots(s, at(2026, 11, 15, 22, 50)) == [] # nothing left today
|
||||||
|
ahead = ordering.slots(snap(hours=EVENINGS, days_ahead=1, slot_minutes=30), at(2026, 11, 15, 22, 50))
|
||||||
|
assert ahead == [] # Monday closed
|
||||||
|
morning = [t.strftime("%H:%M") for t in ordering.slots(s, at(2026, 11, 15, 10, 0))]
|
||||||
|
assert morning[0] == "18:00" and morning[-1] == "22:45"
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_asap_and_requested_times():
|
||||||
|
s = snap(hours=EVENINGS)
|
||||||
|
evening, noon = at(2026, 11, 15, 21, 7), at(2026, 11, 15, 12, 0)
|
||||||
|
assert ordering.check(s, "delivery", None, evening) is None
|
||||||
|
assert ordering.check(s, "delivery", None, noon) == ("order.closed", {}) # closed now: no ASAP
|
||||||
|
assert ordering.check(s, "takeaway", at(2026, 11, 15, 18, 30), noon) is None # but a later slot is fine
|
||||||
|
assert ordering.check(s, "takeaway", at(2026, 11, 15, 18, 31), noon)[0] == "order.time_invalid" # off the grid
|
||||||
|
assert ordering.check(s, "takeaway", at(2026, 11, 15, 21, 15), evening)[0] == "order.time_invalid" # too soon
|
||||||
|
assert ordering.check(snap(asap=False), "delivery", None, evening) == ("order.closed", {})
|
||||||
|
assert ordering.check(snap(services=["takeaway"]), "delivery", None, evening) == ("order.service_unavailable", {"service": "delivery"})
|
||||||
|
assert ordering.check(s, "takeaway", datetime(2026, 11, 15, 18, 30), noon)[0] == "order.time_invalid" # no zone
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_endpoints_enforce_it(client, admin_h):
|
||||||
|
site, numeric = _venue(client, admin_h)
|
||||||
|
# the venue turns delivery off and opens only on Mondays 12:00–13:00
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
snapshot = {"categories": menu["categories"], "timezone": "Europe/Athens",
|
||||||
|
"ordering": {"services": ["takeaway"], "hours": {"0": [["12:00", "13:00"]]}, "prep_minutes": 0,
|
||||||
|
"slot_minutes": 15, "days_ahead": 7, "asap": True}}
|
||||||
|
client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snapshot)})
|
||||||
|
s = client.get(f"/api/orders/{site['site_id']}/slots").json()
|
||||||
|
assert s["services"] == ["takeaway"] and len(s["slots"]) >= 4
|
||||||
|
first = datetime.fromisoformat(s["slots"][0])
|
||||||
|
assert first.astimezone(ATH).weekday() == 0 and first.astimezone(ATH).strftime("%H:%M") >= "12:00"
|
||||||
|
assert client.get(f"/api/menu/{site['site_id']}").json()["ordering"]["services"] == ["takeaway"]
|
||||||
|
assert _code(_order(client, site, "delivery", customer_address="x")) == "order.service_unavailable"
|
||||||
|
r = _order(client, site, "takeaway", requested_for=s["slots"][0])
|
||||||
|
assert r.status_code == 201, r.text
|
||||||
|
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == r.json()["public_ref"])
|
||||||
|
assert datetime.fromisoformat(stored["requested_for"].replace("Z", "+00:00")) == first
|
||||||
|
track = client.get(f"/api/orders/track/{r.json()['tracking_token']}").json()
|
||||||
|
assert track["requested_for"] and track["order_type"] == "takeaway"
|
||||||
|
# a takeaway or delivery order needs a phone number
|
||||||
|
assert _code(_order(client, site, "takeaway", customer_phone="", requested_for=s["slots"][0])) == "order.details_missing"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rate_limits(client, admin_h):
|
||||||
|
from services import ratelimit
|
||||||
|
site, _ = _venue(client, admin_h)
|
||||||
|
statuses = [_order(client, site).status_code for _ in range(11)]
|
||||||
|
assert statuses[:10] == [201] * 10 and statuses[10] == 429
|
||||||
|
assert _code(_order(client, site)) == "rate.limited"
|
||||||
|
# another address is counted apart (behind the proxy)
|
||||||
|
ok = client.post(f"/api/orders/{site['site_id']}", headers={"X-Forwarded-For": "203.0.113.9"},
|
||||||
|
json={"order_type": "takeaway", "customer_name": "A", "customer_phone": "1", "items": [{"product_id": COLA, "quantity": 1}]})
|
||||||
|
assert ok.status_code == 201
|
||||||
|
assert ratelimit.hit("t", "k", 2, 60, now=0) and ratelimit.hit("t", "k", 2, 60, now=1) and not ratelimit.hit("t", "k", 2, 60, now=2)
|
||||||
|
assert ratelimit.hit("t", "k", 2, 60, now=61) # the window moves on
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""The QR menu at the table (plan phase 3S, step S.7): ordering only with a table's QR token
|
||||||
|
(checked by its hash from the snapshot), only when the venue allows it; the public menu says
|
||||||
|
which table the token is and never shows the hashes; a forged token is refused."""
|
||||||
|
import json
|
||||||
|
|
||||||
|
from services import qr
|
||||||
|
from test_checkout import ORDERING, PIE, _code, _h, _order, _venue
|
||||||
|
|
||||||
|
|
||||||
|
def _push_qr(client, site, numeric, ordering=True, tables=None):
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
tables = tables if tables is not None else [{"id": 5, "label": "T5", "token_hash": qr.token_hash("tok-five")},
|
||||||
|
{"id": 6, "label": "Garden 6", "token_hash": qr.token_hash("tok-six")}]
|
||||||
|
snap = {"categories": menu["categories"], "ordering": ORDERING, "timezone": "Europe/Athens",
|
||||||
|
"qr": {"ordering": ordering, "tables": tables}}
|
||||||
|
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snap)})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_table_token_finds_its_table():
|
||||||
|
snap = {"qr": {"tables": [{"id": 5, "label": "T5", "token_hash": qr.token_hash("abc")}]}}
|
||||||
|
assert qr.table_for(snap, "abc") == {"id": 5, "label": "T5"}
|
||||||
|
assert qr.table_for(snap, "abd") is None
|
||||||
|
assert qr.table_for(snap, "") is None and qr.table_for(snap, None) is None
|
||||||
|
assert qr.table_for({}, "abc") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_ordering_at_the_table_needs_a_real_table_token(client, admin_h):
|
||||||
|
site, numeric = _venue(client, admin_h)
|
||||||
|
_push_qr(client, site, numeric)
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-five"}).json()
|
||||||
|
assert menu["table_ordering"] is True and menu["table"] == {"id": 5, "label": "T5"} and menu["table_invalid"] is False
|
||||||
|
assert "qr" not in menu # the hashes stay on the cloud
|
||||||
|
forged = client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-seven"}).json()
|
||||||
|
assert forged["table"] is None and forged["table_invalid"] is True
|
||||||
|
assert "table" not in client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
|
||||||
|
r = _order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 2}])
|
||||||
|
assert r.status_code == 201, r.text
|
||||||
|
stored = next(o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == r.json()["public_ref"])
|
||||||
|
assert (stored["table_id"], stored["table_label"], stored["sales_point"], stored["total"]) == (5, "T5", "qr_table", 10.0)
|
||||||
|
# a forged token, none, or a table name typed in by hand: refused
|
||||||
|
assert _code(_order(client, site, "dine_in", table_token="tok-seven", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
|
||||||
|
assert _code(_order(client, site, "dine_in", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
|
||||||
|
r = _order(client, site, "dine_in", customer_table="5", items=[{"product_id": PIE, "quantity": 1}])
|
||||||
|
assert r.status_code == 403 and _code(r) == "order.table_invalid"
|
||||||
|
# a new QR code for table 5: the old one stops working at the next push
|
||||||
|
_push_qr(client, site, numeric, tables=[{"id": 5, "label": "T5", "token_hash": qr.token_hash("tok-five-new")}])
|
||||||
|
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.table_invalid"
|
||||||
|
assert _order(client, site, "dine_in", table_token="tok-five-new", items=[{"product_id": PIE, "quantity": 1}]).status_code == 201
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_only_menus_take_no_table_orders(client, admin_h):
|
||||||
|
site, numeric = _venue(client, admin_h)
|
||||||
|
_push_qr(client, site, numeric, ordering=False)
|
||||||
|
assert client.get(f"/api/menu/{site['site_id']}", params={"t": "tok-five"}).json()["table_ordering"] is False
|
||||||
|
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.service_unavailable"
|
||||||
|
# the venue allows it, but the sysadmin set the site's menu to view only
|
||||||
|
_push_qr(client, site, numeric, ordering=True)
|
||||||
|
r = client.put(f"/api/sites/{site['site_id']}", headers=admin_h, json={"menu_mode": "view_only"})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert _code(_order(client, site, "dine_in", table_token="tok-five", items=[{"product_id": PIE, "quantity": 1}])) == "order.service_unavailable"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_sysadmin_gets_the_apps_address(client, admin_h, monkeypatch):
|
||||||
|
from config import settings
|
||||||
|
site, _ = _venue(client, admin_h)
|
||||||
|
monkeypatch.setattr(settings, "PUBLIC_APPS_URL", "https://menu.example.com/")
|
||||||
|
got = client.get(f"/api/sites/{site['site_id']}", headers=admin_h).json()
|
||||||
|
assert got["apps_url"] == "https://menu.example.com"
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"""Reservations online (plan phase 3S, step S.6): a table only, or a table with food ready on
|
||||||
|
arrival; times on the venue's grid, inside its hours, with notice, up to N days ahead; party
|
||||||
|
size; the venue confirms or declines, then the guests arrive or the venue cancels."""
|
||||||
|
import json
|
||||||
|
from datetime import date, datetime, timezone
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from services import ordering
|
||||||
|
from test_checkout import COLA, ORDERING, _code, _h, _venue
|
||||||
|
|
||||||
|
ATH = ZoneInfo("Europe/Athens")
|
||||||
|
DINNER = {"0": [["19:00", "23:00"]], "6": [["13:00", "16:00"], ["19:00", "23:00"]]} # Mon, Sun
|
||||||
|
|
||||||
|
|
||||||
|
def snap(**res):
|
||||||
|
return {"timezone": "Europe/Athens", "ordering": {**ORDERING, "reservations": {
|
||||||
|
"enabled": True, "with_food": True, "hours": DINNER, "slot_minutes": 30, "days_ahead": 14,
|
||||||
|
"notice_minutes": 120, "party_max": 8, **res}}}
|
||||||
|
|
||||||
|
|
||||||
|
def at(y, mo, d, h, mi):
|
||||||
|
return datetime(y, mo, d, h, mi, tzinfo=ATH).astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def test_times_days_and_checks():
|
||||||
|
s, now = snap(), at(2026, 11, 15, 18, 10) # Sunday 18:10
|
||||||
|
sunday = [t.strftime("%H:%M") for t in ordering.res_slots(s, date(2026, 11, 15), now)]
|
||||||
|
assert sunday == ["20:30", "21:00", "21:30", "22:00", "22:30"] # 2 h notice; lunch is over
|
||||||
|
monday = [t.strftime("%H:%M") for t in ordering.res_slots(s, date(2026, 11, 16), now)]
|
||||||
|
assert monday[0] == "19:00" and monday[-1] == "22:30"
|
||||||
|
assert ordering.res_slots(s, date(2026, 11, 17), now) == [] # Tuesday: no hours = closed
|
||||||
|
assert ordering.res_slots(s, date(2026, 11, 30), now) == [] # beyond 14 days
|
||||||
|
days = ordering.res_days(s, now)
|
||||||
|
assert days[:3] == ["2026-11-15", "2026-11-16", "2026-11-22"] and "2026-11-17" not in days
|
||||||
|
ok = at(2026, 11, 16, 20, 0)
|
||||||
|
assert ordering.res_check(s, "reservation", ok, 4, now) is None
|
||||||
|
assert ordering.res_check(s, "preorder", ok, 4, now) is None
|
||||||
|
assert ordering.res_check(s, "reservation", ok, 9, now) == ("order.party_invalid", {"max": 8})
|
||||||
|
assert ordering.res_check(s, "reservation", ok, 0, now)[0] == "order.party_invalid"
|
||||||
|
assert ordering.res_check(s, "reservation", ok, None, now)[0] == "order.party_invalid"
|
||||||
|
assert ordering.res_check(s, "reservation", at(2026, 11, 16, 20, 10), 2, now)[0] == "order.time_invalid" # off grid
|
||||||
|
assert ordering.res_check(s, "reservation", at(2026, 11, 15, 19, 0), 2, now)[0] == "order.time_invalid" # too soon
|
||||||
|
assert ordering.res_check(s, "reservation", None, 2, now)[0] == "order.time_invalid"
|
||||||
|
assert ordering.res_check(snap(with_food=False), "preorder", ok, 2, now) == ("order.service_unavailable", {"service": "preorder"})
|
||||||
|
assert ordering.res_check(snap(enabled=False), "reservation", ok, 2, now)[0] == "order.service_unavailable"
|
||||||
|
assert ordering.res_summary(snap(enabled=False), now) == {"enabled": False, "with_food": False, "party_max": 8, "days": []}
|
||||||
|
|
||||||
|
|
||||||
|
def _push(client, site, numeric, **res):
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
hours = {str(d): [["00:00", "23:59"]] for d in range(7)}
|
||||||
|
snapshot = {"categories": menu["categories"], "timezone": "Europe/Athens",
|
||||||
|
"ordering": {**ORDERING, "reservations": {"enabled": True, "with_food": True, "hours": hours, "slot_minutes": 30,
|
||||||
|
"days_ahead": 3, "notice_minutes": 0, "party_max": 6, **res}}}
|
||||||
|
for cat in snapshot["categories"]:
|
||||||
|
for p in cat["products"]:
|
||||||
|
if p["id"] == COLA:
|
||||||
|
p["sold_at"] = [*p["sold_at"], "online_preorder"]
|
||||||
|
p["prices"] = {**p["prices"], "online_preorder": 2.6}
|
||||||
|
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snapshot)})
|
||||||
|
assert r.status_code in (200, 204), r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_book_a_table_with_and_without_food(client, admin_h):
|
||||||
|
site, numeric = _venue(client, admin_h)
|
||||||
|
_push(client, site, numeric)
|
||||||
|
menu = client.get(f"/api/menu/{site['site_id']}").json()
|
||||||
|
res = menu["ordering"]["reservations"]
|
||||||
|
assert res["enabled"] and res["with_food"] and res["party_max"] == 6 and len(res["days"]) == 4
|
||||||
|
day = res["days"][1]
|
||||||
|
slots = client.get(f"/api/orders/{site['site_id']}/reservation-slots", params={"day": day}).json()["slots"]
|
||||||
|
assert len(slots) == 48
|
||||||
|
when = slots[40] # 20:00 tomorrow
|
||||||
|
book = lambda **x: client.post(f"/api/orders/{site['site_id']}", json={ # noqa: E731
|
||||||
|
"order_type": "reservation", "customer_name": "Eleni", "customer_phone": "6977777777", "party_size": 4,
|
||||||
|
"requested_for": when, "customer_notes": "By the window", **x})
|
||||||
|
plain = book()
|
||||||
|
assert plain.status_code == 201, plain.text
|
||||||
|
assert _code(book(party_size=7)) == "order.party_invalid"
|
||||||
|
assert _code(book(customer_phone="")) == "order.details_missing"
|
||||||
|
assert _code(book(items=[{"product_id": COLA, "quantity": 1}])) == "order.items_not_allowed"
|
||||||
|
assert _code(book(requested_for=None)) == "order.time_invalid"
|
||||||
|
food = book(order_type="preorder", items=[{"product_id": COLA, "quantity": 2}], total=5.2)
|
||||||
|
assert food.status_code == 201, food.text
|
||||||
|
assert food.json()["total"] == 5.2 # the preorder price
|
||||||
|
assert _code(book(order_type="preorder", items=[])) == "order.empty"
|
||||||
|
pending = {o["public_ref"]: o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()}
|
||||||
|
p = pending[plain.json()["public_ref"]]
|
||||||
|
assert (p["order_type"], p["party_size"], p["total"], json.loads(p["items_json"]), p["sales_point"]) == ("reservation", 4, 0.0, [], None)
|
||||||
|
assert datetime.fromisoformat(p["requested_for"].replace("Z", "+00:00")) == datetime.fromisoformat(when)
|
||||||
|
f = pending[food.json()["public_ref"]]
|
||||||
|
assert (f["order_type"], f["sales_point"], f["party_size"]) == ("preorder", "online_preorder", 4)
|
||||||
|
# the venue confirms, then the guests arrive (or it cancels); the customer's page follows
|
||||||
|
st = lambda oid, s: client.patch(f"/api/orders/{oid}/status", headers=_h(site), json={"status": s}) # noqa: E731
|
||||||
|
assert st(p["id"], "preparing").status_code == 422
|
||||||
|
assert st(p["id"], "accepted").status_code == 204
|
||||||
|
assert st(p["id"], "delivered").status_code == 204
|
||||||
|
assert st(f["id"], "accepted").status_code == 204 and st(f["id"], "cancelled").status_code == 204
|
||||||
|
track = client.get(f"/api/orders/track/{food.json()['tracking_token']}").json()
|
||||||
|
assert (track["status"], track["order_type"], track["party_size"], track["total"]) == ("cancelled", "preorder", 4, 5.2)
|
||||||
|
# an ordinary order can't be "cancelled" this way
|
||||||
|
order = client.post(f"/api/orders/{site['site_id']}", json={"order_type": "takeaway", "customer_name": "M",
|
||||||
|
"customer_phone": "6900000000", "items": [{"product_id": COLA, "quantity": 1}]})
|
||||||
|
oid = next(o["id"] for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == order.json()["public_ref"])
|
||||||
|
st(oid, "accepted")
|
||||||
|
assert st(oid, "cancelled").status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_reservations_off_by_default(client, admin_h):
|
||||||
|
site, _ = _venue(client, admin_h)
|
||||||
|
assert client.get(f"/api/menu/{site['site_id']}").json()["ordering"]["reservations"]["enabled"] is False
|
||||||
|
r = client.post(f"/api/orders/{site['site_id']}", json={"order_type": "reservation", "customer_name": "E", "customer_phone": "690000000",
|
||||||
|
"party_size": 2, "requested_for": datetime.now(timezone.utc).isoformat()})
|
||||||
|
assert _code(r) == "order.service_unavailable"
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""Cloud schema guard (APPS_PLATFORM D-22): Alembic only, baseline = v1 production, no drift."""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from alembic.autogenerate import compare_metadata
|
||||||
|
from alembic.migration import MigrationContext
|
||||||
|
from sqlalchemy import create_engine, text
|
||||||
|
|
||||||
|
from schema import BASELINE, UnstampedDatabaseError, stamp_baseline, upgrade_to_head
|
||||||
|
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
V1_SQL = (HERE / "fixtures" / "v1_cloud_schema.sql").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _v1_db(path: Path):
|
||||||
|
con = sqlite3.connect(path)
|
||||||
|
con.executescript(V1_SQL)
|
||||||
|
con.execute("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, "
|
||||||
|
"is_locked, license_expires_at, order_counter, menu_mode, menu_hours_en) values "
|
||||||
|
"(1, 'site-1', 'Kopse', 'O', 'o@x', 'h', 1, 0, '2027-05-01 00:00:00', 7, 'order', 'old')")
|
||||||
|
con.commit()
|
||||||
|
con.close()
|
||||||
|
return create_engine(f"sqlite:///{path.as_posix()}")
|
||||||
|
|
||||||
|
|
||||||
|
def _shape(path):
|
||||||
|
con = sqlite3.connect(path)
|
||||||
|
tables = {t: sorted((r[1], r[2].upper(), r[3]) for r in con.execute(f'pragma table_info("{t}")'))
|
||||||
|
for (t,) in con.execute("select name from sqlite_master where type='table' "
|
||||||
|
"and name not in ('alembic_version', 'sqlite_sequence')")}
|
||||||
|
idx = sorted(r[0] for r in con.execute("select name from sqlite_master where type='index' and name not like 'sqlite_%'"))
|
||||||
|
con.close()
|
||||||
|
return tables, idx
|
||||||
|
|
||||||
|
|
||||||
|
def test_baseline_equals_v1_production_schema(tmp_path):
|
||||||
|
from schema import alembic_config
|
||||||
|
from alembic import command
|
||||||
|
eng = create_engine(f"sqlite:///{(tmp_path / 'b.db').as_posix()}")
|
||||||
|
with eng.begin() as conn:
|
||||||
|
command.upgrade(alembic_config(conn), BASELINE)
|
||||||
|
eng.dispose()
|
||||||
|
con = sqlite3.connect(tmp_path / "v1.db")
|
||||||
|
con.executescript(V1_SQL)
|
||||||
|
con.close()
|
||||||
|
assert _shape(tmp_path / "b.db") == _shape(tmp_path / "v1.db")
|
||||||
|
|
||||||
|
|
||||||
|
def test_unstamped_v1_db_is_refused(tmp_path):
|
||||||
|
eng = _v1_db(tmp_path / "prod.db")
|
||||||
|
with pytest.raises(UnstampedDatabaseError):
|
||||||
|
upgrade_to_head(eng)
|
||||||
|
|
||||||
|
|
||||||
|
def test_stamp_then_upgrade_a_v1_db(tmp_path): # the cutover procedure
|
||||||
|
eng = _v1_db(tmp_path / "prod.db")
|
||||||
|
stamp_baseline(eng)
|
||||||
|
upgrade_to_head(eng)
|
||||||
|
with eng.connect() as conn:
|
||||||
|
site = conn.execute(text("select site_id, order_counter, modules from sites")).one()
|
||||||
|
presets = conn.execute(text("select name from plan_presets")).scalars().all()
|
||||||
|
cols = [r[1] for r in conn.execute(text("pragma table_info(sites)"))]
|
||||||
|
eng.dispose()
|
||||||
|
assert site[0] == "site-1" and site[1] == 7 # data kept
|
||||||
|
mods = json.loads(site[2])
|
||||||
|
assert {"ordering", "waiter_app", "kds", "connect_menu"} <= set(mods)
|
||||||
|
assert mods["kds"] == {"limits": {"devices": None}} # v1 had no KDS limit
|
||||||
|
assert presets == ["Everything (v1 sites)"]
|
||||||
|
assert "menu_hours_en" not in cols
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_drift_between_models_and_migrations(tmp_path):
|
||||||
|
from database import Base
|
||||||
|
import models.all # noqa: F401
|
||||||
|
eng = create_engine(f"sqlite:///{(tmp_path / 'd.db').as_posix()}")
|
||||||
|
upgrade_to_head(eng)
|
||||||
|
with eng.connect() as conn:
|
||||||
|
diff = compare_metadata(MigrationContext.configure(conn, opts={"compare_type": True}), Base.metadata)
|
||||||
|
eng.dispose()
|
||||||
|
assert diff == [], "\n".join(map(str, diff))
|
||||||
|
|
||||||
|
|
||||||
|
def test_nothing_calls_create_all():
|
||||||
|
root = HERE.parent
|
||||||
|
bad = [p.relative_to(root).as_posix() for p in root.rglob("*.py")
|
||||||
|
if not p.relative_to(root).as_posix().startswith(("tests/", "migrations/"))
|
||||||
|
and re.search(r"\.create_all\(", p.read_text(encoding="utf-8", errors="ignore"))]
|
||||||
|
assert bad == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_0003_keeps_orders_gives_tokens_and_refs_per_site(tmp_path):
|
||||||
|
"""Existing online orders survive the table rebuild, get a tracking token, and two sites
|
||||||
|
may now both have ORD-0001 (plan phase 3S, S.2)."""
|
||||||
|
from schema import alembic_config
|
||||||
|
from alembic import command
|
||||||
|
import sqlalchemy as sa
|
||||||
|
eng = create_engine(f"sqlite:///{(tmp_path / 'c.db').as_posix()}")
|
||||||
|
with eng.begin() as conn:
|
||||||
|
command.upgrade(alembic_config(conn), "0002_v2_licensing")
|
||||||
|
for sid in (1, 2):
|
||||||
|
conn.execute(text("insert into sites (id, site_id, name, owner_name, contact_email, secret_key_hash, is_active, "
|
||||||
|
"license_expires_at, created_at, order_counter, menu_mode) "
|
||||||
|
"values (:i, :s, 'S', 'O', 'o@x', 'x', 1, '2027-01-01', '2026-01-01', 1, 'order')"), {"i": sid, "s": f"site-{sid}"})
|
||||||
|
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
|
||||||
|
"delivery_fee, total, status, synced_to_local) values (1, 'ORD-0001', 'dine_in', 'A', '[]', 1, 0, 1, 'delivered', 1)"))
|
||||||
|
upgrade_to_head(eng)
|
||||||
|
with eng.begin() as conn:
|
||||||
|
row = conn.execute(text("select public_ref, tracking_token from online_orders")).one()
|
||||||
|
assert row[0] == "ORD-0001" and row[1]
|
||||||
|
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
|
||||||
|
"delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'B', '[]', 1, 0, 1, 'delivered', 0)"))
|
||||||
|
with pytest.raises(sa.exc.IntegrityError):
|
||||||
|
with conn.begin_nested():
|
||||||
|
conn.execute(text("insert into online_orders (site_id, public_ref, order_type, customer_name, items_json, subtotal, "
|
||||||
|
"delivery_fee, total, status, synced_to_local) values (2, 'ORD-0001', 'dine_in', 'C', '[]', 1, 0, 1, 'delivered', 0)"))
|
||||||
|
idx = {i["name"] for i in sa.inspect(conn).get_indexes("online_orders")}
|
||||||
|
eng.dispose()
|
||||||
|
assert {"ix_online_orders_site_id", "ix_online_orders_status"} <= idx
|
||||||
@@ -8,6 +8,16 @@ ARG VITE_CLOUD_URL=
|
|||||||
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
|
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
|
# Build order-app (online ordering: takeaway and delivery, plan phase 3S S.4)
|
||||||
|
FROM node:20-alpine AS order-builder
|
||||||
|
WORKDIR /app/order-app
|
||||||
|
COPY order-app/package.json order-app/package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY order-app/ .
|
||||||
|
ARG VITE_CLOUD_URL=
|
||||||
|
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
|
||||||
|
RUN npm test && npm run build
|
||||||
|
|
||||||
# Build manager-app
|
# Build manager-app
|
||||||
FROM node:20-alpine AS manager-builder
|
FROM node:20-alpine AS manager-builder
|
||||||
WORKDIR /app/manager-app
|
WORKDIR /app/manager-app
|
||||||
@@ -18,8 +28,9 @@ ARG VITE_CLOUD_URL=
|
|||||||
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
|
ENV VITE_CLOUD_URL=$VITE_CLOUD_URL
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# Serve both with nginx
|
# Serve them with nginx
|
||||||
FROM nginx:alpine
|
FROM nginx:alpine
|
||||||
COPY --from=menu-builder /app/menu-app/dist /usr/share/nginx/html/menu
|
COPY --from=menu-builder /app/menu-app/dist /usr/share/nginx/html/menu
|
||||||
COPY --from=manager-builder /app/manager-app/dist /usr/share/nginx/html/manage
|
COPY --from=manager-builder /app/manager-app/dist /usr/share/nginx/html/manage
|
||||||
|
COPY --from=order-builder /app/order-app/dist /usr/share/nginx/html/order
|
||||||
COPY nginx-connect.conf /etc/nginx/conf.d/default.conf
|
COPY nginx-connect.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|||||||
@@ -64,10 +64,20 @@ export default function DashboardPage() {
|
|||||||
|
|
||||||
{lastUpdated && (
|
{lastUpdated && (
|
||||||
<p className="text-xs text-slate-400 text-right">
|
<p className="text-xs text-slate-400 text-right">
|
||||||
Updated {lastUpdated.toLocaleTimeString()}
|
Refreshed {lastUpdated.toLocaleTimeString()}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{stats.snapshot_taken_at && (() => {
|
||||||
|
const diffMin = Math.round((Date.now() - new Date(stats.snapshot_taken_at).getTime()) / 60_000)
|
||||||
|
const label = diffMin < 1 ? 'just now' : `${diffMin} min ago`
|
||||||
|
return (
|
||||||
|
<p className="text-xs text-slate-400 text-right -mt-3">
|
||||||
|
Site data: {label}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
})()}
|
||||||
|
|
||||||
{/* Pending orders */}
|
{/* Pending orders */}
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="el">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
<title>Xenia Menu</title>
|
<meta name="theme-color" content="#1f3a34" />
|
||||||
|
<title>Menu</title>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,400;12..96,500;12..96,600;12..96,700&family=Hanken+Grotesk:wght@400;500;600;700&family=Noto+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
+3054
File diff suppressed because it is too large
Load Diff
@@ -6,14 +6,14 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test": "node --test \"tests/*.test.mjs\""
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.7.9",
|
"axios": "^1.7.9",
|
||||||
"lucide-react": "^1.14.0",
|
"lucide-react": "^1.14.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-hot-toast": "^2.4.1",
|
|
||||||
"react-router-dom": "^6.28.0"
|
"react-router-dom": "^6.28.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
import { Routes, Route, Navigate } from 'react-router-dom'
|
|
||||||
import MenuPage from './pages/MenuPage'
|
|
||||||
import CartPage from './pages/CartPage'
|
|
||||||
import OrderConfirm from './pages/OrderConfirm'
|
|
||||||
|
|
||||||
export default function App() {
|
|
||||||
return (
|
|
||||||
<Routes>
|
|
||||||
<Route path="/:siteSlug" element={<MenuPage />} />
|
|
||||||
<Route path="/:siteSlug/order" element={<CartPage />} />
|
|
||||||
<Route path="/:siteSlug/confirm/:ref" element={<OrderConfirm />} />
|
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
|
||||||
</Routes>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,21 @@
|
|||||||
|
// The cloud's public endpoints for the QR menu (cloud_backend/routers/menu.py, orders.py).
|
||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
|
|
||||||
const BASE = import.meta.env.VITE_CLOUD_URL || ''
|
export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || ''
|
||||||
|
const api = axios.create({ baseURL: CLOUD_URL, timeout: 15000 })
|
||||||
|
|
||||||
const api = axios.create({ baseURL: BASE })
|
/** The menu; with a table's QR token (phase 3S, S.7) also which table it is (`table`, or
|
||||||
|
* `table_invalid`) and whether ordering at the table is on (`table_ordering`). */
|
||||||
export async function fetchMenu(siteSlug) {
|
export const fetchMenu = async (site, tableToken) =>
|
||||||
const { data } = await api.get(`/api/menu/${siteSlug}`)
|
(await api.get(`/api/menu/${encodeURIComponent(site)}`, { params: tableToken ? { t: tableToken } : {} })).data
|
||||||
return data
|
export const placeOrder = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}`, body)).data
|
||||||
}
|
/** The tracking link carries the order's random token (S.2); older links carry the public ref. */
|
||||||
|
export async function track(ref) {
|
||||||
export async function submitOrder(siteSlug, body) {
|
try {
|
||||||
const { data } = await api.post(`/api/orders/${siteSlug}`, body)
|
return (await api.get(`/api/orders/track/${encodeURIComponent(ref)}`)).data
|
||||||
return data // { order_id, public_ref, status }
|
} catch (err) {
|
||||||
}
|
if (err?.response?.status !== 404 || !/^ORD-\d+$/.test(ref)) throw err
|
||||||
|
return (await api.get(`/api/orders/status/${encodeURIComponent(ref)}`)).data
|
||||||
export async function fetchOrderStatus(publicRef) {
|
}
|
||||||
const { data } = await api.get(`/api/orders/status/${publicRef}`)
|
|
||||||
return data // { public_ref, status, rejection_reason }
|
|
||||||
}
|
}
|
||||||
|
export const imageUrl = url => (!url ? null : /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}`)
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
import { useNavigate } from 'react-router-dom'
|
|
||||||
import { ShoppingCart } from 'lucide-react'
|
|
||||||
|
|
||||||
export default function CartButton({ cart, siteSlug }) {
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const count = cart.reduce((s, i) => s + i.quantity, 0)
|
|
||||||
const total = cart.reduce((s, i) => s + i.unit_price * i.quantity, 0)
|
|
||||||
|
|
||||||
if (!count) return null
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed bottom-6 left-0 right-0 flex justify-center px-4 z-30">
|
|
||||||
<button
|
|
||||||
onClick={() => navigate(`/${siteSlug}/order`, { state: { cart } })}
|
|
||||||
className="bg-emerald-500 hover:bg-emerald-600 text-white rounded-2xl px-6 py-3.5 shadow-lg flex items-center gap-3 w-full max-w-sm transition-colors"
|
|
||||||
>
|
|
||||||
<span className="bg-emerald-600 text-white text-xs font-bold w-6 h-6 rounded-full flex items-center justify-center">
|
|
||||||
{count}
|
|
||||||
</span>
|
|
||||||
<span className="flex-1 font-semibold text-left">View order</span>
|
|
||||||
<span className="font-bold">€{total.toFixed(2)}</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
export default function CategoryNav({ categories, active, onSelect }) {
|
|
||||||
return (
|
|
||||||
<div className="flex gap-1 overflow-x-auto px-4 pb-2 pt-1 scrollbar-hide">
|
|
||||||
{categories.map(cat => (
|
|
||||||
<button
|
|
||||||
key={cat.id}
|
|
||||||
onClick={() => onSelect(cat.id)}
|
|
||||||
className={`flex-shrink-0 px-4 py-1.5 rounded-full text-sm font-medium transition-colors ${
|
|
||||||
active === cat.id
|
|
||||||
? 'bg-emerald-500 text-white'
|
|
||||||
: 'bg-slate-100 text-slate-600 hover:bg-slate-200'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{cat.name}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
export default function ProductCard({ product, onSelect }) {
|
|
||||||
const unavailable = !product.digital_available
|
|
||||||
const basePrice = product.digital_price ?? product.base_price
|
|
||||||
const hasDiscount = product.digital_discount > 0 && !product.digital_price
|
|
||||||
const displayPrice = hasDiscount
|
|
||||||
? basePrice * (1 - product.digital_discount / 100)
|
|
||||||
: basePrice
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
onClick={unavailable ? undefined : onSelect}
|
|
||||||
className={`w-full bg-white rounded-2xl shadow-sm p-4 flex gap-4 text-left transition-shadow ${
|
|
||||||
unavailable ? 'opacity-60 cursor-default' : 'hover:shadow-md active:scale-[0.99]'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{/* Image */}
|
|
||||||
{(product.digital_image_url || product.image_url) && (
|
|
||||||
<img
|
|
||||||
src={product.digital_image_url || product.image_url}
|
|
||||||
alt={product.digital_name || product.name}
|
|
||||||
className="w-20 h-20 rounded-xl object-cover flex-shrink-0"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex-1 min-w-0 space-y-1">
|
|
||||||
<div className="flex items-start justify-between gap-2">
|
|
||||||
<h3 className="font-semibold text-slate-800 leading-tight">
|
|
||||||
{product.digital_name || product.name}
|
|
||||||
</h3>
|
|
||||||
{unavailable && (
|
|
||||||
<span className="flex-shrink-0 text-xs bg-slate-100 text-slate-500 px-2 py-0.5 rounded-full">
|
|
||||||
Out of stock
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{product.digital_description && (
|
|
||||||
<p className="text-xs text-slate-500 line-clamp-2">{product.digital_description}</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex items-baseline gap-2 pt-1">
|
|
||||||
<span className="font-bold text-emerald-600">€{displayPrice.toFixed(2)}</span>
|
|
||||||
{hasDiscount && (
|
|
||||||
<>
|
|
||||||
<span className="text-xs text-slate-400 line-through">€{basePrice.toFixed(2)}</span>
|
|
||||||
<span className="text-xs bg-red-100 text-red-600 px-1.5 py-0.5 rounded-full font-semibold">
|
|
||||||
-{product.digital_discount}%
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// The QR menu's texts (en, el; plan step 6.5, same shape as the order app's). The guest's choice
|
||||||
|
// is remembered on this device; the first visit follows the browser's language.
|
||||||
|
import { createContext, useContext } from 'react'
|
||||||
|
|
||||||
|
const STORE = 'xenia-menu-lang'
|
||||||
|
const OLD_STORE = 'ot_lang' // the menu app before 6.5 kept 'en' / 'gr' here
|
||||||
|
|
||||||
|
export const TEXTS = {
|
||||||
|
en: {
|
||||||
|
menu: 'Menu', loading: 'Loading the menu…', notFound: 'This menu was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.',
|
||||||
|
retry: 'Try again', language: 'Language', categories: 'Categories', search: 'Search the menu…', searchOpen: 'Search', close: 'Close',
|
||||||
|
noResults: 'No dishes found', noResultsBody: 'Try a different word.',
|
||||||
|
add: 'Add', soldOut: 'Sold out', more: 'More', less: 'Less',
|
||||||
|
allergens: 'Allergens', contains: 'Contains', mayContain: 'May contain', noAllergens: 'No allergens declared. Ask the staff if you have an allergy.',
|
||||||
|
allergenNote: 'Ask the staff if you have an allergy.',
|
||||||
|
atTable: 'Table {{table}}: order from your phone', tableInvalid: 'This QR code is no longer valid. Please ask the staff.',
|
||||||
|
orderingOff: 'Ordering from the table is not available right now. Please ask the staff.',
|
||||||
|
viewOrder: 'Your order', items_one: '{{count}} item', items_other: '{{count}} items',
|
||||||
|
yourOrder: 'Your order', empty: 'Your order is empty.', emptyBody: 'Add a few dishes to get started.', total: 'Total', continue: 'Continue', back: 'Back',
|
||||||
|
table: 'Table', checkout: 'Send to the kitchen', name: 'Your name (optional)', namePlaceholder: 'e.g. Alex', summary: 'Your order',
|
||||||
|
placeOrder: 'Place order · {{total}}', sending: 'Sending…', payNote: 'You pay at the table.',
|
||||||
|
refused: {
|
||||||
|
changed: 'Something on the menu changed since you opened it. Please reload the page and check your order.',
|
||||||
|
rate: 'Too many attempts. Please wait a few minutes.', failed: 'The order could not be sent. Please try again.',
|
||||||
|
},
|
||||||
|
track: {
|
||||||
|
pending_acceptance: 'Sending your order to the kitchen…', accepted: 'Your order is in the kitchen', rejected: 'Order not taken',
|
||||||
|
acceptedBody: 'Thank you! Your waiter will bring it to your table. Enjoy your meal.',
|
||||||
|
rejectedBody: 'We\'re sorry we couldn\'t take your order this time. Please speak to the staff.',
|
||||||
|
waiting: 'This page updates by itself. Keep it open.', reason: 'Reason: {{reason}}', failed: 'Could not load the order\'s status.', back: 'Back to the menu',
|
||||||
|
},
|
||||||
|
allergen: {
|
||||||
|
gluten: 'Gluten', crustaceans: 'Crustaceans', eggs: 'Eggs', fish: 'Fish', peanuts: 'Peanuts', soybeans: 'Soya', milk: 'Milk',
|
||||||
|
nuts: 'Nuts', celery: 'Celery', mustard: 'Mustard', sesame: 'Sesame', sulphites: 'Sulphites', lupin: 'Lupin', molluscs: 'Molluscs',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
el: {
|
||||||
|
menu: 'Μενού', loading: 'Φόρτωση μενού…', notFound: 'Το μενού δεν βρέθηκε.', loadFailed: 'Το μενού δεν φορτώθηκε. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά.',
|
||||||
|
retry: 'Δοκιμάστε ξανά', language: 'Γλώσσα', categories: 'Κατηγορίες', search: 'Αναζήτηση στο μενού…', searchOpen: 'Αναζήτηση', close: 'Κλείσιμο',
|
||||||
|
noResults: 'Δεν βρέθηκαν πιάτα', noResultsBody: 'Δοκιμάστε άλλη λέξη.',
|
||||||
|
add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', more: 'Περισσότερο', less: 'Λιγότερο',
|
||||||
|
allergens: 'Αλλεργιογόνα', contains: 'Περιέχει', mayContain: 'Μπορεί να περιέχει', noAllergens: 'Δεν έχουν δηλωθεί αλλεργιογόνα. Ρωτήστε το προσωπικό αν έχετε αλλεργία.',
|
||||||
|
allergenNote: 'Ρωτήστε το προσωπικό αν έχετε αλλεργία.',
|
||||||
|
atTable: 'Τραπέζι {{table}}: παραγγείλτε από το κινητό σας', tableInvalid: 'Αυτό το QR δεν ισχύει πλέον. Ρωτήστε το προσωπικό.',
|
||||||
|
orderingOff: 'Η παραγγελία από το τραπέζι δεν είναι διαθέσιμη τώρα. Ρωτήστε το προσωπικό.',
|
||||||
|
viewOrder: 'Η παραγγελία σας', items_one: '{{count}} πιάτο', items_other: '{{count}} πιάτα',
|
||||||
|
yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', emptyBody: 'Προσθέστε μερικά πιάτα για να ξεκινήσετε.', total: 'Σύνολο', continue: 'Συνέχεια', back: 'Πίσω',
|
||||||
|
table: 'Τραπέζι', checkout: 'Αποστολή στην κουζίνα', name: 'Το όνομά σας (προαιρετικά)', namePlaceholder: 'π.χ. Αλέξης', summary: 'Η παραγγελία σας',
|
||||||
|
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', payNote: 'Πληρώνετε στο τραπέζι.',
|
||||||
|
refused: {
|
||||||
|
changed: 'Κάτι άλλαξε στο μενού από τότε που το ανοίξατε. Ανανεώστε τη σελίδα και ελέγξτε την παραγγελία σας.',
|
||||||
|
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', failed: 'Η παραγγελία δεν στάλθηκε. Δοκιμάστε ξανά.',
|
||||||
|
},
|
||||||
|
track: {
|
||||||
|
pending_acceptance: 'Η παραγγελία σας στέλνεται στην κουζίνα…', accepted: 'Η παραγγελία σας είναι στην κουζίνα', rejected: 'Η παραγγελία δεν έγινε δεκτή',
|
||||||
|
acceptedBody: 'Ευχαριστούμε! Ο σερβιτόρος θα τη φέρει στο τραπέζι σας. Καλή όρεξη.',
|
||||||
|
rejectedBody: 'Λυπούμαστε, δεν μπορέσαμε να δεχτούμε την παραγγελία. Μιλήστε με το προσωπικό.',
|
||||||
|
waiting: 'Η σελίδα ενημερώνεται μόνη της. Κρατήστε την ανοιχτή.', reason: 'Λόγος: {{reason}}', failed: 'Δεν φορτώθηκε η κατάσταση της παραγγελίας.', back: 'Πίσω στο μενού',
|
||||||
|
},
|
||||||
|
allergen: {
|
||||||
|
gluten: 'Γλουτένη', crustaceans: 'Καρκινοειδή', eggs: 'Αυγά', fish: 'Ψάρια', peanuts: 'Αράπικα φιστίκια', soybeans: 'Σόγια', milk: 'Γάλα',
|
||||||
|
nuts: 'Ξηροί καρποί', celery: 'Σέλινο', mustard: 'Μουστάρδα', sesame: 'Σουσάμι', sulphites: 'Θειώδη', lupin: 'Λούπινο', molluscs: 'Μαλάκια',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initialLang() {
|
||||||
|
try {
|
||||||
|
const saved = localStorage.getItem(STORE)
|
||||||
|
if (saved && TEXTS[saved]) return saved
|
||||||
|
const old = localStorage.getItem(OLD_STORE)
|
||||||
|
if (old) return old === 'gr' ? 'el' : 'en'
|
||||||
|
} catch { /* private mode */ }
|
||||||
|
return (navigator.language || 'en').toLowerCase().startsWith('el') ? 'el' : 'en'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveLang(lang) {
|
||||||
|
try { localStorage.setItem(STORE, lang) } catch { /* private mode */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** t('a.b', {x}) with {{x}} and _one/_other plurals by `count`. */
|
||||||
|
export function translate(lang, key, params = {}) {
|
||||||
|
const dict = TEXTS[lang] ?? TEXTS.en
|
||||||
|
const find = k => k.split('.').reduce((o, p) => (o == null ? undefined : o[p]), dict)
|
||||||
|
let s = params.count != null ? find(`${key}_${params.count === 1 ? 'one' : 'other'}`) : undefined
|
||||||
|
if (s === undefined) s = find(key)
|
||||||
|
if (typeof s !== 'string') return key
|
||||||
|
return s.replace(/\{\{(\w+)\}\}/g, (_, k) => (params[k] ?? ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
export const LangContext = createContext({ lang: 'en', setLang: () => {} })
|
||||||
|
|
||||||
|
export function useT() {
|
||||||
|
const { lang, setLang } = useContext(LangContext)
|
||||||
|
const money = n => new Intl.NumberFormat(lang === 'el' ? 'el-GR' : 'en-IE', { style: 'currency', currency: 'EUR' }).format(n ?? 0)
|
||||||
|
return { lang, setLang, t: (key, params) => translate(lang, key, params), money }
|
||||||
|
}
|
||||||
@@ -2,5 +2,34 @@
|
|||||||
@tailwind components;
|
@tailwind components;
|
||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
|
||||||
* { box-sizing: border-box; }
|
/* The app's tokens (RGB triples, used through tailwind.config.js). Light only for now. */
|
||||||
body { margin: 0; font-family: 'Geist', system-ui, sans-serif; background: #f8fafc; }
|
:root {
|
||||||
|
--o-canvas: 246 244 239;
|
||||||
|
--o-surface: 255 255 255;
|
||||||
|
--o-surface-2: 239 236 228;
|
||||||
|
--o-line: 226 221 209;
|
||||||
|
--o-ink: 28 36 33;
|
||||||
|
--o-ink-2: 88 96 92;
|
||||||
|
--o-ink-3: 140 145 140;
|
||||||
|
--o-accent: 31 58 52;
|
||||||
|
--o-accent-fg: 247 244 236;
|
||||||
|
--o-accent-soft: 222 234 228;
|
||||||
|
--o-accent-ink: 24 66 56;
|
||||||
|
--o-success: 48 120 78;
|
||||||
|
--o-success-soft: 225 242 231;
|
||||||
|
--o-success-ink: 30 92 56;
|
||||||
|
--o-warning-soft: 252 240 214;
|
||||||
|
--o-warning-ink: 124 82 10;
|
||||||
|
--o-danger-soft: 251 228 222;
|
||||||
|
--o-danger-ink: 160 50 30;
|
||||||
|
--o-shadow: 28 36 33;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body { background: rgb(var(--o-canvas)); color: rgb(var(--o-ink)); }
|
||||||
|
body { font-family: theme('fontFamily.sans'); -webkit-font-smoothing: antialiased; }
|
||||||
|
button { -webkit-tap-highlight-color: transparent; }
|
||||||
|
:focus-visible { outline: 3px solid rgb(var(--o-accent) / 0.45); outline-offset: 2px; }
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
* { transition: none !important; animation: none !important; }
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// The QR menu's logic (plan step 6.5). Pure: unit-tested in Node (tests/logic.test.mjs).
|
||||||
|
//
|
||||||
|
// The venue's menu comes from GET /api/menu/{site}: categories with products, each with the
|
||||||
|
// prices per sales point (this app sells at `qr_table`), its texts per language (`names`,
|
||||||
|
// `descriptions`, 6.4) and allergens (6.3). The cloud prices the order itself; the numbers here
|
||||||
|
// are what the guest sees before sending.
|
||||||
|
|
||||||
|
export const QR_POINT = 'qr_table'
|
||||||
|
export const LANGS = ['el', 'en']
|
||||||
|
|
||||||
|
/** The 14 EU allergens, in the order the venue's apps list them (the site's core/allergens.py). */
|
||||||
|
export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs']
|
||||||
|
|
||||||
|
const round2 = n => Math.round(n * 100) / 100
|
||||||
|
|
||||||
|
/** A product's allergens to show: what it contains, then what it may contain (traces). */
|
||||||
|
export function allergenList(map) {
|
||||||
|
const m = map && typeof map === 'object' && !Array.isArray(map) ? map : {}
|
||||||
|
const list = Array.isArray(map) ? map.filter(k => ALLERGENS.includes(k)).map(key => ({ key, level: 'contains' })) : []
|
||||||
|
for (const level of ['contains', 'may_contain']) for (const key of ALLERGENS) if (m[key] === level) list.push({ key, level })
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A text in the guest's language: `texts` {el, en} from the venue (already falling back), else the base. */
|
||||||
|
const pick = (texts, lang, base) => (texts && texts[lang]) || base || ''
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The menu as this app shows it: the categories with the products sold on the QR menu, each
|
||||||
|
* product's text in `lang`, its price, availability and allergens. A product listed in several
|
||||||
|
* categories shows in each (`repeat` marks the later ones, so search shows it once).
|
||||||
|
*/
|
||||||
|
export function menuFor(data, lang) {
|
||||||
|
const seen = new Set()
|
||||||
|
return (data?.categories ?? []).map(c => ({
|
||||||
|
id: String(c.id),
|
||||||
|
name: pick(c.names, lang, c.name),
|
||||||
|
products: (c.products ?? [])
|
||||||
|
.filter(p => !p.sold_at || p.sold_at.includes(QR_POINT))
|
||||||
|
.map(p => ({
|
||||||
|
id: String(p.id),
|
||||||
|
name: pick(p.names, lang, p.digital_name || p.name),
|
||||||
|
names: p.names ?? null,
|
||||||
|
baseName: p.digital_name || p.name || '',
|
||||||
|
description: pick(p.descriptions, lang, p.digital_description || p.description || ''),
|
||||||
|
price: p.prices ? (p.prices[QR_POINT] ?? 0) : (p.digital_price ?? p.base_price ?? 0),
|
||||||
|
available: p.digital_available !== false,
|
||||||
|
image: p.digital_image_url || p.image_url || null,
|
||||||
|
tags: p.tags ?? [],
|
||||||
|
allergens: allergenList(p.allergens),
|
||||||
|
repeat: seen.has(String(p.id)) || !seen.add(String(p.id)),
|
||||||
|
})),
|
||||||
|
})).filter(c => c.products.length > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lowercase, no accents: "Σουβλάκι" and "σουβλακι" match. */
|
||||||
|
export function fold(text) {
|
||||||
|
return String(text ?? '').normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a search finds, once each: by its name in either language (or as typed) or description. */
|
||||||
|
export function search(categories, query) {
|
||||||
|
const q = fold(query)
|
||||||
|
if (!q) return []
|
||||||
|
return categories.flatMap(c => c.products.filter(p => !p.repeat))
|
||||||
|
.filter(p => [p.name, p.baseName, ...Object.values(p.names ?? {}), p.description].some(s => fold(s).includes(q)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The cart is {productId: quantity}. */
|
||||||
|
export function setQty(cart, id, qty) {
|
||||||
|
const next = { ...cart }
|
||||||
|
if (qty <= 0) delete next[id]
|
||||||
|
else next[id] = Math.min(99, qty)
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The cart's lines priced from the menu; products no longer on it (or sold out) are left out. */
|
||||||
|
export function cartLines(cart, categories) {
|
||||||
|
const byId = new Map(categories.flatMap(c => c.products).map(p => [p.id, p]))
|
||||||
|
return Object.entries(cart ?? {}).flatMap(([id, qty]) => {
|
||||||
|
const p = byId.get(id)
|
||||||
|
if (!p || !p.available || qty <= 0) return []
|
||||||
|
return [{ product: p, qty, total: round2(p.price * qty) }]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const cartTotal = lines => round2(lines.reduce((s, l) => s + l.total, 0))
|
||||||
|
export const cartCount = lines => lines.reduce((s, l) => s + l.qty, 0)
|
||||||
|
|
||||||
|
/** The order as the cloud takes it: at the table its QR code names (the cloud checks the token). */
|
||||||
|
export function orderBody(lines, { tableToken, name, tableLabel, tableWord }) {
|
||||||
|
return {
|
||||||
|
order_type: 'dine_in',
|
||||||
|
table_token: tableToken,
|
||||||
|
customer_name: (name ?? '').trim() || `${tableWord} ${tableLabel ?? ''}`.trim(),
|
||||||
|
items: lines.map(l => ({ product_id: Number(l.product.id), quantity: l.qty, unit_price: l.product.price })),
|
||||||
|
total: cartTotal(lines),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The text key for a refused order (the cloud's error code). */
|
||||||
|
export function refusalKey(code) {
|
||||||
|
if (['order.price_changed', 'order.item_unavailable', 'order.option_unavailable'].includes(code)) return 'refused.changed'
|
||||||
|
if (code === 'order.table_invalid') return 'tableInvalid'
|
||||||
|
if (code === 'order.service_unavailable') return 'orderingOff'
|
||||||
|
if (code === 'rate.limited') return 'refused.rate'
|
||||||
|
return 'refused.failed'
|
||||||
|
}
|
||||||
@@ -1,15 +1,27 @@
|
|||||||
import React from 'react'
|
// The QR menu (plan step 6.5): read the venue's menu, or order at a table with its QR code.
|
||||||
import ReactDOM from 'react-dom/client'
|
import { StrictMode, useState } from 'react'
|
||||||
import { BrowserRouter } from 'react-router-dom'
|
import { createRoot } from 'react-dom/client'
|
||||||
import { Toaster } from 'react-hot-toast'
|
import { BrowserRouter, Route, Routes } from 'react-router-dom'
|
||||||
import App from './App'
|
|
||||||
import './index.css'
|
import './index.css'
|
||||||
|
import { initialLang, LangContext, saveLang } from './i18n'
|
||||||
|
import ConfirmPage from './pages/ConfirmPage'
|
||||||
|
import MenuPage from './pages/MenuPage'
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
function App() {
|
||||||
<React.StrictMode>
|
const [lang, setLangState] = useState(initialLang)
|
||||||
|
const setLang = l => { setLangState(l); saveLang(l); document.documentElement.lang = l }
|
||||||
|
document.documentElement.lang = lang
|
||||||
|
return (
|
||||||
|
<LangContext.Provider value={{ lang, setLang }}>
|
||||||
<BrowserRouter basename="/menu">
|
<BrowserRouter basename="/menu">
|
||||||
<App />
|
<Routes>
|
||||||
<Toaster position="top-center" />
|
<Route path="/:site" element={<MenuPage />} />
|
||||||
|
<Route path="/:site/confirm/:ref" element={<ConfirmPage />} />
|
||||||
|
<Route path="*" element={<p className="p-6 text-ink-2">Xenia</p>} />
|
||||||
|
</Routes>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</React.StrictMode>
|
</LangContext.Provider>
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')).render(<StrictMode><App /></StrictMode>)
|
||||||
|
|||||||
@@ -1,178 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { useParams, useNavigate, useLocation } from 'react-router-dom'
|
|
||||||
import { ArrowLeft, Truck, UtensilsCrossed } from 'lucide-react'
|
|
||||||
import { submitOrder } from '../api'
|
|
||||||
import toast from 'react-hot-toast'
|
|
||||||
|
|
||||||
export default function CartPage() {
|
|
||||||
const { siteSlug } = useParams()
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const { state } = useLocation()
|
|
||||||
const cart = state?.cart || []
|
|
||||||
|
|
||||||
const [orderType, setOrderType] = useState('dine_in')
|
|
||||||
const [name, setName] = useState('')
|
|
||||||
const [phone, setPhone] = useState('')
|
|
||||||
const [address, setAddress] = useState('')
|
|
||||||
const [notes, setNotes] = useState('')
|
|
||||||
const [submitting, setSubmitting] = useState(false)
|
|
||||||
|
|
||||||
const subtotal = cart.reduce((s, i) => s + i.unit_price * i.quantity, 0)
|
|
||||||
const deliveryFee = orderType === 'delivery' ? 2.0 : 0.0
|
|
||||||
const total = subtotal + deliveryFee
|
|
||||||
|
|
||||||
if (!cart.length) {
|
|
||||||
navigate(`/${siteSlug}`, { replace: true })
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSubmit(e) {
|
|
||||||
e.preventDefault()
|
|
||||||
if (!name.trim()) { toast.error('Please enter your name'); return }
|
|
||||||
if (orderType === 'delivery' && !address.trim()) {
|
|
||||||
toast.error('Please enter your delivery address')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setSubmitting(true)
|
|
||||||
try {
|
|
||||||
const result = await submitOrder(siteSlug, {
|
|
||||||
order_type: orderType,
|
|
||||||
customer_name: name.trim(),
|
|
||||||
customer_phone: phone.trim() || null,
|
|
||||||
customer_address: orderType === 'delivery' ? address.trim() : null,
|
|
||||||
customer_notes: notes.trim() || null,
|
|
||||||
items: cart.map(i => ({
|
|
||||||
product_id: i.product_id,
|
|
||||||
name: i.name,
|
|
||||||
quantity: i.quantity,
|
|
||||||
unit_price: i.unit_price,
|
|
||||||
options: i.options || [],
|
|
||||||
})),
|
|
||||||
subtotal,
|
|
||||||
delivery_fee: deliveryFee,
|
|
||||||
total,
|
|
||||||
})
|
|
||||||
navigate(`/${siteSlug}/confirm/${result.public_ref}`, { replace: true })
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err.response?.data?.detail || 'Failed to place order. Please try again.')
|
|
||||||
} finally {
|
|
||||||
setSubmitting(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-slate-50 pb-10">
|
|
||||||
<div className="sticky top-0 z-10 bg-white border-b border-slate-100 shadow-sm">
|
|
||||||
<div className="max-w-lg mx-auto px-4 py-3 flex items-center gap-3">
|
|
||||||
<button onClick={() => navigate(-1)} className="text-slate-500 hover:text-slate-800">
|
|
||||||
<ArrowLeft size={22} />
|
|
||||||
</button>
|
|
||||||
<h1 className="text-lg font-bold text-slate-800">Your Order</h1>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="max-w-lg mx-auto px-4 py-5 space-y-5">
|
|
||||||
|
|
||||||
{/* Order type */}
|
|
||||||
<div className="bg-white rounded-2xl p-4 space-y-3 shadow-sm">
|
|
||||||
<p className="text-sm font-semibold text-slate-700">Order type</p>
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
{[
|
|
||||||
{ id: 'dine_in', label: 'Dine In', Icon: UtensilsCrossed },
|
|
||||||
{ id: 'delivery', label: 'Delivery', Icon: Truck },
|
|
||||||
].map(({ id, label, Icon }) => (
|
|
||||||
<button
|
|
||||||
key={id}
|
|
||||||
type="button"
|
|
||||||
onClick={() => setOrderType(id)}
|
|
||||||
className={`flex flex-col items-center gap-2 py-4 rounded-xl border-2 transition-colors ${
|
|
||||||
orderType === id
|
|
||||||
? 'border-emerald-500 bg-emerald-50 text-emerald-700'
|
|
||||||
: 'border-slate-200 text-slate-500 hover:border-slate-300'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon size={22} />
|
|
||||||
<span className="text-sm font-semibold">{label}</span>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Cart summary */}
|
|
||||||
<div className="bg-white rounded-2xl p-4 shadow-sm space-y-2">
|
|
||||||
<p className="text-sm font-semibold text-slate-700 mb-3">Items</p>
|
|
||||||
{cart.map((item, idx) => (
|
|
||||||
<div key={idx} className="flex justify-between text-sm">
|
|
||||||
<span className="text-slate-700">{item.quantity}× {item.name}</span>
|
|
||||||
<span className="text-slate-600 font-medium">€{(item.unit_price * item.quantity).toFixed(2)}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div className="border-t border-slate-100 pt-2 mt-2 space-y-1">
|
|
||||||
<div className="flex justify-between text-sm text-slate-500">
|
|
||||||
<span>Subtotal</span><span>€{subtotal.toFixed(2)}</span>
|
|
||||||
</div>
|
|
||||||
{deliveryFee > 0 && (
|
|
||||||
<div className="flex justify-between text-sm text-slate-500">
|
|
||||||
<span>Delivery fee</span><span>€{deliveryFee.toFixed(2)}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex justify-between font-bold text-slate-800">
|
|
||||||
<span>Total</span><span>€{total.toFixed(2)}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Customer details */}
|
|
||||||
<div className="bg-white rounded-2xl p-4 shadow-sm space-y-3">
|
|
||||||
<p className="text-sm font-semibold text-slate-700">Your details</p>
|
|
||||||
{[
|
|
||||||
{ label: 'Name *', value: name, set: setName, type: 'text', placeholder: 'Full name' },
|
|
||||||
{ label: 'Phone', value: phone, set: setPhone, type: 'tel', placeholder: 'Optional' },
|
|
||||||
].map(({ label, value, set, type, placeholder }) => (
|
|
||||||
<div key={label}>
|
|
||||||
<label className="text-xs text-slate-500 font-medium">{label}</label>
|
|
||||||
<input
|
|
||||||
type={type}
|
|
||||||
value={value}
|
|
||||||
onChange={e => set(e.target.value)}
|
|
||||||
placeholder={placeholder}
|
|
||||||
className="mt-1 w-full border border-slate-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-emerald-400 focus:ring-1 focus:ring-emerald-100"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{orderType === 'delivery' && (
|
|
||||||
<div>
|
|
||||||
<label className="text-xs text-slate-500 font-medium">Delivery address *</label>
|
|
||||||
<textarea
|
|
||||||
value={address}
|
|
||||||
onChange={e => setAddress(e.target.value)}
|
|
||||||
placeholder="Street, number, city"
|
|
||||||
rows={2}
|
|
||||||
className="mt-1 w-full border border-slate-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-emerald-400 focus:ring-1 focus:ring-emerald-100 resize-none"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div>
|
|
||||||
<label className="text-xs text-slate-500 font-medium">Notes</label>
|
|
||||||
<textarea
|
|
||||||
value={notes}
|
|
||||||
onChange={e => setNotes(e.target.value)}
|
|
||||||
placeholder="Allergies, special requests…"
|
|
||||||
rows={2}
|
|
||||||
className="mt-1 w-full border border-slate-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-emerald-400 focus:ring-1 focus:ring-emerald-100 resize-none"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={submitting}
|
|
||||||
className="w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white py-4 rounded-xl font-bold text-base transition-colors"
|
|
||||||
>
|
|
||||||
{submitting ? 'Placing order…' : `Place order · €${total.toFixed(2)}`}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// After a table order (plan step 6.5): sending → in the kitchen, or not taken (with the
|
||||||
|
// venue's reason). Polls every 10 s until it's settled.
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { Link, useParams } from 'react-router-dom'
|
||||||
|
import { Check, Clock, X } from 'lucide-react'
|
||||||
|
import { track } from '../api'
|
||||||
|
import { useT } from '../i18n'
|
||||||
|
|
||||||
|
const SETTLED = new Set(['accepted', 'rejected', 'delivered', 'preparing', 'ready'])
|
||||||
|
const POLL_MS = 10_000
|
||||||
|
|
||||||
|
export default function ConfirmPage() {
|
||||||
|
const { site, ref } = useParams()
|
||||||
|
const { t } = useT()
|
||||||
|
const [order, setOrder] = useState(null)
|
||||||
|
const [failed, setFailed] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let timer
|
||||||
|
let stop = false
|
||||||
|
const poll = async () => {
|
||||||
|
try {
|
||||||
|
const data = await track(ref)
|
||||||
|
if (stop) return
|
||||||
|
setOrder(data)
|
||||||
|
if (!SETTLED.has(data.status)) timer = setTimeout(poll, POLL_MS)
|
||||||
|
} catch { if (!stop) setFailed(true) }
|
||||||
|
}
|
||||||
|
poll()
|
||||||
|
return () => { stop = true; clearTimeout(timer) }
|
||||||
|
}, [ref])
|
||||||
|
|
||||||
|
const status = order?.status
|
||||||
|
const state = status === 'rejected' ? 'rejected' : SETTLED.has(status) ? 'accepted' : 'pending_acceptance'
|
||||||
|
const Icon = { pending_acceptance: Clock, accepted: Check, rejected: X }[state]
|
||||||
|
const tone = { pending_acceptance: 'bg-warning-soft text-warning-ink', accepted: 'bg-success-soft text-success-ink', rejected: 'bg-danger-soft text-danger-ink' }[state]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-lg min-h-dvh bg-canvas flex flex-col items-center justify-center gap-3 px-6 py-12 text-center">
|
||||||
|
<div className={`w-20 h-20 rounded-full flex items-center justify-center ${tone}`}><Icon size={38} strokeWidth={2.2} aria-hidden="true" /></div>
|
||||||
|
{order?.public_ref && <p className="text-xs font-semibold uppercase tracking-[0.2em] text-ink-3">{order.public_ref}</p>}
|
||||||
|
<h1 data-testid="confirm-status" data-status={status ?? ''} className="font-display text-2xl font-semibold text-ink leading-tight">
|
||||||
|
{failed ? t('track.failed') : t(`track.${state}`)}
|
||||||
|
</h1>
|
||||||
|
{order?.rejection_reason && <p className="text-ink-2">{t('track.reason', { reason: order.rejection_reason })}</p>}
|
||||||
|
{state === 'accepted' && <p className="max-w-xs text-ink-2">{t('track.acceptedBody')}</p>}
|
||||||
|
{state === 'rejected' && <p className="max-w-xs text-ink-2">{t('track.rejectedBody')}</p>}
|
||||||
|
{state === 'pending_acceptance' && !failed && (<>
|
||||||
|
<p className="text-sm text-ink-3">{t('track.waiting')}</p>
|
||||||
|
<div className="w-5 h-5 rounded-full border-2 border-accent border-t-transparent animate-spin" role="status" aria-label={t('track.waiting')} />
|
||||||
|
</>)}
|
||||||
|
<Link to={`/${site}`} className="mt-4 px-5 h-11 rounded-full bg-surface border border-line text-ink font-semibold flex items-center">{t('track.back')}</Link>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,119 +1,337 @@
|
|||||||
import { useState, useEffect } from 'react'
|
// The QR menu (plan step 6.5, rebuilt on the customer apps' look). Without a table it's a menu to
|
||||||
import { useParams, useNavigate } from 'react-router-dom'
|
// read; scanned at a table whose venue allows it (phase 3S, S.7) the guest orders from their
|
||||||
import { ShoppingCart, AlertCircle } from 'lucide-react'
|
// phone: the order goes to the table's order and the kitchen, and the cloud prices it itself.
|
||||||
import { fetchMenu } from '../api'
|
// Texts in the guest's language (the venue's translations, 6.4), each dish's allergens (6.3).
|
||||||
import CategoryNav from '../components/CategoryNav'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import ProductCard from '../components/ProductCard'
|
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||||
import CartButton from '../components/CartButton'
|
import { Armchair, ChevronLeft, Minus, Plus, Search, Send, ShoppingBag, TriangleAlert, X } from 'lucide-react'
|
||||||
import ProductModal from './ProductModal'
|
import { fetchMenu, imageUrl, placeOrder } from '../api'
|
||||||
|
import { useT } from '../i18n'
|
||||||
|
import { cartCount, cartLines, cartTotal, menuFor, orderBody, refusalKey, search, setQty } from '../logic'
|
||||||
|
|
||||||
|
const TABLE_KEY = site => `xenia-qr-table:${site}`
|
||||||
|
const CART_KEY = site => `xenia-qr-cart:${site}`
|
||||||
|
|
||||||
export default function MenuPage() {
|
export default function MenuPage() {
|
||||||
const { siteSlug } = useParams()
|
const { site } = useParams()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const [params] = useSearchParams()
|
||||||
const [menu, setMenu] = useState(null)
|
const { t, lang } = useT()
|
||||||
|
// the table's QR code carries its token (?t=…); kept for this visit so a reload keeps the table
|
||||||
|
const [tableToken] = useState(() => {
|
||||||
|
const fromUrl = params.get('t')
|
||||||
|
try {
|
||||||
|
if (fromUrl) sessionStorage.setItem(TABLE_KEY(site), fromUrl)
|
||||||
|
return fromUrl || sessionStorage.getItem(TABLE_KEY(site)) || null
|
||||||
|
} catch { return fromUrl }
|
||||||
|
})
|
||||||
|
const [data, setData] = useState(null)
|
||||||
const [error, setError] = useState(null)
|
const [error, setError] = useState(null)
|
||||||
const [loading, setLoading] = useState(true)
|
const [cart, setCart] = useState(() => { try { return JSON.parse(sessionStorage.getItem(CART_KEY(site))) || {} } catch { return {} } })
|
||||||
const [activeCat, setActiveCat] = useState(null)
|
const [open, setOpen] = useState(null) // a product shown big
|
||||||
const [cart, setCart] = useState([])
|
const [searching, setSearching] = useState(false)
|
||||||
const [selected, setSelected] = useState(null) // product for modal
|
const [stage, setStage] = useState(null) // 'cart' | 'checkout'
|
||||||
|
|
||||||
useEffect(() => {
|
const load = () => {
|
||||||
fetchMenu(siteSlug)
|
setError(null)
|
||||||
.then(data => {
|
fetchMenu(site, tableToken).then(setData).catch(err => setError(err?.response?.status === 404 ? 'notFound' : 'loadFailed'))
|
||||||
setMenu(data)
|
|
||||||
if (data.categories?.length) setActiveCat(data.categories[0].id)
|
|
||||||
})
|
|
||||||
.catch(() => setError('Menu not available. Please try again.'))
|
|
||||||
.finally(() => setLoading(false))
|
|
||||||
}, [siteSlug])
|
|
||||||
|
|
||||||
function addToCart(product, quantity, options) {
|
|
||||||
const price = product.digital_price ?? product.base_price
|
|
||||||
const discounted = product.digital_discount > 0 && !product.digital_price
|
|
||||||
? price * (1 - product.digital_discount / 100)
|
|
||||||
: price
|
|
||||||
setCart(prev => {
|
|
||||||
const key = product.id
|
|
||||||
const existing = prev.find(i => i.product_id === key)
|
|
||||||
if (existing) {
|
|
||||||
return prev.map(i => i.product_id === key
|
|
||||||
? { ...i, quantity: i.quantity + quantity }
|
|
||||||
: i)
|
|
||||||
}
|
}
|
||||||
return [...prev, {
|
useEffect(load, [site, tableToken]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
product_id: product.id,
|
useEffect(() => { try { sessionStorage.setItem(CART_KEY(site), JSON.stringify(cart)) } catch { /* private mode */ } }, [cart, site])
|
||||||
name: product.digital_name || product.name,
|
|
||||||
quantity,
|
const categories = useMemo(() => menuFor(data, lang), [data, lang])
|
||||||
unit_price: discounted,
|
const lines = useMemo(() => cartLines(cart, categories), [cart, categories])
|
||||||
options,
|
const count = cartCount(lines)
|
||||||
}]
|
const canOrder = !!(data?.table_ordering && data?.table)
|
||||||
})
|
const add = p => setCart(c => setQty(c, p.id, (c[p.id] || 0) + 1))
|
||||||
setSelected(null)
|
const remove = p => setCart(c => setQty(c, p.id, (c[p.id] || 0) - 1))
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<div className="p-6 grid gap-4 text-center">
|
||||||
|
<p className="text-ink-2">{t(error)}</p>
|
||||||
|
{error === 'loadFailed' && <button type="button" className="mx-auto px-5 h-11 rounded-full bg-accent text-accent-fg font-semibold" onClick={load}>{t('retry')}</button>}
|
||||||
|
</div>
|
||||||
|
</Shell>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
if (!data) return <Shell><p className="p-6 text-center text-ink-2" role="status">{t('loading')}</p></Shell>
|
||||||
|
|
||||||
const activeCategory = menu?.categories?.find(c => c.id === activeCat)
|
const r = data.restaurant ?? {}
|
||||||
const cartCount = cart.reduce((s, i) => s + i.quantity, 0)
|
const tagline = r.tagline?.[lang === 'el' ? 'gr' : 'en']
|
||||||
|
const visible = categories.filter(c => c.products.some(p => !p.repeat))
|
||||||
if (loading) return (
|
|
||||||
<div className="min-h-screen flex items-center justify-center">
|
|
||||||
<div className="w-8 h-8 rounded-full border-2 border-emerald-500 border-t-transparent animate-spin" />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
|
|
||||||
if (error) return (
|
|
||||||
<div className="min-h-screen flex flex-col items-center justify-center gap-3 p-8 text-center">
|
|
||||||
<AlertCircle className="text-red-400" size={40} />
|
|
||||||
<p className="text-slate-600">{error}</p>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-slate-50 pb-28">
|
<Shell>
|
||||||
{/* Header */}
|
<header className="px-4 pt-5 pb-3 grid gap-3 bg-surface border-b border-line">
|
||||||
<div className="sticky top-0 z-20 bg-white border-b border-slate-100 shadow-sm">
|
<div className="flex items-start gap-3">
|
||||||
<div className="max-w-2xl mx-auto px-4 py-3 flex items-center justify-between">
|
<div className="flex-1 min-w-0">
|
||||||
<h1 className="text-lg font-bold text-slate-800">Menu</h1>
|
<h1 className="font-display text-2xl font-semibold text-ink leading-tight" data-testid="venue-name">{r.name || t('menu')}</h1>
|
||||||
{cartCount > 0 && (
|
{tagline && <p className="text-sm text-ink-2 mt-0.5">{tagline}</p>}
|
||||||
<button
|
|
||||||
onClick={() => navigate(`/${siteSlug}/order`, { state: { cart } })}
|
|
||||||
className="flex items-center gap-2 bg-emerald-500 text-white px-4 py-2 rounded-full text-sm font-semibold"
|
|
||||||
>
|
|
||||||
<ShoppingCart size={16} />
|
|
||||||
{cartCount} items
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
<CategoryNav
|
<LangSwitch />
|
||||||
categories={menu.categories}
|
|
||||||
active={activeCat}
|
|
||||||
onSelect={setActiveCat}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
{(data.table && canOrder) || data.table_invalid ? (
|
||||||
|
<p data-testid={data.table_invalid ? 'table-invalid' : 'table-banner'}
|
||||||
|
className={`p-3 rounded-control text-sm font-medium flex items-center gap-2 ${data.table_invalid ? 'bg-danger-soft text-danger-ink' : 'bg-accent-soft text-accent-ink'}`}>
|
||||||
|
{data.table_invalid ? <TriangleAlert size={16} aria-hidden="true" /> : <Armchair size={16} aria-hidden="true" />}
|
||||||
|
{data.table_invalid ? t('tableInvalid') : t('atTable', { table: data.table.label })}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</header>
|
||||||
|
|
||||||
{/* Products */}
|
<nav className="sticky top-0 z-10 bg-canvas/95 backdrop-blur px-4 py-2 flex gap-2 overflow-x-auto border-b border-line" aria-label={t('categories')}>
|
||||||
<div className="max-w-2xl mx-auto px-4 pt-4 space-y-3">
|
<button type="button" onClick={() => setSearching(true)} aria-label={t('searchOpen')} data-testid="search-open"
|
||||||
{activeCategory?.products.map(p => (
|
className="shrink-0 w-9 h-9 rounded-full bg-surface border border-line flex items-center justify-center text-ink-2"><Search size={16} /></button>
|
||||||
<ProductCard
|
{visible.map(c => (
|
||||||
key={p.id}
|
<a key={c.id} href={`#cat-${c.id}`} className="shrink-0 px-3.5 h-9 rounded-full flex items-center text-sm font-medium bg-surface text-ink-2 border border-line">{c.name}</a>
|
||||||
product={p}
|
|
||||||
onSelect={() => setSelected(p)}
|
|
||||||
/>
|
|
||||||
))}
|
))}
|
||||||
{!activeCategory?.products.length && (
|
</nav>
|
||||||
<p className="text-center text-slate-400 py-12">No items in this category.</p>
|
|
||||||
)}
|
<main className="px-4 pb-32 pt-3 grid gap-6">
|
||||||
|
{categories.map(c => (
|
||||||
|
<section key={c.id} id={`cat-${c.id}`} className="grid gap-2 scroll-mt-16" aria-labelledby={`h-${c.id}`} data-testid="menu-section">
|
||||||
|
<h2 id={`h-${c.id}`} className="font-display text-lg font-semibold text-ink">{c.name}</h2>
|
||||||
|
{c.products.map(p => (
|
||||||
|
<ProductCard key={`${c.id}-${p.id}`} product={p} qty={cart[p.id] || 0} canOrder={canOrder}
|
||||||
|
onOpen={() => setOpen(p)} onAdd={() => add(p)} onRemove={() => remove(p)} />
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
<p className="text-xs text-ink-3 text-center">{t('allergenNote')}</p>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{canOrder && count > 0 && (
|
||||||
|
<div className="fixed inset-x-0 bottom-0 p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
|
||||||
|
<button type="button" onClick={() => setStage('cart')} data-testid="cart-button"
|
||||||
|
className="mx-auto max-w-lg w-full h-14 px-5 rounded-full bg-accent text-accent-fg shadow-bar flex items-center gap-3 font-semibold">
|
||||||
|
<ShoppingBag size={20} aria-hidden="true" />
|
||||||
|
<span className="flex-1 text-left">{t('viewOrder')} · {t('items', { count })}</span>
|
||||||
|
<Money value={cartTotal(lines)} />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CartButton cart={cart} siteSlug={siteSlug} />
|
|
||||||
|
|
||||||
{selected && (
|
|
||||||
<ProductModal
|
|
||||||
product={selected}
|
|
||||||
onClose={() => setSelected(null)}
|
|
||||||
onAdd={addToCart}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{open && <ProductSheet product={open} canOrder={canOrder} qty={cart[open.id] || 0} onClose={() => setOpen(null)} onAdd={() => add(open)} onRemove={() => remove(open)} />}
|
||||||
|
{searching && <SearchSheet categories={categories} cart={cart} canOrder={canOrder} onClose={() => setSearching(false)}
|
||||||
|
onOpen={p => { setSearching(false); setOpen(p) }} onAdd={add} onRemove={remove} />}
|
||||||
|
{stage && canOrder && (
|
||||||
|
<CartSheet stage={stage} setStage={setStage} lines={lines} table={data.table}
|
||||||
|
onAdd={add} onRemove={remove}
|
||||||
|
onSend={async name => {
|
||||||
|
const result = await placeOrder(site, orderBody(lines, { tableToken, name, tableLabel: data.table.label, tableWord: t('table') }))
|
||||||
|
setCart({})
|
||||||
|
try { sessionStorage.removeItem(CART_KEY(site)) } catch { /* private mode */ }
|
||||||
|
navigate(`/${site}/confirm/${result.tracking_token ?? result.public_ref}`)
|
||||||
|
}} />
|
||||||
|
)}
|
||||||
|
</Shell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Shell({ children }) {
|
||||||
|
return <div className="mx-auto max-w-lg min-h-dvh bg-canvas">{children}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function LangSwitch() {
|
||||||
|
const { lang, setLang, t } = useT()
|
||||||
|
return (
|
||||||
|
<div className="flex rounded-full bg-surface-2 p-0.5 text-sm font-semibold shrink-0" role="group" aria-label={t('language')}>
|
||||||
|
{['el', 'en'].map(l => (
|
||||||
|
<button key={l} type="button" onClick={() => setLang(l)} aria-pressed={lang === l} data-testid={`lang-${l}`}
|
||||||
|
className={`px-2.5 h-8 rounded-full ${lang === l ? 'bg-surface text-ink shadow-card' : 'text-ink-2'}`}>{l.toUpperCase()}</button>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Money({ value }) {
|
||||||
|
const { money } = useT()
|
||||||
|
return <span className="tabular-nums">{money(value)}</span>
|
||||||
|
}
|
||||||
|
|
||||||
|
function Qty({ qty, onAdd, onRemove }) {
|
||||||
|
const { t } = useT()
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<button type="button" onClick={onRemove} aria-label={t('less')} className="w-9 h-9 rounded-full bg-surface-2 text-ink flex items-center justify-center"><Minus size={16} /></button>
|
||||||
|
<span className="w-7 text-center font-semibold" data-testid="qty">{qty}</span>
|
||||||
|
<button type="button" onClick={onAdd} aria-label={t('more')} className="w-9 h-9 rounded-full bg-accent text-accent-fg flex items-center justify-center"><Plus size={16} /></button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AddButton({ product, qty, canOrder, onAdd, onRemove }) {
|
||||||
|
const { t } = useT()
|
||||||
|
if (!product.available) return <span className="text-sm font-medium text-ink-3">{t('soldOut')}</span>
|
||||||
|
if (!canOrder) return null
|
||||||
|
if (qty > 0) return <Qty qty={qty} onAdd={onAdd} onRemove={onRemove} />
|
||||||
|
return (
|
||||||
|
<button type="button" onClick={onAdd} data-testid="menu-add"
|
||||||
|
className="h-9 px-4 rounded-full bg-accent text-accent-fg text-sm font-semibold flex items-center gap-1"><Plus size={15} aria-hidden="true" />{t('add')}</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProductCard({ product, qty, canOrder, onOpen, onAdd, onRemove }) {
|
||||||
|
const { t } = useT()
|
||||||
|
const img = imageUrl(product.image)
|
||||||
|
const contains = product.allergens.filter(a => a.level === 'contains')
|
||||||
|
return (
|
||||||
|
<article className="p-3 rounded-card bg-surface border border-line shadow-card flex gap-3" data-testid="menu-product" data-product={product.id}>
|
||||||
|
{img && <button type="button" onClick={onOpen} className="shrink-0" aria-label={product.name}><img src={img} alt="" loading="lazy" className="w-20 h-20 rounded-control object-cover bg-surface-2" /></button>}
|
||||||
|
<div className="flex-1 min-w-0 grid gap-1 content-start">
|
||||||
|
<button type="button" onClick={onOpen} className="text-left font-semibold text-ink leading-snug" data-testid="menu-name">{product.name}</button>
|
||||||
|
{product.description && <p className="text-sm text-ink-2 line-clamp-2">{product.description}</p>}
|
||||||
|
{contains.length > 0 && (
|
||||||
|
<p className="text-xs text-warning-ink" data-testid="card-allergens">{t('contains')}: {contains.map(a => t(`allergen.${a.key}`)).join(', ')}</p>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center justify-between gap-2 mt-1">
|
||||||
|
<span className="font-semibold text-ink" data-testid="price"><Money value={product.price} /></span>
|
||||||
|
<AddButton product={product} qty={qty} canOrder={canOrder} onAdd={onAdd} onRemove={onRemove} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The dish's allergens: what it contains, then what it may contain. */
|
||||||
|
function AllergenBlock({ allergens }) {
|
||||||
|
const { t } = useT()
|
||||||
|
const contains = allergens.filter(a => a.level === 'contains')
|
||||||
|
const traces = allergens.filter(a => a.level === 'may_contain')
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2 p-3 rounded-control bg-surface-2" data-testid="allergens" data-count={allergens.length}>
|
||||||
|
<p className="text-xs font-semibold uppercase tracking-wide text-ink-3">{t('allergens')}</p>
|
||||||
|
{allergens.length === 0 && <p className="text-sm text-ink-2">{t('noAllergens')}</p>}
|
||||||
|
{[['contains', contains], ['mayContain', traces]].filter(([, list]) => list.length).map(([label, list]) => (
|
||||||
|
<div key={label} className="flex flex-wrap items-center gap-1.5">
|
||||||
|
<span className="text-sm text-ink-2">{t(label)}:</span>
|
||||||
|
{list.map(a => (
|
||||||
|
<span key={a.key} data-allergen={a.key} data-level={a.level}
|
||||||
|
className={`px-2 py-0.5 rounded-full text-xs font-semibold ${a.level === 'contains' ? 'bg-warning-soft text-warning-ink' : 'border border-dashed border-line text-ink-2'}`}>
|
||||||
|
{t(`allergen.${a.key}`)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Sheet({ onClose, labelledBy, children }) {
|
||||||
|
useEffect(() => {
|
||||||
|
const esc = e => { if (e.key === 'Escape') onClose() }
|
||||||
|
document.addEventListener('keydown', esc)
|
||||||
|
return () => document.removeEventListener('keydown', esc)
|
||||||
|
}, [onClose])
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-20 flex items-end justify-center bg-ink/40" role="dialog" aria-modal="true" aria-labelledby={labelledBy} onClick={onClose}>
|
||||||
|
<div className="w-full max-w-lg max-h-[90dvh] overflow-y-auto bg-surface rounded-t-[22px] p-4 pb-[max(1rem,env(safe-area-inset-bottom))] grid gap-3" onClick={e => e.stopPropagation()}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProductSheet({ product, canOrder, qty, onClose, onAdd, onRemove }) {
|
||||||
|
const { t } = useT()
|
||||||
|
const img = imageUrl(product.image)
|
||||||
|
return (
|
||||||
|
<Sheet onClose={onClose} labelledBy="product-title">
|
||||||
|
<div data-testid="product-sheet" className="grid gap-3">
|
||||||
|
{img && <img src={img} alt="" className="w-full max-h-64 rounded-card object-cover bg-surface-2" />}
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<h2 id="product-title" className="flex-1 font-display text-xl font-semibold text-ink">{product.name}</h2>
|
||||||
|
<button type="button" onClick={onClose} aria-label={t('close')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center shrink-0"><X size={18} /></button>
|
||||||
|
</div>
|
||||||
|
{product.description && <p className="text-ink-2 whitespace-pre-line">{product.description}</p>}
|
||||||
|
<AllergenBlock allergens={product.allergens} />
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<span className="text-lg font-semibold text-ink"><Money value={product.price} /></span>
|
||||||
|
<AddButton product={product} qty={qty} canOrder={canOrder} onAdd={onAdd} onRemove={onRemove} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Sheet>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SearchSheet({ categories, cart, canOrder, onClose, onOpen, onAdd, onRemove }) {
|
||||||
|
const { t } = useT()
|
||||||
|
const [q, setQ] = useState('')
|
||||||
|
const found = useMemo(() => search(categories, q), [categories, q])
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-20 bg-canvas flex flex-col" role="dialog" aria-modal="true" aria-label={t('searchOpen')}>
|
||||||
|
<div className="mx-auto w-full max-w-lg flex items-center gap-2 p-3">
|
||||||
|
<div className="flex-1 flex items-center gap-2 h-11 px-3.5 rounded-full bg-surface border border-line">
|
||||||
|
<Search size={18} className="text-ink-3" aria-hidden="true" />
|
||||||
|
<input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder={t('search')} aria-label={t('search')} data-testid="search-input"
|
||||||
|
className="flex-1 bg-transparent outline-none text-ink placeholder:text-ink-3" />
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={onClose} className="px-2 h-11 text-sm font-medium text-ink-2">{t('back')}</button>
|
||||||
|
</div>
|
||||||
|
<div className="mx-auto w-full max-w-lg flex-1 overflow-y-auto px-4 pb-6 grid gap-2 content-start">
|
||||||
|
{q.trim() && found.length === 0 && (
|
||||||
|
<div className="mt-16 text-center grid gap-1"><p className="font-display text-lg text-ink">{t('noResults')}</p><p className="text-sm text-ink-3">{t('noResultsBody')}</p></div>
|
||||||
|
)}
|
||||||
|
{found.map(p => <ProductCard key={p.id} product={p} qty={cart[p.id] || 0} canOrder={canOrder} onOpen={() => onOpen(p)} onAdd={() => onAdd(p)} onRemove={() => onRemove(p)} />)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CartSheet({ stage, setStage, lines, table, onAdd, onRemove, onSend }) {
|
||||||
|
const { t, money } = useT()
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [sending, setSending] = useState(false)
|
||||||
|
const [problem, setProblem] = useState(null)
|
||||||
|
const total = cartTotal(lines)
|
||||||
|
const close = () => setStage(null)
|
||||||
|
const send = async () => {
|
||||||
|
setSending(true)
|
||||||
|
setProblem(null)
|
||||||
|
try { await onSend(name) } catch (err) { setProblem(refusalKey(err?.response?.data?.detail?.code ?? err?.response?.data?.error?.code)); setSending(false) }
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Sheet onClose={close} labelledBy="cart-title">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{stage === 'checkout' && <button type="button" onClick={() => setStage('cart')} aria-label={t('back')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><ChevronLeft size={18} /></button>}
|
||||||
|
<h2 id="cart-title" className="flex-1 font-display text-xl font-semibold text-ink">{stage === 'cart' ? t('yourOrder') : t('checkout')}</h2>
|
||||||
|
<button type="button" onClick={close} aria-label={t('close')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><X size={18} /></button>
|
||||||
|
</div>
|
||||||
|
{lines.length === 0 ? (
|
||||||
|
<div className="py-10 text-center grid gap-1"><p className="font-display text-lg text-ink">{t('empty')}</p><p className="text-sm text-ink-3">{t('emptyBody')}</p></div>
|
||||||
|
) : stage === 'cart' ? (<>
|
||||||
|
<ul className="grid gap-2">
|
||||||
|
{lines.map(l => (
|
||||||
|
<li key={l.product.id} className="flex items-center gap-3 p-2.5 rounded-control bg-surface-2" data-testid="cart-line">
|
||||||
|
<span className="flex-1 min-w-0 grid"><span className="font-medium text-ink truncate">{l.product.name}</span><span className="text-sm text-ink-2"><Money value={l.product.price} /></span></span>
|
||||||
|
<Qty qty={l.qty} onAdd={() => onAdd(l.product)} onRemove={() => onRemove(l.product)} />
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<div className="flex items-baseline justify-between"><span className="text-sm text-ink-2">{t('total')}</span><span className="text-xl font-semibold text-ink"><Money value={total} /></span></div>
|
||||||
|
<button type="button" onClick={() => setStage('checkout')} data-testid="cart-continue" className="h-12 rounded-full bg-accent text-accent-fg font-semibold">{t('continue')}</button>
|
||||||
|
</>) : (<>
|
||||||
|
<p className="font-semibold text-ink" data-testid="checkout-table">{t('table')} {table?.label}</p>
|
||||||
|
<label className="grid gap-1.5">
|
||||||
|
<span className="text-sm font-medium text-ink-2">{t('name')}</span>
|
||||||
|
<input value={name} onChange={e => setName(e.target.value)} placeholder={t('namePlaceholder')} maxLength={100} autoComplete="given-name"
|
||||||
|
className="h-12 px-3.5 rounded-control bg-surface border border-line text-ink outline-none focus:border-accent" />
|
||||||
|
</label>
|
||||||
|
<div className="grid gap-1 p-3 rounded-control bg-surface-2">
|
||||||
|
<p className="text-xs font-semibold uppercase tracking-wide text-ink-3">{t('summary')}</p>
|
||||||
|
{lines.map(l => (
|
||||||
|
<div key={l.product.id} className="flex justify-between gap-2 text-sm"><span className="text-ink-2"><b className="text-ink">{l.qty}×</b> {l.product.name}</span><Money value={l.total} /></div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-ink-3">{t('payNote')}</p>
|
||||||
|
{problem && <p role="alert" className="p-3 rounded-control bg-danger-soft text-danger-ink text-sm">{t(problem)}</p>}
|
||||||
|
<button type="button" disabled={sending} onClick={send} data-testid="place-order"
|
||||||
|
className="h-12 rounded-full bg-accent text-accent-fg font-semibold flex items-center justify-center gap-2 disabled:opacity-60">
|
||||||
|
<Send size={16} aria-hidden="true" />{sending ? t('sending') : t('placeOrder', { total: money(total) })}
|
||||||
|
</button>
|
||||||
|
</>)}
|
||||||
|
</Sheet>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
import { useEffect, useState } from 'react'
|
|
||||||
import { useParams } from 'react-router-dom'
|
|
||||||
import { CheckCircle, Clock, XCircle, ChefHat, Truck, Package } from 'lucide-react'
|
|
||||||
import { fetchOrderStatus } from '../api'
|
|
||||||
|
|
||||||
const STATUS_CONFIG = {
|
|
||||||
pending_acceptance: { label: 'Waiting for confirmation', Icon: Clock, color: 'text-amber-500', bg: 'bg-amber-50' },
|
|
||||||
accepted: { label: 'Order accepted!', Icon: CheckCircle, color: 'text-emerald-500', bg: 'bg-emerald-50' },
|
|
||||||
rejected: { label: 'Order declined', Icon: XCircle, color: 'text-red-500', bg: 'bg-red-50' },
|
|
||||||
preparing: { label: 'Being prepared', Icon: ChefHat, color: 'text-blue-500', bg: 'bg-blue-50' },
|
|
||||||
ready: { label: 'Ready for pickup!', Icon: Package, color: 'text-emerald-500', bg: 'bg-emerald-50' },
|
|
||||||
out_for_delivery: { label: 'Out for delivery', Icon: Truck, color: 'text-blue-500', bg: 'bg-blue-50' },
|
|
||||||
delivered: { label: 'Delivered!', Icon: CheckCircle, color: 'text-emerald-500', bg: 'bg-emerald-50' },
|
|
||||||
}
|
|
||||||
|
|
||||||
const TERMINAL = new Set(['rejected', 'delivered'])
|
|
||||||
const POLL_MS = 10_000
|
|
||||||
|
|
||||||
export default function OrderConfirm() {
|
|
||||||
const { ref } = useParams()
|
|
||||||
const [orderStatus, setOrderStatus] = useState(null)
|
|
||||||
const [rejectionReason, setRejectionReason] = useState(null)
|
|
||||||
const [error, setError] = useState(false)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let timer
|
|
||||||
|
|
||||||
async function poll() {
|
|
||||||
try {
|
|
||||||
const data = await fetchOrderStatus(ref)
|
|
||||||
setOrderStatus(data.status)
|
|
||||||
setRejectionReason(data.rejection_reason)
|
|
||||||
if (!TERMINAL.has(data.status)) {
|
|
||||||
timer = setTimeout(poll, POLL_MS)
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
setError(true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
poll()
|
|
||||||
return () => clearTimeout(timer)
|
|
||||||
}, [ref])
|
|
||||||
|
|
||||||
const cfg = STATUS_CONFIG[orderStatus] || STATUS_CONFIG['pending_acceptance']
|
|
||||||
const { label, Icon, color, bg } = cfg
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-slate-50 flex items-center justify-center p-6">
|
|
||||||
<div className="bg-white rounded-2xl shadow-sm p-8 w-full max-w-sm text-center space-y-5">
|
|
||||||
|
|
||||||
<div className={`w-20 h-20 ${bg} rounded-full flex items-center justify-center mx-auto`}>
|
|
||||||
<Icon className={color} size={40} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-1">
|
|
||||||
<p className="text-xs text-slate-400 font-mono tracking-widest uppercase">{ref}</p>
|
|
||||||
<h1 className="text-2xl font-bold text-slate-800">
|
|
||||||
{error ? 'Could not load status' : label}
|
|
||||||
</h1>
|
|
||||||
{rejectionReason && (
|
|
||||||
<p className="text-sm text-slate-500 mt-1">Reason: {rejectionReason}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!TERMINAL.has(orderStatus) && !error && (
|
|
||||||
<p className="text-xs text-slate-400">
|
|
||||||
We'll update this page automatically. Keep it open.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{orderStatus === 'rejected' && (
|
|
||||||
<p className="text-sm text-slate-500">
|
|
||||||
We're sorry we couldn't take your order this time. Please try again or visit us in person.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{orderStatus === 'delivered' && (
|
|
||||||
<p className="text-sm text-slate-500">Thank you for your order! Enjoy your meal.</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!TERMINAL.has(orderStatus) && !error && (
|
|
||||||
<div className="flex justify-center">
|
|
||||||
<div className="w-5 h-5 rounded-full border-2 border-emerald-400 border-t-transparent animate-spin" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { X, Plus, Minus } from 'lucide-react'
|
|
||||||
|
|
||||||
export default function ProductModal({ product, onClose, onAdd }) {
|
|
||||||
const [quantity, setQuantity] = useState(1)
|
|
||||||
const [selectedOptions, setSelectedOptions] = useState([])
|
|
||||||
|
|
||||||
const basePrice = product.digital_price ?? product.base_price
|
|
||||||
const hasDiscount = product.digital_discount > 0 && !product.digital_price
|
|
||||||
const displayPrice = hasDiscount
|
|
||||||
? basePrice * (1 - product.digital_discount / 100)
|
|
||||||
: basePrice
|
|
||||||
|
|
||||||
function toggleOption(opt) {
|
|
||||||
setSelectedOptions(prev =>
|
|
||||||
prev.find(o => o.id === opt.id)
|
|
||||||
? prev.filter(o => o.id !== opt.id)
|
|
||||||
: [...prev, opt]
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const optionsTotal = selectedOptions.reduce((s, o) => s + (o.price || 0), 0)
|
|
||||||
const lineTotal = (displayPrice + optionsTotal) * quantity
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
|
|
||||||
<div className="absolute inset-0 bg-black/40" onClick={onClose} />
|
|
||||||
<div className="relative bg-white w-full max-w-lg rounded-t-2xl sm:rounded-2xl max-h-[90vh] overflow-y-auto">
|
|
||||||
|
|
||||||
{/* Image */}
|
|
||||||
{(product.digital_image_url || product.image_url) && (
|
|
||||||
<img
|
|
||||||
src={product.digital_image_url || product.image_url}
|
|
||||||
alt={product.digital_name || product.name}
|
|
||||||
className="w-full h-48 object-cover rounded-t-2xl sm:rounded-t-2xl"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={onClose}
|
|
||||||
className="absolute top-3 right-3 bg-white/90 rounded-full p-1.5 shadow"
|
|
||||||
>
|
|
||||||
<X size={18} />
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div className="p-5 space-y-4">
|
|
||||||
<div>
|
|
||||||
<h2 className="text-xl font-bold text-slate-800">
|
|
||||||
{product.digital_name || product.name}
|
|
||||||
</h2>
|
|
||||||
{product.digital_description && (
|
|
||||||
<p className="text-sm text-slate-500 mt-1">{product.digital_description}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Price */}
|
|
||||||
<div className="flex items-baseline gap-2">
|
|
||||||
<span className="text-2xl font-bold text-emerald-600">
|
|
||||||
€{displayPrice.toFixed(2)}
|
|
||||||
</span>
|
|
||||||
{hasDiscount && (
|
|
||||||
<span className="text-sm text-slate-400 line-through">
|
|
||||||
€{basePrice.toFixed(2)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{hasDiscount && (
|
|
||||||
<span className="text-xs bg-red-100 text-red-600 px-2 py-0.5 rounded-full font-semibold">
|
|
||||||
-{product.digital_discount}%
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Quick options */}
|
|
||||||
{product.quick_options?.length > 0 && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<p className="text-sm font-semibold text-slate-700">Options</p>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{product.quick_options.map(opt => {
|
|
||||||
const active = selectedOptions.find(o => o.id === opt.id)
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={opt.id}
|
|
||||||
onClick={() => toggleOption(opt)}
|
|
||||||
className={`px-3 py-1.5 rounded-full text-sm font-medium border transition-colors ${
|
|
||||||
active
|
|
||||||
? 'bg-emerald-500 text-white border-emerald-500'
|
|
||||||
: 'bg-white text-slate-700 border-slate-200 hover:border-emerald-300'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{opt.name}{opt.price > 0 ? ` +€${opt.price.toFixed(2)}` : ''}
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Quantity */}
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<span className="text-sm font-semibold text-slate-700">Quantity</span>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<button
|
|
||||||
onClick={() => setQuantity(q => Math.max(1, q - 1))}
|
|
||||||
className="w-9 h-9 rounded-full bg-slate-100 flex items-center justify-center hover:bg-slate-200"
|
|
||||||
>
|
|
||||||
<Minus size={16} />
|
|
||||||
</button>
|
|
||||||
<span className="text-lg font-bold w-6 text-center">{quantity}</span>
|
|
||||||
<button
|
|
||||||
onClick={() => setQuantity(q => q + 1)}
|
|
||||||
className="w-9 h-9 rounded-full bg-slate-100 flex items-center justify-center hover:bg-slate-200"
|
|
||||||
>
|
|
||||||
<Plus size={16} />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Add to cart */}
|
|
||||||
{product.digital_available ? (
|
|
||||||
<button
|
|
||||||
onClick={() => onAdd(product, quantity, selectedOptions)}
|
|
||||||
className="w-full bg-emerald-500 hover:bg-emerald-600 text-white py-3.5 rounded-xl font-semibold flex items-center justify-between px-5 transition-colors"
|
|
||||||
>
|
|
||||||
<span>Add to order</span>
|
|
||||||
<span>€{lineTotal.toFixed(2)}</span>
|
|
||||||
</button>
|
|
||||||
) : (
|
|
||||||
<div className="w-full bg-slate-100 text-slate-400 py-3.5 rounded-xl font-semibold text-center">
|
|
||||||
Currently unavailable
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,29 @@
|
|||||||
|
// The QR menu (plan step 6.5) on the customer apps' look: the same tokens as the order app.
|
||||||
/** @type {import('tailwindcss').Config} */
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
// Colours are tokens (CSS variables in src/index.css), never literals in components: one
|
||||||
|
// place to restyle the app, the same token names as the venue apps' @xenia/ui.
|
||||||
|
const c = name => `rgb(var(--o-${name}) / <alpha-value>)`
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
content: ['./index.html', './src/**/*.{js,jsx}'],
|
content: ['./index.html', './src/**/*.{js,jsx}'],
|
||||||
theme: {
|
theme: {
|
||||||
extend: {
|
extend: {
|
||||||
fontFamily: { sans: ['Geist', 'system-ui', 'sans-serif'] },
|
fontFamily: {
|
||||||
|
sans: ['Hanken Grotesk', 'Noto Sans', 'system-ui', 'sans-serif'],
|
||||||
|
display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'],
|
||||||
|
},
|
||||||
|
colors: {
|
||||||
|
canvas: c('canvas'),
|
||||||
|
surface: { DEFAULT: c('surface'), 2: c('surface-2') },
|
||||||
|
line: c('line'),
|
||||||
|
ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') },
|
||||||
|
accent: { DEFAULT: c('accent'), fg: c('accent-fg'), soft: c('accent-soft'), ink: c('accent-ink') },
|
||||||
|
success: { DEFAULT: c('success'), soft: c('success-soft'), ink: c('success-ink') },
|
||||||
|
warning: { soft: c('warning-soft'), ink: c('warning-ink') },
|
||||||
|
danger: { soft: c('danger-soft'), ink: c('danger-ink') },
|
||||||
|
},
|
||||||
|
borderRadius: { card: '18px', control: '12px' },
|
||||||
|
boxShadow: { card: '0 6px 18px -12px rgb(var(--o-shadow) / 0.45)', bar: '0 12px 28px -10px rgb(var(--o-shadow) / 0.6)' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
plugins: [],
|
plugins: [],
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
// The QR menu's logic (plan step 6.5).
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { allergenList, cartCount, cartLines, cartTotal, fold, menuFor, orderBody, refusalKey, search, setQty } from '../src/logic.js'
|
||||||
|
|
||||||
|
const data = { categories: [
|
||||||
|
{ id: 1, name: 'Ψητά', names: { el: 'Ψητά', en: 'Grill' }, products: [
|
||||||
|
{ id: 5, name: 'Σουβλάκι', names: { el: 'Σουβλάκι', en: 'Pork skewer' }, descriptions: { el: 'Με πίτα', en: 'With pitta' },
|
||||||
|
prices: { qr_table: 3.5, online_delivery: 4 }, sold_at: ['qr_table', 'online_delivery'], allergens: { gluten: 'contains', sesame: 'may_contain' } },
|
||||||
|
{ id: 6, name: 'Μπριζόλα', prices: { qr_table: 12 }, sold_at: ['qr_table'], digital_available: false },
|
||||||
|
{ id: 7, name: 'Delivery only', prices: { online_delivery: 9 }, sold_at: ['online_delivery'] },
|
||||||
|
] },
|
||||||
|
{ id: 2, name: 'Ορεκτικά', products: [{ id: 5, name: 'Σουβλάκι', names: { el: 'Σουβλάκι', en: 'Pork skewer' }, prices: { qr_table: 3.5 }, sold_at: ['qr_table'] }] },
|
||||||
|
{ id: 3, name: 'Empty', products: [{ id: 7, name: 'x', prices: {}, sold_at: ['online_takeaway'] }] },
|
||||||
|
] }
|
||||||
|
|
||||||
|
test('the menu in the guest\'s language, the QR menu\'s prices, only what it sells', () => {
|
||||||
|
const en = menuFor(data, 'en')
|
||||||
|
assert.deepEqual(en.map(c => c.name), ['Grill', 'Ορεκτικά']) // a category without a translation: as typed
|
||||||
|
const souv = en[0].products[0]
|
||||||
|
assert.equal(souv.name, 'Pork skewer')
|
||||||
|
assert.equal(souv.description, 'With pitta')
|
||||||
|
assert.equal(souv.price, 3.5)
|
||||||
|
assert.equal(en[0].products.length, 2) // the delivery-only dish isn't here
|
||||||
|
assert.equal(en[0].products[1].available, false)
|
||||||
|
assert.equal(en[1].products[0].repeat, true) // listed twice: search shows it once
|
||||||
|
assert.equal(menuFor(data, 'el')[0].products[0].name, 'Σουβλάκι')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('allergens: contains first, then may contain; older array data still read', () => {
|
||||||
|
assert.deepEqual(allergenList({ sesame: 'may_contain', milk: 'contains', pollen: 'contains' }), [{ key: 'milk', level: 'contains' }, { key: 'sesame', level: 'may_contain' }])
|
||||||
|
assert.deepEqual(allergenList(['gluten', 'dairy']), [{ key: 'gluten', level: 'contains' }])
|
||||||
|
assert.deepEqual(allergenList(null), [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('search: either language, no accents, each dish once', () => {
|
||||||
|
const en = menuFor(data, 'en')
|
||||||
|
assert.deepEqual(search(en, 'σουβλακι').map(p => p.id), ['5'])
|
||||||
|
assert.deepEqual(search(en, 'pork').map(p => p.id), ['5'])
|
||||||
|
assert.deepEqual(search(en, 'pitta').map(p => p.id), ['5'])
|
||||||
|
assert.deepEqual(search(en, ''), [])
|
||||||
|
assert.equal(fold('Σουβλάκι'), 'σουβλακι')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('the cart, its total and the order the cloud takes', () => {
|
||||||
|
const en = menuFor(data, 'en')
|
||||||
|
let cart = setQty({}, '5', 2)
|
||||||
|
cart = setQty(cart, '6', 1) // sold out: left out
|
||||||
|
cart = setQty(cart, '99', 1) // not on the menu any more
|
||||||
|
const lines = cartLines(cart, en)
|
||||||
|
assert.deepEqual(lines.map(l => [l.product.id, l.qty, l.total]), [['5', 2, 7]])
|
||||||
|
assert.equal(cartTotal(lines), 7)
|
||||||
|
assert.equal(cartCount(lines), 2)
|
||||||
|
assert.deepEqual(setQty({ 5: 1 }, '5', 0), {})
|
||||||
|
assert.deepEqual(orderBody(lines, { tableToken: 'tok', name: ' ', tableLabel: '5', tableWord: 'Table' }), {
|
||||||
|
order_type: 'dine_in', table_token: 'tok', customer_name: 'Table 5', items: [{ product_id: 5, quantity: 2, unit_price: 3.5 }], total: 7,
|
||||||
|
})
|
||||||
|
assert.equal(refusalKey('order.price_changed'), 'refused.changed')
|
||||||
|
assert.equal(refusalKey('order.table_invalid'), 'tableInvalid')
|
||||||
|
assert.equal(refusalKey('nope'), 'refused.failed')
|
||||||
|
})
|
||||||
@@ -7,6 +7,12 @@ server {
|
|||||||
try_files $uri $uri/ /menu/index.html;
|
try_files $uri $uri/ /menu/index.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Online ordering SPA (takeaway, delivery)
|
||||||
|
location /order/ {
|
||||||
|
alias /usr/share/nginx/html/order/;
|
||||||
|
try_files $uri $uri/ /order/index.html;
|
||||||
|
}
|
||||||
|
|
||||||
# Remote manager SPA
|
# Remote manager SPA
|
||||||
location /manage/ {
|
location /manage/ {
|
||||||
alias /usr/share/nginx/html/manage/;
|
alias /usr/share/nginx/html/manage/;
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
|
<meta name="theme-color" content="#1f3a34" />
|
||||||
|
<title>Order online</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Hanken+Grotesk:wght@400;500;600;700&family=Noto+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+3061
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"name": "order-app",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"test": "node --test \"tests/*.test.mjs\""
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.7.9",
|
||||||
|
"leaflet": "^1.9.4",
|
||||||
|
"lucide-react": "^1.14.0",
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1",
|
||||||
|
"react-router-dom": "^6.28.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-react": "^4.3.4",
|
||||||
|
"autoprefixer": "^10.4.20",
|
||||||
|
"postcss": "^8.4.49",
|
||||||
|
"tailwindcss": "^3.4.16",
|
||||||
|
"vite": "^6.0.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// The cloud's public endpoints for online ordering (cloud_backend/routers/orders.py, menu.py).
|
||||||
|
import axios from 'axios'
|
||||||
|
|
||||||
|
export const CLOUD_URL = import.meta.env.VITE_CLOUD_URL || ''
|
||||||
|
const api = axios.create({ baseURL: CLOUD_URL, timeout: 15000 })
|
||||||
|
|
||||||
|
/** The venue's menu, areas and ordering summary (services, open now, slots). */
|
||||||
|
export const fetchMenu = async site => (await api.get(`/api/menu/${encodeURIComponent(site)}`)).data
|
||||||
|
export const fetchSlots = async site => (await api.get(`/api/orders/${encodeURIComponent(site)}/slots`)).data
|
||||||
|
export const quote = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}/quote`, body)).data
|
||||||
|
export const placeOrder = async (site, body) => (await api.post(`/api/orders/${encodeURIComponent(site)}`, body)).data
|
||||||
|
export const track = async token => (await api.get(`/api/orders/track/${encodeURIComponent(token)}`)).data
|
||||||
|
export const imageUrl = url => (!url ? null : /^https?:\/\//i.test(url) ? url : `${CLOUD_URL}${url}`)
|
||||||
|
/** One venue day's table booking times (S.6): {day, slots: [iso]}. */
|
||||||
|
export const fetchBookingSlots = async (site, day) => (await api.get(`/api/orders/${encodeURIComponent(site)}/reservation-slots`, { params: { day } })).data
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
// The ordering app's texts (en, el). The customer's choice is remembered on this device; the
|
||||||
|
// first visit follows the browser's language.
|
||||||
|
import { createContext, useContext } from 'react'
|
||||||
|
|
||||||
|
const STORE = 'xenia-order-lang'
|
||||||
|
|
||||||
|
export const TEXTS = {
|
||||||
|
en: {
|
||||||
|
service: 'How', bookTable: 'Book a table',
|
||||||
|
book: {
|
||||||
|
party: 'People', day: 'Day', time: 'Time', none: 'No tables can be booked online right now.', noTimes: 'No free times this day. Try another day.',
|
||||||
|
food: 'Order food for when you arrive', foodHint: 'Pick dishes now: the kitchen prepares them for your arrival. You pay at the venue.',
|
||||||
|
continue: 'Continue', title: 'Book a table', tableFor_one: 'Table for {{count}}', tableFor_other: 'Table for {{count}}',
|
||||||
|
send: 'Request booking', note: 'The venue confirms your booking. You pay at the venue.', foodReady: 'Ready for when you arrive.',
|
||||||
|
},
|
||||||
|
takeaway: 'Takeaway', delivery: 'Delivery', open: 'Open now', closed: 'Closed now',
|
||||||
|
closedBody: 'You can still order for a later time.', noOrdering: 'Online ordering is not available right now.',
|
||||||
|
loading: 'Loading the menu…', notFound: 'This venue was not found.', loadFailed: 'The menu could not be loaded. Check your connection and try again.',
|
||||||
|
contains: 'Contains', mayContain: 'May contain',
|
||||||
|
allergen: {
|
||||||
|
gluten: 'Gluten', crustaceans: 'Crustaceans', eggs: 'Eggs', fish: 'Fish', peanuts: 'Peanuts', soybeans: 'Soya', milk: 'Milk',
|
||||||
|
nuts: 'Nuts', celery: 'Celery', mustard: 'Mustard', sesame: 'Sesame', sulphites: 'Sulphites', lupin: 'Lupin', molluscs: 'Molluscs',
|
||||||
|
},
|
||||||
|
retry: 'Try again', add: 'Add', soldOut: 'Sold out', options: 'Extras', addToOrder: 'Add to order', cancel: 'Cancel',
|
||||||
|
viewOrder: 'View order', items_one: '{{count}} item', items_other: '{{count}} items',
|
||||||
|
yourOrder: 'Your order', empty: 'Your order is empty.', products: 'Products', fee: 'Delivery fee', total: 'Total',
|
||||||
|
pricing: 'Working out the price…', details: 'Your details', name: 'Name', phone: 'Phone',
|
||||||
|
address: 'Street and number', area: 'Area', areaPick: 'Pick your area', byPostcode: 'Or enter your postcode',
|
||||||
|
byArea: 'Pick from the list', postcode: 'Postcode', notes: 'Notes for the venue (optional)',
|
||||||
|
byMap: 'Pin it on the map', pinHint: 'Tap the map where we deliver to. The coloured areas are where the venue delivers.',
|
||||||
|
myLocation: 'Use my location', locating: 'Finding you…', locationFailed: 'Your location could not be found. Tap the map instead.',
|
||||||
|
pinned: 'Pinned on the map', mapTiles: 'Map',
|
||||||
|
when: 'When', asap: 'As soon as possible', pickTime: 'Pick a time', today: 'Today', tomorrow: 'Tomorrow',
|
||||||
|
placeOrder: 'Place order · {{total}}', sending: 'Sending…', back: 'Back',
|
||||||
|
payNote: 'You pay at the venue or on delivery.',
|
||||||
|
problem: {
|
||||||
|
party: 'Pick how many people.',
|
||||||
|
name: 'Enter your name.', phone: 'Enter a phone number we can call.', address: 'Enter the delivery address.',
|
||||||
|
area: 'Pick your area.', postcode: 'Enter your postcode.', when: 'Pick a time.', pin: 'Tap the map where we deliver to.',
|
||||||
|
},
|
||||||
|
refused: {
|
||||||
|
minimum_not_met: 'The minimum order for delivery is {{minimum}}.', area_not_served: 'Sorry, we don\'t deliver to this address.',
|
||||||
|
price_changed: 'Prices changed since you opened the menu. Check your order: it now shows the current prices.',
|
||||||
|
item_unavailable: 'Something in your order is no longer available. Please remove it.', option_unavailable: 'An extra you chose is no longer available.',
|
||||||
|
service_unavailable: 'This service is not available right now.', closed: 'We\'re closed right now. Pick a later time.',
|
||||||
|
time_invalid: 'That time is no longer available. Pick another.', details_missing: 'Please fill in your details.',
|
||||||
|
party_invalid: 'We take online bookings for up to {{max}} people. Call us for larger groups.',
|
||||||
|
rate: 'Too many attempts. Please wait a few minutes.', no_menu: 'The menu is not available right now.', failed: 'Something went wrong. Please try again.',
|
||||||
|
},
|
||||||
|
track: {
|
||||||
|
booking: {
|
||||||
|
title: 'Booking {{ref}}', placed: 'Thank you! We got your booking request.',
|
||||||
|
pending_acceptance: 'Waiting for the venue to confirm', accepted: 'Confirmed', delivered: 'Welcome, you\'re here',
|
||||||
|
rejected: 'The venue could not take this booking', cancelled: 'Cancelled by the venue',
|
||||||
|
},
|
||||||
|
title: 'Order {{ref}}', placed: 'Thank you! We got your order.', for: 'For {{when}}', asap: 'As soon as possible',
|
||||||
|
keep: 'Keep this page open, or save its address, to follow your order.',
|
||||||
|
status: {
|
||||||
|
pending_acceptance: 'Waiting for the venue to confirm', accepted: 'Confirmed', preparing: 'Being prepared',
|
||||||
|
ready: 'Ready to collect', out_for_delivery: 'On its way', delivered: 'Done', rejected: 'Not accepted',
|
||||||
|
},
|
||||||
|
rejected: 'The venue could not take this order.', reason: 'Reason: {{reason}}', newOrder: 'Order again', notFound: 'This order was not found.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
el: {
|
||||||
|
service: 'Τρόπος', bookTable: 'Κράτηση τραπεζιού',
|
||||||
|
book: {
|
||||||
|
party: 'Άτομα', day: 'Ημέρα', time: 'Ώρα', none: 'Δεν γίνονται online κρατήσεις αυτή τη στιγμή.', noTimes: 'Δεν υπάρχουν ελεύθερες ώρες αυτή τη μέρα. Δοκιμάστε άλλη.',
|
||||||
|
food: 'Παραγγείλετε φαγητό για την άφιξή σας', foodHint: 'Διαλέξτε πιάτα τώρα: η κουζίνα τα ετοιμάζει για την ώρα που έρχεστε. Πληρώνετε στο κατάστημα.',
|
||||||
|
continue: 'Συνέχεια', title: 'Κράτηση τραπεζιού', tableFor_one: 'Τραπέζι για {{count}}', tableFor_other: 'Τραπέζι για {{count}}',
|
||||||
|
send: 'Αίτημα κράτησης', note: 'Το κατάστημα επιβεβαιώνει την κράτηση. Πληρώνετε στο κατάστημα.', foodReady: 'Έτοιμα για την άφιξή σας.',
|
||||||
|
},
|
||||||
|
takeaway: 'Παραλαβή', delivery: 'Διανομή', open: 'Ανοιχτά τώρα', closed: 'Κλειστά τώρα',
|
||||||
|
closedBody: 'Μπορείτε να παραγγείλετε για αργότερα.', noOrdering: 'Οι online παραγγελίες δεν είναι διαθέσιμες αυτή τη στιγμή.',
|
||||||
|
loading: 'Φόρτωση μενού…', notFound: 'Το κατάστημα δεν βρέθηκε.', loadFailed: 'Το μενού δεν φόρτωσε. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.',
|
||||||
|
contains: 'Περιέχει', mayContain: 'Μπορεί να περιέχει',
|
||||||
|
allergen: {
|
||||||
|
gluten: 'Γλουτένη', crustaceans: 'Καρκινοειδή', eggs: 'Αυγά', fish: 'Ψάρια', peanuts: 'Αράπικα φιστίκια', soybeans: 'Σόγια', milk: 'Γάλα',
|
||||||
|
nuts: 'Ξηροί καρποί', celery: 'Σέλινο', mustard: 'Μουστάρδα', sesame: 'Σουσάμι', sulphites: 'Θειώδη', lupin: 'Λούπινο', molluscs: 'Μαλάκια',
|
||||||
|
},
|
||||||
|
retry: 'Δοκιμάστε ξανά', add: 'Προσθήκη', soldOut: 'Εξαντλήθηκε', options: 'Έξτρα', addToOrder: 'Στην παραγγελία', cancel: 'Ακύρωση',
|
||||||
|
viewOrder: 'Η παραγγελία', items_one: '{{count}} τεμάχιο', items_other: '{{count}} τεμάχια',
|
||||||
|
yourOrder: 'Η παραγγελία σας', empty: 'Η παραγγελία σας είναι άδεια.', products: 'Προϊόντα', fee: 'Χρέωση διανομής', total: 'Σύνολο',
|
||||||
|
pricing: 'Υπολογισμός τιμής…', details: 'Τα στοιχεία σας', name: 'Όνομα', phone: 'Τηλέφωνο',
|
||||||
|
address: 'Οδός και αριθμός', area: 'Περιοχή', areaPick: 'Επιλέξτε περιοχή', byPostcode: 'Ή γράψτε τον Τ.Κ.',
|
||||||
|
byArea: 'Επιλογή από τη λίστα', postcode: 'Τ.Κ.', notes: 'Σημειώσεις για το κατάστημα (προαιρετικά)',
|
||||||
|
byMap: 'Σημείο στον χάρτη', pinHint: 'Πατήστε στον χάρτη εκεί που θα παραδώσουμε. Οι χρωματιστές περιοχές είναι εκεί που παραδίδει το κατάστημα.',
|
||||||
|
myLocation: 'Η τοποθεσία μου', locating: 'Αναζήτηση…', locationFailed: 'Η τοποθεσία σας δεν βρέθηκε. Πατήστε στον χάρτη.',
|
||||||
|
pinned: 'Σημείο στον χάρτη', mapTiles: 'Χάρτης',
|
||||||
|
when: 'Πότε', asap: 'Το συντομότερο', pickTime: 'Επιλέξτε ώρα', today: 'Σήμερα', tomorrow: 'Αύριο',
|
||||||
|
placeOrder: 'Αποστολή · {{total}}', sending: 'Αποστολή…', back: 'Πίσω',
|
||||||
|
payNote: 'Πληρώνετε στο κατάστημα ή κατά την παράδοση.',
|
||||||
|
problem: {
|
||||||
|
party: 'Επιλέξτε πόσα άτομα.',
|
||||||
|
name: 'Γράψτε το όνομά σας.', phone: 'Γράψτε ένα τηλέφωνο επικοινωνίας.', address: 'Γράψτε τη διεύθυνση παράδοσης.',
|
||||||
|
area: 'Επιλέξτε την περιοχή σας.', postcode: 'Γράψτε τον Τ.Κ.', when: 'Επιλέξτε ώρα.', pin: 'Πατήστε στον χάρτη εκεί που θα παραδώσουμε.',
|
||||||
|
},
|
||||||
|
refused: {
|
||||||
|
minimum_not_met: 'Η ελάχιστη παραγγελία για διανομή είναι {{minimum}}.', area_not_served: 'Δυστυχώς δεν κάνουμε διανομή σε αυτή τη διεύθυνση.',
|
||||||
|
price_changed: 'Οι τιμές άλλαξαν από τότε που ανοίξατε το μενού. Ελέγξτε την παραγγελία: δείχνει πλέον τις τρέχουσες τιμές.',
|
||||||
|
item_unavailable: 'Κάτι στην παραγγελία σας δεν είναι πλέον διαθέσιμο. Αφαιρέστε το.', option_unavailable: 'Ένα έξτρα που επιλέξατε δεν είναι πλέον διαθέσιμο.',
|
||||||
|
service_unavailable: 'Αυτή η υπηρεσία δεν είναι διαθέσιμη τώρα.', closed: 'Είμαστε κλειστά τώρα. Επιλέξτε αργότερη ώρα.',
|
||||||
|
time_invalid: 'Η ώρα αυτή δεν είναι πλέον διαθέσιμη. Επιλέξτε άλλη.', details_missing: 'Συμπληρώστε τα στοιχεία σας.',
|
||||||
|
party_invalid: 'Online κρατήσεις έως {{max}} άτομα. Για μεγαλύτερες παρέες τηλεφωνήστε μας.',
|
||||||
|
rate: 'Πολλές προσπάθειες. Περιμένετε λίγα λεπτά.', no_menu: 'Το μενού δεν είναι διαθέσιμο αυτή τη στιγμή.', failed: 'Κάτι πήγε στραβά. Δοκιμάστε ξανά.',
|
||||||
|
},
|
||||||
|
track: {
|
||||||
|
booking: {
|
||||||
|
title: 'Κράτηση {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε το αίτημα κράτησης.',
|
||||||
|
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', delivered: 'Καλώς ήρθατε',
|
||||||
|
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την κράτηση', cancelled: 'Ακυρώθηκε από το κατάστημα',
|
||||||
|
},
|
||||||
|
title: 'Παραγγελία {{ref}}', placed: 'Ευχαριστούμε! Λάβαμε την παραγγελία σας.', for: 'Για {{when}}', asap: 'Το συντομότερο',
|
||||||
|
keep: 'Κρατήστε αυτή τη σελίδα ανοιχτή, ή αποθηκεύστε τη διεύθυνσή της, για να παρακολουθείτε την παραγγελία.',
|
||||||
|
status: {
|
||||||
|
pending_acceptance: 'Αναμένεται επιβεβαίωση', accepted: 'Επιβεβαιώθηκε', preparing: 'Ετοιμάζεται',
|
||||||
|
ready: 'Έτοιμη για παραλαβή', out_for_delivery: 'Καθ\' οδόν', delivered: 'Ολοκληρώθηκε', rejected: 'Δεν έγινε δεκτή',
|
||||||
|
},
|
||||||
|
rejected: 'Το κατάστημα δεν μπόρεσε να δεχτεί την παραγγελία.', reason: 'Λόγος: {{reason}}', newOrder: 'Νέα παραγγελία', notFound: 'Η παραγγελία δεν βρέθηκε.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initialLang() {
|
||||||
|
try {
|
||||||
|
const saved = localStorage.getItem(STORE)
|
||||||
|
if (saved && TEXTS[saved]) return saved
|
||||||
|
} catch { /* private mode */ }
|
||||||
|
return (navigator.language || 'en').toLowerCase().startsWith('el') ? 'el' : 'en'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveLang(lang) {
|
||||||
|
try { localStorage.setItem(STORE, lang) } catch { /* private mode */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** t('a.b', {x}) with {{x}} and _one/_other plurals by `count`. */
|
||||||
|
export function translate(lang, key, params = {}) {
|
||||||
|
const dict = TEXTS[lang] ?? TEXTS.en
|
||||||
|
const find = k => k.split('.').reduce((o, p) => (o == null ? undefined : o[p]), dict)
|
||||||
|
let s = params.count != null ? find(`${key}_${params.count === 1 ? 'one' : 'other'}`) : undefined
|
||||||
|
if (s === undefined) s = find(key)
|
||||||
|
if (typeof s !== 'string') return key
|
||||||
|
return s.replace(/\{\{(\w+)\}\}/g, (_, k) => (params[k] ?? ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
export const LangContext = createContext({ lang: 'en', setLang: () => {} })
|
||||||
|
|
||||||
|
export function useT() {
|
||||||
|
const { lang, setLang } = useContext(LangContext)
|
||||||
|
const money = n => new Intl.NumberFormat(lang === 'el' ? 'el-GR' : 'en-IE', { style: 'currency', currency: 'EUR' }).format(n ?? 0)
|
||||||
|
return { lang, setLang, t: (key, params) => translate(lang, key, params), money }
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
/* The app's tokens (RGB triples, used through tailwind.config.js). Light only for now. */
|
||||||
|
:root {
|
||||||
|
--o-canvas: 246 244 239;
|
||||||
|
--o-surface: 255 255 255;
|
||||||
|
--o-surface-2: 239 236 228;
|
||||||
|
--o-line: 226 221 209;
|
||||||
|
--o-ink: 28 36 33;
|
||||||
|
--o-ink-2: 88 96 92;
|
||||||
|
--o-ink-3: 140 145 140;
|
||||||
|
--o-accent: 31 58 52;
|
||||||
|
--o-accent-fg: 247 244 236;
|
||||||
|
--o-accent-soft: 222 234 228;
|
||||||
|
--o-accent-ink: 24 66 56;
|
||||||
|
--o-success: 48 120 78;
|
||||||
|
--o-success-soft: 225 242 231;
|
||||||
|
--o-success-ink: 30 92 56;
|
||||||
|
--o-warning-soft: 252 240 214;
|
||||||
|
--o-warning-ink: 124 82 10;
|
||||||
|
--o-danger-soft: 251 228 222;
|
||||||
|
--o-danger-ink: 160 50 30;
|
||||||
|
--o-shadow: 28 36 33;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body { background: rgb(var(--o-canvas)); color: rgb(var(--o-ink)); }
|
||||||
|
body { font-family: theme('fontFamily.sans'); -webkit-font-smoothing: antialiased; }
|
||||||
|
button { -webkit-tap-highlight-color: transparent; }
|
||||||
|
:focus-visible { outline: 3px solid rgb(var(--o-accent) / 0.45); outline-offset: 2px; }
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
* { transition: none !important; animation: none !important; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
// The online ordering app's logic (plan phase 3S, step S.4). Pure: unit-tested in Node
|
||||||
|
// (tests/logic.test.mjs). Prices shown come from the venue's menu for the chosen service;
|
||||||
|
// what is charged is the cloud's answer (POST /api/orders/{site}/quote and the order itself).
|
||||||
|
|
||||||
|
export const SERVICES = ['takeaway', 'delivery']
|
||||||
|
// 'preorder': food ordered with a table booking, ready on arrival (S.6)
|
||||||
|
export const POINT = { takeaway: 'online_takeaway', delivery: 'online_delivery', preorder: 'online_preorder' }
|
||||||
|
export const BOOKING_TYPES = ['reservation', 'preorder']
|
||||||
|
|
||||||
|
const round2 = n => Math.round(n * 100) / 100
|
||||||
|
|
||||||
|
/** A product's price for a service, or null when it isn't sold that way. */
|
||||||
|
export function priceFor(product, service) {
|
||||||
|
const point = POINT[service]
|
||||||
|
if (product.sold_at && !product.sold_at.includes(point)) return null
|
||||||
|
if (product.prices) return product.prices[point] ?? null
|
||||||
|
return product.digital_price ?? product.base_price ?? null // menus from before S.2
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The menu for a service: categories with the products sold that way (once each, priced). */
|
||||||
|
export function menuFor(categories, service) {
|
||||||
|
const seen = new Set()
|
||||||
|
return (categories ?? []).map(c => ({
|
||||||
|
...c,
|
||||||
|
products: (c.products ?? []).filter(p => {
|
||||||
|
const price = priceFor(p, service)
|
||||||
|
return price != null
|
||||||
|
}).map(p => ({ ...p, price: priceFor(p, service), available: p.digital_available !== false, repeat: seen.has(p.id) || !seen.add(p.id) })),
|
||||||
|
})).filter(c => c.products.length > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const productName = p => p.digital_name || p.name
|
||||||
|
|
||||||
|
/** The 14 EU allergens (plan step 6.3), in the venue's order. */
|
||||||
|
export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs']
|
||||||
|
|
||||||
|
/** A product's allergens by level: {contains: [keys], may_contain: [keys]}. */
|
||||||
|
export function allergensOf(p) {
|
||||||
|
const m = p?.allergens && typeof p.allergens === 'object' && !Array.isArray(p.allergens) ? p.allergens : {}
|
||||||
|
return { contains: ALLERGENS.filter(k => m[k] === 'contains'), may_contain: ALLERGENS.filter(k => m[k] === 'may_contain') }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The menu in the guest's language (plan step 6.4): the venue sends each product's, quick option's
|
||||||
|
* and category's `names` (and `descriptions`) per menu language, already falling back to the text
|
||||||
|
* as typed; menus from older sites have none and stay as they are.
|
||||||
|
*/
|
||||||
|
export function localizeMenu(categories, lang) {
|
||||||
|
const pick = (texts, base) => (texts && texts[lang]) || base
|
||||||
|
return (categories ?? []).map(c => ({
|
||||||
|
...c,
|
||||||
|
name: pick(c.names, c.name),
|
||||||
|
products: (c.products ?? []).map(p => (p.names ? {
|
||||||
|
...p,
|
||||||
|
name: pick(p.names, p.digital_name || p.name),
|
||||||
|
digital_name: null,
|
||||||
|
digital_description: pick(p.descriptions, p.digital_description || '') || null,
|
||||||
|
quick_options: (p.quick_options ?? []).map(o => ({ ...o, name: pick(o.names, o.name) })),
|
||||||
|
} : p)),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
export const productText = p => p.digital_description || ''
|
||||||
|
|
||||||
|
/** A cart line's key: the product and its chosen options. */
|
||||||
|
export const lineKey = (productId, options = []) => [productId, ...[...options].sort((a, b) => a - b)].join(':')
|
||||||
|
|
||||||
|
/** Add one (or `qty`) of a product with options. */
|
||||||
|
export function addToCart(cart, product, options = [], qty = 1) {
|
||||||
|
const key = lineKey(product.id, options)
|
||||||
|
const found = cart.find(l => l.key === key)
|
||||||
|
if (found) return cart.map(l => (l.key === key ? { ...l, qty: Math.min(99, l.qty + qty) } : l))
|
||||||
|
return [...cart, { key, productId: product.id, options: [...options].sort((a, b) => a - b), qty }]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setQty(cart, key, qty) {
|
||||||
|
return qty <= 0 ? cart.filter(l => l.key !== key) : cart.map(l => (l.key === key ? { ...l, qty: Math.min(99, qty) } : l))
|
||||||
|
}
|
||||||
|
|
||||||
|
export const cartCount = cart => cart.reduce((s, l) => s + l.qty, 0)
|
||||||
|
|
||||||
|
/** The cart priced from the menu (what's shown before the cloud answers); lines whose product
|
||||||
|
* isn't sold for this service any more are dropped. */
|
||||||
|
export function cartLines(cart, products, service) {
|
||||||
|
const byId = new Map(products.map(p => [p.id, p]))
|
||||||
|
return cart.flatMap(l => {
|
||||||
|
const p = byId.get(l.productId)
|
||||||
|
const price = p ? priceFor(p, service) : null
|
||||||
|
if (price == null) return []
|
||||||
|
const opts = (p.quick_options ?? []).filter(o => l.options.includes(o.id))
|
||||||
|
const unit = round2(price + opts.reduce((s, o) => s + (o.price || 0), 0))
|
||||||
|
return [{ ...l, name: productName(p), unit, total: round2(unit * l.qty), optionNames: opts.map(o => o.name) }]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Items as the cloud takes them. */
|
||||||
|
export const itemsBody = lines => lines.map(l => ({ product_id: l.productId, quantity: l.qty, options: l.options, unit_price: l.unit }))
|
||||||
|
|
||||||
|
/** What checkout still needs: a list of field keys (empty = can order). */
|
||||||
|
export function checkoutProblems(form, service, { areas = [], asap = true, slots = [] } = {}) {
|
||||||
|
const out = []
|
||||||
|
if (!form.name.trim()) out.push('name')
|
||||||
|
if (!/^[+\d][\d\s-]{5,}$/.test(form.phone.trim())) out.push('phone')
|
||||||
|
if (service === 'delivery') {
|
||||||
|
if (!form.address.trim()) out.push('address')
|
||||||
|
if (areas.length && form.where === 'area' && !form.areaId) out.push('area')
|
||||||
|
if (form.where === 'postcode' && !form.postcode.trim()) out.push('postcode')
|
||||||
|
if (form.where === 'map' && !form.pin) out.push('pin') // 6R.G
|
||||||
|
}
|
||||||
|
if (form.when === 'asap' ? !asap : !slots.includes(form.when)) out.push('when')
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The order request (POST /api/orders/{site}). `quote` is the cloud's last answer. */
|
||||||
|
export function orderBody(form, service, lines, quote) {
|
||||||
|
return {
|
||||||
|
order_type: service,
|
||||||
|
customer_name: form.name.trim(),
|
||||||
|
customer_phone: form.phone.trim(),
|
||||||
|
customer_address: service === 'delivery' ? form.address.trim() : null,
|
||||||
|
customer_notes: form.notes.trim() || null,
|
||||||
|
area_id: service === 'delivery' && form.where === 'area' && form.areaId ? Number(form.areaId) : null,
|
||||||
|
postcode: service === 'delivery' && form.where === 'postcode' ? form.postcode.trim() || null : null,
|
||||||
|
// 6R.G: the customer's pin on the map (the venue's drawn areas are matched by it); only when given
|
||||||
|
...(service === 'delivery' && form.where === 'map' && form.pin ? { lat: form.pin[0], lng: form.pin[1] } : {}),
|
||||||
|
requested_for: form.when === 'asap' ? null : form.when,
|
||||||
|
items: itemsBody(lines),
|
||||||
|
total: quote?.total ?? undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Slots grouped by local day for the picker: [{ day: 'YYYY-MM-DD', times: [{ iso, label }] }]. */
|
||||||
|
export function slotDays(slots, timeZone) {
|
||||||
|
const dayFmt = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })
|
||||||
|
const timeFmt = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', minute: '2-digit', hour12: false })
|
||||||
|
const out = []
|
||||||
|
for (const iso of slots ?? []) {
|
||||||
|
const d = new Date(iso)
|
||||||
|
const day = dayFmt.format(d)
|
||||||
|
let g = out.find(x => x.day === day)
|
||||||
|
if (!g) out.push(g = { day, times: [] })
|
||||||
|
g.times.push({ iso, label: timeFmt.format(d) })
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a table booking still needs (S.6): field keys (empty = can send). */
|
||||||
|
export function bookingProblems(form, booking, partyMax = 99) {
|
||||||
|
const out = []
|
||||||
|
if (!form.name.trim()) out.push('name')
|
||||||
|
if (!/^[+\d][\d\s-]{5,}$/.test(form.phone.trim())) out.push('phone')
|
||||||
|
if (!(booking.party >= 1 && booking.party <= partyMax)) out.push('party')
|
||||||
|
if (!booking.when) out.push('when')
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The booking request (POST /api/orders/{site}): a table only, or with food (a preorder). */
|
||||||
|
export function bookingBody(form, booking, lines, quote) {
|
||||||
|
const food = lines.length > 0
|
||||||
|
return {
|
||||||
|
order_type: food ? 'preorder' : 'reservation',
|
||||||
|
customer_name: form.name.trim(),
|
||||||
|
customer_phone: form.phone.trim(),
|
||||||
|
customer_notes: form.notes.trim() || null,
|
||||||
|
party_size: booking.party,
|
||||||
|
requested_for: booking.when,
|
||||||
|
items: food ? itemsBody(lines) : [],
|
||||||
|
total: food ? (quote?.total ?? undefined) : undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The tracking page's steps for an order type, and how far it got. */
|
||||||
|
export function trackSteps(orderType, status) {
|
||||||
|
if (BOOKING_TYPES.includes(orderType)) {
|
||||||
|
const steps = ['pending_acceptance', 'accepted', 'delivered']
|
||||||
|
const over = ['rejected', 'cancelled'].includes(status)
|
||||||
|
return { steps, at: over ? -1 : steps.indexOf(status), done: status === 'delivered' || over }
|
||||||
|
}
|
||||||
|
const steps = orderType === 'delivery'
|
||||||
|
? ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered']
|
||||||
|
: ['pending_acceptance', 'accepted', 'preparing', 'ready', 'delivered']
|
||||||
|
return { steps, at: status === 'rejected' ? -1 : steps.indexOf(status), done: status === 'delivered' || status === 'rejected' }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A refusal from the cloud → a message key and its params. */
|
||||||
|
export function refusal(err) {
|
||||||
|
const d = err?.response?.data?.detail
|
||||||
|
if (err?.response?.status === 429) return ['rate', {}]
|
||||||
|
if (d && typeof d === 'object' && d.code) return [d.code.replace(/^order\./, ''), d.params ?? {}]
|
||||||
|
return ['failed', {}]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 6R.G: delivery areas drawn on a map ───────────────────────────────────────────────────
|
||||||
|
/** The venue's areas split by how the customer says where they are: `listed` (picked by name,
|
||||||
|
* postcode areas) and `shapes` (drawn on a map or a circle: the customer pins their address). */
|
||||||
|
export function areaKinds(areas = []) {
|
||||||
|
return {
|
||||||
|
listed: areas.filter(a => (a.kind ?? 'postcodes') === 'postcodes'),
|
||||||
|
shapes: areas.filter(a => a.kind === 'polygon' || a.kind === 'circle'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The ways offered to say where the delivery goes, in order: 'map' (when the venue drew areas),
|
||||||
|
* 'area' (a list to pick from), 'postcode' (always). The first is the default. */
|
||||||
|
export function whereOptions(areas = []) {
|
||||||
|
const { listed, shapes } = areaKinds(areas)
|
||||||
|
return [...(shapes.length ? ['map'] : []), ...(listed.length ? ['area'] : []), 'postcode']
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { StrictMode, useState } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import { BrowserRouter, Route, Routes } from 'react-router-dom'
|
||||||
|
import './index.css'
|
||||||
|
import { initialLang, LangContext, saveLang } from './i18n'
|
||||||
|
import OrderPage from './pages/OrderPage'
|
||||||
|
import TrackPage from './pages/TrackPage'
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [lang, setLangState] = useState(initialLang)
|
||||||
|
const setLang = l => { setLangState(l); saveLang(l); document.documentElement.lang = l }
|
||||||
|
document.documentElement.lang = lang
|
||||||
|
return (
|
||||||
|
<LangContext.Provider value={{ lang, setLang }}>
|
||||||
|
<BrowserRouter basename="/order">
|
||||||
|
<Routes>
|
||||||
|
<Route path="/:site" element={<OrderPage />} />
|
||||||
|
<Route path="/:site/track/:token" element={<TrackPage />} />
|
||||||
|
<Route path="*" element={<p className="p-6 text-ink-2">Xenia</p>} />
|
||||||
|
</Routes>
|
||||||
|
</BrowserRouter>
|
||||||
|
</LangContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')).render(<StrictMode><App /></StrictMode>)
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// Booking a table (plan phase 3S, step S.6): how many people, which day, what time, and
|
||||||
|
// (when the venue allows it) food ordered ahead to be ready on arrival. The days come with the
|
||||||
|
// menu (ordering.reservations.days); the times of a day from the cloud, in venue time.
|
||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import { Minus, Plus, Users } from 'lucide-react'
|
||||||
|
import { fetchBookingSlots } from '../api'
|
||||||
|
import { useT } from '../i18n'
|
||||||
|
import { slotDays } from '../logic'
|
||||||
|
|
||||||
|
export default function BookingPicker({ site, res, timeZone, booking, setBooking }) {
|
||||||
|
const { t, lang } = useT()
|
||||||
|
const [slots, setSlots] = useState(null)
|
||||||
|
const set = patch => setBooking(b => ({ ...b, ...patch }))
|
||||||
|
const day = booking.day ?? res.days[0] ?? null
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!day) return undefined
|
||||||
|
let alive = true
|
||||||
|
setSlots(null)
|
||||||
|
fetchBookingSlots(site, day).then(d => alive && setSlots(d.slots)).catch(() => alive && setSlots([]))
|
||||||
|
return () => { alive = false }
|
||||||
|
}, [site, day])
|
||||||
|
|
||||||
|
const times = useMemo(() => slotDays(slots ?? [], timeZone)[0]?.times ?? [], [slots, timeZone])
|
||||||
|
const today = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date())
|
||||||
|
const dayLabel = iso => {
|
||||||
|
const d = new Date(`${iso}T12:00:00Z`)
|
||||||
|
const diff = Math.round((d - new Date(`${today}T12:00:00Z`)) / 86_400_000)
|
||||||
|
if (diff === 0) return t('today')
|
||||||
|
if (diff === 1) return t('tomorrow')
|
||||||
|
return new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }).format(d)
|
||||||
|
}
|
||||||
|
const chip = on => `shrink-0 px-3.5 h-10 rounded-full text-sm font-semibold ${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`
|
||||||
|
|
||||||
|
if (!res.days.length) return <p className="p-3 rounded-control bg-warning-soft text-warning-ink text-sm" data-testid="no-booking">{t('book.none')}</p>
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid gap-3" data-testid="booking">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="flex-1 flex items-center gap-2 font-medium text-ink"><Users size={18} aria-hidden="true" />{t('book.party')}</span>
|
||||||
|
<button type="button" aria-label="−" onClick={() => set({ party: Math.max(1, booking.party - 1) })}
|
||||||
|
className="w-10 h-10 rounded-full bg-surface-2 flex items-center justify-center"><Minus size={16} /></button>
|
||||||
|
<span className="w-8 text-center text-lg font-semibold" data-testid="party">{booking.party}</span>
|
||||||
|
<button type="button" aria-label="+" onClick={() => set({ party: Math.min(res.party_max, booking.party + 1) })}
|
||||||
|
className="w-10 h-10 rounded-full bg-accent text-accent-fg flex items-center justify-center"><Plus size={16} /></button>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 overflow-x-auto pb-1" role="radiogroup" aria-label={t('book.day')}>
|
||||||
|
{res.days.map(d => (
|
||||||
|
<button key={d} type="button" role="radio" aria-checked={d === day} className={chip(d === day)} data-testid="book-day" data-day={d}
|
||||||
|
onClick={() => set({ day: d, when: null })}>{dayLabel(d)}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-4 gap-2" role="radiogroup" aria-label={t('book.time')} data-testid="book-times">
|
||||||
|
{slots === null && <p className="col-span-4 text-sm text-ink-2" role="status">{t('loading')}</p>}
|
||||||
|
{slots !== null && times.length === 0 && <p className="col-span-4 text-sm text-ink-2">{t('book.noTimes')}</p>}
|
||||||
|
{times.map(s => (
|
||||||
|
<button key={s.iso} type="button" role="radio" aria-checked={booking.when === s.iso} data-testid="book-time"
|
||||||
|
onClick={() => set({ day, when: s.iso })}
|
||||||
|
className={`h-10 rounded-control text-sm font-semibold ${booking.when === s.iso ? 'bg-accent text-accent-fg' : 'bg-surface border border-line text-ink'}`}>{s.label}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{res.with_food && (
|
||||||
|
<label className="flex items-start gap-3 p-3 rounded-control bg-surface-2 cursor-pointer">
|
||||||
|
<input type="checkbox" checked={booking.food} onChange={e => set({ food: e.target.checked })} data-testid="book-food"
|
||||||
|
className="mt-0.5 w-5 h-5 accent-[rgb(var(--o-accent))]" />
|
||||||
|
<span className="grid gap-0.5">
|
||||||
|
<span className="font-semibold text-ink">{t('book.food')}</span>
|
||||||
|
<span className="text-sm text-ink-2">{t('book.foodHint')}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
// Checkout (plan phase 3S, step S.4): the order priced by the cloud (products at this service's
|
||||||
|
// prices, the delivery fee from the venue's rules, the minimum), the customer's details, when
|
||||||
|
// (as soon as possible while open, or a time slot) and "Place order". Every price shown here is
|
||||||
|
// the cloud's answer; the order is refused if it changed meanwhile and the new prices show.
|
||||||
|
// S.6: service 'book' = a table booking (`booking` {party, when}), with food ordered ahead
|
||||||
|
// when there are lines (priced as a pre-order); no address, no time picker here.
|
||||||
|
// 6R.G: when the venue drew its delivery areas on a map, the customer pins the address (PinMap; the
|
||||||
|
// browser's location offered); the pin goes with the quote and the order and finds the area.
|
||||||
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import { ArrowLeft, LocateFixed, Minus, Plus } from 'lucide-react'
|
||||||
|
import { fetchSlots, placeOrder, quote } from '../api'
|
||||||
|
import { useT } from '../i18n'
|
||||||
|
import { areaKinds, bookingBody, bookingProblems, checkoutProblems, itemsBody, orderBody, refusal, setQty, slotDays, whereOptions } from '../logic'
|
||||||
|
import PinMap from './PinMap'
|
||||||
|
|
||||||
|
const QUOTE_DELAY = 250
|
||||||
|
const SLOTS_EVERY = 60_000
|
||||||
|
const FORM_KEY = 'xenia-order-details'
|
||||||
|
|
||||||
|
function savedDetails() {
|
||||||
|
try { return JSON.parse(localStorage.getItem(FORM_KEY) || '{}') } catch { return {} }
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Checkout({ site, service, booking, menu, lines, setCart, onBack, onPlaced }) {
|
||||||
|
const { t, money, lang } = useT()
|
||||||
|
const book = service === 'book'
|
||||||
|
const quoteType = book ? 'preorder' : service
|
||||||
|
const areas = menu.delivery_areas ?? []
|
||||||
|
const { listed, shapes } = areaKinds(areas)
|
||||||
|
const ways = whereOptions(areas)
|
||||||
|
const [form, setForm] = useState(() => ({
|
||||||
|
name: '', phone: '', address: '', notes: '', postcode: '', ...savedDetails(),
|
||||||
|
where: ways[0], areaId: '', when: 'asap', pin: null,
|
||||||
|
}))
|
||||||
|
const [locating, setLocating] = useState(null) // null | 'busy' | 'failed'
|
||||||
|
const [slots, setSlots] = useState(menu.ordering ?? { slots: [], asap: false, timezone: 'Europe/Athens' })
|
||||||
|
const [priced, setPriced] = useState({ quote: null, problem: null, pending: true })
|
||||||
|
const [tried, setTried] = useState(false)
|
||||||
|
const [sending, setSending] = useState(false)
|
||||||
|
const [sendProblem, setSendProblem] = useState(null)
|
||||||
|
const seq = useRef(0)
|
||||||
|
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
|
||||||
|
|
||||||
|
// the slots move on with the clock
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true
|
||||||
|
const load = () => fetchSlots(site).then(s => alive && setSlots(s)).catch(() => {})
|
||||||
|
load()
|
||||||
|
const id = setInterval(load, SLOTS_EVERY)
|
||||||
|
return () => { alive = false; clearInterval(id) }
|
||||||
|
}, [site])
|
||||||
|
useEffect(() => {
|
||||||
|
if (!book && form.when === 'asap' && !slots.asap && slots.slots?.length) set('when', slots.slots[0])
|
||||||
|
}, [slots, form.when, book])
|
||||||
|
|
||||||
|
// the cloud prices the order whenever what affects the price changes
|
||||||
|
const quoteKey = JSON.stringify([itemsBody(lines).map(i => [i.product_id, i.quantity, i.options]), service,
|
||||||
|
service === 'delivery' ? [form.where, form.areaId, form.postcode.trim(), form.pin] : null])
|
||||||
|
useEffect(() => {
|
||||||
|
const mine = ++seq.current
|
||||||
|
if (!lines.length) { setPriced({ quote: null, problem: null, pending: false }); return undefined }
|
||||||
|
setPriced(p => ({ ...p, pending: true }))
|
||||||
|
const id = setTimeout(async () => {
|
||||||
|
const body = orderBody(form, service, lines, null)
|
||||||
|
try {
|
||||||
|
const q = await quote(site, { order_type: quoteType, items: body.items, area_id: body.area_id, postcode: body.postcode, lat: body.lat, lng: body.lng })
|
||||||
|
if (mine === seq.current) setPriced({ quote: q, problem: null, pending: false })
|
||||||
|
} catch (err) {
|
||||||
|
if (mine === seq.current) setPriced({ quote: null, problem: refusal(err), pending: false })
|
||||||
|
}
|
||||||
|
}, QUOTE_DELAY)
|
||||||
|
return () => clearTimeout(id)
|
||||||
|
}, [quoteKey]) // eslint-disable-line react-hooks/exhaustive-deps -- quoteKey is what changes the price
|
||||||
|
|
||||||
|
const days = useMemo(() => slotDays(slots.slots ?? [], slots.timezone || 'Europe/Athens'), [slots])
|
||||||
|
const problems = book
|
||||||
|
? bookingProblems(form, booking, menu.ordering?.reservations?.party_max)
|
||||||
|
: checkoutProblems(form, service, { areas: listed, asap: !!slots.asap, slots: slots.slots ?? [] })
|
||||||
|
const q = priced.quote
|
||||||
|
const canSend = book && !lines.length ? !sending : (q && !priced.pending && !priced.problem && !sending)
|
||||||
|
const tz = menu.ordering?.timezone || 'Europe/Athens'
|
||||||
|
const bookedFor = book && booking.when
|
||||||
|
? new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', { weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit', hour12: false, timeZone: tz }).format(new Date(booking.when))
|
||||||
|
: null
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
setTried(true)
|
||||||
|
setSendProblem(null)
|
||||||
|
if (problems.length || !canSend) return
|
||||||
|
setSending(true)
|
||||||
|
try {
|
||||||
|
const body = book ? bookingBody(form, booking, lines, q) : orderBody(form, service, lines, q)
|
||||||
|
const result = await placeOrder(site, body)
|
||||||
|
try { localStorage.setItem(FORM_KEY, JSON.stringify({ name: form.name, phone: form.phone, address: form.address, postcode: form.postcode })) } catch { /* private mode */ }
|
||||||
|
onPlaced(result)
|
||||||
|
} catch (err) {
|
||||||
|
const [code, params] = refusal(err)
|
||||||
|
setSendProblem([code, params])
|
||||||
|
// the refusal carries the current prices: show them; "Place order" again sends the new total
|
||||||
|
if (code === 'price_changed' && params.lines) setPriced({ quote: params, problem: null, pending: false })
|
||||||
|
setSending(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const locate = () => {
|
||||||
|
if (!navigator.geolocation) { setLocating('failed'); return }
|
||||||
|
setLocating('busy')
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
p => { set('pin', [Math.round(p.coords.latitude * 1e6) / 1e6, Math.round(p.coords.longitude * 1e6) / 1e6]); setLocating(null) },
|
||||||
|
() => setLocating('failed'), { enableHighAccuracy: true, timeout: 15000 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const fieldErr = k => (tried && problems.includes(k) ? t(`problem.${k}`) : null)
|
||||||
|
const input = 'w-full h-12 px-3.5 rounded-control bg-surface border border-line text-ink placeholder:text-ink-3'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pb-10" data-testid="checkout">
|
||||||
|
<header className="px-4 py-3 flex items-center gap-2 bg-surface border-b border-line sticky top-0 z-10">
|
||||||
|
<button type="button" onClick={onBack} aria-label={t('back')} className="w-10 h-10 rounded-full bg-surface-2 flex items-center justify-center"><ArrowLeft size={18} /></button>
|
||||||
|
<h1 className="font-display text-xl font-semibold">{book ? t('book.title') : `${t('yourOrder')} · ${t(service)}`}</h1>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{book && (
|
||||||
|
<section className="mx-4 mt-4 p-4 rounded-card bg-accent-soft text-accent-ink grid gap-0.5" data-testid="booking-summary">
|
||||||
|
<p className="font-semibold">{t('book.tableFor', { count: booking.party })}</p>
|
||||||
|
<p>{bookedFor}</p>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<section className="p-4 grid gap-2" aria-label={t('yourOrder')}>
|
||||||
|
{lines.length === 0 && !book && <p className="text-ink-2">{t('empty')}</p>}
|
||||||
|
{lines.map(l => {
|
||||||
|
const cloudLine = q?.lines?.find(x => x.product_id === l.productId && JSON.stringify((x.options ?? []).map(o => o.id).sort()) === JSON.stringify(l.options))
|
||||||
|
return (
|
||||||
|
<div key={l.key} className="p-3 rounded-card bg-surface border border-line flex items-center gap-3" data-testid="line">
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="font-medium text-ink">{l.name}</p>
|
||||||
|
{l.optionNames.length > 0 && <p className="text-sm text-ink-2">{l.optionNames.join(', ')}</p>}
|
||||||
|
<p className="text-sm text-ink-2">{money(cloudLine?.unit_price ?? l.unit)}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<button type="button" onClick={() => setCart(c => setQty(c, l.key, l.qty - 1))} aria-label="−" className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><Minus size={16} /></button>
|
||||||
|
<span className="w-7 text-center font-semibold">{l.qty}</span>
|
||||||
|
<button type="button" onClick={() => setCart(c => setQty(c, l.key, l.qty + 1))} aria-label="+" className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><Plus size={16} /></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="px-4 grid gap-3" aria-labelledby="details-h">
|
||||||
|
<h2 id="details-h" className="font-display text-lg font-semibold">{t('details')}</h2>
|
||||||
|
<Field label={t('name')} error={fieldErr('name')}>
|
||||||
|
<input className={input} value={form.name} onChange={e => set('name', e.target.value)} autoComplete="name" maxLength={100} data-testid="f-name" />
|
||||||
|
</Field>
|
||||||
|
<Field label={t('phone')} error={fieldErr('phone')}>
|
||||||
|
<input className={input} value={form.phone} onChange={e => set('phone', e.target.value)} autoComplete="tel" inputMode="tel" maxLength={40} data-testid="f-phone" />
|
||||||
|
</Field>
|
||||||
|
{service === 'delivery' && (
|
||||||
|
<>
|
||||||
|
{ways.length > 1 && (
|
||||||
|
<div className="flex flex-wrap gap-2 text-sm" role="radiogroup" aria-label={t('area')}>
|
||||||
|
{ways.map(w => (
|
||||||
|
<button key={w} type="button" role="radio" aria-checked={form.where === w} onClick={() => set('where', w)} data-testid={`where-${w}`}
|
||||||
|
className={`px-3 h-9 rounded-full font-medium ${form.where === w ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
|
||||||
|
{w === 'map' ? t('byMap') : w === 'area' ? t('byArea') : t('byPostcode')}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{form.where === 'map' && shapes.length > 0 ? (
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<p className="text-sm text-ink-2">{t('pinHint')}</p>
|
||||||
|
<PinMap shapes={shapes} venue={menu.venue_point} value={form.pin} onChange={p => set('pin', p)} />
|
||||||
|
<button type="button" onClick={locate} disabled={locating === 'busy'} data-testid="locate"
|
||||||
|
className="justify-self-start px-3 h-10 rounded-full bg-surface-2 text-ink font-medium flex items-center gap-2">
|
||||||
|
<LocateFixed size={16} aria-hidden="true" />{locating === 'busy' ? t('locating') : t('myLocation')}
|
||||||
|
</button>
|
||||||
|
{locating === 'failed' && <p className="text-sm text-danger-ink" role="alert">{t('locationFailed')}</p>}
|
||||||
|
{fieldErr('pin') && <p className="text-sm text-danger-ink" role="alert">{fieldErr('pin')}</p>}
|
||||||
|
</div>
|
||||||
|
) : form.where === 'area' && listed.length > 0 ? (
|
||||||
|
<Field label={t('area')} error={fieldErr('area')}>
|
||||||
|
<select className={input} value={form.areaId} onChange={e => set('areaId', e.target.value)} data-testid="f-area">
|
||||||
|
<option value="">{t('areaPick')}</option>
|
||||||
|
{listed.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
) : (
|
||||||
|
<Field label={t('postcode')} error={fieldErr('postcode')}>
|
||||||
|
<input className={input} value={form.postcode} onChange={e => set('postcode', e.target.value)} autoComplete="postal-code" maxLength={20} data-testid="f-postcode" />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
<Field label={t('address')} error={fieldErr('address')}>
|
||||||
|
<input className={input} value={form.address} onChange={e => set('address', e.target.value)} autoComplete="street-address" maxLength={300} data-testid="f-address" />
|
||||||
|
</Field>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Field label={t('notes')}>
|
||||||
|
<textarea className={`${input} h-20 py-2.5`} value={form.notes} onChange={e => set('notes', e.target.value)} maxLength={500} />
|
||||||
|
</Field>
|
||||||
|
{!book && <Field label={t('when')} error={fieldErr('when')}>
|
||||||
|
<select className={input} value={form.when} onChange={e => set('when', e.target.value)} data-testid="f-when">
|
||||||
|
{slots.asap && <option value="asap">{t('asap')}</option>}
|
||||||
|
{!slots.asap && <option value="asap" disabled>{t('pickTime')}</option>}
|
||||||
|
{days.map((d, i) => (
|
||||||
|
<optgroup key={d.day} label={i === 0 ? t('today') : i === 1 ? t('tomorrow') : d.day}>
|
||||||
|
{d.times.map(s => <option key={s.iso} value={s.iso}>{s.label}</option>)}
|
||||||
|
</optgroup>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</Field>}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{(!book || lines.length > 0) && <section className="m-4 p-4 rounded-card bg-surface border border-line grid gap-1.5" aria-live="polite" data-testid="totals"
|
||||||
|
data-total={q?.total ?? ''} data-fee={q?.delivery_fee ?? ''}>
|
||||||
|
{priced.pending && <p className="text-sm text-ink-2">{t('pricing')}</p>}
|
||||||
|
{priced.problem && <p className="text-sm font-medium text-danger-ink" role="alert" data-testid="quote-problem" data-code={priced.problem[0]}>{refusedText(t, money, priced.problem)}</p>}
|
||||||
|
{q && (
|
||||||
|
<>
|
||||||
|
<Row label={t('products')} value={money(q.subtotal)} />
|
||||||
|
{service === 'delivery' && <Row label={t('fee') + (q.area_name ? ` · ${q.area_name}` : '')} value={money(q.delivery_fee)} testId="fee" />}
|
||||||
|
<Row label={t('total')} value={money(q.total)} strong />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</section>}
|
||||||
|
|
||||||
|
<div className="px-4 grid gap-2">
|
||||||
|
{sendProblem && <p className="text-sm font-medium text-danger-ink" role="alert" data-testid="send-problem" data-code={sendProblem[0]}>{refusedText(t, money, sendProblem)}</p>}
|
||||||
|
<button type="button" onClick={submit} disabled={sending || (!book && !lines.length)} data-testid="place-order"
|
||||||
|
className={`h-14 rounded-full font-semibold ${canSend ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-3'}`}>
|
||||||
|
{sending ? t('sending') : book ? t('book.send') : t('placeOrder', { total: q ? money(q.total) : '…' })}
|
||||||
|
</button>
|
||||||
|
<p className="text-sm text-ink-2 text-center">{book ? t('book.note') : t('payNote')}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function refusedText(t, money, [code, params]) {
|
||||||
|
return t(`refused.${code}`, { ...params, minimum: params.minimum != null ? money(params.minimum) : '' })
|
||||||
|
}
|
||||||
|
|
||||||
|
function Field({ label, error, children }) {
|
||||||
|
return (
|
||||||
|
<label className="grid gap-1">
|
||||||
|
<span className="text-sm font-medium text-ink-2">{label}</span>
|
||||||
|
{children}
|
||||||
|
{error && <span className="text-sm text-danger-ink" role="alert">{error}</span>}
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Row({ label, value, strong, testId }) {
|
||||||
|
return (
|
||||||
|
<div className={`flex items-baseline justify-between ${strong ? 'text-lg font-semibold text-ink pt-1 border-t border-line' : 'text-ink-2'}`} data-testid={testId}>
|
||||||
|
<span>{label}</span><span>{value}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
// Online ordering (plan phase 3S, step S.4): /order/{site}. The customer picks takeaway or
|
||||||
|
// delivery (what the venue offers), adds products at that service's prices, and checks out:
|
||||||
|
// the cart is priced by the cloud (with the delivery fee and minimum), then the order is
|
||||||
|
// placed for "as soon as possible" or a time slot, and the tracking page opens.
|
||||||
|
// S.6: "Book a table" (when the venue takes bookings): party, day, time, and maybe food ordered
|
||||||
|
// ahead at the pre-order prices; the details and the request on the next screen.
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { useNavigate, useParams } from 'react-router-dom'
|
||||||
|
import { Bike, CalendarDays, Clock, Minus, Plus, ShoppingBag, Store, X } from 'lucide-react'
|
||||||
|
import { fetchMenu, imageUrl } from '../api'
|
||||||
|
import { useT } from '../i18n'
|
||||||
|
import { addToCart, allergensOf, cartCount, cartLines, localizeMenu, menuFor, productName, productText, SERVICES } from '../logic'
|
||||||
|
import BookingPicker from './BookingPicker'
|
||||||
|
import Checkout from './Checkout'
|
||||||
|
|
||||||
|
const CART_KEY = site => `xenia-order-cart:${site}`
|
||||||
|
|
||||||
|
export default function OrderPage() {
|
||||||
|
const { site } = useParams()
|
||||||
|
const { t, lang, setLang, money } = useT()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const [menu, setMenu] = useState(null)
|
||||||
|
const [error, setError] = useState(null)
|
||||||
|
const [service, setService] = useState(null)
|
||||||
|
const [cart, setCart] = useState(() => {
|
||||||
|
try { return JSON.parse(sessionStorage.getItem(CART_KEY(site)) || '[]') } catch { return [] }
|
||||||
|
})
|
||||||
|
const [picking, setPicking] = useState(null) // a product whose extras are being chosen
|
||||||
|
const [checkout, setCheckout] = useState(false)
|
||||||
|
const [category, setCategory] = useState(null)
|
||||||
|
const [booking, setBooking] = useState({ party: 2, day: null, when: null, food: false })
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setError(null)
|
||||||
|
try {
|
||||||
|
const data = await fetchMenu(site)
|
||||||
|
setMenu(data)
|
||||||
|
setService(s => s ?? data.ordering?.services?.[0] ?? (data.ordering?.reservations?.enabled ? 'book' : null))
|
||||||
|
} catch (err) {
|
||||||
|
setError(err?.response?.status === 404 ? 'notFound' : 'loadFailed')
|
||||||
|
}
|
||||||
|
}, [site])
|
||||||
|
useEffect(() => { load() }, [load])
|
||||||
|
useEffect(() => {
|
||||||
|
try { sessionStorage.setItem(CART_KEY(site), JSON.stringify(cart)) } catch { /* private mode */ }
|
||||||
|
}, [cart, site])
|
||||||
|
|
||||||
|
const book = service === 'book'
|
||||||
|
// the prices: the service's; a booking's food at the pre-order prices (only when food is on)
|
||||||
|
const priceService = book ? (booking.food ? 'preorder' : null) : service
|
||||||
|
const sections = useMemo(() => (menu && priceService ? menuFor(localizeMenu(menu.categories, lang), priceService) : []), [menu, priceService, lang])
|
||||||
|
const products = useMemo(() => sections.flatMap(c => c.products), [sections])
|
||||||
|
const lines = useMemo(() => (priceService ? cartLines(cart, products, priceService) : []), [cart, products, priceService])
|
||||||
|
const count = cartCount(lines)
|
||||||
|
const subtotal = lines.reduce((s, l) => s + l.total, 0)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<div className="p-6 grid gap-4 text-center">
|
||||||
|
<p className="text-body text-ink-2">{t(error)}</p>
|
||||||
|
{error === 'loadFailed' && <button className="mx-auto px-5 h-11 rounded-full bg-accent text-accent-fg font-semibold" onClick={load}>{t('retry')}</button>}
|
||||||
|
</div>
|
||||||
|
</Shell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!menu) return <Shell><p className="p-6 text-center text-ink-2" role="status">{t('loading')}</p></Shell>
|
||||||
|
|
||||||
|
const ordering = menu.ordering ?? { services: [] }
|
||||||
|
const res = ordering.reservations ?? { enabled: false, days: [] }
|
||||||
|
const offered = [...SERVICES.filter(s => ordering.services.includes(s)), ...(res.enabled ? ['book'] : [])]
|
||||||
|
const ICON = { delivery: Bike, takeaway: Store, book: CalendarDays }
|
||||||
|
const name = menu.restaurant?.name || site
|
||||||
|
const add = (product, options = []) => setCart(c => addToCart(c, product, options))
|
||||||
|
|
||||||
|
if (checkout && service) {
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<Checkout site={site} service={book ? 'book' : service} booking={book ? booking : null} menu={menu} lines={lines} setCart={setCart}
|
||||||
|
onBack={() => setCheckout(false)}
|
||||||
|
onPlaced={(result) => {
|
||||||
|
// cleared here too: the page unmounts before its storage effect would run
|
||||||
|
try { sessionStorage.removeItem(CART_KEY(site)) } catch { /* private mode */ }
|
||||||
|
setCart([])
|
||||||
|
navigate(`/${site}/track/${result.tracking_token}`, { state: { placed: true } })
|
||||||
|
}} />
|
||||||
|
</Shell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<header className="px-4 pt-5 pb-3 grid gap-3 bg-surface border-b border-line">
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<h1 className="font-display text-2xl font-semibold text-ink leading-tight" data-testid="venue-name">{name}</h1>
|
||||||
|
{menu.restaurant?.tagline?.[lang === 'el' ? 'gr' : 'en'] && (
|
||||||
|
<p className="text-sm text-ink-2 mt-0.5">{menu.restaurant.tagline[lang === 'el' ? 'gr' : 'en']}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex rounded-full bg-surface-2 p-0.5 text-sm font-semibold" role="group" aria-label="Language">
|
||||||
|
{['el', 'en'].map(l => (
|
||||||
|
<button key={l} type="button" onClick={() => setLang(l)} aria-pressed={lang === l}
|
||||||
|
className={`px-2.5 h-8 rounded-full ${lang === l ? 'bg-surface text-ink shadow-card' : 'text-ink-2'}`}>{l.toUpperCase()}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{offered.length === 0 ? (
|
||||||
|
<p className="p-3 rounded-control bg-warning-soft text-warning-ink text-sm" data-testid="no-ordering">{t('noOrdering')}</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className={`grid gap-2 ${offered.length === 3 ? 'grid-cols-3' : offered.length === 2 ? 'grid-cols-2' : 'grid-cols-1'}`} role="radiogroup" aria-label={t('service')}>
|
||||||
|
{offered.map(s => {
|
||||||
|
const Icon = ICON[s]
|
||||||
|
return (
|
||||||
|
<button key={s} type="button" role="radio" aria-checked={service === s} onClick={() => setService(s)} data-testid={`service-${s}`}
|
||||||
|
className={`h-12 rounded-control flex items-center justify-center gap-2 font-semibold transition-colors
|
||||||
|
${offered.length === 3 ? 'gap-1.5 px-1.5 text-sm leading-tight' : ''}
|
||||||
|
${service === s ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
|
||||||
|
<Icon size={18} aria-hidden="true" />{t(s === 'book' ? 'bookTable' : s)}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
{book ? (
|
||||||
|
<BookingPicker site={site} res={res} timeZone={ordering.timezone || 'Europe/Athens'} booking={booking} setBooking={setBooking} />
|
||||||
|
) : (
|
||||||
|
<p className={`text-sm flex items-center gap-1.5 ${ordering.open_now ? 'text-success-ink' : 'text-warning-ink'}`} data-testid="open-state">
|
||||||
|
<Clock size={15} aria-hidden="true" />
|
||||||
|
{ordering.open_now ? t('open') : `${t('closed')} · ${t('closedBody')}`}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{sections.length > 1 && (
|
||||||
|
<nav className="sticky top-0 z-10 bg-canvas/95 backdrop-blur px-4 py-2 flex gap-2 overflow-x-auto border-b border-line" aria-label="Categories">
|
||||||
|
{sections.filter(c => c.products.some(p => !p.repeat)).map(c => (
|
||||||
|
<a key={c.id} href={`#cat-${c.id}`} onClick={() => setCategory(c.id)}
|
||||||
|
className={`shrink-0 px-3.5 h-9 rounded-full flex items-center text-sm font-medium ${category === c.id ? 'bg-accent text-accent-fg' : 'bg-surface text-ink-2 border border-line'}`}>{c.name}</a>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<main className="px-4 pb-32 pt-3 grid gap-6">
|
||||||
|
{sections.map(c => (
|
||||||
|
<section key={c.id} id={`cat-${c.id}`} className="grid gap-2 scroll-mt-16" aria-labelledby={`h-${c.id}`}>
|
||||||
|
<h2 id={`h-${c.id}`} className="font-display text-lg font-semibold text-ink">{c.name}</h2>
|
||||||
|
{c.products.map(p => (
|
||||||
|
<ProductCard key={`${c.id}-${p.id}`} product={p} qty={lines.filter(l => l.productId === p.id).reduce((s, l) => s + l.qty, 0)}
|
||||||
|
onAdd={() => (p.quick_options?.length ? setPicking(p) : add(p))}
|
||||||
|
onRemove={() => setCart(cc => {
|
||||||
|
const i = cc.map(l => l.productId).lastIndexOf(p.id)
|
||||||
|
if (i < 0) return cc
|
||||||
|
return cc[i].qty > 1 ? cc.map((l, j) => (j === i ? { ...l, qty: l.qty - 1 } : l)) : cc.filter((_, j) => j !== i)
|
||||||
|
})} />
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{book && booking.when && (
|
||||||
|
<div className="fixed inset-x-0 bottom-0 p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
|
||||||
|
<button type="button" onClick={() => setCheckout(true)} data-testid="book-continue"
|
||||||
|
className="mx-auto max-w-lg w-full h-14 px-5 rounded-full bg-accent text-accent-fg shadow-bar flex items-center gap-3 font-semibold">
|
||||||
|
<CalendarDays size={20} aria-hidden="true" />
|
||||||
|
<span className="flex-1 text-left">{t('book.continue')}{count > 0 ? ` · ${t('items', { count })}` : ''}</span>
|
||||||
|
{count > 0 && <span>{money(subtotal)}</span>}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!book && count > 0 && service && (
|
||||||
|
<div className="fixed inset-x-0 bottom-0 p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
|
||||||
|
<button type="button" onClick={() => setCheckout(true)} data-testid="view-order"
|
||||||
|
className="mx-auto max-w-lg w-full h-14 px-5 rounded-full bg-accent text-accent-fg shadow-bar flex items-center gap-3 font-semibold">
|
||||||
|
<ShoppingBag size={20} aria-hidden="true" />
|
||||||
|
<span className="flex-1 text-left">{t('viewOrder')} · {t('items', { count })}</span>
|
||||||
|
<span>{money(subtotal)}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{picking && <ExtrasSheet product={picking} onClose={() => setPicking(null)} onAdd={opts => { add(picking, opts); setPicking(null) }} />}
|
||||||
|
</Shell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Shell({ children }) {
|
||||||
|
return <div className="mx-auto max-w-lg min-h-dvh bg-canvas">{children}</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProductCard({ product, qty, onAdd, onRemove }) {
|
||||||
|
const { t, money } = useT()
|
||||||
|
const img = imageUrl(product.digital_image_url || product.image_url)
|
||||||
|
const text = productText(product)
|
||||||
|
return (
|
||||||
|
<article className="p-3 rounded-card bg-surface border border-line shadow-card flex gap-3" data-testid="product" data-product={product.id}>
|
||||||
|
{img && <img src={img} alt="" loading="lazy" className="w-20 h-20 rounded-control object-cover bg-surface-2 shrink-0" />}
|
||||||
|
<div className="flex-1 min-w-0 grid gap-1 content-start">
|
||||||
|
<h3 className="font-semibold text-ink leading-snug">{productName(product)}</h3>
|
||||||
|
{text && <p className="text-sm text-ink-2 line-clamp-2">{text}</p>}
|
||||||
|
<AllergenLine product={product} />
|
||||||
|
<div className="flex items-center justify-between gap-2 mt-1">
|
||||||
|
<span className="font-semibold text-ink" data-testid="price">{money(product.price)}</span>
|
||||||
|
{!product.available ? (
|
||||||
|
<span className="text-sm font-medium text-ink-3">{t('soldOut')}</span>
|
||||||
|
) : qty > 0 ? (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<button type="button" onClick={onRemove} aria-label="−" className="w-9 h-9 rounded-full bg-surface-2 text-ink flex items-center justify-center"><Minus size={16} /></button>
|
||||||
|
<span className="w-7 text-center font-semibold" data-testid="qty">{qty}</span>
|
||||||
|
<button type="button" onClick={onAdd} aria-label="+" className="w-9 h-9 rounded-full bg-accent text-accent-fg flex items-center justify-center"><Plus size={16} /></button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button type="button" onClick={onAdd} data-testid="add"
|
||||||
|
className="h-9 px-4 rounded-full bg-accent text-accent-fg text-sm font-semibold flex items-center gap-1"><Plus size={15} aria-hidden="true" />{t('add')}</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a dish contains and may contain (plan steps 6.3, 6.5). */
|
||||||
|
function AllergenLine({ product }) {
|
||||||
|
const { t } = useT()
|
||||||
|
const a = allergensOf(product)
|
||||||
|
if (!a.contains.length && !a.may_contain.length) return null
|
||||||
|
return (
|
||||||
|
<p className="text-xs" data-testid="allergens">
|
||||||
|
{a.contains.length > 0 && <span className="text-warning-ink">{t('contains')}: {a.contains.map(k => t(`allergen.${k}`)).join(', ')}</span>}
|
||||||
|
{a.contains.length > 0 && a.may_contain.length > 0 && ' · '}
|
||||||
|
{a.may_contain.length > 0 && <span className="text-ink-3">{t('mayContain')}: {a.may_contain.map(k => t(`allergen.${k}`)).join(', ')}</span>}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ExtrasSheet({ product, onClose, onAdd }) {
|
||||||
|
const { t, money } = useT()
|
||||||
|
const [chosen, setChosen] = useState([])
|
||||||
|
const toggle = id => setChosen(c => (c.includes(id) ? c.filter(x => x !== id) : [...c, id]))
|
||||||
|
const total = product.price + (product.quick_options ?? []).filter(o => chosen.includes(o.id)).reduce((s, o) => s + (o.price || 0), 0)
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-20 flex items-end justify-center bg-ink/40" role="dialog" aria-modal="true" aria-labelledby="extras-title" onClick={onClose}>
|
||||||
|
<div className="w-full max-w-lg bg-surface rounded-t-[22px] p-4 pb-[max(1rem,env(safe-area-inset-bottom))] grid gap-3" onClick={e => e.stopPropagation()}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h2 id="extras-title" className="flex-1 font-display text-lg font-semibold">{productName(product)}</h2>
|
||||||
|
<button type="button" onClick={onClose} aria-label={t('cancel')} className="w-9 h-9 rounded-full bg-surface-2 flex items-center justify-center"><X size={18} /></button>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm font-semibold text-ink-2">{t('options')}</p>
|
||||||
|
<div className="grid gap-1">
|
||||||
|
{product.quick_options.map(o => (
|
||||||
|
<label key={o.id} className="flex items-center gap-3 p-2.5 rounded-control bg-surface-2 cursor-pointer">
|
||||||
|
<input type="checkbox" checked={chosen.includes(o.id)} onChange={() => toggle(o.id)} className="w-5 h-5 accent-[rgb(var(--o-accent))]" />
|
||||||
|
<span className="flex-1">{o.name}</span>
|
||||||
|
{o.price ? <span className="text-sm text-ink-2">+{money(o.price)}</span> : null}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={() => onAdd(chosen)} data-testid="extras-add"
|
||||||
|
className="h-12 rounded-full bg-accent text-accent-fg font-semibold">{t('addToOrder')} · {money(total)}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
// The customer pins the delivery address on a map (plan 6R.G): Leaflet on OpenStreetMap tiles
|
||||||
|
// (attribution shown). The venue's drawn areas show in the accent colour, its own place as a dot;
|
||||||
|
// a tap (or "Use my location") puts the pin, which the cloud uses to find the area and the fee.
|
||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
import L from 'leaflet'
|
||||||
|
import 'leaflet/dist/leaflet.css'
|
||||||
|
|
||||||
|
const TILE = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
|
||||||
|
const ATTRIBUTION = '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
|
||||||
|
const rgb = name => `rgb(${getComputedStyle(document.documentElement).getPropertyValue(name).trim().split(/\s+/).join(',')})`
|
||||||
|
const pinIcon = () => L.divIcon({
|
||||||
|
className: '', iconSize: [28, 28], iconAnchor: [14, 28],
|
||||||
|
html: '<span style="display:block;width:28px;height:28px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);background:rgb(var(--o-accent));border:3px solid rgb(var(--o-surface));box-shadow:0 2px 6px rgb(var(--o-shadow) / .5)"></span>',
|
||||||
|
})
|
||||||
|
const venueIcon = () => L.divIcon({
|
||||||
|
className: '', iconSize: [14, 14], iconAnchor: [7, 7],
|
||||||
|
html: '<span style="display:block;width:14px;height:14px;border-radius:50%;background:rgb(var(--o-danger-ink));border:2px solid rgb(var(--o-surface))"></span>',
|
||||||
|
})
|
||||||
|
|
||||||
|
function boundsOf(a) {
|
||||||
|
if (a.kind === 'polygon' && Array.isArray(a.geometry) && a.geometry.length) return L.latLngBounds(a.geometry)
|
||||||
|
if (a.kind === 'circle' && a.geometry?.center && a.geometry.radius_m > 0) {
|
||||||
|
const [lat, lng] = a.geometry.center
|
||||||
|
const dLat = a.geometry.radius_m / 111320
|
||||||
|
const dLng = a.geometry.radius_m / (111320 * Math.max(0.01, Math.cos(lat * Math.PI / 180)))
|
||||||
|
return L.latLngBounds([lat - dLat, lng - dLng], [lat + dLat, lng + dLng])
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PinMap({ shapes = [], venue = null, value = null, onChange }) {
|
||||||
|
const box = useRef(null)
|
||||||
|
const map = useRef(null)
|
||||||
|
const marker = useRef(null)
|
||||||
|
const change = useRef(onChange)
|
||||||
|
useEffect(() => { change.current = onChange })
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const m = L.map(box.current, { zoomControl: true })
|
||||||
|
L.tileLayer(TILE, { maxZoom: 19, attribution: ATTRIBUTION }).addTo(m)
|
||||||
|
m.attributionControl.setPrefix('<a href="https://leafletjs.com">Leaflet</a>')
|
||||||
|
const accent = rgb('--o-accent')
|
||||||
|
for (const a of shapes) {
|
||||||
|
const style = { color: accent, weight: 2, fillOpacity: 0.12, interactive: false }
|
||||||
|
if (a.kind === 'polygon' && a.geometry?.length >= 3) L.polygon(a.geometry, style).addTo(m)
|
||||||
|
if (a.kind === 'circle' && a.geometry?.center) L.circle(a.geometry.center, { radius: a.geometry.radius_m, ...style }).addTo(m)
|
||||||
|
}
|
||||||
|
if (venue) L.marker([venue.lat, venue.lng], { icon: venueIcon(), interactive: false }).addTo(m)
|
||||||
|
const boxes = shapes.map(boundsOf).filter(Boolean)
|
||||||
|
if (value) m.setView(value, 16)
|
||||||
|
else if (boxes.length) m.fitBounds(boxes.reduce((all, b) => all.extend(b), L.latLngBounds(boxes[0].getSouthWest(), boxes[0].getNorthEast())).pad(0.1))
|
||||||
|
else if (venue) m.setView([venue.lat, venue.lng], 14)
|
||||||
|
else m.setView([38.3, 23.3], 7)
|
||||||
|
m.on('click', e => change.current?.([Math.round(e.latlng.lat * 1e6) / 1e6, Math.round(e.latlng.lng * 1e6) / 1e6]))
|
||||||
|
const ro = new ResizeObserver(() => m.invalidateSize())
|
||||||
|
ro.observe(box.current)
|
||||||
|
map.current = m
|
||||||
|
return () => { ro.disconnect(); m.remove(); map.current = null }
|
||||||
|
}, []) // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const m = map.current
|
||||||
|
if (!m) return
|
||||||
|
if (marker.current) { marker.current.remove(); marker.current = null }
|
||||||
|
if (value) {
|
||||||
|
marker.current = L.marker(value, { icon: pinIcon(), interactive: false }).addTo(m)
|
||||||
|
if (!m.getBounds().contains(value)) m.setView(value, Math.max(m.getZoom(), 16))
|
||||||
|
}
|
||||||
|
}, [value])
|
||||||
|
|
||||||
|
return <div ref={box} className="w-full h-72 rounded-card border border-line overflow-hidden relative z-0" data-testid="pin-map" data-pinned={value ? 'true' : 'false'} />
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// The customer's order tracking (plan phase 3S, step S.4): /order/{site}/track/{token}. The
|
||||||
|
// token is the order's private code (the address is the customer's to keep). Polls the cloud
|
||||||
|
// until the order is done or not accepted; shows the steps, what was ordered and for when.
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { Link, useLocation, useParams } from 'react-router-dom'
|
||||||
|
import { Check, X } from 'lucide-react'
|
||||||
|
import { track } from '../api'
|
||||||
|
import { useT } from '../i18n'
|
||||||
|
import { BOOKING_TYPES, trackSteps } from '../logic'
|
||||||
|
|
||||||
|
const POLL_MS = 8000
|
||||||
|
|
||||||
|
export default function TrackPage() {
|
||||||
|
const { site, token } = useParams()
|
||||||
|
const { t, money, lang } = useT()
|
||||||
|
const placed = useLocation().state?.placed
|
||||||
|
const [order, setOrder] = useState(null)
|
||||||
|
const [missing, setMissing] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let timer
|
||||||
|
let alive = true
|
||||||
|
const poll = async () => {
|
||||||
|
try {
|
||||||
|
const o = await track(token)
|
||||||
|
if (!alive) return
|
||||||
|
setOrder(o)
|
||||||
|
if (!trackSteps(o.order_type, o.status).done) timer = setTimeout(poll, POLL_MS)
|
||||||
|
} catch (err) {
|
||||||
|
if (!alive) return
|
||||||
|
if (err?.response?.status === 404) setMissing(true)
|
||||||
|
else timer = setTimeout(poll, POLL_MS) // offline for a moment: try again
|
||||||
|
}
|
||||||
|
}
|
||||||
|
poll()
|
||||||
|
return () => { alive = false; clearTimeout(timer) }
|
||||||
|
}, [token])
|
||||||
|
|
||||||
|
if (missing) return <Page><p className="p-6 text-center text-ink-2">{t('track.notFound')}</p></Page>
|
||||||
|
if (!order) return <Page><p className="p-6 text-center text-ink-2" role="status">{t('loading')}</p></Page>
|
||||||
|
|
||||||
|
const { steps, at } = trackSteps(order.order_type, order.status)
|
||||||
|
const rejected = order.status === 'rejected' || order.status === 'cancelled'
|
||||||
|
const booked = BOOKING_TYPES.includes(order.order_type) // a table booking (S.6)
|
||||||
|
const when = order.requested_for
|
||||||
|
? new Intl.DateTimeFormat(lang === 'el' ? 'el-GR' : 'en-GB', booked
|
||||||
|
? { weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit', hour12: false }
|
||||||
|
: { weekday: 'long', hour: '2-digit', minute: '2-digit' }).format(new Date(order.requested_for))
|
||||||
|
: null
|
||||||
|
const st = s => t(booked ? `track.booking.${s}` : `track.status.${s}`)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Page>
|
||||||
|
<div className="p-4 grid gap-4" data-testid="track" data-status={order.status}>
|
||||||
|
{placed && <p className="p-3 rounded-control bg-success-soft text-success-ink font-medium">{t(booked ? 'track.booking.placed' : 'track.placed')}</p>}
|
||||||
|
<header className="grid gap-1">
|
||||||
|
<h1 className="font-display text-2xl font-semibold" data-testid="track-ref">{t(booked ? 'track.booking.title' : 'track.title', { ref: order.public_ref })}</h1>
|
||||||
|
<p className="text-ink-2">
|
||||||
|
{booked ? `${t('book.tableFor', { count: order.party_size ?? 1 })} · ${when}`
|
||||||
|
: `${t(order.order_type === 'delivery' ? 'delivery' : 'takeaway')} · ${order.requested_for ? t('track.for', { when }) : t('track.asap')}`}
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{rejected ? (
|
||||||
|
<div className="p-4 rounded-card bg-danger-soft text-danger-ink grid gap-1" role="status">
|
||||||
|
<p className="font-semibold flex items-center gap-2"><X size={18} aria-hidden="true" />{booked ? st(order.status) : t('track.rejected')}</p>
|
||||||
|
{order.rejection_reason && <p>{t('track.reason', { reason: order.rejection_reason })}</p>}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ol className="grid gap-0" aria-label={st(order.status)}>
|
||||||
|
{steps.map((s, i) => {
|
||||||
|
const done = i < at || order.status === 'delivered'
|
||||||
|
const now = i === at && order.status !== 'delivered'
|
||||||
|
return (
|
||||||
|
<li key={s} className="flex items-center gap-3 py-2" aria-current={now ? 'step' : undefined}>
|
||||||
|
<span className={`w-7 h-7 rounded-full flex items-center justify-center shrink-0 text-sm font-semibold
|
||||||
|
${done ? 'bg-accent text-accent-fg' : now ? 'bg-accent-soft text-accent-ink ring-2 ring-accent' : 'bg-surface-2 text-ink-3'}`}>
|
||||||
|
{done ? <Check size={15} aria-hidden="true" /> : i + 1}
|
||||||
|
</span>
|
||||||
|
<span className={done || now ? 'text-ink font-medium' : 'text-ink-3'}>{st(s)}</span>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{(!booked || (order.lines ?? []).length > 0) && <section className="p-4 rounded-card bg-surface border border-line grid gap-1.5">
|
||||||
|
{(order.lines ?? []).map((l, i) => (
|
||||||
|
<div key={i} className="flex justify-between gap-3 text-ink-2">
|
||||||
|
<span>{l.quantity}× {l.name}{l.options?.length ? ` (${l.options.join(', ')})` : ''}</span>
|
||||||
|
<span>{money(l.unit_price * l.quantity)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{order.delivery_fee > 0 && <div className="flex justify-between text-ink-2"><span>{t('fee')}</span><span>{money(order.delivery_fee)}</span></div>}
|
||||||
|
<div className="flex justify-between text-lg font-semibold pt-1 border-t border-line"><span>{t('total')}</span><span data-testid="track-total">{money(order.total)}</span></div>
|
||||||
|
{booked && <p className="text-sm text-ink-2">{t('book.foodReady')}</p>}
|
||||||
|
</section>}
|
||||||
|
{!trackSteps(order.order_type, order.status).done && <p className="text-sm text-ink-2">{t('track.keep')}</p>}
|
||||||
|
<Link to={`/${site}`} className="text-center text-accent-ink font-semibold">{t('track.newOrder')}</Link>
|
||||||
|
</div>
|
||||||
|
</Page>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Page({ children }) {
|
||||||
|
return <div className="mx-auto max-w-lg min-h-dvh bg-canvas">{children}</div>
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
// Colours are tokens (CSS variables in src/index.css), never literals in components: one
|
||||||
|
// place to restyle the app, the same token names as the venue apps' @xenia/ui.
|
||||||
|
const c = name => `rgb(var(--o-${name}) / <alpha-value>)`
|
||||||
|
|
||||||
|
export default {
|
||||||
|
content: ['./index.html', './src/**/*.{js,jsx}'],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
fontFamily: {
|
||||||
|
sans: ['Hanken Grotesk', 'Noto Sans', 'system-ui', 'sans-serif'],
|
||||||
|
display: ['Bricolage Grotesque', 'Noto Sans', 'system-ui', 'sans-serif'],
|
||||||
|
},
|
||||||
|
colors: {
|
||||||
|
canvas: c('canvas'),
|
||||||
|
surface: { DEFAULT: c('surface'), 2: c('surface-2') },
|
||||||
|
line: c('line'),
|
||||||
|
ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') },
|
||||||
|
accent: { DEFAULT: c('accent'), fg: c('accent-fg'), soft: c('accent-soft'), ink: c('accent-ink') },
|
||||||
|
success: { DEFAULT: c('success'), soft: c('success-soft'), ink: c('success-ink') },
|
||||||
|
warning: { soft: c('warning-soft'), ink: c('warning-ink') },
|
||||||
|
danger: { soft: c('danger-soft'), ink: c('danger-ink') },
|
||||||
|
},
|
||||||
|
borderRadius: { card: '18px', control: '12px' },
|
||||||
|
boxShadow: { card: '0 6px 18px -12px rgb(var(--o-shadow) / 0.45)', bar: '0 12px 28px -10px rgb(var(--o-shadow) / 0.6)' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
// The online ordering app's logic (plan phase 3S, step S.4).
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import {
|
||||||
|
allergensOf, localizeMenu, productName,
|
||||||
|
addToCart, cartCount, cartLines, checkoutProblems, menuFor, orderBody, priceFor, refusal, setQty, slotDays, trackSteps,
|
||||||
|
} from '../src/logic.js'
|
||||||
|
|
||||||
|
const cola = { id: 1, name: 'Cola', sold_at: ['qr_table', 'online_takeaway', 'online_delivery'], prices: { qr_table: 3.5, online_takeaway: 2.5, online_delivery: 2.8 },
|
||||||
|
quick_options: [{ id: 7, name: 'Ice', price: 0.2 }] }
|
||||||
|
const pie = { id: 2, name: 'Pie', digital_name: 'Spinach pie', sold_at: ['online_takeaway'], prices: { online_takeaway: 4 }, digital_available: false }
|
||||||
|
const old = { id: 3, name: 'Old', digital_price: 5 }
|
||||||
|
const cats = [{ id: 10, name: 'Drinks', products: [cola] }, { id: 11, name: 'Food', products: [pie, old] }, { id: 12, name: 'Also', products: [cola] }]
|
||||||
|
|
||||||
|
test('the menu and prices per service', () => {
|
||||||
|
assert.equal(priceFor(cola, 'takeaway'), 2.5)
|
||||||
|
assert.equal(priceFor(cola, 'delivery'), 2.8)
|
||||||
|
assert.equal(priceFor(pie, 'delivery'), null)
|
||||||
|
assert.equal(priceFor(old, 'delivery'), 5)
|
||||||
|
const m = menuFor(cats, 'delivery')
|
||||||
|
assert.deepEqual(m.map(c => [c.name, c.products.map(p => [p.id, p.price, p.repeat])]), [['Drinks', [[1, 2.8, false]]], ['Food', [[3, 5, false]]], ['Also', [[1, 2.8, true]]]])
|
||||||
|
assert.equal(menuFor(cats, 'takeaway')[1].products[0].available, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('the cart', () => {
|
||||||
|
let cart = addToCart([], cola)
|
||||||
|
cart = addToCart(cart, cola)
|
||||||
|
cart = addToCart(cart, cola, [7])
|
||||||
|
assert.deepEqual(cart.map(l => [l.key, l.qty]), [['1', 2], ['1:7', 1]])
|
||||||
|
assert.equal(cartCount(cart), 3)
|
||||||
|
const lines = cartLines(cart, [cola, pie], 'takeaway')
|
||||||
|
assert.deepEqual(lines.map(l => [l.unit, l.total, l.optionNames]), [[2.5, 5, []], [2.7, 2.7, ['Ice']]])
|
||||||
|
assert.deepEqual(cartLines(addToCart(cart, pie), [cola, pie], 'delivery').length, 2) // the pie isn't delivered
|
||||||
|
assert.deepEqual(setQty(cart, '1', 0).map(l => l.key), ['1:7'])
|
||||||
|
assert.equal(setQty(cart, '1', 500)[0].qty, 99)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('checkout checks and the order body', () => {
|
||||||
|
const form = { name: ' Maria ', phone: '690 000 0000', address: '', notes: '', where: 'area', areaId: '', postcode: '', when: 'asap' }
|
||||||
|
assert.deepEqual(checkoutProblems(form, 'takeaway'), [])
|
||||||
|
assert.deepEqual(checkoutProblems(form, 'delivery', { areas: [{ id: 1 }] }), ['address', 'area'])
|
||||||
|
assert.deepEqual(checkoutProblems({ ...form, name: '', phone: 'abc' }, 'takeaway'), ['name', 'phone'])
|
||||||
|
assert.deepEqual(checkoutProblems(form, 'takeaway', { asap: false }), ['when'])
|
||||||
|
assert.deepEqual(checkoutProblems({ ...form, when: 'X' }, 'takeaway', { slots: ['X'] }), [])
|
||||||
|
const lines = cartLines(addToCart([], cola), [cola], 'delivery')
|
||||||
|
const body = orderBody({ ...form, address: 'Main sq 3', areaId: '2', notes: ' bell ' }, 'delivery', lines, { total: 4.8 })
|
||||||
|
assert.deepEqual(body, {
|
||||||
|
order_type: 'delivery', customer_name: 'Maria', customer_phone: '690 000 0000', customer_address: 'Main sq 3', customer_notes: 'bell',
|
||||||
|
area_id: 2, postcode: null, requested_for: null, items: [{ product_id: 1, quantity: 1, options: [], unit_price: 2.8 }], total: 4.8,
|
||||||
|
})
|
||||||
|
assert.equal(orderBody({ ...form, when: '2026-11-16T10:00:00+00:00' }, 'takeaway', lines, null).requested_for, '2026-11-16T10:00:00+00:00')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('slots by day in the venue time zone, tracking steps, refusals', () => {
|
||||||
|
const days = slotDays(['2026-11-15T19:45:00+00:00', '2026-11-15T22:00:00+00:00'], 'Europe/Athens')
|
||||||
|
assert.deepEqual(days, [{ day: '2026-11-15', times: [{ iso: '2026-11-15T19:45:00+00:00', label: '21:45' }] },
|
||||||
|
{ day: '2026-11-16', times: [{ iso: '2026-11-15T22:00:00+00:00', label: '00:00' }] }])
|
||||||
|
assert.deepEqual(trackSteps('delivery', 'preparing'), { steps: ['pending_acceptance', 'accepted', 'preparing', 'out_for_delivery', 'delivered'], at: 2, done: false })
|
||||||
|
assert.equal(trackSteps('takeaway', 'ready').at, 3)
|
||||||
|
assert.deepEqual(trackSteps('takeaway', 'rejected'), { ...trackSteps('takeaway', 'rejected'), at: -1, done: true })
|
||||||
|
assert.deepEqual(refusal({ response: { status: 409, data: { detail: { code: 'order.minimum_not_met', params: { minimum: 10 } } } } }), ['minimum_not_met', { minimum: 10 }])
|
||||||
|
assert.deepEqual(refusal({ response: { status: 429, data: {} } }), ['rate', {}])
|
||||||
|
assert.deepEqual(refusal(new Error('x')), ['failed', {}])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('booking a table, with or without food (S.6)', async () => {
|
||||||
|
const { bookingBody, bookingProblems } = await import('../src/logic.js')
|
||||||
|
const form = { name: 'Eleni', phone: '6977777777', notes: '' }
|
||||||
|
const booking = { party: 4, when: '2026-11-16T18:00:00+00:00' }
|
||||||
|
assert.deepEqual(bookingProblems(form, booking, 8), [])
|
||||||
|
assert.deepEqual(bookingProblems({ ...form, name: ' ' }, { party: 9, when: null }, 8), ['name', 'party', 'when'])
|
||||||
|
assert.deepEqual(bookingBody(form, booking, [], null), {
|
||||||
|
order_type: 'reservation', customer_name: 'Eleni', customer_phone: '6977777777', customer_notes: null,
|
||||||
|
party_size: 4, requested_for: booking.when, items: [], total: undefined,
|
||||||
|
})
|
||||||
|
const food = bookingBody(form, booking, [{ productId: 1, qty: 2, options: [], unit: 2.6 }], { total: 5.2 })
|
||||||
|
assert.equal(food.order_type, 'preorder')
|
||||||
|
assert.deepEqual(food.items, [{ product_id: 1, quantity: 2, options: [], unit_price: 2.6 }])
|
||||||
|
assert.equal(food.total, 5.2)
|
||||||
|
assert.deepEqual(trackSteps('reservation', 'accepted'), { steps: ['pending_acceptance', 'accepted', 'delivered'], at: 1, done: false })
|
||||||
|
assert.equal(trackSteps('preorder', 'cancelled').done, true)
|
||||||
|
assert.equal(trackSteps('preorder', 'cancelled').at, -1)
|
||||||
|
assert.equal(priceFor({ sold_at: ['online_preorder'], prices: { online_preorder: 2.6 } }, 'preorder'), 2.6)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('the menu in the guest’s language (6.4): names, descriptions, extras; old menus untouched', () => {
|
||||||
|
const cats = [{ id: 1, name: 'Ψητά', names: { el: 'Ψητά', en: 'Grill' }, products: [
|
||||||
|
{ id: 5, name: 'Σουβλάκι', digital_name: 'Σουβλάκι χοιρινό', names: { el: 'Σουβλάκι χοιρινό', en: 'Pork skewer' }, descriptions: { el: 'Με πίτα', en: 'With pitta' },
|
||||||
|
quick_options: [{ id: 9, name: 'Πίτα', names: { el: 'Πίτα', en: 'Pitta' } }] },
|
||||||
|
{ id: 6, name: 'Old', digital_name: 'Old one' }] }]
|
||||||
|
const en = localizeMenu(cats, 'en')
|
||||||
|
assert.equal(en[0].name, 'Grill')
|
||||||
|
assert.equal(productName(en[0].products[0]), 'Pork skewer')
|
||||||
|
assert.equal(en[0].products[0].digital_description, 'With pitta')
|
||||||
|
assert.equal(en[0].products[0].quick_options[0].name, 'Pitta')
|
||||||
|
assert.equal(productName(en[0].products[1]), 'Old one')
|
||||||
|
assert.equal(productName(localizeMenu(cats, 'el')[0].products[0]), 'Σουβλάκι χοιρινό')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a dish\'s allergens by level (6.3)', () => {
|
||||||
|
assert.deepEqual(allergensOf({ allergens: { sesame: 'may_contain', milk: 'contains', gluten: 'contains' } }), { contains: ['gluten', 'milk'], may_contain: ['sesame'] })
|
||||||
|
assert.deepEqual(allergensOf({ allergens: ['gluten'] }), { contains: [], may_contain: [] })
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test('6R.G: where the delivery goes: a pin when the venue drew areas', async () => {
|
||||||
|
const { areaKinds, whereOptions } = await import('../src/logic.js')
|
||||||
|
const areas = [{ id: 1, name: 'Centre', kind: 'postcodes' }, { id: 2, name: 'Drawn', kind: 'polygon', geometry: [[37, 22], [37, 22.1], [37.1, 22]] },
|
||||||
|
{ id: 3, name: 'Ring', kind: 'circle', geometry: { center: [37, 22], radius_m: 900 } }, { id: 4, name: 'Old style' }]
|
||||||
|
assert.deepEqual(areaKinds(areas).listed.map(a => a.id), [1, 4])
|
||||||
|
assert.deepEqual(areaKinds(areas).shapes.map(a => a.id), [2, 3])
|
||||||
|
assert.deepEqual(whereOptions(areas), ['map', 'area', 'postcode'])
|
||||||
|
assert.deepEqual(whereOptions([areas[0]]), ['area', 'postcode'])
|
||||||
|
assert.deepEqual(whereOptions([]), ['postcode'])
|
||||||
|
const form = { name: 'Maria', phone: '6911111111', address: 'Harbour 7', notes: '', postcode: '', areaId: '', where: 'map', pin: null, when: 'asap' }
|
||||||
|
assert.deepEqual(checkoutProblems(form, 'delivery', { areas, asap: true }), ['pin'])
|
||||||
|
const pinned = { ...form, pin: [37.05, 22.05] }
|
||||||
|
assert.deepEqual(checkoutProblems(pinned, 'delivery', { areas, asap: true }), [])
|
||||||
|
const body = orderBody(pinned, 'delivery', [], null)
|
||||||
|
assert.deepEqual([body.lat, body.lng, body.area_id, body.postcode], [37.05, 22.05, null, null])
|
||||||
|
assert.deepEqual([orderBody(pinned, 'takeaway', [], null).lat, orderBody({ ...pinned, where: 'postcode' }, 'delivery', [], null).lng], [undefined, undefined])
|
||||||
|
})
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
// The online ordering app (plan phase 3S, step S.4), served at /order/ next to the QR menu.
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
base: '/order/',
|
||||||
|
server: { host: '0.0.0.0', port: 5210 },
|
||||||
|
preview: { port: 5211 },
|
||||||
|
build: { outDir: 'dist' },
|
||||||
|
})
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# cloud-service — VPS Pack
|
||||||
|
|
||||||
|
Everything that runs **on the developer's VPS** and serves all client sites.
|
||||||
|
This folder is its **own git repo**, nested inside the `xenia-pos` parent repo.
|
||||||
|
|
||||||
|
> **Read the global rules first:** [../../docs/README.md](../../docs/README.md). This file adds only the rules specific to this pack.
|
||||||
|
> The feature catalog, the local ↔ cloud contract, known issues and site records all live in the parent's `docs/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Services
|
||||||
|
|
||||||
|
| Service | Stack | Host port | Audience |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `cloud_backend` | FastAPI + SQLAlchemy + SQLite (`${BACKEND_DATA}`) | 8001 | local sites (heartbeat/sync), sysadmin, connect apps |
|
||||||
|
| `sysadmin_panel` | React + Vite (`VITE_CLOUD_URL` baked in at build) | 5175 | the developer only |
|
||||||
|
| `connect_frontend` | nginx serving three SPAs: `menu-app` at `/menu/` (the QR menu: read, or order at a table with its QR code), `order-app` at `/order/` (online ordering: takeaway, delivery, table bookings; phase 3S), `manager-app` at `/manage/`. Public address = `PUBLIC_APPS_URL` (cloud `.env`), sent to sites with the heartbeat | 3100 | restaurant customers, remote managers |
|
||||||
|
|
||||||
|
TLS and domains are handled in front of these ports on the VPS (`xenia-api.bonamin.net` → cloud_backend, `xenia-admin.bonamin.net` → sysadmin panel, `registry.bonamin.net` → image registry).
|
||||||
|
|
||||||
|
## Routers (`cloud_backend/routers/`)
|
||||||
|
|
||||||
|
| Prefix | File | Auth | Used by |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `/api/auth` | `auth.py` | admin login | sysadmin panel |
|
||||||
|
| `/api/sites` | `sites.py` | admin bearer | sysadmin panel |
|
||||||
|
| `/api/heartbeat` | `heartbeat.py` | `X-Site-ID` + `X-Site-Key` | local sites |
|
||||||
|
| `/api/menu` | `menu.py` | public GET (`?t=` a table's QR token → `table`; the snapshot's `fees` and `qr` never leave the cloud); site headers for sync | menu-app, order-app, local sites |
|
||||||
|
| `/api/orders` | `orders.py` | public create/quote/slots/track (priced by `services/checkout.py`, fees `services/fees.py`, hours and slots `services/ordering.py` (bookings: `res_*`, `/reservation-slots`), table codes `services/qr.py`, rate-limited `services/ratelimit.py`; never the browser's numbers); site headers for pending/synced/status (own site only) | menu-app, order-app, local sites |
|
||||||
|
| `/api/manager` | `manager_auth.py` | manager bearer | manager-app, sysadmin |
|
||||||
|
| `/api/remote` | `remote_dashboard.py` | manager bearer; site headers for `POST /snapshot` | manager-app, local sites |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pack-specific rules
|
||||||
|
|
||||||
|
> **Branch `platform-v2`:** CL-1 applies **within v2** only (v1 sites stay on the `main` cloud until cutover, D-21), and CL-2 is replaced by Alembic (below). The license token is `v: 2` with a `modules` map (CL-6).
|
||||||
|
|
||||||
|
**CL-1. Old sites are always talking to you.**
|
||||||
|
Sites upgrade slowly, and some may be several versions behind. Every endpoint a site calls (the contract, C-1 … C-7) must stay backward compatible:
|
||||||
|
- add optional fields only
|
||||||
|
- never rename, remove or retype fields
|
||||||
|
- never make a new request field required
|
||||||
|
|
||||||
|
Any change to one of these endpoints updates the parent's `docs/reference/cloud-contract.md` (global Rule 6).
|
||||||
|
|
||||||
|
**CL-2. Schema changes are Alembic revisions** (branch `platform-v2`, D-22). Change the model, add it to `models/all.py` if new, then from `cloud_backend/`: `alembic revision --autogenerate --rev-id NNNN_short_name -m "..."`, review the file, run `python -m pytest tests -q` (drift guard, stamp+upgrade test). `create_all` is never used. The production DB is stamped to `0001_cloud_baseline` once at cutover (`DEPLOYMENT_GUIDE.md` → Part 6); until then the v2 cloud refuses it.
|
||||||
|
*(On `main`, the v1 rule still applies: `_run_migrations()`, additive only.)*
|
||||||
|
|
||||||
|
**CL-3. The cloud is never on the service-critical path.**
|
||||||
|
If the cloud is down, restaurants must keep taking orders (global Rule 8). Don't design features where the local site blocks while waiting on the cloud.
|
||||||
|
|
||||||
|
**CL-4. Public endpoints are hostile territory.**
|
||||||
|
`menu-app` endpoints are reachable by anyone on the internet. Validate everything, rate-limit where it makes sense, and never return data from another site. Site secrets (`SITE_KEY`) are shown **once**, at registration.
|
||||||
|
|
||||||
|
**CL-6. The license signing key is permanent.**
|
||||||
|
`LICENSE_SIGNING_KEY` (cloud `.env`) signs every site's license. Its public half is built into the site code. Never regenerate or lose it: a new key means every site needs a new image. Keep the backup at `%USERPROFILE%\.xenia\license_signing_key.txt` safe. Never add fields to the token payload that old sites would misread; bump `v` for incompatible changes.
|
||||||
|
|
||||||
|
**CL-9. Rate limits live in the process.** `services/ratelimit.py` counts per caller address in memory: right for the one uvicorn process the image runs. If the cloud ever runs several workers or replicas, move the counters to a shared store first, or each worker allows the full rate.
|
||||||
|
|
||||||
|
**CL-10. Table QR tokens are the site's secret.** The cloud only receives their sha256 (`qr.tables[].token_hash`) and compares in constant time (`services/qr.py`). Never store or log a token the cloud receives, and never return `qr` from a public endpoint.
|
||||||
|
|
||||||
|
**CL-8. The fee engine has two copies.** (6R.G: areas drawn on a map are matched by the customer's pin `lat` / `lng`: `price_cart(pin=)`, `online_orders.lat` / `lng` (Alembic 0007), the order app's `PinMap.jsx` on Leaflet + OpenStreetMap tiles.) `cloud_backend/services/fees.py` is byte-identical to the site's `local_backend/services/fees.py` (the cloud charges what the manager's "test an order" shows). Change both, and `tests/fixtures/fee_cases.json` in both repos; the site's `tests/test_fees.py` compares them.
|
||||||
|
|
||||||
|
**CL-5. Frontend URLs are baked in at build time.**
|
||||||
|
`VITE_CLOUD_URL` is a build arg, so changing it means rebuilding the image, not restarting it.
|
||||||
|
|
||||||
|
**CL-7. Licensed modules live in `sites.modules`** (v2). The sysadmin panel edits them (per site, or by applying a plan preset from `/api/presets`). The module editor is built from the catalogue each site reports in its heartbeat (`sites.module_catalog`), with `sysadmin_panel/src/moduleCatalog.js` as the fallback; keep that file in step with the local manifests.
|
||||||
|
|
||||||
|
## Common commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Deploy on the VPS
|
||||||
|
cd ~/stacks/xenia-pos-cloud && docker compose up -d --build
|
||||||
|
|
||||||
|
# Dev
|
||||||
|
cd cloud_backend && uvicorn main:app --reload --port 8001
|
||||||
|
cd cloud_backend && python -m pytest tests -q # schema guards, licensing v2 (pip install -r requirements-dev.txt)
|
||||||
|
cd sysadmin_panel && npm run dev
|
||||||
|
cd connect_frontend/menu-app && npm run dev
|
||||||
|
cd connect_frontend/order-app && npm run dev && npm test # VITE_CLOUD_URL=http://localhost:8001; e2e: client-services/tests/e2e/order_app.mjs
|
||||||
|
cd connect_frontend/manager-app && npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Releasing a new client version also means bumping `LATEST_VERSION` in `cloud_backend/.env` and redeploying. See the parent's `DEPLOYMENT_GUIDE.md`.
|
||||||
@@ -7,6 +7,12 @@ server {
|
|||||||
try_files $uri $uri/ /menu/index.html;
|
try_files $uri $uri/ /menu/index.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Online ordering SPA (takeaway, delivery)
|
||||||
|
location /order/ {
|
||||||
|
alias /usr/share/nginx/html/order/;
|
||||||
|
try_files $uri $uri/ /order/index.html;
|
||||||
|
}
|
||||||
|
|
||||||
# Remote manager SPA
|
# Remote manager SPA
|
||||||
location /manage/ {
|
location /manage/ {
|
||||||
alias /usr/share/nginx/html/manage/;
|
alias /usr/share/nginx/html/manage/;
|
||||||
|
|||||||
Generated
+10
@@ -9,6 +9,7 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.7.9",
|
"axios": "^1.7.9",
|
||||||
|
"qrcode.react": "^4.2.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-hot-toast": "^2.4.1",
|
"react-hot-toast": "^2.4.1",
|
||||||
@@ -2472,6 +2473,15 @@
|
|||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/qrcode.react": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
|
||||||
|
"license": "ISC",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/queue-microtask": {
|
"node_modules/queue-microtask": {
|
||||||
"version": "1.2.3",
|
"version": "1.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.7.9",
|
"axios": "^1.7.9",
|
||||||
|
"qrcode.react": "^4.2.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-hot-toast": "^2.4.1",
|
"react-hot-toast": "^2.4.1",
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import LoginPage from './pages/LoginPage'
|
|||||||
import SitesPage from './pages/SitesPage'
|
import SitesPage from './pages/SitesPage'
|
||||||
import SiteDetailPage from './pages/SiteDetailPage'
|
import SiteDetailPage from './pages/SiteDetailPage'
|
||||||
import RegisterSitePage from './pages/RegisterSitePage'
|
import RegisterSitePage from './pages/RegisterSitePage'
|
||||||
|
import PresetsPage from './pages/PresetsPage'
|
||||||
|
|
||||||
function Layout({ children }) {
|
function Layout({ children }) {
|
||||||
const { logout } = useAuthStore()
|
const { logout } = useAuthStore()
|
||||||
@@ -32,11 +33,16 @@ function Layout({ children }) {
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<span className={`text-xs px-2.5 py-1 rounded font-mono ${
|
<button onClick={() => navigate('/sites')} className={`text-xs px-2.5 py-1 rounded font-mono ${
|
||||||
location.pathname.startsWith('/sites') ? 'text-cyan-400 bg-cyan-500/10' : 'text-gray-500'
|
location.pathname.startsWith('/sites') ? 'text-cyan-400 bg-cyan-500/10' : 'text-gray-500 hover:text-gray-300'
|
||||||
}`}>
|
}`}>
|
||||||
Sites
|
Sites
|
||||||
</span>
|
</button>
|
||||||
|
<button onClick={() => navigate('/presets')} className={`text-xs px-2.5 py-1 rounded font-mono ${
|
||||||
|
location.pathname.startsWith('/presets') ? 'text-cyan-400 bg-cyan-500/10' : 'text-gray-500 hover:text-gray-300'
|
||||||
|
}`}>
|
||||||
|
Presets
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={handleLogout}
|
onClick={handleLogout}
|
||||||
className="text-xs text-gray-500 hover:text-gray-300 transition-colors"
|
className="text-xs text-gray-500 hover:text-gray-300 transition-colors"
|
||||||
@@ -75,6 +81,9 @@ export default function App() {
|
|||||||
<Route path="/sites/:siteId" element={
|
<Route path="/sites/:siteId" element={
|
||||||
<RequireAuth><Layout><SiteDetailPage /></Layout></RequireAuth>
|
<RequireAuth><Layout><SiteDetailPage /></Layout></RequireAuth>
|
||||||
} />
|
} />
|
||||||
|
<Route path="/presets" element={
|
||||||
|
<RequireAuth><Layout><PresetsPage /></Layout></RequireAuth>
|
||||||
|
} />
|
||||||
<Route path="*" element={<Navigate to="/sites" replace />} />
|
<Route path="*" element={<Navigate to="/sites" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -22,3 +22,16 @@ client.interceptors.response.use(
|
|||||||
)
|
)
|
||||||
|
|
||||||
export default client
|
export default client
|
||||||
|
|
||||||
|
// ── Remote Manager accounts ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const getManagersBySite = (siteId) =>
|
||||||
|
client.get(`/api/manager/by-site/${siteId}`)
|
||||||
|
|
||||||
|
export const addManagerToSite = (email, fullName, password, siteId) =>
|
||||||
|
client.post('/api/manager/register', {
|
||||||
|
email, full_name: fullName, password, site_ids: [siteId],
|
||||||
|
})
|
||||||
|
|
||||||
|
export const removeManagerSiteAccess = (managerId, siteId) =>
|
||||||
|
client.delete('/api/manager/site-access', { data: { manager_id: managerId, site_id: siteId } })
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
// Edits a license module map: { key: { limits?: {name: int|null}, exp?: ISO } } (APPS_PLATFORM §5.1).
|
||||||
|
// Core modules are always licensed and aren't shown. A limit field left empty uses the
|
||||||
|
// module's licensed default; "∞" sends null (unlimited). Expiry is optional, per module.
|
||||||
|
import { KIND_LABELS } from '../moduleCatalog'
|
||||||
|
|
||||||
|
function LimitInput({ limit, value, onChange }) {
|
||||||
|
const unlimited = value === null
|
||||||
|
const shown = value === undefined || value === null ? '' : String(value)
|
||||||
|
const fallback = limit.licensed_default === null || limit.licensed_default === undefined ? '∞' : limit.licensed_default
|
||||||
|
return (
|
||||||
|
<label className="flex items-center gap-1.5 text-xs text-gray-400">
|
||||||
|
<span className="font-mono">{limit.key}</span>
|
||||||
|
<input
|
||||||
|
type="number" min="0" disabled={unlimited} value={shown} placeholder={`default ${fallback}`}
|
||||||
|
onChange={e => onChange(e.target.value === '' ? undefined : Math.max(0, parseInt(e.target.value, 10) || 0))}
|
||||||
|
className="w-24 bg-gray-800 border border-gray-700 rounded px-2 py-1 text-gray-200 disabled:opacity-40"
|
||||||
|
/>
|
||||||
|
<button type="button" onClick={() => onChange(unlimited ? undefined : null)}
|
||||||
|
className={`px-1.5 py-0.5 rounded border ${unlimited ? 'border-cyan-500 text-cyan-300' : 'border-gray-700 text-gray-500'}`}
|
||||||
|
title="Unlimited">∞</button>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ModuleMapEditor({ catalog, value, onChange }) {
|
||||||
|
const map = value || {}
|
||||||
|
const groups = ['feature', 'app', 'integration']
|
||||||
|
|
||||||
|
function setEntry(key, entry) {
|
||||||
|
const next = { ...map }
|
||||||
|
if (entry === undefined) delete next[key]
|
||||||
|
else next[key] = entry
|
||||||
|
onChange(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setLimit(key, name, v) {
|
||||||
|
const entry = { ...(map[key] || {}) }
|
||||||
|
const limits = { ...(entry.limits || {}) }
|
||||||
|
if (v === undefined) delete limits[name]
|
||||||
|
else limits[name] = v
|
||||||
|
if (Object.keys(limits).length) entry.limits = limits
|
||||||
|
else delete entry.limits
|
||||||
|
setEntry(key, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setExp(key, date) {
|
||||||
|
const entry = { ...(map[key] || {}) }
|
||||||
|
if (date) entry.exp = `${date}T23:59:59+00:00`
|
||||||
|
else delete entry.exp
|
||||||
|
setEntry(key, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{groups.map(kind => {
|
||||||
|
const mods = catalog.filter(m => m.kind === kind)
|
||||||
|
if (!mods.length) return null
|
||||||
|
return (
|
||||||
|
<div key={kind}>
|
||||||
|
<div className="text-[11px] uppercase tracking-wider text-gray-500 mb-2">{KIND_LABELS[kind]}</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{mods.map(m => {
|
||||||
|
const on = m.key in map
|
||||||
|
const entry = map[m.key] || {}
|
||||||
|
return (
|
||||||
|
<div key={m.key} className={`rounded-lg border px-3 py-2 ${on ? 'border-cyan-800 bg-cyan-950/30' : 'border-gray-800'}`}>
|
||||||
|
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||||
|
<label className="flex items-center gap-2 text-sm text-gray-200 cursor-pointer">
|
||||||
|
<input type="checkbox" checked={on} onChange={e => setEntry(m.key, e.target.checked ? {} : undefined)} />
|
||||||
|
<span>{m.name}</span>
|
||||||
|
<span className="font-mono text-[11px] text-gray-500">{m.key}</span>
|
||||||
|
</label>
|
||||||
|
{on && (
|
||||||
|
<label className="flex items-center gap-1.5 text-xs text-gray-400">
|
||||||
|
expires
|
||||||
|
<input type="date" value={entry.exp ? entry.exp.slice(0, 10) : ''}
|
||||||
|
onChange={e => setExp(m.key, e.target.value)}
|
||||||
|
className="bg-gray-800 border border-gray-700 rounded px-2 py-1 text-gray-200" />
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{on && (m.limits || []).length > 0 && (
|
||||||
|
<div className="flex gap-4 flex-wrap mt-2 pl-6">
|
||||||
|
{m.limits.map(l => (
|
||||||
|
<LimitInput key={l.key} limit={l} value={entry.limits?.[l.key]}
|
||||||
|
onChange={v => setLimit(m.key, l.key, v)} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// Licensed modules of one site (APPS_PLATFORM D-3, §5.2): apply a preset, then edit per site.
|
||||||
|
// The site receives the map in its next heartbeat, inside the signed v2 license token.
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import client from '../api/client'
|
||||||
|
import { FALLBACK_CATALOG } from '../moduleCatalog'
|
||||||
|
import ModuleMapEditor from './ModuleMapEditor'
|
||||||
|
|
||||||
|
export default function SiteModulesCard({ site, onSaved }) {
|
||||||
|
const [map, setMap] = useState(site.modules || {})
|
||||||
|
const [presets, setPresets] = useState([])
|
||||||
|
const [presetId, setPresetId] = useState('')
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const reported = Array.isArray(site.module_catalog) && site.module_catalog.length > 0
|
||||||
|
const catalog = reported ? site.module_catalog : FALLBACK_CATALOG
|
||||||
|
const dirty = JSON.stringify(map) !== JSON.stringify(site.modules || {})
|
||||||
|
|
||||||
|
useEffect(() => { setMap(site.modules || {}) }, [site])
|
||||||
|
useEffect(() => {
|
||||||
|
client.get('/api/presets/').then(r => setPresets(r.data)).catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const { data } = await client.put(`/api/sites/${site.site_id}/modules`, { modules: map })
|
||||||
|
onSaved(data)
|
||||||
|
toast.success('Modules saved — the site picks them up on its next heartbeat')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(e.response?.data?.detail || 'Could not save modules')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyPreset() {
|
||||||
|
if (!presetId) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const { data } = await client.post(`/api/sites/${site.site_id}/apply-preset/${presetId}`)
|
||||||
|
onSaved(data)
|
||||||
|
toast.success('Preset applied')
|
||||||
|
} catch {
|
||||||
|
toast.error('Could not apply preset')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 mb-4">
|
||||||
|
<div className="flex items-center justify-between mb-1 gap-3 flex-wrap">
|
||||||
|
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider">Licensed modules</h2>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<select value={presetId} onChange={e => setPresetId(e.target.value)}
|
||||||
|
className="bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200">
|
||||||
|
<option value="">Preset…</option>
|
||||||
|
{presets.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
|
||||||
|
</select>
|
||||||
|
<button onClick={applyPreset} disabled={!presetId || saving}
|
||||||
|
className="text-xs px-2.5 py-1 rounded border border-gray-700 text-gray-300 hover:border-cyan-600 disabled:opacity-40">
|
||||||
|
Apply
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 mb-3">
|
||||||
|
{reported
|
||||||
|
? `Catalogue reported by the site${site.module_catalog_at ? ` (${new Date(site.module_catalog_at).toLocaleString()})` : ''}.`
|
||||||
|
: 'The site has not reported its catalogue yet — showing the standard list.'}{' '}
|
||||||
|
Core and catalogue are always included. Unlicensed modules fall back to the free tier.
|
||||||
|
</p>
|
||||||
|
<ModuleMapEditor catalog={catalog} value={map} onChange={setMap} />
|
||||||
|
<div className="flex justify-end gap-2 mt-4">
|
||||||
|
{dirty && (
|
||||||
|
<button onClick={() => setMap(site.modules || {})} className="text-xs px-3 py-1.5 text-gray-400 hover:text-gray-200">
|
||||||
|
Discard
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button onClick={save} disabled={!dirty || saving}
|
||||||
|
className="text-xs px-3 py-1.5 rounded bg-cyan-600 text-white hover:bg-cyan-500 disabled:opacity-40">
|
||||||
|
{saving ? 'Saving…' : 'Save modules'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// Fallback module catalogue (APPS_PLATFORM §4.2) for sites that haven't reported theirs yet
|
||||||
|
// and for editing presets. A site's own catalogue (heartbeat `module_catalog`, D-20) always
|
||||||
|
// wins, because it lists exactly what that site's code can run.
|
||||||
|
// Keep in step with client-services/local_backend/modules/*/manifest.py.
|
||||||
|
export const FALLBACK_CATALOG = [
|
||||||
|
{ key: 'core', kind: 'core', name: 'Core', limits: [] },
|
||||||
|
{ key: 'catalog', kind: 'core', name: 'Catalogue', limits: [] },
|
||||||
|
{ key: 'history', kind: 'feature', name: 'Order history', limits: [{ key: 'history_days', free: 31, licensed_default: null }] },
|
||||||
|
{ key: 'ordering', kind: 'feature', name: 'Ordering', limits: [] },
|
||||||
|
{ key: 'reports', kind: 'feature', name: 'Reports', limits: [{ key: 'history_days', free: 0, licensed_default: null }] },
|
||||||
|
{ key: 'pricing', kind: 'feature', name: 'Pricing', limits: [] },
|
||||||
|
{ key: 'tabs', kind: 'feature', name: 'Tabs', limits: [] },
|
||||||
|
{ key: 'crm', kind: 'feature', name: 'Customers', limits: [] },
|
||||||
|
{ key: 'expenses', kind: 'feature', name: 'Expenses', limits: [] },
|
||||||
|
{ key: 'inventory', kind: 'feature', name: 'Inventory', limits: [] },
|
||||||
|
{ key: 'staff_planning', kind: 'feature', name: 'Staff planning', limits: [] },
|
||||||
|
{ key: 'notes', kind: 'feature', name: 'Notes', limits: [] },
|
||||||
|
{ key: 'chat', kind: 'feature', name: 'Staff chat', limits: [] },
|
||||||
|
{ key: 'reservations', kind: 'feature', name: 'Reservations', limits: [] },
|
||||||
|
{ key: 'connect_menu', kind: 'feature', name: 'QR menu', limits: [] },
|
||||||
|
{ key: 'connect_orders', kind: 'feature', name: 'Online orders', limits: [] },
|
||||||
|
{ key: 'connect_remote', kind: 'feature', name: 'Remote manager', limits: [] },
|
||||||
|
{ key: 'waiter_app', kind: 'app', name: 'Waiter app', limits: [] },
|
||||||
|
{ key: 'kds', kind: 'app', name: 'Kitchen display', limits: [{ key: 'devices', free: 0, licensed_default: 1 }] },
|
||||||
|
{ key: 'pos_counter', kind: 'app', name: 'Counter POS', limits: [{ key: 'devices', free: 0, licensed_default: 1 }] },
|
||||||
|
{ key: 'customer_display', kind: 'app', name: 'Customer display', limits: [{ key: 'devices', free: 0, licensed_default: 1 }] },
|
||||||
|
{ key: 'signage', kind: 'app', name: 'Digital signage', limits: [{ key: 'devices', free: 0, licensed_default: 1 }] },
|
||||||
|
{ key: 'menu_tablet', kind: 'app', name: 'Menu tablet', limits: [{ key: 'devices', free: 0, licensed_default: 1 }] },
|
||||||
|
{ key: 'caller_id', kind: 'integration', name: 'Caller ID', limits: [] },
|
||||||
|
{ key: 'fiscal', kind: 'integration', name: 'Fiscal device', limits: [] },
|
||||||
|
]
|
||||||
|
|
||||||
|
export const KIND_LABELS = { feature: 'Features', app: 'Apps', integration: 'Integrations' }
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// Plan presets (APPS_PLATFORM D-3, §5.2): named module maps applied to sites.
|
||||||
|
// A preset only fills in a site's map; after applying, each site is edited on its own.
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import client from '../api/client'
|
||||||
|
import { FALLBACK_CATALOG } from '../moduleCatalog'
|
||||||
|
import ModuleMapEditor from '../components/ModuleMapEditor'
|
||||||
|
|
||||||
|
const EMPTY = { id: null, name: '', description: '', modules: {} }
|
||||||
|
|
||||||
|
export default function PresetsPage() {
|
||||||
|
const [presets, setPresets] = useState([])
|
||||||
|
const [editing, setEditing] = useState(null)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
setPresets((await client.get('/api/presets/')).data)
|
||||||
|
} catch {
|
||||||
|
toast.error('Could not load presets')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
useEffect(() => { load() }, [])
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (!editing.name.trim()) { toast.error('Give the preset a name'); return }
|
||||||
|
setSaving(true)
|
||||||
|
const body = { name: editing.name.trim(), description: editing.description || null, modules: editing.modules }
|
||||||
|
try {
|
||||||
|
if (editing.id) await client.put(`/api/presets/${editing.id}`, body)
|
||||||
|
else await client.post('/api/presets/', body)
|
||||||
|
toast.success('Preset saved')
|
||||||
|
setEditing(null)
|
||||||
|
load()
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(e.response?.data?.detail || 'Could not save preset')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(p) {
|
||||||
|
if (!window.confirm(`Delete preset "${p.name}"? Sites keep their modules.`)) return
|
||||||
|
await client.delete(`/api/presets/${p.id}`)
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h1 className="text-lg font-semibold text-white">Plan presets</h1>
|
||||||
|
{!editing && (
|
||||||
|
<button onClick={() => setEditing({ ...EMPTY })}
|
||||||
|
className="text-xs px-3 py-1.5 rounded bg-cyan-600 text-white hover:bg-cyan-500">New preset</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{editing ? (
|
||||||
|
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2 mb-4">
|
||||||
|
<input value={editing.name} onChange={e => setEditing({ ...editing, name: e.target.value })} placeholder="Name"
|
||||||
|
className="bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-gray-200" />
|
||||||
|
<input value={editing.description || ''} onChange={e => setEditing({ ...editing, description: e.target.value })}
|
||||||
|
placeholder="Description (optional)" className="bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm text-gray-200" />
|
||||||
|
</div>
|
||||||
|
<ModuleMapEditor catalog={FALLBACK_CATALOG} value={editing.modules}
|
||||||
|
onChange={modules => setEditing({ ...editing, modules })} />
|
||||||
|
<div className="flex justify-end gap-2 mt-4">
|
||||||
|
<button onClick={() => setEditing(null)} className="text-xs px-3 py-1.5 text-gray-400 hover:text-gray-200">Cancel</button>
|
||||||
|
<button onClick={save} disabled={saving}
|
||||||
|
className="text-xs px-3 py-1.5 rounded bg-cyan-600 text-white hover:bg-cyan-500 disabled:opacity-40">
|
||||||
|
{saving ? 'Saving…' : 'Save preset'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{presets.length === 0 && <p className="text-sm text-gray-500">No presets yet.</p>}
|
||||||
|
{presets.map(p => (
|
||||||
|
<div key={p.id} className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex items-start justify-between gap-4">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-sm text-white font-medium">{p.name}</div>
|
||||||
|
{p.description && <div className="text-xs text-gray-500">{p.description}</div>}
|
||||||
|
<div className="text-xs text-gray-400 mt-1 font-mono break-words">{Object.keys(p.modules).join(', ') || '(nothing)'}</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3 shrink-0">
|
||||||
|
<button onClick={() => setEditing({ ...p })} className="text-xs text-cyan-400 hover:text-cyan-300">Edit</button>
|
||||||
|
<button onClick={() => remove(p)} className="text-xs text-red-400 hover:text-red-300">Delete</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import client from '../api/client'
|
import client from '../api/client'
|
||||||
|
|
||||||
@@ -9,7 +9,10 @@ export default function RegisterSitePage() {
|
|||||||
owner_name: '',
|
owner_name: '',
|
||||||
contact_email: '',
|
contact_email: '',
|
||||||
license_expires_at: '',
|
license_expires_at: '',
|
||||||
|
preset: 'Everything (v1 sites)',
|
||||||
})
|
})
|
||||||
|
const [presets, setPresets] = useState([])
|
||||||
|
useEffect(() => { client.get('/api/presets/').then(r => setPresets(r.data)).catch(() => {}) }, [])
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [created, setCreated] = useState(null) // { site_id, secret_key, name }
|
const [created, setCreated] = useState(null) // { site_id, secret_key, name }
|
||||||
@@ -30,6 +33,7 @@ export default function RegisterSitePage() {
|
|||||||
owner_name: form.owner_name.trim(),
|
owner_name: form.owner_name.trim(),
|
||||||
contact_email: form.contact_email.trim(),
|
contact_email: form.contact_email.trim(),
|
||||||
license_expires_at: new Date(form.license_expires_at).toISOString(),
|
license_expires_at: new Date(form.license_expires_at).toISOString(),
|
||||||
|
preset: form.preset || null, // fills the site's licensed modules; editable afterwards
|
||||||
})
|
})
|
||||||
setCreated(data)
|
setCreated(data)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -179,6 +183,18 @@ export default function RegisterSitePage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wider">Licensed modules (preset)</label>
|
||||||
|
<select
|
||||||
|
value={form.preset}
|
||||||
|
onChange={e => update('preset', e.target.value)}
|
||||||
|
className="w-full bg-gray-800 border border-gray-600 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-1 focus:ring-cyan-500"
|
||||||
|
>
|
||||||
|
{presets.map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
|
||||||
|
<option value="">None (free tier until modules are set)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<p className="text-red-400 text-sm bg-red-900/20 border border-red-800/50 rounded-lg px-3 py-2">{error}</p>
|
<p className="text-red-400 text-sm bg-red-900/20 border border-red-800/50 rounded-lg px-3 py-2">{error}</p>
|
||||||
)}
|
)}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user