diff --git a/docs/README.md b/docs/README.md index fcc149e..b29c7cb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -50,6 +50,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media///` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). **`data/media` belongs in every site backup together with `pos.db`** (the database only holds ids and hashes; DEPLOYMENT_GUIDE → Backups). Served public by hash at `/api/media/file//` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m`. **Videos (5.4e, `services/video.py`):** MP4 / MOV / WebM kept as uploaded; a background thread (`start_worker` in `main.py`'s lifespan, one video at a time, low priority, 2 threads) makes the still frame (the same `thumb` / `card` / `full` WebP) and, when `needs_version()` says so (not H.264 MP4, over 1920 px, 10-bit / HDR, other audio, > 12 Mbps), `play.mp4` (H.264 + AAC, ≤ 1920 px, HDR tone-mapped, faststart). `Media.processing` waiting → working (`progress`) → done | failed; migration 0031 queues existing videos. ffmpeg comes from the pinned `imageio-ffmpeg` wheel (static, Linux x86-64 / ARM64 / Windows; `XENIA_FFMPEG` overrides); without it videos stay as uploaded (`processing` null). `urls` gains `thumb`/`card`/`full`/`play` as they exist; `media.video_src()` is what a screen plays; `video.on_done(fn)` listeners (signage tells the screens playing it) | | `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out | | `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage. **Call a waiter (5.7b):** device config `table` (ref `tables`) + `call_waiter`; `POST /api/menu-tablet/call` sends a `table_call` staff message (the open order's waiters, else the zone's; `qr_orders.waiters_for`) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" **Ordering at the table (6.6, D-30):** `services/tablet_orders.py` + `models/tablet_order.py` (`tablet_orders`, 0034). Device config `ordering` (off), `bill`, and per-tablet overrides `order_confirm` / `order_no_order` / `order_max_items` / `order_max_of_one` / `order_min_seconds` (-1 / `venue` = the venue's); the venue's rules are the JSON setting `menu_tablet.ordering` (`GET/PUT /api/menu-tablet/ordering`, Settings → Menu tablets). `/menu` adds `table.can_order`, `table.can_see_bill` and `ordering` (rules + `choices`: the POS product shape at in-store prices, so the tablet reuses `pos/ProductDialog`). `POST /quote` / `/order` take POS lines by id (`pos_cart.resolve_line`, never prices or discounts); every order is a `TabletOrder` row (it also times the limit); kitchen mode places it with `orders_api.add_priced_items(source="tablet")`, waiter mode leaves it `waiting` until `POST /requests/{id}/accept|decline` (`ordering.orders.open`; the phone's `TabletRequests` on the table page). Events: `tablet_order_updated` {id, table_id, status} to all (the phones refresh their list), `menu_tablet.order` to the tablet. Staff message type `tablet_order`. `GET/POST /bill`: the table's open order and asking for the bill (a `table_call` message, once a minute) | +| `local_backend/routers/pricing.py`, `services/pricing.py`, `manager_dashboard/src/pages/pricing/` | Pricing (6.7): price groups, modifiers (price rules), deals, discount limits. Every set-up endpoint needs `pricing.manage` and broadcasts `pricing.changed` (the page's `useLiveQuery`); the phones keep reading rules / deals with any signed-in user. Conditions are checked on save (`_condition_ok` → `pricing.bad_condition`): an incomplete one used to raise in `services/pricing.py::_eval_condition` at quote time. Venue limits live in settings `discounts.*` (empty = no limit; `pricing.bad_limit`). The page's rules as data: `pricingLogic.js` (`tests/pricing.test.mjs`) | | `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more | | `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) | | `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` | diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 0a39893..55c8d8c 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -233,6 +233,8 @@ CODES: dict[str, tuple[int, str]] = { "price_group.not_found": (404, "Price group not found."), "modifier.not_found": (404, "Price rule not found."), "deal.not_found": (404, "Deal not found."), + "pricing.bad_condition": (422, "A condition is incomplete: fill in all its values."), + "pricing.bad_limit": (422, "A discount limit must be a number of 0 or more, or empty for no limit."), "catalog.category_not_found": (404, "Category not found."), "catalog.parent_not_found": (404, "The parent category doesn't exist."), "catalog.nest_has_children": (400, "A category with sub-categories can't go under another one."), diff --git a/local_backend/routers/pricing.py b/local_backend/routers/pricing.py index 18d4449..d006ce4 100644 --- a/local_backend/routers/pricing.py +++ b/local_backend/routers/pricing.py @@ -20,12 +20,21 @@ from schemas.pricing import ( WaiterDiscountSettingsIn, WaiterDiscountSettingsOut, PriceEventOut, ) -from routers.deps import get_current_user, require_manager +from routers.deps import get_current_user +from core.access.deps import require from models.user import User from core.errors import XeniaError router = APIRouter() +MANAGE = "pricing.manage" # setting up price groups, modifiers, deals and the discount limits (6.7) + + +def _changed() -> None: + """Tell the manager's pricing pages (and the counters' quotes) that the rules changed.""" + from services.ws_bus import broadcast_sync + broadcast_sync("pricing.changed", {}) + @@ -45,7 +54,7 @@ def list_price_groups( def create_price_group( body: PriceGroupCreate, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): pg = PriceGroup( name=body.name, @@ -59,6 +68,7 @@ def create_price_group( ) db.add(pg) db.commit() + _changed() db.refresh(pg) return pg @@ -68,7 +78,7 @@ def update_price_group( group_id: int, body: PriceGroupUpdate, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first() if not pg: @@ -81,6 +91,7 @@ def update_price_group( pg.auto_disable_time = body.auto_disable_time pg.auto_days = json.dumps(body.auto_days) if body.auto_days is not None else None db.commit() + _changed() db.refresh(pg) return pg @@ -89,13 +100,14 @@ def update_price_group( def toggle_price_group( group_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first() if not pg: raise XeniaError("price_group.not_found") pg.is_active = 0 if pg.is_active else 1 db.commit() + _changed() db.refresh(pg) return pg @@ -104,13 +116,14 @@ def toggle_price_group( def delete_price_group( group_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first() if not pg: raise XeniaError("price_group.not_found") db.delete(pg) db.commit() + _changed() # ============================================================================= @@ -150,7 +163,7 @@ def list_favorite_modifiers( def create_modifier( body: PriceModifierCreate, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): m = PriceModifier( name=body.name, @@ -172,6 +185,7 @@ def create_modifier( _sync_conditions(m, body.conditions, db, model="modifier") _sync_modifier_targets(m, body.targets, db) db.commit() + _changed() db.refresh(m) return m @@ -181,7 +195,7 @@ def update_modifier( modifier_id: int, body: PriceModifierUpdate, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first() if not m: @@ -209,6 +223,7 @@ def update_modifier( _sync_conditions(m, body.conditions, db, model="modifier") _sync_modifier_targets(m, body.targets, db) db.commit() + _changed() db.refresh(m) return m @@ -217,7 +232,7 @@ def update_modifier( def toggle_modifier( modifier_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first() if not m: @@ -226,6 +241,7 @@ def toggle_modifier( m.updated_at = utcnow() m.updated_by = user.id db.commit() + _changed() db.refresh(m) return m @@ -234,13 +250,14 @@ def toggle_modifier( def reorder_modifiers( body: PriceModifierReorderRequest, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): for item in body.items: db.query(PriceModifier).filter(PriceModifier.id == item.id).update( {"sort_order": item.sort_order} ) db.commit() + _changed() return {"ok": True} @@ -248,13 +265,14 @@ def reorder_modifiers( def delete_modifier( modifier_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first() if not m: raise XeniaError("modifier.not_found") db.delete(m) db.commit() + _changed() # ============================================================================= @@ -273,7 +291,7 @@ def list_deals( def create_deal( body: DealCreate, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): d = Deal( name=body.name, @@ -298,6 +316,7 @@ def create_deal( _sync_conditions(d, body.conditions, db, model="deal") _sync_deal_targets(d, body.targets, db) db.commit() + _changed() db.refresh(d) return d @@ -307,7 +326,7 @@ def update_deal( deal_id: int, body: DealUpdate, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): d = db.query(Deal).filter(Deal.id == deal_id).first() if not d: @@ -335,6 +354,7 @@ def update_deal( _sync_conditions(d, body.conditions, db, model="deal") _sync_deal_targets(d, body.targets, db) db.commit() + _changed() db.refresh(d) return d @@ -343,13 +363,14 @@ def update_deal( def toggle_deal( deal_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): d = db.query(Deal).filter(Deal.id == deal_id).first() if not d: raise XeniaError("deal.not_found") d.is_active = 0 if d.is_active else 1 db.commit() + _changed() db.refresh(d) return d @@ -358,13 +379,14 @@ def toggle_deal( def delete_deal( deal_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): d = db.query(Deal).filter(Deal.id == deal_id).first() if not d: raise XeniaError("deal.not_found") db.delete(d) db.commit() + _changed() # ============================================================================= @@ -374,7 +396,7 @@ def delete_deal( @router.get("/discount-settings/global") def get_global_discount_settings( db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): from models.settings import PosSettings keys = [ @@ -387,33 +409,48 @@ def get_global_discount_settings( row_map = {r.key.split(".", 1)[1]: r.value for r in rows} # Coerce types so frontend toggle/number fields work correctly def _coerce(k, v): - if v is None: - return None + if v is None or v == "" or v == "None": + return None if k != "enabled" else True if k == "enabled": return v.lower() in ("true", "1", "yes") try: return float(v) if "." in str(v) else int(v) except Exception: return v - return {k: _coerce(k, v) for k, v in row_map.items()} + out = {k: None for k in ("max_total_value_workday", "max_total_value_shift", "max_items_per_shift")} + out["enabled"] = True + out.update({k: _coerce(k, v) for k, v in row_map.items()}) + return out @router.put("/discount-settings/global") def set_global_discount_settings( body: dict, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): from models.settings import PosSettings allowed = { "enabled", "max_total_value_workday", "max_total_value_shift", "max_items_per_shift", } - now = utcnow().isoformat() + now = utcnow() # was .isoformat(): saving failed on platform v2 for k, v in body.items(): if k not in allowed: continue full_key = f"discounts.{k}" + if k == "enabled": + v = "true" if v in (True, "true", "1", 1) else "false" + elif v is None or v == "": + v = "" # no limit + else: + try: + v = float(v) + except (TypeError, ValueError): + raise XeniaError("pricing.bad_limit", key=k) + if v < 0: + raise XeniaError("pricing.bad_limit", key=k) + v = int(v) if k == "max_items_per_shift" or v.is_integer() else v row = db.query(PosSettings).filter(PosSettings.key == full_key).first() if row: row.value = str(v) @@ -421,6 +458,7 @@ def set_global_discount_settings( else: db.add(PosSettings(key=full_key, value=str(v), updated_at=now)) db.commit() + _changed() return {"ok": True} @@ -441,7 +479,7 @@ def get_my_discount_settings( def get_waiter_discount_settings( user_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): s = db.query(WaiterDiscountSettings).filter( WaiterDiscountSettings.user_id == user_id @@ -457,7 +495,7 @@ def set_waiter_discount_settings( user_id: int, body: WaiterDiscountSettingsIn, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("pricing.manage")), ): s = db.query(WaiterDiscountSettings).filter( WaiterDiscountSettings.user_id == user_id @@ -474,6 +512,7 @@ def set_waiter_discount_settings( s.max_items_per_workday = body.max_items_per_workday s.max_items_per_order = body.max_items_per_order db.commit() + _changed() db.refresh(s) return s @@ -643,8 +682,50 @@ def dismiss_deal_offer( # Internal helpers # ============================================================================= +def _condition_ok(ctype: str, p: dict) -> bool: + """A condition the price engine can evaluate (an incomplete one used to break the POS).""" + import re + from datetime import date + + def hhmm(v): + return isinstance(v, str) and re.fullmatch(r"([01]\d|2[0-3]):[0-5]\d", v) is not None + + def day(v): + try: + date.fromisoformat(v) + return True + except (TypeError, ValueError): + return False + + def num(v, low): + return isinstance(v, (int, float)) and not isinstance(v, bool) and v >= low + + if ctype == "time_range": + return hhmm(p.get("from")) and hhmm(p.get("to")) and p["from"] != p["to"] + if ctype == "date_range": + return day(p.get("from")) and day(p.get("to")) and p["from"] <= p["to"] + if ctype == "specific_date": + return bool(p.get("dates")) and all(day(d) for d in p["dates"]) + if ctype == "day_of_week": + return bool(p.get("days")) and all(isinstance(d, int) and 0 <= d <= 6 for d in p["days"]) + if ctype == "min_item_quantity": + return num(p.get("min", 1), 1) + if ctype == "min_category_qty": + return isinstance(p.get("category_id"), int) and num(p.get("min", 1), 1) + if ctype == "min_order_value": + return num(p.get("min", 0), 0) + if ctype == "order_channel": + return bool(p.get("channels")) + if ctype == "price_group_active": + return isinstance(p.get("price_group_id"), int) + return ctype in ("user_tier", "low_stock") # old placeholders: kept, never added + + def _sync_conditions(parent, conditions_in, db: Session, model: str): """Write condition rows for a modifier or deal.""" + for c in conditions_in: + if not _condition_ok(c.condition_type, c.params or {}): + raise XeniaError("pricing.bad_condition", type=c.condition_type) for c in conditions_in: if model == "modifier": db.add(PriceModifierCondition( diff --git a/local_backend/services/pricing.py b/local_backend/services/pricing.py index 0297ba1..1628c52 100644 --- a/local_backend/services/pricing.py +++ b/local_backend/services/pricing.py @@ -654,7 +654,10 @@ def check_waiter_discount_limits( # --- Global limits from pos_settings --- def _gs(key): row = db.query(PosSettings).filter(PosSettings.key == key).first() - return float(row.value) if row and row.value else None + try: + return float(row.value) if row and row.value else None + except ValueError: # an old "None" (fixed in 6.7): no limit + return None g_max_wd_value = _gs("discounts.max_total_value_workday") g_max_shift_val = _gs("discounts.max_total_value_shift") diff --git a/local_backend/tests/test_pricing_setup.py b/local_backend/tests/test_pricing_setup.py new file mode 100644 index 0000000..9ae2148 --- /dev/null +++ b/local_backend/tests/test_pricing_setup.py @@ -0,0 +1,71 @@ +"""Pricing set-up on platform v2 (plan step 6.7): who may change it, conditions the price engine +can evaluate, the venue's discount limits, live changes, and a happy-hour rule pricing a sale.""" +from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures) +from tests.test_pos import menu, till # noqa: F401 (fixtures) + + +def happy_hour(**extra): + return {"name": "Happy hour", "action_type": "add_percent", "action_value": -20, "scope": "global", + "targets": [{"target_type": "all"}], + "conditions": [{"condition_type": "time_range", "params": {"from": "00:00", "to": "23:59"}}], **extra} + + +def test_only_pricing_managers_change_the_rules(client, owner_h, make_user, login): + waiter = login(make_user(role="waiter"), client="waiter") + assert client.get("/api/pricing/modifiers", headers=waiter).status_code == 200 # the phones read them + assert client.post("/api/pricing/modifiers", headers=waiter, json=happy_hour()).status_code == 403 + assert client.put("/api/pricing/discount-settings/global", headers=waiter, json={"enabled": False}).status_code == 403 + assert client.post("/api/pricing/modifiers", headers=owner_h, json=happy_hour()).status_code == 201 + + +def test_incomplete_conditions_are_refused(client, owner_h): + for cond in ({"condition_type": "time_range", "params": {"from": "17:00"}}, + {"condition_type": "date_range", "params": {"from": "2026-12-01", "to": "2026-11-01"}}, + {"condition_type": "day_of_week", "params": {"days": []}}, + {"condition_type": "price_group_active", "params": {}}, + {"condition_type": "min_category_qty", "params": {"min": 2}}): + r = client.post("/api/pricing/modifiers", headers=owner_h, json=happy_hour(conditions=[cond])) + assert err(r) == "pricing.bad_condition", cond + deal = {"name": "Beer", "action_type": "free_item", "conditions": [{"condition_type": "order_channel", "params": {"channels": []}}]} + assert err(client.post("/api/pricing/deals", headers=owner_h, json=deal)) == "pricing.bad_condition" + + +def test_the_venue_discount_limits(client, owner_h, db): + from models.settings import PosSettings + assert client.get("/api/pricing/discount-settings/global", headers=owner_h).json() == { + "enabled": True, "max_total_value_workday": None, "max_total_value_shift": None, "max_items_per_shift": None} + r = client.put("/api/pricing/discount-settings/global", headers=owner_h, + json={"enabled": False, "max_total_value_workday": 50, "max_total_value_shift": 12.5, "max_items_per_shift": None}) + assert r.status_code == 200 + assert client.get("/api/pricing/discount-settings/global", headers=owner_h).json() == { + "enabled": False, "max_total_value_workday": 50, "max_total_value_shift": 12.5, "max_items_per_shift": None} + # "no limit" is stored empty (it used to be "None", which broke every later discount) + row = db.query(PosSettings).filter(PosSettings.key == "discounts.max_items_per_shift").first() + assert row is None or row.value == "" + assert err(client.put("/api/pricing/discount-settings/global", headers=owner_h, json={"max_items_per_shift": -1})) == "pricing.bad_limit" + + +def test_changes_are_announced(client, owner_h, monkeypatch): + import services.ws_bus as bus + sent = [] + monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, **kw: sent.append(t)) + g = client.post("/api/pricing/groups", headers=owner_h, json={"name": "Summer"}).json() + client.patch(f"/api/pricing/groups/{g['id']}/toggle", headers=owner_h) + assert sent.count("pricing.changed") == 2 + + +def test_a_happy_hour_rule_prices_a_counter_sale(client, owner_h, till, menu): + """The done-when: a happy-hour modifier made in the manager prices a POS sale.""" + line = {"product_id": menu["coffee"].id, "quantity": 2} + before = client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json() + assert before["total"] == 6.0 + r = client.post("/api/pricing/modifiers", headers=owner_h, json=happy_hour(targets=[{"target_type": "item", "target_ids": [menu["coffee"].id]}])) + assert r.status_code == 201, r.text + after = client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json() + assert after["lines"][0]["unit_price"] == 2.4 and after["total"] == 4.8 + # the burger isn't a target: its price stays + burger = client.post("/api/pos/quote", headers=till["h"], json={"lines": [{"product_id": menu["burger"].id, "quantity": 1, + "prefs": [{"set_id": menu["cook"].id, "choices": [{"id": menu["rare"].id}], "shared": "Fries"}]}]}).json() + assert burger["total"] == 10.0 + client.patch(f"/api/pricing/modifiers/{r.json()['id']}/toggle", headers=owner_h) # off: back to the menu price + assert client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()["total"] == 6.0 diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 83c92b3..52db3cf 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -38,7 +38,7 @@ import SessionsPage from './pages/staff/SessionsPage' import ApprovalsPage from './pages/staff/ApprovalsPage' import ManagementSchedulePage from './pages/Management/SchedulePage' import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage' -import PricingPage from './pages/Management/PricingPage' +import PricingPage from './pages/pricing/PricingPage' // Inventory import ThrowawaysPage from './pages/inventory/ThrowawaysPage' diff --git a/manager_dashboard/src/pages/Management/PricingPage.jsx b/manager_dashboard/src/pages/Management/PricingPage.jsx deleted file mode 100644 index 3091a11..0000000 --- a/manager_dashboard/src/pages/Management/PricingPage.jsx +++ /dev/null @@ -1,43 +0,0 @@ -import { useState } from 'react' -import { Percent, Tag, Gift, Users } from 'lucide-react' -import { TabGroup, TabCard } from '../../ui/Tabs' -import PriceGroupsTab from './pricing/PriceGroupsTab' -import ModifiersTab from './pricing/ModifiersTab' -import DealsTab from './pricing/DealsTab' -import DiscountSettingsTab from './pricing/DiscountSettingsTab' - -const TABS = [ - { id: 'groups', label: 'Ομάδες Τιμών', icon: Tag }, - { id: 'modifiers', label: 'Τροποποιητές Τιμής', icon: Percent }, - { id: 'deals', label: 'Προσφορές', icon: Gift }, - { id: 'discounts', label: 'Ρυθμίσεις Εκπτώσεων', icon: Users }, -] - -export default function PricingPage() { - const [tab, setTab] = useState('groups') - - return ( -
- {/* Page header */} -
-
- -
-
-

