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:
@@ -17,7 +17,7 @@ from models.printer import Printer
|
||||
from schemas.business_day import BusinessDayOut, OpenBusinessDayRequest, CloseBusinessDayRequest
|
||||
from routers.deps import get_current_user, require_manager
|
||||
from models.user import User
|
||||
from middleware.license_check import license_state
|
||||
from services.license_state import license_state
|
||||
|
||||
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
|
||||
import csv
|
||||
import io
|
||||
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 pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -28,11 +30,36 @@ from services.printer_service import (
|
||||
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
|
||||
# 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.
|
||||
history_router = APIRouter()
|
||||
history_router = APIRouter(dependencies=[Depends(_business_day_guard("history"))])
|
||||
|
||||
|
||||
def _item_val(item) -> float:
|
||||
@@ -57,11 +84,12 @@ def shift_summary(
|
||||
):
|
||||
"""Payments collected per waiter — based on paid_by on order items."""
|
||||
if from_dt and to_dt:
|
||||
start = parse_api_datetime(from_dt)
|
||||
start = history_since(from_dt, 'reports')
|
||||
end = parse_api_datetime(to_dt)
|
||||
else:
|
||||
# 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 = clamp_start(start, 'reports')
|
||||
|
||||
q = db.query(OrderItem).filter(
|
||||
OrderItem.status == "paid",
|
||||
@@ -135,10 +163,11 @@ def shift_orders_summary(
|
||||
q = q.join(Order).filter(Order.business_day_id == business_day_id)
|
||||
else:
|
||||
if from_dt and to_dt:
|
||||
start = parse_api_datetime(from_dt)
|
||||
start = history_since(from_dt, 'reports')
|
||||
end = parse_api_datetime(to_dt)
|
||||
else:
|
||||
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)
|
||||
if waiter_id:
|
||||
q = q.filter(OrderItem.added_by == waiter_id)
|
||||
@@ -258,8 +287,9 @@ def order_history(
|
||||
if business_day_id:
|
||||
q = q.filter(Order.business_day_id == business_day_id)
|
||||
elif from_date or to_date:
|
||||
if from_date:
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_date))
|
||||
_since = history_since(from_date, 'history')
|
||||
if _since:
|
||||
q = q.filter(Order.opened_at >= _since)
|
||||
if to_date:
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_date))
|
||||
if waiter_id:
|
||||
@@ -400,8 +430,9 @@ def printer_totals(
|
||||
):
|
||||
"""Returns totals per printer based on print_log entries in the date range."""
|
||||
q = db.query(PrintLog).filter(PrintLog.success == True)
|
||||
if from_date:
|
||||
q = q.filter(PrintLog.printed_at >= parse_api_datetime(from_date))
|
||||
_since = history_since(from_date, 'reports')
|
||||
if _since:
|
||||
q = q.filter(PrintLog.printed_at >= _since)
|
||||
if to_date:
|
||||
q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_date))
|
||||
logs = q.all()
|
||||
@@ -568,7 +599,7 @@ def print_waiter(
|
||||
if not printer:
|
||||
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)
|
||||
|
||||
# Gather orders for this waiter in time range
|
||||
@@ -640,7 +671,7 @@ def print_printer_totals(
|
||||
if 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:
|
||||
from_dt = parse_api_datetime(body.from_dt)
|
||||
from_dt = history_since(body.from_dt, 'reports')
|
||||
to_dt = parse_api_datetime(body.to_dt)
|
||||
q = q.filter(PrintLog.printed_at >= from_dt, PrintLog.printed_at <= to_dt)
|
||||
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_is_workday = True
|
||||
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
|
||||
period_label = (
|
||||
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()
|
||||
label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}"
|
||||
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
|
||||
label = (
|
||||
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)
|
||||
elif body.from_dt and body.to_dt:
|
||||
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),
|
||||
)
|
||||
items = q.all()
|
||||
@@ -797,7 +828,7 @@ def print_categories(
|
||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||
elif body.from_dt and body.to_dt:
|
||||
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),
|
||||
)
|
||||
items = q.all()
|
||||
@@ -874,7 +905,7 @@ def print_tables(
|
||||
q = q.filter(Order.business_day_id == body.business_day_id)
|
||||
elif body.from_dt and body.to_dt:
|
||||
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),
|
||||
)
|
||||
orders = q.all()
|
||||
@@ -935,8 +966,9 @@ def shifts_report(
|
||||
q = q.filter(WaiterShift.waiter_id == waiter_id)
|
||||
if business_day_id:
|
||||
q = q.filter(WaiterShift.business_day_id == business_day_id)
|
||||
if from_dt:
|
||||
q = q.filter(WaiterShift.started_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(WaiterShift.started_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(WaiterShift.started_at <= parse_api_datetime(to_dt))
|
||||
if active_only:
|
||||
@@ -963,8 +995,9 @@ def product_performance(
|
||||
from models.waste import WasteLog
|
||||
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
if from_dt:
|
||||
q = q.filter(OrderItem.added_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(OrderItem.added_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
@@ -979,7 +1012,7 @@ def product_performance(
|
||||
wq = wq.filter(WasteLog.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
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),
|
||||
)
|
||||
waste_entries = wq.all()
|
||||
@@ -1068,8 +1101,9 @@ def table_performance(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
||||
if from_dt:
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(Order.opened_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
@@ -1147,8 +1181,9 @@ def traffic_analysis(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
q = db.query(Order)
|
||||
if from_dt:
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(Order.opened_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
@@ -1178,8 +1213,9 @@ def business_days_list(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
q = db.query(BusinessDay)
|
||||
if from_dt:
|
||||
q = q.filter(BusinessDay.opened_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'history')
|
||||
if _since:
|
||||
q = q.filter(BusinessDay.opened_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(BusinessDay.opened_at <= parse_api_datetime(to_dt))
|
||||
days = q.order_by(BusinessDay.opened_at.desc()).all()
|
||||
@@ -1327,8 +1363,9 @@ def revenue_trends(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
||||
if from_dt:
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(Order.opened_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
orders = q.all()
|
||||
@@ -1388,8 +1425,9 @@ def category_performance(
|
||||
from models.product import Product, Category
|
||||
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
if from_dt:
|
||||
q = q.filter(OrderItem.added_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(OrderItem.added_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
@@ -1466,8 +1504,8 @@ def cancellations_log(
|
||||
q = db.query(OrderItem).filter(OrderItem.status == "cancelled")
|
||||
|
||||
# Date filter on cancelled_at if available, otherwise fall back to added_at
|
||||
if from_dt:
|
||||
dt_from = parse_api_datetime(from_dt)
|
||||
dt_from = history_since(from_dt, 'reports') # clamped even without a "from" (D-6)
|
||||
if dt_from:
|
||||
from sqlalchemy import or_
|
||||
q = q.filter(or_(
|
||||
OrderItem.cancelled_at >= dt_from,
|
||||
@@ -1542,8 +1580,9 @@ def printer_history(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
q = db.query(PrintLog)
|
||||
if from_dt:
|
||||
q = q.filter(PrintLog.printed_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(PrintLog.printed_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_dt))
|
||||
if printer_id:
|
||||
@@ -1840,8 +1879,9 @@ def prep_zones_report(
|
||||
|
||||
# Query order items in the requested range
|
||||
q = db.query(OrderItem).join(Order)
|
||||
if from_dt:
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(from_dt))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(Order.opened_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
@@ -1965,8 +2005,9 @@ def print_prep_zone(
|
||||
product_ids = {product.id for product in zone.products}
|
||||
|
||||
q = db.query(OrderItem).join(Order)
|
||||
if body.from_dt:
|
||||
q = q.filter(Order.opened_at >= parse_api_datetime(body.from_dt))
|
||||
_since = history_since(body.from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(Order.opened_at >= _since)
|
||||
if body.to_dt:
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
|
||||
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)
|
||||
elif from_dt and to_dt:
|
||||
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),
|
||||
)
|
||||
if applied_by:
|
||||
|
||||
@@ -22,7 +22,7 @@ from services import printer_service
|
||||
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.tls_identity import tls_info
|
||||
from middleware.license_check import license_state
|
||||
from services.license_state import license_state
|
||||
from config import settings
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
Reference in New Issue
Block a user