Commit graph

392 commits

Author SHA1 Message Date
SJCoetz
21a2d7728b chore(collection-map): drop bottom-list placeholder
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 12:30:20 +02:00
SJCoetz
fdd95add30 feat(collection-map): 'X of Y collected' line in supplier popup 2026-07-12 12:26:23 +02:00
SJCoetz
9769dbb5ae feat(collection-map): sidebar with legend, driver cards, unassigned compact (page split) 2026-07-12 12:23:13 +02:00
SJCoetz
0d63061ea0 refactor(collection-map): flex column root + map flex-1, drop bottom list shell 2026-07-12 12:17:03 +02:00
SJCoetz
56626c8270 feat(pin-model): add aggregateDriverStatus helper (TDD) 2026-07-12 12:12:41 +02:00
SJCoetz
8c21347ecc feat(collection-map): drop date filter; thread ready-gate into assign dialog 2026-07-12 00:46:44 +02:00
SJCoetz
d78d479091 feat(assign-api): hard-gate on ready_for_collection, drop auto-flip 2026-07-12 00:33:00 +02:00
SJCoetz
ee9a0e1001 test(collection-map): pin toolbar shape to prevent filter-chip regression 2026-07-11 23:46:46 +02:00
SJCoetz
adfde8a0fa test(collection-map): pin-bucket split; absorb orphaned assigned items into pool 2026-07-11 23:45:42 +02:00
SJCoetz
d4c72057bf feat(collection-map): two-pin model per supplier (letter + ✓/✕) 2026-07-11 23:45:07 +02:00
SJCoetz
dcfe662c9f refactor(collection-map): drop Drivers sidebar card + driver multi-select 2026-07-11 23:43:10 +02:00
SJCoetz
d876455e41 refactor(collection-map): drop status / readiness / search filters 2026-07-11 23:42:13 +02:00
SJCoetz
ed9503706d feat(collection-pool): gate assign UI on ready_for_collection
Both the per-row Assign Driver button and the bulk-assign button in each
supplier section header now disable when the target row(s) have not been
marked ready for collection. Tooltips explain the reason.

