Skip to content

fix(orders): sync KDS readiness to pickup board - #1404

Merged
khaira777 merged 10 commits into
mainfrom
fm/flocafe-1401-takeaway-customer-display
Oct 29, 2026
Merged

khaira777 merged 10 commits into
mainfrom
fm/flocafe-1401-takeaway-customer-display

Conversation

@khaira777

@khaira777 khaira777 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1401

Intent

Fix FloCafe issue #1401 ("Bug: Takeaway Order Status Not Updating") across order types and prepaid counter orders using a minimal YAGNI approach with no major product changes, no new settings UI, and no schema version bump:

  1. When KDS is enabled, automatically reconcile active (non-completed, non-cancelled) parent orders.status (pending, preparing, ready, served) transactionally from the order's full authoritative live item set across all order types (dine_in, takeaway, delivery, online) across all KDS item-status write paths and order-item mutation endpoints: promote pending -> preparing when kitchen work starts while unfinished items remain, promote to ready (Ready for pickup on /customer-display) only once all live positive-quantity items are ready (or mixed ready with already served/completed lines), promote to served once all live items are served/completed so handed-over orders clear off /customer-display automatically, and demote ready or served back to preparing (clearing stale ready_at/served_at) if unfinished items are appended, restored, edited to add pending work, or requeued.
  2. When KDS is enabled, include financially settled (orders.status = 'completed') orders that still have live items in pending, preparing, or ready on both authenticated and paired /customer-display feeds by projecting their effective board status (pending/preparing -> Preparing, ready -> Ready for pickup) from live item statuses without reopening or mutating orders.status = 'completed', and automatically omit them from /customer-display once KDS marks all live items served (Delivered).
  3. Keep /customer-display order-type eligibility, CustomerDisplayConfig.statuses filtering, KDS-disabled manual order-status workflows, and cancelled terminal orders unchanged.

What Changed

  • Reconcile active non-terminal orders.status (pending, preparing, ready, served) and lifecycle timestamps transactionally from live positive-quantity order_items when KDS is enabled via deriveOrderStatusFromItems and reconcileActiveOrderStatusFromItems, wired across KDS REST/standalone/WebSocket status updates, PATCH /api/order-items/:id/status, order-item append/cancel/edit/restore routes, and item refunds with order audit and cloud-sync events.
  • Project effective pickup-board statuses (pending, preparing, ready) from unserved live items for completed orders created within a rolling 24-hour window without mutating orders.status = 'completed', omitting them once all live items are served across paired GET /api/customer-display/feed and signed-in /customer-display.
  • Add pre-pagination ?board_status filtering on GET /api/orders, keyset-batched completed-order projection with page-level bill_number lookup on customer display feeds, and runtime-ensured partial index idx_order_items_active_kds at schema v121+ without bumping the schema version.

Risk Assessment

✅ Low: Active order status reconciliation runs transactionally only when KDS is enabled without mutating completed or cancelled orders or bumping the schema version, and both GET /api/orders (?view=active, ?status=active, ?board_status=...) and paired GET /api/customer-display/feed combine indexed active-queue selection with a bounded 24-hour completed-order KDS projection window (keyset-batched at LIMIT 200) so historical closed orders are never scanned.

Testing

