Task 5 of the non-invoiceable-order-extras plan.
buildQbInvoicePayload now keeps order_item_ids built from ALL
rows (so n8n's 'Build PocketBase Invoice Update' node flips
excluded rows to invoiced alongside their siblings — the order
closes normally), and builds items from BILLABLE rows only (so
QuickBooks never learns about the excluded lines).
billableRows helper exported for sharing with the invoice UI
(Task 6) and the delivery-note route (Task 7) — three callers,
one definition of 'billable'.
Added exclude_from_invoice to RawInvoicingRow AND the
INVOICING_FIELDS projection. The projection is load-bearing:
omit it and PB returns undefined, every extra silently bills
the customer. Confirmed by inspection and by the failing
'mixed set' test if the projection drifts.
4 tests + 1 mutation-test prove the split:
- mixed: excluded ids in order_item_ids, absent from items
- all-billable: identical output to the no-flag case
- all-excluded: empty items, full order_item_ids
- billableRows helper unit tests
- mutation (items built from input.rows): mixed and all-excluded
tests fail
Co-Authored-By: Claude <noreply@anthropic.com>
Task 4 of the non-invoiceable-order-extras plan.
The page-level margin gate (process/page.tsx) short-circuits when
the item has exclude_from_invoice. An excluded line has
selling_price forced to 0 (Task 2), so the computed markup is
always -100 and the gate would wedge every extra into
approval_needed and block the order. Bypassing the gate keeps the
operational flow unblocked.
Suppressed low-margin colouring for excluded rows — a red
'-100%' chip on every extra is noise. The 'Not invoiced' badge
(T3) replaces the price chip visually.
Server-side guard in requestOrderItemMarginApproval refuses to gate
an excluded item with code 'excluded_from_invoice' (status 422).
Belt-and-braces: the MCP path can't weaponise the approval queue
to push an excluded row through manager review. Checked BEFORE
the missing_prices guard so an excluded item with selling=0 throws
the descriptive error rather than the misleading missing_prices
one.
2 tests + 1 mutation-test prove both sides of the bypass:
- excluded: throws 'excluded_from_invoice', webhook NOT fired
- non-excluded: proceeds to approval_needed, webhook DOES fire
- mutation (guard disabled): the excluded test fails
Co-Authored-By: Claude <noreply@anthropic.com>
Task 3 of the non-invoiceable-order-extras plan.
- New POST /api/v1/orders/{id}/items route wraps
createOrderItemForOrder. Same-origin browser auth (PB session
cookie), mirrors the posture of /quote after the order-quote
migration.
- AddItemSheet component on the process page: right-side Sheet
(mirrors PriceEditSheet's layout) with description / quantity /
cost / selling / supplier / notes + the load-bearing
'exclude_from_invoice' checkbox. When ticked, the selling-price
input is forced to 0 and disabled, a 'Not invoiced' badge replaces
the margin chip so a -100% red chip on every extra is noise.
- Add Item button below the item card stack — always available,
not gated on item_status. The empty-state copy above ('No line
items on this order. Add items before processing.') now points at
a real action.
- Existing excluded rows render with a muted 'Not invoiced' badge
in the card stack so the operator can spot them at a glance
without opening the sheet.
- The server (Task 2) forces selling_price=0 from the flag
regardless of caller input — the client forcing here is for UX
consistency.
Co-Authored-By: Claude <noreply@anthropic.com>
Dropped the pending gate in createOrderItemForOrder. The original
gate's reasoning was that adding a row alongside an in-flight PO
would orphan that PO's pricing/supplier reference — wrong model
of what adding a row does. A new row is independent: it gets its
own PO when the operator processes it, never mutates an existing
one.
The unrelated nonPending gate in setOrderQuote (preventing a
quote link change after items are past pending) stays — different
invariant.
exclude_from_invoice flag: when set, selling_price is forced to
0 regardless of what the caller passes — the flag is the source of
truth downstream, the price column is not consulted by the
invoice/delivery-note payload builders. The flag itself is
persisted in the secondary-field patch alongside sku/unit/
supplier/notes.
orderLocked return field kept for API compatibility — now always
false. Pre-existing callers reading the shape compile and read a
constant.
3 tests + 2 mutations prove the assertions guard real behavior:
deleting the flag-persistence line and the force-zero line each
break their target test.
Co-Authored-By: Claude <noreply@anthropic.com>
Added the boolean to src/lib/types.ts per the non-invoiceable
extras design. No behavior change yet — this is just the type.
Tasks 2+ wire up the operational flow.
Co-Authored-By: Claude <noreply@anthropic.com>
Two coupled corrections to delivery-note repeat detection.
Self-match: delivery notes have no line-item collection -- items are
order_items rows tagged with delivery_note_number. The Path A flow
stamps that number onto rows that KEEP their `order` relation, so a
processed order and its own DN are backed by the same database rows.
isExactItemMatch compared them against themselves and returned true
unconditionally. 149 live rows are in that state. Guarded both by DN
id and, for combined DNs whose `order` is empty, by inspecting the DN
rows' own order relation.
Candidate statuses: `draft` and `loaded` are real deliveries here.
The owner confirmed drafts simply never get advanced in the system,
and `loaded` is reachable directly from draft, so goods can go out
without ever passing through `sent`. Excluding both left a candidate
pool of 3 DNs out of 116, making the feature inert. Ordering matters:
the self-match guard had to land first, because the DN that exposed
the bug is itself a draft.
Cancelled stays excluded pending confirmation -- it is 84 of 116 and
may have been used to clear superseded delivery orders rather than to
mark abandonment.
Tests: a prior review showed by mutation that the existing tests
assert output shape but pin no scoping decision -- company-vs-customer,
the status filter and the tie-break could all be inverted with the
suite green. Added filter-inspecting and self-match tests, each
verified by mutation to fail when its guard is removed.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Blue Truck pill on the orders list, distinct from the amber quote
suggestion and the teal linked quote. Reads
potential_delivery_note_number (denormalized, no expand needed) —
the service writes the relation and the number in the same update
call so the list query doesn't pay for a second expanded relation
(see orders-service.ts:253 for why the codebase avoids that).
Additive — an order can show both a quote pill and a delivery-note
pill at once; they're independent facts (a repeat-order
observation, not a provenance link).
Added potential_delivery_note: string and
potential_delivery_note_number: string to the Order interface in
src/lib/types.ts so the page gets the new fields via full-record
return from getOrdersDashboardData (no fields: projection in the
list path).
Co-Authored-By: Claude <noreply@anthropic.com>
Thin wrapper around suggestDeliveryNoteForOrder(id). The route
mirrors the quote matcher's /quote-match endpoint for the case
where an order's items were edited after intake, or the order
predates the automatic intake check.
Co-Authored-By: Claude <noreply@anthropic.com>
Two independent try/catch blocks inside the existing runQuoteMatch
closure in createOrder. Each matcher (quote + delivery-note) is its
own scope, so a failure in one cannot starve the other. The
intake-path after()/E468 guard from Task 6 stays in place — this
adds the second matcher call alongside the first.
The 3-test block in createOrder delivery-note auto-detection proves
the independence in both directions: a quote matcher throw doesn't
prevent the delivery-note match, and vice versa. Mutation-tested by
merging the two try/catches — guards the design itself, not just
the wiring.
Co-Authored-By: Claude <noreply@anthropic.com>
Five new fields on the `orders` collection:
- potential_delivery_note (relation → delivery_notes, single) — the
DN whose items exactly matched this order's items
- potential_delivery_note_number (text) — denormalized copy of the
matched DN's delivery_note_number, written alongside the relation
so the orders list can render the number without a second `expand`
(PB issues a separate IN query per expanded relation —
orders-service.ts:253 documents why this is avoided here)
- delivery_note_match_confidence (number) — always 1 when set, kept
for shape parity with quote_match_confidence
- delivery_note_match_method (text) — 'exact_items' or 'no_match',
text not select for the same forward-compatibility reason
quote_match_method is text
- delivery_note_matching_attempted (bool) — audit flag
Idempotent — each step detects its own 'already done' state.
Verified by re-running after the first apply.
Plan-staleness fix: PB stores relation options FLAT at the top
level of the field object (collectionId / cascadeDelete /
minSelect / maxSelect), not nested under an `options` key. The
plan's snippet had the nested form and PB rejected it with
'fields.N.collectionId Cannot be blank.' Verified the correct
shape against the live orders.potential_quote field before fixing.
Co-Authored-By: Claude <noreply@anthropic.com>
Wraps the pure comparator with PB reads/writes. Same shape as
suggestQuoteForOrder:
- skip when order has no company (don't stamp attempted)
- write potential_delivery_note + number + confidence + method +
attempted:true on completion
- empty write when no candidate matched
Tie-break order:
1. priced quote match (status=delivery_note, selling_price == order)
2. most recent (created desc)
Co-Authored-By: Claude <noreply@anthropic.com>
Pure module — no I/O, mirrors the separation established by
order-quote-match.ts.
isExactItemMatch is multiset equality on (normalizeLine(description),
quantity). Empty sets return false (would otherwise vacuously flag
every zero-line order against every zero-line DN).
14 tests cover: exact match, qty diff, extra line on either side,
multiplicity enforcement, the empty-set case, normalization
collapsing whitespace + case, and punctuation-sensitive 'exact'.
Co-Authored-By: Claude <noreply@anthropic.com>
Closes the same vanishing-buyer-notes bug B12 fixed on the process
page, this time on the order detail page that operators see first.
- Inline row indicators (MessageSquare icon for a buyer note,
Paperclip + count for per-line attachments) inside the Description
TableCell. Hidden when the line has no signal. Click toggles a
QuoteLineContext panel below the row.
- QuoteLineContext panel wrapped in a Fragment-keyed extra row,
colSpan=8 (matches the eight TableHead columns: Description, Qty,
Selling, Supplier, Cost, Total, Status, Edit). The plan called
for colSpan=9, but the Driver column was removed 2026-08-24 and
the live count is 8.
- quoteAttachments intentionally empty in the detail-page panel —
order-level attachments have their own card below the table.
Migration off pb-helpers (AGENTS.md §'data access layer discipline'):
- /api/v1/orders/{id}/quote route now treats empty quote_id as the
unlink path (clears quote + potential_quote + matching fields),
and dropped assertAgentAuth so the page can call it from a
browser session (admin auth happens via the PB session cookie at
the PocketBase layer; the MCP forwarder still works without that
gate because the MCP route gates at its own boundary).
- /api/v1/orders/{id}/quote-match is a thin wrapper around
suggestQuoteForOrder (returns the new SuggestQuoteResult shape —
best.quoteId / best.quoteNumber, not the old best.quote.id /
best.quote.quote_number).
- Page migrated four pb-helpers calls: findMatchingQuotesForOrder →
POST quote-match, applyOrderQuoteMatch → merge into quote-match +
QuoteMatchCard accepts the result via SuggestionCard from the
fetched order, clearOrderQuoteMatch → POST quote with empty
quote_id, setOrderQuoteManually → POST quote with the picked id.
- runMatch signature simplified — accept-vs-suggest was the old
split; the new endpoint only ever suggests. 'Accept' now goes
through linkQuoteManually via POST /quote.
- Stale matcher block (4 functions + 3 helpers + re-exports +
imports) deleted from pb-helpers.ts. The pure scoring helpers now
import directly from @/lib/server/order-quote-match.
Known follow-up: QuoteMatchCard still reads from matchResult (a
QuoteMatchResult shape). Clearing matchResult after runMatch means
the SuggestionCard renders empty until the next fetchOrder lands.
Reads from order.expand.potential_quote after that. A future task
can rewrite the card to drop the in-memory result entirely.
Co-Authored-By: Claude <noreply@anthropic.com>
This is the actual fix for the vanishing-buyer-notes bug the matcher
service exists to prevent. Before this commit, the process page did
an exact/substring description match on every render — and silently
hid the buyer note whenever the PO's wording differed from the
quote's, even after the matcher had resolved a confident pair.
- Server-resolved linePairs now drives the per-item lookup in three
places (inline quote preview row, the price-edit sheet's matched
prop, and copyCostFromMatch).
- findMatchedQuoteItem — the local exact/substring guesser that was
the root cause — is deleted. No other callers exist.
- QuoteLineContext renders description (when different), buyer note,
per-line and quote-level attachments, plus the 'possible match'
banner + confirm button. Replaces a hand-rolled block that had
drifted from the orders detail page.
- QuoteLineNoMatch renders when the order has a quote relation but
this specific order line didn't pair to any quote line —
previously this case rendered nothing, which was indistinguishable
from 'the quote line had no note'.
- onConfirmPair POSTs to /api/v1/orders/{id}/quote-line (Task 10)
and re-runs fetchAll so the next render sees the pair as
'confident'. Only exposed for tier === 'possible'.
- The Pricing source grid stays inline — it's order-side data
(SKU / pricing_source / matched_price_list_id / pricing_notes
round-trip from quote_items onto order_items), not part of the
quote context, and is editable on the order.
Co-Authored-By: Claude <noreply@anthropic.com>
Shared presentation of a paired quote line — description (when it
differs from the order), buyer note, line attachments, quote
attachments, plus a 'possible match' warning banner for the
operator's confirm button.
Used by both the order detail table (Task 13) and the process page
(Task 12) so the two never drift. The process page used to own the
only copy; the detail page showed nothing.
tier='possible' framing is the load-bearing part: a buyer is never
shown a note from the wrong line without being told it might be
wrong.
Co-Authored-By: Claude <noreply@anthropic.com>
The order detail page and process page need the pairing, not the
matcher — until now the process page was doing an exact/substring
guess at render time and silently hiding buyer notes when the PO's
wording differed from the quote's.
- matched-attachments response gains linePairs (keyed by order_item_id,
carrying quote_item_id, confidence, tier). pairOrderLines is called
defensively — a pairing failure cannot kill the attachments
response (catch returns null → empty linePairs object, the rest of
the payload still serves).
- POST /api/v1/orders/[id]/quote-line writes the operator's confirm
decision (or unlink with empty quote_item_id) onto
order_items.quote_item. Guards against patching a line that
belongs to a different order (404 otherwise).
Both routes are additive — the existing matched-attachments fields are
unchanged, the MCP orders.list_attachments consumer keeps working.
Co-Authored-By: Claude <noreply@anthropic.com>
Pure move — bodies copied verbatim from process/page.tsx into
src/components/orders/attachment-list.tsx. The order detail page
(Task 13) will now import the same component instead of growing a
second copy.
The 4 icon imports (FileText, Image as ImageIcon, FileQuestion,
ExternalLink) became unused after the move and were removed from
process/page.tsx. Re-exported from the new file alongside the
MatchedAttachment type, attachmentHref helper, and inferKind helper.
No behaviour change. tsc clean. No new lint errors in the touched
files.
Co-Authored-By: Claude <noreply@anthropic.com>
Hermes (n8n) drops the AGENT_API_KEY on direct REST calls, so anything
n8n needs to run must exist as an MCP tool. This forwards the agent's
JSON-RPC call to POST /api/v1/orders/quote-match/sweep, mirroring the
existing orders.set_quote forwarding pattern.
Updated the tools/list expected-list test to include the new tool so
the catalog stays self-documenting.
Co-Authored-By: Claude <noreply@anthropic.com>
The matcher only runs on orders created from now on. This sweeps the
historical backlog plus any order whose lines changed after creation.
- sweepUnmatchedOrders in order-quote-link-service.ts walks
quote_matching_attempted = false && quote = '' (the codebase's
pattern for an empty relation, verified against orders-service.ts
usage) in batches, projecting only id (the wider order fields are
re-fetched inside suggestQuoteForOrder).
- bucketAgeGaps exposes the histogram that lets FUZZY_WINDOW_DAYS be
re-tuned from real data instead of the 90-day estimate.
- POST /api/v1/orders/quote-match/sweep is the agent-auth surface
with maxDuration=300 for the 500-order worst case.
Tests cover the filter shape, the field projection (load-bearing —
over-projection wastes wire bytes), the no-op on no-match path, the
fault tolerance (one row throwing doesn't kill the batch), and all
six histogram bucket boundaries including the ≤ N vs < N edges.
Co-Authored-By: Claude <noreply@anthropic.com>
The mock for next/server's after() detaches the callback regardless of
what production code does, which left the outer catch's fire-and-forget
fallback untested and the runQuoteMatch inner catch tested for nothing.
- New test 'falls back to an inline match when after() is unavailable'
forces after() to throw and asserts suggestQuoteForOrder was called
anyway, plus that the fallback log fired. Mutation: deleting the
'void runQuoteMatch()' line breaks it.
- 'never fails order creation when the matcher throws' now spies on
console.error and asserts the inner catch's swallow actually logged.
Mutation: deleting the inner console.error breaks it.
- The outer catch now logs [createOrder] after() unavailable... so a
silent switch to fire-and-forget (after upgrade, waitUntil missing on
deploy target) is impossible to miss in production logs.
- Comment names error code E468, Next 16.2.6, and
node_modules/next/dist/server/after/after.js, and corrects the
justification: createOrder is an exported service function reachable
from multiple layers, not 'a smoke script or another background job'.
Verified against the documented baseline — same single pre-existing
failure (splitOrderForContinuation > moves pending items...), no new
failures introduced.
Co-Authored-By: Claude <noreply@anthropic.com>
createOrder previously hard-coded quote_matching_attempted: false and
never scheduled a match, so ~85% of orders that correspond to an
existing quote arrived unmatched and stayed that way until an
operator opened the order and clicked a button. Fire
suggestQuoteForOrder(order.id) via next/server's after() once the
response has been sent, so intake latency is unaffected, and guard
both the matcher call and the after() call itself: after() throws
synchronously outside a request scope (confirmed by reading
node_modules/next/dist/server/after/after.js), so a caller without
one (e.g. a background script invoking createOrder directly) falls
back to firing the match inline instead of crashing order creation.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The previous commit's two "happy path" pairing tests never reset
pairOrderLines' mock call history — vitest.config.ts doesn't set
clearMocks, and the file's global beforeEach only clears the PB
store. A prior passing setOrderQuote test left toHaveBeenCalledWith
already satisfied on entry, so those two tests passed even with the
production call site deleted. Add mockClear() after the dynamic
import in both so they actually exercise the call they claim to.
Also: reworded the idempotent-path comment to note the strict-pending
gate runs first, so pairing only re-runs there while every line is
still pending (not a general refresh mechanism); fixed the
"don't write, don't stamp" line, which the pairing call now
contradicts (order_items.quote_item is a write); and replaced a
comment pointer to a nonexistent plan section with a standalone
statement of the deferred-signal gap.
setOrderQuote is the single choke point for creating orders.quote —
used by the UI, REST API, and Hermes/n8n. Call pairOrderLines(orderId,
quoteId) right after the hard link lands so confident order-line to
quote-line pairs persist automatically instead of needing a separate
manual step.
Pairing also runs on the idempotent no-op path (order already points
at the requested quote) — it's safe to repeat and lets an operator
refresh pairing by re-running the same call after editing order lines.
A pairing failure never fails the link itself (console.error only,
by design) — the hard link is the operator's important intent and
must land even if pairing can't complete.
pairOrderLines' no-overwrite guard only checked whether an order
line's own row already carried a quote_item, not whether the quote
line it was about to claim was already held by a different order
line. A description drift (or a hand-confirmed link) on one line let
a fresh confident match on another line silently double-assign the
same quote_item, so two parts would render the same estimator's note
and attachments — the exact failure this feature exists to prevent,
reached from the other direction. Fixed by seeding a claimed-quote-item
set from the fetched order rows before the write loop, and skipping
any confident pair that targets an already-claimed quote line.
unmatchedOrderItemIds now also excludes any line that already carries
a link, even when this run's pairing pass didn't re-propose it.
Also names the two field projections (PAIR_ORDER_ITEM_FIELDS,
PAIR_QUOTE_ITEM_FIELDS) next to the existing MATCHER_QUOTE_ITEM_FIELDS
constant, and adds a test that asserts on the actual `fields` string
passed to each getFullList call. Previously nothing distinguished
`fields: "id,description"` from `fields: "id,description,quote_item"`
at the order-items query — a one-token trim silently disabled the
no-overwrite guard (every row read as unlinked) with the full suite
staying green, since the existing behavioral tests supply `quote_item`
values directly in their fixtures rather than through the query. Verified
by re-running that exact mutation against the new test: it fails, and
neither pre-existing behavioral test catches it on its own.
Adds pairOrderLines to order-quote-link-service.ts: pairs an order's
lines against a quote's lines via pairQuoteLines, writes quote_item
only for confident (>=0.5 Jaccard) pairs, and never overwrites a
line's existing quote_item. Possible-tier pairs are returned but left
unwritten so an operator has to confirm them before a buyer sees a
note attached on a guess.
Reuses fetchQuoteItemsForQuotesAdmin (already used by the fuzzy pass
in this file) to fetch quote_items rather than reintroducing a raw
QUOTE_ITEMS_COLLECTION query. Writes stay sequential, matching the
existing bulk-update convention in orders-service.ts.
Six review findings on suggestQuoteForOrder, all bite hardest once
order intake and the backlog sweep start calling it:
1. fetchQuoteItemsForQuotesAdmin's `fields` string was a hardcoded
constant owned by the duplicate-quote scan. The matcher now passes
its own `fields` (an added, defaulted parameter) instead of
depending on that string never being trimmed out from under it —
losing `description`/`selling_price` would have collapsed every
confidence score toward zero with no exception and no failing
test.
2. The candidate-quote query in fuzzyPass had no `fields`, so it
pulled full quote records (email_body, ai_insights,
migration_meta) for up to 200 candidates, twice per order when the
window widens, to read five scalars. Added
`fields: "id,quote_number,company,customer,created"`.
3. findExactMatch's bare `catch {}` swallowed everything, not just
the "field doesn't exist on an older PB schema" case it claimed to
guard (all four fields exist per pb_schema-2.json). An expired
admin token or a PB blip during the sweep would silently fall
through to the fuzzy path, and writeSuggestion would then persist
quote_matching_attempted: true / quote_match_method: "no_match" -
permanently hiding an order that had a valid citation from the
sweep's retry filter. Narrowed to rethrow anything that isn't a
ClientResponseError with status 400.
4. Exact-identifier lookups (quote_reference_text, rfq_number are
customer free text) weren't scoped to the order's company, so a
reference-number collision across two customers could return a
confidence-1.0 suggestion pointing at the wrong company's quote.
Added `company = "..."` to the filter when the order has one.
5. SuggestQuoteResult.window used the literal "90d", hardcoding
FUZZY_WINDOW_DAYS. Renamed to "initial" so retuning the constant
can't make the sweep's reporting lie.
6. order-quote-link-service.test.ts's makePb forced every test to
redeclare the full collection map. Gave it a default map merged
with a per-test override and renamed useP to mockAdminPb, since
two more tasks add tests to this file.
Adds tests for #1 (matcher's quote_items fields include description
and selling_price), #2 (candidate query's fields), and #4 (a
same-reference quote belonging to another company is not returned).
fuzzyPass built a single `quote = "x" || quote = "y" || ...` OR-chain
across up to FUZZY_CANDIDATE_CAP (200) candidate quotes to fetch their
items. The predecessor in pb-helpers.ts documents exactly why that
doesn't scale: PB's filter expression has a max length, and a naive
OR-chain 400s past roughly 50 ids. There was no try/catch, so
getFullList's rejection propagated straight out of
suggestQuoteForOrder - the matcher failed outright for precisely the
high-volume companies where auto-matching matters most.
Reuse fetchQuoteItemsForQuotesAdmin (now exported from
quotes-service.ts) instead of a third copy of the same chunking logic.
It already does this for the duplicate-quote scan: try PB's `IN (...)`
syntax first, fall back to 80-id chunked OR-chains on rejection.
Adds a regression test that simulates PB rejecting an oversized filter
across 100 candidate quotes and asserts the fetch recovers via
multiple chunked calls rather than rejecting outright. Confirmed it
fails against the pre-fix code (uncaught rejection propagates out of
suggestQuoteForOrder) before verifying it passes against the fix.
Ports the PocketBase half of the order<->quote matcher off the
browser's PB singleton and onto getAdminPocketBase(), so matching can
run at order intake and from a backlog sweep instead of only on a
button click. Reuses the pure scoring in order-quote-match.ts
untouched (scoreOrderVsQuote, quoteWindowForOrder,
quoteToOrderAgeDays).
suggestQuoteForOrder tries the four exact-identifier fields first
(never date-limited), then falls back to a company/customer/
description/price fuzzy scan windowed to 90 days before the order
date, widening to 365 days only if that comes up empty.
Writes only the soft suggestion (potential_quote,
potential_quote_confidence, quote_matching_attempted,
quote_match_method) - never orders.quote, the hard link. Orders that
already carry a hard link are skipped untouched.
pb-helpers.ts's findMatchingQuotesForOrder is left in place; a later
task migrates its last UI caller and removes it.
Two findings from review of the quote-line-pairing task:
- quoteToOrderAgeDays: Math.round ties toward +Infinity, so a negative
half-day gap rounds to -0. Normalize to a clean 0.
- quoteWindowForOrder / quoteToOrderAgeDays relied on `new Date(...)`
parsing PocketBase's space-separated datetime form
("2026-08-29 10:00:00.000Z") the same as ISO 8601. That happens to
work on V8 but is implementation-defined per spec. Both now go
through a shared parseFlexibleDate helper that normalizes the
separator explicitly.
Adds tests pinning both behaviours; the existing 40 tests stay green.
Adds quoteWindowForOrder (pure) to constrain the fuzzy-match candidate
scan to a date window anchored on the order's own created date, plus
the forward grace period for quotes raised a few days after the PO.
Also adds quoteToOrderAgeDays, used by a later task's age-gap
histogram, with test coverage the plan omitted (normal, inverted, and
unparseable-input cases).
Code review found LINE_PAIR_POSSIBLE was decorative -- pairLinesByDescription
still filtered on a hardcoded 0.3 literal, so editing the constant wouldn't
change behaviour. Also adds a test pinned to an exact 0.5 Jaccard pair to
catch off-by-one mutations on the confident/possible tier boundary.
The original sample scored 0.222 Jaccard — below the 0.3 candidate
floor — so it would have been dropped rather than tiered. Verified
0.333 for the replacement.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
13 TDD tasks across two phases. Phase 1 (backend) ends with orders
matched automatically at intake plus a backlog sweep; Phase 2 surfaces
the paired quote line's note and attachments on both order pages.
Resolves the spec's two open questions: `after` is stable in
next/server on Next 16.2.6, and PocketBase date filters take
`.toISOString()`.
Two deviations from the spec, both noted in the plan: line pairing
hooks into the existing setOrderQuote rather than a new
linkQuoteToOrder, and the per-line context extends the existing
matched-attachments response rather than adding an endpoint.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Design for closing three gaps in the existing order↔quote matcher:
- The matcher only runs when an operator clicks it, so the ~85% of
orders that arrive against a quote stay unlinked. Adds a call from
createOrder plus a catch-up sweep for the backlog.
- order_items.quote_item is only written when an order is created
from a quote, so post-hoc links never pair lines. Adds persistence
for confident pairs.
- findMatchedQuoteItem re-guesses the pairing at render time using
exact/substring matching, so buyer notes and per-line attachments
silently vanish on any wording difference. Replaced with the
tokenised matcher already in the repo.
Fuzzy candidates are windowed to 90 days before the order's own date
(widening to 12 months only when nothing clears the threshold);
exact-identifier lookups stay unwindowed.
No PocketBase schema changes required.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Moving the admin panels below the items table left them at a third of
the row each (~186px of tab strip), which is too narrow for the labels
they carry. "Outbound" plus its count needs ~71px against the ~58px it
was given, so the three Attachments labels overlapped each other; the
same squeeze hit "Email Status" on the Activity card.
Lays the panels out two-up instead: Attachments spans both columns on
its own row (its three tabs, dropzone and file list want the space),
with Linked Orders and Activity sharing the row beneath at half width.
Both strips now have several times the headroom they need, measured at
a 1044px viewport, and mobile is unchanged (single column, no
page-level horizontal scroll).
Also drops the `ml-1.5` from the attachment count spans — TabsTrigger
already applies `gap-1.5` between its children, so the margin was
double-spacing and contributed to the overflow — and adds
`tabular-nums` so the tab widths stay steady as counts tick past 9.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The detail page was a 3-column grid with the Items card in a
lg:col-span-2 and the admin panels beside it. That left the items
table ~430px for a table whose natural width is ~790px, so pricing a
quote meant scrolling the table sideways.
Stacks the page instead: the items table (the actual work surface)
takes the full width, and Attachments / Linked Orders / Activity sit
3-up underneath, where they read fine at a third of the width because
they're reference panels rather than things you act on while pricing.
Two width trims make the table fit outright rather than merely fit
better:
- Description's min-width 360px → 280px. It's a floor, not a target;
the table is table-layout:auto so Description still absorbs any
width the fixed columns leave. 360 was forcing overflow on its own.
- The "Processed" header is whitespace-nowrap, so the word set a
~78px floor on a column whose content is a 2-3 character badge.
Renamed to "Done" (title="Processed") at w-[64px].
Measured at a 1044px viewport: the table went from 110px of horizontal
overflow to 0. Mobile is unaffected — it uses the stacked card list,
and the admin grid collapses to one column.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The table had 9 header cells against 8 body cells: a stray duplicate
"Description" header sat above the one carrying min-w-[360px]. Every
column therefore rendered one position off its label (the "Qty" header
sat over the supplier cell, "Supplier" over cost, and so on), and the
360px reserved for Description landed on Qty instead.
The visible symptom was a long description crushed into ~99px and
wrapped one word per line down a tall thin column, while the Qty cell
sat in 360px of empty space.
Removing the stray header restores the header/cell alignment and gives
Description its intended 360px. Also switches the row action from a
"Update price" text button to an icon-only button with the same title
and an aria-label, which trims the table's natural width from 911px to
789px — the card it lives in is only ~430px wide, so every pixel is
horizontal scrolling the operator has to do.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
When a mine puts a spot out to tender, several engineering companies
each ask us to price the same item list. Before pricing a new one the
operator wants to see what the earlier quote went out at.
The per-line answer already existed: populateItemIntel powers the ⓘ
popover on each row and returns recent_quote (prior quote number,
company, selling price, days ago). This adds no new matching logic —
it runs that same lookup across every line of a quote and rolls the
results up, so the operator gets one panel instead of clicking ⓘ on
each row.
What the roll-up adds over the per-line popover:
- "N of M lines have been quoted before" at a glance
- relatedQuotes ranked by HOW MANY of this quote's lines they also
carried; a prior quote covering 5 of 5 is very likely the same
tender from a different bidder, one covering 1 of 5 is a shared
commodity line
Two honesty details, both driven by what the first live run showed:
- match confidence is surfaced as close/likely/loose. The underlying
matcher accepts anything above 0.5, and a live check returned a
R150 hit against a magnetic base drill — a loose row must not look
as trustworthy as a close one.
- an unpriced prior quote renders "unpriced", never R0.00, which
would read as "we quoted it at zero".
Read-only: passes write:false so viewing the panel doesn't persist
intel onto rows the operator only looked at. On-demand rather than
auto-loading, since it costs one intel computation per line
(~400-650ms each, batched 5 at a time, capped at 40 lines).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Adds findDuplicateQuotes(), which groups quotes representing the same
underlying request. The business case is mining tendering: several
engineering companies each ask us to price the SAME item list because
they're all bidding for one spot on a mine, and the office needs to
find what the earlier quote went out at.
That inverts the usual dedupe rules, so both are deliberate:
- matching is CROSS-COMPANY (two customers sending the same list is
the signal, not a false positive)
- the email-body pass is CROSS-SENDER (bidders forward the same
tender document from different addresses)
Three passes: item_content (normalised line fingerprint, order
independent), email_body, and email_message_id.
Noise filtering is tuned against live data. The n8n intake writes an
"items from email request <name>" placeholder when it can't extract
line items; without excluding those, every unextracted email matches
every other one. A minimum line length drops junk like a bare "quote"
while keeping real one-liners the office genuinely re-quotes.
The completed-quote window measures `created`, not `updated`: a bulk
backfill rewrote `updated` on all 8,964 rows to a single timestamp, so
an `updated >=` cutoff matches the whole collection.
Not wired to the UI. A live run showed the quotes collection has no
trustworthy per-quote date (94% of `created` and 95% of `updated` are
migration stamps; quote_date and email_received_at are ~empty), so the
recency window can't currently bound the scan, and full-history content
matching returns groups of up to 53 for commonly-quoted commodities.
Landing the service on its own so the matching logic is available for
the on-demand "have we quoted this before?" lookup.
Also fixes a latent bug in the test PB mock's filter parser, which
stripped outer parens even when the leading "(" didn't match the
trailing ")", corrupting `(a) || (b)` into `a) || (b`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
.claude/launch.json lets the Browser pane start the app on :4001 by
name instead of needing a manually-run dev server. The .tmp screenshots
are visual verification captures from mobile dashboard debugging.
The archive's search fetched the entire recency-windowed matching set
(thousands of rows once "Include older" is on) and substring-filtered
it in memory, taking several seconds per keystroke; it now delegates
to the same ranked pushdown search service the main /quotes list uses.
Also fixes pagination being hidden while searching (results past page
1 were unreachable) and the match count showing the current page's
size instead of the true total.
Adds the chevron item-preview toggle to archive rows (extracted into
a shared QuoteItemsExpanded component, backed by a new GET
/api/v1/quotes/[id]/items route), removes a duplicate "Customer or
Company" label in the new-quote form, and drops the stray
warning-colored search box styling that leaked from DataTable onto
every list page that uses it.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
- Updated the search input handling to improve responsiveness by integrating a debounced search mechanism, reducing latency from 550 ms to approximately 300 ms.
- Added keyboard shortcut support for focusing the search box, enhancing accessibility and usability for frequent users.
- Improved the search placeholder to reflect all searchable fields, providing clearer guidance to operators.
- Introduced a clear-search button to streamline user interactions, allowing quick resets of the search input.
- Enhanced the display of search results with a live result count badge, providing immediate feedback on search outcomes.
These changes collectively enhance the search experience for operators, making it more intuitive and efficient.
- Added `email_sender`, `email_subject`, and `email_body` fields to the order creation input schema for improved traceability of inbound emails.
- Updated logic to include these fields in the order creation process, allowing operators to track the source of orders without needing follow-up updates.
- Enhanced documentation to reflect the new optional fields and their purpose in the order management workflow.
This update improves the audit trail for orders and enhances user experience by linking orders directly to their source emails.
- Introduced `order_number` field in the order creation input schema, allowing users to provide a custom identifier (e.g., PO/reference).
- Implemented logic to handle empty or whitespace values, defaulting to auto-generated order numbers.
- Added error handling for order_number collisions, returning structured error responses for better client-side handling.
- Updated documentation to reflect the new order_number functionality and its implications.
This enhancement improves order management flexibility and user experience.