This enforces the rule that a stop must be ready before it can be
assigned to a driver — same gate for single-row and bulk flows.
2026-07-11 22:56:42 +02:00
SJCoetz
c88a52cf2d refactor(collection-pool): drop redundant supplier name from row body
The supplier name is already shown in the SupplierGroup section header,
so repeating it on each row inside the section adds visual weight
without information. Keep it on the checkbox aria-label for screen
readers only.
2026-07-11 22:52:39 +02:00
SJCoetz
da9b3e8b58 refactor(collection-pool): split PoolRow + SupplierGroup into components.tsx 2026-07-11 00:13:20 +02:00
SJCoetz
a5eaae6f7b test(collection-pool): cover groups, bulk assign, notes tooltip 2026-07-11 00:07:13 +02:00
SJCoetz
c5731a1206 feat(collection-pool): sequential bulk-assign PATCH 2026-07-11 00:04:27 +02:00
SJCoetz
75a111a334 feat(collection-pool): wire bulk-assign dialog mount 2026-07-11 00:01:25 +02:00
SJCoetz
5984f2f814 feat(collection-pool): render supplier-grouped sections 2026-07-10 23:58:47 +02:00
SJCoetz
8e4289b104 fix(collection-pool): align SupplierGroup with spec (a11y, chevron, assign) 2026-07-10 23:55:23 +02:00
SJCoetz
c17f7c662e feat(collection-pool): add SupplierGroup component 2026-07-10 23:52:50 +02:00
SJCoetz
b6ed9f2685 feat(collection-pool): add per-row selection state and checkbox
- selectedIds Set state plus toggleRowSelected / toggleSectionSelected callbacks
- PoolRow signature extended with selected + onToggleSelected
- New flex wrapper around supplier/description block with leading checkbox input
- bg-primary/5 row tint applied when selected
- aria-label composes supplier + description for screen readers
2026-07-10 23:50:17 +02:00
SJCoetz
7ce4445865 feat(collection-pool): replace notes title with hover tooltip 2026-07-10 23:46:59 +02:00
SJCoetz
0b03a6cb81 style(collection-pool): promote time-in-list to text-primary 2026-07-10 23:44:27 +02:00
SJCoetz
c989d0d12e feat(collection-pool): sort by supplier name first 2026-07-10 23:41:45 +02:00
SJCoetz
4662347ca0 feat(collection-pool): add buildSupplierGroups helper 2026-07-10 23:39:05 +02:00
SJCoetz
cdaa2e2b25 fix, feat, style: standardize quote numbers, polish UI
- Standardize quote number format from Q-YYYY-MM-NNN to QYYYYMMNNN across all client, server, test and API code
- Add atomic backfill logic for quote counters to avoid sequence collisions with existing records
- Rearrange Delivery Notes and Repairs to the Operations sidebar section
- Add supplier count badge to pricelist catalogue and improve filter tab overflow styling
- Optimize font loading in root layout to skip preloading unused font weights
- Improve table styling for customer and company pages with better text wrapping and empty states
- Fix rep display logic in quotes page to show "Unassigned" when no rep is assigned
- Add supporting documentation, PocketBase counter schemas and setup migration scripts
- Remove embedded SupplierMap from suppliers page for cleaner layout
- Improve invoice card layout for company and customer info spacing
- Improve filter label styling and accessibility in collection map page
2026-07-10 22:21:50 +02:00
SJCoetz
47b01bddfa feat: add picking slips, bulk print tracking, supplier map
- Add Supplier Map component to suppliers page and reorganize sidebar navigation
- Implement picking slip PDF generation with supplier per line item and picked-by signature footer
- Add invoice bulk print tracking API and view models to track printed invoice state
- Extend company search and form to support email/telephone fields and improve searchability
- Fix data table debounce race condition by using useRef for onSearch handler
- Fix supplier page fetch race condition with debounced timeout
- Reduce list page item counts to 10 per page for customers, companies, and suppliers
- Update company search filter to include email and telephone in search queries
- Add comprehensive test suite for new and existing components and APIs
- Add pdf-lib dependency for PDF generation and update related tooling
- Clean up unused code and fix minor linting issues
2026-07-10 10:47:11 +02:00
SJCoetz
ae66762b76 feat(invoicing): add per-order color stripe on group sections 2026-07-10 02:09:29 +02:00
SJCoetz
bbd1e1df7c feat(collection-confirm): add per-order color stripe on group sections 2026-07-10 02:07:25 +02:00
SJCoetz
6d03be2ebc feat(collection-confirm): rewrite row card as stacked vertical sections 2026-07-10 01:07:29 +02:00
SJCoetz
9ab4be2666 feat(collection-confirm): show signed-in-as pill in the page header 2026-07-10 01:02:59 +02:00
SJCoetz
6074e79be0 fix(collection-confirm): hydrate actor from dev-identity cookie, not localStorage 2026-07-10 01:01:24 +02:00
SJCoetz
961d09a798 fix(collection-map): use ISO 8601 UTC bounds for assigned_at day filter 2026-07-10 00:51:17 +02:00
SJCoetz
1846e86b9e test(collection-map): cover assigned_at clear on unassign 2026-07-10 00:49:36 +02:00
SJCoetz
5ce3ef1000 fix(collection-map): clear assigned_at on unassign so item returns to pool 2026-07-10 00:48:23 +02:00
SJCoetz
72b2ec09e2 test(collection-pool): simplify operational sort test + correct spec reasoning 2026-07-10 00:38:31 +02:00
SJCoetz
363cdebe36 test(collection-pool): pin nearby-sort behaviour for missing coords 2026-07-10 00:36:28 +02:00
SJCoetz
e5285e67df chore(collection-pool): rename labels Ready/Pending instead of Ready/Awaiting 2026-07-10 00:24:43 +02:00
SJCoetz
32194e8bb3 feat(collection-pool): require note on Mark Ready 2026-07-10 00:15:24 +02:00
SJCoetz
00fb9a38f0 test(collection-map): cover ready_notes required-on-ready 2026-07-10 00:05:54 +02:00
SJCoetz
13165bfb8c feat(collection-map): require ready_notes when marking ready 2026-07-10 00:04:01 +02:00
SJCoetz
0eef0abd92 feat(orders): make Send PO modal wider and two-column, scrollable body 2026-07-09 23:48:26 +02:00
SJCoetz
f44f090351 test(po-attachments): use node env so the 25 MB cap assertion works 2026-07-09 23:39:12 +02:00
SJCoetz
0e59d83107 feat(mcp): add purchase_orders.add_attachment tool 2026-07-09 23:37:42 +02:00
SJCoetz
a6139b7c8a chore(orders): drop unused attachmentsLoading state from Send PO panel 2026-07-09 23:34:51 +02:00
SJCoetz
14e1a12cfe feat(orders): add additional attachments panel to Send PO modal 2026-07-09 23:33:56 +02:00
SJCoetz
2b3b50596c feat(po): include additional_attachments in send-email webhook 2026-07-09 23:25:05 +02:00
SJCoetz
9bc9d389ce test(po-attachments): use NextRequest instead of any cast 2026-07-09 23:20:10 +02:00
SJCoetz
1477265db9 feat(po-attachments): add delete route for PO additional attachments 2026-07-09 23:18:51 +02:00
SJCoetz
fff095caae test(po-attachments): cover delete route behaviour 2026-07-09 23:16:53 +02:00
SJCoetz
b362d92256 feat(po-attachments): add upload route for PO additional attachments 2026-07-09 23:15:08 +02:00
SJCoetz
a16b8fcdcb test(po-attachments): cover upload route behaviour 2026-07-09 23:01:55 +02:00
SJCoetz
dfe52a62d9 fix(orders): seed Send PO body with this PO's line count, not the order's 2026-07-09 22:43:52 +02:00
SJCoetz
44db71e6d7 feat(orders): add n8n shortcut icon to Supplier POs card 2026-07-09 22:34:04 +02:00
SJCoetz
f146e42ed0 test(po-pdf): cover token capture + proxy routing 2026-07-09 22:23:49 +02:00
SJCoetz
6a7dcc0af2 fix(po-pdf): capture PB token on upload and route GET through proxy 2026-07-09 22:18:53 +02:00
SJCoetz
1e99d23e8b feat(po-pdf): add token field to PurchaseOrderDocumentEntry 2026-07-09 22:17:21 +02:00
SJCoetz
2bee7aa4be feat(quotes/process): load customers with company expanded for picker 2026-07-09 21:45:00 +02:00
SJCoetz
18334721cb feat(invoicing): add QuickBooks invoicing flow and print functionality
Add complete end-to-end QuickBooks invoicing workflow for the invoicing page:
- Add `jspdf` dependency for client-side PDF generation
- Implement updated item status handling with fallback for new invoice statuses
- Add server-side proxy API for secure QuickBooks customer lookup
- Build utilities to combine QuickBooks invoices and picking slips into a single PDF
- Add invoicing view models for row grouping, payload construction, and status checks
- Add full test coverage for all new components, APIs, and utilities
- Include feature design documentation and sample n8n workflow config
2026-07-09 09:44:55 +02:00
SJCoetz
9378685164 feat(collection-confirm): add full collection confirm workflow
Implement the complete collection confirm feature set:
- Add new `/collection-confirm` operational page for reviewing and confirming collected order items
- Add sidebar navigation entries for Collection Confirm and Invoicing
- Add `order_items` to the file proxy API whitelist for attachment access
- Install required testing dependencies and configure Vitest test setup
- Add full design documentation, test suite, and page overview screenshot
- Update package.json and build configuration files
2026-07-08 01:35:00 +02:00
SJCoetz
5f1838051f feat(collection-pool): add nearby supplier cluster sort mode
Add optional nearby-supplier cluster sort mode to the collection pool table, keeping operational sort as the default. Also includes:
- Update UserSearch component to support fallback selected label for pre-selected values
- Refactor AssignDriverDialog into a separate inner component with intent and pre-filled driver label support
- Add assignment badge helper types and functions
- Add full test coverage for new sort logic and component behaviors
- Update implementation plans and documentation files
- Fix minor code consistency and lint issues across touched files
2026-07-07 21:56:29 +02:00
SJCoetz
b9828def38 feat(collection-pool): add unified redesigned collection pool view
Remove redundant Assign Drivers top-level navigation link since driver assignment is now embedded directly in the collection pool page per-row, and add an Other nav section for leftover navigation items
Extract collection pool view logic into a dedicated view-model module with full Vitest test coverage for assignment state classification, row sorting, pool age labeling, and proximity marker grouping
Flatten the collection pool page into a single unified list replacing the old grouped assigned/unassigned layout, with updated row UI showing all required operational details and context-aware actions
Add database migration to add optional `collection_photo` field to order_items for driver pickup proof photos
Add complete design documentation, planning artifacts, and brainstorming session files for the collection pool redesign project
2026-07-07 20:49:31 +02:00
SJCoetz
17ae928331 refactor: update pool UI, fix tiles and config
overhaul the collection pool page's ready status UI: split the clickable chip into a static status indicator and dedicated toggle button with loading state, improving user clarity between status and actionable elements
update all related copy (toast messages, filter labels, button text) to use consistent "awaiting supplier confirmation" terminology across the interface
remove invalid `transparent` prop from traffic tile layers in both the collection map and traffic tiles components, update comments to reflect Leaflet does not support this option
add wildcard to allowedDevOrigins in next.config.ts to simplify local development testing across different network interfaces
add a comprehensive database backfill script to fix assigned order items missing the `ready_for_collection` flag, ensuring drivers see their correct assigned stops in the driver app
2026-07-07 18:01:43 +02:00
SJCoetz
7f924ccc45 refactor: switch hardcoded UI colors to semantic theme tokens
Overhaul the app's color system by replacing all hardcoded Tailwind color classes with semantic theme variables to ensure consistent theming across all components, pages, and tests.

