Commit graph

244 commits

Author SHA1 Message Date
d32d71f55b refactor(orders): hoist WINDOW_DAYS, add 60-day boundary tests, clarify comment 2026-08-30 22:20:29 +02:00
a6d88cef1c feat(orders): widen DN repeat-match to any status, add 60-day window 2026-08-30 22:18:02 +02:00
75b1e524ad test(orders): pin no-match _attempted flag + 60-day boundary for order duplicate matcher 2026-08-30 22:15:36 +02:00
f981cf96c3 refactor(orders): drop no-op .replace('Z','Z') from pbDate helper 2026-08-30 22:12:31 +02:00
dae184ef57 feat(orders): flag exact item-match duplicates, same company, last 60 days 2026-08-30 22:10:39 +02:00
1a824d3477 fix(orders): document PB schema prerequisite + strengthen duplicate-matcher tests 2026-08-30 22:08:24 +02:00
9ec4cf2421 feat(orders): flag exact order_number duplicates, any status, no time limit 2026-08-30 22:04:57 +02:00
d59a2a1825 feat(orders): add cancelOrderItem service for soft-deleting lines
Operator-driven soft delete at item scope — flips item_status to
'cancelled' rather than removing the PB row, so any PO / DN /
invoice history the line carries is preserved for audit.

Mirrors cancelOrder's blocked-status list (delivered / invoiced /
cancelled): a line that's already reached the customer can't be
soft-deleted without orphaning the customer-facing record — a UI
gate should prevent the call from reaching the service, but the
service gate is the last line of defence.

The exclude_from_invoice flag doesn't affect eligibility — a normal
line and a non-invoiceable extra cancel the same way. The flag
only governs what reaches the customer invoice / delivery note.

When an actor is supplied, stamps [ISO timestamp] cancelled by
{name|id} on the row's notes field (appended, not replaced — preserves
any operator note that was already on the line). Soft delete leaves
a full audit trail in PB.

