feat: pricing on v2 (platform-v2 step 6.7)
- manager src/pages/pricing: price rules, price groups, deals, discounts on the tokens, English and Greek; the rules as data in pricingLogic.js (tests/pricing.test.mjs) - routers/pricing: set-up needs pricing.manage, broadcasts pricing.changed; incomplete conditions refused (pricing.bad_condition); venue discount settings saved again (the date-as-text bug) with empty = no limit (pricing.bad_limit), old "None" tolerated - nav: Offers & pricing needs pricing.manage - tests: test_pricing_setup.py (a happy-hour rule prices a counter quote), manager.mjs e2e Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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/<sha[:2]>/<sha>/` (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/<sha>/<variant>` 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/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/<sha[:2]>/<sha>/` (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/<sha>/<variant>` 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/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/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/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) |
|
| `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()` |
|
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
||||||
|
|||||||
@@ -233,6 +233,8 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"price_group.not_found": (404, "Price group not found."),
|
"price_group.not_found": (404, "Price group not found."),
|
||||||
"modifier.not_found": (404, "Price rule not found."),
|
"modifier.not_found": (404, "Price rule not found."),
|
||||||
"deal.not_found": (404, "Deal 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.category_not_found": (404, "Category not found."),
|
||||||
"catalog.parent_not_found": (404, "The parent category doesn't exist."),
|
"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."),
|
"catalog.nest_has_children": (400, "A category with sub-categories can't go under another one."),
|
||||||
|
|||||||
@@ -20,12 +20,21 @@ from schemas.pricing import (
|
|||||||
WaiterDiscountSettingsIn, WaiterDiscountSettingsOut,
|
WaiterDiscountSettingsIn, WaiterDiscountSettingsOut,
|
||||||
PriceEventOut,
|
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 models.user import User
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
|
|
||||||
router = APIRouter()
|
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(
|
def create_price_group(
|
||||||
body: PriceGroupCreate,
|
body: PriceGroupCreate,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require("pricing.manage")),
|
||||||
):
|
):
|
||||||
pg = PriceGroup(
|
pg = PriceGroup(
|
||||||
name=body.name,
|
name=body.name,
|
||||||
@@ -59,6 +68,7 @@ def create_price_group(
|
|||||||
)
|
)
|
||||||
db.add(pg)
|
db.add(pg)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(pg)
|
db.refresh(pg)
|
||||||
return pg
|
return pg
|
||||||
|
|
||||||
@@ -68,7 +78,7 @@ def update_price_group(
|
|||||||
group_id: int,
|
group_id: int,
|
||||||
body: PriceGroupUpdate,
|
body: PriceGroupUpdate,
|
||||||
db: Session = Depends(get_db),
|
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()
|
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
|
||||||
if not pg:
|
if not pg:
|
||||||
@@ -81,6 +91,7 @@ def update_price_group(
|
|||||||
pg.auto_disable_time = body.auto_disable_time
|
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
|
pg.auto_days = json.dumps(body.auto_days) if body.auto_days is not None else None
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(pg)
|
db.refresh(pg)
|
||||||
return pg
|
return pg
|
||||||
|
|
||||||
@@ -89,13 +100,14 @@ def update_price_group(
|
|||||||
def toggle_price_group(
|
def toggle_price_group(
|
||||||
group_id: int,
|
group_id: int,
|
||||||
db: Session = Depends(get_db),
|
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()
|
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
|
||||||
if not pg:
|
if not pg:
|
||||||
raise XeniaError("price_group.not_found")
|
raise XeniaError("price_group.not_found")
|
||||||
pg.is_active = 0 if pg.is_active else 1
|
pg.is_active = 0 if pg.is_active else 1
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(pg)
|
db.refresh(pg)
|
||||||
return pg
|
return pg
|
||||||
|
|
||||||
@@ -104,13 +116,14 @@ def toggle_price_group(
|
|||||||
def delete_price_group(
|
def delete_price_group(
|
||||||
group_id: int,
|
group_id: int,
|
||||||
db: Session = Depends(get_db),
|
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()
|
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
|
||||||
if not pg:
|
if not pg:
|
||||||
raise XeniaError("price_group.not_found")
|
raise XeniaError("price_group.not_found")
|
||||||
db.delete(pg)
|
db.delete(pg)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -150,7 +163,7 @@ def list_favorite_modifiers(
|
|||||||
def create_modifier(
|
def create_modifier(
|
||||||
body: PriceModifierCreate,
|
body: PriceModifierCreate,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require("pricing.manage")),
|
||||||
):
|
):
|
||||||
m = PriceModifier(
|
m = PriceModifier(
|
||||||
name=body.name,
|
name=body.name,
|
||||||
@@ -172,6 +185,7 @@ def create_modifier(
|
|||||||
_sync_conditions(m, body.conditions, db, model="modifier")
|
_sync_conditions(m, body.conditions, db, model="modifier")
|
||||||
_sync_modifier_targets(m, body.targets, db)
|
_sync_modifier_targets(m, body.targets, db)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(m)
|
db.refresh(m)
|
||||||
return m
|
return m
|
||||||
|
|
||||||
@@ -181,7 +195,7 @@ def update_modifier(
|
|||||||
modifier_id: int,
|
modifier_id: int,
|
||||||
body: PriceModifierUpdate,
|
body: PriceModifierUpdate,
|
||||||
db: Session = Depends(get_db),
|
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()
|
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
|
||||||
if not m:
|
if not m:
|
||||||
@@ -209,6 +223,7 @@ def update_modifier(
|
|||||||
_sync_conditions(m, body.conditions, db, model="modifier")
|
_sync_conditions(m, body.conditions, db, model="modifier")
|
||||||
_sync_modifier_targets(m, body.targets, db)
|
_sync_modifier_targets(m, body.targets, db)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(m)
|
db.refresh(m)
|
||||||
return m
|
return m
|
||||||
|
|
||||||
@@ -217,7 +232,7 @@ def update_modifier(
|
|||||||
def toggle_modifier(
|
def toggle_modifier(
|
||||||
modifier_id: int,
|
modifier_id: int,
|
||||||
db: Session = Depends(get_db),
|
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()
|
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
|
||||||
if not m:
|
if not m:
|
||||||
@@ -226,6 +241,7 @@ def toggle_modifier(
|
|||||||
m.updated_at = utcnow()
|
m.updated_at = utcnow()
|
||||||
m.updated_by = user.id
|
m.updated_by = user.id
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(m)
|
db.refresh(m)
|
||||||
return m
|
return m
|
||||||
|
|
||||||
@@ -234,13 +250,14 @@ def toggle_modifier(
|
|||||||
def reorder_modifiers(
|
def reorder_modifiers(
|
||||||
body: PriceModifierReorderRequest,
|
body: PriceModifierReorderRequest,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require("pricing.manage")),
|
||||||
):
|
):
|
||||||
for item in body.items:
|
for item in body.items:
|
||||||
db.query(PriceModifier).filter(PriceModifier.id == item.id).update(
|
db.query(PriceModifier).filter(PriceModifier.id == item.id).update(
|
||||||
{"sort_order": item.sort_order}
|
{"sort_order": item.sort_order}
|
||||||
)
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
@@ -248,13 +265,14 @@ def reorder_modifiers(
|
|||||||
def delete_modifier(
|
def delete_modifier(
|
||||||
modifier_id: int,
|
modifier_id: int,
|
||||||
db: Session = Depends(get_db),
|
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()
|
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
|
||||||
if not m:
|
if not m:
|
||||||
raise XeniaError("modifier.not_found")
|
raise XeniaError("modifier.not_found")
|
||||||
db.delete(m)
|
db.delete(m)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -273,7 +291,7 @@ def list_deals(
|
|||||||
def create_deal(
|
def create_deal(
|
||||||
body: DealCreate,
|
body: DealCreate,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require("pricing.manage")),
|
||||||
):
|
):
|
||||||
d = Deal(
|
d = Deal(
|
||||||
name=body.name,
|
name=body.name,
|
||||||
@@ -298,6 +316,7 @@ def create_deal(
|
|||||||
_sync_conditions(d, body.conditions, db, model="deal")
|
_sync_conditions(d, body.conditions, db, model="deal")
|
||||||
_sync_deal_targets(d, body.targets, db)
|
_sync_deal_targets(d, body.targets, db)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(d)
|
db.refresh(d)
|
||||||
return d
|
return d
|
||||||
|
|
||||||
@@ -307,7 +326,7 @@ def update_deal(
|
|||||||
deal_id: int,
|
deal_id: int,
|
||||||
body: DealUpdate,
|
body: DealUpdate,
|
||||||
db: Session = Depends(get_db),
|
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()
|
d = db.query(Deal).filter(Deal.id == deal_id).first()
|
||||||
if not d:
|
if not d:
|
||||||
@@ -335,6 +354,7 @@ def update_deal(
|
|||||||
_sync_conditions(d, body.conditions, db, model="deal")
|
_sync_conditions(d, body.conditions, db, model="deal")
|
||||||
_sync_deal_targets(d, body.targets, db)
|
_sync_deal_targets(d, body.targets, db)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(d)
|
db.refresh(d)
|
||||||
return d
|
return d
|
||||||
|
|
||||||
@@ -343,13 +363,14 @@ def update_deal(
|
|||||||
def toggle_deal(
|
def toggle_deal(
|
||||||
deal_id: int,
|
deal_id: int,
|
||||||
db: Session = Depends(get_db),
|
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()
|
d = db.query(Deal).filter(Deal.id == deal_id).first()
|
||||||
if not d:
|
if not d:
|
||||||
raise XeniaError("deal.not_found")
|
raise XeniaError("deal.not_found")
|
||||||
d.is_active = 0 if d.is_active else 1
|
d.is_active = 0 if d.is_active else 1
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(d)
|
db.refresh(d)
|
||||||
return d
|
return d
|
||||||
|
|
||||||
@@ -358,13 +379,14 @@ def toggle_deal(
|
|||||||
def delete_deal(
|
def delete_deal(
|
||||||
deal_id: int,
|
deal_id: int,
|
||||||
db: Session = Depends(get_db),
|
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()
|
d = db.query(Deal).filter(Deal.id == deal_id).first()
|
||||||
if not d:
|
if not d:
|
||||||
raise XeniaError("deal.not_found")
|
raise XeniaError("deal.not_found")
|
||||||
db.delete(d)
|
db.delete(d)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
@@ -374,7 +396,7 @@ def delete_deal(
|
|||||||
@router.get("/discount-settings/global")
|
@router.get("/discount-settings/global")
|
||||||
def get_global_discount_settings(
|
def get_global_discount_settings(
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require("pricing.manage")),
|
||||||
):
|
):
|
||||||
from models.settings import PosSettings
|
from models.settings import PosSettings
|
||||||
keys = [
|
keys = [
|
||||||
@@ -387,33 +409,48 @@ def get_global_discount_settings(
|
|||||||
row_map = {r.key.split(".", 1)[1]: r.value for r in rows}
|
row_map = {r.key.split(".", 1)[1]: r.value for r in rows}
|
||||||
# Coerce types so frontend toggle/number fields work correctly
|
# Coerce types so frontend toggle/number fields work correctly
|
||||||
def _coerce(k, v):
|
def _coerce(k, v):
|
||||||
if v is None:
|
if v is None or v == "" or v == "None":
|
||||||
return None
|
return None if k != "enabled" else True
|
||||||
if k == "enabled":
|
if k == "enabled":
|
||||||
return v.lower() in ("true", "1", "yes")
|
return v.lower() in ("true", "1", "yes")
|
||||||
try:
|
try:
|
||||||
return float(v) if "." in str(v) else int(v)
|
return float(v) if "." in str(v) else int(v)
|
||||||
except Exception:
|
except Exception:
|
||||||
return v
|
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")
|
@router.put("/discount-settings/global")
|
||||||
def set_global_discount_settings(
|
def set_global_discount_settings(
|
||||||
body: dict,
|
body: dict,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require("pricing.manage")),
|
||||||
):
|
):
|
||||||
from models.settings import PosSettings
|
from models.settings import PosSettings
|
||||||
allowed = {
|
allowed = {
|
||||||
"enabled", "max_total_value_workday",
|
"enabled", "max_total_value_workday",
|
||||||
"max_total_value_shift", "max_items_per_shift",
|
"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():
|
for k, v in body.items():
|
||||||
if k not in allowed:
|
if k not in allowed:
|
||||||
continue
|
continue
|
||||||
full_key = f"discounts.{k}"
|
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()
|
row = db.query(PosSettings).filter(PosSettings.key == full_key).first()
|
||||||
if row:
|
if row:
|
||||||
row.value = str(v)
|
row.value = str(v)
|
||||||
@@ -421,6 +458,7 @@ def set_global_discount_settings(
|
|||||||
else:
|
else:
|
||||||
db.add(PosSettings(key=full_key, value=str(v), updated_at=now))
|
db.add(PosSettings(key=full_key, value=str(v), updated_at=now))
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
@@ -441,7 +479,7 @@ def get_my_discount_settings(
|
|||||||
def get_waiter_discount_settings(
|
def get_waiter_discount_settings(
|
||||||
user_id: int,
|
user_id: int,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require("pricing.manage")),
|
||||||
):
|
):
|
||||||
s = db.query(WaiterDiscountSettings).filter(
|
s = db.query(WaiterDiscountSettings).filter(
|
||||||
WaiterDiscountSettings.user_id == user_id
|
WaiterDiscountSettings.user_id == user_id
|
||||||
@@ -457,7 +495,7 @@ def set_waiter_discount_settings(
|
|||||||
user_id: int,
|
user_id: int,
|
||||||
body: WaiterDiscountSettingsIn,
|
body: WaiterDiscountSettingsIn,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_manager),
|
user: User = Depends(require("pricing.manage")),
|
||||||
):
|
):
|
||||||
s = db.query(WaiterDiscountSettings).filter(
|
s = db.query(WaiterDiscountSettings).filter(
|
||||||
WaiterDiscountSettings.user_id == user_id
|
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_workday = body.max_items_per_workday
|
||||||
s.max_items_per_order = body.max_items_per_order
|
s.max_items_per_order = body.max_items_per_order
|
||||||
db.commit()
|
db.commit()
|
||||||
|
_changed()
|
||||||
db.refresh(s)
|
db.refresh(s)
|
||||||
return s
|
return s
|
||||||
|
|
||||||
@@ -643,8 +682,50 @@ def dismiss_deal_offer(
|
|||||||
# Internal helpers
|
# 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):
|
def _sync_conditions(parent, conditions_in, db: Session, model: str):
|
||||||
"""Write condition rows for a modifier or deal."""
|
"""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:
|
for c in conditions_in:
|
||||||
if model == "modifier":
|
if model == "modifier":
|
||||||
db.add(PriceModifierCondition(
|
db.add(PriceModifierCondition(
|
||||||
|
|||||||
@@ -654,7 +654,10 @@ def check_waiter_discount_limits(
|
|||||||
# --- Global limits from pos_settings ---
|
# --- Global limits from pos_settings ---
|
||||||
def _gs(key):
|
def _gs(key):
|
||||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
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_wd_value = _gs("discounts.max_total_value_workday")
|
||||||
g_max_shift_val = _gs("discounts.max_total_value_shift")
|
g_max_shift_val = _gs("discounts.max_total_value_shift")
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -38,7 +38,7 @@ import SessionsPage from './pages/staff/SessionsPage'
|
|||||||
import ApprovalsPage from './pages/staff/ApprovalsPage'
|
import ApprovalsPage from './pages/staff/ApprovalsPage'
|
||||||
import ManagementSchedulePage from './pages/Management/SchedulePage'
|
import ManagementSchedulePage from './pages/Management/SchedulePage'
|
||||||
import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage'
|
import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage'
|
||||||
import PricingPage from './pages/Management/PricingPage'
|
import PricingPage from './pages/pricing/PricingPage'
|
||||||
|
|
||||||
// Inventory
|
// Inventory
|
||||||
import ThrowawaysPage from './pages/inventory/ThrowawaysPage'
|
import ThrowawaysPage from './pages/inventory/ThrowawaysPage'
|
||||||
|
|||||||
@@ -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 (
|
|
||||||
<div className="flex flex-col h-full min-h-0 p-6 gap-4">
|
|
||||||
{/* Page header */}
|
|
||||||
<div className="flex items-center gap-3 shrink-0">
|
|
||||||
<div className="w-9 h-9 rounded-xl bg-sky-100 flex items-center justify-center shrink-0">
|
|
||||||
<Percent className="w-5 h-5 text-sky-600" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h1 className="text-[15px] font-semibold text-slate-900">Προσφορές & Τιμές</h1>
|
|
||||||
<p className="text-[12px] text-slate-500">Δυναμικές τιμές, τροποποιητές, προσφορές και εκπτώσεις</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<TabCard className="flex-1">
|
|
||||||
<TabGroup tabs={TABS} active={tab} onChange={setTab} />
|
|
||||||
<div className="flex-1 overflow-y-auto">
|
|
||||||
{tab === 'groups' && <PriceGroupsTab />}
|
|
||||||
{tab === 'modifiers' && <ModifiersTab />}
|
|
||||||
{tab === 'deals' && <DealsTab />}
|
|
||||||
{tab === 'discounts' && <DiscountSettingsTab />}
|
|
||||||
</div>
|
|
||||||
</TabCard>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -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 (
|
|
||||||
<div className="border border-slate-200 rounded-lg p-3 space-y-2 bg-slate-50">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<select className="input flex-1 text-[12px]" value={cond.condition_type}
|
|
||||||
onChange={e => setType(e.target.value)}>
|
|
||||||
{CONDITION_TYPES.map(ct => <option key={ct.value} value={ct.value}>{ct.label}</option>)}
|
|
||||||
</select>
|
|
||||||
<button type="button" onClick={onRemove}
|
|
||||||
className="p-1.5 rounded text-slate-400 hover:text-rose-500 hover:bg-rose-50 transition-colors">
|
|
||||||
<X className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{cond.condition_type === 'min_item_quantity' && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Ελάχιστη ποσότητα</label>
|
|
||||||
<input type="number" min={1} className="input w-28 text-[12px]"
|
|
||||||
value={cond.params.min ?? 1} onChange={e => set('min', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{cond.condition_type === 'min_order_value' && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Ελάχιστη αξία (€)</label>
|
|
||||||
<input type="number" min={0} step={0.5} className="input w-28 text-[12px]"
|
|
||||||
value={cond.params.min ?? 0} onChange={e => set('min', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{cond.condition_type === 'time_range' && (
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Από</label>
|
|
||||||
<input type="time" className="input w-full text-[12px]" value={cond.params.from ?? ''}
|
|
||||||
onChange={e => set('from', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Έως</label>
|
|
||||||
<input type="time" className="input w-full text-[12px]" value={cond.params.to ?? ''}
|
|
||||||
onChange={e => set('to', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{cond.condition_type === 'day_of_week' && (
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{DAYS.map((d, i) => (
|
|
||||||
<button type="button" key={i}
|
|
||||||
onClick={() => { const days = cond.params.days ?? []; set('days', days.includes(i) ? days.filter(x => x !== i) : [...days, i]) }}
|
|
||||||
className={`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${
|
|
||||||
(cond.params.days ?? []).includes(i) ? 'bg-sky-100 text-sky-700' : 'bg-white border border-slate-200 text-slate-500 hover:bg-slate-50'
|
|
||||||
}`}>{d.slice(0, 3)}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{cond.condition_type === 'date_range' && (
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Από</label>
|
|
||||||
<input type="date" className="input w-full text-[12px]" value={cond.params.from ?? ''}
|
|
||||||
onChange={e => set('from', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Έως</label>
|
|
||||||
<input type="date" className="input w-full text-[12px]" value={cond.params.to ?? ''}
|
|
||||||
onChange={e => set('to', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{cond.condition_type === 'order_channel' && (
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{CHANNELS.map(ch => (
|
|
||||||
<button type="button" key={ch}
|
|
||||||
onClick={() => { const channels = normalizeSalesPoints(cond.params.channels); set('channels', channels.includes(ch) ? channels.filter(x => x !== ch) : [...channels, ch]) }}
|
|
||||||
className={`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${
|
|
||||||
normalizeSalesPoints(cond.params.channels).includes(ch) ? 'bg-sky-100 text-sky-700' : 'bg-white border border-slate-200 text-slate-500 hover:bg-slate-50'
|
|
||||||
}`}>{t(`salesPoints.${ch}.name`)}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{cond.condition_type === 'price_group_active' && (
|
|
||||||
<div>
|
|
||||||
<select className="input w-full text-[12px]" value={cond.params.price_group_id ?? ''}
|
|
||||||
onChange={e => set('price_group_id', Number(e.target.value))}>
|
|
||||||
<option value="">— Επιλογή ομάδας —</option>
|
|
||||||
{(groups ?? []).map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Shared multi-picker (same logic as ModifiersTab) ─────────────────────────
|
|
||||||
|
|
||||||
function MultiPicker({ items, selected, onToggle, labelKey = 'name', valueKey = 'id' }) {
|
|
||||||
return (
|
|
||||||
<div className="border border-slate-200 rounded-lg overflow-hidden">
|
|
||||||
{items.length === 0 && (
|
|
||||||
<p className="text-[11px] text-slate-400 px-3 py-2">Δεν βρέθηκαν αποτελέσματα</p>
|
|
||||||
)}
|
|
||||||
{items.map(item => {
|
|
||||||
const val = item[valueKey]
|
|
||||||
const checked = selected.includes(val)
|
|
||||||
return (
|
|
||||||
<div key={val} onClick={() => 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'
|
|
||||||
}`}>
|
|
||||||
<div className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${
|
|
||||||
checked ? 'bg-sky-500 border-sky-500' : 'border-slate-300 bg-white'
|
|
||||||
}`}>
|
|
||||||
{checked && <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4l3 3 5-6" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
|
|
||||||
</div>
|
|
||||||
{item[labelKey]}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
|
||||||
<div className="space-y-2">
|
|
||||||
{allTags.length > 0 && (
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{allTags.map(tag => {
|
|
||||||
const active = selected.includes(tag)
|
|
||||||
return (
|
|
||||||
<button type="button" key={tag} onClick={() => onToggle(tag)}
|
|
||||||
className={`px-2 py-0.5 rounded-full text-[11px] font-medium border transition-colors ${
|
|
||||||
active ? 'bg-sky-500 border-sky-500 text-white' : 'border-slate-300 text-slate-600 hover:border-sky-400 hover:text-sky-600'
|
|
||||||
}`}>{tag}</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{selected.length > 0 && (
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{selected.map(tag => (
|
|
||||||
<span key={tag} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-sky-100 text-sky-700 text-[11px] font-medium">
|
|
||||||
{tag}
|
|
||||||
<button type="button" onClick={() => onToggle(tag)} className="hover:text-sky-900">
|
|
||||||
<X className="w-3 h-3" />
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<input className="input flex-1 text-[12px]" placeholder="Νέο tag..." value={draft}
|
|
||||||
onChange={e => setDraft(e.target.value)}
|
|
||||||
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); handleAdd() } }} />
|
|
||||||
<button type="button" onClick={handleAdd}
|
|
||||||
className="px-3 py-1.5 rounded-lg bg-slate-100 text-slate-600 text-[12px] hover:bg-slate-200 transition-colors">
|
|
||||||
+
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── 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 (
|
|
||||||
<div className="border border-slate-200 rounded-lg p-3 space-y-2 bg-slate-50">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<select className="input flex-1 text-[12px]" value={target.target_type}
|
|
||||||
onChange={e => onChange({ target_type: e.target.value, target_id: null, target_tag: null, target_ids: [], target_tags: [] })}>
|
|
||||||
<option value="any">Οποιοδήποτε προϊόν</option>
|
|
||||||
<option value="item">Προϊόντα</option>
|
|
||||||
<option value="category">Κατηγορίες</option>
|
|
||||||
<option value="tag">Ετικέτες (tags)</option>
|
|
||||||
</select>
|
|
||||||
<button type="button" onClick={onRemove}
|
|
||||||
className="p-1.5 rounded text-slate-400 hover:text-rose-500 hover:bg-rose-50 transition-colors">
|
|
||||||
<X className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{target.target_type === 'item' && (
|
|
||||||
<MultiPicker items={products} selected={ids} onToggle={toggleId} />
|
|
||||||
)}
|
|
||||||
{target.target_type === 'category' && (
|
|
||||||
<MultiPicker items={categories} selected={ids} onToggle={toggleId} />
|
|
||||||
)}
|
|
||||||
{target.target_type === 'tag' && (
|
|
||||||
<TagPicker selected={tags} onToggle={toggleTag} onAdd={tag => setTags([...tags, tag])} allTags={allTags} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── 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 (
|
|
||||||
<form id="deal-form" onSubmit={submit} className="space-y-5">
|
|
||||||
|
|
||||||
{/* ── Info tab ── */}
|
|
||||||
{activeTab === 'info' && (
|
|
||||||
<>
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
<div className="col-span-2">
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1">Όνομα προσφοράς</label>
|
|
||||||
<input className="input w-full" value={f.name} onChange={e => set('name', e.target.value)}
|
|
||||||
placeholder="π.χ. 3+1 Μπύρες" autoFocus />
|
|
||||||
</div>
|
|
||||||
<div className="col-span-2">
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1">Περιγραφή</label>
|
|
||||||
<input className="input w-full" value={f.description ?? ''}
|
|
||||||
onChange={e => set('description', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1.5">Χρώμα</label>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{COLORS.map(c => (
|
|
||||||
<button type="button" key={c} onClick={() => set('color', c)}
|
|
||||||
className={`w-6 h-6 rounded-full transition-transform ${f.color === c ? 'ring-2 ring-offset-1 ring-slate-400 scale-110' : 'hover:scale-105'}`}
|
|
||||||
style={{ background: c }} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<label className="flex items-center gap-2 cursor-pointer select-none">
|
|
||||||
<div onClick={() => set('is_active', !f.is_active)}
|
|
||||||
className={`relative rounded-full transition-colors ${f.is_active ? 'bg-sky-500' : 'bg-slate-200'}`}
|
|
||||||
style={{ width: 32, height: 18 }}>
|
|
||||||
<span className={`absolute top-0.5 left-0.5 w-3.5 h-3.5 rounded-full bg-white shadow transition-transform ${f.is_active ? 'translate-x-3.5' : ''}`} />
|
|
||||||
</div>
|
|
||||||
<span className="text-[12px] text-slate-700">Ενεργή</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* ── Trigger & Conditions tab ── */}
|
|
||||||
{activeTab === 'trigger' && (
|
|
||||||
<>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<span className="text-[12px] font-semibold text-slate-600 uppercase tracking-wide">Trigger</span>
|
|
||||||
<span className="text-[11px] text-slate-400 ml-1.5">Αγορά αυτών</span>
|
|
||||||
</div>
|
|
||||||
<button type="button" onClick={addTarget}
|
|
||||||
className="text-[12px] text-sky-600 hover:text-sky-700 flex items-center gap-1">
|
|
||||||
<Plus className="w-3.5 h-3.5" />Προσθήκη
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<p className="text-[11px] text-slate-400">
|
|
||||||
Ποια προϊόντα πρέπει να υπάρχουν στην παραγγελία για να ενεργοποιηθεί η προσφορά;
|
|
||||||
</p>
|
|
||||||
{f.targets.map((t, i) => (
|
|
||||||
<DealTargetRow key={i} target={t} onChange={v => updTarget(i, v)} onRemove={() => remTarget(i)}
|
|
||||||
products={products} categories={categories} allTags={allTags} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<span className="text-[12px] font-semibold text-slate-600 uppercase tracking-wide">Επιπλέον Συνθήκες</span>
|
|
||||||
<span className="text-[11px] text-slate-400 ml-1.5">(προαιρετικά)</span>
|
|
||||||
</div>
|
|
||||||
<button type="button" onClick={addCond}
|
|
||||||
className="text-[12px] text-sky-600 hover:text-sky-700 flex items-center gap-1">
|
|
||||||
<Plus className="w-3.5 h-3.5" />Προσθήκη
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{f.conditions.length === 0 && (
|
|
||||||
<p className="text-[12px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2.5">
|
|
||||||
Χωρίς επιπλέον συνθήκες — αρκεί μόνο το trigger.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{f.conditions.map((c, i) => (
|
|
||||||
<ConditionRow key={i} cond={c} onChange={v => updCond(i, v)} onRemove={() => remCond(i)} groups={groups} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* ── Action tab ── */}
|
|
||||||
{activeTab === 'action' && (
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
|
|
||||||
{ACTION_TYPES.map(({ value, label }) => (
|
|
||||||
<button type="button" key={value} onClick={() => set('action_type', value)}
|
|
||||||
className={`py-2 rounded-lg border text-[12px] font-medium transition-colors text-center ${
|
|
||||||
f.action_type === value ? 'border-sky-500 bg-sky-50 text-sky-700' : 'border-slate-200 text-slate-500 hover:bg-slate-50'
|
|
||||||
}`}>{label}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{f.action_type === 'apply_modifier' && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1">Τροποποιητής (χωρίς συνθήκες)</label>
|
|
||||||
<select className="input w-full text-[12px]" value={f.action_modifier_id ?? ''}
|
|
||||||
onChange={e => set('action_modifier_id', Number(e.target.value))}>
|
|
||||||
<option value="">— Επιλογή —</option>
|
|
||||||
{(modifiers ?? []).filter(m => !m.conditions?.length).map(m => (
|
|
||||||
<option key={m.id} value={m.id}>{m.name}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<p className="text-[11px] text-slate-400 mt-1">Εμφανίζονται μόνο τροποποιητές χωρίς συνθήκες (χειροκίνητοι).</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{(f.action_type === 'set_price' || f.action_type === 'add_amount' || f.action_type === 'add_percent') && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1">
|
|
||||||
{f.action_type === 'set_price' ? 'Νέα τιμή (€)' :
|
|
||||||
f.action_type === 'add_amount' ? 'Ποσό (€, αρνητικό = έκπτωση)' :
|
|
||||||
'Ποσοστό (%, αρνητικό = έκπτωση)'}
|
|
||||||
</label>
|
|
||||||
<input type="number" step={0.1} className="input w-36 text-[12px]"
|
|
||||||
value={f.action_value ?? 0} onChange={e => set('action_value', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{f.action_type === 'free_item' && (
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1">Δωρεάν προϊόν</label>
|
|
||||||
<select className="input w-full text-[12px]" value={f.action_free_item_id ?? ''}
|
|
||||||
onChange={e => set('action_free_item_id', Number(e.target.value))}>
|
|
||||||
<option value="">— Επιλογή —</option>
|
|
||||||
{products.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1">Ποσότητα</label>
|
|
||||||
<input type="number" min={1} className="input w-20 text-[12px]"
|
|
||||||
value={f.action_free_quantity} onChange={e => set('action_free_quantity', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{f.action_type === 'free_choice' && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{[['item','Προϊόντα'],['category','Κατηγορία'],['tag','Ετικέτα']].map(([v,l]) => (
|
|
||||||
<button type="button" key={v} onClick={() => { set('action_free_target_type', v); set('action_free_target_ids', []) }}
|
|
||||||
className={`px-3 py-1 rounded text-[12px] font-medium border transition-colors ${
|
|
||||||
f.action_free_target_type === v ? 'border-sky-500 bg-sky-50 text-sky-700' : 'border-slate-200 text-slate-500 hover:bg-slate-50'
|
|
||||||
}`}>{l}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
{f.action_free_target_type === 'item' && (
|
|
||||||
<div className="max-h-40 overflow-y-auto border border-slate-200 rounded-lg p-2 space-y-1">
|
|
||||||
{products.map(p => (
|
|
||||||
<label key={p.id} className="flex items-center gap-2 cursor-pointer py-0.5">
|
|
||||||
<input type="checkbox" className="rounded"
|
|
||||||
checked={(f.action_free_target_ids ?? []).includes(p.id)}
|
|
||||||
onChange={() => toggleFreeId(p.id)} />
|
|
||||||
<span className="text-[12px] text-slate-700">{p.name}</span>
|
|
||||||
</label>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{f.action_free_target_type === 'category' && (
|
|
||||||
<div className="max-h-40 overflow-y-auto border border-slate-200 rounded-lg p-2 space-y-1">
|
|
||||||
{categories.map(c => (
|
|
||||||
<label key={c.id} className="flex items-center gap-2 cursor-pointer py-0.5">
|
|
||||||
<input type="checkbox" className="rounded"
|
|
||||||
checked={(f.action_free_target_ids ?? []).includes(c.id)}
|
|
||||||
onChange={() => toggleFreeId(c.id)} />
|
|
||||||
<span className="text-[12px] text-slate-700">{c.name}</span>
|
|
||||||
</label>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{f.action_free_target_type === 'tag' && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1">Ετικέτες (μία ανά γραμμή)</label>
|
|
||||||
<textarea className="input w-full text-[12px] font-mono" rows={3}
|
|
||||||
value={(f.action_free_target_ids ?? []).join('\n')}
|
|
||||||
onChange={e => set('action_free_target_ids', e.target.value.split('\n').map(s => s.trim()).filter(Boolean))} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1">Ποσότητα δωρεάν</label>
|
|
||||||
<input type="number" min={1} className="input w-20 text-[12px]"
|
|
||||||
value={f.action_free_quantity} onChange={e => set('action_free_quantity', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
</form>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Deal card ────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function DealCard({ deal, onEdit, onDelete }) {
|
|
||||||
const qc = useQueryClient()
|
|
||||||
const toggle = useMutation({
|
|
||||||
mutationFn: () => api.toggle(deal.id),
|
|
||||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['pricing-deals'] }),
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
|
|
||||||
const actionLabel = ACTION_TYPES.find(a => a.value === deal.action_type)?.label ?? deal.action_type
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={`bg-white rounded-xl border shadow-sm p-4 flex items-start gap-3 transition-opacity ${deal.is_active ? 'border-slate-200' : 'border-slate-100 opacity-60'}`}>
|
|
||||||
<div className="w-3 h-3 rounded-full mt-1 shrink-0" style={{ background: deal.color ?? '#22c55e' }} />
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
|
||||||
<span className="text-[14px] font-semibold text-slate-800">{deal.name}</span>
|
|
||||||
<span className={`text-[11px] font-medium px-1.5 py-0.5 rounded-full ${
|
|
||||||
deal.is_active ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500'
|
|
||||||
}`}>{deal.is_active ? 'Ενεργή' : 'Ανενεργή'}</span>
|
|
||||||
<span className="text-[11px] text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded-full">{actionLabel}</span>
|
|
||||||
</div>
|
|
||||||
{deal.description && <p className="text-[12px] text-slate-500 mt-0.5">{deal.description}</p>}
|
|
||||||
<p className="text-[11px] text-slate-400 mt-1">
|
|
||||||
{deal.conditions?.length ?? 0} συνθήκες · {deal.targets?.length ?? 0} targets
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-1 shrink-0">
|
|
||||||
<button onClick={() => toggle.mutate()}
|
|
||||||
className={`p-1.5 rounded-lg transition-colors ${
|
|
||||||
deal.is_active ? 'text-emerald-600 hover:bg-emerald-50' : 'text-slate-400 hover:bg-slate-100'
|
|
||||||
}`}>
|
|
||||||
<Power className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button onClick={() => onEdit(deal)}
|
|
||||||
className="p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
|
|
||||||
<Pencil className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button onClick={() => onDelete(deal)}
|
|
||||||
className="p-1.5 rounded-lg text-slate-400 hover:bg-rose-50 hover:text-rose-500 transition-colors">
|
|
||||||
<Trash2 className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Main tab ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export default function DealsTab() {
|
|
||||||
const qc = useQueryClient()
|
|
||||||
const [showForm, setShowForm] = useState(false)
|
|
||||||
const [editing, setEditing] = useState(null)
|
|
||||||
const [deleting, setDeleting] = useState(null)
|
|
||||||
const [formTab, setFormTab] = useState('info')
|
|
||||||
|
|
||||||
const { data: deals = [], isLoading } = useQuery({ queryKey: ['pricing-deals'], queryFn: api.list })
|
|
||||||
const { data: modifiers = [] } = useQuery({ queryKey: ['pricing-modifiers'], queryFn: api.modifiers })
|
|
||||||
const { data: groups = [] } = useQuery({ queryKey: ['pricing-groups'], queryFn: () => client.get('/api/pricing/groups').then(r => r.data) })
|
|
||||||
|
|
||||||
const create = useMutation({
|
|
||||||
mutationFn: api.create,
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-deals'] }); setShowForm(false); toast.success('Δημιουργήθηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
const update = useMutation({
|
|
||||||
mutationFn: ({ id, body }) => api.update(id, body),
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-deals'] }); setEditing(null); toast.success('Αποθηκεύτηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
const remove = useMutation({
|
|
||||||
mutationFn: api.remove,
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-deals'] }); setDeleting(null); toast.success('Διαγράφηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
|
|
||||||
const formProps = { modifiers, groups }
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="p-6 space-y-4">
|
|
||||||
<div className="flex items-start justify-between gap-4">
|
|
||||||
<div>
|
|
||||||
<h2 className="text-[14px] font-semibold text-slate-800">Προσφορές</h2>
|
|
||||||
<p className="text-[12px] text-slate-500 mt-0.5">
|
|
||||||
Αυτόματες δράσεις που ενεργοποιούνται όταν ο σερβιτόρος προσθέτει συγκεκριμένα προϊόντα στην παραγγελία.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button variant="primary" onClick={() => setShowForm(true)}>
|
|
||||||
<Plus className="w-4 h-4 mr-1.5" />Νέα Προσφορά
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-start gap-3 bg-sky-50 border border-sky-200 rounded-lg px-4 py-3">
|
|
||||||
<Info className="w-4 h-4 text-sky-500 shrink-0 mt-0.5" />
|
|
||||||
<p className="text-[12px] text-sky-700">
|
|
||||||
Όταν μια προσφορά ενεργοποιηθεί, ο σερβιτόρος λαμβάνει prompt στην εφαρμογή και επιλέγει αν θα την εφαρμόσει.
|
|
||||||
Τίποτα δεν εφαρμόζεται αυτόματα χωρίς επιβεβαίωση.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="flex justify-center py-12">
|
|
||||||
<div className="w-5 h-5 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
|
|
||||||
</div>
|
|
||||||
) : deals.length === 0 ? (
|
|
||||||
<div className="flex flex-col items-center justify-center py-16 text-slate-400">
|
|
||||||
<Gift className="w-10 h-10 mb-3 opacity-30" />
|
|
||||||
<p className="text-[13px]">Δεν υπάρχουν προσφορές</p>
|
|
||||||
<p className="text-[12px] mt-1">π.χ. «Αγόρασε 3 μπύρες, πάρε 1 δωρεάν»</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-3">
|
|
||||||
{deals.map(d => (
|
|
||||||
<DealCard key={d.id} deal={d} onEdit={d => { setEditing(d); setFormTab('info') }} onDelete={setDeleting} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{showForm && (
|
|
||||||
<Modal title="Νέα Προσφορά" onClose={() => { setShowForm(false); setFormTab('info') }}
|
|
||||||
maxWidth="max-w-xl" tabs={DEAL_TABS} activeTab={formTab} onTabChange={setFormTab}
|
|
||||||
footer={<>
|
|
||||||
<Button type="button" variant="secondary" onClick={() => { setShowForm(false); setFormTab('info') }}>Ακύρωση</Button>
|
|
||||||
<Button type="submit" form="deal-form" variant="primary" disabled={create.isPending}>
|
|
||||||
{create.isPending ? 'Αποθήκευση...' : 'Αποθήκευση'}
|
|
||||||
</Button>
|
|
||||||
</>}>
|
|
||||||
<DealForm onSave={body => create.mutate(body)} onCancel={() => { setShowForm(false); setFormTab('info') }}
|
|
||||||
saving={create.isPending} {...formProps} activeTab={formTab} onTabChange={setFormTab} />
|
|
||||||
</Modal>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{editing && (
|
|
||||||
<Modal title="Επεξεργασία Προσφοράς" onClose={() => { setEditing(null); setFormTab('info') }}
|
|
||||||
maxWidth="max-w-xl" tabs={DEAL_TABS} activeTab={formTab} onTabChange={setFormTab}
|
|
||||||
footer={<>
|
|
||||||
<Button type="button" variant="secondary" onClick={() => { setEditing(null); setFormTab('info') }}>Ακύρωση</Button>
|
|
||||||
<Button type="submit" form="deal-form" variant="primary" disabled={update.isPending}>
|
|
||||||
{update.isPending ? 'Αποθήκευση...' : 'Αποθήκευση'}
|
|
||||||
</Button>
|
|
||||||
</>}>
|
|
||||||
<DealForm initial={editing} onSave={body => update.mutate({ id: editing.id, body })}
|
|
||||||
onCancel={() => { setEditing(null); setFormTab('info') }} saving={update.isPending}
|
|
||||||
{...formProps} activeTab={formTab} onTabChange={setFormTab} />
|
|
||||||
</Modal>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{deleting && (
|
|
||||||
<ConfirmModal title="Διαγραφή Προσφοράς"
|
|
||||||
message={`Θέλετε να διαγράψετε την προσφορά "${deleting.name}";`}
|
|
||||||
confirmLabel="Διαγραφή"
|
|
||||||
onConfirm={() => remove.mutate(deleting.id)}
|
|
||||||
onCancel={() => setDeleting(null)} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,265 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
|
||||||
import { Users, ShieldCheck, Save } from 'lucide-react'
|
|
||||||
import toast from 'react-hot-toast'
|
|
||||||
import client from '../../../api/client'
|
|
||||||
import Button from '../../../ui/Button'
|
|
||||||
|
|
||||||
// ─── API ─────────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const api = {
|
|
||||||
globalGet: () => client.get('/api/pricing/discount-settings/global').then(r => r.data),
|
|
||||||
globalPut: body => client.put('/api/pricing/discount-settings/global', body).then(r => r.data),
|
|
||||||
waiterGet: id => client.get(`/api/pricing/discount-settings/${id}`).then(r => r.data),
|
|
||||||
waiterPut: (id,b) => client.put(`/api/pricing/discount-settings/${id}`, b).then(r => r.data),
|
|
||||||
staff: () => client.get('/api/waiters/').then(r => r.data),
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Toggle helpers ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function Toggle({ value, onChange }) {
|
|
||||||
return (
|
|
||||||
<div onClick={() => onChange(!value)}
|
|
||||||
className={`relative rounded-full cursor-pointer transition-colors shrink-0 ${value ? 'bg-sky-500' : 'bg-slate-200'}`}
|
|
||||||
style={{ width: 36, height: 20 }}>
|
|
||||||
<span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${value ? 'translate-x-4' : ''}`} />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Numeric field ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function NumField({ label, hint, value, onChange, step = 1, min = 0, unit = '' }) {
|
|
||||||
return (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600">{label}</label>
|
|
||||||
{hint && <p className="text-[11px] text-slate-400">{hint}</p>}
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<input
|
|
||||||
type="number" min={min} step={step}
|
|
||||||
className="input w-28 text-[12px]"
|
|
||||||
placeholder="—"
|
|
||||||
value={value ?? ''}
|
|
||||||
onChange={e => onChange(e.target.value === '' ? null : Number(e.target.value))}
|
|
||||||
/>
|
|
||||||
{unit && <span className="text-[12px] text-slate-500">{unit}</span>}
|
|
||||||
{value !== null && value !== undefined && (
|
|
||||||
<button type="button" onClick={() => onChange(null)}
|
|
||||||
className="text-[11px] text-slate-400 hover:text-slate-600 underline ml-1">
|
|
||||||
Αφαίρεση
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Global settings panel ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function GlobalPanel() {
|
|
||||||
const qc = useQueryClient()
|
|
||||||
const { data, isLoading } = useQuery({ queryKey: ['discount-global'], queryFn: api.globalGet })
|
|
||||||
|
|
||||||
const blankGlobal = {
|
|
||||||
enabled: false,
|
|
||||||
max_total_value_workday: null,
|
|
||||||
max_total_value_shift: null,
|
|
||||||
max_items_per_shift: null,
|
|
||||||
}
|
|
||||||
const [f, setF] = useState(null)
|
|
||||||
const current = f ?? (data ? { ...blankGlobal, ...data } : blankGlobal)
|
|
||||||
const set = (k, v) => setF(p => ({ ...(p ?? current), [k]: v }))
|
|
||||||
|
|
||||||
const save = useMutation({
|
|
||||||
mutationFn: () => api.globalPut(current),
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['discount-global'] }); setF(null); toast.success('Αποθηκεύτηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
|
|
||||||
if (isLoading) return <div className="h-24 flex items-center justify-center"><div className="w-4 h-4 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" /></div>
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5 space-y-5">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="w-8 h-8 rounded-lg bg-sky-100 flex items-center justify-center shrink-0">
|
|
||||||
<ShieldCheck className="w-4 h-4 text-sky-600" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h3 className="text-[13px] font-semibold text-slate-800">Καθολικές Ρυθμίσεις</h3>
|
|
||||||
<p className="text-[11px] text-slate-500">Εφαρμόζονται σε όλους τους σερβιτόρους ανεξαρτήτως ατομικών ρυθμίσεων</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Master enable */}
|
|
||||||
<div className="flex items-center justify-between py-2 border-b border-slate-100">
|
|
||||||
<div>
|
|
||||||
<span className="text-[13px] font-medium text-slate-700">Εκπτώσεις Ενεργές</span>
|
|
||||||
<p className="text-[11px] text-slate-400 mt-0.5">Αν είναι ανενεργό, κανένας σερβιτόρος δεν μπορεί να εφαρμόσει εκπτώσεις</p>
|
|
||||||
</div>
|
|
||||||
<Toggle value={current.enabled ?? false} onChange={v => set('enabled', v)} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Limits */}
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
|
||||||
<NumField label="Μέγιστο ανά εργάσιμη ημέρα" hint="Ολόκληρο το κατάστημα"
|
|
||||||
value={current.max_total_value_workday} onChange={v => set('max_total_value_workday', v)} step={0.5} unit="€" />
|
|
||||||
<NumField label="Μέγιστο ανά βάρδια" hint="Όλες οι βάρδιες μαζί"
|
|
||||||
value={current.max_total_value_shift} onChange={v => set('max_total_value_shift', v)} step={0.5} unit="€" />
|
|
||||||
<NumField label="Μέγιστα αντικείμενα/βάρδια" hint="Σύνολο αντικειμένων με έκπτωση"
|
|
||||||
value={current.max_items_per_shift} onChange={v => set('max_items_per_shift', v)} unit="τεμ." />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end">
|
|
||||||
<Button variant="primary" onClick={() => save.mutate()} disabled={save.isPending}>
|
|
||||||
<Save className="w-3.5 h-3.5 mr-1.5" />{save.isPending ? 'Αποθήκευση...' : 'Αποθήκευση'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Per-waiter settings panel ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const WAITER_BLANK = {
|
|
||||||
can_apply_discounts: false,
|
|
||||||
max_discount_percent: null,
|
|
||||||
max_discount_amount: null,
|
|
||||||
max_total_value_shift: null,
|
|
||||||
max_total_value_workday: null,
|
|
||||||
max_items_per_shift: null,
|
|
||||||
max_items_per_workday: null,
|
|
||||||
max_items_per_order: null,
|
|
||||||
}
|
|
||||||
|
|
||||||
function WaiterPanel({ waiters }) {
|
|
||||||
const qc = useQueryClient()
|
|
||||||
const [selectedId, setSelectedId] = useState(waiters[0]?.id ?? null)
|
|
||||||
const [dirty, setDirty] = useState(null)
|
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
|
||||||
queryKey: ['discount-waiter', selectedId],
|
|
||||||
queryFn: () => api.waiterGet(selectedId),
|
|
||||||
enabled: !!selectedId,
|
|
||||||
})
|
|
||||||
|
|
||||||
const current = dirty ?? (data ? { ...WAITER_BLANK, ...data } : WAITER_BLANK)
|
|
||||||
const set = (k, v) => setDirty(p => ({ ...(p ?? current), [k]: v }))
|
|
||||||
|
|
||||||
const save = useMutation({
|
|
||||||
mutationFn: () => api.waiterPut(selectedId, current),
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['discount-waiter', selectedId] }); setDirty(null); toast.success('Αποθηκεύτηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
|
|
||||||
const selectedWaiter = waiters.find(w => w.id === selectedId)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5 space-y-5">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="w-8 h-8 rounded-lg bg-indigo-100 flex items-center justify-center shrink-0">
|
|
||||||
<Users className="w-4 h-4 text-indigo-600" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h3 className="text-[13px] font-semibold text-slate-800">Ανά Σερβιτόρο</h3>
|
|
||||||
<p className="text-[11px] text-slate-500">Ατομικά όρια — ισχύουν παράλληλα με τα καθολικά</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Waiter picker */}
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{waiters.map(w => (
|
|
||||||
<button key={w.id} type="button"
|
|
||||||
onClick={() => { setSelectedId(w.id); setDirty(null) }}
|
|
||||||
className={`px-3 py-1.5 rounded-lg text-[12px] font-medium border transition-colors ${
|
|
||||||
w.id === selectedId ? 'border-indigo-500 bg-indigo-50 text-indigo-700' : 'border-slate-200 text-slate-600 hover:bg-slate-50'
|
|
||||||
}`}>
|
|
||||||
{w.nickname || w.full_name || w.username}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!selectedId ? (
|
|
||||||
<p className="text-[12px] text-slate-400 text-center py-8">Επιλέξτε σερβιτόρο</p>
|
|
||||||
) : isLoading ? (
|
|
||||||
<div className="h-24 flex items-center justify-center"><div className="w-4 h-4 rounded-full border-2 border-indigo-400 border-t-transparent animate-spin" /></div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-5">
|
|
||||||
{/* Can apply toggle */}
|
|
||||||
<div className="flex items-center justify-between py-2 border-b border-slate-100">
|
|
||||||
<div>
|
|
||||||
<span className="text-[13px] font-medium text-slate-700">
|
|
||||||
{selectedWaiter?.nickname || selectedWaiter?.full_name || selectedWaiter?.username} — Δικαίωμα εκπτώσεων
|
|
||||||
</span>
|
|
||||||
<p className="text-[11px] text-slate-400 mt-0.5">Απενεργοποίηση κλειδώνει τον σερβιτόρο εντελώς</p>
|
|
||||||
</div>
|
|
||||||
<Toggle value={current.can_apply_discounts} onChange={v => set('can_apply_discounts', v)} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Per-discount limits */}
|
|
||||||
<div>
|
|
||||||
<p className="text-[11px] font-semibold text-slate-500 uppercase tracking-wide mb-3">Ανά Έκπτωση</p>
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
|
||||||
<NumField label="Μέγιστο ποσοστό %" hint="Μέγιστη έκπτωση σε % ανά εφαρμογή"
|
|
||||||
value={current.max_discount_percent} onChange={v => set('max_discount_percent', v)} step={5} unit="%" />
|
|
||||||
<NumField label="Μέγιστο ποσό €" hint="Μέγιστο € που αφαιρείται ανά εφαρμογή"
|
|
||||||
value={current.max_discount_amount} onChange={v => set('max_discount_amount', v)} step={0.5} unit="€" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Scope limits */}
|
|
||||||
<div>
|
|
||||||
<p className="text-[11px] font-semibold text-slate-500 uppercase tracking-wide mb-3">Συνολικά Όρια</p>
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
|
||||||
<NumField label="Αξία/Βάρδια" hint="Συνολική αξία εκπτώσεων ανά βάρδια"
|
|
||||||
value={current.max_total_value_shift} onChange={v => set('max_total_value_shift', v)} step={0.5} unit="€" />
|
|
||||||
<NumField label="Αξία/Εργάσιμη ημέρα" hint="Συνολική αξία εκπτώσεων ανά ημέρα"
|
|
||||||
value={current.max_total_value_workday} onChange={v => set('max_total_value_workday', v)} step={0.5} unit="€" />
|
|
||||||
<NumField label="Αντικείμενα/Βάρδια"
|
|
||||||
value={current.max_items_per_shift} onChange={v => set('max_items_per_shift', v)} unit="τεμ." />
|
|
||||||
<NumField label="Αντικείμενα/Εργάσιμη ημέρα"
|
|
||||||
value={current.max_items_per_workday} onChange={v => set('max_items_per_workday', v)} unit="τεμ." />
|
|
||||||
<NumField label="Αντικείμενα/Παραγγελία" hint="Μέγιστος αριθμός αντικειμένων με έκπτωση ανά παραγγελία"
|
|
||||||
value={current.max_items_per_order} onChange={v => set('max_items_per_order', v)} unit="τεμ." />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end">
|
|
||||||
<Button variant="primary" onClick={() => save.mutate()} disabled={save.isPending}>
|
|
||||||
<Save className="w-3.5 h-3.5 mr-1.5" />{save.isPending ? 'Αποθήκευση...' : 'Αποθήκευση'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Main tab ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export default function DiscountSettingsTab() {
|
|
||||||
const { data: staff = [] } = useQuery({ queryKey: ['waiters'], queryFn: api.staff })
|
|
||||||
const waiters = staff.filter(u => u.is_active !== false)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="p-6 space-y-5">
|
|
||||||
<div>
|
|
||||||
<h2 className="text-[14px] font-semibold text-slate-800">Ρυθμίσεις Εκπτώσεων</h2>
|
|
||||||
<p className="text-[12px] text-slate-500 mt-0.5">
|
|
||||||
Ελέγξτε ποιοι σερβιτόροι μπορούν να εφαρμόζουν εκπτώσεις και ποια είναι τα όρια ανά βάρδια ή εργάσιμη ημέρα.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<GlobalPanel />
|
|
||||||
|
|
||||||
{waiters.length > 0
|
|
||||||
? <WaiterPanel waiters={waiters} />
|
|
||||||
: (
|
|
||||||
<div className="bg-white rounded-xl border border-slate-200 p-8 text-center text-slate-400">
|
|
||||||
<Users className="w-8 h-8 mx-auto mb-2 opacity-30" />
|
|
||||||
<p className="text-[13px]">Δεν βρέθηκαν ενεργοί σερβιτόροι</p>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,813 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
|
||||||
import {
|
|
||||||
Plus, Percent, Power, Pencil, Trash2, Star, Layers,
|
|
||||||
GripVertical, ChevronDown, ChevronUp, 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: (params) => client.get('/api/pricing/modifiers', { params }).then(r => r.data),
|
|
||||||
create: body => client.post('/api/pricing/modifiers', body).then(r => r.data),
|
|
||||||
update: (id, b) => client.put(`/api/pricing/modifiers/${id}`, b).then(r => r.data),
|
|
||||||
toggle: id => client.patch(`/api/pricing/modifiers/${id}/toggle`).then(r => r.data),
|
|
||||||
reorder: items => client.patch('/api/pricing/modifiers/reorder', { items }),
|
|
||||||
remove: id => client.delete(`/api/pricing/modifiers/${id}`),
|
|
||||||
groups: () => client.get('/api/pricing/groups').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),
|
|
||||||
prepZones: () => client.get('/api/prep-zones').then(r => r.data),
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Constants ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const COLORS = [
|
|
||||||
'#6366f1','#8b5cf6','#ec4899','#f43f5e','#f97316',
|
|
||||||
'#eab308','#22c55e','#14b8a6','#0ea5e9','#64748b',
|
|
||||||
]
|
|
||||||
|
|
||||||
const CONDITION_TYPES = [
|
|
||||||
{ value: 'time_range', label: 'Ώρα ημέρας (εύρος)' },
|
|
||||||
{ value: 'date_range', label: 'Εύρος ημερομηνιών' },
|
|
||||||
{ value: 'specific_date', label: 'Συγκεκριμένη ημερομηνία' },
|
|
||||||
{ value: 'day_of_week', label: 'Ημέρα εβδομάδας' },
|
|
||||||
{ value: 'min_item_quantity', label: 'Ελάχιστη ποσότητα προϊόντος' },
|
|
||||||
{ value: 'min_category_qty', label: 'Ελάχιστη ποσότητα κατηγορίας' },
|
|
||||||
{ value: 'min_order_value', label: 'Ελάχιστη αξία παραγγελίας' },
|
|
||||||
{ value: 'order_channel', label: 'Σημείο πώλησης' },
|
|
||||||
{ value: 'price_group_active', label: 'Ομάδα τιμής ενεργή' },
|
|
||||||
{ value: 'user_tier', label: 'Επίπεδο πελάτη (placeholder)' },
|
|
||||||
{ value: 'low_stock', label: 'Χαμηλό απόθεμα (placeholder)' },
|
|
||||||
]
|
|
||||||
|
|
||||||
const DAYS = ['Δευτέρα','Τρίτη','Τετάρτη','Πέμπτη','Παρασκευή','Σάββατο','Κυριακή']
|
|
||||||
const CHANNELS = SALES_POINTS // phase 3S: the order_channel condition holds sales points
|
|
||||||
|
|
||||||
const ROUND_OPTIONS = [
|
|
||||||
{ value: '', label: 'Χωρίς στρογγυλοποίηση' },
|
|
||||||
{ value: '0.05', label: 'Στο κοντινότερο €0,05' },
|
|
||||||
{ value: '0.10', label: 'Στο κοντινότερο €0,10' },
|
|
||||||
{ value: '0.20', label: 'Στο κοντινότερο €0,20' },
|
|
||||||
{ value: '0.50', label: 'Στο κοντινότερο €0,50' },
|
|
||||||
{ value: 'x.99', label: 'Σε x,99 (π.χ. 4,99)' },
|
|
||||||
{ value: 'x.00', label: 'Σε x,00 (στρογγυλό)' },
|
|
||||||
]
|
|
||||||
|
|
||||||
// ─── Condition editor ─────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function ConditionEditor({ cond, onChange, onRemove, groups, categories, prepZones }) {
|
|
||||||
const { t } = useTranslation('common')
|
|
||||||
const set = (k, v) => onChange({ ...cond, params: { ...cond.params, [k]: v } })
|
|
||||||
const setType = t => onChange({ condition_type: t, params: {} })
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="border border-slate-200 rounded-lg p-3 space-y-2 bg-slate-50">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<select className="input flex-1 text-[12px]" value={cond.condition_type}
|
|
||||||
onChange={e => setType(e.target.value)}>
|
|
||||||
{CONDITION_TYPES.map(ct => (
|
|
||||||
<option key={ct.value} value={ct.value}>{ct.label}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<button type="button" onClick={onRemove}
|
|
||||||
className="p-1.5 rounded text-slate-400 hover:text-rose-500 hover:bg-rose-50 transition-colors">
|
|
||||||
<X className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Params per type */}
|
|
||||||
{cond.condition_type === 'time_range' && (
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Από</label>
|
|
||||||
<input type="time" className="input w-full text-[12px]" value={cond.params.from ?? ''}
|
|
||||||
onChange={e => set('from', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Έως</label>
|
|
||||||
<input type="time" className="input w-full text-[12px]" value={cond.params.to ?? ''}
|
|
||||||
onChange={e => set('to', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{cond.condition_type === 'date_range' && (
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Από</label>
|
|
||||||
<input type="date" className="input w-full text-[12px]" value={cond.params.from ?? ''}
|
|
||||||
onChange={e => set('from', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Έως</label>
|
|
||||||
<input type="date" className="input w-full text-[12px]" value={cond.params.to ?? ''}
|
|
||||||
onChange={e => set('to', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{cond.condition_type === 'specific_date' && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Ημερομηνίες (μία ανά γραμμή)</label>
|
|
||||||
<textarea className="input w-full text-[12px] font-mono" rows={3}
|
|
||||||
placeholder="YYYY-MM-DD"
|
|
||||||
value={(cond.params.dates ?? []).join('\n')}
|
|
||||||
onChange={e => set('dates', e.target.value.split('\n').map(s => s.trim()).filter(Boolean))} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{cond.condition_type === 'day_of_week' && (
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{DAYS.map((d, i) => (
|
|
||||||
<button type="button" key={i}
|
|
||||||
onClick={() => {
|
|
||||||
const days = cond.params.days ?? []
|
|
||||||
set('days', days.includes(i) ? days.filter(x => x !== i) : [...days, i])
|
|
||||||
}}
|
|
||||||
className={`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${
|
|
||||||
(cond.params.days ?? []).includes(i) ? 'bg-sky-100 text-sky-700' : 'bg-white border border-slate-200 text-slate-500 hover:bg-slate-50'
|
|
||||||
}`}>{d.slice(0, 3)}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{cond.condition_type === 'min_item_quantity' && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Ελάχιστη ποσότητα</label>
|
|
||||||
<input type="number" min={1} className="input w-32 text-[12px]"
|
|
||||||
value={cond.params.min ?? 1} onChange={e => set('min', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{cond.condition_type === 'min_category_qty' && (
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Κατηγορία</label>
|
|
||||||
<select className="input w-full text-[12px]" value={cond.params.category_id ?? ''}
|
|
||||||
onChange={e => set('category_id', Number(e.target.value))}>
|
|
||||||
<option value="">— Επιλογή —</option>
|
|
||||||
{(categories ?? []).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div className="w-24">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Ελάχ.</label>
|
|
||||||
<input type="number" min={1} className="input w-full text-[12px]"
|
|
||||||
value={cond.params.min ?? 1} onChange={e => set('min', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{cond.condition_type === 'min_order_value' && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Ελάχιστη αξία παραγγελίας (€)</label>
|
|
||||||
<input type="number" min={0} step={0.5} className="input w-32 text-[12px]"
|
|
||||||
value={cond.params.min ?? 0} onChange={e => set('min', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{cond.condition_type === 'order_channel' && (
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{CHANNELS.map(ch => (
|
|
||||||
<button type="button" key={ch}
|
|
||||||
onClick={() => {
|
|
||||||
const channels = normalizeSalesPoints(cond.params.channels)
|
|
||||||
set('channels', channels.includes(ch) ? channels.filter(x => x !== ch) : [...channels, ch])
|
|
||||||
}}
|
|
||||||
className={`px-2.5 py-1 rounded text-[11px] font-medium transition-colors ${
|
|
||||||
normalizeSalesPoints(cond.params.channels).includes(ch) ? 'bg-sky-100 text-sky-700' : 'bg-white border border-slate-200 text-slate-500 hover:bg-slate-50'
|
|
||||||
}`}>{t(`salesPoints.${ch}.name`)}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{cond.condition_type === 'price_group_active' && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Ομάδα τιμής</label>
|
|
||||||
<select className="input w-full text-[12px]" value={cond.params.price_group_id ?? ''}
|
|
||||||
onChange={e => set('price_group_id', Number(e.target.value))}>
|
|
||||||
<option value="">— Επιλογή —</option>
|
|
||||||
{(groups ?? []).map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{(cond.condition_type === 'user_tier' || cond.condition_type === 'low_stock') && (
|
|
||||||
<p className="text-[11px] text-amber-600 bg-amber-50 rounded px-2 py-1 flex items-center gap-1.5">
|
|
||||||
<Info className="w-3.5 h-3.5 shrink-0" />
|
|
||||||
Placeholder — θα ενεργοποιηθεί σε μελλοντική έκδοση
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Shared multi-picker ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function MultiPicker({ items, selected, onToggle, labelKey = 'name', valueKey = 'id', placeholder = 'Επιλέξτε...' }) {
|
|
||||||
return (
|
|
||||||
<div className="border border-slate-200 rounded-lg overflow-hidden">
|
|
||||||
{items.length === 0 && (
|
|
||||||
<p className="text-[11px] text-slate-400 px-3 py-2">{placeholder}</p>
|
|
||||||
)}
|
|
||||||
{items.map(item => {
|
|
||||||
const val = item[valueKey]
|
|
||||||
const checked = selected.includes(val)
|
|
||||||
return (
|
|
||||||
<div key={val} onClick={() => 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'
|
|
||||||
}`}>
|
|
||||||
<div className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${
|
|
||||||
checked ? 'bg-sky-500 border-sky-500' : 'border-slate-300 bg-white'
|
|
||||||
}`}>
|
|
||||||
{checked && <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4l3 3 5-6" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
|
|
||||||
</div>
|
|
||||||
{item[labelKey]}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
|
||||||
<div className="space-y-2">
|
|
||||||
{/* Quick-select existing tags */}
|
|
||||||
{allTags.length > 0 && (
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{allTags.map(tag => {
|
|
||||||
const active = selected.includes(tag)
|
|
||||||
return (
|
|
||||||
<button type="button" key={tag} onClick={() => onToggle(tag)}
|
|
||||||
className={`px-2 py-0.5 rounded-full text-[11px] font-medium border transition-colors ${
|
|
||||||
active ? 'bg-sky-500 border-sky-500 text-white' : 'border-slate-300 text-slate-600 hover:border-sky-400 hover:text-sky-600'
|
|
||||||
}`}>{tag}</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* Selected chips */}
|
|
||||||
{selected.length > 0 && (
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{selected.map(tag => (
|
|
||||||
<span key={tag} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-sky-100 text-sky-700 text-[11px] font-medium">
|
|
||||||
{tag}
|
|
||||||
<button type="button" onClick={() => onToggle(tag)} className="hover:text-sky-900">
|
|
||||||
<X className="w-3 h-3" />
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* Manual entry */}
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<input className="input flex-1 text-[12px]" placeholder="Νέο tag..." value={draft}
|
|
||||||
onChange={e => setDraft(e.target.value)}
|
|
||||||
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); handleAdd() } }} />
|
|
||||||
<button type="button" onClick={handleAdd}
|
|
||||||
className="px-3 py-1.5 rounded-lg bg-slate-100 text-slate-600 text-[12px] hover:bg-slate-200 transition-colors">
|
|
||||||
+
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Target editor ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function TargetEditor({ target, onChange, onRemove, products, categories, prepZones, 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 (
|
|
||||||
<div className="border border-slate-200 rounded-lg p-3 space-y-2 bg-slate-50">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<select className="input flex-1 text-[12px]" value={target.target_type}
|
|
||||||
onChange={e => onChange({ target_type: e.target.value, target_id: null, target_tag: null, target_ids: [], target_tags: [] })}>
|
|
||||||
<option value="all">Όλα τα προϊόντα</option>
|
|
||||||
<option value="item">Προϊόντα</option>
|
|
||||||
<option value="category">Κατηγορίες</option>
|
|
||||||
<option value="prep_zone">Ζώνες ετοιμασίας</option>
|
|
||||||
<option value="tag">Ετικέτες (tags)</option>
|
|
||||||
</select>
|
|
||||||
<button type="button" onClick={onRemove}
|
|
||||||
className="p-1.5 rounded text-slate-400 hover:text-rose-500 hover:bg-rose-50 transition-colors">
|
|
||||||
<X className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{target.target_type === 'item' && (
|
|
||||||
<MultiPicker items={products} selected={ids} onToggle={toggleId} />
|
|
||||||
)}
|
|
||||||
{target.target_type === 'category' && (
|
|
||||||
<MultiPicker items={categories} selected={ids} onToggle={toggleId} />
|
|
||||||
)}
|
|
||||||
{target.target_type === 'prep_zone' && (
|
|
||||||
<MultiPicker items={prepZones} selected={ids} onToggle={toggleId} />
|
|
||||||
)}
|
|
||||||
{target.target_type === 'tag' && (
|
|
||||||
<TagPicker selected={tags} onToggle={toggleTag} onAdd={tag => setTags([...tags, tag])} allTags={allTags} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Modifier form ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const MODIFIER_TABS = [
|
|
||||||
{ key: 'info', label: 'Πληροφορίες' },
|
|
||||||
{ key: 'target', label: 'Στόχος' },
|
|
||||||
{ key: 'conditions', label: 'Συνθήκες' },
|
|
||||||
{ key: 'price', label: 'Τιμή' },
|
|
||||||
]
|
|
||||||
|
|
||||||
function ModifierForm({ initial, onSave, onCancel, saving, 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: prepZones = [] } = useQuery({
|
|
||||||
queryKey: ['prep-zones'],
|
|
||||||
queryFn: () => client.get('/api/prep-zones').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[0], is_active: true, is_favorite: false,
|
|
||||||
allow_stack: false, sort_order: 0, scope: 'global', item_id: null,
|
|
||||||
action_type: 'add_percent', action_value: -10, round_to: '',
|
|
||||||
conditions: [], targets: [{ target_type: 'all', target_id: null, target_tag: null, target_ids: [], target_tags: [] }],
|
|
||||||
}
|
|
||||||
const [f, setF] = useState(initial ? {
|
|
||||||
...initial,
|
|
||||||
action_value: initial.action_value ?? 0,
|
|
||||||
round_to: initial.round_to ?? '',
|
|
||||||
conditions: initial.conditions ?? [],
|
|
||||||
targets: (initial.targets ?? []).map(normalizeTarget),
|
|
||||||
} : blank)
|
|
||||||
|
|
||||||
const set = (k, v) => setF(p => ({ ...p, [k]: v }))
|
|
||||||
|
|
||||||
const addCondition = () => set('conditions', [...f.conditions, { condition_type: 'time_range', params: {} }])
|
|
||||||
const updateCondition = (i, c) => set('conditions', f.conditions.map((x, j) => j === i ? c : x))
|
|
||||||
const removeCondition = i => set('conditions', f.conditions.filter((_, j) => j !== i))
|
|
||||||
|
|
||||||
const addTarget = () => set('targets', [...f.targets, { target_type: 'all', target_id: null, target_tag: null, target_ids: [], target_tags: [] }])
|
|
||||||
const updateTarget = (i, t) => set('targets', f.targets.map((x, j) => j === i ? t : x))
|
|
||||||
const removeTarget = i => set('targets', f.targets.filter((_, j) => j !== i))
|
|
||||||
|
|
||||||
function submit(e) {
|
|
||||||
e.preventDefault()
|
|
||||||
if (!f.name.trim()) return toast.error('Απαιτείται όνομα')
|
|
||||||
if (f.scope === 'item' && !f.item_id) return toast.error('Επιλέξτε προϊόν για item-scope')
|
|
||||||
onSave({ ...f, round_to: f.round_to || null })
|
|
||||||
}
|
|
||||||
|
|
||||||
const actionLabel = f.action_type === 'set' ? 'Νέα τιμή (€)' :
|
|
||||||
f.action_type === 'add_amount' ? 'Ποσό (€, αρνητικό = έκπτωση)' :
|
|
||||||
'Ποσοστό (%, αρνητικό = έκπτωση)'
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form id="modifier-form" onSubmit={submit} className="space-y-5">
|
|
||||||
|
|
||||||
{/* ── Info tab ── */}
|
|
||||||
{activeTab === 'info' && (
|
|
||||||
<>
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
<div className="col-span-2">
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1">Όνομα</label>
|
|
||||||
<input className="input w-full" value={f.name} onChange={e => set('name', e.target.value)}
|
|
||||||
placeholder="π.χ. Happy Hour -10%" autoFocus />
|
|
||||||
</div>
|
|
||||||
<div className="col-span-2">
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1">Περιγραφή (προαιρετική)</label>
|
|
||||||
<input className="input w-full" value={f.description ?? ''} onChange={e => set('description', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1.5">Χρώμα</label>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{COLORS.map(c => (
|
|
||||||
<button type="button" key={c} onClick={() => set('color', c)}
|
|
||||||
className={`w-6 h-6 rounded-full transition-transform ${f.color === c ? 'ring-2 ring-offset-1 ring-slate-400 scale-110' : 'hover:scale-105'}`}
|
|
||||||
style={{ background: c }} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-wrap gap-4">
|
|
||||||
{[
|
|
||||||
{ key: 'is_active', label: 'Ενεργός' },
|
|
||||||
{ key: 'is_favorite', label: 'Αγαπημένος (dashboard)' },
|
|
||||||
{ key: 'allow_stack', label: 'Επιτρέπει συσσώρευση' },
|
|
||||||
].map(({ key, label }) => (
|
|
||||||
<label key={key} className="flex items-center gap-2 cursor-pointer select-none">
|
|
||||||
<div onClick={() => set(key, !f[key])}
|
|
||||||
className={`relative rounded-full transition-colors ${f[key] ? 'bg-sky-500' : 'bg-slate-200'}`}
|
|
||||||
style={{ height: '18px', width: '32px' }}>
|
|
||||||
<span className={`absolute top-0.5 left-0.5 w-3.5 h-3.5 rounded-full bg-white shadow transition-transform ${f[key] ? 'translate-x-3.5' : ''}`} />
|
|
||||||
</div>
|
|
||||||
<span className="text-[12px] text-slate-700">{label}</span>
|
|
||||||
</label>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* ── Target tab ── */}
|
|
||||||
{activeTab === 'target' && (
|
|
||||||
<>
|
|
||||||
<div>
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1">Εμβέλεια</label>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{[['global','Καθολικός (με στόχους)'],['item','Συγκεκριμένο προϊόν']].map(([v, l]) => (
|
|
||||||
<button type="button" key={v} onClick={() => set('scope', v)}
|
|
||||||
className={`flex-1 py-2 rounded-lg border text-[12px] font-medium transition-colors ${
|
|
||||||
f.scope === v ? 'border-sky-500 bg-sky-50 text-sky-700' : 'border-slate-200 text-slate-500 hover:bg-slate-50'
|
|
||||||
}`}>{l}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
{f.scope === 'item' && (
|
|
||||||
<select className="input w-full mt-2 text-[13px]" value={f.item_id ?? ''}
|
|
||||||
onChange={e => set('item_id', Number(e.target.value))}>
|
|
||||||
<option value="">— Επιλογή προϊόντος —</option>
|
|
||||||
{products.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
|
|
||||||
</select>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{f.scope === 'global' && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-[12px] font-semibold text-slate-600 uppercase tracking-wide">
|
|
||||||
Στόχοι <span className="font-normal text-slate-400 normal-case ml-1">(OR — αρκεί ένας)</span>
|
|
||||||
</span>
|
|
||||||
<button type="button" onClick={addTarget}
|
|
||||||
className="text-[12px] text-sky-600 hover:text-sky-700 flex items-center gap-1">
|
|
||||||
<Plus className="w-3.5 h-3.5" />Προσθήκη
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{f.targets.length === 0 && (
|
|
||||||
<p className="text-[12px] text-amber-600 bg-amber-50 rounded-lg px-3 py-2.5">
|
|
||||||
Χωρίς στόχο — ο τροποποιητής δεν θα εφαρμοστεί σε κανένα προϊόν.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{f.targets.map((t, i) => (
|
|
||||||
<TargetEditor key={i} target={t}
|
|
||||||
onChange={v => updateTarget(i, v)}
|
|
||||||
onRemove={() => removeTarget(i)}
|
|
||||||
products={products} categories={categories} prepZones={prepZones} allTags={allTags} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* ── Conditions tab ── */}
|
|
||||||
{activeTab === 'conditions' && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<span className="text-[12px] font-semibold text-slate-600 uppercase tracking-wide">Συνθήκες</span>
|
|
||||||
<span className="text-[11px] text-slate-400 ml-1.5">AND — όλες πρέπει να ισχύουν</span>
|
|
||||||
</div>
|
|
||||||
<button type="button" onClick={addCondition}
|
|
||||||
className="text-[12px] text-sky-600 hover:text-sky-700 flex items-center gap-1">
|
|
||||||
<Plus className="w-3.5 h-3.5" />Προσθήκη
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{f.conditions.length === 0 && (
|
|
||||||
<p className="text-[12px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2.5">
|
|
||||||
Χωρίς συνθήκες — ο τροποποιητής εφαρμόζεται χειροκίνητα μέσω ενεργοποίησης.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{f.conditions.map((c, i) => (
|
|
||||||
<ConditionEditor key={i} cond={c}
|
|
||||||
onChange={v => updateCondition(i, v)}
|
|
||||||
onRemove={() => removeCondition(i)}
|
|
||||||
groups={groups} categories={categories} prepZones={prepZones} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* ── Price Modifier tab ── */}
|
|
||||||
{activeTab === 'price' && (
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{[['set','Ορισμός τιμής'],['add_amount','± Ποσό €'],['add_percent','± Ποσοστό %']].map(([v,l]) => (
|
|
||||||
<button type="button" key={v} onClick={() => set('action_type', v)}
|
|
||||||
className={`flex-1 py-1.5 rounded-lg border text-[12px] font-medium transition-colors ${
|
|
||||||
f.action_type === v ? 'border-sky-500 bg-sky-50 text-sky-700' : 'border-slate-200 text-slate-500 hover:bg-slate-50'
|
|
||||||
}`}>{l}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-3 items-end">
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">{actionLabel}</label>
|
|
||||||
<input type="number" step={f.action_type === 'set' ? 0.01 : f.action_type === 'add_amount' ? 0.1 : 1}
|
|
||||||
className="input w-full" value={f.action_value}
|
|
||||||
onChange={e => set('action_value', Number(e.target.value))} />
|
|
||||||
</div>
|
|
||||||
{f.action_type === 'add_percent' && (
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-0.5">Στρογγυλοποίηση (προαιρ.)</label>
|
|
||||||
<select className="input w-full text-[12px]" value={f.round_to ?? ''}
|
|
||||||
onChange={e => set('round_to', e.target.value)}>
|
|
||||||
{ROUND_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<p className="text-[11px] text-slate-400">
|
|
||||||
Το σύστημα στρογγυλοποιεί πάντα την τελική τιμή στο κοντινότερο €0,10 ανεξάρτητα από την παραπάνω επιλογή.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
</form>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Modifier card ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function ModifierCard({ modifier, onEdit, onDelete, dragHandleProps }) {
|
|
||||||
const qc = useQueryClient()
|
|
||||||
const [expanded, setExpanded] = useState(false)
|
|
||||||
|
|
||||||
const toggle = useMutation({
|
|
||||||
mutationFn: () => api.toggle(modifier.id),
|
|
||||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['pricing-modifiers'] }),
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
|
|
||||||
const actionText = modifier.action_type === 'set'
|
|
||||||
? `= €${modifier.action_value}`
|
|
||||||
: modifier.action_type === 'add_amount'
|
|
||||||
? `${modifier.action_value >= 0 ? '+' : ''}€${modifier.action_value}`
|
|
||||||
: `${modifier.action_value >= 0 ? '+' : ''}${modifier.action_value}%`
|
|
||||||
|
|
||||||
const condCount = modifier.conditions?.length ?? 0
|
|
||||||
const targetSummary = modifier.scope === 'item'
|
|
||||||
? 'item-scope'
|
|
||||||
: modifier.targets?.length === 1 && modifier.targets[0]?.target_type === 'all'
|
|
||||||
? 'Όλα τα προϊόντα'
|
|
||||||
: `${modifier.targets?.length ?? 0} στόχοι`
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={`bg-white rounded-xl border shadow-sm transition-opacity ${modifier.is_active ? 'border-slate-200' : 'border-slate-100 opacity-60'}`}>
|
|
||||||
<div className="flex items-center gap-2 px-3 py-3">
|
|
||||||
{/* Drag handle */}
|
|
||||||
<div {...dragHandleProps} className="cursor-grab text-slate-300 hover:text-slate-400 shrink-0">
|
|
||||||
<GripVertical className="w-4 h-4" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Color bar */}
|
|
||||||
<div className="w-1 h-8 rounded-full shrink-0" style={{ background: modifier.color ?? '#64748b' }} />
|
|
||||||
|
|
||||||
{/* Name + badges */}
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-1.5 flex-wrap">
|
|
||||||
<span className="text-[13px] font-semibold text-slate-800 truncate">{modifier.name}</span>
|
|
||||||
{modifier.is_favorite && <Star className="w-3 h-3 text-amber-400 fill-amber-400 shrink-0" />}
|
|
||||||
{modifier.allow_stack && <Layers className="w-3 h-3 text-sky-400 shrink-0" title="Stackable" />}
|
|
||||||
<span className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full ${
|
|
||||||
modifier.action_value < 0 ? 'bg-emerald-100 text-emerald-700' : 'bg-sky-100 text-sky-700'
|
|
||||||
}`}>{actionText}</span>
|
|
||||||
<span className="text-[10px] text-slate-400">{condCount === 0 ? 'χειροκίνητος' : `${condCount} συνθ.`} · {targetSummary}</span>
|
|
||||||
</div>
|
|
||||||
{modifier.description && <p className="text-[11px] text-slate-400 truncate mt-0.5">{modifier.description}</p>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Actions */}
|
|
||||||
<div className="flex items-center gap-0.5 shrink-0">
|
|
||||||
<button onClick={() => setExpanded(e => !e)}
|
|
||||||
className="p-1.5 rounded text-slate-400 hover:bg-slate-100 transition-colors">
|
|
||||||
{expanded ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
|
|
||||||
</button>
|
|
||||||
<button onClick={() => toggle.mutate()}
|
|
||||||
className={`p-1.5 rounded transition-colors ${
|
|
||||||
modifier.is_active ? 'text-emerald-600 hover:bg-emerald-50' : 'text-slate-400 hover:bg-slate-100'
|
|
||||||
}`} title={modifier.is_active ? 'Απενεργοποίηση' : 'Ενεργοποίηση'}>
|
|
||||||
<Power className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
<button onClick={() => onEdit(modifier)}
|
|
||||||
className="p-1.5 rounded text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
|
|
||||||
<Pencil className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
<button onClick={() => onDelete(modifier)}
|
|
||||||
className="p-1.5 rounded text-slate-400 hover:bg-rose-50 hover:text-rose-500 transition-colors">
|
|
||||||
<Trash2 className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Expanded detail */}
|
|
||||||
{expanded && (
|
|
||||||
<div className="border-t border-slate-100 px-4 py-3 text-[12px] text-slate-500 space-y-1.5">
|
|
||||||
{modifier.conditions?.length === 0 && <p className="italic">Χωρίς αυτόματες συνθήκες — μόνο χειροκίνητη ενεργοποίηση</p>}
|
|
||||||
{modifier.conditions?.map((c, i) => (
|
|
||||||
<div key={i} className="flex items-center gap-1.5">
|
|
||||||
<span className="w-1.5 h-1.5 rounded-full bg-sky-400 shrink-0" />
|
|
||||||
<span>{CONDITION_TYPES.find(x => x.value === c.condition_type)?.label ?? c.condition_type}</span>
|
|
||||||
<span className="text-slate-400 font-mono text-[11px]">{JSON.stringify(c.params)}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Main tab ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export default function ModifiersTab() {
|
|
||||||
const qc = useQueryClient()
|
|
||||||
const [showForm, setShowForm] = useState(false)
|
|
||||||
const [editing, setEditing] = useState(null)
|
|
||||||
const [deleting, setDeleting] = useState(null)
|
|
||||||
const [formTab, setFormTab] = useState('info')
|
|
||||||
const [scopeFilter, setScopeFilter] = useState('all')
|
|
||||||
const [items, setItems] = useState(null)
|
|
||||||
const [dragging, setDragging] = useState(null)
|
|
||||||
|
|
||||||
const { data: rawModifiers = [], isLoading } = useQuery({
|
|
||||||
queryKey: ['pricing-modifiers'],
|
|
||||||
queryFn: () => api.list(),
|
|
||||||
})
|
|
||||||
const modifiers = items ?? rawModifiers
|
|
||||||
|
|
||||||
const { data: groups = [] } = useQuery({ queryKey: ['pricing-groups'], queryFn: api.groups, staleTime: 30_000 })
|
|
||||||
|
|
||||||
const create = useMutation({
|
|
||||||
mutationFn: api.create,
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-modifiers'] }); setItems(null); setShowForm(false); toast.success('Δημιουργήθηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
const update = useMutation({
|
|
||||||
mutationFn: ({ id, body }) => api.update(id, body),
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-modifiers'] }); setItems(null); setEditing(null); toast.success('Αποθηκεύτηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
const remove = useMutation({
|
|
||||||
mutationFn: api.remove,
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-modifiers'] }); setItems(null); setDeleting(null); toast.success('Διαγράφηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
const reorder = useMutation({
|
|
||||||
mutationFn: api.reorder,
|
|
||||||
onError: () => { setItems(null); toast.error('Σφάλμα αναδιάταξης') },
|
|
||||||
})
|
|
||||||
|
|
||||||
// Simple drag-to-reorder (no extra library — HTML5 DnD)
|
|
||||||
function handleDragStart(e, id) {
|
|
||||||
setDragging(id)
|
|
||||||
e.dataTransfer.effectAllowed = 'move'
|
|
||||||
}
|
|
||||||
function handleDragOver(e, id) {
|
|
||||||
e.preventDefault()
|
|
||||||
if (dragging == null || dragging === id) return
|
|
||||||
const from = modifiers.findIndex(m => m.id === dragging)
|
|
||||||
const to = modifiers.findIndex(m => m.id === id)
|
|
||||||
if (from === -1 || to === -1) return
|
|
||||||
const reordered = [...modifiers]
|
|
||||||
const [moved] = reordered.splice(from, 1)
|
|
||||||
reordered.splice(to, 0, moved)
|
|
||||||
setItems(reordered)
|
|
||||||
}
|
|
||||||
function handleDrop() {
|
|
||||||
setDragging(null)
|
|
||||||
const payload = (items ?? modifiers).map((m, i) => ({ id: m.id, sort_order: i }))
|
|
||||||
reorder.mutate(payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
const filtered = scopeFilter === 'all' ? modifiers : modifiers.filter(m => m.scope === scopeFilter)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="p-6 space-y-4">
|
|
||||||
<div className="flex items-start justify-between gap-4">
|
|
||||||
<div>
|
|
||||||
<h2 className="text-[14px] font-semibold text-slate-800">Τροποποιητές Τιμής</h2>
|
|
||||||
<p className="text-[12px] text-slate-500 mt-0.5">
|
|
||||||
Κανόνες που αλλάζουν τιμές αυτόματα ή χειροκίνητα. Η σειρά καθορίζει προτεραιότητα.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button variant="primary" onClick={() => setShowForm(true)}>
|
|
||||||
<Plus className="w-4 h-4 mr-1.5" />Νέος Τροποποιητής
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Filter pills */}
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{[['all','Όλοι'],['global','Καθολικοί'],['item','Item-scope']].map(([v,l]) => (
|
|
||||||
<button key={v} onClick={() => setScopeFilter(v)}
|
|
||||||
className={`px-3 py-1 rounded-full text-[12px] font-medium transition-colors ${
|
|
||||||
scopeFilter === v ? 'bg-sky-100 text-sky-700' : 'bg-slate-100 text-slate-500 hover:bg-slate-200'
|
|
||||||
}`}>{l}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="flex justify-center py-12">
|
|
||||||
<div className="w-5 h-5 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
|
|
||||||
</div>
|
|
||||||
) : filtered.length === 0 ? (
|
|
||||||
<div className="flex flex-col items-center justify-center py-16 text-slate-400">
|
|
||||||
<Percent className="w-10 h-10 mb-3 opacity-30" />
|
|
||||||
<p className="text-[13px]">Δεν υπάρχουν τροποποιητές</p>
|
|
||||||
<p className="text-[12px] mt-1">Δημιουργήστε έναν για Happy Hour, εποχιακές τιμές κ.λπ.</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-2" onDragOver={e => e.preventDefault()} onDrop={handleDrop}>
|
|
||||||
{filtered.map(m => (
|
|
||||||
<div key={m.id} draggable
|
|
||||||
onDragStart={e => handleDragStart(e, m.id)}
|
|
||||||
onDragOver={e => handleDragOver(e, m.id)}
|
|
||||||
className={dragging === m.id ? 'opacity-50' : ''}>
|
|
||||||
<ModifierCard modifier={m} onEdit={m => { setEditing(m); setFormTab('info') }} onDelete={setDeleting}
|
|
||||||
dragHandleProps={{
|
|
||||||
onMouseDown: () => {},
|
|
||||||
title: 'Σύρετε για αναδιάταξη',
|
|
||||||
}} />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Create */}
|
|
||||||
{showForm && (
|
|
||||||
<Modal title="Νέος Τροποποιητής Τιμής" onClose={() => { setShowForm(false); setFormTab('info') }}
|
|
||||||
maxWidth="max-w-xl" tabs={MODIFIER_TABS} activeTab={formTab} onTabChange={setFormTab}
|
|
||||||
footer={<>
|
|
||||||
<Button type="button" variant="secondary" onClick={() => { setShowForm(false); setFormTab('info') }}>Ακύρωση</Button>
|
|
||||||
<Button type="submit" form="modifier-form" variant="primary" disabled={create.isPending}>
|
|
||||||
{create.isPending ? 'Αποθήκευση...' : 'Αποθήκευση'}
|
|
||||||
</Button>
|
|
||||||
</>}>
|
|
||||||
<ModifierForm onSave={body => create.mutate(body)} onCancel={() => { setShowForm(false); setFormTab('info') }}
|
|
||||||
saving={create.isPending} groups={groups} activeTab={formTab} onTabChange={setFormTab} />
|
|
||||||
</Modal>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Edit */}
|
|
||||||
{editing && (
|
|
||||||
<Modal title="Επεξεργασία Τροποποιητή" onClose={() => { setEditing(null); setFormTab('info') }}
|
|
||||||
maxWidth="max-w-xl" tabs={MODIFIER_TABS} activeTab={formTab} onTabChange={setFormTab}
|
|
||||||
footer={<>
|
|
||||||
<Button type="button" variant="secondary" onClick={() => { setEditing(null); setFormTab('info') }}>Ακύρωση</Button>
|
|
||||||
<Button type="submit" form="modifier-form" variant="primary" disabled={update.isPending}>
|
|
||||||
{update.isPending ? 'Αποθήκευση...' : 'Αποθήκευση'}
|
|
||||||
</Button>
|
|
||||||
</>}>
|
|
||||||
<ModifierForm initial={editing} onSave={body => update.mutate({ id: editing.id, body })}
|
|
||||||
onCancel={() => { setEditing(null); setFormTab('info') }} saving={update.isPending}
|
|
||||||
groups={groups} activeTab={formTab} onTabChange={setFormTab} />
|
|
||||||
</Modal>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Delete */}
|
|
||||||
{deleting && (
|
|
||||||
<ConfirmModal title="Διαγραφή Τροποποιητή"
|
|
||||||
message={`Θέλετε να διαγράψετε τον τροποποιητή "${deleting.name}";`}
|
|
||||||
confirmLabel="Διαγραφή"
|
|
||||||
onConfirm={() => remove.mutate(deleting.id)}
|
|
||||||
onCancel={() => setDeleting(null)} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,280 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
|
||||||
import { Plus, Tag, Power, Pencil, Trash2, Clock } from 'lucide-react'
|
|
||||||
import toast from 'react-hot-toast'
|
|
||||||
import client from '../../../api/client'
|
|
||||||
import Button from '../../../ui/Button'
|
|
||||||
import Modal from '../../../ui/Modal'
|
|
||||||
import { ConfirmModal } from '../../../ui/Modal'
|
|
||||||
|
|
||||||
const DAYS = ['Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ', 'Κυρ']
|
|
||||||
|
|
||||||
const api = {
|
|
||||||
list: () => client.get('/api/pricing/groups').then(r => r.data),
|
|
||||||
create: body => client.post('/api/pricing/groups', body).then(r => r.data),
|
|
||||||
update: (id,b) => client.put(`/api/pricing/groups/${id}`, b).then(r => r.data),
|
|
||||||
toggle: id => client.patch(`/api/pricing/groups/${id}/toggle`).then(r => r.data),
|
|
||||||
remove: id => client.delete(`/api/pricing/groups/${id}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
const COLORS = [
|
|
||||||
'#6366f1','#8b5cf6','#ec4899','#f43f5e','#f97316',
|
|
||||||
'#eab308','#22c55e','#14b8a6','#0ea5e9','#64748b',
|
|
||||||
]
|
|
||||||
|
|
||||||
function GroupForm({ initial, onSave, onCancel, saving }) {
|
|
||||||
const blank = { name: '', description: '', color: COLORS[0], is_active: false,
|
|
||||||
auto_enable_time: '', auto_disable_time: '', auto_days: [] }
|
|
||||||
const [f, setF] = useState(initial ? {
|
|
||||||
...initial,
|
|
||||||
auto_days: initial.auto_days ?? [],
|
|
||||||
} : blank)
|
|
||||||
|
|
||||||
const set = (k, v) => setF(p => ({ ...p, [k]: v }))
|
|
||||||
const toggleDay = d => set('auto_days', f.auto_days.includes(d)
|
|
||||||
? f.auto_days.filter(x => x !== d)
|
|
||||||
: [...f.auto_days, d])
|
|
||||||
|
|
||||||
const hasSchedule = f.auto_enable_time || f.auto_disable_time || f.auto_days.length > 0
|
|
||||||
|
|
||||||
function submit(e) {
|
|
||||||
e.preventDefault()
|
|
||||||
if (!f.name.trim()) return toast.error('Απαιτείται όνομα')
|
|
||||||
onSave({
|
|
||||||
...f,
|
|
||||||
auto_days: f.auto_days.length ? f.auto_days : null,
|
|
||||||
auto_enable_time: f.auto_enable_time || null,
|
|
||||||
auto_disable_time: f.auto_disable_time || null,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form onSubmit={submit} className="space-y-4">
|
|
||||||
{/* Name */}
|
|
||||||
<div>
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1">Όνομα</label>
|
|
||||||
<input className="input w-full" value={f.name} onChange={e => set('name', e.target.value)}
|
|
||||||
placeholder="π.χ. Happy Hour" autoFocus />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Description */}
|
|
||||||
<div>
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-1">Περιγραφή (προαιρετική)</label>
|
|
||||||
<input className="input w-full" value={f.description ?? ''} onChange={e => set('description', e.target.value)}
|
|
||||||
placeholder="Σύντομη περιγραφή..." />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Color */}
|
|
||||||
<div>
|
|
||||||
<label className="block text-[12px] font-medium text-slate-600 mb-2">Χρώμα</label>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{COLORS.map(c => (
|
|
||||||
<button type="button" key={c} onClick={() => set('color', c)}
|
|
||||||
className={`w-7 h-7 rounded-full transition-transform ${f.color === c ? 'ring-2 ring-offset-2 ring-slate-400 scale-110' : 'hover:scale-105'}`}
|
|
||||||
style={{ background: c }} />
|
|
||||||
))}
|
|
||||||
<input type="color" value={f.color ?? '#6366f1'} onChange={e => set('color', e.target.value)}
|
|
||||||
className="w-7 h-7 rounded-full border-0 cursor-pointer p-0.5 bg-transparent" title="Προσαρμοσμένο χρώμα" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Active toggle */}
|
|
||||||
<label className="flex items-center gap-3 cursor-pointer select-none">
|
|
||||||
<div onClick={() => set('is_active', !f.is_active)}
|
|
||||||
className={`relative w-9 h-5 rounded-full transition-colors ${f.is_active ? 'bg-sky-500' : 'bg-slate-200'}`}>
|
|
||||||
<span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${f.is_active ? 'translate-x-4' : ''}`} />
|
|
||||||
</div>
|
|
||||||
<span className="text-[13px] font-medium text-slate-700">Ενεργή τώρα</span>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
{/* Auto-schedule */}
|
|
||||||
<div className="rounded-lg border border-slate-200 p-3 space-y-3">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Clock className="w-3.5 h-3.5 text-slate-400" />
|
|
||||||
<span className="text-[12px] font-semibold text-slate-600 uppercase tracking-wide">Αυτόματο Χρονοδιάγραμμα</span>
|
|
||||||
<span className="text-[11px] text-slate-400">(προαιρετικό)</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1">Ενεργοποίηση</label>
|
|
||||||
<input type="time" className="input w-full text-[13px]"
|
|
||||||
value={f.auto_enable_time ?? ''} onChange={e => set('auto_enable_time', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1">Απενεργοποίηση</label>
|
|
||||||
<input type="time" className="input w-full text-[13px]"
|
|
||||||
value={f.auto_disable_time ?? ''} onChange={e => set('auto_disable_time', e.target.value)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-[11px] text-slate-500 mb-1.5">Ημέρες</label>
|
|
||||||
<div className="flex gap-1.5 flex-wrap">
|
|
||||||
{DAYS.map((d, i) => (
|
|
||||||
<button type="button" key={i} onClick={() => toggleDay(i)}
|
|
||||||
className={`px-2.5 py-1 rounded text-[12px] font-medium transition-colors ${
|
|
||||||
f.auto_days.includes(i) ? 'bg-sky-100 text-sky-700' : 'bg-slate-100 text-slate-500 hover:bg-slate-200'
|
|
||||||
}`}>{d}</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{hasSchedule && (!f.auto_enable_time || !f.auto_disable_time || !f.auto_days.length) && (
|
|
||||||
<p className="text-[11px] text-amber-600 bg-amber-50 rounded px-2 py-1">
|
|
||||||
Για πλήρες χρονοδιάγραμμα ορίστε ώρα ενεργοποίησης, ώρα απενεργοποίησης και τουλάχιστον μία ημέρα.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Modal.Footer>
|
|
||||||
<Button type="button" variant="secondary" onClick={onCancel}>Ακύρωση</Button>
|
|
||||||
<Button type="submit" variant="primary" disabled={saving}>
|
|
||||||
{saving ? 'Αποθήκευση...' : 'Αποθήκευση'}
|
|
||||||
</Button>
|
|
||||||
</Modal.Footer>
|
|
||||||
</form>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function GroupCard({ group, onEdit, onDelete }) {
|
|
||||||
const qc = useQueryClient()
|
|
||||||
const toggle = useMutation({
|
|
||||||
mutationFn: () => api.toggle(group.id),
|
|
||||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['pricing-groups'] }),
|
|
||||||
onError: () => toast.error('Σφάλμα'),
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-4 flex items-start gap-3">
|
|
||||||
{/* Color dot */}
|
|
||||||
<div className="w-3 h-3 rounded-full mt-1 shrink-0" style={{ background: group.color ?? '#6366f1' }} />
|
|
||||||
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
|
||||||
<span className="text-[14px] font-semibold text-slate-800 truncate">{group.name}</span>
|
|
||||||
<span className={`text-[11px] font-medium px-1.5 py-0.5 rounded-full ${
|
|
||||||
group.is_active ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500'
|
|
||||||
}`}>{group.is_active ? 'Ενεργή' : 'Ανενεργή'}</span>
|
|
||||||
</div>
|
|
||||||
{group.description && <p className="text-[12px] text-slate-500 mt-0.5 truncate">{group.description}</p>}
|
|
||||||
{group.auto_enable_time && group.auto_disable_time && (
|
|
||||||
<p className="text-[11px] text-slate-400 mt-1 flex items-center gap-1">
|
|
||||||
<Clock className="w-3 h-3" />
|
|
||||||
{group.auto_enable_time}–{group.auto_disable_time}
|
|
||||||
{group.auto_days?.length > 0 && (
|
|
||||||
<span className="ml-1">{group.auto_days.map(d => DAYS[d]).join(', ')}</span>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-1 shrink-0">
|
|
||||||
{/* Quick toggle */}
|
|
||||||
<button onClick={() => toggle.mutate()}
|
|
||||||
className={`p-1.5 rounded-lg transition-colors ${
|
|
||||||
group.is_active ? 'text-emerald-600 hover:bg-emerald-50' : 'text-slate-400 hover:bg-slate-100'
|
|
||||||
}`} title={group.is_active ? 'Απενεργοποίηση' : 'Ενεργοποίηση'}>
|
|
||||||
<Power className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button onClick={() => onEdit(group)}
|
|
||||||
className="p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
|
|
||||||
<Pencil className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button onClick={() => onDelete(group)}
|
|
||||||
className="p-1.5 rounded-lg text-slate-400 hover:bg-rose-50 hover:text-rose-500 transition-colors">
|
|
||||||
<Trash2 className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function PriceGroupsTab() {
|
|
||||||
const qc = useQueryClient()
|
|
||||||
const [showForm, setShowForm] = useState(false)
|
|
||||||
const [editing, setEditing] = useState(null)
|
|
||||||
const [deleting, setDeleting] = useState(null)
|
|
||||||
|
|
||||||
const { data: groups = [], isLoading } = useQuery({ queryKey: ['pricing-groups'], queryFn: api.list })
|
|
||||||
|
|
||||||
const create = useMutation({
|
|
||||||
mutationFn: api.create,
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-groups'] }); setShowForm(false); toast.success('Ομάδα δημιουργήθηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα δημιουργίας'),
|
|
||||||
})
|
|
||||||
const update = useMutation({
|
|
||||||
mutationFn: ({ id, body }) => api.update(id, body),
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-groups'] }); setEditing(null); toast.success('Αποθηκεύτηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα αποθήκευσης'),
|
|
||||||
})
|
|
||||||
const remove = useMutation({
|
|
||||||
mutationFn: api.remove,
|
|
||||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['pricing-groups'] }); setDeleting(null); toast.success('Διαγράφηκε') },
|
|
||||||
onError: () => toast.error('Σφάλμα διαγραφής'),
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="p-6 space-y-4">
|
|
||||||
{/* Header row */}
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h2 className="text-[14px] font-semibold text-slate-800">Ομάδες Τιμών</h2>
|
|
||||||
<p className="text-[12px] text-slate-500 mt-0.5">
|
|
||||||
Ονομαστές ομάδες που ενεργοποιούνται χειροκίνητα ή αυτόματα. Χρησιμοποιούνται ως συνθήκη σε τροποποιητές τιμής.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button variant="primary" onClick={() => setShowForm(true)}>
|
|
||||||
<Plus className="w-4 h-4 mr-1.5" />Νέα Ομάδα
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* List */}
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="flex justify-center py-12">
|
|
||||||
<div className="w-5 h-5 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
|
|
||||||
</div>
|
|
||||||
) : groups.length === 0 ? (
|
|
||||||
<div className="flex flex-col items-center justify-center py-16 text-slate-400">
|
|
||||||
<Tag className="w-10 h-10 mb-3 opacity-30" />
|
|
||||||
<p className="text-[13px]">Δεν υπάρχουν ομάδες τιμών</p>
|
|
||||||
<p className="text-[12px] mt-1">Δημιουργήστε μια ομάδα για Happy Hour, Εποχή κ.λπ.</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
|
||||||
{groups.map(g => (
|
|
||||||
<GroupCard key={g.id} group={g}
|
|
||||||
onEdit={setEditing}
|
|
||||||
onDelete={setDeleting} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Create modal */}
|
|
||||||
{showForm && (
|
|
||||||
<Modal title="Νέα Ομάδα Τιμών" onClose={() => setShowForm(false)} maxWidth="max-w-md">
|
|
||||||
<GroupForm onSave={body => create.mutate(body)} onCancel={() => setShowForm(false)} saving={create.isPending} />
|
|
||||||
</Modal>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Edit modal */}
|
|
||||||
{editing && (
|
|
||||||
<Modal title="Επεξεργασία Ομάδας" onClose={() => setEditing(null)} maxWidth="max-w-md">
|
|
||||||
<GroupForm initial={editing} onSave={body => update.mutate({ id: editing.id, body })}
|
|
||||||
onCancel={() => setEditing(null)} saving={update.isPending} />
|
|
||||||
</Modal>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Delete confirm */}
|
|
||||||
{deleting && (
|
|
||||||
<ConfirmModal
|
|
||||||
title="Διαγραφή Ομάδας"
|
|
||||||
message={`Θέλετε σίγουρα να διαγράψετε την ομάδα "${deleting.name}"; Τυχόν τροποποιητές που τη χρησιμοποιούν δεν θα επηρεαστούν αλλά η συνθήκη δεν θα εκπληρώνεται πλέον.`}
|
|
||||||
confirmLabel="Διαγραφή"
|
|
||||||
onConfirm={() => remove.mutate(deleting.id)}
|
|
||||||
onCancel={() => setDeleting(null)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
// Deals (plan step 6.7): offers a waiter is prompted with when an order has the right products,
|
||||||
|
// e.g. "3 beers → a fourth free". A deal has
|
||||||
|
// - when: the products the order must have (any of the rows) and optional conditions (all hold);
|
||||||
|
// - what it gives: a free product, a free one the guest picks from a list, a manual price rule, a
|
||||||
|
// new price, ± an amount or ± a percentage.
|
||||||
|
// Nothing is applied by itself: the waiter's phone shows the offer and the waiter accepts or skips it.
|
||||||
|
import { useState } from 'react'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import { Plus } from 'lucide-react'
|
||||||
|
import { errorMessage } from '@xenia/api'
|
||||||
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||||
|
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||||
|
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||||
|
import * as api from './pricingApi'
|
||||||
|
import { ColourPicker, ConditionList, Missing, PickSeveral, RuleCard, Segmented, TabHead, TagPicker, TargetList } from './PricingParts'
|
||||||
|
import { COLOURS, useCatalog } from './useCatalog'
|
||||||
|
import { DEAL_ACTIONS, DEAL_CONDITIONS, DEAL_TARGETS, FREE_CHOICE_FROM, actionText, dealBody, dealForm, dealProblems } from './pricingLogic'
|
||||||
|
|
||||||
|
const PAGES = ['when', 'gives']
|
||||||
|
|
||||||
|
export default function DealsTab() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { formatMoney } = useFormat()
|
||||||
|
const catalog = useCatalog()
|
||||||
|
const { data: deals, refetch } = useLiveQuery({ queryKey: ['pricing', 'deals'], queryFn: api.listDeals, events: api.PRICING_EVENTS })
|
||||||
|
const { data: rules = [] } = useLiveQuery({ queryKey: ['pricing', 'modifiers'], queryFn: api.listModifiers, events: api.PRICING_EVENTS })
|
||||||
|
const [editing, setEditing] = useState(null)
|
||||||
|
const [deleting, setDeleting] = useState(null)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
|
const run = async (fn, done) => {
|
||||||
|
setBusy(true)
|
||||||
|
try { await fn(); if (done) toast.success(done); await refetch(); return true } catch (err) { toast.error(errorMessage(err, t)); return false } finally { setBusy(false) }
|
||||||
|
}
|
||||||
|
const givesText = d => {
|
||||||
|
if (d.action_type === 'free_item') return t('pricing.deals.givesFree', { count: d.action_free_quantity, name: catalog.products.find(p => p.id === d.action_free_item_id)?.name ?? '—' })
|
||||||
|
if (d.action_type === 'free_choice') return t('pricing.deals.givesChoice', { count: d.action_free_quantity })
|
||||||
|
if (d.action_type === 'apply_modifier') return t('pricing.deals.givesRule', { name: rules.find(r => r.id === d.action_modifier_id)?.name ?? '—' })
|
||||||
|
return actionText(d.action_type, d.action_value, formatMoney)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="grid gap-4" data-testid="pricing-deals">
|
||||||
|
<TabHead title={t('pricing.deals.title')} intro={t('pricing.deals.intro')}
|
||||||
|
action={<Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="pricing-deal-new">{t('pricing.deals.new')}</Button>} />
|
||||||
|
{!deals ? <div className="flex justify-center p-6"><Spinner /></div>
|
||||||
|
: deals.length === 0 ? <EmptyState title={t('pricing.deals.none')} description={t('pricing.deals.noneHint')} />
|
||||||
|
: (
|
||||||
|
<ul className="grid gap-2">
|
||||||
|
{deals.map(d => (
|
||||||
|
<RuleCard key={d.id} testid="pricing-deal" colour={d.color ?? COLOURS[2]} name={d.name} active={d.is_active} busy={busy}
|
||||||
|
description={d.description}
|
||||||
|
badges={<span className="px-2 py-0.5 rounded-full bg-accent-soft text-accent-ink text-caption font-semibold">{givesText(d)}</span>}
|
||||||
|
summary={d.conditions?.length ? t('pricing.rules.conditions', { count: d.conditions.length }) : null}
|
||||||
|
onToggle={() => run(() => api.toggleDeal(d.id))}
|
||||||
|
onEdit={() => setEditing(d)} onDelete={() => setDeleting(d)} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{editing && <DealDialog deal={editing} catalog={catalog} rules={rules} busy={busy} onClose={() => setEditing(null)}
|
||||||
|
onSave={async body => { if (await run(() => api.saveDeal(editing.id, body), t('pricing.saved'))) setEditing(null) }} />}
|
||||||
|
{deleting && (
|
||||||
|
<Dialog open size="sm" title={t('pricing.deals.deleteTitle')} onClose={() => setDeleting(null)}
|
||||||
|
footer={<>
|
||||||
|
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('pricing.cancel')}</Button>
|
||||||
|
<Button variant="danger" loading={busy} data-testid="pricing-confirm-delete"
|
||||||
|
onClick={async () => { if (await run(() => api.deleteDeal(deleting.id), t('pricing.deleted'))) setDeleting(null) }}>{t('pricing.delete')}</Button>
|
||||||
|
</>}>
|
||||||
|
<p>{t('pricing.deals.deleteBody', { name: deleting.name })}</p>
|
||||||
|
</Dialog>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DealDialog({ deal, catalog, rules, busy, onClose, onSave }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const [f, setF] = useState(() => dealForm(deal.id ? deal : null, COLOURS[2]))
|
||||||
|
const [page, setPage] = useState('when')
|
||||||
|
const [tried, setTried] = useState(false)
|
||||||
|
const set = (k, v) => setF(p => ({ ...p, [k]: v }))
|
||||||
|
const problems = dealProblems(f)
|
||||||
|
const manualRules = rules.filter(r => !r.conditions?.length)
|
||||||
|
const a = f.action_type
|
||||||
|
return (
|
||||||
|
<Dialog open size="lg" onClose={onClose} title={t(deal.id ? 'pricing.deals.edit' : 'pricing.deals.new')}
|
||||||
|
footer={<>
|
||||||
|
<Button variant="secondary" onClick={onClose}>{t('pricing.cancel')}</Button>
|
||||||
|
<Button loading={busy} data-testid="pricing-save" onClick={() => { setTried(true); if (!problems.length) onSave(dealBody(f)) }}>{t('pricing.save')}</Button>
|
||||||
|
</>}>
|
||||||
|
<div className="grid gap-4" data-testid="pricing-deal-dialog">
|
||||||
|
<div className="grid sm:grid-cols-2 gap-3">
|
||||||
|
<Field label={t('pricing.name')}><Input value={f.name} autoFocus onChange={e => set('name', e.target.value)} placeholder={t('pricing.deals.namePlaceholder')} data-testid="pricing-name" /></Field>
|
||||||
|
<Field label={t('pricing.description')} hint={t('pricing.deals.descriptionHint')}><Input value={f.description} onChange={e => set('description', e.target.value)} /></Field>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-1 border-b border-line" role="tablist">
|
||||||
|
{PAGES.map(k => (
|
||||||
|
<button key={k} type="button" role="tab" aria-selected={page === k} onClick={() => setPage(k)} data-testid={`pricing-deal-page-${k}`}
|
||||||
|
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast ${page === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
|
||||||
|
{t(`pricing.deals.pages.${k}`)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{page === 'when' && (
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<p className="text-caption text-ink-2">{t('pricing.deals.targetsHint')}</p>
|
||||||
|
<TargetList value={f.targets} onChange={v => set('targets', v)} types={DEAL_TARGETS} catalog={catalog} testid="pricing-deal-targets" />
|
||||||
|
<p className="text-caption text-ink-2">{t('pricing.deals.conditionsHint')}</p>
|
||||||
|
<ConditionList value={f.conditions} onChange={v => set('conditions', v)} types={DEAL_CONDITIONS} catalog={catalog} testid="pricing-deal-conditions" />
|
||||||
|
<Switch checked={f.is_active} onChange={v => set('is_active', v)} label={t('pricing.deals.on')} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{page === 'gives' && (
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<Segmented value={a} onChange={v => set('action_type', v)} testid="pricing-deal-action"
|
||||||
|
options={DEAL_ACTIONS.map(v => ({ value: v, label: t(`pricing.deals.actions.${v}`) }))} />
|
||||||
|
{a === 'free_item' && (
|
||||||
|
<Field label={t('pricing.deals.freeProduct')}>
|
||||||
|
<Select value={f.action_free_item_id ?? ''} onChange={e => set('action_free_item_id', e.target.value === '' ? null : Number(e.target.value))}
|
||||||
|
placeholder={t('pricing.choose')} options={catalog.products.map(p => ({ value: p.id, label: p.name }))} data-testid="pricing-deal-free-product" />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
{a === 'free_choice' && (
|
||||||
|
<>
|
||||||
|
<Segmented value={f.action_free_target_type} onChange={v => setF(p => ({ ...p, action_free_target_type: v, action_free_target_ids: [] }))}
|
||||||
|
options={FREE_CHOICE_FROM.map(v => ({ value: v, label: t(`pricing.deals.freeFrom.${v}`) }))} />
|
||||||
|
{f.action_free_target_type === 'item' && <PickSeveral items={catalog.products} value={f.action_free_target_ids} onChange={v => set('action_free_target_ids', v)} />}
|
||||||
|
{f.action_free_target_type === 'category' && <PickSeveral items={catalog.categories} value={f.action_free_target_ids} onChange={v => set('action_free_target_ids', v)} />}
|
||||||
|
{f.action_free_target_type === 'tag' && <TagPicker value={f.action_free_target_ids} onChange={v => set('action_free_target_ids', v)} known={catalog.tags} />}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{(a === 'free_item' || a === 'free_choice') && (
|
||||||
|
<Field label={t('pricing.deals.quantity')}>
|
||||||
|
<Input type="number" min={1} step={1} className="w-28" value={f.action_free_quantity}
|
||||||
|
onChange={e => set('action_free_quantity', Number(e.target.value))} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
{a === 'apply_modifier' && (
|
||||||
|
<Field label={t('pricing.deals.rule')} hint={t('pricing.deals.ruleHint')}>
|
||||||
|
<Select value={f.action_modifier_id ?? ''} onChange={e => set('action_modifier_id', e.target.value === '' ? null : Number(e.target.value))}
|
||||||
|
placeholder={manualRules.length ? t('pricing.choose') : t('pricing.deals.noManualRules')} options={manualRules.map(r => ({ value: r.id, label: r.name }))} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
{['set_price', 'add_amount', 'add_percent'].includes(a) && (
|
||||||
|
<Field label={t(`pricing.actions.valueLabel.${a === 'set_price' ? 'set' : a}`)} hint={a !== 'set_price' ? t('pricing.actions.minusHint') : undefined}>
|
||||||
|
<Input type="number" step={a === 'add_percent' ? 1 : 0.1} className="w-36" value={Number.isFinite(f.action_value) ? f.action_value : ''}
|
||||||
|
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{tried && <Missing problems={problems} prefix="pricing.deals.problems" />}
|
||||||
|
</div>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
// Waiter discounts (plan step 6.7): the venue's switch and limits, then each person's.
|
||||||
|
// - Venue: discounts on or off for everyone (off: nobody can give one, not even with a manager's
|
||||||
|
// approval), the most the whole venue gives in a business day, the most given during a waiter's
|
||||||
|
// shift (everyone's discounts since that shift began) and how many items.
|
||||||
|
// - Per person: may give discounts at all, the most per discount (% and amount), and their own
|
||||||
|
// totals per shift / per business day / per order. Both sets apply: the first limit reached stops it.
|
||||||
|
// Past a limit a person with "Give discounts beyond the limits" goes on, others need a manager's
|
||||||
|
// approval on the spot (D-10). An empty box = no limit.
|
||||||
|
import { useState } from 'react'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import { errorMessage } from '@xenia/api'
|
||||||
|
import { useTranslation } from '@xenia/i18n'
|
||||||
|
import { Button, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||||
|
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||||
|
import * as api from './pricingApi'
|
||||||
|
import { TabHead } from './PricingParts'
|
||||||
|
import { COUNT_LIMITS, VENUE_LIMITS, WAITER_LIMITS, limitText, parseLimit } from './pricingLogic'
|
||||||
|
|
||||||
|
const UNIT = { max_discount_percent: '%', max_discount_amount: '€', max_total_value_shift: '€', max_total_value_workday: '€' }
|
||||||
|
|
||||||
|
export default function DiscountsTab() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
return (
|
||||||
|
<section className="grid gap-5" data-testid="pricing-discounts">
|
||||||
|
<TabHead title={t('pricing.discounts.title')} intro={t('pricing.discounts.intro')} />
|
||||||
|
<VenueLimits />
|
||||||
|
<PersonLimits />
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function LimitBoxes({ keys, texts, setText, prefix }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
return (
|
||||||
|
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
|
{keys.map(k => {
|
||||||
|
const bad = !parseLimit(texts[k], COUNT_LIMITS.has(k)).ok
|
||||||
|
return (
|
||||||
|
<Field key={k} label={t(`${prefix}.${k}`)} hint={t(`${prefix}.${k}Hint`)} error={bad ? t('pricing.discounts.badNumber') : undefined}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Input inputMode="decimal" className="w-28" value={texts[k]} placeholder={t('pricing.discounts.noLimit')}
|
||||||
|
onChange={e => setText(k, e.target.value)} data-testid={`limit-${k}`} />
|
||||||
|
<span className="text-label text-ink-2">{UNIT[k] ?? t('pricing.discounts.items')}</span>
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const textsOf = (data, keys) => Object.fromEntries(keys.map(k => [k, limitText(data?.[k])]))
|
||||||
|
|
||||||
|
function VenueLimits() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { data, refetch } = useLiveQuery({ queryKey: ['pricing', 'venue-limits'], queryFn: api.venueLimits, events: api.PRICING_EVENTS })
|
||||||
|
if (!data) return <div className="flex justify-center p-6"><Spinner /></div>
|
||||||
|
return <VenueForm key={JSON.stringify(data)} data={data} onSaved={refetch} t={t} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function VenueForm({ data, onSaved, t }) {
|
||||||
|
const [on, setOn] = useState(data.enabled !== false)
|
||||||
|
const [texts, setTexts] = useState(() => textsOf(data, VENUE_LIMITS))
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const parsed = VENUE_LIMITS.map(k => [k, parseLimit(texts[k], COUNT_LIMITS.has(k))])
|
||||||
|
const ok = parsed.every(([, p]) => p.ok)
|
||||||
|
const save = async () => {
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
await api.saveVenueLimits({ enabled: on, ...Object.fromEntries(parsed.map(([k, p]) => [k, p.value])) })
|
||||||
|
toast.success(t('pricing.saved'))
|
||||||
|
await onSaved()
|
||||||
|
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="grid gap-4 p-5 rounded-card border border-line bg-surface shadow-raised" data-testid="pricing-venue-limits">
|
||||||
|
<header className="grid gap-0.5">
|
||||||
|
<h3 className="text-body font-semibold text-ink">{t('pricing.discounts.venue')}</h3>
|
||||||
|
<p className="text-label text-ink-2">{t('pricing.discounts.venueHint')}</p>
|
||||||
|
</header>
|
||||||
|
<Switch checked={on} onChange={setOn} label={t('pricing.discounts.enabled')} description={t('pricing.discounts.enabledHint')} data-testid="discounts-enabled" />
|
||||||
|
<LimitBoxes keys={VENUE_LIMITS} texts={texts} setText={(k, v) => setTexts(s => ({ ...s, [k]: v }))} prefix="pricing.discounts.venueLimits" />
|
||||||
|
<div className="flex justify-end"><Button loading={busy} disabled={!ok} onClick={save} data-testid="pricing-venue-save">{t('pricing.save')}</Button></div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const personName = p => p.nickname || p.full_name || p.username
|
||||||
|
|
||||||
|
function PersonLimits() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { data: staff } = useLiveQuery({ queryKey: ['staff'], queryFn: api.listStaff })
|
||||||
|
const people = (staff ?? []).filter(p => p.is_active !== false)
|
||||||
|
const [chosen, setChosen] = useState(null)
|
||||||
|
const id = chosen ?? people[0]?.id ?? null
|
||||||
|
const { data } = useLiveQuery({ queryKey: ['pricing', 'person-limits', id], queryFn: () => api.waiterLimits(id), enabled: !!id, events: api.PRICING_EVENTS })
|
||||||
|
return (
|
||||||
|
<div className="grid gap-4 p-5 rounded-card border border-line bg-surface shadow-raised" data-testid="pricing-person-limits">
|
||||||
|
<header className="grid gap-0.5">
|
||||||
|
<h3 className="text-body font-semibold text-ink">{t('pricing.discounts.person')}</h3>
|
||||||
|
<p className="text-label text-ink-2">{t('pricing.discounts.personHint')}</p>
|
||||||
|
</header>
|
||||||
|
{!staff ? <Spinner /> : people.length === 0 ? <EmptyState compact title={t('pricing.discounts.nobody')} /> : (
|
||||||
|
<>
|
||||||
|
<Field label={t('pricing.discounts.who')}>
|
||||||
|
<Select value={id ?? ''} onChange={e => setChosen(Number(e.target.value))} data-testid="pricing-person"
|
||||||
|
options={people.map(p => ({ value: p.id, label: personName(p) }))} />
|
||||||
|
</Field>
|
||||||
|
{!data ? <Spinner /> : <PersonForm key={`${id}:${JSON.stringify(data)}`} id={id} data={data} t={t} />}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PersonForm({ id, data, t }) {
|
||||||
|
const [can, setCan] = useState(!!data.can_apply_discounts)
|
||||||
|
const [texts, setTexts] = useState(() => textsOf(data, WAITER_LIMITS))
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const parsed = WAITER_LIMITS.map(k => [k, parseLimit(texts[k], COUNT_LIMITS.has(k))])
|
||||||
|
const ok = parsed.every(([, p]) => p.ok)
|
||||||
|
const save = async () => {
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
await api.saveWaiterLimits(id, { can_apply_discounts: can, ...Object.fromEntries(parsed.map(([k, p]) => [k, p.value])) })
|
||||||
|
toast.success(t('pricing.saved'))
|
||||||
|
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="grid gap-4">
|
||||||
|
<Switch checked={can} onChange={setCan} label={t('pricing.discounts.can')} description={t('pricing.discounts.canHint')} data-testid="discounts-can" />
|
||||||
|
<LimitBoxes keys={WAITER_LIMITS} texts={texts} setText={(k, v) => setTexts(s => ({ ...s, [k]: v }))} prefix="pricing.discounts.personLimits" />
|
||||||
|
<div className="flex justify-end"><Button loading={busy} disabled={!ok} onClick={save} data-testid="pricing-person-save">{t('pricing.save')}</Button></div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
// Price rules (modifiers, plan step 6.7): change the price of some products while conditions hold,
|
||||||
|
// e.g. "drinks −20% from 17:00 to 19:00". A rule has
|
||||||
|
// - what it changes: one product, or (all products | some products | categories | prep zones |
|
||||||
|
// tags; any of the rows);
|
||||||
|
// - when: conditions, all of which must hold (no condition = always while it's on);
|
||||||
|
// - by how much: ± a percentage (with an optional rounding), ± an amount, or a new price.
|
||||||
|
// The order is the priority: of the rules that don't stack only the first that applies counts;
|
||||||
|
// the stacking ones all apply after it, in order. The server rounds the final price to 0.10.
|
||||||
|
// New prices apply to what is added to orders from then on (the counter, the phones, the tablets).
|
||||||
|
import { useState } from 'react'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import { Layers, Plus } from 'lucide-react'
|
||||||
|
import { errorMessage } from '@xenia/api'
|
||||||
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||||
|
import { Button, Dialog, EmptyState, Field, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||||
|
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||||
|
import * as api from './pricingApi'
|
||||||
|
import { ColourPicker, ConditionList, Missing, RuleCard, Segmented, TabHead, TargetList } from './PricingParts'
|
||||||
|
import { COLOURS, useCatalog } from './useCatalog'
|
||||||
|
import {
|
||||||
|
MODIFIER_ACTIONS, MODIFIER_CONDITIONS, MODIFIER_TARGETS, ROUNDINGS, actionText, examplePrice, modifierBody, modifierForm, modifierProblems, moveItem,
|
||||||
|
} from './pricingLogic'
|
||||||
|
|
||||||
|
const PAGES = ['what', 'when', 'price']
|
||||||
|
|
||||||
|
export default function ModifiersTab() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { formatMoney } = useFormat()
|
||||||
|
const catalog = useCatalog()
|
||||||
|
const { data: rules, refetch } = useLiveQuery({ queryKey: ['pricing', 'modifiers'], queryFn: api.listModifiers, events: api.PRICING_EVENTS })
|
||||||
|
const [editing, setEditing] = useState(null)
|
||||||
|
const [deleting, setDeleting] = useState(null)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
|
const run = async (fn, done) => {
|
||||||
|
setBusy(true)
|
||||||
|
try { await fn(); if (done) toast.success(done); await refetch(); return true } catch (err) { toast.error(errorMessage(err, t)); return false } finally { setBusy(false) }
|
||||||
|
}
|
||||||
|
const productName = id => catalog.products.find(p => p.id === id)?.name ?? '—'
|
||||||
|
const whatText = m => (m.scope === 'item' ? productName(m.item_id)
|
||||||
|
: m.targets?.some(x => x.target_type === 'all') ? t('pricing.rules.allProducts') : t('pricing.rules.someProducts', { count: m.targets?.length ?? 0 }))
|
||||||
|
const whenText = m => (m.conditions?.length ? t('pricing.rules.conditions', { count: m.conditions.length }) : t('pricing.rules.always'))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="grid gap-4" data-testid="pricing-rules">
|
||||||
|
<TabHead title={t('pricing.rules.title')} intro={t('pricing.rules.intro')}
|
||||||
|
action={<Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="pricing-rule-new">{t('pricing.rules.new')}</Button>} />
|
||||||
|
{!rules ? <div className="flex justify-center p-6"><Spinner /></div>
|
||||||
|
: rules.length === 0 ? <EmptyState title={t('pricing.rules.none')} description={t('pricing.rules.noneHint')} />
|
||||||
|
: (
|
||||||
|
<>
|
||||||
|
<p className="text-caption text-ink-3">{t('pricing.rules.orderHint')}</p>
|
||||||
|
<ul className="grid gap-2">
|
||||||
|
{rules.map((m, i) => (
|
||||||
|
<RuleCard key={m.id} testid="pricing-rule" colour={m.color ?? COLOURS[0]} name={m.name} active={m.is_active} busy={busy}
|
||||||
|
description={m.description}
|
||||||
|
badges={<>
|
||||||
|
<span className="px-2 py-0.5 rounded-full bg-accent-soft text-accent-ink text-caption font-semibold tabular-nums" data-testid="pricing-rule-action">{actionText(m.action_type, m.action_value, formatMoney)}</span>
|
||||||
|
{m.allow_stack && <span className="inline-flex items-center gap-1 text-caption text-ink-2"><Layers size={12} aria-hidden="true" />{t('pricing.rules.stacks')}</span>}
|
||||||
|
</>}
|
||||||
|
summary={`${whatText(m)} · ${whenText(m)}`}
|
||||||
|
onUp={i > 0 ? () => run(() => api.reorderModifiers(moveItem(rules, i, i - 1))) : undefined}
|
||||||
|
onDown={i < rules.length - 1 ? () => run(() => api.reorderModifiers(moveItem(rules, i, i + 1))) : undefined}
|
||||||
|
onToggle={() => run(() => api.toggleModifier(m.id))}
|
||||||
|
onEdit={() => setEditing(m)} onDelete={() => setDeleting(m)} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{editing && <RuleDialog rule={editing} catalog={catalog} busy={busy} onClose={() => setEditing(null)}
|
||||||
|
onSave={async body => {
|
||||||
|
if (!editing.id) body.sort_order = rules?.length ?? 0 // a new rule goes last
|
||||||
|
if (await run(() => api.saveModifier(editing.id, body), t('pricing.saved'))) setEditing(null)
|
||||||
|
}} />}
|
||||||
|
{deleting && (
|
||||||
|
<Dialog open size="sm" title={t('pricing.rules.deleteTitle')} onClose={() => setDeleting(null)}
|
||||||
|
footer={<>
|
||||||
|
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('pricing.cancel')}</Button>
|
||||||
|
<Button variant="danger" loading={busy} data-testid="pricing-confirm-delete"
|
||||||
|
onClick={async () => { if (await run(() => api.deleteModifier(deleting.id), t('pricing.deleted'))) setDeleting(null) }}>{t('pricing.delete')}</Button>
|
||||||
|
</>}>
|
||||||
|
<p>{t('pricing.rules.deleteBody', { name: deleting.name })}</p>
|
||||||
|
</Dialog>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function RuleDialog({ rule, catalog, busy, onClose, onSave }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { formatMoney } = useFormat()
|
||||||
|
const [f, setF] = useState(() => modifierForm(rule.id ? rule : null, COLOURS[0]))
|
||||||
|
const [page, setPage] = useState('what')
|
||||||
|
const [tried, setTried] = useState(false)
|
||||||
|
const set = (k, v) => setF(p => ({ ...p, [k]: v }))
|
||||||
|
const problems = modifierProblems(f)
|
||||||
|
const sample = 5
|
||||||
|
return (
|
||||||
|
<Dialog open size="lg" onClose={onClose} title={t(rule.id ? 'pricing.rules.edit' : 'pricing.rules.new')}
|
||||||
|
footer={<>
|
||||||
|
<Button variant="secondary" onClick={onClose}>{t('pricing.cancel')}</Button>
|
||||||
|
<Button loading={busy} data-testid="pricing-save" onClick={() => { setTried(true); if (!problems.length) onSave(modifierBody(f)) }}>{t('pricing.save')}</Button>
|
||||||
|
</>}>
|
||||||
|
<div className="grid gap-4" data-testid="pricing-rule-dialog">
|
||||||
|
<div className="grid sm:grid-cols-2 gap-3">
|
||||||
|
<Field label={t('pricing.name')}><Input value={f.name} autoFocus onChange={e => set('name', e.target.value)} placeholder={t('pricing.rules.namePlaceholder')} data-testid="pricing-name" /></Field>
|
||||||
|
<Field label={t('pricing.description')}><Input value={f.description} onChange={e => set('description', e.target.value)} /></Field>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-1 border-b border-line" role="tablist">
|
||||||
|
{PAGES.map(k => (
|
||||||
|
<button key={k} type="button" role="tab" aria-selected={page === k} onClick={() => setPage(k)} data-testid={`pricing-rule-page-${k}`}
|
||||||
|
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast ${page === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
|
||||||
|
{t(`pricing.rules.pages.${k}`)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{page === 'what' && (
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<Segmented value={f.scope} onChange={v => set('scope', v)} testid="pricing-rule-scope"
|
||||||
|
options={['global', 'item'].map(v => ({ value: v, label: t(`pricing.rules.scopes.${v}`) }))} />
|
||||||
|
{f.scope === 'item' ? (
|
||||||
|
<Field label={t('pricing.rules.product')}>
|
||||||
|
<Select value={f.item_id ?? ''} onChange={e => set('item_id', e.target.value === '' ? null : Number(e.target.value))}
|
||||||
|
placeholder={t('pricing.choose')} options={catalog.products.map(p => ({ value: p.id, label: p.name }))} />
|
||||||
|
</Field>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-caption text-ink-2">{t('pricing.rules.targetsHint')}</p>
|
||||||
|
<TargetList value={f.targets} onChange={v => set('targets', v)} types={MODIFIER_TARGETS} catalog={catalog} testid="pricing-rule-targets" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{page === 'when' && (
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<p className="text-caption text-ink-2">{t('pricing.rules.conditionsHint')}</p>
|
||||||
|
<ConditionList value={f.conditions} onChange={v => set('conditions', v)} types={MODIFIER_CONDITIONS} catalog={catalog} testid="pricing-rule-conditions" />
|
||||||
|
<Switch checked={f.is_active} onChange={v => set('is_active', v)} label={t('pricing.rules.on')} description={t('pricing.rules.onHint')} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{page === 'price' && (
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<Segmented value={f.action_type} onChange={v => set('action_type', v)} testid="pricing-rule-action-type"
|
||||||
|
options={MODIFIER_ACTIONS.map(v => ({ value: v, label: t(`pricing.actions.${v}`) }))} />
|
||||||
|
<div className="grid sm:grid-cols-2 gap-3">
|
||||||
|
<Field label={t(`pricing.actions.valueLabel.${f.action_type}`)} hint={f.action_type !== 'set' ? t('pricing.actions.minusHint') : undefined}>
|
||||||
|
<Input type="number" step={f.action_type === 'add_percent' ? 1 : 0.1} value={Number.isFinite(f.action_value) ? f.action_value : ''}
|
||||||
|
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} data-testid="pricing-rule-value" />
|
||||||
|
</Field>
|
||||||
|
{f.action_type === 'add_percent' && (
|
||||||
|
<Field label={t('pricing.rules.rounding')}>
|
||||||
|
<Select value={f.round_to} onChange={e => set('round_to', e.target.value)}
|
||||||
|
options={ROUNDINGS.map(v => ({ value: v, label: t(`pricing.roundings.${v ? v.replace('.', '_') : 'none'}`) }))} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{Number.isFinite(f.action_value) && (
|
||||||
|
<p className="text-label text-ink-2" data-testid="pricing-rule-example">
|
||||||
|
{t('pricing.rules.example', { before: formatMoney(sample), after: formatMoney(examplePrice(sample, f.action_type, f.action_value, f.round_to)) })}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Switch checked={f.allow_stack} onChange={v => set('allow_stack', v)} label={t('pricing.rules.stack')} />
|
||||||
|
<InfoTip>{t('pricing.rules.stackTip')}</InfoTip>
|
||||||
|
</div>
|
||||||
|
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{tried && <Missing problems={problems} prefix="pricing.rules.problems" />}
|
||||||
|
</div>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// Price groups (plan step 6.7): named switches like "Happy hour" or "Summer", on by hand or by a
|
||||||
|
// weekly schedule (from–to on some days, in the venue's time). A price rule or a deal can have the
|
||||||
|
// condition "a price group is on", so several rules follow one switch.
|
||||||
|
import { useState } from 'react'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import { Clock, Plus } from 'lucide-react'
|
||||||
|
import { errorMessage } from '@xenia/api'
|
||||||
|
import { useTranslation } from '@xenia/i18n'
|
||||||
|
import { Button, Dialog, EmptyState, Field, Input, Spinner, Switch } from '@xenia/ui'
|
||||||
|
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||||
|
import * as api from './pricingApi'
|
||||||
|
import { ColourPicker, DayPicker, Missing, RuleCard, TabHead } from './PricingParts'
|
||||||
|
import { COLOURS } from './useCatalog'
|
||||||
|
import { groupBody, groupForm, groupProblems, groupSchedule } from './pricingLogic'
|
||||||
|
|
||||||
|
export default function PriceGroupsTab() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { data: groups, refetch } = useLiveQuery({ queryKey: ['pricing', 'groups'], queryFn: api.listGroups, events: api.PRICING_EVENTS })
|
||||||
|
const [editing, setEditing] = useState(null) // a group, or {} for a new one
|
||||||
|
const [deleting, setDeleting] = useState(null)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
|
const run = async (fn, done) => {
|
||||||
|
setBusy(true)
|
||||||
|
try { await fn(); if (done) toast.success(done); await refetch(); return true } catch (err) { toast.error(errorMessage(err, t)); return false } finally { setBusy(false) }
|
||||||
|
}
|
||||||
|
const days = g => groupSchedule(g)?.days.map(d => t(`signage.weekdays.${d}`)).join(' ')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="grid gap-4" data-testid="pricing-groups">
|
||||||
|
<TabHead title={t('pricing.groups.title')} intro={t('pricing.groups.intro')}
|
||||||
|
action={<Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="pricing-group-new">{t('pricing.groups.new')}</Button>} />
|
||||||
|
{!groups ? <div className="flex justify-center p-6"><Spinner /></div>
|
||||||
|
: groups.length === 0 ? <EmptyState title={t('pricing.groups.none')} description={t('pricing.groups.noneHint')} />
|
||||||
|
: (
|
||||||
|
<ul className="grid gap-2">
|
||||||
|
{groups.map(g => {
|
||||||
|
const s = groupSchedule(g)
|
||||||
|
return (
|
||||||
|
<RuleCard key={g.id} testid="pricing-group" colour={g.color ?? COLOURS[0]} name={g.name} active={g.is_active} busy={busy}
|
||||||
|
description={g.description}
|
||||||
|
summary={s ? <span className="inline-flex items-center gap-1"><Clock size={12} aria-hidden="true" />{t('pricing.groups.scheduled', { from: s.from, to: s.to, days: days(g) })}</span> : t('pricing.groups.byHand')}
|
||||||
|
onToggle={() => run(() => api.toggleGroup(g.id))}
|
||||||
|
onEdit={() => setEditing(g)} onDelete={() => setDeleting(g)} />
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{editing && <GroupDialog group={editing} busy={busy} onClose={() => setEditing(null)}
|
||||||
|
onSave={async body => { if (await run(() => api.saveGroup(editing.id, body), t('pricing.saved'))) setEditing(null) }} />}
|
||||||
|
{deleting && (
|
||||||
|
<Dialog open size="sm" title={t('pricing.groups.deleteTitle')} onClose={() => setDeleting(null)}
|
||||||
|
footer={<>
|
||||||
|
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('pricing.cancel')}</Button>
|
||||||
|
<Button variant="danger" loading={busy} data-testid="pricing-confirm-delete"
|
||||||
|
onClick={async () => { if (await run(() => api.deleteGroup(deleting.id), t('pricing.deleted'))) setDeleting(null) }}>{t('pricing.delete')}</Button>
|
||||||
|
</>}>
|
||||||
|
<p>{t('pricing.groups.deleteBody', { name: deleting.name })}</p>
|
||||||
|
</Dialog>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function GroupDialog({ group, busy, onClose, onSave }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const [f, setF] = useState(() => groupForm(group.id ? group : null, COLOURS[0]))
|
||||||
|
const set = (k, v) => setF(p => ({ ...p, [k]: v }))
|
||||||
|
const problems = groupProblems(f)
|
||||||
|
const [tried, setTried] = useState(false)
|
||||||
|
return (
|
||||||
|
<Dialog open size="md" onClose={onClose} title={t(group.id ? 'pricing.groups.edit' : 'pricing.groups.new')}
|
||||||
|
footer={<>
|
||||||
|
<Button variant="secondary" onClick={onClose}>{t('pricing.cancel')}</Button>
|
||||||
|
<Button loading={busy} data-testid="pricing-save" onClick={() => { setTried(true); if (!problems.length) onSave(groupBody(f)) }}>{t('pricing.save')}</Button>
|
||||||
|
</>}>
|
||||||
|
<div className="grid gap-4" data-testid="pricing-group-dialog">
|
||||||
|
<Field label={t('pricing.name')}><Input value={f.name} autoFocus onChange={e => set('name', e.target.value)} placeholder={t('pricing.groups.namePlaceholder')} data-testid="pricing-name" /></Field>
|
||||||
|
<Field label={t('pricing.description')}><Input value={f.description} onChange={e => set('description', e.target.value)} /></Field>
|
||||||
|
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
|
||||||
|
<Switch checked={f.is_active} onChange={v => set('is_active', v)} label={t('pricing.groups.onNow')} description={t('pricing.groups.onNowHint')} />
|
||||||
|
<fieldset className="grid gap-3 p-3 rounded-control border border-line">
|
||||||
|
<legend className="px-1 text-label font-semibold text-ink">{t('pricing.groups.schedule')}</legend>
|
||||||
|
<p className="text-caption text-ink-2">{t('pricing.groups.scheduleHint')}</p>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<Field label={t('pricing.condition.from')}><Input type="time" value={f.auto_enable_time} onChange={e => set('auto_enable_time', e.target.value)} /></Field>
|
||||||
|
<Field label={t('pricing.condition.to')}><Input type="time" value={f.auto_disable_time} onChange={e => set('auto_disable_time', e.target.value)} /></Field>
|
||||||
|
</div>
|
||||||
|
<DayPicker value={f.auto_days} onChange={v => set('auto_days', v)} />
|
||||||
|
</fieldset>
|
||||||
|
{tried && <Missing problems={problems} prefix="pricing.groups.problems" />}
|
||||||
|
</div>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
// Management → Pricing (plan step 6.7): price rules, price groups, deals and the waiters' discount
|
||||||
|
// limits, one tab each. Changes reach the counter, the phones and the tablets at once: new prices
|
||||||
|
// apply to what is added to orders from then on (lines already on an order keep their price).
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useTranslation } from '@xenia/i18n'
|
||||||
|
import DealsTab from './DealsTab'
|
||||||
|
import DiscountsTab from './DiscountsTab'
|
||||||
|
import ModifiersTab from './ModifiersTab'
|
||||||
|
import PriceGroupsTab from './PriceGroupsTab'
|
||||||
|
|
||||||
|
const TABS = ['rules', 'groups', 'deals', 'discounts']
|
||||||
|
|
||||||
|
export default function PricingPage() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const [tab, setTab] = useState('rules')
|
||||||
|
return (
|
||||||
|
<div className="p-4 md:p-6 grid gap-5 max-w-5xl content-start" data-testid="pricing-page">
|
||||||
|
<header className="grid gap-1">
|
||||||
|
<h1 className="text-heading font-semibold text-ink">{t('pricing.pageTitle')}</h1>
|
||||||
|
<p className="text-body text-ink-2 max-w-3xl">{t('pricing.intro')}</p>
|
||||||
|
</header>
|
||||||
|
<div className="flex flex-wrap gap-1 border-b border-line" role="tablist" aria-label={t('pricing.pageTitle')}>
|
||||||
|
{TABS.map(k => (
|
||||||
|
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`pricing-tab-${k}`}
|
||||||
|
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast
|
||||||
|
${tab === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
|
||||||
|
{t(`pricing.tabs.${k}`)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{tab === 'rules' && <ModifiersTab />}
|
||||||
|
{tab === 'groups' && <PriceGroupsTab />}
|
||||||
|
{tab === 'deals' && <DealsTab />}
|
||||||
|
{tab === 'discounts' && <DiscountsTab />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
// Pieces the pricing tabs share (plan step 6.7): the colour and day pickers, the condition list (AND) and the target list (OR), a searchable
|
||||||
|
// pick-several list, a tag picker, and the card a rule, a deal or a group shows as.
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { ArrowDown, ArrowUp, Check, Pencil, Plus, Power, Trash2, X } from 'lucide-react'
|
||||||
|
import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access'
|
||||||
|
import { latin, useFormat, useTranslation } from '@xenia/i18n'
|
||||||
|
import { Button, IconButton, Input, Select, cx } from '@xenia/ui'
|
||||||
|
import { COLOURS } from './useCatalog'
|
||||||
|
import { OLD_PLACEHOLDERS, WEEKDAYS, blankCondition, conditionComplete, toggleIn } from './pricingLogic'
|
||||||
|
|
||||||
|
export function ColourPicker({ value, onChange, label }) {
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<span className="text-label font-semibold text-ink">{label}</span>
|
||||||
|
<div className="flex flex-wrap gap-2" role="radiogroup" aria-label={label}>
|
||||||
|
{COLOURS.map(c => (
|
||||||
|
<button key={c} type="button" role="radio" aria-checked={value === c} aria-label={c} onClick={() => onChange(c)}
|
||||||
|
className={cx('w-8 h-8 rounded-full grid place-items-center text-accent-fg ring-offset-2 ring-offset-surface', value === c && 'ring-2 ring-[var(--x-ink)]')}
|
||||||
|
style={{ background: c }}>
|
||||||
|
{value === c && <Check size={14} />}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DayPicker({ value = [], onChange, testid }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap gap-1.5" data-testid={testid}>
|
||||||
|
{WEEKDAYS.map(d => (
|
||||||
|
<button key={d} type="button" aria-pressed={value.includes(d)} onClick={() => onChange(toggleIn(value, d).sort())}
|
||||||
|
className={cx('px-3 py-1.5 rounded-control border text-label font-medium transition-colors duration-fast',
|
||||||
|
value.includes(d) ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
|
||||||
|
{t(`signage.weekdays.${d}`)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Chips to pick several values (sales points, days…). */
|
||||||
|
export function Chips({ options, value, onChange, testid }) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap gap-1.5" data-testid={testid}>
|
||||||
|
{options.map(o => (
|
||||||
|
<button key={o.value} type="button" aria-pressed={value.includes(o.value)} onClick={() => onChange(toggleIn(value, o.value))}
|
||||||
|
className={cx('px-3 py-1.5 rounded-control border text-label font-medium transition-colors duration-fast',
|
||||||
|
value.includes(o.value) ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
|
||||||
|
{o.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One of a few choices as buttons (scope, action…). */
|
||||||
|
export function Segmented({ options, value, onChange, testid }) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap gap-2" role="radiogroup" data-testid={testid}>
|
||||||
|
{options.map(o => (
|
||||||
|
<button key={o.value} type="button" role="radio" aria-checked={value === o.value} onClick={() => onChange(o.value)} data-value={o.value}
|
||||||
|
className={cx('flex-1 min-w-[8rem] px-3 py-2 rounded-control border text-label font-medium text-center transition-colors duration-fast',
|
||||||
|
value === o.value ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
|
||||||
|
{o.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A searchable list to pick several (products, categories, zones). */
|
||||||
|
export function PickSeveral({ items, value, onChange, testid }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const [q, setQ] = useState('')
|
||||||
|
const fold = v => latin(String(v)).toLowerCase()
|
||||||
|
const shown = q.trim() ? items.filter(i => fold(i.plain ?? i.name).includes(fold(q.trim()))) : items
|
||||||
|
const chosen = items.filter(i => value.includes(i.id))
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2" data-testid={testid}>
|
||||||
|
{chosen.length > 0 && (
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{chosen.map(i => (
|
||||||
|
<span key={i.id} className="inline-flex items-center gap-1 pl-2.5 pr-1 py-0.5 rounded-full bg-accent-soft text-accent-ink text-label">
|
||||||
|
{i.plain ?? i.name}
|
||||||
|
<button type="button" aria-label={t('pricing.remove')} onClick={() => onChange(value.filter(v => v !== i.id))} className="p-0.5 rounded-full hover:bg-surface"><X size={12} /></button>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{items.length > 8 && <Input size="sm" value={q} onChange={e => setQ(e.target.value)} placeholder={t('pricing.search')} aria-label={t('pricing.search')} />}
|
||||||
|
<ul className="max-h-48 overflow-y-auto rounded-control border border-line divide-y divide-line bg-surface">
|
||||||
|
{shown.length === 0 && <li className="px-3 py-2 text-label text-ink-3">{t('pricing.nothingFound')}</li>}
|
||||||
|
{shown.map(i => {
|
||||||
|
const on = value.includes(i.id)
|
||||||
|
return (
|
||||||
|
<li key={i.id}>
|
||||||
|
<button type="button" role="checkbox" aria-checked={on} onClick={() => onChange(toggleIn(value, i.id))} data-name={i.plain ?? i.name}
|
||||||
|
className={cx('w-full flex items-center gap-2.5 px-3 py-1.5 text-left text-label', on ? 'bg-accent-soft text-accent-ink' : 'text-ink hover:bg-surface-2')}>
|
||||||
|
<span className={cx('w-4 h-4 rounded border grid place-items-center shrink-0', on ? 'bg-accent border-accent text-accent-fg' : 'border-line-strong bg-surface')}>
|
||||||
|
{on && <Check size={12} />}
|
||||||
|
</span>
|
||||||
|
<span className="truncate">{i.name}</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TagPicker({ value, onChange, known }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const [draft, setDraft] = useState('')
|
||||||
|
const add = () => { const v = draft.trim(); if (v && !value.includes(v)) onChange([...value, v]); setDraft('') }
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2">
|
||||||
|
{known.length > 0 && <Chips options={known.map(k => ({ value: k, label: k }))} value={value} onChange={onChange} />}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input size="sm" value={draft} onChange={e => setDraft(e.target.value)} placeholder={t('pricing.newTag')} aria-label={t('pricing.newTag')}
|
||||||
|
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); add() } }} />
|
||||||
|
<Button size="sm" variant="secondary" onClick={add} disabled={!draft.trim()}>{t('pricing.add')}</Button>
|
||||||
|
</div>
|
||||||
|
{value.filter(v => !known.includes(v)).length > 0 && (
|
||||||
|
<Chips options={value.filter(v => !known.includes(v)).map(k => ({ value: k, label: k }))} value={value} onChange={onChange} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The products a rule or a deal looks at: any one of the rows (OR). */
|
||||||
|
export function TargetList({ value, onChange, types, catalog, testid }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const set = (i, v) => onChange(value.map((x, j) => (j === i ? v : x)))
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2" data-testid={testid}>
|
||||||
|
{value.map((tg, i) => (
|
||||||
|
<div key={i} className="grid gap-2 p-3 rounded-control border border-line bg-surface-2" data-testid="pricing-target">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Select size="sm" className="flex-1" value={tg.target_type} aria-label={t('pricing.target.type')}
|
||||||
|
onChange={e => set(i, { target_type: e.target.value, target_ids: [], target_tags: [] })}
|
||||||
|
options={types.map(v => ({ value: v, label: t(`pricing.target.types.${v}`) }))} />
|
||||||
|
{value.length > 1 && <IconButton size="sm" variant="ghost" label={t('pricing.remove')} onClick={() => onChange(value.filter((_, j) => j !== i))}><X size={14} /></IconButton>}
|
||||||
|
</div>
|
||||||
|
{tg.target_type === 'item' && <PickSeveral items={catalog.products} value={tg.target_ids} onChange={v => set(i, { ...tg, target_ids: v })} testid="pricing-target-products" />}
|
||||||
|
{tg.target_type === 'category' && <PickSeveral items={catalog.categories} value={tg.target_ids} onChange={v => set(i, { ...tg, target_ids: v })} testid="pricing-target-categories" />}
|
||||||
|
{tg.target_type === 'prep_zone' && <PickSeveral items={catalog.zones} value={tg.target_ids} onChange={v => set(i, { ...tg, target_ids: v })} />}
|
||||||
|
{tg.target_type === 'tag' && <TagPicker value={tg.target_tags} onChange={v => set(i, { ...tg, target_tags: v })} known={catalog.tags} />}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div><Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => onChange([...value, { target_type: types[0], target_ids: [], target_tags: [] }])}>{t('pricing.target.add')}</Button></div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The conditions: all of them must hold (AND). */
|
||||||
|
export function ConditionList({ value, onChange, types, catalog, testid }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const set = (i, v) => onChange(value.map((x, j) => (j === i ? v : x)))
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2" data-testid={testid}>
|
||||||
|
{value.map((c, i) => (
|
||||||
|
<div key={i} className={cx('grid gap-2 p-3 rounded-control border bg-surface-2', conditionComplete(c) ? 'border-line' : 'border-warning')} data-testid="pricing-condition">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{OLD_PLACEHOLDERS.includes(c.condition_type)
|
||||||
|
? <span className="flex-1 text-label text-ink-2">{t('pricing.condition.placeholder')}</span>
|
||||||
|
: <Select size="sm" className="flex-1" value={c.condition_type} aria-label={t('pricing.condition.type')}
|
||||||
|
onChange={e => set(i, blankCondition(e.target.value))}
|
||||||
|
options={types.map(v => ({ value: v, label: t(`pricing.condition.types.${v}`) }))} />}
|
||||||
|
<IconButton size="sm" variant="ghost" label={t('pricing.remove')} onClick={() => onChange(value.filter((_, j) => j !== i))}><X size={14} /></IconButton>
|
||||||
|
</div>
|
||||||
|
<ConditionFields cond={c} onChange={v => set(i, v)} catalog={catalog} />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div><Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => onChange([...value, blankCondition(types[0])])} data-testid="pricing-condition-add">{t('pricing.condition.add')}</Button></div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConditionFields({ cond, onChange, catalog }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { t: tc } = useTranslation('common')
|
||||||
|
const p = cond.params ?? {}
|
||||||
|
const set = (k, v) => onChange({ ...cond, params: { ...p, [k]: v } })
|
||||||
|
const num = (k, low, step) => (
|
||||||
|
<Input size="sm" type="number" min={low} step={step} className="w-32" value={p[k] ?? ''} aria-label={t(`pricing.condition.fields.${k === 'min' ? cond.condition_type : k}`)}
|
||||||
|
onChange={e => set(k, e.target.value === '' ? null : Number(e.target.value))} />
|
||||||
|
)
|
||||||
|
const pair = (type, a, b) => (
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<label className="grid gap-1 text-caption text-ink-2">{t('pricing.condition.from')}
|
||||||
|
<Input size="sm" type={type} value={p[a] ?? ''} onChange={e => set(a, e.target.value)} data-testid={`pricing-cond-${a}`} /></label>
|
||||||
|
<label className="grid gap-1 text-caption text-ink-2">{t('pricing.condition.to')}
|
||||||
|
<Input size="sm" type={type} value={p[b] ?? ''} onChange={e => set(b, e.target.value)} data-testid={`pricing-cond-${b}`} /></label>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
switch (cond.condition_type) {
|
||||||
|
case 'time_range': return <>{pair('time', 'from', 'to')}<p className="text-caption text-ink-3">{t('pricing.condition.timeHint')}</p></>
|
||||||
|
case 'date_range': return pair('date', 'from', 'to')
|
||||||
|
case 'specific_date': return <DateList value={p.dates ?? []} onChange={v => set('dates', v)} />
|
||||||
|
case 'day_of_week': return <DayPicker value={p.days ?? []} onChange={v => set('days', v)} />
|
||||||
|
case 'min_item_quantity': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 1, 1)}{t('pricing.condition.ofTheDish')}</label>
|
||||||
|
case 'min_order_value': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 0, 0.5)}{t('pricing.condition.orderTotal')}</label>
|
||||||
|
case 'min_category_qty': return (
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{num('min', 1, 1)}
|
||||||
|
<span className="text-label text-ink-2">{t('pricing.condition.fromCategory')}</span>
|
||||||
|
<Select size="sm" className="flex-1 min-w-[10rem]" value={p.category_id ?? ''} aria-label={t('pricing.condition.fields.category_id')}
|
||||||
|
onChange={e => set('category_id', e.target.value === '' ? null : Number(e.target.value))}
|
||||||
|
placeholder={t('pricing.choose')} options={catalog.categories.map(c => ({ value: c.id, label: c.name }))} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
case 'order_channel': return <Chips options={SALES_POINTS.map(s => ({ value: s, label: tc(`salesPoints.${s}.name`) }))}
|
||||||
|
value={normalizeSalesPoints(p.channels)} onChange={v => set('channels', v)} />
|
||||||
|
case 'price_group_active': return (
|
||||||
|
<Select size="sm" value={p.price_group_id ?? ''} aria-label={t('pricing.condition.fields.price_group_id')}
|
||||||
|
onChange={e => set('price_group_id', e.target.value === '' ? null : Number(e.target.value))}
|
||||||
|
placeholder={catalog.groups.length ? t('pricing.choose') : t('pricing.condition.noGroups')}
|
||||||
|
options={catalog.groups.map(g => ({ value: g.id, label: g.name }))} />
|
||||||
|
)
|
||||||
|
default: return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function DateList({ value, onChange }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { formatDate } = useFormat()
|
||||||
|
const [draft, setDraft] = useState('')
|
||||||
|
return (
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input size="sm" type="date" value={draft} onChange={e => setDraft(e.target.value)} aria-label={t('pricing.condition.date')} />
|
||||||
|
<Button size="sm" variant="secondary" disabled={!draft || value.includes(draft)} onClick={() => { onChange([...value, draft].sort()); setDraft('') }}>{t('pricing.add')}</Button>
|
||||||
|
</div>
|
||||||
|
{value.length > 0 && <Chips options={value.map(d => ({ value: d, label: formatDate(d) }))} value={value} onChange={onChange} />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A rule's, a deal's or a group's row: colour, name, badges, a summary, and its buttons. */
|
||||||
|
export function RuleCard({ colour, name, active, badges, summary, description, onToggle, onEdit, onDelete, onUp, onDown, testid, busy }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
return (
|
||||||
|
<li className={cx('flex items-center gap-3 p-3 rounded-card border bg-surface shadow-raised transition-opacity', active ? 'border-line' : 'border-line opacity-60')}
|
||||||
|
data-testid={testid} data-name={name} data-active={active ? 'true' : 'false'}>
|
||||||
|
<span className="w-1.5 self-stretch rounded-full shrink-0" style={{ background: colour }} aria-hidden="true" />
|
||||||
|
<div className="flex-1 min-w-0 grid gap-0.5">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<span className="text-body font-semibold text-ink truncate">{name}</span>
|
||||||
|
<span className={cx('px-2 py-0.5 rounded-full text-caption font-medium', active ? 'bg-success-soft text-success-ink' : 'bg-surface-2 text-ink-2')}>
|
||||||
|
{active ? t('pricing.on') : t('pricing.off')}
|
||||||
|
</span>
|
||||||
|
{badges}
|
||||||
|
</div>
|
||||||
|
{description && <p className="text-label text-ink-2 truncate">{description}</p>}
|
||||||
|
{summary && <p className="text-caption text-ink-3">{summary}</p>}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-0.5 shrink-0">
|
||||||
|
{onUp && <IconButton size="sm" variant="ghost" label={t('pricing.up')} onClick={onUp} disabled={busy}><ArrowUp size={16} /></IconButton>}
|
||||||
|
{onDown && <IconButton size="sm" variant="ghost" label={t('pricing.down')} onClick={onDown} disabled={busy}><ArrowDown size={16} /></IconButton>}
|
||||||
|
<IconButton size="sm" variant="ghost" label={active ? t('pricing.turnOff') : t('pricing.turnOn')} onClick={onToggle} disabled={busy} data-testid="pricing-toggle"><Power size={16} /></IconButton>
|
||||||
|
<IconButton size="sm" variant="ghost" label={t('pricing.edit')} onClick={onEdit} data-testid="pricing-edit"><Pencil size={16} /></IconButton>
|
||||||
|
<IconButton size="sm" variant="ghost" label={t('pricing.delete')} onClick={onDelete} data-testid="pricing-delete"><Trash2 size={16} /></IconButton>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The tab's head: what it is, and its "New" button. */
|
||||||
|
export function TabHead({ title, intro, action }) {
|
||||||
|
return (
|
||||||
|
<header className="flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div className="grid gap-1 max-w-3xl">
|
||||||
|
<h2 className="text-body-lg font-semibold text-ink">{title}</h2>
|
||||||
|
<p className="text-label text-ink-2">{intro}</p>
|
||||||
|
</div>
|
||||||
|
{action}
|
||||||
|
</header>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Fill in: …" under a dialog when something is missing. */
|
||||||
|
export function Missing({ problems, prefix }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
if (!problems.length) return null
|
||||||
|
return <p className="p-3 rounded-control bg-warning-soft text-warning-ink text-label" role="note" data-testid="pricing-missing">
|
||||||
|
{t('pricing.missing', { list: problems.map(p => t(`${prefix}.${p}`)).join(', ') })}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// The pricing page's server calls (plan step 6.7). Backend: routers/pricing.py (/api/pricing),
|
||||||
|
// every change needs pricing.manage and sends the live event `pricing.changed`.
|
||||||
|
import client from '../../api/client'
|
||||||
|
|
||||||
|
const data = r => r.data
|
||||||
|
|
||||||
|
export const PRICING_EVENTS = ['pricing.changed']
|
||||||
|
|
||||||
|
export const listGroups = () => client.get('/api/pricing/groups').then(data)
|
||||||
|
export const saveGroup = (id, body) => (id ? client.put(`/api/pricing/groups/${id}`, body) : client.post('/api/pricing/groups', body)).then(data)
|
||||||
|
export const toggleGroup = id => client.patch(`/api/pricing/groups/${id}/toggle`).then(data)
|
||||||
|
export const deleteGroup = id => client.delete(`/api/pricing/groups/${id}`)
|
||||||
|
|
||||||
|
export const listModifiers = () => client.get('/api/pricing/modifiers').then(data)
|
||||||
|
export const saveModifier = (id, body) => (id ? client.put(`/api/pricing/modifiers/${id}`, body) : client.post('/api/pricing/modifiers', body)).then(data)
|
||||||
|
export const toggleModifier = id => client.patch(`/api/pricing/modifiers/${id}/toggle`).then(data)
|
||||||
|
export const deleteModifier = id => client.delete(`/api/pricing/modifiers/${id}`)
|
||||||
|
export const reorderModifiers = list => client.patch('/api/pricing/modifiers/reorder', { items: list.map((m, i) => ({ id: m.id, sort_order: i })) })
|
||||||
|
|
||||||
|
export const listDeals = () => client.get('/api/pricing/deals').then(data)
|
||||||
|
export const saveDeal = (id, body) => (id ? client.put(`/api/pricing/deals/${id}`, body) : client.post('/api/pricing/deals', body)).then(data)
|
||||||
|
export const toggleDeal = id => client.patch(`/api/pricing/deals/${id}/toggle`).then(data)
|
||||||
|
export const deleteDeal = id => client.delete(`/api/pricing/deals/${id}`)
|
||||||
|
|
||||||
|
export const venueLimits = () => client.get('/api/pricing/discount-settings/global').then(data)
|
||||||
|
export const saveVenueLimits = body => client.put('/api/pricing/discount-settings/global', body).then(data)
|
||||||
|
export const waiterLimits = id => client.get(`/api/pricing/discount-settings/${id}`).then(data)
|
||||||
|
export const saveWaiterLimits = (id, body) => client.put(`/api/pricing/discount-settings/${id}`, body).then(data)
|
||||||
|
export const listStaff = () => client.get('/api/waiters/').then(data)
|
||||||
|
|
||||||
|
// what the rules can point at
|
||||||
|
export const listProducts = () => client.get('/api/products/', { params: { all: true } }).then(data)
|
||||||
|
export const listCategories = () => client.get('/api/products/categories').then(data)
|
||||||
|
export const listPrepZones = () => client.get('/api/prep-zones').then(data)
|
||||||
|
export const listTags = () => client.get('/api/products/tags').then(data)
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
// The pricing page's rules as plain data (plan step 6.7): the forms of a price group, a price rule
|
||||||
|
// (modifier) and a deal, what they send to the server, what's missing before they can be saved,
|
||||||
|
// and their one-line summaries. Tested in tests/pricing-logic.test.mjs.
|
||||||
|
// The server's engine: local_backend/services/pricing.py (conditions AND-ed, targets OR-ed).
|
||||||
|
|
||||||
|
export const WEEKDAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0, as the server counts
|
||||||
|
|
||||||
|
// conditions a rule can have; the deals take fewer
|
||||||
|
export const MODIFIER_CONDITIONS = ['time_range', 'day_of_week', 'date_range', 'specific_date', 'price_group_active',
|
||||||
|
'order_channel', 'min_item_quantity', 'min_category_qty', 'min_order_value']
|
||||||
|
export const DEAL_CONDITIONS = ['min_item_quantity', 'min_order_value', 'time_range', 'day_of_week', 'date_range',
|
||||||
|
'order_channel', 'price_group_active']
|
||||||
|
export const OLD_PLACEHOLDERS = ['user_tier', 'low_stock'] // never did anything; shown, not offered
|
||||||
|
|
||||||
|
export const MODIFIER_TARGETS = ['all', 'item', 'category', 'prep_zone', 'tag']
|
||||||
|
export const DEAL_TARGETS = ['any', 'item', 'category', 'tag']
|
||||||
|
export const MODIFIER_ACTIONS = ['add_percent', 'add_amount', 'set']
|
||||||
|
export const DEAL_ACTIONS = ['free_item', 'free_choice', 'apply_modifier', 'set_price', 'add_amount', 'add_percent']
|
||||||
|
export const ROUNDINGS = ['', '0.05', '0.10', '0.20', '0.50', 'x.99', 'x.00']
|
||||||
|
export const FREE_CHOICE_FROM = ['item', 'category', 'tag']
|
||||||
|
|
||||||
|
/** A condition of a type with its starting values. */
|
||||||
|
export function blankCondition(type) {
|
||||||
|
switch (type) {
|
||||||
|
case 'time_range': return { condition_type: type, params: { from: '17:00', to: '19:00' } }
|
||||||
|
case 'date_range': return { condition_type: type, params: { from: '', to: '' } }
|
||||||
|
case 'specific_date': return { condition_type: type, params: { dates: [] } }
|
||||||
|
case 'day_of_week': return { condition_type: type, params: { days: [] } }
|
||||||
|
case 'min_item_quantity': return { condition_type: type, params: { min: 2 } }
|
||||||
|
case 'min_category_qty': return { condition_type: type, params: { category_id: null, min: 2 } }
|
||||||
|
case 'min_order_value': return { condition_type: type, params: { min: 20 } }
|
||||||
|
case 'order_channel': return { condition_type: type, params: { channels: [] } }
|
||||||
|
case 'price_group_active': return { condition_type: type, params: { price_group_id: null } }
|
||||||
|
default: return { condition_type: type, params: {} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/
|
||||||
|
const DAY = /^\d{4}-\d{2}-\d{2}$/
|
||||||
|
const positive = (v, low) => typeof v === 'number' && Number.isFinite(v) && v >= low
|
||||||
|
|
||||||
|
/** Whether a condition is complete (the server refuses an incomplete one: pricing.bad_condition). */
|
||||||
|
export function conditionComplete({ condition_type: type, params: p = {} }) {
|
||||||
|
switch (type) {
|
||||||
|
case 'time_range': return HHMM.test(p.from ?? '') && HHMM.test(p.to ?? '') && p.from !== p.to
|
||||||
|
case 'date_range': return DAY.test(p.from ?? '') && DAY.test(p.to ?? '') && p.from <= p.to
|
||||||
|
case 'specific_date': return (p.dates ?? []).length > 0 && p.dates.every(d => DAY.test(d))
|
||||||
|
case 'day_of_week': return (p.days ?? []).length > 0
|
||||||
|
case 'min_item_quantity': return positive(p.min ?? 1, 1)
|
||||||
|
case 'min_category_qty': return Number.isInteger(p.category_id) && positive(p.min ?? 1, 1)
|
||||||
|
case 'min_order_value': return positive(p.min ?? 0, 0)
|
||||||
|
case 'order_channel': return (p.channels ?? []).length > 0
|
||||||
|
case 'price_group_active': return Number.isInteger(p.price_group_id)
|
||||||
|
default: return OLD_PLACEHOLDERS.includes(type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const toggleIn = (list, v) => (list.includes(v) ? list.filter(x => x !== v) : [...list, v])
|
||||||
|
|
||||||
|
/** Move an item of a list from one place to another (drag, or the arrows). */
|
||||||
|
export function moveItem(list, from, to) {
|
||||||
|
if (from === to || from < 0 || to < 0 || from >= list.length || to >= list.length) return list
|
||||||
|
const out = [...list]
|
||||||
|
const [x] = out.splice(from, 1)
|
||||||
|
out.splice(to, 0, x)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── price groups ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const blankGroup = colour => ({ name: '', description: '', color: colour, is_active: false,
|
||||||
|
auto_enable_time: '', auto_disable_time: '', auto_days: [] })
|
||||||
|
|
||||||
|
export const groupForm = (g, colour) => (g ? { ...blankGroup(colour), ...g, description: g.description ?? '',
|
||||||
|
auto_enable_time: g.auto_enable_time ?? '', auto_disable_time: g.auto_disable_time ?? '', auto_days: g.auto_days ?? [] } : blankGroup(colour))
|
||||||
|
|
||||||
|
/** A schedule is all three (from, to, a day) or nothing. */
|
||||||
|
export function groupProblems(f) {
|
||||||
|
const out = []
|
||||||
|
if (!f.name.trim()) out.push('name')
|
||||||
|
const parts = [f.auto_enable_time, f.auto_disable_time, f.auto_days.length ? 'x' : ''].filter(Boolean).length
|
||||||
|
if (parts && (parts < 3 || !HHMM.test(f.auto_enable_time) || !HHMM.test(f.auto_disable_time) || f.auto_enable_time === f.auto_disable_time)) out.push('schedule')
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupBody(f) {
|
||||||
|
const scheduled = f.auto_enable_time && f.auto_disable_time && f.auto_days.length
|
||||||
|
return { name: f.name.trim(), description: f.description.trim() || null, color: f.color, is_active: !!f.is_active,
|
||||||
|
auto_enable_time: scheduled ? f.auto_enable_time : null, auto_disable_time: scheduled ? f.auto_disable_time : null,
|
||||||
|
auto_days: scheduled ? [...f.auto_days].sort() : null }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const groupSchedule = g => (g.auto_enable_time && g.auto_disable_time && g.auto_days?.length
|
||||||
|
? { from: g.auto_enable_time, to: g.auto_disable_time, days: [...g.auto_days].sort() } : null)
|
||||||
|
|
||||||
|
// ── price rules (modifiers) ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const ids = t => t.target_ids ?? (t.target_id != null ? [t.target_id] : [])
|
||||||
|
const tags = t => t.target_tags ?? (t.target_tag ? [t.target_tag] : [])
|
||||||
|
export const normalizeTarget = t => ({ target_type: t.target_type, target_ids: ids(t), target_tags: tags(t) })
|
||||||
|
|
||||||
|
export const blankModifier = colour => ({
|
||||||
|
name: '', description: '', color: colour, is_active: true, is_favorite: false, allow_stack: false, sort_order: 0,
|
||||||
|
scope: 'global', item_id: null, action_type: 'add_percent', action_value: -10, round_to: '',
|
||||||
|
conditions: [], targets: [{ target_type: 'all', target_ids: [], target_tags: [] }],
|
||||||
|
})
|
||||||
|
|
||||||
|
export const modifierForm = (m, colour) => (m ? {
|
||||||
|
...blankModifier(colour), ...m, description: m.description ?? '', round_to: m.round_to ?? '',
|
||||||
|
conditions: (m.conditions ?? []).map(c => ({ condition_type: c.condition_type, params: c.params ?? {} })),
|
||||||
|
targets: (m.targets ?? []).map(normalizeTarget),
|
||||||
|
} : blankModifier(colour))
|
||||||
|
|
||||||
|
const targetComplete = t => ['all', 'any'].includes(t.target_type) || (t.target_type === 'tag' ? t.target_tags.length > 0 : t.target_ids.length > 0)
|
||||||
|
|
||||||
|
export function modifierProblems(f) {
|
||||||
|
const out = []
|
||||||
|
if (!f.name.trim()) out.push('name')
|
||||||
|
if (f.scope === 'item' && !f.item_id) out.push('product')
|
||||||
|
if (f.scope === 'global' && (!f.targets.length || !f.targets.every(targetComplete))) out.push('targets')
|
||||||
|
if (!f.conditions.every(conditionComplete)) out.push('conditions')
|
||||||
|
if (!Number.isFinite(f.action_value) || (f.action_type === 'set' && f.action_value < 0)) out.push('value')
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
export function modifierBody(f) {
|
||||||
|
return {
|
||||||
|
name: f.name.trim(), description: f.description.trim() || null, color: f.color, is_active: !!f.is_active,
|
||||||
|
is_favorite: !!f.is_favorite, allow_stack: !!f.allow_stack, sort_order: f.sort_order ?? 0,
|
||||||
|
scope: f.scope, item_id: f.scope === 'item' ? f.item_id : null,
|
||||||
|
action_type: f.action_type, action_value: f.action_value,
|
||||||
|
round_to: f.action_type === 'add_percent' && f.round_to ? f.round_to : null,
|
||||||
|
conditions: f.conditions.map(c => ({ condition_type: c.condition_type, params: c.params })),
|
||||||
|
targets: f.scope === 'global' ? f.targets.map(t => ({
|
||||||
|
target_type: t.target_type,
|
||||||
|
target_ids: t.target_type === 'tag' || t.target_type === 'all' ? null : t.target_ids,
|
||||||
|
target_id: t.target_type === 'tag' || t.target_type === 'all' ? null : t.target_ids[0] ?? null,
|
||||||
|
target_tags: t.target_type === 'tag' ? t.target_tags : null,
|
||||||
|
target_tag: t.target_type === 'tag' ? t.target_tags[0] ?? null : null,
|
||||||
|
})) : [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "−10%", "+€0.50", "= €3.00" (money formatted by the caller's formatter). */
|
||||||
|
export function actionText(type, value, money) {
|
||||||
|
const v = Number(value ?? 0)
|
||||||
|
if (type === 'set' || type === 'set_price') return `= ${money(v)}`
|
||||||
|
const sign = v < 0 ? '−' : '+'
|
||||||
|
if (type === 'add_amount') return `${sign}${money(Math.abs(v))}`
|
||||||
|
return `${sign}${Math.abs(v)}%`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a percentage or amount does to a price (the dialog's example), rounded like the server. */
|
||||||
|
export function examplePrice(base, type, value, roundTo) {
|
||||||
|
let p = type === 'set' ? value : type === 'add_amount' ? base + value : base * (1 + value / 100)
|
||||||
|
p = Math.max(p, 0)
|
||||||
|
if (type === 'add_percent' && roundTo) {
|
||||||
|
const step = { '0.05': 0.05, '0.10': 0.1, '0.20': 0.2, '0.50': 0.5 }[roundTo]
|
||||||
|
if (step) p = Math.round(p / step) * step
|
||||||
|
else if (roundTo === 'x.99') p = p >= 1 ? Math.floor(p) + 0.99 : p
|
||||||
|
else if (roundTo === 'x.00') p = Math.round(p)
|
||||||
|
}
|
||||||
|
return Math.round(Math.round(p / 0.1) * 0.1 * 100) / 100 // the system's final rounding to 0.10
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── deals ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const blankDeal = colour => ({
|
||||||
|
name: '', description: '', color: colour, is_active: true, sort_order: 0, action_type: 'free_item',
|
||||||
|
action_modifier_id: null, action_value: 0, action_free_item_id: null, action_free_target_type: 'item',
|
||||||
|
action_free_target_ids: [], action_free_quantity: 1,
|
||||||
|
conditions: [], targets: [{ target_type: 'any', target_ids: [], target_tags: [] }],
|
||||||
|
})
|
||||||
|
|
||||||
|
export const dealForm = (d, colour) => (d ? {
|
||||||
|
...blankDeal(colour), ...d, description: d.description ?? '', action_value: d.action_value ?? 0,
|
||||||
|
action_free_target_type: d.action_free_target_type ?? 'item', action_free_target_ids: d.action_free_target_ids ?? [],
|
||||||
|
conditions: (d.conditions ?? []).map(c => ({ condition_type: c.condition_type, params: c.params ?? {} })),
|
||||||
|
targets: (d.targets?.length ? d.targets : [{ target_type: 'any' }]).map(normalizeTarget),
|
||||||
|
} : blankDeal(colour))
|
||||||
|
|
||||||
|
export function dealProblems(f) {
|
||||||
|
const out = []
|
||||||
|
if (!f.name.trim()) out.push('name')
|
||||||
|
if (!f.targets.length || !f.targets.every(targetComplete)) out.push('targets')
|
||||||
|
if (!f.conditions.every(conditionComplete)) out.push('conditions')
|
||||||
|
const a = f.action_type
|
||||||
|
if (a === 'apply_modifier' && !f.action_modifier_id) out.push('modifier')
|
||||||
|
if (a === 'free_item' && !f.action_free_item_id) out.push('freeItem')
|
||||||
|
if (a === 'free_choice' && !f.action_free_target_ids.length) out.push('freeChoice')
|
||||||
|
if (['set_price', 'add_amount', 'add_percent'].includes(a) && !Number.isFinite(f.action_value)) out.push('value')
|
||||||
|
if (['free_item', 'free_choice'].includes(a) && !(f.action_free_quantity >= 1)) out.push('quantity')
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dealBody(f) {
|
||||||
|
const a = f.action_type
|
||||||
|
return {
|
||||||
|
name: f.name.trim(), description: f.description.trim() || null, color: f.color, is_active: !!f.is_active,
|
||||||
|
sort_order: f.sort_order ?? 0, action_type: a,
|
||||||
|
action_modifier_id: a === 'apply_modifier' ? f.action_modifier_id : null,
|
||||||
|
action_value: ['set_price', 'add_amount', 'add_percent'].includes(a) ? f.action_value : null,
|
||||||
|
action_free_item_id: a === 'free_item' ? f.action_free_item_id : null,
|
||||||
|
action_free_target_type: a === 'free_choice' ? f.action_free_target_type : null,
|
||||||
|
action_free_target_ids: a === 'free_choice' ? f.action_free_target_ids : null,
|
||||||
|
action_free_quantity: ['free_item', 'free_choice'].includes(a) ? f.action_free_quantity : 1,
|
||||||
|
conditions: f.conditions.map(c => ({ condition_type: c.condition_type, params: c.params })),
|
||||||
|
targets: f.targets.map(t => ({
|
||||||
|
target_type: t.target_type,
|
||||||
|
target_ids: ['item', 'category'].includes(t.target_type) ? t.target_ids : null,
|
||||||
|
target_id: ['item', 'category'].includes(t.target_type) ? t.target_ids[0] ?? null : null,
|
||||||
|
target_tags: t.target_type === 'tag' ? t.target_tags : null,
|
||||||
|
target_tag: t.target_type === 'tag' ? t.target_tags[0] ?? null : null,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── discount limits ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const VENUE_LIMITS = ['max_total_value_workday', 'max_total_value_shift', 'max_items_per_shift']
|
||||||
|
export const WAITER_LIMITS = ['max_discount_percent', 'max_discount_amount', 'max_total_value_shift', 'max_total_value_workday',
|
||||||
|
'max_items_per_shift', 'max_items_per_workday', 'max_items_per_order']
|
||||||
|
export const COUNT_LIMITS = new Set(['max_items_per_shift', 'max_items_per_workday', 'max_items_per_order'])
|
||||||
|
|
||||||
|
/** A limit typed in a box: '' = no limit; a comma works as the decimal point. null when it isn't a number ≥ 0. */
|
||||||
|
export function parseLimit(text, count = false) {
|
||||||
|
const s = String(text ?? '').trim().replace(',', '.')
|
||||||
|
if (s === '') return { ok: true, value: null }
|
||||||
|
const v = Number(s)
|
||||||
|
if (!Number.isFinite(v) || v < 0 || (count && !Number.isInteger(v))) return { ok: false, value: null }
|
||||||
|
return { ok: true, value: v }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const limitText = v => (v == null ? '' : String(v))
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// What the pricing rules can point at (plan step 6.7), loaded once and kept current: products,
|
||||||
|
// categories (as a tree), prep zones, tags and price groups; and the colours a rule can have.
|
||||||
|
import { useMemo } from 'react'
|
||||||
|
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||||
|
import { CATEGORY_COLOURS } from '../products/categoryColours'
|
||||||
|
import { categoryTree, treeLabel } from '../products/productsLogic'
|
||||||
|
import * as api from './pricingApi'
|
||||||
|
|
||||||
|
export const COLOURS = CATEGORY_COLOURS // the venue's colours (data, as the categories')
|
||||||
|
|
||||||
|
export function useCatalog() {
|
||||||
|
const products = useLiveQuery({ queryKey: ['products-all'], queryFn: api.listProducts, events: ['products_changed'], staleTime: 60_000 })
|
||||||
|
const categories = useLiveQuery({ queryKey: ['categories'], queryFn: api.listCategories, events: ['products_changed'], staleTime: 60_000 })
|
||||||
|
const zones = useLiveQuery({ queryKey: ['prep-zones'], queryFn: api.listPrepZones, staleTime: 60_000 })
|
||||||
|
const tags = useLiveQuery({ queryKey: ['product-tags'], queryFn: api.listTags, staleTime: 60_000 })
|
||||||
|
const groups = useLiveQuery({ queryKey: ['pricing', 'groups'], queryFn: api.listGroups, events: api.PRICING_EVENTS })
|
||||||
|
return useMemo(() => ({
|
||||||
|
products: (products.data ?? []).filter(p => p.lifecycle_status !== 'archived' && !p.is_service_item)
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name)).map(p => ({ id: p.id, name: p.name, price: p.base_price })),
|
||||||
|
categories: categoryTree(categories.data ?? []).map(({ cat, depth }) => ({ id: cat.id, name: treeLabel(cat, depth), plain: cat.name })),
|
||||||
|
zones: (zones.data ?? []).map(z => ({ id: z.id, name: z.name })),
|
||||||
|
tags: tags.data ?? [],
|
||||||
|
groups: groups.data ?? [],
|
||||||
|
}), [products.data, categories.data, zones.data, tags.data, groups.data])
|
||||||
|
}
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ export const NAV = [
|
|||||||
{ to: '/management/approvals', icon: ShieldCheck, label: 'nav.approvals', module: 'core', perm: 'core.staff.manage' },
|
{ to: '/management/approvals', icon: ShieldCheck, label: 'nav.approvals', module: 'core', perm: 'core.staff.manage' },
|
||||||
{ to: '/management/schedule', icon: CalendarDays, label: 'nav.schedule', module: 'staff_planning', perm: 'core.staff.manage' },
|
{ to: '/management/schedule', icon: CalendarDays, label: 'nav.schedule', module: 'staff_planning', perm: 'core.staff.manage' },
|
||||||
{ to: '/management/prep-zones', icon: CookingPot, label: 'nav.prepZones', module: 'catalog', perm: 'catalog.menu.manage' },
|
{ to: '/management/prep-zones', icon: CookingPot, label: 'nav.prepZones', module: 'catalog', perm: 'catalog.menu.manage' },
|
||||||
{ to: '/management/pricing', icon: Percent, label: 'nav.pricing', module: 'pricing', perm: 'catalog.menu.manage' },
|
{ to: '/management/pricing', icon: Percent, label: 'nav.pricing', module: 'pricing', perm: 'pricing.manage' },
|
||||||
{ to: '/notes', icon: StickyNote, label: 'nav.notes', module: 'notes', perm: DASH },
|
{ to: '/notes', icon: StickyNote, label: 'nav.notes', module: 'notes', perm: DASH },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
// The pricing page's rules as data (plan step 6.7): forms, what is sent, what's missing, summaries.
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import {
|
||||||
|
actionText, blankCondition, conditionComplete, dealBody, dealForm, dealProblems, examplePrice, groupBody, groupForm, groupProblems,
|
||||||
|
modifierBody, modifierForm, modifierProblems, moveItem, parseLimit,
|
||||||
|
} from '../src/pages/pricing/pricingLogic.js'
|
||||||
|
|
||||||
|
const money = v => `€${v.toFixed(2)}`
|
||||||
|
|
||||||
|
test('a condition is complete only with all its values (the server refuses the rest)', () => {
|
||||||
|
assert.equal(conditionComplete(blankCondition('time_range')), true)
|
||||||
|
assert.equal(conditionComplete({ condition_type: 'time_range', params: { from: '17:00', to: '' } }), false)
|
||||||
|
assert.equal(conditionComplete({ condition_type: 'time_range', params: { from: '22:00', to: '02:00' } }), true) // crosses midnight
|
||||||
|
assert.equal(conditionComplete(blankCondition('date_range')), false)
|
||||||
|
assert.equal(conditionComplete({ condition_type: 'date_range', params: { from: '2026-12-31', to: '2026-12-01' } }), false)
|
||||||
|
assert.equal(conditionComplete(blankCondition('day_of_week')), false)
|
||||||
|
assert.equal(conditionComplete({ condition_type: 'day_of_week', params: { days: [5, 6] } }), true)
|
||||||
|
assert.equal(conditionComplete(blankCondition('price_group_active')), false)
|
||||||
|
assert.equal(conditionComplete({ condition_type: 'min_category_qty', params: { category_id: 3, min: 2 } }), true)
|
||||||
|
assert.equal(conditionComplete({ condition_type: 'user_tier', params: {} }), true) // old placeholder: kept
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a happy-hour rule: form → body', () => {
|
||||||
|
const f = modifierForm(null, '#000')
|
||||||
|
assert.deepEqual(modifierProblems(f), ['name'])
|
||||||
|
f.name = ' Happy hour '
|
||||||
|
f.targets = [{ target_type: 'category', target_ids: [], target_tags: [] }]
|
||||||
|
f.conditions = [blankCondition('time_range')]
|
||||||
|
assert.deepEqual(modifierProblems(f), ['targets'])
|
||||||
|
f.targets[0].target_ids = [4, 7]
|
||||||
|
f.action_value = -20
|
||||||
|
f.round_to = '0.50'
|
||||||
|
assert.deepEqual(modifierProblems(f), [])
|
||||||
|
const body = modifierBody(f)
|
||||||
|
assert.equal(body.name, 'Happy hour')
|
||||||
|
assert.deepEqual(body.targets, [{ target_type: 'category', target_ids: [4, 7], target_id: 4, target_tags: null, target_tag: null }])
|
||||||
|
assert.deepEqual(body.conditions, [{ condition_type: 'time_range', params: { from: '17:00', to: '19:00' } }])
|
||||||
|
assert.equal(body.round_to, '0.50')
|
||||||
|
// rounding only with a percentage; one product: no targets
|
||||||
|
assert.equal(modifierBody({ ...f, action_type: 'add_amount' }).round_to, null)
|
||||||
|
const one = modifierBody({ ...f, scope: 'item', item_id: 9 })
|
||||||
|
assert.deepEqual([one.item_id, one.targets], [9, []])
|
||||||
|
assert.deepEqual(modifierProblems({ ...f, scope: 'item', item_id: null }), ['product'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('an old rule with single target ids loads as lists', () => {
|
||||||
|
const f = modifierForm({ id: 1, name: 'x', action_type: 'set', action_value: 3, targets: [{ target_type: 'item', target_id: 5 }, { target_type: 'tag', target_tag: 'vegan' }], conditions: [] }, '#000')
|
||||||
|
assert.deepEqual(f.targets, [{ target_type: 'item', target_ids: [5], target_tags: [] }, { target_type: 'tag', target_ids: [], target_tags: ['vegan'] }])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('summaries and the example price (rounded to 0.10 like the server)', () => {
|
||||||
|
assert.equal(actionText('add_percent', -10, money), '−10%')
|
||||||
|
assert.equal(actionText('add_amount', 0.5, money), '+€0.50')
|
||||||
|
assert.equal(actionText('set', 3, money), '= €3.00')
|
||||||
|
assert.equal(examplePrice(5, 'add_percent', -20, ''), 4)
|
||||||
|
assert.equal(examplePrice(5, 'add_percent', -15, ''), 4.3) // 4.25 → 4.30
|
||||||
|
assert.equal(examplePrice(5, 'add_percent', -15, 'x.99'), 5) // 4.25 → 4.99, then the system's 0.10 → 5.00
|
||||||
|
assert.equal(examplePrice(2, 'add_amount', -5, ''), 0) // never below 0
|
||||||
|
})
|
||||||
|
|
||||||
|
test('price groups: a schedule is all or nothing', () => {
|
||||||
|
const f = groupForm(null, '#000')
|
||||||
|
f.name = 'Happy hour'
|
||||||
|
assert.deepEqual(groupProblems(f), [])
|
||||||
|
f.auto_enable_time = '17:00'
|
||||||
|
assert.deepEqual(groupProblems(f), ['schedule'])
|
||||||
|
f.auto_disable_time = '19:00'
|
||||||
|
f.auto_days = [4, 0]
|
||||||
|
assert.deepEqual(groupProblems(f), [])
|
||||||
|
assert.deepEqual(groupBody(f).auto_days, [0, 4])
|
||||||
|
assert.equal(groupBody({ ...f, auto_days: [] }).auto_enable_time, null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('deals: what each kind needs', () => {
|
||||||
|
const f = dealForm(null, '#000')
|
||||||
|
f.name = '3 beers'
|
||||||
|
assert.deepEqual(dealProblems(f), ['freeItem'])
|
||||||
|
f.action_free_item_id = 12
|
||||||
|
assert.deepEqual(dealProblems(f), [])
|
||||||
|
const body = dealBody(f)
|
||||||
|
assert.equal(body.action_free_item_id, 12)
|
||||||
|
assert.equal(body.action_value, null)
|
||||||
|
assert.deepEqual(body.targets, [{ target_type: 'any', target_ids: null, target_id: null, target_tags: null, target_tag: null }])
|
||||||
|
assert.deepEqual(dealProblems({ ...f, action_type: 'free_choice' }), ['freeChoice'])
|
||||||
|
assert.deepEqual(dealProblems({ ...f, action_type: 'apply_modifier' }), ['modifier'])
|
||||||
|
const pct = dealBody({ ...f, action_type: 'add_percent', action_value: -50 })
|
||||||
|
assert.deepEqual([pct.action_value, pct.action_free_item_id], [-50, null])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('limits typed in a box', () => {
|
||||||
|
assert.deepEqual(parseLimit(''), { ok: true, value: null })
|
||||||
|
assert.deepEqual(parseLimit('12,5'), { ok: true, value: 12.5 })
|
||||||
|
assert.deepEqual(parseLimit('-1'), { ok: false, value: null })
|
||||||
|
assert.deepEqual(parseLimit('2.5', true), { ok: false, value: null })
|
||||||
|
assert.deepEqual(parseLimit('3', true), { ok: true, value: 3 })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('moving a rule up and down', () => {
|
||||||
|
assert.deepEqual(moveItem([1, 2, 3], 2, 1), [1, 3, 2])
|
||||||
|
assert.deepEqual(moveItem([1, 2, 3], 0, -1), [1, 2, 3])
|
||||||
|
})
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
|
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
|
||||||
"paths": [
|
"paths": [
|
||||||
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products"
|
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing"
|
||||||
],
|
],
|
||||||
"strict": [
|
"strict": [
|
||||||
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products"
|
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -325,5 +325,9 @@
|
|||||||
"waste": {
|
"waste": {
|
||||||
"not_found": "Η καταχώριση απόρριψης δεν βρέθηκε.",
|
"not_found": "Η καταχώριση απόρριψης δεν βρέθηκε.",
|
||||||
"not_today": "Διαγράφονται μόνο απορρίψεις της ανοιχτής εργάσιμης μέρας."
|
"not_today": "Διαγράφονται μόνο απορρίψεις της ανοιχτής εργάσιμης μέρας."
|
||||||
|
},
|
||||||
|
"pricing": {
|
||||||
|
"bad_limit": "Ένα όριο έκπτωσης πρέπει να είναι αριθμός 0 ή μεγαλύτερος, ή κενό για χωρίς όριο.",
|
||||||
|
"bad_condition": "Μια συνθήκη είναι ελλιπής: συμπληρώστε όλες τις τιμές της."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1844,5 +1844,258 @@
|
|||||||
"seconds_other": "{{count}} δευτερόλεπτα",
|
"seconds_other": "{{count}} δευτερόλεπτα",
|
||||||
"minutes_one": "{{count}} λεπτό",
|
"minutes_one": "{{count}} λεπτό",
|
||||||
"minutes_other": "{{count}} λεπτά"
|
"minutes_other": "{{count}} λεπτά"
|
||||||
|
},
|
||||||
|
"pricing": {
|
||||||
|
"pageTitle": "Προσφορές & τιμές",
|
||||||
|
"intro": "Κανόνες που αλλάζουν τιμές μόνοι τους (happy hour, εποχή, σημείο πώλησης), διακόπτες που ενεργοποιούν πολλούς μαζί, προσφορές που προτείνουν οι σερβιτόροι, και πόση έκπτωση μπορεί να δώσει ο καθένας. Οι νέες τιμές ισχύουν για ό,τι προστίθεται στις παραγγελίες από εκεί και πέρα.",
|
||||||
|
"tabs": {
|
||||||
|
"rules": "Κανόνες τιμών",
|
||||||
|
"groups": "Ομάδες τιμών",
|
||||||
|
"deals": "Προσφορές",
|
||||||
|
"discounts": "Εκπτώσεις"
|
||||||
|
},
|
||||||
|
"name": "Όνομα",
|
||||||
|
"description": "Περιγραφή (προαιρετικό)",
|
||||||
|
"colour": "Χρώμα",
|
||||||
|
"save": "Αποθήκευση",
|
||||||
|
"cancel": "Ακύρωση",
|
||||||
|
"delete": "Διαγραφή",
|
||||||
|
"edit": "Επεξεργασία",
|
||||||
|
"remove": "Αφαίρεση",
|
||||||
|
"add": "Προσθήκη",
|
||||||
|
"up": "Μεγαλύτερη προτεραιότητα",
|
||||||
|
"down": "Μικρότερη προτεραιότητα",
|
||||||
|
"turnOn": "Ενεργοποίηση",
|
||||||
|
"turnOff": "Απενεργοποίηση",
|
||||||
|
"on": "Ενεργό",
|
||||||
|
"off": "Ανενεργό",
|
||||||
|
"saved": "Αποθηκεύτηκε.",
|
||||||
|
"deleted": "Διαγράφηκε.",
|
||||||
|
"choose": "Επιλέξτε…",
|
||||||
|
"search": "Αναζήτηση",
|
||||||
|
"nothingFound": "Δεν βρέθηκε τίποτα.",
|
||||||
|
"newTag": "Άλλη ετικέτα",
|
||||||
|
"missing": "Συμπληρώστε: {{list}}.",
|
||||||
|
"target": {
|
||||||
|
"type": "Ποια προϊόντα",
|
||||||
|
"add": "Προσθήκη προϊόντων",
|
||||||
|
"types": {
|
||||||
|
"all": "Όλα τα προϊόντα",
|
||||||
|
"any": "Οποιοδήποτε προϊόν",
|
||||||
|
"item": "Κάποια προϊόντα",
|
||||||
|
"category": "Κατηγορίες",
|
||||||
|
"prep_zone": "Ζώνες ετοιμασίας (κουζίνα, μπαρ…)",
|
||||||
|
"tag": "Ετικέτες"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"condition": {
|
||||||
|
"type": "Συνθήκη",
|
||||||
|
"add": "Προσθήκη συνθήκης",
|
||||||
|
"from": "Από",
|
||||||
|
"to": "Έως",
|
||||||
|
"date": "Ημερομηνία",
|
||||||
|
"timeHint": "Στην ώρα του καταστήματος. Το «Έως» πριν από το «Από» περνά τα μεσάνυχτα (π.χ. 22:00 έως 02:00).",
|
||||||
|
"ofTheDish": "ή περισσότερα από το ίδιο προϊόν στην παραγγελία",
|
||||||
|
"orderTotal": "€ ή περισσότερα στην παραγγελία",
|
||||||
|
"fromCategory": "ή περισσότερα από",
|
||||||
|
"noGroups": "Φτιάξτε πρώτα μια ομάδα τιμών",
|
||||||
|
"placeholder": "Παλιά συνθήκη που δεν κάνει τίποτα (μπορεί να αφαιρεθεί).",
|
||||||
|
"types": {
|
||||||
|
"time_range": "Ώρα της ημέρας",
|
||||||
|
"day_of_week": "Ημέρες της εβδομάδας",
|
||||||
|
"date_range": "Ανάμεσα σε δύο ημερομηνίες",
|
||||||
|
"specific_date": "Σε συγκεκριμένες ημερομηνίες",
|
||||||
|
"price_group_active": "Μια ομάδα τιμών είναι ενεργή",
|
||||||
|
"order_channel": "Σημείο πώλησης",
|
||||||
|
"min_item_quantity": "Τουλάχιστον κάποια από το προϊόν",
|
||||||
|
"min_category_qty": "Τουλάχιστον κάποια από μια κατηγορία",
|
||||||
|
"min_order_value": "Σύνολο παραγγελίας τουλάχιστον"
|
||||||
|
},
|
||||||
|
"fields": {
|
||||||
|
"min_item_quantity": "Πόσα",
|
||||||
|
"min_category_qty": "Πόσα",
|
||||||
|
"min_order_value": "Ποσό",
|
||||||
|
"category_id": "Κατηγορία",
|
||||||
|
"price_group_id": "Ομάδα τιμών"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"add_percent": "± ποσοστό",
|
||||||
|
"add_amount": "± ποσό",
|
||||||
|
"set": "Νέα τιμή",
|
||||||
|
"valueLabel": {
|
||||||
|
"add_percent": "Ποσοστό (%)",
|
||||||
|
"add_amount": "Ποσό (€)",
|
||||||
|
"set": "Η νέα τιμή (€)"
|
||||||
|
},
|
||||||
|
"minusHint": "Το πλην το κάνει φθηνότερο (−10 = 10% έκπτωση)· το συν ακριβότερο."
|
||||||
|
},
|
||||||
|
"roundings": {
|
||||||
|
"none": "Χωρίς στρογγυλοποίηση",
|
||||||
|
"0_05": "Στο πλησιέστερο €0,05",
|
||||||
|
"0_10": "Στο πλησιέστερο €0,10",
|
||||||
|
"0_20": "Στο πλησιέστερο €0,20",
|
||||||
|
"0_50": "Στο πλησιέστερο €0,50",
|
||||||
|
"x_99": "Σε x,99 (π.χ. 4,99)",
|
||||||
|
"x_00": "Σε ακέραιο ευρώ"
|
||||||
|
},
|
||||||
|
"rules": {
|
||||||
|
"title": "Κανόνες τιμών",
|
||||||
|
"new": "Νέος κανόνας τιμής",
|
||||||
|
"edit": "Επεξεργασία κανόνα τιμής",
|
||||||
|
"intro": "Ένας κανόνας αλλάζει την τιμή κάποιων προϊόντων όσο ισχύουν οι συνθήκες του, π.χ. «ποτά −20% από 17:00 έως 19:00 τις καθημερινές». Το ταμείο, τα κινητά, τα tablet και οι online παραγγελίες τον χρησιμοποιούν για ό,τι προστίθεται από εκεί και πέρα.",
|
||||||
|
"none": "Δεν υπάρχουν ακόμα κανόνες τιμών",
|
||||||
|
"noneHint": "Φτιάξτε έναν για happy hour, εποχή ή σημείο πώλησης.",
|
||||||
|
"orderHint": "Ψηλότερα στη λίστα = πρώτος. Από τους κανόνες που δεν συνδυάζονται, μετράει μόνο ο πρώτος που ισχύει για ένα προϊόν· μετά εφαρμόζονται όλοι όσοι συνδυάζονται. Η τελική τιμή στρογγυλοποιείται στα €0,10.",
|
||||||
|
"namePlaceholder": "π.χ. Happy hour ποτά",
|
||||||
|
"allProducts": "Όλα τα προϊόντα",
|
||||||
|
"someProducts_one": "{{count}} ομάδα προϊόντων",
|
||||||
|
"someProducts_other": "{{count}} ομάδες προϊόντων",
|
||||||
|
"conditions_one": "{{count}} συνθήκη",
|
||||||
|
"conditions_other": "{{count}} συνθήκες",
|
||||||
|
"always": "πάντα (όσο είναι ενεργός)",
|
||||||
|
"stacks": "συνδυάζεται",
|
||||||
|
"pages": {
|
||||||
|
"what": "Προϊόντα",
|
||||||
|
"when": "Πότε",
|
||||||
|
"price": "Τιμή"
|
||||||
|
},
|
||||||
|
"scopes": {
|
||||||
|
"global": "Προϊόντα, κατηγορίες, ετικέτες…",
|
||||||
|
"item": "Ένα προϊόν"
|
||||||
|
},
|
||||||
|
"product": "Προϊόν",
|
||||||
|
"targetsHint": "Ο κανόνας αλλάζει τα προϊόντα οποιασδήποτε από αυτές τις γραμμές.",
|
||||||
|
"conditionsHint": "Όλες οι συνθήκες πρέπει να ισχύουν τη στιγμή που προστίθεται ένα προϊόν. Χωρίς καμία, ο κανόνας ισχύει όποτε είναι ενεργός.",
|
||||||
|
"on": "Ενεργός",
|
||||||
|
"onHint": "Ανενεργός: δεν εφαρμόζεται ποτέ, όποιες κι αν είναι οι συνθήκες.",
|
||||||
|
"rounding": "Στρογγυλοποίηση",
|
||||||
|
"example": "Ένα προϊόν των {{before}} κοστίζει {{after}}.",
|
||||||
|
"stack": "Συνδυάζεται με άλλους κανόνες",
|
||||||
|
"stackTip": "Ένας κανόνας που συνδυάζεται εφαρμόζεται μετά τον πρώτο κανόνα που δεν συνδυάζεται, πάνω στο αποτέλεσμά του (π.χ. −10% και μετά −€0,50). Ένας που δεν συνδυάζεται εφαρμόζεται μόνο αν δεν έχει ήδη εφαρμοστεί κάποιος πιο πάνω.",
|
||||||
|
"deleteTitle": "Διαγραφή του κανόνα τιμής;",
|
||||||
|
"deleteBody": "Ο «{{name}}» δεν θα αλλάζει πια καμία τιμή. Οι γραμμές που είναι ήδη σε παραγγελίες κρατούν την τιμή τους.",
|
||||||
|
"problems": {
|
||||||
|
"name": "το όνομα",
|
||||||
|
"product": "το προϊόν",
|
||||||
|
"targets": "ποια προϊόντα",
|
||||||
|
"conditions": "τις τιμές κάθε συνθήκης",
|
||||||
|
"value": "την τιμή"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"groups": {
|
||||||
|
"title": "Ομάδες τιμών",
|
||||||
|
"new": "Νέα ομάδα τιμών",
|
||||||
|
"edit": "Επεξεργασία ομάδας τιμών",
|
||||||
|
"intro": "Μια ομάδα τιμών είναι ένας διακόπτης, όπως «Happy hour» ή «Καλοκαίρι». Οι κανόνες και οι προσφορές με τη συνθήκη «μια ομάδα τιμών είναι ενεργή» την ακολουθούν, οπότε ένας διακόπτης ενεργοποιεί πολλούς. Ενεργοποιείται με το χέρι ή με εβδομαδιαίο πρόγραμμα.",
|
||||||
|
"none": "Δεν υπάρχουν ακόμα ομάδες τιμών",
|
||||||
|
"noneHint": "Φτιάξτε μία για να ενεργοποιείτε πολλούς κανόνες μαζί.",
|
||||||
|
"namePlaceholder": "π.χ. Happy hour",
|
||||||
|
"byHand": "Ενεργοποίηση με το χέρι",
|
||||||
|
"scheduled": "Ενεργή {{from}}–{{to}}, {{days}}",
|
||||||
|
"onNow": "Ενεργή τώρα",
|
||||||
|
"onNowHint": "Με πρόγραμμα είναι επίσης ενεργή μέσα στις ώρες του· έξω από αυτές αποφασίζει αυτός ο διακόπτης.",
|
||||||
|
"schedule": "Εβδομαδιαίο πρόγραμμα (προαιρετικό)",
|
||||||
|
"scheduleHint": "Από, έως και τουλάχιστον μία ημέρα, στην ώρα του καταστήματος· το «Έως» πριν από το «Από» περνά τα μεσάνυχτα.",
|
||||||
|
"deleteTitle": "Διαγραφή της ομάδας τιμών;",
|
||||||
|
"deleteBody": "Κανόνες και προσφορές με τη συνθήκη «η {{name}} είναι ενεργή» δεν θα εφαρμόζονται μέχρι να τους αλλάξετε.",
|
||||||
|
"problems": {
|
||||||
|
"name": "το όνομα",
|
||||||
|
"schedule": "ολόκληρο το πρόγραμμα (από, έως και ημέρα) ή τίποτα από αυτό"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"deals": {
|
||||||
|
"title": "Προσφορές",
|
||||||
|
"new": "Νέα προσφορά",
|
||||||
|
"edit": "Επεξεργασία προσφοράς",
|
||||||
|
"intro": "Μια προσφορά προτείνεται στον σερβιτόρο όταν μια παραγγελία έχει τα σωστά προϊόντα, π.χ. «3 μπύρες → η 4η δώρο». Το κινητό του σερβιτόρου τη δείχνει κι εκείνος την αποδέχεται ή την προσπερνά: τίποτα δεν εφαρμόζεται μόνο του.",
|
||||||
|
"none": "Δεν υπάρχουν ακόμα προσφορές",
|
||||||
|
"noneHint": "π.χ. «Πάρε 3 μπύρες, η 1 δώρο».",
|
||||||
|
"namePlaceholder": "π.χ. 3 μπύρες + 1 δώρο",
|
||||||
|
"descriptionHint": "Ο σερβιτόρος τη βλέπει μαζί με την προσφορά.",
|
||||||
|
"pages": {
|
||||||
|
"when": "Πότε",
|
||||||
|
"gives": "Τι δίνει"
|
||||||
|
},
|
||||||
|
"targetsHint": "Η παραγγελία πρέπει να έχει προϊόντα οποιασδήποτε από αυτές τις γραμμές.",
|
||||||
|
"conditionsHint": "Και, προαιρετικά, όλες αυτές οι συνθήκες.",
|
||||||
|
"on": "Ενεργή",
|
||||||
|
"actions": {
|
||||||
|
"free_item": "Ένα προϊόν δώρο",
|
||||||
|
"free_choice": "Ένα προϊόν δώρο της επιλογής του πελάτη",
|
||||||
|
"apply_modifier": "Έναν κανόνα τιμής",
|
||||||
|
"set_price": "Νέα τιμή",
|
||||||
|
"add_amount": "± ποσό",
|
||||||
|
"add_percent": "± ποσοστό"
|
||||||
|
},
|
||||||
|
"freeProduct": "Προϊόν δώρο",
|
||||||
|
"freeFrom": {
|
||||||
|
"item": "Από αυτά τα προϊόντα",
|
||||||
|
"category": "Από αυτές τις κατηγορίες",
|
||||||
|
"tag": "Με αυτές τις ετικέτες"
|
||||||
|
},
|
||||||
|
"quantity": "Πόσα δώρο",
|
||||||
|
"rule": "Κανόνας τιμής",
|
||||||
|
"ruleHint": "Μόνο κανόνες χωρίς συνθήκες (εφαρμόζονται όταν ο σερβιτόρος αποδεχτεί την προσφορά).",
|
||||||
|
"noManualRules": "Δεν υπάρχει ακόμα κανόνας χωρίς συνθήκες",
|
||||||
|
"givesFree_one": "{{count}} × {{name}} δώρο",
|
||||||
|
"givesFree_other": "{{count}} × {{name}} δώρο",
|
||||||
|
"givesChoice_one": "{{count}} δώρο της επιλογής τους",
|
||||||
|
"givesChoice_other": "{{count}} δώρο της επιλογής τους",
|
||||||
|
"givesRule": "Κανόνας: {{name}}",
|
||||||
|
"deleteTitle": "Διαγραφή της προσφοράς;",
|
||||||
|
"deleteBody": "Η «{{name}}» δεν θα προτείνεται πια.",
|
||||||
|
"problems": {
|
||||||
|
"name": "το όνομα",
|
||||||
|
"targets": "ποια προϊόντα",
|
||||||
|
"conditions": "τις τιμές κάθε συνθήκης",
|
||||||
|
"modifier": "τον κανόνα τιμής",
|
||||||
|
"freeItem": "το προϊόν δώρο",
|
||||||
|
"freeChoice": "από τι διαλέγει ο πελάτης",
|
||||||
|
"value": "το ποσό",
|
||||||
|
"quantity": "πόσα"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"discounts": {
|
||||||
|
"title": "Εκπτώσεις",
|
||||||
|
"intro": "Ποιος μπορεί να κάνει εκπτώσεις και πόσες. Ισχύουν και τα όρια του καταστήματος και του καθενός: όποιο φτάσει πρώτο σταματά την έκπτωση. Πέρα από ένα όριο χρειάζεται έγκριση διευθυντή επί τόπου, εκτός αν ο ρόλος του επιτρέπει «εκπτώσεις πέρα από τα όρια». Κενό κουτί σημαίνει χωρίς όριο.",
|
||||||
|
"venue": "Όλο το κατάστημα",
|
||||||
|
"venueHint": "Για όλους, επιπλέον των ορίων του καθενός.",
|
||||||
|
"enabled": "Επιτρέπονται εκπτώσεις",
|
||||||
|
"enabledHint": "Ανενεργό: κανείς δεν μπορεί να κάνει έκπτωση, ούτε με έγκριση διευθυντή.",
|
||||||
|
"person": "Ο καθένας",
|
||||||
|
"personHint": "Τα δικά του όρια. Επιλέξτε άτομο, αλλάξτε, αποθηκεύστε.",
|
||||||
|
"who": "Άτομο",
|
||||||
|
"nobody": "Δεν υπάρχει ενεργό προσωπικό.",
|
||||||
|
"can": "Μπορεί να κάνει εκπτώσεις",
|
||||||
|
"canHint": "Ανενεργό: αυτό το άτομο δεν μπορεί να κάνει καμία έκπτωση μόνο του.",
|
||||||
|
"noLimit": "χωρίς όριο",
|
||||||
|
"items": "τεμάχια",
|
||||||
|
"badNumber": "Αριθμός 0 ή μεγαλύτερος (ακέραιος για τεμάχια), ή κενό.",
|
||||||
|
"venueLimits": {
|
||||||
|
"max_total_value_workday": "Μέγιστο ανά εργάσιμη ημέρα",
|
||||||
|
"max_total_value_workdayHint": "Όλες οι εκπτώσεις της ημέρας, όλοι μαζί.",
|
||||||
|
"max_total_value_shift": "Μέγιστο σε μια βάρδια",
|
||||||
|
"max_total_value_shiftHint": "Όλες οι εκπτώσεις από την αρχή της βάρδιας του σερβιτόρου, όλοι μαζί.",
|
||||||
|
"max_items_per_shift": "Μέγιστα τεμάχια σε μια βάρδια",
|
||||||
|
"max_items_per_shiftHint": "Τεμάχια με έκπτωση από την αρχή της βάρδιας του σερβιτόρου, όλοι μαζί."
|
||||||
|
},
|
||||||
|
"personLimits": {
|
||||||
|
"max_discount_percent": "Μέγιστο ανά έκπτωση",
|
||||||
|
"max_discount_percentHint": "Το μεγαλύτερο ποσοστό κάθε φορά.",
|
||||||
|
"max_discount_amount": "Μέγιστο από ένα τεμάχιο",
|
||||||
|
"max_discount_amountHint": "Το περισσότερο που αφαιρείται από την τιμή ενός τεμαχίου.",
|
||||||
|
"max_total_value_shift": "Μέγιστο ανά βάρδια",
|
||||||
|
"max_total_value_shiftHint": "Οι εκπτώσεις του σε μία βάρδια.",
|
||||||
|
"max_total_value_workday": "Μέγιστο ανά εργάσιμη ημέρα",
|
||||||
|
"max_total_value_workdayHint": "Οι εκπτώσεις του σε μία ημέρα.",
|
||||||
|
"max_items_per_shift": "Τεμάχια ανά βάρδια",
|
||||||
|
"max_items_per_shiftHint": "Τεμάχια με έκπτωση σε μία βάρδια.",
|
||||||
|
"max_items_per_workday": "Τεμάχια ανά εργάσιμη ημέρα",
|
||||||
|
"max_items_per_workdayHint": "Τεμάχια με έκπτωση σε μία ημέρα.",
|
||||||
|
"max_items_per_order": "Τεμάχια ανά παραγγελία",
|
||||||
|
"max_items_per_orderHint": "Τεμάχια με έκπτωση σε μία παραγγελία."
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -325,5 +325,9 @@
|
|||||||
"waste": {
|
"waste": {
|
||||||
"not_found": "Throwaway entry not found.",
|
"not_found": "Throwaway entry not found.",
|
||||||
"not_today": "Only throwaways of the open business day can be deleted."
|
"not_today": "Only throwaways of the open business day can be deleted."
|
||||||
|
},
|
||||||
|
"pricing": {
|
||||||
|
"bad_limit": "A discount limit must be a number of 0 or more, or empty for no limit.",
|
||||||
|
"bad_condition": "A condition is incomplete: fill in all its values."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1844,5 +1844,258 @@
|
|||||||
"seconds_other": "{{count}} seconds",
|
"seconds_other": "{{count}} seconds",
|
||||||
"minutes_one": "{{count}} minute",
|
"minutes_one": "{{count}} minute",
|
||||||
"minutes_other": "{{count}} minutes"
|
"minutes_other": "{{count}} minutes"
|
||||||
|
},
|
||||||
|
"pricing": {
|
||||||
|
"pageTitle": "Offers & pricing",
|
||||||
|
"intro": "Rules that change prices by themselves (happy hour, a season, a sales point), switches that turn several on at once, deals the waiters offer, and how much discount each person may give. New prices apply to what is added to orders from then on.",
|
||||||
|
"tabs": {
|
||||||
|
"rules": "Price rules",
|
||||||
|
"groups": "Price groups",
|
||||||
|
"deals": "Deals",
|
||||||
|
"discounts": "Discounts"
|
||||||
|
},
|
||||||
|
"name": "Name",
|
||||||
|
"description": "Description (optional)",
|
||||||
|
"colour": "Colour",
|
||||||
|
"save": "Save",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"delete": "Delete",
|
||||||
|
"edit": "Edit",
|
||||||
|
"remove": "Remove",
|
||||||
|
"add": "Add",
|
||||||
|
"up": "Higher priority",
|
||||||
|
"down": "Lower priority",
|
||||||
|
"turnOn": "Turn on",
|
||||||
|
"turnOff": "Turn off",
|
||||||
|
"on": "On",
|
||||||
|
"off": "Off",
|
||||||
|
"saved": "Saved.",
|
||||||
|
"deleted": "Deleted.",
|
||||||
|
"choose": "Choose…",
|
||||||
|
"search": "Search",
|
||||||
|
"nothingFound": "Nothing found.",
|
||||||
|
"newTag": "Another tag",
|
||||||
|
"missing": "Fill in: {{list}}.",
|
||||||
|
"target": {
|
||||||
|
"type": "Which products",
|
||||||
|
"add": "Add products",
|
||||||
|
"types": {
|
||||||
|
"all": "All products",
|
||||||
|
"any": "Any product",
|
||||||
|
"item": "Some products",
|
||||||
|
"category": "Categories",
|
||||||
|
"prep_zone": "Prep zones (kitchen, bar…)",
|
||||||
|
"tag": "Tags"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"condition": {
|
||||||
|
"type": "Condition",
|
||||||
|
"add": "Add a condition",
|
||||||
|
"from": "From",
|
||||||
|
"to": "To",
|
||||||
|
"date": "A date",
|
||||||
|
"timeHint": "In the venue's time. \"To\" earlier than \"From\" crosses midnight (e.g. 22:00 to 02:00).",
|
||||||
|
"ofTheDish": "or more of the same product in the order",
|
||||||
|
"orderTotal": "€ or more in the order",
|
||||||
|
"fromCategory": "or more from",
|
||||||
|
"noGroups": "Make a price group first",
|
||||||
|
"placeholder": "An old condition that does nothing (it can be removed).",
|
||||||
|
"types": {
|
||||||
|
"time_range": "Time of day",
|
||||||
|
"day_of_week": "Days of the week",
|
||||||
|
"date_range": "Between two dates",
|
||||||
|
"specific_date": "On some dates",
|
||||||
|
"price_group_active": "A price group is on",
|
||||||
|
"order_channel": "Sales point",
|
||||||
|
"min_item_quantity": "At least some of the product",
|
||||||
|
"min_category_qty": "At least some from a category",
|
||||||
|
"min_order_value": "Order total at least"
|
||||||
|
},
|
||||||
|
"fields": {
|
||||||
|
"min_item_quantity": "How many",
|
||||||
|
"min_category_qty": "How many",
|
||||||
|
"min_order_value": "Amount",
|
||||||
|
"category_id": "Category",
|
||||||
|
"price_group_id": "Price group"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"add_percent": "± a percentage",
|
||||||
|
"add_amount": "± an amount",
|
||||||
|
"set": "A new price",
|
||||||
|
"valueLabel": {
|
||||||
|
"add_percent": "Percentage (%)",
|
||||||
|
"add_amount": "Amount (€)",
|
||||||
|
"set": "The new price (€)"
|
||||||
|
},
|
||||||
|
"minusHint": "A minus makes it cheaper (−10 = 10% off); a plus makes it dearer."
|
||||||
|
},
|
||||||
|
"roundings": {
|
||||||
|
"none": "No rounding",
|
||||||
|
"0_05": "To the nearest €0.05",
|
||||||
|
"0_10": "To the nearest €0.10",
|
||||||
|
"0_20": "To the nearest €0.20",
|
||||||
|
"0_50": "To the nearest €0.50",
|
||||||
|
"x_99": "To x.99 (e.g. 4.99)",
|
||||||
|
"x_00": "To a whole euro"
|
||||||
|
},
|
||||||
|
"rules": {
|
||||||
|
"title": "Price rules",
|
||||||
|
"new": "New price rule",
|
||||||
|
"edit": "Edit the price rule",
|
||||||
|
"intro": "A rule changes the price of some products while its conditions hold, for example \"drinks −20% from 17:00 to 19:00 on weekdays\". The counter, the phones, the tablets and online orders use it for what is added from then on.",
|
||||||
|
"none": "No price rules yet",
|
||||||
|
"noneHint": "Make one for a happy hour, a season or a sales point.",
|
||||||
|
"orderHint": "Higher in the list = first. Of the rules that don't stack, only the first that applies to a product counts; the stacking ones then all apply. The final price is rounded to €0.10.",
|
||||||
|
"namePlaceholder": "e.g. Happy hour drinks",
|
||||||
|
"allProducts": "All products",
|
||||||
|
"someProducts_one": "{{count}} group of products",
|
||||||
|
"someProducts_other": "{{count}} groups of products",
|
||||||
|
"conditions_one": "{{count}} condition",
|
||||||
|
"conditions_other": "{{count}} conditions",
|
||||||
|
"always": "always (while it's on)",
|
||||||
|
"stacks": "stacks",
|
||||||
|
"pages": {
|
||||||
|
"what": "Products",
|
||||||
|
"when": "When",
|
||||||
|
"price": "Price"
|
||||||
|
},
|
||||||
|
"scopes": {
|
||||||
|
"global": "Products, categories, tags…",
|
||||||
|
"item": "One product"
|
||||||
|
},
|
||||||
|
"product": "Product",
|
||||||
|
"targetsHint": "The rule changes the products of any of these rows.",
|
||||||
|
"conditionsHint": "All the conditions must hold at the moment a product is added. With none, the rule applies whenever it is on.",
|
||||||
|
"on": "On",
|
||||||
|
"onHint": "Off: it never applies, whatever the conditions.",
|
||||||
|
"rounding": "Rounding",
|
||||||
|
"example": "A product at {{before}} costs {{after}}.",
|
||||||
|
"stack": "Stacks with other rules",
|
||||||
|
"stackTip": "A rule that stacks applies after the first non-stacking rule, on its result (e.g. −10% then −€0.50). One that doesn't stack applies only if no rule above it already did.",
|
||||||
|
"deleteTitle": "Delete the price rule?",
|
||||||
|
"deleteBody": "\"{{name}}\" will no longer change any price. Lines already on orders keep their price.",
|
||||||
|
"problems": {
|
||||||
|
"name": "the name",
|
||||||
|
"product": "the product",
|
||||||
|
"targets": "which products",
|
||||||
|
"conditions": "every condition's values",
|
||||||
|
"value": "the price"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"groups": {
|
||||||
|
"title": "Price groups",
|
||||||
|
"new": "New price group",
|
||||||
|
"edit": "Edit the price group",
|
||||||
|
"intro": "A price group is a switch, like \"Happy hour\" or \"Summer\". Price rules and deals with the condition \"a price group is on\" follow it, so one switch turns several on. Turn it on by hand, or give it a weekly schedule.",
|
||||||
|
"none": "No price groups yet",
|
||||||
|
"noneHint": "Make one to turn several price rules on and off together.",
|
||||||
|
"namePlaceholder": "e.g. Happy hour",
|
||||||
|
"byHand": "On and off by hand",
|
||||||
|
"scheduled": "On {{from}}–{{to}}, {{days}}",
|
||||||
|
"onNow": "On now",
|
||||||
|
"onNowHint": "With a schedule it is also on inside the schedule's hours; outside them this switch decides.",
|
||||||
|
"schedule": "Weekly schedule (optional)",
|
||||||
|
"scheduleHint": "From, to and at least one day, in the venue's time; \"To\" earlier than \"From\" crosses midnight.",
|
||||||
|
"deleteTitle": "Delete the price group?",
|
||||||
|
"deleteBody": "Rules and deals with the condition \"{{name}} is on\" will no longer apply until you change them.",
|
||||||
|
"problems": {
|
||||||
|
"name": "the name",
|
||||||
|
"schedule": "the whole schedule (from, to and a day) or none of it"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"deals": {
|
||||||
|
"title": "Deals",
|
||||||
|
"new": "New deal",
|
||||||
|
"edit": "Edit the deal",
|
||||||
|
"intro": "A deal is offered to the waiter when an order has the right products, e.g. \"3 beers → the 4th free\". The waiter's phone shows it and the waiter accepts or skips it: nothing is applied by itself.",
|
||||||
|
"none": "No deals yet",
|
||||||
|
"noneHint": "e.g. \"Buy 3 beers, get 1 free\".",
|
||||||
|
"namePlaceholder": "e.g. 3 beers + 1 free",
|
||||||
|
"descriptionHint": "The waiter sees it with the offer.",
|
||||||
|
"pages": {
|
||||||
|
"when": "When",
|
||||||
|
"gives": "What it gives"
|
||||||
|
},
|
||||||
|
"targetsHint": "The order must have products of any of these rows.",
|
||||||
|
"conditionsHint": "And, optionally, all of these conditions.",
|
||||||
|
"on": "On",
|
||||||
|
"actions": {
|
||||||
|
"free_item": "A free product",
|
||||||
|
"free_choice": "A free product of the guest's choice",
|
||||||
|
"apply_modifier": "A price rule",
|
||||||
|
"set_price": "A new price",
|
||||||
|
"add_amount": "± an amount",
|
||||||
|
"add_percent": "± a percentage"
|
||||||
|
},
|
||||||
|
"freeProduct": "Free product",
|
||||||
|
"freeFrom": {
|
||||||
|
"item": "From these products",
|
||||||
|
"category": "From these categories",
|
||||||
|
"tag": "With these tags"
|
||||||
|
},
|
||||||
|
"quantity": "How many free",
|
||||||
|
"rule": "Price rule",
|
||||||
|
"ruleHint": "Only rules without conditions (they apply when the waiter accepts the deal).",
|
||||||
|
"noManualRules": "No rule without conditions yet",
|
||||||
|
"givesFree_one": "{{count}} × {{name}} free",
|
||||||
|
"givesFree_other": "{{count}} × {{name}} free",
|
||||||
|
"givesChoice_one": "{{count}} free of their choice",
|
||||||
|
"givesChoice_other": "{{count}} free of their choice",
|
||||||
|
"givesRule": "Rule: {{name}}",
|
||||||
|
"deleteTitle": "Delete the deal?",
|
||||||
|
"deleteBody": "\"{{name}}\" will no longer be offered.",
|
||||||
|
"problems": {
|
||||||
|
"name": "the name",
|
||||||
|
"targets": "which products",
|
||||||
|
"conditions": "every condition's values",
|
||||||
|
"modifier": "the price rule",
|
||||||
|
"freeItem": "the free product",
|
||||||
|
"freeChoice": "what the guest chooses from",
|
||||||
|
"value": "the amount",
|
||||||
|
"quantity": "how many"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"discounts": {
|
||||||
|
"title": "Discounts",
|
||||||
|
"intro": "Who may give discounts and how much. The venue's limits and each person's both apply: the first one reached stops the discount. Past a limit, the person needs a manager's approval on the spot, unless their role may \"give discounts beyond the limits\". An empty box means no limit.",
|
||||||
|
"venue": "The whole venue",
|
||||||
|
"venueHint": "For everyone, on top of each person's limits.",
|
||||||
|
"enabled": "Discounts allowed",
|
||||||
|
"enabledHint": "Off: nobody can give a discount, not even with a manager's approval.",
|
||||||
|
"person": "Each person",
|
||||||
|
"personHint": "Their own limits. Choose a person, change, save.",
|
||||||
|
"who": "Person",
|
||||||
|
"nobody": "No active staff.",
|
||||||
|
"can": "May give discounts",
|
||||||
|
"canHint": "Off: this person can't give any discount by themselves.",
|
||||||
|
"noLimit": "no limit",
|
||||||
|
"items": "items",
|
||||||
|
"badNumber": "A number of 0 or more (whole for items), or empty.",
|
||||||
|
"venueLimits": {
|
||||||
|
"max_total_value_workday": "Most per business day",
|
||||||
|
"max_total_value_workdayHint": "All the discounts of the day, everyone together.",
|
||||||
|
"max_total_value_shift": "Most during a shift",
|
||||||
|
"max_total_value_shiftHint": "All discounts given since the waiter's shift began, everyone together.",
|
||||||
|
"max_items_per_shift": "Most items during a shift",
|
||||||
|
"max_items_per_shiftHint": "Discounted items since the waiter's shift began, everyone together."
|
||||||
|
},
|
||||||
|
"personLimits": {
|
||||||
|
"max_discount_percent": "Most per discount",
|
||||||
|
"max_discount_percentHint": "The highest percentage at a time.",
|
||||||
|
"max_discount_amount": "Most off one item",
|
||||||
|
"max_discount_amountHint": "The most taken off one item's price.",
|
||||||
|
"max_total_value_shift": "Most per shift",
|
||||||
|
"max_total_value_shiftHint": "Their discounts in one shift.",
|
||||||
|
"max_total_value_workday": "Most per business day",
|
||||||
|
"max_total_value_workdayHint": "Their discounts in one day.",
|
||||||
|
"max_items_per_shift": "Items per shift",
|
||||||
|
"max_items_per_shiftHint": "Discounted items in one shift.",
|
||||||
|
"max_items_per_workday": "Items per business day",
|
||||||
|
"max_items_per_workdayHint": "Discounted items in one day.",
|
||||||
|
"max_items_per_order": "Items per order",
|
||||||
|
"max_items_per_orderHint": "Discounted items on one order."
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -903,6 +903,56 @@ try {
|
|||||||
JSON.stringify(orderB2))
|
JSON.stringify(orderB2))
|
||||||
await page.screenshot({ path: path.join(OUT, 'manager-products.png') })
|
await page.screenshot({ path: path.join(OUT, 'manager-products.png') })
|
||||||
|
|
||||||
|
// ── 6.7: pricing — a happy-hour rule made on the page prices a counter sale ──
|
||||||
|
const pg = 'pricing:'
|
||||||
|
const plain = (await api('GET', '/api/products/?all=true', { token: boss }))
|
||||||
|
.find(p => p.lifecycle_status === 'active' && !p.is_service_item && !(p.preference_sets?.length) && p.base_price >= 2)
|
||||||
|
const quote = async () => (await api('POST', '/api/pos/quote', { token: boss, body: { order_type: 'here', lines: [{ product_id: plain.id, quantity: 1 }] } })).lines[0].unit_price
|
||||||
|
const basePrice = await quote()
|
||||||
|
await page.goto(`${APP}/management/pricing`)
|
||||||
|
await page.getByTestId('pricing-rules').waitFor({ timeout: 15_000 })
|
||||||
|
await page.getByTestId('pricing-rule-new').click()
|
||||||
|
await page.getByTestId('pricing-name').fill('E2E happy hour')
|
||||||
|
await page.getByTestId('pricing-target').first().locator('select').selectOption('item')
|
||||||
|
await page.getByTestId('pricing-target-products').getByRole('textbox').fill(plain.name).catch(() => {})
|
||||||
|
await page.locator(`[data-testid="pricing-target-products"] [role="checkbox"][data-name="${plain.name}"]`).first().click()
|
||||||
|
await page.getByTestId('pricing-rule-page-when').click()
|
||||||
|
await page.getByTestId('pricing-condition-add').click()
|
||||||
|
await page.getByTestId('pricing-cond-from').fill('00:00')
|
||||||
|
await page.getByTestId('pricing-cond-to').fill('23:59')
|
||||||
|
await page.getByTestId('pricing-rule-page-price').click()
|
||||||
|
await page.getByTestId('pricing-rule-value').fill('-20')
|
||||||
|
const example = await page.getByTestId('pricing-rule-example').textContent().catch(() => '')
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'manager-pricing-rule.png') })
|
||||||
|
await page.getByTestId('pricing-save').click()
|
||||||
|
const ruleRow = page.locator('[data-testid="pricing-rule"][data-name="E2E happy hour"]')
|
||||||
|
r.check(`${pg} a new price rule (one product, all day, −20%) shows in the list`, await ruleRow.waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)
|
||||||
|
&& (await ruleRow.getByTestId('pricing-rule-action').textContent()).includes('20%'), example)
|
||||||
|
const expected = Math.round(Math.round(basePrice * 0.8 / 0.1) * 0.1 * 100) / 100
|
||||||
|
const discounted = await quote()
|
||||||
|
r.check(`${pg} the done-when: the counter prices the product with it (${basePrice} → ${expected})`, discounted === expected, String(discounted))
|
||||||
|
await ruleRow.getByTestId('pricing-toggle').click()
|
||||||
|
await page.locator('[data-testid="pricing-rule"][data-name="E2E happy hour"][data-active="false"]').waitFor({ timeout: 8000 }).catch(() => {})
|
||||||
|
r.check(`${pg} turned off: back to the menu price`, await quote() === basePrice)
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'manager-pricing.png') })
|
||||||
|
// a price group with a schedule; the venue's discount limit
|
||||||
|
await page.getByTestId('pricing-tab-groups').click()
|
||||||
|
await page.getByTestId('pricing-group-new').click()
|
||||||
|
await page.getByTestId('pricing-name').fill('E2E summer')
|
||||||
|
await page.getByTestId('pricing-save').click()
|
||||||
|
r.check(`${pg} a price group is made`, await page.locator('[data-testid="pricing-group"][data-name="E2E summer"]').waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
|
||||||
|
await page.getByTestId('pricing-tab-discounts').click()
|
||||||
|
await page.getByTestId('limit-max_total_value_workday').first().fill('50,5')
|
||||||
|
await page.getByTestId('pricing-venue-save').click()
|
||||||
|
let limits = null
|
||||||
|
for (let i = 0; i < 20 && limits?.max_total_value_workday !== 50.5; i++) { await sleep(250); limits = await api('GET', '/api/pricing/discount-settings/global', { token: boss }) }
|
||||||
|
r.check(`${pg} the venue's discount limit "50,5" is saved as 50.5`, limits?.max_total_value_workday === 50.5, JSON.stringify(limits))
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'manager-pricing-discounts.png') })
|
||||||
|
await page.getByTestId('limit-max_total_value_workday').first().fill('')
|
||||||
|
await page.getByTestId('pricing-venue-save').click()
|
||||||
|
for (let i = 0; i < 20 && limits?.max_total_value_workday !== null; i++) { await sleep(250); limits = await api('GET', '/api/pricing/discount-settings/global', { token: boss }) }
|
||||||
|
r.check(`${pg} emptied: no limit`, limits?.max_total_value_workday === null, JSON.stringify(limits))
|
||||||
|
|
||||||
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
|
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
|
||||||
await page.goto(`${APP}/online-orders`)
|
await page.goto(`${APP}/online-orders`)
|
||||||
await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {})
|
await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {})
|
||||||
|
|||||||
Reference in New Issue
Block a user