Προσφορές & Τιμές

-

Δυναμικές τιμές, τροποποιητές, προσφορές και εκπτώσεις

-
-
- - - -
- {tab === 'groups' && } - {tab === 'modifiers' && } - {tab === 'deals' && } - {tab === 'discounts' && } -
-
-
- ) -} diff --git a/manager_dashboard/src/pages/Management/pricing/DealsTab.jsx b/manager_dashboard/src/pages/Management/pricing/DealsTab.jsx deleted file mode 100644 index b1aed8b..0000000 --- a/manager_dashboard/src/pages/Management/pricing/DealsTab.jsx +++ /dev/null @@ -1,690 +0,0 @@ -import { useState } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import { Plus, Gift, Power, Pencil, Trash2, X, Info } from 'lucide-react' -import toast from 'react-hot-toast' -import client from '../../../api/client' -import { useTranslation } from '@xenia/i18n' -import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access' -import Button from '../../../ui/Button' -import Modal from '../../../ui/Modal' -import { ConfirmModal } from '../../../ui/Modal' - -// ─── API ───────────────────────────────────────────────────────────────────── - -const api = { - list: () => client.get('/api/pricing/deals').then(r => r.data), - create: body => client.post('/api/pricing/deals', body).then(r => r.data), - update: (id,b) => client.put(`/api/pricing/deals/${id}`, b).then(r => r.data), - toggle: id => client.patch(`/api/pricing/deals/${id}/toggle`).then(r => r.data), - remove: id => client.delete(`/api/pricing/deals/${id}`), - modifiers: () => client.get('/api/pricing/modifiers').then(r => r.data), - products: () => client.get('/api/products', { params: { all: true } }).then(r => r.data), - categories:() => client.get('/api/products/categories').then(r => r.data), -} - -const COLORS = [ - '#6366f1','#8b5cf6','#ec4899','#f43f5e','#f97316', - '#eab308','#22c55e','#14b8a6','#0ea5e9','#64748b', -] - -const CONDITION_TYPES = [ - { value: 'min_item_quantity', label: 'Ελάχιστη ποσότητα αντικειμένου' }, - { value: 'min_order_value', label: 'Ελάχιστη αξία παραγγελίας' }, - { value: 'time_range', label: 'Ώρα ημέρας' }, - { value: 'day_of_week', label: 'Ημέρα εβδομάδας' }, - { value: 'date_range', label: 'Εύρος ημερομηνιών' }, - { value: 'order_channel', label: 'Σημείο πώλησης' }, - { value: 'price_group_active',label: 'Ομάδα τιμής ενεργή' }, -] - -const DAYS = ['Δευτέρα','Τρίτη','Τετάρτη','Πέμπτη','Παρασκευή','Σάββατο','Κυριακή'] -const CHANNELS = SALES_POINTS // phase 3S: the order_channel condition holds sales points - -const ACTION_TYPES = [ - { value: 'apply_modifier', label: 'Εφαρμογή τροποποιητή' }, - { value: 'set_price', label: 'Ορισμός τιμής' }, - { value: 'add_amount', label: '± Ποσό €' }, - { value: 'add_percent', label: '± Ποσοστό %' }, - { value: 'free_item', label: 'Δωρεάν προϊόν' }, - { value: 'free_choice', label: 'Επιλογή δωρεάν προϊόντος' }, -] - -// ─── Reuse condition editor (simplified for deals) ──────────────────────────── - -function ConditionRow({ cond, onChange, onRemove, groups }) { - const { t } = useTranslation('common') - const set = (k, v) => onChange({ ...cond, params: { ...cond.params, [k]: v } }) - const setType = t => onChange({ condition_type: t, params: {} }) - - return ( -
-
- - -
- - {cond.condition_type === 'min_item_quantity' && ( -
- - set('min', Number(e.target.value))} /> -
- )} - {cond.condition_type === 'min_order_value' && ( -
- - set('min', Number(e.target.value))} /> -
- )} - {cond.condition_type === 'time_range' && ( -
-
- - set('from', e.target.value)} /> -
-
- - set('to', e.target.value)} /> -
-
- )} - {cond.condition_type === 'day_of_week' && ( -
- {DAYS.map((d, i) => ( - - ))} -
- )} - {cond.condition_type === 'date_range' && ( -
-
- - set('from', e.target.value)} /> -
-
- - set('to', e.target.value)} /> -
-
- )} - {cond.condition_type === 'order_channel' && ( -
- {CHANNELS.map(ch => ( - - ))} -
- )} - {cond.condition_type === 'price_group_active' && ( -
- -
- )} -
- ) -} - -// ─── Shared multi-picker (same logic as ModifiersTab) ───────────────────────── - -function MultiPicker({ items, selected, onToggle, labelKey = 'name', valueKey = 'id' }) { - return ( -
- {items.length === 0 && ( -

Δεν βρέθηκαν αποτελέσματα

- )} - {items.map(item => { - const val = item[valueKey] - const checked = selected.includes(val) - return ( -
onToggle(val)} - className={`flex items-center gap-2.5 px-3 py-1.5 cursor-pointer transition-colors text-[12px] border-b border-slate-100 last:border-0 ${ - checked ? 'bg-sky-50 text-sky-700' : 'hover:bg-slate-50 text-slate-700' - }`}> -
- {checked && } -
- {item[labelKey]} -
- ) - })} -
- ) -} - -function TagPicker({ selected, onToggle, onAdd, allTags }) { - const [draft, setDraft] = useState('') - const handleAdd = () => { - const tag = draft.trim() - if (tag && !selected.includes(tag)) onAdd(tag) - setDraft('') - } - return ( -
- {allTags.length > 0 && ( -
- {allTags.map(tag => { - const active = selected.includes(tag) - return ( - - ) - })} -
- )} - {selected.length > 0 && ( -
- {selected.map(tag => ( - - {tag} - - - ))} -
- )} -
- setDraft(e.target.value)} - onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); handleAdd() } }} /> - -
-
- ) -} - -// ─── Deal target row ────────────────────────────────────────────────────────── - -function DealTargetRow({ target, onChange, onRemove, products, categories, allTags }) { - const ids = target.target_ids ?? [] - const tags = target.target_tags ?? [] - const setIds = v => onChange({ ...target, target_ids: v, target_id: v[0] ?? null }) - const setTags = v => onChange({ ...target, target_tags: v, target_tag: v[0] ?? null }) - const toggleId = id => setIds(ids.includes(id) ? ids.filter(x => x !== id) : [...ids, id]) - const toggleTag = tag => setTags(tags.includes(tag) ? tags.filter(x => x !== tag) : [...tags, tag]) - - return ( -
-
- - -
- {target.target_type === 'item' && ( - - )} - {target.target_type === 'category' && ( - - )} - {target.target_type === 'tag' && ( - setTags([...tags, tag])} allTags={allTags} /> - )} -
- ) -} - -// ─── Deal form ──────────────────────────────────────────────────────────────── - -const DEAL_TABS = [ - { key: 'info', label: 'Πληροφορίες' }, - { key: 'trigger', label: 'Trigger & Συνθήκες' }, - { key: 'action', label: 'Ενέργεια' }, -] - -function DealForm({ initial, onSave, onCancel, saving, modifiers, groups, activeTab, onTabChange }) { - const { data: products = [] } = useQuery({ - queryKey: ['products-all-pricing'], - queryFn: () => client.get('/api/products/', { params: { all: true } }).then(r => r.data), - }) - const { data: categories = [] } = useQuery({ - queryKey: ['categories'], - queryFn: () => client.get('/api/products/categories').then(r => r.data), - staleTime: 60_000, - }) - const { data: allTags = [] } = useQuery({ - queryKey: ['product-tags'], - queryFn: () => client.get('/api/products/tags').then(r => r.data), - staleTime: 60_000, - }) - - const normalizeTarget = t => ({ - ...t, - target_ids: t.target_ids ?? (t.target_id != null ? [t.target_id] : []), - target_tags: t.target_tags ?? (t.target_tag ? [t.target_tag] : []), - }) - - const blank = { - name: '', description: '', color: COLORS[6], is_active: true, sort_order: 0, - action_type: 'free_item', - action_modifier_id: null, action_value: null, - action_free_item_id: null, - action_free_target_type: 'item', action_free_target_ids: [], - action_free_quantity: 1, - conditions: [], targets: [{ target_type: 'any', target_id: null, target_tag: null, target_ids: [], target_tags: [] }], - } - const [f, setF] = useState(initial ? { - ...blank, ...initial, - conditions: initial.conditions ?? [], - targets: (initial.targets ?? [{ target_type: 'any', target_id: null, target_tag: null, target_ids: [], target_tags: [] }]).map(normalizeTarget), - action_free_target_ids: initial.action_free_target_ids ?? [], - } : blank) - - const set = (k, v) => setF(p => ({ ...p, [k]: v })) - - const addCond = () => set('conditions', [...f.conditions, { condition_type: 'min_item_quantity', params: { min: 1 } }]) - const updCond = (i, c) => set('conditions', f.conditions.map((x, j) => j === i ? c : x)) - const remCond = i => set('conditions', f.conditions.filter((_, j) => j !== i)) - - const addTarget = () => set('targets', [...f.targets, { target_type: 'any', target_id: null, target_tag: null, target_ids: [], target_tags: [] }]) - const updTarget = (i, t) => set('targets', f.targets.map((x, j) => j === i ? t : x)) - const remTarget = i => set('targets', f.targets.filter((_, j) => j !== i)) - - const toggleFreeId = id => { - const ids = f.action_free_target_ids ?? [] - set('action_free_target_ids', ids.includes(id) ? ids.filter(x => x !== id) : [...ids, id]) - } - - function submit(e) { - e.preventDefault() - if (!f.name.trim()) return toast.error('Απαιτείται όνομα') - onSave({ - ...f, - action_free_target_ids: f.action_free_target_ids?.length ? f.action_free_target_ids : null, - }) - } - - return ( -
- - {/* ── Info tab ── */} - {activeTab === 'info' && ( - <> -
-
- - set('name', e.target.value)} - placeholder="π.χ. 3+1 Μπύρες" autoFocus /> -
-
- - set('description', e.target.value)} /> -
-
- -
-
- -
- {COLORS.map(c => ( -
-
- -
- - )} - - {/* ── Trigger & Conditions tab ── */} - {activeTab === 'trigger' && ( - <> -
-
-
- Trigger - Αγορά αυτών -
- -
-

- Ποια προϊόντα πρέπει να υπάρχουν στην παραγγελία για να ενεργοποιηθεί η προσφορά; -

- {f.targets.map((t, i) => ( - updTarget(i, v)} onRemove={() => remTarget(i)} - products={products} categories={categories} allTags={allTags} /> - ))} -
- -
-
-
- Επιπλέον Συνθήκες - (προαιρετικά) -
- -
- {f.conditions.length === 0 && ( -

- Χωρίς επιπλέον συνθήκες — αρκεί μόνο το trigger. -

- )} - {f.conditions.map((c, i) => ( - updCond(i, v)} onRemove={() => remCond(i)} groups={groups} /> - ))} -
- - )} - - {/* ── Action tab ── */} - {activeTab === 'action' && ( -
-
- {ACTION_TYPES.map(({ value, label }) => ( - - ))} -
- - {f.action_type === 'apply_modifier' && ( -
- - -

Εμφανίζονται μόνο τροποποιητές χωρίς συνθήκες (χειροκίνητοι).

-
- )} - - {(f.action_type === 'set_price' || f.action_type === 'add_amount' || f.action_type === 'add_percent') && ( -
- - set('action_value', Number(e.target.value))} /> -
- )} - - {f.action_type === 'free_item' && ( -
-
- - -
-
- - set('action_free_quantity', Number(e.target.value))} /> -
-
- )} - - {f.action_type === 'free_choice' && ( -
-
- {[['item','Προϊόντα'],['category','Κατηγορία'],['tag','Ετικέτα']].map(([v,l]) => ( - - ))} -
- {f.action_free_target_type === 'item' && ( -
- {products.map(p => ( - - ))} -
- )} - {f.action_free_target_type === 'category' && ( -
- {categories.map(c => ( - - ))} -
- )} - {f.action_free_target_type === 'tag' && ( -
- -