feat(backend): KDS item claims across screens; zone screens only touch their own items (platform-v2 3.2c)
- order_items.claimed_by / claimed_at (Alembic 0015). POST/DELETE
/api/kds/orders/{id}/items/{item}/claim (kds.bump): someone else's claim is refused
(kds.item_claimed), letting go works for anyone with kds.bump; live kds_item_claimed.
In progress claims for whoever did it; done/served/pending/declined clear the claim.
- Fix: order-level status and decline from a zone screen changed every zone's items;
now only the screen's zone, and a zone screen sees the order status of its own items.
- Terminal: "I'm on it" / "Let go" on the selected card, the cook's name on claimed items.
- Tests: backend +6, terminal unit +1, terminal.mjs +6 with a second screen and cook.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -66,6 +66,9 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
|
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
|
||||||
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
|
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
|
||||||
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
|
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
|
||||||
|
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
|
||||||
|
"kds.item_claimed": (409, "{name} is already on this item."),
|
||||||
|
"kds.claim_needs_staff": (403, "Only a staff member can claim an item."),
|
||||||
"device.revoked": (401, "This device was removed. Pair it again."),
|
"device.revoked": (401, "This device was removed. Pair it again."),
|
||||||
"device.not_paired": (401, "This device isn't paired with the venue."),
|
"device.not_paired": (401, "This device isn't paired with the venue."),
|
||||||
"device.out_of_scope": (403, "A {app} device can't do this ({key})."),
|
"device.out_of_scope": (403, "A {app} device can't do this ({key})."),
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""order_items.claimed_by / claimed_at: a cook claims a KDS item (plan step 3.2c)
|
||||||
|
|
||||||
|
Revision ID: 0015_item_claims
|
||||||
|
Revises: 0014_sync_event_devices
|
||||||
|
Create Date: 2026-11-14 21:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0015_item_claims'
|
||||||
|
down_revision = '0014_sync_event_devices'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('order_items', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('claimed_by', sa.Integer(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('claimed_at', UTCDateTime(), nullable=True))
|
||||||
|
batch_op.create_foreign_key('fk_order_items_claimed_by_users', 'users', ['claimed_by'], ['id'])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('order_items', schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint('fk_order_items_claimed_by_users', type_='foreignkey')
|
||||||
|
batch_op.drop_column('claimed_at')
|
||||||
|
batch_op.drop_column('claimed_by')
|
||||||
@@ -110,6 +110,10 @@ class OrderItem(Base):
|
|||||||
# KDS decline tracking
|
# KDS decline tracking
|
||||||
decline_note = Column(Text, nullable=True) # reason set by kitchen when declining
|
decline_note = Column(Text, nullable=True) # reason set by kitchen when declining
|
||||||
|
|
||||||
|
# KDS claim (plan step 3.2c): the cook working on this item; cleared when it moves on
|
||||||
|
claimed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
|
claimed_at = Column(UTCDateTime, nullable=True)
|
||||||
|
|
||||||
# Courses — optional course assignment for sequenced firing
|
# Courses — optional course assignment for sequenced firing
|
||||||
course_id = Column(Integer, nullable=True)
|
course_id = Column(Integer, nullable=True)
|
||||||
|
|
||||||
@@ -121,6 +125,7 @@ class OrderItem(Base):
|
|||||||
product = relationship("Product", back_populates="order_items")
|
product = relationship("Product", back_populates="order_items")
|
||||||
added_by_user = relationship("User", foreign_keys=[added_by], back_populates="order_items")
|
added_by_user = relationship("User", foreign_keys=[added_by], back_populates="order_items")
|
||||||
paid_by_user = relationship("User", foreign_keys=[paid_by], back_populates="items_paid")
|
paid_by_user = relationship("User", foreign_keys=[paid_by], back_populates="items_paid")
|
||||||
|
claimed_by_user = relationship("User", foreign_keys=[claimed_by])
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def unit_type(self) -> str:
|
def unit_type(self) -> str:
|
||||||
|
|||||||
+132
-21
@@ -23,6 +23,13 @@ GET /api/kds/context
|
|||||||
POST /api/kds/orders/{order_id}/retry-print
|
POST /api/kds/orders/{order_id}/retry-print
|
||||||
Print the order's unprinted items again (the KDS can't reach /api/orders, 3.2a).
|
Print the order's unprinted items again (the KDS can't reach /api/orders, 3.2a).
|
||||||
|
|
||||||
|
POST / DELETE /api/kds/orders/{order_id}/items/{item_id}/claim (kds.bump, plan step 3.2c)
|
||||||
|
A cook claims an item ("I'm on it") or lets it go. An item claimed by someone else is
|
||||||
|
refused (kds.item_claimed); letting go works for anyone holding kds.bump (a cook who left).
|
||||||
|
Moving an item to "preparing" claims it for whoever did it when nobody has; any other
|
||||||
|
status (done, served, back to pending, declined) clears the claim. Live: kds_item_claimed.
|
||||||
|
Order-level status changes from a kitchen screen with a zone only touch that zone's items.
|
||||||
|
|
||||||
Kitchen screens (plan step 3.2a): a call from a paired device running the KDS uses that
|
Kitchen screens (plan step 3.2a): a call from a paired device running the KDS uses that
|
||||||
device's settings. GET /orders returns the screen's prep zone (every zone when it has none;
|
device's settings. GET /orders returns the screen's prep zone (every zone when it has none;
|
||||||
a zone_id sent by the screen is ignored), /print defaults to it, and messages to waiters are signed
|
a zone_id sent by the screen is ignored), /print defaults to it, and messages to waiters are signed
|
||||||
@@ -49,6 +56,7 @@ from models.message import StaffMessage, StaffMessageAck
|
|||||||
from models.shift import WaiterShift
|
from models.shift import WaiterShift
|
||||||
from core.access.context import current_device
|
from core.access.context import current_device
|
||||||
from core.modules import device_config
|
from core.modules import device_config
|
||||||
|
from core.access.deps import require
|
||||||
from routers.deps import get_current_user, require_kds
|
from routers.deps import get_current_user, require_kds
|
||||||
from services.sse_bus import broadcast_sync
|
from services.sse_bus import broadcast_sync
|
||||||
|
|
||||||
@@ -76,6 +84,38 @@ def _device_zone_id(request: Request, db: Session) -> Optional[int]:
|
|||||||
return _screen_settings(dev, db)["prep_zone_id"] if dev else None
|
return _screen_settings(dev, db)["prep_zone_id"] if dev else None
|
||||||
|
|
||||||
|
|
||||||
|
def _real_user_id(user) -> Optional[int]:
|
||||||
|
"""A claim belongs to a staff member; the support account (no DB row) can't hold one."""
|
||||||
|
return user.id if isinstance(user, User) else None
|
||||||
|
|
||||||
|
|
||||||
|
def _claim_follows_status(item: OrderItem, user) -> None:
|
||||||
|
"""In progress = someone is on it: claim for `user` if nobody has; anything else ends it."""
|
||||||
|
if item.kds_status == "preparing":
|
||||||
|
if item.claimed_by is None and _real_user_id(user) is not None:
|
||||||
|
item.claimed_by = user.id
|
||||||
|
item.claimed_at = utcnow()
|
||||||
|
elif item.claimed_by is not None:
|
||||||
|
item.claimed_by = None
|
||||||
|
item.claimed_at = None
|
||||||
|
|
||||||
|
|
||||||
|
def _claimer_name(item: OrderItem) -> Optional[str]:
|
||||||
|
u = item.claimed_by_user
|
||||||
|
return (u.nickname or u.full_name or u.username) if u is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(dt) -> Optional[str]:
|
||||||
|
return dt.isoformat() + "Z" if dt is not None and dt.tzinfo is None else (dt.isoformat() if dt else None)
|
||||||
|
|
||||||
|
|
||||||
|
def _in_screen_zone(item: OrderItem, zone_id: Optional[int]) -> bool:
|
||||||
|
"""A kitchen screen with a zone only changes its own zone's items (order-level actions)."""
|
||||||
|
if zone_id is None:
|
||||||
|
return True
|
||||||
|
return bool(item.product) and any(z.id == zone_id for z in item.product.prep_zones)
|
||||||
|
|
||||||
|
|
||||||
def _sender(request: Request, db: Session, sent: Optional[str]) -> str:
|
def _sender(request: Request, db: Session, sent: Optional[str]) -> str:
|
||||||
"""How waiters see who sent a KDS message. A kitchen screen signs with its zone's
|
"""How waiters see who sent a KDS message. A kitchen screen signs with its zone's
|
||||||
notification name (else the zone's name, else the screen's name); the manager's page
|
notification name (else the zone's name, else the screen's name); the manager's page
|
||||||
@@ -179,6 +219,9 @@ def _build_order_payload(order: Order, tables_map: dict, db: Session) -> dict:
|
|||||||
"unit_type": unit_type or "piece",
|
"unit_type": unit_type or "piece",
|
||||||
"kds_status": item.kds_status,
|
"kds_status": item.kds_status,
|
||||||
"decline_note": item.decline_note,
|
"decline_note": item.decline_note,
|
||||||
|
"claimed_by": item.claimed_by,
|
||||||
|
"claimed_by_name": _claimer_name(item),
|
||||||
|
"claimed_at": _iso(item.claimed_at),
|
||||||
"added_at": item.added_at.isoformat() if item.added_at else None,
|
"added_at": item.added_at.isoformat() if item.added_at else None,
|
||||||
"_added_at_raw": item.added_at, # stripped before response
|
"_added_at_raw": item.added_at, # stripped before response
|
||||||
"prep_zone_ids": prep_zone_ids,
|
"prep_zone_ids": prep_zone_ids,
|
||||||
@@ -223,22 +266,26 @@ def _build_order_payload(order: Order, tables_map: dict, db: Session) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _status_of(statuses: set) -> Optional[str]:
|
||||||
|
"""An order's KDS status from its items' statuses (None when there are none)."""
|
||||||
|
if not statuses:
|
||||||
|
return None
|
||||||
|
if statuses <= {"served"}:
|
||||||
|
return "served"
|
||||||
|
if statuses <= {"done", "served"}:
|
||||||
|
return "done"
|
||||||
|
if statuses <= {"declined"}:
|
||||||
|
return "declined"
|
||||||
|
if "preparing" in statuses or "done" in statuses:
|
||||||
|
return "preparing"
|
||||||
|
return "pending"
|
||||||
|
|
||||||
|
|
||||||
def _sync_order_kds_status(order: Order):
|
def _sync_order_kds_status(order: Order):
|
||||||
"""Derive and set order.kds_status from all non-cancelled items. Call before db.commit()."""
|
"""Derive and set order.kds_status from all non-cancelled items. Call before db.commit()."""
|
||||||
relevant = [i for i in order.items if i.status != "cancelled"]
|
new_status = _status_of({i.kds_status for i in order.items if i.status != "cancelled"})
|
||||||
if not relevant:
|
if new_status is None:
|
||||||
return
|
return
|
||||||
statuses = {i.kds_status for i in relevant}
|
|
||||||
if statuses <= {"served"}:
|
|
||||||
new_status = "served"
|
|
||||||
elif statuses <= {"done", "served"}:
|
|
||||||
new_status = "done"
|
|
||||||
elif statuses <= {"declined"}:
|
|
||||||
new_status = "declined"
|
|
||||||
elif "preparing" in statuses or "done" in statuses:
|
|
||||||
new_status = "preparing"
|
|
||||||
else:
|
|
||||||
new_status = "pending"
|
|
||||||
if new_status != order.kds_status:
|
if new_status != order.kds_status:
|
||||||
order.kds_status = new_status
|
order.kds_status = new_status
|
||||||
order.kds_status_changed_at = utcnow()
|
order.kds_status_changed_at = utcnow()
|
||||||
@@ -287,6 +334,9 @@ def kds_orders(
|
|||||||
p["items"] = [it for it in p["items"] if zone_id in it.get("prep_zone_ids", [])]
|
p["items"] = [it for it in p["items"] if zone_id in it.get("prep_zone_ids", [])]
|
||||||
if not p["items"]:
|
if not p["items"]:
|
||||||
continue
|
continue
|
||||||
|
# for this zone the order is as far as ITS items are (3.2c): the Grill is done
|
||||||
|
# with an order whose drinks are still to do at the bar
|
||||||
|
p["kds_status"] = _status_of({it["kds_status"] for it in p["items"]}) or p["kds_status"]
|
||||||
payloads.append(p)
|
payloads.append(p)
|
||||||
return {"orders": payloads}
|
return {"orders": payloads}
|
||||||
|
|
||||||
@@ -303,9 +353,13 @@ class OrderTypeBody(BaseModel):
|
|||||||
def update_order_kds_status(
|
def update_order_kds_status(
|
||||||
order_id: int,
|
order_id: int,
|
||||||
body: KdsStatusBody,
|
body: KdsStatusBody,
|
||||||
|
request: Request,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(get_current_user),
|
user: User = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
|
"""Set the order's KDS status; pending/preparing/done also set its open items. On a
|
||||||
|
kitchen screen with a prep zone only that zone's items change (3.2c), and the order's
|
||||||
|
status then follows all its items."""
|
||||||
if body.status not in VALID_KDS_STATUSES:
|
if body.status not in VALID_KDS_STATUSES:
|
||||||
raise HTTPException(status_code=400, detail=f"Invalid status '{body.status}'")
|
raise HTTPException(status_code=400, detail=f"Invalid status '{body.status}'")
|
||||||
|
|
||||||
@@ -313,28 +367,32 @@ def update_order_kds_status(
|
|||||||
if not order:
|
if not order:
|
||||||
raise HTTPException(status_code=404, detail="Order not found")
|
raise HTTPException(status_code=404, detail="Order not found")
|
||||||
|
|
||||||
if body.status != order.kds_status:
|
zone_id = _device_zone_id(request, db)
|
||||||
|
if body.status != order.kds_status and zone_id is None:
|
||||||
order.kds_status = body.status
|
order.kds_status = body.status
|
||||||
order.kds_status_changed_at = utcnow()
|
order.kds_status_changed_at = utcnow()
|
||||||
|
|
||||||
# Cascade order-level status to non-cancelled, non-served items only
|
# Cascade order-level status to non-cancelled, non-served items only
|
||||||
if body.status in ("pending", "preparing", "done"):
|
if body.status in ("pending", "preparing", "done"):
|
||||||
for item in order.items:
|
for item in order.items:
|
||||||
if item.status != "cancelled" and item.kds_status != "served":
|
if item.status != "cancelled" and item.kds_status != "served" and _in_screen_zone(item, zone_id):
|
||||||
item.kds_status = body.status
|
item.kds_status = body.status
|
||||||
# auto_ready_to_served: if cascading to 'done', immediately upgrade qualifying items
|
# auto_ready_to_served: if cascading to 'done', immediately upgrade qualifying items
|
||||||
if body.status == "done" and item.product:
|
if body.status == "done" and item.product:
|
||||||
if any(bool(z.auto_ready_to_served) for z in item.product.prep_zones):
|
if any(bool(z.auto_ready_to_served) for z in item.product.prep_zones):
|
||||||
item.kds_status = "served"
|
item.kds_status = "served"
|
||||||
|
_claim_follows_status(item, user)
|
||||||
|
if zone_id is not None:
|
||||||
|
_sync_order_kds_status(order)
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
broadcast_sync("kds_order_updated", {
|
broadcast_sync("kds_order_updated", {
|
||||||
"order_id": order_id,
|
"order_id": order_id,
|
||||||
"kds_status": body.status,
|
"kds_status": order.kds_status,
|
||||||
})
|
})
|
||||||
|
|
||||||
return {"order_id": order_id, "kds_status": body.status}
|
return {"order_id": order_id, "kds_status": order.kds_status}
|
||||||
|
|
||||||
|
|
||||||
@router.put("/orders/{order_id}/items/{item_id}/kds_status")
|
@router.put("/orders/{order_id}/items/{item_id}/kds_status")
|
||||||
@@ -363,6 +421,7 @@ def update_item_kds_status(
|
|||||||
auto_serve = any(bool(z.auto_ready_to_served) for z in item.product.prep_zones)
|
auto_serve = any(bool(z.auto_ready_to_served) for z in item.product.prep_zones)
|
||||||
if auto_serve:
|
if auto_serve:
|
||||||
item.kds_status = "served"
|
item.kds_status = "served"
|
||||||
|
_claim_follows_status(item, user)
|
||||||
|
|
||||||
if item.order:
|
if item.order:
|
||||||
_sync_order_kds_status(item.order)
|
_sync_order_kds_status(item.order)
|
||||||
@@ -519,6 +578,7 @@ class DeclineBody(BaseModel):
|
|||||||
def decline_order(
|
def decline_order(
|
||||||
order_id: int,
|
order_id: int,
|
||||||
body: DeclineBody,
|
body: DeclineBody,
|
||||||
|
request: Request,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(get_current_user),
|
user: User = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
@@ -527,20 +587,25 @@ def decline_order(
|
|||||||
if not order:
|
if not order:
|
||||||
raise HTTPException(status_code=404, detail="Order not found")
|
raise HTTPException(status_code=404, detail="Order not found")
|
||||||
|
|
||||||
|
zone_id = _device_zone_id(request, db) # a zone screen declines only its own items (3.2c)
|
||||||
for item in order.items:
|
for item in order.items:
|
||||||
if item.status != "cancelled":
|
if item.status != "cancelled" and _in_screen_zone(item, zone_id):
|
||||||
item.kds_status = "declined"
|
item.kds_status = "declined"
|
||||||
item.decline_note = body.decline_note
|
item.decline_note = body.decline_note
|
||||||
|
_claim_follows_status(item, user)
|
||||||
|
|
||||||
order.kds_status = "declined"
|
if zone_id is None:
|
||||||
|
order.kds_status = "declined"
|
||||||
|
else:
|
||||||
|
_sync_order_kds_status(order)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
broadcast_sync("kds_order_updated", {
|
broadcast_sync("kds_order_updated", {
|
||||||
"order_id": order_id,
|
"order_id": order_id,
|
||||||
"kds_status": "declined",
|
"kds_status": order.kds_status,
|
||||||
"decline_note": body.decline_note,
|
"decline_note": body.decline_note,
|
||||||
})
|
})
|
||||||
return {"order_id": order_id, "kds_status": "declined"}
|
return {"order_id": order_id, "kds_status": order.kds_status}
|
||||||
|
|
||||||
|
|
||||||
@router.put("/orders/{order_id}/items/{item_id}/decline")
|
@router.put("/orders/{order_id}/items/{item_id}/decline")
|
||||||
@@ -561,6 +626,7 @@ def decline_item(
|
|||||||
|
|
||||||
item.kds_status = "declined"
|
item.kds_status = "declined"
|
||||||
item.decline_note = body.decline_note
|
item.decline_note = body.decline_note
|
||||||
|
_claim_follows_status(item, user)
|
||||||
|
|
||||||
if item.order:
|
if item.order:
|
||||||
_sync_order_kds_status(item.order)
|
_sync_order_kds_status(item.order)
|
||||||
@@ -841,3 +907,48 @@ def kds_retry_print(
|
|||||||
if not unprinted_ids:
|
if not unprinted_ids:
|
||||||
return {"print_results": []}
|
return {"print_results": []}
|
||||||
return {"print_results": route_and_print_sync(order_id, unprinted_ids, db)}
|
return {"print_results": route_and_print_sync(order_id, unprinted_ids, db)}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ─────────────────────────── claims (3.2c) ─────────────────────────────────
|
||||||
|
|
||||||
|
def _claim_item(db: Session, order_id: int, item_id: int) -> OrderItem:
|
||||||
|
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||||
|
if not item:
|
||||||
|
raise XeniaError("kds.item_not_found", item_id=item_id)
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def _claim_out(item: OrderItem) -> dict:
|
||||||
|
return {"order_id": item.order_id, "item_id": item.id, "claimed_by": item.claimed_by,
|
||||||
|
"claimed_by_name": _claimer_name(item), "claimed_at": _iso(item.claimed_at)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/orders/{order_id}/items/{item_id}/claim")
|
||||||
|
def claim_item(order_id: int, item_id: int, db: Session = Depends(get_db), user=Depends(require("kds.bump"))):
|
||||||
|
""""I'm on it": the item is mine. Someone else's claim is refused (kds.item_claimed)."""
|
||||||
|
item = _claim_item(db, order_id, item_id)
|
||||||
|
uid = _real_user_id(user)
|
||||||
|
if uid is None:
|
||||||
|
raise XeniaError("kds.claim_needs_staff")
|
||||||
|
if item.claimed_by is not None and item.claimed_by != uid:
|
||||||
|
raise XeniaError("kds.item_claimed", name=_claimer_name(item) or "")
|
||||||
|
if item.claimed_by != uid:
|
||||||
|
item.claimed_by = uid
|
||||||
|
item.claimed_at = utcnow()
|
||||||
|
db.commit()
|
||||||
|
db.refresh(item)
|
||||||
|
broadcast_sync("kds_item_claimed", _claim_out(item))
|
||||||
|
return _claim_out(item)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/orders/{order_id}/items/{item_id}/claim")
|
||||||
|
def release_item(order_id: int, item_id: int, db: Session = Depends(get_db), user=Depends(require("kds.bump"))):
|
||||||
|
"""Let the item go (anyone holding kds.bump: also for a cook who left)."""
|
||||||
|
item = _claim_item(db, order_id, item_id)
|
||||||
|
if item.claimed_by is not None:
|
||||||
|
item.claimed_by = None
|
||||||
|
item.claimed_at = None
|
||||||
|
db.commit()
|
||||||
|
broadcast_sync("kds_item_claimed", _claim_out(item))
|
||||||
|
return _claim_out(item)
|
||||||
|
|||||||
@@ -149,7 +149,79 @@ def test_item_back_to_pending_reopens_the_order(client, screen, kitchen):
|
|||||||
"""Undo on the screen (3.2b): an item done → back to pending puts the order back too."""
|
"""Undo on the screen (3.2b): an item done → back to pending puts the order back too."""
|
||||||
h, oid = screen["h"], kitchen["order"].id
|
h, oid = screen["h"], kitchen["order"].id
|
||||||
item = client.get("/api/kds/orders", headers=h).json()["orders"][0]["items"][0]["id"]
|
item = client.get("/api/kds/orders", headers=h).json()["orders"][0]["items"][0]["id"]
|
||||||
for status, expected in (("done", "preparing"), ("pending", "pending")): # the Bar item is still to do
|
for status, expected in (("done", "done"), ("pending", "pending")): # as far as this zone goes (3.2c)
|
||||||
assert client.put(f"/api/kds/orders/{oid}/items/{item}/kds_status", headers=h, json={"status": status}).status_code == 200
|
assert client.put(f"/api/kds/orders/{oid}/items/{item}/kds_status", headers=h, json={"status": status}).status_code == 200
|
||||||
order = next(o for o in client.get("/api/kds/orders", headers=h).json()["orders"] if o["id"] == oid)
|
order = next(o for o in client.get("/api/kds/orders", headers=h).json()["orders"] if o["id"] == oid)
|
||||||
assert order["kds_status"] == expected
|
assert order["kds_status"] == expected
|
||||||
|
|
||||||
|
|
||||||
|
# ── claims (3.2c) ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def second_screen(client, pair, make_user, kitchen):
|
||||||
|
token, r = pair("kds", "Grill screen 2", config={"prep_zone_id": kitchen["grill"].id})
|
||||||
|
chef = make_user(role="chef", nickname="Nikos")
|
||||||
|
jwt = terminal_login(client, token, chef)
|
||||||
|
return {"id": r.json()["id"], "h": {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}, "chef": chef}
|
||||||
|
|
||||||
|
|
||||||
|
def steak(client, h, oid):
|
||||||
|
order = next(o for o in client.get("/api/kds/orders", headers=h).json()["orders"] if o["id"] == oid)
|
||||||
|
return order["items"][0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_screens_claim_without_stepping_on_each_other(client, screen, second_screen, kitchen): # "done when"
|
||||||
|
oid = kitchen["order"].id
|
||||||
|
item = steak(client, screen["h"], oid)["id"]
|
||||||
|
url = f"/api/kds/orders/{oid}/items/{item}/claim"
|
||||||
|
r = client.post(url, headers=second_screen["h"])
|
||||||
|
assert r.status_code == 200 and r.json()["claimed_by_name"] == "Nikos"
|
||||||
|
# the other screen sees it and can't take it
|
||||||
|
assert steak(client, screen["h"], oid)["claimed_by_name"] == "Nikos"
|
||||||
|
r = client.post(url, headers=screen["h"])
|
||||||
|
assert r.status_code == 409 and r.json()["error"] == {"code": "kds.item_claimed", "params": {"name": "Nikos"}, "message": "Nikos is already on this item."}
|
||||||
|
# claiming again is harmless; letting go works from any screen (a cook who left)
|
||||||
|
assert client.post(url, headers=second_screen["h"]).status_code == 200
|
||||||
|
assert client.delete(url, headers=screen["h"]).json()["claimed_by"] is None
|
||||||
|
assert client.post(url, headers=screen["h"]).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_in_progress_claims_and_bumping_clears(client, screen, second_screen, kitchen):
|
||||||
|
oid = kitchen["order"].id
|
||||||
|
item = steak(client, screen["h"], oid)["id"]
|
||||||
|
status = f"/api/kds/orders/{oid}/items/{item}/kds_status"
|
||||||
|
assert client.put(status, headers=second_screen["h"], json={"status": "preparing"}).status_code == 200
|
||||||
|
assert steak(client, screen["h"], oid)["claimed_by_name"] == "Nikos"
|
||||||
|
# in progress again from the other screen: still Nikos's
|
||||||
|
client.put(status, headers=screen["h"], json={"status": "preparing"})
|
||||||
|
assert steak(client, screen["h"], oid)["claimed_by_name"] == "Nikos"
|
||||||
|
assert client.put(status, headers=screen["h"], json={"status": "done"}).status_code == 200
|
||||||
|
assert steak(client, screen["h"], oid)["claimed_by"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_claims_need_kds_bump(client, pair, make_user, kitchen, screen):
|
||||||
|
oid = kitchen["order"].id
|
||||||
|
item = steak(client, screen["h"], oid)["id"]
|
||||||
|
token, _ = pair("kds", "Pass", config={"prep_zone_id": kitchen["grill"].id})
|
||||||
|
viewer = make_user(role="chef", remove=("kds.bump",))
|
||||||
|
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, viewer)}"}
|
||||||
|
assert err(client.post(f"/api/kds/orders/{oid}/items/{item}/claim", headers=h)) == "access.denied"
|
||||||
|
|
||||||
|
|
||||||
|
def test_order_actions_on_a_zone_screen_leave_other_zones_alone(client, screen, kitchen, owner_h):
|
||||||
|
oid = kitchen["order"].id
|
||||||
|
r = client.put(f"/api/kds/orders/{oid}/kds_status", headers=screen["h"], json={"status": "done"})
|
||||||
|
assert r.status_code == 200 and r.json()["kds_status"] == "preparing" # the Bar's beer is still to do
|
||||||
|
everything = next(o for o in client.get("/api/kds/orders", headers=owner_h).json()["orders"] if o["id"] == oid)
|
||||||
|
assert {i["product_name"]: i["kds_status"] for i in everything["items"]} == {"Steak": "done", "Beer": "pending"}
|
||||||
|
client.put(f"/api/kds/orders/{oid}/decline", headers=screen["h"], json={"decline_note": "x"})
|
||||||
|
everything = next(o for o in client.get("/api/kds/orders", headers=owner_h).json()["orders"] if o["id"] == oid)
|
||||||
|
assert {i["product_name"]: i["kds_status"] for i in everything["items"]} == {"Steak": "declined", "Beer": "pending"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_zone_screen_sees_how_far_its_own_items_are(client, screen, kitchen, owner_h):
|
||||||
|
oid = kitchen["order"].id
|
||||||
|
client.put(f"/api/kds/orders/{oid}/kds_status", headers=screen["h"], json={"status": "done"})
|
||||||
|
mine = next(o for o in client.get("/api/kds/orders", headers=screen["h"]).json()["orders"] if o["id"] == oid)
|
||||||
|
everything = next(o for o in client.get("/api/kds/orders", headers=owner_h).json()["orders"] if o["id"] == oid)
|
||||||
|
assert (mine["kds_status"], everything["kds_status"]) == ("done", "preparing")
|
||||||
|
|||||||
@@ -72,5 +72,10 @@
|
|||||||
},
|
},
|
||||||
"system": {
|
"system": {
|
||||||
"log_not_found": "Δεν υπάρχει αρχείο καταγραφής για {{date}}."
|
"log_not_found": "Δεν υπάρχει αρχείο καταγραφής για {{date}}."
|
||||||
|
},
|
||||||
|
"kds": {
|
||||||
|
"item_not_found": "Το είδος {{item_id}} δεν βρέθηκε σε αυτή την παραγγελία.",
|
||||||
|
"item_claimed": "Ο/Η {{name}} ασχολείται ήδη με αυτό το είδος.",
|
||||||
|
"claim_needs_staff": "Μόνο μέλος του προσωπικού μπορεί να αναλάβει ένα είδος."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,13 @@
|
|||||||
"undone": "Αναίρεση",
|
"undone": "Αναίρεση",
|
||||||
"redone": "Επανάληψη",
|
"redone": "Επανάληψη",
|
||||||
"settingsSaved": "Οι ρυθμίσεις αποθηκεύτηκαν"
|
"settingsSaved": "Οι ρυθμίσεις αποθηκεύτηκαν"
|
||||||
|
},
|
||||||
|
"claim": {
|
||||||
|
"take": "Το αναλαμβάνω",
|
||||||
|
"release": "Αφήνω",
|
||||||
|
"taken": "Ο/Η {{name}} το έχει ήδη αναλάβει",
|
||||||
|
"taken_by_me": "Το ανέλαβες",
|
||||||
|
"released": "Το άφησες"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,5 +72,10 @@
|
|||||||
},
|
},
|
||||||
"system": {
|
"system": {
|
||||||
"log_not_found": "There is no log file for {{date}}."
|
"log_not_found": "There is no log file for {{date}}."
|
||||||
|
},
|
||||||
|
"kds": {
|
||||||
|
"item_not_found": "Item {{item_id}} not found on this order.",
|
||||||
|
"item_claimed": "{{name}} is already on this item.",
|
||||||
|
"claim_needs_staff": "Only a staff member can claim an item."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,6 +153,13 @@
|
|||||||
"undone": "Undone",
|
"undone": "Undone",
|
||||||
"redone": "Redone",
|
"redone": "Redone",
|
||||||
"settingsSaved": "Settings saved"
|
"settingsSaved": "Settings saved"
|
||||||
|
},
|
||||||
|
"claim": {
|
||||||
|
"take": "I'm on it",
|
||||||
|
"release": "Let go",
|
||||||
|
"taken": "{{name}} is already on it",
|
||||||
|
"taken_by_me": "You're on it",
|
||||||
|
"released": "Let go"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
// connection (useKdsData). Sound needs one tap after the screen starts (browser rule).
|
// connection (useKdsData). Sound needs one tap after the screen starts (browser rule).
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { CookingPot } from 'lucide-react'
|
import { CookingPot } from 'lucide-react'
|
||||||
|
import { useAccess, useCan } from '@xenia/access'
|
||||||
import { useLanguage, useTranslation } from '@xenia/i18n'
|
import { useLanguage, useTranslation } from '@xenia/i18n'
|
||||||
import { useToast } from '@xenia/ui'
|
import { useToast } from '@xenia/ui'
|
||||||
import client from '../../api/client'
|
import client from '../../api/client'
|
||||||
@@ -27,7 +28,7 @@ import { SideRail, TopBar } from './components/Rails'
|
|||||||
import SettingsPanel from './components/SettingsPanel'
|
import SettingsPanel from './components/SettingsPanel'
|
||||||
import SummaryPanel from './components/SummaryPanel'
|
import SummaryPanel from './components/SummaryPanel'
|
||||||
import {
|
import {
|
||||||
ageLabel, ageOrderFor, ageState, bucketCounts, nextItemStatus, readyNotice, tabCounts, visibleOrders,
|
ageLabel, ageOrderFor, ageState, bucketCounts, claimState, claimTargets, nextItemStatus, readyNotice, tabCounts, visibleOrders,
|
||||||
withItemStatus, withOrderStatus,
|
withItemStatus, withOrderStatus,
|
||||||
} from './logic/board'
|
} from './logic/board'
|
||||||
import { layoutBoard } from './logic/layout'
|
import { layoutBoard } from './logic/layout'
|
||||||
@@ -42,6 +43,8 @@ export default function KdsApp() {
|
|||||||
const { t } = useTranslation('terminal')
|
const { t } = useTranslation('terminal')
|
||||||
const { language } = useLanguage()
|
const { language } = useLanguage()
|
||||||
const { me } = useDevice()
|
const { me } = useDevice()
|
||||||
|
const { user } = useAccess()
|
||||||
|
const canClaim = useCan('kds.bump')
|
||||||
const config = me?.config
|
const config = me?.config
|
||||||
const [zoom, setZoom] = useState(null) // percent; null = the saved font_scale
|
const [zoom, setZoom] = useState(null) // percent; null = the saved font_scale
|
||||||
const settings = useMemo(() => boardSettings(config, zoom), [config, zoom])
|
const settings = useMemo(() => boardSettings(config, zoom), [config, zoom])
|
||||||
@@ -182,6 +185,20 @@ export default function KdsApp() {
|
|||||||
} catch { toast(t('kds.toast.declineFailed'), 'danger') }
|
} catch { toast(t('kds.toast.declineFailed'), 'danger') }
|
||||||
}, [reload, t, toast])
|
}, [reload, t, toast])
|
||||||
|
|
||||||
|
// "I'm on it" / let go, for every open item of the card nobody has (or that I hold)
|
||||||
|
const claim = useCallback(async (orderId, action, items) => {
|
||||||
|
const targets = claimTargets(items, user?.id, action)
|
||||||
|
const results = await Promise.allSettled(targets.map(it => (action === 'take'
|
||||||
|
? client.post(`/api/kds/orders/${orderId}/items/${it.id}/claim`)
|
||||||
|
: client.delete(`/api/kds/orders/${orderId}/items/${it.id}/claim`))))
|
||||||
|
const taken = results.find(r => r.status === 'rejected' && r.reason?.xenia?.code === 'kds.item_claimed')
|
||||||
|
if (taken) toast(t('kds.claim.taken', { name: taken.reason.xenia.params?.name ?? '' }), 'warning')
|
||||||
|
else if (results.some(r => r.status === 'rejected')) toast(t('kds.toast.sendFailed'), 'danger')
|
||||||
|
else toast(action === 'take' ? t('kds.claim.taken_by_me') : t('kds.claim.released'))
|
||||||
|
setFocusId(null)
|
||||||
|
reload()
|
||||||
|
}, [user?.id, reload, t, toast])
|
||||||
|
|
||||||
const print = useCallback(async orderId => {
|
const print = useCallback(async orderId => {
|
||||||
try {
|
try {
|
||||||
await client.post(`/api/kds/orders/${orderId}/retry-print`)
|
await client.post(`/api/kds/orders/${orderId}/retry-print`)
|
||||||
@@ -313,6 +330,8 @@ export default function KdsApp() {
|
|||||||
settings={settings} multiFilter={filters.size > 1} courses={courses}
|
settings={settings} multiFilter={filters.size > 1} courses={courses}
|
||||||
onFocus={id => setFocusId(id === realId ? order.id : id)}
|
onFocus={id => setFocusId(id === realId ? order.id : id)}
|
||||||
onStatus={setOrderStatus} onBumpItem={bumpItem} onPrint={print} onCallWaiter={callWaiter}
|
onStatus={setOrderStatus} onBumpItem={bumpItem} onPrint={print} onCallWaiter={callWaiter}
|
||||||
|
claimState={canClaim ? claimState(order.items, user?.id) : 'none'}
|
||||||
|
onClaim={(orderId, action) => claim(orderId, action, order.items)}
|
||||||
onDecline={orderId => setDialog({ decline: { orderId, itemId: null } })}
|
onDecline={orderId => setDialog({ decline: { orderId, itemId: null } })}
|
||||||
onItemDecline={(orderId, itemId, itemName) => setDialog({ decline: { orderId, itemId, itemName } })} />
|
onItemDecline={(orderId, itemId, itemName) => setDialog({ decline: { orderId, itemId, itemName } })} />
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// - ActionBar (the selected card): in progress / done (or back), print, and "Call waiter"
|
// - ActionBar (the selected card): in progress / done (or back), print, and "Call waiter"
|
||||||
// over the footer when the order has a waiter.
|
// over the footer when the order has a waiter.
|
||||||
// - QuickActionBar (long press on a card that isn't selected): prep, ready, decline, close.
|
// - QuickActionBar (long press on a card that isn't selected): prep, ready, decline, close.
|
||||||
import { Ban, BellRing, Check, Flame, Printer, Undo2, X } from 'lucide-react'
|
import { Ban, BellRing, Check, Flame, Hand, Printer, Undo2, X } from 'lucide-react'
|
||||||
import { useTranslation } from '@xenia/i18n'
|
import { useTranslation } from '@xenia/i18n'
|
||||||
import { CARD_FOOT_H_BASE, CARD_HEAD_H_BASE, CARD_SUB_H_BASE } from '../logic/layout'
|
import { CARD_FOOT_H_BASE, CARD_HEAD_H_BASE, CARD_SUB_H_BASE } from '../logic/layout'
|
||||||
import { KDS, alpha } from '../theme'
|
import { KDS, alpha } from '../theme'
|
||||||
@@ -34,7 +34,7 @@ function BarButton({ bg, label, title, onClick, fs, children, testId }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ActionBar({ order, onStatus, onPrint, onCallWaiter, fs = 1, hasWaiter }) {
|
export function ActionBar({ order, onStatus, onPrint, onCallWaiter, onClaim, claimState, fs = 1, hasWaiter }) {
|
||||||
const { t } = useTranslation('terminal')
|
const { t } = useTranslation('terminal')
|
||||||
const isDone = order.kds_status === 'done'
|
const isDone = order.kds_status === 'done'
|
||||||
const isPreparing = order.kds_status === 'preparing'
|
const isPreparing = order.kds_status === 'preparing'
|
||||||
@@ -50,6 +50,12 @@ export function ActionBar({ order, onStatus, onPrint, onCallWaiter, fs = 1, hasW
|
|||||||
bg={isDone ? KDS.done : KDS.freshDeep} onClick={() => onStatus(order.id, isDone ? 'pending' : 'done')}>
|
bg={isDone ? KDS.done : KDS.freshDeep} onClick={() => onStatus(order.id, isDone ? 'pending' : 'done')}>
|
||||||
{isDone ? <Undo2 style={icon} /> : <Check style={icon} />}
|
{isDone ? <Undo2 style={icon} /> : <Check style={icon} />}
|
||||||
</BarButton>
|
</BarButton>
|
||||||
|
{claimState !== 'none' && (
|
||||||
|
<BarButton fs={fs} testId="card-claim" title={claimState === 'mine' ? t('kds.claim.release') : t('kds.claim.take')}
|
||||||
|
bg={claimState === 'mine' ? KDS.done : KDS.progress} onClick={() => onClaim(order.id, claimState === 'mine' ? 'release' : 'take')}>
|
||||||
|
{claimState === 'mine' ? <Undo2 style={icon} /> : <Hand style={icon} />}
|
||||||
|
</BarButton>
|
||||||
|
)}
|
||||||
<BarButton fs={fs} testId="card-print" title={t('kds.actions.print')} bg={alpha('on-status', 0.12)} onClick={() => onPrint(order.id)}>
|
<BarButton fs={fs} testId="card-print" title={t('kds.actions.print')} bg={alpha('on-status', 0.12)} onClick={() => onPrint(order.id)}>
|
||||||
<Printer style={icon} />
|
<Printer style={icon} />
|
||||||
</BarButton>
|
</BarButton>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// One item on an order card: quantity badge, name, changes (− removed, + extras, → choices)
|
// One item on an order card: quantity badge, name, changes (− removed, + extras, → choices)
|
||||||
// and its note. On the selected card a tap moves it on, a long press declines it.
|
// and its note. On the selected card a tap moves it on, a long press declines it.
|
||||||
import { useRef } from 'react'
|
import { useRef } from 'react'
|
||||||
import { ArrowRight, Info, Minus, Plus } from 'lucide-react'
|
import { ArrowRight, Hand, Info, Minus, Plus } from 'lucide-react'
|
||||||
import { dedupeModifiers, formatQty, hasUnit } from '../logic/board'
|
import { dedupeModifiers, formatQty, hasUnit } from '../logic/board'
|
||||||
import { KDS } from '../theme'
|
import { KDS } from '../theme'
|
||||||
|
|
||||||
@@ -68,6 +68,17 @@ export default function ItemBlock({ item, focused, onBump, onDecline, fontScale
|
|||||||
}}>
|
}}>
|
||||||
{item.product_name}
|
{item.product_name}
|
||||||
</span>
|
</span>
|
||||||
|
{item.claimed_by_name && !done && (
|
||||||
|
<span data-testid="item-claim" title={item.claimed_by_name} style={{
|
||||||
|
flexShrink: 0, maxWidth: '45%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
||||||
|
height: badgeH, display: 'inline-flex', alignItems: 'center', gap: 3, padding: `0 ${Math.round(6 * fs)}px`,
|
||||||
|
borderRadius: Math.round(5 * fs), background: KDS.progress, color: KDS.onStatus,
|
||||||
|
fontSize: Math.round(11 * fs), fontWeight: 700,
|
||||||
|
}}>
|
||||||
|
<Hand style={{ width: Math.round(11 * fs), height: Math.round(11 * fs), flexShrink: 0 }} />
|
||||||
|
{item.claimed_by_name}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
{focused && (
|
{focused && (
|
||||||
<span style={{
|
<span style={{
|
||||||
flexShrink: 0, width: 8, height: 8, borderRadius: 4, display: 'inline-block', marginTop: Math.round((badgeH - 8) / 2),
|
flexShrink: 0, width: 8, height: 8, borderRadius: 4, display: 'inline-block', marginTop: Math.round((badgeH - 8) / 2),
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ function glowFor(order, age) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function OrderCard({ order, age, ageText, layout, focused, dimmed, settings, multiFilter, courses, now,
|
export default function OrderCard({ order, age, ageText, layout, focused, dimmed, settings, multiFilter, courses, now,
|
||||||
onFocus, onStatus, onBumpItem, onPrint, onDecline, onItemDecline, onCallWaiter }) {
|
onFocus, onStatus, onBumpItem, onPrint, onDecline, onItemDecline, onCallWaiter, onClaim, claimState }) {
|
||||||
const { t } = useTranslation('terminal')
|
const { t } = useTranslation('terminal')
|
||||||
const fs = settings.fontScale
|
const fs = settings.fontScale
|
||||||
const [headBg, subBg] = headColours(age.age, settings.colours)
|
const [headBg, subBg] = headColours(age.age, settings.colours)
|
||||||
@@ -207,7 +207,7 @@ export default function OrderCard({ order, age, ageText, layout, focused, dimmed
|
|||||||
<QuickActionBar order={order} onStatus={onStatus} onDecline={onDecline} onDismiss={() => setQuick(false)} fs={fs} />
|
<QuickActionBar order={order} onStatus={onStatus} onDecline={onDecline} onDismiss={() => setQuick(false)} fs={fs} />
|
||||||
)}
|
)}
|
||||||
{focused && (
|
{focused && (
|
||||||
<ActionBar order={order} onStatus={onStatus} onPrint={onPrint} onCallWaiter={onCallWaiter} fs={fs} hasWaiter={!!waiter} />
|
<ActionBar order={order} onStatus={onStatus} onPrint={onPrint} onCallWaiter={onCallWaiter} onClaim={onClaim} claimState={claimState} fs={fs} hasWaiter={!!waiter} />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -222,3 +222,21 @@ export function readyNotice(order, itemId, settings) {
|
|||||||
if (done === active.length) return settings.notifyOrderComplete ? { kind: 'order' } : null
|
if (done === active.length) return settings.notifyOrderComplete ? { kind: 'order' } : null
|
||||||
return settings.notifyItemComplete ? { kind: 'items', ready_count: done, total_count: active.length } : null
|
return settings.notifyItemComplete ? { kind: 'items', ready_count: done, total_count: active.length } : null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── claims (3.2c): who is on which item ─────────────────────────────────────
|
||||||
|
|
||||||
|
const isOpen = it => it.status !== 'cancelled' && !['done', 'served', 'declined'].includes(it.kds_status)
|
||||||
|
|
||||||
|
/** What the card's claim button does for `userId`: 'take' (some open items are nobody's),
|
||||||
|
* 'mine' (I hold some and nothing is left to take: let go), or 'none'. */
|
||||||
|
export function claimState(items, userId) {
|
||||||
|
const open = items.filter(isOpen)
|
||||||
|
if (!open.length || userId == null) return 'none'
|
||||||
|
if (open.some(it => it.claimed_by == null)) return 'take'
|
||||||
|
return open.some(it => it.claimed_by === userId) ? 'mine' : 'none'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The items a take / release touches: nobody's open items, or my open ones. */
|
||||||
|
export function claimTargets(items, userId, action) {
|
||||||
|
return items.filter(isOpen).filter(it => (action === 'take' ? it.claimed_by == null : it.claimed_by === userId))
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
|
|||||||
import client from '../../api/client'
|
import client from '../../api/client'
|
||||||
import { useDevice, useLiveEvent, useLiveEvents } from '../../device/context'
|
import { useDevice, useLiveEvent, useLiveEvents } from '../../device/context'
|
||||||
|
|
||||||
export const ORDER_EVENTS = ['kds_order_updated', 'kds_item_updated', 'order_updated', 'order_paid', 'order_closed', 'products_changed']
|
export const ORDER_EVENTS = ['kds_order_updated', 'kds_item_updated', 'order_updated', 'order_paid', 'order_closed', 'products_changed', 'kds_item_claimed']
|
||||||
const COALESCE_MS = 150
|
const COALESCE_MS = 150
|
||||||
const quiet = { xenia: { noOverride: true } }
|
const quiet = { xenia: { noOverride: true } }
|
||||||
|
|
||||||
|
|||||||
@@ -180,3 +180,21 @@ test('device config → board settings; zoom overrides the size for the session'
|
|||||||
assert.equal(senderName({ zone: { name: 'Grill', notification_name: 'Grill station' }, device: { name: 'Screen' } }), 'Grill station')
|
assert.equal(senderName({ zone: { name: 'Grill', notification_name: 'Grill station' }, device: { name: 'Screen' } }), 'Grill station')
|
||||||
assert.equal(senderName({ zone: null, device: { name: 'Screen' } }), 'Screen')
|
assert.equal(senderName({ zone: null, device: { name: 'Screen' } }), 'Screen')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('claims: take what nobody has, let go of mine, nothing when others have it all (3.2c)', async () => {
|
||||||
|
const { claimState, claimTargets } = await import('../src/apps/kds/logic/board.js')
|
||||||
|
const items = [
|
||||||
|
{ id: 1, kds_status: 'pending', claimed_by: null },
|
||||||
|
{ id: 2, kds_status: 'preparing', claimed_by: 7 },
|
||||||
|
{ id: 3, kds_status: 'done', claimed_by: null },
|
||||||
|
{ id: 4, kds_status: 'pending', claimed_by: 9 },
|
||||||
|
]
|
||||||
|
assert.equal(claimState(items, 7), 'take')
|
||||||
|
assert.deepEqual(claimTargets(items, 7, 'take').map(i => i.id), [1])
|
||||||
|
const mine = items.map(i => (i.id === 1 ? { ...i, claimed_by: 7 } : i))
|
||||||
|
assert.equal(claimState(mine, 7), 'mine')
|
||||||
|
assert.deepEqual(claimTargets(mine, 7, 'release').map(i => i.id), [1, 2])
|
||||||
|
assert.equal(claimState(mine.map(i => ({ ...i, claimed_by: i.claimed_by && 9 })), 7), 'none')
|
||||||
|
assert.equal(claimState([{ id: 1, kds_status: 'done' }], 7), 'none')
|
||||||
|
assert.equal(claimState(items, null), 'none')
|
||||||
|
})
|
||||||
|
|||||||
@@ -222,6 +222,44 @@ try {
|
|||||||
await page.waitForFunction(id => document.querySelector(`[data-testid="kds-card"][data-order="${id}"]`)?.dataset.status === 'pending', second.id, { timeout: 5000 }).catch(() => {})
|
await page.waitForFunction(id => document.querySelector(`[data-testid="kds-card"][data-order="${id}"]`)?.dataset.status === 'pending', second.id, { timeout: 5000 }).catch(() => {})
|
||||||
r.check('3.2b: a change made elsewhere shows on the screen by itself', await card2.getAttribute('data-status') === 'pending')
|
r.check('3.2b: a change made elsewhere shows on the screen by itself', await card2.getAttribute('data-status') === 'pending')
|
||||||
|
|
||||||
|
// ── 3.2c: two screens on the same zone, two cooks, claims ────────────────
|
||||||
|
const chef2 = await api('POST', '/api/waiters/', { token: boss, body: { username: 'term_chef2', full_name: 'Nikos Cook', nickname: 'Nikos', pin: '5858', role: 'chef', is_active: true } })
|
||||||
|
const page2 = await screen(await (await browser.newContext({ viewport: { width: 1280, height: 800 } })).newPage())
|
||||||
|
await pairFromManager(page2, boss, { app_key: 'kds', name: 'Kitchen 2', login_mode: 'pin', config: { prep_zone_id: grill.id } })
|
||||||
|
await page2.locator(`[data-user="${chef2.id}"]`).click({ timeout: 15_000 })
|
||||||
|
await page2.keyboard.type('5858')
|
||||||
|
await page2.keyboard.press('Enter')
|
||||||
|
await page2.getByTestId('kds-start').click({ timeout: 15_000 })
|
||||||
|
const other = page2.locator(`[data-testid="kds-card"][data-order="${second.id}"]`)
|
||||||
|
await other.waitFor({ timeout: 8000 })
|
||||||
|
const pill = (loc, name) => loc.locator('[data-testid="item-claim"]', { hasText: name }).waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
|
||||||
|
const noPill = loc => loc.locator('[data-testid="item-claim"]').waitFor({ state: 'detached', timeout: 5000 }).then(() => true).catch(() => false)
|
||||||
|
|
||||||
|
await card2.click({ position: { x: 20, y: 120 } })
|
||||||
|
await card2.getByTestId('card-claim').click()
|
||||||
|
r.check('3.2c: Maria says "I\'m on it" → the other screen shows her name on the item, live', await pill(other, 'Maria'))
|
||||||
|
await other.click({ position: { x: 20, y: 120 } })
|
||||||
|
r.check('3.2c: on the other screen there is nothing left to take (no claim button)',
|
||||||
|
await other.getByTestId('card-prepare').isVisible() && await other.getByTestId('card-claim').count() === 0)
|
||||||
|
const takeover = await page2.evaluate(async ([o, i]) => {
|
||||||
|
try { await window.__xeniaClient.post(`/api/kds/orders/${o}/items/${i}/claim`); return 'allowed' } catch (e) { return e.response?.data?.error?.code }
|
||||||
|
}, [second.id, item2Id])
|
||||||
|
r.check('3.2c: Nikos can\'t take Maria\'s item (kds.item_claimed)', takeover === 'kds.item_claimed', takeover)
|
||||||
|
await page2.keyboard.press('Escape')
|
||||||
|
|
||||||
|
await card2.click({ position: { x: 20, y: 120 } })
|
||||||
|
await card2.getByTestId('card-claim').click() // Maria lets go
|
||||||
|
r.check('3.2c: Maria lets go → the name goes on the other screen', await noPill(other))
|
||||||
|
await other.click({ position: { x: 20, y: 120 } })
|
||||||
|
await other.getByTestId('card-claim').click() // Nikos takes it
|
||||||
|
r.check('3.2c: Nikos takes it → Maria\'s screen shows "Nikos"', await pill(card2, 'Nikos'))
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'terminal-kds-claim.png') })
|
||||||
|
await other.click({ position: { x: 20, y: 120 } })
|
||||||
|
await other.locator('[data-item]').first().click() // Nikos bumps it: done
|
||||||
|
r.check('3.2c: bumping clears the claim (both screens, backend)', await noPill(card2) && (await kdsItem(second.id, item2Id))?.claimed_by == null
|
||||||
|
&& (await kdsItem(second.id, item2Id))?.kds_status === 'done')
|
||||||
|
await page2.context().close()
|
||||||
|
|
||||||
await page.getByRole('button', { name: 'Sign out' }).click()
|
await page.getByRole('button', { name: 'Sign out' }).click()
|
||||||
r.check('sign out → back to the names', await shown(page, 'user-grid'))
|
r.check('sign out → back to the names', await shown(page, 'user-grid'))
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user