Additional changes:
- Add assigned date support for order item status updates: add `assignedDate` field to the order item status PATCH API, implement server-side normalization/validation, and add corresponding tests
- Refactor purchase order PDF workflows to use the consolidated `purchase_orders.documents` field instead of the legacy separate `purchase_order_pdfs` collection
- Fix quote number parsing and formatting to support both dashed (Q-YYYY-MM-NNN) and dashless (QYYYYMMNNN) formats
- Rename `driver_pool` item status to `collection_pool` across the codebase
- Add null handling for order item quantities and pricing to display "—" for missing values
- Improve filter tab styling: make mobile tabs scrollable, prevent text wrapping, hide scrollbar
- Add new utility scripts, API routes, migrations, and polish small UI/UX fixes including tsconfig updates and theme hook improvements
2026-07-07 17:22:03 +02:00
SJCoetz
235c0ad39b fix(attachment-counts api): surface real error details instead of generic PB admin message
capture the thrown error, extract its message if available, and append it to the base "PB admin unavailable" error response. fall back to a generic unknown error message for non-Error failures, revealing actionable debugging details like missing env vars or invalid PB credentials.
2026-07-03 22:52:39 +02:00
SJCoetz
05abe499b0 feat(sprint): add new sprint pricing workflow and supporting code
Add full sprint pricing workflow and supporting infrastructure:
- New sidebar navigation entry for the sprint dashboard
- PocketBase category collection schema and migration script
- Server API routes for sprint item claims, attachments, counts, and file proxying
- Dev identity utilities and UI switcher for multi-user testing
- Reusable FilterTabs component replacing ItemStatusTabs
- Updated TypeScript types for sprint-related entities

