Commit graph

234 commits

Author SHA1 Message Date
b212d0fcd8 feat(manager): a mobile orders board for the managers at /manager
A hidden, installable PWA: one link, opened on a phone, showing where
every order is. New / Processing / Completed, with a tap-to-preview
popup and the invoice/line detail Gary needs. Read-only, and NOT in
the sidebar — the route lives outside `(app)`, so `<Sidebar />` never
renders there.

The preview popup is reused, not rebuilt: the service emits
`UniversalHit`s and the page hands them to the existing
`SearchPreviewDialog`, so the manager gets the desk's quick-overview
verbatim.

Also fixes the /orders Completed tab, which was matching ZERO orders.
`delivered_at` is stamped on only 2 of 12,957 delivered lines and the
business stopped writing `delivered` on 2026-08-14 (the live pipeline
now ends at `invoiced` / `checked_in`), so the old filter never
matched. "Settled" is now defined once — `SETTLED_STATUSES` +
`SETTLED_DATE_FIELDS` — and dated per status: `invoiced_date` for
invoiced (the only properly stamped field, 2,199 lines), `delivered_at`
for delivered, `updated` only where no dedicated column exists.

`delivery_note` and `checked_in` move into `completed` as instructed,
and the standalone `post_processing` tab is retired (a DN is not a
stage of its own). `invoiced` stays in `collected` as well, so
invoiced orders don't vanish from the workflow tabs.

Completed tab: 0 -> 341 orders over 30 days, 112 over 7.
2026-10-26 23:09:01 +02:00
a6d53e3b2b feat(price-check): say whether the POS item is exact or only closest
The blue badge read the same whether the AI had matched the item
exactly or only found the nearest one, so a line priced from an M22
bolt looked like any other line.

Now an exact pick reads as before, a closest pick leads with
"Closest: {name} ({differs})" and raises a closest_only flag, and a
fuzzy match keeps its "Similar items:" wording. The popover shows the
pick and the differences at the top.

A refresh is still a no-AI recompute, but it keeps the stored pick
instead of throwing it away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 23:05:09 +02:00
b7e80e7f85 feat(quote-assistant): price only an exact match, show the closest
A near-miss used to be priced as if it were the item the customer
asked for. Now only an exact match writes a price; a closest match
writes none and records the nearest item with what differs, so the
rep can see it and decide.

The "AI: no match" badge reads "Closest: {name} ({differs})" when
there is a closest item, and the popover shows its price and the
differences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 22:59:25 +02:00
8ef10f9f75 fix(price-check): keep the badge in step with the line's stored intel
The line's ai_item_insights can change under the badge (the assistant
fills the line, the operator saves it) and router.refresh() keeps the
component mounted, so the badge would keep showing the intel it read
at mount. Mirror the prop into local state instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 21:59:56 +02:00
9b3f30a01f feat(process): show the blue price check on both Process pages
The blue price-check badge now appears under the purple AI marker on
every line the AI filled (reviewed or not):

  - quote Process page, mobile card: its own row under the header, so
    the one-line summary is readable on a phone
  - quote Process page, desktop table: inside the Description cell
    rather than the cramped 32-px "#" column, which has no room for a
    summary
  - order Process page: its own full-width row under the markers, so
    the summary is readable on a phone

The summary truncates rather than wrapping — the popover always shows
it in full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 21:45:46 +02:00
3248e3aa03 feat(ui): blue price-check badge with its popover
The blue badge that sits under the purple AI marker: a tag icon plus the
one-line summary, with an orange dot on the icon when the price check
found something worth a look.