5 tests + 1 mutation-test prove:
- pending → cancelled (happy path)
- 404 when order doesn't exist
- 404 when item belongs to a different order
- 409 when item is already terminal (invoiced)
- actor stamp lands on notes
- mutation (don't flip the status): the happy-path test fails

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-30 20:06:26 +02:00
7a1239a187 fix(orders): bill the customer quantity, not the supplier order_qty
`order_items.order_qty` is the SUPPLIER-facing quantity — what prints
on the PO. Five call sites read it as the customer quantity, which is a
money bug in both directions:

  - supplier MOQ (customer 4, we buy 10) → invoiced 10, over-billing 6
  - shorted line (customer 100, supplier covers 40) → invoiced 40,
    under-billing 60 until the operator splits the remainder

The invoicing screen never fetched `quantity` at all (zero occurrences
in page.tsx), so it could not bill the customer quantity even in
principle. Added to the PB field projection, which is load-bearing:
drop it and PB returns undefined and every line silently falls back to
order_qty. A page-level test now fails if the projection drifts.

`maxSurplusFor` measured the surplus as `collected - order_qty`, which
on an MOQ line is always 0 — the overflow was mathematically unbookable
and vanished from inventory by construction, not by operator error.

Four call sites built delivery-note lines by hand; two passed
`quantity` and two forgot it, so the same DN printed the customer's 4
via the service layer and the supplier's 10 via the API routes. All
four now share `buildDeliveryNoteLine`, so they cannot diverge again.

`order_qty` had no doc comment at all next to an 11-line one on
`quantity` — that absence is why five subsystems guessed differently.
Now documented, with a new `src/lib/order-item-qty.ts` holding
`customerQty` / `supplierQty` as the single definition.

driver-stops.ts and collection-confirm/po-card.tsx read `order_qty`
CORRECTLY (they check what the supplier delivered against what we
ordered from them) and carry comments saying so, so the next cleanup
doesn't "fix" them into breaking.

23 new tests. Full suite: no regressions — the 15 failures are
identical before and after (verified by stashing and re-running).

Audit: docs/superpowers/specs/2026-08-30-quantity-handling-audit.md

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-30 18:28:33 +02:00
8b23cc1b6a feat(orders): bypass margin gate for non-invoiceable extras
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>
2026-08-30 17:21:28 +02:00
234ba6d3cd feat(orders): allow adding lines mid-flight, accept exclude_from_invoice
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>
2026-08-30 14:34:37 +02:00
4c5a312e16 feat(orders): type exclude_from_invoice field on OrderItem
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>
2026-08-30 14:30:17 +02:00
eb874bfd93 fix(orders): stop an order matching its own delivery note; include draft/loaded
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>
2026-08-30 14:09:23 +02:00
5a869c5f41 test(orders): widen makePb override param to a plain record 2026-08-30 13:57:30 +02:00
370a270b4c feat(orders): show a repeat-order pill when an order matches a delivery note
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>
2026-08-30 12:59:45 +02:00
fa28aca8bc feat(orders): detect delivery-note repeats at order intake
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>
2026-08-30 12:58:36 +02:00
3cf2837c3f feat(orders): add delivery-note repeat-order detection service
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>
2026-08-30 12:46:13 +02:00
e09de3cc80 feat(orders): add exact-match comparator for delivery-note detection
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>
2026-08-30 12:45:34 +02:00
623cfefc0d feat(orders): show quote line notes and attachments on the order detail page
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>
2026-08-30 12:45:02 +02:00
4e54fd6218 feat(orders): add quote-match backlog sweep with age-gap reporting
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>
2026-08-30 08:45:23 +02:00
093bbafe76 fix(orders): cover the after() fallback path and log when it engages
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>
2026-08-30 08:40:17 +02:00
21bc57797b feat(orders): auto-detect the source quote at order intake
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>
2026-08-29 14:22:21 +02:00
1453f14419 fix(orders): guard the pairing call site properly, correct comments
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.
2026-08-29 14:17:26 +02:00
a0e7e152f7 feat(orders): pair lines when a quote is linked to an order
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.
2026-08-29 14:06:10 +02:00
0a5f352784 fix(orders): close cross-line quote_item collision, pin pairing's field projections
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.
2026-08-29 14:01:13 +02:00
b4ad67680a feat(orders): persist confident order-line to quote-line pairs
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.
2026-08-29 13:49:39 +02:00
8e990e8a57 fix(orders): pin matcher's field deps, project queries, and stop swallowing real errors
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).
2026-08-29 13:44:56 +02:00
cefa52c3e3 fix(orders): chunk the fuzzy matcher's quote_items fetch, don't blow the filter length
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.
2026-08-29 13:32:23 +02:00
699512e216 feat(orders): add server-side quote suggestion service
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.
2026-08-29 13:22:52 +02:00
aba3bdca5d fix(orders): parse PocketBase date format explicitly in the matcher
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.
2026-08-29 13:20:40 +02:00
a4bc52b2ca feat(orders): add order-anchored fuzzy search window
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).
2026-08-29 11:28:10 +02:00
99050dcac5 fix(orders): wire LINE_PAIR_POSSIBLE into the pairing floor, add boundary test
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.
2026-08-29 11:23:38 +02:00
f2a1cbf586 feat(orders): expose tiered quote line pairing 2026-08-29 11:13:59 +02:00
7c3083c017 feat(quotes): add quote-level "Quoted before?" panel to the process page
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>
2026-08-29 08:52:19 +02:00
93cb898f1e feat(quotes): add repeat-request detection service
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>
2026-08-29 08:42:37 +02:00
113735d0ba fix(quotes): speed up archive search and add item preview to archive rows
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>
2026-08-29 02:30:14 +02:00
0efbae8dc5 feat(quotes): enhance search functionality and user experience
- 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.
2026-08-28 20:13:44 +02:00
5eed862007 feat(api): enhance order creation with optional email metadata fields
- 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.
2026-08-28 13:00:31 +02:00
dc0139a62c feat(api): add support for optional custom order_number in order creation
- 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.
2026-08-28 12:30:38 +02:00
16efafc111 fix(boss-dashboard): guard fetch races, surface errors, tighten response type 2026-08-28 00:19:12 +02:00
5a944bc1f9 test(boss-dashboard): honour expand in mock + assert customer name in rep activity 2026-08-28 00:02:02 +02:00
da1ccc48fd feat(boss-dashboard): paginated rep activity feed for drill-down sheet 2026-08-27 23:58:19 +02:00
9aaeee25ec fix(boss-dashboard): route unresolved orders.rep to (unknown) + parallelise 6th fetch 2026-08-27 23:55:59 +02:00
ebbcc73020 fix(boss-dashboard): exclude cancelled orders via order_items.item_status
The cancelled check was reading orders.item_status, which doesn't exist on
the orders collection in PB. Status lives on order_items, so the check
never fired and cancelled orders were counted in orderTotals.total and
each rep's ordersPlaced.