Built the backend and static desktop frontend in the isolated worktree, ran the focused backend test suites for customer-display feeds, KDS contracts and integration, active order search, and schema-reference caching plus the Chromium Playwright pickup-board readiness and TV pagination E2E specs, and stood up an isolated multi-server FloCafe instance (Main API, standalone KDS HTTP/WebSocket, and Server App backed by a disposable SQLite database) to drive all five derived happy-path and adversarial scenarios live in Chromium with ten reviewer-visible screenshots and a sanitized JSON transcript captured in the evidence directory; every automated check and live scenario passed cleanly.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Kitchen advances a multi-item postpaid takeaway order on KDS and mutates items -> pickup board stays in Preparing on partial ready, moves to Ready for pickup only when all live items are ready, demote… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/01-postpaid-partial-ready-still-preparing.png, ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/01b-kds-sta…
Staff updates item statuses across dine-in, delivery, and online orders via standalone KDS HTTP, KDS WebSocket status_update, order-items status API, and partial-bill item refund -> parent orders.stat… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/live-scenario-transcript.json, tests/kds-contract.test.ts, tests/kds-integration.test.ts
Cashier settles an upfront-paid counter order before kitchen completion -> both signed-in and paired /customer-display boards project Preparing then Ready for pickup while orders.status stays complete… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/05-prepaid-completed-projected-preparing.png, ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/06-prepaid-c…
Store configures CustomerDisplayConfig.statuses to Ready-only behind 100+ newer Preparing orders -> signed-in ?board_status=ready and paired feed filter effective board statuses before pagination and… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/08-ready-only-filter-active-and-completed.png, ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/live-scenar…
Store disables KDS or cancels an order -> manual order-status transitions remain intact without KDS auto-demotion on item append, settled orders do not project onto /customer-display when KDS is off,… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/09-kds-disabled-manual-workflow-and-cancelled-guard.png, ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/l…

Paired pickup board keeps postpaid takeaway order in Preparing while 1-of-2 KDS items is Ready
Standalone KDS (:13502/kds-standalone) Tabs view showing split item progress on takeaway order
Signed-in pickup board promotes takeaway order to Ready for pickup once all live items are Ready
Paired pickup board demotes Ready order back to Preparing when unfinished item work is added
Paired pickup board clears postpaid takeaway order automatically once all items are Delivered
Signed-in pickup board projects settled prepaid counter order into Preparing while KDS items remain unfinished
Paired pickup board projects settled prepaid counter order into Ready for pickup without mutating orders.status = completed
Paired pickup board omits settled prepaid counter order once all KDS items are Delivered
Signed-in Ready-only pickup board surfaces active and KDS-ready settled orders on page 1 despite newer Preparing orders
Paired pickup board with KDS disabled preserves manual Ready order workflow and excludes settled and cancelled orders

Evidence: Sanitized JSON transcript of all 5 live multi-service browser, HTTP, and WebSocket scenarios
{
  "startedAt": "2026-10-29T17:23:18.767Z",
  "ports": {
    "main": 13501,
    "kds": 13502,
    "serverApp": 13503
  },
  "scenarios": {
    "scenario1": {
      "orderNumber": "ORD-20261030-0001",
      "transitionsVerified": [
        "pending -> preparing (1-of-2 ready stays preparing)",
        "preparing -> ready (2-of-2 ready moves to Ready for pickup on signed-in and paired boards)",
        "ready -> preparing on append (ready_at cleared)",
        "preparing -> ready on cancel blocker",
        "ready -> preparing on restore blocker",
        "ready -> preparing on quantity-increase item edit",
        "ready -> preparing on item requeue",
        "mixed served + ready stays ready",
        "ready -> served on all items Delivered (auto-cleared off both boards)",
        "served -> preparing on append (served_at cleared)"
      ]
    },
    "scenario2": {
      "dineInStandaloneHttpOrder": "ORD-20261030-0002",
      "deliveryWebSocketOrder": "ORD-20261030-0003",
      "onlineMainApiOrder": "ORD-20261030-0004",
      "partialRefundOrder": "ORD-20261030-0005",
      "allPassed": true
    },
    "scenario3": {
      "orderNumber": "ORD-20261030-0006",
      "billNumber": "INV-20261030-0002",
      "persistedOrderStatusThroughout": "completed",
      "projectedBoardStages": [
        "Preparing (pending)",
        "Preparing (1-of-2 ready)",
        "Ready for pickup (2-of-2 ready)",
        "Omitted (2-of-2 delivered)"
      ]
    },
    "scenario4": {
      "activeReadyOrder": "ORD-20261030-0007",
      "completedReadyBill": "INV-20261030-0003",
      "excludedCompletedPendingBill": "INV-20261030-0004",
      "newerExcludedPreparingOrdersCount": 105,
      "pairedFeedReadyOnlyOrders": [
        {
          "id": 7,
          "number": "ORD-20261030-0007",
          "status": "ready"
        },
        {
          "id": 8,
          "number": "INV-20261030-0003",
          "status": "ready"
        }
      ],
      "page1ReturnedBothReadyOrdersBeforePaging": true
    },
    "scenario5": {
      "manualActiveOrder": "ORD-20261030-0115",
      "kdsDisabledOrderItemStatusHttpCode": 403,
      "manualReadyPreservedAfterAppend": "ready",
      "excludedPaidWhenKdsOff": "INV-20261030-0005",
      "cancelledOrder": "ORD-20261030-0117",
      "cancelledItemMutateHttpStatus": 400,
      "cancelledStatusPreserved": "cancelled"
    }
  },
  "completedAt": "2026-10-29T17:23:51.047Z"
}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