The popover shows POS stock (on hand, status, cost, sell, supplier), the
top three price-list matches, what we last paid each supplier, what we
quoted and ordered before, and how the match was made ("POS item the AI
picked" / "Matched by SKU" / "Similar items"). Refresh re-computes the
intel through the existing /api/v1/items/{collection}/{id}/intel/refresh
route and reads the line back afterwards.

Also closes the colour-token gap: globals.css mapped --color-info to
var(--info), but --info / --info-foreground were never defined, so
text-info rendered nothing. They now have a light and a dark fallback
next to the --ai tokens; themes that define their own --info still win.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 21:33:50 +02:00
d3a52d97f2 feat(orders): purple review for AI-filled order lines
A line the AI filled now shows up purple until a person checks it, so
nothing the assistant priced is ever taken on trust.

- order-assistant-review.ts: the four client helpers — a line is
  pending only while it is filled, unreviewed and still priced from
  the quote; a human save keeps "ai_quote" / "quote" / "catalogue" and
  turns anything else into "manual"; the review patch records who
  checked the line and whether the prices were accepted unchanged.
- order-assistant-save.ts: the save-time merge, the order-side twin of
  quote-assistant-save.ts. The value the operator committed wins over
  the one the page was loaded with, so the one-click "use this cost"
  copy really does end the AI's provenance.
- The Process page applies the purple row class, shows the bot marker
  with the quote it was filled from, the reason and the doubts, and
  routes every line save through the merge.
- The Orders board shows an "AI x/y" badge: how many lines the AI
  filled, and how many still need a review. One query per page, and
  never fatal — the board has to render whether or not the assistant's
  columns exist yet.
- AiFillMarker grows an "order" variant instead of assuming a POS item.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 14:25:11 +02:00
00d09b3b12 feat(orders): show AI quote match on the order page
Task 8 of the AI order assistant plan.

- new AiQuoteMatchPanel: "Linked by AI" / "AI suggests Q…", the
  reason, the doubts and the line-pair table (order line -> quote line
  with same_item)
- the quote match card gains a "Match with AI" button in every state,
  posts to /api/v1/orders/{id}/assistant/run with the PB token, toasts
  the 409 message verbatim, then reloads the order
- new card state: the AI suggested a quote -> the AI panel + Accept
  (links the AI's quote) / Match with AI / Dismiss
- the AI suggestion marks the order as quote_matching_attempted so the
  deterministic sweep cannot overwrite it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 13:13:28 +02:00
e4fbcf3748 feat(orders): label lines split off a short collection
Shows "Short delivered · on <PO>" next to the description on /orders and
the order page so the buyer doesn't re-order units already on back order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 07:59:57 +02:00
511f5dac6e feat(collection): return mistaken pickups to pool 2026-10-21 03:37:01 +02:00
e66ea11845 feat(collection-confirm): Delete photo; drop the Run agent scan button
- Delete photo next to "Add supplier invoice" removes the photo open in
  the previewer (wrong upload, or one of several for the same PO) after an
  inline "Delete …? Yes, delete" confirm; the confirm resets when you
  switch photos. Not offered for the PO PDF.
- POST /api/v1/collection-confirm/delete-photo (browser session) →
  deleteCollectionPhoto: takes the file off every order line carrying it
  (or the stock purchase's photo slot) and deletes the AI's reads of it
  plus the checks built on them (shared forgetReads with Move photo).
- Removed the header's blue "Run agent scan" button and its results panel
  (not in use); the /api/v1/agent/scan route stays for the agent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:26:10 +02:00
af4cdc66da feat(collection-confirm): spot a photo on the wrong PO and move it
Drivers photograph invoices per item and can't see which order a photo
lands on. B&R invoice 00282979 (stock order PO26100702STK) ended up on
the thinners line of PO202610017BLY; the AI read "PO26100702STK" off it
but the card only said "not found".

- The card list now carries each read's po_refs and source file, and sets
  ai_doc.other_po when the document names a PO that exists and isn't the
  row's PO (none named, or this card's PO among them: no hint).
- PO card: "Photo may be for <PO>" in the header; when open, "Invoice <no>
  is for <PO>, not this PO" with a Move photo button. Nothing moves on its
  own.
- POST /api/v1/collection-confirm/move-photo (browser session) →
  movePhotoToPo: copies the photo to the target (a collected line of a
  customer PO, or the stock purchase's single photo slot — refused when
  taken), removes it from the source, deletes the AI's read of it and the
  checks built on it so it is re-read where it now belongs.
- normalizePoReference moves to the client-safe src/lib/po-reference.ts
  (re-exported from the matching service).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:08:47 +02:00
802565d2d8 feat(collection-confirm): check printed prices on delivery notes; show AI reading notes
Plumblink hands out delivery notes with prices on them. The Price tick
was always grey on a delivery note, so a card could go purple without
its prices ever being checked, and the AI's reading notes ("delivery
note, not a tax invoice", "year not printed") were never shown.

- Price tick: compare whenever the document line has a price, invoice
  or delivery note; grey only when no price is printed. The AI still
  only corrects a cost from a tax invoice.
- ai_doc now carries the read's notes; cardNotes() unions them per card
  and the AI findings box lists them under "Reading notes" (the box now
  shows when there are notes but no findings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:50:27 +02:00
a6455376e4 fix(collection-confirm): purple card only when the AI found nothing off
- The collapsed PO card showed white instead of purple: it always carried
  `bg-card`, which beat `bg-ai/10` in the CSS (but lost to the green).
  Now the card gets exactly one background.
- Purple now means "the AI checked every line and no tick is red or
  amber" (grey "couldn't check" ticks are fine). A card the AI checked
  with a line off, or with unchecked lines, goes amber and says
  "AI checked N of M lines · K need a look". Green still means "photo,
  not checked yet".
- cardAiState() in collection-ai-ticks.ts works this out from the same
  computeLineTicks the table uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:20:36 +02:00
d73fb6f0ab feat(collection-ai): read invoice discounts and set the discounted cost
HYCO (I009753) prints full prices on the lines and "Discount 25.00%" in
the totals; Swagelok (622831) has a "Disc %" column on each line. The AI
compared our cost (already the discounted price) with the printed price,
so the Price tick went red on both.

- The read now captures a line's discount_percent and a whole-document
  doc_discount_percent (prompt rule 5b) and stores net_unit_price on each
  line (both discounts stacked).
- The Price tick compares the cost with the price after discount; the
  tooltip and the document-lines panel spell it out
  ("R15.10 less 25% invoice discount = R11.33").
- Owner's call: when a "sure" tax-invoice line has a discount and our
  cost isn't the discounted price, the AI sets the cost to it (customer
  lines through updateOrderItemCost, which adds a cost note; stock lines
  through updateStockPurchaseItem) and records why in ai_check.cost_changed,
  shown in purple under the line. No discount, a delivery note or a
  "likely" match: the cost is never touched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:18:21 +02:00
9ddb811afd feat(collection-confirm): AI checks on/off switch in the page header
The n8n tick was calling in every 5 minutes but WFDASH answered
"disabled" because Collection checks was off in Settings → AI, and
nothing on Collection Confirm said so.

- New "AI checks" switch next to Refresh, the same setting as Settings →
  AI → Collection checks. Purple and "On" when running, with the last
  run in the tooltip; a gear links to /settings/ai.
- GET/PUT /api/v1/collection-confirm/ai/enabled (browser session). Only
  reads/writes collection_ai_enabled and the last run — no key, model or
  prompt goes through it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:18:13 +02:00
86020ed48d feat(collection-confirm): purple for cards and lines the AI checked
A collapsed PO card turned green as soon as the driver uploaded a photo,
whether or not the AI had read it, so "everything is green" said nothing
about the agent. Now:

- A collapsed card with at least one AI-checked line is purple (the AI
  colour) instead of green; green still means "photo, not checked yet".
- The header says "AI checked N of M lines" with the robot icon, open
  or closed.
- Each line the AI checked gets a light purple wash in the items table.

Lines whose documents couldn't be paired (pair_failed, grey ticks) don't
count as checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:13:45 +02:00
4eb4a24b84 fix(collection-confirm): show AI ticks under the description; always fill the SKU
- The AI and POS columns sat at the far right of the items table, hidden
  behind the document preview in the split view. Ticks (now labelled SKU /
  Qty / Desc / Price) and the POS status render under each description,
  and the table is back to its original six columns and width.
- Owner's call: fill an empty SKU on a sure pairing even if the code may
  be misread; the rep edits it and a near-miss still helps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 16:45:34 +02:00
8efee9db42 fix(collection-ai): pre-fill only from the chip's tax invoice, AI column only with ai_check
M2: the confirm dialog pre-fill uses the card's newest document (as the
chip) and only when it is a tax invoice.
M3: the AI ticks column (and its min-width) shows only when a row has
ai_check; the POS column stays whenever in_pos is known.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:20:46 +02:00
d4cdde7384 fix(collection-ai): Add to POS never duplicates SKU-less rows, failures are per row
I5: a customer row without a SKU returns needs_sku and creates nothing; the
Add to POS button is disabled for it ("Set a SKU first").
I6: a createStockItem failure is caught per row (status failed + error), the
route still 200s, and the page toasts "N added, M failed, K need a SKU".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:16:21 +02:00
457ad30f12 fix(collection-ai): stock rows tick and show their own line SKU
I4: ConfirmRow.line_sku carries stock_purchase_items.sku; the SKU tick,
the AI robot and (for stock rows) the SKU column use line_sku before the
catalogue sku via effectiveSku. The SKU pencil keeps line_sku in step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:14:17 +02:00
b49911601d fix(collection-ai): grey ticks when pairing failed, show line findings on the card
I3: ai_check.pair_failed marks lines whose covering document couldn't be
paired; computeLineTicks returns all grey for them. The card findings box
now also lists each row's ai_check.findings after the document findings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:12:42 +02:00
d1956bc1cf fix(collection-ai): only sure/likely pairings count, renumber doc lines, drop filled-SKU tick shortcut
I1: a 'different'/unrated answer never claims a PO line in parsePairs, is
stored as doc_line null (verdict + reason kept), loses to a real pairing,
is not a pairing for the findings, and gives all-red ticks.
I2: document lines are always numbered 1..n.
M1: the SKU tick goes green only through the normalised code match.
Also adds effectiveSku (line_sku before sku) for I4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:10:59 +02:00
137b458a06 fix(collection-ai): page handler tests, full document lines, snapshot dialog defaults, tick aria detail
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 09:45:12 +02:00
c1656f5ccd feat(collection-ai): ticks, findings and POS buttons on Collection Confirm
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 09:41:52 +02:00
6604e8b837 fix(quote-assistant): review minors (templates, forced order, bounds, UI)
- M1: fillQuote and the tick refuse templates ("quote is not open
  (template)"); both quote pages gate the fill button with
  canAiFillQuote (new/follow_up/claimed, not a template).
- M4: run summary keeps <= 20 errors of <= 300 chars (boundRunErrors).
- M5: forced runs offer never-tried lines before tried ones.
- M6: counts route 400s on ids that aren't PB record ids.
- M7: a fill never replaces a supplier already on the line.
- M8: warn dot on the AI marker when a pending fill has doubts.
- M9: MCP hint states the real eligibility rule.
- M10: detail-page price dialog re-reads the line before recording an
  AI review.
- M11: exported QUOTE_NOT_OPEN_ERROR_PREFIX / AI_DISABLED_ERROR used by
  the run route.
- M14: prompt textarea maxLength 50000.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:41:28 +02:00
40094be3f3 feat(quote-assistant): purple AI lines on process and quote pages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 19:56:02 +02:00
c8e977c61e fix(quote-assistant): warn-coloured doubts, real button for no-match badge, more button tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 19:48:19 +02:00
ef6193367d feat(quote-assistant): ai colour token, marker, fill button
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 19:45:44 +02:00
09e4d8f1e1 feat(collection-pool): back-to-pending, collection date, and a safe notes feed
Gives the operator two new controls on a collection-pool stop, and fixes
the audit feed they write into.

Back-to-pending (`items/[id]/back-to-pending`)

  A stop has to come back when the driver can't take it — no-show,
  wrong date, supplier pushed the delivery — or when the supplier
  confirmation was premature. A row can be assigned to a driver and/or
  marked ready at the same time, so the route clears both in one write
  rather than making the operator unwind them in the wrong order.

Collection date (`items/[id]/collection-date`)

  `order_items.collection_date` was a PB date field that existed but
  nothing read or wrote it. On a PENDING stop it is a forecast — the
  supplier said goods land on the 20th, so the stop stays
  un-assignable because promising a driver a pickup for goods that
  don't exist yet would be a lie. On a READY stop it is the confirmed
  collection day.

Notes feed (`src/lib/note-feed.ts`)

  `notes` on order_items / stock_purchase_items is NOT free text — it
  is a JSON array of NoteEntry objects, and every consumer parses it as
  one. The assign route's "mark ready" path wrote a plain string into
  it, which silently destroys the entire history: the next parse falls
  back to an empty feed. All writers now go through `appendNote` with
  the row's current value. Lives in `src/lib` rather than a page view
  model because both the client pages and the server routes need it,
  and an API route must never import from `app/(app)`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-10-16 00:44:49 +02:00
c22e9d1bd6 feat(delivery-notes): lock the cost price, markup stays the only input
A delivery note's cost price is what the business paid. Editing it
while setting a margin rewrites that silently, so a stray keystroke
changes every downstream number on the note without ever looking like
a pricing decision.

The rule lives in quote-pricing.ts as a `costLocked` flag captured at
load time, and repriceLine DROPS a cost patch on a locked line. That
is the guarantee; the read-only cell in the UI is only the
convenience, so no caller can quietly rewrite the cost.

- "Edit note" and "Create quote" grids: cost is read-only with a lock
  icon once the line arrived costed; a blank cost stays fillable and
  still seeds the 25% default markup on first entry.
- readOnly, not disabled, so the number can still be selected and
  checked against a supplier invoice.
- Locked at load, not per keystroke: a cost typed in this session
  stays correctable until save (an operator choice), and locks on the
  next open because the row then carries the cost.
- The DN detail page's edit mode is untouched — it stays the
  deliberate "that cost is simply wrong" correction path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-10-15 15:44:24 +02:00
f355895c75 fix(search): send the PB auth token, and a second instance of the same bug
Universal search returned 401 "Not authenticated." on every query.

Cause: dashboard auth is a PocketBase token in the `Authorization`
header, NOT a cookie — `assertBrowserSession` reads the header and
refreshes it against PB. The page used a bare `fetch()`, which sends
neither. The service underneath was always correct.

Worth being explicit about what was missed: the service was verified
end-to-end against live PB, and the route compiles, but curl against
the dev server returns the same auth-gated shell as /orders does — so
the authenticated path was never actually exercised until a human
opened it in a browser. Green tests plus a working backend is not the
same as a working feature.

The cache-warm call had the same defect, which mattered more than it
looks: an unauthenticated warm is a server no-op, so the first real
search would have quietly paid the full ~4.5s cold build every session.

SECOND INSTANCE, same root cause

`customer-form.tsx` fetched `/api/v1/customers/sites` — a guarded route
— with no Authorization header. The `.catch` swallowed the 401, so the
site-location autocomplete has always silently returned an empty list,
which is indistinguishable from "no sites in use yet". Fixed in the same
pass.

Audited the rest: cross-referenced every route that calls
assertBrowserSession against every client caller, and this is the only
other real one. The `x-wfdash-auth` header installed by
`installAuditFetch` is attribution for the audit trail, not auth, which
is probably what makes this easy to get wrong.

New: 5 tests on the search page covering the auth header on both the
search and the warm call, the truncated-group "showing N of TOTAL"
rendering, the failed-source row, and session expiry. Verified the two
auth tests fail when the header is removed while the other three keep
passing.

Also completed the customer-form pocketbase test mock, which was missing
`authStore` — the real SDK always has one.
2026-10-14 11:49:30 +02:00
60ccfa8122 fix(sidebar): top-level nav rendered only dashboardItems[0]
The Search entry added in 1ee3555 was in the array, in the build, and
typed correctly — and never appeared. The top-level nav block rendered
`dashboardItems[0]` with a hardcoded index, so every entry after the
first was silently dropped. Caught when the operator asked where the
link was.

Rendered as a map so appending an entry just works.

Regression test asserts the whole top-level set (Dashboard + Search)
rather than "Search exists", so the next person to append an entry gets
a passing test instead of an invisible link. Verified it fails when the
map is limited back to a single entry while the three pre-existing
sidebar tests keep passing.
2026-10-14 11:03:04 +02:00
1ee3555239 feat(search): universal search across every collection
One box at /search (sidebar, under Dashboard) covering orders, quotes,
both purchase-order flavours, suppliers, companies, customers and stock
items. Replaces guessing which screen held the answer.

Window: 90 days (UNIVERSAL_SEARCH_WINDOW_DAYS) on orders and quotes —
the two that grow without bound. Suppliers, companies, customers and
stock items are searched in full because they don't expire and an
operator searching for one expects to find it at any age. The UI states
the window so a miss reads as "aged out", not "broken".

THE INVARIANT — a cap must never look like emptiness

Every group reports `total` (uncapped) separately from `hits` (capped),
plus `truncated`. The UI renders "showing 25 of 1,240 — refine". This is
the property the 500-cap bug in orders-service violated: the newest 110
orders silently vanished and it read as a missing search field. The type
makes `total` structurally independent of `hits.length`.

Symmetrically, a source that fails or times out renders as an explicit
"couldn't search quotes" row. "We couldn't search X" and "no X matched"
are different statements and must never look alike. All nine sources
fan out in parallel and settle independently.

PERFORMANCE

Profiling the first build showed 7.8s per search — ~3.5s of it pure
data-fetching (1,070 orders / 4,288 line items re-read on every
keystroke) against ~10ms of actual matching. Added:
  - order snapshot (headers + items + supplier names), 60s TTL
  - reference-collection cache, 5min TTL
  - per-query result cache, 60s TTL

Cold ~4.5s, warm 250ms-1.6s, repeat query 0ms. The page pre-warms on
mount via an empty-query request, so the ~4.5s cold build happens while
the operator is still reading the box rather than in front of them.

Orders match supplier NAMES, not relation ids — verified live that
"truco" returns the Truco order, the 6 matching quotes AND the supplier.

NO Reps group, deliberately

A rep is a filter, not a page: this app has no user detail view and no
page accepts ?search=. A Reps group would be rows whose every link
404s. `orders.rep` is a matched field on the Orders source, so
searching "tiaan" still returns exactly his 96 orders — which is what
was actually asked for.

PO hits link to their parent order, since there is no standalone PO
detail page; orphaned POs fall back to the PO PDF.

Tests: 15 cases over the pure layer — ranking tiers, best-of-not-sum
scoring, filter escaping against injection, the window maths, group
ordering, and the cap/failure invariants. One of them caught a real
defect: scoreField lowercased the haystack but not the query, so an
uppercase query scored 0 against every row.
2026-10-14 10:32:14 +02:00
96a9c2617c feat(collection-confirm): add clearing actions and improve review UI 2026-10-13 11:54:16 +02:00
841121097c fix(invoicing): handle PDF uploads and improve error messaging
This commit addresses issues with PDF handling in the invoicing process. The application now correctly uploads the PDF returned from QuickBooks to the appropriate order item, ensuring that the PDF is available for preview. If no PDF is provided, the system will return a clear message to the user instead of displaying a blank frame.

Additionally, the `readQbWebhookInvoice` function has been updated to include a `pdfBase64` field, allowing for better handling of PDF data. The `PdfPreviewDialog` component has been modified to manage the display of the PDF or an informative message when the PDF is unavailable.

Tests have been added to verify the new functionality and ensure that the application behaves as expected when handling PDF uploads and errors.
2026-10-09 13:27:17 +02:00
6cfb413508 fix(pricing): the 18% floor was applied on every keystroke
Operator report: "If I double click on it and I put in 20 there, goes
to 18... if I take everything out, I start typing, automatically change
it to 18. I need to be able to add any value there and when I click
save and the value is less than 18, it should go to 18."

The floor (`2387a71`) was correct in principle and wrong in WHERE it
sat. It was applied inside `repriceLine`, which runs on every
keystroke in both pricing grids — so the moment a sub-floor digit was
typed the state was raised to 18 and the box snapped.

Typing "20" is the clearest demonstration: the "2" is sub-floor, so it
became 18 mid-keystroke; the next character then APPENDED to "18" and
produced 180. What the operator saw as "goes to 18" was the first
keystroke, and "it jumps around" was the second.

She asked for the floor on SAVE, not while typing. So:

  - `repriceLine` no longer floors. Markup is also rounded to 2dp on
    the way in, so the box holds `80.06` rather than the float noise
    a back-solved markup produces (`80.05999755859375`).
  - The floor applies on BLUR and on SAVE, in both the delivery-note
    editor and the quote review modal, via `applyMarkupFloor` — the
    same function, still the only thing between a typed value and the
    database, so the -100-row hole stays closed.
  - `step="0.5"` replaced with `step="any"`. A back-solved 80.06 is
    not a multiple of 0.5, which left those boxes `:invalid` — and a
    number input in an invalid state fights the caret. This is very
    likely a second contributor to "I can't do anything there".
  - The bulk "set all markups" field gets the same treatment.

Verified with real keystrokes in the browser, not synthetic events
(which had masked this — they set a value in one shot, so the
mid-keystroke floor never fired):

  type "20"  -> stays 20, selling R605,40 (504,50 x 1,20)
  type "15"  -> stays 15 while typing
  blur       -> 18, selling R595,31 (504,50 x 1,18)

Three existing tests asserted the per-keystroke floor. They are
repointed, not deleted: the commit path is now pinned directly, and
`applyMarkupFloor` has its own tests so the database protection is
still asserted.

No data changed — the editor work above was dialog-local state only.

Full suite 3833 passing, tsc clean.
2026-10-09 12:49:13 +02:00
bc6c4fdb31 fix(delivery-note-editor): "Save & show document" was not saving at all
The operator's report: change the quantities, press Save & show, and
the document still carries the old numbers — it "just reverts back".

It wasn't reverting. **The button never saved anything.** Its handler
was:

    onOpenChange(false);
    onSaved?.(deliveryNoteNumber);

which is exactly what Cancel does — close the dialog, show the PDF. The
`save()` call lived only on "Save changes". So the operator changed the
quantities, pressed the button, got the OLD document, and drew the
reasonable conclusion that their edit hadn't taken.

Both buttons now go through `save()`, which takes a flag for whether
to show the document afterwards. The document opens only after the
save resolves, so what she sees is what she just saved.

## Ruled out along the way

Three plausible alternatives, each checked and cleared rather than
assumed:

  - **Browser cache.** No — the PDF route already sends
    `Cache-Control: private, no-store`.
  - **Attachment stacking.** No — `regenerateDeliveryNotePdf` replaces
    the file rather than appending; every item on a regenerated note
    carries exactly one attachment, so reading index [0] is correct.
  - **Silent regeneration failure.** No — `pdfRegenerated: true` comes
    back from the PATCH, and the file's last-modified advances on each
    save.

Verified in the browser on DN26100904: quantity 2 -> 9 via "Save & show
document" now persists to the database AND advances the PDF's
last-modified, i.e. the regenerated document carries the new number.
Data restored to 150/150/150/2 afterwards.

Full suite 3832 passing, tsc clean.
2026-10-09 12:23:33 +02:00
22a82b337e feat(delivery-notes): open the note document to print; surface the real QB error
## Delivery note = document, Edit note = the editor

The "Delivery note" button used to open the editor, so the most common
intent — print the note, or read what it says — started in a pricing
grid. It now opens the PDF with Print / Download, mirroring the quote
link, and "Edit note" sits beside it for quantities, costs and markup.

Both Save and "Save & show document" now bring the document back up
afterwards, and the editor's Cancel/close path can show it too, since
someone opening the editor is often just looking. Six controls still
fit the row at 546px.

## The QuickBooks 502 was undiagnosable by design

The route returns n8n's own error text in an `upstream` field for a
502, and the modal threw it away. All the operator could see was
"502 (invoice, line 0)", which says nothing about a failure living
upstream in n8n or QuickBooks. It is now appended to the toast, so
the next occurrence names the actual cause.

### Not a localhost problem

Worth recording because it was the natural guess:

- the n8n webhook answers from this machine — an empty POST returns a
  validation 400, not a connection error
- a well-formed POST returns 200 and creates the invoice
- `NEXT_PUBLIC_QB_INVOICE_WEBHOOK_URL` IS present in the compiled
  server bundle, so the "not configured" 502 branch is not it either

So it is neither config nor reachability. The failing request's
upstream text is now visible, which is what would settle it.

NOTE: diagnosing that cost a real invoice. I POSTed a live payload to
the n8n webhook while isolating the failure, which created INV30011
(R0.00, order_number DN26100904) in the live QuickBooks book. It needs
voiding. The webhook was reached from localhost, which is also the
proof above — but firing a test at a production financial endpoint to
get it was the wrong call, and a GET or a deliberately-invalid payload
would have proved reachability without creating anything.

Full suite 3817 passing, tsc clean.
2026-10-09 11:00:03 +02:00
f0c8787e3f fix(delivery-note-editor): the pricing route is PATCH, not POST
"Could not save line 'Husqvarna 578BTF backpack leaf blower' (405)" —
and nothing was written.

`/api/v1/delivery-notes/items/[id]/pricing` exports PATCH only. The
editor POSTed to it, so every save 405'd. The DN detail page has been
PATCHing the same URL correctly all along; I should have matched it
rather than assuming POST.

## Why it got through my verification

My browser check opened the editor, typed a cost, watched the totals
recompute — and stopped there. The save path is entirely separate
from the render path, and I never pressed Save, so I verified the one
half that was never broken.

Redone properly: changed a quantity 150 -> 7, pressed Save, reopened
the editor and read 7 back (the other three lines untouched at
150/150/2), then put it back to 150 so the data is as found. That is
the check that matters on these screens — display and persistence are
different code paths, and a perfectly-rendering dialog proves nothing
about either.

Suite: 3817 passing, tsc clean.
2026-10-09 10:22:28 +02:00
58831683d4 feat(delivery-notes): edit the note before quoting, and fix the QuickBooks error
Four things, three of them the operator asked for and one a bug I
introduced earlier in this session.

## Delivery note editor, first in the flow

New "Delivery note" button ahead of "Create quote": quantity, cost,
markup and selling price per line, one Save for the whole note.

Sits FIRST deliberately. The quote is priced from the DN's lines, so
a wrong quantity or a stale cost here becomes a wrong number on a
customer-facing document. Fixing it at the source is the point.

It saves through the existing
`POST /api/v1/delivery-notes/items/[id]/pricing`, which takes cost +
selling + quantity in one call and re-renders the DN PDF. No new
endpoint. One Save rather than per-line saves, so a half-typed cost
can't be left behind on one line while the others commit.

Cost and markup are the inputs; selling is derived, same rule as the
quote review modal. A line that already carries a selling price KEEPS
it and shows the markup that price actually implies — verified live:
a line at R259.74 selling on R200 cost opened showing 29.87%, not
the 25% default, so a deliberate price is never overwritten.

## The QuickBooks invoice error

The modal refused to send when the order number was empty, and a
counter note has no parent order, so it opened blank and blocked. The
operator could not tell that an empty field was the only thing wrong.

The field now seeds with the DELIVERY NOTE number (which is what
`order_number` did before, so nothing changes for notes that have one).
QuickBooks needs a number and the DN number is real, unique and
customer-recognisable. Still editable. Verified live: a note with no
order now opens with DN26100814.

## The signed copy — stated, not toggled

The operator asked for an option to include the signed copy. There
isn't one to offer: when a signed copy exists it REPLACES the rendered
PDF at quote-creation time, so the attachment was already the signed
document. A checkbox there would be a control that cannot change
anything — the exact complaint that started this work.

Instead the send modal now says so plainly when the outgoing PDF is
the customer's signed copy.

## My bug

The editor's first fetch was a bare `fetch()` with no Authorization
header. `assertBrowserSession` 401s without it — the same mistake as
earlier this session, caught in the browser because the dialog hung on
"Loading items…". Fixed and re-verified.

Full suite 3817 passing, tsc clean, no lint warnings.
2026-10-09 09:27:09 +02:00
9a72f2e285 feat(delivery-notes): link a manual invoice, and show the invoice without leaving
Two requests. The second turned out to be much smaller than it
sounded.

## 1. Link an existing invoice (the backlog)

Hundreds of delivery notes were invoiced by hand before this app
existed. The invoice is already in QuickBooks; all the app needs is
the link. New "Link invoice" button beside "Create invoice" opens a
dialog that records the number and completes the note.

`POST /api/v1/delivery-notes/[id}/link-invoice` does two writes, and
the second is the one that's easy to forget:

  1. `reconcileOrderItemInvoicedStatus` — stamps
     `customer_invoice_number` + `invoiced_date` on the note's
     order_items and moves them out of ready-to-invoice.
  2. `markDeliveryNoteCompletedByInvoice` — flips the DN to
     `completed` so it leaves the Active list.

Without (1) the note closes but its lines stay "ready to invoice"
forever, so the Invoicing page still shows the work as outstanding —
done in one place, unfinished in another. Items go FIRST: if that
fails the note is left open and retryable, whereas closing first
would leave a completed note with no obvious way back.

It reuses `buildReconcileRows`, the same quantity rule as the
create-in-QuickBooks path, so the invoice qty is still capped at
min(qty_collected, quantity) and a short pickup isn't stamped as
fully invoiced. A second copy of that rule is how the two paths
would disagree about what "invoiced" means.

Deliberately a SEPARATE button from "Create invoice", not a mode of
it: one fires a webhook and creates money, the other records a
number. Folding them together is how a customer gets invoiced twice.

## 2. The invoice comes back to the screen

Not a new integration at all. n8n already downloads the QuickBooks
invoice PDF and attaches it to the note's order_items as
`qb_invoice_pdf` — 1,209 items carry one today. The Invoicing page
has been printing them from PocketBase all along.

The create route now returns `invoice: { number, date, pdfFileName,
pdfRecordId }` alongside the updated DN (additive — existing callers
are untouched), and the list opens that PDF in the same preview
dialog the quote uses. Print and Download, no navigation.

The `pdfRecordId` matters: the file hangs off the ORDER_ITEM, not
the delivery note, and PB's file URL is
`/api/files/<collection>/<recordId>/<fileName>` — anchoring on the
delivery note would 404.

Verified in the browser as David Els: both buttons render in order
(Create quote · Send · Link invoice · Create invoice), the link
dialog opens on the list, and the URL never leaves /delivery-notes.

Full suite 3783 passing, tsc clean, no lint warnings.
2026-10-08 00:05:32 +02:00
970104e510 feat(delivery-notes): invoice in QuickBooks from the list, with the order number
The "Create invoice" button used to navigate to the note's own page
with ?invoice=1, which opened the invoice modal there. One click, but
it threw her out of the list she was working through. It now opens
in place, on the list.

The ~180-line QuickBooks modal moved out of the detail page into
`QbInvoiceDialog` and both screens mount it — the same pattern used
for the action buttons and the readiness rule, both of which had
drifted precisely because they existed twice.

## The order number

Duplicated from the invoicing screen, which has had it all along:
"Invoice order number", seeded from the note's order, editable, with
a hard stop if it's empty when the operator tries to send. The
backend already accepted `orderNumberOverride` — the route resolves
`override || order.order_number || fallback` — so only the UI was
missing, which is exactly what the operator asked for.

That last fallback matters more here than on the invoicing screen: a
counter delivery note usually has NO parent order, so this field is
often the only place the number on the QuickBooks invoice can come
from. A blank one would silently become `QB-<dn>-<timestamp>`, which
is not a number anyone recognises on an invoice.

## The auto-search could only ever fail

The modal auto-loaded customers when it opened. The n8n webhook
rejects an empty `customer_query` with a 400, the proxy turns that
into a 502, so opening the dialog produced a red toast before the
operator had touched anything. Verified against the live webhook:

  {"customer_query":""}        -> 400 "customer_query is required"
  {"customer_query":"Caliber"} -> 200, real customers back

There is now no auto-search: the operator types (the box is seeded
for a note with an order) and presses Enter or Search.

The loading flag also had to be rewritten. It was first derived from
`loadedFor !== requestKey`, which meant typing in the search box
flipped the spinner on while nothing re-ran the fetch, and it spun
forever until Enter. `loading` now means "a request is genuinely in
flight" and nothing else.

Verified in the browser as David Els: Create invoice opens on the
list with the order number pre-filled (Q202609244), a search for
"Caliber" returns Caliber Machine and Fabrication (Pty) Ltd., and the
URL never leaves /delivery-notes.

Full suite 3676 passing, tsc clean.
2026-10-05 22:56:22 +02:00
d983eccd6c fix(delivery-notes): return to the list after quoting; kill the phantom supplier
Two things the operator hit straight away.

1. Creating a quote parked her on the quote detail page.
   She is working through notes one after another, so that pulled her
   out of the list for a document she had just reviewed in the modal.
   `afterCreate` now defaults to "list": the modal closes, the toast
   confirms, and she is back where she was with the row's first slot
   now showing the quote number.

2. "Couldn't load this quote's PDF" — blaming a supplier.
   The message was right about the failure and wrong about the cause.
   The readiness rule existed in TWO places: `quotes-service.ts` for
   the send path, `quote-pdf-service.ts` for the PDF route. When the
   supplier requirement was dropped I changed one of them and left the
   other enforcing it. So a counter note whose lines never had a
   supplier could be quoted and sent but never rendered.

   Both copies now call one function, `quoteItemReadinessGaps`, so a
   third copy cannot appear. Verified in the browser: Q202609631 now
   fails with "Every item still needs: cost price, not processed,
   selling price" — no supplier — and that quote's line genuinely has
   cost 0, selling 0 and is_processed false, so refusing it is correct.
   The phantom requirement is gone; the real blockers are named.

   `is_processed` is deliberately KEPT. It is the flag that says a
   person reviewed the line, and nothing else can set it on a
   delivery-note quote — the quote_items update whitelists exclude it.
   Dropping it would let a quote go out with lines nobody looked at.

The quotes-service test mock now spreads the real module, so these
tests run against the real rule rather than a stub that could agree
with the implementation while production disagreed.

Full suite 3676 passing, tsc clean, no new lint errors.
2026-10-05 19:49:20 +02:00
afae9cdd99 feat(delivery-notes): one linear flow control, and fix the quote lookup
The operator asked for one action at the end of the row that walks
her through the work, instead of a strip of unlabelled icons.

  [ Create quote ]  [ Send ]  [ Create invoice ]

Once a quote exists the FIRST slot becomes the quote number itself,
clickable, so she never hunts for where the quote went. Clicking it
opens the quote PDF in a popup with Print and Download — she stays on
the delivery-notes list, which is the whole point.

Deliberately not a fixed step 1 -> 2 -> 3: the counter also has
customer-to-customer work that never needs a quote, so "Create
invoice" is always offered and never depends on the quote having
happened. A fixed sequence would strand that path.

Send is mounted in place rather than by navigating to the quote page,
using the existing purpose-built modal (loud To field, alt-email
toggle, rep auto-CC, PDF attached, retry banner on a bounce). The
quote fetch now expands `customer,company` because that modal reads
`quote.expand.customer.rep` to pre-fill CC — without it, sends went
out silently with no CC and the office never saw a copy.

Everything else (signed copy, capture PO, mark invoiced, cancel,
regenerate PDF) stays on the detail page. That is a deliberate
hierarchy, not the drift this component was extracted to prevent: the
list is for scanning plus the three things you do to every note.

--- the bug this uncovered ---

The flow control could never show a quote, because the quote map was
always empty. `getQuotesForDeliveryNotes` built ONE PocketBase filter
of `delivery_note = "x" || ... ` across every id. The list fetches 500
notes, so that filter carried ~250 clauses, and PocketBase rejects it
with a bare `400 Something went wrong`. Measured on this instance: 75
clauses succeed, 100 fail.

The caller treats that fetch as non-fatal and swallows the error, so
it was completely silent. For the life of the feature:
  - the Q icon never switched to "open quote" mode,
  - `hasQuote` was always false,
  - the blue "quoted" row tint never appeared, and
  - the Send action could never be enabled.
A whole session of 3676 tests passed without catching it — they all
use a handful of ids, far under the limit. Only driving the real app
surfaced it.

Now chunked at 50 ids per request. Five sequential requests for a
250-note list is nothing next to the full delivery_notes page already
fetched alongside it.

Verified in the browser as David Els: DN26100599 now shows
Q202610102 in slot 1, Send is enabled, and clicking the quote opens
the generated PDF in a popup showing the priced line (1/2" X 2 1/4"
UNF BOLT, qty 10, R150.00, total R1 500.00) with Print and Download.

Full suite 3676 passing, tsc clean.
2026-10-05 18:21:19 +02:00
55be94b08f fix(delivery-notes): what the browser found — clipped actions, zero-margin lines
Found by driving the real app in a browser as David Els, not by
reading the code. Two of these were invisible to typecheck, build and
3670 unit tests.

1. The action icons were clipped off the right edge
   `preview-dn` and `download-pdf` were the SAME action — on the list
   both opened the DN PDF preview, on the detail both called
   `setPreviewOpen(true)`. A duplicate I had introduced in the
   canonical set. Even after removing it the row still overflowed:
   the Company column was ~294px, the widest thing in the table, and
   every row already sits inside a company group header spelling the
   same name out. Removing the column removed the redundancy AND the
   overflow. Table is now 1140 in a 1140 container, 0px clipped.

2. Entering a first cost produced a ZERO-MARGIN line
   A counter note opens with no cost on file, so the line starts at
   cost 0 / markup 0 / selling 0. Typing a cost left the markup at 0,
   which derived a selling price exactly equal to the cost — a line
   that looks priced and earns nothing, on the commonest path in this
   workflow. Entering a first cost now seeds the default markup, so
   the operator gets R125 selling on R100 cost and a visible 20%
   margin. Seeding only happens when the line had no cost AND no
   markup, so it can never overwrite a margin someone chose.

   Verified in the browser: cost 100 -> markup 25 -> selling R125,00
   -> line total R1 250,00 -> margin R250,00 (20.0%).

   The 20% on a 25% markup is the distinction the whole pricing
   module exists for, and it renders correctly.

3. The actions column also gets `w-px whitespace-nowrap` so the cell
   sizes to its icons instead of being squeezed by its neighbours.

Also pinned with 6 tests (repriceWithCostEntry): seeds on first cost,
yields a margin, does NOT reseed on an already-costed line, does not
override an explicit 0, collapses when the cost is cleared, and is a
no-op without a cost. Verified they bite: removing the seed fails 2.

Known limitation, reported rather than hidden: item DESCRIPTIONS are
not searchable. The list endpoint returns headers only and never
loads items, so "brazing" finds nothing while "kobus" (the customer
on the same row) finds 9. Making descriptions searchable means
loading items for every row.

Full suite 3676 passing, tsc clean, build compiles.
2026-10-05 16:01:55 +02:00
c2eabe1cfc fix(delivery-notes): unblock quoting, and one action set for both screens
Two things stopped the operator quoting a delivery note. Neither was
friction; both were bugs.

1. "The status is not right"
   `createQuoteFromDeliveryNote` opened with `if (dn.status !== "draft")`
   and refused everything else. A note the office had already sent, or
   that the customer had put a PO against, could not be quoted at all,
   and the whole error message was that condition.

   Now any status except `cancelled` can be quoted — cancelled is the
   one genuinely unquotable state, because the work was abandoned and
   pricing it would put dead goods on a customer-facing document.

   Critically, the status write is now conditional. It used to force
   `sent` on every create, which with a relaxed gate would have dragged
   a po_received note BACKWARDS to sent and erased the fact that the
   customer had sent their PO. Pricing a note is not a reason to move
   it. The detail page's Create quote button was also `draft`-only and
   now matches the server.

2. "It needs a supplier and this and that"
   The quote was being created fine — the PDF was refusing to render.
   The readiness check required four things per line, and the two the
   modal already supplied were the only two that were satisfiable:

   - `is_processed` was never set on a delivery-note quote, and
     NOTHING could set it: the quote_items update whitelists exclude
     it, and the only writer was /quotes/[id]/process. So a DN-created
     quote could not produce a PDF without leaving the flow entirely.
     It now derives from the confirmed pricing — cost AND selling
     both present — the same rule the process page uses. A line the
     operator left unpriced still blocks, so the check keeps its teeth.
   - The supplier block is gone. A counter note has no parent order,
     so its lines frequently carry no supplier; demanding one refused
     the PDF for a field the counter form never asked for. The
     supplier is still printed when present.

Signed copy is never a completion signal. The upload route only ever
wrote `signed_copy` — nothing was writing `completed` — and that is now
pinned by a test asserting create-quote never sets `completed` for any
input status, so the relaxed gate cannot introduce it.

One action set, not two
The list and the detail page each hand-wrote the same action set and
had drifted twice: the list got a pricing-review modal the detail page
never received; the detail page got Mark complete, Cancel, Download /
Regenerate PDF and Upload signed that the list never received. The
status gates drifted with them.

`DeliveryNoteActions` now owns the set, the order and the gating. Both
pages render it — icons on the list, labelled buttons on the detail —
and each supplies its own handlers, so behaviour stays where the state
lives but "which buttons, and when" is answered in one place. An
action with no handler is not rendered, so neither presentation can
invent or hide one.

Tests: 27 new. 19 pin the action set and gating, 8 cover the relaxed
gate / no-backwards / is_processed / no-supplier rules. Verified they
bite by regressing create-quote to draft-only and by restoring the
old supplier block. Full suite 3670 passing, tsc clean, no new lint
warnings.
2026-10-05 15:27:39 +02:00
97c3cd4d7e feat(delivery-notes): review pricing before a quote is created
The Create quote button fired blind: the quote appeared with whatever
pricing happened to be on the order items, and a wrong price was only
discoverable by finding the quote afterwards. A new review modal puts
the check in front of the create.

Modal (components/delivery-notes/quote-review-dialog.tsx)
- Letterhead picker. DN-backed quotes never set company_letterhead, so
  the renderer defaulted every one of them to CNL.
- Cost and markup per line; selling price is DERIVED, never typed, so
  the two cannot disagree. See src/lib/quote-pricing.ts.
- A no-cost line shows "No cost on file" and stays at R0.00 rather
  than deriving a fake price off a zero cost, which reads as a
  deliberate free-of-charge item.
- Bulk "set all markups" field — typing 25% into eight lines one at a
  time is the tedium the modal exists to remove.
- Totals, with margin as a share of REVENUE not cost: 25% markup is a
  20% margin, and conflating them quietly under-prices a job.
- Nothing persists until Generate. Cancel discards the whole grid.

Backend
- create-quote now accepts { letterhead, items: [{ orderItemId,
  costPrice, markupPercent }] } and derives selling server-side.
- Overrides are keyed by order_item id and validated against THIS
  note's lines. An unknown id aborts the create rather than moving
  another order's goods into this customer's quote.
- Quote items now go out as one PocketBase batch instead of a loop of
  individual creates. The batch is transactional: the old loop could
  fail on line 5 of 8 and leave a real quote header attached to half
  its lines. The header still has to be created first (the batch API
  can't reference a record created in the same batch), so a failed
  batch deletes the orphaned header rather than leaving it visible.
- Malformed bodies are 400s the operator can read, not 500s. "A quote
  already exists" and "not in draft" are now 409s.

Tests
- 33 new: pricing maths, and the route's validation guards. Verified
  the guards bite by removing them (2 fail) and restored.
- The existing service test's PB mock gained createBatch, modelled as
  genuinely all-or-nothing — the compensation path depends on that
  guarantee being real.

Full suite: 3615 passing. tsc clean.
2026-10-04 21:17:31 +02:00
980f40aa79 feat(delivery-notes): see what's on a note, colour-coded progress, POS-aligned stock search
The delivery-notes list was close to unusable: company groups initialised
to an empty Set, so `isOpen` was false for every group and the page landed
on a stack of company headers with nothing under them. The code comment
claimed the opposite of what the code did.

Screen
- Track *collapsed* group names instead of open ones. Open is now the
  default with no initialisation, and it survives a list re-fetch.
- Rows expand to show the real line items (description, qty, supplier,
  SKU, price, subtotal) via the existing /detail read model, cached after
  first open. Ported from /quotes, which already had this affordance.
- Whole-row click removed so expanding can't be mistaken for opening; the
  DN number and "Open full delivery note ->" navigate instead.
- Row tint as a derived progress ladder — no new stored statuses:
    none = draft · yellow = signed copy · blue = quoted · green = po_received
  `invoiced` leaves the Active tab, so Active is now genuinely what is
  outstanding. Hovering the status badge explains the colour.
- DataTable gained an optional `selectionHeaderLabel`; the checkboxes
  feed one action (Combine) and now say so.

Stock search
- The create-delivery-note dialog was `getFullList`-ing every stock item
  with expand=supplier on each open, before a character was typed. Now a
  debounced typeahead against /api/v1/stock-items/search.
- Deliberately NOT the existing quick-draft search route: that one is
  served with an admin client and no session check, so its result isn't
  gated on the listRule. The new route uses assertBrowserSession.

Fixes
- The PDF preview modal was clamped to 384px wide and 900px tall despite
  passing max-w-[1100px]. DialogContent's default `sm:max-w-sm` is a
  *variant*, so twMerge kept both and the variant won on cascade order
  (verified against the compiled stylesheet: 88,536 vs 258,517). Both
  preview variants now repeat the `sm:` prefix so the conflict resolves.
- Expand-panel fetch was missing the Authorization header. Dashboard auth
  lives in localStorage, so route handlers cannot read it from cookies and
  the request 401'd. A 401 now reports an expired session instead of a
  bare status code.

Notes
- 25 new unit tests. The stage ladder and the PB filter construction are
  the two places where a silent wrong answer looks like a UI bug.
- Unauthenticated write routes on delivery-notes (create, combine,
  create-quote, customer-po, mark-invoiced) have no session check. Left
  as-is and reported separately — locking them is an auth-behaviour change.
2026-10-04 20:40:13 +02:00
d98c263f45 feat(scan): standalone delivery-note scanner PWA at /scan
Scan the QR printed on a delivery note, see what it is, and act on it:
reprint, photograph the signed copy, or walk it toward invoicing. It is its
own route group outside `(app)` so it gets a clean full-bleed layout and its
own manifest — "add to home screen" should give the operator a scanner, not
the CRM. Mirrors the pattern `(counter)` already uses.

Two detectors, not one. `BarcodeDetector` is fast and allocation-free but is
Chrome-only: Safari/iOS still has it "Under Consideration" (WebKit bug
#254573) and Firefox does not ship it. A scanner that only used it would
simply not work on an iPhone. So native where it exists, jsQR everywhere
else — pure JS, so no 2 MB WASM payload on a weak warehouse signal, and the
delivery-note QR is always a QR code. Both run against the same canvas frame
so the caller never branches. Also requires HTTPS, which the page says
plainly when it isn't.

The QR carries the human number, so the first call is a new resolve endpoint
mapping number -> PB id. Everything after that speaks ids, which is what every
existing route already takes. The number is shape-validated before any network
call, so a supplier's packing label can't fire a lookup.

STATUS LADDER. mark-invoiced hard-refuses anything that isn't po_received, and
customer-po refuses a note that isn't sent/loaded — so rather than offering a
button that 500s, each action only appears when the server would accept it, and
the card shows which step comes next. It routes draft -> loaded -> po_received
-> invoiced via the existing load-dn, NOT draft -> sent, because draft -> sent
means "create a quote and email it" and a warehouse scan must never trigger
that silently.

The signed-copy upload deliberately uses the upload-only endpoint, not
/api/v1/deliveries/mark-signed-copy — that one flips the note to `completed`
in the same write, which would jump a note straight past invoicing.

Manual entry is always available, so the page works on a device with no camera
or a browser that won't scan.

Tests decode the REAL delivery-note QR through the production fallback path at
print size, and assert the shape check rejects a supplier QR, a random string
and an over-long number.
2026-10-04 13:15:56 +02:00