Also include:
- Fix PocketBase file URL method casing (getUrl → getURL) across codebase
- Add development utility, smoke test, and helper scripts
- Update package.json with new sprint migration command
2026-07-03 07:29:43 +02:00
SJCoetz
9cdcb3b096 feat: implement sku-based catalogue pricing matching workflow
This commit adds the full end-to-end SKU pricing match flow for quote items:
- Add new QuoteItem and PriceListRow fields for SKU and pricing metadata
- Add sku_normalised to price_list for robust format-agnostic SKU matching
- Refactor price list search to use modular search builder and filter helpers
- Add database migrations, backfill scripts, and new package commands
- Update catalogue search UI and fix quote list accidental click behavior
- Add comprehensive unit, smoke, and end-to-end test suites
- Update documentation for the new price search and extraction logic
2026-06-30 21:20:53 +02:00
SJCoetz
b75873a51b feat(pricelist): Catalogue tab with search + category/brand filters
Adds a second tab on /pricelist that shows the structured
`price_list` collection (AI-extracted line items) instead of the
raw PDF uploads. Operators can now:

  - Search across SKU, description, and brand
  - Filter by category (twist_drill, hss_cutter, countersink, ...)
  - Filter by brand (JEI, TurboSteel, TurboTough, ...)
  - See cost vs selling price side-by-side in ZAR
  - Click a row's 'Source' link to jump back to the raw PDF

The distinct filter values are pulled from a one-shot getList(1, 500)
on mount, with hardcoded fallbacks (FALLBACK_CATEGORIES /
FALLBACK_BRANDS) so the dropdowns are useful even before any
extractions have run.

Layout: Tabs (Raw Uploads | Catalogue) wrap both views; the
header + page chrome stay shared. The DeleteDialog stays outside
the Tabs since it's a modal.

Also ships an idempotent migration to add `source_file` (text)
to `price_list` — used by the n8n workflow to track which raw
PDF each extracted row came from, and by the verify-after-POST
step the workflow uses to decide whether to flip
`raw_price_list.status` to Completed vs Failed.

Price type is in PriceListRow (shared subset) and PriceList
(full record). Supplier names are resolved client-side via
getAllSuppliers() since the live schema has supplier as a text
field rather than a relation.

Tests: 229/230 (same pre-existing failure, unrelated). TypeScript
clean.
2026-06-30 11:49:48 +02:00
SJCoetz
81c9f64158 feat(pricelist): notes field for AI instructions + file_name on upload
Operators can now type per-upload instructions for the AI extraction
step in the Pricelist upload form. The notes go into a new
`raw_price_list.notes` field that the n8n workflow reads and
injects into the LLM user message as per-upload context.

Common uses:
  - "Brand is JEI" → AI stamps every item with brand="JEI"
  - "Apply 30% markup" → Code node regexes this out for selling_price
  - "All prices in ZAR excl. VAT" → AI uses ZAR
  - "Page 4 has discount codes" → AI skips those rows

Also auto-populates `raw_price_list.file_name` (the original
browser-side filename) on upload — PB slugifies the upload to a
token stored inside supplier_file, so without this field the
operator saw the slugged version. Existing rows backfilled by the
admin script.

The `log_summary` field is now reserved for the AI's write-back
summary (set by the n8n workflow after extraction). It was
previously operator-editable on the form, which was wrong —
overwriting it clobbered the AI's output.