Mirror the delivered fix: derive a cancelled-order-id set from
order_items.item_status in the active window. An order is excluded from
total if ANY of its lines carries item_status="cancelled".

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-27 23:52:59 +02:00
9ec621e9f8 fix(boss-dashboard): pin drivers to today window + count delivered orders via order_items 2026-08-27 23:50:54 +02:00
721b310f4d feat(boss-dashboard): aggregate per-rep stats and driver stops per window
Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-27 23:46:25 +02:00
52b4b1f053 feat(boss-dashboard): add windowRange helper with UTC boundaries 2026-08-27 23:42:16 +02:00
Dave
cfd3e3e6be feat(quotes): add person_hint for customer resolution in forwarded emails
Introduces the `person_hint` field to the `EmailIntakePayload`, allowing the system to resolve the actual customer when a rep forwards an email. The `findOrCreateCustomer` function now prioritizes `person_hint` over the sender's email, enabling a more accurate attribution of quotes. This change includes a case-insensitive substring match with a token-drop fallback for multi-token names, ensuring better matching against existing customer records.

Additionally, new unit tests have been added to validate this functionality, covering various scenarios including token-drop behavior and ensuring the correct customer is linked when a rep forwards an RFQ.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-27 11:11:44 +02:00
Dave
dc84ce0f30 feat(quotes): resolve customer from person_hint when rep forwards email
Gary (and any future rep) forwards inbound RFQs to a shared mailbox.
Today the customer linked to the resulting quote is the rep (or the
Unknown Sender sentinel), because the only resolution path is exact
email match — the from_email resolves to Gary, not the actual customer.

Add person_hint to EmailIntakePayload. The AI extraction layer reads
the subject / body / signature for the customer being quoted FOR and
fills person_hint. findOrCreateCustomer now walks three resolution
passes in order:

  1. Exact email match (existing behaviour — direct RFQs unchanged)
  2. person_hint resolution: case-insensitive substring on
     customer.customer, with a companyHint tie-break when multiple
     candidates exist
  3. Existing sender-based create-new path (Gary wins, quoter
     reassigns in the WFDASH UI)

MCP schema for quotes.create_from_email surfaces the new field with
doc explaining the rep-forwarded case. /api/v1/quotes/from-email
doc updated. AI Agent system prompt in the n8n workflow doc now
extracts person_hint with worked examples.

Also extends the mock filter parser to accept PB's bare ~ operator
(production code uses ~; the mock previously only accepted =~).

5 new unit tests + 2 integration tests for the new path.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-27 10:45:51 +02:00
Dave
7986784eaf chore(tests): fix ~60 pre-existing TS errors across 11 test files
Typecheck cleanup after the deploy blocker push — `tsc --noEmit` was
silent on `d11a184` baseline but ~60 errors hid across test files
that only the compiler surfaces (the build was clean because test
files are excluded from the prod bundle). Touched:

- src/app/api/mcp/route.test.ts (16) — generic on `vi.fn()` for
  tuple inference; `as unknown as` two-step cast on record literals
- src/app/api/mcp/po-agent-workflow.test.ts (1) — spread instead of
  duplicate key
- src/components/buyer-tasks/buyer-task-group-card.test.tsx (5) —
  `PurchaseOrderEmailPayload` now requires `subject`/`body`
- src/components/collection-confirm/confirm-stock-dialog.test.tsx (1)
  — removed shadowed `id` from `makeRow` overrides
- src/components/item-intel-popover.test.tsx (2) — missing row
  fields + boolean→object for `verified`
- src/components/quotes/process-item-card.test.tsx (2) — full
  QuoteItem stub; generic on `vi.fn()`
- src/components/sprint-item-pricing-modal.test.tsx (3) — full
  SprintItem/QuoteItemAttachment/QuoteAttachment stubs
- src/lib/server/orders-service-review.test.ts (~60) — annotated
  `getOne` return type to break union widening on the expand option
- src/lib/server/orders-service.test.ts (2) — removed bogus
  `includeArchivedCounts` param; `rfq_number` now whitelisted on Order
- src/lib/server/quotes-service.test.ts (3) — two-step cast on
  Quote header; `unit?` now on QuoteItem
- src/lib/server/stock-purchase-items-service.test.ts (~10) — typed
  `pbMock` via `StockPurchaseItemsPb` so `*WithPb(pb,...)` checks

Also added two optional fields to `src/lib/types.ts`:
- `QuoteItem.unit?` — pre-2026 rows have no unit, so it's optional
- `Order.rfq_number?` — populated by the n8n email agent, inherited
  verbatim by `splitOrder`

Build: clean. Typecheck: 0 errors. Tests: 14 pre-existing runtime
failures + 1 pre-existing unhandled error in `supplier-form.test.tsx`
remain — confirmed they exist on `d11a184` baseline, so they are
outside the cleanup scope and unchanged by this commit.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-27 04:43:40 +02:00