Compare commits

...
2 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 2541a5782e fix(menu-app): show a product once in search when it's listed in several categories
Platform v2 step 1.13 (D-23): the site's menu snapshot can list the same product under several categories. Search flattened all categories, so such a product appeared twice (and with a duplicate React key). Category sections still show it in each category; cart lookups already used the first match. npm run build passes.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:27:47 +02:00
31 changed files with 1312 additions and 62 deletions
+6
View File
@@ -0,0 +1,6 @@
# Never bake local data, secrets or tests into the image
*.db
*.db-*
.env
__pycache__/
tests/
+8
View File
@@ -0,0 +1,8 @@
# Alembic CLI config for cloud_backend (APPS_PLATFORM D-22). The app calls schema.py itself.
# cd cloud_backend
# alembic revision --autogenerate --rev-id 0003_short_name -m "what changed" # then REVIEW it
# alembic upgrade head
# Production cutover (once): alembic stamp 0001_cloud_baseline && alembic upgrade head
[alembic]
script_location = migrations
file_template = %%(rev)s
+8 -38
View File
@@ -1,3 +1,4 @@
"""Cloud backend entry point. Schema: Alembic only (schema.py, APPS_PLATFORM D-22)."""
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
@@ -5,17 +6,11 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from config import settings
from database import engine, Base
from database import engine
from auth_utils import hash_password
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.all # noqa: F401 every model (Alembic + routers)
from routers import auth, sites, heartbeat
from routers import auth, sites, heartbeat, presets
from routers import menu as menu_router
from routers import orders as orders_router
from routers import manager_auth as manager_auth_router
@@ -36,37 +31,11 @@ def _seed_default_admin():
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",
# QR menu branding/config
"ALTER TABLE sites ADD COLUMN menu_mode VARCHAR NOT NULL DEFAULT 'order'",
"ALTER TABLE sites ADD COLUMN menu_tagline_en VARCHAR",
"ALTER TABLE sites ADD COLUMN menu_tagline_gr VARCHAR",
"ALTER TABLE sites ADD COLUMN menu_hours_en VARCHAR", # superseded by menu_hours, kept for history
"ALTER TABLE sites ADD COLUMN menu_hours_gr VARCHAR", # superseded by menu_hours, kept for history
"ALTER TABLE sites ADD COLUMN menu_header_image_url VARCHAR",
"ALTER TABLE sites ADD COLUMN menu_display_name VARCHAR",
"ALTER TABLE sites ADD COLUMN menu_blurb_en VARCHAR",
"ALTER TABLE sites ADD COLUMN menu_blurb_gr VARCHAR",
"ALTER TABLE sites ADD COLUMN menu_hours VARCHAR",
]
for sql in migrations:
try:
with engine.connect() as conn:
conn.execute(text(sql))
conn.commit()
except Exception:
pass
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(bind=engine)
_run_migrations()
# Schema = Alembic revisions only (schema.py, D-22). Refuses an unstamped v1 database.
from schema import upgrade_to_head
upgrade_to_head()
_seed_default_admin()
yield
@@ -83,6 +52,7 @@ app.add_middleware(
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(sites.router, prefix="/api/sites", tags=["sites"])
app.include_router(heartbeat.router, prefix="/api/heartbeat", tags=["heartbeat"])
app.include_router(presets.router, prefix="/api/presets", tags=["presets"])
app.include_router(menu_router.router, prefix="/api/menu", tags=["menu"])
app.include_router(orders_router.router, prefix="/api/orders", tags=["orders"])
app.include_router(manager_auth_router.router, prefix="/api/manager", tags=["manager"])
+42
View File
@@ -0,0 +1,42 @@
"""Alembic environment for cloud_backend (APPS_PLATFORM D-22).
Agent notes: target metadata = models/all.py; render_as_batch for SQLite; a caller may
pass a connection in config.attributes["connection"] (schema.py, tests); otherwise
config.settings.DATABASE_URL is used.
"""
import sys
from pathlib import Path
from alembic import context
from sqlalchemy import create_engine
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from database import Base # noqa: E402
import models.all # noqa: E402,F401
target_metadata = Base.metadata
def _run(connection):
context.configure(connection=connection, target_metadata=target_metadata,
render_as_batch=True, compare_type=True)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connection = context.config.attributes.get("connection")
if connection is not None:
_run(connection)
return
from config import settings
engine = create_engine(settings.DATABASE_URL)
with engine.connect() as conn:
_run(conn)
engine.dispose()
if context.is_offline_mode():
raise SystemExit("Offline (--sql) mode is not supported.")
run_migrations_online()
+22
View File
@@ -0,0 +1,22 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
@@ -0,0 +1,191 @@
"""cloud v1 baseline: exactly the schema the v1 production cloud has (D-22)
Autogenerated from the models, then hand-edited so it equals what v1's create_all +
_run_migrations() produce: sites also has menu_hours_en / menu_hours_gr (v1 superseded
them by menu_hours but never dropped them; 0002 drops them).
The production DB is never upgraded THROUGH this revision: it is stamped to it at
cutover, so this file must describe production, not an ideal schema.
tests/test_schema.py compares it with a database built by v1's code.
Revision ID: 0001_cloud_baseline
Revises:
Create Date: 2026-11-12 19:18:38.281895
"""
from alembic import op
import sqlalchemy as sa
revision = '0001_cloud_baseline'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('admins',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(), nullable=False),
sa.Column('password_hash', sa.String(), nullable=False),
sa.Column('role', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('username')
)
with op.batch_alter_table('admins', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_admins_id'), ['id'], unique=False)
op.create_table('manager_accounts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(), nullable=False),
sa.Column('password_hash', sa.String(), nullable=False),
sa.Column('full_name', sa.String(), nullable=True),
sa.Column('is_active', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('manager_accounts', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_manager_accounts_email'), ['email'], unique=True)
batch_op.create_index(batch_op.f('ix_manager_accounts_id'), ['id'], unique=False)
op.create_table('sites',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('owner_name', sa.String(), nullable=False),
sa.Column('contact_email', sa.String(), nullable=False),
sa.Column('secret_key_hash', sa.String(), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_locked', sa.Boolean(), nullable=True),
sa.Column('lock_reason', sa.String(), nullable=True),
sa.Column('license_expires_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('last_seen_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('last_seen_ip', sa.String(), nullable=True),
sa.Column('last_seen_local_ip', sa.String(), nullable=True),
sa.Column('waiter_domain', sa.String(), nullable=True),
sa.Column('order_counter', sa.Integer(), nullable=False),
sa.Column('menu_mode', sa.String(), nullable=False),
sa.Column('menu_display_name', sa.String(), nullable=True),
sa.Column('menu_tagline_en', sa.String(), nullable=True),
sa.Column('menu_tagline_gr', sa.String(), nullable=True),
sa.Column('menu_blurb_en', sa.String(), nullable=True),
sa.Column('menu_blurb_gr', sa.String(), nullable=True),
sa.Column('menu_hours', sa.String(), nullable=True),
sa.Column('menu_hours_en', sa.String(), nullable=True),
sa.Column('menu_hours_gr', sa.String(), nullable=True),
sa.Column('menu_header_image_url', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('sites', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_sites_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_sites_site_id'), ['site_id'], unique=True)
op.create_table('manager_site_access',
sa.Column('manager_id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['manager_id'], ['manager_accounts.id'], ),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('manager_id', 'site_id')
)
op.create_table('menu_snapshots',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('snapshot_json', sa.Text(), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('menu_snapshots', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_menu_snapshots_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_menu_snapshots_site_id'), ['site_id'], unique=True)
op.create_table('online_orders',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('public_ref', sa.String(), nullable=False),
sa.Column('order_type', sa.String(), nullable=False),
sa.Column('customer_name', sa.String(), nullable=False),
sa.Column('customer_phone', sa.String(), nullable=True),
sa.Column('customer_address', sa.Text(), nullable=True),
sa.Column('customer_notes', sa.Text(), nullable=True),
sa.Column('items_json', sa.Text(), nullable=False),
sa.Column('subtotal', sa.Float(), nullable=False),
sa.Column('delivery_fee', sa.Float(), nullable=False),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('status', sa.String(), nullable=False),
sa.Column('rejection_reason', sa.String(), nullable=True),
sa.Column('synced_to_local', sa.Integer(), nullable=False),
sa.Column('local_order_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('public_ref')
)
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_online_orders_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_online_orders_site_id'), ['site_id'], unique=False)
batch_op.create_index(batch_op.f('ix_online_orders_status'), ['status'], unique=False)
op.create_table('product_images',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('product_id', sa.Integer(), nullable=False),
sa.Column('image_url', sa.String(), nullable=False),
sa.Column('image_hash', sa.String(), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('site_id', 'product_id', name='uq_product_images_site_product')
)
with op.batch_alter_table('product_images', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_product_images_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_product_images_site_id'), ['site_id'], unique=False)
op.create_table('stats_snapshots',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('snapshot_json', sa.Text(), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['site_id'], ['sites.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('site_id')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('stats_snapshots')
with op.batch_alter_table('product_images', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_product_images_site_id'))
batch_op.drop_index(batch_op.f('ix_product_images_id'))
op.drop_table('product_images')
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_online_orders_status'))
batch_op.drop_index(batch_op.f('ix_online_orders_site_id'))
batch_op.drop_index(batch_op.f('ix_online_orders_id'))
op.drop_table('online_orders')
with op.batch_alter_table('menu_snapshots', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_menu_snapshots_site_id'))
batch_op.drop_index(batch_op.f('ix_menu_snapshots_id'))
op.drop_table('menu_snapshots')
op.drop_table('manager_site_access')
with op.batch_alter_table('sites', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_sites_site_id'))
batch_op.drop_index(batch_op.f('ix_sites_id'))
op.drop_table('sites')
with op.batch_alter_table('manager_accounts', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_manager_accounts_id'))
batch_op.drop_index(batch_op.f('ix_manager_accounts_email'))
op.drop_table('manager_accounts')
with op.batch_alter_table('admins', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_admins_id'))
op.drop_table('admins')
# ### end Alembic commands ###
@@ -0,0 +1,70 @@
"""v2 licensing: site modules, catalogue, plan presets (D-3, D-20, D-21, §5.2)
Hand-edited:
- existing sites get V1_SITE_MODULES: every module a v1 site already had, with no
limits tighter than v1 (KDS screens unlimited). At cutover each site keeps doing what
it did; the owner can then change sites in the sysadmin panel. Frozen here on purpose.
- the same map is seeded as the preset "Everything (v1 sites)".
- menu_hours_en / menu_hours_gr (superseded in v1) are dropped.
Revision ID: 0002_v2_licensing
Revises: 0001_cloud_baseline
Create Date: 2026-11-12 19:19:08.073899
"""
import json
from alembic import op
import sqlalchemy as sa
V1_SITE_MODULES = {
"ordering": {}, "waiter_app": {}, "history": {}, "reports": {}, "pricing": {}, "tabs": {},
"crm": {}, "expenses": {}, "inventory": {}, "staff_planning": {}, "notes": {}, "chat": {},
"reservations": {}, "kds": {"limits": {"devices": None}}, "connect_menu": {},
"connect_orders": {}, "connect_remote": {}, "caller_id": {}, "fiscal": {},
}
revision = '0002_v2_licensing'
down_revision = '0001_cloud_baseline'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('plan_presets',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('modules', sa.JSON(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
with op.batch_alter_table('sites', schema=None) as batch_op:
batch_op.add_column(sa.Column('modules', sa.JSON(), nullable=False, server_default=sa.text("'{}'")))
batch_op.add_column(sa.Column('module_catalog', sa.JSON(), nullable=True))
batch_op.add_column(sa.Column('module_catalog_at', sa.DateTime(timezone=True), nullable=True))
batch_op.drop_column('menu_hours_en')
batch_op.drop_column('menu_hours_gr')
# ### end Alembic commands ###
conn = op.get_bind()
conn.execute(sa.text("update sites set modules = :m"), {"m": json.dumps(V1_SITE_MODULES)})
conn.execute(sa.text("insert into plan_presets (name, description, modules) values (:n, :d, :m)"),
{"n": "Everything (v1 sites)", "d": "Every module v1 sites had, no extra limits",
"m": json.dumps(V1_SITE_MODULES)})
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('sites', schema=None) as batch_op:
batch_op.add_column(sa.Column('menu_hours_gr', sa.VARCHAR(), nullable=True))
batch_op.add_column(sa.Column('menu_hours_en', sa.VARCHAR(), nullable=True))
batch_op.drop_column('module_catalog_at')
batch_op.drop_column('module_catalog')
batch_op.drop_column('modules')
op.drop_table('plan_presets')
# ### end Alembic commands ###
+9
View File
@@ -0,0 +1,9 @@
"""Every cloud model, for Alembic autogenerate and the drift guard. Add new model modules here."""
import models.admin # noqa: F401
import models.site # noqa: F401
import models.menu_snapshot # noqa: F401
import models.online_order # noqa: F401
import models.manager_account # noqa: F401
import models.stats_snapshot # noqa: F401
import models.product_image # noqa: F401
import models.plan_preset # noqa: F401
+20
View File
@@ -0,0 +1,20 @@
"""Plan presets (APPS_PLATFORM D-3, §5.2): named module maps the sysadmin applies to a site.
A preset only fills in a site's `modules` map; after applying, the site's map can be
edited freely. Plans are not a concept the sites know about.
"""
from sqlalchemy import JSON, Column, DateTime, Integer, String
from sqlalchemy.sql import func
from database import Base
class PlanPreset(Base):
__tablename__ = "plan_presets"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False, unique=True)
description = Column(String, nullable=True)
modules = Column(JSON, nullable=False, default=dict)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
+9 -1
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy import JSON, Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func
from database import Base
@@ -33,3 +33,11 @@ class Site(Base):
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)
+2
View File
@@ -0,0 +1,2 @@
-r requirements.txt
pytest==8.3.3
+1
View File
@@ -9,3 +9,4 @@ bcrypt==4.0.1
python-multipart==0.0.9
httpx==0.27.2
cryptography==46.0.4
alembic==1.14.0
+3 -5
View File
@@ -30,14 +30,12 @@ def heartbeat(
site.last_seen_ip = request.client.host if request.client else None
if 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()
licensed = site.is_active and (site.license_expires_at.replace(tzinfo=timezone.utc) > now)
return HeartbeatResponse(
licensed=licensed,
locked=site.is_locked,
lock_reason=site.lock_reason,
expires_at=site.license_expires_at,
latest_version=settings.LATEST_VERSION,
waiter_domain=site.waiter_domain,
site_numeric_id=site.id,
+56
View File
@@ -0,0 +1,56 @@
"""Plan presets CRUD (sysadmin): named module maps applied to sites (APPS_PLATFORM D-3, §5.2)."""
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from auth_utils import get_current_admin
from database import get_db
from models.plan_preset import PlanPreset
from routers.sites import _validate_modules
router = APIRouter()
class PresetIn(BaseModel):
name: str
description: str | None = None
modules: dict
def _out(p: PlanPreset) -> dict:
return {"id": p.id, "name": p.name, "description": p.description, "modules": p.modules or {}}
@router.get("/")
def list_presets(db: Session = Depends(get_db), _=Depends(get_current_admin)):
return [_out(p) for p in db.query(PlanPreset).order_by(PlanPreset.name).all()]
@router.post("/", status_code=status.HTTP_201_CREATED)
def create_preset(body: PresetIn, db: Session = Depends(get_db), _=Depends(get_current_admin)):
if db.query(PlanPreset).filter(PlanPreset.name == body.name).first():
raise HTTPException(status_code=409, detail="A preset with that name exists")
p = PlanPreset(name=body.name, description=body.description, modules=_validate_modules(body.modules))
db.add(p)
db.commit()
db.refresh(p)
return _out(p)
@router.put("/{preset_id}")
def update_preset(preset_id: int, body: PresetIn, db: Session = Depends(get_db), _=Depends(get_current_admin)):
p = db.get(PlanPreset, preset_id)
if not p:
raise HTTPException(status_code=404, detail="Preset not found")
p.name, p.description, p.modules = body.name, body.description, _validate_modules(body.modules)
db.commit()
db.refresh(p)
return _out(p)
@router.delete("/{preset_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_preset(preset_id: int, db: Session = Depends(get_db), _=Depends(get_current_admin)):
p = db.get(PlanPreset, preset_id)
if p:
db.delete(p)
db.commit()
+60 -1
View File
@@ -8,7 +8,7 @@ from sqlalchemy.orm import Session
from auth_utils import get_current_admin
from database import get_db
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()
_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")
@@ -16,6 +16,36 @@ _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])
def list_sites(db: Session = Depends(get_db), _=Depends(get_current_admin)):
return db.query(Site).all()
@@ -31,6 +61,7 @@ def create_site(body: SiteCreate, db: Session = Depends(get_db), _=Depends(get_c
contact_email=body.contact_email,
secret_key_hash=_pwd.hash(raw_key),
license_expires_at=body.license_expires_at,
modules=_preset_modules(db, body.preset),
)
db.add(site)
db.commit()
@@ -138,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")
db.delete(site)
db.commit()
# ── Licensed modules (APPS_PLATFORM D-3, §5.2) ─────────────────────────────────
@router.put("/{site_id}/modules", response_model=SiteOut)
def set_site_modules(site_id: str, body: SiteModulesUpdate, db: Session = Depends(get_db), _=Depends(get_current_admin)):
"""Replace the site's module map. The site gets it in its next heartbeat (signed token)."""
site = db.query(Site).filter(Site.site_id == site_id).first()
if not site:
raise HTTPException(status_code=404, detail="Site not found")
site.modules = _validate_modules(body.modules)
db.commit()
db.refresh(site)
return site
@router.post("/{site_id}/apply-preset/{preset_id}", response_model=SiteOut)
def apply_preset(site_id: str, preset_id: int, db: Session = Depends(get_db), _=Depends(get_current_admin)):
"""Copy a preset's module map into the site (then editable per site)."""
from models.plan_preset import PlanPreset
site = db.query(Site).filter(Site.site_id == site_id).first()
preset = db.get(PlanPreset, preset_id)
if not site or not preset:
raise HTTPException(status_code=404, detail="Site or preset not found")
site.modules = dict(preset.modules or {})
db.commit()
db.refresh(site)
return site
+53
View File
@@ -0,0 +1,53 @@
"""The one way the cloud schema is created and upgraded: Alembic (APPS_PLATFORM D-22).
v1 used create_all + an ALTER list in main.py (_run_migrations); both are gone on
platform-v2. The production database predates Alembic: at cutover it is STAMPED to
0001_cloud_baseline (the exact v1 schema) and then upgraded (DEPLOYMENT_GUIDE.md,
"Platform v2 cutover"). Until it is stamped, startup refuses it, so the v2 cloud can
never half-migrate production by accident.
"""
from __future__ import annotations
import logging
from pathlib import Path
from alembic import command
from alembic.config import Config
from sqlalchemy import inspect
logger = logging.getLogger("cloud.schema")
MIGRATIONS_DIR = Path(__file__).resolve().parent / "migrations"
BASELINE = "0001_cloud_baseline"
class UnstampedDatabaseError(RuntimeError):
pass
def alembic_config(connection=None) -> Config:
cfg = Config()
cfg.set_main_option("script_location", str(MIGRATIONS_DIR))
cfg.set_main_option("file_template", "%%(rev)s")
if connection is not None:
cfg.attributes["connection"] = connection
return cfg
def upgrade_to_head(engine=None) -> None:
if engine is None:
from database import engine as app_engine
engine = app_engine
with engine.begin() as conn:
tables = set(inspect(conn).get_table_names())
if tables and "alembic_version" not in tables:
raise UnstampedDatabaseError(
"This cloud database predates Alembic (v1). Back it up, then run "
f"`alembic stamp {BASELINE}` once (DEPLOYMENT_GUIDE.md, Platform v2 cutover).")
command.upgrade(alembic_config(conn), "head")
logger.info("schema upgraded to head")
def stamp_baseline(engine) -> None:
"""Cutover helper: mark a v1 production DB as being at the baseline revision."""
with engine.begin() as conn:
command.stamp(alembic_config(conn), BASELINE)
+17 -9
View File
@@ -7,6 +7,12 @@ class SiteCreate(BaseModel):
owner_name: str
contact_email: str
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):
@@ -35,6 +41,9 @@ class SiteOut(BaseModel):
lock_reason: str | None
license_expires_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_ip: str | None
last_seen_local_ip: str | None
@@ -60,18 +69,17 @@ class LockRequest(BaseModel):
class HeartbeatRequest(BaseModel):
version: str = "1.0.0"
uptime_seconds: int = 0
"""C-1 v2 (docs/reference/cloud-contract.md)."""
version: str
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):
licensed: bool
locked: bool
lock_reason: str | None
expires_at: datetime
# Signed v2 license the site stores and enforces offline (services/license_token.py).
# Everything about licensing is inside it; there are no unsigned license fields.
license_token: str | None
latest_version: str | None = None
waiter_domain: str | None = None
site_numeric_id: int | None = None # cloud DB pk — needed by Connect sync loops
# Signed license the site stores and enforces offline (services/license_token.py)
license_token: str | None = None
site_numeric_id: int # cloud DB pk — needed by the Connect workers
+22 -2
View File
@@ -7,7 +7,11 @@ 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: { v: 1, site_id, active, locked, lock_reason, expires_at, issued_at }
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,
@@ -46,18 +50,34 @@ 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": 1,
"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()))}"
+43
View File
@@ -0,0 +1,43 @@
"""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']}"}
+118
View File
@@ -0,0 +1,118 @@
-- The v1 production cloud schema (create_all + _run_migrations on main, 2026-11-12).
-- Frozen fixture for tests/test_schema.py: the v2 baseline must equal it, and a DB
-- in this shape must stamp + upgrade cleanly (APPS_PLATFORM D-22). Never edit.
CREATE TABLE admins (
id INTEGER NOT NULL,
username VARCHAR NOT NULL,
password_hash VARCHAR NOT NULL,
role VARCHAR,
PRIMARY KEY (id),
UNIQUE (username)
);
CREATE TABLE manager_accounts (
id INTEGER NOT NULL,
email VARCHAR NOT NULL,
password_hash VARCHAR NOT NULL,
full_name VARCHAR,
is_active INTEGER NOT NULL,
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id)
);
CREATE TABLE manager_site_access (
manager_id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
PRIMARY KEY (manager_id, site_id),
FOREIGN KEY(manager_id) REFERENCES manager_accounts (id),
FOREIGN KEY(site_id) REFERENCES sites (id)
);
CREATE TABLE menu_snapshots (
id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
snapshot_json TEXT NOT NULL,
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id),
FOREIGN KEY(site_id) REFERENCES sites (id)
);
CREATE TABLE online_orders (
id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
public_ref VARCHAR NOT NULL,
order_type VARCHAR NOT NULL,
customer_name VARCHAR NOT NULL,
customer_phone VARCHAR,
customer_address TEXT,
customer_notes TEXT,
items_json TEXT NOT NULL,
subtotal FLOAT NOT NULL,
delivery_fee FLOAT NOT NULL,
total FLOAT NOT NULL,
status VARCHAR NOT NULL,
rejection_reason VARCHAR,
synced_to_local INTEGER NOT NULL,
local_order_id INTEGER,
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id),
FOREIGN KEY(site_id) REFERENCES sites (id),
UNIQUE (public_ref)
);
CREATE TABLE product_images (
id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
image_url VARCHAR NOT NULL,
image_hash VARCHAR NOT NULL,
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id),
CONSTRAINT uq_product_images_site_product UNIQUE (site_id, product_id),
FOREIGN KEY(site_id) REFERENCES sites (id)
);
CREATE TABLE sites (
id INTEGER NOT NULL,
site_id VARCHAR NOT NULL,
name VARCHAR NOT NULL,
owner_name VARCHAR NOT NULL,
contact_email VARCHAR NOT NULL,
secret_key_hash VARCHAR NOT NULL,
is_active BOOLEAN,
is_locked BOOLEAN,
lock_reason VARCHAR,
license_expires_at DATETIME NOT NULL,
created_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
last_seen_at DATETIME,
last_seen_ip VARCHAR,
last_seen_local_ip VARCHAR,
waiter_domain VARCHAR,
order_counter INTEGER NOT NULL,
menu_mode VARCHAR NOT NULL,
menu_display_name VARCHAR,
menu_tagline_en VARCHAR,
menu_tagline_gr VARCHAR,
menu_blurb_en VARCHAR,
menu_blurb_gr VARCHAR,
menu_hours VARCHAR,
menu_header_image_url VARCHAR, menu_hours_en VARCHAR, menu_hours_gr VARCHAR,
PRIMARY KEY (id)
);
CREATE TABLE stats_snapshots (
id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
snapshot_json TEXT NOT NULL,
updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP),
PRIMARY KEY (id),
UNIQUE (site_id),
FOREIGN KEY(site_id) REFERENCES sites (id)
);
CREATE INDEX ix_admins_id ON admins (id);
CREATE UNIQUE INDEX ix_manager_accounts_email ON manager_accounts (email);
CREATE INDEX ix_manager_accounts_id ON manager_accounts (id);
CREATE INDEX ix_menu_snapshots_id ON menu_snapshots (id);
CREATE UNIQUE INDEX ix_menu_snapshots_site_id ON menu_snapshots (site_id);
CREATE INDEX ix_online_orders_id ON online_orders (id);
CREATE INDEX ix_online_orders_site_id ON online_orders (site_id);
CREATE INDEX ix_online_orders_status ON online_orders (status);
CREATE INDEX ix_product_images_id ON product_images (id);
CREATE INDEX ix_product_images_site_id ON product_images (site_id);
CREATE INDEX ix_sites_id ON sites (id);
CREATE UNIQUE INDEX ix_sites_site_id ON sites (site_id);
+101
View File
@@ -0,0 +1,101 @@
"""License token v2, site modules, presets, heartbeat catalogue (plan step 1.7, D-3, D-20, D-21)."""
import base64
import json
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from conftest import TEST_PUB
def _decode(token):
body, sig = token.split(".")
pad = lambda s: s + "=" * (-len(s) % 4) # noqa: E731
Ed25519PublicKey.from_public_bytes(base64.b64decode(TEST_PUB)).verify(
base64.urlsafe_b64decode(pad(sig)), body.encode()) # raises if the signature is wrong
return json.loads(base64.urlsafe_b64decode(pad(body)))
def _new_site(client, admin_h, **extra):
r = client.post("/api/sites/", headers=admin_h, json={
"name": "Test", "owner_name": "O", "contact_email": "o@example.com",
"license_expires_at": "2027-06-01T00:00:00+00:00", **extra})
assert r.status_code == 201, r.text
return r.json()
def _heartbeat(client, site, catalog=()):
r = client.post("/api/heartbeat/", headers={"X-Site-ID": site["site_id"], "X-Site-Key": site["secret_key"]},
json={"version": "2.0.0", "local_ip": "192.168.1.10", "module_catalog": list(catalog)})
assert r.status_code == 200, r.text
return r.json()
def test_normalize_modules():
from services.license_token import normalize_modules
assert normalize_modules({"kds": {"limits": {"devices": "2"}, "junk": 1}, "tabs": None}) == \
{"kds": {"limits": {"devices": 2}}, "tabs": {}}
def test_new_site_gets_default_preset_and_v2_token(client, admin_h):
site = _new_site(client, admin_h)
assert "ordering" in site["modules"]
hb = _heartbeat(client, site)
assert set(hb) == {"license_token", "latest_version", "waiter_domain", "site_numeric_id"}
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
+91
View File
@@ -0,0 +1,91 @@
"""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 == []
@@ -484,7 +484,12 @@ function SearchOverlay({ open, onClose, categories, lang, t, onOpen, onAdd, cart
useEffect(() => { if (open && inputRef.current) inputRef.current.focus() }, [open])
useEffect(() => { if (!open) setQ('') }, [open])
const allProducts = useMemo(() => categories.flatMap(c => c.products), [categories])
// A product can be listed in several categories (platform v2, D-23): search shows it once,
// under the first category it appears in.
const allProducts = useMemo(() => {
const seen = new Set()
return categories.flatMap(c => c.products).filter(p => !seen.has(p.id) && seen.add(p.id))
}, [categories])
const results = useMemo(() => {
const term = q.trim().toLowerCase()
+7 -1
View File
@@ -34,6 +34,8 @@ TLS and domains are handled in front of these ports on the VPS (`xenia-api.bonam
## 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
@@ -42,7 +44,8 @@ Sites upgrade slowly, and some may be several versions behind. Every endpoint a
Any change to one of these endpoints updates the parent's `docs/reference/cloud-contract.md` (global Rule 6).
**CL-2. Schema changes go through `_run_migrations()`** in `cloud_backend/main.py`: additive `ALTER TABLE ... ADD COLUMN` only, and never drop columns. Superseded columns stay, with a comment (e.g. `menu_hours_en`).
**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.
@@ -56,6 +59,8 @@ If the cloud is down, restaurants must keep taking orders (global Rule 8). Don't
**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
@@ -64,6 +69,7 @@ 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/manager-app && npm run dev
+12 -3
View File
@@ -4,6 +4,7 @@ import LoginPage from './pages/LoginPage'
import SitesPage from './pages/SitesPage'
import SiteDetailPage from './pages/SiteDetailPage'
import RegisterSitePage from './pages/RegisterSitePage'
import PresetsPage from './pages/PresetsPage'
function Layout({ children }) {
const { logout } = useAuthStore()
@@ -32,11 +33,16 @@ function Layout({ children }) {
</button>
<div className="flex items-center gap-4">
<span 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'
<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 hover:text-gray-300'
}`}>
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
onClick={handleLogout}
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={
<RequireAuth><Layout><SiteDetailPage /></Layout></RequireAuth>
} />
<Route path="/presets" element={
<RequireAuth><Layout><PresetsPage /></Layout></RequireAuth>
} />
<Route path="*" element={<Navigate to="/sites" replace />} />
</Routes>
)
@@ -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>
)
}
+33
View File
@@ -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' }
+96
View File
@@ -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>
)
}
+17 -1
View File
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import client from '../api/client'
@@ -9,7 +9,10 @@ export default function RegisterSitePage() {
owner_name: '',
contact_email: '',
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 [error, setError] = useState('')
const [created, setCreated] = useState(null) // { site_id, secret_key, name }
@@ -30,6 +33,7 @@ export default function RegisterSitePage() {
owner_name: form.owner_name.trim(),
contact_email: form.contact_email.trim(),
license_expires_at: new Date(form.license_expires_at).toISOString(),
preset: form.preset || null, // fills the site's licensed modules; editable afterwards
})
setCreated(data)
} catch (err) {
@@ -179,6 +183,18 @@ export default function RegisterSitePage() {
/>
</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 && (
<p className="text-red-400 text-sm bg-red-900/20 border border-red-800/50 rounded-lg px-3 py-2">{error}</p>
)}
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from 'react'
import SiteModulesCard from '../components/SiteModulesCard'
import { useParams, useNavigate } from 'react-router-dom'
import toast from 'react-hot-toast'
import { QRCodeCanvas } from 'qrcode.react'
@@ -306,6 +307,9 @@ export default function SiteDetailPage() {
</div>
</div>
{/* Licensed modules (platform v2) */}
<SiteModulesCard site={site} onSaved={setSite} />
{/* Heartbeat */}
<div className="bg-gray-900 border border-gray-700 rounded-xl p-4 mb-4">
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">Heartbeat</h2>