New migration: scripts/migrations/2026-06-30-add-pricelist-notes.ts
(idempotent, only adds `notes` if missing — `file_name` was
added manually via the PB admin UI before this commit).

doc/pricelist-extraction.md updated with the n8n LLM user message
shape, the markup regex, and the notes field's role in the pipeline.
2026-06-30 11:09:27 +02:00
SJCoetz
7f70258037 feat(management): new Pricelist page with drag-drop upload + queue table
Adds /pricelist under the Management section. Operators drag a supplier
price-list file (PDF / CSV / text / image) into the upload zone — or
use the explicit Choose file button — and it lands in PocketBase as an
attachment on the raw_price_list collection. The table below shows the
queue: file, supplier (relation to suppliers), status badge, log
summary preview, upload date, and a delete action per row.

Layout matches the rest of the app: Card for the upload zone, DataTable
for the queue, DeleteDialog for the destructive action. Live updates
via the PB subscribe channel so other tabs / the n8n ingest workflow
show new rows without a manual refresh.

PB schema is sourced from docs/pocketbase/raw_price_list.collection.json.
The migration script is idempotent: it creates the collection from the
schema file on a fresh deploy, and on a pre-existing one (the live PB
already had it, with PB's default null/superuser-only rules) it relaxes
the auth rules to @request.auth.id != '' so any logged-in user can
CRUD — matching every other collection in the app.

Field names match the live PB collection (discovered via admin API):
  - supplier_file (the file)
  - supplier_name (relation to suppliers)
  - status        (select: Pending / Processing / Completed / Failed)
  - log_summary   (free text)
2026-06-30 09:14:36 +02:00
SJCoetz
a0332c4159 fix(approve modal): break infinite loop from openNonce in effect deps
The ApproveAndSendDialog had a useEffect whose deps array included
`openNonce` — a state counter the effect itself incremented:

    useEffect(() => {
      if (!open) return;
      setOpenNonce((n) => n + 1);   // updates openNonce
      // ... seed defaults ...
    }, [open, openNonce, ...]);    // openNonce is in deps

This produced Maximum update depth exceeded: the effect fires → state
updates → deps change → effect re-fires → loop, until React pulls the
plug.

The intent was 'seed once per open cycle, not on every claimerName /
repEmail update' (so async lookups arriving after the modal opened
didn't clobber operator edits). The state-counter approach was the
wrong mechanism for that — mutating a dep from inside the effect
*is* the loop.

Fix: replace openNonce (state) with seededFor (ref). A ref mutation
doesn't trigger re-render, so the loop is impossible. We still depend
on [open, quote.id] in the effect, and the ref's purpose is purely
'has this (open, quote.id) cycle been seeded yet?'. Reset to null on
open=false so the next open seeds fresh.

Dropped claimerName / repEmail from the deps too — they were the
reason openNonce existed in the first place (don't re-seed when they
update), and the ref now enforces that without the side-effect trap.

Tests: 229/230 vitest (the 1 failure is the pre-existing attachments
off-by-one, unrelated to this change).
2026-06-29 23:20:16 +02:00
SJCoetz
9b2b0897a1 refactor(quotes detail): move Quote Settings into kebab menu as dialog
The Quote Settings card sat in the right column as a collapsed accordion
alongside History and Email Status — three near-identical cards the
operator had to scan past to find the data they actually came for.
Quote Settings is a low-frequency config action; it belongs with the
other low-frequency actions (Save as Template, Clone, Delete).

  ⋮ → View Quote
     View Order
     Save as Template
     Clone
     ─────────────
     Quote Settings…    ← new
     ─────────────
     Delete Quote (red)

The Settings card is removed from the right column. Its contents now
live in QuoteSettingsDialog — same three fields (Quote date, Valid for
days, Follow up by), same Save handler, but rendered as a focused
modal so the operator sees exactly what they're editing.

The page header's FollowUpChip (the yellow / red bell that surfaces a
follow-up date on a quote) still opens the same dialog via the renamed
`settingsDialogOpen` state. Auto-open on follow_up / problem status
is preserved — same effect, just an opened modal instead of an expanded
accordion.

Template mode (no customer-facing fields) still works: the dialog
shows only the Follow up by field plus the explanatory paragraph about
why date / validity don't apply to templates.

