diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index b883cc9..3a7fe0b 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -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."), diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index 78040e1..07d3fa8 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -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 diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index 6bebac8..8f7edd1 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -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", []), + } diff --git a/local_backend/services/pos_cart.py b/local_backend/services/pos_cart.py index 1a22f75..46642f8 100644 --- a/local_backend/services/pos_cart.py +++ b/local_backend/services/pos_cart.py @@ -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 diff --git a/local_backend/services/printer_service.py b/local_backend/services/printer_service.py index e5faec8..c80ed1c 100644 --- a/local_backend/services/printer_service.py +++ b/local_backend/services/printer_service.py @@ -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) diff --git a/local_backend/tests/test_pos.py b/local_backend/tests/test_pos.py index d358f72..f1f2fa6 100644 --- a/local_backend/tests/test_pos.py +++ b/local_backend/tests/test_pos.py @@ -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" diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 0c78414..c9e26d6 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -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}}." } } diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index 8480180..f494ca9 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -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}}" } } } diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 31b89b0..776f94a 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -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}}." } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index da03955..03231c1 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -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}}" } } } diff --git a/terminal/src/apps/pos/PaymentDialog.jsx b/terminal/src/apps/pos/PaymentDialog.jsx new file mode 100644 index 0000000..e2d941a --- /dev/null +++ b/terminal/src/apps/pos/PaymentDialog.jsx @@ -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 ( + + ) +} diff --git a/terminal/src/apps/pos/PosScreen.jsx b/terminal/src/apps/pos/PosScreen.jsx index 216d8bc..f046856 100644 --- a/terminal/src/apps/pos/PosScreen.jsx +++ b/terminal/src/apps/pos/PosScreen.jsx @@ -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 }) { ))}