feat(backend): license entitlements, enforced limits, free tier
Platform v2 step 1.4 (APPS_PLATFORM D-3..D-6, D-21, §5). - core/modules/entitlements.py: compute() turns the evaluated license into per-module grants: the v2 token's `modules` map (own `exp` with the 5-day grace, never cut mid-service) + the free tier; no/invalid token, expired after grace, inactive, locked or clock tampering -> free tier only; core always. limit(module, name) with token value -> manifest licensed_default -> free value; None = unlimited. LICENSE_MODE=off (dev/test only) = everything - module gating says why: module.not_licensed (402, the first unlicensed module in the dependency chain) before module.disabled (403) - services/license.py accepts only v2 tokens with a modules map; the v1 "legacy unsigned 72h" path is gone - apply_license() always installs entitlements (startup before workers, every heartbeat, workday close); workers follow license changes - the global license middleware is deleted (no more whole-API 402/423); license_state moved to services/license_state.py - history_days enforced in every report/history endpoint: lower date bounds clamped (also when no "from" is given), and business days older than the limit refused by id (license.history_limited); data is never deleted - bootstrap/modules API show license mode, entitlement source and limit values - LICENSE_MODE=off in docker-compose.dev.yml and the e2e launchers; sites default to enforced - tests: entitlement rules, limits, the three done-when checks, signed-token apply_license path; license tests moved to v2 tokens Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,8 @@ services:
|
|||||||
backend:
|
backend:
|
||||||
build: ./local_backend
|
build: ./local_backend
|
||||||
image: ${REGISTRY}/pos-backend:${VERSION:-latest}
|
image: ${REGISTRY}/pos-backend:${VERSION:-latest}
|
||||||
|
environment:
|
||||||
|
- LICENSE_MODE=off # dev machine: every module, no limits (never on a site)
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ services:
|
|||||||
- SITE_ID=${SITE_ID}
|
- SITE_ID=${SITE_ID}
|
||||||
- SITE_KEY=${SITE_KEY}
|
- SITE_KEY=${SITE_KEY}
|
||||||
- CLOUD_URL=${CLOUD_URL}
|
- CLOUD_URL=${CLOUD_URL}
|
||||||
|
- LICENSE_MODE=${LICENSE_MODE:-enforced} # 'off' only for dev/test stacks (all modules, no limits)
|
||||||
- SECRET_KEY=${SECRET_KEY}
|
- SECRET_KEY=${SECRET_KEY}
|
||||||
- LICENSE_GRACE_HOURS=${LICENSE_GRACE_HOURS:-24}
|
- LICENSE_GRACE_HOURS=${LICENSE_GRACE_HOURS:-24}
|
||||||
- DATABASE_URL=sqlite:////app/data/pos.db
|
- DATABASE_URL=sqlite:////app/data/pos.db
|
||||||
|
|||||||
@@ -21,6 +21,10 @@ class Settings(BaseSettings):
|
|||||||
DATABASE_URL: str = f"sqlite:///{_DB_DEFAULT.as_posix()}"
|
DATABASE_URL: str = f"sqlite:///{_DB_DEFAULT.as_posix()}"
|
||||||
VERSION: str = "0.3.1"
|
VERSION: str = "0.3.1"
|
||||||
CONNECT_SYNC_INTERVAL_SECONDS: int = 30 # how often to poll for pending online orders
|
CONNECT_SYNC_INTERVAL_SECONDS: int = 30 # how often to poll for pending online orders
|
||||||
|
# Licensing (APPS_PLATFORM D-3..D-6). "enforced": modules come from the signed v2
|
||||||
|
# token, or the free tier without one. "off": every module, no limits; ONLY for dev
|
||||||
|
# machines and test suites (docker-compose.dev.yml, tests/e2e). Never on a site.
|
||||||
|
LICENSE_MODE: str = "enforced"
|
||||||
|
|
||||||
# Break-glass master account — lives only in env vars, never in the DB
|
# Break-glass master account — lives only in env vars, never in the DB
|
||||||
MASTER_USERNAME: str = ""
|
MASTER_USERNAME: str = ""
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
|
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
|
||||||
"license.limit_reached": (402, "License limit reached for {limit} ({max})."),
|
"license.limit_reached": (402, "License limit reached for {limit} ({max})."),
|
||||||
"license.expired": (402, "The license has expired."),
|
"license.expired": (402, "The license has expired."),
|
||||||
|
"license.history_limited": (402, "This license shows only the last {days} days of history ({module})."),
|
||||||
# identity
|
# identity
|
||||||
"auth.invalid_credentials": (401, "Wrong username or password."),
|
"auth.invalid_credentials": (401, "Wrong username or password."),
|
||||||
"auth.session_ended": (401, "Your session has ended. Please log in again."),
|
"auth.session_ended": (401, "Your session has ended. Please log in again."),
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ Agent notes:
|
|||||||
adds per-user grants; superadmin gets every key (D-7).
|
adds per-user grants; superadmin gets every key (D-7).
|
||||||
- Access: PUT uses require_settings_manager until step 1.5 switches it to
|
- Access: PUT uses require_settings_manager until step 1.5 switches it to
|
||||||
require("core.modules.manage").
|
require("core.modules.manage").
|
||||||
- `entitled` is True for every module until step 1.4.
|
- `entitled`/`entitlement`/limit `value` come from core/modules/entitlements.py (step 1.4).
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ from pydantic import BaseModel
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from core import i18n, timeutil
|
from core import i18n, timeutil
|
||||||
from core.modules import state
|
from core.modules import entitlements, state
|
||||||
from core.modules.registry import all_permissions, registry
|
from core.modules.registry import all_permissions, registry
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from routers.deps import get_current_user, require_settings_manager
|
from routers.deps import get_current_user, require_settings_manager
|
||||||
@@ -48,16 +48,21 @@ def _setting(db: Session, key: str, default: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def _module_out(m, enabled: dict, effective: frozenset) -> dict:
|
def _module_out(m, enabled: dict, effective: frozenset) -> dict:
|
||||||
|
ent = entitlements.current()
|
||||||
|
grant = ent.grants.get(m.key)
|
||||||
return {
|
return {
|
||||||
"key": m.key, "kind": m.kind, "name": m.name, "description": m.description,
|
"key": m.key, "kind": m.kind, "name": m.name, "description": m.description,
|
||||||
"depends": list(m.depends),
|
"depends": list(m.depends),
|
||||||
"entitled": True,
|
"entitled": grant is not None,
|
||||||
|
"entitlement": ({"source": grant.source, "exp": grant.exp, "exp_deferred": grant.exp_deferred}
|
||||||
|
if grant else None),
|
||||||
"enabled": enabled.get(m.key, True),
|
"enabled": enabled.get(m.key, True),
|
||||||
"effective": m.key in effective,
|
"effective": m.key in effective,
|
||||||
"can_disable": m.can_disable,
|
"can_disable": m.can_disable,
|
||||||
"permissions": [{"key": p.key, "description": p.description, "roles": list(p.roles)} for p in m.permissions],
|
"permissions": [{"key": p.key, "description": p.description, "roles": list(p.roles)} for p in m.permissions],
|
||||||
"limits": [{"key": lim.key, "description": lim.description, "free": lim.free,
|
"limits": [{"key": lim.key, "description": lim.description, "free": lim.free,
|
||||||
"licensed_default": lim.licensed_default} for lim in m.limits],
|
"licensed_default": lim.licensed_default,
|
||||||
|
"value": ent.limit(m.key, lim.key)} for lim in m.limits],
|
||||||
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
|
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
|
||||||
for sd in m.settings],
|
for sd in m.settings],
|
||||||
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope)}
|
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope)}
|
||||||
@@ -87,6 +92,7 @@ def bootstrap(
|
|||||||
"business_day_rollover_hour": timeutil.rollover_hour(),
|
"business_day_rollover_hour": timeutil.rollover_hour(),
|
||||||
},
|
},
|
||||||
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
|
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
|
||||||
|
"license": {"mode": entitlements.current().mode, "reason": entitlements.current().reason},
|
||||||
"languages": list(i18n.SUPPORTED_LANGUAGES),
|
"languages": list(i18n.SUPPORTED_LANGUAGES),
|
||||||
"user": None,
|
"user": None,
|
||||||
"language": i18n.venue_language(),
|
"language": i18n.venue_language(),
|
||||||
|
|||||||
@@ -0,0 +1,178 @@
|
|||||||
|
"""Which modules this site may use, and with which limits (APPS_PLATFORM D-3..D-6, §5.1).
|
||||||
|
|
||||||
|
effective = (entitled ∪ free tier) ∩ enabled (state.py adds "enabled" and deps)
|
||||||
|
|
||||||
|
Sources, decided by compute():
|
||||||
|
- LICENSE_MODE=off (config; dev and test machines only): every module, no limits.
|
||||||
|
- a valid v2 token and the global license says "licensed" (services/license.py::evaluate,
|
||||||
|
which already defers expiry/lock to the end of an open workday): the token's
|
||||||
|
`modules` map. A module with its own `exp` gets the same 5-day grace and is never
|
||||||
|
cut off while a workday is open. Plus the free tier for modules the token lacks.
|
||||||
|
- anything else (no token, bad token, expired after grace, inactive, locked, clock
|
||||||
|
tampering): the free tier only (core/modules/free_tier.py).
|
||||||
|
Core modules are always entitled.
|
||||||
|
|
||||||
|
Limits (D-6): limit(module, name) -> int | None (None = unlimited).
|
||||||
|
module from the token: token's limits[name], else the manifest's licensed_default
|
||||||
|
module only from the free tier: FREE_TIER[module]["limits"][name], else Limit.free
|
||||||
|
Limits restrict what is shown or used, never what is stored.
|
||||||
|
|
||||||
|
The current result is held in memory (set by cloud_sync.apply_license at startup, after
|
||||||
|
every heartbeat and at workday close). Tests call set_current(compute(...)) or set_dev().
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from core.modules.free_tier import FREE_TIER
|
||||||
|
from core.timeutil import utcnow
|
||||||
|
from core.modules.registry import registry
|
||||||
|
|
||||||
|
logger = logging.getLogger("xenia.license")
|
||||||
|
|
||||||
|
MODULE_EXPIRY_GRACE = timedelta(days=5) # same as services/license.py EXPIRY_GRACE
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Grant:
|
||||||
|
source: str # "license" | "free" | "dev" | "core"
|
||||||
|
limits: dict = field(default_factory=dict)
|
||||||
|
exp: str | None = None
|
||||||
|
exp_deferred: bool = False # past exp + grace, kept until the open workday closes
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Entitlements:
|
||||||
|
mode: str # "dev" | "licensed" | "free"
|
||||||
|
grants: dict # {module key: Grant}
|
||||||
|
reason: str | None = None # why "free": unverified | expired | inactive | locked | clock
|
||||||
|
|
||||||
|
def entitled(self, key: str) -> bool:
|
||||||
|
return key in self.grants
|
||||||
|
|
||||||
|
def limit(self, module: str, name: str) -> int | None:
|
||||||
|
g = self.grants.get(module)
|
||||||
|
m = registry().get(module)
|
||||||
|
decl = next((lim for lim in m.limits if lim.key == name), None) if m else None
|
||||||
|
if g is None:
|
||||||
|
return 0
|
||||||
|
if g.source == "dev":
|
||||||
|
return None
|
||||||
|
if name in g.limits:
|
||||||
|
return g.limits[name]
|
||||||
|
if decl is None:
|
||||||
|
return None
|
||||||
|
return decl.free if g.source == "free" else decl.licensed_default
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(dt):
|
||||||
|
from services.license import parse_dt
|
||||||
|
return parse_dt(dt)
|
||||||
|
|
||||||
|
|
||||||
|
def compute(payload: dict | None, licensed: bool, locked: bool, now: datetime, workday_open: bool,
|
||||||
|
problem: str | None = None) -> Entitlements:
|
||||||
|
reg = registry()
|
||||||
|
grants: dict[str, Grant] = {k: Grant("core") for k, m in reg.items() if m.kind == "core"}
|
||||||
|
|
||||||
|
def add_free():
|
||||||
|
for k, spec in FREE_TIER.items():
|
||||||
|
if k in reg and k not in grants:
|
||||||
|
grants[k] = Grant("free", dict(spec.get("limits", {})))
|
||||||
|
|
||||||
|
if payload is None or not licensed or locked:
|
||||||
|
add_free()
|
||||||
|
reason = "locked" if locked else (problem or ("unverified" if payload is None else "expired"))
|
||||||
|
return Entitlements("free", grants, reason)
|
||||||
|
|
||||||
|
for k, spec in (payload.get("modules") or {}).items():
|
||||||
|
if k not in reg:
|
||||||
|
logger.info("license.unknown_module key=%s (newer cloud catalogue?)", k)
|
||||||
|
continue
|
||||||
|
spec = spec or {}
|
||||||
|
exp = _parse(spec.get("exp"))
|
||||||
|
deferred = False
|
||||||
|
if exp is not None and now > exp + MODULE_EXPIRY_GRACE:
|
||||||
|
if not workday_open:
|
||||||
|
continue # this module's own license ran out
|
||||||
|
deferred = True # never cut off mid-service
|
||||||
|
if reg[k].kind == "core":
|
||||||
|
grants[k] = Grant("core", dict(spec.get("limits") or {}))
|
||||||
|
continue
|
||||||
|
grants[k] = Grant("license", dict(spec.get("limits") or {}),
|
||||||
|
exp.isoformat() if exp else None, deferred)
|
||||||
|
add_free()
|
||||||
|
return Entitlements("licensed", grants)
|
||||||
|
|
||||||
|
|
||||||
|
def dev() -> Entitlements:
|
||||||
|
return Entitlements("dev", {k: Grant("dev") for k in registry()})
|
||||||
|
|
||||||
|
|
||||||
|
# ── current state ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
_lock = threading.Lock()
|
||||||
|
_current: Entitlements | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def current() -> Entitlements:
|
||||||
|
with _lock:
|
||||||
|
cur = _current
|
||||||
|
if cur is None:
|
||||||
|
# Before the first apply_license(): dev mode if configured, else the free tier.
|
||||||
|
from config import settings
|
||||||
|
cur = dev() if settings.LICENSE_MODE == "off" else compute(None, False, False, utcnow(), False)
|
||||||
|
return cur
|
||||||
|
|
||||||
|
|
||||||
|
def set_current(ent: Entitlements, notify: bool = True) -> None:
|
||||||
|
"""Install a new result; modules and workers follow at once if anything changed.
|
||||||
|
notify=False is for tests that have no database to re-read."""
|
||||||
|
global _current
|
||||||
|
with _lock:
|
||||||
|
changed = _current is None or _current.grants != ent.grants
|
||||||
|
_current = ent
|
||||||
|
if changed and notify:
|
||||||
|
logger.info("license.entitlements mode=%s modules=%d reason=%s", ent.mode, len(ent.grants), ent.reason)
|
||||||
|
from core.modules import state
|
||||||
|
state.notify()
|
||||||
|
|
||||||
|
|
||||||
|
def set_dev() -> None:
|
||||||
|
set_current(dev())
|
||||||
|
|
||||||
|
|
||||||
|
def reset() -> None:
|
||||||
|
global _current
|
||||||
|
with _lock:
|
||||||
|
_current = None
|
||||||
|
|
||||||
|
|
||||||
|
def limit(module: str, name: str) -> int | None:
|
||||||
|
return current().limit(module, name)
|
||||||
|
|
||||||
|
|
||||||
|
def history_floor(module: str) -> datetime | None:
|
||||||
|
"""Earliest moment `module` may show, from its `history_days` limit (D-6). None = no limit."""
|
||||||
|
days = limit(module, "history_days")
|
||||||
|
if days is None:
|
||||||
|
return None
|
||||||
|
return utcnow() - timedelta(days=days)
|
||||||
|
|
||||||
|
|
||||||
|
def clamp_start(start: datetime | None, module: str) -> datetime | None:
|
||||||
|
"""A lower time bound moved forward to the module's history floor (D-6)."""
|
||||||
|
floor = history_floor(module)
|
||||||
|
if floor is None:
|
||||||
|
return start
|
||||||
|
return floor if start is None or start < floor else start
|
||||||
|
|
||||||
|
|
||||||
|
def history_since(value, module: str) -> datetime | None:
|
||||||
|
"""API "from" value -> UTC lower bound, never older than the module allows (D-6).
|
||||||
|
No value and no limit -> None (no bound)."""
|
||||||
|
from core.timeutil import parse_api_datetime
|
||||||
|
return clamp_start(parse_api_datetime(value) if value else None, module)
|
||||||
@@ -13,7 +13,8 @@ module_required(key) is the FastAPI dependency main.py adds to each non-core rou
|
|||||||
Agent notes:
|
Agent notes:
|
||||||
- Always change enablement through set_enabled(), never by writing SiteModule rows,
|
- Always change enablement through set_enabled(), never by writing SiteModule rows,
|
||||||
or the cache and the workers won't follow.
|
or the cache and the workers won't follow.
|
||||||
- Step 1.4 replaces `_entitled()` with the license evaluation (entitled ∪ free tier).
|
- Entitlement comes from core/modules/entitlements.py (license ∪ free tier, step 1.4).
|
||||||
|
A blocked request says why: module.not_licensed (402) before module.disabled (403).
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -73,7 +74,19 @@ def enabled_map(db: Session | None = None) -> dict[str, bool]:
|
|||||||
|
|
||||||
|
|
||||||
def _entitled(key: str) -> bool:
|
def _entitled(key: str) -> bool:
|
||||||
return True # >>> step 1.4: license entitlements ∪ free tier
|
from core.modules import entitlements
|
||||||
|
return entitlements.current().entitled(key)
|
||||||
|
|
||||||
|
|
||||||
|
def notify() -> None:
|
||||||
|
"""Tell listeners (the worker supervisor) the effective set may have changed,
|
||||||
|
e.g. after the license was re-evaluated."""
|
||||||
|
eff = effective_set()
|
||||||
|
for fn in list(_listeners):
|
||||||
|
try:
|
||||||
|
fn(eff)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("module listener failed")
|
||||||
|
|
||||||
|
|
||||||
def effective_set(db: Session | None = None) -> frozenset[str]:
|
def effective_set(db: Session | None = None) -> frozenset[str]:
|
||||||
@@ -122,6 +135,23 @@ def set_enabled(db: Session, key: str, enabled: bool, user_id: int | None = None
|
|||||||
return eff
|
return eff
|
||||||
|
|
||||||
|
|
||||||
|
def blocked_error(key: str, db: Session | None = None) -> XeniaError:
|
||||||
|
"""Why `key` isn't effective: not licensed (itself or a dependency) beats turned off."""
|
||||||
|
reg = registry()
|
||||||
|
seen, stack = set(), [key]
|
||||||
|
while stack:
|
||||||
|
k = stack.pop()
|
||||||
|
if k in seen:
|
||||||
|
continue
|
||||||
|
seen.add(k)
|
||||||
|
if not _entitled(k):
|
||||||
|
return XeniaError("module.not_licensed", module=k)
|
||||||
|
stack.extend(reg[k].depends)
|
||||||
|
enabled = enabled_map(db)
|
||||||
|
off = next((k for k in [key, *sorted(seen - {key})] if not enabled.get(k, True)), key)
|
||||||
|
return XeniaError("module.disabled", module=off)
|
||||||
|
|
||||||
|
|
||||||
def module_required(key: str):
|
def module_required(key: str):
|
||||||
"""FastAPI dependency: the endpoint answers `module.disabled` unless the module is effective."""
|
"""FastAPI dependency: the endpoint answers `module.disabled` unless the module is effective."""
|
||||||
if key not in registry():
|
if key not in registry():
|
||||||
@@ -129,7 +159,7 @@ def module_required(key: str):
|
|||||||
|
|
||||||
def _check(db: Session = Depends(get_db)) -> None:
|
def _check(db: Session = Depends(get_db)) -> None:
|
||||||
if not is_effective(key, db):
|
if not is_effective(key, db):
|
||||||
raise XeniaError("module.disabled", module=key)
|
raise blocked_error(key, db)
|
||||||
|
|
||||||
_check.__name__ = f"module_required_{key}"
|
_check.__name__ = f"module_required_{key}"
|
||||||
return _check
|
return _check
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ logger = logging.getLogger("xenia.main")
|
|||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from database import SessionLocal
|
from database import SessionLocal
|
||||||
from middleware.license_check import LicenseCheckMiddleware
|
|
||||||
from services.cloud_sync import start_cloud_sync
|
from services.cloud_sync import start_cloud_sync
|
||||||
|
|
||||||
# Every model must be registered before the routers import them (see models/all.py).
|
# Every model must be registered before the routers import them (see models/all.py).
|
||||||
@@ -68,6 +67,8 @@ async def lifespan(app: FastAPI):
|
|||||||
if pruned:
|
if pruned:
|
||||||
logger.info("ws_bus: pruned %d old sync_events", pruned)
|
logger.info("ws_bus: pruned %d old sync_events", pruned)
|
||||||
_init_chat()
|
_init_chat()
|
||||||
|
from services.cloud_sync import load_license_at_startup
|
||||||
|
load_license_at_startup() # entitlements from the stored token (or free tier / dev)
|
||||||
sync_task = await start_cloud_sync() # license heartbeat (core, always on)
|
sync_task = await start_cloud_sync() # license heartbeat (core, always on)
|
||||||
# Module workers (connect_* pushes/pulls...) run only while their module is effective
|
# Module workers (connect_* pushes/pulls...) run only while their module is effective
|
||||||
from core.modules import supervisor
|
from core.modules import supervisor
|
||||||
@@ -91,7 +92,7 @@ app.add_middleware(
|
|||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
)
|
)
|
||||||
app.add_middleware(LicenseCheckMiddleware)
|
# (v1's LicenseCheckMiddleware is gone: an unlicensed site gets the free tier, module by module, D-5.)
|
||||||
# Added last = outermost: the request id exists before any other middleware runs.
|
# Added last = outermost: the request id exists before any other middleware runs.
|
||||||
app.add_middleware(RequestContextMiddleware)
|
app.add_middleware(RequestContextMiddleware)
|
||||||
|
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
from fastapi import Request, Response
|
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
|
||||||
|
|
||||||
# Shared mutable state — updated by cloud_sync.py
|
|
||||||
# Fields:
|
|
||||||
# licensed bool — False only after 72h offline OR after expiry grace passes
|
|
||||||
# locked bool — True once lock_pending is enforced at workday close
|
|
||||||
# lock_pending bool — Cloud requested lock; waiting for workday to close
|
|
||||||
# expires_at str|None — ISO timestamp from cloud
|
|
||||||
# days_until_expiry int|None — negative when expired
|
|
||||||
# grace_expires_at str|None — ISO timestamp of expiry + 5 days
|
|
||||||
# last_sync str|None — ISO timestamp of last successful heartbeat
|
|
||||||
# sync_failed bool
|
|
||||||
# latest_version str|None
|
|
||||||
license_state: dict = {
|
|
||||||
"licensed": True,
|
|
||||||
"locked": False,
|
|
||||||
"lock_pending": False,
|
|
||||||
"expires_at": None,
|
|
||||||
"days_until_expiry": None,
|
|
||||||
"grace_expires_at": None,
|
|
||||||
"last_sync": None,
|
|
||||||
"sync_failed": False,
|
|
||||||
"latest_version": None,
|
|
||||||
}
|
|
||||||
|
|
||||||
# Paths that bypass all license checks (health probe, venue identity for pairing)
|
|
||||||
EXEMPT_PATHS = {"/api/system/health", "/api/system/identity"}
|
|
||||||
|
|
||||||
# Paths that are always allowed so the frontend can read license status
|
|
||||||
# and managers can still log in / close the workday when restricted
|
|
||||||
STATUS_ALLOWED_PATHS = {
|
|
||||||
"/api/system/status",
|
|
||||||
"/api/system/sync-license",
|
|
||||||
"/api/auth/login",
|
|
||||||
"/api/auth/me",
|
|
||||||
"/api/business-day/current",
|
|
||||||
"/api/business-day/close",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class LicenseCheckMiddleware(BaseHTTPMiddleware):
|
|
||||||
async def dispatch(self, request: Request, call_next):
|
|
||||||
path = request.url.path
|
|
||||||
|
|
||||||
if path in EXEMPT_PATHS or path in STATUS_ALLOWED_PATHS:
|
|
||||||
return await call_next(request)
|
|
||||||
|
|
||||||
# Hard block: licensed=False means either 72h offline grace expired
|
|
||||||
# OR expiry grace period (5 days) has passed. In both cases the
|
|
||||||
# business_day router already prevented opening a new workday, so
|
|
||||||
# existing operations can still complete — we only block new ones.
|
|
||||||
# The business_day /open endpoint has its own detailed error message.
|
|
||||||
if not license_state.get("licensed", True):
|
|
||||||
return Response(
|
|
||||||
content='{"detail":"license_expired","code":"LICENSE_EXPIRED"}',
|
|
||||||
status_code=402,
|
|
||||||
media_type="application/json",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Hard block: locked=True (lock_pending was enforced at workday close)
|
|
||||||
if license_state.get("locked"):
|
|
||||||
return Response(
|
|
||||||
content='{"detail":"system_locked","code":"SYSTEM_LOCKED"}',
|
|
||||||
status_code=423,
|
|
||||||
media_type="application/json",
|
|
||||||
)
|
|
||||||
|
|
||||||
return await call_next(request)
|
|
||||||
@@ -17,7 +17,7 @@ from models.printer import Printer
|
|||||||
from schemas.business_day import BusinessDayOut, OpenBusinessDayRequest, CloseBusinessDayRequest
|
from schemas.business_day import BusinessDayOut, OpenBusinessDayRequest, CloseBusinessDayRequest
|
||||||
from routers.deps import get_current_user, require_manager
|
from routers.deps import get_current_user, require_manager
|
||||||
from models.user import User
|
from models.user import User
|
||||||
from middleware.license_check import license_state
|
from services.license_state import license_state
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
|
from core.errors import XeniaError
|
||||||
|
from core.modules.entitlements import clamp_start, history_floor, history_since, limit
|
||||||
from core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow
|
from core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow
|
||||||
import csv
|
import csv
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Query, HTTPException, BackgroundTasks
|
from fastapi import APIRouter, Depends, Query, HTTPException, BackgroundTasks, Request
|
||||||
from fastapi.responses import StreamingResponse
|
from fastapi.responses import StreamingResponse
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
@@ -28,11 +30,36 @@ from services.printer_service import (
|
|||||||
print_prep_zone_summary,
|
print_prep_zone_summary,
|
||||||
)
|
)
|
||||||
|
|
||||||
router = APIRouter()
|
def _business_day_guard(module: str):
|
||||||
|
"""Router-level dependency (D-6): a business_day_id (query or JSON body) older than the
|
||||||
|
module's history_days is refused, so per-day views respect the limit too."""
|
||||||
|
async def guard(request: Request, db: Session = Depends(get_db)) -> None:
|
||||||
|
bid = request.query_params.get("business_day_id")
|
||||||
|
if bid is None and request.method in ("POST", "PUT", "PATCH"):
|
||||||
|
try:
|
||||||
|
body = await request.json()
|
||||||
|
bid = body.get("business_day_id") if isinstance(body, dict) else None
|
||||||
|
except Exception:
|
||||||
|
bid = None
|
||||||
|
if not bid:
|
||||||
|
return
|
||||||
|
floor = history_floor(module)
|
||||||
|
if floor is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
day = db.get(BusinessDay, int(bid))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return
|
||||||
|
if day is not None and (day.closed_at or day.opened_at) < floor:
|
||||||
|
raise XeniaError("license.history_limited", module=module, days=limit(module, "history_days"))
|
||||||
|
return guard
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter(dependencies=[Depends(_business_day_guard("reports"))])
|
||||||
# The free `history` module (APPS_PLATFORM §4.2, D-5): order history, business-day
|
# The free `history` module (APPS_PLATFORM §4.2, D-5): order history, business-day
|
||||||
# summaries and the filter lookups. Mounted under the same /api/reports prefix but
|
# summaries and the filter lookups. Mounted under the same /api/reports prefix but
|
||||||
# gated by `history`, so it still works on the free tier when `reports` isn't licensed.
|
# gated by `history`, so it still works on the free tier when `reports` isn't licensed.
|
||||||
history_router = APIRouter()
|
history_router = APIRouter(dependencies=[Depends(_business_day_guard("history"))])
|
||||||
|
|
||||||
|
|
||||||
def _item_val(item) -> float:
|
def _item_val(item) -> float:
|
||||||
@@ -57,11 +84,12 @@ def shift_summary(
|
|||||||
):
|
):
|
||||||
"""Payments collected per waiter — based on paid_by on order items."""
|
"""Payments collected per waiter — based on paid_by on order items."""
|
||||||
if from_dt and to_dt:
|
if from_dt and to_dt:
|
||||||
start = parse_api_datetime(from_dt)
|
start = history_since(from_dt, 'reports')
|
||||||
end = parse_api_datetime(to_dt)
|
end = parse_api_datetime(to_dt)
|
||||||
else:
|
else:
|
||||||
# A date means a business date (D-11): its rollover-to-rollover window in UTC
|
# A date means a business date (D-11): its rollover-to-rollover window in UTC
|
||||||
start, end = business_date_window(report_date or business_date_of())
|
start, end = business_date_window(report_date or business_date_of())
|
||||||
|
start = clamp_start(start, 'reports')
|
||||||
|
|
||||||
q = db.query(OrderItem).filter(
|
q = db.query(OrderItem).filter(
|
||||||
OrderItem.status == "paid",
|
OrderItem.status == "paid",
|
||||||
@@ -135,10 +163,11 @@ def shift_orders_summary(
|
|||||||
q = q.join(Order).filter(Order.business_day_id == business_day_id)
|
q = q.join(Order).filter(Order.business_day_id == business_day_id)
|
||||||
else:
|
else:
|
||||||
if from_dt and to_dt:
|
if from_dt and to_dt:
|
||||||
start = parse_api_datetime(from_dt)
|
start = history_since(from_dt, 'reports')
|
||||||
end = parse_api_datetime(to_dt)
|
end = parse_api_datetime(to_dt)
|
||||||
else:
|
else:
|
||||||
start, end = business_date_window(report_date or business_date_of())
|
start, end = business_date_window(report_date or business_date_of())
|
||||||
|
start = clamp_start(start, 'reports')
|
||||||
q = q.filter(OrderItem.added_at >= start, OrderItem.added_at < end)
|
q = q.filter(OrderItem.added_at >= start, OrderItem.added_at < end)
|
||||||
if waiter_id:
|
if waiter_id:
|
||||||
q = q.filter(OrderItem.added_by == waiter_id)
|
q = q.filter(OrderItem.added_by == waiter_id)
|
||||||
@@ -258,8 +287,9 @@ def order_history(
|
|||||||
if business_day_id:
|
if business_day_id:
|
||||||
q = q.filter(Order.business_day_id == business_day_id)
|
q = q.filter(Order.business_day_id == business_day_id)
|
||||||
elif from_date or to_date:
|
elif from_date or to_date:
|
||||||
if from_date:
|
_since = history_since(from_date, 'history')
|
||||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_date))
|
if _since:
|
||||||
|
q = q.filter(Order.opened_at >= _since)
|
||||||
if to_date:
|
if to_date:
|
||||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_date))
|
q = q.filter(Order.opened_at <= parse_api_datetime(to_date))
|
||||||
if waiter_id:
|
if waiter_id:
|
||||||
@@ -400,8 +430,9 @@ def printer_totals(
|
|||||||
):
|
):
|
||||||
"""Returns totals per printer based on print_log entries in the date range."""
|
"""Returns totals per printer based on print_log entries in the date range."""
|
||||||
q = db.query(PrintLog).filter(PrintLog.success == True)
|
q = db.query(PrintLog).filter(PrintLog.success == True)
|
||||||
if from_date:
|
_since = history_since(from_date, 'reports')
|
||||||
q = q.filter(PrintLog.printed_at >= parse_api_datetime(from_date))
|
if _since:
|
||||||
|
q = q.filter(PrintLog.printed_at >= _since)
|
||||||
if to_date:
|
if to_date:
|
||||||
q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_date))
|
q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_date))
|
||||||
logs = q.all()
|
logs = q.all()
|
||||||
@@ -568,7 +599,7 @@ def print_waiter(
|
|||||||
if not printer:
|
if not printer:
|
||||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||||
|
|
||||||
from_dt = parse_api_datetime(body.from_dt)
|
from_dt = history_since(body.from_dt, 'reports')
|
||||||
to_dt = parse_api_datetime(body.to_dt)
|
to_dt = parse_api_datetime(body.to_dt)
|
||||||
|
|
||||||
# Gather orders for this waiter in time range
|
# Gather orders for this waiter in time range
|
||||||
@@ -640,7 +671,7 @@ def print_printer_totals(
|
|||||||
if body.business_day_id:
|
if body.business_day_id:
|
||||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||||
elif body.from_dt and body.to_dt:
|
elif body.from_dt and body.to_dt:
|
||||||
from_dt = parse_api_datetime(body.from_dt)
|
from_dt = history_since(body.from_dt, 'reports')
|
||||||
to_dt = parse_api_datetime(body.to_dt)
|
to_dt = parse_api_datetime(body.to_dt)
|
||||||
q = q.filter(PrintLog.printed_at >= from_dt, PrintLog.printed_at <= to_dt)
|
q = q.filter(PrintLog.printed_at >= from_dt, PrintLog.printed_at <= to_dt)
|
||||||
return q
|
return q
|
||||||
@@ -651,7 +682,7 @@ def print_printer_totals(
|
|||||||
period_label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
period_label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
||||||
period_is_workday = True
|
period_is_workday = True
|
||||||
else:
|
else:
|
||||||
from_dt = parse_api_datetime(body.from_dt) if body.from_dt else None
|
from_dt = history_since(body.from_dt, 'reports') if body.from_dt else None
|
||||||
to_dt = parse_api_datetime(body.to_dt) if body.to_dt else None
|
to_dt = parse_api_datetime(body.to_dt) if body.to_dt else None
|
||||||
period_label = (
|
period_label = (
|
||||||
f"{venue_strftime(from_dt, '%d/%m/%Y')} - {venue_strftime(to_dt, '%d/%m/%Y')}"
|
f"{venue_strftime(from_dt, '%d/%m/%Y')} - {venue_strftime(to_dt, '%d/%m/%Y')}"
|
||||||
@@ -707,7 +738,7 @@ def _analytics_period(body: PrintAnalyticsBody, db) -> tuple[str, bool]:
|
|||||||
bd = db.query(BusinessDay).filter(BusinessDay.id == body.business_day_id).first()
|
bd = db.query(BusinessDay).filter(BusinessDay.id == body.business_day_id).first()
|
||||||
label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
||||||
return label, True
|
return label, True
|
||||||
from_dt = parse_api_datetime(body.from_dt) if body.from_dt else None
|
from_dt = history_since(body.from_dt, 'reports') if body.from_dt else None
|
||||||
to_dt = parse_api_datetime(body.to_dt) if body.to_dt else None
|
to_dt = parse_api_datetime(body.to_dt) if body.to_dt else None
|
||||||
label = (
|
label = (
|
||||||
f"{venue_strftime(from_dt, '%d/%m/%Y')} - {venue_strftime(to_dt, '%d/%m/%Y')}"
|
f"{venue_strftime(from_dt, '%d/%m/%Y')} - {venue_strftime(to_dt, '%d/%m/%Y')}"
|
||||||
@@ -737,7 +768,7 @@ def print_products(
|
|||||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||||
elif body.from_dt and body.to_dt:
|
elif body.from_dt and body.to_dt:
|
||||||
q = q.filter(
|
q = q.filter(
|
||||||
OrderItem.added_at >= parse_api_datetime(body.from_dt),
|
OrderItem.added_at >= history_since(body.from_dt, 'reports'),
|
||||||
OrderItem.added_at <= parse_api_datetime(body.to_dt),
|
OrderItem.added_at <= parse_api_datetime(body.to_dt),
|
||||||
)
|
)
|
||||||
items = q.all()
|
items = q.all()
|
||||||
@@ -797,7 +828,7 @@ def print_categories(
|
|||||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||||
elif body.from_dt and body.to_dt:
|
elif body.from_dt and body.to_dt:
|
||||||
q = q.filter(
|
q = q.filter(
|
||||||
OrderItem.added_at >= parse_api_datetime(body.from_dt),
|
OrderItem.added_at >= history_since(body.from_dt, 'reports'),
|
||||||
OrderItem.added_at <= parse_api_datetime(body.to_dt),
|
OrderItem.added_at <= parse_api_datetime(body.to_dt),
|
||||||
)
|
)
|
||||||
items = q.all()
|
items = q.all()
|
||||||
@@ -874,7 +905,7 @@ def print_tables(
|
|||||||
q = q.filter(Order.business_day_id == body.business_day_id)
|
q = q.filter(Order.business_day_id == body.business_day_id)
|
||||||
elif body.from_dt and body.to_dt:
|
elif body.from_dt and body.to_dt:
|
||||||
q = q.filter(
|
q = q.filter(
|
||||||
Order.opened_at >= parse_api_datetime(body.from_dt),
|
Order.opened_at >= history_since(body.from_dt, 'reports'),
|
||||||
Order.opened_at <= parse_api_datetime(body.to_dt),
|
Order.opened_at <= parse_api_datetime(body.to_dt),
|
||||||
)
|
)
|
||||||
orders = q.all()
|
orders = q.all()
|
||||||
@@ -935,8 +966,9 @@ def shifts_report(
|
|||||||
q = q.filter(WaiterShift.waiter_id == waiter_id)
|
q = q.filter(WaiterShift.waiter_id == waiter_id)
|
||||||
if business_day_id:
|
if business_day_id:
|
||||||
q = q.filter(WaiterShift.business_day_id == business_day_id)
|
q = q.filter(WaiterShift.business_day_id == business_day_id)
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'reports')
|
||||||
q = q.filter(WaiterShift.started_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(WaiterShift.started_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(WaiterShift.started_at <= parse_api_datetime(to_dt))
|
q = q.filter(WaiterShift.started_at <= parse_api_datetime(to_dt))
|
||||||
if active_only:
|
if active_only:
|
||||||
@@ -963,8 +995,9 @@ def product_performance(
|
|||||||
from models.waste import WasteLog
|
from models.waste import WasteLog
|
||||||
|
|
||||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'reports')
|
||||||
q = q.filter(OrderItem.added_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(OrderItem.added_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt))
|
q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt))
|
||||||
if business_day_id:
|
if business_day_id:
|
||||||
@@ -979,7 +1012,7 @@ def product_performance(
|
|||||||
wq = wq.filter(WasteLog.business_day_id == business_day_id)
|
wq = wq.filter(WasteLog.business_day_id == business_day_id)
|
||||||
elif from_dt and to_dt:
|
elif from_dt and to_dt:
|
||||||
wq = wq.filter(
|
wq = wq.filter(
|
||||||
WasteLog.logged_at >= parse_api_datetime(from_dt),
|
WasteLog.logged_at >= history_since(from_dt, 'reports'),
|
||||||
WasteLog.logged_at <= parse_api_datetime(to_dt),
|
WasteLog.logged_at <= parse_api_datetime(to_dt),
|
||||||
)
|
)
|
||||||
waste_entries = wq.all()
|
waste_entries = wq.all()
|
||||||
@@ -1068,8 +1101,9 @@ def table_performance(
|
|||||||
user: User = Depends(require_reports),
|
user: User = Depends(require_reports),
|
||||||
):
|
):
|
||||||
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'reports')
|
||||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(Order.opened_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||||
if business_day_id:
|
if business_day_id:
|
||||||
@@ -1147,8 +1181,9 @@ def traffic_analysis(
|
|||||||
user: User = Depends(require_reports),
|
user: User = Depends(require_reports),
|
||||||
):
|
):
|
||||||
q = db.query(Order)
|
q = db.query(Order)
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'reports')
|
||||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(Order.opened_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||||
if business_day_id:
|
if business_day_id:
|
||||||
@@ -1178,8 +1213,9 @@ def business_days_list(
|
|||||||
user: User = Depends(require_reports),
|
user: User = Depends(require_reports),
|
||||||
):
|
):
|
||||||
q = db.query(BusinessDay)
|
q = db.query(BusinessDay)
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'history')
|
||||||
q = q.filter(BusinessDay.opened_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(BusinessDay.opened_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(BusinessDay.opened_at <= parse_api_datetime(to_dt))
|
q = q.filter(BusinessDay.opened_at <= parse_api_datetime(to_dt))
|
||||||
days = q.order_by(BusinessDay.opened_at.desc()).all()
|
days = q.order_by(BusinessDay.opened_at.desc()).all()
|
||||||
@@ -1327,8 +1363,9 @@ def revenue_trends(
|
|||||||
user: User = Depends(require_reports),
|
user: User = Depends(require_reports),
|
||||||
):
|
):
|
||||||
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'reports')
|
||||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(Order.opened_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||||
orders = q.all()
|
orders = q.all()
|
||||||
@@ -1388,8 +1425,9 @@ def category_performance(
|
|||||||
from models.product import Product, Category
|
from models.product import Product, Category
|
||||||
|
|
||||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'reports')
|
||||||
q = q.filter(OrderItem.added_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(OrderItem.added_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt))
|
q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt))
|
||||||
if business_day_id:
|
if business_day_id:
|
||||||
@@ -1466,8 +1504,8 @@ def cancellations_log(
|
|||||||
q = db.query(OrderItem).filter(OrderItem.status == "cancelled")
|
q = db.query(OrderItem).filter(OrderItem.status == "cancelled")
|
||||||
|
|
||||||
# Date filter on cancelled_at if available, otherwise fall back to added_at
|
# Date filter on cancelled_at if available, otherwise fall back to added_at
|
||||||
if from_dt:
|
dt_from = history_since(from_dt, 'reports') # clamped even without a "from" (D-6)
|
||||||
dt_from = parse_api_datetime(from_dt)
|
if dt_from:
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
q = q.filter(or_(
|
q = q.filter(or_(
|
||||||
OrderItem.cancelled_at >= dt_from,
|
OrderItem.cancelled_at >= dt_from,
|
||||||
@@ -1542,8 +1580,9 @@ def printer_history(
|
|||||||
user: User = Depends(require_reports),
|
user: User = Depends(require_reports),
|
||||||
):
|
):
|
||||||
q = db.query(PrintLog)
|
q = db.query(PrintLog)
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'reports')
|
||||||
q = q.filter(PrintLog.printed_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(PrintLog.printed_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_dt))
|
q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_dt))
|
||||||
if printer_id:
|
if printer_id:
|
||||||
@@ -1840,8 +1879,9 @@ def prep_zones_report(
|
|||||||
|
|
||||||
# Query order items in the requested range
|
# Query order items in the requested range
|
||||||
q = db.query(OrderItem).join(Order)
|
q = db.query(OrderItem).join(Order)
|
||||||
if from_dt:
|
_since = history_since(from_dt, 'reports')
|
||||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
if _since:
|
||||||
|
q = q.filter(Order.opened_at >= _since)
|
||||||
if to_dt:
|
if to_dt:
|
||||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||||
if business_day_id:
|
if business_day_id:
|
||||||
@@ -1965,8 +2005,9 @@ def print_prep_zone(
|
|||||||
product_ids = {product.id for product in zone.products}
|
product_ids = {product.id for product in zone.products}
|
||||||
|
|
||||||
q = db.query(OrderItem).join(Order)
|
q = db.query(OrderItem).join(Order)
|
||||||
if body.from_dt:
|
_since = history_since(body.from_dt, 'reports')
|
||||||
q = q.filter(Order.opened_at >= parse_api_datetime(body.from_dt))
|
if _since:
|
||||||
|
q = q.filter(Order.opened_at >= _since)
|
||||||
if body.to_dt:
|
if body.to_dt:
|
||||||
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
|
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
|
||||||
if body.business_day_id:
|
if body.business_day_id:
|
||||||
@@ -2020,7 +2061,7 @@ def discounts_report(
|
|||||||
q = q.join(Order, Order.id == OrderDiscount.order_id).filter(Order.business_day_id == business_day_id)
|
q = q.join(Order, Order.id == OrderDiscount.order_id).filter(Order.business_day_id == business_day_id)
|
||||||
elif from_dt and to_dt:
|
elif from_dt and to_dt:
|
||||||
q = q.filter(
|
q = q.filter(
|
||||||
OrderDiscount.applied_at >= parse_api_datetime(from_dt),
|
OrderDiscount.applied_at >= history_since(from_dt, 'reports'),
|
||||||
OrderDiscount.applied_at <= parse_api_datetime(to_dt),
|
OrderDiscount.applied_at <= parse_api_datetime(to_dt),
|
||||||
)
|
)
|
||||||
if applied_by:
|
if applied_by:
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ from services import printer_service
|
|||||||
from services.cloud_sync import _sync_once, _push_menu_snapshot
|
from services.cloud_sync import _sync_once, _push_menu_snapshot
|
||||||
from services.lan_ip import OVERRIDE_KEY, resolve_lan_ip, validate_lan_ip
|
from services.lan_ip import OVERRIDE_KEY, resolve_lan_ip, validate_lan_ip
|
||||||
from services.tls_identity import tls_info
|
from services.tls_identity import tls_info
|
||||||
from middleware.license_check import license_state
|
from services.license_state import license_state
|
||||||
from config import settings
|
from config import settings
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ from pathlib import Path
|
|||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from middleware.license_check import license_state
|
from services.license_state import license_state
|
||||||
from services.license import evaluate, parse_dt, verify_token
|
from services.license import evaluate, parse_dt, verify_token
|
||||||
|
|
||||||
ORDER_POLL_INTERVAL = settings.CONNECT_SYNC_INTERVAL_SECONDS
|
ORDER_POLL_INTERVAL = settings.CONNECT_SYNC_INTERVAL_SECONDS
|
||||||
@@ -73,14 +73,26 @@ def _latest_activity(db) -> datetime | None:
|
|||||||
|
|
||||||
|
|
||||||
def apply_license(now: datetime | None = None) -> None:
|
def apply_license(now: datetime | None = None) -> None:
|
||||||
"""Re-evaluate the license from the stored signed token (no network)."""
|
"""Re-evaluate the license from the stored signed token (no network) and install
|
||||||
if not settings.SITE_ID or not settings.CLOUD_URL:
|
the resulting module entitlements (core/modules/entitlements.py).
|
||||||
return # dev / unregistered / no cloud configured: licensing off, as before KI-006
|
|
||||||
|
Called at startup, after every heartbeat and when a business day closes (expiry,
|
||||||
|
grace and remote locks are deferred to that moment, never mid-service).
|
||||||
|
LICENSE_MODE=off (dev machines only): every module, no limits.
|
||||||
|
No SITE_ID / no valid v2 token / expired / inactive / locked: the free tier."""
|
||||||
|
from core.modules import entitlements
|
||||||
|
|
||||||
|
if settings.LICENSE_MODE == "off":
|
||||||
|
license_state.update({"license_mode": "off", "licensed": True, "license_problem": None,
|
||||||
|
"entitlement_mode": "dev", "locked": False, "lock_pending": False})
|
||||||
|
entitlements.set_dev()
|
||||||
|
return
|
||||||
|
|
||||||
from database import SessionLocal
|
from database import SessionLocal
|
||||||
from models.business_day import BusinessDay
|
from models.business_day import BusinessDay
|
||||||
|
|
||||||
now = now or utcnow()
|
now = now or utcnow()
|
||||||
payload = verify_token(license_state.get("license_token"), settings.SITE_ID)
|
payload = verify_token(license_state.get("license_token"), settings.SITE_ID) if settings.SITE_ID else None
|
||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
try:
|
try:
|
||||||
workday_open = db.query(BusinessDay).filter(BusinessDay.status == "open").first() is not None
|
workday_open = db.query(BusinessDay).filter(BusinessDay.status == "open").first() is not None
|
||||||
@@ -91,7 +103,7 @@ def apply_license(now: datetime | None = None) -> None:
|
|||||||
floors = [parse_dt(license_state.get("time_high_water")), latest_activity,
|
floors = [parse_dt(license_state.get("time_high_water")), latest_activity,
|
||||||
parse_dt(payload["issued_at"]) if payload else None]
|
parse_dt(payload["issued_at"]) if payload else None]
|
||||||
floor = max((f for f in floors if f), default=None)
|
floor = max((f for f in floors if f), default=None)
|
||||||
result = evaluate(payload, now, floor, workday_open, parse_dt(license_state.get("legacy_ok_at")))
|
result = evaluate(payload, now, floor, workday_open)
|
||||||
if result["license_problem"] != "clock":
|
if result["license_problem"] != "clock":
|
||||||
license_state["time_high_water"] = max(floor or now, now).isoformat()
|
license_state["time_high_water"] = max(floor or now, now).isoformat()
|
||||||
|
|
||||||
@@ -106,11 +118,17 @@ def apply_license(now: datetime | None = None) -> None:
|
|||||||
license_state["lock_pending"] = False
|
license_state["lock_pending"] = False
|
||||||
license_state["locked"] = False
|
license_state["locked"] = False
|
||||||
|
|
||||||
|
ent = entitlements.compute(payload if result["license_problem"] != "clock" else None,
|
||||||
|
result["licensed"], bool(license_state.get("locked")), now, workday_open,
|
||||||
|
result["license_problem"])
|
||||||
last_sync = parse_dt(license_state.get("last_sync"))
|
last_sync = parse_dt(license_state.get("last_sync"))
|
||||||
license_state.update({**result, "offline_days": (now - last_sync).days if last_sync else None})
|
license_state.update({**result, "license_mode": "enforced", "entitlement_mode": ent.mode,
|
||||||
|
"offline_days": (now - last_sync).days if last_sync else None})
|
||||||
_persist_state()
|
_persist_state()
|
||||||
|
entitlements.set_current(ent)
|
||||||
if result["license_problem"]:
|
if result["license_problem"]:
|
||||||
logger.warning("License problem: %s (licensed=%s)", result["license_problem"], result["licensed"])
|
logger.warning("License problem: %s (licensed=%s, entitlements=%s)",
|
||||||
|
result["license_problem"], result["licensed"], ent.mode)
|
||||||
|
|
||||||
|
|
||||||
def _get_local_ip() -> str | None:
|
def _get_local_ip() -> str | None:
|
||||||
@@ -148,22 +166,12 @@ async def _sync_once():
|
|||||||
data = resp.json()
|
data = resp.json()
|
||||||
|
|
||||||
token = data.get("license_token")
|
token = data.get("license_token")
|
||||||
if token:
|
if token and verify_token(token, settings.SITE_ID):
|
||||||
if verify_token(token, settings.SITE_ID):
|
|
||||||
license_state["license_token"] = token
|
license_state["license_token"] = token
|
||||||
|
elif token:
|
||||||
|
logger.error("Cloud sent a license token that does not verify (not v2?) - keeping the previous one")
|
||||||
else:
|
else:
|
||||||
logger.error("Cloud sent a license token that does not verify - keeping the previous one")
|
logger.error("Cloud sent no license token - keeping the previous one")
|
||||||
else:
|
|
||||||
# Cloud without license signing (transition): trust this answer for 72h,
|
|
||||||
# keep the old immediate lock handling
|
|
||||||
if data.get("licensed", True):
|
|
||||||
license_state["legacy_ok_at"] = utcnow().isoformat()
|
|
||||||
license_state["expires_at"] = data.get("expires_at")
|
|
||||||
if data.get("locked"):
|
|
||||||
license_state["lock_pending"] = True
|
|
||||||
else:
|
|
||||||
license_state["lock_pending"] = False
|
|
||||||
license_state["locked"] = False
|
|
||||||
|
|
||||||
license_state.update({
|
license_state.update({
|
||||||
"latest_version": data.get("latest_version"),
|
"latest_version": data.get("latest_version"),
|
||||||
@@ -400,9 +408,14 @@ async def _pull_pending_orders():
|
|||||||
logger.warning("Order pull failed: %s", e)
|
logger.warning("Order pull failed: %s", e)
|
||||||
|
|
||||||
|
|
||||||
async def _sync_loop():
|
def load_license_at_startup() -> None:
|
||||||
|
"""Decide from the stored license before anything else runs (main.py lifespan,
|
||||||
|
before the worker supervisor starts), so no module runs a moment longer than allowed."""
|
||||||
_load_persisted_state()
|
_load_persisted_state()
|
||||||
apply_license() # decide from the stored license before the first network attempt
|
apply_license()
|
||||||
|
|
||||||
|
|
||||||
|
async def _sync_loop():
|
||||||
while True:
|
while True:
|
||||||
await _sync_once()
|
await _sync_once()
|
||||||
await asyncio.sleep(SYNC_INTERVAL_SECONDS)
|
await asyncio.sleep(SYNC_INTERVAL_SECONDS)
|
||||||
|
|||||||
@@ -21,10 +21,12 @@ Rules (evaluate()):
|
|||||||
expired: 5-day grace → licensed, warnings in the manager
|
expired: 5-day grace → licensed, warnings in the manager
|
||||||
grace over / site deactivated → unlicensed, but never mid-service:
|
grace over / site deactivated → unlicensed, but never mid-service:
|
||||||
deferred while a workday is open
|
deferred while a workday is open
|
||||||
no valid token:
|
no valid token → unlicensed ("unverified")
|
||||||
old cloud without tokens, heartbeat said licensed < 72h ago → licensed (transition)
|
|
||||||
otherwise → unlicensed ("unverified")
|
|
||||||
Locks from the cloud (token.locked) keep the existing workday-deferred behaviour.
|
Locks from the cloud (token.locked) keep the existing workday-deferred behaviour.
|
||||||
|
|
||||||
|
Platform v2 (D-3, D-21): only `v: 2` tokens are valid, and they must carry a `modules`
|
||||||
|
map. "Unlicensed" no longer blocks the API; it drops the site to the free tier
|
||||||
|
(core/modules/entitlements.py), module by module.
|
||||||
"""
|
"""
|
||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
@@ -41,7 +43,6 @@ LICENSE_PUBLIC_KEY = "2oeFHV6hgAlJsx/ZBvG6fqmWYn5tjSW5hURrrPhLoOw="
|
|||||||
|
|
||||||
EXPIRY_GRACE = timedelta(days=5)
|
EXPIRY_GRACE = timedelta(days=5)
|
||||||
CLOCK_TOLERANCE = timedelta(days=1)
|
CLOCK_TOLERANCE = timedelta(days=1)
|
||||||
LEGACY_UNSIGNED_OK = timedelta(hours=72) # only while the cloud sends no tokens
|
|
||||||
|
|
||||||
|
|
||||||
def _b64url_decode(s: str) -> bytes:
|
def _b64url_decode(s: str) -> bytes:
|
||||||
@@ -71,22 +72,22 @@ def verify_token(token: str | None, site_id: str, public_key_b64: str | None = N
|
|||||||
payload = json.loads(_b64url_decode(body))
|
payload = json.loads(_b64url_decode(body))
|
||||||
except (InvalidSignature, ValueError, TypeError):
|
except (InvalidSignature, ValueError, TypeError):
|
||||||
return None
|
return None
|
||||||
if payload.get("v") != 1 or payload.get("site_id") != site_id:
|
if payload.get("v") != 2 or payload.get("site_id") != site_id:
|
||||||
|
return None
|
||||||
|
if not isinstance(payload.get("modules"), dict):
|
||||||
return None
|
return None
|
||||||
if not parse_dt(payload.get("expires_at")) or not parse_dt(payload.get("issued_at")):
|
if not parse_dt(payload.get("expires_at")) or not parse_dt(payload.get("issued_at")):
|
||||||
return None
|
return None
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
|
||||||
def evaluate(payload: dict | None, now: datetime, floor: datetime | None, workday_open: bool,
|
def evaluate(payload: dict | None, now: datetime, floor: datetime | None, workday_open: bool) -> dict:
|
||||||
legacy_ok_at: datetime | None = None) -> dict:
|
|
||||||
"""Pure license decision. `floor` = latest time this system has provably seen."""
|
"""Pure license decision. `floor` = latest time this system has provably seen."""
|
||||||
base = {"license_verified": payload is not None, "license_problem": None, "grace_over": False,
|
base = {"license_verified": payload is not None, "license_problem": None, "grace_over": False,
|
||||||
"days_until_expiry": None, "grace_expires_at": None, "grace_days_remaining": None}
|
"days_until_expiry": None, "grace_expires_at": None, "grace_days_remaining": None}
|
||||||
|
|
||||||
if payload is None:
|
if payload is None:
|
||||||
legacy = legacy_ok_at is not None and now - legacy_ok_at <= LEGACY_UNSIGNED_OK
|
return {**base, "licensed": False, "license_problem": "unverified"}
|
||||||
return {**base, "licensed": legacy, "license_problem": None if legacy else "unverified"}
|
|
||||||
|
|
||||||
if floor is not None and now < floor - CLOCK_TOLERANCE:
|
if floor is not None and now < floor - CLOCK_TOLERANCE:
|
||||||
return {**base, "licensed": False, "license_problem": "clock"}
|
return {**base, "licensed": False, "license_problem": "clock"}
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""In-memory license status, shared by cloud_sync (writes), system/business-day routers (read).
|
||||||
|
|
||||||
|
Persisted to <data dir>/license_state.json by services/cloud_sync.py. What the site may
|
||||||
|
USE is decided by core/modules/entitlements.py from the same evaluation; this dict is
|
||||||
|
the status the manager's license page shows.
|
||||||
|
|
||||||
|
Fields:
|
||||||
|
license_mode "enforced" | "off" (config LICENSE_MODE; "off" only on dev machines)
|
||||||
|
licensed bool - the global license is valid (expiry/grace/lock deferred to
|
||||||
|
the end of an open workday). False = the free tier applies.
|
||||||
|
license_problem None | "unverified" | "expired" | "inactive" | "clock"
|
||||||
|
entitlement_mode "licensed" | "free" | "dev" (from entitlements.compute)
|
||||||
|
locked bool - remote lock enforced (applied at workday close)
|
||||||
|
lock_pending bool - the cloud asked for a lock; waiting for the workday to close
|
||||||
|
expires_at, days_until_expiry, grace_expires_at, grace_days_remaining, grace_over
|
||||||
|
license_token the signed token as received (verified on every evaluation)
|
||||||
|
last_sync, sync_failed, offline_days, time_high_water, latest_version,
|
||||||
|
waiter_domain, site_numeric_id
|
||||||
|
"""
|
||||||
|
license_state: dict = {
|
||||||
|
"license_mode": "enforced",
|
||||||
|
"licensed": False,
|
||||||
|
"license_problem": "unverified",
|
||||||
|
"entitlement_mode": "free",
|
||||||
|
"locked": False,
|
||||||
|
"lock_pending": False,
|
||||||
|
"expires_at": None,
|
||||||
|
"days_until_expiry": None,
|
||||||
|
"grace_expires_at": None,
|
||||||
|
"last_sync": None,
|
||||||
|
"sync_failed": False,
|
||||||
|
"latest_version": None,
|
||||||
|
}
|
||||||
@@ -70,12 +70,17 @@ def pytest_collection_modifyitems(config, items):
|
|||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _venue_time():
|
def _venue_time():
|
||||||
"""Every test runs in Europe/Athens with rollover 06:00 (D-11) and venue language "en"
|
"""Every test runs in Europe/Athens with rollover 06:00 (D-11), venue language "en"
|
||||||
(D-12), without reading settings from a database. Tests may call configure(...) to change them."""
|
(D-12) and every module entitled without limits (D-3), without reading anything from a
|
||||||
|
database. Tests may call configure(...) / entitlements.set_current(...) to change them."""
|
||||||
from core import i18n, timeutil
|
from core import i18n, timeutil
|
||||||
|
from core.modules import entitlements
|
||||||
timeutil.configure(tz="Europe/Athens", rollover_hour=6)
|
timeutil.configure(tz="Europe/Athens", rollover_hour=6)
|
||||||
i18n.configure(venue_language="en")
|
i18n.configure(venue_language="en")
|
||||||
|
# Every module, no limits (like LICENSE_MODE=off). License tests install their own.
|
||||||
|
entitlements.set_current(entitlements.dev(), notify=False)
|
||||||
yield
|
yield
|
||||||
|
entitlements.reset()
|
||||||
timeutil.invalidate()
|
timeutil.invalidate()
|
||||||
i18n.invalidate()
|
i18n.invalidate()
|
||||||
from core.modules import state as module_state
|
from core.modules import state as module_state
|
||||||
@@ -128,11 +133,12 @@ def client(db):
|
|||||||
"""FastAPI TestClient on the real app, using the test session.
|
"""FastAPI TestClient on the real app, using the test session.
|
||||||
|
|
||||||
The lifespan is NOT run (no cloud sync, print-retry thread or TLS work);
|
The lifespan is NOT run (no cloud sync, print-retry thread or TLS work);
|
||||||
the schema comes from `_engine`. The license middleware is forced open."""
|
the schema comes from `_engine`. Entitlements are "dev" (every module, no limits)
|
||||||
|
via the autouse `_venue_time` fixture; license tests install their own."""
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
import main
|
import main
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from middleware.license_check import license_state
|
from services.license_state import license_state
|
||||||
|
|
||||||
saved = dict(license_state)
|
saved = dict(license_state)
|
||||||
license_state.update(licensed=True, locked=False)
|
license_state.update(licensed=True, locked=False)
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
"""Entitlements, limits, free tier (plan step 1.4, APPS_PLATFORM D-3..D-6, §5)."""
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from core.modules import entitlements as E
|
||||||
|
from core.modules.free_tier import FREE_TIER
|
||||||
|
|
||||||
|
NOW = datetime(2026, 11, 12, 12, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def payload(**modules):
|
||||||
|
return {"v": 2, "site_id": "site-A", "modules": modules}
|
||||||
|
|
||||||
|
|
||||||
|
def ent(mods, licensed=True, locked=False, workday_open=False, now=NOW):
|
||||||
|
return E.compute(payload(**mods), licensed, locked, now, workday_open)
|
||||||
|
|
||||||
|
|
||||||
|
# ── compute ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_token_modules_plus_core_plus_free():
|
||||||
|
e = ent({"ordering": {}, "kds": {"limits": {"devices": 2}}})
|
||||||
|
assert e.mode == "licensed"
|
||||||
|
assert {"core", "catalog", "ordering", "kds", "history"} <= set(e.grants)
|
||||||
|
assert "tabs" not in e.grants and "waiter_app" not in e.grants
|
||||||
|
assert e.grants["kds"].source == "license" and e.grants["history"].source == "free"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("licensed,locked,reason", [(False, False, "expired"), (True, True, "locked")])
|
||||||
|
def test_not_licensed_or_locked_gives_free_tier(licensed, locked, reason):
|
||||||
|
e = ent({"ordering": {}, "kds": {}}, licensed=licensed, locked=locked)
|
||||||
|
assert e.mode == "free" and e.reason == reason
|
||||||
|
assert set(e.grants) == {"core", "catalog"} | set(FREE_TIER)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_token_gives_free_tier():
|
||||||
|
e = E.compute(None, False, False, NOW, False, problem="unverified")
|
||||||
|
assert e.mode == "free" and e.reason == "unverified" and "ordering" not in e.grants
|
||||||
|
|
||||||
|
|
||||||
|
def test_module_exp_with_grace_and_workday():
|
||||||
|
exp = (NOW - timedelta(days=3)).isoformat()
|
||||||
|
assert "caller_id" in ent({"caller_id": {"exp": exp}}).grants # within 5-day grace
|
||||||
|
old = (NOW - timedelta(days=6)).isoformat()
|
||||||
|
assert "caller_id" not in ent({"caller_id": {"exp": old}}).grants # grace over
|
||||||
|
kept = ent({"caller_id": {"exp": old}}, workday_open=True).grants["caller_id"]
|
||||||
|
assert kept.exp_deferred is True # never mid-service
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_module_in_token_is_ignored():
|
||||||
|
assert "teleporter" not in ent({"teleporter": {}, "ordering": {}}).grants
|
||||||
|
|
||||||
|
|
||||||
|
# ── limits ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_limits_token_value_default_and_unlimited():
|
||||||
|
e = ent({"kds": {"limits": {"devices": 2}}, "pos_counter": {}, "reports": {}})
|
||||||
|
assert e.limit("kds", "devices") == 2 # from the token
|
||||||
|
assert e.limit("pos_counter", "devices") == 1 # manifest licensed_default
|
||||||
|
assert e.limit("reports", "history_days") is None # licensed_default None = unlimited
|
||||||
|
assert e.limit("signage", "devices") == 0 # not entitled
|
||||||
|
|
||||||
|
|
||||||
|
def test_free_tier_limits():
|
||||||
|
e = E.compute(None, False, False, NOW, False)
|
||||||
|
assert e.limit("history", "history_days") == FREE_TIER["history"]["limits"]["history_days"]
|
||||||
|
licensed_history = ent({"history": {}})
|
||||||
|
assert licensed_history.limit("history", "history_days") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_mode_has_everything_unlimited():
|
||||||
|
e = E.dev()
|
||||||
|
assert e.mode == "dev" and e.limit("kds", "devices") is None and e.entitled("fiscal")
|
||||||
|
|
||||||
|
|
||||||
|
# ── API: done-when checks ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def install(mods, **kw):
|
||||||
|
E.set_current(ent(mods, **kw), notify=False)
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_without_kds_blocks_kds_api(client, make_user, login): # "done when" 1
|
||||||
|
install({"ordering": {}})
|
||||||
|
r = client.get("/api/kds/orders", headers=login(make_user(role="superadmin")))
|
||||||
|
assert r.status_code == 402
|
||||||
|
assert r.json()["error"] == {"code": "module.not_licensed", "params": {"module": "kds"},
|
||||||
|
"message": "This site's license doesn't include kds."}
|
||||||
|
|
||||||
|
|
||||||
|
def test_dependency_not_licensed_reports_the_dependency(client, make_user, login):
|
||||||
|
install({"kds": {}}) # kds without ordering
|
||||||
|
r = client.get("/api/kds/orders", headers=login(make_user(role="superadmin")))
|
||||||
|
assert r.json()["error"]["params"] == {"module": "ordering"}
|
||||||
|
|
||||||
|
|
||||||
|
def _orders_at(db, user, days_ago_list):
|
||||||
|
from models.order import Order, OrderItem
|
||||||
|
from models.product import Category, Product
|
||||||
|
cat = Category(name="C")
|
||||||
|
db.add(cat)
|
||||||
|
db.flush()
|
||||||
|
prod = Product(name="P", base_price=5.0, category_id=cat.id)
|
||||||
|
db.add(prod)
|
||||||
|
db.flush()
|
||||||
|
for d in days_ago_list:
|
||||||
|
when = datetime.now(timezone.utc) - timedelta(days=d) # noqa: test data
|
||||||
|
o = Order(opened_by=user.id, status="closed", opened_at=when, closed_at=when)
|
||||||
|
db.add(o)
|
||||||
|
db.flush()
|
||||||
|
db.add(OrderItem(order_id=o.id, product_id=prod.id, added_by=user.id, quantity=1,
|
||||||
|
unit_price=5.0, status="paid", added_at=when, paid_at=when))
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_days_clamps_a_90_day_report(client, db, make_user, login): # "done when" 2
|
||||||
|
admin = make_user(role="superadmin")
|
||||||
|
_orders_at(db, admin, [10, 60, 85])
|
||||||
|
since = (datetime.now(timezone.utc) - timedelta(days=90)).date().isoformat()
|
||||||
|
install({"ordering": {}, "reports": {"limits": {"history_days": 30}}})
|
||||||
|
r = client.get("/api/reports/revenue/trends", params={"from": since, "granularity": "monthly"}, headers=login(admin))
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
rows = r.json() if isinstance(r.json(), list) else next(v for v in r.json().values() if isinstance(v, list))
|
||||||
|
assert sum(row["orders"] for row in rows) == 1 # only the 10-day-old order is visible
|
||||||
|
install({"ordering": {}, "reports": {}}) # unlimited again: data was never deleted
|
||||||
|
r = client.get("/api/reports/revenue/trends", params={"from": since, "granularity": "monthly"}, headers=login(admin))
|
||||||
|
rows = r.json() if isinstance(r.json(), list) else next(v for v in r.json().values() if isinstance(v, list))
|
||||||
|
assert sum(row["orders"] for row in rows) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_history_limit_also_applies_without_from(client, db, make_user, login):
|
||||||
|
admin = make_user(role="superadmin")
|
||||||
|
_orders_at(db, admin, [5, 200])
|
||||||
|
install({"ordering": {}, "reports": {"limits": {"history_days": 30}}})
|
||||||
|
r = client.get("/api/reports/traffic", headers=login(admin))
|
||||||
|
assert sum(b["orders"] for b in r.json()["by_hour"]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_old_business_day_refused_by_id(client, db, make_user, login):
|
||||||
|
from models.business_day import BusinessDay
|
||||||
|
from core.timeutil import business_date_of
|
||||||
|
admin = make_user(role="superadmin")
|
||||||
|
opened = datetime.now(timezone.utc) - timedelta(days=60)
|
||||||
|
bd = BusinessDay(opened_by_id=admin.id, opened_at=opened, business_date=business_date_of(opened),
|
||||||
|
status="closed", closed_at=opened + timedelta(hours=10))
|
||||||
|
db.add(bd)
|
||||||
|
db.commit()
|
||||||
|
install({"ordering": {}, "reports": {"limits": {"history_days": 30}}})
|
||||||
|
r = client.get("/api/reports/traffic", params={"business_day_id": bd.id}, headers=login(admin))
|
||||||
|
assert r.status_code == 402 and r.json()["error"]["code"] == "license.history_limited"
|
||||||
|
assert r.json()["error"]["params"] == {"module": "reports", "days": 30}
|
||||||
|
|
||||||
|
|
||||||
|
def test_free_tier_history_is_capped_and_reports_blocked(client, db, make_user, login):
|
||||||
|
admin = make_user(role="superadmin")
|
||||||
|
E.set_current(E.compute(None, False, False, NOW, False), notify=False)
|
||||||
|
assert client.get("/api/reports/orders/history", headers=login(admin)).status_code == 200
|
||||||
|
assert client.get("/api/reports/traffic", headers=login(admin)).json()["error"]["code"] == "module.not_licensed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_expired_site_can_log_in_and_see_license_page_but_not_order(client, make_user): # "done when" 3
|
||||||
|
from conftest import TEST_PASSWORD
|
||||||
|
E.set_current(E.compute(None, False, False, NOW, False, problem="expired"), notify=False)
|
||||||
|
m = make_user(role="store_manager")
|
||||||
|
r = client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD})
|
||||||
|
assert r.status_code == 200
|
||||||
|
h = {"Authorization": f"Bearer {r.json()['access_token']}"}
|
||||||
|
assert client.get("/api/system/status", headers=h).status_code == 200
|
||||||
|
assert client.get("/api/setup/security-config").status_code == 200
|
||||||
|
boot = client.get("/api/platform/bootstrap", headers=h).json()
|
||||||
|
assert boot["license"] == {"mode": "free", "reason": "expired"}
|
||||||
|
assert "ordering" not in {x["key"] for x in boot["modules"]}
|
||||||
|
assert client.get("/api/business-day/current", headers=h).json()["error"]["code"] == "module.not_licensed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalogue_shows_entitlement_and_limit_values(client, make_user, login):
|
||||||
|
install({"ordering": {}, "kds": {"limits": {"devices": 3}}})
|
||||||
|
mods = {m["key"]: m for m in client.get("/api/platform/modules",
|
||||||
|
headers=login(make_user(role="superadmin"))).json()["modules"]}
|
||||||
|
assert mods["kds"]["entitled"] and mods["kds"]["entitlement"]["source"] == "license"
|
||||||
|
assert mods["kds"]["limits"][0]["value"] == 3
|
||||||
|
assert mods["signage"]["entitled"] is False and mods["signage"]["effective"] is False
|
||||||
|
|
||||||
|
|
||||||
|
# ── apply_license end to end (signed token, real code path) ─────────────────
|
||||||
|
|
||||||
|
def test_apply_license_installs_entitlements_from_a_signed_token(monkeypatch):
|
||||||
|
from tests.test_license import PUB, make_token
|
||||||
|
import services.license as L
|
||||||
|
from config import settings
|
||||||
|
from services import cloud_sync
|
||||||
|
from services.license_state import license_state
|
||||||
|
|
||||||
|
monkeypatch.setattr(L, "LICENSE_PUBLIC_KEY", PUB)
|
||||||
|
monkeypatch.setattr(settings, "SITE_ID", "site-A")
|
||||||
|
monkeypatch.setattr(settings, "LICENSE_MODE", "enforced")
|
||||||
|
monkeypatch.setitem(license_state, "license_token", make_token(modules={"ordering": {}, "reports": {}}))
|
||||||
|
monkeypatch.setitem(license_state, "time_high_water", None)
|
||||||
|
cloud_sync.apply_license(now=datetime(2027, 1, 1, tzinfo=timezone.utc))
|
||||||
|
e = E.current()
|
||||||
|
assert e.mode == "licensed" and e.entitled("reports") and not e.entitled("kds")
|
||||||
|
assert license_state["entitlement_mode"] == "licensed" and license_state["licensed"] is True
|
||||||
|
|
||||||
|
monkeypatch.setattr(settings, "LICENSE_MODE", "off")
|
||||||
|
cloud_sync.apply_license()
|
||||||
|
assert E.current().mode == "dev" and license_state["license_mode"] == "off"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Offline-capable licensing rules (services/license.py, KI-006).
|
"""Offline-capable licensing rules (services/license.py, KI-006; v2 tokens, D-21).
|
||||||
|
|
||||||
Tokens are signed with a throwaway key here — the production signing key is
|
Tokens are signed with a throwaway key here — the production signing key is
|
||||||
never needed; verify_token() takes the public key as a parameter.
|
never needed; verify_token() takes the public key as a parameter.
|
||||||
@@ -24,8 +24,9 @@ def b64(data: bytes) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def make_token(signer=KEY, **overrides) -> str:
|
def make_token(signer=KEY, **overrides) -> str:
|
||||||
payload = {"v": 1, "site_id": "site-A", "active": True, "locked": False, "lock_reason": None,
|
payload = {"v": 2, "site_id": "site-A", "active": True, "locked": False, "lock_reason": None,
|
||||||
"expires_at": EXPIRES.isoformat(), "issued_at": ISSUED.isoformat(), **overrides}
|
"expires_at": EXPIRES.isoformat(), "issued_at": ISSUED.isoformat(),
|
||||||
|
"modules": {"ordering": {}}, **overrides}
|
||||||
body = b64(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
|
body = b64(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
|
||||||
return f"{body}.{b64(signer.sign(body.encode()))}"
|
return f"{body}.{b64(signer.sign(body.encode()))}"
|
||||||
|
|
||||||
@@ -48,6 +49,14 @@ def test_edited_expiry_rejected(payload):
|
|||||||
assert verify_token(f"{forged}.{sig}", "site-A", PUB) is None
|
assert verify_token(f"{forged}.{sig}", "site-A", PUB) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_v1_token_rejected(): # D-21: v2 sites accept only v2 tokens
|
||||||
|
assert verify_token(make_token(v=1), "site-A", PUB) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_v2_token_without_modules_rejected():
|
||||||
|
assert verify_token(make_token(modules=None), "site-A", PUB) is None
|
||||||
|
|
||||||
|
|
||||||
def test_token_for_another_site_rejected():
|
def test_token_for_another_site_rejected():
|
||||||
assert verify_token(make_token(site_id="site-B"), "site-A", PUB) is None
|
assert verify_token(make_token(site_id="site-B"), "site-A", PUB) is None
|
||||||
|
|
||||||
@@ -115,16 +124,6 @@ def test_clock_before_signed_issue_time_blocks(payload):
|
|||||||
|
|
||||||
# ── evaluate: no genuine token ───────────────────────────────────────────────
|
# ── evaluate: no genuine token ───────────────────────────────────────────────
|
||||||
|
|
||||||
def test_transition_old_cloud_recent_ok():
|
|
||||||
r = evaluate(None, ISSUED, None, False, legacy_ok_at=ISSUED - timedelta(hours=10))
|
|
||||||
assert (r["licensed"], r["license_problem"]) == (True, None)
|
|
||||||
|
|
||||||
|
|
||||||
def test_transition_old_cloud_stale():
|
|
||||||
r = evaluate(None, ISSUED, None, False, legacy_ok_at=ISSUED - timedelta(hours=80))
|
|
||||||
assert (r["licensed"], r["license_problem"]) == (False, "unverified")
|
|
||||||
|
|
||||||
|
|
||||||
def test_never_licensed_blocks():
|
def test_never_licensed_blocks():
|
||||||
r = evaluate(None, ISSUED, None, False)
|
r = evaluate(None, ISSUED, None, False)
|
||||||
assert (r["licensed"], r["license_problem"]) == (False, "unverified")
|
assert (r["licensed"], r["license_problem"]) == (False, "unverified")
|
||||||
|
|||||||
+1
-1
@@ -59,4 +59,4 @@ Or run one suite at a time:
|
|||||||
- **Ports used:** 8055/8056 (backends), 8101 (cloud), 5180 (Vite), 15173/15174 (nginx), 18080–18444 and 28080–28443 (compose stacks). Your own dev stack's ports (80/443/8081/8443/5173/5174) are never used. Stop anything else on those ports first.
|
- **Ports used:** 8055/8056 (backends), 8101 (cloud), 5180 (Vite), 15173/15174 (nginx), 18080–18444 and 28080–28443 (compose stacks). Your own dev stack's ports (80/443/8081/8443/5173/5174) are never used. Stop anything else on those ports first.
|
||||||
- **Isolated stacks:** the compose stacks run under their own project names (`xenia-e2e-v1/v2`) with their own images and data. They're removed afterwards.
|
- **Isolated stacks:** the compose stacks run under their own project names (`xenia-e2e-v1/v2`) with their own images and data. They're removed afterwards.
|
||||||
- **Output:** screenshots and logs go to `out/`, which is gitignored.
|
- **Output:** screenshots and logs go to `out/`, which is gitignored.
|
||||||
- **Licensing in tests:** the license suite signs with a throwaway key, and the production signing key is never needed. The other suites run their backends without a cloud URL, so licensing is off, as on any dev setup.
|
- **Licensing in tests:** the license suite signs with a throwaway key, and the production signing key is never needed. The other suites run their backends without a cloud URL and with `LICENSE_MODE=off` (`lib/proc.mjs`), so every module is available. On platform v2 a backend **without** `LICENSE_MODE=off` and without a valid v2 token runs the free tier (D-5), so any new launcher must set it. `license_e2e.py` needs a cloud that signs v2 tokens: it's updated in plan step 1.7, and fails until then.
|
||||||
|
|||||||
@@ -59,6 +59,8 @@ export async function startBackend({ port = 8055, siteId = 'test-site-1', siteKe
|
|||||||
env: {
|
env: {
|
||||||
...process.env, DATABASE_URL: `sqlite:///${path.join(dataDir, 'pos.db').replace(/\\/g, '/')}`,
|
...process.env, DATABASE_URL: `sqlite:///${path.join(dataDir, 'pos.db').replace(/\\/g, '/')}`,
|
||||||
SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret',
|
SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret',
|
||||||
|
// No cloud = a test backend: licensing off (every module). The license suite passes a cloudUrl.
|
||||||
|
LICENSE_MODE: cloudUrl ? 'enforced' : 'off',
|
||||||
MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password, ...env,
|
MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password, ...env,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -113,6 +115,7 @@ export function composeStack({ project, version, siteId, http, https, manager, e
|
|||||||
const envFile = path.join(dir, 'e2e.env')
|
const envFile = path.join(dir, 'e2e.env')
|
||||||
writeFileSync(envFile, Object.entries({
|
writeFileSync(envFile, Object.entries({
|
||||||
REGISTRY: 'e2e', VERSION: version, SITE_ID: siteId, SITE_KEY: 'x', CLOUD_URL: '', SECRET_KEY: 'e2e-secret',
|
REGISTRY: 'e2e', VERSION: version, SITE_ID: siteId, SITE_KEY: 'x', CLOUD_URL: '', SECRET_KEY: 'e2e-secret',
|
||||||
|
LICENSE_MODE: 'off',
|
||||||
HOST_IP: '10.0.2.2', TLS_PORT: https, HTTP_PORT: http, MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password,
|
HOST_IP: '10.0.2.2', TLS_PORT: https, HTTP_PORT: http, MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password,
|
||||||
DATA_PATH: fwd(path.join(dir, 'data')), LOGO_PATH: fwd(path.join(dir, 'logo.png')), FISCAL_PATH: fwd(path.join(dir, 'fiscal')),
|
DATA_PATH: fwd(path.join(dir, 'data')), LOGO_PATH: fwd(path.join(dir, 'logo.png')), FISCAL_PATH: fwd(path.join(dir, 'fiscal')),
|
||||||
...extraEnv,
|
...extraEnv,
|
||||||
|
|||||||
Reference in New Issue
Block a user