Adds a small muted caption under the Re-Send / Mark as ready buttons
on the PO Sent tab showing the email address the PO was sent to and
the send timestamp (en-GB short format like '5 Aug 2026, 14:23').
Data sources come from the existing BuyerTaskGroup.emailPayload
exposed in commit f61c173 — no new PB fields, no new types. The
caption only renders when sentAt is present, so legacy rows (or a
fresh draft flipped to po_sent without a successful send) stay clean.
Visible on mail_failed too: the operator can see who we tried to
reach and when, alongside the existing 'Mail failed' banner.
Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: Orca <help@stably.ai>
Adds a Re-Send button next to Mark as ready on the PO Sent tab of the buyer-tasks page. The button opens the existing SendPoModal in resend mode, pre-filled from the PO's previous email_payload (to/cc/bcc/subject/body). Also migrates the hardcoded purple Mark-as-ready color to the themed primary token, and fixes the mail-failed 'Resend' label that previously opened the wrong dialog.
Add `sku` to the order_item.patch MCP tool whitelist and update its documentation
Fix stuck stock POs in buyer tasks po_sent tab by filtering out downstream statuses
Rewrite margin approval webhook to use fire-and-forget dispatch to avoid UI blocking, add server-side error logging
Add MCP feature requests and local setup documentation
Add a vitest suite that enforces critical layout invariants for the quote detail page, and include accompanying Playwright trace snapshots and console logs from the test execution.
This commit fixes a critical PocketBase projection bug where omitting "expand" from fields lists silently drops related data, leading to missing supplier/customer/order info across the app. It also includes usability improvements and test coverage:
1. Add "expand" to PB fields projections in invoicing page, quotes lookup API, sprint page, and quote search helper
2. Update PO Sent tab filter to exclude "collected" and "ready_invoice" statuses
3. Reorder buyer tasks list to sort by supplier first, then order number
4. Add comprehensive regression tests for all fixed issues
Included Playwright test capture artifacts from local testing.
- extract reusable constants and helper functions including escapeFilterValue, dedupeRawRows, listAllInvoicingRows, and loadInvoicingRows
- add safe filter value escaping to prevent query injection risks
- rewrite data fetching to pull all related order items for orders with ready-to-invoice rows, then deduplicate results
- replace raw getFullList calls with paginated PocketBase API usage
- update test suite to mock getList instead of getFullList and add coverage for new behavior
- clean up redundant eslint disable comments in modal components
Remove the initial open state for the first PO card, and update all tests to expect the default collapsed state. Users can expand cards manually to view contents, improving scannability for long PO queues.
- Add server-side `/api/v1/dashboard` endpoint to reduce client-side payload and round trips
- Implement invoice upload and order-item SKU update APIs with complete test suites
- Refactor order and order-items list endpoints (including MCP tools) to support proper PocketBase filter and sort params
- Fix pagination validation for order-items route to clamp page ≥1 and perPage 1-500
- Add redirects in next.config.ts to map underscore collection paths to hyphenated API routes
- Improve buyer tasks page to avoid redundant tab count refetches when switching tabs
- Refactor collection confirm components with editable SKUs and updated accessibility labels
- Add cached admin PocketBase auth to minimize repeated authentication calls
- Add performance testing scripts for dashboard endpoint latency
- Update quotes list route to default to excluding archived counts
- Fix photo strip component text and labels for non-invoice documents
- Refactor sprint page to lazy load supplier/customer data for pricing modal
- Clean up unused imports in test files
- Add full test coverage for all new APIs, services, and components
Production deploy failed the TypeScript type-check (next build exited 1)
because commit 2acfd2d changed CreateQuoteFromEmailResult.items from
'number' to 'QuoteItem[]' without updating:
1. The type import — QuoteItem was never added to the import from
@/lib/types (line 6 only brought in Quote, Customer, Company).
2. The dedup branch (line 1060-1076) — still passed itemsCount: number
where the new shape requires QuoteItem[]. Now fetches the real rows
via getFullList and sets items_count = items.length for back-compat.
The build log shows the error was visible right at 'Running TypeScript ...'
but the deployment platform's log scraper cut off the actual stderr,
making it look like an opaque DeploymentException. Reproduced locally
with 'npm run build' to confirm both errors.
Build now passes (no next build / tsc failures). All 1392 tests pass.
Co-authored-by: Orca <help@stably.ai>
The Source of truth panel previously only showed the email subject and
body inside a collapsed-by-default toggle. Operators couldn't see who
sent the mail or what the subject was without expanding the body.
This change adds a persistent header above the collapsible body with
two always-visible lines:
From: jane@acme.test (AtSign icon)
Subject: RFQ for 10x bolts (Mail icon)
Sender resolution chain (in getOrderReviewData):
1. order.email_sender — n8n ingest snapshot of the actual From:
on the inbound RFQ (best signal)
2. quote.email_sender — covers pre-snapshot legacy orders
3. customer.email — last-resort fallback
4. '' — renders as '(unknown sender)' placeholder
Subject already lived on the same record; the header just promotes it
out of the collapsed body so it's visible without expanding. The
existing '(no subject)' / '(no body)' placeholder pattern is matched
with a new '(unknown sender)' placeholder.
Tests: 7 new (3 modal header, 4 service sender fallback chain). 101
passing total.
Co-authored-by: Orca <help@stably.ai>
- order_items.update happy path: patches cost_price + qty_invoiced
+ supplier_invoice_number, verifies the whitelist strips nothing
and the row is written
- order_items.update forbidden: system-controlled fields (order,
purchase_order, quote_item, id) are rejected
- quotes.update regenerate_pdf:true: patch is saved first, then
the PDF endpoint is called with the freshly-persisted letterhead,
and the response includes both the updated quote and the new PDF
attachment metadata
- tools/list test count: 77 (was 76)
All 1385 tests pass.
Co-authored-by: Orca <help@stably.ai>
Two new capabilities, both requested by the agent for the
collected-vs-invoice reconciliation workflow:
1. order_items.update — patch fields on an order_item for invoice
reconciliation. Lets the agent compare what the supplier invoiced
(qty_invoiced + supplier_invoice_number + cost_price) against what
was ordered (quantity) and what was collected (qty_collected),
then write the differences. Whitelist mirrors the quote_items.update
pattern:
cost_price, selling_price, quantity, markup, markup_percent,
notes, qty_processed/assigned/collected/verified/stocked/picked/
loaded/delivered/invoiced/cancelled, supplier_invoice_number,
customer_invoice_number, collection_date, collected_date,
verified_date, delivered_date, invoiced_date
System-controlled fields (id, order, purchase_order, quote_item,
product, created, updated) are rejected with forbidden_field so
the agent can never accidentally reassign an item to a different
order or PO.
2. quotes.update with regenerate_pdf:true — the agent can now
switch letterhead (or any other header field) AND re-render the
PDF in a single call. The patch is saved first, then the existing
POST /api/v1/quotes/{id}/pdf route is called using the freshly-
persisted letterhead, so the response always matches the record.
Useful for: 'switch this quote to ISHERWOOD and send me the new
PDF'. Without the flag, the existing 2-step workflow still works
(quotes.update, then quotes.get_pdf).
All 1385 tests pass (was 1382; +3: regenerate_pdf happy path,
order_items.update happy path, order_items.update forbidden field).
Co-authored-by: Orca <help@stably.ai>
- quotes.list_attachments: proxies to GET /api/v1/quotes/{id}/attachments
- quotes.get_pdf: proxies to /api/v1/quotes/{id}/pdf/base64 (with optional
letterhead + regenerate query params)
- orders.add_attachment: posts multipart to /api/v1/orders/{id}/attachments/upload
- orders.list_attachments: proxies to /api/v1/orders/{id}/matched-attachments
All four tests use a stubbed global fetch (restored in finally) so
the MCP route's internal HTTP calls are deterministic and don't hit
the real server. Updated the tools/list test to include the four new
tools (76 total, was 72).
All 1382 tests pass.
Co-authored-by: Orca <help@stably.ai>
Closes the four gaps the agent flagged for the email→quote→PDF→send
workflow:
NEW REST ROUTES
- GET /api/v1/quotes/[id]/pdf/base64 — auto-renders the quote PDF
(idempotent against an existing pdf_generated_at) and returns it as
{ pdf: <base64>, attachment_id, filename, size, content_type,
letterhead }. 422 on placeholder customer / unpriced items. Used by
the new quotes.get_pdf MCP tool to give MCP clients a way to
download the rendered PDF — the streaming /api/v1/quotes/[id]/pdf
endpoint is still available for the WebUI's iframe.
- POST /api/v1/orders/[id]/attachments — uploads a file to the
order's MATCHED QUOTE. PB has no order_attachments collection;
orders share the quote_attachments table via their matched quote.
201 returns the new attachment + matched_quote_id so the agent can
confirm where the file landed.
NEW MCP TOOLS (catalog now 76, was 72)
- quotes.list_attachments — list all attachments on a quote
(generated PDF + original RFQ email attachments + operator uploads)
- quotes.get_pdf — auto-render + return the PDF binary as
base64 so the agent can save/forward/email it
- orders.add_attachment — upload to an order (proxy to the new
order upload route; multipart form)
- orders.list_attachments — list attachments on an order (proxies
the existing /api/v1/orders/[id]/matched-attachments route, which
returns the matched quote's attachments)
The 'upload to a PDF' workflow is now: attachments.upload_for_quote
(or orders.add_attachment) → quotes.list_attachments to see what's
there (including the generated PDF) → quotes.get_pdf to download
the PDF → quotes.send_email with selectedAttachmentIds to ship it all.
WHY the existing 'attachments.upload_for_quote' was not enough:
the agent previously had no way to retrieve the rendered PDF binary
or to attach files to orders. Now it has both. The order upload goes
via the matched quote because that's the single attachment table in PB.
All 1382 tests pass (was 1378; +4 for the new tools).
Co-authored-by: Orca <help@stably.ai>
- quotes.update: happy path with whitelisted fields, forbidden_field
rejection for system-controlled fields (status/customer/company/
quote_number/id), empty-patch rejection, missing-id rejection
- create_from_email: unit field now preserved end-to-end, result.items
returns the actual QuoteItem array (not just a count)
Also updates the existing tools/list test (now 72 tools, was 71) and
the create_from_email mock in route.test.ts to use the new
items/items_count shape so it matches the type.
All 1379 tests pass.
Co-authored-by: Orca <help@stably.ai>
Closes the two real gaps from the agent's gap analysis (2026-08-05):
1. **quotes.update MCP tool** — was missing entirely. The quote header
has fields (company_letterhead, quote_date, quote_reference, etc.)
that couldn't be patched via MCP, so the agent had to pass
letterhead at PDF-render time and couldn't persist it on the record.
Now exposed with a strict field whitelist mirroring the
quote_items whitelist pattern: any field outside the allowed set
(status, customer, company, quote_number, id, created, updated, …)
errors with forbidden_field rather than silently writing to PB.
New catalog entry + dispatch handler in src/app/api/mcp/route.ts.
Whitelist constant QUOTE_PATCH_FIELDS colocated with the existing
QUOTE_ITEM_PATCH_FIELDS for reviewer discoverability.
2. **create_from_email now preserves the unit field** — extracted_items
from the AI's RFQ parsing carries {description, quantity, unit,
notes} but the create loop was silently dropping unit. Also the
service returned items: <count> which made the agent believe no
items were created when in fact stub rows existed. Now returns
the actual QuoteItem array (with a back-compat items_count field)
and the unit value lands on each row.
The agent's third claim (PB admin auth unavailable) is a misdiagnosis
— WFDASH uses its own AGENT_API_KEY and all writes go through the
Next.js admin client. No code change needed for that.
All 1379 tests pass. quote_items.update path unaffected. The
quotes.update path mirrors the same pattern: whitelist + reject empty
patch + call pb.collection.update.
Co-authored-by: Orca <help@stably.ai>
Closes architectural gap #1 from the Giellie skill (the operator's AI
agent could ingest quotes via /api/mcp but had no way to enumerate,
add, or patch the resulting line items - every auto-price flow had to
stop and ask a human for the item IDs).
Adds:
- GET /api/v1/quote_items (list w/ filter, sort, expand)
- POST /api/v1/quote_items (create on existing quote)
- GET /api/v1/quote_items/[id] (fetch one)
- PATCH /api/v1/quote_items/[id] (whitelisted patch)
- quote_items.list MCP tool
- quote_items.get MCP tool
- quote_items.create MCP tool
- quote_items.update MCP tool
Patch whitelist on update is identical to bulk_update_quote_items:
cost_price, selling_price, description, sku, unit, supplier, markup,
pricing_source, pricing_notes, matched_price_list_id, user_edited
Everything else (id, quote, created, updated, quantity, is_processed)
returns 400 / MCP error with the allow-list echoed back so the agent
can self-correct.
quote_items.update does NOT enforce the already_priced skip - that's
the safety-net for bulk_update_quote_items. Single-row patches are
explicit writes.
Newly created rows have is_processed=false forced server-side; Giellie
still cannot flip the flag (architectural gap #2 unchanged - that's a
UI gate by design).
Also: removed "JEI" from quotes.company_letterhead select values on
the live PB - valid values are now ["CNL", "ISHERWOOD"]. Use the
uppercase form when setting this field.
Giellie skill doc refreshed: tool count 69 to 73, new "quote_items
CRUD" subsection, three new REST rows, architectural gap #1 marked
RESOLVED, hard rule #1 updated to cover the new endpoint, new worked
example for "add a missing line item + price it", change-log entry.
Tests: 82 passing across the three touched files (was 63 before).
Type-check: zero new errors (pre-existing 29 in
orders-service-review.test.ts unchanged).
Deployment: pending operator rebuild + redeploy. Until then
POST /api/v1/quote_items returns 404 and the new tools don't appear
in tools/list.
Co-authored-by: Orca <help@stably.ai>
Captures the full timeline of the 2026-08-04 incident where WFDASH
/api/mcp silently failed every spec-compliant MCP client's handshake
because the route didn't handle the mandatory 'initialize' method.
Includes:
- Symptom (Hermes log lines + WebUI '0 tools' display)
- Root cause (HTTP 404 on initialize → client terminates session)
- Fix summary (the three new handlers, with the critical 'don't use
the content envelope for initialize' gotcha)
- Verification recipe (curl against the live endpoint)
- Lessons to apply to other JSON-RPC endpoints we might add later
(initialize is mandatory; don't reuse the tools/call envelope;
HTTP 404 is a signal the endpoint isn't MCP at all)
Co-authored-by: Orca <help@stably.ai>
WFDASH /api/mcp previously only handled tools/list and tools/call,
which is fine for our internal curl-based testing but broke every
spec-compliant MCP client (Hermes, Claude Desktop, Cursor, mcp-cli).
The MCP protocol requires a three-step handshake before tools/list:
1. client → server: initialize
2. server → client: result with protocolVersion, capabilities, serverInfo
3. client → server: notifications/initialized (notification, no response)
Before this fix, step 1 got HTTP 404 with error.code -32601, which
MCP clients interpret as 'this isn't an MCP server' and terminate
the session. Symptom: configured servers show 'CONFIGURED' in the
Hermes WebUI but '0 tools', with the runtime logging
'unhandled errors in a TaskGroup ... Session terminated'.
Three new handlers, each with the right response shape:
initialize → 200 + plain result {protocolVersion, capabilities, serverInfo}
notifications/initialized → 204 + empty body (notification, no envelope)
ping → 200 + result {}
Critical: the initialize response uses a PLAIN object for result,
not the content/text envelope that our jsonRpcOk helper wraps
tools/list and tools/call results in. Using jsonRpcOk here would
have left the handshake broken in a subtler way.
Four new Vitest cases:
- initialize returns server info (regression: 2026-08-04)
- initialize echoes client-provided protocolVersion (forward compat)
- notifications/initialized returns 204
- ping returns {}
Bug report with full timeline + lessons: see
docs/bugs/2026-08-04-mcp-initialize-handshake-missing.md
(same commit series; pushed separately as the second commit).
All 46 tests pass.
Co-authored-by: Orca <help@stably.ai>
The earlier change log claimed the catalog went 69 → 70 after wiring
tools.discovery, but tools.discovery was already in the catalog from
the start — only its runtime behavior changed from 'Unknown tool' to
functional. Live post-redeploy smoke test confirms 69 tools.
Fix all six '70' references in the doc to '69', and append a second
change-log entry recording what was verified live after the redeploy:
- tools.discovery returns the flat 69-tool catalog via JSON-RPC ✅
- GET /api/mcp still works ✅
- 5 other bugs reproduce exactly as documented (validates the doc) ✅
- ISHERWOOD + CNL letterhead PDF regeneration on Q000087 still works ✅
Co-authored-by: Orca <help@stably.ai>
Bring the Giellie agent's operating manual in line with the live production
state after the 2026-08-04 smoke test against https://wfdash.apphub.co.za.
Bugs / quirks documented (with workarounds):
- tools.discovery was unwired; now fixed in code (separate commit),
live server needs redeploy before response changes
- orders.list silently ignores 'filter'; only 'search' is honoured
- quotes.lookup returns opaque 'fetch failed' — use quotes.list instead
- collection_pool.list + sprint.list return 'Missing collection context'
- orders.get 'not found' for at least one valid id
- quotes.items.rewrite was incorrectly listed as an MCP tool (it's REST)
Architectural gaps documented:
- No quote_items.list MCP tool; quotes.create_from_email returns item
count only, so a freshly-ingested quote's item IDs can't be recovered
via the agent API
- is_processed is intentionally NOT in bulk_update_quote_items whitelist;
end-to-end create→price→render pipeline requires human in the UI
Credentials & endpoints now include every token the agent might need:
AGENT_API_KEY, PB admin email/password, n8n base URL + API key, six
n8n webhook URLs (rewriter, price-list match, PO send, AI insights,
markup approval, customer list, QB invoice creator), TomTom map key.
Other updates:
- Replaced stale base URL wfdash.davidels.dev with wfdash.apphub.co.za
- Bumped tool count 69 → 70 (tools.discovery added to catalog)
- Added three-way tool discovery guide (tools/list, tools.discovery,
GET /api/mcp)
- Added 'Quote PDF rendering' guide explaining the 422 gates,
status transitions, and letterhead codes
- Added change log at the bottom
- All worked examples updated to the correct host
Co-authored-by: Orca <help@stably.ai>
The tools.discovery tool was declared in the catalog (line 1300) but no
tools/call dispatch branch existed for it — every call fell through to
'Unknown tool: tools.discovery'. Functionality was reachable only via
the parallel GET /api/mcp endpoint, which the JSON-RPC-only MCP clients
in n8n couldn't use.
Add a real handler that returns the same `tools` array as tools/list,
wrapped in the standard JSON-RPC content envelope. Mirrors GET /api/mcp
for JSON-RPC-only clients.
Also add a Vitest case that asserts the catalog shape (array of tools,
each with name+description+inputSchema, and tools.discovery in the list).
Deployment note: this fix is in source; the live apphub.co.za server
runs a built bundle and will keep returning 'Unknown tool' until rebuilt.
Co-authored-by: Orca <help@stably.ai>
The archive sort comparator in both getOrdersArchiveData and
getQuotesArchiveData was:
if (av === undefined) return 1;
if (bv === undefined) return -1;
return (av > bv ? 1 : -1) * sortDir;
PocketBase returns `null` (not `undefined`) for unset fields
like `updated`, `email_body`, etc. The strict equality check
missed nulls, and the `av > bv` comparison where one side is
null fails the production tsc check (TS strict mode rejects
`null > string`).
Production build failed with:
./src/lib/server/orders-service.ts:687:13
Type error: 'av' is possibly 'null'.
Fix: use `== null` (which matches both null and undefined),
and use explicit > / < comparisons that return 0 on equality
rather than a fragile ternary that falls through.
Also fixed in the matching function in quotes-service.ts — the
same sort comparator was used in getQuotesArchiveData and would
fail the same way.
All 1331 tests pass; npm run build completes cleanly.
Co-authored-by: Orca <help@stably.ai>
The webview shortcut in the "Other" sidebar group now displays as
"Giellie" instead of "Hermes". Only the visible label changes — the
underlying /webview?src=hermes URL parameter and the ALLOWED-map
key in src/app/(app)/webview/page.tsx are untouched, since those
are internal identifiers (the URL key is what looks up the embeddable
iframe in the ALLOWED whitelist, not a user-facing string).
If you want the internal key renamed too, that's a follow-up that
needs to update both the sidebar link and the ALLOWED map in the
webview route in the same commit.
Co-authored-by: Orca <help@stably.ai>
Two document scans (2481x3508, A4 @ 300 DPI) that landed in the
repo root. Adding them per user request to commit everything in the
working tree. No code references either file — they're untracked
artifacts from the workspace, not source assets.
# Tracked here so they're not lost
Co-authored-by: Orca <help@stably.ai>
Parallel to the orders archive treatment. On the live PB the
'Completed' tab on /quotes held 7,849 of 8,466 quotes (93%) and
the 'All' tab was 8,454. Same shape as orders: a 4k-id IN clause
blowing past PB's filter cap, with 'Page 1 of 392' on the tab
that operators didn't actually use for active work.
This commit moves both buckets to a dedicated /quotes/archive
page so:
- Main /quotes is fast (active workflow: new, claimed,
pending_approval, cancelled, delivery_note, email_failed,
problem, templates = 542 quotes vs 8,466)
- Archive can be honest about pagination
- The badge counts on the main page stop being dominated by
'Completed (7,849)'
# Service layer
- getQuotesArchiveData(params) in src/lib/server/quotes-service.ts
- view: 'completed' (default, 7,849) or 'all' (8,466)
- Strategy: one getFullList on quotes (fields: id,status) to
populate the matching set AND the header counts in a single
walk, chunk by 100 ids (PB's URL/filter cap is between
4.5-6.7 KB), fire parallel getFullList queries on quotes
with deep expand, sort + paginate in memory
- Search hits quote_number, quote_reference, rfq_number,
company, customer
- /api/v1/quotes/archive thin route: page, perPage, search,
sort, view
# Page
- /quotes/archive/page.tsx: card list with header counts
(completed / all badges), view toggle (Completed | All),
search input, pagination footer. Click a quote to open
/quotes/[id] in detail.
# Main /quotes updates
- Completed + All removed from the tab strip
- Counts on the main page now exclude completed + all
- 'Archive' button in the page header takes the operator to
/quotes/archive
- Safety useEffect: if activeTab is completed/all (e.g.
stale URL or local state), reset to 'new'
# Tests
4 new tests in quotes-service.test.ts:
- Default 'completed' view returns only completed quotes,
counts header includes both
- 'all' view returns every counted-status quote
- Search by quote_number and quote_reference
- Empty result when no quotes match
# Also: webview tweaks by another agent
- /webview?src=hermes label in sidebar
- Hermes URL whitelist updated
- Some header text removed (the probe status remains)
Full suite: 1331/1331 pass.
Co-authored-by: Orca <help@stably.ai>
Work by another agent on the PO send flow. Adds a 'Resend' CTA
on the order detail page for POs that were already sent
(operator wants to send another copy to the supplier), plus
acceptance of the same flow from the modal. Includes:
- purchase-orders-service: accept 'sent' as a resend-from state
(in addition to 'draft' and 'mail_failed')
- send-po-modal: title flips to 'Resend Purchase Order ...' when
the PO was previously sent; 'Send' button becomes 'Resend'
- send-po-modal.test: covers the resend path
- orders/[id]/page: shows Resend button in the same sendable
state group as Send (was draft / mail_failed, now also 'sent')
- purchase-orders pdf route: updates docstring to reflect that
status is the outbound-email pipeline's responsibility
- stock-purchases pdf route: download URL uses file proxy for
admin-auth compatibility
Co-authored-by: Orca <help@stably.ai>
The 'Delivered' tab on /orders was broken \u2014 4,326 of 4,514 orders
(96%) have at least one delivered item. The old tab tried to
build a WHERE id IN (...) filter with 4,326 ids (~120 KB),
blowing past PB's ~4 KB filter cap and 400ing. This commit
moves historical orders to a dedicated page so:
- The main /orders view is fast (22-28 active orders, not 4.5k
historical)
- The archive can be honest about its pagination ('Page 1 of
217' is expected when looking for something from last month)
- The badge counts on the main page stop being dominated by
'Delivered (4,326)' / 'Cancelled (111)'
# Measured against the live PB
/api/v1/orders/archive?page=1&perPage=2 \u2014 15.2s cold, 6.5 KB
response. The 15s is the order_items.getFullList over 13,256
items (the bottleneck; PB paginates over many round-trips).
Per-row payload is the standard 5-6 KB for orders with deep
expand. Subsequent pages within the same minute would be much
faster since PB caches the order_items query.
# Service layer
- getOrdersArchiveData(params) in src/lib/server/orders-service.ts
- Returns paginated list of orders with \u22651 item in
(delivered, cancelled) status, plus per-status distinct
counts for the header totals
- Strategy: getFullList on order_items (ids + status only),
dedupe + per-status counts in one pass, chunk the order ids
by 100 (PB's URL/filter cap is between 4.5-6.7 KB) and fire
parallel getFullList queries on orders with deep expand
- Search hits order_number, company, customer, contact_name
- Sort defaults to -created, override via the sort param
- /api/v1/orders/archive thin route: page, perPage, search, sort
(no tab, no nocache \u2014 archive is one bucket, not a tab split)
# Page
- /orders/archive/page.tsx: card list with header counts
(delivered / cancelled badges), search input, pagination
footer. Click an order to open /orders/[id] in detail.
# Main /orders updates
- Delivered + Cancelled removed from the tab strip (passed
tabKeys=['new','processing','collection_pool','collected'] to
ItemStatusTabs)
- Counts on the main page now exclude delivered + cancelled
- 'Archive' button in the page header takes the operator to
/orders/archive
- Safety useEffect: if activeTab is delivered/cancelled (e.g.
stale URL or local state), reset to 'new'
# Tests
4 new tests in orders-service.test.ts:
- Returns orders with \u22651 delivered/cancelled item, plus counts
- Dedupe: one order with multiple matching items counts as 1
- Search by order_number and contact_name
- Empty result when no orders match
Full suite: 1321/1321 pass.
Co-authored-by: Orca <help@stably.ai>
# Regression: orders/quotes list lost customer/company/rep data
Last commit added a `fields` parameter to the orders and quotes
list queries to trim the wire payload. Measured on a stale test
result, looked like a 16x win. Actual: PB 0.26's `fields`
parameter is a HARD ALLOWLIST of MAIN record columns only \u2014
specifying it makes PB drop the entire `expand` payload from
the response. Result: customer, company, rep, quote names
disappeared from every order/quote card.
Verified against the live PB:
- With `fields`: expand is dropped, just relation IDs returned
- Without `fields`: expand works, full records (55-57 KB for
20 rows with deep expand)
Fix: remove the `fields` parameter from both list queries. The
slim-payload intent has to be paid at the schema level (cap the
unbounded text columns) rather than via PB query params.
The earlier '12x smaller' / '16x smaller' benchmarks were
measurements of the BROKEN response, not the working one. Real
wire sizes are unchanged from before the perf work \u2014 but the
other wins (server-side tab filter, combined status counts,
targeted users fetch, 60s counts cache) all still apply.
# Bonus: show contact_name on the order card
~76 of ~4.5k orders have `contact_name` set (the free-text
person the order is for, captured during email-intake when the
customer record is just the company). Added to the OrderCard
header between customer and rep, with a docstring explaining
the distinction from the customer relation and email_sender.
Added contact_name to the Order type and pinned the regression
with a test that asserts the orders list query does NOT pass
`fields` (so a future 'let's slim the payload' attempt
doesn't reintroduce the bug).
# REP label
The rep column on the order card now reads 'REP' (uppercase)
instead of 'rep' (lowercase). All 1312 tests pass.
Co-authored-by: Orca <help@stably.ai>
Same shape as the orders refactor \u2014 applied to the quotes page,
with a fix for a long-standing tab-count bug along the way.
# Measured against the live PB (8,466 quotes, 4,514 orders, 25,612 items)
Before:
- 22 parallel per-status getList(1, 1) queries for the badge
counts: 2.6s wall time (no quotes.status index)
- 64 KB JSON response for 20 quotes with full deep-expand
(45+ fields per quote, including unbounded email_body)
- Page footer shows 'Page 1 of N' where N is the global count
\u2014 'Completed' tab had 7,849 quotes = 'Page 1 of 393'
After (no PB index, just code):
- 1 combined counts query: 138ms (19x faster)
- 5.5 KB JSON response (12x smaller)
- Server-side tab filter: page 1 of N reflects the tab's set
- Cancelled tab badge now correctly counts rejected+cancelled
# Server-side read model
- getQuotesDashboardData in src/lib/server/quotes-service.ts
- tab-scoped list + global counts in one round-trip
- tab param drives a server-side filter (status IN (...) for
workflow tabs, relation filter for delivery_note, is_template
for templates, excludeTemplate for 'all')
- pagination reflects the active tab's matching set, not the
global ~8.5k quote count
- getQuoteStatusTabCounts: one combined getFullList with all
17 counted statuses ORed (fields: 'status'), deduped in memory.
Replaces 22 separate per-status scans. Cached 60s on the server
with bypassCache option for future realtime refetches.
- /api/v1/quotes/list thin route: validates tab against
QUOTE_TAB_ORDER, threads tab + nocache params to the service.
# Slim wire payload
- fields param on the orders list: just the columns the page reads
+ per-expand limits (quote.quote_number doesn't need
email_body, company.company doesn't need its address field, etc.)
- Dropped the customer.company 3-level expand (the page never read
expand.customer.expand.company \u2014 only expand.company.company,
which is a direct relation from quote)
- searchQuotesWithItems: same fields added, with
fetchQuoteItemsForQuotes now accepting fields
# Bonus bug: 'Cancelled' tab badge was always empty
The old getQuoteStatusCounts mapped both 'cancelled' AND 'rejected'
to the 'completed' count, so the page's 'Cancelled' tab badge
showed 0 even when 60+ rejected quotes existed. The page's
tabFilters separately grouped them under 'cancelled', so a quote
that was rejected showed up in the list but not the count.
The new QUOTE_TAB_STATUSES in the service layer is the canonical
mapping (cancelled absorbs both statuses). Page constants and
service constants now derive from the same source \u2014 no more drift.
# Index migration
scripts/migrations/2026-08-04-add-quotes-status-index.ts. Idempotent.
The live PB has no quotes.status index today (verified by hitting
/api/collections/quotes). With the index, the combined counts
query drops from 138ms to sub-10ms on the live instance.
# Tests
6 new tests in quotes-service.test.ts:
- QUOTE_TAB_STATUSES contract (cancelled absorbs rejected,
no empty status lists unless special-cased)
- getQuoteStatusTabCounts buckets correctly into tabs
- Cache hit returns the same counts on second call
- bypassCache: true sees new state
- getQuotesDashboardData end-to-end: tab-scoped items +
global counts
- Regression guard for the cancelled/rejected bug
Mock infrastructure upgrade: the quotes-service mock's where
function is now a proper recursive-descent filter parser (handles
nested || inside parens, empty quoted values). getList mock now
returns totalPages.
Full suite: 1312/1312 pass.
Co-authored-by: Orca <help@stably.ai>
Three rounds of fixes for the /orders page:
#1 Correctness \u2014 server-side tab filter
- Add `tab` query param to /api/v1/orders/list; the route validates
it against TAB_GROUP_ORDER and threads it to getOrdersDashboardData.
- listOrdersWithItems now resolves order ids for the tab via
getOrderIdsForTabGroup (using the existing tabGroupFilter helper),
then fetches just those orders. The footer pagination reflects
the matching set ("Page 1 of N"), not the global 4520-order
count ("Page 1 of 226"). The "Processing (4)" badge now
matches what page 1 actually shows.
- Client: fetchOrders depends on activeTab, so switching tabs
triggers a fresh server-side query. The redundant visibleOrders
client filter is removed. The empty state now nudges the operator
to busy tabs ("Busy tabs: New (12) \u00b7 Delivered (4)").
#2 Perf \u2014 combined counts + targeted users + slim deep expand
- getOrderItemStatusTabCounts collapses 6 parallel per-tab
getFullList calls into ONE combined query, with batch: 5000.
6 filter scans \u2192 1 scan; ~9x fewer internal round-trips.
Bumped cache TTL 30s \u2192 60s.
- Replaced users.getFullList with fetchRepUsersForOrders \u2014 only
fetches the user ids the loaded orders actually reference.
- Dropped potential_quote from the deep expand (list view only
checks the field's existence).
- Added a migration script for the order_items.item_status index
(scripts/migrations/2026-08-04-...). Idempotent: the live PB
already has the index per the schema export, so the script
no-ops on most installs; documented as the recommended manual
step in case an older instance is missing it.
#3 Perf \u2014 wire-payload limits on deep expand
- The quotes collection has unbounded text fields (email_body,
email_message). Without limiting, the orders deep-expand was
dragging the full email body of every linked quote into the
list response \u2014 20 orders with deep expand = 1-5 MB JSON.
- The orders list now passes a `fields` param with the
`expandField.subfield` syntax PB supports: only
`quote.quote_number`, `company.company`, `customer.customer`,
`customer.rep.{id,name,email}` come back, not the full records.
- The items query likewise limits fields to the 8 columns the list
view + search predicate actually read; the supplier expand (not
rendered per-line) is dropped.
Tests: 22 new tests in orders-service.test.ts (tab filter, cache
bypass, combined-query call count, pagination honesty, field-list
contract). Full suite: 1306/1306 pass. The mock's where helper was
upgraded to support || and != / =~ / !~ operators, and the
getFullList mock now honours the filter arg.
Realtime: debounce bumped 300ms \u2192 1000ms, and the realtime path
passes nocache=1 so the 30/60s tab-counts cache is bypassed on
changes the operator just made.
Co-authored-by: Orca <help@stably.ai>
Three review-modal polish items rolled up:
1. Persisted line items now expose a description input in edit mode
(mirroring the existing qty / selling inputs). The save route +
the orders service's `updateOrderItemsPrices` accept the new
`description` field and write `description` + `po_description`
together (rejecting a blank description per row, with a
per-row failure entry so the operator can retry just those).
2. The source-of-truth panel now ALWAYS renders the email body, not
only when there are no attachments. The body is collapsed by
default and capped at `max-h-40` so the email stays a secondary
audit block instead of pushing the operator's real work
(line items + attachments) down the page. The toggle button is
unchanged.
3. The chip strip and file list inside the source-of-truth panel
were using `key={a.id}`. `orderAttachementsToQuotes` synthesizes
every attachment with `id: order.id` (PB file URLs need
`/files/{collectionId}/{recordId}/{filename}`), so a multi-file
order was throwing 'Encountered two children with the same key'.
Switched to `key={a.filename}` — unique per file in the
multi-file field, leaves the file URL untouched.
The Order type grew `email_subject`, `email_sender`,
`email_body`, and `email_message_id`. These columns exist in the
live PB (the local `pb_schema-2.json` snapshot is reference-only
per AGENTS.md, so the drift is expected). `getOrderReviewData`
prefers the order's own `email_body` and falls back to the
related `quote.email_body` for legacy orders that pre-date the
snapshot columns — quoting the operator's outbound is better than
showing '(no body)'.
Co-authored-by: Orca <help@stably.ai>