diff --git a/.env.example b/.env.example index c70d481e..eebddbca 100644 --- a/.env.example +++ b/.env.example @@ -60,6 +60,13 @@ PAYKIT_KIT_SECRET= MERQO_BASE_URL= MERQO_CUSTOMER_SECRET= +# Optional "your order is ready" email, sent through Resend's REST API when a +# customer ticked the opt-in box at checkout. RESEND_FROM is the sender, for +# example "Merqo " (mail.merqo.io is verified in Resend). +# Server-only. If either is unset the send is skipped and everything else works. +RESEND_API_KEY= +RESEND_FROM= + # Bearer secret for POST /api/printkit/print-status — printkit calling INTO # qkit with a print job's terminal status. A plain shared secret (no # kit_slug prefix): this endpoint has exactly one caller (printkit), unlike diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bbf4c03..885cbaaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,48 @@ All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +## [0.10.0] - 2026-12-02 + +### Changed + +- Discount codes: cancelling an order now gives the use back to the exact code it redeemed (matched by id), so deleting a code and creating a new one with the same text no longer lets old cancelled orders reduce the new code's uses. + +## [0.9.0] - 2026-12-02 + +### Changed + +- Account menu: Text size is now a submenu under a Preferences label ("Text size · 100%") with a preset list from 75% to 200%, replacing the inline A-/100%/A+ buttons. Re-pins `@merqo/ui` to v0.68.0. + +## [0.8.0] - 2026-12-02 + +### Added + +- Order-ready email: at checkout a customer can tick "Email me when my order is ready" and give an address. When the vendor marks the order Ready they get one email with the booth name, order number and a link to their order page. The address is kept only for that, in a table no customer or board view can read, and is deleted once the email is sent or the order completes or is cancelled. Available on every plan; needs `RESEND_API_KEY` and `RESEND_FROM` (skipped when unset) and migration 0131. Walk-up orders never get it. + +### Changed + +- Live board: defaults to two columns, Incoming and Preparing. Ready orders sit at the bottom of Preparing with their Picked up action until collected, and the phone switcher drops its Ready tab. Vendors can bring the Ready column back with "Show a Ready column" in Settings. The Settings "Unpaid orders" card is now "Board display" with both switches and a colour key for the two blues. Needs migration `0133_board_settings_show_ready_column.sql` applied to save the new setting; until then the board stays on two columns. + +## [0.7.1] - 2026-12-02 + +### Changed + +- Sales and menu CSV downloads use the shared `downloadCsv`, so the files now start with a UTF-8 BOM and Excel reads non-ASCII text correctly. The menu CSV and recent-orders list use the shared `csvCell`, `readStored` and `writeStored` instead of local copies. + +## [0.7.0] - 2026-12-01 + +### Added + +- Minimum order quantity: vendors can set a minimum per menu item ("Minimum per order" in the menu editor, any plan). Customers adding the item start at the minimum, going below it removes the item, and the order is refused below it on the server. The minimum can be at most 20. An item whose minimum is above its stock or the per-order limit shows as unavailable, and the editor will not save such a minimum. Migration 0130 adds the check (apply before deploying). + +## [0.6.2] - 2026-12-01 + +### Changed + +- FAQ: the cost section is now "Cost and plans" and says qkit finished its pilot in Sep 2026 and is open for founding vendors, with charging from 1 January 2027. Paykit answers now say it is deployed and in early access instead of "still in build". + ## [0.6.1] - 2026-12-01 ### Security @@ -12,8 +54,6 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.6.0] - 2026-12-01 -## [0.6.0] - 2026-12-01 - ### Added - Discount codes: paid vendors (Pro or a running Event Pass) create, switch off and delete percent or fixed codes with an optional last day and use cap at Dashboard > Codes. Customers enter a code at checkout; the order total, the order page and the live board card show the discount, and the server re-checks the code when the order is placed. Free vendors see an upgrade prompt. A cancelled order (including an unpaid one swept after its payment window) gives its code use back. Adds a service-role-only `issue_reward_code` function for other kits (migration 0129, apply before deploying). @@ -21,6 +61,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Changed +- Booth edit: More settings is now two balanced columns, with Order flow, Limits, Printing and Pickup on the left and Menu, Payment and Social links on the right, instead of a short left column and a long right one. - The account menu now has a Text size row (A-, 100%, A+) and the text size control comes from `@merqo/ui` v0.67.0 instead of a local copy. It shares the board's saved value, so every vendor's existing text size is kept. - Demo recorder `options` scene now replaces the onboarding sample menu with the Milk and Sugar items, so the clip shows the option choices (scripts only, no app change). - Live board: the ticket is now compact at the default text size (smaller order number, tighter padding and gaps, 44px buttons kept), and on wide screens each status column fits more than one ticket per row. The A-/A+ text size control is unchanged. diff --git a/README.md b/README.md index 903b2296..30ca3438 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,14 @@ Next.js 16 App Router, React 19, strict TypeScript, Tailwind v4, shadcn/Radix, React Hook Form, Zod, Supabase Auth/Postgres/Realtime, and the shared `@merqo/ui` (pinned at v0.65.1) package. Use `package.json` and `pnpm-lock.yaml` for exact versions. The app runs Next.js 16.4.6, which clears GHSA-mfr8-8qww-v76h. +CSV exports go through the shared `downloadCsv`/`csvCell`, and the recent-orders list uses the shared `readStored`/`writeStored`. Loading states use the shared `Skeleton` primitive and `ListSkeleton` from `@merqo/ui`, and every vendor-facing control grows to a 44px hit area under `pointer-coarse`. The shared UI dependency is pinned to a reviewed immutable Git commit. Its exact archive identity is approved for package preparation in `pnpm-workspace.yaml`; update that permission alongside the dependency and lockfile when adopting a new shared UI revision. The current revision is the -commit `8d2da3abcb4e5c3bab2b3a3482c740797e2d5c03` (`v0.67.0`), which supplies the `ScreenSizeControl` (the board and queue display text size, also the account menu's Text size row), the `PageHeader` (the dashboard page titles, including Live orders, Menu, the booth forms and the User guide), `useLeaveGuard` (the unsaved-changes prompt), the `RadioGroup` behind the customer screen's booth picker, `SegmentedControl`, `StatTile card`, `ConfirmDialog` and `TierChip` that qkit now uses in place of local copies, on top of the User guide nav icon and `tierLabel` (the stored `qkit` tier reads "Pro") from `v0.41.0`. Since `v0.39.0` it has the `PricingLadder` the plan page renders. +commit `5a08fd875ad6c96f096fbcb4d56ed50eb238f33e` (`v0.68.0`), which supplies the `ScreenSizeControl` (the board and queue display text size, also the account menu Text size submenu), the `PageHeader` (the dashboard page titles, including Live orders, Menu, the booth forms and the User guide), `useLeaveGuard` (the unsaved-changes prompt), the `RadioGroup` behind the customer screen's booth picker, `SegmentedControl`, `StatTile card`, `ConfirmDialog` and `TierChip` that qkit now uses in place of local copies, on top of the User guide nav icon and `tierLabel` (the stored `qkit` tier reads "Pro") from `v0.41.0`. Since `v0.39.0` it has the `PricingLadder` the plan page renders. Since `v0.34.2` it treats a Next.js `redirect()` from a server action as navigation, so the dashboard's Sign out no longer flashes "NEXT_REDIRECT". Since `v0.34.0` it has `DataCollectionNotice`, the PDPA diff --git a/e2e/vendor-fulfillment.spec.ts b/e2e/vendor-fulfillment.spec.ts index c84b559c..84d9966f 100644 --- a/e2e/vendor-fulfillment.spec.ts +++ b/e2e/vendor-fulfillment.spec.ts @@ -62,6 +62,18 @@ test("vendor starts, readies and hands over a customer's order", async ({ await expect(markReady).toBeVisible({ timeout: 20_000 }); await markReady.click(); + // The board defaults to two columns: the ready order waits at the bottom of + // Preparing, still offering its Picked up action, and no Ready column exists. + await expect(board.getByRole("heading", { name: /^Ready \(/ })).toHaveCount( + 0, + ); + await expect( + board + .locator("section") + .filter({ has: board.getByRole("heading", { name: /^Preparing \(/ }) }) + .getByRole("button", { name: `More actions for order #${number}` }), + ).toBeVisible({ timeout: 20_000 }); + // The customer's page polls; it turns to ready on its own. await expect(customer.getByText("It's ready").first()).toBeVisible({ timeout: 30_000, diff --git a/package.json b/package.json index 9c2605d2..55f60c1f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "qkit", - "version": "0.6.1", + "version": "0.10.0", "private": true, "packageManager": "pnpm@11.28.5", "engines": { @@ -29,7 +29,7 @@ "@dnd-kit/sortable": "10.0.0", "@dnd-kit/utilities": "3.2.2", "@hookform/resolvers": "5.2.2", - "@merqo/ui": "github:merqo-io/merqo-ui#8d2da3abcb4e5c3bab2b3a3482c740797e2d5c03", + "@merqo/ui": "github:merqo-io/merqo-ui#5a08fd875ad6c96f096fbcb4d56ed50eb238f33e", "@supabase/ssr": "^0.10.3", "@supabase/supabase-js": "2.107.0", "class-variance-authority": "^0.7.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 340d3ad3..9d4a220e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -39,8 +39,8 @@ importers: specifier: 5.2.2 version: 5.2.2(react-hook-form@7.77.0(react@19.2.7)) '@merqo/ui': - specifier: github:merqo-io/merqo-ui#8d2da3abcb4e5c3bab2b3a3482c740797e2d5c03 - version: https://codeload.github.com/merqo-io/merqo-ui/tar.gz/8d2da3abcb4e5c3bab2b3a3482c740797e2d5c03(@eslint-community/eslint-plugin-eslint-comments@4.8.1(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)))(@playwright/test@1.61.1)(@supabase/ssr@0.10.3(@supabase/supabase-js@2.107.0))(@supabase/supabase-js@2.107.0)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(eslint-plugin-sonarjs@4.2.2(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)))(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))(next-themes@0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(next@16.4.6(@babel/core@7.29.7(supports-color@7.2.0))(@playwright/test@1.61.1)(@types/node@24.13.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(radix-ui@1.4.3(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(sonner@1.7.4(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(supports-color@7.2.0)(tailwindcss@4.3.0)(zod@4.6.6) + specifier: github:merqo-io/merqo-ui#5a08fd875ad6c96f096fbcb4d56ed50eb238f33e + version: https://codeload.github.com/merqo-io/merqo-ui/tar.gz/5a08fd875ad6c96f096fbcb4d56ed50eb238f33e(@eslint-community/eslint-plugin-eslint-comments@4.8.1(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)))(@playwright/test@1.61.1)(@supabase/ssr@0.10.3(@supabase/supabase-js@2.107.0))(@supabase/supabase-js@2.107.0)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(eslint-plugin-sonarjs@4.2.2(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)))(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))(next-themes@0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(next@16.4.6(@babel/core@7.29.7(supports-color@7.2.0))(@playwright/test@1.61.1)(@types/node@24.13.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(radix-ui@1.4.3(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(sonner@1.7.4(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(supports-color@7.2.0)(tailwindcss@4.3.0)(zod@4.6.6) '@supabase/ssr': specifier: ^0.10.3 version: 0.10.3(@supabase/supabase-js@2.107.0) @@ -992,9 +992,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} - '@merqo/ui@https://codeload.github.com/merqo-io/merqo-ui/tar.gz/8d2da3abcb4e5c3bab2b3a3482c740797e2d5c03': - resolution: {gitHosted: true, integrity: sha512-ng6yGVBmggWX5yqAVVqFUucSWNJwRgjhfNp+YaigTZk0U286GJuOmNLWuBca0ZKjjSR2Qs/zjKWx/IrDYUumfA==, tarball: https://codeload.github.com/merqo-io/merqo-ui/tar.gz/8d2da3abcb4e5c3bab2b3a3482c740797e2d5c03} - version: 0.67.0 + '@merqo/ui@https://codeload.github.com/merqo-io/merqo-ui/tar.gz/5a08fd875ad6c96f096fbcb4d56ed50eb238f33e': + resolution: {gitHosted: true, integrity: sha512-VQhYGj8jL65lLuWUAgLjZpy4PlzzLW1+uCs9kUJ1tphR910N9aZlsEPpnVlyQwg1H1XHyYG8w0UqZXGiQXiMLQ==, tarball: https://codeload.github.com/merqo-io/merqo-ui/tar.gz/5a08fd875ad6c96f096fbcb4d56ed50eb238f33e} + version: 0.68.0 engines: {node: '>=24'} peerDependencies: '@eslint-community/eslint-plugin-eslint-comments': '>=4.8.1' @@ -5708,7 +5708,7 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 - '@merqo/ui@https://codeload.github.com/merqo-io/merqo-ui/tar.gz/8d2da3abcb4e5c3bab2b3a3482c740797e2d5c03(@eslint-community/eslint-plugin-eslint-comments@4.8.1(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)))(@playwright/test@1.61.1)(@supabase/ssr@0.10.3(@supabase/supabase-js@2.107.0))(@supabase/supabase-js@2.107.0)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(eslint-plugin-sonarjs@4.2.2(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)))(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))(next-themes@0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(next@16.4.6(@babel/core@7.29.7(supports-color@7.2.0))(@playwright/test@1.61.1)(@types/node@24.13.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(radix-ui@1.4.3(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(sonner@1.7.4(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(supports-color@7.2.0)(tailwindcss@4.3.0)(zod@4.6.6)': + '@merqo/ui@https://codeload.github.com/merqo-io/merqo-ui/tar.gz/5a08fd875ad6c96f096fbcb4d56ed50eb238f33e(@eslint-community/eslint-plugin-eslint-comments@4.8.1(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)))(@playwright/test@1.61.1)(@supabase/ssr@0.10.3(@supabase/supabase-js@2.107.0))(@supabase/supabase-js@2.107.0)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(eslint-plugin-sonarjs@4.2.2(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0)))(eslint@9.39.4(jiti@2.7.0)(supports-color@7.2.0))(next-themes@0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(next@16.4.6(@babel/core@7.29.7(supports-color@7.2.0))(@playwright/test@1.61.1)(@types/node@24.13.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(radix-ui@1.4.3(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(sonner@1.7.4(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(supports-color@7.2.0)(tailwindcss@4.3.0)(zod@4.6.6)': dependencies: '@icons-pack/react-simple-icons': 13.13.0(react@19.2.7) class-variance-authority: 0.7.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 96e62619..d66642fa 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -3,7 +3,7 @@ allowBuilds: sharp: true supabase: true unrs-resolver: true - "@merqo/ui@https://codeload.github.com/merqo-io/merqo-ui/tar.gz/8d2da3abcb4e5c3bab2b3a3482c740797e2d5c03": true + "@merqo/ui@https://codeload.github.com/merqo-io/merqo-ui/tar.gz/5a08fd875ad6c96f096fbcb4d56ed50eb238f33e": true # Scoped overrides retain patched floors and compatible major versions. overrides: diff --git a/src/app/dashboard/README.md b/src/app/dashboard/README.md index 8738a13a..788b1769 100644 --- a/src/app/dashboard/README.md +++ b/src/app/dashboard/README.md @@ -10,8 +10,8 @@ The authenticated vendor area — a shared header/nav shell wrapping the live or - `booths/` — booth list, create/edit form, and printable QR-code sub-routes. - `completed/` — paginated history of the vendor's completed orders (own README). -- `dashboard-nav.dom.test.tsx` — RTL/jsdom tests for `DashboardNav`: asserts the inline nav links (Orders/Completed/Booths/Stats, no Plan link), the account-menu item order (Switch products, Profile, Settings, Plan, Get help, Feedback, User guide, Theme, Text size, then Sign out), that the "Switch products" submenu lists loopkit/paykit/stockkit each linking to that kit's live `*.merqo.io` URL, the `data-tour="nav-account"` trigger stamp, the tier badge, `aria-current` on the active link, that the account-menu subtitle shows the vendor's real name (not a generic "Vendor account" label) both on the trigger and in the open dropdown, and shows whatever `accountLabel` it is given with no local fallback (`layout.dom.test.tsx` covers the stall name and the empty-name fallback to the shared chain), and — via mocked `submitFeedback`/`submitSupportMessage` — that the Feedback/Get-help sheets' throw-adapters call those actions with the right fields (`nps`/`message` for feedback, `category`/`body` for support) and that a `{success:false}` result surfaces the sheet's own inline error rather than failing silently. -- `dashboard-nav.tsx` — `DashboardNav({ signOut, accountLabel, avatarUrl, tier })` client component: the sticky header row, composed from `@merqo/ui`'s `DashboardNav`/`AccountMenu` (burger, inline `Orders`/`Completed`/`Booths`/`Stats` links, account dropdown, and Feedback/Get-help `Sheet` chrome all live in the shared package now). This file supplies qkit-specific pieces only: no `LinkComponent` prop (`AppLinkProvider` in `src/components/layout/providers.tsx` hands `next/link` to the shared nav links and its composed `AccountMenu`, so route changes are client-side), the `wordmark` (the "QKit" link), the `LINKS`/`isActive`/`tourAnchor` wiring passed as `navLinks`/`isActiveHref`/`tourAnchor`, the `TierChip` from `@merqo/ui` (passed via the `tierBadge` slot, shown next to the account label, which `layout.tsx` computes with `@merqo/ui`'s `accountLabel(user, vendor.name)` and which is used as both the trigger name and subtitle with no local fallback, so it matches the landing nav), `kitLocalSettingsHref="/dashboard/settings"`, `textSizeKey="qkit:scale:board"` (the account menu's Text size row shares the board header's key so one saved value drives both and only one root font size is applied), `switchKits={getSwitchKits("qkit")}` (`@merqo/ui`'s centralized `KIT_FAMILY` registry, filtered to the other three live kits — loopkit/paykit/stockkit's live URLs, qkit itself excluded — so the account menu's "Switch products" submenu can send a signed-in vendor to another kit's dashboard; SSO via the shared `.merqo.io` cookie already signs them in there, this is purely in-product navigation, no live per-vendor filtering by design; a future new kit only needs adding to `@merqo/ui`'s registry, not to every kit's own nav wrapper), and thin throw-adapting wrappers around `submitFeedback`/`submitSupportMessage` — both return a `{success, error}` result rather than throwing, but `@merqo/ui`'s `onSubmit` contract requires a promise that rejects on failure so the shared sheet's own inline error UI can show it; the support adapter also renames the sheet's `message` field to `submitSupportMessage`'s `body`. `FeedbackForm` (`@/components`) is unused by this file now but remains in the tree, still used standalone by the customer star-rating flow and the non-Sheet `dashboard/feedback/` page; the old local `SupportForm` (this file's previous Sheet body) was deleted once the Sheet chrome moved into `@merqo/ui`. +- `dashboard-nav.dom.test.tsx` — RTL/jsdom tests for `DashboardNav`: asserts the inline nav links (Orders/Completed/Booths/Stats, no Plan link), the account-menu item order (Switch products, Profile, Settings, Plan, Get help, Feedback, User guide, Theme, Text size · 100%, then Sign out), that the "Switch products" submenu lists loopkit/paykit/stockkit each linking to that kit's live `*.merqo.io` URL, the `data-tour="nav-account"` trigger stamp, the tier badge, `aria-current` on the active link, that the account-menu subtitle shows the vendor's real name (not a generic "Vendor account" label) both on the trigger and in the open dropdown, and shows whatever `accountLabel` it is given with no local fallback (`layout.dom.test.tsx` covers the stall name and the empty-name fallback to the shared chain), and — via mocked `submitFeedback`/`submitSupportMessage` — that the Feedback/Get-help sheets' throw-adapters call those actions with the right fields (`nps`/`message` for feedback, `category`/`body` for support) and that a `{success:false}` result surfaces the sheet's own inline error rather than failing silently. +- `dashboard-nav.tsx` — `DashboardNav({ signOut, accountLabel, avatarUrl, tier })` client component: the sticky header row, composed from `@merqo/ui`'s `DashboardNav`/`AccountMenu` (burger, inline `Orders`/`Completed`/`Booths`/`Stats` links, account dropdown, and Feedback/Get-help `Sheet` chrome all live in the shared package now). This file supplies qkit-specific pieces only: no `LinkComponent` prop (`AppLinkProvider` in `src/components/layout/providers.tsx` hands `next/link` to the shared nav links and its composed `AccountMenu`, so route changes are client-side), the `wordmark` (the "QKit" link), the `LINKS`/`isActive`/`tourAnchor` wiring passed as `navLinks`/`isActiveHref`/`tourAnchor`, the `TierChip` from `@merqo/ui` (passed via the `tierBadge` slot, shown next to the account label, which `layout.tsx` computes with `@merqo/ui`'s `accountLabel(user, vendor.name)` and which is used as both the trigger name and subtitle with no local fallback, so it matches the landing nav), `kitLocalSettingsHref="/dashboard/settings"`, `textSizeKey="qkit:scale:board"` (the account menu Text size submenu (under Preferences) shares the board header's key so one saved value drives both and only one root font size is applied), `switchKits={getSwitchKits("qkit")}` (`@merqo/ui`'s centralized `KIT_FAMILY` registry, filtered to the other three live kits — loopkit/paykit/stockkit's live URLs, qkit itself excluded — so the account menu's "Switch products" submenu can send a signed-in vendor to another kit's dashboard; SSO via the shared `.merqo.io` cookie already signs them in there, this is purely in-product navigation, no live per-vendor filtering by design; a future new kit only needs adding to `@merqo/ui`'s registry, not to every kit's own nav wrapper), and thin throw-adapting wrappers around `submitFeedback`/`submitSupportMessage` — both return a `{success, error}` result rather than throwing, but `@merqo/ui`'s `onSubmit` contract requires a promise that rejects on failure so the shared sheet's own inline error UI can show it; the support adapter also renames the sheet's `message` field to `submitSupportMessage`'s `body`. `FeedbackForm` (`@/components`) is unused by this file now but remains in the tree, still used standalone by the customer star-rating flow and the non-Sheet `dashboard/feedback/` page; the old local `SupportForm` (this file's previous Sheet body) was deleted once the Sheet chrome moved into `@merqo/ui`. - `feedback/` — vendor-facing "share feedback about qkit" page. - `help/` — the vendor user guide at `/dashboard/help` (own README); article text lives in `src/content/help`. - `layout.dom.test.tsx` — RTL test that awaits `DashboardLayout({ children })` directly (a plain async function, no RSC machinery of its own) and renders the returned element tree, asserting exactly one `
` landmark — the case a ``-only test can't see, since `@merqo/ui`'s `DashboardNav` now renders its own `
` internally and `layout.tsx` must not wrap it in a second one. A third test asserts the layout ends with the footer (no sign-in link, `print:hidden`). A second test asserts the structural precondition for sticky positioning: the header's immediate parent carries both `contents` and `print:hidden` classes (jsdom doesn't compute layout, so it can't prove the header actually sticks on scroll, but it can prove the wrapper isn't a plain box that would break the containing block). @@ -58,10 +58,10 @@ The authenticated vendor area — a shared header/nav shell wrapping the live or - `payment-evidence-actions.test.ts` — who may read (bad id, no session, order or booth RLS hides, an admin on another vendor's order, a transaction of another vendor), the legacy path (paykit never asked), and the paykit path (link and signals, the three duplicate cases, paykit unreachable or without a transaction). On both paths a duplicate from today is named by its board number (`0024` shown as `001`), and one from an earlier day by its permanent number and day. - `proof-actions.test.ts` — vitest suite (mocked Supabase client + storage) for `getProofPhotoUrl`'s invalid-id/no-path/signed-url-error branches and its happy path, and `findDuplicateProofOrder`'s invalid-id/no-hash/no-match/match branches. - `proof-actions.ts` — service-scoped (RLS-gated, not service-role) reads for the payment-proof review UI: `getProofPhotoUrl(orderId)` mints a short-lived (300s) signed URL for an order's `payment_proof_path` in the private `payment-proofs` bucket (migration 0087) — never a public URL, since a stranger's bank-app screenshot has no business being publicly reachable; `findDuplicateProofOrder(orderId)` looks up another order sharing the same `payment_proof_hash` for the duplicate-photo hint and returns its `booth_id`, `order_number` and `created_at`, so the caller can name it by its board number (`payment-proof-viewer.tsx` in `@/components`), scoped to the caller's own vendor entirely by the existing RLS `orders_vendor_select` policy rather than an explicit vendor-id check here. -- `realtime-order-board.tsx` — The live vendor board subscribes to owned booth orders, presents Incoming, Preparing and Ready columns, and supports booth filtering, pause controls and guarded batch readiness and pickup. Each batch action supplies its expected fulfillment status; rejected actions are counted without advancing stale rows or hiding partial failures. The Incoming column offers "Start all" for two or more orders that need no check first: not one with unconfirmed payment, and none at a booth that waits for the customer to arrive. The Accepted column always has its header, which carries "Mark all N ready" for two or more orders still being made (pick-up stays one at a time, or through Select) and the Select button. Terminal cards remain visible during fulfillment undo. New-order alerts, desktop notifications, tickets and the walk-up dialog use the same daily display number. A walk-up this board placed through its own dialog raises no new-order alert here (the dialog reports each placement through `onPlacing`/`onPlaced`; an INSERT that lands first is held until the number is known); other devices still alert. At a booth that waits for arrival, a pending ticket's badge reads "Not here yet". The event dialog auto-opens only for an active event booth. Board state does not confirm payment; settlement uses explicit Paykit-backed actions. +- `realtime-order-board.tsx` — The live vendor board subscribes to owned booth orders, presents Incoming and Preparing columns (plus Ready when the `show_ready_column` setting is on; otherwise ready orders sit at the bottom of Preparing), and supports booth filtering, pause controls and guarded batch readiness and pickup. Each batch action supplies its expected fulfillment status; rejected actions are counted without advancing stale rows or hiding partial failures. The Incoming column offers "Start all" for two or more orders that need no check first: not one with unconfirmed payment, and none at a booth that waits for the customer to arrive. The Accepted column always has its header, which carries "Mark all N ready" for two or more orders still being made (pick-up stays one at a time, or through Select) and the Select button. Terminal cards remain visible during fulfillment undo. New-order alerts, desktop notifications, tickets and the walk-up dialog use the same daily display number. A walk-up this board placed through its own dialog raises no new-order alert here (the dialog reports each placement through `onPlacing`/`onPlaced`; an INSERT that lands first is held until the number is known); other devices still alert. At a booth that waits for arrival, a pending ticket's badge reads "Not here yet". The event dialog auto-opens only for an active event booth. Board state does not confirm payment; settlement uses explicit Paykit-backed actions. - `board-header.tsx` — `BoardHeader`: the shared `PageHeader` title with the controls as its action, active-booth pill, Booths and New order buttons, and the board's shared `ScreenSizeControl` (`qkit:scale:board`, the same key the account menu's Text size row uses so the two stay in step). - `board-filter-bar.tsx` — `BoardFilterBar`: the booth filter chips and the earliest/latest sort toggle. -- `board-columns.tsx` — `BoardColumns` (Incoming, Preparing and Ready with their batch actions: Start all on Incoming, Mark all ready and Select on Preparing, Select on Ready) and `BoardSelectionBar`. +- `board-columns.tsx` — `BoardColumns` (Incoming and Preparing, plus Ready when `showReadyColumn` is true; off by default, with ready orders last in Preparing and Select covering both; their batch actions: Start all on Incoming, Mark all ready and Select on Preparing, Select on Ready) and `BoardSelectionBar`. - `board-card-renderer.tsx` — `renderBoardCard`: builds one `OrderCard` from the board's shared state. - `board-booth-dialog.tsx` — `BoothStatusDialog`: the multi-booth pause/resume dialog. - `setup-checklist-data.ts` — server helpers for the checklist: `checklistBoothOf` (the earliest booth as plain props) and `vendorHasOrders` (the board's unfinished orders, else a one-row check across all orders). @@ -74,12 +74,12 @@ The authenticated vendor area — a shared header/nav shell wrapping the live or - `use-booth-active.ts` — optimistic booth active flags and the active count. - `use-board-lifecycle.ts` — undo-window ids, the walk-up auto-open on load and the periodic order sweeps. - `use-board-numbering.ts` — the day's order-number baselines and the number shown for a new order. -- `board-sections.tsx` — the board's three columns and what frames them: `OrderSection` (one column, with an optional control in its header), `SectionSwitcher` (the Incoming/Preparing/Ready switch shown below `lg`) and `LoadErrorBanner`. Moved out of `realtime-order-board.tsx` unchanged. On touch screens (`pointer-coarse`) the column header row is at least 44px tall. +- `board-sections.tsx` — the board's three columns and what frames them: `OrderSection` (one column, with an optional control in its header), `SectionSwitcher` (the Incoming/Preparing switch shown below `lg`, with a Ready tab only when the Ready column is on) and `LoadErrorBanner`. Moved out of `realtime-order-board.tsx` unchanged. On touch screens (`pointer-coarse`) the column header row is at least 44px tall. - `board-sections.dom.test.tsx` — the column header row keeps its 44px touch height. - `board-booths.tsx` — the booth controls in the board's header: the `BoothView` and `BoothFilter` types, `BoothToggle` (reads "Not serving" with an "Over plan limit" link to the booths page for an active booth beyond the plan's serve limit, via `BoothView.over_limit`), `BoothRow` (with one pill combining the cup count and Start new service for a booth with a daily limit, or a label-only pill for a booth with just per-item Sold-out limits), `resolveBoothFilter` and `boothFilterLabel`. Moved out unchanged. - `start-service-button.tsx` — `StartServiceButton`: "Start new service" behind a confirmation naming the booth, which calls `startNewService` and toasts the result. A labelled pill (`compact`, optionally with the day's count) in the board's booth row, labelled in the booth edit page's Limits card. - `board-batch.tsx` — batch actions: `SelectButton` (in the Preparing and Ready column headers), `SelectionBar` (select mode's Cancel / Select all / Mark N, a fixed bar over the bottom of the board that says "Pick orders" while nothing is ticked; its `data-selection-bar` attribute is the hook `globals.css` uses to hide the floating tour replay button while the bar is open), `useBatchSelection` (advance many, with the toast's Undo), `isBatchable` and `BATCH_BUTTON`. -- `board-columns.dom.test.tsx` — RTL tests for the Ready column header: Select appears only while an order is waiting for pickup, not for picked-up orders in their undo window. +- `board-columns.dom.test.tsx` — RTL tests for both column modes and the Ready column header: Select appears only while an order is waiting for pickup, not for picked-up orders in their undo window. - `board-derive.test.ts` — unit tests for `groupVisibleOrders`: the Incoming/Preparing/Ready split and per-column batch ids. - `realtime-order-board.dom.test.tsx` — RTL tests: the earliest/latest sort toggle, the daily order-number reset (real number when the setting is off, the display-rank number when a baseline is supplied, and the board's own derived baseline when the setting is on but the server sent none, per booth), the per-booth `BoothToggle` (queried by its own state-carrying `aria-label`, e.g. "Kopi Corner is open. Tap to pause." — inline for a single booth, gated behind the "Booths" dialog for 2+, stays reachable for a paused/empty booth, toggles + reverts on failure, and — the `visibleBooths` regression — stays selectable and paired with a still-present filter `Select` after pausing the exact booth the board is filtered to), the walk-up button (opens the dialog for the sole active booth and fetches its menu; shows a no-booths state instead when nothing's active), event-mode auto-open (a sole `walkup_default: true` booth opens the walk-up dialog with no click needed; an ordinary QR booth never does), and the "No booths yet" empty state's two CTAs (`/dashboard/booths/new` and `/dashboard/booths/new?mode=event`). - `settings/` — board-preferences page: aging/overdue thresholds, the tap-undo @@ -115,6 +115,7 @@ Plan badge and tier labels come from `tierLabel` in `@merqo/ui` in client files Select all targets eligible preparing orders. While tickets are being ticked the selection bar floats over the bottom of the screen (clear of a phone's home indicator) and the board gets room under its last ticket, a tap anywhere on a ticket ticks it (its own buttons still do their own job), and the toast for a batch carries an Undo that walks every moved order back one step with `revertOrderAdvance`. On a phone the Incoming/Accepted switch is a pair of 44px pressed-state buttons, and the settings gear is left to the navigation. The customer-screen dialog opens the public booth display. Walk-up entry places the order before its optional payment step; collecting payment calls explicit Paykit-backed confirmation. Stale-order sweeps update fulfillment state independently of payment settlement. +- Board settings gain `show_ready_column` (default false, migration 0133): opt-in Ready column; two columns otherwise. - Board settings gain `show_unpaid_border` (default true, migration 0128): blue border on open unpaid order cards, toggled in dashboard settings. - `discounts/` is the vendor discount codes page (`page.tsx`, `discount-codes-manager.tsx`, `actions.ts`): paid vendors create, switch off and delete codes; free vendors see an upgrade prompt. Linked from the dashboard nav as "Codes". diff --git a/src/app/dashboard/board-columns.dom.test.tsx b/src/app/dashboard/board-columns.dom.test.tsx index c4f6d15c..41396f87 100644 --- a/src/app/dashboard/board-columns.dom.test.tsx +++ b/src/app/dashboard/board-columns.dom.test.tsx @@ -34,6 +34,7 @@ function renderColumns(controls: BatchControls) { incoming={[]} preparing={[]} ready={[completed]} + showReadyColumn phoneSection="ready" onPhoneSectionChange={vi.fn()} batch={controls} @@ -61,3 +62,48 @@ describe("BoardColumns Ready header", () => { ).toBeInTheDocument(); }); }); + +describe("BoardColumns without a Ready column", () => { + afterEach(cleanup); + + const making = { id: "m", status: "preparing" } as unknown as BoardOrder; + const waiting = { id: "r", status: "ready" } as unknown as BoardOrder; + + function renderTwo() { + render( +
card {o.id}
} + />, + { wrapper: TooltipProvider }, + ); + } + + it("shows only Incoming and Preparing, ready orders last in Preparing", () => { + renderTwo(); + expect( + screen.queryByRole("heading", { name: /^ready/i }), + ).not.toBeInTheDocument(); + expect( + screen.getByRole("heading", { name: "Preparing (2)" }), + ).toBeInTheDocument(); + const cards = screen.getAllByText(/^card /).map((n) => n.textContent); + expect(cards).toEqual(["card m", "card r"]); + }); + + it("drops the Ready tab and counts ready orders under Preparing", () => { + renderTwo(); + expect( + screen.queryByRole("button", { name: /^ready \(/i }), + ).not.toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Preparing (2)", pressed: true }), + ).toBeInTheDocument(); + }); +}); diff --git a/src/app/dashboard/board-columns.tsx b/src/app/dashboard/board-columns.tsx index 0407dbdd..a40ea4ae 100644 --- a/src/app/dashboard/board-columns.tsx +++ b/src/app/dashboard/board-columns.tsx @@ -33,8 +33,16 @@ export interface BatchControls { * tap, and Select. Both step aside while Select is on; its bar has the * controls then. */ -function PreparingAction({ batch }: { batch: BatchControls }) { +function PreparingAction({ + batch, + includesReady, +}: { + batch: BatchControls; + includesReady: boolean; +}) { const { preparingIds, advancing, paymentById } = batch; + const canSelect = + preparingIds.length > 0 || (includesReady && batch.readyIds.length > 0); return (
{preparingIds.length > 1 && ( @@ -49,9 +57,7 @@ function PreparingAction({ batch }: { batch: BatchControls }) { Mark all {preparingIds.length} ready )} - {preparingIds.length > 0 && ( - - )} + {canSelect && }
); } @@ -76,6 +82,7 @@ export function BoardColumns({ incoming, preparing, ready, + showReadyColumn = false, phoneSection, onPhoneSectionChange, batch, @@ -84,24 +91,37 @@ export function BoardColumns({ incoming: BoardOrder[]; preparing: BoardOrder[]; ready: BoardOrder[]; + showReadyColumn?: boolean; phoneSection: PhoneSection; onPhoneSectionChange: (section: PhoneSection) => void; batch: BatchControls; renderCard: (order: BoardOrder) => ReactNode; }) { - const hide = (section: PhoneSection) => phoneSection !== section; + const activeSection = + !showReadyColumn && phoneSection === "ready" ? "preparing" : phoneSection; + const hide = (section: PhoneSection) => activeSection !== section; + const preparingOrders = showReadyColumn + ? preparing + : [...preparing, ...ready]; return ( <> -
+
} - empty={Nothing being made} - renderCard={renderCard} - /> - 0 && ( - + !batch.selectMode && ( + ) } - empty={Nothing waiting for pickup} + empty={Nothing being made} renderCard={renderCard} /> + {showReadyColumn && ( + 0 && ( + + ) + } + empty={Nothing waiting for pickup} + renderCard={renderCard} + /> + )}
); diff --git a/src/app/dashboard/board-derive.ts b/src/app/dashboard/board-derive.ts index 70303f94..b2ea0386 100644 --- a/src/app/dashboard/board-derive.ts +++ b/src/app/dashboard/board-derive.ts @@ -49,7 +49,8 @@ export function groupVisibleOrders( o.status === "cancelled", ); const preparing = visible.filter((o) => o.status === "preparing"); - // A picked-up order stays in Ready for its undo window. + // A picked-up order stays in Ready for its undo window. With the Ready + // column off the board appends this list to Preparing, so Undo stays reachable. const ready = visible.filter( (o) => o.status === "ready" || o.status === "completed", ); diff --git a/src/app/dashboard/board-sections.tsx b/src/app/dashboard/board-sections.tsx index a93c834e..e26448ec 100644 --- a/src/app/dashboard/board-sections.tsx +++ b/src/app/dashboard/board-sections.tsx @@ -57,16 +57,19 @@ export function SectionSwitcher({ value, onChange, counts, + showReady = true, }: { + showReady?: boolean; value: PhoneSection; onChange: (next: PhoneSection) => void; counts: Record; }) { - const tabs: { key: PhoneSection; label: string; count: number }[] = [ + const allTabs: { key: PhoneSection; label: string; count: number }[] = [ { key: "incoming", label: "Incoming", count: counts.incoming }, { key: "preparing", label: "Preparing", count: counts.preparing }, { key: "ready", label: "Ready", count: counts.ready }, ]; + const tabs = allTabs.filter((tab) => showReady || tab.key !== "ready"); return (
{ expect(h.updateSpy).not.toHaveBeenCalled(); }); + it("rejects a minimum order above the sold-out limit", async () => { + h.loadEntitlementMock.mockResolvedValue({ + user: { id: "v1" }, + entitlement: ENTITLEMENTS.qkit, + }); + const res = await saveMenuItems(BOOTH_ID, [ + makeItem({ name: "Skewer", stock: 3, minOrderQty: 4 }), + ]); + + expect(res).toEqual({ + success: false, + error: "Skewer: the minimum order is more than its sold-out limit", + }); + expect(h.updateSpy).not.toHaveBeenCalled(); + }); + + it("rejects a minimum order above the booth's per-order limit", async () => { + h.state.prevResult = { + data: { menu_items: [], max_items_per_order: 3 }, + }; + const res = await saveMenuItems(BOOTH_ID, [ + makeItem({ name: "Skewer", minOrderQty: 4 }), + ]); + + expect(res.success).toBe(false); + expect(h.updateSpy).not.toHaveBeenCalled(); + }); + + it("rejects a minimum order above the 20-per-line cap", async () => { + const res = await saveMenuItems(BOOTH_ID, [ + makeItem({ name: "Skewer", minOrderQty: 21 }), + ]); + + expect(res.success).toBe(false); + expect(h.updateSpy).not.toHaveBeenCalled(); + }); + + it("saves a valid minimum order on any plan", async () => { + const res = await saveMenuItems(BOOTH_ID, [makeItem({ minOrderQty: 2 })]); + + expect(res).toEqual({ success: true }); + const row = h.updateSpy.mock.calls[0]![0] as { + menu_items: Array>; + }; + expect(row.menu_items[0]).toHaveProperty("minOrderQty", 2); + }); + it("strips per-item stock on a free-plan save", async () => { const res = await saveMenuItems(BOOTH_ID, [makeItem({ stock: 10 })]); diff --git a/src/app/dashboard/booths/actions.ts b/src/app/dashboard/booths/actions.ts index a0375e2d..9786fdda 100644 --- a/src/app/dashboard/booths/actions.ts +++ b/src/app/dashboard/booths/actions.ts @@ -33,6 +33,7 @@ import { drainProofDeletions } from "@/lib/proof-storage-cleanup"; import { fail, ok, type ActionResult } from "@/lib/action-result"; import type { Database, PaymentKind } from "@/lib/types"; import { paymentMarker } from "@/lib/payment-marker"; +import { validateMinOrderQty } from "@/lib/min-order-qty"; type BoothRow = Database["qkit"]["Tables"]["booths"]["Update"] & { name: string; @@ -508,11 +509,14 @@ export async function saveMenuItems( // RLS scopes this to the vendor's own booths; a foreign id reads null. const { data: prev } = await supabase .from("booths") - .select("menu_items, modifier_groups, menu_revision") + .select("menu_items, modifier_groups, menu_revision, max_items_per_order") .eq("id", boothId) .maybeSingle(); if (!prev) return fail("Booth not found"); + const minError = validateMinOrderQty(stripped, prev.max_items_per_order); + if (minError) return fail(minError); + // Linked copies are re-expanded from the stored library so a stale client // can never write a copy that disagrees with it. const library = parseStoredLibrary(prev.modifier_groups); diff --git a/src/app/dashboard/booths/booth-form.dom.test.tsx b/src/app/dashboard/booths/booth-form.dom.test.tsx index 142dfb3c..9c9df902 100644 --- a/src/app/dashboard/booths/booth-form.dom.test.tsx +++ b/src/app/dashboard/booths/booth-form.dom.test.tsx @@ -618,6 +618,24 @@ describe("BoothForm short create form", () => { }); describe("BoothForm More settings on edit", () => { + it("groups the cards into two balanced columns by topic", async () => { + await renderEdit({}); + const titles = (column: string) => { + const el = document.querySelector(`[data-settings-column="${column}"]`); + expect(el).not.toBeNull(); + return within(el as HTMLElement) + .getAllByRole("heading") + .map((h) => h.textContent); + }; + const operations = titles("operations"); + const customer = titles("customer"); + expect(operations).toEqual(["Order flow", "Limits", "Printing", "Pickup"]); + expect(customer).toEqual(["Menu", "Payment", "Social links"]); + expect(Math.abs(operations.length - customer.length)).toBeLessThanOrEqual( + 1, + ); + }); + it("keeps the rest collapsed behind a labelled, expandable control", async () => { const user = await renderEdit({}, { expand: false }); const toggle = screen.getByRole("button", { name: "More settings" }); diff --git a/src/app/dashboard/booths/booth-form.tsx b/src/app/dashboard/booths/booth-form.tsx index 02702a0b..dacbd3fc 100644 --- a/src/app/dashboard/booths/booth-form.tsx +++ b/src/app/dashboard/booths/booth-form.tsx @@ -360,7 +360,7 @@ export function BoothForm({ onToggle={() => setMoreOpen((open) => !open)} >
-
+
} eyebrow="How orders come in" @@ -418,38 +418,6 @@ export function BoothForm({ savedDailyCupCap={initial?.daily_cup_cap} hasItemLimits={initial?.hasItemLimits} /> -
- -
-
} - eyebrow="What you sell" - title="Menu" - description="Add items customers can order." - > - {initial ? ( - - ) : null} -
- -
-
} - eyebrow="How you get paid" - title="Payment" - description="Optional, but skip it and customers have no way to pay through qkit. You'd collect payment in person instead." - > - -
-
} @@ -487,6 +455,38 @@ export function BoothForm({ ) : null}
+
+ +
+
} + eyebrow="What you sell" + title="Menu" + description="Add items customers can order." + > + {initial ? ( + + ) : null} +
+ +
+
} + eyebrow="How you get paid" + title="Payment" + description="Optional, but skip it and customers have no way to pay through qkit. You'd collect payment in person instead." + > + +
+
} diff --git a/src/app/dashboard/booths/menu-editor.tsx b/src/app/dashboard/booths/menu-editor.tsx index 958881fc..b7fba116 100644 --- a/src/app/dashboard/booths/menu-editor.tsx +++ b/src/app/dashboard/booths/menu-editor.tsx @@ -43,6 +43,7 @@ interface Props { onChange: (items: MenuItemFormInput[]) => void; entitlement: Entitlement; hasBoothLimit?: boolean; + maxItemsPerOrder?: number | null; categories?: MenuCategory[]; onCategoriesChange?: (categories: MenuCategory[]) => void; library?: OptionGroup[]; @@ -56,6 +57,7 @@ export function MenuEditor({ onChange, entitlement, hasBoothLimit = false, + maxItemsPerOrder = null, categories = [], onCategoriesChange = () => {}, library, @@ -203,6 +205,7 @@ export function MenuEditor({ vendorId={vendorId} entitlement={entitlement} hasBoothLimit={hasBoothLimit} + maxItemsPerOrder={maxItemsPerOrder} categories={categories} atItemCap={atItemCap} isOpen={expanded.has(item.id)} diff --git a/src/app/dashboard/booths/menu-item-fields.tsx b/src/app/dashboard/booths/menu-item-fields.tsx index 1ad48bc4..2ca9220e 100644 --- a/src/app/dashboard/booths/menu-item-fields.tsx +++ b/src/app/dashboard/booths/menu-item-fields.tsx @@ -13,13 +13,28 @@ import { } from "@merqo/ui/primitives"; import { ProLock } from "@/components/widgets/pro-lock"; -import type { MenuItemFormInput } from "@/lib/schemas"; +import { MAX_LINE_QTY, type MenuItemFormInput } from "@/lib/schemas"; import type { MenuCategory } from "@/lib/types"; // Radix Select reserves "" for "no selection" — a real sentinel stands in // for "no section" instead. const NO_CATEGORY = "__none__"; +function minOrderQtyError( + item: MenuItemFormInput, + maxItemsPerOrder: number | null, +): string | null { + const min = item.minOrderQty; + if (min === undefined) return null; + if (min < 2) return "Use 2 or more, or leave blank."; + if (min > MAX_LINE_QTY) return `Use ${MAX_LINE_QTY} or fewer.`; + if (maxItemsPerOrder !== null && min > maxItemsPerOrder) + return "More than the items allowed per order."; + if (typeof item.stock === "number" && min > item.stock) + return "More than the sold-out limit."; + return null; +} + /** * Price/cost/sold-out limit/section as one compact row, each * field with a persistent label (not just a placeholder, which @@ -36,9 +51,11 @@ export function MenuItemPricingFields({ categories, stockCaps, hasBoothLimit = false, + maxItemsPerOrder = null, onPrice, onCost, onStock, + onMinOrderQty = () => {}, onCountsTowardLimit = () => {}, onCategory, }: { @@ -50,13 +67,18 @@ export function MenuItemPricingFields({ stockCaps: boolean; // Whether the booth has a daily item limit; without one the tick is moot. hasBoothLimit?: boolean; + // The booth's per-order item cap, which a minimum may not exceed. + maxItemsPerOrder?: number | null; onPrice: (cents: number | undefined) => void; onCost: (cents: number | undefined) => void; // The raw text typed into the sold-out limit, parsed by the editor. onStock: (raw: string) => void; + // The raw text typed into the minimum order quantity, parsed by the editor. + onMinOrderQty?: (raw: string) => void; onCountsTowardLimit?: (counts: boolean) => void; onCategory: (category: string | null) => void; }) { + const minQtyError = minOrderQtyError(item, maxItemsPerOrder); return (
@@ -140,6 +162,33 @@ export function MenuItemPricingFields({ Sold-out limit
)} +
+
+ + +
+ onMinOrderQty(e.target.value)} + aria-invalid={minQtyError !== null} + className="h-9 w-full rounded-lg" + /> + {minQtyError && ( +

{minQtyError}

+ )} +
{categories.length > 0 && (