🔧 **Rebase** - 1 issue found → auto-fixed ✅
  • ⚠️ docs/reference/api.md - merge conflict rebasing onto origin/main

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Kitchen advances a multi-item postpaid takeaway order on KDS and mutates items -> pickup board stays in Preparing on partial ready, moves to Ready for pickup only when all live items are ready, demote… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/01-postpaid-partial-ready-still-preparing.png, ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/01b-kds-sta…
Staff updates item statuses across dine-in, delivery, and online orders via standalone KDS HTTP, KDS WebSocket status_update, order-items status API, and partial-bill item refund -> parent orders.stat… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/live-scenario-transcript.json, tests/kds-contract.test.ts, tests/kds-integration.test.ts
Cashier settles an upfront-paid counter order before kitchen completion -> both signed-in and paired /customer-display boards project Preparing then Ready for pickup while orders.status stays complete… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/05-prepaid-completed-projected-preparing.png, ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/06-prepaid-c…
Store configures CustomerDisplayConfig.statuses to Ready-only behind 100+ newer Preparing orders -> signed-in ?board_status=ready and paired feed filter effective board statuses before pagination and… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/08-ready-only-filter-active-and-completed.png, ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/live-scenar…
Store disables KDS or cancels an order -> manual order-status transitions remain intact without KDS auto-demotion on item append, settled orders do not project onto /customer-display when KDS is off,… ✅ pass live ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/09-kds-disabled-manual-workflow-and-cancelled-guard.png, ~/.no-mistakes/evidence/01M648H4SWA17QTQM9X198YNZP/l…
  • npm run build && npm run build:frontend
  • npm run test:customer-display-feed
  • npm run test:kds-contract
  • npm run test:kds-integration
  • npm run test:schema-reference-cache
  • node tests/run-electron-node-test.cjs tests/orders-search-api.test.ts
  • cd frontend && CI=1 E2E_TASK_LOCAL_PORTS=1 E2E_BASE_URL=http://127.0.0.1:13401 E2E_KDS_BASE_URL=http://127.0.0.1:13402 E2E_SERVER_APP_BASE_URL=http://127.0.0.1:13403 npx playwright test --config=playwright.config.ts --project=chromium --retries=0 e2e/customer-display-kds-readiness.spec.ts
  • cd frontend && CI=1 E2E_TASK_LOCAL_PORTS=1 E2E_BASE_URL=http://127.0.0.1:13401 E2E_KDS_BASE_URL=http://127.0.0.1:13402 E2E_SERVER_APP_BASE_URL=http://127.0.0.1:13403 npx playwright test --config=playwright.config.ts --project=chromium --retries=0 e2e/layout-integrity.spec.ts -g "customer display wraps full receipt numbers and pages on TV"
  • Live isolated 5-scenario validation against node tests/e2e-server.cjs on ports 13501/13502/13503 driving Playwright Chromium signed-in /customer-display, paired /customer-display, standalone /kds-standalone, REST endpoints (/api/kds/items/:id/status on :13501 and :13502, /api/order-items/:id/status, /api/orders, /api/refunds, /api/customer-display/feed), and KDS WebSocket (ws://127.0.0.1:13502/kds)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Reconcile KDS order status and prepaid customer-display readiness

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Reconcile active order status from all live KDS items, including after item mutations and refunds.
• Show unfinished prepaid orders on both customer displays without reopening completed sales.
• Add indexed feed queries, regression tests, and lifecycle documentation.
Diagram

graph TD
  KDS["KDS writers"] --> Items[("Order items")] --> Derive["Status derivation"] --> Orders[("Orders")] --> Boards["Customer boards"]
  Mutations["Item mutations"] --> Items
  Items --> Projection["Completed projection"] --> Boards
  Orders --> Projection
Loading
High-Level Assessment

Shared derivation and transactional reconciliation address active orders while read-time projection preserves completed orders' financial status. A separate persisted fulfillment state would require a broader schema and lifecycle change for this targeted fix.

Files changed (22) +2570 / -292

Bug fix (11) +783 / -217
page.tsxProject prepaid status on the signed-in board +20/-11

Project prepaid status on the signed-in board

• Fetches active orders, derives board status for completed orders from their items, and applies configured status filtering to the effective status.

frontend/src/app/customer-display/page.tsx

kds-server.tsReconcile standalone KDS REST updates +30/-3

Reconcile standalone KDS REST updates

• Reconciles the parent inside successful item-update transactions and records resulting order changes for cloud sync.

main/kds-server.ts

kds.tsReconcile embedded KDS item updates +377/-182

Reconcile embedded KDS item updates

• Adds transactional parent reconciliation and post-commit cloud-sync notification to embedded KDS status writes. Much of the remaining diff formats existing route code.

main/routes/kds.ts

order-items.tsReconcile direct item-status writes +15/-0

Reconcile direct item-status writes

• Updates the parent in the same transaction as 'PATCH /api/order-items/:id/status' and emits a cloud-sync event when its status changes.

main/routes/order-items.ts

orders.tsInclude unfinished prepaid orders in active view +24/-12

Include unfinished prepaid orders in active view

• Uses indexed item candidates for active-order queries and reconciles parent status after item append, cancel, edit, and restore operations.

main/routes/orders.ts

refunds.tsNotify displays after item refunds +29/-0

Notify displays after item refunds

• Emits cloud-sync and KDS notifications after a non-replayed item refund, using the reconciled order status when it changed.

main/routes/refunds.ts

customer-display-tokens.tsMerge projected prepaid orders into paired feed +107/-3

Merge projected prepaid orders into paired feed

• Finds completed orders with unfinished KDS items, derives and filters their board statuses, then merges them into cursor-paginated feed results.

main/services/customer-display-tokens.ts

kds.tsReconcile WebSocket status updates +21/-1

Reconcile WebSocket status updates

• Reconciles parent status within successful WebSocket item-write transactions and records changed orders for cloud sync.

main/services/kds.ts

orders.tsCentralize active-order reconciliation +97/-2

Centralize active-order reconciliation

• Derives status from the full live item set when KDS is enabled, updates preparation and service timestamps, and audits parent transitions without reopening terminal orders.

main/services/orders.ts

refund.tsReconcile parent orders during item refunds +5/-0

Reconcile parent orders during item refunds

• Recomputes active parent status after an item refund changes the live item set.

main/services/refund.ts

order-item-status.tsDerive order readiness from live items +58/-3

Derive order readiness from live items

• Adds shared rules for excluding terminal or zero-quantity lines and deriving pending, preparing, ready, served, or display-projected status.

shared/order-item-status.ts

Tests (6) +1702 / -54
customer-display-kds-readiness.spec.tsExercise postpaid and prepaid pickup journeys +618/-0

Exercise postpaid and prepaid pickup journeys

• Adds Playwright coverage for KDS readiness, item append/cancel/restore, and automatic removal from signed-in and paired boards without reloading.

frontend/e2e/customer-display-kds-readiness.spec.ts

layout-integrity.spec.tsExpect active-view board requests +3/-3

Expect active-view board requests

• Adjusts the existing customer-display pagination test to assert the new 'view=active' request parameter.

frontend/e2e/layout-integrity.spec.ts

customer-display-feed.test.tsTest prepaid feed projection and pagination +263/-0

Test prepaid feed projection and pagination

• Covers projected statuses, configuration and KDS-disabled filtering, delivery removal, cursor deduplication, zero-quantity exclusions, and query-plan index use.

tests/customer-display-feed.test.ts

kds-contract.test.tsCover reconciliation across order types and mutations +518/-1

Cover reconciliation across order types and mutations

• Tests item-status transitions, multi-station visibility, timestamps, audits, cloud events, append/cancel/restore/edit/refund behavior, and terminal or KDS-disabled safeguards.

tests/kds-contract.test.ts

kds-integration.test.tsTest standalone REST and WebSocket reconciliation +234/-50

Test standalone REST and WebSocket reconciliation

• Verifies parent readiness and timestamps after standalone REST writes and staged WebSocket updates, including actor-attributed audit entries.

tests/kds-integration.test.ts

schema-reference-cache.test.tsTest runtime index backup compatibility +66/-0

Test runtime index backup compatibility

• Checks restoration without the runtime index, rejection of a mismatched index, and health of a historical pre-index schema.

tests/schema-reference-cache.test.ts

Documentation (4) +59 / -19
data-and-migrations.mdDocument runtime KDS index compatibility +7/-3

Document runtime KDS index compatibility

• Explains how the runtime-created index interacts with schema health checks and direct-restore backups.

docs/architecture/data-and-migrations.md

frontend.mdDocument customer-display status projection +9/-5

Document customer-display status projection

• Describes active-view pagination and how the signed-in board presents unfinished completed orders.

docs/architecture/frontend.md

order-lifecycle.mdDescribe KDS-driven order transitions +33/-2

Describe KDS-driven order transitions

• Defines live-item readiness, reconciliation triggers, audit behavior, and the distinction between active and completed orders.

docs/architecture/order-lifecycle.md

api.mdClarify KDS and display API behavior +10/-9

Clarify KDS and display API behavior

• Documents active-order eligibility, parent-status reconciliation on item updates, and projected completed orders in the paired feed.

docs/reference/api.md

Other (1) +26 / -2
db.tsEnsure an indexed active-KDS lookup +26/-2

Ensure an indexed active-KDS lookup

• Creates a partial order-item index at runtime for supported schemas and allows older backups to omit it while rejecting mismatched definitions.

main/db.ts

@qodo-code-review

qodo-code-review Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Kitchen updates never reach FloAdmin ⊘ Outdated
Description
The new KDS reconciliation paths call cloudSync.recordOrderChanged for order-status changes, but
FloAdmin has no handler for the /api/pos/events endpoint used to deliver them. When order cloud
sync is enabled, these newly queued notifications receive a 404 and remain undelivered.
Code

main/services/kds.ts[R576-579]

+        cloudSync.recordOrderChanged(
+          result.reconciledEvent.orderId,
+          `order.${result.reconciledEvent.status}`,
+        );
Relevance

●●● Strong

Cloud-sync events target an endpoint absent from the cited FloAdmin router, causing deterministic
delivery failures.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The changed KDS path records an order event. FloCafe posts queued events to /api/pos/events and
treats a non-OK response as a delivery failure; FloAdmin registers its POS routes without that
endpoint, and its router returns 404 for unmatched paths.

FloCafe -> FloAdmin
main/services/kds.ts[574-581]
main/services/cloud-sync.ts[2921-2927]
main/services/cloud-sync.ts[3070-3102]
External repo: FreeOpenSourcePOS/FloAdmin, src/routes/pos.php [438-534]
External repo: FreeOpenSourcePOS/FloAdmin, src/Router.php [10-29]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
New KDS status notifications are queued for an endpoint that FloAdmin does not implement.

## Fix Focus Areas
- main/services/kds.ts[574-581]
- main/services/cloud-sync.ts[3068-3090]
- /cross_repos/FloAdmin/src/routes/pos.php[438-497]

## Recommended Fix
Coordinate a signed `/api/pos/events` handler in FloAdmin that accepts the queued order events before relying on these notifications, and test delivery against that handler.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Every display poll loads all paid orders with open kitchen lines ✓ Resolved
Description
buildDisplayFeed calls .all() on completed-order queries without a SQL LIMIT, sorting and
materializing every matching order and computing its bill_number before the JavaScript loop stops
at FEED_ORDER_LIMIT + 1. When paid orders retain pending, preparing, or ready items, each
paired-board poll—up to 120 requests per minute—does work that grows with that history rather than
with the page of at most 100 orders.
Code

main/services/customer-display-tokens.ts[R233-241]

+        : db
+            .prepare(
+              `${completedSelect}
+               WHERE oi.status IN ('pending', 'preparing', 'ready')
+                 AND oi.quantity > 0
+                 AND co.status = 'completed'
+               ORDER BY co.created_at DESC, co.id DESC`,
+            )
+            .all()
Relevance

●●● Strong

Unbounded completed-candidate materialization conflicts with bounded feed work; similar
customer-feed limiting was accepted.

PR-#1105

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The active-order query uses LIMIT FEED_ORDER_LIMIT + 1, but neither branch of the
completed-candidate query has a limit, and both call .all(). The 101-row stopping condition runs
only afterward in JavaScript. Paying a bill marks its order completed without advancing its items to
served, so orders with unfinished items can continue accumulating in the candidate set.

main/services/customer-display-tokens.ts[209-289]
main/routes/bills.ts[3517-3532]
main/services/customer-display-tokens.ts[215-249]
main/services/customer-display-tokens.ts[276-306]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The completed-order candidate queries in `buildDisplayFeed` load and sort every matching order on each paired-feed poll, including a bill-number subquery per candidate, before JavaScript applies the page-size cutoff.

## Fix Focus Areas
- main/services/customer-display-tokens.ts[209-306]

## Recommended Fix
Fetch completed candidates in bounded, cursor-ordered SQL batches in both query branches. Project and filter each batch, then re-query using a `(created_at, id)` keyset cursor from the last candidate until enough eligible rows exist to merge with active rows and determine the next cursor, or no candidates remain. Compute `number` only for rows that make it onto the page.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Active-order pages rebuild the full queue ✗ Dismissed
Description
activeOrderPredicate uses an uncorrelated UNION to construct and deduplicate active order IDs
for every request. Cursor conditions and the page limit apply to the outer query, so fetching
successive signed-in display pages repeats that work across the active-order and kitchen-item sets.
Code

main/routes/orders.ts[R616-619]

+      const activeOrderPredicate = `orders.id IN (
+        SELECT id FROM orders WHERE status IN ('pending', 'preparing', 'ready', 'served')
+        UNION
+        SELECT oi.order_id FROM order_items AS oi
Relevance

●● Moderate

Repeated UNION work may affect large queues, but indexed subqueries and outer pagination make impact
uncertain.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new UNION has no cursor or limit within either branch; the cursor predicate and LIMIT are
added only to the outer orders query. The branches have indexes, but those do not remove the
repeated set construction and deduplication.

main/routes/orders.ts[616-625]
main/routes/orders.ts[754-781]
main/db.ts[7996-8004]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Each active-order page rebuilds and deduplicates an unbounded set of eligible order IDs before the outer cursor and limit are applied.
## Fix Focus Areas
- main/routes/orders.ts[616-625]
- main/routes/orders.ts[754-781]
## Recommended Fix
Make eligibility operate on cursor-constrained orders rather than an uncorrelated global `UNION`, while preserving the completed-order item predicate and checking the resulting query plan for later pages.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

4. Old paid orders reappear on the customer board ✓ Resolved
Description
projectBoardStatusFromItems and the feed/view=active predicates show any completed order that
has a positive-quantity line in pending, preparing or ready, with no time limit. Bill payment
marks orders completed without advancing their items. So when KDS is turned on after running
without it, or when kitchen staff mark items ready but never served, every such historical paid
order shows up on the customer-facing board as Preparing or Ready for pickup, and stays there until
someone bumps each item on the KDS.
Code

frontend/src/app/customer-display/page.tsx[R531-536]

+function resolveOrderBoardStatus(order: Order): string | null {
+  if (order.status === 'completed') {
+    return projectBoardStatusFromItems(order.items);
+  }
+  return order.status;
+}
Relevance

●● Moderate

Intent explicitly includes settled orders with live items, but unlimited historical projection may
create stale board entries.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
settleBill sets the order to completed and leaves order_items.status alone. Only the manual
PATCH-to-completed path marks items served. The new projection treats any pending item on a
completed order as Preparing, with no cutoff on completed_at or created_at.

main/routes/bills.ts[3517-3532]
main/routes/orders.ts[2929-2937]
main/routes/orders.ts[616-625]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Completed orders whose items were never bumped stay on the customer display forever, including history from before KDS was enabled.

## Fix Focus Areas
- main/services/customer-display-tokens.ts[219-239]
- main/routes/orders.ts[616-625]

## Recommended Fix
Only project completed orders whose `completed_at` (or `created_at`) falls within a bounded window, such as the current business day or the last N hours. Apply the same window in both the feed query and the `view=active` completed branch.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Eligible orders vanish from the signed-in board ✓ Resolved
Description
fetchOrders requests view=active without applying the configured statuses until after each page
is returned. If 5,000 newer active orders have statuses the display does not show, the 50-page limit
is reached before an older eligible order is fetched; a paired display can still show that order.
Code

frontend/src/app/customer-display/page.tsx[746]

+              view: 'active',
Relevance

● Weak

The same 50-page customer-display truncation concern was explicitly rejected in recent pagination
review.

PR-#1270

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new request fetches broad active pages, the client filters them afterward, and the loop stops
after 50 pages. The active predicate includes served and other statuses regardless of display
configuration, whereas the paired feed projects completed candidates before its final pagination.

frontend/src/app/customer-display/page.tsx[44-46]
frontend/src/app/customer-display/page.tsx[739-756]
main/routes/orders.ts[616-637]
main/routes/orders.ts[771-790]
main/services/customer-display-tokens.ts[276-306]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The signed-in display paginates all active orders, then filters configured statuses locally, allowing unrelated orders to consume its 50-page limit.
## Fix Focus Areas
- frontend/src/app/customer-display/page.tsx[739-756]
- main/routes/orders.ts[616-625]
## Recommended Fix
Provide a database-side board eligibility filter that applies configured effective statuses, including projected completed orders, before cursor pagination. Use it for the signed-in display rather than filtering a broad active result set only after fetching pages.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #39
  🌐 PR #34
⚠️ Tickets: not configured — No jira, linear integration is connected for the linked tickets
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
  Explored: repo: FreeOpenSourcePOS/FloAdmin (sha: e5d6830b) — View relationship
Review mode: Auto: 🧠 Deep: Broad transactional status logic spans many independent backend and display paths.

Grey Divider

Tip of the day
💡 Did you know, you can add REVIEW.md to your repo root and Qodo follows it on every PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread main/routes/orders.ts Resolved
Comment thread main/services/kds.ts Resolved
@khaira777 khaira777 changed the title fix: reconcile order status and customer display with KDS items fix(orders): sync KDS readiness to pickup board Oct 29, 2026
@khaira777 khaira777 changed the title fix(orders): sync KDS readiness to pickup board fix: reconcile order status and customer display from KDS items Oct 29, 2026
@khaira777 khaira777 changed the title fix: reconcile order status and customer display from KDS items fix(orders): sync KDS readiness to pickup board Oct 29, 2026
Reconcile active non-terminal parent order statuses (pending, preparing, ready, served) transactionally from the full live order_items set across all KDS item-status writers and order-item append, cancel, edit, and restore routes when KDS is enabled.

Project effective board statuses for upfront-paid completed orders that still have unserved KDS items on both authenticated /customer-display and paired /api/customer-display/feed boards via idx_order_items_active_kds without mutating completed orders or scanning closed sales history, omitting them automatically once all live items are served.

Fixes #1401
…end/e2e/customer-display-kds-readiness.spec.ts that caused strict-mode pos-product-card locator failures in diagnostics-checkout-recovery.spec.ts (and downstream End-to-End Playwright Tests / Required Checks Gate failures). Root cause & invariant: - Every Playwright spec sharing the single-worker tests/e2e-server.cjs backend must clean up any catalog categories, products, display tokens, settings overrides, and active KDS items it creates before subsequent specs run so the baseline single-product POS fixture (e2e-category / e2e-product) remains intact across specs and worker retries. - customer-display-kds-readiness.spec.ts created Pickup KDS 1401, Pickup Espresso 1401, and Pickup Croissant 1401 in beforeAll without deleting them in afterAll, leaving 3 pos-product-card buttons in /pos when diagnostics-checkout-recovery.spec.ts called addOneProduct(). Changes in frontend/e2e/customer-display-kds-readiness.spec.ts: - Added cleanupPickupCatalog() and wired test.afterAll to delete the created products first, then delete the now-empty Pickup KDS 1401 category, and restore snapshotted settings. - Guarded settingsSnapshot restoration in afterEach/afterAll if beforeAll fails early, and recorded orderId in cleanupOrderIds immediately on POST /api/orders in the prepaid test before awaiting bill/payment responses. Verification: - Reproduced the exact 4 failures before the fix by running customer-display-kds-readiness.spec.ts followed by diagnostics-checkout-recovery.spec.ts. - Re-ran both specs together after the fix: 7/7 passed. - Ran the full CI Playwright Shard 1/4 command (--shard=1/4 --retries=0): 87/87 passed. - Ran npm run lint, npm run lint:budget, node scripts/ci/check-changed-format.cjs --base 1d04ad3, npm run build, npm run build:frontend, and git diff --check: all passed. (Shards 2-4 of npm run test:e2e:browser were not re-run locally as they already passed in CI and only customer-display-kds-readiness.spec.ts in Shard 1/4 was modified.)
Bound completed-order KDS board projection to a shared rolling 24-hour orders.created_at window across paired and authenticated active feeds while keeping non-completed active orders unbounded.

Replace unbounded completed-candidate fetching in buildDisplayFeed with 200-row keyset batches and deferred page-level bill_number lookups, and restore the cursor-friendly correlated activeOrderPredicate in GET /api/orders.
Add a ?board_status query filter on GET /api/orders backed by shared pickup-board page selection so signed-in /customer-display filters effective board statuses (including <24h KDS-projected completed orders) before pagination instead of spending its 50-page fetch budget on excluded active statuses.
@khaira777
khaira777 force-pushed the fm/flocafe-1401-takeaway-customer-display branch from 8cd6288 to f2acccf Compare October 29, 2026 17:49
@khaira777 khaira777 changed the title fix(orders): sync KDS readiness to pickup board fix(orders): reconcile KDS status with orders and customer display Oct 29, 2026
@khaira777 khaira777 changed the title fix(orders): reconcile KDS status with orders and customer display fix(orders): sync KDS readiness to pickup board Oct 29, 2026
@khaira777
khaira777 merged commit 126f67d into main Oct 29, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-1401-takeaway-customer-display branch October 29, 2026 19:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Takeaway Order Status Not Updating

1 participant