- services/day_auto.py: a minute loop (venue time, offline) opens the day when the opening
hours start (or at business_day.auto_open_time) and closes it when they end (or at
auto_close_time); 'alert' only tells the managers. Offsets before / after, one day across
the break or one per span, spans past midnight belong to the day they start, a day closed
by hand isn't reopened in the same span, a restart catches up the open (until the business
date changes for 'time') and alerts a missed close instead of doing it late.
- The close runs only when no order of the day is unclosed (Q-10): otherwise a sticky alert
and a new try every 15 minutes. A locked / expired license turns the open into an alert.
- Sticky notifications: notifications.resolved_at + core.notifications.resolve(); the
alerts resolve when the day opens / closes (by hand or by itself).
- services/business_days.py: the one open / close path (the routes and the loop); days opened
or closed by the system have no opener / closer and opened_auto / closed_auto (Alembic 0052).
- Manager: Settings -> Operation "Opening and closing the day"; the bell's action buttons
("Open now", "Go to the overview"); Reports -> Days marks days opened / closed by itself.
Plan platform-v2 6F.8.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
160 lines
6.3 KiB
Python
160 lines
6.3 KiB
Python
"""Local backend entry point: logging, app, middleware, routers, startup.
|
|
|
|
Schema is created/upgraded only by Alembic (core/schema.py::upgrade_to_head, D-13).
|
|
The v1 create_all + _run_migrations() ALTER list was deleted in platform-v2 step 1.0.
|
|
"""
|
|
import os
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
from core.logging import setup_logging, apply_retention_setting, RequestContextMiddleware
|
|
|
|
# First thing: every logger below (and uvicorn's) writes through these handlers.
|
|
setup_logging()
|
|
logger = logging.getLogger("xenia.main")
|
|
|
|
from config import settings
|
|
from database import SessionLocal
|
|
from services.cloud_sync import start_cloud_sync
|
|
|
|
# Every model must be registered before the routers import them (see models/all.py).
|
|
import models.all # noqa: F401
|
|
|
|
|
|
|
|
def _init_chat():
|
|
"""Bootstrap the system group chat and sync all active users into it."""
|
|
from services.chat_service import ensure_system_group, add_user_to_system_group
|
|
from models.user import User
|
|
from database import SessionLocal
|
|
db = SessionLocal()
|
|
try:
|
|
ensure_system_group(db)
|
|
active_users = db.query(User).filter(User.is_active == True).all() # noqa: E712
|
|
for u in active_users:
|
|
add_user_to_system_group(db, u.id)
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
import asyncio
|
|
from services.ws_bus import init_loop as ws_init_loop, prune_old_events
|
|
from services.reservation_tasks import start_reservation_tasks
|
|
from services.printer_service import start_print_retry_thread
|
|
loop = asyncio.get_running_loop()
|
|
ws_init_loop(loop)
|
|
# Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases.
|
|
from core.schema import upgrade_to_head
|
|
upgrade_to_head()
|
|
_db = SessionLocal()
|
|
try:
|
|
apply_retention_setting(_db)
|
|
from services.media import import_builtin
|
|
try:
|
|
import_builtin(_db) # pictures shipped with the server (5.4a)
|
|
except Exception as e: # never blocks the start
|
|
logger.warning("built-in pictures not imported: %s", e)
|
|
finally:
|
|
_db.close()
|
|
logger.info("startup version=%s", settings.VERSION)
|
|
# Before the app reports healthy: the proxy's :8443 needs these files to start
|
|
from services.tls_identity import ensure_tls_identity
|
|
ensure_tls_identity()
|
|
start_print_retry_thread()
|
|
from services.video import start_worker as start_video_worker
|
|
start_video_worker() # videos' still frames and playable versions (5.4e)
|
|
pruned = prune_old_events(hours=24)
|
|
if pruned:
|
|
logger.info("ws_bus: pruned %d old sync_events", pruned)
|
|
_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)
|
|
# Module workers (connect_* pushes/pulls...) run only while their module is effective
|
|
from core.modules import supervisor
|
|
supervisor.start(loop)
|
|
reservation_task = await start_reservation_tasks()
|
|
from services import day_auto
|
|
day_task = await day_auto.start() # the day opens / closes by itself (6F.8)
|
|
yield
|
|
day_task.cancel()
|
|
supervisor.stop_all()
|
|
sync_task.cancel()
|
|
reservation_task.cancel()
|
|
|
|
|
|
app = FastAPI(title="POS Local Backend", lifespan=lifespan)
|
|
|
|
# Error responses: {"error": {code, params, message}, "detail"} (core/errors.py, §3.2)
|
|
from core.errors import install_error_handlers # noqa: E402
|
|
install_error_handlers(app)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
# (v1's LicenseCheckMiddleware is gone: an unlicensed site gets the free tier, module by module, D-5.)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def _menu_change_push(request, call_next):
|
|
"""A successful change to products, price rules or fees pushes the customer apps' menu
|
|
soon (phase 3S; services/cloud_sync.request_menu_push)."""
|
|
response = await call_next(request)
|
|
from services.cloud_sync import menu_changed, request_menu_push
|
|
if menu_changed(request.method, request.url.path, response.status_code):
|
|
request_menu_push()
|
|
from starlette.concurrency import run_in_threadpool
|
|
await run_in_threadpool(_signage_menu_changed)
|
|
return response
|
|
|
|
|
|
def _signage_menu_changed() -> None:
|
|
"""The signage screens showing a menu board (5.4b) and the menu tablets (5.7a) read their menu again."""
|
|
try:
|
|
from routers.menu_tablet import menu_changed as tablet_menu_changed
|
|
from routers.signage import menu_changed as signage_menu_changed
|
|
db = SessionLocal()
|
|
try:
|
|
signage_menu_changed(db)
|
|
tablet_menu_changed(db) # the menu tablets read their menu again (5.7a)
|
|
finally:
|
|
db.close()
|
|
except Exception as e: # never breaks the request that changed the menu
|
|
logger.warning("signage: menu change not sent: %s", e)
|
|
|
|
|
|
# Added last = outermost: the request id exists before any other middleware runs.
|
|
app.add_middleware(RequestContextMiddleware)
|
|
|
|
# Product photos live in the media library (/api/media/file/..., step 5.2); the old
|
|
# data/product_images folder is left on disk untouched after Alembic 0027 copied it in.
|
|
|
|
# Serve waiter avatars as static files
|
|
AVATAR_DIR = "/app/data/avatars"
|
|
os.makedirs(AVATAR_DIR, exist_ok=True)
|
|
app.mount("/static/avatars", StaticFiles(directory=AVATAR_DIR), name="avatars")
|
|
|
|
# Routers come from the module manifests (modules/<key>/manifest.py, APPS_PLATFORM D-19).
|
|
# All are always mounted; non-core ones answer `module.disabled` while their module is off.
|
|
def _mount_module_routers(app: FastAPI) -> None:
|
|
import importlib
|
|
from fastapi import Depends
|
|
from core.modules.registry import registry
|
|
from core.modules.state import module_required
|
|
for m in registry().values():
|
|
deps = [] if m.kind == "core" else [Depends(module_required(m.key))]
|
|
for mt in m.routers:
|
|
r = getattr(importlib.import_module(mt.module), mt.attr)
|
|
app.include_router(r, prefix=mt.prefix, tags=list(mt.tags) or [m.key], dependencies=deps)
|
|
|
|
|
|
_mount_module_routers(app)
|