From 8b16146c50e14d0afc70a655ffd334f66a2dc1b0 Mon Sep 17 00:00:00 2001 From: Clarence Lee <35331421+cljiahao@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:43:56 +0800 Subject: [PATCH 1/8] docs(faq): replace pilot and in-build wording with dated, true labels (#506) * docs(faq): replace pilot and in-build wording with dated, true labels Co-Authored-By: Claude Sonnet 5.5 * docs(changelog): drop stray empty 0.6.0 heading above 0.6.1 Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src/app/faq/README.md | 2 +- src/app/faq/faq-content.ts | 10 +++++----- src/app/faq/page.dom.test.tsx | 2 +- 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bbf4c03..ae8446d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ 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). +## [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 diff --git a/package.json b/package.json index 9c2605d2..3c2022db 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "qkit", - "version": "0.6.1", + "version": "0.6.2", "private": true, "packageManager": "pnpm@11.28.5", "engines": { diff --git a/src/app/faq/README.md b/src/app/faq/README.md index cbcebec8..d625b33b 100644 --- a/src/app/faq/README.md +++ b/src/app/faq/README.md @@ -4,7 +4,7 @@ The public `/faq` page: full answers for vendors beyond the three rows on the landing page, in four groups (getting started, day to day, money and payment, -cost and pilot). +cost and plans). ## Contents diff --git a/src/app/faq/faq-content.ts b/src/app/faq/faq-content.ts index 922c34d7..a17d33e1 100644 --- a/src/app/faq/faq-content.ts +++ b/src/app/faq/faq-content.ts @@ -44,7 +44,7 @@ export const FAQ_GROUPS: FaqGroup[] = [ rows: [ { q: "Can I take PayNow?", - a: "Yes, through paykit, a separate Merqo app that is still in build. The customer pays in their banking app and marks the order as paid. The ticket then says to check the payment, and it only counts as paid once you confirm it. The money goes to your own account and qkit never holds it. Online card payment is not available.", + a: "Yes, through paykit, a separate Merqo app, deployed and in early access. The customer pays in their banking app and marks the order as paid. The ticket then says to check the payment, and it only counts as paid once you confirm it. The money goes to your own account and qkit never holds it. Online card payment is not available.", }, { q: "Do I have to take payment through qkit?", @@ -52,17 +52,17 @@ export const FAQ_GROUPS: FaqGroup[] = [ }, { q: "Does qkit see my PayNow or bank details?", - a: "No. qkit only shows what kind of payment you have set up. You enter your PayNow details once in paykit, a separate Merqo app that is still in build, and qkit does not keep them.", + a: "No. qkit only shows what kind of payment you have set up. You enter your PayNow details once in paykit, a separate Merqo app, deployed and in early access, and qkit does not keep them.", }, ], }, { - id: "cost-and-pilot", - heading: "Cost and pilot", + id: "cost-and-plans", + heading: "Cost and plans", rows: [ { q: "Is it free, and is qkit finished?", - a: "qkit is piloting and running with a few vendors. Free during the pilot. If we start charging, you'll get at least 30 days' notice first.", + a: "qkit finished its pilot in Sep 2026 and is open for founding vendors. Charging starts 1 January 2027. Free stays free: the whole order flow, including ready alerts.", }, { q: "Who runs qkit, and what if I want to stop?", diff --git a/src/app/faq/page.dom.test.tsx b/src/app/faq/page.dom.test.tsx index 7e8bbdf8..03383e05 100644 --- a/src/app/faq/page.dom.test.tsx +++ b/src/app/faq/page.dom.test.tsx @@ -25,7 +25,7 @@ describe("FaqRoute", () => { "Getting started", "Day to day", "Money and payment", - "Cost and pilot", + "Cost and plans", ]) { expect( screen.getByRole("heading", { level: 2, name: heading }), From f1d4aeea873d2fd5d29a43dae24f4806dcc2eec7 Mon Sep 17 00:00:00 2001 From: Clarence Lee <35331421+cljiahao@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:10:15 +0800 Subject: [PATCH 2/8] feat(board): two-column board by default with an opt-in Ready column (#503) * feat(board): two-column board by default with an opt-in Ready column Ready orders sit at the bottom of Preparing unless Settings turns on a Ready column. Settings gets a Board display card with a colour key for the two blues. Co-Authored-By: Claude Sonnet 5.5 * test(board): cover both column modes in the realtime board tests Co-Authored-By: Claude Sonnet 5.5 * feat(discounts): vendor discount codes (#487) * feat(discounts): vendor discount codes with checkout, order and board display 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. Customers enter a code at checkout; place_order re-validates and redeems it atomically so the client total is never trusted and a total never goes below zero. The order page and the live board card show the code and amount taken off. Also adds the service-role-only qkit.issue_reward_code(...) for loopkit, idempotent on source_ref. Co-Authored-By: Claude Sonnet 5.5 * test(discounts): avoid DELETE inside subselect in pgTAP Co-Authored-By: Claude Sonnet 5.5 * fix(discounts): lock preview to service role, release uses on cancel, free cart Co-Authored-By: Claude Sonnet 5.5 * fix(discounts): justify service client import in checkout action Co-Authored-By: Claude Sonnet 5.5 * test(discounts): prove the cancel trigger releases a use only once Co-Authored-By: Claude Sonnet 5.5 * docs: HitPay QR ordering rate and break-even scenarios (#489) Co-authored-by: Claude Sonnet 5.5 * docs: align Hawkers competitors row with handoff doc (#499) Add Hawker POS and Rewardly as direct and EPOS as adjacent for hawkers, matching the 2026-12-01 addendum and the business handoff doc. Co-authored-by: Claude Opus 5.5 * fix(demo): options scene shows the option items (#488) * fix(demo): options scene replaces the onboarding sample menu Co-Authored-By: Claude Opus 5.5 * fix(demo): wait for menu rows before removing the sample items --------- Co-authored-by: Claude Opus 5.5 * chore(release): stamp 0.6.0 Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 * feat(ui): adopt @merqo/ui 0.67.0 text size control; add Text size to account menu (#501) * feat(ui): adopt @merqo/ui 0.67.0 text size control and add Text size to the account menu Co-Authored-By: Claude Sonnet 5.5 * docs(readme): note the v0.67.0 pin and shared text size control Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 * fix(board): two-column skeleton and document undo-window orders in Preparing The loading skeleton now matches the default two-column board, and board-derive notes why picked-up orders stay in the ready list. Co-Authored-By: Claude Sonnet 5.5 * fix(board): renumber show_ready_column migration to 0133 Staging already has 0129_discount_codes.sql, and 0130-0132 are taken by other PRs. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + e2e/vendor-fulfillment.spec.ts | 12 ++ src/app/dashboard/README.md | 9 +- src/app/dashboard/board-columns.dom.test.tsx | 46 ++++++++ src/app/dashboard/board-columns.tsx | 68 +++++++---- src/app/dashboard/board-derive.ts | 3 +- src/app/dashboard/board-sections.tsx | 5 +- .../realtime-order-board.dom.test.tsx | 94 ++++++++++++--- src/app/dashboard/realtime-order-board.tsx | 1 + src/app/dashboard/settings/README.md | 2 +- .../settings/board-display-section.tsx | 109 ++++++++++++++++++ .../settings/settings-form.dom.test.tsx | 47 +++++++- src/app/dashboard/settings/settings-form.tsx | 13 ++- .../settings/unpaid-orders-section.tsx | 43 ------- src/components/skeletons/README.md | 2 +- src/components/skeletons/board-skeleton.tsx | 6 +- .../skeletons/skeletons.dom.test.tsx | 7 +- src/lib/schemas.ts | 3 + src/lib/types.ts | 4 + .../0133_board_settings_show_ready_column.sql | 71 ++++++++++++ supabase/migrations/README.md | 1 + supabase/tests/board-settings-patch.test.sql | 6 + 22 files changed, 454 insertions(+), 99 deletions(-) create mode 100644 src/app/dashboard/settings/board-display-section.tsx delete mode 100644 src/app/dashboard/settings/unpaid-orders-section.tsx create mode 100644 supabase/migrations/0133_board_settings_show_ready_column.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index ae8446d1..20d0a29d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### 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. - 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/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/src/app/dashboard/README.md b/src/app/dashboard/README.md index 8738a13a..8834097a 100644 --- a/src/app/dashboard/README.md +++ b/src/app/dashboard/README.md @@ -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 (
{ order({ id: "waiting", status: "pending" }), order({ id: "making", status: "preparing" }), ]} - boardSettings={DEFAULT_BOARD_SETTINGS} + boardSettings={{ ...DEFAULT_BOARD_SETTINGS, show_ready_column: true }} />, { wrapper: TooltipProvider }, ); @@ -461,7 +461,7 @@ describe("RealtimeOrderBoard phone section switcher", () => { , { wrapper: TooltipProvider }, ); @@ -1530,12 +1530,15 @@ describe("RealtimeOrderBoard batch mark-ready", () => { }); }); -function renderBoard(orders: BoardOrder[]) { +function renderBoard(orders: BoardOrder[], showReadyColumn = false) { render( , { wrapper: TooltipProvider }, ); @@ -1629,14 +1632,17 @@ describe("RealtimeOrderBoard Preparing header", () => { }); }); -describe("RealtimeOrderBoard three-column split", () => { +describe("RealtimeOrderBoard Ready column on", () => { it("puts pending, preparing and ready orders in their own columns", () => { - renderBoard([ - order({ id: "o1", order_number: "0001", status: "pending" }), - order({ id: "o2", order_number: "0002", status: "confirmed" }), - order({ id: "o3", order_number: "0003", status: "preparing" }), - order({ id: "o4", order_number: "0004", status: "ready" }), - ]); + renderBoard( + [ + order({ id: "o1", order_number: "0001", status: "pending" }), + order({ id: "o2", order_number: "0002", status: "confirmed" }), + order({ id: "o3", order_number: "0003", status: "preparing" }), + order({ id: "o4", order_number: "0004", status: "ready" }), + ], + true, + ); expect( screen.getByRole("heading", { name: "Incoming (2)" }), ).toBeInTheDocument(); @@ -1649,7 +1655,7 @@ describe("RealtimeOrderBoard three-column split", () => { }); it("keeps every column, with an empty state, when only one has orders", () => { - renderBoard([order({ id: "o1", status: "preparing" })]); + renderBoard([order({ id: "o1", status: "preparing" })], true); expect( screen.getByRole("heading", { name: "Incoming (0)" }), ).toBeInTheDocument(); @@ -1661,10 +1667,13 @@ describe("RealtimeOrderBoard three-column split", () => { }); it("offers Select in the Ready header and no bulk mark-ready there", () => { - renderBoard([ - order({ id: "o1", order_number: "0001", status: "ready" }), - order({ id: "o2", order_number: "0002", status: "ready" }), - ]); + renderBoard( + [ + order({ id: "o1", order_number: "0001", status: "ready" }), + order({ id: "o2", order_number: "0002", status: "ready" }), + ], + true, + ); const header = screen.getByRole("heading", { name: "Ready (2)" }) .parentElement as HTMLElement; expect( @@ -1674,6 +1683,59 @@ describe("RealtimeOrderBoard three-column split", () => { screen.queryByRole("button", { name: /^mark all/i }), ).not.toBeInTheDocument(); }); + + it("keeps the phone switcher at three tabs", () => { + renderBoard([order({ id: "o1", status: "ready" })], true); + const group = screen.getByRole("group", { name: "Which orders to show" }); + expect(within(group).getAllByRole("button")).toHaveLength(3); + }); +}); + +describe("RealtimeOrderBoard Ready column off (default)", () => { + it("shows two columns with ready orders last in Preparing", () => { + renderBoard([ + order({ id: "o1", order_number: "0001", status: "pending" }), + order({ id: "o3", order_number: "0003", status: "ready" }), + order({ id: "o4", order_number: "0004", status: "preparing" }), + ]); + expect( + screen.getByRole("heading", { name: "Incoming (1)" }), + ).toBeInTheDocument(); + expect( + screen.getByRole("heading", { name: "Preparing (2)" }), + ).toBeInTheDocument(); + expect( + screen.queryByRole("heading", { name: /^Ready \(/ }), + ).not.toBeInTheDocument(); + const column = screen + .getByRole("heading", { name: "Preparing (2)" }) + .closest("section") as HTMLElement; + const picked = within(column).getByRole("button", { + name: "Mark Picked Up", + }); + const making = within(column).getByRole("button", { name: "Mark Ready" }); + expect( + making.compareDocumentPosition(picked) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + }); + + it("offers two phone tabs, with ready orders counted under Preparing", () => { + renderBoard([order({ id: "o1", status: "ready" })]); + const group = screen.getByRole("group", { name: "Which orders to show" }); + expect(within(group).getAllByRole("button")).toHaveLength(2); + expect( + within(group).getByRole("button", { name: "Preparing (1)" }), + ).toBeInTheDocument(); + }); + + it("selects across Preparing and ready orders from the Preparing header", () => { + renderBoard([order({ id: "o1", order_number: "0001", status: "ready" })]); + const header = screen.getByRole("heading", { name: "Preparing (1)" }) + .parentElement as HTMLElement; + expect( + within(header).getByRole("button", { name: /^select$/i }), + ).toBeInTheDocument(); + }); }); describe("RealtimeOrderBoard start all incoming", () => { diff --git a/src/app/dashboard/realtime-order-board.tsx b/src/app/dashboard/realtime-order-board.tsx index 0aa0532d..fd55c768 100644 --- a/src/app/dashboard/realtime-order-board.tsx +++ b/src/app/dashboard/realtime-order-board.tsx @@ -228,6 +228,7 @@ export function RealtimeOrderBoard({ incoming={groups.incoming} preparing={groups.preparing} ready={groups.ready} + showReadyColumn={boardSettings.show_ready_column === true} phoneSection={phoneSection} onPhoneSectionChange={setPhoneSection} batch={{ diff --git a/src/app/dashboard/settings/README.md b/src/app/dashboard/settings/README.md index d218ded2..c5f76405 100644 --- a/src/app/dashboard/settings/README.md +++ b/src/app/dashboard/settings/README.md @@ -190,7 +190,7 @@ blank here) disables the sweep entirely for that vendor. - `backup-prep-help-text.tsx` is the help text under the default prep time, explaining the estimate from recent orders. -The "Unpaid orders" card (`unpaid-orders-section.tsx`, right after Board timing) holds a "Highlight unpaid orders" `Switch` for +The "Board display" card (`board-display-section.tsx`, right after Board timing) holds a "Show a Ready column" `Switch` for `show_ready_column` (reads `?? false`) and a "Highlight unpaid orders" `Switch` for `show_unpaid_border` (blue border on open unpaid cards; the says-paid wash is never toggleable). It saves the moment it is flipped through `saveSwitch`, and reads `?? true` so a vendor row without the key keeps the border. diff --git a/src/app/dashboard/settings/board-display-section.tsx b/src/app/dashboard/settings/board-display-section.tsx new file mode 100644 index 00000000..ef2bc852 --- /dev/null +++ b/src/app/dashboard/settings/board-display-section.tsx @@ -0,0 +1,109 @@ +"use client"; + +import { LayoutDashboard } from "lucide-react"; +import { Label, Switch } from "@merqo/ui/primitives"; + +import { Section } from "@/components/widgets/ticket-section"; + +interface Props { + showReadyColumn: boolean; + onShowReadyColumnChange: (value: boolean) => void; + showUnpaidBorder: boolean; + onShowUnpaidBorderChange: (value: boolean) => void; + saving: boolean; +} + +function SwitchRow({ + id, + label, + help, + checked, + onChange, + disabled, +}: { + id: string; + label: string; + help: string; + checked: boolean; + onChange: (value: boolean) => void; + disabled: boolean; +}) { + return ( +
+ +
+ +

{help}

+
+
+ ); +} + +function KeyRow({ + swatchClassName, + children, +}: { + swatchClassName: string; + children: string; +}) { + return ( +
  • + + {children} +
  • + ); +} + +export function BoardDisplaySection({ + showReadyColumn, + onShowReadyColumnChange, + showUnpaidBorder, + onShowUnpaidBorderChange, + saving, +}: Props) { + return ( +
    } + title="Board display" + description="Choose what the live board shows." + > +
    + + +
      + + Blue background: the customer says they paid. Check your payment + app, then tap Mark paid on the order. + + + Blue border: not paid yet (only when Highlight unpaid orders is on). + +
    +
    +
    + ); +} diff --git a/src/app/dashboard/settings/settings-form.dom.test.tsx b/src/app/dashboard/settings/settings-form.dom.test.tsx index fd1301b9..1d943694 100644 --- a/src/app/dashboard/settings/settings-form.dom.test.tsx +++ b/src/app/dashboard/settings/settings-form.dom.test.tsx @@ -41,6 +41,7 @@ const DEFAULTS: BoardSettings = { ready_auto_clear_min: 3, customer_telegram_notify_enabled: true, show_unpaid_border: true, + show_ready_column: false, }; const PREP_ESTIMATE = { avgMinutes: null, sampleCount: 0, minSample: 10 }; @@ -244,7 +245,7 @@ describe("SettingsForm customer notify toggle", () => { }); describe("SettingsForm unpaid border toggle", () => { - it("sits in its own Unpaid orders card, defaults checked and saves the moment it is flipped", async () => { + it("sits in the Board display card, defaults checked and saves the moment it is flipped", async () => { updateBoardSettings.mockResolvedValue({ success: true }); const user = userEvent.setup(); render(); @@ -254,7 +255,7 @@ describe("SettingsForm unpaid border toggle", () => { }); expect(toggle).toBeChecked(); const card = toggle.closest("section"); - expect(card).toHaveTextContent(/^Unpaid orders/); + expect(card).toHaveTextContent(/^Board display/); expect(card).not.toHaveTextContent(/board timing/i); await user.click(toggle); @@ -617,3 +618,45 @@ describe("SettingsForm customer order screen", () => { ).not.toBeInTheDocument(); }); }); + +describe("SettingsForm Ready column toggle", () => { + it("defaults off, shares the Board display card and saves when flipped", async () => { + updateBoardSettings.mockResolvedValue({ success: true }); + const user = userEvent.setup(); + render(); + + const toggle = screen.getByRole("switch", { name: /show a ready column/i }); + expect(toggle).not.toBeChecked(); + expect(toggle.closest("section")).toHaveTextContent( + /highlight unpaid orders/i, + ); + + await user.click(toggle); + + await waitFor(() => + expect(updateBoardSettings).toHaveBeenCalledWith({ + show_ready_column: true, + }), + ); + }); + + it("reads a legacy row without the key as off", () => { + const { show_ready_column: _omit, ...legacyRest } = DEFAULTS; + render( + , + ); + expect( + screen.getByRole("switch", { name: /show a ready column/i }), + ).not.toBeChecked(); + }); + + it("explains the two blues in a colour key", () => { + render(); + const key = screen.getByRole("list", { name: /colour key/i }); + expect(key).toHaveTextContent(/blue background.*mark paid/i); + expect(key).toHaveTextContent(/blue border.*not paid yet/i); + }); +}); diff --git a/src/app/dashboard/settings/settings-form.tsx b/src/app/dashboard/settings/settings-form.tsx index e1ce7f2e..1fda28d7 100644 --- a/src/app/dashboard/settings/settings-form.tsx +++ b/src/app/dashboard/settings/settings-form.tsx @@ -33,7 +33,7 @@ import { DesktopNotifySection, useDesktopNotifySection, } from "./desktop-notify-section"; -import { UnpaidOrdersSection } from "./unpaid-orders-section"; +import { BoardDisplaySection } from "./board-display-section"; import { saveBoardSettingsSection } from "./save-board-settings-section"; const SOUND_OPTIONS: { id: SoundId; label: string }[] = [ @@ -73,6 +73,9 @@ export function SettingsForm({ const [showUnpaidBorder, setShowUnpaidBorder] = useState( initial.show_unpaid_border ?? true, ); + const [showReadyColumn, setShowReadyColumn] = useState( + initial.show_ready_column ?? false, + ); const [thresholdError, setThresholdError] = useState(null); const { pending: savingThresholds, run: runThresholds } = useAsyncAction( "Could not save timing settings. Please try again.", @@ -121,6 +124,7 @@ export function SettingsForm({ key: | "customer_telegram_notify_enabled" | "daily_order_number_reset" + | "show_ready_column" | "show_unpaid_border" | "show_wait_estimate", value: boolean, @@ -160,6 +164,7 @@ export function SettingsForm({ readyAutoClearMin.trim() === "" ? null : Number(readyAutoClearMin), customer_telegram_notify_enabled: customerNotify, show_unpaid_border: showUnpaidBorder, + show_ready_column: showReadyColumn, }; } @@ -259,7 +264,11 @@ export function SettingsForm({ onSave={saveThresholds} /> - + saveSwitch("show_ready_column", checked, setShowReadyColumn) + } showUnpaidBorder={showUnpaidBorder} onShowUnpaidBorderChange={(checked) => saveSwitch("show_unpaid_border", checked, setShowUnpaidBorder) diff --git a/src/app/dashboard/settings/unpaid-orders-section.tsx b/src/app/dashboard/settings/unpaid-orders-section.tsx deleted file mode 100644 index a62a4095..00000000 --- a/src/app/dashboard/settings/unpaid-orders-section.tsx +++ /dev/null @@ -1,43 +0,0 @@ -"use client"; - -import { CircleDollarSign } from "lucide-react"; -import { Label, Switch } from "@merqo/ui/primitives"; - -import { Section } from "@/components/widgets/ticket-section"; - -interface Props { - showUnpaidBorder: boolean; - onShowUnpaidBorderChange: (value: boolean) => void; - saving: boolean; -} - -export function UnpaidOrdersSection({ - showUnpaidBorder, - onShowUnpaidBorderChange, - saving, -}: Props) { - return ( -
    } - title="Unpaid orders" - description="Make orders that are not paid yet easy to spot on the board." - > -
    - -
    - -

    - Blue border on orders that are not paid yet. -

    -
    -
    -
    - ); -} diff --git a/src/components/skeletons/README.md b/src/components/skeletons/README.md index 54db0130..ac79fa1b 100644 --- a/src/components/skeletons/README.md +++ b/src/components/skeletons/README.md @@ -9,7 +9,7 @@ shows the outline of its real page and nothing jumps when content arrives. - `loading-region.tsx`: `LoadingRegion`, the `role="status"` / `aria-busy` wrapper with the single sr-only "Loading" label. - `page-skeletons.tsx`: `PageHeaderSkeleton`, `CardSkeleton`, `FormSkeleton`, `RowListSkeleton`, the building blocks for dashboard pages. -- `board-skeleton.tsx`: `BoardSkeleton`, the live order board (header, booth row, filter bar, three columns at lg, a tab bar and one column below). +- `board-skeleton.tsx`: `BoardSkeleton`, the live order board (header, booth row, filter bar, two columns at lg, a tab bar and one column below). - `queue-display-skeleton.tsx`: `QueueDisplaySkeleton`, the dark TV queue display (Preparing, Ready, ordering QR). ## Connectivity diff --git a/src/components/skeletons/board-skeleton.tsx b/src/components/skeletons/board-skeleton.tsx index 5fc95292..183a40da 100644 --- a/src/components/skeletons/board-skeleton.tsx +++ b/src/components/skeletons/board-skeleton.tsx @@ -1,7 +1,7 @@ import { cn, Skeleton } from "@merqo/ui/primitives"; import { LoadingRegion } from "./loading-region"; -const COLUMN_TICKETS = [3, 2, 2] as const; +const COLUMN_TICKETS = [3, 2] as const; function TicketSkeleton() { return ( @@ -17,7 +17,7 @@ function TicketSkeleton() { ); } -/** Mirrors the vendor board: header, booth row, filter bar, then three columns at lg or a tab bar and one column below. */ +/** Mirrors the vendor board: header, booth row, filter bar, then two columns at lg or a tab bar and one column below. */ export function BoardSkeleton() { return ( @@ -38,7 +38,7 @@ export function BoardSkeleton() {
    -
    +
    {COLUMN_TICKETS.map((count, col) => (
    { expect(container.querySelector('[aria-hidden="true"]')).not.toBeNull(); }); - it("lays out three columns at lg, two of them hidden below it", () => { + it("lays out two columns at lg, one of them hidden below it", () => { render(); const columns = screen.getAllByTestId("board-skeleton-column"); - expect(columns).toHaveLength(3); + expect(columns).toHaveLength(2); expect(columns[0].className).not.toContain("hidden"); expect(columns[1].className).toContain("hidden lg:block"); - expect(columns[2].className).toContain("hidden lg:block"); - expect(columns[0].parentElement?.className).toContain("lg:grid-cols-3"); + expect(columns[0].parentElement?.className).toContain("lg:grid-cols-2"); }); }); diff --git a/src/lib/schemas.ts b/src/lib/schemas.ts index 09e91e7b..c758c2b6 100644 --- a/src/lib/schemas.ts +++ b/src/lib/schemas.ts @@ -534,6 +534,8 @@ const boardSettingsFields = z.object({ // Opt-out for the same reason: rows saved before this key existed must keep // the blue unpaid border they would get by default. show_unpaid_border: z.boolean().default(true), + // Opt-in: a missing key reads as false so the board defaults to two columns. + show_ready_column: z.boolean().default(false), }); export const boardSettingsSchema = boardSettingsFields.refine( @@ -549,6 +551,7 @@ export const boardSettingsPatchSchema = boardSettingsFields .extend({ customer_telegram_notify_enabled: z.boolean().optional(), show_unpaid_border: z.boolean().optional(), + show_ready_column: z.boolean().optional(), }) .strict() .refine( diff --git a/src/lib/types.ts b/src/lib/types.ts index e55a2db6..a4673442 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -80,6 +80,9 @@ export type BoardSettings = { // Blue border on open orders that are not paid yet. Default true; the // says-paid wash is not governed by this. show_unpaid_border: boolean; + // Separate Ready column on the board. Default false: ready orders sit at the + // bottom of Preparing until picked up. + show_ready_column: boolean; }; // Falls back to this until migration 0050 (board_settings column) has been @@ -98,6 +101,7 @@ export const DEFAULT_BOARD_SETTINGS: BoardSettings = { ready_auto_clear_min: 3, customer_telegram_notify_enabled: true, show_unpaid_border: true, + show_ready_column: false, }; export type PaymentStatus = diff --git a/supabase/migrations/0133_board_settings_show_ready_column.sql b/supabase/migrations/0133_board_settings_show_ready_column.sql new file mode 100644 index 00000000..15cc8c3e --- /dev/null +++ b/supabase/migrations/0133_board_settings_show_ready_column.sql @@ -0,0 +1,71 @@ +-- Same as 0128, plus show_ready_column in the boolean allowlist. +-- Merge section-owned preferences under the caller's existing vendor RLS policies. +CREATE OR REPLACE FUNCTION qkit.patch_board_settings(p_patch jsonb) +RETURNS jsonb +LANGUAGE plpgsql +SECURITY INVOKER +SET search_path = '' +AS $$ +DECLARE + current_settings jsonb; + merged jsonb; + field text; + value jsonb; + minimum numeric; + maximum numeric; +BEGIN + IF auth.uid() IS NULL THEN + RAISE EXCEPTION 'Not signed in' USING ERRCODE = '42501'; + END IF; + IF p_patch IS NULL OR jsonb_typeof(p_patch) <> 'object' OR p_patch = '{}'::jsonb THEN + RAISE EXCEPTION 'Invalid settings patch' USING ERRCODE = '22023'; + END IF; + FOR field, value IN SELECT * FROM jsonb_each(p_patch) LOOP + CASE field + WHEN 'sound_id' THEN + IF jsonb_typeof(value) <> 'string' OR value #>> '{}' NOT IN ('chime','bell','ding','horn','triple','none') THEN + RAISE EXCEPTION 'Invalid sound' USING ERRCODE = '22023'; + END IF; + WHEN 'desktop_notify', 'daily_order_number_reset', 'show_wait_estimate', + 'customer_telegram_notify_enabled', 'pickup_scan_enabled', 'show_unpaid_border', 'show_ready_column' THEN + IF jsonb_typeof(value) <> 'boolean' THEN + RAISE EXCEPTION 'Invalid boolean setting' USING ERRCODE = '22023'; + END IF; + WHEN 'aging_min', 'overdue_min', 'undo_seconds', 'default_prep_minutes', 'ready_auto_clear_min' THEN + IF value = 'null'::jsonb AND field IN ('default_prep_minutes', 'ready_auto_clear_min') THEN + CONTINUE; + END IF; + IF jsonb_typeof(value) <> 'number' THEN + RAISE EXCEPTION 'Invalid numeric setting' USING ERRCODE = '22023'; + END IF; + minimum := CASE WHEN field = 'undo_seconds' THEN 2 ELSE 1 END; + maximum := CASE WHEN field IN ('aging_min','overdue_min') THEN 240 WHEN field = 'undo_seconds' THEN 15 ELSE 60 END; + IF (value #>> '{}')::numeric < minimum OR (value #>> '{}')::numeric > maximum + OR mod((value #>> '{}')::numeric, 1) <> 0 THEN + RAISE EXCEPTION 'Setting outside allowed range' USING ERRCODE = '22023'; + END IF; + ELSE + RAISE EXCEPTION 'Unknown setting' USING ERRCODE = '22023'; + END CASE; + END LOOP; + + SELECT board_settings INTO current_settings FROM qkit.vendors + WHERE id = auth.uid() FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Vendor unavailable' USING ERRCODE = '42501'; + END IF; + merged := current_settings || p_patch; + IF jsonb_typeof(merged -> 'aging_min') IS DISTINCT FROM 'number' + OR jsonb_typeof(merged -> 'overdue_min') IS DISTINCT FROM 'number' THEN + RAISE EXCEPTION 'Invalid stored timing settings' USING ERRCODE = '22023'; + END IF; + IF (merged ->> 'overdue_min')::numeric <= (merged ->> 'aging_min')::numeric THEN + RAISE EXCEPTION 'Overdue must be later than amber' USING ERRCODE = '22023'; + END IF; + UPDATE qkit.vendors SET board_settings = merged WHERE id = auth.uid(); + RETURN merged; +END; +$$; + +REVOKE ALL ON FUNCTION qkit.patch_board_settings(jsonb) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION qkit.patch_board_settings(jsonb) TO authenticated; diff --git a/supabase/migrations/README.md b/supabase/migrations/README.md index 9c87e739..add2ce96 100644 --- a/supabase/migrations/README.md +++ b/supabase/migrations/README.md @@ -106,4 +106,5 @@ The audit additions follow these deployed versions as 0100 through 0103. Local d - 0126_pricing_2027_gates.sql removes the Starter tier (starter rows become `qkit`, the tier CHECK admits `free | qkit`), relaxes the free menu-cap trigger so an over-cap menu can still be edited, renamed, toggled or shrunk (it only rejects growth past 6 items or 3 option groups per item), and adds `qkit.booth_pro_gates_active(booth)` (vendor_entitled for the booth's vendor) so the daily item limit, per-item sold-out limits and opening hours bind only an entitled vendor (`enforce_daily_cup_cap`, `booth_cups_left`, `booth_remaining_stock`, `hold_cart`, `place_order`, and `get_booth_for_order`, which returns no hours otherwise). Stored values stay and apply again on upgrade; manual pause (`is_active`) is unaffected. - 0127_order_page_shows_sold_out_items.sql redefines `qkit.get_booth_for_order` to return unavailable (sold out) menu items with their `available` flag instead of dropping them, so the order page can grey them out. Cost fields stay stripped, and `place_order` / `place_walkup_order` still reject unavailable items. Apply before deploying the app; until the app ships, customers would see sold-out items as addable and be rejected on submit. It is built on 0126 (Pro-gated hours) and must apply after it. - 0128_board_settings_show_unpaid_border.sql redefines `qkit.patch_board_settings` (built on 0100) so the boolean allowlist accepts `show_unpaid_border`, the vendor toggle for the blue unpaid-order border. Apply before deploying the app; until then saving the setting is rejected as an unknown key. +- 0133_board_settings_show_ready_column.sql redefines `qkit.patch_board_settings` (built on 0128) so the boolean allowlist accepts `show_ready_column`, the opt-in Ready column on the board. Apply before the vendor can save it; until then the board stays on two columns. - 0129_discount_codes.sql adds `qkit.discount_codes` (vendor-owned percent or fixed codes with optional expiry and use cap; RLS lets a vendor read, update and delete only their rows, inserts are gated on a paid plan), `orders.discount_code` / `orders.discount_cents` (`total_cents` stays the amount actually charged), `qkit.can_create_discount_codes()`, a checkout preview function and `qkit.place_order` with a trailing `p_discount_code` argument that re-validates and redeems the code in the order transaction (conditional UPDATE, race-safe, total never below zero). Also adds `qkit.issue_reward_code(p_vendor, p_kind, p_value, p_expires_at, p_source_ref)`: SECURITY DEFINER, `search_path = ''`, EXECUTE for `service_role` only, mints a single-use `LK-` code; a repeated `p_source_ref` returns the existing code (unique `source_ref`). The checkout preview function is service-role only and answers every bad code with one generic error, so codes cannot be enumerated. A trigger on `orders` releases a code's use when an order moves to cancelled (`uses = greatest(uses - 1, 0)`, once per transition), and a zero subtotal applies no discount. Reward codes are hidden from the vendor code list. Apply before deploying the app. diff --git a/supabase/tests/board-settings-patch.test.sql b/supabase/tests/board-settings-patch.test.sql index 91b56e80..4c58101f 100644 --- a/supabase/tests/board-settings-patch.test.sql +++ b/supabase/tests/board-settings-patch.test.sql @@ -29,6 +29,12 @@ select is((select board_settings->>'show_unpaid_border' from qkit.vendors), 'fal 'the unpaid border toggle is persisted'); select throws_ok($$ select qkit.patch_board_settings('{"show_unpaid_border":"no"}') $$,'22023',null, 'the unpaid border toggle must be a real boolean'); +select lives_ok($$ select qkit.patch_board_settings('{"show_ready_column":true}') $$, + 'the ready column toggle can be saved'); +select is((select board_settings->>'show_ready_column' from qkit.vendors), 'true', + 'the ready column toggle is persisted'); +select throws_ok($$ select qkit.patch_board_settings('{"show_ready_column":"yes"}') $$,'22023',null, + 'the ready column toggle must be a real boolean'); select throws_ok($$ select qkit.patch_board_settings('{"plan":"pro"}') $$,'22023',null, 'unknown privileged keys are rejected'); select throws_ok($$ select qkit.patch_board_settings('{"desktop_notify":"true"}') $$,'22023',null, From d153a14ab4ec42de0c4b1ba2462fccec2f4abc7e Mon Sep 17 00:00:00 2001 From: Clarence Lee <35331421+cljiahao@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:04:45 +0800 Subject: [PATCH 3/8] feat(menu): minimum order quantity per item (#508) * feat(discounts): vendor discount codes with checkout, order and board display 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. Customers enter a code at checkout; place_order re-validates and redeems it atomically so the client total is never trusted and a total never goes below zero. The order page and the live board card show the code and amount taken off. Also adds the service-role-only qkit.issue_reward_code(...) for loopkit, idempotent on source_ref. Co-Authored-By: Claude Sonnet 5.5 * test(discounts): avoid DELETE inside subselect in pgTAP Co-Authored-By: Claude Sonnet 5.5 * fix(discounts): lock preview to service role, release uses on cancel, free cart Co-Authored-By: Claude Sonnet 5.5 * fix(discounts): justify service client import in checkout action Co-Authored-By: Claude Sonnet 5.5 * test(discounts): prove the cancel trigger releases a use only once Co-Authored-By: Claude Sonnet 5.5 * feat(order): minimum order quantity per menu item Vendors set an optional minimum per item. The cart starts the item at the minimum, removes it when decremented below, and the DB refuses customer orders below it (migration 0130, ORDER_BELOW_MIN). Co-Authored-By: Claude Sonnet 5.5 * fix(order): cap minimum order quantity at the 20-per-line order limit place_order refuses any line above 20, so a larger minimum could never be ordered. The editor, save validation and cart now treat it as invalid or unreachable, and the editor flags a minimum above the booth's per-order cap. Co-Authored-By: Claude Sonnet 5.5 * chore(release): 0.7.0 Co-Authored-By: Claude Sonnet 5.5 * docs(changelog): drop duplicated 0.6.0 heading Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- CHANGELOG.md | 10 ++- package.json | 2 +- src/app/dashboard/booths/README.md | 4 +- .../dashboard/booths/[boothId]/menu/page.tsx | 4 +- src/app/dashboard/booths/actions.test.ts | 47 +++++++++++++ src/app/dashboard/booths/actions.ts | 6 +- src/app/dashboard/booths/menu-editor.tsx | 3 + src/app/dashboard/booths/menu-item-fields.tsx | 51 +++++++++++++- src/app/dashboard/booths/menu-item-row.tsx | 5 ++ src/app/dashboard/booths/menu-manager.tsx | 3 + .../dashboard/booths/use-menu-mutations.ts | 12 ++++ src/app/o/[code]/actions.place-order.test.ts | 18 +++++ src/app/o/[code]/actions.ts | 2 + src/components/order/README.md | 4 +- src/components/order/cart-summary.tsx | 8 +++ src/components/order/menu-item-card.tsx | 10 +++ src/components/order/order-form.dom.test.tsx | 39 +++++++++++ src/components/order/order-form.tsx | 65 ++++++++++++++---- .../help/menu-and-stock/menu-and-stock.ts | 6 +- src/hooks/README.md | 2 +- src/hooks/use-cart.ts | 6 +- src/lib/README.md | 5 +- src/lib/availability.test.ts | 41 ++++++++++++ src/lib/availability.ts | 37 +++++++++++ src/lib/min-order-qty.ts | 20 ++++++ src/lib/schemas.ts | 8 ++- src/lib/types.ts | 2 + .../migrations/0130_item_min_order_qty.sql | 66 +++++++++++++++++++ supabase/migrations/README.md | 1 + supabase/tests/README.md | 1 + supabase/tests/item-min-order-qty.test.sql | 53 +++++++++++++++ 31 files changed, 512 insertions(+), 29 deletions(-) create mode 100644 src/lib/min-order-qty.ts create mode 100644 supabase/migrations/0130_item_min_order_qty.sql create mode 100644 supabase/tests/item-min-order-qty.test.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 20d0a29d..9cef37f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ 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.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 @@ -18,8 +26,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). diff --git a/package.json b/package.json index 3c2022db..a8239a86 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "qkit", - "version": "0.6.2", + "version": "0.7.0", "private": true, "packageManager": "pnpm@11.28.5", "engines": { diff --git a/src/app/dashboard/booths/README.md b/src/app/dashboard/booths/README.md index f5f4fd22..150f58f5 100644 --- a/src/app/dashboard/booths/README.md +++ b/src/app/dashboard/booths/README.md @@ -41,7 +41,9 @@ through `saveMenuItems` and `saveMenuCategories`. `MenuEditor` owns grouping, item/section reorder, availability and duplication. Its pure ordering rules live in `menu-order.ts`, its drag-and-drop wrappers in `menu-sortables.tsx` and an item's price, cost, sold-out limit and section row in -`menu-item-fields.tsx`, which also holds the "Counts toward booth limit" tick +`menu-item-fields.tsx`, which also holds the "Minimum per order" field +(`minOrderQty`, any plan; `saveMenuItems` rejects one above the item's stock or +the booth's per-order limit) and the "Counts toward booth limit" tick (`excludeFromBoothLimit`, shown only with stock caps and a booth daily limit, and stripped on save without stock caps); `OptionGroupsEditor` owns choices, prices, costs and allergens. These are the exclusive application diff --git a/src/app/dashboard/booths/[boothId]/menu/page.tsx b/src/app/dashboard/booths/[boothId]/menu/page.tsx index 80a1d1e8..24dd898c 100644 --- a/src/app/dashboard/booths/[boothId]/menu/page.tsx +++ b/src/app/dashboard/booths/[boothId]/menu/page.tsx @@ -25,7 +25,7 @@ export default async function BoothMenuPage({ params, searchParams }: Props) { const { data: booth } = await supabase .from("booths") .select( - "id, name, menu_items, menu_categories, modifier_groups, daily_cup_cap", + "id, name, menu_items, menu_categories, modifier_groups, daily_cup_cap, max_items_per_order", ) .eq("id", boothId) .maybeSingle(); @@ -43,6 +43,7 @@ export default async function BoothMenuPage({ params, searchParams }: Props) { available: m.available, stock: m.stock, excludeFromBoothLimit: m.excludeFromBoothLimit, + minOrderQty: m.minOrderQty, category: m.category, })); const categories = parseMenuCategories(booth.menu_categories); @@ -57,6 +58,7 @@ export default async function BoothMenuPage({ params, searchParams }: Props) { hasBoothLimit={ booth.daily_cup_cap !== null && booth.daily_cup_cap !== undefined } + maxItemsPerOrder={booth.max_items_per_order ?? null} initialItems={items} initialCategories={categories} initialLibrary={library} diff --git a/src/app/dashboard/booths/actions.test.ts b/src/app/dashboard/booths/actions.test.ts index 5e244376..51ded951 100644 --- a/src/app/dashboard/booths/actions.test.ts +++ b/src/app/dashboard/booths/actions.test.ts @@ -403,6 +403,53 @@ describe("saveMenuItems", () => { 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/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 && (