feat(backend,waiter,manager): moves between tables and orders on the record
Owner 2026-11-23 (plan 6F.4). services/moves.py: every table transfer, lines moved and orders merged
is an order_moves row with its lines (order_move_items: line, quantity then); OrderItem.split_from_id
links a split part to its line, so a part carries the moves made before the split; combining moves
the removed lines' moves to the kept one. Alembic 0048: the tables, the column, and a backfill from
the audit notes written before (note='backfill'). A split part now also keeps the line's price change,
kitchen state, course, cost and names (it used to restart as pending at the menu price).
GET /api/orders/{id}/moves (the order's path, each line's); GET /api/reports/moves (+ export).
Waiter: a moved order's banner (T2 -> T5), moved lines marked, a line's Move history. Manager: the
order's Moves tab, each moved line's path, Reports -> Moves.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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')
|
||||||
@@ -133,6 +133,9 @@ class OrderItem(Base):
|
|||||||
# Deal binding — which deal created this item, and which original item it's linked to
|
# Deal binding — which deal created this item, and which original item it's linked to
|
||||||
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
||||||
linked_item_id = Column(Integer, ForeignKey("order_items.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)
|
||||||
|
|
||||||
order = relationship("Order", back_populates="items")
|
order = relationship("Order", back_populates="items")
|
||||||
product = relationship("Product", back_populates="order_items")
|
product = relationship("Product", back_populates="order_items")
|
||||||
@@ -261,3 +264,34 @@ def _snapshot_item_names(session, flush_context, instances):
|
|||||||
cat = session.get(Category, obj.category_id)
|
cat = session.get(Category, obj.category_id)
|
||||||
obj.category_name = cat.name if cat else None
|
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")
|
||||||
|
|||||||
@@ -1497,6 +1497,9 @@ def transfer_order(
|
|||||||
order.table_id = body.target_table_id
|
order.table_id = body.target_table_id
|
||||||
_audit(db, order_id, "TABLE_TRANSFER", waiter_id=user.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}")
|
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.commit()
|
||||||
db.refresh(order)
|
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"})
|
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "old_table_id": old_table_id, "status": order.status, "action": "transferred"})
|
||||||
@@ -1539,6 +1542,8 @@ def merge_order(
|
|||||||
raise XeniaError("order.same_order")
|
raise XeniaError("order.same_order")
|
||||||
|
|
||||||
# Move all items to target 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 = []
|
moved_item_ids = []
|
||||||
for item in source.items:
|
for item in source.items:
|
||||||
item.order_id = target.id
|
item.order_id = target.id
|
||||||
@@ -1627,6 +1632,11 @@ def split_item(
|
|||||||
notes=item.notes,
|
notes=item.notes,
|
||||||
status="active",
|
status="active",
|
||||||
printed=item.printed,
|
printed=item.printed,
|
||||||
|
split_from_id=item.id, # 6F.4: the moves the line had come with this part
|
||||||
|
# the rest of what the line was (kitchen, course, price, names, cost) goes with the part
|
||||||
|
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,
|
||||||
)
|
)
|
||||||
db.add(new_item)
|
db.add(new_item)
|
||||||
db.commit()
|
db.commit()
|
||||||
@@ -1683,6 +1693,20 @@ def adjust_item_price(
|
|||||||
return item
|
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")
|
@router.get("/{order_id}/price-changes")
|
||||||
def order_price_changes(order_id: int, db: Session = Depends(get_db),
|
def order_price_changes(order_id: int, db: Session = Depends(get_db),
|
||||||
user: User = Depends(require("ordering.prices.view_changes"))):
|
user: User = Depends(require("ordering.prices.view_changes"))):
|
||||||
@@ -1962,6 +1986,8 @@ def move_items(
|
|||||||
if not items:
|
if not items:
|
||||||
raise XeniaError("order.no_active_items")
|
raise XeniaError("order.no_active_items")
|
||||||
|
|
||||||
|
from services import moves # 6F.4
|
||||||
|
moves.record(db, kind="items_moved", source=source, target=target, items=items, user_id=user.id)
|
||||||
moved_ids = []
|
moved_ids = []
|
||||||
for item in items:
|
for item in items:
|
||||||
item.order_id = target.id
|
item.order_id = target.id
|
||||||
@@ -2164,6 +2190,8 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
|
|||||||
rest_ids = [i.id for i in rest]
|
rest_ids = [i.id for i in rest]
|
||||||
db.query(PriceEventLog).filter(PriceEventLog.order_item_id.in_(rest_ids)).update(
|
db.query(PriceEventLog).filter(PriceEventLog.order_item_id.in_(rest_ids)).update(
|
||||||
{PriceEventLog.order_item_id: keep.id}, synchronize_session=False)
|
{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:
|
for i in rest:
|
||||||
db.delete(i)
|
db.delete(i)
|
||||||
_audit(db, order_id, "ITEMS_COMBINED", waiter_id=user.id, item_ids=[keep.id] + rest_ids,
|
_audit(db, order_id, "ITEMS_COMBINED", waiter_id=user.id, item_ids=[keep.id] + rest_ids,
|
||||||
|
|||||||
@@ -1872,6 +1872,72 @@ def print_prep_zone(
|
|||||||
# Phase 2L — Discount audit report
|
# 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")
|
@router.get("/price-changes")
|
||||||
def price_changes_report(
|
def price_changes_report(
|
||||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ class OrderItemOut(BaseModel):
|
|||||||
source: Optional[str] = None # waiter | counter | qr | online (4.8); None = before 4.8
|
source: Optional[str] = None # waiter | counter | qr | online (4.8); None = before 4.8
|
||||||
deal_id: Optional[int] = None
|
deal_id: Optional[int] = None
|
||||||
linked_item_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)
|
system_key: Optional[str] = None # a line the system added: "delivery_fee" (phase 3S, S.5)
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
model_config = {"from_attributes": True}
|
||||||
|
|||||||
@@ -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,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
|
||||||
@@ -58,6 +58,7 @@ import PrepZonesPage from './pages/reports/prepzones/PrepZonesReport'
|
|||||||
import ExpensesReportPage from './pages/reports/expenses/ExpensesReport'
|
import ExpensesReportPage from './pages/reports/expenses/ExpensesReport'
|
||||||
import TechnicalPage from './pages/reports/technical/TechnicalReport'
|
import TechnicalPage from './pages/reports/technical/TechnicalReport'
|
||||||
import MiscPage from './pages/reports/misc/MiscReport'
|
import MiscPage from './pages/reports/misc/MiscReport'
|
||||||
|
import MovesPage from './pages/reports/moves/MovesReport'
|
||||||
|
|
||||||
// Other
|
// Other
|
||||||
import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage'
|
import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage'
|
||||||
@@ -172,6 +173,7 @@ export default function App() {
|
|||||||
<Route path="reports/expenses" element={<ExpensesReportPage />} />
|
<Route path="reports/expenses" element={<ExpensesReportPage />} />
|
||||||
<Route path="reports/technical" element={<TechnicalPage />} />
|
<Route path="reports/technical" element={<TechnicalPage />} />
|
||||||
<Route path="reports/misc" element={<MiscPage />} />
|
<Route path="reports/misc" element={<MiscPage />} />
|
||||||
|
<Route path="reports/moves" element={<MovesPage />} />
|
||||||
|
|
||||||
{/* ── Apps & Settings ── */}
|
{/* ── Apps & Settings ── */}
|
||||||
<Route path="apps" element={<AppsPage />} />
|
<Route path="apps" element={<AppsPage />} />
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||||
import { EmptyState, cx } from '@xenia/ui'
|
import { EmptyState, cx } from '@xenia/ui'
|
||||||
import { Pill } from '../overview/parts'
|
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 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 [] } }
|
const ids = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
|
||||||
@@ -76,3 +76,44 @@ export function PriceEventList({ events }) {
|
|||||||
</ul>
|
</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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,12 +12,12 @@ import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
|
|||||||
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
|
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
|
||||||
import client from '../../api/client'
|
import client from '../../api/client'
|
||||||
import { Pill } from '../overview/parts'
|
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 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', manual_price: 'text-warning-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 { t } = useTranslation('manager')
|
||||||
const { formatMoney, formatTime } = useFormat()
|
const { formatMoney, formatTime } = useFormat()
|
||||||
const canDiscount = useCan('pricing.discounts.apply')
|
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.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.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>}
|
{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">
|
<div className="text-caption text-ink-3">
|
||||||
{t('orders.lines.added', { time: formatTime(item.added_at), name: item.added_by_name ?? '' })}
|
{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 })}`}
|
{item.paid_by_name && ` · ${t('orders.lines.paidBy', { name: item.paid_by_name })}`}
|
||||||
|
|||||||
@@ -21,12 +21,12 @@ import OrderLines from './OrderLines'
|
|||||||
import OrderPeople from './OrderPeople'
|
import OrderPeople from './OrderPeople'
|
||||||
import PayDialog from './PayDialog'
|
import PayDialog from './PayDialog'
|
||||||
import PrintProblemsCard from './PrintProblemsCard'
|
import PrintProblemsCard from './PrintProblemsCard'
|
||||||
import { AuditList, PriceEventList } from './OrderHistory'
|
import { AuditList, MoveList, PriceEventList } from './OrderHistory'
|
||||||
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
|
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
|
||||||
|
|
||||||
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
|
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 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() {
|
export default function OrderPage() {
|
||||||
const { orderId } = useParams()
|
const { orderId } = useParams()
|
||||||
@@ -90,9 +90,14 @@ function OrderView({ orderId }) {
|
|||||||
queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), events: ['order_updated'],
|
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 = () => {
|
const refresh = () => {
|
||||||
qc.invalidateQueries({ queryKey: ['order', orderId] })
|
qc.invalidateQueries({ queryKey: ['order', orderId] })
|
||||||
qc.invalidateQueries({ queryKey: ['price-events', orderId] })
|
qc.invalidateQueries({ queryKey: ['price-events', orderId] })
|
||||||
|
qc.invalidateQueries({ queryKey: ['order-moves', orderId] })
|
||||||
qc.invalidateQueries({ queryKey: ['orders-active'] })
|
qc.invalidateQueries({ queryKey: ['orders-active'] })
|
||||||
}
|
}
|
||||||
const onError = err => toast.error(errorMessage(err, t))
|
const onError = err => toast.error(errorMessage(err, t))
|
||||||
@@ -155,7 +160,7 @@ function OrderView({ orderId }) {
|
|||||||
{tab === 'order' && (
|
{tab === 'order' && (
|
||||||
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
|
<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">
|
<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 })} />
|
onPay={(ids, amount, after) => setPaying({ ids, amount, after })} />
|
||||||
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
|
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
|
||||||
</div>
|
</div>
|
||||||
@@ -163,6 +168,7 @@ function OrderView({ orderId }) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
|
{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>}
|
{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}
|
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
|
||||||
|
|||||||
@@ -104,3 +104,11 @@ export function flagsByTable(defs = [], assignments = []) {
|
|||||||
|
|
||||||
/** Where a table's card goes: its order, or a new order at that table. */
|
/** 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}`)
|
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(' → ')
|
||||||
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
// converts those routers.
|
// converts those routers.
|
||||||
// anyPerm instead of perm: any one of these keys is enough (the media library)
|
// anyPerm instead of perm: any one of these keys is enough (the media library)
|
||||||
// label a key in the i18n `manager` namespace
|
// 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'
|
const DASH = 'core.dashboard.access'
|
||||||
// The media library: whoever manages something that shows pictures (routers/media.py MANAGE)
|
// 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/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/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/misc', icon: Tag, label: 'nav.reportsMisc', module: 'reports', perm: 'reports.view' },
|
||||||
|
{ to: '/reports/moves', icon: ArrowRightLeft, label: 'nav.reportsMoves', module: 'reports', perm: 'reports.view' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -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.",
|
"_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"],
|
"paths": ["src"],
|
||||||
"strict": [
|
"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"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,7 +50,8 @@
|
|||||||
"media": "Πολυμέσα",
|
"media": "Πολυμέσα",
|
||||||
"signage": "Προβολή",
|
"signage": "Προβολή",
|
||||||
"main": "Κύριο μενού",
|
"main": "Κύριο μενού",
|
||||||
"scenes": "Σκηνές"
|
"scenes": "Σκηνές",
|
||||||
|
"reportsMoves": "Μεταφορές"
|
||||||
},
|
},
|
||||||
"profile": {
|
"profile": {
|
||||||
"edit": "Επεξεργασία προφίλ",
|
"edit": "Επεξεργασία προφίλ",
|
||||||
@@ -3286,7 +3287,8 @@
|
|||||||
"tabs": {
|
"tabs": {
|
||||||
"order": "Παραγγελία",
|
"order": "Παραγγελία",
|
||||||
"prices": "Αλλαγές τιμών",
|
"prices": "Αλλαγές τιμών",
|
||||||
"history": "Ιστορικό"
|
"history": "Ιστορικό",
|
||||||
|
"moves": "Μεταφορές"
|
||||||
},
|
},
|
||||||
"payAll": "Πληρωμή όλων",
|
"payAll": "Πληρωμή όλων",
|
||||||
"close": "Κλείσιμο",
|
"close": "Κλείσιμο",
|
||||||
@@ -3454,7 +3456,19 @@
|
|||||||
"saved": "Οι σημαίες αποθηκεύτηκαν",
|
"saved": "Οι σημαίες αποθηκεύτηκαν",
|
||||||
"sent": "Σημαίες αποθηκεύτηκαν και το μήνυμα στάλθηκε"
|
"sent": "Σημαίες αποθηκεύτηκαν και το μήνυμα στάλθηκε"
|
||||||
},
|
},
|
||||||
"printHelp": "Τα δελτία ξαναδοκιμάζονται κάθε 8 δευτερόλεπτα μέχρι να τυπωθούν. Αν ένας εκτυπωτής είναι κλειστός ή χωρίς χαρτί, στείλτε τα σε άλλον, ή σημειώστε ότι τα χειριστήκατε όταν μάθει η κουζίνα."
|
"printHelp": "Τα δελτία ξαναδοκιμάζονται κάθε 8 δευτερόλεπτα μέχρι να τυπωθούν. Αν ένας εκτυπωτής είναι κλειστός ή χωρίς χαρτί, στείλτε τα σε άλλον, ή σημειώστε ότι τα χειριστήκατε όταν μάθει η κουζίνα.",
|
||||||
|
"moves": {
|
||||||
|
"none": "Τίποτα δεν μεταφέρθηκε σε αυτή την παραγγελία.",
|
||||||
|
"wholeOrder": "Όλη η παραγγελία: {{path}}",
|
||||||
|
"linePath": "μεταφέρθηκε: {{path}}",
|
||||||
|
"lines_one": "{{count}} γραμμή",
|
||||||
|
"lines_other": "{{count}} γραμμές",
|
||||||
|
"kind": {
|
||||||
|
"table_transfer": "Όλο το τραπέζι",
|
||||||
|
"items_moved": "Μεταφορά γραμμών",
|
||||||
|
"orders_merged": "Ένωση τραπεζιών"
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"printing": {
|
"printing": {
|
||||||
"back": "Πίσω",
|
"back": "Πίσω",
|
||||||
@@ -4195,6 +4209,23 @@
|
|||||||
"dueDate": "Λήξη {{date}}",
|
"dueDate": "Λήξη {{date}}",
|
||||||
"payments": "Πληρωμές",
|
"payments": "Πληρωμές",
|
||||||
"noPayments": "Δεν έχει πληρωθεί τίποτα ακόμα."
|
"noPayments": "Δεν έχει πληρωθεί τίποτα ακόμα."
|
||||||
|
},
|
||||||
|
"moves": {
|
||||||
|
"title": "Μεταφορές μεταξύ τραπεζιών",
|
||||||
|
"kind": "Τι",
|
||||||
|
"from": "Από",
|
||||||
|
"to": "Προς",
|
||||||
|
"lines": "Γραμμές",
|
||||||
|
"by": "Από ποιον",
|
||||||
|
"allKinds": "Όλα τα είδη",
|
||||||
|
"count": "Μεταφορές",
|
||||||
|
"list": "Όλες οι μεταφορές",
|
||||||
|
"listTip": "Ολόκληρο τραπέζι σε ελεύθερο, γραμμές σε άλλο τραπέζι, ή ένωση δύο τραπεζιών. Κάθε γραμμή κρατά τις μεταφορές της όπου κι αν καταλήξει, ακόμη κι αν χωριστεί ή μεταφερθεί ξανά.",
|
||||||
|
"kinds": {
|
||||||
|
"table_transfer": "Όλο το τραπέζι",
|
||||||
|
"items_moved": "Μεταφορά γραμμών",
|
||||||
|
"orders_merged": "Ένωση τραπεζιών"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"finance": {
|
"finance": {
|
||||||
|
|||||||
@@ -880,5 +880,21 @@
|
|||||||
"served": "μετά το σερβίρισμα"
|
"served": "μετά το σερβίρισμα"
|
||||||
},
|
},
|
||||||
"approvedBy": "με έγκριση {{name}}"
|
"approvedBy": "με έγκριση {{name}}"
|
||||||
|
},
|
||||||
|
"moves": {
|
||||||
|
"orderCame": "Μεταφέρθηκε: {{path}}",
|
||||||
|
"details": "Λεπτομέρειες",
|
||||||
|
"orderTitle": "Μεταφορές της παραγγελίας",
|
||||||
|
"lineTitle": "Ιστορικό μεταφορών",
|
||||||
|
"lineSub": "Τα τραπέζια από όπου πέρασε αυτή η γραμμή",
|
||||||
|
"lineMoved": "Ήρθε εδώ από άλλο τραπέζι",
|
||||||
|
"movedShort": "μεταφ.",
|
||||||
|
"lines_one": "{{count}} γραμμή",
|
||||||
|
"lines_other": "{{count}} γραμμές",
|
||||||
|
"kind": {
|
||||||
|
"table_transfer": "Όλο το τραπέζι",
|
||||||
|
"items_moved": "Μεταφορά γραμμών",
|
||||||
|
"orders_merged": "Ένωση τραπεζιών"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,7 +50,8 @@
|
|||||||
"media": "Media",
|
"media": "Media",
|
||||||
"signage": "Signage",
|
"signage": "Signage",
|
||||||
"main": "Main menu",
|
"main": "Main menu",
|
||||||
"scenes": "Scenes"
|
"scenes": "Scenes",
|
||||||
|
"reportsMoves": "Moves"
|
||||||
},
|
},
|
||||||
"profile": {
|
"profile": {
|
||||||
"edit": "Edit profile",
|
"edit": "Edit profile",
|
||||||
@@ -3286,7 +3287,8 @@
|
|||||||
"tabs": {
|
"tabs": {
|
||||||
"order": "Order",
|
"order": "Order",
|
||||||
"prices": "Price changes",
|
"prices": "Price changes",
|
||||||
"history": "History"
|
"history": "History",
|
||||||
|
"moves": "Moves"
|
||||||
},
|
},
|
||||||
"payAll": "Pay everything",
|
"payAll": "Pay everything",
|
||||||
"close": "Close",
|
"close": "Close",
|
||||||
@@ -3454,7 +3456,19 @@
|
|||||||
"saved": "Flags saved",
|
"saved": "Flags saved",
|
||||||
"sent": "Flags saved and message sent"
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"printing": {
|
"printing": {
|
||||||
"back": "Back",
|
"back": "Back",
|
||||||
@@ -4195,6 +4209,23 @@
|
|||||||
"dueDate": "Due by {{date}}",
|
"dueDate": "Due by {{date}}",
|
||||||
"payments": "Payments",
|
"payments": "Payments",
|
||||||
"noPayments": "Nothing paid yet."
|
"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": {
|
"finance": {
|
||||||
|
|||||||
@@ -880,5 +880,21 @@
|
|||||||
"served": "after serving"
|
"served": "after serving"
|
||||||
},
|
},
|
||||||
"approvedBy": "approved by {{name}}"
|
"approvedBy": "approved by {{name}}"
|
||||||
|
},
|
||||||
|
"moves": {
|
||||||
|
"orderCame": "Moved here: {{path}}",
|
||||||
|
"details": "Details",
|
||||||
|
"orderTitle": "This order's moves",
|
||||||
|
"lineTitle": "Move history",
|
||||||
|
"lineSub": "The tables this line went through",
|
||||||
|
"lineMoved": "Moved here from another table",
|
||||||
|
"movedShort": "moved",
|
||||||
|
"lines_one": "{{count}} line",
|
||||||
|
"lines_other": "{{count}} lines",
|
||||||
|
"kind": {
|
||||||
|
"table_transfer": "Whole table",
|
||||||
|
"items_moved": "Lines moved",
|
||||||
|
"orders_merged": "Tables joined"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1244,6 +1244,18 @@ try {
|
|||||||
await page.getByTestId('cancel-no-print').click()
|
await page.getByTestId('cancel-no-print').click()
|
||||||
for (let i = 0; i < 20 && !mo?.items?.some(x => x.product_id === pB.id && x.status === 'cancelled'); i++) { await sleep(250); mo = await api('GET', `/api/orders/${oid}`, { token: boss }) }
|
for (let i = 0; i < 20 && !mo?.items?.some(x => x.product_id === pB.id && x.status === 'cancelled'); i++) { await sleep(250); mo = await api('GET', `/api/orders/${oid}`, { token: boss }) }
|
||||||
r.check(`${od} a line added, then cancelled (no ticket)`, mo.items.some(x => x.product_id === pB.id && x.status === 'cancelled'))
|
r.check(`${od} a line added, then cancelled (no ticket)`, mo.items.some(x => x.product_id === pB.id && x.status === 'cancelled'))
|
||||||
|
// 6F.4: the order moved to another free table: its Moves tab shows the path, each line is marked
|
||||||
|
{
|
||||||
|
const busyNow = new Set((await api('GET', '/api/orders/', { token: boss })).map(o => o.table_id))
|
||||||
|
const freeT = (await api('GET', '/api/tables/', { token: boss })).find(x => x.is_active !== false && !busyNow.has(x.id) && x.id !== otable.id)
|
||||||
|
await api('POST', `/api/orders/${oid}/transfer`, { token: boss, body: { target_table_id: freeT.id } })
|
||||||
|
await page.reload()
|
||||||
|
await page.getByTestId('order-tab-moves').click()
|
||||||
|
r.check(`${od} a transferred order: Moves shows the whole order's path (6F.4)`,
|
||||||
|
await page.getByTestId('order-move').first().waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
|
||||||
|
await page.getByTestId('order-tab-order').click()
|
||||||
|
r.check(`${od} …and each line says where it came from`, await page.getByTestId('line-moved').first().waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
|
||||||
|
}
|
||||||
await page.screenshot({ path: path.join(OUT, 'manager-order.png'), fullPage: true })
|
await page.screenshot({ path: path.join(OUT, 'manager-order.png'), fullPage: true })
|
||||||
await page.getByTestId('order-close').click()
|
await page.getByTestId('order-close').click()
|
||||||
const payFirst = await page.getByTestId('pay-dialog').waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
|
const payFirst = await page.getByTestId('pay-dialog').waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
|
||||||
@@ -1437,6 +1449,8 @@ try {
|
|||||||
r.check(`${rp} Discounts opens`, await page.getByTestId('report-period').waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
|
r.check(`${rp} Discounts opens`, await page.getByTestId('report-period').waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
|
||||||
await page.getByTestId('report-tab-price-changes').click()
|
await page.getByTestId('report-tab-price-changes').click()
|
||||||
r.check(`${rp} Price changes opens (6F.3)`, await page.getByTestId('price-changes-count').waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
|
r.check(`${rp} Price changes opens (6F.3)`, await page.getByTestId('price-changes-count').waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
|
||||||
|
await opens('/reports/moves', 'moves-count', 'Moves (6F.4)')
|
||||||
|
r.check(`${rp} Moves lists the order moved earlier`, await page.getByTestId('report-move').first().waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
|
||||||
await opens('/reports/technical', 'printing-total', 'Technical → Printing')
|
await opens('/reports/technical', 'printing-total', 'Technical → Printing')
|
||||||
await opens('/reports/prep-zones', 'report-period', 'Prep zones')
|
await opens('/reports/prep-zones', 'report-period', 'Prep zones')
|
||||||
await opens('/reports/expenses', 'expenses-total', 'Expenses')
|
await opens('/reports/expenses', 'expenses-total', 'Expenses')
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ const PAGES = [
|
|||||||
'management/approvals', 'management/schedule', 'management/prep-zones', 'management/pricing', 'management/pricing?tab=channels',
|
'management/approvals', 'management/schedule', 'management/prep-zones', 'management/pricing', 'management/pricing?tab=channels',
|
||||||
'management/products', 'management/tables', 'management/tables?tab=floor', 'management/scenes', 'management/signage?tab=playlists', 'management/signage?tab=schedules', 'inventory/throwaways', 'notes',
|
'management/products', 'management/tables', 'management/tables?tab=floor', 'management/scenes', 'management/signage?tab=playlists', 'management/signage?tab=schedules', 'inventory/throwaways', 'notes',
|
||||||
'reports/today', 'reports/store', 'devices', 'license', 'apps', 'settings?tab=operation',
|
'reports/today', 'reports/store', 'devices', 'license', 'apps', 'settings?tab=operation',
|
||||||
'settings?tab=security', 'settings?tab=identity', 'settings?tab=print-fonts', 'settings?tab=venue',
|
'settings?tab=security', 'settings?tab=identity', 'settings?tab=print-fonts', 'settings?tab=venue', 'reports/moves',
|
||||||
]
|
]
|
||||||
const SHOTS = ['dashboard', 'tables', 'tables?view=qr', 'online-orders?tab=settings', 'crm/contacts', 'crm/customers', 'financials/expenses',
|
const SHOTS = ['dashboard', 'tables', 'tables?view=qr', 'online-orders?tab=settings', 'crm/contacts', 'crm/customers', 'financials/expenses',
|
||||||
'management/products', 'management/tables?tab=floor', 'management/pricing?tab=channels', 'financials/tabs', 'management/staff', 'settings?tab=operation']
|
'management/products', 'management/tables?tab=floor', 'management/pricing?tab=channels', 'financials/tabs', 'management/staff', 'settings?tab=operation']
|
||||||
|
|||||||
@@ -342,6 +342,19 @@ try {
|
|||||||
await a.keyboard.press('Escape').catch(() => {})
|
await a.keyboard.press('Escape').catch(() => {})
|
||||||
await setting(boss, 'orders.price_change_reason', 'false')
|
await setting(boss, 'orders.price_change_reason', 'false')
|
||||||
await api('PUT', `/api/waiters/${maria.id}/permissions`, { token: boss, body: { keys: mariaKeys } })
|
await api('PUT', `/api/waiters/${maria.id}/permissions`, { token: boss, body: { keys: mariaKeys } })
|
||||||
|
// 6F.4: the order moved to another table: the phone shows where it came from and the line's moves
|
||||||
|
const busyNow = new Set((await api('GET', '/api/orders/', { token: boss })).map(o => o.table_id))
|
||||||
|
const tq = (await api('GET', '/api/tables/', { token: boss })).find(x => x.is_active !== false && !busyNow.has(x.id) && x.id !== tp.id)
|
||||||
|
await api('POST', `/api/orders/${op.id}/transfer`, { token: boss, body: { target_table_id: tq.id } })
|
||||||
|
await a.goto(`${APP}/tables/${tq.id}`)
|
||||||
|
r.check('6F.4: a moved order says where it came from', await shown(a, 'order-moved', 10_000)
|
||||||
|
&& (await a.getByTestId('order-moved').textContent()).includes('→'))
|
||||||
|
r.check('6F.4: …and its lines are marked as moved', await shown(a, 'item-moved', 5000))
|
||||||
|
await a.locator('.order-item').first().click()
|
||||||
|
await a.getByRole('button', { name: 'ACTIONS', exact: true }).last().click()
|
||||||
|
await a.getByText('Move history').first().click({ timeout: 10_000 })
|
||||||
|
r.check('6F.4: the line\'s move history on the phone', await shown(a, 'move-row', 8000))
|
||||||
|
await a.keyboard.press('Escape').catch(() => {})
|
||||||
await setting(boss, 'orders.close_with_unpaid', 'true')
|
await setting(boss, 'orders.close_with_unpaid', 'true')
|
||||||
await api('POST', `/api/orders/${op.id}/close`, { token: boss })
|
await api('POST', `/api/orders/${op.id}/close`, { token: boss })
|
||||||
await setting(boss, 'orders.close_with_unpaid', 'false')
|
await setting(boss, 'orders.close_with_unpaid', 'false')
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// Where an order or a line came from (plan 6F.4): GET /api/orders/{id}/moves gives the whole
|
||||||
|
// order's path (table transfers, orders joined into it) and each moved line's (its own moves, and
|
||||||
|
// its parent's before it was split from it), however many times it moved.
|
||||||
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||||
|
import { pathText } from '../logic/moves'
|
||||||
|
|
||||||
|
/** The banner over a moved order: its path, tap for the details. */
|
||||||
|
export function MovedOrderBanner({ moves, onOpen }) {
|
||||||
|
const { t } = useTranslation('waiter')
|
||||||
|
if (!moves?.length) return null
|
||||||
|
return (
|
||||||
|
<button type="button" onClick={onOpen} data-testid="order-moved" style={{
|
||||||
|
width: '100%', display: 'flex', alignItems: 'center', gap: 8, margin: '0 0 8px', padding: '8px 12px', borderRadius: 10,
|
||||||
|
border: '1px solid rgb(var(--x-info-rgb) / 0.35)', background: 'rgb(var(--x-info-rgb) / 0.1)', color: 'var(--x-info)',
|
||||||
|
fontSize: 13, fontWeight: 700, cursor: 'pointer', textAlign: 'left',
|
||||||
|
}}>
|
||||||
|
<span aria-hidden="true">↪</span>
|
||||||
|
<span style={{ flex: 1 }}>{t('moves.orderCame', { path: pathText(moves) })}</span>
|
||||||
|
<span style={{ fontSize: 12, fontWeight: 600 }}>{t('moves.details')}</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function MoveHistory({ title, subtitle, moves, itemId, onClose }) {
|
||||||
|
const { t } = useTranslation('waiter')
|
||||||
|
const { formatDateTime, formatNumber } = useFormat()
|
||||||
|
return (
|
||||||
|
<div className="modal-overlay" onClick={onClose}>
|
||||||
|
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="move-history">
|
||||||
|
<div className="modal-handle" />
|
||||||
|
<h2 className="modal-title">{title}</h2>
|
||||||
|
{subtitle && <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>{subtitle}</p>}
|
||||||
|
<div style={{ display: 'grid', gap: 8 }}>
|
||||||
|
{moves.map(m => {
|
||||||
|
const mine = itemId != null ? m.items.find(i => i.item_id === itemId) : null
|
||||||
|
return (
|
||||||
|
<div key={m.id} data-testid="move-row" style={{ padding: '10px 12px', borderRadius: 12, background: 'var(--bg3)', border: '1px solid var(--border)', display: 'grid', gap: 2 }}>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, fontWeight: 700 }}>
|
||||||
|
<span>{m.from_table || '—'} → {m.to_table || '—'}</span>
|
||||||
|
<span style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 600 }}>{t(`moves.kind.${m.kind}`)}</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 12, color: 'var(--muted)' }}>
|
||||||
|
{formatDateTime(m.at, 'datetimeShort')}{m.by ? ` · ${m.by}` : ''}
|
||||||
|
{mine?.quantity != null ? ` · ×${formatNumber(mine.quantity, { maxDecimals: 3 })}` : ''}
|
||||||
|
{itemId == null ? ` · ${t('moves.lines', { count: m.items.length })}` : ''}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<button className="btn btn--secondary" style={{ width: '100%', marginTop: 16 }} onClick={onClose}>{t('common.close')}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -320,7 +320,7 @@ function MergedBadge({ item }) {
|
|||||||
|
|
||||||
// ── ItemRow ───────────────────────────────────────────────────────────────────
|
// ── ItemRow ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kdsDisplayStyle, orderItemLayout, waiterMap, courses, priceEvents }) {
|
function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kdsDisplayStyle, orderItemLayout, waiterMap, courses, priceEvents, moved = false }) {
|
||||||
const { t } = useTranslation('waiter')
|
const { t } = useTranslation('waiter')
|
||||||
const isPaid = item.status === 'paid'
|
const isPaid = item.status === 'paid'
|
||||||
const isCancelled = item.status === 'cancelled'
|
const isCancelled = item.status === 'cancelled'
|
||||||
@@ -404,6 +404,13 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
|
|||||||
{item.product?.name || `#${item.product_id}`}
|
{item.product?.name || `#${item.product_id}`}
|
||||||
{courseBadge}
|
{courseBadge}
|
||||||
{sourceBadge}
|
{sourceBadge}
|
||||||
|
{moved && (
|
||||||
|
<span data-testid="item-moved" title={t('moves.lineMoved')}
|
||||||
|
style={{ marginLeft: 6, fontSize: 10, fontWeight: 800, padding: '1px 5px', borderRadius: 4, verticalAlign: 'middle',
|
||||||
|
background: 'rgb(var(--x-info-rgb) / 0.15)', color: 'var(--x-info)', border: '1px solid rgb(var(--x-info-rgb) / 0.35)' }}>
|
||||||
|
↪ {t('moves.movedShort')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -681,7 +688,7 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function OrderSummary({ order, selectable = false, selectedIds = [], onToggle, onLongPressItem, waiterMap, courses = [], priceEventsMap = {} }) {
|
export default function OrderSummary({ order, selectable = false, selectedIds = [], onToggle, onLongPressItem, waiterMap, courses = [], priceEventsMap = {}, movedItems = {} }) {
|
||||||
const { t } = useTranslation('waiter')
|
const { t } = useTranslation('waiter')
|
||||||
const kdsDisplayStyle = useTableViewStore(s => s.kdsDisplayStyle || 'badge')
|
const kdsDisplayStyle = useTableViewStore(s => s.kdsDisplayStyle || 'badge')
|
||||||
const orderItemLayout = useTableViewStore(s => s.orderItemLayout || 'compact')
|
const orderItemLayout = useTableViewStore(s => s.orderItemLayout || 'compact')
|
||||||
@@ -710,6 +717,7 @@ export default function OrderSummary({ order, selectable = false, selectedIds =
|
|||||||
waiterMap={waiterMap}
|
waiterMap={waiterMap}
|
||||||
courses={courses}
|
courses={courses}
|
||||||
priceEvents={priceEventsMap[item.id] ?? []}
|
priceEvents={priceEventsMap[item.id] ?? []}
|
||||||
|
moved={!!movedItems[item.id]}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
<div className="order-summary__total">
|
<div className="order-summary__total">
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// Moves (plan 6F.4), plain JS so Node tests can import it.
|
||||||
|
|
||||||
|
/** "T2 → T5 → T7": the tables in the order they were visited ('—' 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(' → ')
|
||||||
|
}
|
||||||
@@ -19,6 +19,7 @@ import { parseNumber, useTranslation } from '@xenia/i18n'
|
|||||||
import PriceReason from '../components/PriceReason'
|
import PriceReason from '../components/PriceReason'
|
||||||
import { priceReasonText } from '../logic/priceRules'
|
import { priceReasonText } from '../logic/priceRules'
|
||||||
import PriceHistory from '../components/PriceHistory'
|
import PriceHistory from '../components/PriceHistory'
|
||||||
|
import MoveHistory, { MovedOrderBanner } from '../components/MoveHistory'
|
||||||
import { usePriceRules } from '../hooks/usePriceRules'
|
import { usePriceRules } from '../hooks/usePriceRules'
|
||||||
import { fade } from '../logic/colour'
|
import { fade } from '../logic/colour'
|
||||||
import SeatsHint from '../components/SeatsHint'
|
import SeatsHint from '../components/SeatsHint'
|
||||||
@@ -265,7 +266,7 @@ function PriceAdjustModal({ item, rules, error, onConfirm, onClose }) {
|
|||||||
|
|
||||||
// ─── Item action modal (long-press) ──────────────────────────────────────────
|
// ─── Item action modal (long-press) ──────────────────────────────────────────
|
||||||
|
|
||||||
function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, canSeePriceHistory, onPriceHistory, onClose }) {
|
function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, canSeePriceHistory, onPriceHistory, movedLine, onMoveHistory, onClose }) {
|
||||||
const { t } = useTranslation('waiter')
|
const { t } = useTranslation('waiter')
|
||||||
const { items, singleStacked, multiSelect } = target
|
const { items, singleStacked, multiSelect } = target
|
||||||
const label = multiSelect
|
const label = multiSelect
|
||||||
@@ -273,6 +274,21 @@ function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCance
|
|||||||
: items[0]?.product?.name || `#${items[0]?.product_id}`
|
: items[0]?.product?.name || `#${items[0]?.product_id}`
|
||||||
|
|
||||||
const actionRows = [
|
const actionRows = [
|
||||||
|
// 6F.4: where this line has been (tables, orders), however many moves
|
||||||
|
...(!multiSelect && movedLine ? [{
|
||||||
|
key: 'move_history',
|
||||||
|
color: 'var(--x-info)',
|
||||||
|
iconBg: 'rgb(var(--x-info-rgb) / 0.15)',
|
||||||
|
label: t('moves.lineTitle'),
|
||||||
|
sub: t('moves.lineSub'),
|
||||||
|
icon: (
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none">
|
||||||
|
<path d="M4 7h11l-3-3M20 17H9l3 3" stroke="var(--x-info)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
onClick: onMoveHistory,
|
||||||
|
enabled: true,
|
||||||
|
}] : []),
|
||||||
// 6F.3: who changed this line's price, when, from what, why (ordering.prices.view_changes)
|
// 6F.3: who changed this line's price, when, from what, why (ordering.prices.view_changes)
|
||||||
...(!multiSelect && canSeePriceHistory && items[0]?.price_adjustment ? [{
|
...(!multiSelect && canSeePriceHistory && items[0]?.price_adjustment ? [{
|
||||||
key: 'price_history',
|
key: 'price_history',
|
||||||
@@ -1166,6 +1182,8 @@ export default function TableDetailPage() {
|
|||||||
const [customerCountOpen, setCustomerCountOpen] = useState(false)
|
const [customerCountOpen, setCustomerCountOpen] = useState(false)
|
||||||
const [showDiscountModal, setShowDiscountModal] = useState(false)
|
const [showDiscountModal, setShowDiscountModal] = useState(false)
|
||||||
const [priceEventsMap, setPriceEventsMap] = useState({})
|
const [priceEventsMap, setPriceEventsMap] = useState({})
|
||||||
|
const [moves, setMoves] = useState({ order: [], items: {} }) // 6F.4: where the order and its lines came from
|
||||||
|
const [moveSheet, setMoveSheet] = useState(null) // { title, subtitle, moves, itemId }
|
||||||
const [cancelConfirm, setCancelConfirm] = useState(null) // null | { mode: 'items', ids: [...] } | { mode: 'order' }
|
const [cancelConfirm, setCancelConfirm] = useState(null) // null | { mode: 'items', ids: [...] } | { mode: 'order' }
|
||||||
const [paidSelectedIds, setPaidSelectedIds] = useState([])
|
const [paidSelectedIds, setPaidSelectedIds] = useState([])
|
||||||
|
|
||||||
@@ -1331,6 +1349,14 @@ export default function TableDetailPage() {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [order?.id, order?.items?.length])
|
}, [order?.id, order?.items?.length])
|
||||||
|
|
||||||
|
// 6F.4: the order's path and its moved lines (a transfer changes the table, a move the items)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!order?.id) { setMoves({ order: [], items: {} }); return }
|
||||||
|
client.get(`/api/orders/${order.id}/moves`)
|
||||||
|
.then(r => setMoves({ order: r.data?.order ?? [], items: r.data?.items ?? {} }))
|
||||||
|
.catch(() => {})
|
||||||
|
}, [order?.id, order?.items?.length, order?.table_id])
|
||||||
|
|
||||||
// Handle ?action= param from table list long-press quick actions
|
// Handle ?action= param from table list long-press quick actions
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const action = searchParams.get('action')
|
const action = searchParams.get('action')
|
||||||
@@ -1903,6 +1929,7 @@ export default function TableDetailPage() {
|
|||||||
|
|
||||||
{activeTab === 'active' && (
|
{activeTab === 'active' && (
|
||||||
<>
|
<>
|
||||||
|
<MovedOrderBanner moves={moves.order} onOpen={() => setMoveSheet({ title: t('moves.orderTitle'), moves: moves.order })} />
|
||||||
<OrderSummary
|
<OrderSummary
|
||||||
order={{ ...order, items: displayActiveItems }}
|
order={{ ...order, items: displayActiveItems }}
|
||||||
selectable={canInteract && !paying}
|
selectable={canInteract && !paying}
|
||||||
@@ -1910,6 +1937,7 @@ export default function TableDetailPage() {
|
|||||||
onToggle={toggleItem}
|
onToggle={toggleItem}
|
||||||
waiterMap={waiterMap}
|
waiterMap={waiterMap}
|
||||||
priceEventsMap={priceEventsMap}
|
priceEventsMap={priceEventsMap}
|
||||||
|
movedItems={moves.items}
|
||||||
onLongPressItem={(item) => {
|
onLongPressItem={(item) => {
|
||||||
if (selectedIds.length > 1) {
|
if (selectedIds.length > 1) {
|
||||||
const items = displayActiveItems.filter(i => selectedIds.includes(i.id))
|
const items = displayActiveItems.filter(i => selectedIds.includes(i.id))
|
||||||
@@ -2236,6 +2264,12 @@ export default function TableDetailPage() {
|
|||||||
setPriceAdjustItem(item)
|
setPriceAdjustItem(item)
|
||||||
}}
|
}}
|
||||||
canSeePriceHistory={seesPriceChanges && !isOffline}
|
canSeePriceHistory={seesPriceChanges && !isOffline}
|
||||||
|
movedLine={!!moves.items[itemActionTarget.items[0]?.id]}
|
||||||
|
onMoveHistory={() => {
|
||||||
|
const item = itemActionTarget.items[0]
|
||||||
|
setItemActionTarget(null)
|
||||||
|
setMoveSheet({ title: t('moves.lineTitle'), subtitle: item.product_name || item.product?.name, moves: moves.items[item.id] ?? [], itemId: item.id })
|
||||||
|
}}
|
||||||
onPriceHistory={() => {
|
onPriceHistory={() => {
|
||||||
const item = itemActionTarget.items[0]
|
const item = itemActionTarget.items[0]
|
||||||
setItemActionTarget(null)
|
setItemActionTarget(null)
|
||||||
@@ -2285,6 +2319,7 @@ export default function TableDetailPage() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{historyItem && <PriceHistory orderId={order.id} item={historyItem} onClose={() => setHistoryItem(null)} />}
|
{historyItem && <PriceHistory orderId={order.id} item={historyItem} onClose={() => setHistoryItem(null)} />}
|
||||||
|
{moveSheet && <MoveHistory {...moveSheet} onClose={() => setMoveSheet(null)} />}
|
||||||
|
|
||||||
{/* Cancel confirmation */}
|
{/* Cancel confirmation */}
|
||||||
{cancelConfirm && (
|
{cancelConfirm && (
|
||||||
|
|||||||
@@ -25,3 +25,10 @@ test('the reason sent: a quick reason, a typed one, or none', async () => {
|
|||||||
const own = priceRules(set({ 'orders.price_change_reasons': '["Friend"]' }))
|
const own = priceRules(set({ 'orders.price_change_reasons': '["Friend"]' }))
|
||||||
assert.equal(priceReasonText(own, t, { choice: 'v0' }), 'Friend')
|
assert.equal(priceReasonText(own, t, { choice: 'v0' }), 'Friend')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('a moved order\'s path (6F.4)', async () => {
|
||||||
|
const { pathText } = await import('../src/logic/moves.js')
|
||||||
|
assert.equal(pathText([]), '')
|
||||||
|
assert.equal(pathText([{ from_table: 'T2', to_table: 'T5' }, { from_table: 'T5', to_table: 'T7' }]), 'T2 → T5 → T7')
|
||||||
|
assert.equal(pathText([{ from_table: null, to_table: 'T1' }]), '— → T1')
|
||||||
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user