feat(manager): notification bell, sign-in/venue/print settings, log download (platform-v2 2.6f)
- Bell in the header: /api/platform/notifications with unread count, live via
the new LiveProvider (one createLiveClient connection) on platform_notification
and reconnect; mark read / all; warning+critical pop a toast.
- Settings: Sign-in card (manager/waiter/device modes, require username, one
session per manager/waiter, username autofill) replaces the dead v1
security.login_method card; new "Venue & language" tab (language, time zone);
print alert threshold in Printing. Tab labels are i18n keys.
- Technical > Log files: list + download of the daily logs (owner-level).
Backend: GET /api/system/logs, /api/system/logs/{date} (core.settings.manage),
error system.log_not_found.
- Setup wizard asks staff language and time zone (setup/init stores them).
- @xenia/ui theme helpers (applyTheme, getStoredTheme); the manager stays light
until phase 6 converts the older pages (owner decision 2026-11-14).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -86,6 +86,7 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
# domain
|
||||
"order.not_found": (404, "Order {order_id} not found."),
|
||||
"notification.not_found": (404, "Notification {notification_id} not found."),
|
||||
"system.log_not_found": (404, "There is no log file for {date}."),
|
||||
"catalog.unknown_category": (422, "There is no category {category_id}."),
|
||||
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
|
||||
}
|
||||
|
||||
@@ -277,3 +277,30 @@ class RequestContextMiddleware:
|
||||
lvl = logging.WARNING if (code or 500) >= 500 else logging.INFO
|
||||
_http_log.log(lvl, "http %s %s status=%s ms=%d", method, scope.get("path"), code, ms)
|
||||
_ctx.reset(token)
|
||||
|
||||
|
||||
# ── download (plan step 2.6f) ────────────────────────────────────────────────
|
||||
|
||||
def log_dir() -> Path:
|
||||
"""Where the daily files are: the active handler's folder, else the default."""
|
||||
return _file_handler.directory if _file_handler is not None else default_log_dir()
|
||||
|
||||
|
||||
def list_log_files(directory: Path | None = None) -> list[dict]:
|
||||
"""[{date, name, size}] newest first, for the manager's log download."""
|
||||
d = directory or log_dir()
|
||||
out = []
|
||||
if d.is_dir():
|
||||
for f in d.glob(f"{FILE_PREFIX}*.log"):
|
||||
m = _FILE_RE.match(f.name)
|
||||
if m:
|
||||
out.append({"date": m.group(1), "name": f.name, "size": f.stat().st_size})
|
||||
return sorted(out, key=lambda x: x["date"], reverse=True)
|
||||
|
||||
|
||||
def log_file_for(date_str: str, directory: Path | None = None) -> Path | None:
|
||||
"""The file of one UTC day, or None (bad date or no file). Only names we write."""
|
||||
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_str or ""):
|
||||
return None
|
||||
f = (directory or log_dir()) / f"{FILE_PREFIX}{date_str}.log"
|
||||
return f if f.is_file() else None
|
||||
|
||||
@@ -26,6 +26,8 @@ class SetupInitRequest(BaseModel):
|
||||
venue_type: Optional[str] = None
|
||||
venue_name: Optional[str] = None
|
||||
pin: Optional[str] = None
|
||||
language: Optional[str] = None # venue.language (2.6f): v2 defaults to English otherwise
|
||||
timezone: Optional[str] = None # venue.timezone, IANA (the browser's zone)
|
||||
|
||||
|
||||
class SetupInitResponse(BaseModel):
|
||||
@@ -81,6 +83,16 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
|
||||
if existing:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken.")
|
||||
|
||||
from core import i18n, timeutil
|
||||
from core.errors import XeniaError
|
||||
if body.language and not i18n.is_supported(body.language):
|
||||
raise XeniaError("validation.unknown_language", language=body.language)
|
||||
if body.timezone:
|
||||
try:
|
||||
timeutil.validate_tz(body.timezone)
|
||||
except ValueError:
|
||||
raise XeniaError("validation.unknown_timezone", timezone=body.timezone)
|
||||
|
||||
password_hash = bcrypt.hashpw(body.password.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
raw_pin = body.pin if (body.pin and body.pin.isdigit() and 4 <= len(body.pin) <= 6) else "0000"
|
||||
@@ -100,6 +112,19 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
|
||||
db.add(user)
|
||||
|
||||
# Persist venue settings if provided
|
||||
from models.settings import PosSettings
|
||||
|
||||
def _put(key, value):
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if row:
|
||||
row.value = value
|
||||
row.updated_at = utcnow()
|
||||
else:
|
||||
db.add(PosSettings(key=key, value=value, updated_at=utcnow()))
|
||||
if body.language:
|
||||
_put("venue.language", body.language)
|
||||
if body.timezone:
|
||||
_put("venue.timezone", body.timezone)
|
||||
if body.venue_name or body.venue_type:
|
||||
from models.settings import PosSettings
|
||||
from datetime import datetime, timezone
|
||||
@@ -120,6 +145,9 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
|
||||
db.add(PosSettings(key="venue.type", value=body.venue_type, updated_at=now))
|
||||
|
||||
db.commit()
|
||||
if body.language or body.timezone:
|
||||
i18n.invalidate()
|
||||
timeutil.invalidate()
|
||||
db.refresh(user)
|
||||
add_user_to_system_group(db, user.id)
|
||||
return SetupInitResponse(ok=True)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from core.access.deps import public
|
||||
from core.access.queries import holders_filter
|
||||
from core.access.deps import require
|
||||
import asyncio
|
||||
import ipaddress
|
||||
import json
|
||||
@@ -77,6 +78,29 @@ def _lock_reason() -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
# ── Log download (plan step 2.6f, APPS_PLATFORM §10) ───────────────────────────
|
||||
# The daily files of core/logging.py. Owner-level (core.settings.manage): lines carry
|
||||
# usernames, IPs and order ids (never secrets).
|
||||
|
||||
@router.get("/logs")
|
||||
def list_logs(user: User = Depends(require("core.settings.manage"))):
|
||||
"""[{date, name, size}] newest first (UTC days)."""
|
||||
from core.logging import list_log_files
|
||||
return list_log_files()
|
||||
|
||||
|
||||
@router.get("/logs/{date}")
|
||||
def download_log(date: str, user: User = Depends(require("core.settings.manage"))):
|
||||
"""One day's file as an attachment (today's is still being written: a snapshot)."""
|
||||
from fastapi.responses import FileResponse
|
||||
from core.errors import XeniaError
|
||||
from core.logging import log_file_for
|
||||
f = log_file_for(date)
|
||||
if f is None:
|
||||
raise XeniaError("system.log_not_found", date=date)
|
||||
return FileResponse(f, media_type="text/plain; charset=utf-8", filename=f.name)
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def system_status(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
printers = db.query(Printer).filter(Printer.is_active == True).all()
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Log download for the manager (plan step 2.6f): list + one day's file, owner-level."""
|
||||
import pytest
|
||||
|
||||
from core import logging as xlog
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def logs(tmp_path, monkeypatch):
|
||||
(tmp_path / "xenia-2026-11-13.log").write_text("2026-11-13T10:00:00.000Z INFO x [req=- user=- device=-] hello\n", encoding="utf-8")
|
||||
(tmp_path / "xenia-2026-11-14.log").write_text("today\n", encoding="utf-8")
|
||||
(tmp_path / "other.txt").write_text("not a log", encoding="utf-8")
|
||||
monkeypatch.setattr(xlog, "log_dir", lambda: tmp_path)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_list_and_download(client, make_user, login, logs):
|
||||
h = login(make_user(role="owner"))
|
||||
rows = client.get("/api/system/logs", headers=h).json()
|
||||
assert [r["date"] for r in rows] == ["2026-11-14", "2026-11-13"] and rows[1]["size"] > 10
|
||||
r = client.get("/api/system/logs/2026-11-13", headers=h)
|
||||
assert r.status_code == 200 and "hello" in r.text
|
||||
assert 'filename="xenia-2026-11-13.log"' in r.headers["content-disposition"]
|
||||
|
||||
|
||||
def test_missing_and_bad_dates(client, make_user, login, logs):
|
||||
h = login(make_user(role="owner"))
|
||||
for d in ("2026-01-01", "..%2Fpos", "x"):
|
||||
r = client.get(f"/api/system/logs/{d}", headers=h)
|
||||
assert r.status_code == 404, (d, r.text)
|
||||
assert client.get("/api/system/logs/2026-01-01", headers=h).json()["error"]["code"] == "system.log_not_found"
|
||||
|
||||
|
||||
def test_needs_settings_permission(client, make_user, login, logs):
|
||||
h = login(make_user(role="staff_manager"))
|
||||
assert client.get("/api/system/logs", headers=h).json()["error"]["code"] == "access.denied"
|
||||
@@ -0,0 +1,24 @@
|
||||
"""The setup wizard sets the venue language and time zone (plan step 2.6f)."""
|
||||
import pytest
|
||||
|
||||
from models.settings import PosSettings
|
||||
|
||||
|
||||
def _setting(db, key):
|
||||
row = db.query(PosSettings).filter_by(key=key).first()
|
||||
return row.value if row else None
|
||||
|
||||
|
||||
def test_init_sets_language_and_timezone(client, db):
|
||||
from models.user import User
|
||||
if db.query(User).count():
|
||||
pytest.skip("db has users")
|
||||
bad = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "language": "xx"})
|
||||
assert bad.json()["error"]["code"] == "validation.unknown_language"
|
||||
bad = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "timezone": "Mars/Base"})
|
||||
assert bad.json()["error"]["code"] == "validation.unknown_timezone"
|
||||
r = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "language": "el",
|
||||
"timezone": "Europe/Berlin"})
|
||||
assert r.status_code in (200, 201), r.text
|
||||
db.expire_all()
|
||||
assert _setting(db, "venue.language") == "el" and _setting(db, "venue.timezone") == "Europe/Berlin"
|
||||
Reference in New Issue
Block a user