feat: foundations for the manager conversion (platform-v2 step 6.1)
- Backend: every HTTPException in routers/ is an error code now (260 raises, ~105 new codes, texts in en + el); XeniaError(detail=...) keeps the three v1-shaped answers old pages read; bad / unknown tokens answer auth.session_ended; test_errors refuses new HTTPExceptions. - Manager: v2.json is the list of pages on the v2 rules: scripts/lint.mjs lints them, tests/v2-guards.test.mjs refuses Greek and colour literals, `strict` paths make set-state-in-effect an error. - src/live/useLiveQuery.js (react-query + live events + refresh on reconnect); Signed in now uses it. - Dead manager files removed (3.1k lines unreachable from main.jsx). - Tests: backend 544 passed, manager unit 33, run-all (no Android) passed (manager's live bell check passed on a rerun). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,8 +11,8 @@ Every error response has this shape:
|
||||
New and converted code raises XeniaError:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
The status comes from the registry below; pass status= only to override it.
|
||||
Plain HTTPException (still in most v1 routers; converted gradually, plan step 6.x)
|
||||
is wrapped as code "http.<status>" with its original `detail` untouched.
|
||||
Plain HTTPException is wrapped as code "http.<status>" with its original `detail` untouched
|
||||
(the routers have none since step 6.1; tests/test_errors.py refuses new ones).
|
||||
Request validation errors become "validation.invalid" with the field errors in params.
|
||||
Unhandled exceptions become "internal.error" (500) with the request id in params.
|
||||
|
||||
@@ -147,18 +147,129 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"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."),
|
||||
# converted from HTTPException (plan step 6.1)
|
||||
"auth.password_current_required": (400, "Enter your current password to set a new one."),
|
||||
"auth.no_password": (400, "This account has no password yet."),
|
||||
"auth.password_wrong": (400, "The current password is wrong."),
|
||||
"auth.password_too_short": (400, "The password must be at least {min} characters long."),
|
||||
"auth.pin_too_short": (400, "The PIN must be at least {min} digits long."),
|
||||
"license.locked": (423, "The system was locked by the administrator. Contact support."),
|
||||
"settings.invalid_json": (422, "The settings must be valid JSON."),
|
||||
"settings.unknown_key": (400, "There is no setting {key}."),
|
||||
"business_day.already_open": (400, "A business day is already open."),
|
||||
"business_day.none_open": (404, "No business day is open."),
|
||||
"business_day.closed": (403, "The venue isn't open: a manager must open the business day first."),
|
||||
"business_day.orders_open": (409, "{open_orders} table(s) still open, {partially_paid} with unpaid items."),
|
||||
"business_day.not_found": (404, "Business day not found."),
|
||||
"business_day.not_closed": (400, "Only a closed business day can be edited."),
|
||||
"business_day.close_in_future": (400, "The closing time can't be in the future."),
|
||||
"business_day.close_before_last_order": (400, "The closing time can't be earlier than the last order's close ({time})."),
|
||||
"business_day.delete_open": (400, "An open business day can't be deleted. Close it first."),
|
||||
"business_day.has_shifts": (409, "This business day has {count} shift(s). Delete those first."),
|
||||
"validation.datetime": (422, "That date or time isn't valid."),
|
||||
"validation.choice": (400, "{field} can't be {value}."),
|
||||
"validation.range": (400, "{field} must be between {min} and {max}."),
|
||||
"validation.positive": (400, "{field} must be more than zero."),
|
||||
"validation.missing": (400, "{field} is required."),
|
||||
"validation.lan_ip": (422, "Enter a local network IPv4 address (e.g. 192.168.1.50 or 10.0.0.5)."),
|
||||
"chat.not_found": (404, "Conversation not found."),
|
||||
"chat.not_participant": (403, "You're not in this conversation."),
|
||||
"chat.empty_message": (400, "The message is empty."),
|
||||
"chat.system_group": (403, "You can't leave the staff group."),
|
||||
"chat.leave_direct": (400, "A one-to-one conversation can't be left."),
|
||||
"chat.direct_two": (400, "A one-to-one conversation has exactly two people."),
|
||||
"chat.group_name": (400, "A group conversation needs a name."),
|
||||
"customer.not_found": (404, "Customer not found."),
|
||||
"transfer.wrong_type": (400, "This file isn't a {expected} export."),
|
||||
"transfer.version": (400, "This export's version isn't supported."),
|
||||
"contact.not_found": (404, "Contact not found."),
|
||||
"expense.not_found": (404, "Expense not found."),
|
||||
"flag.not_found": (404, "Mark not found."),
|
||||
"flag.in_use": (409, "This mark is on {count} table(s). Remove it there first."),
|
||||
"flag.invalid_ids": (400, "Some of these marks don't exist."),
|
||||
"staff_message.template_not_found": (404, "Message template not found."),
|
||||
"staff_message.not_found": (404, "Message not found."),
|
||||
"note.not_found": (404, "Note not found."),
|
||||
"todo.not_found": (404, "To-do not found."),
|
||||
"order.not_yours": (403, "This order isn't one of your tables."),
|
||||
"order.not_open": (400, "This order isn't open any more."),
|
||||
"order.item_not_found": (404, "That item isn't on the order any more."),
|
||||
"order.item_paid": (400, "This item is already paid."),
|
||||
"order.item_not_active": (400, "Only items still on the order can be changed."),
|
||||
"order.nothing_paid": (404, "There are no paid items to undo."),
|
||||
"order.cannot_close": (400, "This order can't be closed now ({status})."),
|
||||
"order.no_active_items": (400, "None of these items are on the order any more."),
|
||||
"order.waiter_assigned": (400, "That waiter is already on this order."),
|
||||
"order.assignment_not_found": (404, "That waiter isn't on this order."),
|
||||
"order.same_table": (400, "The order is already on that table."),
|
||||
"order.same_order": (400, "An order can't be joined with itself."),
|
||||
"order.target_not_found": (404, "The other order isn't there any more."),
|
||||
"order.split_quantity": (400, "Split into 1 to {max} pieces."),
|
||||
"order.discounts_off": (403, "Discounts are turned off for this venue."),
|
||||
"order.no_customer": (400, "Give the order a customer first."),
|
||||
"order.item_not_tabbable": (400, "This item is already {status}: it can't go on a tab."),
|
||||
"order.product_unavailable": (400, "Product {product_id} isn't available."),
|
||||
"printer.not_found": (404, "That printer isn't there or is turned off."),
|
||||
"print_job.not_found": (404, "That print job isn't there any more."),
|
||||
"print_job.not_pending": (400, "Only tickets still waiting to print can be cancelled."),
|
||||
"table.not_found": (404, "Table not found."),
|
||||
"table.busy": (400, "That table already has an open order."),
|
||||
"table.has_order": (400, "A table with an open order can't be deleted or turned off."),
|
||||
"table.name_too_long": (400, "The table names would be too long ({name}: at most {max} characters). Shorten the prefix or make fewer."),
|
||||
"table_group.name_taken": (400, "There is already a group with that name."),
|
||||
"table_group.not_found": (404, "Table group not found."),
|
||||
"prep_zone.not_found": (404, "Prep zone not found."),
|
||||
"price_group.not_found": (404, "Price group not found."),
|
||||
"modifier.not_found": (404, "Price rule not found."),
|
||||
"deal.not_found": (404, "Deal not found."),
|
||||
"catalog.category_not_found": (404, "Category not found."),
|
||||
"catalog.parent_not_found": (404, "The parent category doesn't exist."),
|
||||
"catalog.nest_has_children": (400, "A category with sub-categories can't go under another one."),
|
||||
"catalog.too_deep": (400, "Categories go at most two levels deep."),
|
||||
"catalog.own_parent": (400, "A category can't be its own parent."),
|
||||
"catalog.group_not_found": (404, "Option group not found."),
|
||||
"product.not_found": (404, "Product not found."),
|
||||
"product.in_past_orders": (400, "This product is in past orders, so it can't be deleted. Archive it instead."),
|
||||
"staff.not_found": (404, "Staff member not found."),
|
||||
"staff.username_taken": (409, "That username is already taken."),
|
||||
"staff.superadmin_protected": (403, "A superadmin account can't be changed."),
|
||||
"staff.superadmin_only": (403, "Only a superadmin can give the superadmin role."),
|
||||
"staff.role_invalid": (400, "There is no role {role}."),
|
||||
"staff.avatar_type": (400, "The photo must be a picture file."),
|
||||
"staff.assignment_exists": (400, "That assignment already exists."),
|
||||
"staff.assignment_not_found": (404, "Assignment not found."),
|
||||
"schedule.shift_not_found": (404, "Scheduled shift not found."),
|
||||
"setup.done": (409, "Setup is already done: a manager account exists."),
|
||||
"shift.already_active": (400, "This person already has a shift going."),
|
||||
"shift.start_needs_manager": (403, "Starting the shift needs a manager's approval."),
|
||||
"shift.end_needs_manager": (403, "Ending the shift needs a manager's approval."),
|
||||
"shift.others_need_manager": (403, "Only managers can start shifts for other staff."),
|
||||
"shift.none_active": (404, "No shift is going."),
|
||||
"shift.not_found": (404, "Shift not found."),
|
||||
"shift.not_yours": (403, "This shift belongs to someone else."),
|
||||
"shift.ended": (400, "This shift has already ended."),
|
||||
"shift.on_break": (400, "A break is already going."),
|
||||
"shift.no_break": (404, "No break is going."),
|
||||
"shift.delete_active": (400, "A shift that is still going can't be deleted. End it first."),
|
||||
"tab.not_found": (404, "Tab not found."),
|
||||
"tab.already_open": (400, "This customer already has an open tab."),
|
||||
"tab.over_balance": (400, "That's more than the balance ({balance})."),
|
||||
"tab.has_balance": (400, "The tab still owes {balance}. Pay it or forgive it first."),
|
||||
"waste.not_found": (404, "Throwaway entry not found."),
|
||||
"waste.not_today": (403, "Only throwaways of the open business day can be deleted."),
|
||||
}
|
||||
|
||||
|
||||
class XeniaError(Exception):
|
||||
"""An API error with a registered code. raise XeniaError("order.not_found", order_id=5)."""
|
||||
|
||||
def __init__(self, code: str, status: int | None = None, **params):
|
||||
def __init__(self, code: str, status: int | None = None, *, detail=None, **params):
|
||||
if code not in CODES:
|
||||
raise KeyError(f"unregistered error code {code!r}: add it to core/errors.py CODES")
|
||||
default_status, template = CODES[code]
|
||||
self.code = code
|
||||
self.status = status or default_status
|
||||
self.detail = detail # v1-shaped `detail` some old pages still read (6.x removes)
|
||||
self.params = params
|
||||
try:
|
||||
self.message = template.format(**params)
|
||||
@@ -173,7 +284,7 @@ def error_body(code: str, message: str, params: dict | None = None, detail=None)
|
||||
|
||||
|
||||
async def _xenia_error_handler(request: Request, exc: XeniaError):
|
||||
return JSONResponse(error_body(exc.code, exc.message, exc.params), status_code=exc.status)
|
||||
return JSONResponse(error_body(exc.code, exc.message, exc.params, detail=exc.detail), status_code=exc.status)
|
||||
|
||||
|
||||
async def _http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
|
||||
@@ -7,7 +7,7 @@ import threading
|
||||
from typing import Optional
|
||||
|
||||
import jwt
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from fastapi import APIRouter, Depends, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -369,26 +369,26 @@ def update_me(body: UpdateMeRequest, db: Session = Depends(get_db), user: User =
|
||||
# Password change — requires current_password verification
|
||||
if body.new_password is not None:
|
||||
if not body.current_password:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="current_password is required to set a new password")
|
||||
raise XeniaError("auth.password_current_required")
|
||||
if not user.password_hash:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Account has no password set")
|
||||
raise XeniaError("auth.no_password")
|
||||
if not bcrypt.checkpw(body.current_password.encode(), user.password_hash.encode()):
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Current password is incorrect")
|
||||
raise XeniaError("auth.password_wrong")
|
||||
if len(body.new_password) < 6:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="New password must be at least 6 characters")
|
||||
raise XeniaError("auth.password_too_short", min=6)
|
||||
user.password_hash = bcrypt.hashpw(body.new_password.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
# PIN change — no current PIN required (already authenticated)
|
||||
if body.new_pin is not None:
|
||||
if len(body.new_pin) < 4:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="PIN must be at least 4 digits")
|
||||
raise XeniaError("auth.pin_too_short", min=4)
|
||||
user.pin_hash = bcrypt.hashpw(body.new_pin.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
# Username change — check uniqueness
|
||||
if body.username is not None and body.username != user.username:
|
||||
conflict = db.query(User).filter(User.username == body.username, User.id != user.id).first()
|
||||
if conflict:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken")
|
||||
raise XeniaError("staff.username_taken")
|
||||
user.username = body.username
|
||||
|
||||
# Display name
|
||||
@@ -421,7 +421,7 @@ def put_my_settings(body: WaiterSettingsPayload, db: Session = Depends(get_db),
|
||||
try:
|
||||
_json.loads(body.settings) # validate it's valid JSON
|
||||
except Exception:
|
||||
raise HTTPException(status_code=422, detail="settings must be valid JSON")
|
||||
raise XeniaError("settings.invalid_json")
|
||||
user.waiter_settings = body.settings
|
||||
db.commit()
|
||||
return {"settings": user.waiter_settings}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from core.timeutil import business_date_of, parse_api_datetime, utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
@@ -18,6 +18,7 @@ from schemas.business_day import BusinessDayOut, OpenBusinessDayRequest, CloseBu
|
||||
from routers.deps import get_current_user, require_manager
|
||||
from models.user import User
|
||||
from services.license_state import license_state
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -44,29 +45,23 @@ def open_business_day(
|
||||
):
|
||||
existing = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="A business day is already open")
|
||||
raise XeniaError("business_day.already_open")
|
||||
|
||||
# Gate: admin lock (already enforced or pending)
|
||||
if license_state.get("locked") or license_state.get("lock_pending"):
|
||||
raise HTTPException(
|
||||
status_code=423,
|
||||
detail={
|
||||
raise XeniaError("license.locked", detail={
|
||||
"code": "SYSTEM_LOCKED",
|
||||
"message": "Το σύστημα έχει κλειδωθεί από διαχειριστή. Επικοινωνήστε με την υποστήριξη.",
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
# Gate: license expired and expiry grace period also over
|
||||
if not license_state.get("licensed", True):
|
||||
expires_at = license_state.get("expires_at", "")
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
raise XeniaError("license.expired", detail={
|
||||
"code": "LICENSE_EXPIRED",
|
||||
"message": "Η άδεια χρήσης έχει λήξει. Ανανεώστε την άδεια ή επικοινωνήστε με την υποστήριξη.",
|
||||
"expires_at": expires_at,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
opened_at = utcnow()
|
||||
day = BusinessDay(opened_by_id=user.id, notes=body.notes,
|
||||
@@ -85,7 +80,7 @@ def close_business_day(
|
||||
):
|
||||
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if not day:
|
||||
raise HTTPException(status_code=404, detail="No open business day")
|
||||
raise XeniaError("business_day.none_open")
|
||||
|
||||
open_orders = db.query(Order).filter(
|
||||
Order.business_day_id == day.id,
|
||||
@@ -102,14 +97,11 @@ def close_business_day(
|
||||
OrderItem.status == "active",
|
||||
).first() is not None
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={
|
||||
raise XeniaError("business_day.orders_open", detail={
|
||||
"message": f"{len(open_orders)} table(s) still open, {with_pending} with unpaid items.",
|
||||
"open_orders": len(open_orders),
|
||||
"partially_paid": with_pending,
|
||||
},
|
||||
)
|
||||
}, open_orders=len(open_orders), partially_paid=with_pending)
|
||||
|
||||
now = utcnow()
|
||||
|
||||
@@ -195,18 +187,18 @@ def patch_business_day(
|
||||
"""
|
||||
day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first()
|
||||
if not day:
|
||||
raise HTTPException(status_code=404, detail="Business day not found")
|
||||
raise XeniaError("business_day.not_found")
|
||||
if day.status != "closed":
|
||||
raise HTTPException(status_code=400, detail="Can only edit a closed business day")
|
||||
raise XeniaError("business_day.not_closed")
|
||||
|
||||
try:
|
||||
new_closed = parse_api_datetime(body.closed_at)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(status_code=422, detail="Invalid datetime format")
|
||||
raise XeniaError("validation.datetime")
|
||||
|
||||
now = utcnow()
|
||||
if new_closed > now:
|
||||
raise HTTPException(status_code=400, detail="Close time cannot be in the future")
|
||||
raise XeniaError("business_day.close_in_future")
|
||||
|
||||
# Must not be earlier than the latest order closed_at in this day
|
||||
last_order_close = (
|
||||
@@ -218,10 +210,7 @@ def patch_business_day(
|
||||
if last_order_close.tzinfo is None:
|
||||
last_order_close = last_order_close.replace(tzinfo=timezone.utc)
|
||||
if new_closed < last_order_close:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Close time cannot be earlier than the last order's close time ({_dt(last_order_close)})"
|
||||
)
|
||||
raise XeniaError("business_day.close_before_last_order", time=_dt(last_order_close))
|
||||
|
||||
day.closed_at = new_closed
|
||||
db.commit()
|
||||
@@ -237,16 +226,13 @@ def delete_business_day(
|
||||
"""Permanently delete a business day. Only allowed when it has no shifts."""
|
||||
day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first()
|
||||
if not day:
|
||||
raise HTTPException(status_code=404, detail="Business day not found")
|
||||
raise XeniaError("business_day.not_found")
|
||||
if day.status == "open":
|
||||
raise HTTPException(status_code=400, detail="Cannot delete an open business day — close it first")
|
||||
raise XeniaError("business_day.delete_open")
|
||||
|
||||
shift_count = db.query(WaiterShift).filter(WaiterShift.business_day_id == day_id).count()
|
||||
if shift_count > 0:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"Δεν είναι δυνατή η διαγραφή: η εργάσιμη μέρα έχει {shift_count} βάρδια/ες. Διαγράψτε πρώτα όλες τις βάρδιες.",
|
||||
)
|
||||
raise XeniaError("business_day.has_shifts", count=shift_count)
|
||||
|
||||
db.query(Order).filter(Order.business_day_id == day_id).update(
|
||||
{"business_day_id": None}, synchronize_session=False
|
||||
@@ -266,11 +252,11 @@ def business_day_summary(
|
||||
if day_id:
|
||||
day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first()
|
||||
if not day:
|
||||
raise HTTPException(status_code=404, detail="Business day not found")
|
||||
raise XeniaError("business_day.not_found")
|
||||
else:
|
||||
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if not day:
|
||||
raise HTTPException(status_code=404, detail="No open business day")
|
||||
raise XeniaError("business_day.none_open")
|
||||
|
||||
orders = db.query(Order).filter(Order.business_day_id == day.id).all()
|
||||
order_ids = [o.id for o in orders]
|
||||
|
||||
@@ -5,7 +5,7 @@ from core.timeutil import utcnow
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from fastapi import APIRouter, Depends, Query, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from database import get_db
|
||||
@@ -21,6 +21,7 @@ from schemas.chat import (
|
||||
ParticipantOut,
|
||||
)
|
||||
from services.ws_bus import broadcast_sync
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -117,10 +118,10 @@ def _require_participant(db: Session, conv_id: int, user: User) -> Conversation:
|
||||
"""Return the conversation if user is a participant, else 403/404."""
|
||||
conv = db.query(Conversation).filter(Conversation.id == conv_id).first()
|
||||
if not conv:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found")
|
||||
raise XeniaError("chat.not_found")
|
||||
is_participant = any(p.user_id == user.id for p in conv.participants)
|
||||
if not is_participant:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not a participant")
|
||||
raise XeniaError("chat.not_participant")
|
||||
return conv
|
||||
|
||||
|
||||
@@ -180,10 +181,7 @@ def create_conversation(
|
||||
|
||||
if payload.type == "direct":
|
||||
if len(participant_ids) != 2:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Direct conversations must have exactly 2 participants",
|
||||
)
|
||||
raise XeniaError("chat.direct_two")
|
||||
other_id = next(pid for pid in participant_ids if pid != user.id)
|
||||
|
||||
# Check for an existing non-system direct conversation between these two users
|
||||
@@ -215,15 +213,9 @@ def create_conversation(
|
||||
|
||||
elif payload.type == "group":
|
||||
if not payload.name:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Group conversations require a name",
|
||||
)
|
||||
raise XeniaError("chat.group_name")
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="type must be 'direct' or 'group'",
|
||||
)
|
||||
raise XeniaError("validation.choice", field='type', value=payload.type)
|
||||
|
||||
# Create the conversation
|
||||
conv = Conversation(
|
||||
@@ -292,10 +284,7 @@ def send_message(
|
||||
conv = _require_participant(db, conv_id, user)
|
||||
|
||||
if not payload.body.strip():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Message body cannot be empty",
|
||||
)
|
||||
raise XeniaError("chat.empty_message")
|
||||
|
||||
msg = ChatMessage(
|
||||
conversation_id=conv_id,
|
||||
@@ -372,15 +361,9 @@ def leave_conversation(
|
||||
conv = _require_participant(db, conv_id, user)
|
||||
|
||||
if conv.is_system:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Cannot leave the system group conversation",
|
||||
)
|
||||
raise XeniaError("chat.system_group")
|
||||
if conv.type == "direct":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot leave a direct conversation — just stop using it",
|
||||
)
|
||||
raise XeniaError("chat.leave_direct")
|
||||
|
||||
participant = (
|
||||
db.query(ConversationParticipant)
|
||||
|
||||
@@ -27,7 +27,7 @@ import logging
|
||||
from typing import Literal, Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session, selectinload
|
||||
|
||||
@@ -174,7 +174,7 @@ def get_orders_by_status(status: str, db: Session = Depends(get_db), user=Depend
|
||||
if status == "history":
|
||||
return (db.query(Order).filter(Order.source == "online", Order.online_status.in_(FINISHED))
|
||||
.order_by(Order.opened_at.desc()).limit(50).all())
|
||||
raise HTTPException(status_code=400, detail=f"Unknown status filter '{status}'. Use 'active' or 'history'.")
|
||||
raise XeniaError("validation.choice", field='status', value=status)
|
||||
|
||||
|
||||
@router.get("/orders/incoming", response_model=list[OrderOut])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from fastapi import APIRouter, Depends, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
@@ -9,6 +9,7 @@ from models.user import User
|
||||
from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest
|
||||
from core.access.deps import require_any
|
||||
from routers.deps import require_manager, get_current_user
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -81,7 +82,7 @@ def lookup_customer(phone: str = Query(..., max_length=40), db: Session = Depend
|
||||
def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
c = db.query(Customer).filter(Customer.id == customer_id).first()
|
||||
if not c:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
raise XeniaError("customer.not_found")
|
||||
return _customer_out(c, db)
|
||||
|
||||
|
||||
@@ -89,7 +90,7 @@ def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = D
|
||||
def update_customer(customer_id: int, body: CustomerUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
c = db.query(Customer).filter(Customer.id == customer_id).first()
|
||||
if not c:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
raise XeniaError("customer.not_found")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(c, field, value)
|
||||
db.commit()
|
||||
@@ -101,7 +102,7 @@ def update_customer(customer_id: int, body: CustomerUpdate, db: Session = Depend
|
||||
def delete_customer(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
c = db.query(Customer).filter(Customer.id == customer_id).first()
|
||||
if not c:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
raise XeniaError("customer.not_found")
|
||||
c.is_active = False
|
||||
db.commit()
|
||||
|
||||
@@ -110,7 +111,7 @@ def delete_customer(customer_id: int, db: Session = Depends(get_db), user: User
|
||||
def customer_orders(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
c = db.query(Customer).filter(Customer.id == customer_id).first()
|
||||
if not c:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
raise XeniaError("customer.not_found")
|
||||
from models.table import Table
|
||||
orders = db.query(Order).filter(Order.customer_id == customer_id).order_by(Order.opened_at.desc()).all()
|
||||
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
|
||||
@@ -2,7 +2,7 @@ from core.timeutil import venue_date, utcnow
|
||||
import json
|
||||
from core import sales_points
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -14,6 +14,7 @@ from models.product import (
|
||||
from models.table import Table, TableGroup
|
||||
from models.user import User
|
||||
from routers.deps import require_manager
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -146,9 +147,9 @@ def export_tables(db: Session = Depends(get_db), user: User = Depends(require_ma
|
||||
@router.post("/import/catalog")
|
||||
def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
if payload.get("bundle") != "catalog":
|
||||
raise HTTPException(status_code=400, detail="Wrong bundle type. Expected 'catalog'.")
|
||||
raise XeniaError("transfer.wrong_type", expected='catalog')
|
||||
if payload.get("xenia_export_version", 0) != CATALOG_EXPORT_VERSION:
|
||||
raise HTTPException(status_code=400, detail="Unsupported export version.")
|
||||
raise XeniaError("transfer.version")
|
||||
|
||||
data = payload.get("data", {})
|
||||
categories_data = data.get("categories", [])
|
||||
@@ -299,9 +300,9 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
@router.post("/import/tables")
|
||||
def import_tables(payload: dict, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
if payload.get("bundle") != "tables":
|
||||
raise HTTPException(status_code=400, detail="Wrong bundle type. Expected 'tables'.")
|
||||
raise XeniaError("transfer.wrong_type", expected='tables')
|
||||
if payload.get("xenia_export_version", 0) != EXPORT_VERSION:
|
||||
raise HTTPException(status_code=400, detail="Unsupported export version.")
|
||||
raise XeniaError("transfer.version")
|
||||
|
||||
data = payload.get("data", {})
|
||||
for group_data in data.get("table_groups", []):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from core.timeutil import utcnow
|
||||
import jwt
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from fastapi import Depends, Request, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -67,7 +67,7 @@ def decode_session(token: str, db: Session | None = None):
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise XeniaError("auth.session_ended")
|
||||
except jwt.InvalidTokenError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
raise XeniaError("auth.session_ended")
|
||||
return payload, sessions.validate(payload.get("sid"), db)
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ def user_from_token(token: str, request: Request, db: Session):
|
||||
return make_support_user(), payload.get("sid")
|
||||
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
||||
raise XeniaError("auth.session_ended")
|
||||
set_log_context(user=user.id)
|
||||
return user, payload.get("sid")
|
||||
|
||||
@@ -115,6 +115,7 @@ get_current_user.__xenia_access__ = ("signed_in",)
|
||||
# Kept as aliases so the ~200 existing route signatures stay as they are. New code
|
||||
# uses core.access.deps.require("<key>") directly.
|
||||
from core.access.deps import require # noqa: E402
|
||||
from core.errors import XeniaError
|
||||
|
||||
require_manager = require("core.dashboard.access")
|
||||
require_staff_manager = require("core.staff.manage")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from core.timeutil import utcnow
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from fastapi import APIRouter, Depends, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
@@ -13,6 +13,7 @@ from schemas.expenses import (
|
||||
ExpensePaymentCreate, ExpensePaymentOut,
|
||||
)
|
||||
from routers.deps import require_manager
|
||||
from core.errors import XeniaError
|
||||
|
||||
contacts_router = APIRouter()
|
||||
expenses_router = APIRouter()
|
||||
@@ -97,7 +98,7 @@ def create_contact(body: ContactCreate, db: Session = Depends(get_db), user: Use
|
||||
def update_contact(contact_id: int, body: ContactUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
contact = db.query(Contact).filter(Contact.id == contact_id).first()
|
||||
if not contact:
|
||||
raise HTTPException(status_code=404, detail="Contact not found")
|
||||
raise XeniaError("contact.not_found")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(contact, field, value)
|
||||
db.commit()
|
||||
@@ -109,7 +110,7 @@ def update_contact(contact_id: int, body: ContactUpdate, db: Session = Depends(g
|
||||
def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
contact = db.query(Contact).filter(Contact.id == contact_id).first()
|
||||
if not contact:
|
||||
raise HTTPException(status_code=404, detail="Contact not found")
|
||||
raise XeniaError("contact.not_found")
|
||||
contact.is_active = False
|
||||
db.commit()
|
||||
|
||||
@@ -174,7 +175,7 @@ def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: Use
|
||||
def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
expense = db.query(Expense).filter(Expense.id == expense_id).first()
|
||||
if not expense:
|
||||
raise HTTPException(status_code=404, detail="Expense not found")
|
||||
raise XeniaError("expense.not_found")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(expense, field, value)
|
||||
db.commit()
|
||||
@@ -186,7 +187,7 @@ def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(g
|
||||
def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
expense = db.query(Expense).filter(Expense.id == expense_id).first()
|
||||
if not expense:
|
||||
raise HTTPException(status_code=404, detail="Expense not found")
|
||||
raise XeniaError("expense.not_found")
|
||||
db.delete(expense)
|
||||
db.commit()
|
||||
|
||||
@@ -200,9 +201,9 @@ def record_payment(
|
||||
):
|
||||
expense = db.query(Expense).filter(Expense.id == expense_id).first()
|
||||
if not expense:
|
||||
raise HTTPException(status_code=404, detail="Expense not found")
|
||||
raise XeniaError("expense.not_found")
|
||||
if body.amount <= 0:
|
||||
raise HTTPException(status_code=400, detail="Payment amount must be positive")
|
||||
raise XeniaError("validation.positive", field='amount')
|
||||
payment = ExpensePayment(
|
||||
expense_id=expense_id,
|
||||
amount=body.amount,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
|
||||
@@ -8,6 +8,7 @@ from schemas.flag import FlagDefCreate, FlagDefUpdate, FlagDefOut, FlagAssignmen
|
||||
from routers.deps import get_current_user, require_manager
|
||||
from models.user import User
|
||||
from services.ws_bus import broadcast_sync
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -48,7 +49,7 @@ def update_flag_def(
|
||||
):
|
||||
flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first()
|
||||
if not flag:
|
||||
raise HTTPException(status_code=404, detail="Flag not found")
|
||||
raise XeniaError("flag.not_found")
|
||||
for k, v in body.model_dump(exclude_unset=True).items():
|
||||
setattr(flag, k, v)
|
||||
db.commit()
|
||||
@@ -64,7 +65,7 @@ def toggle_flag_active(
|
||||
):
|
||||
flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first()
|
||||
if not flag:
|
||||
raise HTTPException(status_code=404, detail="Flag not found")
|
||||
raise XeniaError("flag.not_found")
|
||||
flag.is_active = not flag.is_active
|
||||
db.commit()
|
||||
db.refresh(flag)
|
||||
@@ -79,13 +80,10 @@ def delete_flag_def(
|
||||
):
|
||||
flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first()
|
||||
if not flag:
|
||||
raise HTTPException(status_code=404, detail="Flag not found")
|
||||
raise XeniaError("flag.not_found")
|
||||
in_use = db.query(TableFlagAssignment).filter(TableFlagAssignment.flag_id == flag_id).count()
|
||||
if in_use:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Η σήμανση χρησιμοποιείται σε {in_use} τραπέζι{'α' if in_use != 1 else ''}. Αφαιρέστε την πρώτα.",
|
||||
)
|
||||
raise XeniaError("flag.in_use", count=in_use)
|
||||
db.delete(flag)
|
||||
db.commit()
|
||||
|
||||
@@ -129,7 +127,7 @@ def set_table_flags(
|
||||
TableFlagDef.is_active == True,
|
||||
).count()
|
||||
if valid != len(body.flag_ids):
|
||||
raise HTTPException(status_code=400, detail="One or more flag IDs are invalid")
|
||||
raise XeniaError("flag.invalid_ids")
|
||||
|
||||
# Delete existing assignments for this table
|
||||
db.query(TableFlagAssignment).filter(
|
||||
|
||||
@@ -40,7 +40,7 @@ from core.access.queries import holders_filter
|
||||
from core.errors import XeniaError
|
||||
from core.timeutil import utcnow
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from pydantic import BaseModel
|
||||
@@ -367,11 +367,11 @@ def update_order_kds_status(
|
||||
kitchen screen with a prep zone only that zone's items change (3.2c), and the order's
|
||||
status then follows all its items."""
|
||||
if body.status not in VALID_KDS_STATUSES:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid status '{body.status}'")
|
||||
raise XeniaError("validation.choice", field='status', value=body.status)
|
||||
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
zone_id = _device_zone_id(request, db)
|
||||
if body.status != order.kds_status and zone_id is None:
|
||||
@@ -410,14 +410,14 @@ def update_item_kds_status(
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if body.status not in VALID_KDS_STATUSES:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid status '{body.status}'")
|
||||
raise XeniaError("validation.choice", field='status', value=body.status)
|
||||
|
||||
item = db.query(OrderItem).filter(
|
||||
OrderItem.id == item_id,
|
||||
OrderItem.order_id == order_id,
|
||||
).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
raise XeniaError("order.item_not_found")
|
||||
|
||||
item.kds_status = body.status
|
||||
|
||||
@@ -451,11 +451,11 @@ def update_order_type(
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if body.order_type not in VALID_ORDER_TYPES:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid order_type '{body.order_type}'")
|
||||
raise XeniaError("validation.choice", field='order_type', value=body.order_type)
|
||||
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
order.order_type = body.order_type
|
||||
db.commit()
|
||||
@@ -477,7 +477,7 @@ def mark_items_served(
|
||||
"""Mark a list of items as served (kds_status=served). Works on active and paid items."""
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
updated = []
|
||||
ids_set = set(body.item_ids)
|
||||
@@ -507,7 +507,7 @@ def mark_all_items_served(
|
||||
"""Mark all non-pending items in an order as served."""
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
updated = []
|
||||
for item in order.items:
|
||||
@@ -591,7 +591,7 @@ def decline_order(
|
||||
"""Mark all active items on an order as declined."""
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
zone_id = _device_zone_id(request, db) # a zone screen declines only its own items (3.2c)
|
||||
for item in order.items:
|
||||
@@ -628,7 +628,7 @@ def decline_item(
|
||||
OrderItem.order_id == order_id,
|
||||
).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
raise XeniaError("order.item_not_found")
|
||||
|
||||
item.kds_status = "declined"
|
||||
item.decline_note = body.decline_note
|
||||
@@ -717,7 +717,7 @@ def kds_notify_order_complete(
|
||||
joinedload(Order.waiters),
|
||||
).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
waiter_ids = _waiter_ids_for_order(order)
|
||||
if not waiter_ids:
|
||||
@@ -758,7 +758,7 @@ def kds_notify_items_ready(
|
||||
joinedload(Order.waiters),
|
||||
).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
waiter_ids = _waiter_ids_for_order(order)
|
||||
if not waiter_ids:
|
||||
@@ -793,7 +793,7 @@ def kds_call_waiter_order(
|
||||
joinedload(Order.waiters),
|
||||
).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
waiter_ids = _waiter_ids_for_order(order)
|
||||
if not waiter_ids:
|
||||
@@ -824,7 +824,7 @@ def kds_call_waiter_general(
|
||||
):
|
||||
"""Call one or more on-shift waiters to the prep zone."""
|
||||
if not body.waiter_ids:
|
||||
raise HTTPException(status_code=400, detail="waiter_ids must not be empty")
|
||||
raise XeniaError("validation.missing", field='waiter_ids')
|
||||
|
||||
zone = _sender(request, db, body.kds_zone)
|
||||
msg_body = f"Κλήση από {zone}"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from typing import List
|
||||
|
||||
@@ -12,6 +12,7 @@ from schemas.message import (
|
||||
)
|
||||
from routers.deps import get_current_user, require_manager
|
||||
from services.ws_bus import broadcast_sync
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -78,7 +79,7 @@ def update_template(
|
||||
):
|
||||
t = db.query(QuickMessageTemplate).filter(QuickMessageTemplate.id == template_id).first()
|
||||
if not t:
|
||||
raise HTTPException(status_code=404, detail="Template not found")
|
||||
raise XeniaError("staff_message.template_not_found")
|
||||
for k, v in body.model_dump(exclude_unset=True).items():
|
||||
setattr(t, k, v)
|
||||
db.commit()
|
||||
@@ -94,7 +95,7 @@ def delete_template(
|
||||
):
|
||||
t = db.query(QuickMessageTemplate).filter(QuickMessageTemplate.id == template_id).first()
|
||||
if not t:
|
||||
raise HTTPException(status_code=404, detail="Template not found")
|
||||
raise XeniaError("staff_message.template_not_found")
|
||||
t.is_active = False
|
||||
db.commit()
|
||||
|
||||
@@ -194,7 +195,7 @@ def ack_message(
|
||||
):
|
||||
msg = db.query(StaffMessage).filter(StaffMessage.id == message_id).first()
|
||||
if not msg:
|
||||
raise HTTPException(status_code=404, detail="Message not found")
|
||||
raise XeniaError("staff_message.not_found")
|
||||
existing = db.query(StaffMessageAck).filter(
|
||||
StaffMessageAck.message_id == message_id,
|
||||
StaffMessageAck.waiter_id == user.id,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from core.timeutil import utcnow
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
|
||||
@@ -9,6 +9,7 @@ from models.notes import SiteNote, SiteTodo
|
||||
from models.user import User
|
||||
from schemas.notes import NoteCreate, NoteUpdate, NoteOut, TodoCreate, TodoUpdate, TodoOut
|
||||
from routers.deps import require_manager
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -74,7 +75,7 @@ def create_note(body: NoteCreate, db: Session = Depends(get_db), user: User = De
|
||||
def update_note(note_id: int, body: NoteUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
note = db.query(SiteNote).filter(SiteNote.id == note_id).first()
|
||||
if not note:
|
||||
raise HTTPException(status_code=404, detail="Note not found")
|
||||
raise XeniaError("note.not_found")
|
||||
if body.body is not None:
|
||||
note.body = body.body
|
||||
if body.is_pinned is not None:
|
||||
@@ -89,7 +90,7 @@ def update_note(note_id: int, body: NoteUpdate, db: Session = Depends(get_db), u
|
||||
def delete_note(note_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
note = db.query(SiteNote).filter(SiteNote.id == note_id).first()
|
||||
if not note:
|
||||
raise HTTPException(status_code=404, detail="Note not found")
|
||||
raise XeniaError("note.not_found")
|
||||
db.delete(note)
|
||||
db.commit()
|
||||
|
||||
@@ -123,7 +124,7 @@ def create_todo(body: TodoCreate, db: Session = Depends(get_db), user: User = De
|
||||
def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first()
|
||||
if not todo:
|
||||
raise HTTPException(status_code=404, detail="Todo not found")
|
||||
raise XeniaError("todo.not_found")
|
||||
if body.body is not None:
|
||||
todo.body = body.body
|
||||
if body.priority is not None:
|
||||
@@ -145,6 +146,6 @@ def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), u
|
||||
def delete_todo(todo_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first()
|
||||
if not todo:
|
||||
raise HTTPException(status_code=404, detail="Todo not found")
|
||||
raise XeniaError("todo.not_found")
|
||||
db.delete(todo)
|
||||
db.commit()
|
||||
|
||||
@@ -3,7 +3,7 @@ from core.errors import XeniaError
|
||||
from core.timeutil import parse_api_datetime, venue_strftime, utcnow
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status, BackgroundTasks
|
||||
from fastapi import APIRouter, Depends, Request, status, BackgroundTasks
|
||||
from core.access.override import require_override
|
||||
from core.access.context import authorize
|
||||
|
||||
@@ -333,7 +333,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
# Resolve all user IDs referenced by this order in one query
|
||||
user_ids = set()
|
||||
@@ -442,11 +442,11 @@ def open_order(body: OrderCreate, db: Session = Depends(get_db), user: User = De
|
||||
from models.shift import WaiterShift
|
||||
|
||||
if not (holds(user, "core.dashboard.access") or holds(user, "ordering.orders.open")):
|
||||
raise HTTPException(status_code=403, detail="Δεν έχετε δικαίωμα ανοίγματος παραγγελιών")
|
||||
raise XeniaError("access.denied", key='ordering.orders.open')
|
||||
|
||||
active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if not active_day:
|
||||
raise HTTPException(status_code=403, detail="Restaurant is not open — manager must open the business day first")
|
||||
raise XeniaError("business_day.closed")
|
||||
|
||||
if holds(user, "waiter_app.access") and not holds(user, "core.dashboard.access"):
|
||||
active_shift = db.query(WaiterShift).filter(
|
||||
@@ -454,11 +454,11 @@ def open_order(body: OrderCreate, db: Session = Depends(get_db), user: User = De
|
||||
WaiterShift.ended_at == None,
|
||||
).first()
|
||||
if not active_shift:
|
||||
raise HTTPException(status_code=403, detail="You do not have an active shift")
|
||||
raise XeniaError("pos.shift_required", status=403)
|
||||
|
||||
order_type = body.order_type or "here"
|
||||
if order_type not in ("here", "takeaway", "delivery"):
|
||||
raise HTTPException(status_code=400, detail="Invalid order_type")
|
||||
raise XeniaError("validation.choice", field='order_type', value=order_type)
|
||||
|
||||
if body.table_id is not None:
|
||||
existing = db.query(Order).filter(
|
||||
@@ -466,7 +466,7 @@ def open_order(body: OrderCreate, db: Session = Depends(get_db), user: User = De
|
||||
Order.status.in_(["open", "partially_paid", "paid"]),
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Table already has an open order")
|
||||
raise XeniaError("table.busy")
|
||||
|
||||
from core.sales_points import for_order
|
||||
order = Order(table_id=body.table_id, order_type=order_type, opened_by=user.id, business_day_id=active_day.id,
|
||||
@@ -566,7 +566,7 @@ def quote_lines(body: QuoteRequest, db: Session = Depends(get_db), user: User =
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=body.order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
existing, order_type, point = pos_cart.order_cart(order), order.order_type or "here", of_order(order)
|
||||
lines, manual = _resolve_lines(db, body.lines, point)
|
||||
try:
|
||||
@@ -594,7 +594,7 @@ def add_items(order_id: int, body: AddLinesRequest, request: Request, db: Sessio
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
lines, manual = _resolve_lines(db, body.lines, of_order(order))
|
||||
approval = None
|
||||
if any(manual) or any(line.discount_pct for line in lines):
|
||||
@@ -628,9 +628,9 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
if order.status not in ("open", "partially_paid", "paid"):
|
||||
raise HTTPException(status_code=400, detail="Order is not open")
|
||||
raise XeniaError("order.not_open")
|
||||
|
||||
# Adding items to a fully-paid order reopens it — partially_paid since prior items were paid
|
||||
if order.status == "paid":
|
||||
@@ -653,7 +653,7 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
|
||||
for item_in in body.items:
|
||||
product = db.query(Product).filter(Product.id == item_in.product_id).first()
|
||||
if not product or not product.is_available:
|
||||
raise HTTPException(status_code=400, detail=f"Product {item_in.product_id} not available")
|
||||
raise XeniaError("order.product_unavailable", product_id=item_in.product_id)
|
||||
if not is_sold_at(product, order_channel):
|
||||
raise XeniaError("order.not_sold_here", name=product.name)
|
||||
|
||||
@@ -863,7 +863,7 @@ def retry_print(
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
unprinted_ids = [item.id for item in order.items if not item.printed and item.status == "active"]
|
||||
if not unprinted_ids:
|
||||
@@ -878,7 +878,7 @@ def retry_print(
|
||||
def edit_item(order_id: int, item_id: int, notes: Optional[str] = None, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
raise XeniaError("order.item_not_found")
|
||||
if notes is not None:
|
||||
item.notes = notes
|
||||
db.commit()
|
||||
@@ -902,7 +902,7 @@ def cancel_item(
|
||||
|
||||
is_manager = holds(user, "core.dashboard.access")
|
||||
if not is_manager and not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
approval = None
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
# a manager may approve this one cancellation with their PIN (D-10)
|
||||
@@ -910,9 +910,9 @@ def cancel_item(
|
||||
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
raise XeniaError("order.item_not_found")
|
||||
if item.status == "paid":
|
||||
raise HTTPException(status_code=400, detail="Το αντικείμενο έχει ήδη πληρωθεί")
|
||||
raise XeniaError("order.item_paid")
|
||||
|
||||
now = utcnow()
|
||||
item.status = "cancelled"
|
||||
@@ -949,7 +949,7 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
_need(request, db, user, "ordering.orders.close", target=f"order:{order_id}")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
from models.shift import WaiterShift
|
||||
from services.fiscal import (
|
||||
@@ -969,10 +969,7 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
|
||||
missing = validate_items_for_fiscal(items, db)
|
||||
if missing:
|
||||
names = ", ".join(missing)
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail=f"Fiscal printing is ON but the following products have no VAT group assigned: {names}"
|
||||
)
|
||||
raise XeniaError("pos.fiscal_vat_missing", names=names)
|
||||
|
||||
now = utcnow()
|
||||
active_shift = db.query(WaiterShift).filter(
|
||||
@@ -1042,7 +1039,7 @@ def revert_payment(order_id: int, body: RevertPaymentRequest, request: Request,
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
# ordering.payments.revert (owners, store managers); others with a manager's PIN (4.3)
|
||||
approval = _need(request, db, user, "ordering.payments.revert", target=f"order:{order_id}")
|
||||
|
||||
@@ -1053,7 +1050,7 @@ def revert_payment(order_id: int, body: RevertPaymentRequest, request: Request,
|
||||
).all()
|
||||
|
||||
if not items:
|
||||
raise HTTPException(status_code=404, detail="No paid items found to revert")
|
||||
raise XeniaError("order.nothing_paid")
|
||||
|
||||
reverted_ids = []
|
||||
for item in items:
|
||||
@@ -1090,9 +1087,9 @@ def close_order(order_id: int, request: Request, db: Session = Depends(get_db),
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
_need(request, db, user, "ordering.orders.close", target=f"order:{order_id}")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
if order.status not in ("paid", "open", "partially_paid"):
|
||||
raise HTTPException(status_code=400, detail="Cannot close order in current status")
|
||||
raise XeniaError("order.cannot_close", status=order.status)
|
||||
|
||||
now = utcnow()
|
||||
|
||||
@@ -1149,7 +1146,7 @@ def pay_items_offline(
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
# Check for duplicate UUID on this order
|
||||
existing_uuid = db.query(OrderAuditLog).filter(
|
||||
@@ -1167,7 +1164,7 @@ def pay_items_offline(
|
||||
|
||||
# Reject empty payments — client had no offline snapshot for this table
|
||||
if not items and not is_duplicate:
|
||||
raise HTTPException(status_code=400, detail="No active items found — payment rejected")
|
||||
raise XeniaError("order.no_active_items")
|
||||
|
||||
# Use the client-recorded offline timestamp as paid_at so audit reflects real payment time
|
||||
try:
|
||||
@@ -1244,7 +1241,7 @@ def cancel_order(
|
||||
|
||||
is_manager = holds(user, "core.dashboard.access")
|
||||
if not is_manager and not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
approval = None
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
# a manager may approve this one cancellation with their PIN (D-10)
|
||||
@@ -1301,7 +1298,7 @@ def cancel_items_bulk(
|
||||
|
||||
is_manager = holds(user, "core.dashboard.access")
|
||||
if not is_manager and not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
approval = None
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
# a manager may approve this one cancellation with their PIN (D-10)
|
||||
@@ -1359,7 +1356,7 @@ def assign_waiter(order_id: int, body: AssignWaiterRequest, db: Session = Depend
|
||||
OrderWaiter.order_id == order_id, OrderWaiter.waiter_id == body.waiter_id
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Waiter already assigned")
|
||||
raise XeniaError("order.waiter_assigned")
|
||||
db.add(OrderWaiter(order_id=order_id, waiter_id=body.waiter_id))
|
||||
db.commit()
|
||||
return {"status": "assigned"}
|
||||
@@ -1382,7 +1379,7 @@ def assign_customer(order_id: int, body: AssignCustomerBody, db: Session = Depen
|
||||
if body.customer_id is not None:
|
||||
customer = db.query(Customer).filter(Customer.id == body.customer_id, Customer.is_active == True).first()
|
||||
if not customer:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
raise XeniaError("customer.not_found")
|
||||
order.customer_id = body.customer_id
|
||||
db.commit()
|
||||
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "status": order.status, "action": "customer_assigned"})
|
||||
@@ -1395,7 +1392,7 @@ def remove_waiter(order_id: int, waiter_id: int, db: Session = Depends(get_db),
|
||||
OrderWaiter.order_id == order_id, OrderWaiter.waiter_id == waiter_id
|
||||
).first()
|
||||
if not assignment:
|
||||
raise HTTPException(status_code=404, detail="Assignment not found")
|
||||
raise XeniaError("order.assignment_not_found")
|
||||
db.delete(assignment)
|
||||
db.commit()
|
||||
|
||||
@@ -1416,7 +1413,7 @@ def print_order(
|
||||
|
||||
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
raise XeniaError("printer.not_found")
|
||||
|
||||
table = db.query(Table).filter(Table.id == order.table_id).first()
|
||||
table_name = (table.label or f"T{table.number}") if table else f"#{order.table_id}"
|
||||
@@ -1473,22 +1470,22 @@ def transfer_order(
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
_need(request, db, user, "ordering.orders.open")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
if order.status not in ("open", "partially_paid", "paid"):
|
||||
raise HTTPException(status_code=400, detail="Order is not active")
|
||||
raise XeniaError("order.not_open")
|
||||
|
||||
target_table = db.query(Table).filter(Table.id == body.target_table_id, Table.is_active == True).first()
|
||||
if not target_table:
|
||||
raise HTTPException(status_code=404, detail="Target table not found")
|
||||
raise XeniaError("table.not_found")
|
||||
if body.target_table_id == order.table_id:
|
||||
raise HTTPException(status_code=400, detail="Table is already assigned to this order")
|
||||
raise XeniaError("order.same_table")
|
||||
|
||||
conflict = db.query(Order).filter(
|
||||
Order.table_id == body.target_table_id,
|
||||
Order.status.in_(["open", "partially_paid", "paid"]),
|
||||
).first()
|
||||
if conflict:
|
||||
raise HTTPException(status_code=400, detail="Target table already has an active order")
|
||||
raise XeniaError("table.busy")
|
||||
|
||||
old_table_id = order.table_id
|
||||
order.table_id = body.target_table_id
|
||||
@@ -1518,22 +1515,22 @@ def merge_order(
|
||||
"""
|
||||
source = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not source:
|
||||
raise HTTPException(status_code=404, detail="Source order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
_need(request, db, user, "ordering.orders.open")
|
||||
if not _can_access_order(source, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
if source.status not in ("open", "partially_paid", "paid"):
|
||||
raise HTTPException(status_code=400, detail="Source order is not active")
|
||||
raise XeniaError("order.not_open")
|
||||
|
||||
target = db.query(Order).filter(Order.id == body.target_order_id).first()
|
||||
if not target:
|
||||
raise HTTPException(status_code=404, detail="Target order not found")
|
||||
raise XeniaError("order.target_not_found")
|
||||
if not _can_access_order(target, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied to target order")
|
||||
raise XeniaError("order.not_yours")
|
||||
if target.status not in ("open", "partially_paid", "paid"):
|
||||
raise HTTPException(status_code=400, detail="Target order is not active")
|
||||
raise XeniaError("order.not_open")
|
||||
if source.id == target.id:
|
||||
raise HTTPException(status_code=400, detail="Cannot merge an order with itself")
|
||||
raise XeniaError("order.same_order")
|
||||
|
||||
# Move all items to target order
|
||||
moved_item_ids = []
|
||||
@@ -1598,18 +1595,15 @@ def split_item(
|
||||
OrderItem.id == item_id, OrderItem.order_id == order_id
|
||||
).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
raise XeniaError("order.item_not_found")
|
||||
if item.status != "active":
|
||||
raise HTTPException(status_code=400, detail="Only active items can be split")
|
||||
raise XeniaError("order.item_not_active")
|
||||
if body.quantity <= 0 or body.quantity >= item.quantity:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Split quantity must be between 1 and {item.quantity - 1}"
|
||||
)
|
||||
raise XeniaError("order.split_quantity", max=item.quantity - 1)
|
||||
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
# Reduce original item
|
||||
item.quantity -= body.quantity
|
||||
@@ -1656,13 +1650,13 @@ def adjust_item_price(
|
||||
OrderItem.id == item_id, OrderItem.order_id == order_id
|
||||
).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
raise XeniaError("order.item_not_found")
|
||||
if item.status != "active":
|
||||
raise HTTPException(status_code=400, detail="Only active items can have price adjusted")
|
||||
raise XeniaError("order.item_not_active")
|
||||
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
_need(request, db, user, "ordering.prices.modify", target=f"order:{order_id} item:{item_id}")
|
||||
|
||||
item.price_adjustment = body.price_adjustment
|
||||
@@ -1696,10 +1690,10 @@ def apply_waiter_discount(
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
_need(request, db, user, "pricing.discounts.apply", target=f"order:{order_id}")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
if body.discount_percent <= 0 or body.discount_percent > 100:
|
||||
raise HTTPException(status_code=400, detail="discount_percent must be between 0 and 100")
|
||||
raise XeniaError("validation.range", field='discount_percent', min=0, max=100)
|
||||
|
||||
# Fetch all target items
|
||||
items = db.query(OrderItem).filter(
|
||||
@@ -1708,12 +1702,12 @@ def apply_waiter_discount(
|
||||
OrderItem.status == "active",
|
||||
).all()
|
||||
if not items:
|
||||
raise HTTPException(status_code=404, detail="No active items found for given IDs")
|
||||
raise XeniaError("order.no_active_items", status=404)
|
||||
|
||||
item_unit_prices = {i.id: i.unit_price + i.price_adjustment for i in items}
|
||||
|
||||
if not discounts_enabled(db):
|
||||
raise HTTPException(status_code=403, detail="Discounts are globally disabled")
|
||||
raise XeniaError("order.discounts_off")
|
||||
|
||||
# Validate limits before touching anything. Beyond them: pricing.discounts.over_limit,
|
||||
# or a manager approves this one discount with their PIN (D-10).
|
||||
@@ -1846,13 +1840,13 @@ def cancel_print_job(
|
||||
"""Staff cancels a pending print job (failed print, still retrying)."""
|
||||
pj = db.query(PrintJob).filter(PrintJob.id == job_id, PrintJob.order_id == order_id).first()
|
||||
if not pj:
|
||||
raise HTTPException(status_code=404, detail="Print job not found")
|
||||
raise XeniaError("print_job.not_found")
|
||||
if pj.status != "pending":
|
||||
raise HTTPException(status_code=400, detail="Only pending print jobs can be cancelled")
|
||||
raise XeniaError("print_job.not_pending")
|
||||
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not order or not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
from datetime import datetime, timezone
|
||||
pj.status = "cancelled"
|
||||
@@ -1889,7 +1883,7 @@ def update_customer_count(
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
order.customer_count = body.customer_count
|
||||
db.commit()
|
||||
@@ -1911,21 +1905,21 @@ def move_items(
|
||||
_need(request, db, user, "ordering.orders.open")
|
||||
source = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not source:
|
||||
raise HTTPException(status_code=404, detail="Source order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(source, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
if source.status not in ("open", "partially_paid"):
|
||||
raise HTTPException(status_code=400, detail="Source order is not active")
|
||||
raise XeniaError("order.not_open")
|
||||
|
||||
target = db.query(Order).filter(Order.id == body.target_order_id).first()
|
||||
if not target:
|
||||
raise HTTPException(status_code=404, detail="Target order not found")
|
||||
raise XeniaError("order.target_not_found")
|
||||
if not _can_access_order(target, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied to target order")
|
||||
raise XeniaError("order.not_yours")
|
||||
if target.status not in ("open", "partially_paid"):
|
||||
raise HTTPException(status_code=400, detail="Target order is not active")
|
||||
raise XeniaError("order.not_open")
|
||||
if source.id == target.id:
|
||||
raise HTTPException(status_code=400, detail="Source and target orders are the same")
|
||||
raise XeniaError("order.same_order")
|
||||
|
||||
items = db.query(OrderItem).filter(
|
||||
OrderItem.id.in_(body.item_ids),
|
||||
@@ -1933,7 +1927,7 @@ def move_items(
|
||||
OrderItem.status == "active",
|
||||
).all()
|
||||
if not items:
|
||||
raise HTTPException(status_code=400, detail="No active items found to move")
|
||||
raise XeniaError("order.no_active_items")
|
||||
|
||||
moved_ids = []
|
||||
for item in items:
|
||||
@@ -1982,11 +1976,11 @@ def print_synopsis(
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
|
||||
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
raise XeniaError("printer.not_found")
|
||||
|
||||
table = db.query(Table).filter(Table.id == order.table_id).first()
|
||||
table_name = (table.label or f"T{table.number}") if table else f"#{order.table_id}"
|
||||
@@ -2042,13 +2036,13 @@ def put_item_on_tab(
|
||||
if not order:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not order.customer_id:
|
||||
raise HTTPException(status_code=400, detail="Order has no customer assigned — assign a customer first")
|
||||
raise XeniaError("order.no_customer")
|
||||
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
raise XeniaError("order.item_not_found")
|
||||
if item.status != "active":
|
||||
raise HTTPException(status_code=400, detail=f"Item is already {item.status} — cannot tab it")
|
||||
raise XeniaError("order.item_not_tabbable", status=item.status)
|
||||
|
||||
# Find or auto-create the customer's open tab
|
||||
tab = db.query(Tab).filter(Tab.customer_id == order.customer_id, Tab.status == "open").first()
|
||||
@@ -2110,7 +2104,7 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
_need(request, db, user, "ordering.orders.open", target=f"order:{order_id}")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("order.not_yours")
|
||||
ids = sorted(set(body.item_ids))
|
||||
items = db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.id.in_(ids)).order_by(OrderItem.id).all()
|
||||
if len(items) != len(ids) or len(items) < 2:
|
||||
|
||||
@@ -8,7 +8,7 @@ DELETE /api/prep-zones/{id} delete a prep zone
|
||||
"""
|
||||
import json
|
||||
from core.i18n import normalize_language
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
@@ -18,6 +18,7 @@ from models.prep_zone import PrepZone
|
||||
from models.printer import Printer
|
||||
from routers.deps import require_manager
|
||||
from models.user import User
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -155,7 +156,7 @@ def update_prep_zone(
|
||||
):
|
||||
zone = db.query(PrepZone).filter(PrepZone.id == zone_id).first()
|
||||
if not zone:
|
||||
raise HTTPException(status_code=404, detail="Prep zone not found")
|
||||
raise XeniaError("prep_zone.not_found")
|
||||
|
||||
if body.name is not None:
|
||||
zone.name = body.name
|
||||
@@ -216,7 +217,7 @@ def delete_prep_zone(
|
||||
):
|
||||
zone = db.query(PrepZone).filter(PrepZone.id == zone_id).first()
|
||||
if not zone:
|
||||
raise HTTPException(status_code=404, detail="Prep zone not found")
|
||||
raise XeniaError("prep_zone.not_found")
|
||||
db.delete(zone)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@@ -3,7 +3,7 @@ import json
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from database import get_db
|
||||
@@ -22,6 +22,7 @@ from schemas.pricing import (
|
||||
)
|
||||
from routers.deps import get_current_user, require_manager
|
||||
from models.user import User
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -71,7 +72,7 @@ def update_price_group(
|
||||
):
|
||||
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
|
||||
if not pg:
|
||||
raise HTTPException(status_code=404, detail="Price group not found")
|
||||
raise XeniaError("price_group.not_found")
|
||||
pg.name = body.name
|
||||
pg.description = body.description
|
||||
pg.color = body.color
|
||||
@@ -92,7 +93,7 @@ def toggle_price_group(
|
||||
):
|
||||
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
|
||||
if not pg:
|
||||
raise HTTPException(status_code=404, detail="Price group not found")
|
||||
raise XeniaError("price_group.not_found")
|
||||
pg.is_active = 0 if pg.is_active else 1
|
||||
db.commit()
|
||||
db.refresh(pg)
|
||||
@@ -107,7 +108,7 @@ def delete_price_group(
|
||||
):
|
||||
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
|
||||
if not pg:
|
||||
raise HTTPException(status_code=404, detail="Price group not found")
|
||||
raise XeniaError("price_group.not_found")
|
||||
db.delete(pg)
|
||||
db.commit()
|
||||
|
||||
@@ -184,7 +185,7 @@ def update_modifier(
|
||||
):
|
||||
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
|
||||
if not m:
|
||||
raise HTTPException(status_code=404, detail="Modifier not found")
|
||||
raise XeniaError("modifier.not_found")
|
||||
m.name = body.name
|
||||
m.description = body.description
|
||||
m.color = body.color
|
||||
@@ -220,7 +221,7 @@ def toggle_modifier(
|
||||
):
|
||||
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
|
||||
if not m:
|
||||
raise HTTPException(status_code=404, detail="Modifier not found")
|
||||
raise XeniaError("modifier.not_found")
|
||||
m.is_active = 0 if m.is_active else 1
|
||||
m.updated_at = utcnow()
|
||||
m.updated_by = user.id
|
||||
@@ -251,7 +252,7 @@ def delete_modifier(
|
||||
):
|
||||
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
|
||||
if not m:
|
||||
raise HTTPException(status_code=404, detail="Modifier not found")
|
||||
raise XeniaError("modifier.not_found")
|
||||
db.delete(m)
|
||||
db.commit()
|
||||
|
||||
@@ -310,7 +311,7 @@ def update_deal(
|
||||
):
|
||||
d = db.query(Deal).filter(Deal.id == deal_id).first()
|
||||
if not d:
|
||||
raise HTTPException(status_code=404, detail="Deal not found")
|
||||
raise XeniaError("deal.not_found")
|
||||
d.name = body.name
|
||||
d.description = body.description
|
||||
d.color = body.color
|
||||
@@ -346,7 +347,7 @@ def toggle_deal(
|
||||
):
|
||||
d = db.query(Deal).filter(Deal.id == deal_id).first()
|
||||
if not d:
|
||||
raise HTTPException(status_code=404, detail="Deal not found")
|
||||
raise XeniaError("deal.not_found")
|
||||
d.is_active = 0 if d.is_active else 1
|
||||
db.commit()
|
||||
db.refresh(d)
|
||||
@@ -361,7 +362,7 @@ def delete_deal(
|
||||
):
|
||||
d = db.query(Deal).filter(Deal.id == deal_id).first()
|
||||
if not d:
|
||||
raise HTTPException(status_code=404, detail="Deal not found")
|
||||
raise XeniaError("deal.not_found")
|
||||
db.delete(d)
|
||||
db.commit()
|
||||
|
||||
@@ -535,11 +536,11 @@ def accept_deal_offer(
|
||||
|
||||
deal = db.query(Deal).filter(Deal.id == deal_id).first()
|
||||
if not deal:
|
||||
raise HTTPException(status_code=404, detail="Deal not found")
|
||||
raise XeniaError("deal.not_found")
|
||||
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not order:
|
||||
raise HTTPException(status_code=404, detail="Order not found")
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
|
||||
added_item_ids = []
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from core.access.check import holds
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
@@ -239,19 +239,19 @@ def reparent_category(category_id: int, body: CategoryReparentRequest, db: Sessi
|
||||
"""
|
||||
cat = db.query(Category).filter(Category.id == category_id).first()
|
||||
if not cat:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
raise XeniaError("catalog.category_not_found")
|
||||
if body.parent_id is not None:
|
||||
new_parent = db.query(Category).filter(Category.id == body.parent_id).first()
|
||||
if not new_parent:
|
||||
raise HTTPException(status_code=404, detail="Target parent category not found")
|
||||
raise XeniaError("catalog.parent_not_found")
|
||||
if new_parent.parent_id is not None:
|
||||
raise HTTPException(status_code=400, detail="Cannot nest more than two levels deep")
|
||||
raise XeniaError("catalog.too_deep")
|
||||
if body.parent_id == category_id:
|
||||
raise HTTPException(status_code=400, detail="A category cannot be its own parent")
|
||||
raise XeniaError("catalog.own_parent")
|
||||
# If cat currently has children and is being made a sub, block it
|
||||
has_children = db.query(Category).filter(Category.parent_id == category_id).count() > 0
|
||||
if has_children and body.parent_id is not None:
|
||||
raise HTTPException(status_code=400, detail="Cannot nest a category that has subcategories")
|
||||
raise XeniaError("catalog.nest_has_children")
|
||||
# Assign new sort_order at the end of the destination level
|
||||
sibling_count = db.query(Category).filter(Category.parent_id == body.parent_id).count()
|
||||
cat.parent_id = body.parent_id
|
||||
@@ -266,7 +266,7 @@ def reparent_category(category_id: int, body: CategoryReparentRequest, db: Sessi
|
||||
def update_category(category_id: int, body: CategoryUpdate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
cat = db.query(Category).filter(Category.id == category_id).first()
|
||||
if not cat:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
raise XeniaError("catalog.category_not_found")
|
||||
for field, value in body.model_dump(exclude_none=True, exclude={"media_id"}).items():
|
||||
setattr(cat, field, value)
|
||||
if "media_id" in body.model_fields_set:
|
||||
@@ -281,7 +281,7 @@ def update_category(category_id: int, body: CategoryUpdate, db: Session = Depend
|
||||
def delete_category(category_id: int, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
cat = db.query(Category).filter(Category.id == category_id).first()
|
||||
if not cat:
|
||||
raise HTTPException(status_code=404, detail="Category not found")
|
||||
raise XeniaError("catalog.category_not_found")
|
||||
from services.catalog import remove_category
|
||||
remove_category(db, category_id) # its listings go; products whose main category it was get their next one
|
||||
db.delete(cat)
|
||||
@@ -428,7 +428,7 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
|
||||
# system products (the delivery fee line, S.5) are not part of the catalogue
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
raise XeniaError("product.not_found")
|
||||
scalar_fields = body.model_dump(
|
||||
exclude_none=True,
|
||||
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups",
|
||||
@@ -485,7 +485,7 @@ def create_modifier_group(product_id: int, body: ModifierGroupCreate, db: Sessio
|
||||
# system products (the delivery fee line, S.5) are not part of the catalogue
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
raise XeniaError("product.not_found")
|
||||
g = ProductModifierGroup(product_id=product_id, modifier_type=body.modifier_type, name=body.name, sort_order=body.sort_order)
|
||||
db.add(g)
|
||||
db.commit()
|
||||
@@ -498,7 +498,7 @@ def create_modifier_group(product_id: int, body: ModifierGroupCreate, db: Sessio
|
||||
def update_modifier_group(product_id: int, group_id: int, body: ModifierGroupCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
g = db.query(ProductModifierGroup).filter(ProductModifierGroup.id == group_id, ProductModifierGroup.product_id == product_id).first()
|
||||
if not g:
|
||||
raise HTTPException(status_code=404, detail="Group not found")
|
||||
raise XeniaError("catalog.group_not_found")
|
||||
g.name = body.name
|
||||
g.sort_order = body.sort_order
|
||||
db.commit()
|
||||
@@ -511,7 +511,7 @@ def update_modifier_group(product_id: int, group_id: int, body: ModifierGroupCre
|
||||
def delete_modifier_group(product_id: int, group_id: int, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
g = db.query(ProductModifierGroup).filter(ProductModifierGroup.id == group_id, ProductModifierGroup.product_id == product_id).first()
|
||||
if not g:
|
||||
raise HTTPException(status_code=404, detail="Group not found")
|
||||
raise XeniaError("catalog.group_not_found")
|
||||
# Un-group all items in this group before deleting
|
||||
db.query(ProductOption).filter(ProductOption.group_id == group_id).update({"group_id": None})
|
||||
db.query(ProductIngredient).filter(ProductIngredient.group_id == group_id).update({"group_id": None})
|
||||
@@ -526,14 +526,11 @@ def delete_product(product_id: int, hard: bool = False, db: Session = Depends(ge
|
||||
# system products (the delivery fee line, S.5) are not part of the catalogue
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
raise XeniaError("product.not_found")
|
||||
if hard:
|
||||
has_orders = db.query(OrderItem).filter(OrderItem.product_id == product_id).first()
|
||||
if has_orders:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Cannot permanently delete a product that appears in past orders. Archive it instead."
|
||||
)
|
||||
raise XeniaError("product.in_past_orders")
|
||||
db.delete(product)
|
||||
else:
|
||||
# If product has order history, archive it; otherwise hard delete
|
||||
|
||||
@@ -6,7 +6,7 @@ import csv
|
||||
import io
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, HTTPException, BackgroundTasks, Request
|
||||
from fastapi import APIRouter, Depends, Query, BackgroundTasks, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -601,7 +601,7 @@ def print_waiter(
|
||||
):
|
||||
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
raise XeniaError("printer.not_found")
|
||||
|
||||
from_dt = history_since(body.from_dt, 'reports')
|
||||
to_dt = parse_api_datetime(body.to_dt)
|
||||
@@ -665,7 +665,7 @@ def print_printer_totals(
|
||||
# The physical printer that will receive the paper
|
||||
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
raise XeniaError("printer.not_found")
|
||||
|
||||
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
|
||||
@@ -762,7 +762,7 @@ def print_products(
|
||||
|
||||
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
raise XeniaError("printer.not_found")
|
||||
|
||||
period_label, period_is_workday = _analytics_period(body, db)
|
||||
|
||||
@@ -827,7 +827,7 @@ def print_categories(
|
||||
|
||||
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
raise XeniaError("printer.not_found")
|
||||
|
||||
period_label, period_is_workday = _analytics_period(body, db)
|
||||
|
||||
@@ -899,7 +899,7 @@ def print_tables(
|
||||
):
|
||||
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
raise XeniaError("printer.not_found")
|
||||
|
||||
period_label, period_is_workday = _analytics_period(body, db)
|
||||
|
||||
@@ -2007,11 +2007,11 @@ def print_prep_zone(
|
||||
):
|
||||
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found or inactive")
|
||||
raise XeniaError("printer.not_found")
|
||||
|
||||
zone = db.query(PrepZone).filter(PrepZone.id == body.zone_id).first()
|
||||
if not zone:
|
||||
raise HTTPException(status_code=404, detail="Prep zone not found")
|
||||
raise XeniaError("prep_zone.not_found")
|
||||
|
||||
# Resolve period label
|
||||
if body.business_day_id:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from core.timeutil import utcnow, venue_day_window
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status, Query
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
from datetime import datetime, timezone
|
||||
@@ -12,6 +12,7 @@ from schemas.reservation import (
|
||||
)
|
||||
from routers.deps import get_current_user, require_manager
|
||||
from models.user import User
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -37,7 +38,7 @@ def create_reservation(
|
||||
):
|
||||
if body.table_id:
|
||||
if not db.query(Table).filter(Table.id == body.table_id, Table.is_active == True).first():
|
||||
raise HTTPException(status_code=400, detail="Table not found or inactive")
|
||||
raise XeniaError("table.not_found", status=400)
|
||||
|
||||
r = Reservation(
|
||||
guest_name=body.guest_name,
|
||||
@@ -71,7 +72,7 @@ def list_reservations(
|
||||
try:
|
||||
day = datetime.fromisoformat(date).date()
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid date format")
|
||||
raise XeniaError("validation.datetime", status=400)
|
||||
# The venue's calendar day, as a UTC window (D-11; 23 h / 25 h on DST days)
|
||||
start, end = venue_day_window(day)
|
||||
q = q.filter(Reservation.reserved_for >= start, Reservation.reserved_for < end)
|
||||
@@ -106,7 +107,7 @@ def get_reservation(
|
||||
):
|
||||
r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Reservation not found")
|
||||
raise XeniaError("reservation.not_found", reservation_id=reservation_id)
|
||||
return _enrich(r)
|
||||
|
||||
|
||||
@@ -119,16 +120,16 @@ def update_reservation(
|
||||
):
|
||||
r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Reservation not found")
|
||||
raise XeniaError("reservation.not_found", reservation_id=reservation_id)
|
||||
|
||||
updates = body.model_dump(exclude_none=True)
|
||||
|
||||
if "table_id" in updates and updates["table_id"] is not None:
|
||||
if not db.query(Table).filter(Table.id == updates["table_id"], Table.is_active == True).first():
|
||||
raise HTTPException(status_code=400, detail="Table not found or inactive")
|
||||
raise XeniaError("table.not_found", status=400)
|
||||
|
||||
if "status" in updates and updates["status"] not in VALID_STATUSES:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid status: {updates['status']}")
|
||||
raise XeniaError("validation.choice", field='status', value=updates['status'])
|
||||
|
||||
for field, value in updates.items():
|
||||
setattr(r, field, value)
|
||||
@@ -148,11 +149,11 @@ def update_reservation_status(
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if body.status not in VALID_STATUSES:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid status: {body.status}")
|
||||
raise XeniaError("validation.choice", field='status', value=body.status)
|
||||
|
||||
r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Reservation not found")
|
||||
raise XeniaError("reservation.not_found", reservation_id=reservation_id)
|
||||
|
||||
if r.online_order_cloud_id and r.status in ("requested", "pending") and body.status in ("arrived", "cancelled", "no_show"):
|
||||
# an online booking (phase 3S, S.6): the same steps as the counter's, and the customer's page follows
|
||||
@@ -185,6 +186,6 @@ def delete_reservation(
|
||||
):
|
||||
r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
|
||||
if not r:
|
||||
raise HTTPException(status_code=404, detail="Reservation not found")
|
||||
raise XeniaError("reservation.not_found", reservation_id=reservation_id)
|
||||
db.delete(r)
|
||||
db.commit()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from core.access.queries import holders_filter
|
||||
from core.timeutil import to_venue, venue_day_window, venue_date
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from fastapi import APIRouter, Depends, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
@@ -11,6 +11,7 @@ from models.shift import WaiterShift
|
||||
from models.user import User
|
||||
from schemas.schedule import ScheduledShiftCreate, ScheduledShiftUpdate, ScheduledShiftOut
|
||||
from routers.deps import require_manager
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -74,7 +75,7 @@ def create_scheduled_shift(
|
||||
):
|
||||
target = db.query(User).filter(User.id == body.user_id, User.is_active == True).first()
|
||||
if not target:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
raise XeniaError("staff.not_found")
|
||||
s = ScheduledShift(
|
||||
user_id=body.user_id,
|
||||
scheduled_date=body.scheduled_date,
|
||||
@@ -98,7 +99,7 @@ def update_scheduled_shift(
|
||||
):
|
||||
s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
|
||||
if not s:
|
||||
raise HTTPException(status_code=404, detail="Scheduled shift not found")
|
||||
raise XeniaError("schedule.shift_not_found")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(s, field, value)
|
||||
db.commit()
|
||||
@@ -114,7 +115,7 @@ def delete_scheduled_shift(
|
||||
):
|
||||
s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
|
||||
if not s:
|
||||
raise HTTPException(status_code=404, detail="Scheduled shift not found")
|
||||
raise XeniaError("schedule.shift_not_found")
|
||||
db.delete(s)
|
||||
db.commit()
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from core import i18n, timeutil
|
||||
from core.errors import XeniaError
|
||||
from core.timeutil import utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime, timezone
|
||||
|
||||
@@ -52,7 +52,7 @@ def update_setting(
|
||||
user: User = Depends(require_settings_manager),
|
||||
):
|
||||
if key not in valid_settings():
|
||||
raise HTTPException(status_code=400, detail=f"Unknown setting key: {key}")
|
||||
raise XeniaError("settings.unknown_key", key=key)
|
||||
from core.modules.registry import setting_defs
|
||||
sd = setting_defs()[key][0]
|
||||
if (sd.type == "enum" and body.value not in sd.choices) or (sd.type == "bool" and body.value not in ("true", "false")) or (sd.type == "int" and not body.value.lstrip("-").isdigit()):
|
||||
@@ -66,7 +66,7 @@ def update_setting(
|
||||
raise XeniaError("validation.unknown_language", language=body.value)
|
||||
if key == "business_day.rollover_hour":
|
||||
if not (body.value.isdigit() and 0 <= int(body.value) <= 23):
|
||||
raise HTTPException(status_code=422, detail="rollover_hour must be 0-23")
|
||||
raise XeniaError("validation.range", status=422, field='rollover_hour', min=0, max=23)
|
||||
|
||||
setting = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if setting:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from core.access.deps import public
|
||||
from core.access.queries import holders_filter
|
||||
from core.timeutil import utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from typing import Optional
|
||||
@@ -10,6 +10,7 @@ import bcrypt
|
||||
from database import get_db
|
||||
from models.user import User
|
||||
from services.chat_service import add_user_to_system_group
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -50,19 +51,16 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
|
||||
User.is_active == True,
|
||||
).first()
|
||||
if has_manager:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Setup already completed — a manager account already exists.",
|
||||
)
|
||||
raise XeniaError("setup.done")
|
||||
|
||||
if not body.username.strip():
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Username is required.")
|
||||
raise XeniaError("auth.username_required")
|
||||
if len(body.password) < 6:
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Password must be at least 6 characters.")
|
||||
raise XeniaError("auth.password_too_short", status=422, min=6)
|
||||
|
||||
existing = db.query(User).filter(User.username == body.username.strip()).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken.")
|
||||
raise XeniaError("staff.username_taken")
|
||||
|
||||
from core import i18n, timeutil
|
||||
from core.errors import XeniaError
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from core.access.check import holds
|
||||
from core.timeutil import utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
from datetime import datetime, timezone
|
||||
@@ -13,6 +13,7 @@ from models.settings import PosSettings
|
||||
from models.user import User
|
||||
from schemas.shift import StartShiftRequest, EndShiftRequest
|
||||
from routers.deps import get_current_user, require_manager
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -163,25 +164,25 @@ def start_shift(
|
||||
|
||||
if target_id and target_id != user.id:
|
||||
if not holds(user, "core.dashboard.access"):
|
||||
raise HTTPException(status_code=403, detail="Only managers can start shifts for other staff")
|
||||
raise XeniaError("shift.others_need_manager")
|
||||
target = db.query(User).filter(User.id == target_id, User.is_active == True).first()
|
||||
if not target:
|
||||
raise HTTPException(status_code=404, detail="Staff member not found")
|
||||
raise XeniaError("staff.not_found")
|
||||
else:
|
||||
target_id = user.id
|
||||
if not holds(user, "core.dashboard.access") and _get_setting(db, "shifts.waiter_self_start") != "true":
|
||||
raise HTTPException(status_code=403, detail="Shift start requires manager confirmation")
|
||||
raise XeniaError("shift.start_needs_manager")
|
||||
|
||||
active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if not active_day:
|
||||
raise HTTPException(status_code=400, detail="No open business day — manager must open the restaurant first")
|
||||
raise XeniaError("business_day.closed", status=400)
|
||||
|
||||
existing = db.query(WaiterShift).filter(
|
||||
WaiterShift.waiter_id == target_id,
|
||||
WaiterShift.ended_at == None,
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Waiter already has an active shift")
|
||||
raise XeniaError("shift.already_active")
|
||||
|
||||
target_user = db.query(User).filter(User.id == target_id).first()
|
||||
shift = WaiterShift(
|
||||
@@ -203,14 +204,14 @@ def end_shift(
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if not holds(user, "core.dashboard.access") and _get_setting(db, "shifts.waiter_self_end") != "true":
|
||||
raise HTTPException(status_code=403, detail="Shift end requires manager confirmation")
|
||||
raise XeniaError("shift.end_needs_manager")
|
||||
|
||||
shift = db.query(WaiterShift).filter(
|
||||
WaiterShift.waiter_id == user.id,
|
||||
WaiterShift.ended_at == None,
|
||||
).first()
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="No active shift found")
|
||||
raise XeniaError("shift.none_active")
|
||||
|
||||
now = utcnow()
|
||||
total = compute_shift_total(shift.id, db)
|
||||
@@ -240,22 +241,22 @@ def manager_start_shift(
|
||||
user: User = Depends(require_manager),
|
||||
):
|
||||
if not body.waiter_id:
|
||||
raise HTTPException(status_code=400, detail="waiter_id is required")
|
||||
raise XeniaError("validation.missing", field='waiter_id')
|
||||
|
||||
target = db.query(User).filter(User.id == body.waiter_id, User.is_active == True).first()
|
||||
if not target:
|
||||
raise HTTPException(status_code=404, detail="Waiter not found")
|
||||
raise XeniaError("staff.not_found")
|
||||
|
||||
active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if not active_day:
|
||||
raise HTTPException(status_code=400, detail="No open business day")
|
||||
raise XeniaError("business_day.none_open", status=400)
|
||||
|
||||
existing = db.query(WaiterShift).filter(
|
||||
WaiterShift.waiter_id == body.waiter_id,
|
||||
WaiterShift.ended_at == None,
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Waiter already has an active shift")
|
||||
raise XeniaError("shift.already_active")
|
||||
|
||||
shift = WaiterShift(
|
||||
waiter_id=body.waiter_id,
|
||||
@@ -281,7 +282,7 @@ def manager_end_shift(
|
||||
WaiterShift.ended_at == None,
|
||||
).first()
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="Active shift not found")
|
||||
raise XeniaError("shift.none_active")
|
||||
|
||||
now = utcnow()
|
||||
total = compute_shift_total(shift.id, db)
|
||||
@@ -312,17 +313,17 @@ def start_break(
|
||||
):
|
||||
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="Shift not found")
|
||||
raise XeniaError("shift.not_found")
|
||||
if shift.waiter_id != user.id and not holds(user, "core.dashboard.access"):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("shift.not_yours")
|
||||
if shift.ended_at:
|
||||
raise HTTPException(status_code=400, detail="Shift already ended")
|
||||
raise XeniaError("shift.ended")
|
||||
|
||||
open_break = db.query(ShiftBreak).filter(
|
||||
ShiftBreak.shift_id == shift_id, ShiftBreak.ended_at == None
|
||||
).first()
|
||||
if open_break:
|
||||
raise HTTPException(status_code=400, detail="Break already in progress")
|
||||
raise XeniaError("shift.on_break")
|
||||
|
||||
b = ShiftBreak(shift_id=shift_id)
|
||||
db.add(b)
|
||||
@@ -339,15 +340,15 @@ def end_break(
|
||||
):
|
||||
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="Shift not found")
|
||||
raise XeniaError("shift.not_found")
|
||||
if shift.waiter_id != user.id and not holds(user, "core.dashboard.access"):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
raise XeniaError("shift.not_yours")
|
||||
|
||||
open_break = db.query(ShiftBreak).filter(
|
||||
ShiftBreak.shift_id == shift_id, ShiftBreak.ended_at == None
|
||||
).first()
|
||||
if not open_break:
|
||||
raise HTTPException(status_code=404, detail="No active break found")
|
||||
raise XeniaError("shift.no_break")
|
||||
|
||||
open_break.ended_at = utcnow()
|
||||
db.commit()
|
||||
@@ -382,7 +383,7 @@ def get_shift(
|
||||
):
|
||||
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="Shift not found")
|
||||
raise XeniaError("shift.not_found")
|
||||
return _enrich_shift(shift, db)
|
||||
|
||||
|
||||
@@ -398,9 +399,9 @@ def delete_shift(
|
||||
|
||||
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="Shift not found")
|
||||
raise XeniaError("shift.not_found")
|
||||
if shift.ended_at is None:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete an active shift — end it first")
|
||||
raise XeniaError("shift.delete_active")
|
||||
|
||||
# Find all orders opened during this shift's time window by this waiter
|
||||
orders = db.query(Order).filter(
|
||||
@@ -440,7 +441,7 @@ def get_shift_summary(
|
||||
|
||||
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
|
||||
if not shift:
|
||||
raise HTTPException(status_code=404, detail="Shift not found")
|
||||
raise XeniaError("shift.not_found")
|
||||
|
||||
waiter_id = shift.waiter_id
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -27,6 +27,7 @@ from services.lan_ip import OVERRIDE_KEY, resolve_lan_ip, validate_lan_ip
|
||||
from services.tls_identity import tls_info
|
||||
from services.license_state import license_state
|
||||
from config import settings
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -165,7 +166,7 @@ def set_lan_ip_override(body: LanIpOverride, db: Session = Depends(get_db), user
|
||||
try:
|
||||
value = validate_lan_ip(body.ip)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=422, detail=str(e))
|
||||
raise XeniaError("validation.lan_ip")
|
||||
if row:
|
||||
row.value = value
|
||||
row.updated_by_id = user.id or None
|
||||
@@ -218,7 +219,7 @@ def create_printer(body: PrinterCreate, db: Session = Depends(get_db), user: Use
|
||||
def test_printer(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
printer = db.query(Printer).filter(Printer.id == printer_id).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found")
|
||||
raise XeniaError("printer.not_found")
|
||||
success, error = printer_service.send_test_print(printer.ip_address, printer.port, printer.name, printer.codepage_n)
|
||||
return {"success": success, "error": error}
|
||||
|
||||
@@ -227,7 +228,7 @@ def test_printer(printer_id: int, db: Session = Depends(get_db), user: User = De
|
||||
def test_order_print(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
printer = db.query(Printer).filter(Printer.id == printer_id).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found")
|
||||
raise XeniaError("printer.not_found")
|
||||
success, error = printer_service.send_test_order_print(printer.ip_address, printer.port, db, printer.line_width, printer.codepage_n)
|
||||
return {"success": success, "error": error}
|
||||
|
||||
@@ -236,7 +237,7 @@ def test_order_print(printer_id: int, db: Session = Depends(get_db), user: User
|
||||
def test_beep(printer_id: int, n1: int = 2, n2: int = 2, n3: int = 1, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
printer = db.query(Printer).filter(Printer.id == printer_id).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found")
|
||||
raise XeniaError("printer.not_found")
|
||||
success, error = printer_service.send_test_beep(printer.ip_address, printer.port, n1, n2, n3, printer.codepage_n)
|
||||
return {"success": success, "error": error}
|
||||
|
||||
@@ -245,7 +246,7 @@ def test_beep(printer_id: int, n1: int = 2, n2: int = 2, n3: int = 1, db: Sessio
|
||||
def update_printer(printer_id: int, body: PrinterUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
printer = db.query(Printer).filter(Printer.id == printer_id).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found")
|
||||
raise XeniaError("printer.not_found")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(printer, field, value)
|
||||
db.commit()
|
||||
@@ -257,7 +258,7 @@ def update_printer(printer_id: int, body: PrinterUpdate, db: Session = Depends(g
|
||||
def delete_printer(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
printer = db.query(Printer).filter(Printer.id == printer_id).first()
|
||||
if not printer:
|
||||
raise HTTPException(status_code=404, detail="Printer not found")
|
||||
raise XeniaError("printer.not_found")
|
||||
db.delete(printer)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from core.access.check import holds
|
||||
from core.timeutil import utcnow
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Body
|
||||
from fastapi import APIRouter, Depends, status, Body
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
from datetime import datetime, timezone, timedelta
|
||||
@@ -34,7 +34,7 @@ def list_groups(db: Session = Depends(get_db), user: User = Depends(get_current_
|
||||
@router.post("/groups", response_model=TableGroupOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_group(body: TableGroupCreate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
|
||||
if db.query(TableGroup).filter(TableGroup.name == body.name).first():
|
||||
raise HTTPException(status_code=400, detail="Group name already exists")
|
||||
raise XeniaError("table_group.name_taken")
|
||||
sort_order = db.query(TableGroup).count()
|
||||
group = TableGroup(name=body.name, prefix=body.prefix, color=body.color, sort_order=sort_order)
|
||||
db.add(group)
|
||||
@@ -54,7 +54,7 @@ def reorder_groups(body: List[int] = Body(...), db: Session = Depends(get_db), u
|
||||
def update_group(group_id: int, body: TableGroupUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
|
||||
group = db.query(TableGroup).filter(TableGroup.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found")
|
||||
raise XeniaError("table_group.not_found")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(group, field, value)
|
||||
db.commit()
|
||||
@@ -66,7 +66,7 @@ def update_group(group_id: int, body: TableGroupUpdate, db: Session = Depends(ge
|
||||
def delete_group(group_id: int, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
|
||||
group = db.query(TableGroup).filter(TableGroup.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found")
|
||||
raise XeniaError("table_group.not_found")
|
||||
db.query(Table).filter(Table.group_id == group_id).update({"group_id": None})
|
||||
db.delete(group)
|
||||
db.commit()
|
||||
@@ -149,7 +149,7 @@ def create_table(body: TableCreate, db: Session = Depends(get_db), user: User =
|
||||
@router.post("/batch", response_model=List[TableOut], status_code=status.HTTP_201_CREATED)
|
||||
def batch_create_tables(body: TableBatchCreate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
|
||||
if body.count < 1 or body.count > 200:
|
||||
raise HTTPException(status_code=400, detail="Count must be between 1 and 200")
|
||||
raise XeniaError("validation.range", field='count', min=1, max=200)
|
||||
|
||||
# Group-local label numbering: find highest suffix already used in this group
|
||||
existing_in_group = (
|
||||
@@ -171,10 +171,7 @@ def batch_create_tables(body: TableBatchCreate, db: Session = Depends(get_db), u
|
||||
last_n = start_label_n + body.count - 1
|
||||
worst_case = f"{body.name_prefix}{last_n}"
|
||||
if len(worst_case) > MAX_TABLE_NAME_LENGTH:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Table name '{worst_case}' would exceed {MAX_TABLE_NAME_LENGTH} characters. Shorten the prefix or reduce the count.",
|
||||
)
|
||||
raise XeniaError("table.name_too_long", name=worst_case, max=MAX_TABLE_NAME_LENGTH)
|
||||
|
||||
created = []
|
||||
for i in range(body.count):
|
||||
@@ -199,7 +196,7 @@ def batch_create_tables(body: TableBatchCreate, db: Session = Depends(get_db), u
|
||||
def update_table(table_id: int, body: TableUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
|
||||
table = db.query(Table).filter(Table.id == table_id).first()
|
||||
if not table:
|
||||
raise HTTPException(status_code=404, detail="Table not found")
|
||||
raise XeniaError("table.not_found")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(table, field, value)
|
||||
db.commit()
|
||||
@@ -211,16 +208,13 @@ def update_table(table_id: int, body: TableUpdate, db: Session = Depends(get_db)
|
||||
def delete_table(table_id: int, hard: bool = False, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
|
||||
table = db.query(Table).filter(Table.id == table_id).first()
|
||||
if not table:
|
||||
raise HTTPException(status_code=404, detail="Table not found")
|
||||
raise XeniaError("table.not_found")
|
||||
active_order = db.query(Order).filter(
|
||||
Order.table_id == table_id,
|
||||
Order.status.in_(["open", "partially_paid", "paid"])
|
||||
).first()
|
||||
if active_order:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Cannot delete or deactivate a table with an active order"
|
||||
)
|
||||
raise XeniaError("table.has_order")
|
||||
if hard:
|
||||
# Delete all past (non-active) orders for this table so FK constraint doesn't block deletion.
|
||||
# Active orders are already blocked above. Items/waiters/print_logs cascade via ORM.
|
||||
@@ -238,7 +232,7 @@ def delete_table(table_id: int, hard: bool = False, db: Session = Depends(get_db
|
||||
def table_status(table_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
table = db.query(Table).filter(Table.id == table_id).first()
|
||||
if not table:
|
||||
raise HTTPException(status_code=404, detail="Table not found")
|
||||
raise XeniaError("table.not_found")
|
||||
active_order = (
|
||||
db.query(Order)
|
||||
.filter(Order.table_id == table_id, Order.status.in_(["open", "partially_paid", "paid"]))
|
||||
@@ -255,7 +249,7 @@ def table_status(table_id: int, db: Session = Depends(get_db), user: User = Depe
|
||||
def update_floorplan(table_id: int, body: TableFloorplanUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
|
||||
table = db.query(Table).filter(Table.id == table_id).first()
|
||||
if not table:
|
||||
raise HTTPException(status_code=404, detail="Table not found")
|
||||
raise XeniaError("table.not_found")
|
||||
table.floor_x = body.floor_x
|
||||
table.floor_y = body.floor_y
|
||||
db.commit()
|
||||
@@ -276,6 +270,7 @@ def _table_in_zones(db: Session, user: User, table: Table) -> bool:
|
||||
|
||||
from core.access.deps import require as _require # noqa: E402
|
||||
from core.modules.state import module_required as _module_required # noqa: E402
|
||||
from core.errors import XeniaError
|
||||
|
||||
|
||||
@router.get("/{table_id}/history", dependencies=[Depends(_module_required("history"))])
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from core.timeutil import utcnow
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
@@ -11,6 +11,7 @@ from models.order import Order, OrderItem
|
||||
from models.user import User
|
||||
from schemas.tabs import TabOut, TabEntryOut, TabPaymentOut, TabPayRequest, TabForgiveRequest, TabCloseRequest
|
||||
from routers.deps import require_manager
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -94,7 +95,7 @@ def list_tabs(
|
||||
def get_tab(tab_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
tab = db.query(Tab).filter(Tab.id == tab_id).first()
|
||||
if not tab:
|
||||
raise HTTPException(status_code=404, detail="Tab not found")
|
||||
raise XeniaError("tab.not_found")
|
||||
return _tab_out(tab)
|
||||
|
||||
|
||||
@@ -102,10 +103,10 @@ def get_tab(tab_id: int, db: Session = Depends(get_db), user: User = Depends(req
|
||||
def open_tab(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
customer = db.query(Customer).filter(Customer.id == customer_id, Customer.is_active == True).first()
|
||||
if not customer:
|
||||
raise HTTPException(status_code=404, detail="Customer not found")
|
||||
raise XeniaError("customer.not_found")
|
||||
existing = db.query(Tab).filter(Tab.customer_id == customer_id, Tab.status == "open").first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Customer already has an open tab")
|
||||
raise XeniaError("tab.already_open")
|
||||
tab = Tab(customer_id=customer_id)
|
||||
db.add(tab)
|
||||
db.commit()
|
||||
@@ -125,9 +126,9 @@ def add_tab_entry(
|
||||
):
|
||||
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
|
||||
if not tab:
|
||||
raise HTTPException(status_code=404, detail="Open tab not found")
|
||||
raise XeniaError("tab.not_found")
|
||||
if amount <= 0:
|
||||
raise HTTPException(status_code=400, detail="Amount must be positive")
|
||||
raise XeniaError("validation.positive", field='amount')
|
||||
entry = TabEntry(
|
||||
tab_id=tab_id, order_id=order_id, order_item_id=order_item_id,
|
||||
amount=amount, description=description, created_by_id=user.id,
|
||||
@@ -147,14 +148,14 @@ def pay_tab(
|
||||
):
|
||||
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
|
||||
if not tab:
|
||||
raise HTTPException(status_code=404, detail="Open tab not found")
|
||||
raise XeniaError("tab.not_found")
|
||||
if body.amount <= 0:
|
||||
raise HTTPException(status_code=400, detail="Amount must be positive")
|
||||
raise XeniaError("validation.positive", field='amount')
|
||||
total_charged = sum(e.amount for e in tab.entries)
|
||||
total_paid = sum(p.amount for p in tab.payments)
|
||||
balance = total_charged - total_paid
|
||||
if body.amount > balance + 0.005:
|
||||
raise HTTPException(status_code=400, detail=f"Payment exceeds balance ({balance:.2f})")
|
||||
raise XeniaError("tab.over_balance", balance=f'{balance:.2f}')
|
||||
payment = TabPayment(
|
||||
tab_id=tab_id, amount=body.amount,
|
||||
payment_method=body.payment_method, notes=body.notes,
|
||||
@@ -175,12 +176,12 @@ def close_tab(
|
||||
):
|
||||
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
|
||||
if not tab:
|
||||
raise HTTPException(status_code=404, detail="Open tab not found")
|
||||
raise XeniaError("tab.not_found")
|
||||
total_charged = sum(e.amount for e in tab.entries)
|
||||
total_paid = sum(p.amount for p in tab.payments)
|
||||
balance = round(total_charged - total_paid, 2)
|
||||
if balance > 0.005:
|
||||
raise HTTPException(status_code=400, detail=f"Tab still has a balance of €{balance:.2f} — pay it off first or use /forgive")
|
||||
raise XeniaError("tab.has_balance", balance=f'{balance:.2f}')
|
||||
tab.status = "closed"
|
||||
tab.closed_at = utcnow()
|
||||
tab.closed_by_id = user.id
|
||||
@@ -200,7 +201,7 @@ def forgive_tab(
|
||||
):
|
||||
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
|
||||
if not tab:
|
||||
raise HTTPException(status_code=404, detail="Open tab not found")
|
||||
raise XeniaError("tab.not_found")
|
||||
tab.status = "forgiven"
|
||||
tab.closed_at = utcnow()
|
||||
tab.closed_by_id = user.id
|
||||
|
||||
@@ -2,7 +2,7 @@ import os
|
||||
import uuid
|
||||
import bcrypt
|
||||
from core.i18n import normalize_language
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
|
||||
from fastapi import APIRouter, Depends, status, UploadFile, File
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
from pydantic import BaseModel
|
||||
@@ -29,14 +29,14 @@ AVATAR_DIR = "/app/data/avatars"
|
||||
def _user_or_404(user_id: int, db: Session) -> User:
|
||||
u = db.query(User).filter(User.id == user_id).first()
|
||||
if not u:
|
||||
raise HTTPException(status_code=404, detail="Staff member not found")
|
||||
raise XeniaError("staff.not_found")
|
||||
return u
|
||||
|
||||
|
||||
def _guard_superadmin_target(target: User, acting_user: User):
|
||||
"""Prevent any modification of a superadmin by a non-superadmin."""
|
||||
if target.role == "superadmin" and acting_user.role != "superadmin":
|
||||
raise HTTPException(status_code=403, detail="Cannot modify a superadmin account")
|
||||
raise XeniaError("staff.superadmin_protected")
|
||||
|
||||
|
||||
def _guard_grant(acting_user: User, keys) -> None:
|
||||
@@ -146,11 +146,11 @@ def list_staff(db: Session = Depends(get_db), user: User = Depends(require_staff
|
||||
@router.post("/", response_model=UserOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_staff(body: UserCreate, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
||||
if body.role not in VALID_ROLES:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid role. Valid roles: {sorted(VALID_ROLES)}")
|
||||
raise XeniaError("staff.role_invalid", role=body.role)
|
||||
if body.role == "superadmin" and user.role != "superadmin":
|
||||
raise HTTPException(status_code=403, detail="Only a superadmin can create another superadmin")
|
||||
raise XeniaError("staff.superadmin_only")
|
||||
if db.query(User).filter(User.username == body.username).first():
|
||||
raise HTTPException(status_code=400, detail="Username already exists")
|
||||
raise XeniaError("staff.username_taken", status=400)
|
||||
|
||||
pin_hash = bcrypt.hashpw(body.pin.encode(), bcrypt.gensalt()).decode()
|
||||
new_user = User(
|
||||
@@ -186,9 +186,9 @@ def update_staff(waiter_id: int, body: UserUpdate, db: Session = Depends(get_db)
|
||||
_guard_superadmin_target(target, user)
|
||||
|
||||
if body.role is not None and body.role not in VALID_ROLES:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid role. Valid roles: {sorted(VALID_ROLES)}")
|
||||
raise XeniaError("staff.role_invalid", role=body.role)
|
||||
if body.role == "superadmin" and user.role != "superadmin":
|
||||
raise HTTPException(status_code=403, detail="Only a superadmin can assign the superadmin role")
|
||||
raise XeniaError("staff.superadmin_only")
|
||||
|
||||
if body.language is not None:
|
||||
body.language = normalize_language(body.language) or ""
|
||||
@@ -238,7 +238,7 @@ def delete_staff(waiter_id: int, db: Session = Depends(get_db), user: User = Dep
|
||||
async def upload_avatar(waiter_id: int, file: UploadFile = File(...), db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
||||
target = _user_or_404(waiter_id, db)
|
||||
if not file.content_type.startswith("image/"):
|
||||
raise HTTPException(status_code=400, detail="File must be an image")
|
||||
raise XeniaError("staff.avatar_type")
|
||||
|
||||
if target.avatar_url:
|
||||
old_path = os.path.join(AVATAR_DIR, os.path.basename(target.avatar_url))
|
||||
@@ -305,7 +305,7 @@ def assign_assistant(waiter_id: int, assistant_id: int, db: Session = Depends(ge
|
||||
AssistantAssignment.assistant_waiter_id == assistant_id,
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Assignment already exists")
|
||||
raise XeniaError("staff.assignment_exists")
|
||||
assignment = AssistantAssignment(primary_waiter_id=waiter_id, assistant_waiter_id=assistant_id)
|
||||
db.add(assignment)
|
||||
db.commit()
|
||||
@@ -319,6 +319,6 @@ def remove_assistant(waiter_id: int, db: Session = Depends(get_db), user: User =
|
||||
AssistantAssignment.primary_waiter_id == waiter_id
|
||||
).first()
|
||||
if not assignment:
|
||||
raise HTTPException(status_code=404, detail="Assignment not found")
|
||||
raise XeniaError("staff.assignment_not_found")
|
||||
db.delete(assignment)
|
||||
db.commit()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from core.timeutil import parse_api_datetime
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from fastapi import APIRouter, Depends, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
|
||||
@@ -11,6 +11,7 @@ from models.business_day import BusinessDay
|
||||
from models.user import User
|
||||
from schemas.waste import WasteLogCreate, WasteLogOut, VALID_REASONS, REASON_LABELS
|
||||
from routers.deps import require_manager
|
||||
from core.errors import XeniaError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -80,13 +81,13 @@ def log_waste(
|
||||
user: User = Depends(require_manager),
|
||||
):
|
||||
if body.reason not in VALID_REASONS:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid reason. Valid: {sorted(VALID_REASONS)}")
|
||||
raise XeniaError("validation.choice", field='reason', value=body.reason)
|
||||
if body.quantity <= 0:
|
||||
raise HTTPException(status_code=400, detail="Quantity must be positive")
|
||||
raise XeniaError("validation.positive", field='quantity')
|
||||
|
||||
product = db.query(Product).filter(Product.id == body.product_id).first()
|
||||
if not product:
|
||||
raise HTTPException(status_code=404, detail="Product not found")
|
||||
raise XeniaError("product.not_found")
|
||||
|
||||
# Snapshot current effective cost
|
||||
unit_cost = _effective_cost(product)
|
||||
@@ -119,12 +120,12 @@ def delete_waste(
|
||||
):
|
||||
entry = db.query(WasteLog).filter(WasteLog.id == entry_id).first()
|
||||
if not entry:
|
||||
raise HTTPException(status_code=404, detail="Waste entry not found")
|
||||
raise XeniaError("waste.not_found")
|
||||
|
||||
# Only allow deletion within the same business day
|
||||
active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if active_day and entry.business_day_id != active_day.id:
|
||||
raise HTTPException(status_code=403, detail="Can only delete waste entries from the current open business day")
|
||||
raise XeniaError("waste.not_today")
|
||||
|
||||
db.delete(entry)
|
||||
db.commit()
|
||||
|
||||
@@ -97,3 +97,30 @@ def test_unknown_order_on_real_api(client, make_user, login): # plan step 1.2 "
|
||||
assert r.status_code == 404
|
||||
assert r.json()["error"] == {"code": "order.not_found", "params": {"order_id": 999999},
|
||||
"message": "Order 999999 not found."}
|
||||
|
||||
|
||||
def test_backend_code_raises_codes_not_http_exceptions():
|
||||
"""Step 6.1: every error the app raises is a registered code (XeniaError) with texts in
|
||||
both languages; a plain HTTPException would reach the apps as an untranslated `http.<status>`."""
|
||||
import pathlib
|
||||
import re
|
||||
root = pathlib.Path(__file__).resolve().parents[1]
|
||||
found = [f"{p.relative_to(root)}:{n}" for d in ("routers", "services", "core", "modules")
|
||||
for p in (root / d).rglob("*.py") if p.name != "errors.py"
|
||||
for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1)
|
||||
if re.search(r"\bHTTPException\s*\(", line)]
|
||||
assert found == [], "use XeniaError (core/errors.py) instead: " + ", ".join(found)
|
||||
|
||||
|
||||
def test_a_code_can_keep_a_v1_shaped_detail():
|
||||
app = FastAPI()
|
||||
install_error_handlers(app)
|
||||
|
||||
@app.get("/x")
|
||||
def x():
|
||||
raise XeniaError("business_day.orders_open", open_orders=2, partially_paid=1,
|
||||
detail={"message": "2 tables open", "open_orders": 2, "partially_paid": 1})
|
||||
|
||||
body = TestClient(app).get("/x").json()
|
||||
assert body["error"]["code"] == "business_day.orders_open" and body["error"]["params"] == {"open_orders": 2, "partially_paid": 1}
|
||||
assert body["detail"]["open_orders"] == 2
|
||||
|
||||
@@ -182,7 +182,7 @@ def test_discount_over_limit_needs_approval(client, db, venue, make_user, login)
|
||||
token = approve(client, v["waiter_h"], "pricing.discounts.over_limit", v["manager"].username).json()["override_token"]
|
||||
r = client.post(url, headers=dict(v["waiter_h"], **{"X-Xenia-Override": token}),
|
||||
json={"item_ids": [v["items"][2].id], "discount_percent": 20})
|
||||
assert r.status_code == 403 and r.json()["detail"] == "Discounts are globally disabled"
|
||||
assert r.status_code == 403 and r.json()["error"]["code"] == "order.discounts_off"
|
||||
|
||||
|
||||
# ── check() with a token (require() routes) ──────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user