Tests: 229/230 vitest (the 1 failure is the pre-existing attachments
off-by-one, unrelated to this change).
2026-06-29 23:04:03 +02:00
SJCoetz
4e085a3f69 refactor(quotes detail): two-column layout with hero Items card
The quote detail page had grown to eight stacked cards, all with
identical Card chrome — Items, Outbound, Linked Orders, Notes, Settings,
History, Email Status, and a TODO 'Generate PDF (coming soon)' card. The
Items card (the page's hero) had the same visual weight as the
admin-panel cards, so the eye had nowhere to land.

Two-column layout on desktop (lg:grid-cols-3, primary 2/3, secondary 1/3):

  Left column (primary)
    - Description card (conditional)
    - Items card — hero treatment:
        * Left primary-blue accent border (border-l-4 border-l-primary)
        * Tinted primary header background (bg-primary/5)
        * Larger title (text-base font-semibold)
        * Rewrite with AI demoted from loud amber pill to outline variant
          (matches the accent trap from MEMORY.md)
    - Notes card (conditional)

  Right column (secondary)
    - Customer meta card — replaces the old 5-card info strip with
      a single compact card: customer name, company, letterhead,
      created date, quote date (if set), and claimed-by with avatar.
    - Outbound attachments card
    - Linked orders card
    - Quote Settings accordion (collapsed by default)
    - History accordion (collapsed by default)
    - Email Status card — tightened to 2-col grid

Mobile (below lg) collapses to single column with content-then-meta
order: Description → Items → Notes → Customer meta → Outbound → Linked
→ Settings → History → Email Status.

The 'Generate PDF (coming soon)' placeholder card is removed — that was
a TODO shipped to users. The actual Generate PDF flow lives in the
'View Quote' menu item (QuotePdfViewer) and the 'Approve' modal, neither
of which need this stub.

Items card header is flex-col on mobile so the title, totals, and
Rewrite button each get their own line instead of getting clipped.

Tests: 229/230 vitest (the 1 failure is the pre-existing attachments
off-by-one, unrelated to this change).
2026-06-29 22:23:44 +02:00
SJCoetz
5c46dfed88 refactor(quotes): collapse 10 workflow tabs into 8, add follow-up + replied chips
The list page had grown 10 colour-coded tabs (one per legacy PB status)
that fragmented the workflow rather than grouping it. Merging the
overlapping concepts into workflow buckets per the operator's flow:

  - new              ← new + follow_up  (follow-up rows show a bell chip)
  - claimed          ← claimed
  - pending_approval ← processed + approval_pending + sending
  - completed        ← approved + complete + emailed + cancelled + rejected
                       (emailed renders as 'Awaiting reply', cancelled + rejected
                        are substatus pills inside the Completed tab)
  - email_failed     ← email_failed + mail_failed + unmatched_bounce  (new tab)
  - problem          ← problem
  - templates        ← is_template = true
  - all              ← catch-all

Two row-level indicators added next to the quote number:

  - Bell chip for follow-up rows (status=follow_up OR follow_up_due set
    on an actionable status). Colour flips to red when overdue.
  - Reply-bubble chip for rows where last_reply_at is set, so the
    operator can distinguish 'fresh new' from 'replied new' at a glance.

Implementation notes:

  - getQuotes now accepts string[] statuses and OR-chains them in the
    PB filter (PB 0.26 has no IN operator). getQuoteStatusCounts sums
    per-status totals into the new tab buckets in one batch.
  - formatQuoteStatus gains workflow-friendly label overrides
    ('Awaiting reply', 'Sending…', 'Pending approval', etc.) shared by
    the list, archived, and process pages.
  - The detail page's local statusLabels map is kept in sync so toast
    + history-row interpolations read correctly.

Tests: 229/230 vitest (the 1 failure is the pre-existing attachments
off-by-one, unrelated to this change). Updated quote-status.test.ts
for the new label overrides.
2026-06-29 22:15:32 +02:00
SJCoetz
6c07a91693 refactor: drop order-level status, shift to item-driven workflow
This commit overhauls the order management system to use item-level status tracking instead of a single order-level status:
- Remove deprecated `orders.status` field and add `invoiced` and quote match audit fields
- Add `isOrderComplete` utility with tests to validate fully delivered orders
- Add purchase order PDF rendering support and tooling
- Add geo coordinate fields for companies/customers with map link UI
- Add REST management APIs for customers, companies, and suppliers
- Update customer/company services to use relation fields instead of free text
- Add status pill and tab filter components for item status visualization
- Add quote-to-order matching logic and unit tests
- Update all pages, components, and tests to match the new schema
- Include all required PocketBase migrations and schema updates
2026-06-29 13:06:01 +02:00
SJCoetz
bb4233a9f2 feat(dashboard): add multi-theme system and supporting improvements
Add complete multi-theme dashboard system including:
- 8 selectable themes with persistent per-browser preferences
- Theme bootstrap script to prevent FOUC on page load
- 12+ reusable chart components (area, bar, donut, radial gauge, etc)
- Custom checkbox UI component
- New settings page for appearance customization

Other changes:
- Optimize supplier map API payload with getMappableSuppliers helper
- Add aria-label attributes to back buttons on detail pages for better accessibility
- Update next.config.ts to include new local development IP 192.168.1.128
- Update site manifest with all new favicon and PWA assets
- Fix styling and layout spacing in rewrite quote modal
2026-06-26 17:59:40 +02:00
SJCoetz
588e9762c2 feat: add quote templates, improved email, new statuses
Add complete quote template functionality, enhanced outbound email sending, new quote statuses, and supporting infrastructure:
- Add new quote statuses (template, sending, mail_failed) with tailored UI styling for status pills
- Implement full template workflows: save real quotes as templates, create new quotes from existing templates
- Add support for custom quote dates and extended validity periods on generated PDF documents
- Build out improved email pipeline with persisted compose fields and retry functionality for failed sends
- Add attachment direction tracking to categorize inbound, outbound, and generated quote attachments
- Fix tooltip component to properly handle Radix `asChild` prop to avoid React DOM attribute errors
- Add comprehensive test coverage, schema migrations, and update sample test and production data
2026-06-24 22:57:01 +02:00
SJCoetz
714e910949 feat: add branded quote PDF generation and in-app viewer
This commit adds full quote PDF generation functionality with per-company letterhead branding:
- Server-side PDF rendering using @react-pdf/renderer matching the sample quote layout
- In-app modal PDF viewer with print, download, and new-tab controls
- Letterhead service to fetch and apply company-specific branding (CNL/ISHERWOOD)
- ZAR currency and date formatting utilities for South African quotes
- Updated QuoteAttachment type to handle PocketBase's array-based file tokens
- Fixed PocketBase attachment URL generation in quote email card
- Removed deprecated `included_in_quote` field from QuoteItem and quotes service
- Updated quote item creation test to validate draft item logic
- Added comprehensive unit tests for PDF rendering and formatting helpers
- Added dev scripts for debugging PDF and image rendering issues
- Added sample generated PDF files for visual verification
- Updated tsconfig to exclude development scripts directory
- Added @react-pdf/renderer production dependency
- Removed JEI as a valid letterhead option per requirements
2026-06-23 08:30:38 +02:00
SJCoetz
4c0b6b0163 feat: enhance toasts and add quote item toggle
- completely rewrite the Sonner toaster component with theme-aligned styling, default top-center position, brand-colored toast states, and improved spacing/sizing
- update root layout to remove hardcoded Toaster position prop since the component now handles its own positioning
- add toggle to show/hide completed quote items on the quote process page
- add empty state message when all quote items are fully processed
- memoize displayed quote items for stable sorting and filtering
2026-06-22 23:50:33 +02:00
SJCoetz
86c942a466 feat: add locked pricing and overhaul quote rewrite
- Bump quote rewrite API timeout to 180s for longer AI batch processing
- Extend structured quote item fields to include model and size, remove old type field
- Overhaul n8n quote rewriter workflow with updated prompt and null-safe output handling
- Add locked source-of-truth pricing controls to auto-calculate cost/selling prices
- Remove inline cost/selling inputs from quote items table and refine table layout
- Improve rewrite modal UI with sticky headers, better empty chip handling, and styling
2026-06-22 23:07:53 +02:00
SJCoetz
2c6155abbb feat: add AI quote item rewriter and supporting UI/UX changes
- Add `user_edited` field to QuoteItem type to gate AI rewrites on user-edited content
- Add idempotent migration script to add and backfill the `user_edited` field across quote items
- Replace plain Select components with searchable SupplierSearch combobox across order and quote pages
- Add working days calculation utility and aged quote warning badges for overdue quotes
- Implement expandable row previews in the quotes list view
- Add full AI rewrite workflow: backend API endpoint, frontend modal, and n8n workflow definition
- Update package scripts for the new migration
2026-06-22 18:29:59 +02:00
SJCoetz
a18ab0f19f feat: add quote email tracking, user color coding, and improved attachments
Add comprehensive quote management and UI improvements:
- Add `email_received_at` field to quotes collection, TypeScript types, and setup script
- Update quote attachments schema to mark `kind` optional for legacy attachments, add `uploaded_at` field, and improve documentation comments
- Create `/api/v1/users/lookup` server endpoint to resolve user IDs to display names
- Add stable user ID → color mapping for visual grouping of claimed quotes
- Enhance quotes list page: reorder tab filters, show claimer names, color-code rows per claimant
- Update quote detail page to display claimer info with user icon
- Expand DataTable component to support per-row custom class and style props
- Overhaul QuoteEmailCard: add proper HTML/plain text body sanitization/linkification, inline PDF/image previews, improved metadata display, and fixed auth-aware attachment previews via blob URLs
2026-06-22 15:15:00 +02:00
SJCoetz
41b5fc4cbf feat(quotes): add email-to-quote pipeline with attachments and replies 2026-06-16 20:46:28 +02:00
SJCoetz
c4e1c62882 chore: standardize line endings and add full test + config scaffolding
Fix inconsistent line endings across all project files for cross-environment consistency.
Add complete unit test suite covering core utilities, API routes, and server services.
Add Playwright E2E test setup with smoke, auth, and agent API tests.
Update all project configuration files to match standardized formatting.
Fix MCP API error handling to properly propagate HTTP status codes and use correct JSON-RPC error codes.
Add VSCode workspace configuration, extensions, and example MCP config files.
Update .gitignore to exclude new test and build artifacts.
2026-06-11 20:30:02 +02:00
SJCoetz
83935c990b Add dark map, marker editing and fullscreen
Add dark-theme styles and Leaflet z-index tweaks; switch tile layer URL/attribution based on Next.js theme. Introduce theme hook, PocketBase helper import and tile constants; lower label zoom breakpoint. Replace ZoomWatcher with MapWatcher that invalidates map size when toggling fullscreen. Add fullscreen UI, edit mode toggle, draggable markers when editing, and saveSupplierLocation to persist coordinate updates to PocketBase with optimistic UI and toast feedback. Misc: simplify cluster marker popup handling, ensure popups close before cluster flyTo, and tweak cluster distance label to reflect current zoom.
2026-05-27 17:57:24 +02:00
SJCoetz
54644c7ce8 Improve map clustering and labels
Enhance supplier map UX by introducing zoom-aware clustering and refined marker visuals. Adds clusterIcon, clusterDistanceForZoom, ZoomWatcher, ClusterMarker and SupplierPopup components; switches to dynamic cluster sizes and distances based on zoom, and flies into clusters on click. Shows individual supplier markers and optional permanent labels above configurable zoom breakpoints, and reduces marker sizes/shadows for a cleaner look. Also adds .supplier-map-label CSS for tooltip-style permanent labels.
2026-05-27 14:53:54 +02:00
SJCoetz
565b1a6e2b Add supplier map feature with Leaflet UI
Introduce a new SupplierMap component and page to visualize suppliers on a Leaflet map (client-side, dynamic import). Wire the feature into the app by importing Leaflet CSS in the global layout and adding a Supplier Map entry to the sidebar. The map fetches suppliers, parses coordinates, groups nearby suppliers into proximity clusters, and shows markers, tooltips, and lists of missing coordinates. Update package.json to include leaflet, react-leaflet and types; remove a Windows-specific lightningcss package. Also normalize Dockerfile ENV formatting (no behavior change).
2026-05-27 14:39:00 +02:00
SJCoetz
fd1571e294 Add PocketBase collections, APIs & migration docs
Introduce PocketBase workflow support, migration tooling, server APIs and documentation. Adds a set of PocketBase collection JSONs (order_items, order_items_v2, collection_pool, delivery_notes, delivery_note_items, repairs) and a large import manifest for workflow collections; includes docs describing MCP/API layer, migration audit, order-item schema and rollout plans. Adds server-side agent/MCP endpoints and services (api/mcp, api/v1/orders, collection-pool, order-items status, health) plus helper modules (pocketbase-admin, orders-service, order-item-status, agent-auth) and a migration script to create order_items_v2/collection_pool. UI: new pages for collection-pool, delivery-notes, repairs and several updates to orders/quotes pages, sidebar, tooltip and pb helpers/types. Also updates package.json (migration script and related changes) and global styles. Required env vars and suggested migration command are documented (e.g. NEXT_PUBLIC_POCKETBASE_URL, PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD, ORDER_ITEMS_COLLECTION; run npm run pb:migrate:orders-v2).
2026-05-25 18:39:33 +02:00
SJCoetz
954dc266e4 feat: add service worker, offline page, and manifest for PWA support 2026-05-24 17:02:07 +02:00
SJCoetz
a828432540 fix: improve responsiveness and accessibility of dashboard and quotes pages 2026-05-24 16:51:12 +02:00
SJCoetz
363786ea36 feat: add UI components for separator, sheet, sonner, switch, table, tabs, textarea, tooltip
- Introduced a new Separator component for visual separation in UI.
- Added Sheet component for modal-like functionality with triggers and overlays.
- Implemented Toaster component for notifications using Sonner library.
- Created Switch component for toggle functionality.
- Developed Table component with headers, body, footer, and rows for structured data display.
- Added Tabs component for organizing content into tabbed interfaces.
- Implemented Textarea component for multi-line text input.
- Created Tooltip component for displaying additional information on hover.

feat: add PocketBase helpers and types

- Implemented various helper functions for interacting with PocketBase collections (customers, companies, suppliers, quotes, orders).
- Added type definitions for entities such as Customer, Company, Supplier, Quote, Order, and their respective items.
- Included utility functions for generating unique identifiers for quotes, orders, and purchase orders.
- Added functions for calculating totals and formatting currency and dates.

chore: add TypeScript configuration

- Added tsconfig.json for TypeScript support with strict type checking and module resolution.
2026-05-24 16:31:01 +02:00