feat(terminal): quick sale at the counter: cash/card/split, change, cash drawer, fiscal (platform-v2 3.3b)

- POST /api/pos/sales: all checks first (shift, lines, payment split, cash given,
  discount → ordering.prices.modify or manager approval, fiscal VAT groups), then the
  existing open_order / add_items / pay_items functions, so tickets, KDS, price events,
  shift totals and the fiscal receipt work as for any order.
- Cash drawer: printer_service.open_cash_drawer (ESC @ + ESC p 0 25 250) to the screen's
  receipt printer on cash, logged and audited (DRAWER_OPENED / DRAWER_FAILED).
- orders._can_access_order: the people assigned to an order may act on it (a cashier's
  own takeaway order); pos_cart prices a batch with the lines before it, as add_items does.
- Terminal: Charge → payment dialog (exact cash pre-selected, quick amounts, change,
  card, split by line), per-line discounts, sale summary and "Same again".
- Tests: backend +6 (socket printer receives the drawer kick, fiscal file in the bridge
  folder), terminal unit +1, terminal.mjs +9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 00:28:33 +02:00
co-authored by Claude Opus 5.5
parent 17bee66df1
commit bff82a332a
15 changed files with 632 additions and 14 deletions
+3
View File
@@ -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_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."),
"pos.shift_required": (409, "Start your shift before selling."),
"pos.payment_invalid": (422, "This payment doesn't add up ({reason})."),
"pos.fiscal_vat_missing": (422, "Fiscal receipts are on, but these products have no VAT group: {names}."),
"pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."),
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."),
+3
View File
@@ -77,6 +77,9 @@ def _can_access_order(order: Order, user: User, db: Session) -> bool:
Standalone orders (table_id=None) are accessible to all waiters with any zone assignment."""
if holds(user, "core.dashboard.access"):
return True
# Whoever the order is assigned to may act on it (e.g. a cashier's own counter sale, 3.3b)
if any(ow.waiter_id == user.id for ow in order.waiters):
return True
zones = db.query(WaiterZone).filter(WaiterZone.waiter_id == user.id).all()
if not zones:
return False
+99 -1
View File
@@ -3,6 +3,8 @@
GET /api/pos/session the signed-in cashier's shift and the business day (shift gate)
GET /api/pos/menu categories and products to sell, with options and today's price
POST /api/pos/quote a cart priced by the backend (services/pos_cart.py)
POST /api/pos/sales a quick sale (3.3b): order + items + payment(s) in one call, the
cash drawer on cash, the fiscal receipt as for any payment
Prices are never computed on the screen: the menu's `price` is the pricing engine's answer for
one unit with no options right now (happy hours, price groups), and the cart is priced with
@@ -150,11 +152,107 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi
priced = pos_cart.price_lines(db, lines, body.order_type) if lines else []
out = []
for line, (unit, events) in zip(lines, priced):
adj = pos_cart.discount_adjustment(unit, line.discount_pct)
out.append({
"product_id": line.product.id, "name": line.product.name, "quantity": line.quantity,
"base_price": round(line.product.base_price, 2), "extra": line.extra,
"unit_price": round(unit, 2), "total": round(unit * line.quantity, 2),
"discount_pct": line.discount_pct, "discount": adj,
"unit_price": round(unit + adj, 2), "total": round((unit + adj) * line.quantity, 2),
"entries": [{"name": e["name"], "price": e["price_delta"], "type": e["type"]} for e in line.entries],
"removed": line.removed, "notes": line.notes, "adjustments": _adjustments(db, events),
})
return {"order_type": body.order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)}
# ── quick sale (3.3b) ─────────────────────────────────────────────────────────
class Payment(BaseModel):
method: Literal["cash", "card"]
lines: Optional[List[int]] = None # indexes into `lines`; None = all of them
class SaleBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(min_length=1, max_length=200)
payments: List[Payment] = Field(min_length=1, max_length=2)
cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
def _payment_groups(body: SaleBody, n: int) -> list:
if len(body.payments) == 1 and body.payments[0].lines is None:
return [(body.payments[0].method, list(range(n)))]
seen = [i for pay in body.payments for i in (pay.lines or [])]
if sorted(seen) != list(range(n)) or len({pay.method for pay in body.payments}) != len(body.payments):
raise XeniaError("pos.payment_invalid", reason="lines")
return [(pay.method, list(pay.lines)) for pay in body.payments if pay.lines]
@router.post("/sales", status_code=201)
def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Sell the cart on the spot: open a takeaway / counter order (no table), add the lines
exactly as POST /api/orders/{id}/items would (prices, price events, deals, kitchen
tickets, KDS), take the payment(s) through POST /api/orders/{id}/pay (the cashier's
shift, the fiscal receipt, auto-close), and open the cash drawer of the screen's receipt
printer when cash was taken. The checks run before anything is written. Discounted lines
need ordering.prices.modify or a manager's approval (D-10)."""
from core.access.context import authorize, current_device
from core.modules import device_config
from models.order import OrderItem
from models.printer import Printer
from models.shift import WaiterShift
from models.user import User
from routers import orders as orders_api
from schemas.order import AddItemsRequest, OrderCreate, OrderItemInput, PayItemsRequest, SelectedOptionInput
from services.fiscal_service import is_fiscal_enabled
from services.printer_service import open_cash_drawer
if not isinstance(user, User) or db.query(WaiterShift).filter(
WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() is None:
raise XeniaError("pos.shift_required")
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
groups = _payment_groups(body, len(lines))
if any(line.discount_pct for line in lines):
authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
if is_fiscal_enabled(db):
missing = sorted({line.product.name for line in lines if not line.product.fiscal_vat_group_id})
if missing:
raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
priced = pos_cart.price_lines(db, lines, body.order_type)
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)]
cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2)
if body.cash_given is not None and cash_due and body.cash_given + 0.004 < cash_due:
raise XeniaError("pos.payment_invalid", reason="cash_short")
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
items_in = [OrderItemInput(
product_id=line.product.id, quantity=line.quantity,
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
) for line, adj in zip(lines, adjs)]
added = orders_api.add_items(order.id, AddItemsRequest(items=items_in), db, user)
item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
paid, fiscal = [], None
for method, idx in groups:
res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=[item_ids[i] for i in idx], payment_method=method), db, user)
paid.append({"method": method, "amount": round(sum(totals[i] for i in idx), 2), "item_ids": res["paid_item_ids"]})
fiscal = res.get("fiscal") or fiscal
drawer = "none"
if cash_due > 0:
dev = current_device(request, db)
cfg = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db)
printer = db.get(Printer, cfg["receipt_printer_id"]) if cfg.get("receipt_printer_id") else None
if printer is not None and printer.is_active:
ok, _ = open_cash_drawer(printer, db, reason=f"order {order.id}")
drawer = "opened" if ok else "failed"
orders_api._audit(db, order.id, "DRAWER_OPENED" if ok else "DRAWER_FAILED", waiter_id=user.id, note=printer.name)
db.commit()
change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None
return {
"order_id": order.id, "total": round(sum(totals), 2), "payments": paid,
"cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal,
"print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []),
}
+17 -3
View File
@@ -20,7 +20,9 @@ Rules (the same as the waiter's options dialog, waiter_pwa ItemOptionsModal.jsx)
- quantities: per-choice qty only on multi-select sets, per-add-on qty only on allow_multiple.
Anything else → XeniaError("pos.line_invalid", line=n, reason=...), reason one of
product_unavailable | unknown_quick | unknown_option | unknown_choice | unknown_sub |
choice_required | sub_required | unknown_ingredient | quantity.
choice_required | sub_required | unknown_ingredient | quantity | discount.
A line may carry `discount_pct` (0–100, whole percent): the quote shows it; selling it needs
ordering.prices.modify or a manager's approval (routers/pos.py).
"""
from __future__ import annotations
@@ -61,6 +63,7 @@ class Line:
entries: list = field(default_factory=list) # selected_options entries
removed: list = field(default_factory=list) # ingredient names
notes: Optional[str] = None
discount_pct: int = 0 # 3.3b: needs ordering.prices.modify (or approval)
@property
def extra(self) -> float:
@@ -96,6 +99,10 @@ def resolve_line(db, raw: dict, n: int) -> Line:
if isinstance(quantity, bool) or not isinstance(quantity, (int, float)) or quantity <= 0 or quantity > 999:
raise _bad(n, "quantity")
line = Line(product=product, quantity=quantity, notes=(raw.get("notes") or "").strip() or None)
pct = raw.get("discount_pct", 0) or 0
if isinstance(pct, bool) or not isinstance(pct, int) or not 0 <= pct <= 100:
raise _bad(n, "discount")
line.discount_pct = pct
quick = {q.id: q for q in product.quick_options}
for sel in raw.get("quick") or []:
@@ -170,8 +177,8 @@ def resolve_line(db, raw: dict, n: int) -> Line:
def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | None = None):
"""[(unit_price, [PriceEvent])] for each line, with the same context POST
/api/orders/{id}/items builds: the order's existing items plus this line (the other new
lines of the same batch don't count, as there)."""
/api/orders/{id}/items builds: the order's existing items, the lines before it in the
same batch (at their resolved price), and this line."""
from core.timeutil import utcnow
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = utcnow()
@@ -186,4 +193,11 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No
ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active)
unit, events = resolve_price(p, line.quantity, line.extra, ctx, db)
out.append((unit, events))
cart.append({**here, "unit_price": unit})
return out
def discount_adjustment(unit_price: float, pct) -> float:
"""A line's discount (percent of its unit price) as the order item's price_adjustment
(negative, rounded to cents)."""
return -round(unit_price * pct / 100.0, 2) if pct else 0.0
+21
View File
@@ -324,6 +324,27 @@ def send_test_beep(ip: str, port: int, n1: int, n2: int, n3: int, codepage_n: in
return False, str(e)
DRAWER_KICK = bytes([0x1b, 0x70, 0x00, 0x19, 0xfa]) # ESC p m t1 t2: pin 2, 50 ms on, 500 ms off
def open_cash_drawer(printer, db: Session, reason: str = "") -> Tuple[bool, str]:
"""Pulse the cash drawer wired to `printer` (counter POS cash payments, plan step 3.3b).
A job of its own: ESC @ then ESC p 0 25 250, nothing printed. Logs one line either way.
Spoof printing drops it like any print. -> (ok, error)"""
if _is_spoof_mode(db):
logger.info("Cash drawer: spoof printing ON, not sent to %s (%s)", printer.name, reason)
return True, ""
try:
p = Network(printer.ip_address, printer.port, timeout=PRINTER_TIMEOUT)
p._raw(bytes([0x1b, 0x40]) + DRAWER_KICK)
p.close()
logger.info("Cash drawer: opened on %s (%s:%s) %s", printer.name, printer.ip_address, printer.port, reason)
return True, ""
except Exception as e:
logger.warning("Cash drawer: FAILED on %s (%s:%s) %s: %s", printer.name, printer.ip_address, printer.port, reason, e)
return False, str(e)
def send_test_print(ip: str, port: int, name: str, codepage_n: int = 29) -> Tuple[bool, str]:
if is_spoof_mode():
logger.info("Spoof printing ON — dropping test print for %s", name)
+152
View File
@@ -143,3 +143,155 @@ def test_pos_settings_validate_their_references(client, owner_h, till, menu):
assert err(client.patch(f"/api/devices/{till['id']}", headers=owner_h,
json={"config": {"receipt_printer_id": 999999}})) == "validation.device_config"
assert client.get("/api/pos/menu", headers=till["h"]).json()["settings"]["default_order_type"] == "here"
# ── quick sale (3.3b) ────────────────────────────────────────────────────────
import socket
import threading
import time
@pytest.fixture
def on_shift(db, till, make_user):
"""An open business day and the cashier's own shift with 50 in the drawer."""
from core.timeutil import business_date_of, utcnow
from models.business_day import BusinessDay
from models.shift import WaiterShift
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if day is None:
day = BusinessDay(status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()),
opened_by_id=make_user(role="owner").id)
db.add(day)
db.flush()
shift = WaiterShift(waiter_id=till["cashier"].id, business_day_id=day.id, starting_cash=50)
db.add(shift)
db.commit()
return shift
@pytest.fixture
def drawer_printer(db, client, owner_h, till):
"""A printer on a local socket that records what it gets; the till's receipt printer."""
from models.printer import Printer
srv = socket.socket()
srv.bind(("127.0.0.1", 0))
srv.listen(4)
got = []
def serve():
while True:
try:
conn, _ = srv.accept()
except OSError:
return
data = b""
while chunk := conn.recv(1024):
data += chunk
got.append(data)
conn.close()
threading.Thread(target=serve, daemon=True).start()
printer = Printer(name="Counter receipt", ip_address="127.0.0.1", port=srv.getsockname()[1], is_active=True)
db.add(printer)
db.commit()
assert client.patch(f"/api/devices/{till['id']}", headers=owner_h,
json={"config": {"receipt_printer_id": printer.id}}).status_code == 200
yield got
srv.close()
def sale(client, till, lines, payments, **extra):
return client.post("/api/pos/sales", headers=till["h"], json={"order_type": "takeaway", "lines": lines, "payments": payments, **extra})
def test_cash_sale_pays_gives_change_and_opens_the_drawer(client, db, till, menu, on_shift, drawer_printer):
from models.order import OrderItem
m = menu
r = sale(client, till, [burger_line(m), {"product_id": m["coffee"].id, "quantity": 2}], [{"method": "cash"}], cash_given=20)
assert r.status_code == 201, r.text
body = r.json()
assert body["total"] == 16.0 and body["change"] == 4.0 and body["drawer"] == "opened"
for _ in range(20):
if drawer_printer:
break
time.sleep(0.05)
assert drawer_printer and drawer_printer[0].endswith(bytes([0x1b, 0x70, 0x00, 0x19, 0xfa])) # ESC p 0 25 250
items = db.query(OrderItem).filter(OrderItem.order_id == body["order_id"]).order_by(OrderItem.id).all()
assert [i.status for i in items] == ["paid", "paid"] and {i.payment_method for i in items} == {"cash"}
assert {i.paid_in_shift_id for i in items} == {on_shift.id}
# the burger's choices were stored as the waiter app stores them, with the database's prices
assert json.loads(items[0].selected_options) == [{"id": m["rare"].id, "name": "Rare", "price_delta": 0.0, "extra_cost": None, "type": "pref"},
{"id": None, "name": "Fries", "price_delta": 0.0, "extra_cost": None, "type": "pref_sub"}]
shift = client.get("/api/shifts/my", headers=till["h"]).json()
assert shift["cash_sales"] == 16.0 and shift["net_to_deliver"] == 66.0
def test_card_and_split_payments(client, db, till, menu, on_shift, drawer_printer):
m = menu
r = sale(client, till, [{"product_id": m["coffee"].id}], [{"method": "card"}])
assert r.status_code == 201 and r.json()["drawer"] == "none" and r.json()["change"] is None
r = sale(client, till, [burger_line(m), {"product_id": m["coffee"].id}],
[{"method": "card", "lines": [0]}, {"method": "cash", "lines": [1]}], cash_given=5)
assert r.status_code == 201, r.text
assert [(p["method"], p["amount"]) for p in r.json()["payments"]] == [("card", 10.0), ("cash", 3.0)]
assert r.json()["change"] == 2.0 and r.json()["drawer"] == "opened"
shift = client.get("/api/shifts/my", headers=till["h"]).json()
assert (shift["cash_sales"], shift["card_sales"]) == (3.0, 13.0)
def test_sale_checks_run_before_anything_is_written(client, db, till, menu, on_shift):
from models.order import Order
before = db.query(Order).count()
m = menu
assert err(sale(client, till, [{"product_id": m["coffee"].id}], [{"method": "cash"}], cash_given=1)) == "pos.payment_invalid"
assert err(sale(client, till, [{"product_id": m["coffee"].id}, {"product_id": m["coffee"].id}],
[{"method": "cash", "lines": [0]}, {"method": "card", "lines": [0]}])) == "pos.payment_invalid"
assert err(sale(client, till, [{"product_id": m["burger"].id}], [{"method": "cash"}])) == "pos.line_invalid"
# a discount needs ordering.prices.modify, or a manager's approval
assert err(sale(client, till, [{"product_id": m["coffee"].id, "discount_pct": 10}], [{"method": "card"}])) == "access.override_possible"
assert db.query(Order).count() == before
def test_a_manager_can_sell_with_a_discount(client, pair, make_user, menu, db):
from core.timeutil import business_date_of, utcnow
from models.business_day import BusinessDay
from models.shift import WaiterShift
token, _ = pair("pos_counter", "Till 2")
boss = make_user(role="owner")
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"}
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() or BusinessDay(
status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id)
db.add(day)
db.flush()
db.add(WaiterShift(waiter_id=boss.id, business_day_id=day.id))
db.commit()
q = client.post("/api/pos/quote", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "discount_pct": 10}]}).json()
assert q["lines"][0]["unit_price"] == 2.7 and q["lines"][0]["discount"] == -0.3
r = client.post("/api/pos/sales", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "discount_pct": 10}], "payments": [{"method": "card"}]})
assert r.status_code == 201 and r.json()["total"] == 2.7
def test_sale_needs_the_cashiers_shift(client, till, menu):
assert err(sale(client, till, [{"product_id": menu["coffee"].id}], [{"method": "card"}])) == "pos.shift_required"
def test_fiscal_receipt_follows_the_payment(client, db, till, menu, on_shift, tmp_path):
from models.settings import PosSettings
for key, value in (("fiscal.enabled", "true"), ("fiscal.out_folder", str(tmp_path / "out")), ("fiscal.in_folder", str(tmp_path / "in"))):
row = db.get(PosSettings, key)
if row is None:
db.add(PosSettings(key=key, value=value))
else:
row.value = value
db.commit()
assert err(sale(client, till, [{"product_id": menu["coffee"].id}], [{"method": "cash"}])) == "pos.fiscal_vat_missing"
menu["coffee"].fiscal_vat_group_id = 2
db.commit()
r = sale(client, till, [{"product_id": menu["coffee"].id}], [{"method": "cash"}])
assert r.status_code == 201 and r.json()["fiscal"] == "pending"
for _ in range(40):
files = list((tmp_path / "out").glob("*")) if (tmp_path / "out").exists() else []
if files:
break
time.sleep(0.05)
assert files, "the fiscal file was written to the bridge's OUT folder"
+4 -1
View File
@@ -79,6 +79,9 @@
"claim_needs_staff": "Μόνο μέλος του προσωπικού μπορεί να αναλάβει ένα είδος."
},
"pos": {
"line_invalid": "Η γραμμή {{line}} του καλαθιού δεν μπορεί να πουληθεί όπως επιλέχθηκε ({{reason}})."
"line_invalid": "Η γραμμή {{line}} του καλαθιού δεν μπορεί να πουληθεί όπως επιλέχθηκε ({{reason}}).",
"shift_required": "Ξεκινήστε τη βάρδιά σας πριν πουλήσετε.",
"payment_invalid": "Αυτή η πληρωμή δεν βγαίνει ({{reason}}).",
"fiscal_vat_missing": "Οι φορολογικές αποδείξεις είναι ενεργές, αλλά αυτά τα προϊόντα δεν έχουν ομάδα ΦΠΑ: {{names}}."
}
}
+33
View File
@@ -204,6 +204,39 @@
"startingCash": "Μετρητά στο συρτάρι τώρα",
"badAmount": "Γράψτε ένα ποσό, π.χ. 50 ή 50,00",
"start": "Έναρξη βάρδιας"
},
"charge": "Χρέωση {{total}}",
"discount": "Έκπτωση",
"noDiscount": "Χωρίς έκπτωση",
"discountNeedsApproval": "Μια έκπτωση χρειάζεται έγκριση διαχειριστή κατά τη χρέωση.",
"discountLine": "−{{pct}}%: {{amount}} το ένα",
"pay": {
"title": "Πληρωμή: {{total}}",
"method": "Τρόπος πληρωμής",
"cash": "Μετρητά",
"card": "Κάρτα",
"split": "Μοιρασμένα",
"confirmCash": "Είσπραξη {{amount}} μετρητά",
"confirmCard": "Πληρώθηκαν {{amount}} με κάρτα",
"confirmSplit": "Είσπραξη",
"cashPart": "Μετρητά: {{amount}}",
"cardPart": "Κάρτα: {{amount}}",
"cardHint": "Πληκτρολογήστε {{amount}} στο τερματικό καρτών και επιβεβαιώστε εδώ μόλις εγκριθεί.",
"given": "Μετρητά που δόθηκαν",
"exact": "Ακριβώς: {{amount}}",
"change": "Ρέστα: {{amount}}",
"short": "Είναι λιγότερα από το ποσό που οφείλεται"
},
"done": {
"paid": "Πληρώθηκαν {{total}}",
"cash": "Μετρητά {{amount}}",
"card": "Κάρτα {{amount}}",
"drawerOpened": "Το συρτάρι άνοιξε",
"drawerFailed": "Το συρτάρι δεν άνοιξε",
"fiscal": "Η απόδειξη στάλθηκε στον φορολογικό μηχανισμό",
"again": "Τα ίδια ξανά",
"toast": "Πληρώθηκε",
"toastChange": "Πληρώθηκε. Ρέστα: {{change}}"
}
}
}
+4 -1
View File
@@ -79,6 +79,9 @@
"claim_needs_staff": "Only a staff member can claim an item."
},
"pos": {
"line_invalid": "Cart line {{line}} can't be sold as chosen ({{reason}})."
"line_invalid": "Cart line {{line}} can't be sold as chosen ({{reason}}).",
"shift_required": "Start your shift before selling.",
"payment_invalid": "This payment doesn't add up ({{reason}}).",
"fiscal_vat_missing": "Fiscal receipts are on, but these products have no VAT group: {{names}}."
}
}
+33
View File
@@ -204,6 +204,39 @@
"startingCash": "Cash in the drawer now",
"badAmount": "Enter an amount, e.g. 50 or 50,00",
"start": "Start shift"
},
"charge": "Charge {{total}}",
"discount": "Discount",
"noDiscount": "No discount",
"discountNeedsApproval": "A discount needs a manager's approval when you charge.",
"discountLine": "−{{pct}}%: {{amount}} each",
"pay": {
"title": "Payment: {{total}}",
"method": "Payment method",
"cash": "Cash",
"card": "Card",
"split": "Split",
"confirmCash": "Take {{amount}} in cash",
"confirmCard": "Paid {{amount}} by card",
"confirmSplit": "Take the payment",
"cashPart": "Cash: {{amount}}",
"cardPart": "Card: {{amount}}",
"cardHint": "Enter {{amount}} on the card terminal, then confirm here once it's approved.",
"given": "Cash given",
"exact": "Exact: {{amount}}",
"change": "Change: {{amount}}",
"short": "That's less than the amount due"
},
"done": {
"paid": "Paid {{total}}",
"cash": "Cash {{amount}}",
"card": "Card {{amount}}",
"drawerOpened": "Drawer opened",
"drawerFailed": "The drawer didn't open",
"fiscal": "Receipt sent to the fiscal device",
"again": "Same again",
"toast": "Paid",
"toastChange": "Paid. Change: {{change}}"
}
}
}
+117
View File
@@ -0,0 +1,117 @@
// Taking the payment at the counter (plan step 3.3b, D-26): cash (amount given → change,
// quick amounts), card (typed on the card terminal, recorded as card), or split between them
// by line. One call does the whole sale (POST /api/pos/sales): order, kitchen tickets,
// payment(s) on the cashier's shift, fiscal receipt, cash drawer. Cash with the exact amount
// is pre-selected: Charge → Cash → Take = three taps.
import { useState } from 'react'
import { Banknote, Check, CreditCard, Split } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input } from '@xenia/ui'
import client from '../../api/client'
import { changeFor, quickAmounts, splitPayments } from './logic/cart'
const tab = on => `flex-1 min-h-[var(--x-control-lg)] rounded-control flex items-center justify-center gap-2 text-body-lg font-medium transition-colors duration-fast
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
export default function PaymentDialog({ cart, quote, orderType, names, onPaid, onClose }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const total = quote.total
const totals = quote.lines.map(l => l.total)
const [method, setMethod] = useState('cash')
const [split, setSplit] = useState(() => cart.map(() => 'card'))
const parts = splitPayments(split, totals)
const cashDue = method === 'cash' ? total : method === 'split' ? parts.cash : 0
const [givenText, setGivenText] = useState('') // empty = the exact amount
const given = givenText.trim() === '' ? null : parseNumber(givenText, { decimals: 2, allowNegative: false })
const change = cashDue > 0 ? changeFor(given ?? cashDue, cashDue) : null
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const short = cashDue > 0 && change == null
const pay = async () => {
if (busy || short) return
setBusy(true)
setError('')
const payments = method === 'split' ? parts.payments : [{ method }]
try {
const { data } = await client.post('/api/pos/sales', {
order_type: orderType, lines: cart, payments, cash_given: cashDue > 0 ? (given ?? cashDue) : null,
})
onPaid(data)
} catch (err) {
setError(errorMessage(err, t))
} finally {
setBusy(false)
}
}
return (
<Dialog open onClose={busy ? undefined : onClose} size="md" title={t('pos.pay.title', { total: formatMoney(total) })}
footer={<>
<Button variant="secondary" size="lg" onClick={onClose} disabled={busy}>{t('pos.dialog.close')}</Button>
<Button size="lg" icon={<Check size={18} />} loading={busy} disabled={short || (method === 'split' && (!parts.cash || !parts.card))}
onClick={pay} data-testid="pay-confirm">
{method === 'card' ? t('pos.pay.confirmCard', { amount: formatMoney(total) })
: method === 'cash' ? t('pos.pay.confirmCash', { amount: formatMoney(total) })
: t('pos.pay.confirmSplit')}
</Button>
</>}>
<div className="grid gap-4" data-testid="payment-dialog">
<div className="flex gap-2" role="radiogroup" aria-label={t('pos.pay.method')}>
{[['cash', Banknote], ['card', CreditCard], ['split', Split]].map(([m, Icon]) => (
<button key={m} type="button" role="radio" aria-checked={method === m} className={tab(method === m)} onClick={() => { setMethod(m); setGivenText('') }} data-testid={`pay-${m}`}>
<Icon size={18} />{t(`pos.pay.${m}`)}
</button>
))}
</div>
{method === 'split' && (
<div className="grid gap-1" data-testid="split-lines">
{cart.map((line, i) => (
<div key={i} className="flex items-center gap-2 py-1 border-b border-line">
<span className="flex-1 min-w-0 text-body text-ink truncate">{line.quantity}× {names[i]}</span>
<span className="text-body text-ink-2">{formatMoney(totals[i])}</span>
<span className="flex gap-1">
{['cash', 'card'].map(m => (
<button key={m} type="button" aria-pressed={split[i] === m} data-split={`${i}-${m}`}
onClick={() => setSplit(s => s.map((x, j) => (j === i ? m : x)))}
className={`px-3 min-h-[var(--x-control-sm)] rounded-control text-label font-medium ${split[i] === m ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
{t(`pos.pay.${m}`)}
</button>
))}
</span>
</div>
))}
<div className="flex justify-between text-body pt-1">
<span>{t('pos.pay.cashPart', { amount: formatMoney(parts.cash) })}</span>
<span>{t('pos.pay.cardPart', { amount: formatMoney(parts.card) })}</span>
</div>
</div>
)}
{method === 'card' && <p className="text-body text-ink-2">{t('pos.pay.cardHint', { amount: formatMoney(total) })}</p>}
{cashDue > 0 && (
<div className="grid gap-2">
<label className="grid gap-1 text-label text-ink-2">
{t('pos.pay.given')}
<Input inputMode="decimal" size="lg" value={givenText} onChange={e => setGivenText(e.target.value)} data-testid="cash-given"
placeholder={t('pos.pay.exact', { amount: formatMoney(cashDue) })} />
</label>
<div className="flex flex-wrap gap-2">
{quickAmounts(cashDue).map(a => (
<Button key={a} variant="secondary" onClick={() => setGivenText(a.toFixed(2))} data-testid="quick-amount">{formatMoney(a)}</Button>
))}
</div>
<div className={`text-heading font-semibold ${short ? 'text-danger-ink' : 'text-ink'}`} data-testid="change">
{short ? t('pos.pay.short') : t('pos.pay.change', { amount: formatMoney(change) })}
</div>
</div>
)}
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div>
</Dialog>
)
}
+56 -8
View File
@@ -1,14 +1,17 @@
// The counter POS screen (plan step 3.3a): categories on the left, the product grid with a
// search on top, the cart on the right. A tap adds a product (or opens its choices when it
// has preferences to pick); the (i) button checks its price without adding it. Every price is
// the backend's: the menu's and the cart's quote. Paying comes in 3.3b.
// the backend's: the menu's and the cart's quote. Charge → PaymentDialog (3.3b); after a sale
// the cart shows what happened and "Same again".
import { useMemo, useState } from 'react'
import { Info, Minus, Plus, Search, ShoppingBag, Trash2, Utensils, X } from 'lucide-react'
import { Banknote, Info, Minus, Plus, Repeat, Search, ShoppingBag, Trash2, Utensils, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
import { useCan } from '@xenia/access'
import { Button, EmptyState, IconButton, Input, Select, Spinner, useToast } from '@xenia/ui'
import {
addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf,
DISCOUNTS, addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf,
} from './logic/cart'
import PaymentDialog from './PaymentDialog'
import ProductDialog from './ProductDialog'
import { useMenu, useQuote } from './usePos'
@@ -27,7 +30,12 @@ function Counter({ menu, t }) {
const [orderType, setOrderType] = useState(menu.settings.default_order_type)
const [cart, setCart] = useState([])
const [dialog, setDialog] = useState(null) // product
const [paying, setPaying] = useState(false)
const [lastSale, setLastSale] = useState(null) // { lines, orderType, result }
const quote = useQuote(cart, orderType)
const toast = useToast()
const canDiscount = useCan('ordering.prices.modify')
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
const byId = useMemo(() => new Map(menu.products.map(p => [p.id, p])), [menu.products])
const categories = useMemo(() => categoriesWithProducts(menu.categories, menu.products), [menu])
@@ -84,11 +92,13 @@ function Counter({ menu, t }) {
))}
</div>
<div className="flex-1 overflow-y-auto">
{cart.length === 0 && lastSale && <SaleDone sale={lastSale} onAgain={() => { setCart(lastSale.lines); setOrderType(lastSale.orderType); setLastSale(null) }} />}
{cart.length === 0
? <EmptyState compact title={t('pos.cartEmpty')} description={t('pos.cartEmptyBody')} />
? !lastSale && <EmptyState compact title={t('pos.cartEmpty')} description={t('pos.cartEmptyBody')} />
: cart.map((line, i) => (
<CartLine key={i} line={line} priced={quote.quote?.lines?.[i]} product={byId.get(line.product_id)}
onQty={q => setCart(c => setLineQty(c, i, q))} />
<CartLine key={i} line={line} priced={quote.quote?.lines?.[i]} product={byId.get(line.product_id)} canDiscount={canDiscount}
onQty={q => setCart(c => setLineQty(c, i, q))}
onDiscount={pct => setCart(c => c.map((l, j) => (j === i ? { ...l, discount_pct: pct || undefined } : l)))} />
))}
</div>
<div className="border-t border-line p-3 grid gap-3">
@@ -99,10 +109,24 @@ function Counter({ menu, t }) {
{formatMoney(quote.quote?.total ?? 0)}
</span>
</div>
<Button size="lg" icon={<Banknote size={20} />} disabled={!ready} onClick={() => setPaying(true)} data-testid="charge">
{t('pos.charge', { total: formatMoney(quote.quote?.total ?? 0) })}
</Button>
<Button variant="secondary" icon={<Trash2 size={16} />} disabled={!cart.length} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
</div>
</aside>
{paying && quote.quote && (
<PaymentDialog cart={cart} quote={quote.quote} orderType={orderType} names={cart.map(l => byId.get(l.product_id)?.name ?? '')}
onClose={() => setPaying(false)}
onPaid={result => {
setPaying(false)
setLastSale({ lines: cart, orderType, result })
setCart([])
toast.success(result.change != null ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
}} />
)}
{dialog && (
<ProductDialog product={dialog} orderType={orderType} onClose={() => setDialog(null)}
onAdd={line => setCart(c => addLine(c, line))} />
@@ -145,7 +169,26 @@ function ProductCard({ product, onTap, onInfo }) {
)
}
function CartLine({ line, priced, product, onQty }) {
function SaleDone({ sale, onAgain }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const r = sale.result
return (
<div className="m-3 p-4 rounded-card bg-success-soft text-success-ink grid gap-2" data-testid="sale-done" data-order={r.order_id}>
<div className="text-title font-semibold">{t('pos.done.paid', { total: formatMoney(r.total) })}</div>
{r.change != null && <div className="text-heading font-semibold" data-testid="sale-change">{t('pos.pay.change', { amount: formatMoney(r.change) })}</div>}
<div className="text-label">
{r.payments.map(p => t(`pos.done.${p.method}`, { amount: formatMoney(p.amount) })).join(' · ')}
{r.drawer === 'opened' && ` · ${t('pos.done.drawerOpened')}`}
{r.drawer === 'failed' && <span className="text-danger-ink"> · {t('pos.done.drawerFailed')}</span>}
{r.fiscal === 'pending' && ` · ${t('pos.done.fiscal')}`}
</div>
<Button variant="secondary" icon={<Repeat size={16} />} onClick={onAgain} data-testid="same-again">{t('pos.done.again')}</Button>
</div>
)
}
function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = product ? unitOf(product) : null
@@ -169,7 +212,12 @@ function CartLine({ line, priced, product, onQty }) {
<span className="min-w-12 text-center text-body font-semibold" data-testid="line-qty">{qtyText}</span>
<IconButton size="sm" variant="secondary" label={t('pos.more')} onClick={() => onQty(line.quantity + step)}><Plus size={16} /></IconButton>
{priced && line.quantity !== 1 && <span className="text-caption text-ink-3">{t('pos.each', { price: formatMoney(priced.unit_price) })}</span>}
<span className="flex-1" />
<Select size="sm" value={String(line.discount_pct ?? 0)} onChange={e => onDiscount(Number(e.target.value))} aria-label={t('pos.discount')}
title={canDiscount ? undefined : t('pos.discountNeedsApproval')} data-testid="line-discount" className="w-36"
options={DISCOUNTS.map(d => ({ value: String(d), label: d ? `−${d}%` : t('pos.noDiscount') }))} />
</div>
{priced?.discount ? <span className="text-label text-success-ink">{t('pos.discountLine', { pct: priced.discount_pct, amount: formatMoney(priced.discount) })}</span> : null}
</div>
)
}
+34
View File
@@ -187,3 +187,37 @@ export const UNITS = {
}
export const unitOf = product => UNITS[product.unit_type] ?? null
// ── paying (3.3b) ───────────────────────────────────────────────────────────
/** Amounts a customer typically hands over for `total`: the exact amount, then the next
* round amounts above it (notes of 5, 10, 20, 50, 100), at most five. */
export function quickAmounts(total) {
const out = [round2(total)]
for (const step of [5, 10, 20, 50, 100]) {
const v = Math.ceil((total + 0.0001) / step) * step
if (v > total + 0.004 && !out.includes(v)) out.push(v)
}
return out.slice(0, 5)
}
/** Change to give back (null when not enough was given). */
export function changeFor(given, due) {
if (given == null || Number.isNaN(given)) return null
const c = round2(given - due)
return c < 0 ? null : c
}
/** Cash and card parts of a split: methods[i] is 'cash' | 'card' for line i, totals from the
* quote. → { cash, card, payments } (payments as POST /api/pos/sales takes them). */
export function splitPayments(methods, totals) {
const lines = { cash: [], card: [] }
methods.forEach((m, i) => lines[m].push(i))
const sum = idx => round2(idx.reduce((s, i) => s + (totals[i] ?? 0), 0))
const payments = ['card', 'cash'].filter(m => lines[m].length).map(m => ({ method: m, lines: lines[m] }))
return { cash: sum(lines.cash), card: sum(lines.card), payments }
}
export const DISCOUNTS = [0, 5, 10, 15, 20, 25, 50, 100]
const round2 = n => Math.round(n * 100) / 100
+11
View File
@@ -87,3 +87,14 @@ test('cart: the same choices add up, different choices are separate lines; 0 rem
assert.deepEqual(setLineQty(cart, 0, 0).map(l => l.product_id), [1, 1])
assert.equal(setLineQty(cart, 0, 0.30000000000000004)[0].quantity, 0.3)
})
test('paying: quick amounts, change, split parts (3.3b)', async () => {
const { changeFor, quickAmounts, splitPayments } = await import('../src/apps/pos/logic/cart.js')
assert.deepEqual(quickAmounts(12.2), [12.2, 15, 20, 50, 100])
assert.deepEqual(quickAmounts(20), [20, 25, 30, 40, 50])
assert.equal(changeFor(20, 16), 4)
assert.equal(changeFor(15, 16), null)
assert.equal(changeFor(16, 16), 0)
assert.deepEqual(splitPayments(['card', 'cash', 'cash'], [10, 3, 2.5]),
{ cash: 5.5, card: 10, payments: [{ method: 'card', lines: [0] }, { method: 'cash', lines: [1, 2] }] })
})
+45
View File
@@ -10,6 +10,7 @@
// - server unreachable → banner → back by itself
// - removed from the manager → back to pairing with a notice and a new code
// node terminal.mjs
import net from 'node:net'
import path from 'node:path'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, OUT, reporter, sleep } from './lib/env.mjs'
@@ -312,6 +313,12 @@ try {
} })
const posMenu = await api('GET', '/api/pos/menu', { token: boss })
const simple = posMenu.products.find(p => !p.prefs.length && p.id !== burgerP.id && p.categories.every(c => c.category_id !== cats[0].id))
// 3.3b: the counter's receipt printer is a local socket that records what it gets (cash drawer)
const drawerBytes = []
const drawerServer = net.createServer(sock => { const chunks = []; sock.on('data', c => chunks.push(c)); sock.on('end', () => drawerBytes.push(Buffer.concat(chunks))) })
await new Promise(res => drawerServer.listen(0, '127.0.0.1', res))
const receipt = await api('POST', '/api/system/printers', { token: boss, body: { name: 'Counter receipt', ip_address: '127.0.0.1', port: drawerServer.address().port, is_active: true } })
await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { config: { receipt_printer_id: receipt.id } } })
await page.locator(`[data-user="${mgr.id}"]`).click()
await page.getByLabel('Password').fill('password')
await page.getByRole('button', { name: 'Sign in' }).click()
@@ -363,6 +370,44 @@ try {
&& (await page.getByTestId('line-qty').nth(1).textContent()).includes('2') && (await page.getByTestId('cart-total').textContent()).includes(expected),
`${await page.getByTestId('cart-total').textContent()} vs ${expected}`)
await page.screenshot({ path: path.join(OUT, 'terminal-pos.png') })
// ── 3.3b: charge it ──────────────────────────────────────────────────────
const cartTotal = Number(expected)
await page.getByTestId('charge').click() // tap 1
await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 })
r.check('3.3b: Charge opens the payment on cash with the exact amount', await page.getByTestId('pay-cash').getAttribute('aria-checked') === 'true'
&& (await page.getByTestId('change').textContent()).includes('0.00'))
await page.getByTestId('quick-amount').nth(1).click()
const givenNow = Number((await page.getByTestId('cash-given').inputValue()).replace(',', '.'))
const changeText = await page.getByTestId('change').textContent()
r.check('3.3b: a quick amount shows the change', changeText.includes((givenNow - cartTotal).toFixed(2)), `${givenNow} → ${changeText}`)
await page.screenshot({ path: path.join(OUT, 'terminal-pos-pay.png') })
await page.getByTestId('pay-confirm').click() // tap 2 (3 with typing an amount)
r.check('3.3b: paid → the cart shows the change and is ready for the next sale', await shown(page, 'sale-done', 10_000)
&& (await page.getByTestId('sale-change').textContent()).includes((givenNow - cartTotal).toFixed(2)) && await page.getByTestId('cart-line').count() === 0)
await page.waitForFunction(() => true, null, { timeout: 100 })
for (let i = 0; i < 20 && !drawerBytes.length; i++) await sleep(100)
r.check('3.3b: the cash drawer opened (ESC p 0 25 250 to the receipt printer)',
drawerBytes.some(b => b.includes(Buffer.from([0x1b, 0x70, 0x00, 0x19, 0xfa]))) && (await page.getByTestId('sale-done').textContent()).includes('Drawer opened'))
const myShift = await page.evaluate(async () => (await window.__xeniaClient.get('/api/shifts/my')).data)
r.check('3.3b: the sale is in the cashier\'s shift cash', Math.abs(myShift.cash_sales - cartTotal) < 0.005 && Math.abs(myShift.net_to_deliver - (cartTotal + 20)) < 0.005,
JSON.stringify({ cash: myShift.cash_sales, net: myShift.net_to_deliver }))
const saleOrder = Number(await page.getByTestId('sale-done').getAttribute('data-order'))
const kdsSeen = (await api('GET', '/api/kds/orders', { token: boss })).orders.some(o => o.id === saleOrder)
r.check('3.3b: the kitchen got the order like any other (KDS)', kdsSeen)
await page.getByTestId('same-again').click()
r.check('3.3b: "Same again" puts the last sale back in the cart', await page.getByTestId('cart-line').count() === 2)
await page.waitForFunction(x => document.querySelector('[data-testid="cart-total"]')?.textContent.includes(x), expected, { timeout: 5000 }).catch(() => {})
await page.getByTestId('charge').click()
await page.getByTestId('pay-card').click()
const drawerBefore = drawerBytes.length
await page.getByTestId('pay-confirm').click()
r.check('3.3b: a card payment is recorded as card, no drawer', await page.getByTestId('sale-done').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)
&& (await page.getByTestId('sale-done').textContent()).includes('Card') && !(await page.getByTestId('sale-done').textContent()).includes('Drawer'))
await sleep(300)
r.check('3.3b: …and the drawer stayed shut', drawerBytes.length === drawerBefore)
drawerServer.close()
await page.getByRole('button', { name: 'Sign out' }).click()
// ── a customer display: no sign-in ───────────────────────────────────────