Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f107deca8c | ||
|
|
096bd53dbd | ||
|
|
7706bf2470 | ||
|
|
3eeafb565a | ||
|
|
72e175ab73 | ||
|
|
0a353c5f97 | ||
|
|
f87f9ff23c | ||
|
|
e3f4f3eeee |
@@ -53,6 +53,7 @@ Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column
|
||||
| A small panel under a button | `Popover` (`open`, `anchor` = the button's ref, `onClose`) | a colour picker, an "Add…" menu. Drawn over everything (portal), flips above, stays inside the window: **never an `absolute` panel inside a section** (it is clipped and makes the section scroll) |
|
||||
| A colour (a venue's: data) | `ColourField` (`auto`, `opacity`, `presets`) | a field with its swatch and code; its panel (over the page) has 12 ready colours, the picker, the opacity (`#rrggbbaa`) and the code. `auto` = a first choice that leaves it to something else ("As the slide"). **Never** a bare `<input type="color">` |
|
||||
| An icon from a set | `IconPicker` (`icons` = { key: component }) | a field showing the icon; a grid of the set over the page, "No icon" first |
|
||||
| Money, a weight, any number with decimals | `MoneyInput` (€, cents), `DecimalInput` (`decimals`, `allowNegative`, `suffix`) | typed with a comma **or** a dot ("12,50", "1.234,50"); reports a number, `null` when empty, `NaN` when it isn't a number (show the error). **Never** `type="number"` with a decimal step, `parseFloat` or `.replace(',', '.')`: they drop the comma a Greek keypad types (6F.2; guarded by `packages/i18n/tests/typed-numbers.test.mjs`). Fields kept as text read it with `parseNumber` |
|
||||
| A whole number (seconds, counts) | `NumberInput` (`min`, `max`, `suffix`) | − / + on its sides, as tall as an input; it may be emptied while typing (`onChange(null)`): the form shows the error and blocks saving. **Never** clamp on every key (the user can't clear the field). With a `min` below 0 a minus may be typed in front |
|
||||
| A note in a box (what works, a caution) | `Notice` (`tone`, `title`, `icon`, `items` = [{ tone, label, text }]) | a tinted box with a bar on its left; `items` are points with a tone dot and a bold label. **Never** a local `bg-info-soft` paragraph rebuilt per page |
|
||||
| A slider with its value | `Slider` (`suffix`) | framed and as tall as the fields beside it; the value sits as close to it as the frame's padding. **Never** a bare `<input type="range">` |
|
||||
|
||||
+6
-1
@@ -40,8 +40,13 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
|
||||
| `local_backend/services/cloud_sync.py` | Every call to the cloud (see the parent's `docs/reference/cloud-contract.md`) |
|
||||
| `local_backend/roles.py`, `routers/deps.py` | Roles, permission checks, auth dependencies |
|
||||
| `local_backend/services/fiscal/` | Fiscal devices behind one driver interface (D-27, step 3.3e): `base.py` (`prepare_receipt` / `prepare_credit_note` → send, `credit_notes` flag, `status`), `txt_file.py` (the dTEC100extra folder bridge, the only driver today; no credit notes yet), `__init__.py` (the venue's driver from `fiscal.type`, item building, background issue). **A new machine = a new driver module listed in `DRIVERS`**; never write to a device from a router |
|
||||
| `local_backend/services/split_bills.py`, `models/order.py` (`SplitBill`) | Split by amount (6F.6): `split_bills` (amounts JSON, mode, parts, `undone_at`, `receipt_issued_at`), `order_items.split_bill_id`. Parts are locked (no cancel / move / combine / discount); undo only while nothing is paid; the fiscal receipt is the settled lines, issued once when the last part is paid, with each method's amount (`prepare_receipt(payments=)`) |
|
||||
| `local_backend/services/moves.py`, `models/order.py` (`OrderMove`, `OrderMoveItem`, `OrderItem.split_from_id`) | Moves on the record (6F.4): `order_moves` / `order_move_items` written by transfer, move-items and merge; a line's path follows `split_from_id`; never deleted. `routers/orders.py` `cut_part()` is the one way to cut a line (quantity lowered, split) |
|
||||
| `local_backend/services/price_changes.py` | Prices changed by hand (6F.3): the venue switch `orders.price_change`, the keys, the reason, and one `PriceEventLog` row `manual_price` per change (stage cart / sent / served, approver) |
|
||||
| `local_backend/services/business_days.py`, `services/day_auto.py` | The one way to open / close the business day (the manager's buttons and the automatic loop, 6F.8). `day_auto` runs every minute from `main.py`'s lifespan: opening hours / a time / alert, closes only with no unclosed order (retry every 15 min), sticky alerts (`notifications.resolved_at`, `core.notifications.resolve`). Tests drive `tick(db, now=…)` with a fake clock |
|
||||
| `local_backend/core/sessions.py` | Sessions and sign-in rules; 6F.7: `auth.single_session_waiter` `ask` (the default; `auth.session_elsewhere`, `replace: true`), only the `waiter` client counts; `terminal_requires_username` (venue + `devices.require_username`) |
|
||||
| `local_backend/services/fees.py` | Delivery fee engine (phase 3S). **Byte-identical copy in `cloud-service/cloud_backend/services/fees.py`**: change both, and `tests/fixtures/fee_cases.json` in both; `tests/test_fees.py` fails if they differ |
|
||||
| `local_backend/services/sales.py`, `services/csv_export.py` | **How every report counts sales** (6.12a, 6.13c): sold = active, paid and tabbed lines (a tab line is sold, not paid), each net of what was refunded of it, system lines (the delivery fee) apart as fees; `Totals.on_tab`. Every analytics endpoint, printed report and export uses it. Exports: UTF-8 mark, venue time with the zone in the header, `;` and decimal commas for a Greek venue |
|
||||
| `local_backend/services/sales.py`, `services/csv_export.py` | **How every report counts sales** (6.12a, 6.13c): sold = active, paid and tabbed lines (a tab line is sold, not paid), each net of what was refunded of it, system lines (the delivery fee) apart as fees; `Totals.on_tab`. **Split bills (6F.6), the settlement-line rule:** the lines settled by a split have status `split` and **are the sale** (products, categories, costs, the waiter); the split's **part lines** (`split_part` system lines) are **the money** (shift cash / card, payment methods, tabs, the day's takings) and never a product. Anything that picks lines by status uses `split_bills.sold_filter()` / `counts_as_sale()`; money paths keep reading `paid` lines. A refunded part comes off the settled lines by its share (`_split_refunds`). Every analytics endpoint, printed report and export uses it. Exports: UTF-8 mark, venue time with the zone in the header, `;` and decimal commas for a Greek venue |
|
||||
| `local_backend/services/tab_books.py` | **Tabs in the books** (6.13c, owner rule "every movement recorded"): a line put on a tab and a tab payment record the business day and the shift of whoever did it; `for_shift` / `for_day`. A shift's drawer adds the tab cash it received; money taken by someone with no shift is theirs, in the day, in no drawer |
|
||||
| `local_backend/services/refunds.py` | Refunds: their own records (`models/refund.py`), never edits of the paid items; shift / day totals subtract them |
|
||||
| `local_backend/services/system_products.py`, `services/online_check.py` | Lines the system adds itself (phase 3S): the delivery fee is an order line whose product has `system_key` and `lifecycle_status = "system"` (never on a menu or in the catalogue, never added by hand, added printed + served so the kitchen never sees it; paid, counted, receipted and refunded like any line). The site's own price check of a pulled online order (`orders.online_price_diff`): shown, never applied — the customer pays the cloud's prices |
|
||||
|
||||
@@ -57,6 +57,7 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"auth.invalid_credentials": (401, "Wrong username or password."),
|
||||
"auth.session_ended": (401, "Your session has ended. Please log in again."),
|
||||
"auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."),
|
||||
"auth.session_elsewhere": (409, "You're signed in on another device ({device}, since {since}). Continue? It will be signed out."),
|
||||
"auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."),
|
||||
"auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."),
|
||||
"auth.username_required": (422, "Enter your username."),
|
||||
@@ -221,6 +222,22 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"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.price_change_off": (403, "Changing prices by hand is turned off for this venue."),
|
||||
"order.one_more_off": (400, "\"One more\" isn't turned on for this product."),
|
||||
"order.one_more_line": (400, "This line can't be ordered again with one tap."),
|
||||
"order.quantity_change_off": (403, "Changing quantities is turned off for this venue."),
|
||||
"order.quantity_remove_off": (403, "Quantities can only go up at this venue."),
|
||||
"order.quantity_invalid": (400, "Choose a whole number from 1 to {max}."),
|
||||
"order.quantity_line": (400, "This line's quantity can't be changed here."),
|
||||
"order.price_change_sent_off": (403, "Prices can only be changed before the items are sent."),
|
||||
"order.price_reason_required": (400, "Say why the price changes."),
|
||||
"split.not_allowed": (403, "Splitting a bill this way isn't turned on for this venue."),
|
||||
"split.lines_changed": (409, "Some of these items were paid or changed meanwhile. Look again."),
|
||||
"split.amount_invalid": (400, "Each part must be more than 0 and less than the total ({total})."),
|
||||
"split.part_locked": (400, "This is part of a split bill: undo the split to change it."),
|
||||
"split.not_found": (404, "That split bill isn't there any more."),
|
||||
"split.paid_already": (409, "A part is already paid or on a tab: the split can't be undone."),
|
||||
"split.parts_unpaid": (400, "Parts of a split bill are still unpaid: take their payment first."),
|
||||
"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."),
|
||||
|
||||
@@ -53,7 +53,8 @@
|
||||
"paid_total": "Πληρωμενο: {value:.2f}e",
|
||||
"pending": "ΕΚΚΡΕΜΗ:",
|
||||
"remaining": "Εκκρεμει: {value:.2f}e",
|
||||
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ"
|
||||
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ",
|
||||
"split": "ΔΙΑΧΩΡΙΣΜΟΣ (ΕΞΟΦΛΕΙΤΑΙ ΑΠΟ ΤΑ ΜΕΡΗ):"
|
||||
},
|
||||
"ticket": {
|
||||
"compact_guests": " | {count}ατ.",
|
||||
@@ -89,10 +90,17 @@
|
||||
"print": {
|
||||
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
|
||||
"failing": "Ένα δελτίο της παραγγελίας #{order_id} δεν έχει τυπωθεί ακόμα στον εκτυπωτή {printer} (αποτυχημένες προσπάθειες μέχρι τώρα: {attempts}· συνεχίζει να προσπαθεί). Ελέγξτε τον εκτυπωτή."
|
||||
},
|
||||
"business_day": {
|
||||
"not_open": "Είναι {time} και η ημέρα δεν έχει ανοίξει.",
|
||||
"open_blocked": "Η ημέρα δεν άνοιξε μόνη της στις {time}: η άδεια δεν το επιτρέπει ({reason}).",
|
||||
"tables_open": "Είναι ώρα κλεισίματος ({time}) αλλά {count} παραγγελίες είναι ακόμα ανοιχτές. Η ημέρα κλείνει μόνη της μόλις κλείσουν.",
|
||||
"not_closed": "Η ημέρα έπρεπε να κλείσει στις {time} και είναι ακόμα ανοιχτή."
|
||||
}
|
||||
},
|
||||
"system_product": {
|
||||
"delivery_fee": "Μεταφορικά"
|
||||
"delivery_fee": "Μεταφορικά",
|
||||
"split_part": "Διαχωρισμός λογαριασμού"
|
||||
},
|
||||
"qr": {
|
||||
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
|
||||
@@ -104,5 +112,8 @@
|
||||
"order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.",
|
||||
"order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.",
|
||||
"bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό."
|
||||
},
|
||||
"split": {
|
||||
"part_name": "Μέρος λογαριασμού {n}/{of}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,8 @@
|
||||
"paid_total": "Paid: {value:.2f}e",
|
||||
"pending": "PENDING:",
|
||||
"remaining": "Remaining: {value:.2f}e",
|
||||
"title": "ORDER SUMMARY"
|
||||
"title": "ORDER SUMMARY",
|
||||
"split": "SPLIT BILL (SETTLED BY THE PARTS):"
|
||||
},
|
||||
"ticket": {
|
||||
"compact_guests": " | {count}pax",
|
||||
@@ -89,10 +90,17 @@
|
||||
"print": {
|
||||
"failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts).",
|
||||
"failing": "A ticket for order #{order_id} hasn't printed on {printer} yet (failed attempts so far: {attempts}; still retrying). Check the printer."
|
||||
},
|
||||
"business_day": {
|
||||
"not_open": "It's {time} and the day isn't open.",
|
||||
"open_blocked": "The day didn't open by itself at {time}: the license doesn't allow it ({reason}).",
|
||||
"tables_open": "It's closing time ({time}) but {count} orders are still open. The day closes by itself once they are closed.",
|
||||
"not_closed": "The day should have closed at {time} and is still open."
|
||||
}
|
||||
},
|
||||
"system_product": {
|
||||
"delivery_fee": "Delivery fee"
|
||||
"delivery_fee": "Delivery fee",
|
||||
"split_part": "Split bill"
|
||||
},
|
||||
"qr": {
|
||||
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
|
||||
@@ -104,5 +112,8 @@
|
||||
"order_sent": "Table {table} ordered from the tablet ({count} items): sent to the kitchen.",
|
||||
"order_waiting": "Table {table} ordered from the tablet ({count} items): confirm it on the table.",
|
||||
"bill_message": "Table {table}: the guests ask for the bill."
|
||||
},
|
||||
"split": {
|
||||
"part_name": "Split bill {n}/{of}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +85,7 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
|
||||
row = db.query(Notification).filter(
|
||||
Notification.dedupe_key == dedupe_key,
|
||||
(Notification.expires_at.is_(None)) | (Notification.expires_at > now),
|
||||
Notification.resolved_at.is_(None),
|
||||
).order_by(Notification.id.desc()).first()
|
||||
if row is not None:
|
||||
if not fold:
|
||||
@@ -119,6 +120,27 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
|
||||
db.close()
|
||||
|
||||
|
||||
def resolve(db, dedupe_keys) -> int:
|
||||
"""Sticky alerts whose cause is gone (6F.8): hide the live rows with these dedupe keys.
|
||||
Sends `platform_notification` {id, resolved: true} so open bells refresh. Commits."""
|
||||
from models.notification import Notification
|
||||
rows = db.query(Notification).filter(Notification.dedupe_key.in_(list(dedupe_keys)),
|
||||
Notification.resolved_at.is_(None)).all()
|
||||
if not rows:
|
||||
return 0
|
||||
now = utcnow()
|
||||
for r in rows:
|
||||
r.resolved_at = now
|
||||
db.commit()
|
||||
try:
|
||||
from services.ws_bus import broadcast_sync
|
||||
for r in rows:
|
||||
broadcast_sync(EVENT, {"id": r.id, "resolved": True}, user_ids=recipients(db, r.audience))
|
||||
except Exception:
|
||||
logger.exception("notification.resolve_event_failed")
|
||||
return len(rows)
|
||||
|
||||
|
||||
# ── producers that need a little logic ───────────────────────────────────────
|
||||
|
||||
EXPIRY_WARN_DAYS = (14, 7, 3, 1)
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
|
||||
Sessions
|
||||
- start(db, user, client, request) creates a row and applies the client's single-session
|
||||
rule (setting auth.single_session_<client>: off | refuse_new | end_old).
|
||||
rule (setting auth.single_session_<client>: off | refuse_new | end_old | ask).
|
||||
`ask` (waiters, the default since 6F.7): a login while signed in elsewhere is refused with
|
||||
auth.session_elsewhere (where, since when) until the app retries with replace=True; then
|
||||
the old sessions end with reason "replaced" (their sockets get session.ended at once).
|
||||
Only the waiter's phones count: a terminal session (the counter) is its own client.
|
||||
- validate(sid) is called on every authenticated request (routers.deps.decode_token).
|
||||
Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once,
|
||||
so an ended session is refused on its very next request.
|
||||
@@ -61,15 +65,32 @@ def _setting(db, key: str, default: str) -> str:
|
||||
|
||||
|
||||
def single_session_rule(db, client: str) -> str:
|
||||
return _setting(db, f"auth.single_session_{client}", "off") if client in ("manager", "waiter") else "off"
|
||||
if client == "waiter":
|
||||
return _setting(db, "auth.single_session_waiter", "ask") # 6F.7: ask is the default
|
||||
return _setting(db, "auth.single_session_manager", "off") if client == "manager" else "off"
|
||||
|
||||
|
||||
# ── lifecycle ────────────────────────────────────────────────────────────────
|
||||
|
||||
def start(db, user, client: str, request=None, *, device=None, expires_at=None):
|
||||
def device_label(user_agent: str | None) -> str:
|
||||
"""A short, language-neutral name for where a session runs ("Android · Chrome")."""
|
||||
ua = user_agent or ""
|
||||
system = next((name for key, name in (("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"),
|
||||
("Windows", "Windows"), ("Macintosh", "Mac"), ("Linux", "Linux"))
|
||||
if key in ua), "")
|
||||
browser = next((name for key, name in (("EdgA", "Edge"), ("Edg/", "Edge"), ("Firefox", "Firefox"), ("FxiOS", "Firefox"),
|
||||
("CriOS", "Chrome"), ("Chrome", "Chrome"), ("Safari", "Safari"))
|
||||
if key in ua), "")
|
||||
if "; wv)" in ua:
|
||||
browser = "app"
|
||||
return " · ".join(x for x in (system, browser) if x)
|
||||
|
||||
|
||||
def start(db, user, client: str, request=None, *, device=None, expires_at=None, replace: bool = False):
|
||||
"""Create a session for user (None user_id for the support account). Commits.
|
||||
`device`: the paired device of a terminal login; its previous sessions are replaced
|
||||
(a shared screen shows one user at a time)."""
|
||||
(a shared screen shows one user at a time). `replace`: the person said yes to signing
|
||||
out their other session (rule `ask`)."""
|
||||
from models.session import LoginSession
|
||||
if client not in CLIENTS:
|
||||
raise ValueError(f"unknown client {client!r}")
|
||||
@@ -80,6 +101,11 @@ def start(db, user, client: str, request=None, *, device=None, expires_at=None):
|
||||
LoginSession.ended_at.is_(None)).all()
|
||||
if active and rule == "refuse_new":
|
||||
raise XeniaError("auth.session_exists", client=client)
|
||||
if active and rule == "ask" and not replace:
|
||||
last = max(active, key=lambda s: s.created_at)
|
||||
from core.timeutil import iso_z
|
||||
raise XeniaError("auth.session_elsewhere", client=client, since=iso_z(last.created_at),
|
||||
device=device_label(last.user_agent) or "?", ip=last.ip or "")
|
||||
for s in active:
|
||||
_end_row(s, "replaced")
|
||||
if device is not None:
|
||||
@@ -186,7 +212,8 @@ def validate(sid: str | None, db=None) -> Active:
|
||||
if row is None or row.ended_at is not None:
|
||||
with _lock:
|
||||
_cache.pop(sid, None)
|
||||
raise XeniaError("auth.session_ended")
|
||||
# why it ended (replaced, logout, idle...): the app can say "you signed in elsewhere"
|
||||
raise XeniaError("auth.session_ended", reason=(row.end_reason if row is not None else None) or "unknown")
|
||||
info = Active(row.user_id, row.device_id, row.expires_at)
|
||||
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
||||
finally:
|
||||
@@ -233,3 +260,12 @@ def waiter_login_mode(db) -> str:
|
||||
|
||||
def waiter_requires_username(db) -> bool:
|
||||
return _setting(db, "auth.waiter_require_username", "false") == "true"
|
||||
|
||||
|
||||
def terminal_requires_username(db, device=None) -> bool:
|
||||
"""Paired screens (6F.7): type a username instead of picking a name. The device's own
|
||||
choice (Device.require_username) wins over the venue's auth.terminal_require_username."""
|
||||
own = getattr(device, "require_username", None)
|
||||
if own is not None:
|
||||
return bool(own)
|
||||
return _setting(db, "auth.terminal_require_username", "false") == "true"
|
||||
|
||||
@@ -79,7 +79,10 @@ async def lifespan(app: FastAPI):
|
||||
from core.modules import supervisor
|
||||
supervisor.start(loop)
|
||||
reservation_task = await start_reservation_tasks()
|
||||
from services import day_auto
|
||||
day_task = await day_auto.start() # the day opens / closes by itself (6F.8)
|
||||
yield
|
||||
day_task.cancel()
|
||||
supervisor.stop_all()
|
||||
sync_task.cancel()
|
||||
reservation_task.cancel()
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3).
|
||||
|
||||
- price_event_log: approved_by_user_id, stage (cart | sent | served), quantity, for the new
|
||||
event type manual_price (services/price_changes.py).
|
||||
- The keys ordering.prices.modify_sent (everyone who holds ordering.prices.modify today: nobody
|
||||
loses what they could do) and ordering.prices.view_changes (owners and store managers).
|
||||
|
||||
Revision ID: 0047_price_changes
|
||||
Revises: 0046_media_folders
|
||||
Create Date: 2026-11-23 12:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '0047_price_changes'
|
||||
down_revision = '0046_media_folders'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('price_event_log') as b:
|
||||
b.add_column(sa.Column('approved_by_user_id', sa.Integer(), nullable=True))
|
||||
b.add_column(sa.Column('stage', sa.String(), nullable=True))
|
||||
b.add_column(sa.Column('quantity', sa.Float(), nullable=True))
|
||||
b.create_foreign_key('fk_price_event_approved_by', 'users', ['approved_by_user_id'], ['id'])
|
||||
bind = op.get_bind()
|
||||
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||
"select user_id, 'ordering.prices.modify_sent' from user_permissions where key = 'ordering.prices.modify'"))
|
||||
# a venue that changed a role's default for modify gets the same for modify_sent
|
||||
bind.execute(sa.text("insert or ignore into role_permissions (role, key, granted) "
|
||||
"select role, 'ordering.prices.modify_sent', granted from role_permissions where key = 'ordering.prices.modify'"))
|
||||
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||
"select id, 'ordering.prices.view_changes' from users where role in ('owner', 'store_manager')"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
bind.execute(sa.text("delete from user_permissions where key in ('ordering.prices.modify_sent', 'ordering.prices.view_changes')"))
|
||||
bind.execute(sa.text("delete from role_permissions where key = 'ordering.prices.modify_sent'"))
|
||||
with op.batch_alter_table('price_event_log') as b:
|
||||
b.drop_constraint('fk_price_event_approved_by', type_='foreignkey')
|
||||
b.drop_column('quantity')
|
||||
b.drop_column('stage')
|
||||
b.drop_column('approved_by_user_id')
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Moves on the record (owner 2026-11-23, plan 6F.4, services/moves.py).
|
||||
|
||||
- order_moves / order_move_items: every table transfer, lines moved, orders merged, with its lines.
|
||||
- order_items.split_from_id: the line a line was cut from (a split), so its path follows it.
|
||||
- Backfill from the audit log written before 6F.4 (notes "Transferred from table A to table B",
|
||||
"Moved to order #N (table T)", "Items merged from order #N (table T)"): one move each, marked
|
||||
note='backfill'. A transfer's lines are the order's lines added before it; quantities unknown.
|
||||
|
||||
Revision ID: 0048_order_moves
|
||||
Revises: 0047_price_changes
|
||||
Create Date: 2026-11-23 15:00:00
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.timeutil import UTCDateTime
|
||||
|
||||
revision = '0048_order_moves'
|
||||
down_revision = '0047_price_changes'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_TABLE = r"(?:table )?(\d+|None)"
|
||||
|
||||
|
||||
def _int(v):
|
||||
return int(v) if v not in (None, "None", "") else None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
'order_moves',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('kind', sa.String(), nullable=False),
|
||||
sa.Column('from_order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=True),
|
||||
sa.Column('to_order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=True),
|
||||
sa.Column('from_table_id', sa.Integer(), sa.ForeignKey('tables.id'), nullable=True),
|
||||
sa.Column('to_table_id', sa.Integer(), sa.ForeignKey('tables.id'), nullable=True),
|
||||
sa.Column('by_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||
sa.Column('approved_by_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
|
||||
sa.Column('at', UTCDateTime(), nullable=False),
|
||||
sa.Column('note', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
for col in ('id', 'kind', 'from_order_id', 'to_order_id', 'business_day_id', 'at'):
|
||||
op.create_index(f'ix_order_moves_{col}', 'order_moves', [col])
|
||||
op.create_table(
|
||||
'order_move_items',
|
||||
sa.Column('move_id', sa.Integer(), sa.ForeignKey('order_moves.id', ondelete='CASCADE'), nullable=False),
|
||||
sa.Column('item_id', sa.Integer(), sa.ForeignKey('order_items.id'), nullable=False),
|
||||
sa.Column('quantity', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('move_id', 'item_id'),
|
||||
)
|
||||
op.create_index('ix_order_move_items_item_id', 'order_move_items', ['item_id'])
|
||||
with op.batch_alter_table('order_items') as b:
|
||||
b.add_column(sa.Column('split_from_id', sa.Integer(), nullable=True))
|
||||
b.create_index('ix_order_items_split_from_id', ['split_from_id'])
|
||||
b.create_foreign_key('fk_order_items_split_from', 'order_items', ['split_from_id'], ['id'])
|
||||
_backfill(op.get_bind())
|
||||
|
||||
|
||||
def _backfill(bind) -> None:
|
||||
rows = bind.execute(sa.text(
|
||||
"select a.id, a.order_id, a.event_type, a.waiter_id, a.item_ids, a.note, a.created_at, o.table_id, o.business_day_id "
|
||||
"from order_audit_log a join orders o on o.id = a.order_id "
|
||||
"where a.event_type in ('TABLE_TRANSFER', 'ITEMS_MOVED_OUT', 'ITEMS_ADDED') and a.note is not null order by a.id")).fetchall()
|
||||
existing_items = {r[0] for r in bind.execute(sa.text("select id from order_items")).fetchall()}
|
||||
existing_orders = {r[0] for r in bind.execute(sa.text("select id from orders")).fetchall()}
|
||||
|
||||
def add(kind, frm, to, ft, tt, by, at, day, items):
|
||||
res = bind.execute(sa.text(
|
||||
"insert into order_moves (kind, from_order_id, to_order_id, from_table_id, to_table_id, by_user_id, business_day_id, at, note) "
|
||||
"values (:k, :fo, :to, :ft, :tt, :by, :day, :at, 'backfill')"),
|
||||
{'k': kind, 'fo': frm if frm in existing_orders else None, 'to': to if to in existing_orders else None,
|
||||
'ft': ft, 'tt': tt, 'by': by, 'day': day, 'at': at})
|
||||
mid = res.lastrowid
|
||||
for iid in sorted({i for i in items if i in existing_items}):
|
||||
bind.execute(sa.text("insert or ignore into order_move_items (move_id, item_id, quantity) values (:m, :i, null)"),
|
||||
{'m': mid, 'i': iid})
|
||||
|
||||
def ids(raw):
|
||||
try:
|
||||
v = json.loads(raw or '[]')
|
||||
return [int(x) for x in v if isinstance(x, int)]
|
||||
except (ValueError, TypeError):
|
||||
return []
|
||||
|
||||
for (_id, order_id, kind, by, item_ids, note, at, table_id, day) in rows:
|
||||
if kind == 'TABLE_TRANSFER':
|
||||
m = re.match(rf"Transferred from table (\d+|None) to table (\d+|None)", note)
|
||||
if not m:
|
||||
continue
|
||||
items = [r[0] for r in bind.execute(sa.text(
|
||||
"select id from order_items where order_id = :o and added_at <= :at"), {'o': order_id, 'at': at}).fetchall()]
|
||||
add('table_transfer', order_id, order_id, _int(m.group(1)), _int(m.group(2)), by, at, day, items)
|
||||
elif kind == 'ITEMS_MOVED_OUT':
|
||||
m = re.match(rf"Moved to order #(\d+) \({_TABLE}\)", note)
|
||||
if not m:
|
||||
continue
|
||||
add('items_moved', order_id, int(m.group(1)), table_id, _int(m.group(2)), by, at, day, ids(item_ids))
|
||||
elif kind == 'ITEMS_ADDED':
|
||||
m = re.match(rf"Items merged from order #(\d+) \({_TABLE}\)", note)
|
||||
if not m:
|
||||
continue
|
||||
add('orders_merged', int(m.group(1)), order_id, _int(m.group(2)), table_id, by, at, day, ids(item_ids))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('order_items') as b:
|
||||
b.drop_constraint('fk_order_items_split_from', type_='foreignkey')
|
||||
b.drop_index('ix_order_items_split_from_id')
|
||||
b.drop_column('split_from_id')
|
||||
op.drop_index('ix_order_move_items_item_id', 'order_move_items')
|
||||
op.drop_table('order_move_items')
|
||||
for col in ('id', 'kind', 'from_order_id', 'to_order_id', 'business_day_id', 'at'):
|
||||
op.drop_index(f'ix_order_moves_{col}', 'order_moves')
|
||||
op.drop_table('order_moves')
|
||||
@@ -0,0 +1,30 @@
|
||||
"""One more and quantity changes (owner 2026-11-23, plan 6F.5).
|
||||
|
||||
- products.one_more_enabled (off: the owner turns it on per product).
|
||||
- The key ordering.items.change_quantity for owners and store managers (the venue's setting
|
||||
orders.quantity_change starts 'off').
|
||||
|
||||
Revision ID: 0049_one_more
|
||||
Revises: 0048_order_moves
|
||||
Create Date: 2026-11-23 18:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '0049_one_more'
|
||||
down_revision = '0048_order_moves'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('products') as b:
|
||||
b.add_column(sa.Column('one_more_enabled', sa.Boolean(), nullable=False, server_default='0'))
|
||||
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||
"select id, 'ordering.items.change_quantity' from users where role in ('owner', 'store_manager')"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.items.change_quantity'"))
|
||||
with op.batch_alter_table('products') as b:
|
||||
b.drop_column('one_more_enabled')
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
|
||||
|
||||
- split_bills: chosen lines settled together and cut into parts paid on their own.
|
||||
- order_items.split_bill_id: on the settled lines (status 'split') and on the part lines.
|
||||
- The key ordering.payments.split_amount for everyone who takes payments (holds
|
||||
ordering.orders.close); the venue's setting payments.split_amount starts 'off'.
|
||||
|
||||
Revision ID: 0050_split_bills
|
||||
Revises: 0049_one_more
|
||||
Create Date: 2026-11-23 21:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.timeutil import UTCDateTime
|
||||
|
||||
revision = '0050_split_bills'
|
||||
down_revision = '0049_one_more'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
'split_bills',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=False),
|
||||
sa.Column('total', sa.Float(), nullable=False),
|
||||
sa.Column('mode', sa.String(), nullable=False),
|
||||
sa.Column('parts', sa.Integer(), nullable=False),
|
||||
sa.Column('amounts', sa.Text(), nullable=False),
|
||||
sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
|
||||
sa.Column('undone_at', UTCDateTime(), nullable=True),
|
||||
sa.Column('undone_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||
sa.Column('receipt_issued_at', UTCDateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
for col in ('id', 'order_id', 'business_day_id'):
|
||||
op.create_index(f'ix_split_bills_{col}', 'split_bills', [col])
|
||||
with op.batch_alter_table('order_items') as b:
|
||||
b.add_column(sa.Column('split_bill_id', sa.Integer(), nullable=True))
|
||||
b.create_index('ix_order_items_split_bill_id', ['split_bill_id'])
|
||||
b.create_foreign_key('fk_order_items_split_bill', 'split_bills', ['split_bill_id'], ['id'])
|
||||
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||
"select user_id, 'ordering.payments.split_amount' from user_permissions "
|
||||
"where key = 'ordering.orders.close'"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.payments.split_amount'"))
|
||||
with op.batch_alter_table('order_items') as b:
|
||||
b.drop_constraint('fk_order_items_split_bill', type_='foreignkey')
|
||||
b.drop_index('ix_order_items_split_bill_id')
|
||||
b.drop_column('split_bill_id')
|
||||
for col in ('id', 'order_id', 'business_day_id'):
|
||||
op.drop_index(f'ix_split_bills_{col}', 'split_bills')
|
||||
op.drop_table('split_bills')
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Sign-in (owner 2026-11-23, plan 6F.7).
|
||||
|
||||
- devices.require_username: a paired screen's own choice (NULL = the venue's
|
||||
auth.terminal_require_username).
|
||||
- auth.single_session_waiter: 'ask' is the new default; a venue that has the row set to
|
||||
'off' gets 'ask' too (Q-9). A venue that chose refuse_new / end_old keeps its choice.
|
||||
|
||||
Revision ID: 0051_sign_in
|
||||
Revises: 0050_split_bills
|
||||
Create Date: 2026-11-23 22:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '0051_sign_in'
|
||||
down_revision = '0050_split_bills'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('devices') as b:
|
||||
b.add_column(sa.Column('require_username', sa.Boolean(), nullable=True))
|
||||
op.get_bind().execute(sa.text("update pos_settings set value = 'ask' "
|
||||
"where key = 'auth.single_session_waiter' and value = 'off'"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('devices') as b:
|
||||
b.drop_column('require_username')
|
||||
@@ -0,0 +1,35 @@
|
||||
"""The day opens and closes by itself (owner 2026-11-23, plan 6F.8, services/day_auto.py).
|
||||
|
||||
- business_days.opened_auto / closed_auto; opened_by_id may be NULL (opened by the system).
|
||||
- notifications.resolved_at: sticky alerts that stay until their cause is gone.
|
||||
|
||||
Revision ID: 0052_day_auto
|
||||
Revises: 0051_sign_in
|
||||
Create Date: 2026-11-23 23:30:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.timeutil import UTCDateTime
|
||||
|
||||
revision = '0052_day_auto'
|
||||
down_revision = '0051_sign_in'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('business_days') as b:
|
||||
b.alter_column('opened_by_id', existing_type=sa.Integer(), nullable=True)
|
||||
b.add_column(sa.Column('opened_auto', sa.Boolean(), nullable=False, server_default='0'))
|
||||
b.add_column(sa.Column('closed_auto', sa.Boolean(), nullable=False, server_default='0'))
|
||||
with op.batch_alter_table('notifications') as b:
|
||||
b.add_column(sa.Column('resolved_at', UTCDateTime(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('notifications') as b:
|
||||
b.drop_column('resolved_at')
|
||||
with op.batch_alter_table('business_days') as b:
|
||||
b.drop_column('closed_auto')
|
||||
b.drop_column('opened_auto')
|
||||
@@ -1,4 +1,4 @@
|
||||
from sqlalchemy import Column, Date, Integer, String, Float, ForeignKey, Text
|
||||
from sqlalchemy import Boolean, Column, Date, Integer, String, Float, ForeignKey, Text
|
||||
from core.timeutil import UTCDateTime, utcnow
|
||||
from sqlalchemy.orm import relationship
|
||||
from database import Base
|
||||
@@ -15,7 +15,9 @@ class BusinessDay(Base):
|
||||
# The date this day counts as (D-11): set once when the day opens with
|
||||
# core.timeutil.business_date_of(opened_at), never recalculated. Reports group by it.
|
||||
business_date = Column(Date, nullable=False, index=True)
|
||||
opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=True) # NULL = opened by the system (6F.8)
|
||||
opened_auto = Column(Boolean, nullable=False, default=False) # 6F.8: opened / closed by
|
||||
closed_auto = Column(Boolean, nullable=False, default=False) # services/day_auto.py
|
||||
closed_at = Column(UTCDateTime, nullable=True)
|
||||
closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
notes = Column(Text, nullable=True)
|
||||
|
||||
@@ -13,7 +13,7 @@ Devices are never deleted: revoked rows keep their token hash so the device is t
|
||||
`device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id.
|
||||
Read and written through routers/devices.py and core/access/context.py.
|
||||
"""
|
||||
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
|
||||
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String
|
||||
|
||||
from core.timeutil import UTCDateTime, utcnow
|
||||
from database import Base
|
||||
@@ -29,6 +29,7 @@ class Device(Base):
|
||||
app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app
|
||||
config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone)
|
||||
login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode
|
||||
require_username = Column(Boolean, nullable=True) # NULL = site default auth.terminal_require_username (6F.7)
|
||||
token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up
|
||||
linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True)
|
||||
user_agent = Column(String, nullable=True) # from the pairing request
|
||||
|
||||
@@ -7,8 +7,10 @@ failures (later: Ergani, close-day reminders). NOT staff chat or manager message
|
||||
- The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered
|
||||
in the reader's language when listed.
|
||||
- audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>".
|
||||
- dedupe_key: while a row with the same key is still live (expires_at NULL or future),
|
||||
notify() bumps its `count` / `last_at` instead of adding a row.
|
||||
- dedupe_key: while a row with the same key is still live (expires_at NULL or future, not
|
||||
resolved), notify() bumps its `count` / `last_at` instead of adding a row.
|
||||
- resolved_at (6F.8): a sticky alert ("the day isn't open") stays until its cause is gone;
|
||||
core.notifications.resolve() then hides it.
|
||||
Written through core/notifications.py only.
|
||||
"""
|
||||
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
|
||||
@@ -31,6 +33,7 @@ class Notification(Base):
|
||||
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
|
||||
last_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||
expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this
|
||||
resolved_at = Column(UTCDateTime, nullable=True) # 6F.8: a sticky alert whose cause is gone (hidden, dedupe ends)
|
||||
|
||||
|
||||
class NotificationRead(Base):
|
||||
|
||||
@@ -133,6 +133,12 @@ class OrderItem(Base):
|
||||
# Deal binding — which deal created this item, and which original item it's linked to
|
||||
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
||||
linked_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
|
||||
# the line this one was cut from (6F.4): a split, a lowered quantity, a split payment; its moves
|
||||
# before the cut are this line's too (services/moves.py)
|
||||
split_from_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True)
|
||||
# a split bill (6F.6): on the lines it settled (status "split") and on its part lines (the
|
||||
# system product split_part, paid like any line); services/split_bills.py
|
||||
split_bill_id = Column(Integer, ForeignKey("split_bills.id"), nullable=True, index=True)
|
||||
|
||||
order = relationship("Order", back_populates="items")
|
||||
product = relationship("Product", back_populates="order_items")
|
||||
@@ -261,3 +267,54 @@ def _snapshot_item_names(session, flush_context, instances):
|
||||
cat = session.get(Category, obj.category_id)
|
||||
obj.category_name = cat.name if cat else None
|
||||
|
||||
|
||||
class OrderMove(Base):
|
||||
"""Something moved between tables or orders (owner 2026-11-23, plan 6F.4, services/moves.py):
|
||||
a whole order to another table (`table_transfer`), chosen lines to another order
|
||||
(`items_moved`), or one order joined into another (`orders_merged`). Never deleted."""
|
||||
__tablename__ = "order_moves"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
kind = Column(String, nullable=False, index=True) # table_transfer | items_moved | orders_merged
|
||||
from_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
|
||||
to_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
|
||||
from_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
|
||||
to_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
|
||||
by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
|
||||
note = Column(Text, nullable=True) # the importer / backfill: where it came from
|
||||
|
||||
items = relationship("OrderMoveItem", back_populates="move", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class OrderMoveItem(Base):
|
||||
"""A line that went with a move, and how much of it (its quantity at the time)."""
|
||||
__tablename__ = "order_move_items"
|
||||
|
||||
move_id = Column(Integer, ForeignKey("order_moves.id", ondelete="CASCADE"), primary_key=True)
|
||||
item_id = Column(Integer, ForeignKey("order_items.id"), primary_key=True, index=True)
|
||||
quantity = Column(Float, nullable=True)
|
||||
|
||||
move = relationship("OrderMove", back_populates="items")
|
||||
|
||||
|
||||
class SplitBill(Base):
|
||||
"""A bill split by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py): chosen lines
|
||||
settled together (status "split") and cut into `parts` part lines that are paid on their own.
|
||||
Undone (undone_at) only while no part was paid or put on a tab."""
|
||||
__tablename__ = "split_bills"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||
total = Column(Float, nullable=False)
|
||||
mode = Column(String, nullable=False) # equal | custom
|
||||
parts = Column(Integer, nullable=False)
|
||||
amounts = Column(Text, nullable=False) # JSON [4.5, 10.5]: each part, in order
|
||||
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||
undone_at = Column(UTCDateTime, nullable=True)
|
||||
undone_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
receipt_issued_at = Column(UTCDateTime, nullable=True) # the fiscal receipt of the settled lines (last part paid)
|
||||
|
||||
@@ -227,6 +227,7 @@ class PriceEventLog(Base):
|
||||
# deal_offer_dismissed — waiter dismissed the deal offer
|
||||
# waiter_discount — manual waiter discount applied
|
||||
# free_item_added — free item added to order as result of a deal
|
||||
# manual_price — a price changed by hand (6F.3, services/price_changes.py)
|
||||
|
||||
modifier_id = Column(Integer, ForeignKey("price_modifiers.id"), nullable=True)
|
||||
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
||||
@@ -236,10 +237,15 @@ class PriceEventLog(Base):
|
||||
price_after = Column(Float, nullable=True)
|
||||
delta_amount = Column(Float, nullable=True) # price_after - price_before; negative = discount
|
||||
|
||||
# Waiter discount fields
|
||||
# Waiter discount fields (also manual_price: who changed it, and the reason)
|
||||
applied_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
waiter_note = Column(Text, nullable=True)
|
||||
|
||||
# manual_price (6F.3, services/price_changes.py): a price changed by hand
|
||||
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True) # a manager's PIN (D-10)
|
||||
stage = Column(String, nullable=True) # cart | sent | served
|
||||
quantity = Column(Float, nullable=True) # the line's quantity at the time
|
||||
|
||||
# Snapshot of the conditions that evaluated to True when the event fired.
|
||||
# JSON object: {"condition_type": evaluated_value, ...}
|
||||
# e.g. {"day_of_week": 5, "time_range": "21:45", "price_group_active": true}
|
||||
@@ -255,6 +261,7 @@ class PriceEventLog(Base):
|
||||
modifier = relationship("PriceModifier", foreign_keys=[modifier_id])
|
||||
deal = relationship("Deal", foreign_keys=[deal_id])
|
||||
applied_by = relationship("User", foreign_keys=[applied_by_user_id])
|
||||
approved_by = relationship("User", foreign_keys=[approved_by_user_id])
|
||||
|
||||
|
||||
class WaiterDiscountSettings(Base):
|
||||
|
||||
@@ -82,6 +82,8 @@ class Product(Base):
|
||||
|
||||
# Quick Add: allow adding 1 unit directly from product list without opening config modal
|
||||
quick_add_enabled = Column(Boolean, default=True, nullable=False)
|
||||
# "One more" (6F.5): a sent line of this product shows +1 (re-order the same, printed as new)
|
||||
one_more_enabled = Column(Boolean, default=False, nullable=False, server_default="0")
|
||||
|
||||
# Service item: non-inventoried table-service items (cutlery, glasses, etc.)
|
||||
is_service_item = Column(Boolean, default=False, nullable=False)
|
||||
|
||||
@@ -27,7 +27,8 @@ MODULE = Module(
|
||||
SettingDef('auth.default_login_mode', 'pin', "How staff log in on paired devices (KDS, counter POS) unless the device sets its own: 'pin' | 'password' | 'tap' | 'none'. Apps that can't use it fall back to their first mode.", type='enum', choices=('pin', 'password', 'tap', 'none')),
|
||||
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
|
||||
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||
SettingDef('auth.single_session_waiter', 'ask', "One waiter session per user, phones only (no double login): 'off' | 'refuse_new' | 'end_old' | 'ask' (the default: the phone asks, yes signs the other one out)", type='enum', choices=('off', 'refuse_new', 'end_old', 'ask')),
|
||||
SettingDef('auth.terminal_require_username', 'false', 'Paired screens (counter, KDS): type a username instead of picking a name; no names are listed, and "tap" is not used. A device can choose otherwise on the Devices page.', type='bool'),
|
||||
SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'),
|
||||
SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'),
|
||||
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
|
||||
|
||||
@@ -11,20 +11,37 @@ MODULE = Module(
|
||||
Perm('ordering.orders.open', 'Open orders and add items', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
|
||||
Perm('ordering.orders.close', 'Take payments and close orders', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
|
||||
Perm('ordering.orders.cancel', 'Cancel items already sent', roles=('owner', 'store_manager'), overridable=True),
|
||||
Perm('ordering.prices.modify', "Change an item's price", roles=('owner',), overridable=True),
|
||||
Perm('ordering.prices.modify', "Change an item's price before it is sent", roles=('owner',), overridable=True),
|
||||
Perm('ordering.prices.modify_sent', "Change the price of an item already sent or served", roles=('owner',), overridable=True),
|
||||
Perm('ordering.items.change_quantity', "Change a sent line's quantity (no new ticket)", roles=('owner', 'store_manager'), overridable=True),
|
||||
Perm('ordering.prices.view_changes', 'See the prices changed by hand (who, when, why)', roles=('owner', 'store_manager')),
|
||||
Perm('ordering.refunds', 'Refund payments from other shifts', roles=('owner', 'store_manager'), overridable=True),
|
||||
Perm('ordering.payments.revert', 'Turn paid items back to unpaid', roles=('owner', 'store_manager'), overridable=True),
|
||||
Perm('ordering.payments.split_amount', 'Split a bill by amount (equal parts or a ratio)', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter'), overridable=True),
|
||||
Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')),
|
||||
),
|
||||
settings=(
|
||||
SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'),
|
||||
SettingDef('business_day.auto_open', 'off', "The day opens by itself (6F.8): 'off' | 'schedule' (at the opening hours) | 'time' (every day at business_day.auto_open_time) | 'alert' (at the opening hours, only tell the managers)", type='enum', choices=('off', 'schedule', 'time', 'alert')),
|
||||
SettingDef('business_day.auto_close', 'off', "The day closes by itself (6F.8): 'off' | 'schedule' | 'time' | 'alert'. Closes only when every order of the day is closed; otherwise the managers are alerted and it tries again every 15 minutes.", type='enum', choices=('off', 'schedule', 'time', 'alert')),
|
||||
SettingDef('business_day.auto_open_time', '09:00', "HH:MM venue time, for business_day.auto_open = 'time' (6F.8).", type='str'),
|
||||
SettingDef('business_day.auto_close_time', '23:30', "HH:MM venue time, for business_day.auto_close = 'time' (6F.8).", type='str'),
|
||||
SettingDef('business_day.auto_ignore_break', 'true', "A day's opening spans count as one (first opening to last closing); 'false' = the break between spans closes the day and the next span opens a new one (6F.8).", type='bool'),
|
||||
SettingDef('business_day.auto_open_offset_min', '0', 'Open this many minutes before the opening hours start (6F.8, 0-720).', type='int'),
|
||||
SettingDef('business_day.auto_close_offset_min', '0', 'Close this many minutes after the opening hours end (6F.8, 0-720).', type='int'),
|
||||
SettingDef('business_day.rollover_hour', '6', 'Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.', type='int'),
|
||||
SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'),
|
||||
SettingDef('orders.close_with_unpaid', 'false', "Allow closing an order that still has unpaid items (they are written off as unpaid): 'true' | 'false'. When 'false', closing asks for the payment first (plan step 4.8).", type='bool'),
|
||||
SettingDef('orders.bypass_kds_serve', 'false', "Skip KDS pending/serve flow — new orders and items are immediately marked as served: 'true' | 'false'", type='bool'),
|
||||
SettingDef('orders.quantity_change', 'off', "Changing a sent line's quantity without sending it again (6F.5): 'off' | 'add_only' | 'add_and_remove' (lowering cancels the difference; also needs ordering.orders.cancel). Who may: ordering.items.change_quantity.", type='enum', choices=('off', 'add_only', 'add_and_remove')),
|
||||
SettingDef('orders.price_change', 'anytime', "Changing a line's price by hand (6F.3): 'off' | 'before_sending' (only in the cart) | 'anytime' (also a sent or served line). Who may: the keys ordering.prices.modify / modify_sent.", type='enum', choices=('off', 'before_sending', 'anytime')),
|
||||
SettingDef('orders.price_change_reason', 'false', "A price changed by hand needs a reason: 'true' | 'false' (6F.3).", type='bool'),
|
||||
SettingDef('orders.price_change_reasons', '[]', 'JSON array of quick reasons offered when a price is changed by hand (6F.3); [] = the built-in ones.', type='json'),
|
||||
SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'),
|
||||
SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'),
|
||||
SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'),
|
||||
SettingDef('payments.split_amount', 'off', "Splitting a bill by amount (6F.6), each level with the ones before: 'off' | 'two_equal' (half and half) | 'two_custom' (two parts in any ratio) | 'multiple_equal' (2 to payments.split_max_parts equal parts). Who may: ordering.payments.split_amount.", type='enum', choices=('off', 'two_equal', 'two_custom', 'multiple_equal')),
|
||||
SettingDef('payments.split_max_parts', '10', 'The most equal parts a bill can be split into (6F.6, 2-50).', type='int'),
|
||||
SettingDef('payments.card_enabled', 'false', "Allow waiters to record card payments (in addition to cash): 'true' | 'false'", type='bool'),
|
||||
SettingDef('print.alert_after_failures', '2', 'Tell managers when a kitchen/bar ticket has failed to print this many times and is still retrying (0 = never; they are always told when a ticket is finally given up).', type='int'),
|
||||
SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'),
|
||||
|
||||
@@ -44,7 +44,7 @@ def _check_secret(user, pin, password, db) -> bool:
|
||||
|
||||
|
||||
def do_login(db: Session, request: Request, *, client: str, username: str | None, user_id: int | None,
|
||||
pin: str | None, password: str | None) -> TokenResponse:
|
||||
pin: str | None, password: str | None, replace: bool = False) -> TokenResponse:
|
||||
"""The one login path. Applies the client's login mode, its access key and the
|
||||
single-session rule, then creates a session (core/sessions.py)."""
|
||||
if client not in ("manager", "waiter", "terminal"):
|
||||
@@ -81,7 +81,7 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
|
||||
if not holds(user, needed):
|
||||
raise XeniaError("auth.client_not_allowed", client=client)
|
||||
|
||||
row = sessions.start(db, user, client, request)
|
||||
row = sessions.start(db, user, client, request, replace=replace)
|
||||
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
|
||||
|
||||
|
||||
@@ -104,6 +104,10 @@ def _terminal_login(db: Session, request: Request, *, username, user_id, pin, pa
|
||||
raise XeniaError("auth.login_mode_not_allowed", mode="password")
|
||||
if mode == "password" and not password:
|
||||
raise XeniaError("auth.login_mode_not_allowed", mode="pin")
|
||||
if sessions.terminal_requires_username(db, device):
|
||||
if not username:
|
||||
raise XeniaError("auth.username_required")
|
||||
user_id = None # usernames only: a picked id isn't enough (6F.7)
|
||||
|
||||
q = db.query(User).filter(User.is_active == True) # noqa: E712
|
||||
user = q.filter(User.username == username).first() if username else (
|
||||
@@ -122,7 +126,7 @@ def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
|
||||
"""POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}.
|
||||
"terminal" = a user on a paired device: send the X-Xenia-Device header."""
|
||||
return do_login(db, request, client=body.client, username=body.username,
|
||||
user_id=body.user_id, pin=body.pin, password=body.password)
|
||||
user_id=body.user_id, pin=body.pin, password=body.password, replace=body.replace)
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=TokenResponse)
|
||||
|
||||
@@ -44,25 +44,8 @@ def open_business_day(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_manager),
|
||||
):
|
||||
existing = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if existing:
|
||||
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 XeniaError("license.locked")
|
||||
|
||||
# Gate: license expired and expiry grace period also over
|
||||
if not license_state.get("licensed", True):
|
||||
raise XeniaError("license.expired")
|
||||
|
||||
opened_at = utcnow()
|
||||
day = BusinessDay(opened_by_id=user.id, notes=body.notes,
|
||||
opened_at=opened_at, business_date=business_date_of(opened_at))
|
||||
db.add(day)
|
||||
db.commit()
|
||||
db.refresh(day)
|
||||
return day
|
||||
from services.business_days import open_day
|
||||
return open_day(db, user_id=user.id, notes=body.notes)
|
||||
|
||||
|
||||
@router.post("/close", response_model=BusinessDayOut)
|
||||
@@ -71,90 +54,9 @@ def close_business_day(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_manager),
|
||||
):
|
||||
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if not day:
|
||||
raise XeniaError("business_day.none_open")
|
||||
|
||||
open_orders = db.query(Order).filter(
|
||||
Order.business_day_id == day.id,
|
||||
Order.status.in_(["open", "partially_paid"]),
|
||||
).all()
|
||||
|
||||
if open_orders and not body.force:
|
||||
# Count orders that have at least one active (unpaid) item — covers both
|
||||
# "open" (fully unpaid) and "partially_paid" (partially unpaid) orders.
|
||||
with_pending = sum(
|
||||
1 for o in open_orders
|
||||
if db.query(OrderItem).filter(
|
||||
OrderItem.order_id == o.id,
|
||||
OrderItem.status == "active",
|
||||
).first() is not None
|
||||
)
|
||||
raise XeniaError("business_day.orders_open", open_orders=len(open_orders), partially_paid=with_pending)
|
||||
|
||||
now = utcnow()
|
||||
|
||||
# Close all non-terminal orders for this business day (open, partially_paid, paid)
|
||||
all_unclosed = db.query(Order).filter(
|
||||
Order.business_day_id == day.id,
|
||||
Order.status.in_(["open", "partially_paid", "paid"]),
|
||||
).all()
|
||||
for order in all_unclosed:
|
||||
was_unpaid = order.status in ("open", "partially_paid")
|
||||
order.status = "closed"
|
||||
order.closed_at = now
|
||||
order.closed_by = user.id
|
||||
if was_unpaid:
|
||||
db.add(OrderAuditLog(
|
||||
order_id=order.id,
|
||||
event_type="ORDER_CLOSED",
|
||||
waiter_id=user.id,
|
||||
note="Force-closed at end of business day",
|
||||
))
|
||||
|
||||
active_shifts = db.query(WaiterShift).filter(
|
||||
WaiterShift.business_day_id == day.id,
|
||||
WaiterShift.ended_at == None,
|
||||
).all()
|
||||
for shift in active_shifts:
|
||||
from routers.shifts import compute_shift_total
|
||||
shift.total_collected = compute_shift_total(shift.id, db)
|
||||
shift.ended_at = now
|
||||
|
||||
# Clear all table flags and staff messages — fresh slate for the next day
|
||||
db.query(TableFlagAssignment).delete(synchronize_session=False)
|
||||
db.query(StaffMessageAck).delete(synchronize_session=False)
|
||||
db.query(StaffMessage).delete(synchronize_session=False)
|
||||
|
||||
day.status = "closed"
|
||||
day.closed_at = now
|
||||
day.closed_by_id = user.id
|
||||
if body.notes:
|
||||
day.notes = body.notes
|
||||
|
||||
# Phase 2E: store-level cash reconciliation
|
||||
if body.store_closing_cash is not None:
|
||||
day.store_closing_cash = body.store_closing_cash
|
||||
# expected = store_opening_cash + sum of all waiter collected amounts this day
|
||||
all_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == day.id).all()
|
||||
total_collected = sum(s.total_collected or 0.0 for s in all_shifts)
|
||||
expected_closing = (day.store_opening_cash or 0.0) + total_collected
|
||||
day.store_cash_discrepancy = round(body.store_closing_cash - expected_closing, 2)
|
||||
|
||||
db.commit()
|
||||
db.refresh(day)
|
||||
|
||||
# Deferred lock: if cloud requested a lock while the workday was open,
|
||||
# enforce it now that the day has closed.
|
||||
if license_state.get("lock_pending"):
|
||||
license_state["lock_pending"] = False
|
||||
license_state["locked"] = True
|
||||
# Re-evaluate the license now that no workday is open (an expiry whose grace
|
||||
# ended mid-service takes effect here) — also persists the state
|
||||
from services.cloud_sync import apply_license
|
||||
apply_license()
|
||||
|
||||
return day
|
||||
from services.business_days import close_day
|
||||
return close_day(db, user_id=user.id, force=body.force, notes=body.notes,
|
||||
store_closing_cash=body.store_closing_cash)
|
||||
|
||||
|
||||
class PatchBusinessDayRequest(BaseModel):
|
||||
@@ -312,8 +214,9 @@ def business_day_summary(
|
||||
if o.table_id:
|
||||
waiter_tables.setdefault(o.opened_by, set()).add(o.table_id)
|
||||
|
||||
from services.split_bills import is_part
|
||||
for item in all_items:
|
||||
if item.status == "cancelled":
|
||||
if item.status == "cancelled" or is_part(item): # 6F.6: a split bill's parts are money, not items ordered
|
||||
continue
|
||||
e = _waiter_entry(item.added_by)
|
||||
e["items_ordered"] += item.quantity
|
||||
@@ -407,7 +310,8 @@ def business_day_summary(
|
||||
for item in o.items:
|
||||
if item.status == "cancelled":
|
||||
continue
|
||||
entry["items"] += item.quantity
|
||||
if not is_part(item):
|
||||
entry["items"] += item.quantity
|
||||
if item.status == "paid":
|
||||
entry["revenue"] += gross(item)
|
||||
|
||||
@@ -594,6 +498,7 @@ def business_day_history(
|
||||
"opened_by_name": (w_opener.full_name or w_opener.username) if w_opener else None,
|
||||
"closed_by_id": day.closed_by_id,
|
||||
"closed_by_name": (w_closer.full_name or w_closer.username) if w_closer else None,
|
||||
"opened_auto": bool(day.opened_auto), "closed_auto": bool(day.closed_auto), # 6F.8
|
||||
"notes": day.notes,
|
||||
"order_count": order_count,
|
||||
"revenue": round(revenue, 2),
|
||||
|
||||
@@ -151,6 +151,8 @@ def effective_login_mode(db, device) -> str:
|
||||
can't use that one, the app's first mode (signage etc.: 'none')."""
|
||||
modes = _app(device.app_key).device_app.login_modes
|
||||
mode = device.login_mode or sessions._setting(db, "auth.default_login_mode", "pin")
|
||||
if mode == "tap" and sessions.terminal_requires_username(db, device):
|
||||
mode = next((m for m in ("pin", "password") if m in modes), mode) # usernames: no name to tap (6F.7)
|
||||
return mode if mode in modes else modes[0]
|
||||
|
||||
|
||||
@@ -175,6 +177,8 @@ def _out(d: Device, db) -> dict:
|
||||
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key,
|
||||
"config": _effective_config(d, db) if d.app_key in registry() else {},
|
||||
"login_mode": d.login_mode,
|
||||
"require_username": d.require_username,
|
||||
"effective_require_username": sessions.terminal_requires_username(db, d),
|
||||
"effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None,
|
||||
"linked_device_id": d.linked_device_id, "user_agent": d.user_agent,
|
||||
"paired_at": iso_z(d.paired_at), "paired_by": d.paired_by,
|
||||
@@ -191,6 +195,7 @@ def _self_out(d: Device, db) -> dict:
|
||||
return {
|
||||
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db),
|
||||
"login_mode": effective_login_mode(db, d),
|
||||
"require_username": sessions.terminal_requires_username(db, d),
|
||||
"linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key}
|
||||
if linked is not None and linked.revoked_at is None else None),
|
||||
"app_status": status, # "ok" | "module.disabled" | "module.not_licensed": show "app disabled"
|
||||
@@ -249,6 +254,7 @@ class PairApprove(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=60)
|
||||
config: Optional[dict] = None
|
||||
login_mode: Optional[str] = None # None/"" = site default
|
||||
require_username: Optional[bool] = None # None = site default (6F.7)
|
||||
linked_device_id: Optional[int] = None
|
||||
|
||||
|
||||
@@ -256,6 +262,7 @@ class DevicePatch(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=60)
|
||||
config: Optional[dict] = None
|
||||
login_mode: Optional[str] = None # "" or null = back to the site default
|
||||
require_username: Optional[bool] = None # null = back to the site default (6F.7)
|
||||
linked_device_id: Optional[int] = None # null/0 = unlink
|
||||
|
||||
|
||||
@@ -285,6 +292,7 @@ def approve_device(body: PairApprove, db: Session = Depends(get_db), user=Depend
|
||||
d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key,
|
||||
config=_config(body.app_key, body.config, db),
|
||||
login_mode=_check_mode(body.app_key, body.login_mode),
|
||||
require_username=body.require_username,
|
||||
linked_device_id=_check_link(db, None, body.linked_device_id),
|
||||
user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None)
|
||||
db.add(d)
|
||||
@@ -307,8 +315,8 @@ def device_users(db: Session = Depends(get_db), device=Depends(require_device())
|
||||
"""Who can log in on this device (holders of '<app>.access'), for the name picker."""
|
||||
from core.access.queries import users_with_key
|
||||
from models.user import User
|
||||
if effective_login_mode(db, device) == "none":
|
||||
return []
|
||||
if effective_login_mode(db, device) == "none" or sessions.terminal_requires_username(db, device):
|
||||
return [] # usernames on (6F.7): nobody is listed, the screen asks for a username
|
||||
users = users_with_key(db, f"{device.app_key}.access").order_by(User.full_name).all()
|
||||
return [{"id": u.id, "full_name": u.full_name, "nickname": u.nickname, "avatar_url": u.avatar_url}
|
||||
for u in users if u.role != "superadmin"]
|
||||
@@ -357,6 +365,8 @@ def update_device(device_id: int, body: DevicePatch, db: Session = Depends(get_d
|
||||
d.config = _config(d.app_key, body.config, db)
|
||||
if "login_mode" in sent:
|
||||
d.login_mode = _check_mode(d.app_key, body.login_mode)
|
||||
if "require_username" in sent:
|
||||
d.require_username = body.require_username
|
||||
if "linked_device_id" in sent:
|
||||
d.linked_device_id = _check_link(db, d.id, body.linked_device_id)
|
||||
db.commit()
|
||||
|
||||
@@ -299,7 +299,7 @@ def bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"
|
||||
return {"lines": [], "total": 0, "paid": 0, "due": 0}
|
||||
lines = []
|
||||
for i in order.items:
|
||||
if i.status == "cancelled":
|
||||
if i.status in ("cancelled", "split"): # 6F.6: a split bill's parts stand for the lines it settled
|
||||
continue
|
||||
unit = (i.unit_price or 0) + (i.price_adjustment or 0)
|
||||
texts = menu_languages.product_texts(i.product, customer=False) if i.product else {}
|
||||
|
||||
@@ -21,7 +21,8 @@ router = APIRouter()
|
||||
|
||||
def _live(user):
|
||||
now = utcnow()
|
||||
return (visible_filter(user), (Notification.expires_at.is_(None)) | (Notification.expires_at > now))
|
||||
return (visible_filter(user), (Notification.expires_at.is_(None)) | (Notification.expires_at > now),
|
||||
Notification.resolved_at.is_(None))
|
||||
|
||||
|
||||
def _text(n, lang) -> str:
|
||||
|
||||
+310
-32
@@ -61,6 +61,7 @@ from core.access.deps import require
|
||||
from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket
|
||||
from models.settings import PosSettings
|
||||
from services.ws_bus import broadcast_sync
|
||||
from services import split_bills
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -343,7 +344,8 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"id": i.id,
|
||||
"order_id": i.order_id,
|
||||
"product_id": i.product_id,
|
||||
"product": {"id": i.product.id, "name": i.product.name} if i.product else None,
|
||||
"product": {"id": i.product.id, "name": i.product.name, "unit_type": i.product.unit_type or "piece",
|
||||
"one_more_enabled": bool(i.product.one_more_enabled)} if i.product else None, # 6F.5: +1
|
||||
"product_name": i.product_name, "category_id": i.category_id, "category_name": i.category_name,
|
||||
"added_by": i.added_by,
|
||||
"added_by_name": name_map.get(i.added_by),
|
||||
@@ -366,6 +368,10 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"system_key": i.system_key, # the delivery fee line (phase 3S, S.5)
|
||||
"source": i.source, # waiter | counter | qr | online (4.8)
|
||||
"course_id": i.course_id,
|
||||
"deal_id": i.deal_id, "linked_item_id": i.linked_item_id,
|
||||
"split_from_id": i.split_from_id, # 6F.4: the line it was cut from
|
||||
"cancel_reason": i.cancel_reason,
|
||||
"split_bill_id": i.split_bill_id, # 6F.6: settled into a split bill (status split) or one of its parts
|
||||
}
|
||||
|
||||
def fmt_log(l):
|
||||
@@ -418,6 +424,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"requested_for": _iso(order.requested_for),
|
||||
"online_delivery_area": order.online_delivery_area,
|
||||
"items": [fmt_item(i) for i in order.items],
|
||||
"split_bills": [split_bills.bill_out(b, order.items) for b in split_bills.live_bills(db, order.id)], # 6F.6
|
||||
"waiters": [{"waiter_id": w.waiter_id} for w in order.waiters],
|
||||
"audit_logs": [fmt_log(l) for l in order.audit_logs],
|
||||
}
|
||||
@@ -584,20 +591,27 @@ def add_items(order_id: int, body: AddLinesRequest, request: Request, db: Sessio
|
||||
raise XeniaError("order.not_yours")
|
||||
lines, manual = _resolve_lines(db, body.lines, of_order(order))
|
||||
approval = None
|
||||
reasons = [None] * len(lines)
|
||||
if any(manual) or any(line.discount_pct for line in lines):
|
||||
from services import price_changes # the venue's switch and the reason first (6F.3)
|
||||
reasons = [price_changes.check(db, sent=False, reason=(raw or {}).get("price_reason") if isinstance(raw, dict) else None,
|
||||
by_hand=bool(hand)) if hand or line.discount_pct else None
|
||||
for raw, line, hand in zip(body.lines, lines, manual)]
|
||||
approval = _need(request, db, user, "ordering.prices.modify", target=f"order {order_id} new items")
|
||||
discounts = [0.0] * len(lines)
|
||||
if any(line.discount_pct for line in lines):
|
||||
priced = pos_cart.price_lines(db, lines, order.order_type or "here", pos_cart.order_cart(order), point=of_order(order))
|
||||
discounts = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
|
||||
items = []
|
||||
for raw, line, hand, disc in zip(body.lines, lines, manual, discounts):
|
||||
for raw, line, hand, disc, reason in zip(body.lines, lines, manual, discounts, reasons):
|
||||
adj = round(hand + disc, 2)
|
||||
items.append(OrderItemInput(
|
||||
product_id=line.product.id, quantity=line.quantity,
|
||||
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
|
||||
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
|
||||
is_service_item=raw.get("is_service_item") is True, course_id=raw.get("course_id"),
|
||||
price_reason=reason if adj else None,
|
||||
price_approved_by=approval.approved_by if approval is not None and adj else None,
|
||||
))
|
||||
result = add_priced_items(order_id, AddItemsRequest(items=items, order_note=body.order_note,
|
||||
customer_count=body.customer_count), db, user)
|
||||
@@ -708,6 +722,11 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
|
||||
db.add(item)
|
||||
db.flush()
|
||||
new_item_ids.append(item.id)
|
||||
if item.price_adjustment: # a price changed by hand in the cart (6F.3)
|
||||
from services import price_changes
|
||||
price_changes.record(db, item=item, before=unit_price, after=unit_price + item.price_adjustment,
|
||||
user_id=user.id, stage="cart", reason=item_in.price_reason,
|
||||
approved_by=item_in.price_approved_by)
|
||||
|
||||
# Stamp order_id on events and queue them — written after commit
|
||||
if price_events:
|
||||
@@ -907,6 +926,9 @@ def cancel_item(
|
||||
raise XeniaError("order.item_not_found")
|
||||
if item.status == "paid":
|
||||
raise XeniaError("order.item_paid")
|
||||
if item.status not in ("active", "ready"):
|
||||
raise XeniaError("order.item_not_active")
|
||||
split_bills.refuse_parts([item]) # 6F.6: undo the split instead
|
||||
|
||||
now = utcnow()
|
||||
item.status = "cancelled"
|
||||
@@ -957,10 +979,13 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
|
||||
OrderItem.status.in_(["active", "ready"]), # ready items are also payable
|
||||
).all()
|
||||
|
||||
# Fiscal validation: if enabled, all items must have VAT group assigned before payment
|
||||
# Fiscal validation: if enabled, all items must have VAT group assigned before payment.
|
||||
# A split bill's parts (6F.6) aren't on a receipt themselves: the settled lines are, once the
|
||||
# last part is paid (checked when the bill was made).
|
||||
fiscal_on = is_fiscal_enabled(db)
|
||||
if fiscal_on and items:
|
||||
missing = validate_items_for_fiscal(items, db)
|
||||
own = [i for i in items if not split_bills.is_part(i)]
|
||||
if fiscal_on and own:
|
||||
missing = validate_items_for_fiscal(own, db)
|
||||
if missing:
|
||||
names = ", ".join(missing)
|
||||
raise XeniaError("pos.fiscal_vat_missing", names=names)
|
||||
@@ -1004,7 +1029,12 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
|
||||
order.closed_by = user.id
|
||||
auto_closed = True
|
||||
|
||||
if fiscal_on and items:
|
||||
bills_due = split_bills.receipts_due(db, items) # 6F.6: the last part of a split bill
|
||||
for due in bills_due:
|
||||
_audit(db, order_id, "SPLIT_SETTLED", waiter_id=user.id, item_ids=[i.id for i in due["lines"]],
|
||||
amount=due["bill"].total, note=" + ".join(f"{p['method']} {p['amount']:.2f}" for p in due["payments"]))
|
||||
fiscal_sent = fiscal_on and (bool(own) or bool(bills_due))
|
||||
if fiscal_sent:
|
||||
order.fiscal_status = "pending"
|
||||
|
||||
db.commit()
|
||||
@@ -1012,18 +1042,25 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
|
||||
if auto_closed:
|
||||
broadcast_sync("order_closed", {"order_id": order_id, "table_id": order.table_id, "auto_closed": True})
|
||||
|
||||
if fiscal_on and items:
|
||||
if fiscal_on and own:
|
||||
from database import SessionLocal
|
||||
fiscal_items = build_fiscal_items(items)
|
||||
send_fiscal_receipt_background(fiscal_items, effective_method, total_paid, db,
|
||||
fiscal_items = build_fiscal_items(own)
|
||||
own_total = sum((i.unit_price + (i.price_adjustment or 0.0)) * i.quantity for i in own)
|
||||
send_fiscal_receipt_background(fiscal_items, effective_method, own_total, db,
|
||||
order_id=order_id, db_factory=SessionLocal,
|
||||
timeout_seconds=60)
|
||||
if fiscal_on:
|
||||
from database import SessionLocal
|
||||
for due in bills_due: # the settled lines as if paid normally, with each method's amount (Q-3)
|
||||
send_fiscal_receipt_background(build_fiscal_items(due["lines"]), effective_method, due["bill"].total, db,
|
||||
order_id=order_id, db_factory=SessionLocal, timeout_seconds=60,
|
||||
payments=due["payments"])
|
||||
|
||||
return {
|
||||
"status": order.status,
|
||||
"paid_item_ids": paid_ids,
|
||||
"auto_closed": auto_closed,
|
||||
"fiscal": "pending" if fiscal_on and items else None,
|
||||
"fiscal": "pending" if fiscal_sent else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -1084,6 +1121,8 @@ def close_order(order_id: int, request: Request, db: Session = Depends(get_db),
|
||||
raise XeniaError("order.not_yours")
|
||||
if order.status not in ("paid", "open", "partially_paid"):
|
||||
raise XeniaError("order.cannot_close", status=order.status)
|
||||
if split_bills.has_unpaid_parts(db, order_id): # 6F.6: never written off: the settled lines were sold
|
||||
raise XeniaError("split.parts_unpaid")
|
||||
|
||||
now = utcnow()
|
||||
|
||||
@@ -1240,6 +1279,8 @@ def cancel_order(
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
# a manager may approve this one cancellation with their PIN (D-10)
|
||||
approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
|
||||
if split_bills.has_unpaid_parts(db, order_id): # 6F.6: undo the split first
|
||||
raise XeniaError("split.parts_unpaid")
|
||||
|
||||
now = utcnow()
|
||||
|
||||
@@ -1303,11 +1344,12 @@ def cancel_items_bulk(
|
||||
OrderItem.order_id == order_id,
|
||||
).all()
|
||||
|
||||
split_bills.refuse_parts(items) # 6F.6: undo the split instead
|
||||
now = utcnow()
|
||||
cancelled_ids = []
|
||||
skipped_paid = []
|
||||
for item in items:
|
||||
if item.status == "paid":
|
||||
if item.status not in ("active", "ready"): # paid, on a tab, settled by a split bill (6F.6)
|
||||
skipped_paid.append(item.id)
|
||||
continue
|
||||
item.status = "cancelled"
|
||||
@@ -1420,6 +1462,8 @@ def print_order(
|
||||
if item.status == "cancelled":
|
||||
continue
|
||||
product_name = item.product.name if item.product else f"#{item.product_id}"
|
||||
if item.split_bill_id is not None and item.status != "split":
|
||||
product_name = item.product_name # 6F.6: "Split bill 1/3"
|
||||
adj = getattr(item, 'price_adjustment', 0.0) or 0.0
|
||||
effective_price = item.unit_price + adj
|
||||
items_data.append({
|
||||
@@ -1431,7 +1475,7 @@ def print_order(
|
||||
"status": item.status,
|
||||
})
|
||||
|
||||
grand_total = sum(i["total"] for i in items_data)
|
||||
grand_total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them
|
||||
|
||||
receipt = {
|
||||
"order_id": order.id,
|
||||
@@ -1485,6 +1529,9 @@ def transfer_order(
|
||||
order.table_id = body.target_table_id
|
||||
_audit(db, order_id, "TABLE_TRANSFER", waiter_id=user.id,
|
||||
note=f"Transferred from table {old_table_id} to table {body.target_table_id}")
|
||||
from services import moves # 6F.4: the whole order and its lines, on the record
|
||||
moves.record(db, kind="table_transfer", source=order, target=order, items=list(order.items), user_id=user.id,
|
||||
from_table_id=old_table_id, to_table_id=body.target_table_id)
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "old_table_id": old_table_id, "status": order.status, "action": "transferred"})
|
||||
@@ -1527,10 +1574,14 @@ def merge_order(
|
||||
raise XeniaError("order.same_order")
|
||||
|
||||
# Move all items to target order
|
||||
from services import moves # 6F.4
|
||||
moves.record(db, kind="orders_merged", source=source, target=target, items=list(source.items), user_id=user.id)
|
||||
moved_item_ids = []
|
||||
for item in source.items:
|
||||
item.order_id = target.id
|
||||
moved_item_ids.append(item.id)
|
||||
from models.order import SplitBill # 6F.6: a split bill goes with its lines
|
||||
db.query(SplitBill).filter(SplitBill.order_id == source.id).update({SplitBill.order_id: target.id}, synchronize_session=False)
|
||||
|
||||
# Copy source waiters to target (no duplicates)
|
||||
existing_waiter_ids = {w.waiter_id for w in target.waiters}
|
||||
@@ -1568,6 +1619,68 @@ def merge_order(
|
||||
return target
|
||||
|
||||
|
||||
# ─── Split the bill by amount (6F.6, services/split_bills.py) ─────────────────
|
||||
|
||||
class SplitBillRequest(BaseModel):
|
||||
item_ids: List[int] = Field(min_length=1, max_length=500)
|
||||
mode: str = "equal" # equal | custom (two parts)
|
||||
parts: int = Field(default=2, ge=2, le=50)
|
||||
first_amount: Optional[float] = Field(default=None, gt=0, le=1000000) # custom: part 1, part 2 is the rest
|
||||
|
||||
|
||||
@router.post("/{order_id}/split-bills")
|
||||
def create_split_bill(order_id: int, body: SplitBillRequest, request: Request, db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user)):
|
||||
"""Settle the chosen unpaid lines into a split bill and cut it into parts paid on their own
|
||||
(equal parts, the remainder on the last; or two parts, part 1 typed). The venue's
|
||||
payments.split_amount decides which splits exist; the key ordering.payments.split_amount (a
|
||||
manager may approve it once, D-10) who may. The parts are paid with POST /pay like any line."""
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
if order.status not in ("open", "partially_paid"):
|
||||
raise XeniaError("order.not_open")
|
||||
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):
|
||||
raise XeniaError("split.lines_changed")
|
||||
bill = split_bills.create(db, order, items, mode=body.mode, parts=body.parts, first=body.first_amount, user=user)
|
||||
amounts = json.loads(bill.amounts)
|
||||
note = f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts)
|
||||
approved = _approval_note(approval)
|
||||
_audit(db, order_id, "SPLIT_CREATED", waiter_id=user.id, item_ids=ids, amount=bill.total,
|
||||
note=f"{note}; {approved}" if approved else note)
|
||||
db.commit()
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_created"})
|
||||
db.refresh(order)
|
||||
return split_bills.bill_out(bill, order.items)
|
||||
|
||||
|
||||
@router.post("/{order_id}/split-bills/{bill_id}/undo")
|
||||
def undo_split_bill(order_id: int, bill_id: int, request: Request, db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user)):
|
||||
"""Undo a split while none of its parts is paid or on a tab (Q-2): the parts are cancelled
|
||||
("split undone"), the lines are unpaid again. Same key as splitting."""
|
||||
from models.order import SplitBill
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
bill = db.get(SplitBill, bill_id)
|
||||
if bill is None:
|
||||
raise XeniaError("split.not_found")
|
||||
back = split_bills.undo(db, order, bill, user)
|
||||
_audit(db, order_id, "SPLIT_UNDONE", waiter_id=user.id, item_ids=back, amount=bill.total, note=_approval_note(approval))
|
||||
db.commit()
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_undone"})
|
||||
return {"item_ids": back}
|
||||
|
||||
|
||||
# ─── Split a stacked item into two rows ──────────────────────────────────────
|
||||
|
||||
@router.post("/{order_id}/items/{item_id}/split", response_model=List[OrderItemOut])
|
||||
@@ -1601,21 +1714,7 @@ def split_item(
|
||||
|
||||
# Reduce original item
|
||||
item.quantity -= body.quantity
|
||||
|
||||
# Create split-off item
|
||||
new_item = OrderItem(
|
||||
source=item.source,
|
||||
order_id=order_id,
|
||||
product_id=item.product_id,
|
||||
added_by=item.added_by,
|
||||
quantity=body.quantity,
|
||||
unit_price=item.unit_price,
|
||||
selected_options=item.selected_options,
|
||||
removed_ingredients=item.removed_ingredients,
|
||||
notes=item.notes,
|
||||
status="active",
|
||||
printed=item.printed,
|
||||
)
|
||||
new_item = cut_part(item, body.quantity)
|
||||
db.add(new_item)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
@@ -1623,10 +1722,141 @@ def split_item(
|
||||
return [item, new_item]
|
||||
|
||||
|
||||
def cut_part(item, quantity, **changes):
|
||||
"""A new line cut from `item` (a split, a lowered quantity, 6F.4/6F.5): everything the line was
|
||||
(product, price and its change, choices, note, kitchen state, course, cost, names, source) for
|
||||
`quantity`, linked by split_from_id so its moves follow it. Not added to the session."""
|
||||
fields = dict(
|
||||
source=item.source, order_id=item.order_id, product_id=item.product_id, added_by=item.added_by,
|
||||
quantity=quantity, unit_price=item.unit_price, selected_options=item.selected_options,
|
||||
removed_ingredients=item.removed_ingredients, notes=item.notes, status="active", printed=item.printed,
|
||||
split_from_id=item.id, kds_status=item.kds_status, course_id=item.course_id,
|
||||
price_adjustment=item.price_adjustment, unit_cost=item.unit_cost, product_name=item.product_name,
|
||||
category_id=item.category_id, category_name=item.category_name,
|
||||
) # added_at = now: the moment it was cut (services/moves.py reads it)
|
||||
fields.update(changes)
|
||||
return OrderItem(**fields)
|
||||
|
||||
|
||||
# ─── One more of a line, and a line's quantity (6F.5) ────────────────────────
|
||||
|
||||
class AgainRequest(BaseModel):
|
||||
quantity: int = Field(default=1, ge=1, le=50)
|
||||
|
||||
|
||||
@router.post("/{order_id}/items/{item_id}/again", response_model=AddItemsResponse)
|
||||
def order_again(order_id: int, item_id: int, body: AgainRequest, request: Request, db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user)):
|
||||
""""One more" (6F.5): a new line just like this one (product, choices, removed ingredients, note,
|
||||
course) for `quantity`, priced by the server now and sent like any new line (kitchen ticket,
|
||||
KDS). Only for products with one_more_enabled, counted in pieces, from an active, paid or
|
||||
tabbed line that isn't a deal's or the system's. Needs ordering.orders.open."""
|
||||
from core.access.context import current_device
|
||||
from schemas.order import OrderItemInput, SelectedOptionInput
|
||||
_need(request, db, user, "ordering.orders.open", target=f"order:{order_id}")
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||
if item is None:
|
||||
raise XeniaError("order.item_not_found")
|
||||
product = item.product
|
||||
if product is None or not product.one_more_enabled:
|
||||
raise XeniaError("order.one_more_off")
|
||||
if item.status not in ("active", "paid", "tabbed") or item.deal_id or item.linked_item_id \
|
||||
or product.system_key or (product.unit_type or "piece") != "piece":
|
||||
raise XeniaError("order.one_more_line")
|
||||
try:
|
||||
options = [SelectedOptionInput(**o) for o in json.loads(item.selected_options or "[]") if isinstance(o, dict)]
|
||||
removed = [str(x) for x in json.loads(item.removed_ingredients or "[]")]
|
||||
except (ValueError, TypeError):
|
||||
options, removed = [], []
|
||||
device = current_device(request, db)
|
||||
source = "counter" if device is not None and device.app_key == "pos_counter" else "waiter"
|
||||
result = add_priced_items(order_id, AddItemsRequest(items=[OrderItemInput(
|
||||
product_id=item.product_id, quantity=body.quantity, selected_options=options or None,
|
||||
removed_ingredients=removed or None, notes=item.notes, course_id=item.course_id, source=source,
|
||||
)]), db, user)
|
||||
_audit(db, order_id, "ITEM_REORDERED", waiter_id=user.id, item_ids=[item.id],
|
||||
note=f"{body.quantity:g} more of #{item.id}")
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
class QuantityRequest(BaseModel):
|
||||
quantity: int = Field(ge=1, le=999)
|
||||
print_cancellation: bool = False # lowering: send a cancellation to the kitchen (the app asks)
|
||||
|
||||
|
||||
@router.post("/{order_id}/items/{item_id}/quantity")
|
||||
def change_quantity(order_id: int, item_id: int, body: QuantityRequest, request: Request, background_tasks: BackgroundTasks,
|
||||
db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
"""Change a sent line's quantity without sending it again (6F.5). The venue
|
||||
(orders.quantity_change: off | add_only | add_and_remove) and ordering.items.change_quantity
|
||||
decide; lowering also needs ordering.orders.cancel (or a manager's PIN each). Up: the line
|
||||
grows, nothing is printed. Down: the removed part becomes its own cancelled line ("quantity
|
||||
lowered", split_from_id = the line) and, when asked, a cancellation ticket goes to the kitchen.
|
||||
Only unpaid lines counted in pieces, not a deal's or the system's."""
|
||||
from models.settings import PosSettings
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
row = db.query(PosSettings).filter(PosSettings.key == "orders.quantity_change").first()
|
||||
mode = row.value if row is not None and row.value in ("off", "add_only", "add_and_remove") else "off"
|
||||
if mode == "off":
|
||||
raise XeniaError("order.quantity_change_off")
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||
if item is None:
|
||||
raise XeniaError("order.item_not_found")
|
||||
product = item.product
|
||||
if item.status != "active" or item.deal_id or item.linked_item_id or (product is not None and product.system_key) \
|
||||
or (item.unit_type or "piece") != "piece" or item.quantity != int(item.quantity):
|
||||
raise XeniaError("order.quantity_line")
|
||||
old = int(item.quantity)
|
||||
if body.quantity == old:
|
||||
return {"item_id": item.id, "quantity": old, "cancelled_item_id": None}
|
||||
lowering = body.quantity < old
|
||||
if lowering and mode != "add_and_remove":
|
||||
raise XeniaError("order.quantity_remove_off")
|
||||
approval = _need(request, db, user, "ordering.items.change_quantity", target=f"order:{order_id} item:{item_id}")
|
||||
cancel_approval = None
|
||||
if lowering and not holds(user, "core.dashboard.access") and not _waiter_can_cancel(user, db):
|
||||
cancel_approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
|
||||
note = f"{old} → {body.quantity}" + (f" · {_approval_note(approval)}" if approval is not None else "")
|
||||
part = None
|
||||
if lowering:
|
||||
now = utcnow()
|
||||
part = cut_part(item, old - body.quantity, status="cancelled", cancelled_by=user.id, cancelled_at=now,
|
||||
cancel_reason="quantity lowered")
|
||||
db.add(part)
|
||||
item.quantity = body.quantity
|
||||
db.flush()
|
||||
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=[part.id],
|
||||
note=("quantity lowered" + (f" · {_approval_note(cancel_approval)}" if cancel_approval is not None else "")
|
||||
+ ("" if body.print_cancellation else " · no kitchen ticket")))
|
||||
else:
|
||||
item.quantity = body.quantity
|
||||
_audit(db, order_id, "QUANTITY_CHANGED", waiter_id=user.id, item_ids=[item.id], note=note)
|
||||
db.commit()
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
|
||||
"action": "quantity_changed", "item_ids": [item.id]})
|
||||
if part is not None:
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
|
||||
"action": "items_cancelled", "item_ids": [part.id]})
|
||||
if body.print_cancellation:
|
||||
background_tasks.add_task(print_cancellation_ticket, order_id, [part.id])
|
||||
return {"item_id": item.id, "quantity": item.quantity, "cancelled_item_id": part.id if part is not None else None}
|
||||
|
||||
|
||||
# ─── Adjust price on an existing item ────────────────────────────────────────
|
||||
|
||||
class PriceAdjustRequest(BaseModel):
|
||||
price_adjustment: float # delta from unit_price (can be negative)
|
||||
reason: Optional[str] = Field(default=None, max_length=200) # 6F.3: needed when the venue asks for one
|
||||
|
||||
|
||||
@router.patch("/{order_id}/items/{item_id}/price-adjust", response_model=OrderItemOut)
|
||||
@@ -1638,8 +1868,10 @@ def adjust_item_price(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Apply an on-the-fly price adjustment to an active order item. Without
|
||||
ordering.prices.modify a manager can approve it once (X-Xenia-Override, D-10)."""
|
||||
"""Change a sent line's price by hand (6F.3): the venue must allow it after sending
|
||||
(orders.price_change = anytime), it needs ordering.prices.modify_sent (a manager can approve it
|
||||
once, X-Xenia-Override, D-10) and, when the venue asks, a reason. Recorded as a manual_price
|
||||
event (before → after, who, the approver, the stage, the reason)."""
|
||||
item = db.query(OrderItem).filter(
|
||||
OrderItem.id == item_id, OrderItem.order_id == order_id
|
||||
).first()
|
||||
@@ -1647,19 +1879,56 @@ def adjust_item_price(
|
||||
raise XeniaError("order.item_not_found")
|
||||
if item.status != "active":
|
||||
raise XeniaError("order.item_not_active")
|
||||
split_bills.refuse_parts([item]) # 6F.6
|
||||
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
_need(request, db, user, "ordering.prices.modify", target=f"order:{order_id} item:{item_id}")
|
||||
from services import price_changes
|
||||
reason = price_changes.check(db, sent=True, reason=body.reason)
|
||||
approval = _need(request, db, user, "ordering.prices.modify_sent", target=f"order:{order_id} item:{item_id}")
|
||||
if not -10000 <= body.price_adjustment <= 10000 or item.unit_price + body.price_adjustment < 0:
|
||||
raise XeniaError("order.line.price", line=1, name=item.product_name)
|
||||
|
||||
item.price_adjustment = body.price_adjustment
|
||||
before = item.unit_price + (item.price_adjustment or 0.0)
|
||||
item.price_adjustment = round(body.price_adjustment, 2)
|
||||
price_changes.record(db, item=item, before=before, after=item.unit_price + item.price_adjustment, user_id=user.id,
|
||||
stage=price_changes.stage_of(item), reason=reason,
|
||||
approved_by=approval.approved_by if approval is not None else None)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "item_price_adjusted"})
|
||||
return item
|
||||
|
||||
|
||||
@router.get("/{order_id}/moves")
|
||||
def order_moves(order_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
"""Where an order and its lines came from (6F.4): {order: [the whole order's transfers and
|
||||
merges], items: {line id: [its moves, its parents' before it was split from them]}}. Each move:
|
||||
kind, at, from / to table (id, name) and order, who, the lines and quantities."""
|
||||
from services import moves
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
return moves.for_order(db, order)
|
||||
|
||||
|
||||
@router.get("/{order_id}/price-changes")
|
||||
def order_price_changes(order_id: int, db: Session = Depends(get_db),
|
||||
user: User = Depends(require("ordering.prices.view_changes"))):
|
||||
"""The prices changed by hand on an order (6F.3), oldest first, for the waiter app and the
|
||||
counter: [{id, item_id, product_name, before, after, delta, quantity, stage, reason, by, approved_by, at}]."""
|
||||
from models.pricing import PriceEventLog
|
||||
from services import price_changes
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
return [price_changes.event_out(ev, db) for ev in db.query(PriceEventLog).filter(
|
||||
PriceEventLog.order_id == order_id, PriceEventLog.event_type == price_changes.EVENT).order_by(PriceEventLog.id)]
|
||||
|
||||
|
||||
# ─── Waiter-applied manual discount ─────────────────────────────────────────
|
||||
|
||||
from schemas.pricing import ApplyDiscountRequest, ApplyDiscountResponse
|
||||
@@ -1697,6 +1966,7 @@ def apply_waiter_discount(
|
||||
).all()
|
||||
if not items:
|
||||
raise XeniaError("order.no_active_items", status=404)
|
||||
split_bills.refuse_parts(items) # 6F.6
|
||||
|
||||
item_unit_prices = {i.id: i.unit_price + i.price_adjustment for i in items}
|
||||
|
||||
@@ -1924,7 +2194,10 @@ def move_items(
|
||||
).all()
|
||||
if not items:
|
||||
raise XeniaError("order.no_active_items")
|
||||
split_bills.refuse_parts(items) # 6F.6: a part stays with its bill
|
||||
|
||||
from services import moves # 6F.4
|
||||
moves.record(db, kind="items_moved", source=source, target=target, items=items, user_id=user.id)
|
||||
moved_ids = []
|
||||
for item in items:
|
||||
item.order_id = target.id
|
||||
@@ -1988,6 +2261,8 @@ def print_synopsis(
|
||||
if item.status == "cancelled":
|
||||
continue
|
||||
product_name = item.product.name if item.product else f"#{item.product_id}"
|
||||
if item.split_bill_id is not None and item.status != "split":
|
||||
product_name = item.product_name # 6F.6: "Split bill 1/3"
|
||||
adj = getattr(item, 'price_adjustment', 0.0) or 0.0
|
||||
effective_price = item.unit_price + adj
|
||||
items_data.append({
|
||||
@@ -1999,7 +2274,7 @@ def print_synopsis(
|
||||
"status": item.status,
|
||||
})
|
||||
|
||||
total = sum(i["total"] for i in items_data)
|
||||
total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them
|
||||
paid_total = sum(i["total"] for i in items_data if i["status"] == "paid")
|
||||
|
||||
synopsis = {
|
||||
@@ -2112,6 +2387,7 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
|
||||
raise XeniaError("order.items_not_combinable", reason="not_found")
|
||||
if any(i.status != "active" for i in items):
|
||||
raise XeniaError("order.items_not_combinable", reason="not_unpaid")
|
||||
split_bills.refuse_parts(items) # 6F.6
|
||||
if any(i.deal_id or i.linked_item_id for i in items) or \
|
||||
db.query(OrderItem).filter(OrderItem.linked_item_id.in_(ids)).first() is not None:
|
||||
raise XeniaError("order.items_not_combinable", reason="deal")
|
||||
@@ -2127,6 +2403,8 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
|
||||
rest_ids = [i.id for i in rest]
|
||||
db.query(PriceEventLog).filter(PriceEventLog.order_item_id.in_(rest_ids)).update(
|
||||
{PriceEventLog.order_item_id: keep.id}, synchronize_session=False)
|
||||
from services import moves # 6F.4
|
||||
moves.repoint(db, rest_ids, keep.id)
|
||||
for i in rest:
|
||||
db.delete(i)
|
||||
_audit(db, order_id, "ITEMS_COMBINED", waiter_id=user.id, item_ids=[keep.id] + rest_ids,
|
||||
|
||||
@@ -89,6 +89,7 @@ def _product_out(p, price: float, prices: dict | None = None) -> dict:
|
||||
"price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()},
|
||||
"sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON],
|
||||
"base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
|
||||
"one_more": bool(p.one_more_enabled), # 6F.5
|
||||
"tags": _tags(p.tags),
|
||||
"allergens": allergens.of(p),
|
||||
"primary_category_id": p.primary_category_id,
|
||||
@@ -140,8 +141,12 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi
|
||||
by_point = {sp: pos_cart.unit_prices(db, products, sp) for sp in sales_points.IN_PERSON}
|
||||
default = pos_cart.point_for(settings["default_order_type"])
|
||||
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
|
||||
from services import price_changes, split_bills
|
||||
return {
|
||||
"settings": settings,
|
||||
# + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount
|
||||
"settings": {**settings, "price_change": price_changes.mode(db),
|
||||
# 6F.6: splitting a bill by amount (the level and the most equal parts)
|
||||
"split_amount": split_bills.level(db), "split_max_parts": split_bills.max_parts(db)},
|
||||
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
|
||||
for c in cats],
|
||||
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON})
|
||||
@@ -177,14 +182,25 @@ class Payment(BaseModel):
|
||||
lines: Optional[List[int]] = None # indexes into `lines`; None = all of them
|
||||
|
||||
|
||||
class SaleSplit(BaseModel):
|
||||
"""A quick sale split by amount (6F.6, Q-4): the parts and how each is paid, all now."""
|
||||
mode: Literal["equal", "custom"] = "equal"
|
||||
parts: int = Field(default=2, ge=2, le=50)
|
||||
first_amount: Optional[float] = Field(default=None, gt=0, le=1000000)
|
||||
methods: List[Literal["cash", "card"]] = Field(min_length=2, max_length=50) # one per part
|
||||
|
||||
|
||||
class SaleBody(BaseModel):
|
||||
order_type: Literal["takeaway", "here"] = "takeaway"
|
||||
lines: List[dict] = Field(min_length=1, max_length=200)
|
||||
payments: List[Payment] = Field(min_length=1, max_length=2)
|
||||
payments: List[Payment] = Field(default_factory=list, max_length=2) # without `split`: at least one
|
||||
split: Optional[SaleSplit] = None
|
||||
cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
|
||||
|
||||
|
||||
def _payment_groups(body: SaleBody, n: int) -> list:
|
||||
if not body.payments:
|
||||
raise XeniaError("pos.payment_invalid", reason="lines")
|
||||
if len(body.payments) == 1 and body.payments[0].lines is None:
|
||||
return [(body.payments[0].method, list(range(n)))]
|
||||
seen = [i for pay in body.payments for i in (pay.lines or [])]
|
||||
@@ -208,17 +224,19 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
|
||||
_require_shift(db, user)
|
||||
orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key
|
||||
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
|
||||
groups = _payment_groups(body, len(lines))
|
||||
_check_discounts(request, db, user, lines)
|
||||
groups = _payment_groups(body, len(lines)) if body.split is None else []
|
||||
approved_by = _check_discounts(request, db, user, lines)
|
||||
_check_fiscal(db, {line.product for line in lines})
|
||||
priced = pos_cart.price_lines(db, lines, body.order_type)
|
||||
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
|
||||
totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)]
|
||||
if body.split is not None:
|
||||
return _split_sale(body, request, db, user, lines, adjs, approved_by, totals)
|
||||
cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2)
|
||||
_check_cash(body.cash_given, cash_due)
|
||||
|
||||
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
|
||||
item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
|
||||
paid, fiscal = [], None
|
||||
for method, idx in groups:
|
||||
@@ -236,6 +254,53 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
|
||||
}
|
||||
|
||||
|
||||
def _split_sale(body, request, db, user, lines, adjs, approved_by, totals):
|
||||
"""A quick sale split by amount (6F.6, Q-4): the order and its lines as any quick sale, then
|
||||
the lines settled into a split bill and each part paid now by its own method (one payment per
|
||||
method). The fiscal receipt is the lines themselves, issued with the last part (Q-3)."""
|
||||
from models.order import OrderItem
|
||||
from routers import orders as orders_api
|
||||
from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest
|
||||
from services import split_bills
|
||||
sp = body.split
|
||||
orders_api._need(request, db, user, "ordering.payments.split_amount", target="pos sale")
|
||||
if len(sp.methods) != sp.parts:
|
||||
raise XeniaError("pos.payment_invalid", reason="lines")
|
||||
if not split_bills.allowed(split_bills.level(db), sp.mode, sp.parts, split_bills.max_parts(db)):
|
||||
raise XeniaError("split.not_allowed")
|
||||
total = round(sum(totals), 2)
|
||||
if total < 0.01 * sp.parts:
|
||||
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
|
||||
amounts = split_bills.amounts(total, sp.mode, sp.parts, sp.first_amount)
|
||||
cash_due = round(sum(a for a, m in zip(amounts, sp.methods) if m == "cash"), 2)
|
||||
_check_cash(body.cash_given, cash_due)
|
||||
|
||||
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
|
||||
items = db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()
|
||||
bill = split_bills.create(db, order, items, mode=sp.mode, parts=sp.parts, first=sp.first_amount, user=user)
|
||||
orders_api._audit(db, order.id, "SPLIT_CREATED", waiter_id=user.id, item_ids=[i.id for i in items], amount=bill.total,
|
||||
note=f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts))
|
||||
db.commit()
|
||||
parts = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id, OrderItem.status == "active").order_by(OrderItem.id).all()
|
||||
paid, fiscal = [], None
|
||||
for method in ("cash", "card"):
|
||||
ids = [p.id for p, m in zip(parts, sp.methods) if m == method]
|
||||
if not ids:
|
||||
continue
|
||||
res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=ids, payment_method=method), request, db, user)
|
||||
paid.append({"method": method, "amount": round(sum(a for a, m in zip(amounts, sp.methods) if m == method), 2),
|
||||
"item_ids": res["paid_item_ids"]})
|
||||
fiscal = res.get("fiscal") or fiscal
|
||||
drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none"
|
||||
change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None
|
||||
return {
|
||||
"order_id": order.id, "total": total, "payments": paid, "split": {"id": bill.id, "amounts": amounts, "methods": sp.methods},
|
||||
"cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal,
|
||||
"print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []),
|
||||
}
|
||||
|
||||
|
||||
# ── shared checks (3.3b, 3.3c) ─────────────────────────────────────────────────
|
||||
|
||||
def _require_shift(db, user):
|
||||
@@ -247,9 +312,16 @@ def _require_shift(db, user):
|
||||
|
||||
|
||||
def _check_discounts(request, db, user, lines):
|
||||
"""A % discount at the counter is a price change in the cart (6F.3): the venue's switch, then
|
||||
the key (or a manager's PIN). Returns the approving manager's id, else None. The reason isn't
|
||||
asked: the discount itself says what it is."""
|
||||
from core.access.context import authorize
|
||||
from services import price_changes
|
||||
if any(line.discount_pct for line in lines):
|
||||
authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
|
||||
price_changes.check(db, sent=False, by_hand=False)
|
||||
approval = authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
|
||||
return approval.approved_by if approval is not None else None
|
||||
return None
|
||||
|
||||
|
||||
def _check_fiscal(db, products):
|
||||
@@ -265,14 +337,17 @@ def _check_cash(cash_given, cash_due):
|
||||
raise XeniaError("pos.payment_invalid", reason="cash_short")
|
||||
|
||||
|
||||
def _items_in(lines, adjs):
|
||||
def _items_in(lines, adjs, approved_by=None):
|
||||
"""Resolved lines as orders.add_priced_items takes them (selected_options entries with the
|
||||
database's prices; a discount as the item's price_adjustment)."""
|
||||
database's prices; a discount as the item's price_adjustment, recorded as a manual_price event
|
||||
with "−N %" as its reason, 6F.3)."""
|
||||
from schemas.order import OrderItemInput, SelectedOptionInput
|
||||
return [OrderItemInput(
|
||||
product_id=line.product.id, quantity=line.quantity,
|
||||
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
|
||||
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None, source="counter",
|
||||
price_reason=f"−{line.discount_pct:g} %" if adj and line.discount_pct else None,
|
||||
price_approved_by=approved_by if adj else None,
|
||||
) for line, adj in zip(lines, adjs)]
|
||||
|
||||
|
||||
@@ -407,13 +482,13 @@ def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: S
|
||||
elif not _in_zones(db, user, table):
|
||||
raise XeniaError("pos.table_not_yours", table=_table_name(table))
|
||||
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
|
||||
_check_discounts(request, db, user, lines)
|
||||
approved_by = _check_discounts(request, db, user, lines)
|
||||
existing = pos_cart.order_cart(order) if order is not None else None
|
||||
priced = pos_cart.price_lines(db, lines, (order.order_type or "here") if order is not None else "here", existing)
|
||||
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
|
||||
if order is None:
|
||||
order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
|
||||
return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])}
|
||||
|
||||
|
||||
@@ -445,7 +520,8 @@ def pos_order_pay(order_id: int, body: OrderPayBody, request: Request, db: Sessi
|
||||
items = {i.id: i for i in db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.id.in_(wanted)).all()}
|
||||
if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()):
|
||||
raise XeniaError("pos.items_changed")
|
||||
_check_fiscal(db, {i.product for i in items.values()})
|
||||
from services.split_bills import is_part
|
||||
_check_fiscal(db, {i.product for i in items.values() if not is_part(i)}) # 6F.6: the settled lines were checked
|
||||
amount = {pay.method: round(sum(_item_total(items[i]) for i in pay.item_ids), 2) for pay in body.payments}
|
||||
cash_due = amount.get("cash", 0.0)
|
||||
_check_cash(body.cash_given, cash_due)
|
||||
|
||||
@@ -527,12 +527,11 @@ def get_order_price_events(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
events = (
|
||||
db.query(PriceEventLog)
|
||||
.filter(PriceEventLog.order_id == order_id)
|
||||
.order_by(PriceEventLog.applied_at)
|
||||
.all()
|
||||
)
|
||||
from services import price_changes
|
||||
q = db.query(PriceEventLog).filter(PriceEventLog.order_id == order_id)
|
||||
if not price_changes.can_view(user): # prices changed by hand: ordering.prices.view_changes (6F.3)
|
||||
q = q.filter(PriceEventLog.event_type != price_changes.EVENT)
|
||||
events = q.order_by(PriceEventLog.applied_at).all()
|
||||
result = []
|
||||
for ev in events:
|
||||
out = PriceEventOut.model_validate(ev)
|
||||
@@ -541,7 +540,9 @@ def get_order_price_events(
|
||||
if ev.deal:
|
||||
out.deal_name = ev.deal.name
|
||||
if ev.applied_by:
|
||||
out.applied_by_username = ev.applied_by.username
|
||||
out.applied_by_username = ev.applied_by.nickname or ev.applied_by.username
|
||||
if ev.approved_by:
|
||||
out.approved_by_username = ev.approved_by.nickname or ev.approved_by.username
|
||||
result.append(out)
|
||||
return result
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ from core.access.queries import holders_filter
|
||||
from core.errors import XeniaError
|
||||
from core.modules.entitlements import clamp_start, history_floor, history_since, limit
|
||||
from core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow
|
||||
from services import tab_books
|
||||
from services import split_bills, tab_books # split_bills: 6F.6, settled lines count, parts never
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
@@ -164,7 +164,7 @@ def shift_orders_summary(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
"""Items sent (added) per waiter — regardless of payment status."""
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
q = db.query(OrderItem).filter(split_bills.sold_filter())
|
||||
start = end = None # 6.12a: with a business day there is no window (was a crash)
|
||||
if business_day_id:
|
||||
q = q.join(Order).filter(Order.business_day_id == business_day_id)
|
||||
@@ -496,7 +496,7 @@ def printer_totals(
|
||||
item_ids = []
|
||||
for item_id in item_ids:
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id).first()
|
||||
if item and item.status in ("active", "paid"):
|
||||
if item and split_bills.counts_as_sale(item):
|
||||
summary[pid]["items"] += item.quantity
|
||||
val = _item_val(item)
|
||||
summary[pid]["total"] += val
|
||||
@@ -565,7 +565,7 @@ def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, m
|
||||
item_ids = []
|
||||
for item_id in item_ids:
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id).first()
|
||||
if item and item.status in ("active", "paid"):
|
||||
if item and split_bills.counts_as_sale(item):
|
||||
items_count += item.quantity
|
||||
val = _item_val(item)
|
||||
grand_total += val
|
||||
@@ -633,7 +633,7 @@ def print_waiter(
|
||||
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
order_data = []
|
||||
for o in orders:
|
||||
active_items = [i for i in o.items if i.status in ("active", "paid")]
|
||||
active_items = [i for i in o.items if split_bills.counts_as_sale(i)]
|
||||
total = sum(_item_val(i) for i in active_items)
|
||||
order_data.append({
|
||||
"id": o.id,
|
||||
@@ -648,7 +648,7 @@ def print_waiter(
|
||||
})
|
||||
|
||||
items_count = sum(
|
||||
i.quantity for o in orders for i in o.items if i.status in ("active", "paid")
|
||||
i.quantity for o in orders for i in o.items if split_bills.counts_as_sale(i)
|
||||
)
|
||||
grand_total = sum(d["total"] for d in order_data)
|
||||
|
||||
@@ -778,7 +778,7 @@ def print_products(
|
||||
period_label, period_is_workday = _analytics_period(body, db)
|
||||
|
||||
# Build sold-item summary
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
q = db.query(OrderItem).filter(split_bills.sold_filter())
|
||||
if body.business_day_id:
|
||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||
elif body.from_dt and body.to_dt:
|
||||
@@ -837,7 +837,7 @@ def print_categories(
|
||||
|
||||
period_label, period_is_workday = _analytics_period(body, db)
|
||||
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
q = db.query(OrderItem).filter(split_bills.sold_filter())
|
||||
if body.business_day_id:
|
||||
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
|
||||
elif body.from_dt and body.to_dt:
|
||||
@@ -974,7 +974,7 @@ def product_performance(
|
||||
from models.product import Product
|
||||
from models.waste import WasteLog
|
||||
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
q = db.query(OrderItem).filter(split_bills.sold_filter())
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(OrderItem.added_at >= _since)
|
||||
@@ -1187,6 +1187,7 @@ def business_days_list(
|
||||
"closed_at": _dt(d.closed_at),
|
||||
"opened_by": (opener.full_name or opener.username) if opener else None,
|
||||
"closed_by": (closer.full_name or closer.username) if closer else None,
|
||||
"opened_auto": bool(d.opened_auto), "closed_auto": bool(d.closed_auto), # 6F.8: by the system
|
||||
"notes": d.notes,
|
||||
"order_count": len(orders),
|
||||
"closed_order_count": len(closed_orders),
|
||||
@@ -1337,7 +1338,7 @@ def category_performance(
|
||||
):
|
||||
from models.product import Product, Category
|
||||
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
q = db.query(OrderItem).filter(split_bills.sold_filter())
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(OrderItem.added_at >= _since)
|
||||
@@ -1504,7 +1505,7 @@ def printer_history(
|
||||
order_total = sum(
|
||||
_item_val(i)
|
||||
for i in order.items
|
||||
if i.status in ("active", "paid")
|
||||
if split_bills.counts_as_sale(i)
|
||||
)
|
||||
if log.success and log.order_id not in seen_order_totals:
|
||||
seen_order_totals[log.order_id] = order_total
|
||||
@@ -1713,7 +1714,7 @@ def prep_zones_report(
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
if business_day_id:
|
||||
q = q.filter(Order.business_day_id == business_day_id)
|
||||
q = q.filter(OrderItem.status.in_(["active", "paid"]))
|
||||
q = q.filter(split_bills.sold_filter())
|
||||
items = q.all()
|
||||
|
||||
# Aggregate per zone
|
||||
@@ -1839,7 +1840,7 @@ def print_prep_zone(
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
|
||||
if body.business_day_id:
|
||||
q = q.filter(Order.business_day_id == body.business_day_id)
|
||||
q = q.filter(OrderItem.status.in_(["active", "paid"]))
|
||||
q = q.filter(split_bills.sold_filter())
|
||||
items = q.all()
|
||||
|
||||
product_counts: dict[str, dict] = {}
|
||||
@@ -1872,6 +1873,133 @@ def print_prep_zone(
|
||||
# Phase 2L — Discount audit report
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.get("/moves")
|
||||
def moves_report(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
to_dt: Optional[str] = Query(default=None, alias="to"),
|
||||
business_day_id: Optional[int] = None,
|
||||
kind: Optional[str] = None,
|
||||
by: Optional[int] = None,
|
||||
table_id: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
"""Moves between tables and orders (6F.4) in a period or a business day: each move (kind, from /
|
||||
to table and order, who, the lines with their quantity and value), counts per kind and per
|
||||
person. `table_id`: moves from or to that table."""
|
||||
from models.order import OrderMove, OrderItem
|
||||
from services import moves
|
||||
q = db.query(OrderMove)
|
||||
if business_day_id:
|
||||
q = q.filter(OrderMove.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
q = q.filter(OrderMove.at >= history_since(from_dt, 'reports'), OrderMove.at <= parse_api_datetime(to_dt))
|
||||
if kind:
|
||||
q = q.filter(OrderMove.kind == kind)
|
||||
if by:
|
||||
q = q.filter(OrderMove.by_user_id == by)
|
||||
if table_id:
|
||||
q = q.filter((OrderMove.from_table_id == table_id) | (OrderMove.to_table_id == table_id))
|
||||
rows = q.order_by(OrderMove.at.desc()).all()
|
||||
tables, users = moves._names(db)
|
||||
item_ids = {i.item_id for m in rows for i in m.items}
|
||||
lines = {i.id: i for i in db.query(OrderItem).filter(OrderItem.id.in_(item_ids)).all()} if item_ids else {}
|
||||
names = {i.id: i.product_name for i in lines.values()}
|
||||
out, by_kind, by_person = [], {}, {}
|
||||
for m in rows:
|
||||
row = moves.move_out(m, tables, users, names)
|
||||
row["at"] = _dt(m.at)
|
||||
row["value"] = round(sum(((lines[i.item_id].unit_price or 0) + (lines[i.item_id].price_adjustment or 0)) * (i.quantity or lines[i.item_id].quantity or 0)
|
||||
for i in m.items if i.item_id in lines), 2)
|
||||
out.append(row)
|
||||
by_kind[m.kind] = by_kind.get(m.kind, 0) + 1
|
||||
p = by_person.setdefault(m.by_user_id, {"user_id": m.by_user_id, "name": row["by"], "count": 0})
|
||||
p["count"] += 1
|
||||
return {"moves": out, "count": len(out), "by_kind": by_kind,
|
||||
"by_person": sorted(by_person.values(), key=lambda x: -x["count"])}
|
||||
|
||||
|
||||
@router.get("/moves/export")
|
||||
def moves_export(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
to_dt: Optional[str] = Query(default=None, alias="to"),
|
||||
business_day_id: Optional[int] = None,
|
||||
kind: Optional[str] = None,
|
||||
by: Optional[int] = None,
|
||||
table_id: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
data = moves_report(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, kind=kind, by=by, table_id=table_id, db=db, user=user)
|
||||
rows = [{"id": m["id"], "at": m["at"], "kind": m["kind"], "from_table": m["from_table"] or "", "to_table": m["to_table"] or "",
|
||||
"from_order": m["from_order_id"], "to_order": m["to_order_id"], "by": m["by"] or "",
|
||||
"lines": "; ".join(f"{i.get('name') or i['item_id']} ×{i['quantity'] if i['quantity'] is not None else '?'}" for i in m["items"]),
|
||||
"value": m["value"]} for m in data["moves"]]
|
||||
fields = ["id", "at", "kind", "from_table", "to_table", "from_order", "to_order", "by", "lines", "value"]
|
||||
return csv_export.response(db, rows, fields, f"moves-{(from_dt or '')[:10]}.csv", times=("at",))
|
||||
|
||||
|
||||
@router.get("/price-changes")
|
||||
def price_changes_report(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
to_dt: Optional[str] = Query(default=None, alias="to"),
|
||||
business_day_id: Optional[int] = None,
|
||||
applied_by: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
"""Prices changed by hand (6F.3) in a period or a business day: each change (the line, before →
|
||||
after, the difference for its quantity, the stage, who, the approving manager, why, the table),
|
||||
totals per person. Needs ordering.prices.view_changes besides the reports key."""
|
||||
from core.access.check import holds
|
||||
from models.pricing import PriceEventLog
|
||||
from services import price_changes
|
||||
if not holds(user, "ordering.prices.view_changes"):
|
||||
raise XeniaError("access.denied", key="ordering.prices.view_changes")
|
||||
q = db.query(PriceEventLog).filter(PriceEventLog.event_type == price_changes.EVENT)
|
||||
if business_day_id:
|
||||
q = q.join(Order, Order.id == PriceEventLog.order_id).filter(Order.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
q = q.filter(PriceEventLog.applied_at >= history_since(from_dt, 'reports'),
|
||||
PriceEventLog.applied_at <= parse_api_datetime(to_dt))
|
||||
if applied_by:
|
||||
q = q.filter(PriceEventLog.applied_by_user_id == applied_by)
|
||||
events = q.order_by(PriceEventLog.applied_at.desc()).all()
|
||||
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
orders_map = {o.id: o for o in db.query(Order).filter(Order.id.in_({e.order_id for e in events})).all()} if events else {}
|
||||
rows, by_person, total = [], {}, 0.0
|
||||
for ev in events:
|
||||
row = price_changes.event_out(ev, db)
|
||||
row["at"] = _dt(ev.applied_at)
|
||||
order = orders_map.get(ev.order_id)
|
||||
row["table_name"] = tables_map.get(order.table_id) if order is not None and order.table_id else None
|
||||
row["value"] = round((ev.delta_amount or 0.0) * (ev.quantity or 1.0), 2)
|
||||
total += row["value"]
|
||||
p = by_person.setdefault(ev.applied_by_user_id, {"user_id": ev.applied_by_user_id, "name": row["by"], "count": 0, "total_value": 0.0})
|
||||
p["count"] += 1
|
||||
p["total_value"] = round(p["total_value"] + row["value"], 2)
|
||||
rows.append(row)
|
||||
return {"changes": rows, "total_value": round(total, 2), "count": len(rows),
|
||||
"by_person": sorted(by_person.values(), key=lambda x: x["total_value"])}
|
||||
|
||||
|
||||
@router.get("/price-changes/export")
|
||||
def price_changes_export(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
to_dt: Optional[str] = Query(default=None, alias="to"),
|
||||
business_day_id: Optional[int] = None,
|
||||
applied_by: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
data = price_changes_report(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, applied_by=applied_by, db=db, user=user)
|
||||
rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table_name"] or "", "product": c["product_name"] or "",
|
||||
"quantity": c["quantity"], "before": c["before"], "after": c["after"], "value": c["value"], "stage": c["stage"] or "",
|
||||
"by": c["by"] or "", "approved_by": c["approved_by"] or "", "reason": c["reason"] or "", "at": c["at"]} for c in data["changes"]]
|
||||
fields = ["id", "order_id", "table", "product", "quantity", "before", "after", "value", "stage", "by", "approved_by", "reason", "at"]
|
||||
return csv_export.response(db, rows, fields, f"price-changes-{(from_dt or '')[:10]}.csv", times=("at",))
|
||||
|
||||
|
||||
@router.get("/discounts")
|
||||
def discounts_report(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
|
||||
@@ -89,4 +89,7 @@ def update_setting(
|
||||
timeutil.invalidate() # live: next call re-reads the setting
|
||||
if key == "venue.language":
|
||||
i18n.invalidate()
|
||||
if key in ("auth.default_login_mode", "auth.terminal_require_username"):
|
||||
from services import ws_bus
|
||||
ws_bus.notify_device(every_device=True) # paired screens re-read how people sign in (6F.7)
|
||||
return {"key": setting.key, "value": setting.value}
|
||||
|
||||
@@ -8,6 +8,7 @@ class LoginRequest(BaseModel):
|
||||
user_id: int | None = None # waiter picks their name (when the username isn't required)
|
||||
pin: str | None = None
|
||||
password: str | None = None
|
||||
replace: bool = False # rule "ask": yes, sign my other phone out (6F.7)
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
|
||||
@@ -9,7 +9,9 @@ class BusinessDayOut(BaseModel):
|
||||
status: str
|
||||
opened_at: UTCDatetime
|
||||
business_date: date
|
||||
opened_by_id: int
|
||||
opened_by_id: Optional[int] = None # None = opened by the system (6F.8)
|
||||
opened_auto: bool = False
|
||||
closed_auto: bool = False
|
||||
closed_at: Optional[UTCDatetime] = None
|
||||
closed_by_id: Optional[int] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
@@ -26,6 +26,9 @@ class OrderItemInput(BaseModel):
|
||||
is_service_item: bool = False # priceless: print-once ephemeral; priced: saved as real item
|
||||
course_id: Optional[int] = None
|
||||
source: Optional[str] = None # set by the server (4.8): waiter | counter | qr | online
|
||||
# a price changed by hand (6F.3), set by the server: the reason and the approving manager
|
||||
price_reason: Optional[str] = None
|
||||
price_approved_by: Optional[int] = None
|
||||
|
||||
|
||||
class AddItemsRequest(BaseModel):
|
||||
@@ -37,6 +40,8 @@ class AddItemsRequest(BaseModel):
|
||||
class ProductNameOut(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
one_more_enabled: bool = False # 6F.5: the line shows +1
|
||||
unit_type: Optional[str] = None
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
@@ -68,6 +73,7 @@ class OrderItemOut(BaseModel):
|
||||
source: Optional[str] = None # waiter | counter | qr | online (4.8); None = before 4.8
|
||||
deal_id: Optional[int] = None
|
||||
linked_item_id: Optional[int] = None
|
||||
split_from_id: Optional[int] = None # 6F.4: the line it was cut from
|
||||
system_key: Optional[str] = None # a line the system added: "delivery_fee" (phase 3S, S.5)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -308,10 +308,15 @@ class PriceEventOut(BaseModel):
|
||||
conditions_snapshot: Optional[dict]
|
||||
selected_item_ids: Optional[List[int]]
|
||||
applied_at: datetime
|
||||
# manual_price (6F.3)
|
||||
approved_by_user_id: Optional[int] = None
|
||||
stage: Optional[str] = None
|
||||
quantity: Optional[float] = None
|
||||
# Resolved names (joined at query time)
|
||||
modifier_name: Optional[str] = None
|
||||
deal_name: Optional[str] = None
|
||||
applied_by_username: Optional[str] = None
|
||||
approved_by_username: Optional[str] = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
@@ -386,6 +386,7 @@ class ProductBase(BaseModel):
|
||||
cost_breakdown: Optional[List[CostBreakdownItem]] = None
|
||||
# Quick Add
|
||||
quick_add_enabled: bool = True
|
||||
one_more_enabled: bool = False # 6F.5
|
||||
# Tags
|
||||
tags: Optional[List[str]] = None
|
||||
# The EU allergens (plan step 6.3): {key: "contains" | "may_contain"}, core/allergens.py
|
||||
@@ -437,6 +438,7 @@ class ProductUpdate(BaseModel):
|
||||
cost_breakdown: Optional[List[CostBreakdownItem]] = None
|
||||
# Quick Add
|
||||
quick_add_enabled: Optional[bool] = None
|
||||
one_more_enabled: Optional[bool] = None # 6F.5
|
||||
# Tags
|
||||
tags: Optional[List[str]] = None
|
||||
allergens: Optional[Dict[str, str]] = None # None = unchanged, {} = none
|
||||
@@ -510,6 +512,7 @@ class ProductOut(ProductBase):
|
||||
'cost_simple': data.cost_simple,
|
||||
'cost_breakdown': parsed,
|
||||
'quick_add_enabled': getattr(data, 'quick_add_enabled', True),
|
||||
'one_more_enabled': bool(getattr(data, 'one_more_enabled', False)),
|
||||
'tags': json.loads(data.tags) if isinstance(getattr(data, 'tags', None), str) else (getattr(data, 'tags', None) or []),
|
||||
'allergens': _allergens_of(data),
|
||||
'translations': _menu_tr_of(data),
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Opening and closing the business day: the one way, used by the manager's buttons
|
||||
(routers/business_day.py) and by the automatic open / close (services/day_auto.py, plan 6F.8).
|
||||
|
||||
- open_day(db, user_id=None, auto=True): a day opened by the system has no opener
|
||||
(opened_by_id NULL) and opened_auto set. The license gates apply to both.
|
||||
- close_day(db, user_id=None, auto=True): the same close as a manager's: unclosed orders are
|
||||
closed (the automatic close only runs when there are none, Q-10), open shifts end with
|
||||
their totals, flags and staff messages are cleared, a lock the cloud asked for while the
|
||||
day was open takes effect, the license is re-evaluated.
|
||||
- unclosed_orders(db, day): what "a table is still open" means for the automatic close: every
|
||||
order of the day that isn't closed or cancelled (paid but not closed counts too).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from core.errors import XeniaError
|
||||
from core.timeutil import business_date_of, utcnow
|
||||
|
||||
|
||||
def current(db):
|
||||
from models.business_day import BusinessDay
|
||||
return db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
|
||||
|
||||
def license_blocked() -> str | None:
|
||||
"""The error code that stops a day from opening now, or None."""
|
||||
from services.license_state import license_state
|
||||
if license_state.get("locked") or license_state.get("lock_pending"):
|
||||
return "license.locked"
|
||||
if not license_state.get("licensed", True):
|
||||
return "license.expired"
|
||||
return None
|
||||
|
||||
|
||||
def open_day(db, *, user_id: int | None = None, notes: str | None = None, auto: bool = False, at=None):
|
||||
from models.business_day import BusinessDay
|
||||
if current(db) is not None:
|
||||
raise XeniaError("business_day.already_open")
|
||||
blocked = license_blocked()
|
||||
if blocked:
|
||||
raise XeniaError(blocked)
|
||||
opened_at = at or utcnow() # `at`: the automatic open's clock (tests drive it)
|
||||
day = BusinessDay(opened_by_id=user_id, notes=notes, opened_at=opened_at,
|
||||
business_date=business_date_of(opened_at), opened_auto=auto)
|
||||
db.add(day)
|
||||
db.commit()
|
||||
db.refresh(day)
|
||||
from services import day_auto
|
||||
day_auto.resolve_alerts(db)
|
||||
return day
|
||||
|
||||
|
||||
def unclosed_orders(db, day):
|
||||
from models.order import Order
|
||||
return db.query(Order).filter(Order.business_day_id == day.id,
|
||||
Order.status.in_(["open", "partially_paid", "paid"])).all()
|
||||
|
||||
|
||||
def close_day(db, *, user_id: int | None = None, force: bool = False, notes: str | None = None,
|
||||
store_closing_cash: float | None = None, auto: bool = False, at=None):
|
||||
from models.business_day import BusinessDay # noqa: F401
|
||||
from models.flag import TableFlagAssignment
|
||||
from models.message import StaffMessage, StaffMessageAck
|
||||
from models.order import Order, OrderAuditLog, OrderItem
|
||||
from models.shift import WaiterShift
|
||||
from services.license_state import license_state
|
||||
|
||||
day = current(db)
|
||||
if not day:
|
||||
raise XeniaError("business_day.none_open")
|
||||
|
||||
open_orders = db.query(Order).filter(
|
||||
Order.business_day_id == day.id,
|
||||
Order.status.in_(["open", "partially_paid"]),
|
||||
).all()
|
||||
if open_orders and not force:
|
||||
# Count orders that have at least one active (unpaid) item — covers both
|
||||
# "open" (fully unpaid) and "partially_paid" (partially unpaid) orders.
|
||||
with_pending = sum(
|
||||
1 for o in open_orders
|
||||
if db.query(OrderItem).filter(OrderItem.order_id == o.id, OrderItem.status == "active").first() is not None
|
||||
)
|
||||
raise XeniaError("business_day.orders_open", open_orders=len(open_orders), partially_paid=with_pending)
|
||||
|
||||
now = at or utcnow()
|
||||
# Close all non-terminal orders for this business day (open, partially_paid, paid)
|
||||
for order in unclosed_orders(db, day):
|
||||
was_unpaid = order.status in ("open", "partially_paid")
|
||||
order.status = "closed"
|
||||
order.closed_at = now
|
||||
order.closed_by = user_id
|
||||
if was_unpaid:
|
||||
db.add(OrderAuditLog(order_id=order.id, event_type="ORDER_CLOSED", waiter_id=user_id,
|
||||
note="Force-closed at end of business day"))
|
||||
|
||||
from routers.shifts import compute_shift_total
|
||||
for shift in db.query(WaiterShift).filter(WaiterShift.business_day_id == day.id, WaiterShift.ended_at == None).all(): # noqa: E711
|
||||
shift.total_collected = compute_shift_total(shift.id, db)
|
||||
shift.ended_at = now
|
||||
|
||||
# Clear all table flags and staff messages — fresh slate for the next day
|
||||
db.query(TableFlagAssignment).delete(synchronize_session=False)
|
||||
db.query(StaffMessageAck).delete(synchronize_session=False)
|
||||
db.query(StaffMessage).delete(synchronize_session=False)
|
||||
|
||||
day.status = "closed"
|
||||
day.closed_at = now
|
||||
day.closed_by_id = user_id
|
||||
day.closed_auto = auto
|
||||
if notes:
|
||||
day.notes = notes
|
||||
|
||||
# Phase 2E: store-level cash reconciliation
|
||||
if store_closing_cash is not None:
|
||||
day.store_closing_cash = store_closing_cash
|
||||
all_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == day.id).all()
|
||||
expected_closing = (day.store_opening_cash or 0.0) + sum(s.total_collected or 0.0 for s in all_shifts)
|
||||
day.store_cash_discrepancy = round(store_closing_cash - expected_closing, 2)
|
||||
|
||||
db.commit()
|
||||
db.refresh(day)
|
||||
|
||||
# Deferred lock: if cloud requested a lock while the workday was open, enforce it now.
|
||||
if license_state.get("lock_pending"):
|
||||
license_state["lock_pending"] = False
|
||||
license_state["locked"] = True
|
||||
# Re-evaluate the license now that no workday is open (an expiry whose grace
|
||||
# ended mid-service takes effect here) — also persists the state
|
||||
from services.cloud_sync import apply_license
|
||||
apply_license()
|
||||
from services import day_auto
|
||||
day_auto.resolve_alerts(db)
|
||||
return day
|
||||
@@ -43,7 +43,8 @@ def card(db, customer) -> dict:
|
||||
from models.table import Table
|
||||
orders = db.query(Order).filter(Order.customer_id == customer.id).order_by(Order.opened_at.desc()).all()
|
||||
done = [o for o in orders if o.status in ("closed", "paid")]
|
||||
live = lambda o: [i for i in o.items if i.status in ("active", "paid")] # noqa: E731
|
||||
from services.split_bills import counts_as_sale
|
||||
live = lambda o: [i for i in o.items if counts_as_sale(i)] # noqa: E731 (6F.6: settled lines, not parts)
|
||||
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
return {
|
||||
"id": customer.id, "name": customer.name, "nickname": customer.nickname, "phone": customer.phone,
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
"""The business day opens and closes by itself (owner 2026-11-23, plan 6F.8).
|
||||
|
||||
Settings (modules/ordering/manifest.py, Settings → Operation → "Opening and closing the day"):
|
||||
- business_day.auto_open / auto_close: 'off' | 'schedule' (the venue's opening hours,
|
||||
venue.opening_hours) | 'time' (every day at business_day.auto_open_time / auto_close_time,
|
||||
whatever the hours) | 'alert' (at the opening hours' moment, only tell the managers).
|
||||
- business_day.auto_ignore_break: on = a day's spans count as one (first opening → last
|
||||
closing); off = the gap between spans closes the day and the next span opens a new one.
|
||||
- business_day.auto_open_offset_min / auto_close_offset_min (Q-11): open N minutes before the
|
||||
hours start, close N minutes after they end. Not used by 'time'.
|
||||
|
||||
How it decides (tick(), every minute in the background, venue time, offline-safe):
|
||||
- Windows: each day's spans from the opening hours (a span whose `to` is before `from` ends the
|
||||
next day and belongs to the day it starts), with the offsets; yesterday, today and tomorrow
|
||||
are looked at. 'time' opens from its time until the next rollover hour (business_day.
|
||||
rollover_hour: a restart catches up only while it's still that business date) and closes at
|
||||
the last close time.
|
||||
- Open is due inside a window when no day is open and no day was opened or closed since the
|
||||
window began (a day a manager closed by hand isn't reopened inside the same span). On a
|
||||
restart this opens a day that is still due (catch-up).
|
||||
- Close is due when a day is open and was opened before the last closing moment. It runs only
|
||||
when no order of the day is still unclosed (Q-10); otherwise it alerts "tables still open"
|
||||
and tries again every 15 minutes. A close missed while the server was off isn't done later:
|
||||
the managers are alerted instead.
|
||||
- Alerts are sticky notifications for holders of ordering.business_day.manage (core
|
||||
notifications, dedupe below); they resolve when the day opens / closes (resolve_alerts, also
|
||||
called by services/business_days.py at once). A locked or expired license makes the open an
|
||||
alert too.
|
||||
- The day opened / closed by the system has no opener / closer and opened_auto / closed_auto.
|
||||
|
||||
Agent notes:
|
||||
- tick(db, now=..., started_at=...) is pure apart from the DB and the in-memory retry time, so
|
||||
tests drive it with a fake clock (tests/test_day_auto.py). `now` is aware UTC, like utcnow().
|
||||
- Only one process runs the loop (the backend's lifespan); the retry time lives in memory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import date, datetime, time, timedelta
|
||||
|
||||
from core.timeutil import utcnow
|
||||
|
||||
logger = logging.getLogger("xenia.day_auto")
|
||||
|
||||
MODES = ("off", "schedule", "time", "alert")
|
||||
CHECK_EVERY_S = 60
|
||||
RETRY_CLOSE = timedelta(minutes=15)
|
||||
AUDIENCE = "perm:ordering.business_day.manage"
|
||||
# sticky alerts (dedupe keys)
|
||||
NOT_OPEN = "business_day.not_open"
|
||||
OPEN_BLOCKED = "business_day.open_blocked"
|
||||
TABLES_OPEN = "business_day.tables_open"
|
||||
NOT_CLOSED = "business_day.not_closed"
|
||||
|
||||
_state = {"next_close_try": None, "started_at": None}
|
||||
|
||||
|
||||
# ── settings ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def _setting(db, key, default):
|
||||
from core.sessions import _setting as read
|
||||
return read(db, key, default)
|
||||
|
||||
|
||||
def _mode(db, which):
|
||||
v = _setting(db, f"business_day.auto_{which}", "off")
|
||||
return v if v in MODES else "off"
|
||||
|
||||
|
||||
def _minutes(db, key):
|
||||
try:
|
||||
return max(0, min(720, int(_setting(db, key, "0"))))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def _clock(v):
|
||||
try:
|
||||
h, m = (int(x) for x in (v or "").split(":"))
|
||||
return time(h, m)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
# ── windows (venue time, naive) ──────────────────────────────────────────────
|
||||
|
||||
def spans_of(hours_days, d: date, ignore_break: bool) -> list[tuple[datetime, datetime]]:
|
||||
"""The opening spans of calendar day d (Monday-first hours), as naive venue datetimes."""
|
||||
out = []
|
||||
for s in (hours_days[d.weekday()] if hours_days and len(hours_days) == 7 else []):
|
||||
a, b = _clock(s.get("from")), _clock(s.get("to"))
|
||||
if a is None or b is None:
|
||||
continue
|
||||
start = datetime.combine(d, a)
|
||||
end = datetime.combine(d, b)
|
||||
if end <= start:
|
||||
end += timedelta(days=1) # past midnight: belongs to the day it starts
|
||||
out.append((start, end))
|
||||
out.sort()
|
||||
if ignore_break and out:
|
||||
out = [(out[0][0], max(e for _, e in out))]
|
||||
return out
|
||||
|
||||
|
||||
def windows(db, which: str, now_local: datetime) -> list[tuple[datetime, datetime]]:
|
||||
"""Open windows (start, end) around now for the open ('open') or close ('close') side."""
|
||||
mode = _mode(db, which)
|
||||
if mode == "time":
|
||||
at = _clock(_setting(db, f"business_day.auto_{which}_time", ""))
|
||||
if at is None:
|
||||
return []
|
||||
if which == "open":
|
||||
first = datetime.combine(now_local.date(), at)
|
||||
if first > now_local:
|
||||
first -= timedelta(days=1)
|
||||
# catch-up only until the business date changes (the rollover hour), not all night
|
||||
from core.timeutil import rollover_hour
|
||||
end = datetime.combine(first.date(), time(rollover_hour()))
|
||||
while end <= first:
|
||||
end += timedelta(days=1)
|
||||
return [(first, end)]
|
||||
last = datetime.combine(now_local.date(), at)
|
||||
if last > now_local:
|
||||
last -= timedelta(days=1)
|
||||
return [(last - timedelta(days=1), last)] # only its end (the close moment) is used
|
||||
from routers.identity import hours_out
|
||||
days = hours_out(db)["days"]
|
||||
ignore = _setting(db, "business_day.auto_ignore_break", "true") == "true"
|
||||
before = timedelta(minutes=_minutes(db, "business_day.auto_open_offset_min"))
|
||||
after = timedelta(minutes=_minutes(db, "business_day.auto_close_offset_min"))
|
||||
out = []
|
||||
for k in (-1, 0, 1):
|
||||
for a, b in spans_of(days, now_local.date() + timedelta(days=k), ignore):
|
||||
out.append((a - before, b + after))
|
||||
return sorted(out)
|
||||
|
||||
|
||||
# ── alerts ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def _alert(db, dedupe, key, params, severity="warning"):
|
||||
from core.notifications import notify
|
||||
notify(key, severity, AUDIENCE, params, dedupe_key=dedupe, fold=False, db=db)
|
||||
|
||||
|
||||
def resolve_alerts(db) -> None:
|
||||
"""Hide the alerts whose cause is gone: a day is open → the 'not open' ones; none open → the
|
||||
closing ones. Never raises."""
|
||||
try:
|
||||
from core.notifications import resolve
|
||||
from services.business_days import current
|
||||
resolve(db, [NOT_OPEN, OPEN_BLOCKED] if current(db) is not None else [TABLES_OPEN, NOT_CLOSED])
|
||||
except Exception:
|
||||
logger.exception("day_auto.resolve_failed")
|
||||
|
||||
|
||||
# ── the tick ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def tick(db, now: datetime | None = None, started_at: datetime | None = None) -> list[str]:
|
||||
"""Do what is due now. Returns what happened (for logs and tests): 'opened', 'closed',
|
||||
'alert:<key>', 'waiting' (tables open, retry later)."""
|
||||
from core.timeutil import to_venue, venue_local_to_utc
|
||||
from models.business_day import BusinessDay
|
||||
from services import business_days as ops
|
||||
|
||||
now = now or utcnow()
|
||||
started_at = started_at or _state["started_at"] or datetime.min.replace(tzinfo=now.tzinfo)
|
||||
open_mode, close_mode = _mode(db, "open"), _mode(db, "close")
|
||||
did: list[str] = []
|
||||
if open_mode == "off" and close_mode == "off":
|
||||
return did
|
||||
now_local = to_venue(now).replace(tzinfo=None)
|
||||
utc = venue_local_to_utc # naive venue time → aware UTC
|
||||
hhmm = lambda local: local.strftime("%H:%M") # noqa: E731
|
||||
day = ops.current(db)
|
||||
|
||||
# ── close first (a break's end closes before the next span opens) ──
|
||||
if close_mode != "off" and day is not None:
|
||||
ends = [e for _, e in windows(db, "close", now_local) if e <= now_local]
|
||||
last = max(ends) if ends else None
|
||||
if last is not None and day.opened_at < utc(last):
|
||||
if close_mode == "alert" or started_at > utc(last):
|
||||
_alert(db, NOT_CLOSED, NOT_CLOSED, {"time": hhmm(last), "action": "overview"})
|
||||
did.append(f"alert:{NOT_CLOSED}")
|
||||
else:
|
||||
retry = _state["next_close_try"]
|
||||
if retry is None or now >= retry:
|
||||
unclosed = ops.unclosed_orders(db, day)
|
||||
if unclosed:
|
||||
_state["next_close_try"] = now + RETRY_CLOSE
|
||||
_alert(db, TABLES_OPEN, TABLES_OPEN, {"time": hhmm(last), "count": len(unclosed), "action": "overview"})
|
||||
did += [f"alert:{TABLES_OPEN}", "waiting"]
|
||||
else:
|
||||
ops.close_day(db, auto=True, at=now)
|
||||
_state["next_close_try"] = None
|
||||
logger.info("day_auto.closed day=%s moment=%s", day.id, last)
|
||||
did.append("closed")
|
||||
day = None
|
||||
else:
|
||||
did.append("waiting")
|
||||
|
||||
# ── open ──
|
||||
if open_mode != "off" and day is None:
|
||||
inside = [(a, b) for a, b in windows(db, "open", now_local) if a <= now_local < b]
|
||||
if inside:
|
||||
start = max(a for a, _ in inside)
|
||||
since = utc(start)
|
||||
touched = db.query(BusinessDay).filter((BusinessDay.opened_at >= since) | (BusinessDay.closed_at >= since)).first()
|
||||
if touched is None:
|
||||
blocked = ops.license_blocked()
|
||||
if open_mode == "alert":
|
||||
_alert(db, NOT_OPEN, NOT_OPEN, {"time": hhmm(start), "action": "open_day"})
|
||||
did.append(f"alert:{NOT_OPEN}")
|
||||
elif blocked:
|
||||
_alert(db, OPEN_BLOCKED, OPEN_BLOCKED, {"time": hhmm(start), "reason": blocked}, severity="critical")
|
||||
did.append(f"alert:{OPEN_BLOCKED}")
|
||||
else:
|
||||
ops.open_day(db, auto=True, at=now)
|
||||
logger.info("day_auto.opened moment=%s", start)
|
||||
did.append("opened")
|
||||
resolve_alerts(db)
|
||||
return did
|
||||
|
||||
|
||||
# ── the loop ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def _tick_once() -> None:
|
||||
from database import SessionLocal
|
||||
db = SessionLocal()
|
||||
try:
|
||||
did = tick(db)
|
||||
if did:
|
||||
logger.info("day_auto.tick %s", ",".join(did))
|
||||
except Exception:
|
||||
logger.exception("day_auto.tick_failed")
|
||||
db.rollback()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
async def _run() -> None:
|
||||
_state["started_at"] = utcnow()
|
||||
while True:
|
||||
await asyncio.to_thread(_tick_once)
|
||||
await asyncio.sleep(CHECK_EVERY_S)
|
||||
|
||||
|
||||
async def start() -> asyncio.Task:
|
||||
return asyncio.create_task(_run())
|
||||
|
||||
|
||||
def reset_for_tests() -> None:
|
||||
_state.update(next_close_try=None, started_at=None)
|
||||
@@ -125,13 +125,14 @@ def _in_background(db_factory, model, row_id: int, prepare, timeout_seconds: int
|
||||
|
||||
|
||||
def send_fiscal_receipt_background(items: list[dict], payment_method: str, total: float, db, order_id: int,
|
||||
db_factory, timeout_seconds: int = 60) -> None:
|
||||
db_factory, timeout_seconds: int = 60, payments: list[dict] | None = None) -> None:
|
||||
"""Issue the receipt through the venue's driver in a background thread; order.fiscal_status
|
||||
becomes success or failed when the device answers (or the wait times out)."""
|
||||
becomes success or failed when the device answers (or the wait times out). `payments`
|
||||
[{"method", "amount"}]: a receipt paid in several ways (a split bill's parts, 6F.6)."""
|
||||
from models.order import Order
|
||||
driver = driver_for(db)
|
||||
_in_background(db_factory, Order, order_id, lambda: driver.prepare_receipt(db, items, payment_method, total),
|
||||
timeout_seconds)
|
||||
_in_background(db_factory, Order, order_id,
|
||||
lambda: driver.prepare_receipt(db, items, payment_method, total, payments=payments), timeout_seconds)
|
||||
|
||||
|
||||
def send_credit_note_background(items: list[dict], method: str, total: float, db, refund_id: int, original: dict,
|
||||
|
||||
@@ -28,8 +28,9 @@ class FiscalDriver:
|
||||
# cashier is told to issue the credit note on the machine itself (owner decision 2026-11-15).
|
||||
credit_notes: bool = False
|
||||
|
||||
def prepare_receipt(self, db, items: list[dict], method: str, total: float) -> Send:
|
||||
"""A sales receipt, ready to send."""
|
||||
def prepare_receipt(self, db, items: list[dict], method: str, total: float, payments: list[dict] | None = None) -> Send:
|
||||
"""A sales receipt, ready to send. `payments` [{"method", "amount"}] when it was paid in
|
||||
several ways (a split bill, 6F.6); else all of it by `method`."""
|
||||
raise NotImplementedError
|
||||
|
||||
def prepare_credit_note(self, db, items: list[dict], method: str, total: float, original: dict | None = None) -> Send:
|
||||
|
||||
@@ -62,7 +62,7 @@ def _get_folders(db) -> tuple[str, str]:
|
||||
return out_folder, in_folder
|
||||
|
||||
|
||||
def _build_command_file(items: list[dict], payment_method: str, total: float, db) -> str:
|
||||
def _build_command_file(items: list[dict], payment_method: str, total: float, db, payments: list[dict] | None = None) -> str:
|
||||
"""
|
||||
Build the fiscal command file content as a string.
|
||||
|
||||
@@ -98,7 +98,15 @@ def _build_command_file(items: list[dict], payment_method: str, total: float, db
|
||||
if msg_line.strip():
|
||||
lines.append(f"FM|{i}|{msg_line.upper()}")
|
||||
|
||||
if payment_method == "card":
|
||||
if payments and len(payments) > 1:
|
||||
# Paid in several ways (a split bill, 6F.6; the driver manual's "multiple ways to close"):
|
||||
# each card amount through the EFT/POS first, then cash closes the rest.
|
||||
card = [p for p in payments if p.get("method") == "card" and p.get("amount", 0) > 0]
|
||||
for p in card:
|
||||
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{p['amount']:.2f}")
|
||||
if round(sum(p.get("amount", 0) for p in payments if p not in card), 2) > 0:
|
||||
lines.append(f"CR|{clerk_id}")
|
||||
elif (payments[0].get("method") if payments else payment_method) == "card":
|
||||
total_str = f"{total:.2f}"
|
||||
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{total_str}")
|
||||
else:
|
||||
@@ -177,11 +185,11 @@ class TxtFileDriver(FiscalDriver):
|
||||
name = "dTEC100extra (text-file bridge)"
|
||||
credit_notes = False
|
||||
|
||||
def prepare_receipt(self, db, items, method, total):
|
||||
def prepare_receipt(self, db, items, method, total, payments=None):
|
||||
out_folder, in_folder = _get_folders(db)
|
||||
os.makedirs(out_folder, exist_ok=True)
|
||||
os.makedirs(in_folder, exist_ok=True)
|
||||
content = _build_command_file(items, method, total, db)
|
||||
content = _build_command_file(items, method, total, db, payments)
|
||||
filename = _unique_filename()
|
||||
return lambda timeout_seconds: _write_and_poll(out_folder, in_folder, content, filename, timeout_seconds)
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Moves on the record (owner 2026-11-23, plan step 6F.4).
|
||||
|
||||
Every move between tables or orders is an `OrderMove` row with the lines that went
|
||||
(`OrderMoveItem`: the line and its quantity then):
|
||||
- `table_transfer`: the whole order went to another (free) table (POST /api/orders/{id}/transfer);
|
||||
- `items_moved`: chosen lines went to another open order (POST /api/orders/{id}/move-items);
|
||||
- `orders_merged`: an order was joined into another (POST /api/orders/{id}/merge).
|
||||
|
||||
A line keeps its id when it moves, so its path is its own moves. A line cut from another
|
||||
(`OrderItem.split_from_id`: a split, later a lowered quantity or a split payment) also carries
|
||||
the moves its parent had **before** the cut, however many times that happened. Combining lines
|
||||
moves the removed lines' moves to the line that stays (routers/orders.combine_items).
|
||||
|
||||
Readers: GET /api/orders/{id}/moves (the order's path and each line's), Reports → Moves
|
||||
(GET /api/reports/moves). The old OrderAuditLog rows stay as they were.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
KINDS = ("table_transfer", "items_moved", "orders_merged")
|
||||
|
||||
|
||||
def record(db, *, kind: str, source, target, items, user_id: int | None, from_table_id=None, to_table_id=None,
|
||||
approved_by: int | None = None):
|
||||
"""One move (flushed with the caller's commit). `source` / `target`: orders; `items`: lines."""
|
||||
from models.order import OrderMove, OrderMoveItem
|
||||
assert kind in KINDS, kind
|
||||
move = OrderMove(
|
||||
kind=kind, from_order_id=getattr(source, "id", None), to_order_id=getattr(target, "id", None),
|
||||
from_table_id=from_table_id if from_table_id is not None else getattr(source, "table_id", None),
|
||||
to_table_id=to_table_id if to_table_id is not None else getattr(target, "table_id", None),
|
||||
by_user_id=user_id, approved_by_user_id=approved_by,
|
||||
business_day_id=getattr(target, "business_day_id", None) or getattr(source, "business_day_id", None),
|
||||
)
|
||||
move.items = [OrderMoveItem(item_id=i.id, quantity=i.quantity) for i in items]
|
||||
db.add(move)
|
||||
return move
|
||||
|
||||
|
||||
def repoint(db, from_ids, to_id: int) -> None:
|
||||
"""Lines removed by a combine: their moves (and children) now belong to the line kept."""
|
||||
from models.order import OrderItem, OrderMoveItem
|
||||
from_ids = [i for i in from_ids if i != to_id]
|
||||
if not from_ids:
|
||||
return
|
||||
for mi in db.query(OrderMoveItem).filter(OrderMoveItem.item_id.in_(from_ids)).all():
|
||||
taken = db.query(OrderMoveItem).filter(OrderMoveItem.move_id == mi.move_id, OrderMoveItem.item_id == to_id).first()
|
||||
if taken is None:
|
||||
db.add(OrderMoveItem(move_id=mi.move_id, item_id=to_id, quantity=mi.quantity))
|
||||
else:
|
||||
taken.quantity = (taken.quantity or 0) + (mi.quantity or 0)
|
||||
db.delete(mi)
|
||||
db.query(OrderItem).filter(OrderItem.split_from_id.in_(from_ids)).update(
|
||||
{OrderItem.split_from_id: to_id}, synchronize_session=False)
|
||||
|
||||
|
||||
def _lineage(db, item):
|
||||
"""[(line id, moves up to when) …]: the line itself (all its moves), then each parent up to the
|
||||
moment the child was cut from it."""
|
||||
from models.order import OrderItem
|
||||
out, seen = [(item.id, None)], {item.id}
|
||||
child = item
|
||||
while child.split_from_id and child.split_from_id not in seen:
|
||||
parent = db.get(OrderItem, child.split_from_id)
|
||||
if parent is None:
|
||||
break
|
||||
out.append((parent.id, child.added_at))
|
||||
seen.add(parent.id)
|
||||
child = parent
|
||||
return out
|
||||
|
||||
|
||||
def item_moves(db, item) -> list:
|
||||
"""The moves a line went through, oldest first (its parents' before it was cut from them)."""
|
||||
from models.order import OrderMove, OrderMoveItem
|
||||
found = {}
|
||||
for line_id, until in _lineage(db, item):
|
||||
q = db.query(OrderMove).join(OrderMoveItem, OrderMoveItem.move_id == OrderMove.id).filter(OrderMoveItem.item_id == line_id)
|
||||
if until is not None:
|
||||
q = q.filter(OrderMove.at <= until)
|
||||
for m in q.all():
|
||||
found[m.id] = m
|
||||
return sorted(found.values(), key=lambda m: (m.at, m.id))
|
||||
|
||||
|
||||
def order_moves(db, order) -> list:
|
||||
"""The whole order's path: table transfers and merges into it, and the orders merged into it
|
||||
(their own transfers too), oldest first."""
|
||||
from models.order import OrderMove
|
||||
ids, todo, found = set(), [order.id], {}
|
||||
while todo:
|
||||
oid = todo.pop()
|
||||
if oid in ids:
|
||||
continue
|
||||
ids.add(oid)
|
||||
for m in db.query(OrderMove).filter(OrderMove.to_order_id == oid,
|
||||
OrderMove.kind.in_(("table_transfer", "orders_merged"))).all():
|
||||
found[m.id] = m
|
||||
if m.kind == "orders_merged" and m.from_order_id:
|
||||
todo.append(m.from_order_id)
|
||||
return sorted(found.values(), key=lambda m: (m.at, m.id))
|
||||
|
||||
|
||||
def _names(db):
|
||||
from models.table import Table
|
||||
from models.user import User
|
||||
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
users = {u.id: (u.nickname or u.full_name or u.username) for u in db.query(User).all()}
|
||||
return tables, users
|
||||
|
||||
|
||||
def move_out(m, tables, users, item_names=None) -> dict:
|
||||
return {
|
||||
"id": m.id, "kind": m.kind, "at": m.at,
|
||||
"from_order_id": m.from_order_id, "to_order_id": m.to_order_id,
|
||||
"from_table_id": m.from_table_id, "to_table_id": m.to_table_id,
|
||||
"from_table": tables.get(m.from_table_id), "to_table": tables.get(m.to_table_id),
|
||||
"by_id": m.by_user_id, "by": users.get(m.by_user_id),
|
||||
"approved_by": users.get(m.approved_by_user_id),
|
||||
"items": [{"item_id": i.item_id, "quantity": i.quantity,
|
||||
**({"name": item_names.get(i.item_id)} if item_names is not None else {})} for i in m.items],
|
||||
}
|
||||
|
||||
|
||||
def for_order(db, order) -> dict:
|
||||
"""GET /api/orders/{id}/moves: {order: [moves of the whole order], items: {line id: [moves]}}
|
||||
(only lines that moved)."""
|
||||
tables, users = _names(db)
|
||||
per_item = {}
|
||||
for item in order.items:
|
||||
ms = item_moves(db, item)
|
||||
if ms:
|
||||
per_item[str(item.id)] = [move_out(m, tables, users) for m in ms]
|
||||
return {"order": [move_out(m, tables, users) for m in order_moves(db, order)], "items": per_item}
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Prices changed by hand, on the record (owner 2026-11-23, plan step 6F.3).
|
||||
|
||||
Who may change a line's price, in three levels like every permission:
|
||||
- the venue (setting `orders.price_change`): `off` | `before_sending` (only in the cart, before
|
||||
the line is sent) | `anytime` (also a line already sent or served; the default, as before 6F.3);
|
||||
- the keys: `ordering.prices.modify` (in the cart; the counter's % discount too) and
|
||||
`ordering.prices.modify_sent` (a line already sent), role defaults per venue, changed per person;
|
||||
both may be approved once by a manager's PIN (D-10);
|
||||
- `orders.price_change_reason`: when on, a by-hand price needs a reason (the venue's quick
|
||||
reasons, `orders.price_change_reasons`, or typed).
|
||||
|
||||
Every change writes one `PriceEventLog` row, `event_type = "manual_price"`: the line, its unit price
|
||||
before and after, the change, the quantity, who, the approving manager, the stage
|
||||
(cart | sent | served) and the reason (`waiter_note`), plus an `OrderAuditLog` `PRICE_CHANGED`.
|
||||
Rows are never deleted; combining lines moves them to the kept line (orders.combine_items).
|
||||
Who sees them: `ordering.prices.view_changes` (GET /api/pricing/events/order/{id},
|
||||
GET /api/orders/{id}/items/{item}/price-changes, Reports → Cancellations, discounts and price changes).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from core.errors import XeniaError
|
||||
|
||||
EVENT = "manual_price"
|
||||
MODES = ("off", "before_sending", "anytime")
|
||||
STAGES = ("cart", "sent", "served")
|
||||
REASON_MAX = 200
|
||||
|
||||
|
||||
def _setting(db, key: str, default: str) -> str:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
return row.value if row is not None and row.value not in (None, "") else default
|
||||
|
||||
|
||||
def mode(db) -> str:
|
||||
v = _setting(db, "orders.price_change", "anytime")
|
||||
return v if v in MODES else "anytime"
|
||||
|
||||
|
||||
def reason_required(db) -> bool:
|
||||
return _setting(db, "orders.price_change_reason", "false") == "true"
|
||||
|
||||
|
||||
def quick_reasons(db) -> list[str]:
|
||||
try:
|
||||
v = json.loads(_setting(db, "orders.price_change_reasons", "[]"))
|
||||
except ValueError:
|
||||
return []
|
||||
return [str(x).strip() for x in v if isinstance(x, str) and x.strip()] if isinstance(v, list) else []
|
||||
|
||||
|
||||
def clean_reason(reason) -> str | None:
|
||||
text = " ".join(str(reason or "").split())[:REASON_MAX]
|
||||
return text or None
|
||||
|
||||
|
||||
def check(db, *, sent: bool, reason=None, by_hand: bool = True) -> str | None:
|
||||
"""Refuse a price change the venue doesn't allow (order.price_change_off /
|
||||
order.price_change_sent_off) or one without its reason (order.price_reason_required, only for
|
||||
a price typed by hand: the counter's % discount has none). Returns the cleaned reason."""
|
||||
m = mode(db)
|
||||
if m == "off":
|
||||
raise XeniaError("order.price_change_off")
|
||||
if sent and m != "anytime":
|
||||
raise XeniaError("order.price_change_sent_off")
|
||||
text = clean_reason(reason)
|
||||
if by_hand and text is None and reason_required(db):
|
||||
raise XeniaError("order.price_reason_required")
|
||||
return text
|
||||
|
||||
|
||||
def stage_of(item) -> str:
|
||||
"""Where a line is when its price changes: in the cart (being added), sent, or served."""
|
||||
if item is None or getattr(item, "id", None) is None:
|
||||
return "cart"
|
||||
return "served" if getattr(item, "kds_status", None) == "served" else "sent"
|
||||
|
||||
|
||||
def record(db, *, item, before: float, after: float, user_id: int | None, stage: str,
|
||||
reason: str | None = None, approved_by: int | None = None, audit: bool = True):
|
||||
"""One manual_price event for `item` (flushed with the caller's commit) and its audit row."""
|
||||
from models.order import OrderAuditLog
|
||||
from models.pricing import PriceEventLog
|
||||
before, after = round(float(before), 2), round(float(after), 2)
|
||||
if abs(after - before) < 0.005:
|
||||
return None
|
||||
ev = PriceEventLog(
|
||||
order_id=item.order_id, order_item_id=item.id, event_type=EVENT,
|
||||
price_before=before, price_after=after, delta_amount=round(after - before, 2),
|
||||
applied_by_user_id=user_id, approved_by_user_id=approved_by, waiter_note=reason,
|
||||
stage=stage if stage in STAGES else "cart", quantity=item.quantity,
|
||||
)
|
||||
db.add(ev)
|
||||
if audit:
|
||||
db.add(OrderAuditLog(order_id=item.order_id, event_type="PRICE_CHANGED", waiter_id=user_id,
|
||||
item_ids=json.dumps([item.id]),
|
||||
note=f"{before:.2f} → {after:.2f}" + (f" · {reason}" if reason else "")
|
||||
+ (f" · approved by user {approved_by}" if approved_by else "")))
|
||||
return ev
|
||||
|
||||
|
||||
def _name(user) -> str | None:
|
||||
return (user.nickname or user.full_name or user.username) if user is not None else None
|
||||
|
||||
|
||||
def event_out(ev, db) -> dict:
|
||||
"""One manual_price event for the apps and the reports."""
|
||||
item = ev.order_item
|
||||
return {
|
||||
"id": ev.id, "order_id": ev.order_id, "item_id": ev.order_item_id,
|
||||
"product_name": item.product_name if item is not None else None,
|
||||
"before": ev.price_before, "after": ev.price_after, "delta": ev.delta_amount,
|
||||
"quantity": ev.quantity, "stage": ev.stage, "reason": ev.waiter_note,
|
||||
"by_id": ev.applied_by_user_id, "by": _name(ev.applied_by),
|
||||
"approved_by_id": ev.approved_by_user_id, "approved_by": _name(ev.approved_by),
|
||||
"at": ev.applied_at,
|
||||
}
|
||||
|
||||
|
||||
def can_view(user) -> bool:
|
||||
from core.access.check import holds
|
||||
return holds(user, "ordering.prices.view_changes")
|
||||
@@ -7,6 +7,10 @@ in every report, on screen, printed and exported.
|
||||
- A line's **value** = (unit price + its price change) × quantity, then **minus what was refunded**
|
||||
of it (services/refunds.py: refunds are per line and quantity, so they come off the line, the
|
||||
product, the category, the table, the hour and the day they belong to).
|
||||
- **A split bill** (6F.6, services/split_bills.py): the lines it settled (`split`) are sold like
|
||||
paid lines; its **part lines** are the money for them, never a sale (left out here; the shifts'
|
||||
drawers, payment methods and tabs count them). A refund of a part comes off the settled lines
|
||||
by their share of the bill.
|
||||
- **Fees** (lines the system adds, `system_key` set: the delivery fee) are counted apart: they are
|
||||
money taken, but not a product sold. `revenue` everywhere is products only; `fees` is beside it;
|
||||
`takings` = revenue + fees.
|
||||
@@ -17,7 +21,7 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
SOLD = ("active", "paid", "tabbed")
|
||||
SOLD = ("active", "paid", "tabbed", "split")
|
||||
|
||||
|
||||
def gross(item, quantity: float | None = None) -> float:
|
||||
@@ -58,17 +62,40 @@ def lines(db, items) -> list[Line]:
|
||||
"""Sold lines (see the module doc) with their refunds taken off. A line refunded in full
|
||||
stays (quantity 0, value 0) so its refund is counted; `sold()` leaves it out of lists."""
|
||||
from services.refunds import refunded_quantities
|
||||
sold = [i for i in items if i.status in SOLD]
|
||||
from services.split_bills import is_part
|
||||
sold = [i for i in items if i.status in SOLD and not is_part(i)]
|
||||
back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"])
|
||||
shares = _split_refunds(db, {i.split_bill_id for i in sold if i.status == "split"})
|
||||
fees = _fee_products(db) if sold else set()
|
||||
out = []
|
||||
for i in sold:
|
||||
r = min(back.get(i.id, 0.0), i.quantity)
|
||||
if i.status == "split":
|
||||
r = i.quantity * shares.get(i.split_bill_id, 0.0)
|
||||
else:
|
||||
r = min(back.get(i.id, 0.0), i.quantity)
|
||||
q = max(i.quantity - r, 0.0)
|
||||
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=i.product_id in fees))
|
||||
return out
|
||||
|
||||
|
||||
def _split_refunds(db, bill_ids) -> dict[int, float]:
|
||||
"""{split_bill_id: the share of the bill refunded} from its parts' refunds (6F.6)."""
|
||||
from models.order import OrderItem, SplitBill
|
||||
from services.refunds import refunded_quantities
|
||||
ids = {b for b in bill_ids if b is not None}
|
||||
if not ids:
|
||||
return {}
|
||||
parts = db.query(OrderItem).filter(OrderItem.split_bill_id.in_(ids), OrderItem.status == "paid").all()
|
||||
back = refunded_quantities(db, [p.id for p in parts])
|
||||
if not back:
|
||||
return {}
|
||||
totals = {b.id: b.total for b in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all()}
|
||||
value: dict[int, float] = {}
|
||||
for p in parts:
|
||||
value[p.split_bill_id] = value.get(p.split_bill_id, 0.0) + gross(p, min(back.get(p.id, 0.0), p.quantity))
|
||||
return {b: min(v / totals[b], 1.0) for b, v in value.items() if totals.get(b)}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Totals:
|
||||
revenue: float = 0.0 # products, net of refunds
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Split a bill by amount (owner 2026-11-23, plan 6F.6). One rule for every app:
|
||||
|
||||
- The chosen unpaid lines are **settled** at once into a split bill: status `split` (sold, settled by
|
||||
the bill; `paid_at` / `paid_by` say when and who split, no shift, no payment method), so no
|
||||
drawer, payment method or person is charged for them.
|
||||
- `parts` **part lines** appear on the order: the system product `split_part`, named "Split bill
|
||||
1/3", one each, already printed and served (the kitchen never sees them). They are paid like any
|
||||
line (cash, card, on a tab, at different times, by different people): they are the money.
|
||||
- Counting (services/sales.py): the settled lines are the sales (products, categories, costs);
|
||||
parts are settlement lines, never sales, but money taken (shifts' drawers, payment methods,
|
||||
tabs, the day's takings), so nothing is counted twice. A refund of a part comes off the settled
|
||||
lines by their share.
|
||||
- Locks: settled lines are no longer `active`, so cancelling, moving, combining, re-pricing and
|
||||
splitting them is refused everywhere; parts can't be moved, re-priced, combined or cancelled one
|
||||
by one (undo the split instead).
|
||||
- Undo while no part is paid or on a tab (Q-2): parts cancelled ("split undone"), lines back to
|
||||
unpaid. Refused once any payment was taken.
|
||||
- Fiscal (Greece, Q-3): a split is whole lines, so the receipt is the settled lines themselves, as
|
||||
if paid normally: issued once, when the **last part is paid**, with each method's amount as the
|
||||
receipt's payments (`receipts_due`). A part on a tab: no receipt from the split (like any line
|
||||
on a tab) — open point for the accountant (plan 6F.6).
|
||||
|
||||
Venue setting `payments.split_amount` (levels include the ones before, Q-1): off | two_equal |
|
||||
two_custom | multiple_equal (2…`payments.split_max_parts` equal parts). Key
|
||||
`ordering.payments.split_amount`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from core.errors import XeniaError
|
||||
|
||||
LEVELS = ("off", "two_equal", "two_custom", "multiple_equal")
|
||||
PART_KEY = "split_part"
|
||||
|
||||
|
||||
def _setting(db, key: str, default: str) -> str:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
return row.value if row is not None and row.value not in (None, "") else default
|
||||
|
||||
|
||||
def level(db) -> str:
|
||||
v = _setting(db, "payments.split_amount", "off")
|
||||
return v if v in LEVELS else "off"
|
||||
|
||||
|
||||
def max_parts(db) -> int:
|
||||
try:
|
||||
n = int(_setting(db, "payments.split_max_parts", "10"))
|
||||
except ValueError:
|
||||
n = 10
|
||||
return max(2, min(50, n))
|
||||
|
||||
|
||||
def allowed(lvl: str, mode: str, parts: int, most: int) -> bool:
|
||||
"""Whether the venue's level allows this split (each level includes the ones before)."""
|
||||
rank = LEVELS.index(lvl) if lvl in LEVELS else 0
|
||||
if mode == "custom":
|
||||
return parts == 2 and rank >= LEVELS.index("two_custom")
|
||||
if parts == 2:
|
||||
return rank >= LEVELS.index("two_equal")
|
||||
return rank >= LEVELS.index("multiple_equal") and 2 < parts <= most
|
||||
|
||||
|
||||
def amounts(total: float, mode: str, parts: int, first: float | None = None) -> list[float]:
|
||||
"""Each part, to the cent. Equal: the remainder goes on the last part (10.00 / 3 = 3.33 + 3.33
|
||||
+ 3.34). Custom (two parts): `first` is part 1, part 2 the rest."""
|
||||
cents = round(total * 100)
|
||||
if mode == "custom":
|
||||
a = round((first or 0) * 100)
|
||||
if not 0 < a < cents:
|
||||
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
|
||||
return [a / 100, (cents - a) / 100]
|
||||
base = cents // parts
|
||||
return [base / 100] * (parts - 1) + [(cents - base * (parts - 1)) / 100]
|
||||
|
||||
|
||||
def is_part(item) -> bool:
|
||||
"""A split bill's part line (money for the settled lines), not a sale."""
|
||||
return getattr(item, "split_bill_id", None) is not None and item.status != "split"
|
||||
|
||||
|
||||
def counts_as_sale(item, statuses=("active", "paid")) -> bool:
|
||||
"""For the older reports that pick lines by status: a settled line counts, a part never."""
|
||||
return item.status == "split" or (item.status in statuses and not is_part(item))
|
||||
|
||||
|
||||
def sold_filter(statuses=("active", "paid")):
|
||||
"""The same as SQL (OrderItem): settled lines, or lines in `statuses` that aren't parts."""
|
||||
from sqlalchemy import and_, or_
|
||||
from models.order import OrderItem
|
||||
return or_(OrderItem.status == "split", and_(OrderItem.status.in_(statuses), OrderItem.split_bill_id.is_(None)))
|
||||
|
||||
|
||||
def refuse_parts(items) -> None:
|
||||
if any(is_part(i) for i in items):
|
||||
raise XeniaError("split.part_locked")
|
||||
|
||||
|
||||
def live_bills(db, order_id: int) -> list:
|
||||
from models.order import SplitBill
|
||||
return db.query(SplitBill).filter(SplitBill.order_id == order_id, SplitBill.undone_at.is_(None)).order_by(SplitBill.id).all()
|
||||
|
||||
|
||||
def has_unpaid_parts(db, order_id: int) -> bool:
|
||||
from models.order import OrderItem
|
||||
return db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.split_bill_id.isnot(None),
|
||||
OrderItem.status.in_(("active", "ready"))).first() is not None
|
||||
|
||||
|
||||
def create(db, order, items, *, mode: str, parts: int, first: float | None, user) -> object:
|
||||
"""Settle `items` (unpaid lines of `order`) into a split bill with `parts` part lines.
|
||||
The caller checked the key; this checks the venue's level, the lines and fiscal."""
|
||||
from core.i18n import t, venue_language
|
||||
from core.timeutil import utcnow
|
||||
from models.order import OrderItem, SplitBill
|
||||
from services import system_products
|
||||
from services.sales import gross
|
||||
|
||||
if mode not in ("equal", "custom"):
|
||||
raise XeniaError("validation.choice", field="mode", value=mode)
|
||||
if not allowed(level(db), mode, parts, max_parts(db)):
|
||||
raise XeniaError("split.not_allowed")
|
||||
if not items or any(i.order_id != order.id or i.status not in ("active", "ready") for i in items):
|
||||
raise XeniaError("split.lines_changed")
|
||||
refuse_parts(items)
|
||||
total = round(sum(gross(i) for i in items), 2)
|
||||
if total < 0.01 * parts:
|
||||
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
|
||||
split = amounts(total, mode, parts, first)
|
||||
from services.fiscal import is_fiscal_enabled, validate_items_for_fiscal
|
||||
if is_fiscal_enabled(db):
|
||||
missing = validate_items_for_fiscal(items, db)
|
||||
if missing:
|
||||
raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
|
||||
|
||||
now = utcnow()
|
||||
bill = SplitBill(order_id=order.id, total=total, mode=mode, parts=parts, amounts=json.dumps(split),
|
||||
created_by=user.id, created_at=now, business_day_id=order.business_day_id)
|
||||
db.add(bill)
|
||||
db.flush()
|
||||
for i in items:
|
||||
i.status = "split"
|
||||
i.split_bill_id = bill.id
|
||||
i.paid_at = now
|
||||
i.paid_by = user.id
|
||||
i.payment_method = None
|
||||
i.paid_in_shift_id = None
|
||||
product = system_products.get(db, PART_KEY)
|
||||
lang = venue_language()
|
||||
for n, amount in enumerate(split, start=1):
|
||||
db.add(OrderItem(order_id=order.id, product_id=product.id, added_by=user.id, quantity=1, unit_price=amount,
|
||||
price_adjustment=0.0, status="active", printed=True, kds_status="served", split_bill_id=bill.id,
|
||||
product_name=t("split.part_name", lang, n=n, of=parts), source=items[0].source))
|
||||
db.flush()
|
||||
return bill
|
||||
|
||||
|
||||
def undo(db, order, bill, user) -> list[int]:
|
||||
"""Undo a split while no part was paid or put on a tab (Q-2). Returns the lines given back."""
|
||||
from core.timeutil import utcnow
|
||||
from models.order import OrderItem
|
||||
if bill.undone_at is not None or bill.order_id != order.id:
|
||||
raise XeniaError("split.not_found")
|
||||
rows = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id).all()
|
||||
parts = [i for i in rows if i.status != "split"]
|
||||
if any(p.status not in ("active", "ready", "cancelled") for p in parts):
|
||||
raise XeniaError("split.paid_already")
|
||||
now = utcnow()
|
||||
for p in parts:
|
||||
if p.status != "cancelled":
|
||||
p.status = "cancelled"
|
||||
p.cancelled_at = now
|
||||
p.cancelled_by = user.id
|
||||
p.cancel_reason = "split undone"
|
||||
back = []
|
||||
for i in rows:
|
||||
if i.status == "split":
|
||||
i.status = "active"
|
||||
i.split_bill_id = None
|
||||
i.paid_at = None
|
||||
i.paid_by = None
|
||||
back.append(i.id)
|
||||
bill.undone_at = now
|
||||
bill.undone_by = user.id
|
||||
db.flush()
|
||||
return back
|
||||
|
||||
|
||||
def receipts_due(db, paid_items) -> list[dict]:
|
||||
"""After parts were paid: the split bills whose last part is now paid get their fiscal receipt
|
||||
(marked issued here). [{"bill", "lines", "payments": [{"method", "amount"}]}]."""
|
||||
from core.timeutil import utcnow
|
||||
from models.order import OrderItem, SplitBill
|
||||
ids = {i.split_bill_id for i in paid_items if is_part(i)}
|
||||
out = []
|
||||
for bill in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all() if ids else []:
|
||||
if bill.undone_at is not None or bill.receipt_issued_at is not None:
|
||||
continue
|
||||
rows = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id).order_by(OrderItem.id).all()
|
||||
parts = [i for i in rows if i.status not in ("split", "cancelled")]
|
||||
if not parts or any(p.status != "paid" for p in parts):
|
||||
continue # unpaid, or on a tab: no receipt from the split (open point, plan 6F.6)
|
||||
by_method: dict[str, float] = {}
|
||||
for p in parts:
|
||||
m = p.payment_method or "cash"
|
||||
by_method[m] = round(by_method.get(m, 0.0) + (p.unit_price or 0.0) * p.quantity, 2)
|
||||
bill.receipt_issued_at = utcnow()
|
||||
out.append({"bill": bill, "lines": [i for i in rows if i.status == "split"],
|
||||
"payments": [{"method": m, "amount": a} for m, a in by_method.items()]})
|
||||
return out
|
||||
|
||||
|
||||
def bill_out(bill, rows) -> dict:
|
||||
"""What the apps show: the bill, its settled lines and its parts (with how each was paid)."""
|
||||
parts = [i for i in rows if i.split_bill_id == bill.id and i.status != "split" and i.status != "cancelled"]
|
||||
return {
|
||||
"id": bill.id, "total": bill.total, "mode": bill.mode, "parts": bill.parts,
|
||||
"amounts": json.loads(bill.amounts or "[]"),
|
||||
"created_by": bill.created_by,
|
||||
"created_at": bill.created_at.isoformat() + "Z" if bill.created_at and bill.created_at.tzinfo is None else (bill.created_at.isoformat() if bill.created_at else None),
|
||||
"line_ids": [i.id for i in rows if i.split_bill_id == bill.id and i.status == "split"],
|
||||
"part_ids": [p.id for p in parts],
|
||||
"paid": round(sum((p.unit_price or 0.0) * p.quantity for p in parts if p.status == "paid"), 2),
|
||||
"can_undo": all(p.status in ("active", "ready") for p in parts),
|
||||
"receipt_issued": bill.receipt_issued_at is not None,
|
||||
}
|
||||
@@ -21,7 +21,8 @@ from __future__ import annotations
|
||||
from collections import Counter
|
||||
|
||||
DELIVERY_FEE = "delivery_fee"
|
||||
KEYS = (DELIVERY_FEE,)
|
||||
SPLIT_PART = "split_part" # a split bill's part line (6F.6, services/split_bills.py)
|
||||
KEYS = (DELIVERY_FEE, SPLIT_PART)
|
||||
|
||||
|
||||
def _usual_vat_group(db):
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""The day opens and closes by itself (plan 6F.8): services/day_auto.tick with a fake clock.
|
||||
|
||||
Hours used: Monday 09:00-15:00 and 18:00-23:00; Tuesday 10:00-01:00 (past midnight).
|
||||
2026-11-30 is a Monday; Athens is UTC+2 then."""
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from services import day_auto
|
||||
|
||||
HOURS = {"days": [[{"from": "09:00", "to": "15:00"}, {"from": "18:00", "to": "23:00"}],
|
||||
[{"from": "10:00", "to": "01:00"}], [], [], [], [], []], "note": None}
|
||||
|
||||
|
||||
def at(local: str):
|
||||
from core.timeutil import venue_local_to_utc
|
||||
return venue_local_to_utc(datetime.fromisoformat(local))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def boss(make_user, login):
|
||||
return login(make_user(role="owner"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def venue(client, boss, monkeypatch):
|
||||
import services.cloud_sync as cs
|
||||
monkeypatch.setattr(cs, "apply_license", lambda *a, **k: None) # no cloud license here: keep it as it is
|
||||
day_auto.reset_for_tests()
|
||||
|
||||
def set_(**values):
|
||||
for k, v in values.items():
|
||||
r = client.put(f"/api/settings/business_day.{k}", headers=boss, json={"value": v})
|
||||
assert r.status_code == 200, r.text
|
||||
assert client.put("/api/identity/hours", headers=boss, json=HOURS).status_code == 200
|
||||
yield set_
|
||||
day_auto.reset_for_tests()
|
||||
|
||||
|
||||
def days(db):
|
||||
from models.business_day import BusinessDay
|
||||
db.expire_all()
|
||||
return db.query(BusinessDay).order_by(BusinessDay.id).all()
|
||||
|
||||
|
||||
def alerts(client, boss):
|
||||
return [n["key"] for n in client.get("/api/platform/notifications", headers=boss).json()["items"]
|
||||
if n["key"].startswith("business_day.")]
|
||||
|
||||
|
||||
def test_off_by_default_does_nothing(db, venue):
|
||||
assert day_auto.tick(db, now=at("2026-11-30T09:00")) == []
|
||||
assert days(db) == []
|
||||
|
||||
|
||||
def test_schedule_one_day_over_the_break(db, venue):
|
||||
venue(auto_open="schedule", auto_close="schedule")
|
||||
assert day_auto.tick(db, now=at("2026-11-30T08:59")) == []
|
||||
assert day_auto.tick(db, now=at("2026-11-30T09:00")) == ["opened"]
|
||||
d = days(db)[0]
|
||||
assert d.status == "open" and d.opened_auto and d.opened_by_id is None
|
||||
assert day_auto.tick(db, now=at("2026-11-30T16:00")) == [] # the break: one day
|
||||
assert day_auto.tick(db, now=at("2026-11-30T23:00")) == ["closed"]
|
||||
d = days(db)[0]
|
||||
assert d.status == "closed" and d.closed_auto and d.closed_by_id is None
|
||||
assert day_auto.tick(db, now=at("2026-11-30T23:05")) == [] # not reopened
|
||||
assert len(days(db)) == 1
|
||||
|
||||
|
||||
def test_break_closes_and_reopens_when_not_ignored(db, venue):
|
||||
venue(auto_open="schedule", auto_close="schedule", auto_ignore_break="false")
|
||||
day_auto.tick(db, now=at("2026-11-30T09:00"))
|
||||
assert day_auto.tick(db, now=at("2026-11-30T15:00")) == ["closed"]
|
||||
assert day_auto.tick(db, now=at("2026-11-30T17:59")) == []
|
||||
assert day_auto.tick(db, now=at("2026-11-30T18:00")) == ["opened"]
|
||||
assert [d.status for d in days(db)] == ["closed", "open"]
|
||||
|
||||
|
||||
def test_a_day_closed_by_hand_is_not_reopened_in_the_same_span(db, venue, client, boss):
|
||||
venue(auto_open="schedule")
|
||||
day_auto.tick(db, now=at("2026-11-30T09:00"))
|
||||
assert client.post("/api/business-day/close", headers=boss, json={}).status_code == 200
|
||||
assert day_auto.tick(db, now=at("2026-11-30T12:00")) == []
|
||||
assert day_auto.tick(db, now=at("2026-12-01T10:00")) == ["opened"] # the next day's span
|
||||
|
||||
|
||||
def test_span_past_midnight_belongs_to_the_day_it_starts(db, venue):
|
||||
venue(auto_open="schedule", auto_close="schedule")
|
||||
assert day_auto.tick(db, now=at("2026-12-01T10:00")) == ["opened"] # Tuesday
|
||||
assert day_auto.tick(db, now=at("2026-12-02T00:30")) == [] # still Tuesday's span
|
||||
assert day_auto.tick(db, now=at("2026-12-02T01:00")) == ["closed"]
|
||||
|
||||
|
||||
def test_offsets(db, venue):
|
||||
venue(auto_open="schedule", auto_close="schedule", auto_open_offset_min="30", auto_close_offset_min="45")
|
||||
assert day_auto.tick(db, now=at("2026-11-30T08:30")) == ["opened"]
|
||||
assert day_auto.tick(db, now=at("2026-11-30T23:30")) == []
|
||||
assert day_auto.tick(db, now=at("2026-11-30T23:45")) == ["closed"]
|
||||
|
||||
|
||||
def test_time_overrides_the_hours(db, venue):
|
||||
venue(auto_open="time", auto_open_time="07:00", auto_close="time", auto_close_time="22:00")
|
||||
assert day_auto.tick(db, now=at("2026-12-03T06:59")) == [] # Thursday: no hours at all
|
||||
assert day_auto.tick(db, now=at("2026-12-03T07:00")) == ["opened"]
|
||||
assert day_auto.tick(db, now=at("2026-12-03T22:00")) == ["closed"]
|
||||
assert day_auto.tick(db, now=at("2026-12-03T23:00")) == []
|
||||
assert day_auto.tick(db, now=at("2026-12-04T06:30")) == [] # past the rollover: no catch-up
|
||||
assert day_auto.tick(db, now=at("2026-12-04T07:00")) == ["opened"]
|
||||
|
||||
|
||||
def test_alert_is_one_sticky_notification_that_resolves(db, venue, client, boss):
|
||||
venue(auto_open="alert", auto_close="alert")
|
||||
assert day_auto.tick(db, now=at("2026-11-30T09:00")) == ["alert:business_day.not_open"]
|
||||
day_auto.tick(db, now=at("2026-11-30T09:05"))
|
||||
assert alerts(client, boss) == ["business_day.not_open"] # one, not two
|
||||
n = client.get("/api/platform/notifications", headers=boss).json()["items"][0]
|
||||
assert n["params"]["action"] == "open_day" and "09:00" in n["message"] and n["expires_at"] is None
|
||||
assert days(db) == [] # alert only
|
||||
assert client.post("/api/business-day/open", headers=boss, json={}).status_code == 201
|
||||
assert alerts(client, boss) == [] # resolved at once
|
||||
day_auto.tick(db, now=at("2026-11-30T23:00"))
|
||||
assert alerts(client, boss) == ["business_day.not_closed"]
|
||||
assert client.post("/api/business-day/close", headers=boss, json={}).status_code == 200
|
||||
assert alerts(client, boss) == []
|
||||
|
||||
|
||||
def test_open_tables_block_the_close_and_it_retries(db, venue, client, boss, make_user):
|
||||
from models.order import Order
|
||||
venue(auto_open="schedule", auto_close="schedule")
|
||||
day_auto.tick(db, now=at("2026-11-30T09:00"))
|
||||
d = days(db)[0]
|
||||
o = Order(opened_by=make_user(role="waiter").id, business_day_id=d.id, status="paid")
|
||||
db.add(o)
|
||||
db.commit()
|
||||
assert day_auto.tick(db, now=at("2026-11-30T23:00")) == ["alert:business_day.tables_open", "waiting"]
|
||||
assert alerts(client, boss) == ["business_day.tables_open"]
|
||||
o.status = "closed"
|
||||
db.commit()
|
||||
assert day_auto.tick(db, now=at("2026-11-30T23:10")) == ["waiting"] # every 15 minutes
|
||||
assert days(db)[0].status == "open"
|
||||
assert day_auto.tick(db, now=at("2026-11-30T23:15")) == ["closed"]
|
||||
assert alerts(client, boss) == []
|
||||
|
||||
|
||||
def test_restart_catches_up_the_open_and_alerts_a_missed_close(db, venue, client, boss):
|
||||
venue(auto_open="schedule", auto_close="schedule")
|
||||
assert day_auto.tick(db, now=at("2026-11-30T11:00"), started_at=at("2026-11-30T11:00")) == ["opened"]
|
||||
out = day_auto.tick(db, now=at("2026-11-30T23:40"), started_at=at("2026-11-30T23:30"))
|
||||
assert out == ["alert:business_day.not_closed"] and days(db)[0].status == "open"
|
||||
assert alerts(client, boss) == ["business_day.not_closed"]
|
||||
|
||||
|
||||
def test_locked_license_alerts_instead_of_opening(db, venue, client, boss, monkeypatch):
|
||||
from services.license_state import license_state
|
||||
venue(auto_open="schedule")
|
||||
monkeypatch.setitem(license_state, "locked", True)
|
||||
assert day_auto.tick(db, now=at("2026-11-30T09:00")) == ["alert:business_day.open_blocked"]
|
||||
assert days(db) == [] and alerts(client, boss) == ["business_day.open_blocked"]
|
||||
|
||||
|
||||
def test_spans_of():
|
||||
from datetime import date
|
||||
mon = date(2026, 11, 30)
|
||||
assert [(a.hour, b.hour) for a, b in day_auto.spans_of(HOURS["days"], mon, False)] == [(9, 15), (18, 23)]
|
||||
assert [(a.hour, b.hour) for a, b in day_auto.spans_of(HOURS["days"], mon, True)] == [(9, 23)]
|
||||
(a, b), = day_auto.spans_of(HOURS["days"], date(2026, 12, 1), True)
|
||||
assert b.day == 2 and b.hour == 1
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Moves on the record (owner 2026-11-23, plan 6F.4, services/moves.py).
|
||||
|
||||
A table transfer, lines moved to another order and two orders merged each leave one move with its
|
||||
lines; a line's path survives being moved three times, being split (the part carries the moves made
|
||||
before the split, not after) and being combined; the order shows where it came from; Reports →
|
||||
Moves lists them.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_printing(monkeypatch):
|
||||
import routers.orders as orders
|
||||
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def floor(db, shop):
|
||||
"""Four free tables and the shop's waiter's order put on the first."""
|
||||
from models.table import Table, TableGroup
|
||||
g = TableGroup(name="Hall")
|
||||
db.add(g)
|
||||
db.flush()
|
||||
ts = [Table(number=n, group_id=g.id, is_active=True) for n in (1, 2, 3, 4)]
|
||||
db.add_all(ts)
|
||||
db.flush()
|
||||
shop["order"].table_id = ts[0].id
|
||||
shop["order"].status = "open"
|
||||
for i in shop["items"]:
|
||||
i.status = "active"
|
||||
db.commit()
|
||||
return ts
|
||||
|
||||
|
||||
def new_order(db, shop, table, n=1):
|
||||
from models.order import Order, OrderItem
|
||||
o = Order(opened_by=shop["waiter"].id, table_id=table.id, status="open")
|
||||
db.add(o)
|
||||
db.flush()
|
||||
items = [OrderItem(order_id=o.id, product_id=shop["items"][0].product_id, added_by=shop["waiter"].id, quantity=1, unit_price=4.0)
|
||||
for _ in range(n)]
|
||||
db.add_all(items)
|
||||
db.commit()
|
||||
return o, items
|
||||
|
||||
|
||||
def test_a_transfer_is_one_move_with_its_lines(client, db, shop, floor):
|
||||
o = shop["order"]
|
||||
r = client.post(f"/api/orders/{o.id}/transfer", headers=shop["h"], json={"target_table_id": floor[1].id})
|
||||
assert r.status_code == 200, r.text
|
||||
got = client.get(f"/api/orders/{o.id}/moves", headers=shop["h"]).json()
|
||||
[m] = got["order"]
|
||||
assert m["kind"] == "table_transfer" and (m["from_table_id"], m["to_table_id"]) == (floor[0].id, floor[1].id)
|
||||
assert m["from_table"] == "T1" and m["to_table"] == "T2" and m["by_id"] == shop["waiter"].id
|
||||
assert {i["item_id"] for i in m["items"]} == {i.id for i in shop["items"]}
|
||||
assert set(got["items"]) == {str(i.id) for i in shop["items"]}
|
||||
|
||||
|
||||
def test_a_line_moved_three_times_shows_every_step(client, db, shop, floor):
|
||||
o1 = shop["order"]
|
||||
o2, _ = new_order(db, shop, floor[1])
|
||||
o3, _ = new_order(db, shop, floor[2])
|
||||
line = shop["items"][0]
|
||||
for src, dst in ((o1, o2), (o2, o3), (o3, o1)):
|
||||
r = client.post(f"/api/orders/{src.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": dst.id})
|
||||
assert r.status_code == 200, r.text
|
||||
path = client.get(f"/api/orders/{o1.id}/moves", headers=shop["h"]).json()["items"][str(line.id)]
|
||||
assert [(m["from_table"], m["to_table"]) for m in path] == [("T1", "T2"), ("T2", "T3"), ("T3", "T1")]
|
||||
assert all(m["kind"] == "items_moved" for m in path)
|
||||
|
||||
|
||||
def test_a_split_part_keeps_the_moves_before_the_split_only(client, db, shop, floor):
|
||||
o1 = shop["order"]
|
||||
o2, _ = new_order(db, shop, floor[1])
|
||||
o3, _ = new_order(db, shop, floor[2])
|
||||
line = shop["items"][0]
|
||||
line.quantity = 3
|
||||
line.price_adjustment = -0.5
|
||||
line.kds_status = "served"
|
||||
db.commit()
|
||||
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": o2.id})
|
||||
r = client.post(f"/api/orders/{o2.id}/items/{line.id}/split", headers=shop["h"], json={"quantity": 1})
|
||||
assert r.status_code == 200, r.text
|
||||
part = [x for x in r.json() if x["id"] != line.id][0]
|
||||
assert part["split_from_id"] == line.id
|
||||
# the part keeps what the line was (its price change, the kitchen state)
|
||||
from models.order import OrderItem
|
||||
db.expire_all()
|
||||
p = db.get(OrderItem, part["id"])
|
||||
assert p.price_adjustment == -0.5 and p.kds_status == "served"
|
||||
# the original moves on; the part stays
|
||||
client.post(f"/api/orders/{o2.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": o3.id})
|
||||
part_path = client.get(f"/api/orders/{o2.id}/moves", headers=shop["h"]).json()["items"][str(part["id"])]
|
||||
assert [(m["from_table"], m["to_table"]) for m in part_path] == [("T1", "T2")]
|
||||
line_path = client.get(f"/api/orders/{o3.id}/moves", headers=shop["h"]).json()["items"][str(line.id)]
|
||||
assert [(m["from_table"], m["to_table"]) for m in line_path] == [("T1", "T2"), ("T2", "T3")]
|
||||
|
||||
|
||||
def test_a_merge_brings_the_other_orders_path(client, db, shop, floor):
|
||||
o1 = shop["order"]
|
||||
o2, lines2 = new_order(db, shop, floor[1])
|
||||
client.post(f"/api/orders/{o2.id}/transfer", headers=shop["h"], json={"target_table_id": floor[3].id})
|
||||
r = client.post(f"/api/orders/{o2.id}/merge", headers=shop["h"], json={"target_order_id": o1.id})
|
||||
assert r.status_code == 200, r.text
|
||||
got = client.get(f"/api/orders/{o1.id}/moves", headers=shop["h"]).json()
|
||||
assert [m["kind"] for m in got["order"]] == ["table_transfer", "orders_merged"]
|
||||
merged = got["order"][1]
|
||||
assert (merged["from_order_id"], merged["to_order_id"], merged["from_table"], merged["to_table"]) == (o2.id, o1.id, "T4", "T1")
|
||||
assert [m["kind"] for m in got["items"][str(lines2[0].id)]] == ["table_transfer", "orders_merged"]
|
||||
|
||||
|
||||
def test_combining_lines_keeps_their_moves(client, db, shop, floor):
|
||||
o1 = shop["order"]
|
||||
o2, _ = new_order(db, shop, floor[1])
|
||||
a, b = shop["items"][0], shop["items"][1]
|
||||
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [a.id, b.id], "target_order_id": o2.id})
|
||||
r = client.post(f"/api/orders/{o2.id}/items/combine", headers=shop["h"], json={"item_ids": [a.id, b.id]})
|
||||
assert r.status_code == 200, r.text
|
||||
from models.order import OrderMoveItem
|
||||
db.expire_all()
|
||||
[mi] = db.query(OrderMoveItem).all()
|
||||
assert mi.item_id == a.id and mi.quantity == 2
|
||||
|
||||
|
||||
def test_the_moves_report(client, db, shop, floor, make_user, login):
|
||||
o1 = shop["order"]
|
||||
o2, _ = new_order(db, shop, floor[1])
|
||||
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [shop["items"][0].id], "target_order_id": o2.id})
|
||||
client.post(f"/api/orders/{o2.id}/transfer", headers=shop["h"], json={"target_table_id": floor[2].id})
|
||||
boss = login(make_user(role="owner"))
|
||||
rep = client.get("/api/reports/moves", headers=boss).json()
|
||||
assert rep["count"] == 2 and rep["by_kind"] == {"items_moved": 1, "table_transfer": 1}
|
||||
moved = next(m for m in rep["moves"] if m["kind"] == "items_moved")
|
||||
assert moved["value"] == 4.0 and moved["items"][0]["name"] and rep["by_person"][0]["count"] == 2
|
||||
assert client.get(f"/api/reports/moves?table_id={floor[2].id}", headers=boss).json()["count"] == 1
|
||||
assert client.get("/api/reports/moves?kind=table_transfer", headers=boss).json()["count"] == 1
|
||||
csv = client.get("/api/reports/moves/export", headers=boss)
|
||||
assert csv.status_code == 200 and "items_moved" in csv.text
|
||||
@@ -0,0 +1,123 @@
|
||||
"""One more, and a sent line's quantity (owner 2026-11-23, plan 6F.5).
|
||||
|
||||
- POST /api/orders/{id}/items/{item}/again: a new line like the old one, priced now, printed as new;
|
||||
only with the product's one_more_enabled, from active / paid / tabbed lines in pieces.
|
||||
- POST /api/orders/{id}/items/{item}/quantity: the venue's switch (off | add_only | add_and_remove),
|
||||
the key ordering.items.change_quantity; up changes the line only (no ticket); down cuts a
|
||||
cancelled part ("quantity lowered") and prints a cancellation only when asked.
|
||||
"""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_live import err
|
||||
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def printed(monkeypatch):
|
||||
"""What went to the kitchen: new lines (route_and_print_sync) and cancellations."""
|
||||
import routers.orders as orders
|
||||
got = {"tickets": [], "cancellations": []}
|
||||
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: (got["tickets"].append(a), [])[1])
|
||||
monkeypatch.setattr(orders, "print_cancellation_ticket", lambda order_id, ids: got["cancellations"].append(list(ids)))
|
||||
return got
|
||||
|
||||
|
||||
def setting(db, key, value):
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if row is None:
|
||||
db.add(PosSettings(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
|
||||
|
||||
def lines(db, order_id):
|
||||
from models.order import OrderItem
|
||||
db.expire_all()
|
||||
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
|
||||
|
||||
|
||||
def test_one_more_needs_the_products_switch(client, db, shop, printed):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/again"
|
||||
assert err(client.post(url, headers=shop["h"], json={})) == "order.one_more_off"
|
||||
item.product.one_more_enabled = True
|
||||
item.notes = "no ice"
|
||||
item.selected_options = json.dumps([{"id": None, "name": "Sweet", "price_delta": 0.0, "type": "quick"}])
|
||||
db.commit()
|
||||
before = len(lines(db, o.id))
|
||||
r = client.post(url, headers=shop["h"], json={"quantity": 2})
|
||||
assert r.status_code == 200, r.text
|
||||
new = lines(db, o.id)[-1]
|
||||
assert len(lines(db, o.id)) == before + 1 and new.id != item.id
|
||||
assert (new.product_id, new.quantity, new.notes, new.status) == (item.product_id, 2, "no ice", "active")
|
||||
assert json.loads(new.selected_options)[0]["name"] == "Sweet" and new.unit_price == 4.0
|
||||
assert len(printed["tickets"]) == 1 # sent to the kitchen like any new line
|
||||
# from a paid line too; never from a cancelled one
|
||||
paid = shop["items"][2]
|
||||
assert client.post(f"/api/orders/{o.id}/items/{paid.id}/again", headers=shop["h"], json={}).status_code == 200
|
||||
paid.status = "cancelled"
|
||||
db.commit()
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/{paid.id}/again", headers=shop["h"], json={})) == "order.one_more_line"
|
||||
|
||||
|
||||
def test_one_more_needs_ordering_orders_open(client, db, shop, login, printed):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
item.product.one_more_enabled = True
|
||||
db.commit()
|
||||
h = login(shop["new_waiter"](remove=("ordering.orders.open",)), client="waiter")
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/{item.id}/again", headers=h, json={})) == "access.denied"
|
||||
|
||||
|
||||
def test_quantity_follows_the_venue_and_the_key(client, db, shop, login, printed):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/quantity"
|
||||
assert err(client.post(url, headers=shop["h"], json={"quantity": 3})) == "order.quantity_change_off"
|
||||
setting(db, "orders.quantity_change", "add_only")
|
||||
# a waiter without the key: a manager may approve it
|
||||
assert err(client.post(url, headers=shop["h"], json={"quantity": 3})) == "access.override_possible"
|
||||
h = login(shop["new_waiter"](add=("ordering.items.change_quantity",)), client="waiter")
|
||||
r = client.post(url, headers=h, json={"quantity": 3})
|
||||
assert r.status_code == 200, r.text
|
||||
assert lines(db, o.id)[0].quantity == 3 and printed["tickets"] == [] and printed["cancellations"] == []
|
||||
assert err(client.post(url, headers=h, json={"quantity": 2})) == "order.quantity_remove_off"
|
||||
from models.order import OrderAuditLog
|
||||
log = db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "QUANTITY_CHANGED").one()
|
||||
assert log.note.startswith("1 → 3")
|
||||
|
||||
|
||||
def test_lowering_cancels_the_difference_and_asks_about_the_ticket(client, db, shop, login, printed):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
item.quantity = 5
|
||||
db.commit()
|
||||
setting(db, "orders.quantity_change", "add_and_remove")
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/quantity"
|
||||
# the key, but not the cancel key: a manager's approval for the cancel part
|
||||
h = login(shop["new_waiter"](add=("ordering.items.change_quantity",), remove=("ordering.orders.cancel",)), client="waiter")
|
||||
assert err(client.post(url, headers=h, json={"quantity": 3})) == "access.override_possible"
|
||||
h = login(shop["new_waiter"](add=("ordering.items.change_quantity", "ordering.orders.cancel")), client="waiter")
|
||||
r = client.post(url, headers=h, json={"quantity": 3, "print_cancellation": False})
|
||||
assert r.status_code == 200, r.text
|
||||
part_id = r.json()["cancelled_item_id"]
|
||||
rows = {i.id: i for i in lines(db, o.id)}
|
||||
assert rows[item.id].quantity == 3 and rows[item.id].status == "active"
|
||||
part = rows[part_id]
|
||||
assert (part.quantity, part.status, part.cancel_reason, part.split_from_id) == (2, "cancelled", "quantity lowered", item.id)
|
||||
assert printed["cancellations"] == []
|
||||
r = client.post(url, headers=h, json={"quantity": 2, "print_cancellation": True})
|
||||
assert printed["cancellations"] == [[r.json()["cancelled_item_id"]]]
|
||||
|
||||
|
||||
def test_only_unpaid_lines_in_pieces(client, db, shop, printed, login):
|
||||
setting(db, "orders.quantity_change", "add_and_remove")
|
||||
o = shop["order"]
|
||||
paid = shop["items"][2]
|
||||
boss = login(shop["owner"])
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/{paid.id}/quantity", headers=boss, json={"quantity": 2})) == "order.quantity_line"
|
||||
item = shop["items"][0]
|
||||
item.product.unit_type = "kg"
|
||||
db.commit()
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/{item.id}/quantity", headers=boss, json={"quantity": 2})) == "order.quantity_line"
|
||||
@@ -94,7 +94,7 @@ def test_waiter_cancels_after_manager_pin(client, db, venue, login):
|
||||
|
||||
def test_token_is_bound_to_its_key(client, db, venue, make_user, login):
|
||||
v = venue
|
||||
token = approve(client, v["waiter_h"], "ordering.prices.modify", make_user(role="owner").username).json()["override_token"]
|
||||
token = approve(client, v["waiter_h"], "ordering.prices.modify_sent", make_user(role="owner").username).json()["override_token"]
|
||||
# used for another key: refused, and NOT burned
|
||||
r = cancel(client, v, v["items"][0], token)
|
||||
assert err(r) == "access.override_invalid"
|
||||
@@ -104,7 +104,10 @@ def test_token_is_bound_to_its_key(client, db, venue, make_user, login):
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
def test_token_is_bound_to_its_session(client, venue, login):
|
||||
def test_token_is_bound_to_its_session(client, db, venue, login):
|
||||
from models.settings import PosSettings
|
||||
db.add(PosSettings(key="auth.single_session_waiter", value="off")) # two phones of one waiter
|
||||
db.commit()
|
||||
v = venue
|
||||
token = approve(client, v["waiter_h"], "ordering.orders.cancel", v["manager"].username).json()["override_token"]
|
||||
other_phone = login(v["waiter"], client="waiter")
|
||||
@@ -192,7 +195,7 @@ def test_check_consumes_a_valid_token(db, venue):
|
||||
from core.access import override
|
||||
from core.access.check import AccessContext, check
|
||||
v = venue
|
||||
row = sessions.start(db, v["waiter"], "waiter")
|
||||
row = sessions.start(db, v["waiter"], "waiter", replace=True)
|
||||
token, _ = override.grant(db, key="ordering.orders.cancel", username=v["manager"].username, pin=TEST_PIN,
|
||||
requester=v["waiter"], sid=row.id)
|
||||
ctx = AccessContext(user=v["waiter"], session=row.id, override_token=token, target="unit")
|
||||
|
||||
@@ -189,7 +189,7 @@ def test_fiscal_driver_with_credit_notes_issues_one(client, db, till, menu, on_s
|
||||
class Machine(FiscalDriver):
|
||||
key, credit_notes = "test_machine", True
|
||||
|
||||
def prepare_receipt(self, db, items, method, total):
|
||||
def prepare_receipt(self, db, items, method, total, payments=None):
|
||||
return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
|
||||
|
||||
def prepare_credit_note(self, db, items, method, total, original=None):
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3, services/price_changes.py).
|
||||
|
||||
- The venue's switch `orders.price_change`: off refuses every by-hand price, before_sending refuses
|
||||
a sent line's, anytime allows both.
|
||||
- A sent line needs ordering.prices.modify_sent (modify alone is the cart); a manager's PIN is
|
||||
recorded as the approver.
|
||||
- `orders.price_change_reason`: a typed price needs a reason; the counter's % discount doesn't.
|
||||
- Every change is one manual_price event (before → after, quantity, who, stage, reason) and a
|
||||
PRICE_CHANGED audit row; only holders of ordering.prices.view_changes see them.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from conftest import TEST_PIN
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_order_lines import items_of, open_order
|
||||
from tests.test_pos import burger_line, menu, on_shift, till # noqa: F401 (fixtures)
|
||||
from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures)
|
||||
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_printing(monkeypatch):
|
||||
import routers.orders as orders
|
||||
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
|
||||
|
||||
|
||||
def setting(db, key, value):
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if row is None:
|
||||
db.add(PosSettings(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
|
||||
|
||||
def manual_events(db, order_id=None):
|
||||
from models.pricing import PriceEventLog
|
||||
db.expire_all()
|
||||
q = db.query(PriceEventLog).filter(PriceEventLog.event_type == "manual_price")
|
||||
if order_id is not None:
|
||||
q = q.filter(PriceEventLog.order_id == order_id)
|
||||
return q.order_by(PriceEventLog.id).all()
|
||||
|
||||
|
||||
def test_a_sent_line_changed_by_hand_is_recorded(client, db, shop, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
item.kds_status = "served"
|
||||
db.commit()
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
r = client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h,
|
||||
json={"price_adjustment": -1.5, "reason": " regular customer "})
|
||||
assert r.status_code == 200, r.text
|
||||
[ev] = manual_events(db, o.id)
|
||||
assert (ev.order_item_id, ev.price_before, ev.price_after, ev.delta_amount) == (item.id, 4.0, 2.5, -1.5)
|
||||
assert ev.stage == "served" and ev.quantity == 1 and ev.waiter_note == "regular customer" and ev.approved_by_user_id is None
|
||||
# a second change records from the changed price, the first stays
|
||||
r = client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": 0})
|
||||
assert r.status_code == 200
|
||||
evs = manual_events(db, o.id)
|
||||
assert [(e.price_before, e.price_after) for e in evs] == [(4.0, 2.5), (2.5, 4.0)]
|
||||
from models.order import OrderAuditLog
|
||||
assert db.query(OrderAuditLog).filter(OrderAuditLog.order_id == o.id, OrderAuditLog.event_type == "PRICE_CHANGED").count() == 2
|
||||
|
||||
|
||||
def test_the_venue_switch(client, db, shop, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
|
||||
boss = login(shop["owner"])
|
||||
setting(db, "orders.price_change", "before_sending")
|
||||
assert err(client.patch(url, headers=boss, json={"price_adjustment": -1})) == "order.price_change_sent_off"
|
||||
setting(db, "orders.price_change", "off")
|
||||
assert err(client.patch(url, headers=boss, json={"price_adjustment": -1})) == "order.price_change_off"
|
||||
setting(db, "orders.price_change", "anytime")
|
||||
assert client.patch(url, headers=boss, json={"price_adjustment": -1}).status_code == 200
|
||||
assert len(manual_events(db, o.id)) == 1
|
||||
|
||||
|
||||
def test_a_reason_when_the_venue_asks(client, db, shop, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
setting(db, "orders.price_change_reason", "true")
|
||||
assert err(client.patch(url, headers=h, json={"price_adjustment": -1})) == "order.price_reason_required"
|
||||
assert err(client.patch(url, headers=h, json={"price_adjustment": -1, "reason": " "})) == "order.price_reason_required"
|
||||
assert client.patch(url, headers=h, json={"price_adjustment": -1, "reason": "Burnt a bit"}).status_code == 200
|
||||
assert manual_events(db, o.id)[0].waiter_note == "Burnt a bit"
|
||||
|
||||
|
||||
def test_a_managers_pin_is_the_approver(client, db, shop, make_user, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
boss = make_user(role="owner")
|
||||
approved = client.post("/api/access/override", headers=shop["h"],
|
||||
json={"key": "ordering.prices.modify_sent", "username": boss.username, "pin": TEST_PIN})
|
||||
assert approved.status_code == 200, approved.text
|
||||
h = dict(shop["h"], **{"X-Xenia-Override": approved.json()["override_token"]})
|
||||
assert client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": 1}).status_code == 200
|
||||
[ev] = manual_events(db, o.id)
|
||||
assert ev.approved_by_user_id == boss.id and ev.applied_by_user_id == shop["waiter"].id
|
||||
|
||||
|
||||
def test_a_price_typed_in_the_cart(client, db, menu, phone, floor, make_user, login):
|
||||
oid = open_order(client, phone["h"], floor["t1"])
|
||||
line = {"product_id": menu["coffee"].id, "quantity": 2, "price_adjustment": -0.5, "price_reason": "Friend of the house"}
|
||||
from models.user import WaiterZone
|
||||
w = make_user(role="waiter", add=("ordering.prices.modify",))
|
||||
db.add(WaiterZone(waiter_id=w.id, group_id=None))
|
||||
db.commit()
|
||||
h = login(w, "waiter")
|
||||
r = client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [line]})
|
||||
assert r.status_code == 200, r.text
|
||||
[item] = items_of(db, oid)
|
||||
[ev] = manual_events(db, oid)
|
||||
assert ev.order_item_id == item.id and ev.stage == "cart" and ev.quantity == 2
|
||||
assert (ev.price_before, ev.price_after) == (item.unit_price, item.unit_price - 0.5) and ev.waiter_note == "Friend of the house"
|
||||
# the venue asks for a reason: a typed price without one is refused, nothing is added
|
||||
setting(db, "orders.price_change_reason", "true")
|
||||
assert err(client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [{**line, "price_reason": None}]})) == "order.price_reason_required"
|
||||
assert len(items_of(db, oid)) == 1
|
||||
setting(db, "orders.price_change", "off")
|
||||
assert err(client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [line]})) == "order.price_change_off"
|
||||
|
||||
|
||||
def test_the_counters_discount_is_recorded_without_a_reason(client, db, menu, pair, make_user):
|
||||
from core.timeutil import business_date_of, utcnow
|
||||
from models.business_day import BusinessDay
|
||||
from models.shift import WaiterShift
|
||||
from tests.test_live import terminal_login
|
||||
token, _ = pair("pos_counter", "Till 2")
|
||||
boss = make_user(role="owner")
|
||||
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"}
|
||||
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() or BusinessDay(
|
||||
status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id)
|
||||
db.add(day)
|
||||
db.flush()
|
||||
db.add(WaiterShift(waiter_id=boss.id, business_day_id=day.id))
|
||||
db.commit()
|
||||
setting(db, "orders.price_change_reason", "true")
|
||||
r = client.post("/api/pos/sales", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "discount_pct": 10}], "payments": [{"method": "card"}]})
|
||||
assert r.status_code == 201, r.text
|
||||
[ev] = manual_events(db, r.json()["order_id"])
|
||||
assert ev.stage == "cart" and ev.waiter_note == "−10 %" and ev.delta_amount < 0
|
||||
|
||||
|
||||
def test_only_holders_see_the_changes(client, db, shop, make_user, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": -1, "reason": "x"})
|
||||
seer = login(make_user(role="store_manager"))
|
||||
blind = login(make_user(role="store_manager", remove=("ordering.prices.view_changes",)))
|
||||
assert [e["event_type"] for e in client.get(f"/api/pricing/events/order/{o.id}", headers=seer).json()] == ["manual_price"]
|
||||
assert client.get(f"/api/pricing/events/order/{o.id}", headers=blind).json() == []
|
||||
got = client.get(f"/api/orders/{o.id}/price-changes", headers=seer).json()
|
||||
assert len(got) == 1 and got[0]["before"] == 4.0 and got[0]["after"] == 3.0 and got[0]["reason"] == "x" and got[0]["product_name"]
|
||||
assert client.get(f"/api/orders/{o.id}/price-changes", headers=blind).status_code == 403
|
||||
rep = client.get(f"/api/reports/price-changes?business_day_id={o.business_day_id}" if o.business_day_id else
|
||||
"/api/reports/price-changes", headers=seer).json()
|
||||
assert rep["count"] >= 1 and rep["total_value"] <= -1.0 and rep["by_person"][0]["count"] >= 1
|
||||
assert client.get("/api/reports/price-changes", headers=blind).status_code == 403
|
||||
|
||||
|
||||
def test_combining_lines_keeps_their_changes(client, db, shop, login):
|
||||
o, items = shop["order"], shop["items"]
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
for it in items[:2]:
|
||||
assert client.patch(f"/api/orders/{o.id}/items/{it.id}/price-adjust", headers=h, json={"price_adjustment": -1}).status_code == 200
|
||||
r = client.post(f"/api/orders/{o.id}/items/combine", headers=h, json={"item_ids": [items[0].id, items[1].id]})
|
||||
assert r.status_code == 200, r.text
|
||||
assert {e.order_item_id for e in manual_events(db, o.id)} == {items[0].id}
|
||||
assert len(manual_events(db, o.id)) == 2
|
||||
@@ -68,6 +68,7 @@ def test_waiter_pin_by_id(client, make_user):
|
||||
|
||||
def test_waiter_modes(client, make_user, admin_h):
|
||||
w = make_user(role="waiter")
|
||||
_set(client, admin_h, "auth.single_session_waiter", "off") # several logins of one waiter here
|
||||
_set(client, admin_h, "auth.waiter_login_mode", "password")
|
||||
r = client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN})
|
||||
assert r.json()["error"]["code"] == "auth.login_mode_not_allowed"
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Sign-in (plan 6F.7): one session per waiter asks before signing the other phone out (the
|
||||
default), only phones count; usernames on paired screens (venue setting + the device's own)."""
|
||||
import pytest
|
||||
|
||||
from conftest import TEST_PIN
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
|
||||
ANDROID = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36"
|
||||
|
||||
|
||||
def _phone(client, user, **extra):
|
||||
return client.post("/api/auth/login", headers={"user-agent": ANDROID},
|
||||
json={"client": "waiter", "user_id": user.id, "pin": TEST_PIN, **extra})
|
||||
|
||||
|
||||
def _h(r):
|
||||
assert r.status_code == 200, r.text
|
||||
return {"Authorization": f"Bearer {r.json()['access_token']}"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ended(monkeypatch):
|
||||
from services import ws_bus
|
||||
got = []
|
||||
real = ws_bus.end_session
|
||||
monkeypatch.setattr(ws_bus, "end_session", lambda sid, reason: (got.append(reason), real(sid, reason))[1])
|
||||
return got
|
||||
|
||||
|
||||
def test_ask_is_the_default_and_says_where(client, make_user, ended):
|
||||
w = make_user(role="waiter")
|
||||
first = _h(_phone(client, w))
|
||||
r = _phone(client, w)
|
||||
assert r.status_code == 409 and err(r) == "auth.session_elsewhere"
|
||||
params = r.json()["error"]["params"]
|
||||
assert params["device"] == "Android · Chrome" and params["since"].endswith("Z")
|
||||
assert client.get("/api/auth/me", headers=first).status_code == 200 # asking ends nothing
|
||||
second = _h(_phone(client, w, replace=True))
|
||||
gone = client.get("/api/auth/me", headers=first)
|
||||
assert gone.status_code == 401 and err(gone) == "auth.session_ended"
|
||||
assert gone.json()["error"]["params"]["reason"] == "replaced" # the old phone can say why
|
||||
assert ended == ["replaced"] # its socket was told at once
|
||||
assert client.get("/api/auth/me", headers=second).status_code == 200
|
||||
|
||||
|
||||
def test_replace_does_not_bypass_refuse_new(client, make_user, owner_h):
|
||||
assert client.put("/api/settings/auth.single_session_waiter", headers=owner_h, json={"value": "refuse_new"}).status_code == 200
|
||||
w = make_user(role="waiter")
|
||||
_h(_phone(client, w))
|
||||
r = _phone(client, w, replace=True)
|
||||
assert r.status_code == 409 and err(r) == "auth.session_exists"
|
||||
|
||||
|
||||
def test_only_phones_count(client, make_user, pair):
|
||||
owner = make_user(role="owner")
|
||||
token, dev = pair("pos_counter", "Till")
|
||||
till = client.post("/api/auth/login", headers={"X-Xenia-Device": token},
|
||||
json={"client": "terminal", "user_id": owner.id, "pin": TEST_PIN})
|
||||
assert till.status_code == 200, till.text
|
||||
_h(_phone(client, owner)) # the counter's session isn't a phone: no question
|
||||
till_h = {"Authorization": f"Bearer {till.json()['access_token']}", "X-Xenia-Device": token}
|
||||
assert client.get("/api/auth/me", headers=till_h).status_code == 200
|
||||
|
||||
|
||||
def test_usernames_on_terminals(client, make_user, owner_h, pair):
|
||||
cashier = make_user(role="owner")
|
||||
token, dev = pair("pos_counter", "Till")
|
||||
dh = {"X-Xenia-Device": token}
|
||||
assert len(client.get("/api/devices/me/users", headers=dh).json()) > 0
|
||||
assert client.put("/api/settings/auth.terminal_require_username", headers=owner_h, json={"value": "true"}).status_code == 200
|
||||
assert client.get("/api/devices/me/users", headers=dh).json() == []
|
||||
assert client.get("/api/devices/me", headers=dh).json()["require_username"] is True
|
||||
by_id = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "user_id": cashier.id, "pin": TEST_PIN})
|
||||
assert by_id.status_code == 422 and err(by_id) == "auth.username_required"
|
||||
wrong = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": "nobody_here", "pin": TEST_PIN})
|
||||
assert wrong.status_code == 401 and err(wrong) == "auth.invalid_credentials"
|
||||
ok = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": cashier.username, "pin": TEST_PIN})
|
||||
assert ok.status_code == 200, ok.text
|
||||
|
||||
# "tap" can't go with usernames: the screen asks for the PIN instead
|
||||
dev_id = dev.json()["id"]
|
||||
assert client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"login_mode": "tap"}).status_code == 200
|
||||
assert client.get("/api/devices/me", headers=dh).json()["login_mode"] == "pin"
|
||||
tap = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": cashier.username})
|
||||
assert tap.status_code == 403 and err(tap) == "auth.login_mode_not_allowed"
|
||||
|
||||
# the device's own choice wins over the venue's
|
||||
out = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"require_username": False}).json()
|
||||
assert out["require_username"] is False and out["effective_require_username"] is False
|
||||
assert client.get("/api/devices/me", headers=dh).json()["login_mode"] == "tap"
|
||||
assert len(client.get("/api/devices/me/users", headers=dh).json()) > 0
|
||||
out = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"require_username": None}).json()
|
||||
assert out["require_username"] is None and out["effective_require_username"] is True
|
||||
|
||||
|
||||
def test_device_label():
|
||||
from core.sessions import device_label
|
||||
assert device_label(ANDROID) == "Android · Chrome"
|
||||
assert device_label("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1") == "iPhone · Safari"
|
||||
assert device_label("Mozilla/5.0 (Linux; Android 14; wv) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36".replace("wv)", "Pixel; wv)")) == "Android · app"
|
||||
assert device_label(None) == ""
|
||||
@@ -0,0 +1,237 @@
|
||||
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
|
||||
|
||||
- POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status split) and adds part
|
||||
lines (the system product split_part), paid like any line; the venue's level and the key decide.
|
||||
- Undo while no part is paid; parts can't be cancelled, moved or re-priced on their own.
|
||||
- Counting: the settled lines are the sales, the parts are the money (drawers), never both.
|
||||
- Fiscal: one receipt with the settled lines, when the last part is paid, with each method's amount.
|
||||
- The counter: a quick sale split and paid at once (Q-4).
|
||||
"""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
|
||||
from tests.test_pos import burger_line, drawer_printer, menu, on_shift, sale, till # noqa: F401 (fixtures)
|
||||
from tests.test_pos_refunds import fiscal_on, refund, shift_of, wait_for
|
||||
|
||||
|
||||
def setting(db, key, value):
|
||||
from models.settings import PosSettings
|
||||
row = db.get(PosSettings, key)
|
||||
if row is None:
|
||||
db.add(PosSettings(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def table_order(db, till, menu, on_shift):
|
||||
"""The cashier's order with a 10.00 burger and a 5.00 (two coffees at 2.50), nothing paid."""
|
||||
from models.order import Order, OrderItem, OrderWaiter
|
||||
o = Order(opened_by=till["cashier"].id, order_type="here", status="open", business_day_id=on_shift.business_day_id)
|
||||
db.add(o)
|
||||
db.flush()
|
||||
db.add(OrderWaiter(order_id=o.id, waiter_id=till["cashier"].id))
|
||||
items = [OrderItem(order_id=o.id, product_id=menu["burger"].id, added_by=till["cashier"].id, quantity=1, unit_price=10.0,
|
||||
printed=True, kds_status="preparing", unit_cost=3.5),
|
||||
OrderItem(order_id=o.id, product_id=menu["coffee"].id, added_by=till["cashier"].id, quantity=2, unit_price=2.5,
|
||||
printed=True)]
|
||||
db.add_all(items)
|
||||
db.commit()
|
||||
return {"order": o, "items": items}
|
||||
|
||||
|
||||
def split(client, till, order_id, ids, **body):
|
||||
return client.post(f"/api/orders/{order_id}/split-bills", headers=till["h"], json={"item_ids": ids, **body})
|
||||
|
||||
|
||||
def rows(db, order_id):
|
||||
from models.order import OrderItem
|
||||
db.expire_all()
|
||||
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
|
||||
|
||||
|
||||
def pay(client, till, order_id, method, ids):
|
||||
return client.post(f"/api/pos/orders/{order_id}/pay", headers=till["h"], json={"payments": [{"method": method, "item_ids": ids}]})
|
||||
|
||||
|
||||
def test_amounts_and_levels():
|
||||
from services.split_bills import allowed, amounts
|
||||
assert amounts(10.0, "equal", 3) == [3.33, 3.33, 3.34]
|
||||
assert amounts(15.0, "equal", 2) == [7.5, 7.5]
|
||||
assert amounts(15.0, "custom", 2, 4.5) == [4.5, 10.5]
|
||||
assert sum(amounts(17.21, "equal", 7)) == pytest.approx(17.21)
|
||||
# each level includes the ones before; multiple ways are equal parts only (Q-1)
|
||||
assert not allowed("off", "equal", 2, 10)
|
||||
assert allowed("two_equal", "equal", 2, 10) and not allowed("two_equal", "custom", 2, 10)
|
||||
assert allowed("two_custom", "custom", 2, 10) and not allowed("two_custom", "equal", 3, 10)
|
||||
assert allowed("multiple_equal", "equal", 10, 10) and not allowed("multiple_equal", "equal", 11, 10)
|
||||
assert allowed("multiple_equal", "custom", 2, 10) and not allowed("multiple_equal", "custom", 3, 10)
|
||||
|
||||
|
||||
def test_split_30_70_paid_cash_and_card(client, db, till, table_order):
|
||||
"""10 + 5 into 4.50 + 10.50: the lines settled, two parts paid apart; the drawer counts the
|
||||
parts, the sales count the lines, never both."""
|
||||
from services import sales
|
||||
o, items = table_order["order"], table_order["items"]
|
||||
ids = [i.id for i in items]
|
||||
assert err(split(client, till, o.id, ids, mode="custom", first_amount=4.5)) == "split.not_allowed" # off by default
|
||||
setting(db, "payments.split_amount", "two_custom")
|
||||
r = split(client, till, o.id, ids, mode="custom", first_amount=4.5)
|
||||
assert r.status_code == 200, r.text
|
||||
bill = r.json()
|
||||
assert (bill["total"], bill["amounts"], bill["parts"], bill["can_undo"]) == (15.0, [4.5, 10.5], 2, True)
|
||||
lines = rows(db, o.id)
|
||||
settled = [i for i in lines if i.status == "split"]
|
||||
parts = [i for i in lines if i.split_bill_id and i.status != "split"]
|
||||
assert {i.id for i in settled} == set(ids) and all(i.paid_in_shift_id is None and i.payment_method is None for i in settled)
|
||||
assert [(p.product_name, p.unit_price, p.status, p.printed, p.kds_status) for p in parts] == [
|
||||
("Split bill 1/2", 4.5, "active", True, "served"), ("Split bill 2/2", 10.5, "active", True, "served")]
|
||||
assert parts[0].product.system_key == "split_part"
|
||||
# the settled burger is still cooking: the kitchen state is untouched
|
||||
assert next(i for i in settled if i.unit_price == 10.0).kds_status == "preparing"
|
||||
got = client.get(f"/api/orders/{o.id}", headers=till["h"]).json()
|
||||
assert got["split_bills"][0]["part_ids"] == [p.id for p in parts]
|
||||
|
||||
assert pay(client, till, o.id, "cash", [parts[0].id]).status_code == 200
|
||||
# undo refused once a part is paid (Q-2)
|
||||
assert err(client.post(f"/api/orders/{o.id}/split-bills/{bill['id']}/undo", headers=till["h"])) == "split.paid_already"
|
||||
r = pay(client, till, o.id, "card", [parts[1].id])
|
||||
assert r.status_code == 200 and r.json()["status"] in ("paid", "closed"), r.text
|
||||
|
||||
s = shift_of(client, till)
|
||||
assert (s["cash_sales"], s["card_sales"]) == (4.5, 10.5)
|
||||
money = sales.totals(sales.lines(db, rows(db, o.id))).out()
|
||||
assert (money["revenue"], money["fees"], money["takings"], money["total_cost"]) == (15.0, 0.0, 15.0, 3.5)
|
||||
assert {p["product_name"] for p in sales.products(db, rows(db, o.id)).values()} == {"Burger", "Freddo"}
|
||||
|
||||
|
||||
def test_equal_parts_levels_and_the_key(client, db, till, table_order, login, make_user):
|
||||
o, items = table_order["order"], table_order["items"]
|
||||
ids = [i.id for i in items]
|
||||
setting(db, "payments.split_amount", "two_equal")
|
||||
assert err(split(client, till, o.id, ids, parts=3)) == "split.not_allowed"
|
||||
assert err(split(client, till, o.id, ids, mode="custom", first_amount=5)) == "split.not_allowed"
|
||||
setting(db, "payments.split_amount", "multiple_equal")
|
||||
setting(db, "payments.split_max_parts", "4")
|
||||
assert err(split(client, till, o.id, ids, parts=5)) == "split.not_allowed"
|
||||
# the key: someone without it is refused (a manager could approve it, D-10)
|
||||
from models.user import WaiterZone
|
||||
w = make_user(role="waiter", remove=("ordering.payments.split_amount",))
|
||||
db.add(WaiterZone(waiter_id=w.id, group_id=None))
|
||||
db.commit()
|
||||
r = client.post(f"/api/orders/{o.id}/split-bills", headers=login(w, client="waiter"), json={"item_ids": ids, "parts": 3})
|
||||
assert err(r) in ("access.denied", "access.override_possible")
|
||||
r = split(client, till, o.id, ids, parts=4)
|
||||
assert r.status_code == 200 and r.json()["amounts"] == [3.75, 3.75, 3.75, 3.75]
|
||||
# the same lines can't be split twice
|
||||
assert err(split(client, till, o.id, ids, parts=2)) == "split.lines_changed"
|
||||
|
||||
|
||||
def test_locks_close_and_undo(client, db, till, table_order):
|
||||
from models.order import OrderAuditLog
|
||||
o, items = table_order["order"], table_order["items"]
|
||||
setting(db, "payments.split_amount", "multiple_equal")
|
||||
bill = split(client, till, o.id, [i.id for i in items], parts=3).json()
|
||||
assert bill["amounts"] == [5.0, 5.0, 5.0]
|
||||
part = bill["part_ids"][0]
|
||||
h = till["h"]
|
||||
assert err(client.delete(f"/api/orders/{o.id}/items/{part}", headers=h)) in ("split.part_locked", "access.override_possible")
|
||||
assert err(client.patch(f"/api/orders/{o.id}/items/{part}/price-adjust", headers=h, json={"price_adjustment": -1})) == "split.part_locked"
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/combine", headers=h, json={"item_ids": bill["part_ids"][:2]})) == "split.part_locked"
|
||||
assert err(client.patch(f"/api/orders/{o.id}/items/{items[0].id}/price-adjust", headers=h, json={"price_adjustment": -1})) == "order.item_not_active"
|
||||
setting(db, "orders.close_with_unpaid", "true")
|
||||
assert err(client.post(f"/api/orders/{o.id}/close", headers=h)) == "split.parts_unpaid" # never written off
|
||||
# undo: the parts cancelled, the lines unpaid again
|
||||
r = client.post(f"/api/orders/{o.id}/split-bills/{bill['id']}/undo", headers=h)
|
||||
assert r.status_code == 200, r.text
|
||||
lines = rows(db, o.id)
|
||||
assert [i.status for i in lines if i.id in (items[0].id, items[1].id)] == ["active", "active"]
|
||||
assert all(i.split_bill_id is None and i.paid_at is None for i in lines if i.id in (items[0].id, items[1].id))
|
||||
assert [(i.status, i.cancel_reason) for i in lines if i.id in bill["part_ids"]] == [("cancelled", "split undone")] * 3
|
||||
assert client.get(f"/api/orders/{o.id}", headers=h).json()["split_bills"] == []
|
||||
events = [a.event_type for a in db.query(OrderAuditLog).filter(OrderAuditLog.order_id == o.id).order_by(OrderAuditLog.id)]
|
||||
assert events[-2:] == ["SPLIT_CREATED", "SPLIT_UNDONE"]
|
||||
|
||||
|
||||
def test_the_fiscal_receipt_is_the_lines_when_the_last_part_is_paid(client, db, till, menu, table_order, tmp_path, monkeypatch):
|
||||
from services import fiscal
|
||||
from services.fiscal.base import FiscalDriver
|
||||
issued = []
|
||||
|
||||
class Machine(FiscalDriver):
|
||||
key = "test_machine"
|
||||
|
||||
def prepare_receipt(self, db, items, method, total, payments=None):
|
||||
issued.append((items, method, total, payments))
|
||||
return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
|
||||
|
||||
monkeypatch.setitem(fiscal.DRIVERS, "test_machine", Machine())
|
||||
monkeypatch.setattr(fiscal, "_set_status", lambda *a: None)
|
||||
fiscal_on(db, tmp_path)
|
||||
setting(db, "fiscal.type", "test_machine")
|
||||
o, items = table_order["order"], table_order["items"]
|
||||
setting(db, "payments.split_amount", "two_custom")
|
||||
assert err(split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5)) == "pos.fiscal_vat_missing"
|
||||
menu["burger"].fiscal_vat_group_id = 1
|
||||
menu["coffee"].fiscal_vat_group_id = 2
|
||||
db.commit()
|
||||
bill = split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5).json()
|
||||
r = pay(client, till, o.id, "cash", [bill["part_ids"][0]])
|
||||
assert r.status_code == 200 and r.json()["fiscal"] is None and issued == [] # part 1: no receipt yet
|
||||
r = pay(client, till, o.id, "card", [bill["part_ids"][1]])
|
||||
assert r.status_code == 200 and r.json()["fiscal"] == "pending"
|
||||
assert wait_for(lambda: issued)
|
||||
lines, _method, total, payments = issued[0]
|
||||
assert sorted((x["name"], x["qty"], x["unit_price"], x["vat_group_id"]) for x in lines) == [("Burger", 1, 10.0, 1), ("Freddo", 2, 2.5, 2)]
|
||||
assert total == 15.0 and sorted((p["method"], p["amount"]) for p in payments) == [("card", 10.5), ("cash", 4.5)]
|
||||
assert sum(x["qty"] * x["unit_price"] for x in lines) == pytest.approx(sum(p["amount"] for p in payments))
|
||||
assert len(issued) == 1
|
||||
|
||||
|
||||
def test_the_text_file_closes_with_card_then_cash(db, tmp_path):
|
||||
from services.fiscal.txt_file import _build_command_file
|
||||
fiscal_on(db, tmp_path)
|
||||
out = _build_command_file([{"name": "Burger", "qty": 1, "unit_price": 10.0, "vat_group_id": 1}], "cash", 10.0, db,
|
||||
payments=[{"method": "cash", "amount": 4.5}, {"method": "card", "amount": 5.5}])
|
||||
assert out.split("\r\n")[-3:] == ["CD|2|1|1|5.50", "CR|2", ""]
|
||||
out = _build_command_file([{"name": "Burger", "qty": 1, "unit_price": 10.0, "vat_group_id": 1}], "cash", 10.0, db,
|
||||
payments=[{"method": "card", "amount": 10.0}])
|
||||
assert out.split("\r\n")[-2:] == ["CD|2|1|1|10.00", ""]
|
||||
|
||||
|
||||
def test_a_refunded_part_comes_off_the_settled_lines(client, db, till, table_order, drawer_printer):
|
||||
from services import sales
|
||||
o, items = table_order["order"], table_order["items"]
|
||||
setting(db, "payments.split_amount", "two_custom")
|
||||
bill = split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5).json()
|
||||
assert pay(client, till, o.id, "cash", bill["part_ids"]).status_code == 200
|
||||
r = refund(client, till, o.id, [{"item_id": bill["part_ids"][0], "quantity": 1}], reason="Overcharged")
|
||||
assert r.status_code == 201, r.text
|
||||
money = sales.totals(sales.lines(db, rows(db, o.id))).out()
|
||||
assert (money["revenue"], money["refunded"]) == (10.5, 4.5)
|
||||
assert shift_of(client, till)["cash_refunds"] == 4.5
|
||||
|
||||
|
||||
def test_a_quick_sale_split_and_paid_at_once(client, db, till, menu, on_shift, drawer_printer):
|
||||
"""Q-4: the counter splits a quick sale into equal parts, each paid its own way now."""
|
||||
from models.order import Order
|
||||
setting(db, "payments.split_amount", "multiple_equal")
|
||||
lines = [{"product_id": menu["coffee"].id, "quantity": 3}, burger_line(menu)]
|
||||
r = sale(client, till, lines, [], split={"mode": "equal", "parts": 3, "methods": ["cash", "card", "cash"]}, cash_given=20)
|
||||
assert r.status_code == 201, r.text
|
||||
body = r.json()
|
||||
assert body["total"] == 19.0 and body["split"]["amounts"] == [6.33, 6.33, 6.34]
|
||||
assert sorted((p["method"], p["amount"]) for p in body["payments"]) == [("card", 6.33), ("cash", 12.67)]
|
||||
assert body["change"] == 7.33
|
||||
db.expire_all()
|
||||
assert db.get(Order, body["order_id"]).status in ("paid", "closed")
|
||||
s = shift_of(client, till)
|
||||
assert (s["cash_sales"], s["card_sales"]) == (12.67, 6.33)
|
||||
# off at this venue → refused before anything is written
|
||||
setting(db, "payments.split_amount", "two_equal")
|
||||
n = db.query(Order).count()
|
||||
r = sale(client, till, lines, [], split={"mode": "equal", "parts": 3, "methods": ["cash", "card", "cash"]})
|
||||
assert err(r) == "split.not_allowed" and db.query(Order).count() == n
|
||||
@@ -98,10 +98,13 @@ def test_revert_payment_is_a_key_a_manager_can_approve(client, db, shop):
|
||||
|
||||
|
||||
def test_price_change_needs_only_the_key_no_venue_switch(client, shop, login):
|
||||
"""A sent line's price: ordering.prices.modify_sent since 6F.3 (modify alone is for the cart)."""
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
|
||||
assert err(client.patch(url, headers=shop["h"], json={"price_adjustment": -1})) == "access.override_possible"
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify",)), client="waiter")
|
||||
assert err(client.patch(url, headers=h, json={"price_adjustment": -1})) == "access.override_possible"
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
r = client.patch(url, headers=h, json={"price_adjustment": -1})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ import PrepZonesPage from './pages/reports/prepzones/PrepZonesReport'
|
||||
import ExpensesReportPage from './pages/reports/expenses/ExpensesReport'
|
||||
import TechnicalPage from './pages/reports/technical/TechnicalReport'
|
||||
import MiscPage from './pages/reports/misc/MiscReport'
|
||||
import MovesPage from './pages/reports/moves/MovesReport'
|
||||
|
||||
// Other
|
||||
import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage'
|
||||
@@ -172,6 +173,7 @@ export default function App() {
|
||||
<Route path="reports/expenses" element={<ExpensesReportPage />} />
|
||||
<Route path="reports/technical" element={<TechnicalPage />} />
|
||||
<Route path="reports/misc" element={<MiscPage />} />
|
||||
<Route path="reports/moves" element={<MovesPage />} />
|
||||
|
||||
{/* ── Apps & Settings ── */}
|
||||
<Route path="apps" element={<AppsPage />} />
|
||||
|
||||
@@ -5,10 +5,15 @@
|
||||
// `platform_notification` {id} and after every reconnect ('ready').
|
||||
// - A NEW warning/critical one also pops up as a toast.
|
||||
// - Opening an item marks it read; "Mark all as read" does the rest.
|
||||
// - 6F.8: an item whose params carry an `action` gets a button: 'open_day' opens the business
|
||||
// day here (POST /api/business-day/open), 'overview' goes to the overview. Those alerts stay
|
||||
// until their cause is gone (the backend resolves them; a live event refreshes the list).
|
||||
// Not staff chat (/api/notifications, the chat module), which stays separate.
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Bell, CheckCheck } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation, useFormat } from '@xenia/i18n'
|
||||
import client from '../api/client'
|
||||
import { useLiveEvent } from '../live/useLiveEvent'
|
||||
@@ -22,6 +27,7 @@ export default function NotificationBell() {
|
||||
const [data, setData] = useState({ items: [], unread: 0 })
|
||||
const [open, setOpen] = useState(false)
|
||||
const ref = useRef(null)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const asked = useRef(0)
|
||||
const load = useCallback(async () => {
|
||||
@@ -74,6 +80,20 @@ export default function NotificationBell() {
|
||||
load()
|
||||
}
|
||||
|
||||
async function act(n) {
|
||||
await markRead(n)
|
||||
if (n.params?.action === 'overview') { setOpen(false); navigate('/'); return }
|
||||
if (n.params?.action === 'open_day') {
|
||||
try {
|
||||
await client.post('/api/business-day/open', {})
|
||||
toast.success(t('notifications.dayOpened'))
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t))
|
||||
}
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
const badge = data.unread > 9 ? '9+' : String(data.unread)
|
||||
|
||||
return (
|
||||
@@ -109,11 +129,17 @@ export default function NotificationBell() {
|
||||
: (
|
||||
<ul className="max-h-[60vh] overflow-y-auto divide-y divide-line">
|
||||
{data.items.map(n => (
|
||||
<li key={n.id}>
|
||||
<li key={n.id} className="relative">
|
||||
{n.params?.action && (
|
||||
<button onClick={() => act(n)} data-testid={`notif-action-${n.id}`}
|
||||
className="absolute right-3 top-3 z-10 rounded-control border border-line bg-surface px-2.5 py-1 text-caption font-medium text-accent-ink hover:bg-surface-2">
|
||||
{t(`notifications.actions.${n.params.action}`, { defaultValue: n.params.action })}
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => markRead(n)} className={`w-full text-left flex gap-3 px-4 py-3 hover:bg-surface-2 ${n.read ? '' : 'bg-accent-soft/40'}`}
|
||||
data-testid={`notif-${n.id}`} data-read={n.read ? 'true' : 'false'}>
|
||||
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${DOT[n.severity] || DOT.info}`} />
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className={`flex-1 min-w-0 ${n.params?.action ? 'pr-28' : ''}`}>
|
||||
<span className={`block text-label ${n.read ? 'text-ink-2' : 'text-ink font-medium'}`}>{n.message}</span>
|
||||
<span className="block text-caption text-ink-3 mt-0.5">
|
||||
{f.formatRelative(n.last_at)}
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
// table flags, quick messages to the staff, and sending the digital menu to the cloud now.
|
||||
// Each part shows only with its app on. Dropped from v1: "automatic store schedule" (its switches
|
||||
// were kept in the browser only and nothing ever read them).
|
||||
import { useState } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useId, useState } from 'react'
|
||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { ArrowDown, ArrowUp, Plus, RefreshCw, Trash2 } from 'lucide-react'
|
||||
import { useModule } from '@xenia/access'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Columns, IconButton, InfoTip, Input, Spinner, Switch } from '@xenia/ui'
|
||||
import { Button, Columns, IconButton, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||
import client from '../../../api/client'
|
||||
import QuickMessages from './QuickMessages'
|
||||
import RolePermissions from './RolePermissions'
|
||||
@@ -64,11 +64,138 @@ function OrderingSettings() {
|
||||
<Toggle s={s} k="orders.bypass_kds_serve" label={o('bypassKds')} hint={o('bypassKdsHint')} tip={o('bypassKdsTip')} />
|
||||
<Toggle s={s} k="orders.courses_enabled" label={o('courses')} hint={o('coursesHint')} tip={o('coursesTip')} />
|
||||
{s.get('orders.courses_enabled') === 'true' && <Courses s={s} />}
|
||||
<QuickNotes s={s} />
|
||||
<TextList s={s} k="orders.quick_notes" title={o('quickNotes')} hint={o('quickNotesHint')} tip={o('quickNotesTip')}
|
||||
itemLabel={o('quickNote')} placeholder={o('newQuickNote')} testId="settings-quick-notes" newTestId="quick-note" />
|
||||
</SettingsCard>
|
||||
<PriceChangeSettings s={s} />
|
||||
<QuantitySettings s={s} />
|
||||
<SplitSettings s={s} />
|
||||
<AutoDaySettings s={s} />
|
||||
</>)
|
||||
}
|
||||
|
||||
const DAY_MODES = ['off', 'schedule', 'time', 'alert']
|
||||
const OFFSETS = ['0', '15', '30', '45', '60', '90', '120']
|
||||
|
||||
/** The day opens and closes by itself (6F.8, services/day_auto.py): at the opening hours (the
|
||||
* Schedule page), at a time of its own, or only an alert. Closing waits for every table (Q-10). */
|
||||
function AutoDaySettings({ s }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const a = (k, o) => t(`settings.autoDay.${k}`, o)
|
||||
const ids = { open: useId(), close: useId(), openTime: useId(), closeTime: useId(), openOff: useId(), closeOff: useId() }
|
||||
const { data: hours } = useQuery({ queryKey: ['opening-hours'], queryFn: () => client.get('/api/identity/hours').then(r => r.data) })
|
||||
const mode = which => s.get(`business_day.auto_${which}`, 'off')
|
||||
const usesHours = ['open', 'close'].some(w => ['schedule', 'alert'].includes(mode(w)))
|
||||
const noHours = usesHours && hours && !hours.set
|
||||
const side = which => {
|
||||
const m = mode(which)
|
||||
const key = `business_day.auto_${which}`
|
||||
return (<>
|
||||
<SettingRow label={a(which)} hint={which === 'close' ? a('closeHint') : a('openHint')} tip={a(`${which}Tip`)} htmlFor={ids[which]}
|
||||
warning={m !== 'off' && m !== 'time' && noHours ? a('noHours') : undefined}>
|
||||
<Select id={ids[which]} value={m} disabled={s.saving} data-testid={`setting-${key}`}
|
||||
onChange={e => s.save(key, e.target.value)}
|
||||
options={DAY_MODES.map(v => ({ value: v, label: a(`modes.${which}.${v}`) }))} />
|
||||
</SettingRow>
|
||||
{m === 'time' && (
|
||||
<SettingRow label={a(`${which}Time`)} htmlFor={ids[`${which}Time`]}>
|
||||
<TimeField id={ids[`${which}Time`]} value={s.get(`${key}_time`, which === 'open' ? '09:00' : '23:30')} disabled={s.saving}
|
||||
testId={`setting-${key}_time`} onSave={v => s.save(`${key}_time`, v)} />
|
||||
</SettingRow>
|
||||
)}
|
||||
{m === 'schedule' && (
|
||||
<SettingRow label={a(`${which}Offset`)} htmlFor={ids[`${which}Off`]}>
|
||||
<Select id={ids[`${which}Off`]} value={String(s.get(`${key}_offset_min`, '0'))} disabled={s.saving} data-testid={`setting-${key}_offset_min`}
|
||||
onChange={e => s.save(`${key}_offset_min`, e.target.value)}
|
||||
options={OFFSETS.map(n => ({ value: n, label: n === '0' ? a('offsetNone') : a(which === 'open' ? 'before' : 'after', { count: Number(n) }) }))} />
|
||||
</SettingRow>
|
||||
)}
|
||||
</>)
|
||||
}
|
||||
return (
|
||||
<SettingsCard title={a('title')} description={a('intro')} testId="settings-auto-day">
|
||||
{side('open')}
|
||||
{side('close')}
|
||||
{usesHours && <Toggle s={s} k="business_day.auto_ignore_break" fallback="true" label={a('ignoreBreak')} hint={a('ignoreBreakHint')} tip={a('ignoreBreakTip')} />}
|
||||
</SettingsCard>
|
||||
)
|
||||
}
|
||||
|
||||
/** HH:MM, saved when a whole time is typed. */
|
||||
function TimeField({ id, value, disabled, testId, onSave }) {
|
||||
const [v, setV] = useState(value)
|
||||
return (
|
||||
<Input id={id} type="time" value={v} disabled={disabled} data-testid={testId} className="w-32"
|
||||
onChange={e => { setV(e.target.value); if (/^\d\d:\d\d$/.test(e.target.value) && e.target.value !== value) onSave(e.target.value) }} />
|
||||
)
|
||||
}
|
||||
|
||||
/** Splitting a bill by amount (6F.6), each level with the ones before. Who may:
|
||||
* ordering.payments.split_amount ("What each role may do", a person's permissions). */
|
||||
function SplitSettings({ s }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const q = k => t(`settings.split.${k}`)
|
||||
const id = useId()
|
||||
const maxId = useId()
|
||||
const level = s.get('payments.split_amount', 'off')
|
||||
return (
|
||||
<SettingsCard title={q('title')} description={q('intro')} testId="settings-split">
|
||||
<SettingRow label={q('when')} hint={q('whenHint')} tip={q('whenTip')} htmlFor={id}>
|
||||
<Select id={id} value={level} disabled={s.saving} data-testid="setting-payments.split_amount"
|
||||
onChange={e => s.save('payments.split_amount', e.target.value)}
|
||||
options={['off', 'two_equal', 'two_custom', 'multiple_equal'].map(v => ({ value: v, label: q(`levels.${v}`) }))} />
|
||||
</SettingRow>
|
||||
{level === 'multiple_equal' && (
|
||||
<SettingRow label={q('max')} hint={q('maxHint')} htmlFor={maxId}>
|
||||
<Select id={maxId} value={String(s.get('payments.split_max_parts', '10'))} disabled={s.saving} data-testid="setting-payments.split_max_parts"
|
||||
onChange={e => s.save('payments.split_max_parts', e.target.value)}
|
||||
options={[3, 4, 5, 6, 8, 10, 12, 15, 20].map(n => ({ value: String(n), label: String(n) }))} />
|
||||
</SettingRow>
|
||||
)}
|
||||
</SettingsCard>
|
||||
)
|
||||
}
|
||||
|
||||
/** A sent line's quantity changed without a new ticket (6F.5). Who may: ordering.items.change_quantity;
|
||||
* lowering also needs ordering.orders.cancel ("What each role may do", a person's permissions). */
|
||||
function QuantitySettings({ s }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const q = k => t(`settings.quantity.${k}`)
|
||||
const id = useId()
|
||||
return (
|
||||
<SettingsCard title={q('title')} description={q('intro')} testId="settings-quantity">
|
||||
<SettingRow label={q('when')} hint={q('whenHint')} tip={q('whenTip')} htmlFor={id}>
|
||||
<Select id={id} value={s.get('orders.quantity_change', 'off')} disabled={s.saving} data-testid="setting-orders.quantity_change"
|
||||
onChange={e => s.save('orders.quantity_change', e.target.value)}
|
||||
options={['off', 'add_only', 'add_and_remove'].map(v => ({ value: v, label: q(`modes.${v}`) }))} />
|
||||
</SettingRow>
|
||||
</SettingsCard>
|
||||
)
|
||||
}
|
||||
|
||||
/** Prices changed by hand (6F.3): the venue's switch, the reason, the quick reasons. Who may: the
|
||||
* keys ordering.prices.modify / modify_sent ("What each role may do", a person's permissions). */
|
||||
function PriceChangeSettings({ s }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const p = k => t(`settings.prices.${k}`)
|
||||
const id = useId()
|
||||
const reasonOn = s.get('orders.price_change_reason', 'false') === 'true'
|
||||
return (
|
||||
<SettingsCard title={p('title')} description={p('intro')} testId="settings-price-changes">
|
||||
<SettingRow label={p('when')} hint={p('whenHint')} tip={p('whenTip')} htmlFor={id}>
|
||||
<Select id={id} value={s.get('orders.price_change', 'anytime')} disabled={s.saving} data-testid="setting-orders.price_change"
|
||||
onChange={e => s.save('orders.price_change', e.target.value)}
|
||||
options={['off', 'before_sending', 'anytime'].map(v => ({ value: v, label: p(`modes.${v}`) }))} />
|
||||
</SettingRow>
|
||||
{s.get('orders.price_change', 'anytime') !== 'off' && (<>
|
||||
<Toggle s={s} k="orders.price_change_reason" label={p('reason')} hint={p('reasonHint')} tip={p('reasonTip')} />
|
||||
{reasonOn && <TextList s={s} k="orders.price_change_reasons" title={p('reasons')} hint={p('reasonsHint')}
|
||||
itemLabel={p('reasonItem')} placeholder={p('newReason')} testId="settings-price-reasons" newTestId="price-reason" />}
|
||||
</>)}
|
||||
</SettingsCard>
|
||||
)
|
||||
}
|
||||
|
||||
/** orders.courses: [{ id, name, color }] in the order they are served. */
|
||||
function Courses({ s }) {
|
||||
const { t } = useTranslation('manager')
|
||||
@@ -94,29 +221,30 @@ function Courses({ s }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** orders.quick_notes: the notes a waiter can add to a line with one tap. */
|
||||
function QuickNotes({ s }) {
|
||||
/** A JSON list of short texts in a setting (orders.quick_notes: notes a waiter adds to a line with
|
||||
* one tap; orders.price_change_reasons: quick reasons for a price changed by hand, 6F.3). */
|
||||
function TextList({ s, k, title, hint, tip, itemLabel, placeholder, testId, newTestId }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const notes = readJson(s.get('orders.quick_notes', '[]'), [])
|
||||
const notes = readJson(s.get(k, '[]'), [])
|
||||
const [typed, setTyped] = useState('')
|
||||
const [edits, setEdits] = useState({})
|
||||
const save = next => s.save('orders.quick_notes', JSON.stringify(cleanNotes(next)))
|
||||
const save = next => s.save(k, JSON.stringify(cleanNotes(next)))
|
||||
const add = () => { if (typed.trim()) { save([...notes, typed]); setTyped('') } }
|
||||
return (
|
||||
<div className="px-5 py-3 grid gap-2" data-testid="settings-quick-notes">
|
||||
<span className="flex items-center gap-1 text-body font-medium text-ink">{t('settings.ops.quickNotes')}<InfoTip>{t('settings.ops.quickNotesTip')}</InfoTip></span>
|
||||
<span className="text-label text-ink-2 -mt-1">{t('settings.ops.quickNotesHint')}</span>
|
||||
<div className="px-5 py-3 grid gap-2" data-testid={testId}>
|
||||
<span className="flex items-center gap-1 text-body font-medium text-ink">{title}{tip && <InfoTip>{tip}</InfoTip>}</span>
|
||||
<span className="text-label text-ink-2 -mt-1">{hint}</span>
|
||||
{notes.map((n, i) => (
|
||||
<div key={`${i}-${n}`} className="flex items-center gap-2">
|
||||
<Input value={edits[i] ?? n} aria-label={t('settings.ops.quickNote')} onChange={e => setEdits(x => ({ ...x, [i]: e.target.value }))}
|
||||
<Input value={edits[i] ?? n} aria-label={itemLabel} onChange={e => setEdits(x => ({ ...x, [i]: e.target.value }))}
|
||||
onBlur={() => { if (edits[i] != null && edits[i] !== n) save(notes.map((x, j) => (j === i ? edits[i] : x))); setEdits({}) }} />
|
||||
<IconButton size="sm" variant="ghost" label={t('settings.ops.remove', { name: n })} onClick={() => save(notes.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex items-center gap-2">
|
||||
<Input value={typed} placeholder={t('settings.ops.newQuickNote')} aria-label={t('settings.ops.newQuickNote')} onChange={e => setTyped(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid="quick-note-new" />
|
||||
<Button size="sm" variant="secondary" icon={<Plus size={14} />} disabled={!typed.trim()} onClick={add} data-testid="quick-note-add">{t('settings.ops.add')}</Button>
|
||||
<Input value={typed} placeholder={placeholder} aria-label={placeholder} onChange={e => setTyped(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid={`${newTestId}-new`} />
|
||||
<Button size="sm" variant="secondary" icon={<Plus size={14} />} disabled={!typed.trim()} onClick={add} data-testid={`${newTestId}-add`}>{t('settings.ops.add')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// auth.default_login_mode (paired devices; a device can choose its own on the Devices page),
|
||||
// auth.single_session_manager / _waiter, security.autofill_username (the sign-in page) and
|
||||
// auth.idle_days (sign out after N days without use, 0 = never; owner decision 2026-11-14, 2.99d).
|
||||
// 6F.7: waiters get 'ask' (the default: the phone asks before signing the other one out; only
|
||||
// phones count), and auth.terminal_require_username (paired screens list nobody).
|
||||
// Replaces the v1 "login method" card, whose setting (security.login_method) no longer exists.
|
||||
import { useId } from 'react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
@@ -11,6 +13,7 @@ import { SettingRow, SettingsCard } from './SettingsCard'
|
||||
import { useSettings } from './useSettings'
|
||||
|
||||
const SESSION_RULES = ['off', 'refuse_new', 'end_old']
|
||||
const WAITER_SESSION_RULES = ['ask', 'off', 'refuse_new', 'end_old']
|
||||
const IDLE_DAYS = ['7', '14', '30', '60', '90', '0']
|
||||
|
||||
export default function SignInSettings() {
|
||||
@@ -56,11 +59,14 @@ export default function SignInSettings() {
|
||||
<SettingRow label={t('settings.signIn.device')} htmlFor={idDevice} hint={t('settings.signIn.deviceHint')} tip={t('settings.signIn.deviceTip')}>
|
||||
{select('auth.default_login_mode', 'pin', opts(['pin', 'password', 'tap', 'none'], 'settings.mode'), idDevice)}
|
||||
</SettingRow>
|
||||
<SettingRow label={t('settings.signIn.terminalUsername')} hint={t('settings.signIn.terminalUsernameHint')} tip={t('settings.signIn.terminalUsernameTip')}>
|
||||
{toggle('auth.terminal_require_username', 'false', t('settings.signIn.terminalUsername'))}
|
||||
</SettingRow>
|
||||
<SettingRow label={t('settings.signIn.singleManager')} htmlFor={idSingleManager} tip={t('settings.signIn.singleTip')}>
|
||||
{select('auth.single_session_manager', 'off', opts(SESSION_RULES, 'settings.session'), idSingleManager)}
|
||||
</SettingRow>
|
||||
<SettingRow label={t('settings.signIn.singleWaiter')} htmlFor={idSingleWaiter} tip={t('settings.signIn.singleTip')}>
|
||||
{select('auth.single_session_waiter', 'off', opts(SESSION_RULES, 'settings.session'), idSingleWaiter)}
|
||||
<SettingRow label={t('settings.signIn.singleWaiter')} htmlFor={idSingleWaiter} hint={t('settings.signIn.singleWaiterHint')} tip={t('settings.signIn.singleWaiterTip')}>
|
||||
{select('auth.single_session_waiter', 'ask', opts(WAITER_SESSION_RULES, 'settings.session'), idSingleWaiter)}
|
||||
</SettingRow>
|
||||
<SettingRow label={t('settings.signIn.idle')} htmlFor={idIdle} hint={t('settings.signIn.idleHint')} tip={t('settings.signIn.idleTip')}>
|
||||
{select('auth.idle_days', '14', idleOptions, idIdle)}
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
// evaluated by the backend's engine (local_backend/services/fees.py, the same file the cloud
|
||||
// runs); this file only turns forms into request bodies and rules into readable lines.
|
||||
// Pure: unit-tested in Node (tests/fees.test.mjs).
|
||||
import { parseNumber } from '@xenia/i18n/number'
|
||||
|
||||
export const ACTIONS = ['set', 'add', 'percent', 'free', 'minimum']
|
||||
export const DAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0
|
||||
|
||||
const num = v => (v === '' || v == null ? null : Number(String(v).replace(',', '.')))
|
||||
const num = v => (v === '' || v == null ? null : (parseNumber(String(v)) ?? NaN))
|
||||
|
||||
/** Postcodes typed with commas, semicolons or new lines → a tidy list without duplicates. */
|
||||
export function parsePostcodes(text) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { EmptyState, cx } from '@xenia/ui'
|
||||
import { Pill } from '../overview/parts'
|
||||
import { nameOf } from './orderLogic'
|
||||
import { nameOf, pathText } from './orderLogic'
|
||||
|
||||
const EVENT_TONE = { PAYMENT: 'success', PAYMENT_OFFLINE: 'success', ORDER_CLOSED: 'neutral', ORDER_CANCELLED: 'danger', ITEM_CANCELLED: 'danger' }
|
||||
const ids = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
|
||||
@@ -59,6 +59,8 @@ export function PriceEventList({ events }) {
|
||||
<span className="flex flex-wrap gap-x-3">
|
||||
{(ev.modifier_name || ev.deal_name) && <span className="font-semibold">{ev.modifier_name || ev.deal_name}</span>}
|
||||
{ev.applied_by_username && <span className="text-ink-3">{t('orders.history.by', { name: ev.applied_by_username })}</span>}
|
||||
{ev.approved_by_username && <span className="text-ink-3">{t('orders.history.approvedBy', { name: ev.approved_by_username })}</span>}
|
||||
{ev.stage && <span className="text-ink-3">{t(`orders.history.stage.${ev.stage}`)}</span>}
|
||||
{ev.delta_amount != null && (
|
||||
<span className={cx('font-semibold tabular-nums', ev.delta_amount < 0 ? 'text-success-ink' : 'text-danger-ink')}>
|
||||
{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}
|
||||
@@ -74,3 +76,44 @@ export function PriceEventList({ events }) {
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** The order's moves (6F.4): the whole order's path (table transfers, tables joined into it), then
|
||||
* each moved line's own path, however many moves. */
|
||||
export function MoveList({ moves, order }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatDateTime, formatNumber } = useFormat()
|
||||
const byId = new Map(order.items.map(i => [i.id, i]))
|
||||
const lines = Object.entries(moves.items ?? {}).map(([id, ms]) => [byId.get(Number(id)), ms]).filter(([i]) => i)
|
||||
if (!moves.order?.length && !lines.length) return <EmptyState compact title={t('orders.moves.none')} />
|
||||
const row = (m, itemId) => {
|
||||
const mine = itemId != null ? m.items.find(i => i.item_id === itemId) : null
|
||||
return (
|
||||
<li key={`${itemId ?? 'o'}-${m.id}`} className="px-4 py-2 flex items-start gap-3" data-testid="order-move">
|
||||
<Pill tone="info">{t(`orders.moves.kind.${m.kind}`)}</Pill>
|
||||
<span className="flex-1 min-w-0 text-label text-ink">
|
||||
<span className="font-semibold">{m.from_table || '—'} → {m.to_table || '—'}</span>
|
||||
{m.by && <span className="ml-2 text-ink-3">{t('orders.history.by', { name: m.by })}</span>}
|
||||
{mine?.quantity != null && <span className="ml-2 text-ink-3">×{formatNumber(mine.quantity, { maxDecimals: 3 })}</span>}
|
||||
{itemId == null && <span className="ml-2 text-ink-3">{t('orders.moves.lines', { count: m.items.length })}</span>}
|
||||
</span>
|
||||
<span className="text-caption text-ink-3 shrink-0">{formatDateTime(m.at, 'datetimeShort')}</span>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="divide-y divide-line" data-testid="order-moves">
|
||||
{moves.order?.length > 0 && (
|
||||
<section>
|
||||
<h3 className="px-4 pt-3 pb-1 text-label font-semibold text-ink-2">{t('orders.moves.wholeOrder', { path: pathText(moves.order) })}</h3>
|
||||
<ul className="divide-y divide-line">{moves.order.map(m => row(m))}</ul>
|
||||
</section>
|
||||
)}
|
||||
{lines.map(([item, ms]) => (
|
||||
<section key={item.id}>
|
||||
<h3 className="px-4 pt-3 pb-1 text-label font-semibold text-ink-2">{nameOf(item)} · {pathText(ms)}</h3>
|
||||
<ul className="divide-y divide-line">{ms.map(m => row(m, item.id))}</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,16 +8,16 @@ import toast from 'react-hot-toast'
|
||||
import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react'
|
||||
import { useCan, useModule } from '@xenia/access'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { Pill } from '../overview/parts'
|
||||
import { lineAmount, lineDetails, nameOf, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic'
|
||||
import { lineAmount, lineDetails, nameOf, pathText, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic'
|
||||
|
||||
const STATUS_TONE = { paid: 'success', cancelled: 'danger', tabbed: 'info', closed: 'warning' }
|
||||
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink' }
|
||||
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink', manual_price: 'text-warning-ink' }
|
||||
|
||||
export default function OrderLines({ order, open, priceEvents, onPay, onChanged }) {
|
||||
export default function OrderLines({ order, open, priceEvents, moves = {}, onPay, onChanged }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney, formatTime } = useFormat()
|
||||
const canDiscount = useCan('pricing.discounts.apply')
|
||||
@@ -70,6 +70,11 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
|
||||
{d.choices.length > 0 && <div className="text-caption text-ink-2">{d.choices.join(', ')}</div>}
|
||||
{d.removed.length > 0 && <div className="text-caption text-ink-2">{t('orders.lines.without', { list: d.removed.join(', ') })}</div>}
|
||||
{d.note && <div className="text-caption text-warning-ink">{d.note}</div>}
|
||||
{moves[item.id]?.length > 0 && (
|
||||
<div className="text-caption text-info-ink" data-testid="line-moved">
|
||||
↪ {t('orders.moves.linePath', { path: pathText(moves[item.id]) })}
|
||||
</div>
|
||||
)}
|
||||
<div className="text-caption text-ink-3">
|
||||
{t('orders.lines.added', { time: formatTime(item.added_at), name: item.added_by_name ?? '' })}
|
||||
{item.paid_by_name && ` · ${t('orders.lines.paidBy', { name: item.paid_by_name })}`}
|
||||
@@ -79,6 +84,12 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
|
||||
<span aria-hidden="true">↳</span>
|
||||
<span>{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}</span>
|
||||
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
|
||||
{ev.event_type === 'manual_price' && (
|
||||
<span className="text-ink-3" data-testid="line-price-change">
|
||||
{formatMoney(ev.price_before)} → {formatMoney(ev.price_after)}
|
||||
{ev.applied_by_username && ` · ${ev.applied_by_username}`}{ev.waiter_note && ` · ${ev.waiter_note}`}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -123,7 +134,7 @@ function DiscountDialog({ orderId, itemIds, amount, onClose, onDone }) {
|
||||
const { formatMoney } = useFormat()
|
||||
const [pct, setPct] = useState('10')
|
||||
const [note, setNote] = useState('')
|
||||
const value = Number(String(pct).replace(',', '.'))
|
||||
const value = parseNumber(String(pct)) ?? NaN
|
||||
const ok = value > 0 && value <= 100
|
||||
const apply = useMutation({
|
||||
mutationFn: () => client.post(`/api/orders/${orderId}/items/discount`, { item_ids: itemIds, discount_percent: value, note: note.trim() || null }),
|
||||
|
||||
@@ -21,12 +21,14 @@ import OrderLines from './OrderLines'
|
||||
import OrderPeople from './OrderPeople'
|
||||
import PayDialog from './PayDialog'
|
||||
import PrintProblemsCard from './PrintProblemsCard'
|
||||
import { AuditList, PriceEventList } from './OrderHistory'
|
||||
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
|
||||
import { AuditList, MoveList, PriceEventList } from './OrderHistory'
|
||||
import { closeStep, isSplitPart, totals, unpaidIds, venueRules } from './orderLogic'
|
||||
import { SplitBillsCard } from './SplitAmount'
|
||||
import { useCan } from '@xenia/access'
|
||||
|
||||
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
|
||||
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
|
||||
const TABS = ['order', 'prices', 'history']
|
||||
const TABS = ['order', 'prices', 'moves', 'history']
|
||||
|
||||
export default function OrderPage() {
|
||||
const { orderId } = useParams()
|
||||
@@ -78,6 +80,7 @@ function OrderView({ orderId }) {
|
||||
const venue = useVenue()
|
||||
const [tab, setTab] = useState('order')
|
||||
const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after }
|
||||
const maySplit = useCan('ordering.payments.split_amount') // 6F.6
|
||||
const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel'
|
||||
const [printerId, setPrinterId] = useState('')
|
||||
|
||||
@@ -90,9 +93,14 @@ function OrderView({ orderId }) {
|
||||
queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), events: ['order_updated'],
|
||||
})
|
||||
|
||||
const { data: moves = { order: [], items: {} } } = useLiveQuery({ // 6F.4
|
||||
queryKey: ['order-moves', orderId], queryFn: () => client.get(`/api/orders/${orderId}/moves`).then(r => r.data), events: ['order_updated'],
|
||||
})
|
||||
|
||||
const refresh = () => {
|
||||
qc.invalidateQueries({ queryKey: ['order', orderId] })
|
||||
qc.invalidateQueries({ queryKey: ['price-events', orderId] })
|
||||
qc.invalidateQueries({ queryKey: ['order-moves', orderId] })
|
||||
qc.invalidateQueries({ queryKey: ['orders-active'] })
|
||||
}
|
||||
const onError = err => toast.error(errorMessage(err, t))
|
||||
@@ -151,11 +159,12 @@ function OrderView({ orderId }) {
|
||||
</div>
|
||||
|
||||
<PrintProblemsCard orderId={order.id} />
|
||||
<SplitBillsCard order={order} canUndo={maySplit} onChanged={refresh} />
|
||||
|
||||
{tab === 'order' && (
|
||||
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
|
||||
<div className="grid gap-4 min-w-0">
|
||||
<OrderLines order={order} open={editable} priceEvents={priceEvents} onChanged={refresh}
|
||||
<OrderLines order={order} open={editable} priceEvents={priceEvents} moves={moves.items} onChanged={refresh}
|
||||
onPay={(ids, amount, after) => setPaying({ ids, amount, after })} />
|
||||
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
|
||||
</div>
|
||||
@@ -163,9 +172,13 @@ function OrderView({ orderId }) {
|
||||
</div>
|
||||
)}
|
||||
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
|
||||
{tab === 'moves' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><MoveList moves={moves} order={order} /></section>}
|
||||
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
|
||||
|
||||
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
|
||||
split={venue.split.on && maySplit && !paying.thenClose && !order.items.some(i => paying.ids.includes(i.id) && isSplitPart(i))
|
||||
? { choices: venue.split, customerCount: order.customer_count } : null}
|
||||
onSplit={() => { toast.success(t('orders.split.done')); paying.after?.(); setPaying(null); refresh() }}
|
||||
onClose={() => setPaying(null)}
|
||||
onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
|
||||
|
||||
|
||||
@@ -3,17 +3,20 @@
|
||||
// "instant-pay close": the rest is paid and the order closed in one go, for venues that don't
|
||||
// close with unpaid items (orders.close_with_unpaid, 4.8).
|
||||
import { useState } from 'react'
|
||||
import { Banknote, CreditCard } from 'lucide-react'
|
||||
import { Banknote, CreditCard, Divide } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { SplitAmountForm } from './SplitAmount'
|
||||
|
||||
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, onClose, onDone }) {
|
||||
/** `split` ({ choices, customerCount }, 6F.6): offers "Split the amount" instead of paying now. */
|
||||
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, split = null, onSplit, onClose, onDone }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney } = useFormat()
|
||||
const [busy, setBusy] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
const [splitting, setSplitting] = useState(false)
|
||||
|
||||
async function pay(method) {
|
||||
setBusy(method)
|
||||
@@ -44,6 +47,13 @@ export default function PayDialog({ orderId, itemIds, amount, card = true, thenC
|
||||
</Button>
|
||||
</div>
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
|
||||
{split && !splitting && (
|
||||
<Button variant="ghost" icon={<Divide size={18} />} disabled={!!busy} onClick={() => setSplitting(true)} data-testid="pay-split">{t('orders.split.button')}</Button>
|
||||
)}
|
||||
{split && splitting && (
|
||||
<SplitAmountForm orderId={orderId} itemIds={itemIds} amount={amount} choices={split.choices} customerCount={split.customerCount}
|
||||
onCancel={() => setSplitting(false)} onDone={onSplit} />
|
||||
)}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// Splitting a bill by amount in the manager (plan 6F.6), as the phones and the counter do: the chosen
|
||||
// lines are settled into a split bill and cut into equal parts (pre-filled from the customers) or, for
|
||||
// two parts, any amounts; each part is then paid like any line. Undo while no part is paid.
|
||||
import { useState } from 'react'
|
||||
import { Minus, Plus, Undo2 } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { defaultParts, splitAmounts } from '@xenia/ordering/split'
|
||||
import { Button, IconButton, Input } from '@xenia/ui'
|
||||
import toast from 'react-hot-toast'
|
||||
import client from '../../api/client'
|
||||
|
||||
/** The part of the pay dialog that splits instead of paying (choices from splitChoices()). */
|
||||
export function SplitAmountForm({ orderId, itemIds, amount, choices, customerCount, onDone, onCancel }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney } = useFormat()
|
||||
const [parts, setParts] = useState(() => defaultParts(customerCount, choices.maxParts))
|
||||
const [mode, setMode] = useState('equal')
|
||||
const [first, setFirst] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState(null)
|
||||
const uneven = mode === 'custom' && parts === 2
|
||||
const typed = first.trim() ? parseNumber(first, { decimals: 2, allowNegative: false }) : null
|
||||
const amounts = splitAmounts(amount, uneven ? 'custom' : 'equal', parts, typed)
|
||||
const step = d => { setParts(p => Math.max(2, Math.min(choices.maxParts, p + d))); setMode('equal') }
|
||||
|
||||
async function split() {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await client.post(`/api/orders/${orderId}/split-bills`, uneven
|
||||
? { item_ids: itemIds, mode: 'custom', parts: 2, first_amount: amounts[0] }
|
||||
: { item_ids: itemIds, mode: 'equal', parts })
|
||||
onDone()
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, t))
|
||||
} finally { setBusy(false) }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-3 border-t border-line pt-3" data-testid="split-form">
|
||||
{choices.maxParts > 2 && (
|
||||
<div className="flex items-center justify-center gap-4">
|
||||
<IconButton label={t('orders.split.fewer')} variant="secondary" disabled={parts <= 2} onClick={() => step(-1)}><Minus size={18} /></IconButton>
|
||||
<span className="text-display font-semibold min-w-16 text-center tabular-nums" data-testid="split-parts">{parts}</span>
|
||||
<IconButton label={t('orders.split.more')} variant="secondary" disabled={parts >= choices.maxParts} onClick={() => step(1)} data-testid="split-more"><Plus size={18} /></IconButton>
|
||||
</div>
|
||||
)}
|
||||
{choices.custom && parts === 2 && (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{['equal', 'custom'].map(m => (
|
||||
<Button key={m} size="sm" variant={mode === m ? 'primary' : 'secondary'} aria-pressed={mode === m} onClick={() => setMode(m)} data-testid={`split-${m}`}>
|
||||
{t(`orders.split.${m}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{uneven && (
|
||||
<label className="grid gap-1 text-label text-ink-2">
|
||||
{t('orders.split.first')}
|
||||
<Input inputMode="decimal" value={first} onChange={e => setFirst(e.target.value)} placeholder={formatMoney(Math.round(amount * 50) / 100)} data-testid="split-first" />
|
||||
</label>
|
||||
)}
|
||||
{amounts ? (
|
||||
<ul className="grid gap-0.5 text-body" data-testid="split-preview">
|
||||
{amounts.map((a, i) => (
|
||||
<li key={i} className="flex justify-between"><span>{t('orders.split.part', { n: i + 1, of: amounts.length })}</span><span className="tabular-nums font-medium">{formatMoney(a)}</span></li>
|
||||
))}
|
||||
</ul>
|
||||
) : <p className="text-label text-danger-ink">{t('orders.split.invalid')}</p>}
|
||||
<p className="text-caption text-ink-2">{t('orders.split.hint')}</p>
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="secondary" onClick={onCancel} disabled={busy}>{t('orders.back')}</Button>
|
||||
<Button loading={busy} disabled={!amounts} onClick={split} data-testid="split-confirm">{t('orders.split.confirm', { count: amounts?.length ?? parts })}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The order's split bills: parts, paid so far, and Undo while nothing is paid. */
|
||||
export function SplitBillsCard({ order, canUndo, onChanged }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney } = useFormat()
|
||||
const [busy, setBusy] = useState(null)
|
||||
const bills = order.split_bills ?? []
|
||||
if (!bills.length) return null
|
||||
async function undo(bill) {
|
||||
setBusy(bill.id)
|
||||
try {
|
||||
await client.post(`/api/orders/${order.id}/split-bills/${bill.id}/undo`)
|
||||
toast.success(t('orders.split.undone'))
|
||||
onChanged()
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t))
|
||||
} finally { setBusy(null) }
|
||||
}
|
||||
return (
|
||||
<section className="rounded-card border border-line bg-surface shadow-raised p-3 grid gap-2" data-testid="split-bills">
|
||||
{bills.map(b => (
|
||||
<div key={b.id} className="flex flex-wrap items-center gap-3" data-testid="split-bill">
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block text-body font-medium text-ink">{t('orders.split.bill', { count: b.parts, total: formatMoney(b.total) })}</span>
|
||||
<span className="block text-label text-ink-2">{t('orders.split.paid', { paid: formatMoney(b.paid), due: formatMoney(Math.max(0, b.total - b.paid)) })}</span>
|
||||
</span>
|
||||
{canUndo && b.can_undo && (
|
||||
<Button size="sm" variant="secondary" icon={<Undo2 size={16} />} loading={busy === b.id} onClick={() => undo(b)} data-testid="split-undo">{t('orders.split.undo')}</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
// items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise
|
||||
// the rest is paid first.
|
||||
|
||||
import { splitChoices, splitLevel, splitMax } from '@xenia/ordering/split'
|
||||
|
||||
export const OPEN_STATUSES = ['open', 'partially_paid', 'paid']
|
||||
export const isOpen = order => !!order && OPEN_STATUSES.includes(order.status)
|
||||
|
||||
@@ -59,9 +61,13 @@ export function closeStep(order, closeWithUnpaid) {
|
||||
/** The venue's settings rows (GET /api/settings/) → the two that matter here. */
|
||||
export function venueRules(settings) {
|
||||
const v = key => settings?.[key]?.value
|
||||
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false' }
|
||||
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false',
|
||||
split: splitChoices(splitLevel(settings), splitMax(settings)) } // 6F.6
|
||||
}
|
||||
|
||||
/** A split bill's part line (6F.6): paid on its own, never split again. */
|
||||
export const isSplitPart = item => item?.split_bill_id != null && item.status !== 'split'
|
||||
|
||||
/** The cart's lines as the server takes them, plus the order's note (POST /api/orders/{id}/items). */
|
||||
export function sendBody(cart, note) {
|
||||
return { lines: cart.map(c => c.line), order_note: note?.trim() || null }
|
||||
@@ -104,3 +110,11 @@ export function flagsByTable(defs = [], assignments = []) {
|
||||
|
||||
/** Where a table's card goes: its order, or a new order at that table. */
|
||||
export const cardTarget = card => (card.order ? `/orders/${card.order.id}` : `/orders/new?table=${card.table.id}`)
|
||||
|
||||
/** "T2 → T5 → T7": the tables a moved order or line went through (6F.4; '—' for no table). */
|
||||
export function pathText(moves) {
|
||||
if (!moves?.length) return ''
|
||||
const stops = [moves[0].from_table || '—']
|
||||
for (const m of moves) stops.push(m.to_table || '—')
|
||||
return stops.join(' → ')
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
|
||||
{evs.map((ev, i) => (
|
||||
<div key={i} className={cx('flex items-center gap-2 pl-4 text-caption', EVENT_TONE[ev.event_type])}>
|
||||
<span aria-hidden="true">↳</span>
|
||||
<span className="flex-1">{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}</span>
|
||||
<span className="flex-1">{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}{ev.event_type === 'manual_price' && ev.waiter_note ? ` · ${ev.waiter_note}` : ''}</span>
|
||||
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
|
||||
{ev.price_after != null && <span className="text-ink-3">→ {formatMoney(ev.price_after)}</span>}
|
||||
</div>
|
||||
|
||||
@@ -277,10 +277,24 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, initialApp, onC
|
||||
)
|
||||
}
|
||||
|
||||
/** Usernames on this screen (6F.7): the venue's choice, or its own yes / no. */
|
||||
function usernameOptions(device, t) {
|
||||
// the venue's value = what applies when the device has no choice of its own
|
||||
const venue = device.require_username == null ? device.effective_require_username : null
|
||||
const yes = t('devices.form.usernamesYes')
|
||||
const no = t('devices.form.usernamesNo')
|
||||
return [
|
||||
{ value: '', label: venue == null ? t('devices.signIn.defaultPlain') : t('devices.form.usernamesDefault', { value: venue ? yes : no }) },
|
||||
{ value: 'true', label: yes },
|
||||
{ value: 'false', label: no },
|
||||
]
|
||||
}
|
||||
|
||||
function EditDialog({ device, apps, devices, onClose, onSave }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [name, setName] = useState(device.name)
|
||||
const [mode, setMode] = useState(device.login_mode || '')
|
||||
const [usernames, setUsernames] = useState(device.require_username == null ? '' : String(device.require_username))
|
||||
const [link, setLink] = useState(device.linked_device_id ? String(device.linked_device_id) : '')
|
||||
const app = apps.find(a => a.key === device.app_key)
|
||||
const fields = app?.device_app?.config || []
|
||||
@@ -293,6 +307,7 @@ function EditDialog({ device, apps, devices, onClose, onSave }) {
|
||||
e.preventDefault()
|
||||
if (!name.trim() || busy) return
|
||||
run({ name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null,
|
||||
...(modes ? { require_username: usernames === '' ? null : usernames === 'true' } : {}),
|
||||
...(fields.length ? { config } : {}) })
|
||||
}
|
||||
|
||||
@@ -308,6 +323,12 @@ function EditDialog({ device, apps, devices, onClose, onSave }) {
|
||||
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
|
||||
</Field>
|
||||
)}
|
||||
{modes && (
|
||||
<Field label={t('devices.form.usernames')} info={<InfoTip>{t('devices.form.usernamesTip')}</InfoTip>}>
|
||||
<Select value={usernames} onChange={e => setUsernames(e.target.value)} data-testid="device-usernames"
|
||||
options={usernameOptions(device, t)} />
|
||||
</Field>
|
||||
)}
|
||||
{targets.length > 0 && (
|
||||
<Field label={t('devices.form.link')} hint={t('devices.form.linkHint')}>
|
||||
<Select value={link} onChange={e => setLink(e.target.value)}
|
||||
|
||||
@@ -9,7 +9,7 @@ import toast from 'react-hot-toast'
|
||||
import { Plus } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||
import { Button, DecimalInput, Dialog, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import * as api from './pricingApi'
|
||||
import { ColourPicker, ConditionList, Missing, PickSeveral, RuleCard, Segmented, TabHead, TagPicker, TargetList } from './PricingParts'
|
||||
@@ -145,8 +145,8 @@ function DealDialog({ deal, catalog, rules, busy, onClose, onSave }) {
|
||||
)}
|
||||
{['set_price', 'add_amount', 'add_percent'].includes(a) && (
|
||||
<Field label={t(`pricing.actions.valueLabel.${a === 'set_price' ? 'set' : a}`)} hint={a !== 'set_price' ? t('pricing.actions.minusHint') : undefined}>
|
||||
<Input type="number" step={a === 'add_percent' ? 1 : 0.1} className="w-36" value={Number.isFinite(f.action_value) ? f.action_value : ''}
|
||||
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} />
|
||||
<DecimalInput allowNegative decimals={2} suffix={a === 'add_percent' ? '%' : '€'} className="w-36" value={f.action_value}
|
||||
onChange={v => set('action_value', v ?? NaN)} />
|
||||
</Field>
|
||||
)}
|
||||
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
|
||||
|
||||
@@ -12,7 +12,7 @@ import toast from 'react-hot-toast'
|
||||
import { Layers, Plus } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Field, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||
import { Button, DecimalInput, Dialog, EmptyState, Field, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import * as api from './pricingApi'
|
||||
import { ColourPicker, ConditionList, Missing, RuleCard, Segmented, TabHead, TargetList } from './PricingParts'
|
||||
@@ -147,8 +147,8 @@ function RuleDialog({ rule, catalog, busy, onClose, onSave }) {
|
||||
options={MODIFIER_ACTIONS.map(v => ({ value: v, label: t(`pricing.actions.${v}`) }))} />
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
<Field label={t(`pricing.actions.valueLabel.${f.action_type}`)} hint={f.action_type !== 'set' ? t('pricing.actions.minusHint') : undefined}>
|
||||
<Input type="number" step={f.action_type === 'add_percent' ? 1 : 0.1} value={Number.isFinite(f.action_value) ? f.action_value : ''}
|
||||
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} data-testid="pricing-rule-value" />
|
||||
<DecimalInput allowNegative decimals={2} suffix={f.action_type === 'add_percent' ? '%' : '€'} value={f.action_value}
|
||||
onChange={v => set('action_value', v ?? NaN)} data-testid="pricing-rule-value" />
|
||||
</Field>
|
||||
{f.action_type === 'add_percent' && (
|
||||
<Field label={t('pricing.rules.rounding')}>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState } from 'react'
|
||||
import { ArrowDown, ArrowUp, Check, Pencil, Plus, Power, Trash2, X } from 'lucide-react'
|
||||
import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access'
|
||||
import { latin, useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dropdown, IconButton, Input, Select, cx } from '@xenia/ui'
|
||||
import { Button, Dropdown, IconButton, Input, MoneyInput, Select, cx } from '@xenia/ui'
|
||||
import { COLOURS } from './useCatalog'
|
||||
import { OLD_PLACEHOLDERS, WEEKDAYS, blankCondition, conditionComplete, toggleIn } from './pricingLogic'
|
||||
|
||||
@@ -202,7 +202,13 @@ function ConditionFields({ cond, onChange, catalog }) {
|
||||
case 'specific_date': return <DateList value={p.dates ?? []} onChange={v => set('dates', v)} />
|
||||
case 'day_of_week': return <DayPicker value={p.days ?? []} onChange={v => set('days', v)} />
|
||||
case 'min_item_quantity': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 1, 1)}{t('pricing.condition.ofTheDish')}</label>
|
||||
case 'min_order_value': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 0, 0.5)}{t('pricing.condition.orderTotal')}</label>
|
||||
case 'min_order_value': return (
|
||||
<label className="flex items-center gap-2 text-label text-ink-2">
|
||||
<MoneyInput size="sm" className="w-32" value={p.min ?? null} aria-label={t('pricing.condition.fields.min_order_value')}
|
||||
onChange={v => set('min', Number.isFinite(v) ? v : null)} />
|
||||
{t('pricing.condition.orderTotal')}
|
||||
</label>
|
||||
)
|
||||
case 'min_category_qty': return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{num('min', 1, 1)}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// (modifier) and a deal, what they send to the server, what's missing before they can be saved,
|
||||
// and their one-line summaries. Tested in tests/pricing-logic.test.mjs.
|
||||
// The server's engine: local_backend/services/pricing.py (conditions AND-ed, targets OR-ed).
|
||||
import { parseNumber } from '@xenia/i18n/number'
|
||||
|
||||
export const WEEKDAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0, as the server counts
|
||||
|
||||
@@ -226,9 +227,9 @@ export const COUNT_LIMITS = new Set(['max_items_per_shift', 'max_items_per_workd
|
||||
|
||||
/** A limit typed in a box: '' = no limit; a comma works as the decimal point. null when it isn't a number ≥ 0. */
|
||||
export function parseLimit(text, count = false) {
|
||||
const s = String(text ?? '').trim().replace(',', '.')
|
||||
const s = String(text ?? '').trim()
|
||||
if (s === '') return { ok: true, value: null }
|
||||
const v = Number(s)
|
||||
const v = parseNumber(s) ?? NaN
|
||||
if (!Number.isFinite(v) || v < 0 || (count && !Number.isInteger(v))) return { ok: false, value: null }
|
||||
return { ok: true, value: v }
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { parseNumber, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Page, Pane, Spinner } from '@xenia/ui'
|
||||
import { Package } from 'lucide-react'
|
||||
import client from '../../api/client'
|
||||
@@ -23,7 +23,7 @@ import { emptyProduct } from './editor/formLogic'
|
||||
import { NO_FILTERS, SCOPES, applyFilters, bulkCategories, groupProducts, isArchived, isCategoryScope, listedIn, scopeProducts, subsOf } from './productsLogic'
|
||||
|
||||
const EVENTS = ['products_changed']
|
||||
const number = v => (v === '' ? null : Number(String(v).replace(',', '.')))
|
||||
const number = v => (v === '' ? null : (parseNumber(String(v)) ?? NaN))
|
||||
|
||||
export default function ProductsPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
|
||||
@@ -43,6 +43,7 @@ export function InfoTab({ form, set, setForm, categories, prepZones }) {
|
||||
<AllergensField value={form.allergens} onChange={v => set('allergens', v)} />
|
||||
<Switch checked={form.is_available} onChange={v => set('is_available', v)} label={t('products.editor.available')} info={<InfoTip>{t('products.editor.availableTip')}</InfoTip>} description={t('products.editor.availableHint')} />
|
||||
<Switch checked={form.quick_add_enabled} onChange={v => set('quick_add_enabled', v)} label={t('products.editor.quickAdd')} info={<InfoTip>{t('products.editor.quickAddTip')}</InfoTip>} description={t('products.editor.quickAddHint')} />
|
||||
<Switch checked={form.one_more_enabled} onChange={v => set('one_more_enabled', v)} label={t('products.editor.oneMore')} info={<InfoTip>{t('products.editor.oneMoreTip')}</InfoTip>} description={t('products.editor.oneMoreHint')} data-testid="product-one-more" />
|
||||
<MediaField value={form.image} onChange={image => set('image', image)} nameAfter={shownText(form.names, venue, form.name)} label={t('media.photo')} testid="product-photo" />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// with a price: printed in its own SERVICE section and counted in the takings.
|
||||
import { useState } from 'react'
|
||||
import { DEFAULT_LANGUAGE } from '@xenia/access'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { parseNumber, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Field } from '@xenia/ui'
|
||||
import { PrepZonesField } from './InfoTabs'
|
||||
import { LanguagePicker, TrInput } from './LanguageFields'
|
||||
@@ -19,7 +19,7 @@ export default function ServiceItemDialog({ product, prepZones, saving, onSave,
|
||||
const [lang, setLang] = useState(DEFAULT_LANGUAGE)
|
||||
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
|
||||
const isNew = !product.id
|
||||
const paid = Number(String(form.base_price ?? '').replace(',', '.')) > 0
|
||||
const paid = (parseNumber(String(form.base_price ?? '')) ?? 0) > 0
|
||||
return (
|
||||
<EditLang.Provider value={editLangOf(lang, venue)}>
|
||||
<Dialog open size="md" onClose={onClose}
|
||||
|
||||
@@ -7,12 +7,13 @@
|
||||
// language picker picks which language the fields edit; "Default" is the venue's language.
|
||||
import { SALES_POINTS } from '@xenia/access/salesPoints'
|
||||
import { MENU_LANGUAGES, shownText } from '@xenia/access/menuLanguages'
|
||||
import { parseNumber } from '@xenia/i18n/number'
|
||||
|
||||
export const UNITS = ['piece', 'portion', 'kg', 'liter', 'gram', 'ml']
|
||||
export const WEIGHED = new Set(['kg', 'liter', 'gram', 'ml'])
|
||||
export const LISTS = { quick: 'quick_options', ingredient: 'ingredients', option: 'options', pref: 'preference_sets' }
|
||||
|
||||
const num = v => (v === '' || v == null ? 0 : Number(String(v).replace(',', '.')) || 0)
|
||||
const num = v => (v === '' || v == null ? 0 : parseNumber(String(v)) || 0)
|
||||
const sub = s => ({ name: s.name ?? '', tr: { ...(s.translations ?? {}) }, extra_cost: s.extra_cost ?? 0, is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
|
||||
const field = (tr, k) => Object.fromEntries(Object.entries(tr ?? {}).filter(([, v]) => v?.[k]).map(([l, v]) => [l, v[k]]))
|
||||
|
||||
@@ -80,6 +81,7 @@ export function buildForm(p) {
|
||||
cost_simple: p.cost_simple ?? '',
|
||||
cost_breakdown: (p.cost_breakdown ?? []).map(e => ({ label: e.label, amount: e.amount })),
|
||||
quick_add_enabled: p.quick_add_enabled ?? true,
|
||||
one_more_enabled: !!p.one_more_enabled, // 6F.5
|
||||
tags: [...(p.tags ?? [])],
|
||||
is_service_item: !!p.is_service_item,
|
||||
fiscal_name: p.fiscal_name ?? '',
|
||||
@@ -142,6 +144,7 @@ export function buildBody(f, venue = 'el') {
|
||||
cost_breakdown: f.cost_mode === 'detailed' && f.cost_breakdown.length
|
||||
? f.cost_breakdown.map(e => ({ label: e.label, amount: num(e.amount) })) : null,
|
||||
quick_add_enabled: f.quick_add_enabled,
|
||||
one_more_enabled: !!f.one_more_enabled,
|
||||
tags: f.tags,
|
||||
is_service_item: f.is_service_item,
|
||||
fiscal_name: f.fiscal_name.trim() || null,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// language picked at the top of the editor.
|
||||
import { useState } from 'react'
|
||||
import { ChevronDown, ChevronUp, Heart, Minus, Pencil, Plus, Trash2 } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { parseNumber, useTranslation } from '@xenia/i18n'
|
||||
import { Button, FilterChip, IconButton, cx } from '@xenia/ui'
|
||||
import { TrInput } from './LanguageFields'
|
||||
import { useEditLang } from './editLang'
|
||||
@@ -12,7 +12,7 @@ import { labelIn } from './formLogic'
|
||||
/** A price with − / + of 0.10 (negative allowed for choices that lower the price). */
|
||||
export function PriceInput({ value, onChange, allowNegative = false, size = 'md', className, label, ...rest }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const n = Number(String(value ?? '').replace(',', '.')) || 0
|
||||
const n = parseNumber(String(value ?? '')) || 0
|
||||
const step = d => {
|
||||
const next = Math.round((n + d) * 100) / 100
|
||||
onChange(allowNegative ? next : Math.max(0, next))
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// cancelled line (what, how much, who sent it, who cancelled it, why) and every discount given
|
||||
// (on what, how much, by whom, why), with totals per person; exports for Excel.
|
||||
import { useState } from 'react'
|
||||
import { useCan } from '@xenia/access'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import client from '../../../api/client'
|
||||
import { useLiveQuery } from '../../../live/useLiveQuery'
|
||||
@@ -12,9 +13,11 @@ import { defaultPeriod, periodParams, periodSlug } from '../kit/reportLogic'
|
||||
|
||||
export default function MiscReport() {
|
||||
const { t } = useTranslation('manager')
|
||||
const seesChanges = useCan('ordering.prices.view_changes')
|
||||
const tabs = [
|
||||
{ id: 'cancellations', label: t('reports.misc.cancellations'), Component: CancellationsTab },
|
||||
{ id: 'discounts', label: t('reports.misc.discounts'), Component: DiscountsTab },
|
||||
...(seesChanges ? [{ id: 'price-changes', label: t('reports.misc.priceChanges'), Component: PriceChangesTab }] : []),
|
||||
]
|
||||
return <ReportPage title={t('reports.misc.title')} tabs={tabs} testId="report-misc" />
|
||||
}
|
||||
@@ -102,3 +105,46 @@ function DiscountsTab() {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
/** Prices changed by hand (6F.3): each change, before → after, its value for the line's quantity,
|
||||
* where (cart / sent / served), who, the approving manager, why; totals per person. */
|
||||
function PriceChangesTab() {
|
||||
const { t } = useTranslation('manager')
|
||||
const fmt = useFormat()
|
||||
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
|
||||
const params = periodParams(period)
|
||||
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-price-changes', params], queryFn: () => client.get('/api/reports/price-changes', { params }).then(r => r.data) })
|
||||
const rows = data?.changes ?? []
|
||||
const columns = [
|
||||
{ key: 'at', label: t('reports.misc.when'), render: c => fmt.formatDateTime(c.at, 'datetimeShort') },
|
||||
{ key: 'product_name', label: t('reports.prod.product'), render: c => <span className="font-semibold text-ink">{c.product_name}</span> },
|
||||
{ key: 'table_name', label: t('reports.place'), render: c => c.table_name || t('reports.noTable') },
|
||||
{ key: 'before', label: t('reports.misc.priceWas'), align: 'right', render: c => fmt.formatMoney(c.before) },
|
||||
{ key: 'after', label: t('reports.misc.priceNow'), align: 'right', render: c => fmt.formatMoney(c.after) },
|
||||
{ key: 'value', label: t('reports.misc.value'), align: 'right', render: c => <span className={c.value < 0 ? 'font-semibold text-danger-ink' : 'font-semibold text-success-ink'}>{fmt.formatMoney(c.value, { signDisplay: 'exceptZero' })}</span> },
|
||||
{ key: 'stage', label: t('reports.misc.stage'), render: c => (c.stage ? t(`orders.history.stage.${c.stage}`) : '') },
|
||||
{ key: 'by', label: t('reports.misc.changedBy'), render: c => c.by || '' },
|
||||
{ key: 'approved_by', label: t('reports.misc.approvedBy'), render: c => c.approved_by || '' },
|
||||
{ key: 'reason', label: t('reports.misc.reason'), render: c => c.reason || '' },
|
||||
]
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<PeriodPicker value={period} onChange={setPeriod} right={<ExportButton endpoint="/api/reports/price-changes/export" params={params} filename={`price-changes-${periodSlug(period)}.csv`} />} />
|
||||
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
|
||||
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
|
||||
<Stat label={t('reports.misc.changes')} value={data.count} testId="price-changes-count" />
|
||||
<Stat label={t('reports.misc.changesValue')} tone={data.total_value < 0 ? 'danger' : 'success'} value={fmt.formatMoney(data.total_value, { signDisplay: 'exceptZero' })} tip={t('reports.misc.changesValueTip')} />
|
||||
</div>
|
||||
{data.by_person.length > 1 && (
|
||||
<Panel title={t('reports.misc.byWhom')}>
|
||||
<BarList format={v => fmt.formatMoney(v, { signDisplay: 'exceptZero' })} rows={data.by_person.map(p => ({ key: p.user_id ?? '—', label: p.name ?? '—', value: p.total_value, sub: t('reports.misc.changesCount', { count: p.count }) }))} />
|
||||
</Panel>
|
||||
)}
|
||||
<Panel padded={false} title={t('reports.misc.priceChanges')}>
|
||||
<Table columns={columns} rows={rows} rowTestId="report-price-change" initialSort={{ key: 'at', dir: 'desc' }} limit={500} />
|
||||
</Panel>
|
||||
</>)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// Reports → Moves (plan 6F.4, owner 2026-11-23): every move between tables and orders in a period:
|
||||
// a whole table moved, lines moved to another table, tables joined; from / to, who, the lines
|
||||
// with their quantities and value; counts per kind and per person; export for Excel.
|
||||
// GET /api/reports/moves (+ /export).
|
||||
import { useState } from 'react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Dropdown, Toolbar } from '@xenia/ui'
|
||||
import client from '../../../api/client'
|
||||
import { useLiveQuery } from '../../../live/useLiveQuery'
|
||||
import { BarList } from '../kit/charts'
|
||||
import { ExportButton, Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts'
|
||||
import { PeriodPicker } from '../kit/Period'
|
||||
import { defaultPeriod, periodParams, periodSlug } from '../kit/reportLogic'
|
||||
|
||||
const KINDS = ['table_transfer', 'items_moved', 'orders_merged']
|
||||
|
||||
export default function MovesReport() {
|
||||
const { t } = useTranslation('manager')
|
||||
return <ReportPage title={t('reports.moves.title')} testId="report-moves"><MovesBody /></ReportPage>
|
||||
}
|
||||
|
||||
function MovesBody() {
|
||||
const { t } = useTranslation('manager')
|
||||
const fmt = useFormat()
|
||||
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
|
||||
const [kinds, setKinds] = useState([])
|
||||
const params = { ...periodParams(period), ...(kinds.length === 1 ? { kind: kinds[0] } : {}) }
|
||||
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-moves', params], queryFn: () => client.get('/api/reports/moves', { params }).then(r => r.data) })
|
||||
const rows = (data?.moves ?? []).filter(m => !kinds.length || kinds.includes(m.kind))
|
||||
const columns = [
|
||||
{ key: 'at', label: t('reports.misc.when'), render: m => fmt.formatDateTime(m.at, 'datetimeShort') },
|
||||
{ key: 'kind', label: t('reports.moves.kind'), render: m => t(`reports.moves.kinds.${m.kind}`) },
|
||||
{ key: 'from_table', label: t('reports.moves.from'), render: m => <span className="font-semibold text-ink">{m.from_table || t('reports.noTable')}</span> },
|
||||
{ key: 'to_table', label: t('reports.moves.to'), render: m => <span className="font-semibold text-ink">{m.to_table || t('reports.noTable')}</span> },
|
||||
{ key: 'items', label: t('reports.moves.lines'), sortable: false,
|
||||
render: m => <span className="text-label text-ink-2">{m.items.map(i => `${i.name ?? `#${i.item_id}`}${i.quantity != null ? ` ×${fmt.formatNumber(i.quantity, { maxDecimals: 3 })}` : ''}`).join(', ')}</span> },
|
||||
{ key: 'value', label: t('reports.misc.value'), align: 'right', render: m => fmt.formatMoney(m.value) },
|
||||
{ key: 'by', label: t('reports.moves.by'), render: m => m.by || '' },
|
||||
{ key: 'orders', label: '#', sortable: false, render: m => <span className="tabular-nums text-ink-3">#{m.from_order_id}{m.to_order_id !== m.from_order_id ? ` → #${m.to_order_id}` : ''}</span> },
|
||||
]
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<PeriodPicker value={period} onChange={setPeriod} right={<ExportButton endpoint="/api/reports/moves/export" params={params} filename={`moves-${periodSlug(period)}.csv`} />} />
|
||||
<Toolbar>
|
||||
<Dropdown multiple value={kinds} onChange={setKinds} allLabel={t('reports.moves.allKinds')} aria-label={t('reports.moves.kind')}
|
||||
options={KINDS.map(k => ({ value: k, label: t(`reports.moves.kinds.${k}`) }))} data-testid="moves-kind" />
|
||||
</Toolbar>
|
||||
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
|
||||
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
|
||||
<Stat label={t('reports.moves.count')} value={rows.length} testId="moves-count" />
|
||||
{KINDS.map(k => <Stat key={k} label={t(`reports.moves.kinds.${k}`)} value={data.by_kind[k] ?? 0} />)}
|
||||
</div>
|
||||
{data.by_person.length > 1 && (
|
||||
<Panel title={t('reports.misc.byWhom')}>
|
||||
<BarList format={v => fmt.formatNumber(v)} rows={data.by_person.map(p => ({ key: p.user_id ?? '—', label: p.name ?? '—', value: p.count }))} />
|
||||
</Panel>
|
||||
)}
|
||||
<Panel padded={false} title={t('reports.moves.list')} tip={t('reports.moves.listTip')}>
|
||||
<Table columns={columns} rows={rows} rowTestId="report-move" initialSort={{ key: 'at', dir: 'desc' }} limit={500} />
|
||||
</Panel>
|
||||
</>)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -48,7 +48,14 @@ export default function DaysTab() {
|
||||
const columns = [
|
||||
{ key: 'opened_at', label: t('reports.store.day'), render: d => <span className="font-semibold text-ink capitalize">{dateOf(d)}</span> },
|
||||
{ key: 'times', label: t('reports.store.hours'), sort: false,
|
||||
render: d => `${fmt.formatTime(d.opened_at)} – ${d.closed_at ? fmt.formatTime(d.closed_at) : '…'} (${since(d.opened_at, d.closed_at ? Date.parse(d.closed_at) : undefined)})` },
|
||||
render: d => (<>
|
||||
{`${fmt.formatTime(d.opened_at)} – ${d.closed_at ? fmt.formatTime(d.closed_at) : '…'} (${since(d.opened_at, d.closed_at ? Date.parse(d.closed_at) : undefined)})`}
|
||||
{(d.opened_auto || d.closed_auto) && (
|
||||
<span className="block text-caption text-ink-3" data-testid="day-auto">
|
||||
{t(d.opened_auto && d.closed_auto ? 'reports.store.autoBoth' : d.opened_auto ? 'reports.store.autoOpened' : 'reports.store.autoClosed')}
|
||||
</span>
|
||||
)}
|
||||
</>) },
|
||||
{ key: 'order_count', label: t('reports.orders'), align: 'right' },
|
||||
{ key: 'revenue', label: t('reports.revenue'), align: 'right', render: d => <span className="font-semibold">{fmt.formatMoney(d.revenue)}</span> },
|
||||
{ key: 'fees', label: t('reports.fees'), align: 'right', render: d => (d.fees ? fmt.formatMoney(d.fees) : '') },
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// The staff page as plain data (plan step 6.11), tested in tests/staff.test.mjs.
|
||||
import { parseNumber } from '@xenia/i18n/number'
|
||||
|
||||
/** The roles in the order the page lists them (backend roles.py); names are i18n `roles.*`. */
|
||||
export const ROLES = ['owner', 'store_manager', 'staff_manager', 'chef', 'assistant_chef', 'barista', 'barman', 'waiter', 'assistant_waiter', 'custom']
|
||||
@@ -58,8 +59,9 @@ export function staffProblems(form, isNew) {
|
||||
if (!form.full_name.trim()) out.push('full_name')
|
||||
if (!form.nickname.trim()) out.push('nickname')
|
||||
if (!/^[^\s]{2,}$/.test(form.username.trim())) out.push('username')
|
||||
const rate = String(form.hourly_rate).trim().replace(',', '.')
|
||||
if (rate && !(Number(rate) >= 0)) out.push('hourly_rate')
|
||||
const rate = String(form.hourly_rate ?? '').trim()
|
||||
const rateValue = rate ? parseNumber(rate) : null
|
||||
if (rate && !(rateValue != null && rateValue >= 0)) out.push('hourly_rate')
|
||||
if (isNew && !validPin(form.pin)) out.push('pin')
|
||||
if (isNew && form.password && !validPassword(form.password)) out.push('password')
|
||||
return out
|
||||
@@ -68,11 +70,11 @@ export function staffProblems(form, isNew) {
|
||||
/** POST /api/waiters/ (new) or PUT /api/waiters/{id} (edit). */
|
||||
export function staffBody(form, isNew) {
|
||||
const text = v => (v ?? '').trim() || null
|
||||
const rate = String(form.hourly_rate).trim().replace(',', '.')
|
||||
const rate = String(form.hourly_rate ?? '').trim()
|
||||
const body = {
|
||||
full_name: form.full_name.trim(), nickname: form.nickname.trim(), username: form.username.trim(), role: form.role,
|
||||
mobile_phone: text(form.mobile_phone), email: text(form.email), note: text(form.note),
|
||||
hourly_rate: rate ? Number(rate) : null, language: form.language || '',
|
||||
hourly_rate: rate ? parseNumber(rate, { decimals: 2 }) : null, language: form.language || '',
|
||||
}
|
||||
if (isNew) {
|
||||
body.pin = form.pin
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// converts those routers.
|
||||
// anyPerm instead of perm: any one of these keys is enough (the media library)
|
||||
// label a key in the i18n `manager` namespace
|
||||
import { Activity, AppWindow, BadgeCheck, BarChart2, BookUser, Boxes, CalendarDays, ConciergeBell, CookingPot, CreditCard, FileText, Images, LayoutDashboard, LayoutGrid, LogIn, MonitorSmartphone, Package, PartyPopper, Percent, Plug, Printer, Receipt, Settings, ShieldCheck, ShoppingBag, ShoppingCart, StickyNote, TableProperties, Tag, Trash2, TrendingUp, Tv, UserCog, Users, Users2 } from 'lucide-react'
|
||||
import { Activity, AppWindow, ArrowRightLeft, BadgeCheck, BarChart2, BookUser, Boxes, CalendarDays, ConciergeBell, CookingPot, CreditCard, FileText, Images, LayoutDashboard, LayoutGrid, LogIn, MonitorSmartphone, Package, PartyPopper, Percent, Plug, Printer, Receipt, Settings, ShieldCheck, ShoppingBag, ShoppingCart, StickyNote, TableProperties, Tag, Trash2, TrendingUp, Tv, UserCog, Users, Users2 } from 'lucide-react'
|
||||
|
||||
const DASH = 'core.dashboard.access'
|
||||
// The media library: whoever manages something that shows pictures (routers/media.py MANAGE)
|
||||
@@ -90,6 +90,7 @@ export const NAV = [
|
||||
{ to: '/reports/expenses', icon: FileText, label: 'nav.reportsExpenses', module: 'reports', perm: 'reports.view' },
|
||||
{ to: '/reports/technical', icon: Printer, label: 'nav.reportsTechnical', module: 'reports', perm: 'reports.view' },
|
||||
{ to: '/reports/misc', icon: Tag, label: 'nav.reportsMisc', module: 'reports', perm: 'reports.view' },
|
||||
{ to: '/reports/moves', icon: ArrowRightLeft, label: 'nav.reportsMoves', module: 'reports', perm: 'reports.view' },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -28,8 +28,12 @@ test('close: nothing unpaid closes; unpaid lines are paid first unless the venue
|
||||
assert.equal(closeStep(order, false), 'payFirst')
|
||||
assert.equal(closeStep(order, true), 'writeOff')
|
||||
assert.equal(closeStep({ items: [item(1, 'paid', 5)] }, false), 'close')
|
||||
assert.deepEqual(venueRules({ 'orders.close_with_unpaid': { value: 'true' } }), { closeWithUnpaid: true, card: true })
|
||||
assert.deepEqual(venueRules({ 'payments.card_enabled': { value: 'false' } }), { closeWithUnpaid: false, card: false })
|
||||
const off = { on: false, maxParts: 2, custom: false }
|
||||
assert.deepEqual(venueRules({ 'orders.close_with_unpaid': { value: 'true' } }), { closeWithUnpaid: true, card: true, split: off })
|
||||
assert.deepEqual(venueRules({ 'payments.card_enabled': { value: 'false' } }), { closeWithUnpaid: false, card: false, split: off })
|
||||
// 6F.6: splitting by amount, the venue's level and the most parts
|
||||
assert.deepEqual(venueRules({ 'payments.split_amount': { value: 'multiple_equal' }, 'payments.split_max_parts': { value: '6' } }).split,
|
||||
{ on: true, maxParts: 6, custom: true })
|
||||
})
|
||||
|
||||
test('what a line has, the body sent (ids only), waiters to add', () => {
|
||||
|
||||
@@ -140,3 +140,11 @@ test('a category dropped above or below a row lands where the line showed (2026-
|
||||
assert.equal(moveIdTo([1, 2, 3], 1, 2, false), null) // already there
|
||||
assert.equal(moveIdTo([1, 2, 3], 2, 2, true), null)
|
||||
})
|
||||
|
||||
test('"One more" travels with the product, off unless set (6F.5)', () => {
|
||||
assert.equal(buildForm({ name: 'Beer', base_price: 4 }).one_more_enabled, false)
|
||||
const f = buildForm({ name: 'Beer', base_price: 4, one_more_enabled: true })
|
||||
assert.equal(f.one_more_enabled, true)
|
||||
assert.equal(buildBody(f).one_more_enabled, true)
|
||||
assert.equal(buildBody({ ...f, one_more_enabled: false }).one_more_enabled, false)
|
||||
})
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
"_comment": "Plan step 6.1 → 6.14b: what is on the v2 rules. `paths` is all of `src` (6.14b): tests/v2-guards.test.mjs refuses Greek and colour literals anywhere in it (colour data files: the guard's DATA list). `strict`: also no setState in effects (data loads with useLiveQuery / react-query); a few older files still load in an effect and are left out.",
|
||||
"paths": ["src"],
|
||||
"strict": [
|
||||
"src/App.jsx", "src/hooks", "src/live", "src/pages/Settings/SettingsPage.jsx", "src/pages/Settings/sections/DataTransfer.jsx", "src/pages/Settings/sections/DevelopmentSettings.jsx", "src/pages/Settings/sections/FiscalSettings.jsx", "src/pages/Settings/sections/OperationSettings.jsx", "src/pages/Settings/sections/QuickMessages.jsx", "src/pages/Settings/sections/SecuritySettings.jsx", "src/pages/Settings/sections/SystemSettings.jsx", "src/pages/Settings/sections/TableColours.jsx", "src/pages/Settings/sections/TableFlags.jsx", "src/pages/customers", "src/pages/finance", "src/pages/floor", "src/pages/inventory", "src/pages/notes", "src/pages/online/OnlineOrdersPage.jsx", "src/pages/orders", "src/pages/overview", "src/pages/pricing", "src/pages/printing", "src/pages/products", "src/pages/reports/expenses", "src/pages/reports/kit", "src/pages/reports/misc", "src/pages/reports/prepzones", "src/pages/reports/products", "src/pages/reports/staff", "src/pages/reports/store", "src/pages/reports/technical", "src/pages/reports/today", "src/pages/schedule", "src/pages/setup", "src/pages/staff", "src/pages/staff/SessionsPage.jsx", "src/pages/tables", "src/shell"
|
||||
"src/App.jsx", "src/hooks", "src/live", "src/pages/Settings/SettingsPage.jsx", "src/pages/Settings/sections/DataTransfer.jsx", "src/pages/Settings/sections/DevelopmentSettings.jsx", "src/pages/Settings/sections/FiscalSettings.jsx", "src/pages/Settings/sections/OperationSettings.jsx", "src/pages/Settings/sections/QuickMessages.jsx", "src/pages/Settings/sections/SecuritySettings.jsx", "src/pages/Settings/sections/SystemSettings.jsx", "src/pages/Settings/sections/TableColours.jsx", "src/pages/Settings/sections/TableFlags.jsx", "src/pages/customers", "src/pages/finance", "src/pages/floor", "src/pages/inventory", "src/pages/notes", "src/pages/online/OnlineOrdersPage.jsx", "src/pages/orders", "src/pages/overview", "src/pages/pricing", "src/pages/printing", "src/pages/products", "src/pages/reports/expenses", "src/pages/reports/kit", "src/pages/reports/misc", "src/pages/reports/moves", "src/pages/reports/prepzones", "src/pages/reports/products", "src/pages/reports/staff", "src/pages/reports/store", "src/pages/reports/technical", "src/pages/reports/today", "src/pages/schedule", "src/pages/setup", "src/pages/staff", "src/pages/staff/SessionsPage.jsx", "src/pages/tables", "src/shell"
|
||||
]
|
||||
}
|
||||
|
||||
Generated
+1
@@ -9729,6 +9729,7 @@
|
||||
"name": "@xenia/ui",
|
||||
"version": "0.0.0",
|
||||
"peerDependencies": {
|
||||
"@xenia/i18n": "*",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Order lines: what POST /api/orders/{id}/items and POST /api/orders/quote take (plan step 4.4).
|
||||
//
|
||||
// An app never sends a price. A line says what was chosen, by id (sub-choices by name):
|
||||
// { product_id, quantity, notes?, course_id?, price_adjustment?, is_service_item?,
|
||||
// { product_id, quantity, notes?, course_id?, price_adjustment?, price_reason?, is_service_item?,
|
||||
// quick: [{id, qty?}], options: [{id, qty?, subs: [name]}],
|
||||
// prefs: [{set_id, choices: [{id, qty?, sub?}], shared?}], removed: [ingredient_id] }
|
||||
// and the server prices it (local_backend/services/pos_cart.py; the counter POS builds the
|
||||
@@ -108,6 +108,7 @@ export function wireLine(item, product) {
|
||||
if (item.notes?.trim()) line.notes = item.notes.trim()
|
||||
if (item.course_id != null) line.course_id = item.course_id
|
||||
if (item.price_adjustment) line.price_adjustment = cents(item.price_adjustment)
|
||||
if (item.price_adjustment && item.price_reason) line.price_reason = String(item.price_reason).slice(0, 200) // 6F.3
|
||||
if (item.is_service_item) line.is_service_item = true
|
||||
return line
|
||||
}
|
||||
|
||||
@@ -64,6 +64,12 @@ test('a price changed by hand and a service item travel with the line; nothing e
|
||||
assert.deepEqual(line, { product_id: 1, quantity: 1, price_adjustment: -1, is_service_item: true })
|
||||
})
|
||||
|
||||
test('the reason for a price changed by hand travels with it, never alone (6F.3)', () => {
|
||||
assert.deepEqual(wireLine({ product_id: 1, quantity: 1, price_adjustment: -0.5, price_reason: 'Regular customer' }, burger),
|
||||
{ product_id: 1, quantity: 1, price_adjustment: -0.5, price_reason: 'Regular customer' })
|
||||
assert.deepEqual(wireLine({ product_id: 1, quantity: 1, price_reason: 'nothing changed' }, burger), { product_id: 1, quantity: 1 })
|
||||
})
|
||||
|
||||
test('what is not on the menu any more is refused, not dropped', () => {
|
||||
assert.throws(() => lineFromOptions(burger, { selected_options: [e('extra', 99, 'Truffle')] }), LineError)
|
||||
assert.throws(() => lineFromOptions(burger, { selected_options: [e('quick', null, 'Bacon')] }), LineError)
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"invalid_credentials": "Λάθος όνομα χρήστη ή κωδικός.",
|
||||
"session_ended": "Η σύνδεσή σας έληξε. Συνδεθείτε ξανά.",
|
||||
"session_exists": "Είστε ήδη συνδεδεμένοι σε άλλο {{client}}. Αποσυνδεθείτε πρώτα από εκεί.",
|
||||
"session_elsewhere": "Είστε συνδεδεμένοι σε άλλη συσκευή ({{device}}, από {{since}}). Συνέχεια; Εκείνη θα αποσυνδεθεί.",
|
||||
"login_mode_not_allowed": "Αυτός ο τρόπος σύνδεσης δεν είναι ενεργός ({{mode}}).",
|
||||
"mode_needs_device": "Η σύνδεση με {{mode}} γίνεται μόνο σε συζευγμένη συσκευή.",
|
||||
"username_required": "Συμπληρώστε το όνομα χρήστη.",
|
||||
@@ -102,7 +103,16 @@
|
||||
"discounts_off": "Οι εκπτώσεις είναι απενεργοποιημένες σε αυτό το κατάστημα.",
|
||||
"no_customer": "Ορίστε πρώτα πελάτη στην παραγγελία.",
|
||||
"item_not_tabbable": "Αυτό το είδος είναι ήδη {{status}}: δεν μπαίνει σε καρτέλα.",
|
||||
"product_unavailable": "Το προϊόν {{product_id}} δεν είναι διαθέσιμο."
|
||||
"product_unavailable": "Το προϊόν {{product_id}} δεν είναι διαθέσιμο.",
|
||||
"price_change_off": "Η αλλαγή τιμής με το χέρι είναι κλειστή σε αυτό το κατάστημα.",
|
||||
"price_change_sent_off": "Οι τιμές αλλάζουν μόνο πριν σταλούν τα είδη.",
|
||||
"price_reason_required": "Γράψτε γιατί αλλάζει η τιμή.",
|
||||
"one_more_off": "Το «Άλλο ένα» δεν είναι ενεργό για αυτό το προϊόν.",
|
||||
"one_more_line": "Αυτή η γραμμή δεν ξαναπαραγγέλνεται με ένα πάτημα.",
|
||||
"quantity_change_off": "Η αλλαγή ποσότητας είναι κλειστή σε αυτό το κατάστημα.",
|
||||
"quantity_remove_off": "Εδώ οι ποσότητες μόνο αυξάνονται.",
|
||||
"quantity_invalid": "Διαλέξτε ακέραιο από 1 έως {{max}}.",
|
||||
"quantity_line": "Η ποσότητα αυτής της γραμμής δεν αλλάζει εδώ."
|
||||
},
|
||||
"notification": {
|
||||
"not_found": "Η ειδοποίηση {{notification_id}} δεν βρέθηκε."
|
||||
@@ -366,5 +376,14 @@
|
||||
"scene": {
|
||||
"not_found": "Η σκηνή δεν βρέθηκε.",
|
||||
"until_past": "Αυτή η ώρα έχει περάσει: διαλέξτε μια μεταγενέστερη."
|
||||
},
|
||||
"split": {
|
||||
"not_allowed": "Αυτός ο διαχωρισμός λογαριασμού δεν είναι ενεργός σε αυτό το κατάστημα.",
|
||||
"lines_changed": "Κάποια από αυτά πληρώθηκαν ή άλλαξαν στο μεταξύ. Δείτε ξανά.",
|
||||
"amount_invalid": "Κάθε μέρος πρέπει να είναι πάνω από 0 και κάτω από το σύνολο ({{total}}).",
|
||||
"part_locked": "Αυτό είναι μέρος διαχωρισμένου λογαριασμού: αναιρέστε τον διαχωρισμό για να το αλλάξετε.",
|
||||
"not_found": "Αυτός ο διαχωρισμός δεν υπάρχει πια.",
|
||||
"paid_already": "Ένα μέρος έχει ήδη πληρωθεί ή μπει σε καρτέλα: ο διαχωρισμός δεν αναιρείται.",
|
||||
"parts_unpaid": "Μέρη διαχωρισμένου λογαριασμού είναι ακόμα απλήρωτα: πληρώστε τα πρώτα."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,8 @@
|
||||
"media": "Πολυμέσα",
|
||||
"signage": "Προβολή",
|
||||
"main": "Κύριο μενού",
|
||||
"scenes": "Σκηνές"
|
||||
"scenes": "Σκηνές",
|
||||
"reportsMoves": "Μεταφορές"
|
||||
},
|
||||
"profile": {
|
||||
"edit": "Επεξεργασία προφίλ",
|
||||
@@ -221,7 +222,12 @@
|
||||
"linkHint": "Για παράδειγμα μια οθόνη πελάτη που δείχνει την παραγγελία ενός ταμείου πάγκου.",
|
||||
"full": "{{label}}: η άδεια επιτρέπει {{max}} και χρησιμοποιούνται όλα. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια.",
|
||||
"noApps": "Καμία εφαρμογή συσκευών δεν είναι ενεργή. Ενεργοποιήστε μία πρώτα από τις Εφαρμογές.",
|
||||
"signInTip": "PIN ή κωδικός: ο καθένας συνδέεται. Πάτημα στο όνομα: ο καθένας αλλάζει χρήστη χωρίς μυστικό (κοινό ταμείο). Κανένας: η οθόνη δουλεύει χωρίς χρήστη (οθόνη κουζίνας)."
|
||||
"signInTip": "PIN ή κωδικός: ο καθένας συνδέεται. Πάτημα στο όνομα: ο καθένας αλλάζει χρήστη χωρίς μυστικό (κοινό ταμείο). Κανένας: η οθόνη δουλεύει χωρίς χρήστη (οθόνη κουζίνας).",
|
||||
"usernames": "Το προσωπικό γράφει το όνομα χρήστη",
|
||||
"usernamesDefault": "Όπως το κατάστημα ({{value}})",
|
||||
"usernamesYes": "Ναι",
|
||||
"usernamesNo": "Όχι, επιλέγουν το όνομά τους",
|
||||
"usernamesTip": "Ναι: η οθόνη δεν δείχνει κανέναν και ζητά όνομα χρήστη, μετά PIN ή κωδικό. Η «Επιλογή ονόματος» δεν γίνεται μαζί του."
|
||||
},
|
||||
"actions": {
|
||||
"rename": "Μετονομασία",
|
||||
@@ -362,7 +368,12 @@
|
||||
"empty": "Τίποτα καινούργιο. Εδώ εμφανίζονται ειδοποιήσεις για την άδεια, την εκτύπωση και την υποστήριξη.",
|
||||
"markAll": "Όλες διαβασμένες",
|
||||
"times_one": "{{count}} φορά",
|
||||
"times_other": "{{count}} φορές"
|
||||
"times_other": "{{count}} φορές",
|
||||
"dayOpened": "Η ημέρα άνοιξε",
|
||||
"actions": {
|
||||
"open_day": "Άνοιγμα τώρα",
|
||||
"overview": "Στην επισκόπηση"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"saved": "Αποθηκεύτηκε",
|
||||
@@ -388,7 +399,8 @@
|
||||
"session": {
|
||||
"off": "Επιτρέπεται σε πολλές συσκευές",
|
||||
"refuse_new": "Άρνηση δεύτερης σύνδεσης",
|
||||
"end_old": "Αποσύνδεση της παλιότερης"
|
||||
"end_old": "Αποσύνδεση της παλιότερης",
|
||||
"ask": "Ερώτηση, μετά αποσύνδεση του άλλου κινητού"
|
||||
},
|
||||
"signIn": {
|
||||
"title": "Σύνδεση",
|
||||
@@ -403,8 +415,13 @@
|
||||
"requireUsernameHint": "Αντί να επιλέγουν το όνομά τους από τη λίστα.",
|
||||
"device": "Στις συζευγμένες συσκευές (οθόνη κουζίνας, ταμείο πάγκου) το προσωπικό συνδέεται με",
|
||||
"deviceHint": "Κάθε συσκευή μπορεί να έχει δική της επιλογή στη σελίδα Συσκευές.",
|
||||
"terminalUsername": "Στις συζευγμένες συσκευές το προσωπικό γράφει το όνομα χρήστη",
|
||||
"terminalUsernameHint": "Η οθόνη δεν δείχνει ονόματα· η «Επιλογή ονόματος» ζητά τότε PIN. Κάθε συσκευή μπορεί να επιλέξει αλλιώς στη σελίδα Συσκευές.",
|
||||
"terminalUsernameTip": "Όποιος στέκεται στο ταμείο δεν βλέπει ποιοι δουλεύουν εδώ ούτε δοκιμάζει το PIN συναδέλφου πατώντας ονόματα.",
|
||||
"singleManager": "Μία σύνδεση ανά υπεύθυνο",
|
||||
"singleWaiter": "Μία σύνδεση ανά σερβιτόρο",
|
||||
"singleWaiterHint": "Μετράνε μόνο τα κινητά: η σύνδεση και στο ταμείο επιτρέπεται.",
|
||||
"singleWaiterTip": "Ερώτηση: το κινητό λέει πού είναι ήδη συνδεδεμένος ο σερβιτόρος και από πότε. Η «Συνέχεια» αποσυνδέει αμέσως εκείνο το κινητό, που δείχνει γιατί. Παραγγελίες που είχε ακόμα να στείλει μένουν σε αυτό και φεύγουν την επόμενη φορά που θα συνδεθεί κάποιος εκεί.",
|
||||
"singleTip": "Όταν κάποιος είναι ήδη συνδεδεμένος σε άλλη συσκευή: επιτρέπονται και οι δύο, απορρίπτεται η νέα σύνδεση ή αποσυνδέεται η παλιότερη.",
|
||||
"idle": "Αποσύνδεση μετά από",
|
||||
"idleHint": "Ημέρες χωρίς χρήση της εφαρμογής (διαχείριση, εφαρμογή σερβιτόρων και συζευγμένες συσκευές). Την επόμενη φορά συνδέονται ξανά.",
|
||||
@@ -739,6 +756,89 @@
|
||||
"spoof": "Προσποιητή εκτύπωση",
|
||||
"spoofHint": "Κάθε εκτύπωση απορρίπτεται· οι εφαρμογές συμπεριφέρονται σαν να τυπώθηκε.",
|
||||
"spoofOn": "Ενεργό: οι εκτυπωτές δεν τυπώνουν τίποτα."
|
||||
},
|
||||
"prices": {
|
||||
"title": "Τιμές που αλλάζουν με το χέρι",
|
||||
"intro": "Πότε το προσωπικό γράφει δική του τιμή σε μια γραμμή και αν πρέπει να πει γιατί. Κάθε αλλαγή κρατιέται: ποιος, πότε, από πόσο σε πόσο, γιατί.",
|
||||
"when": "Το προσωπικό αλλάζει τιμή",
|
||||
"whenHint": "Ποιος: «Τι επιτρέπεται σε κάθε ρόλο» και τα δικαιώματα κάθε ατόμου.",
|
||||
"whenTip": "Ποτέ: κανείς δεν γράφει τιμή, ούτε οι ιδιοκτήτες. Πριν την αποστολή: μόνο στο καλάθι, πριν πάει η παραγγελία στην κουζίνα. Οποτεδήποτε: και σε γραμμή που έχει σταλεί ή σερβιριστεί (θέλει δικό του δικαίωμα, «ήδη σταλμένο ή σερβιρισμένο»).",
|
||||
"modes": {
|
||||
"off": "Ποτέ",
|
||||
"before_sending": "Μόνο πριν την αποστολή",
|
||||
"anytime": "Οποτεδήποτε"
|
||||
},
|
||||
"reason": "Να ζητείται αιτία",
|
||||
"reasonHint": "Μια τιμή που αλλάζει με το χέρι δεν αποθηκεύεται χωρίς αιτία.",
|
||||
"reasonTip": "Η αιτία κρατιέται με την αλλαγή και φαίνεται στο ιστορικό της παραγγελίας και στις Αναφορές → Ακυρώσεις, εκπτώσεις και αλλαγές τιμών. Οι εκπτώσεις % του ταμείου δεν ζητούν: η έκπτωση λέει τι είναι.",
|
||||
"reasons": "Γρήγορες αιτίες",
|
||||
"reasonsHint": "Με ένα πάτημα· το προσωπικό μπορεί και να γράψει δική του. Καμία: οι έτοιμες.",
|
||||
"reasonItem": "Γρήγορη αιτία",
|
||||
"newReason": "Νέα γρήγορη αιτία…"
|
||||
},
|
||||
"quantity": {
|
||||
"title": "Αλλαγή ποσότητας σταλμένης γραμμής",
|
||||
"intro": "Το προσωπικό διορθώνει πόσα είναι σε μια γραμμή χωρίς να ξαναστείλει στην κουζίνα. Κάθε αλλαγή κρατιέται στο ιστορικό της παραγγελίας.",
|
||||
"when": "Το προσωπικό μπορεί",
|
||||
"whenHint": "Ποιος: «Τι επιτρέπεται σε κάθε ρόλο» και τα δικαιώματα κάθε ατόμου.",
|
||||
"whenTip": "Μόνο προσθήκη: η ποσότητα μόνο ανεβαίνει (μια μπίρα από το ψυγείο), δεν τυπώνεται τίποτα. Προσθήκη και αφαίρεση: όταν κατεβαίνει, η διαφορά ακυρώνεται ως ξεχωριστή γραμμή και ρωτά αν θα σταλεί ακύρωση στην κουζίνα. Η αφαίρεση θέλει και το δικαίωμα ακύρωσης.",
|
||||
"modes": {
|
||||
"off": "Καθόλου",
|
||||
"add_only": "Μόνο προσθήκη",
|
||||
"add_and_remove": "Προσθήκη και αφαίρεση"
|
||||
}
|
||||
},
|
||||
"split": {
|
||||
"title": "Διαχωρισμός λογαριασμού με ποσά",
|
||||
"intro": "Το προσωπικό χωρίζει έναν λογαριασμό σε μέρη που πληρώνονται χωριστά: οι γραμμές εξοφλούνται μαζί και κάθε μέρος πληρώνεται μετρητά, με κάρτα ή σε καρτέλα.",
|
||||
"when": "Το προσωπικό μπορεί να χωρίσει",
|
||||
"whenHint": "Ποιος: «Τι επιτρέπεται σε κάθε ρόλο» και τα δικαιώματα κάθε ατόμου.",
|
||||
"whenTip": "Κάθε επιλογή περιλαμβάνει τις προηγούμενες. Μισά μισά: δύο ίσα μέρη. Δύο μέρη, όποια ποσά: και αναλογία ή τι πληρώνει το μέρος 1. Σε ίσα μέρη: από 2 έως το μέγιστο παρακάτω, το υπόλοιπο λεπτό στο τελευταίο μέρος. Ο διαχωρισμός αναιρείται μέχρι να πληρωθεί ένα μέρος. Η απόδειξη είναι οι ίδιες οι γραμμές και τυπώνεται όταν πληρωθεί το τελευταίο μέρος.",
|
||||
"levels": {
|
||||
"off": "Καθόλου",
|
||||
"two_equal": "Μισά μισά",
|
||||
"two_custom": "Δύο μέρη, όποια ποσά",
|
||||
"multiple_equal": "Σε ίσα μέρη (και δύο με όποια ποσά)"
|
||||
},
|
||||
"max": "Μέγιστα ίσα μέρη",
|
||||
"maxHint": "Τα μέρη ξεκινούν από τους πελάτες του τραπεζιού, όταν υπάρχουν."
|
||||
},
|
||||
"autoDay": {
|
||||
"title": "Άνοιγμα και κλείσιμο της ημέρας",
|
||||
"intro": "Η εργάσιμη ημέρα μπορεί να ανοίγει και να κλείνει μόνη της, στο ωράριο (σελίδα Πρόγραμμα) ή σε δική της ώρα. Δουλεύει και χωρίς ίντερνετ.",
|
||||
"open": "Η ημέρα ανοίγει",
|
||||
"openHint": "Μια ημέρα που έκλεισε υπεύθυνος με το χέρι δεν ξανανοίγει πριν το επόμενο άνοιγμα.",
|
||||
"openTip": "Στο ωράριο: η ημέρα ανοίγει όταν αρχίζει το ωράριο. Σε ώρα: κάθε μέρα εκείνη την ώρα, όποιο κι αν είναι το ωράριο. Μόνο ειδοποίηση: οι υπεύθυνοι παίρνουν μήνυμα που μένει μέχρι να ανοίξει η ημέρα, με κουμπί «Άνοιγμα τώρα».",
|
||||
"close": "Η ημέρα κλείνει",
|
||||
"closeHint": "Κλείνει μόνο όταν έχουν κλείσει όλα τα τραπέζια· αλλιώς ειδοποιείστε και ξαναδοκιμάζει κάθε 15 λεπτά.",
|
||||
"closeTip": "Οι ανοιχτές βάρδιες τελειώνουν όπως σε χειροκίνητο κλείσιμο. Αν ο server ήταν κλειστός την ώρα του κλεισίματος, η ημέρα δεν κλείνει αργότερα μόνη της: ειδοποιείστε.",
|
||||
"modes": {
|
||||
"open": {
|
||||
"off": "Με το χέρι",
|
||||
"schedule": "Μόνη της στο ωράριο",
|
||||
"time": "Μόνη της σε ώρα",
|
||||
"alert": "Μόνο ειδοποίηση στο ωράριο"
|
||||
},
|
||||
"close": {
|
||||
"off": "Με το χέρι",
|
||||
"schedule": "Μόνη της στο τέλος του ωραρίου",
|
||||
"time": "Μόνη της σε ώρα",
|
||||
"alert": "Μόνο ειδοποίηση στο τέλος του ωραρίου"
|
||||
}
|
||||
},
|
||||
"openTime": "Ανοίγει στις",
|
||||
"closeTime": "Κλείνει στις",
|
||||
"openOffset": "Άνοιγμα νωρίτερα",
|
||||
"closeOffset": "Κλείσιμο αργότερα",
|
||||
"offsetNone": "Ακριβώς στο ωράριο",
|
||||
"before_one": "{{count}} λεπτό πριν",
|
||||
"before_other": "{{count}} λεπτά πριν",
|
||||
"after_one": "{{count}} λεπτό μετά",
|
||||
"after_other": "{{count}} λεπτά μετά",
|
||||
"ignoreBreak": "Μία ημέρα και με διάλειμμα",
|
||||
"ignoreBreakHint": "Κλειστό: το διάλειμμα ανάμεσα σε δύο διαστήματα κλείνει την ημέρα και το επόμενο ανοίγει νέα.",
|
||||
"ignoreBreakTip": "Με ωράριο 12:00–16:00 και 19:00–23:00: ανοιχτό = μία ημέρα 12:00–23:00· κλειστό = δύο ημέρες.",
|
||||
"noHours": "Δεν υπάρχει ακόμα ωράριο: ορίστε το στη σελίδα Πρόγραμμα, αλλιώς δεν γίνεται τίποτα."
|
||||
}
|
||||
},
|
||||
"logs": {
|
||||
@@ -2290,7 +2390,8 @@
|
||||
"event": {
|
||||
"waiter_discount": "Έκπτωση",
|
||||
"free_item_added": "Δωρεάν",
|
||||
"modifier_applied": "Τροποποιητής"
|
||||
"modifier_applied": "Τροποποιητής",
|
||||
"manual_price": "Τιμή με το χέρι"
|
||||
}
|
||||
},
|
||||
"orderStatus": {
|
||||
@@ -2792,7 +2893,10 @@
|
||||
"availableTip": "Όχι: εξαφανίζεται από τα μενού των σερβιτόρων και του ταμείου μέχρι να το ενεργοποιήσετε ξανά (τελείωσε για σήμερα). Τίποτε άλλο δεν αλλάζει.",
|
||||
"quickAddTip": "Ναι: ένα πάτημα στη λίστα του σερβιτόρου το προσθέτει κατευθείαν, χωρίς να ανοίξουν οι επιλογές του. Αφήστε το κλειστό για προϊόντα που χρειάζονται επιλογή (ψήσιμο, συνοδευτικά).",
|
||||
"vatGroupTip": "Ο συντελεστής ΦΠΑ που χρησιμοποιεί η φορολογική απόδειξη για το προϊόν. Χρειάζεται για να πληρωθεί όσο ο φορολογικός μηχανισμός είναι ενεργός.",
|
||||
"costTip": "Τι σας κοστίζει μία μονάδα (υλικά, συσκευασία). Οι αναφορές το χρησιμοποιούν για το κέρδος· προϊόντα χωρίς κόστος κάνουν το κέρδος κατώτερη εκτίμηση."
|
||||
"costTip": "Τι σας κοστίζει μία μονάδα (υλικά, συσκευασία). Οι αναφορές το χρησιμοποιούν για το κέρδος· προϊόντα χωρίς κόστος κάνουν το κέρδος κατώτερη εκτίμηση.",
|
||||
"oneMore": "Άλλο ένα (+1)",
|
||||
"oneMoreHint": "Μια σταλμένη γραμμή αυτού του προϊόντος έχει κουμπί +1 στα κινητά και στο ταμείο.",
|
||||
"oneMoreTip": "Για ό,τι τα τραπέζια ξαναπαραγγέλνουν (μπίρες, καφέδες). Το +1 παραγγέλνει το ίδιο ξανά, με τις ίδιες επιλογές και σημείωση, στη σημερινή τιμή, και το στέλνει στην κουζίνα ή στο μπαρ όπως κάθε νέα παραγγελία. Κλειστό αρχικά."
|
||||
}
|
||||
},
|
||||
"menuTabletSettings": {
|
||||
@@ -3266,7 +3370,8 @@
|
||||
"tabs": {
|
||||
"order": "Παραγγελία",
|
||||
"prices": "Αλλαγές τιμών",
|
||||
"history": "Ιστορικό"
|
||||
"history": "Ιστορικό",
|
||||
"moves": "Μεταφορές"
|
||||
},
|
||||
"payAll": "Πληρωμή όλων",
|
||||
"close": "Κλείσιμο",
|
||||
@@ -3311,7 +3416,8 @@
|
||||
"paid": "Πληρώθηκε",
|
||||
"cancelled": "Ακυρώθηκε",
|
||||
"tabbed": "Στην καρτέλα",
|
||||
"closed": "Απλήρωτο"
|
||||
"closed": "Απλήρωτο",
|
||||
"split": "Σε διαχωρισμό"
|
||||
},
|
||||
"without": "Χωρίς {{list}}",
|
||||
"added": "{{time}} · {{name}}",
|
||||
@@ -3368,7 +3474,14 @@
|
||||
"PAYMENT_OFFLINE": "Πληρωμή (offline)",
|
||||
"ORDER_CLOSED": "Κλείσιμο",
|
||||
"ORDER_CANCELLED": "Ακύρωση",
|
||||
"ITEM_CANCELLED": "Ακύρωση γραμμής"
|
||||
"ITEM_CANCELLED": "Ακύρωση γραμμής",
|
||||
"PRICE_CHANGED": "Αλλαγή τιμής",
|
||||
"PRICE_SET_BY_HAND": "Τιμή με το χέρι (εγκρίθηκε)",
|
||||
"QUANTITY_CHANGED": "Αλλαγή ποσότητας",
|
||||
"ITEM_REORDERED": "Άλλο ένα",
|
||||
"SPLIT_CREATED": "Διαχωρισμός λογαριασμού",
|
||||
"SPLIT_UNDONE": "Αναίρεση διαχωρισμού",
|
||||
"SPLIT_SETTLED": "Εξόφληση διαχωρισμού"
|
||||
},
|
||||
"price": {
|
||||
"modifier_applied": "Κανόνας τιμής",
|
||||
@@ -3377,7 +3490,14 @@
|
||||
"deal_offer_accepted": "Προσφορά (αποδεκτή)",
|
||||
"deal_offer_dismissed": "Προσφορά (απορρίφθηκε)",
|
||||
"waiter_discount": "Έκπτωση",
|
||||
"free_item_added": "Δωρεάν προϊόν"
|
||||
"free_item_added": "Δωρεάν προϊόν",
|
||||
"manual_price": "Τιμή με το χέρι"
|
||||
},
|
||||
"approvedBy": "με έγκριση {{name}}",
|
||||
"stage": {
|
||||
"cart": "πριν την αποστολή",
|
||||
"sent": "μετά την αποστολή",
|
||||
"served": "μετά το σερβίρισμα"
|
||||
}
|
||||
},
|
||||
"add": {
|
||||
@@ -3425,7 +3545,38 @@
|
||||
"saved": "Οι σημαίες αποθηκεύτηκαν",
|
||||
"sent": "Σημαίες αποθηκεύτηκαν και το μήνυμα στάλθηκε"
|
||||
},
|
||||
"printHelp": "Τα δελτία ξαναδοκιμάζονται κάθε 8 δευτερόλεπτα μέχρι να τυπωθούν. Αν ένας εκτυπωτής είναι κλειστός ή χωρίς χαρτί, στείλτε τα σε άλλον, ή σημειώστε ότι τα χειριστήκατε όταν μάθει η κουζίνα."
|
||||
"printHelp": "Τα δελτία ξαναδοκιμάζονται κάθε 8 δευτερόλεπτα μέχρι να τυπωθούν. Αν ένας εκτυπωτής είναι κλειστός ή χωρίς χαρτί, στείλτε τα σε άλλον, ή σημειώστε ότι τα χειριστήκατε όταν μάθει η κουζίνα.",
|
||||
"moves": {
|
||||
"none": "Τίποτα δεν μεταφέρθηκε σε αυτή την παραγγελία.",
|
||||
"wholeOrder": "Όλη η παραγγελία: {{path}}",
|
||||
"linePath": "μεταφέρθηκε: {{path}}",
|
||||
"lines_one": "{{count}} γραμμή",
|
||||
"lines_other": "{{count}} γραμμές",
|
||||
"kind": {
|
||||
"table_transfer": "Όλο το τραπέζι",
|
||||
"items_moved": "Μεταφορά γραμμών",
|
||||
"orders_merged": "Ένωση τραπεζιών"
|
||||
}
|
||||
},
|
||||
"split": {
|
||||
"button": "Διαχωρισμός ποσού",
|
||||
"fewer": "Ένα μέρος λιγότερο",
|
||||
"more": "Ένα μέρος ακόμη",
|
||||
"equal": "Ίσα μέρη",
|
||||
"custom": "Διαφορετικά ποσά",
|
||||
"first": "Το μέρος 1 πληρώνει",
|
||||
"part": "Μέρος {{n}} από {{of}}",
|
||||
"invalid": "Αυτό το ποσό δεν μοιράζεται έτσι.",
|
||||
"hint": "Οι γραμμές εξοφλούνται μαζί· κάθε μέρος πληρώνεται μετά χωριστά (μετρητά, κάρτα ή καρτέλα). Αναιρείται μέχρι να πληρωθεί ένα μέρος.",
|
||||
"confirm_one": "Διαχωρισμός σε {{count}} μέρος",
|
||||
"confirm_other": "Διαχωρισμός σε {{count}} μέρη",
|
||||
"done": "Ο λογαριασμός διαχωρίστηκε: πληρώστε κάθε μέρος χωριστά.",
|
||||
"undone": "Ο διαχωρισμός αναιρέθηκε.",
|
||||
"bill_one": "Διαχωρισμός · {{count}} μέρος από {{total}}",
|
||||
"bill_other": "Διαχωρισμός · {{count}} μέρη από {{total}}",
|
||||
"paid": "Πληρώθηκαν {{paid}} · απομένουν {{due}}",
|
||||
"undo": "Αναίρεση διαχωρισμού"
|
||||
}
|
||||
},
|
||||
"printing": {
|
||||
"back": "Πίσω",
|
||||
@@ -3973,7 +4124,10 @@
|
||||
"anyTable": "Κάθε τραπέζι",
|
||||
"cancelledLines": "Ακυρωμένες γραμμές",
|
||||
"ordersCount_one": "{{count}} παραγγελία · {{total}}",
|
||||
"ordersCount_other": "{{count}} παραγγελίες · {{total}}"
|
||||
"ordersCount_other": "{{count}} παραγγελίες · {{total}}",
|
||||
"autoBoth": "Άνοιξε και έκλεισε μόνη της",
|
||||
"autoOpened": "Άνοιξε μόνη της",
|
||||
"autoClosed": "Έκλεισε μόνη της"
|
||||
},
|
||||
"traffic": {
|
||||
"orders": "Παραγγελίες",
|
||||
@@ -4069,7 +4223,7 @@
|
||||
}
|
||||
},
|
||||
"misc": {
|
||||
"title": "Ακυρώσεις και εκπτώσεις",
|
||||
"title": "Ακυρώσεις, εκπτώσεις και αλλαγές τιμών",
|
||||
"cancellations": "Ακυρώσεις",
|
||||
"discounts": "Εκπτώσεις",
|
||||
"when": "Πότε",
|
||||
@@ -4093,7 +4247,18 @@
|
||||
"discountTotal": "Σύνολο εκπτώσεων",
|
||||
"alreadyOff": "έχουν ήδη αφαιρεθεί από τα έσοδα",
|
||||
"times_one": "{{count}} φορά",
|
||||
"times_other": "{{count}} φορές"
|
||||
"times_other": "{{count}} φορές",
|
||||
"priceChanges": "Αλλαγές τιμών",
|
||||
"priceWas": "Ήταν",
|
||||
"priceNow": "Έγινε",
|
||||
"stage": "Πότε",
|
||||
"changedBy": "Άλλαξε από",
|
||||
"approvedBy": "Ενέκρινε",
|
||||
"changes": "Αλλαγές τιμών",
|
||||
"changesValue": "Διαφορά",
|
||||
"changesValueTip": "Τι πρόσθεσαν (+) ή αφαίρεσαν (−) οι αλλαγές, για την ποσότητα κάθε γραμμής τη στιγμή της αλλαγής.",
|
||||
"changesCount_one": "{{count}} αλλαγή",
|
||||
"changesCount_other": "{{count}} αλλαγές"
|
||||
},
|
||||
"tech": {
|
||||
"title": "Τεχνικά",
|
||||
@@ -4155,6 +4320,23 @@
|
||||
"dueDate": "Λήξη {{date}}",
|
||||
"payments": "Πληρωμές",
|
||||
"noPayments": "Δεν έχει πληρωθεί τίποτα ακόμα."
|
||||
},
|
||||
"moves": {
|
||||
"title": "Μεταφορές μεταξύ τραπεζιών",
|
||||
"kind": "Τι",
|
||||
"from": "Από",
|
||||
"to": "Προς",
|
||||
"lines": "Γραμμές",
|
||||
"by": "Από ποιον",
|
||||
"allKinds": "Όλα τα είδη",
|
||||
"count": "Μεταφορές",
|
||||
"list": "Όλες οι μεταφορές",
|
||||
"listTip": "Ολόκληρο τραπέζι σε ελεύθερο, γραμμές σε άλλο τραπέζι, ή ένωση δύο τραπεζιών. Κάθε γραμμή κρατά τις μεταφορές της όπου κι αν καταλήξει, ακόμη κι αν χωριστεί ή μεταφερθεί ξανά.",
|
||||
"kinds": {
|
||||
"table_transfer": "Όλο το τραπέζι",
|
||||
"items_moved": "Μεταφορά γραμμών",
|
||||
"orders_merged": "Ένωση τραπεζιών"
|
||||
}
|
||||
}
|
||||
},
|
||||
"finance": {
|
||||
|
||||
@@ -454,14 +454,20 @@
|
||||
"cancel": "Ακύρωση ειδών που έχουν σταλεί"
|
||||
},
|
||||
"prices": {
|
||||
"modify": "Αλλαγή τιμής είδους"
|
||||
"modify": "Αλλαγή τιμής είδους πριν σταλεί",
|
||||
"modify_sent": "Αλλαγή τιμής είδους που έχει ήδη σταλεί ή σερβιριστεί",
|
||||
"view_changes": "Προβολή τιμών που άλλαξαν με το χέρι (ποιος, πότε, γιατί)"
|
||||
},
|
||||
"business_day": {
|
||||
"manage": "Άνοιγμα και κλείσιμο της εργάσιμης ημέρας"
|
||||
},
|
||||
"refunds": "Επιστροφή χρημάτων για πληρωμές άλλων βαρδιών",
|
||||
"payments": {
|
||||
"revert": "Αναίρεση πληρωμής (πληρωμένα → απλήρωτα)"
|
||||
"revert": "Αναίρεση πληρωμής (πληρωμένα → απλήρωτα)",
|
||||
"split_amount": "Διαχωρισμός λογαριασμού με ποσά (ίσα μέρη ή αναλογία)"
|
||||
},
|
||||
"items": {
|
||||
"change_quantity": "Αλλαγή ποσότητας σταλμένης γραμμής (χωρίς νέο δελτίο)"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -14,7 +14,10 @@
|
||||
"submit": "Σύνδεση",
|
||||
"back": "Πίσω",
|
||||
"empty": "Κανείς δεν μπορεί να συνδεθεί εδώ ακόμη",
|
||||
"emptyBody": "Δώστε σε κάποιον το δικαίωμα {{app}} στο Προσωπικό, στη διαχείριση."
|
||||
"emptyBody": "Δώστε σε κάποιον το δικαίωμα {{app}} στο Προσωπικό, στη διαχείριση.",
|
||||
"username": "Όνομα χρήστη",
|
||||
"next": "Επόμενο",
|
||||
"typeUsername": "Γράψτε το όνομα χρήστη σας"
|
||||
},
|
||||
"blocked": {
|
||||
"off": "Η εφαρμογή {{app}} είναι απενεργοποιημένη",
|
||||
@@ -215,7 +218,20 @@
|
||||
"given": "Μετρητά που δόθηκαν",
|
||||
"exact": "Ακριβώς: {{amount}}",
|
||||
"change": "Ρέστα: {{amount}}",
|
||||
"short": "Είναι λιγότερα από το ποσό που οφείλεται"
|
||||
"short": "Είναι λιγότερα από το ποσό που οφείλεται",
|
||||
"amount": "Με ποσά",
|
||||
"confirmAmount_one": "Είσπραξη {{count}} μέρους",
|
||||
"confirmAmount_other": "Είσπραξη των {{count}} μερών",
|
||||
"fewerParts": "Ένα μέρος λιγότερο",
|
||||
"moreParts": "Ένα μέρος ακόμη",
|
||||
"share": {
|
||||
"equal": "Ίσα μέρη",
|
||||
"custom": "Διαφορετικά ποσά"
|
||||
},
|
||||
"firstPart": "Το μέρος 1 πληρώνει",
|
||||
"part": "Μέρος {{n}} από {{of}}",
|
||||
"splitInvalid": "Αυτό το ποσό δεν μοιράζεται έτσι.",
|
||||
"amountHint": "Τα είδη εξοφλούνται μαζί και κάθε μέρος πληρώνεται τώρα, μετρητά ή κάρτα."
|
||||
},
|
||||
"done": {
|
||||
"paid": "Πληρώθηκαν {{total}}",
|
||||
@@ -281,7 +297,8 @@
|
||||
"cash": "πληρώθηκε · μετρητά",
|
||||
"card": "πληρώθηκε · κάρτα"
|
||||
},
|
||||
"readyItem": "έτοιμο"
|
||||
"readyItem": "έτοιμο",
|
||||
"settled": "Στον διαχωρισμό"
|
||||
},
|
||||
"online": {
|
||||
"arrived_one": "Νέα online παραγγελία",
|
||||
@@ -466,6 +483,11 @@
|
||||
},
|
||||
"dialog": {
|
||||
"close": "Κλείσιμο"
|
||||
},
|
||||
"oneMore": {
|
||||
"send": "Αποστολή +{{count}}",
|
||||
"label": "Άλλο ένα",
|
||||
"sent": "Στάλθηκαν {{count}} ακόμη {{name}}"
|
||||
}
|
||||
},
|
||||
"display": {
|
||||
|
||||
@@ -29,7 +29,8 @@
|
||||
"startQuestion": "Θέλεις να ξεκινήσεις τη βάρδια σου;",
|
||||
"startingCash": "Αρχικά μετρητά (προαιρετικό)",
|
||||
"starting": "Εκκίνηση…",
|
||||
"startShift": "Έναρξη Βάρδιας"
|
||||
"startShift": "Έναρξη Βάρδιας",
|
||||
"badAmount": "Γράψτε ένα ποσό, π.χ. 50 ή 50,00."
|
||||
},
|
||||
"nav": {
|
||||
"tables": "Τραπέζια",
|
||||
@@ -83,7 +84,13 @@
|
||||
"username": "Όνομα χρήστη",
|
||||
"password": "Κωδικός",
|
||||
"signIn": "Σύνδεση",
|
||||
"enterPin": "Εισάγετε PIN"
|
||||
"enterPin": "Εισάγετε PIN",
|
||||
"elsewhereTitle": "Συνδεδεμένοι σε άλλη συσκευή",
|
||||
"elsewhereBody": "Είστε συνδεδεμένοι σε άλλη συσκευή ({{device}}) από τις {{time}}. Συνέχεια; Εκείνη θα αποσυνδεθεί.",
|
||||
"elsewhereContinue": "Συνέχεια",
|
||||
"elsewhereCancel": "Άκυρο",
|
||||
"signedOutReplaced": "Αποσυνδεθήκατε: συνδεθήκατε σε άλλη συσκευή.",
|
||||
"signedOut": "Αποσυνδεθήκατε. Συνδεθείτε ξανά."
|
||||
},
|
||||
"card": {
|
||||
"freeLower": "Ελεύθερο",
|
||||
@@ -527,7 +534,10 @@
|
||||
"merge": "Σφάλμα συγχώνευσης",
|
||||
"moveItems": "Σφάλμα μεταφοράς αντικειμένων",
|
||||
"flags": "Σφάλμα αποθήκευσης σημαιών",
|
||||
"combine": "Σφάλμα συνδυασμού"
|
||||
"combine": "Σφάλμα συνδυασμού",
|
||||
"price": "Η τιμή δεν άλλαξε.",
|
||||
"again": "Το «άλλο ένα» δεν στάλθηκε.",
|
||||
"quantity": "Η ποσότητα δεν άλλαξε."
|
||||
},
|
||||
"openOrder": "Άνοιγμα Παραγγελίας",
|
||||
"noPaid": "Δεν υπάρχουν πληρωμένα αντικείμενα",
|
||||
@@ -856,5 +866,91 @@
|
||||
"accepted": "Στάλθηκε στην κουζίνα",
|
||||
"declined": "Απορρίφθηκε",
|
||||
"note": "Σημείωση: {{note}}"
|
||||
},
|
||||
"price": {
|
||||
"reason": "Γιατί αλλάζει η τιμή;",
|
||||
"reasonMissing": "Γράψτε γιατί αλλάζει η τιμή",
|
||||
"reasons": {
|
||||
"regular": "Τακτικός πελάτης",
|
||||
"mistake": "Λάθος τιμή στο μενού",
|
||||
"compensation": "Αποζημίωση για πρόβλημα",
|
||||
"manager": "Απόφαση υπευθύνου",
|
||||
"happyHour": "Προσφορά ημέρας",
|
||||
"other": "Άλλο"
|
||||
},
|
||||
"history": "Ιστορικό τιμής",
|
||||
"historySub": "Ποιος την άλλαξε, πότε και γιατί",
|
||||
"historyNone": "Καμία αλλαγή τιμής σε αυτή τη γραμμή.",
|
||||
"historyFailed": "Το ιστορικό τιμής δεν φόρτωσε.",
|
||||
"stage": {
|
||||
"cart": "πριν την αποστολή",
|
||||
"sent": "μετά την αποστολή",
|
||||
"served": "μετά το σερβίρισμα"
|
||||
},
|
||||
"approvedBy": "με έγκριση {{name}}"
|
||||
},
|
||||
"moves": {
|
||||
"orderCame": "Μεταφέρθηκε: {{path}}",
|
||||
"details": "Λεπτομέρειες",
|
||||
"orderTitle": "Μεταφορές της παραγγελίας",
|
||||
"lineTitle": "Ιστορικό μεταφορών",
|
||||
"lineSub": "Τα τραπέζια από όπου πέρασε αυτή η γραμμή",
|
||||
"lineMoved": "Ήρθε εδώ από άλλο τραπέζι",
|
||||
"movedShort": "μεταφ.",
|
||||
"lines_one": "{{count}} γραμμή",
|
||||
"lines_other": "{{count}} γραμμές",
|
||||
"kind": {
|
||||
"table_transfer": "Όλο το τραπέζι",
|
||||
"items_moved": "Μεταφορά γραμμών",
|
||||
"orders_merged": "Ένωση τραπεζιών"
|
||||
}
|
||||
},
|
||||
"oneMore": {
|
||||
"label": "Άλλο ένα",
|
||||
"send": "Αποστολή +{{count}}"
|
||||
},
|
||||
"quantity": {
|
||||
"title": "Αλλαγή ποσότητας",
|
||||
"actionSub": "Διόρθωση ποσότητας· δεν ξαναστέλνεται στην κουζίνα",
|
||||
"now": "Τώρα",
|
||||
"new": "Νέα",
|
||||
"less": "Ένα λιγότερο",
|
||||
"more": "Ένα ακόμη",
|
||||
"save": "Αποθήκευση",
|
||||
"upNote_one": "{{count}} ακόμη, χωρίς νέο δελτίο",
|
||||
"upNote_other": "{{count}} ακόμη, χωρίς νέο δελτίο",
|
||||
"downNote_one": "{{count}} θα ακυρωθεί",
|
||||
"downNote_other": "{{count}} θα ακυρωθούν",
|
||||
"noChange": "Αλλάξτε τη με − και +",
|
||||
"onlyUp": "Σε αυτό το κατάστημα οι ποσότητες μόνο αυξάνονται.",
|
||||
"sendCancel": "Αποστολή ακύρωσης στην κουζίνα"
|
||||
},
|
||||
"split": {
|
||||
"button": "Διαχωρισμός ποσού",
|
||||
"title": "Διαχωρισμός ποσού",
|
||||
"items_one": "{{count}} είδος",
|
||||
"items_other": "{{count}} είδη",
|
||||
"partsLabel": "μέρη",
|
||||
"fewer": "Ένα μέρος λιγότερο",
|
||||
"more": "Ένα μέρος ακόμη",
|
||||
"equal": "Ίσα μέρη",
|
||||
"custom": "Διαφορετικά ποσά",
|
||||
"ratio": "Πώς μοιράζεται",
|
||||
"firstAmount": "Το μέρος 1 πληρώνει",
|
||||
"part": "Μέρος {{n}} από {{of}}",
|
||||
"invalid": "Αυτό το ποσό δεν μοιράζεται έτσι.",
|
||||
"howItWorks": "Τα είδη εξοφλούνται μαζί· κάθε μέρος πληρώνεται μετά χωριστά (μετρητά, κάρτα ή καρτέλα). Αναιρείται μέχρι να πληρωθεί ένα μέρος.",
|
||||
"confirm_one": "Διαχωρισμός σε {{count}} μέρος",
|
||||
"confirm_other": "Διαχωρισμός σε {{count}} μέρη",
|
||||
"bill_one": "Διαχωρισμός · {{count}} μέρος από {{total}}",
|
||||
"bill_other": "Διαχωρισμός · {{count}} μέρη από {{total}}",
|
||||
"billPaid": "Πληρώθηκαν {{paid}} · απομένουν {{due}}",
|
||||
"undo": "Αναίρεση",
|
||||
"settled": "Διαχωρισμός",
|
||||
"settledHint": "Εξοφλείται από διαχωρισμένο λογαριασμό: τα μέρη του το πληρώνουν.",
|
||||
"err": {
|
||||
"split": "Ο λογαριασμός δεν διαχωρίστηκε.",
|
||||
"undo": "Ο διαχωρισμός δεν αναιρέθηκε."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"invalid_credentials": "Wrong username or password.",
|
||||
"session_ended": "Your session has ended. Please log in again.",
|
||||
"session_exists": "You're already logged in on another {{client}}. Log out there first.",
|
||||
"session_elsewhere": "You're signed in on another device ({{device}}, since {{since}}). Continue? It will be signed out.",
|
||||
"login_mode_not_allowed": "This way of logging in isn't enabled ({{mode}}).",
|
||||
"mode_needs_device": "Logging in by {{mode}} only works on a paired device.",
|
||||
"username_required": "Enter your username.",
|
||||
@@ -102,7 +103,16 @@
|
||||
"discounts_off": "Discounts are turned off for this venue.",
|
||||
"no_customer": "Give the order a customer first.",
|
||||
"item_not_tabbable": "This item is already {{status}}: it can't go on a tab.",
|
||||
"product_unavailable": "Product {{product_id}} isn't available."
|
||||
"product_unavailable": "Product {{product_id}} isn't available.",
|
||||
"price_change_off": "Changing prices by hand is turned off for this venue.",
|
||||
"price_change_sent_off": "Prices can only be changed before the items are sent.",
|
||||
"price_reason_required": "Say why the price changes.",
|
||||
"one_more_off": "\"One more\" isn't turned on for this product.",
|
||||
"one_more_line": "This line can't be ordered again with one tap.",
|
||||
"quantity_change_off": "Changing quantities is turned off for this venue.",
|
||||
"quantity_remove_off": "Quantities can only go up at this venue.",
|
||||
"quantity_invalid": "Choose a whole number from 1 to {{max}}.",
|
||||
"quantity_line": "This line's quantity can't be changed here."
|
||||
},
|
||||
"notification": {
|
||||
"not_found": "Notification {{notification_id}} not found."
|
||||
@@ -366,5 +376,14 @@
|
||||
"scene": {
|
||||
"not_found": "Scene not found.",
|
||||
"until_past": "That time has already passed: pick a later one."
|
||||
},
|
||||
"split": {
|
||||
"not_allowed": "Splitting a bill this way isn't turned on for this venue.",
|
||||
"lines_changed": "Some of these items were paid or changed meanwhile. Look again.",
|
||||
"amount_invalid": "Each part must be more than 0 and less than the total ({{total}}).",
|
||||
"part_locked": "This is part of a split bill: undo the split to change it.",
|
||||
"not_found": "That split bill isn't there any more.",
|
||||
"paid_already": "A part is already paid or on a tab: the split can't be undone.",
|
||||
"parts_unpaid": "Parts of a split bill are still unpaid: take their payment first."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,8 @@
|
||||
"media": "Media",
|
||||
"signage": "Signage",
|
||||
"main": "Main menu",
|
||||
"scenes": "Scenes"
|
||||
"scenes": "Scenes",
|
||||
"reportsMoves": "Moves"
|
||||
},
|
||||
"profile": {
|
||||
"edit": "Edit profile",
|
||||
@@ -221,7 +222,12 @@
|
||||
"linkHint": "For example a customer display that shows a counter POS's order.",
|
||||
"full": "{{label}}: the license allows {{max}}, all in use. Remove one or ask for a bigger license.",
|
||||
"noApps": "No device app is turned on. Turn one on in Apps first.",
|
||||
"signInTip": "PIN or password: each person signs in. Tap your name: anyone switches user without a secret (a shared counter). None: the screen works without a user (a kitchen display)."
|
||||
"signInTip": "PIN or password: each person signs in. Tap your name: anyone switches user without a secret (a shared counter). None: the screen works without a user (a kitchen display).",
|
||||
"usernames": "Staff type their username",
|
||||
"usernamesDefault": "Venue default ({{value}})",
|
||||
"usernamesYes": "Yes",
|
||||
"usernamesNo": "No, they pick their name",
|
||||
"usernamesTip": "Yes: the screen lists nobody and asks for a username, then the PIN or password. \"Tap your name\" can't be used with it."
|
||||
},
|
||||
"actions": {
|
||||
"rename": "Rename",
|
||||
@@ -362,7 +368,12 @@
|
||||
"empty": "Nothing new. Licence, printing and support alerts show up here.",
|
||||
"markAll": "Mark all as read",
|
||||
"times_one": "{{count}} time",
|
||||
"times_other": "{{count}} times"
|
||||
"times_other": "{{count}} times",
|
||||
"dayOpened": "The day is open",
|
||||
"actions": {
|
||||
"open_day": "Open now",
|
||||
"overview": "Go to the overview"
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"saved": "Saved",
|
||||
@@ -388,7 +399,8 @@
|
||||
"session": {
|
||||
"off": "Allowed on several devices",
|
||||
"refuse_new": "Refuse a second sign-in",
|
||||
"end_old": "Sign out the older one"
|
||||
"end_old": "Sign out the older one",
|
||||
"ask": "Ask, then sign out the other phone"
|
||||
},
|
||||
"signIn": {
|
||||
"title": "Sign-in",
|
||||
@@ -403,8 +415,13 @@
|
||||
"requireUsernameHint": "Instead of picking their name from the list.",
|
||||
"device": "On paired devices (kitchen display, counter POS), staff sign in with",
|
||||
"deviceHint": "Each device can choose its own on the Devices page.",
|
||||
"terminalUsername": "On paired devices, staff type their username",
|
||||
"terminalUsernameHint": "No names are listed on the screen; \"Tap your name\" asks for the PIN instead. Each device can choose otherwise on the Devices page.",
|
||||
"terminalUsernameTip": "Someone standing at the counter can't see who works here or try a colleague's PIN by tapping names.",
|
||||
"singleManager": "One session per manager",
|
||||
"singleWaiter": "One session per waiter",
|
||||
"singleWaiterHint": "Only phones count: signing in at the counter as well is fine.",
|
||||
"singleWaiterTip": "Ask: the phone says where the waiter is already signed in and since when. Continue signs that phone out at once, and it shows why. Orders it still had to send stay on it and go out the next time someone signs in there.",
|
||||
"singleTip": "When someone is already signed in on another device: allow both, refuse the new sign-in, or sign out the older one.",
|
||||
"idle": "Sign people out after",
|
||||
"idleHint": "Days without using the app (manager, waiter app and paired devices). They sign in again next time.",
|
||||
@@ -739,6 +756,89 @@
|
||||
"spoof": "Pretend to print",
|
||||
"spoofHint": "Every print job is dropped; the apps behave as if it printed.",
|
||||
"spoofOn": "On: the printers print nothing."
|
||||
},
|
||||
"prices": {
|
||||
"title": "Prices changed by hand",
|
||||
"intro": "When staff may type a line's own price, and whether they must say why. Every change is kept: who, when, from what to what, why.",
|
||||
"when": "Staff may change a price",
|
||||
"whenHint": "Who may: \"What each role may do\" and each person's permissions.",
|
||||
"whenTip": "Never: nobody types a price, owners included. Before sending: only in the cart, before the order goes to the kitchen. Any time: also a line already sent or served (needs its own permission, \"already sent or served\").",
|
||||
"modes": {
|
||||
"off": "Never",
|
||||
"before_sending": "Before sending only",
|
||||
"anytime": "Any time"
|
||||
},
|
||||
"reason": "Ask for a reason",
|
||||
"reasonHint": "A price changed by hand can't be saved without one.",
|
||||
"reasonTip": "The reason is kept with the change and shown in the order's history and in Reports → Cancellations, discounts and price changes. The counter's % discounts don't ask: the discount says what it is.",
|
||||
"reasons": "Quick reasons",
|
||||
"reasonsHint": "Offered with one tap; staff can still type their own. None: the built-in ones.",
|
||||
"reasonItem": "Quick reason",
|
||||
"newReason": "A new quick reason…"
|
||||
},
|
||||
"quantity": {
|
||||
"title": "Changing a sent line's quantity",
|
||||
"intro": "Staff correct how many of a line there are without sending it to the kitchen again. Every change is kept in the order's history.",
|
||||
"when": "Staff may",
|
||||
"whenHint": "Who may: \"What each role may do\" and each person's permissions.",
|
||||
"whenTip": "Only add: the quantity can go up (a beer taken from the fridge), nothing is printed. Add and remove: lowering it also cancels the difference as its own cancelled line, and asks whether to send a cancellation to the kitchen. Removing needs the permission to cancel too.",
|
||||
"modes": {
|
||||
"off": "Not at all",
|
||||
"add_only": "Only add",
|
||||
"add_and_remove": "Add and remove"
|
||||
}
|
||||
},
|
||||
"split": {
|
||||
"title": "Splitting a bill by amount",
|
||||
"intro": "Staff split a bill into parts that are paid on their own: the lines are settled together and each part is paid in cash, by card or on a tab.",
|
||||
"when": "Staff may split",
|
||||
"whenHint": "Who may: \"What each role may do\" and each person's permissions.",
|
||||
"whenTip": "Each choice includes the ones before. Half and half: two equal parts. Two parts, any amounts: also a ratio, or what part 1 pays. Into equal parts: 2 up to the most below, the remainder of a cent on the last part. A split can be undone until a part is paid. The receipt is the lines themselves, printed when the last part is paid.",
|
||||
"levels": {
|
||||
"off": "Not at all",
|
||||
"two_equal": "Half and half",
|
||||
"two_custom": "Two parts, any amounts",
|
||||
"multiple_equal": "Into equal parts (and two any amounts)"
|
||||
},
|
||||
"max": "The most equal parts",
|
||||
"maxHint": "The parts start at the table's customers when it has some."
|
||||
},
|
||||
"autoDay": {
|
||||
"title": "Opening and closing the day",
|
||||
"intro": "The business day can open and close by itself, at the opening hours (Schedule page) or at a time of its own. It works without the internet.",
|
||||
"open": "The day opens",
|
||||
"openHint": "A day a manager closed by hand isn't reopened before the next opening.",
|
||||
"openTip": "At the opening hours: the day opens when the hours start. At a time: every day at that time, whatever the hours. Only alert: managers get a message that stays until the day is opened, with an \"Open now\" button.",
|
||||
"close": "The day closes",
|
||||
"closeHint": "Closes only when every table is closed; otherwise you're alerted and it tries again every 15 minutes.",
|
||||
"closeTip": "Open shifts end as with a manual close. If the server was off at closing time, the day isn't closed later by itself: you're alerted instead.",
|
||||
"modes": {
|
||||
"open": {
|
||||
"off": "By hand",
|
||||
"schedule": "By itself at the opening hours",
|
||||
"time": "By itself at a time",
|
||||
"alert": "Only alert at the opening hours"
|
||||
},
|
||||
"close": {
|
||||
"off": "By hand",
|
||||
"schedule": "By itself at the end of the opening hours",
|
||||
"time": "By itself at a time",
|
||||
"alert": "Only alert at the end of the opening hours"
|
||||
}
|
||||
},
|
||||
"openTime": "Opens at",
|
||||
"closeTime": "Closes at",
|
||||
"openOffset": "Open earlier",
|
||||
"closeOffset": "Close later",
|
||||
"offsetNone": "Exactly at the hours",
|
||||
"before_one": "{{count}} minute before",
|
||||
"before_other": "{{count}} minutes before",
|
||||
"after_one": "{{count}} minute after",
|
||||
"after_other": "{{count}} minutes after",
|
||||
"ignoreBreak": "One day across the break",
|
||||
"ignoreBreakHint": "Off: the break between two opening spans closes the day and the next span opens a new one.",
|
||||
"ignoreBreakTip": "With hours 12:00–16:00 and 19:00–23:00: on = one day from 12:00 to 23:00; off = two days.",
|
||||
"noHours": "No opening hours yet: set them on the Schedule page, or nothing happens."
|
||||
}
|
||||
},
|
||||
"logs": {
|
||||
@@ -2290,7 +2390,8 @@
|
||||
"event": {
|
||||
"waiter_discount": "Discount",
|
||||
"free_item_added": "Free",
|
||||
"modifier_applied": "Price change"
|
||||
"modifier_applied": "Price change",
|
||||
"manual_price": "Price changed by hand"
|
||||
}
|
||||
},
|
||||
"orderStatus": {
|
||||
@@ -2792,7 +2893,10 @@
|
||||
"availableTip": "Off: it disappears from the waiters' and the counter's menus until you switch it back on (sold out today). Nothing else about it changes.",
|
||||
"quickAddTip": "On: one tap in the waiter's product list adds it straight to the order without opening its choices. Leave it off for products whose choices must be picked (cooking, sides).",
|
||||
"vatGroupTip": "The VAT rate the fiscal receipt uses for this product. Needed before it can be paid while the fiscal device is on.",
|
||||
"costTip": "What one unit costs you (ingredients, packaging). Reports use it for the profit; products without a cost make the profit a lower estimate."
|
||||
"costTip": "What one unit costs you (ingredients, packaging). Reports use it for the profit; products without a cost make the profit a lower estimate.",
|
||||
"oneMore": "One more (+1)",
|
||||
"oneMoreHint": "A sent line of this product gets a +1 button on the phones and the counter.",
|
||||
"oneMoreTip": "For what tables keep ordering again (beers, coffees). +1 orders the same again, with the same choices and note, at today's price, and sends it to the kitchen or bar like any new order. Off by default."
|
||||
}
|
||||
},
|
||||
"menuTabletSettings": {
|
||||
@@ -3266,7 +3370,8 @@
|
||||
"tabs": {
|
||||
"order": "Order",
|
||||
"prices": "Price changes",
|
||||
"history": "History"
|
||||
"history": "History",
|
||||
"moves": "Moves"
|
||||
},
|
||||
"payAll": "Pay everything",
|
||||
"close": "Close",
|
||||
@@ -3311,7 +3416,8 @@
|
||||
"paid": "Paid",
|
||||
"cancelled": "Cancelled",
|
||||
"tabbed": "On the tab",
|
||||
"closed": "Written off"
|
||||
"closed": "Written off",
|
||||
"split": "In a split bill"
|
||||
},
|
||||
"without": "Without {{list}}",
|
||||
"added": "{{time}} · {{name}}",
|
||||
@@ -3368,7 +3474,14 @@
|
||||
"PAYMENT_OFFLINE": "Payment (offline)",
|
||||
"ORDER_CLOSED": "Closed",
|
||||
"ORDER_CANCELLED": "Cancelled",
|
||||
"ITEM_CANCELLED": "Line cancelled"
|
||||
"ITEM_CANCELLED": "Line cancelled",
|
||||
"PRICE_CHANGED": "Price changed",
|
||||
"PRICE_SET_BY_HAND": "Price set by hand (approved)",
|
||||
"QUANTITY_CHANGED": "Quantity changed",
|
||||
"ITEM_REORDERED": "One more",
|
||||
"SPLIT_CREATED": "Bill split",
|
||||
"SPLIT_UNDONE": "Split undone",
|
||||
"SPLIT_SETTLED": "Split bill paid"
|
||||
},
|
||||
"price": {
|
||||
"modifier_applied": "Price rule",
|
||||
@@ -3377,7 +3490,14 @@
|
||||
"deal_offer_accepted": "Deal accepted",
|
||||
"deal_offer_dismissed": "Deal declined",
|
||||
"waiter_discount": "Discount",
|
||||
"free_item_added": "Free item"
|
||||
"free_item_added": "Free item",
|
||||
"manual_price": "Price changed by hand"
|
||||
},
|
||||
"approvedBy": "approved by {{name}}",
|
||||
"stage": {
|
||||
"cart": "before sending",
|
||||
"sent": "after sending",
|
||||
"served": "after serving"
|
||||
}
|
||||
},
|
||||
"add": {
|
||||
@@ -3425,7 +3545,38 @@
|
||||
"saved": "Flags saved",
|
||||
"sent": "Flags saved and message sent"
|
||||
},
|
||||
"printHelp": "Tickets are tried again every 8 seconds until they print. If a printer is off or out of paper, send them to another one, or mark them handled once the kitchen knows."
|
||||
"printHelp": "Tickets are tried again every 8 seconds until they print. If a printer is off or out of paper, send them to another one, or mark them handled once the kitchen knows.",
|
||||
"moves": {
|
||||
"none": "Nothing moved on this order.",
|
||||
"wholeOrder": "The whole order: {{path}}",
|
||||
"linePath": "moved: {{path}}",
|
||||
"lines_one": "{{count}} line",
|
||||
"lines_other": "{{count}} lines",
|
||||
"kind": {
|
||||
"table_transfer": "Whole table",
|
||||
"items_moved": "Lines moved",
|
||||
"orders_merged": "Tables joined"
|
||||
}
|
||||
},
|
||||
"split": {
|
||||
"button": "Split the amount",
|
||||
"fewer": "One part less",
|
||||
"more": "One part more",
|
||||
"equal": "Equal parts",
|
||||
"custom": "Different amounts",
|
||||
"first": "Part 1 pays",
|
||||
"part": "Part {{n}} of {{of}}",
|
||||
"invalid": "This amount can't be split that way.",
|
||||
"hint": "The lines are settled together; each part is then paid on its own (cash, card or a tab). It can be undone until a part is paid.",
|
||||
"confirm_one": "Split into {{count}} part",
|
||||
"confirm_other": "Split into {{count}} parts",
|
||||
"done": "The bill is split: pay each part on its own.",
|
||||
"undone": "The split was undone.",
|
||||
"bill_one": "Split bill · {{count}} part of {{total}}",
|
||||
"bill_other": "Split bill · {{count}} parts of {{total}}",
|
||||
"paid": "Paid {{paid}} · still due {{due}}",
|
||||
"undo": "Undo the split"
|
||||
}
|
||||
},
|
||||
"printing": {
|
||||
"back": "Back",
|
||||
@@ -3973,7 +4124,10 @@
|
||||
"anyTable": "Any table",
|
||||
"cancelledLines": "Cancelled lines",
|
||||
"ordersCount_one": "{{count}} order · {{total}}",
|
||||
"ordersCount_other": "{{count}} orders · {{total}}"
|
||||
"ordersCount_other": "{{count}} orders · {{total}}",
|
||||
"autoBoth": "Opened and closed by itself",
|
||||
"autoOpened": "Opened by itself",
|
||||
"autoClosed": "Closed by itself"
|
||||
},
|
||||
"traffic": {
|
||||
"orders": "Orders",
|
||||
@@ -4069,7 +4223,7 @@
|
||||
}
|
||||
},
|
||||
"misc": {
|
||||
"title": "Cancellations and discounts",
|
||||
"title": "Cancellations, discounts and price changes",
|
||||
"cancellations": "Cancellations",
|
||||
"discounts": "Discounts",
|
||||
"when": "When",
|
||||
@@ -4093,7 +4247,18 @@
|
||||
"discountTotal": "Total off",
|
||||
"alreadyOff": "already taken off the revenue",
|
||||
"times_one": "{{count}} time",
|
||||
"times_other": "{{count}} times"
|
||||
"times_other": "{{count}} times",
|
||||
"priceChanges": "Price changes",
|
||||
"priceWas": "Was",
|
||||
"priceNow": "Became",
|
||||
"stage": "When",
|
||||
"changedBy": "Changed by",
|
||||
"approvedBy": "Approved by",
|
||||
"changes": "Prices changed",
|
||||
"changesValue": "Difference",
|
||||
"changesValueTip": "What the changes added (+) or took off (−), for each line's quantity at the time of the change.",
|
||||
"changesCount_one": "{{count}} change",
|
||||
"changesCount_other": "{{count}} changes"
|
||||
},
|
||||
"tech": {
|
||||
"title": "Technical",
|
||||
@@ -4155,6 +4320,23 @@
|
||||
"dueDate": "Due by {{date}}",
|
||||
"payments": "Payments",
|
||||
"noPayments": "Nothing paid yet."
|
||||
},
|
||||
"moves": {
|
||||
"title": "Moves between tables",
|
||||
"kind": "What",
|
||||
"from": "From",
|
||||
"to": "To",
|
||||
"lines": "Lines",
|
||||
"by": "By",
|
||||
"allKinds": "Every kind",
|
||||
"count": "Moves",
|
||||
"list": "Every move",
|
||||
"listTip": "A whole table moved to a free one, lines moved to another table, or two tables joined. Each line keeps its moves wherever it ends up, even split or moved again.",
|
||||
"kinds": {
|
||||
"table_transfer": "Whole table",
|
||||
"items_moved": "Lines moved",
|
||||
"orders_merged": "Tables joined"
|
||||
}
|
||||
}
|
||||
},
|
||||
"finance": {
|
||||
|
||||
@@ -454,14 +454,20 @@
|
||||
"cancel": "Cancel items already sent"
|
||||
},
|
||||
"prices": {
|
||||
"modify": "Change an item's price"
|
||||
"modify": "Change an item's price before it is sent",
|
||||
"modify_sent": "Change the price of an item already sent or served",
|
||||
"view_changes": "See prices changed by hand (who, when, why)"
|
||||
},
|
||||
"business_day": {
|
||||
"manage": "Open and close the business day"
|
||||
},
|
||||
"refunds": "Refund payments from other shifts",
|
||||
"payments": {
|
||||
"revert": "Turn paid items back to unpaid"
|
||||
"revert": "Turn paid items back to unpaid",
|
||||
"split_amount": "Split a bill by amount (equal parts or a ratio)"
|
||||
},
|
||||
"items": {
|
||||
"change_quantity": "Change a sent line's quantity (no new ticket)"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -14,7 +14,10 @@
|
||||
"submit": "Sign in",
|
||||
"back": "Back",
|
||||
"empty": "Nobody can sign in here yet",
|
||||
"emptyBody": "Give someone the {{app}} permission under Staff in the manager."
|
||||
"emptyBody": "Give someone the {{app}} permission under Staff in the manager.",
|
||||
"username": "Username",
|
||||
"next": "Next",
|
||||
"typeUsername": "Type your username"
|
||||
},
|
||||
"blocked": {
|
||||
"off": "{{app}} is turned off",
|
||||
@@ -215,7 +218,20 @@
|
||||
"given": "Cash given",
|
||||
"exact": "Exact: {{amount}}",
|
||||
"change": "Change: {{amount}}",
|
||||
"short": "That's less than the amount due"
|
||||
"short": "That's less than the amount due",
|
||||
"amount": "By amount",
|
||||
"confirmAmount_one": "Take {{count}} part",
|
||||
"confirmAmount_other": "Take the {{count}} parts",
|
||||
"fewerParts": "One part less",
|
||||
"moreParts": "One part more",
|
||||
"share": {
|
||||
"equal": "Equal parts",
|
||||
"custom": "Different amounts"
|
||||
},
|
||||
"firstPart": "Part 1 pays",
|
||||
"part": "Part {{n}} of {{of}}",
|
||||
"splitInvalid": "This amount can't be split that way.",
|
||||
"amountHint": "The items are settled together and each part is paid now, by cash or card."
|
||||
},
|
||||
"done": {
|
||||
"paid": "Paid {{total}}",
|
||||
@@ -281,7 +297,8 @@
|
||||
"cash": "paid · cash",
|
||||
"card": "paid · card"
|
||||
},
|
||||
"readyItem": "ready"
|
||||
"readyItem": "ready",
|
||||
"settled": "In the split bill"
|
||||
},
|
||||
"online": {
|
||||
"arrived_one": "New online order",
|
||||
@@ -466,6 +483,11 @@
|
||||
},
|
||||
"dialog": {
|
||||
"close": "Close"
|
||||
},
|
||||
"oneMore": {
|
||||
"send": "Send +{{count}}",
|
||||
"label": "One more",
|
||||
"sent": "{{count}} more {{name}} sent"
|
||||
}
|
||||
},
|
||||
"display": {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user