Commit graph

560 commits

Author SHA1 Message Date
Dave
0b6171b851 feat(collection-pool): enhance stock row handling and filtering logic
- Added `drv_id` to the stock row data structure to ensure proper assignment tracking.
- Implemented a new `isReadyForCollection` function to streamline the logic for determining if stock rows are ready for collection.
- Updated the `buildVisibleRows` function to utilize the new readiness check, improving the accuracy of row filtering based on the ready status.
- Added a test case to verify that stock rows are correctly included in the ready filter, ensuring expected behavior in the collection pool view.
- Enhanced coordinate parsing logic to handle various input formats, improving robustness in the driver stops API.
2026-08-17 22:33:47 +02:00
Dave
519fb422ae fix(pdf): adjust totals alignment in quote document
- Updated the `totals` style in the PDF generation to ensure totals are pushed to the right edge of the totals row, regardless of the presence of the operator note. This prevents shifting when the note is empty, enhancing the layout consistency.
2026-08-17 15:44:21 +02:00
Dave
50944a3526 feat(quotes): add operator-facing notes functionality to quotes
- Introduced a new `quote_notes` field to store operator-facing free-text notes, distinct from the existing `notes` field used for rejection audit logs.
- Updated the quote processing page to include a `QuoteNoteCard` for editing and displaying the operator notes, ensuring seamless integration into the PDF generation flow.
- Enhanced the PDF generation logic to render the operator notes in a blue callout below the totals, improving visibility for end-users.
- Implemented a new service function `setQuoteNotes` to handle the saving of notes, including trimming whitespace and handling non-string inputs defensively.
- Added unit tests for the `setQuoteNotes` function to ensure correct behavior and data integrity when updating notes.
- Updated relevant types and documentation to reflect the new functionality and its intended use cases.
2026-08-17 15:22:16 +02:00
Dave
9e8bb0a1ad feat(order-splitting): enhance order item splitting functionality and error handling
- Implemented a new split mechanism for order items, allowing operators to split quantities based on in-stock and non-in-stock statuses.
- Updated the payload for creating split order items to ensure it adheres to the PocketBase schema, avoiding empty strings for relation fields and removing deprecated fields.
- Enhanced error handling in the split route to log unexpected errors for better debugging.
- Improved the UI to conditionally render split buttons based on item availability, ensuring a clearer user experience.
- Added unit tests to validate the new splitting logic and payload structure, ensuring robustness against schema changes.
2026-08-17 14:14:27 +02:00
Dave
437ed3529c feat(collection-confirm): implement confirmation dialog for stock collection
- Introduced a new `ConfirmStockDialog` to handle stock collection confirmations, allowing operators to review per-line quantities and any short lines before finalizing the action.
- Updated the `CollectionConfirmPage` to manage the new confirmation state and trigger the dialog upon clicking the "Confirm collection" button.
- Enhanced tests to cover the new dialog functionality, ensuring correct behavior for both full and short quantity lines during the confirmation process.
- Improved documentation to clarify the flow and user interactions with the new confirmation dialog.
2026-08-17 11:41:55 +02:00
Dave
d29b91c7c0 feat(collection-confirm): update stock item filtering logic in listCollectedItems
- Modified the filter criteria in the `listCollectedItems` function to exclude stock lines that have been fully received, ensuring only pending items are displayed.
- Updated related tests to reflect the new filtering logic, enhancing clarity on the conditions under which stock items are included in the list.
- Improved documentation comments to explain the filtering behavior and its implications for the stock confirmation process.
2026-08-17 08:27:36 +02:00
Dave
9d80d52c17 feat(collection-confirm): improve idempotency handling in stock confirmation
- Updated the `confirmStockRows` function to handle cases where a stock line is already fully received, returning a success response without throwing an error. This change prevents the confirm-stock button from becoming inoperable due to previous confirmations.
- Enhanced tests to verify the new behavior, ensuring that full-quantity rows are omitted from updates and partial rows are processed correctly.
- Added documentation to clarify the idempotency behavior and its implications for the stock confirmation process.
2026-08-17 08:19:38 +02:00
Dave
fc55613070 feat(collection-confirm): add quantity editing tests for order items and stock sources
- Implemented tests for quantity editing functionality, ensuring that pressing Enter updates the quantity for order items and stock sources correctly.
- Added validation for input errors, rejecting fractions and negatives with appropriate inline error messages.
- Enhanced test coverage for the quantity handling logic, confirming correct API calls and data submissions for both customer and stock items.
2026-08-17 07:21:50 +02:00
Dave
d0fb8e81f0 feat(collection-confirm): add quantity collection handling and deduplication improvements
- Introduced a new `handleQtyChange` function to manage per-row quantity updates for both customer and stock items, ensuring correct data submission to the appropriate endpoints.
- Enhanced the `dedupeAttachments` function to handle additional document sources, including parent purchase orders, and skip empty filenames to prevent 404 errors.
- Updated the `ItemsTable` and `PoCard` components to support quantity editing, allowing users to modify collected quantities directly in the UI.
- Added tests to validate the new quantity handling logic and attachment deduplication, ensuring robust functionality across various scenarios.
2026-08-17 02:17:27 +02:00
Dave
4a59288a01 feat(deliveries): enhance delivery notes management and UI
- Introduced a new `DeliveryNoteRow` type to track delivery notes alongside items, improving the organization of delivery data.
- Updated the `DeliveryListResponse` type to include delivery notes, allowing for better integration with the existing delivery management system.
- Enhanced the `groupByCustomerOrder` function to accommodate delivery notes, ensuring they are grouped correctly with their respective orders.
- Implemented state management for delivery notes in the `DeliveriesPage` component, including loading and error handling.
- Added search functionality for delivery notes, enabling operators to filter by delivery note number, customer PO, and order details.
- Updated the UI to display delivery notes alongside items, improving the overall user experience in the deliveries management interface.
- Enhanced tests to cover new delivery notes functionality and ensure correct behavior across various scenarios.
2026-08-17 01:27:03 +02:00
Dave
1640c1e09a feat(delivery-notes): implement QuickBooks invoice auto-close functionality
- Added a new service function `markDeliveryNoteCompletedByInvoice` to auto-close delivery notes after successful QuickBooks invoice creation, updating the status to "completed" and appending an audit banner to the notes.
- Enhanced the delivery note detail page with a modal for creating invoices via QuickBooks, including customer selection and billing company options.
- Implemented state management for the invoice modal, including loading states and error handling for customer fetching.
- Updated tests to cover the new auto-close functionality and ensure correct behavior across various scenarios.
- Improved documentation for the delivery notes service to reflect the new functionality and its usage.
2026-08-16 22:24:08 +02:00
Dave
46e0683635 feat(duplicate-orders): enhance duplicate order detection and UI
- Introduced a new `DuplicateKind` type to differentiate between "order_number" and "line_aggregate" duplicates.
- Updated the `DuplicateOrdersDialog` component to support tabbed navigation between order number and line aggregate views, improving user experience.
- Enhanced the data structure for duplicate records to include `totalQuantity` and `totalSellingPrice`, facilitating more accurate duplicate detection.
- Implemented logic to auto-flip to the tab with available content, ensuring operators do not encounter empty views.
- Expanded test coverage for the `findDuplicateOrders` function to validate new line-aggregate matching logic and ensure accurate detection of duplicates across different scenarios.
- Improved documentation for the duplicate order handling process, clarifying the criteria for identifying duplicates.
2026-08-16 11:25:00 +02:00
Dave
17580b5280 feat(invoicing): implement detailed view toggle for supplier and PO number
- Added a switch to toggle the visibility of supplier names and PO numbers in the invoicing page, enhancing user experience by allowing operators to view detailed information as needed.
- Updated the `RowIdentity` component to conditionally render supplier and PO details based on the toggle state.
- Introduced localStorage persistence for the detailed view preference, ensuring user settings are retained across sessions.
- Enhanced tests to verify the functionality of the detailed view toggle and its impact on displayed data.
2026-08-16 11:01:52 +02:00
Dave
1bc80dc686 feat(orders): enhance order retrieval and statistics functionality
- Updated the `GET /api/v1/orders` endpoint to support additional query parameters including `customer`, `createdAfter`, `createdBefore`, and `status`, allowing for more granular order filtering.
- Implemented logic to resolve customer IDs from names and aggregate order items by their statuses for improved data retrieval.
- Introduced new helper functions in `orders-service.ts` for fetching order statistics and daily summaries, enhancing reporting capabilities.
- Added comprehensive documentation for the new query parameters and their usage in the API documentation.
- Improved error handling for invalid customer and status inputs, ensuring clearer feedback for API consumers.
2026-08-16 00:51:24 +02:00
Dave
cf87a370cf feat(quotes): enhance quotes.submit functionality and error handling
- Updated the `quotes.submit` tool to allow submission of quotes with unpriced items by introducing a `partial: true` flag, transitioning the quote to `partial_approval_pending` instead of `approval_pending`.
- Enhanced the response structure of `submitQuote` to include `previousStatus`, `submittedAt`, and `targetStatus`, providing better context for the agent.
- Improved error handling in the `sendQuoteEmail` function to surface detailed readiness issues when a PDF cannot be generated, allowing operators to address specific gaps in quote items.
- Regenerated API documentation in `docs/api-mcp-layer.md` to reflect these changes, ensuring accuracy and clarity in tool descriptions.
- Added comprehensive tests to validate the new functionality and error handling improvements.
2026-08-15 23:57:51 +02:00
Dave
e5e31a7bdc feat(mcp): implement upstream origin resolution for internal API calls
- Added a new `upstreamOrigin` function to resolve the correct upstream API origin for internal MCP to REST calls, addressing issues with container deployments where `req.nextUrl.origin` resolves incorrectly.
- The function prioritizes environment variables for configuration, ensuring proper routing in various deployment scenarios.
- Updated multiple API fetch calls to utilize the new `upstreamOrigin` function, improving reliability and consistency in internal API interactions.
2026-08-15 23:22:19 +02:00
Dave
e7672ab7c9 feat(mcp): implement structured MCP error handling for upstream fetches
- Introduced structured error handling for MCP upstream fetches, distinguishing between network errors (`-32010`) and upstream errors (`-32011`). This allows the agent to provide more informative feedback based on the type of failure encountered.
- Updated the `fetchUpstreamJson` function to throw `McpUpstreamError` with detailed error data, including hints and next actions for specific tools.
- Enhanced the `TOOL_HINTS` mapping to provide tool-specific guidance for handling errors, improving the agent's ability to respond to various failure scenarios.
- Added comprehensive unit tests to validate the new error handling logic and ensure correct behavior across different error cases.
- Updated documentation in `docs/agents/hermes-skill.md` to include a new section on structured MCP errors, detailing the error codes and their meanings.
2026-08-15 22:32:11 +02:00
Dave
151ae8d67f feat(quotes): introduce quotes.submit tool for approval transition
- Added a new `quotes.submit` tool that transitions a quote from `new` to `approval_pending` once all line items are priced. This tool ensures that only fully priced quotes can be submitted for approval, enhancing the integrity of the approval process.
- Updated the API documentation in `docs/api-mcp-layer.md` to include the new `quotes.submit` tool and its usage details.
- Enhanced the `quotes` status enum in `docs/agents/hermes-skill.md` to reflect the new transition and its implications.
- Regenerated documentation to ensure accuracy, increasing the total tool count from 126 to 127.
- Added comprehensive tests for the `submitQuote` function to cover various scenarios, including idempotency and error handling for unpriced items.
2026-08-15 19:01:52 +02:00
Dave
c4b53bcc4b feat(mcp): add walk-in quote creation and enhance customer filtering
- Introduced a new `quotes.create` tool for creating quotes from scratch without an inbound email, allowing operators to generate quotes directly from the dashboard.
- Updated `customers.list` to support filtering by representative using either a 15-char PB user ID or a case-insensitive name/email match.
- Enhanced API documentation in `docs/api-mcp-layer.md` to reflect the addition of the new quote creation tool and updated customer filtering capabilities.
- Regenerated documentation to ensure accuracy, increasing the total tool count from 125 to 126.
2026-08-15 11:50:48 +02:00
Dave
80a08a742b feat(mcp): enhance API documentation and add new tools
- Updated `docs/api-mcp-layer.md` to reflect the current state of the API, including new endpoints and tools.
- Added `category` field to `QUOTE_ITEM_PATCH_FIELDS` and `ORDER_ITEM_PATCH_FIELDS` to support item categorization.
- Introduced 22 new MCP tools to cover previously missing REST functionalities, increasing the total tool count from 103 to 125.
- Improved descriptions for several existing tools to clarify their usage and parameters.
- Regenerated the API documentation to ensure accuracy and completeness.
2026-08-15 00:06:40 +02:00
Dave
48053a6205 feat: add support for stock purchase attachments
- update backend service to fetch stock purchase attachments
- refactor dedupe logic to avoid filename collisions between customer and stock attachments
- adjust PoCard to generate correct file URLs for stock attachments
- update test expectations for the modified service query
2026-08-14 18:25:05 +02:00
Dave
e27184245b refactor(agent scan route): remove debug logs and redundant sanity check
Remove dev-time console logging and the unnecessary stock_purchases collection probe check to clean up the route handler.
2026-08-14 17:55:58 +02:00
Dave
162e47e80e refactor: clean imports, update types and fix issues
- move CollectionConfirmValidationError imports from stock-purchase-items-service to collection-confirm-service
- update ConfirmRow type: add supplier_sku field and remove unused nested expand properties
- refactor sortRowsByField generic in orders-service to fix type access errors
- add non-null assertion to firstRow.stock_purchase_id in collection confirm page upload handler
2026-08-14 17:13:04 +02:00
Dave
59f245d798 feat(collection-confirm): add stock item edits
- Add new POST API endpoints at `/api/v1/stock-purchase-items/[id]/sku` and `/api/v1/stock-purchase-items/[id]/cost` for updating stock purchase item details
- Update ItemsTable to support cost and SKU edits for all row types, add supplier SKU column and editing for stock rows
- Extend PoCard to pass edit callbacks and add stock-specific invoice upload functionality
- Update all related test suites to cover new editing and UI features
- Adjust invoice upload messaging to differentiate between customer and stock purchase orders
2026-08-14 16:39:46 +02:00
Dave
9e74968b5e feat: add PO agent workflow and inline SKU editing
Add full purchase order agent tooling and supporting changes:
- Add server-side purchase-order-agent-service for scanning both stock and customer POs, with complete test coverage
- Add inline SKU and supplier SKU editing flows to stock order detail pages
- Update MCP API route to support new PO agent tools (purchase_orders.scan, diff, record_diff_report) and stock_purchase_items.list
- Fix flaky CollectionPoolPage tests by wrapping state-dependent assertions in waitFor
- Refactor CollectionPoolPage auto-collapse logic to avoid react-hooks lint trap and run exactly once on initial load
- Delete temporary .tmp-inspect-pool.mjs development script
2026-08-14 12:37:13 +02:00
Dave
541676dabb refactor(invoicing): remove intermediate trimmedOverride variable 2026-08-14 11:25:10 +02:00
Dave
999948861e feat: add server-side quote search & PO number format update
Implement new server-side ranked quote search endpoint at `/api/v1/quotes/search`, replacing the legacy 500-row client-side substring scan that missed older quotes and didn't rank results by relevance. The new search scores matches across quote identifiers, customer/company headers, and line item fields.
Update PO number generation and validation to use a dashless format (POYYYYMMNNNXXX) with per-company scoped sequence numbers, and ignore legacy PO formats when calculating new sequences.
Remove legacy `searchQuotesWithItems` function and its associated test file, then update the quotes page to use the new server-side search API.
Add comprehensive unit and integration tests for the new quote search service and updated PO number logic.
2026-08-14 11:15:38 +02:00
Dave
3b8bc0fc35 feat(delivery-notes, migrations): add tabs, grouping, markup, and fix DN relations
- Add shared env loader for migration scripts to load .env and .env.local files at module init
- Add migration script to fix broken delivery note relation fields and backfill missing company data
- Update delivery notes list page: add status filter tabs, company-based collapsible grouping, increased fetch limit, and improved global search
- Add per-item cost price, markup calculations, and total summary rows for cost, selling price, markup, and margin to delivery note detail pages
2026-08-14 09:41:14 +02:00
Dave
43de97501c feat(tv): add TV dashboard + refine workflows
Add full PIN-protected TV dashboard stack including auth, redirects, map view, APIs, and server services.

Also include these critical refinements:
- Overhaul PO number generation to use per-company monthly sequences
- Rework quote rejection to bounce quotes back to operator queues instead of marking them terminal
- Add post_processing order tab group for clearer workflow visibility
- Fix collection pool tooltip positioning, overflow clipping, and default collapsed state
- Refactor customer list API, clean up unused form props, and fix item intel popover target ID handling
- Add comprehensive tests for new components and update existing test expectations
2026-08-13 20:55:22 +02:00
Dave
dce9bfb04a feat(invoicing, dn): add surplus tracking, fix qty, update branding
- Fix resolveInvoiceLineDefaults to prioritize customer order quantity over supplier-collected quantity, ensuring invoices reflect what the customer actually ordered
- Add surplusQty utility function to calculate supplier MOQ overflow that should be booked to stock via /api/v1/stock/surplus-book
- Add surplus stock indicators in order and delivery note modals with descriptive tooltips explaining the surplus amount
- Expand supported letterhead codes to include WESTSCOTT GROUP, and configure all delivery notes to use the Westcott Group letterhead globally per business branding rules
- Improve error handling and logging in the delivery notes API POST route to include PocketBase error details and request context for easier debugging
- Add comprehensive unit tests for the updated invoice line logic and new surplusQty function to prevent regressions
2026-08-13 13:02:37 +02:00
Dave
8a224a7a24 feat(delivery-notes): add order disambiguation, fix PDF layout, update combine flow and qty resolution
- Fix delivery note PDF signature section overlapping page contents by removing fixed absolute positioning
- Add client-side picker for duplicate order numbers when merging delivery notes
- Add orderId parameter to combine delivery notes API for direct order lookup
- Update resolveDeliveryNoteLineQty to prioritize operator-edited quantity first
- Refactor combine delivery notes service and API to handle order lookup errors and candidate selection
2026-08-13 12:00:51 +02:00
Dave
617c5b3422 feat(delivery-notes): add inline qty editing and bulk combine features
Add inline quantity editing for delivery note items:
- New PATCH API endpoint and service function to update item quantities
- Optimistic UI updates on the detail page with error and loading states
- Input validation and status gating for draft/sent delivery notes

Add bulk delivery note combine functionality:
- New POST API endpoint and service to merge multiple draft/sent notes
- Row selection support in DataTable across pagination
- Confirmation modal with selected notes preview and optional order linking
- Automatic audit trail updates for merged and cancelled records

Extend OrderItem TypeScript interface with optional order expand field
Fix minor type casting issues in createAdHocDeliveryNote utility
2026-08-13 11:24:05 +02:00
Dave
4dd5898007 feat(delivery-notes): add pdf regeneration and fix ad-hoc pdf saves
Add new POST API endpoint at /api/v1/delivery-notes/[id]/regenerate-pdf to re-render and save delivery note PDFs from current line items. Add a "Regenerate PDF" button to the delivery note detail page with loading state and single-flight protection to prevent duplicate requests. Update ad-hoc delivery note creation to automatically attach PDFs to order items so print and download buttons work immediately after creation. Add helper utilities for resolving relation names and calculating line item quantities for PDF rendering.
2026-08-13 10:59:22 +02:00
Dave
18397bc9be feat(counter): add standalone counter order PWA
This commit adds a full unauthenticated PWA for in-store retail order taking:
- Dedicated `/new-order` route with complete order form, customer/company picker
- Public `/api/counter/*` endpoints for search, order creation, and photo uploads
- Photo capture and gallery selection with 10-photo per order limit
- Offline caching via dedicated service worker and app manifest
- Shortcut redirect at `/counter` for quick installation
- Comprehensive setup and usage documentation in `docs/counter-pwa.md`
- Minor cleanup to root layout metadata and service worker registration
- Small layout fix for collection pool row text truncation

Orders submitted via the PWA appear immediately in the main CRM's New tab, and the app is designed for trusted office kiosk phones without requiring user login.
2026-08-13 09:27:20 +02:00
Dave
c0ec3c99ef feat(orders,invoicing): add duplicate order cleanup and soft cancellation
Add a complete workflow for managing duplicate intake orders:
- Add new server API endpoints for single order cancellation, duplicate detection, and bulk duplicate cancellation
- Add client UI components for bulk duplicate cleanup and single order soft cancellation
- Add a "Duplicates" button to the orders dashboard for quick access to the cleanup tool
- Refactor invoicing module: rename customerNameSimilarity to nameSimilarity, update QB customer picker to use radio buttons and remove automatic preselection
- Add comprehensive test coverage for the new order service utilities
2026-08-13 09:02:27 +02:00
Dave
756597068e fix(delivery-notes): correct DN cancellation and filter issues
Update the cancel delivery note dialog description to correctly state items are marked as cancelled
Fix PocketBase expand field whitelisting for delivery items to avoid missing related entity data
Change order item status to "cancelled" instead of "completed" when cancelling a delivery note, with updated JSDoc explaining the choice of status
Update the buyer tasks PO sent filter and its regression test to cover all current ItemStatus values
2026-08-12 15:36:31 +02:00
Dave
9eea138662 feat(delivery-notes): add mark complete and cancel delivery note functionality
Add backend API routes and service functions for delivery note status updates with strict validation rules
Add UI action buttons and cancellation confirmation modal to the delivery note detail page
Update table layouts and styling across delivery notes and invoicing pages to improve responsiveness
Fix text overflow issues by adding whitespace-nowrap and break-words classes
Refactor order items table to display status inline and reduce redundant layout code
2026-08-12 08:55:56 +02:00
Dave
8efb952c76 feat(order-status): add delivery_note and fix tab mappings
- add `delivery_note` to the ItemStatus union type
- move delivery_note visual config from EXTRA_ITEM_STATUS_VISUAL to ITEM_STATUS_VISUAL
- update tab group mappings: add delivery_note to processing tab, expand collected tab with post-pickup statuses
- move removed status to the cancelled tab group
- replace silent fallback in itemStatusToTabGroup with explicit error for unmapped statuses
- add comprehensive regression test to ensure all ItemStatus values are mapped to a tab
2026-08-12 08:09:36 +02:00
Dave
8856146023 fix(orders,delivery-notes): resolve build type errors after supplier removal 2026-08-12 01:42:19 +02:00
Dave
6344948b0b feat: add driverless collection confirm and new order tooling
This commit adds several key features, improvements, and cleanups across the codebase:
- Add `order_items.confirm_collected` MCP/REST endpoint to mark order items as collected without requiring driver assignment
- Add standalone order creation and order split APIs for flexible order management
- Update order list sort to oldest-first to align with user workflow of working through oldest orders first
- Improve order search to show cross-tab matches and display source tab indicators on search results
- Add customer name similarity check to warn about mismatched QuickBooks customers during invoice creation
- Remove supplier name column from delivery note PDFs and clean up related data passing across delivery note routes
- Add validation and debug logging to ItemIntelPopover for missing item ID on apply actions
- Remove unused OrderItemContextPopoverTrigger component from order detail page
- Add delivery note regeneration script and update test suites for new and existing functionality
- Update documentation and add test coverage for the new collection confirm tool
2026-08-12 01:13:46 +02:00
Dave
cfc56f5c86 feat(quotes): add approval page and email updates
- add operator (claimer) display section to quote approval review page
- add per-line-item supplier pricing proof popover with lazy-loaded attachment previews
- improve customer/company text styling and responsive layout on approvals pages
- fix markup and selling price rounding to whole currency values for cleaner outputs
- completely overhaul default quote email templates for better readability and clear CTAs
- update sticky action bar styling and responsive behavior on approval page
- remove hardcoded "The Sales Team" fallback sender name in email templates
2026-08-11 16:09:40 +02:00
Dave
7d4e4c34f2 feat(api/v1/items): add item intel refresh route
Add a new Next.js POST API endpoint that regenerates AI item insights for specific quote_item or order_item records. Support dry-run mode to preview insights without persisting changes, validate input parameters and existing records to return clear error responses, and use admin-level PocketBase access for trusted server-side callers including n8n webhooks and batch cron jobs.
2026-08-11 11:28:51 +02:00
Dave
397df8e2b2 fix: correct quote expiry handling for PocketBase's 0 default
PocketBase returns 0 for unset number fields, which broke the original
null-coalescing check in effectiveValidityDays, leading to PDFs showing
"Valid until: today" for all new quotes created via email ingest.

Changes include:
- Update effectiveValidityDays to treat 0, negatives, null/undefined as falling back to 30-day default
- Add test cases for 0 and negative validity_days inputs
- Explicitly set validity_days to QUOTE_VALID_DAYS when creating new quotes
- Add one-time idempotent migration script to backfill legacy invalid validity values
- Refactor item intel popover patch logic to use PocketBase SDK for authenticated requests
- Add n8n workflow for AI-powered item insight matching
2026-08-11 08:32:17 +02:00
Dave
608a6ab978 feat(invoicing): widen the recent-window filter from 3 to 5 days
Single-line behavioural change: buildRecentInvoiceRange now subtracts
5 days from today instead of 3. The "in last 3 days OR unprinted" rule
shipped in the previous commit picks up the new window automatically —
the window affects which old-but-unprinted rows are still considered
"in the window" (purely a UX nuance; the unprinted branch already
covers anything older).

Also tighten the section-header + empty-state copy and the test
fixtures to reflect the new window. The "INV-OLD-*" dates in the
range test had to push back from 2026-07-05 to 2026-07-02 — 2026-07-05
fell inside the new 5-day window, which would have flipped the test's
expectation (it was asserting that printed-old dates are hidden).

Files:
- src/app/(app)/invoicing/view-model.ts — buildRecentInvoiceRange: -3 → -5
- src/app/(app)/invoicing/view-model.test.ts — expected `from` date
  shifts by 2 days; test name updated
- src/app/(app)/invoicing/page.tsx — section header + empty state +
  inline comments mention "5 days" instead of "3 days"
- src/app/(app)/invoicing/page.test.tsx — test name updated;
  INV-OLD-*/INV-OLD-PRINTED fixture dates pushed back from 07-05 to 07-02
  to stay outside the new 5-day window
2026-08-11 07:43:05 +02:00
Dave
228caf1680 feat(invoicing): surface all unprinted invoices + delivery notes on the Invoiced tab
The Invoiced tab used to filter to the last 3 days only, which
meant an invoice or delivery note that fell off the window would
disappear from the operator's list even if they hadn't printed
it yet. The only way back was the per-row "Print" button on a row
that no longer existed in the tab.

Change the filter rule from "in last 3 days" to "in last 3 days OR
unprinted". A row surfaces if either:
  - its date falls inside recentInvoiceRange, OR
  - it has not been printed yet (printed !== true).

This means an invoice or DN stays on the operator's list until it's
printed, regardless of age. The list doubles as the "what's still
outstanding" view — print a row, it drops off the next reload.

Stock bookings are unchanged (still windowed to the last 3 days
only) — there's no print tracking on stock_purchases yet, so
"unprinted stock booking" is undefined.

Also broaden the bulk-print button from "Print Today's Unprinted"
to "Print All Unprinted" so the operator can clear the backlog
in one pass instead of having to print each row individually.
The button iterates every invoice + DN group whose items haven't
all been printed, regardless of date.

Section header + empty state text updated to reflect the new rule.

Files:
- src/app/(app)/invoicing/page.tsx — filter logic, button copy,
  section header, empty state, bulk-print handler
- src/app/(app)/invoicing/page.test.tsx — updated existing tests
  to match the new behaviour; renamed "bulk prints only today's
  unprinted invoices" to "bulk prints every unprinted invoice,
  regardless of date"
2026-08-11 07:36:01 +02:00
Dave
3a59fa104c feat(item-intel): add new item intel popover and backend workflows
This commit replaces the legacy item history and AI insights system with a standardized, fuzzy-matched item intel workflow:
- Update AiItemHistoryTrigger component to support both quote and order items via the `collection` prop, replacing the old `insights` prop with `intel`
- Add full `ItemIntel` type definitions to `src/lib/types.ts` for the new standardized insight payload
- Create new REST API endpoints for fetching and computing item intel for `quote_items` and `order_items`
- Rewrite the MCP insight endpoint to use the new shared `item-intel-service` instead of legacy individual insight functions
- Reorder quotes page tabs to place Delivery Note quotes alongside New quotes for better daily operator workflow
- Add item intel triggers to quote process and order process pages
- Remove deprecated document-level `AiInsightsPanel` components from quote and order detail pages
- Add bulk backfill endpoint for populating intel across existing active items
2026-08-11 02:57:57 +02:00
Dave
47d58db0c9 feat(mcp): add price_list.add_items tool for agent-driven catalogue upsert
Add a new MCP tool that lets the agent read a supplier PDF, quote PDF,
or pasted supplier email with its native vision, extract the per-line
fields, and commit them to the price_list catalogue in one round-trip.

Why: the only pre-existing path was operator upload via /pricelist ->
n8n ingest -> raw_price_list -> AI extraction -> price_list. That flow
is async, human-in-the-loop, and gates on n8n being healthy. This
tool gives the agent a synchronous shortcut for ad-hoc catalogue
updates -- paste a PDF, get the catalogue updated, no async hops.

The agent does the OCR; the tool does the commit. No LLM work moves
into the MCP server.

Behaviour:

- Dedupe by (sku, supplier) -- exact match. Different suppliers with
  the same SKU get separate rows.
- Upsert policy: cost_price overwrites (latest price wins).
  Description, selling_price, unit, category, subcategory, brand,
  markup, stock_qty, search_text, sku_normalised also patched in
  place on update.
- sku_normalised auto-computed (uppercase, strip non-alphanumeric --
  same canonical form price-list-match.ts uses).
- search_text auto-computed (lowercased, space-separated concat of
  sku + description + brand + supplier + category + subcategory +
  synonyms).
- Skipped items returned with per-item reason (missing_sku,
  missing_supplier, invalid_cost_price, pb_write_failed). Never
  silent.
- Bulk cap 500 items per call; larger lists rejected with
  too_many_items reason.
- source_file_id + source_label supported so new rows can be
  traced back to a raw_price_list upload (optional).
- Supplier stored verbatim on price_list.supplier (free-text field,
  no FK resolution -- same as the live schema).

Files:

- src/lib/server/price-list-service.ts (new) -- addPriceListItems +
  buildSearchText + computeSellingPrice helpers
- src/lib/server/price-list-service.test.ts (new) -- 17 tests
  covering validation, upsert, dedupe filter shape, normalisation
- src/app/api/mcp/route.ts -- new tool definition + dispatch block
- src/app/api/mcp/route.test.ts -- 2 dispatch tests + tool-list
  assertion update
- .agents/skills/wfdash-giellie/SKILL.md -- new section "8. Price-
  list catalogue" documenting input/output shapes + failure modes

Tests:

- 134/134 pass across the affected files
- 1775/1778 in the full suite (3 pre-existing failures unrelated
  to this change: pocketbase-admin.test.ts PB mock mismatch,
  quotes/items/[id]/attachments/upload/route.test.ts timeout,
  supplier-form.test.tsx race -- all reproducible on main)
- npm run build clean
2026-08-10 12:45:05 +02:00
Dave
e9ffa6df4e feat(quotes/process): add mobile card layout for quote items
Replace the cramped horizontal table layout on mobile viewports with responsive vertical cards for each quote item. The new `ProcessItemCard` component provides full-width form fields, properly sized 44px tap targets for all actions, and maintains full parity with the desktop table implementation by reusing the same state handlers and callbacks. Add comprehensive test coverage for the new component, and fix existing mobile overflow issues in the quote process page header and table layout.
2026-08-10 10:47:36 +02:00
Dave
d9c60aff6d feat: add split views, stock picking slips, and invoice viewer
Comprehensive changes including:
- Refactor picking slip line handling for multiple document types across print endpoints
- Add new `/api/v1/stock-purchases/picking-slip` API for stock booking picking slips
- Implement reusable Splitter component and useSplitRatio hook for resizable panels
- Add floating/fullscreen invoice viewer to collection confirm page
- Add real-time stock booking update event for invoicing tab
- Add full test coverage for all new components and APIs
- Include temporary chat attachment images for testing purposes
2026-08-09 23:16:55 +02:00
Dave
9eef1fbd56 feat(mcp): add partial=true flag to PO invoice matching for buyer-side mark-and-flip
When the supplier ships a partial invoice (BREATHER on PO26080502STK was
not invoiced this round, but the other 7 lines were), the buyer wants
to:
  - mark and flip what we can confirm came in
  - leave the rest for the buyer to reconcile manually

Adding a new 'partial: true' flag to stock_purchases.match_and_receive_from_invoice
that:
  - widens the verdict gate to allow 'unmatched_po_lines' and 'cost_mismatch'
    to proceed when partial=true (the buyer is explicitly accepting these)
  - passes per-line quantity_received:0 overrides for unmatched PO lines
    into the existing receiveStockPurchase(items) override path, so only
    matched lines get booked into stock_ledger
  - surfaces 'skipped_po_line_ids' in the response so the buyer sees
    exactly what was held back
  - leaves the customer-PO path unchanged (every matched line is stamped,
    partial semantics only apply to stock purchases for now)

Hard stops regardless of partial: qty_mismatch on matched lines,
unmatched_invoice_lines, supplier_mismatch, wrong_status.

Test coverage: +1 dispatch test (partial flag forwarding) plus the
existing 'partial: false' assertion on the dry-run dispatch test.

Live-validated on PO26080502STK + invoice WR248939 (G-Man #1, 7 lines):
- 6 matched CIRCLIP/KM/MB lines booked, qty_received bumped
- BREATHER 3/4 line skipped via qty_received=0, surfaced in
  skipped_po_line_ids for manual reconciliation
- PO status flipped sent -> received
2026-08-09 20:41:27 +02:00
SJCoetz
87cead1bcf feat(mcp): expand stock purchase invoice matching service with 5 phases
Build out the buyer-side PO reconciliation workflow that landed in
60d3204 ('stock purchase invoice reconciliation tool') into a full
3-document × 2-PO-kind matching service. The tool now covers every
real-life supplier document the buyer can receive.

Renamed the service entry point from matchAndReceiveFromInvoice to
matchAndReceiveFromPoDocument (old name kept as a back-compat alias).
The MCP tool name stays stock_purchases.match_and_receive_from_invoice
so existing callers don't break; the input arg shape changed from
'invoice:' to 'document:' (old 'invoice:' arg still accepted for
back-compat).

Phase 1 — supplier_sku backfill (prep work, not in service code)
Phase 2 — auto-detect stock vs customer POs (single tool, both kinds)
Phase 3 — GRN (delivery-note) mode via new mode: 'grn' flag
Phase 4 — pack-size inference (Orapi case: per-unit vs per-pack)
Phase 5 — PO reference normalisation (PO202608017 vs PO-2026-08-017)

Also adds 3 new MCP tools for the collection-confirm buyer workflow:
collection_confirm.list, collection_confirm.upload_invoice,
collection_confirm.confirm_order_items.

Docs: updated .agents/skills/wfdash-giellie/SKILL.md and
src/app/api/mcp/FEATURE-REQUESTS.md to describe the new modes and
shape. 1,661/1,664 vitest tests pass; the 3 failing tests are
pre-existing (PocketBase SDK mock mismatch in pocketbase-admin.test,
5s timeout in quotes/items/[id]/attachments/upload/route.test —
both reproducible on main without this change).
2026-08-09 20:23:36 +02:00
SJCoetz
f88f451d6e fix(invoicing): print bundle fails on production due to self-fetch
The /api/invoicing/print-bundle route was doing a self-fetch through
its own public URL to download the invoice PDF it needed to bundle:

  fetch(`${origin}/api/v1/files/order_items/${id}/${token}`)

That works on local because Node inside the container can hit
localhost:3000 as a loopback. On production (Coolify / Docker) the
container's fetch to its own public hostname fails — DNS resolves to
an external IP that doesn't route back, the outbound TCP is blocked,
or the TLS handshake fails. Node's fetch throws 'fetch failed' at
that point, which bubbles up to the browser as a 500 toast.

Fix: fetch the invoice PDF directly from PocketBase with admin auth,
the same pattern /api/v1/files/... uses internally and that
delivery-note-pdf already uses. Drop the now-unused 'origin'
parameter from handlePrintBundle and the GET/POST wrappers.

Tests updated to mock pb.files.getURL + pb.authStore.token and assert
the new PB file URL + Authorization header.

All 65 tests across the print-bundle, picking-slip, view-model, and
invoicing page suites pass. The 2 pre-existing pocketbase-admin.test
failures are unrelated (reproducible on main without this change).
2026-08-09 20:23:26 +02:00
SJCoetz
60d320411d feat(mcp): add stock purchase invoice reconciliation tool
Add the full buyer-side supplier invoice reconciliation workflow:
- Include the new `stock_purchases.match_and_receive_from_invoice` MCP tool for deterministic PO-invoice matching
- Create core matching service with strict, rule-based line matching (sku → supplier_sku → description overlap)
- Support dry-run default mode to validate matches before committing
- Add automatic attachment handling with standard `supplier_invoice_*` naming convention
- Add full test suite for the matching logic
- Update documentation and agent skill profile to document the new tool and workflow

Pre-existing test failures (3 total) are unrelated to this change.
2026-08-09 16:59:44 +02:00
SJCoetz
63048e51c9 feat: add AI quote processing pipeline and admin settings UI
Add complete end-to-end AI-powered quote extraction workflow:
- Disable PB SDK auto-cancellation to support parallel batch requests
- Add required runtime dependencies for AI processing and document parsing
- Implement AI settings backend, operator UI, and REST API routes
- Add quote ingestion, insight population, and manual re-run AI endpoints
- Build service layers for quote items, AI settings, and structured item insights
- Fix attachment upload handling and quote item history blob parsing
- Add supporting migrations, smoke tests, and shared utility functions
- Export previously private helper functions for cross-service reuse
2026-08-09 16:17:29 +02:00
SJCoetz
b52de77f8c fix(sprint): filter stale quote items, add cleanup migrations
- Update sprint page query to only show unprocessed items from active (new/claimed) quotes, plus orphans
- Add one-shot migration to mark existing stale unprocessed quote items as processed
- Add one-shot migration to fix duplicate Q202608235 quote number entries
- Refine comments in the sprint page component for better maintainability
2026-08-07 20:15:46 +02:00
SJCoetz
2de8cf1a56 chore(context): lint + build adjustments
Co-authored-by: Orca <help@stably.ai>
2026-08-07 03:04:28 +02:00
SJCoetz
f5185d3a2c feat(context): swap orders-page AI history ⓘ for context popover
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:59:27 +02:00
SJCoetz
995b7ed675 feat(context): swap sprint modal AI Insights for context panel
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:58:47 +02:00
SJCoetz
c5fbb7422f test(context): OrderItemContextPopoverTrigger UI tests
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:55:39 +02:00
SJCoetz
f75c1b2bbd feat(context): OrderItemContextPopoverTrigger (ⓘ on orders page)
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:55:14 +02:00
SJCoetz
b3a73c0040 test(context): OrderItemContextPanel UI tests
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:54:24 +02:00
SJCoetz
efd2ad6540 feat(context): OrderItemContextPanel (inline expandable, 4 rows)
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:53:21 +02:00
SJCoetz
5291fd2fd1 test(context): /api/v1/order-items/[id]/context route tests
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:50:44 +02:00
SJCoetz
7ad7375dd2 feat(context): GET /api/v1/order-items/[id]/context route
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:46:18 +02:00
SJCoetz
351c1b2b96 test(context): getOrderItemContext unit tests (null, quote, stock low/out, invoiced)
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:42:57 +02:00
SJCoetz
ced25be47a feat(context): implement getOrderItemContext (5 PB reads, fuzzy fallback)
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:34:45 +02:00
SJCoetz
18afe7d2d9 feat(context): add order-item-context-service skeleton + types
Co-authored-by: Orca <help@stably.ai>
2026-08-07 02:23:45 +02:00
SJCoetz
f35779369a fix(stock-purchase-items): drop dead drv_collected_at write to unblock build
The markLineCollected service and the stock-orders page's
handleAssignDriver (delivery-sentinel auto-collect path) both
wrote `drv_collected_at` to `stock_purchase_items`, but that
field exists on `order_items`, not on `stock_purchase_items`
(verified against pb_schema-2.json). Per AGENTS.md "select
fields are not self-service", PB would 500 both writes at
runtime. The TS error from the service was the build break
flagged in the 2026-08-06 23:34 deployment.

The page.tsx write was a latent runtime bug — TypeScript
never caught it because PB's loose `update` patch typing
accepts any field name. Both writes are removed; the
collection moment is captured by PB's `updated` timestamp on
the line row, which is sufficient for the auto-collect audit
trail. Inline comments point to FEATURE-REQUESTS as the
follow-up if a dedicated collection-date field is wanted
later (would need a PB admin schema change).

Also drops the matching test assertions that read
`drv_collected_at` off the response and replaces them with
a comment explaining the absence.

Tests: vitest 59/59 across stock-purchase-items-service +
stock-orders/[id]; npm run build compiles clean
(Next.js 16.2.6 Turbopack + TypeScript).

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-07 01:39:03 +02:00
SJCoetz
fe8a3c6872 feat: rework invoicing stock booking section
Move StockBookingSection from above the tab strip into the To Invoice tab's card list for consistent visual styling. Add expandable, lazy-loaded purchase order line items with session-based caching to reduce redundant network requests. Update component UI, styling, and documentation, and fix test mocks to prevent conflation of stock_purchases and order_items collection calls. Add ZAR currency formatting helper for displaying stock line item costs.
2026-08-07 01:07:56 +02:00
SJCoetz
c4125ee40a feat: add split-invoice stock PO workflow and supporting tooling
Ship full split-invoice stock purchase order workflow:
- Add 5 new MCP tools for per-line stock purchase item management and catalogue updates
- Add idempotent database migration adding sku, unit, and supplier_sku fields to stock_purchase_items
- Implement service layers for all new operations, including auto-closing the parent PO when all lines are fully collected
- Add complete test coverage for new services and API routes
- Update all relevant documentation including MCP API specs, agent instructions, and feature request logs
2026-08-07 00:53:29 +02:00
SJCoetz
d167f81ad5 feat(stock-orders): inline cost_price editing on lines table
Co-authored-by: Orca <help@stably.ai>
Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-06 23:36:27 +02:00
SJCoetz
bbfe20ec2d docs: register stock_purchases.add_attachment in feature backlog + API reference
Co-authored-by: Orca <help@stably.ai>
2026-08-06 23:29:55 +02:00
SJCoetz
dd57d29de3 feat(stock-orders): attachments card on detail page
Co-authored-by: Orca <help@stably.ai>
2026-08-06 23:29:00 +02:00
SJCoetz
f89bbb3a35 feat(mcp): add stock_purchases.add_attachment tool
Co-authored-by: Orca <help@stably.ai>
2026-08-06 23:24:00 +02:00
SJCoetz
ccf04bc39f feat(api): add stock-purchase attachments delete route
Co-authored-by: Orca <help@stably.ai>
2026-08-06 23:21:25 +02:00
SJCoetz
a72c5ca0a7 feat(api): add stock-purchase attachments upload route
Co-authored-by: Orca <help@stably.ai>
2026-08-06 23:21:00 +02:00
SJCoetz
70c158b374 feat(stock-purchases): add additional_attachments service helpers
Co-authored-by: Orca <help@stably.ai>
2026-08-06 23:20:26 +02:00
SJCoetz
9e118a3b5f feat(stock-purchase): split warehouse confirm from accountant booking
Repositioned booking responsibility: warehouse confirms physical
collection only (records quantity_received + flips header to
"received"); the accountant books into inventory via the new
invoicing flow once the supplier invoice is processed. This way
the payment-cycle reasoning lives at the booking step, not at
receipt.

Changes
- Migration: add booked_at + booked_by to stock_purchases
- Service: bookStockFromInvoice (accountant-side, splits from
  bookStockRows)
- API route: POST /api/v1/invoicing/stock-book
- UI: stock rows surfaced on invoicing page (StockBookingSection)
- UI: stock-purchase detail page
  - Driver picker on header (sentinel "delivery" user auto-collects
    every line, real drivers set assigned_to_driver)
  - "Confirm collection" replaces "Mark received" (warehouse-side
    only — no inventory writes)
  - Cancel button with confirmation dialog
- collection-confirm: confirmStockRows stripped of inventory writes;
  the prior /api/v1/collection-confirm/book-stock route was renamed
  to /confirm-stock and is now strictly the warehouse-side confirm
- Tests for all new flows (5/5 passing on the stock-order detail
  page; 10/10 on StockBookingSection)

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-06 23:01:15 +02:00
SJCoetz
bf54511db1 fix(buyer-tasks): make card layout mobile-friendly
At <=640px the buyer-tasks card content was crushed by the action
column sitting beside it: the PO number badge broke mid-string
('PO-2026-08-042' wrapping to 4 lines), supplier names wrapped to
6 lines, and the new 'Sent to ...' caption overlapped the PO
badge on the PO Sent tab.

Three responsive tweaks, all using Tailwind breakpoint utilities:

1. Outer card container switches from 'flex items-start' to
   'flex flex-col sm:flex-row sm:items-start'. The action column
   drops below the info column on mobile, giving the info all the
   available width and the buttons full-width tap targets.

2. PO number badge gains 'whitespace-nowrap'. The badge stays
   atomic; the parent's 'flex-wrap' carries the whole badge to a
   new line when it doesn't fit.

3. PO Sent right column: buttons stack vertically on mobile
   ('flex-col sm:flex-row' + 'flex-1 sm:flex-none' on each
   button) and the caption switches from 'text-right' to
   'text-left sm:text-right' so it sits under the buttons.

Desktop layout is unchanged — verified at 1280px that the
side-by-side buttons, right-aligned caption, and inline single
button all still render exactly as before.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-06 18:21:38 +02:00
SJCoetz
d2ffbea6bc feat(buyer-tasks): show recipient + send date on PO Sent card
Adds a small muted caption under the Re-Send / Mark as ready buttons
on the PO Sent tab showing the email address the PO was sent to and
the send timestamp (en-GB short format like '5 Aug 2026, 14:23').

Data sources come from the existing BuyerTaskGroup.emailPayload
exposed in commit f61c173 — no new PB fields, no new types. The
caption only renders when sentAt is present, so legacy rows (or a
fresh draft flipped to po_sent without a successful send) stay clean.

Visible on mail_failed too: the operator can see who we tried to
reach and when, alongside the existing 'Mail failed' banner.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-06 18:16:22 +02:00
SJCoetz
add7ab3302 fix(send-po-modal): seed default body when resend has no prior email_payload
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-06 18:10:08 +02:00
SJCoetz
abdc3a4d9f fix(send-po-modal): preserve previous message body on resend (don't overwrite with default template)
Co-authored-by: Orca <help@stably.ai>
2026-08-06 18:06:22 +02:00
SJCoetz
f61c173a1a fix(buyer-tasks): surface PO email_payload + attachments on group for resend modal prefill
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-06 18:01:58 +02:00
SJCoetz
6008f17c9a feat(buyer-tasks): add Re-Send button on PO Sent tab + theme-token cleanup
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-06 17:43:17 +02:00
SJCoetz
7f477ca949 fix: resolve PO bug, add sku, improve webhooks
Add `sku` to the order_item.patch MCP tool whitelist and update its documentation
Fix stuck stock POs in buyer tasks po_sent tab by filtering out downstream statuses
Rewrite margin approval webhook to use fire-and-forget dispatch to avoid UI blocking, add server-side error logging
Add MCP feature requests and local setup documentation
2026-08-06 13:13:57 +02:00
SJCoetz
4a69b57ec2 docs(pdf): remove stray duplicate 'from quoteSubtotal() in two ways:' line
Co-authored-by: Orca <help@stably.ai>
2026-08-06 12:22:22 +02:00
SJCoetz
68dcdd565d chore(pdf): silence unused-vars on intentional totalAmount destructure
Co-authored-by: Orca <help@stably.ai>
2026-08-06 12:21:00 +02:00
SJCoetz
180288e6e3 test(pdf): add render smoke tests for PO PDF (covers VAT totals)
Co-authored-by: Orca <help@stably.ai>
2026-08-06 12:13:52 +02:00
SJCoetz
07900075a4 docs(pdf): move VAT bullet to Layout block + tidy effective-qty comment
Co-authored-by: Orca <help@stably.ai>
2026-08-06 12:08:14 +02:00
SJCoetz
7a6e32cadb feat(pdf): add 15% VAT line + VAT-inclusive Total to PO PDF
Co-authored-by: Orca <help@stably.ai>
2026-08-06 12:02:55 +02:00
SJCoetz
a1714833a8 docs(pdf): fix poSubtotal JSDoc summary (effective-qty prose) + tidy blank lines
Co-authored-by: Orca <help@stably.ai>
2026-08-06 12:00:48 +02:00
SJCoetz
965f3e3bbe docs(pdf): restore poSubtotal JSDoc + clarify fallback uses || not ??
Co-authored-by: Orca <help@stably.ai>
2026-08-06 11:56:51 +02:00
SJCoetz
b3d9eeb5ce feat(pdf): add poSubtotal helper for PO PDF totals
Co-authored-by: Orca <help@stably.ai>
2026-08-06 11:54:23 +02:00
SJCoetz
5053ec96ea test: add quote detail page layout regression tests
Add a vitest suite that enforces critical layout invariants for the quote detail page, and include accompanying Playwright trace snapshots and console logs from the test execution.
2026-08-06 02:04:28 +02:00
SJCoetz
e2bcafe4d8 chore(playwright-mcp): add test snapshot and console logs 2026-08-06 01:56:47 +02:00
SJCoetz
2bd8fcf247 fix: resolve PocketBase expand projection bug
This commit fixes a critical PocketBase projection bug where omitting "expand" from fields lists silently drops related data, leading to missing supplier/customer/order info across the app. It also includes usability improvements and test coverage:

1.  Add "expand" to PB fields projections in invoicing page, quotes lookup API, sprint page, and quote search helper
2.  Update PO Sent tab filter to exclude "collected" and "ready_invoice" statuses
3.  Reorder buyer tasks list to sort by supplier first, then order number
4.  Add comprehensive regression tests for all fixed issues

Included Playwright test capture artifacts from local testing.
2026-08-06 01:33:16 +02:00
SJCoetz
d8dea63d16 feat(invoicing): include sibling order items in invoicing rows
- extract reusable constants and helper functions including escapeFilterValue, dedupeRawRows, listAllInvoicingRows, and loadInvoicingRows
- add safe filter value escaping to prevent query injection risks
- rewrite data fetching to pull all related order items for orders with ready-to-invoice rows, then deduplicate results
- replace raw getFullList calls with paginated PocketBase API usage
- update test suite to mock getList instead of getFullList and add coverage for new behavior
- clean up redundant eslint disable comments in modal components
2026-08-05 23:17:06 +02:00
SJCoetz
9f601002af refactor(collection-confirm): make PO cards start collapsed by default
Remove the initial open state for the first PO card, and update all tests to expect the default collapsed state. Users can expand cards manually to view contents, improving scannability for long PO queues.
2026-08-05 23:08:44 +02:00
SJCoetz
12fa65a481 feat: add new order, invoice, and dashboard management tools
- Add server-side `/api/v1/dashboard` endpoint to reduce client-side payload and round trips
- Implement invoice upload and order-item SKU update APIs with complete test suites
- Refactor order and order-items list endpoints (including MCP tools) to support proper PocketBase filter and sort params
- Fix pagination validation for order-items route to clamp page ≥1 and perPage 1-500
- Add redirects in next.config.ts to map underscore collection paths to hyphenated API routes
- Improve buyer tasks page to avoid redundant tab count refetches when switching tabs
- Refactor collection confirm components with editable SKUs and updated accessibility labels
- Add cached admin PocketBase auth to minimize repeated authentication calls
- Add performance testing scripts for dashboard endpoint latency
- Update quotes list route to default to excluding archived counts
- Fix photo strip component text and labels for non-invoice documents
- Refactor sprint page to lazy load supplier/customer data for pricing modal
- Clean up unused imports in test files
- Add full test coverage for all new APIs, services, and components
2026-08-05 23:00:54 +02:00
SJCoetz
d79c433704 fix(quotes): import QuoteItem + return real array from dedup branch
Production deploy failed the TypeScript type-check (next build exited 1)
because commit 2acfd2d changed CreateQuoteFromEmailResult.items from
'number' to 'QuoteItem[]' without updating:

  1. The type import — QuoteItem was never added to the import from
     @/lib/types (line 6 only brought in Quote, Customer, Company).

  2. The dedup branch (line 1060-1076) — still passed itemsCount: number
     where the new shape requires QuoteItem[]. Now fetches the real rows
     via getFullList and sets items_count = items.length for back-compat.

The build log shows the error was visible right at 'Running TypeScript ...'
but the deployment platform's log scraper cut off the actual stderr,
making it look like an opaque DeploymentException. Reproduced locally
with 'npm run build' to confirm both errors.

Build now passes (no next build / tsc failures). All 1392 tests pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-05 16:18:31 +02:00
SJCoetz
ba1f916102 feat(orders): show From + Subject in review modal Source of truth header
The Source of truth panel previously only showed the email subject and
body inside a collapsed-by-default toggle. Operators couldn't see who
sent the mail or what the subject was without expanding the body.

This change adds a persistent header above the collapsible body with
two always-visible lines:

  From:     jane@acme.test    (AtSign icon)
  Subject:  RFQ for 10x bolts  (Mail icon)

Sender resolution chain (in getOrderReviewData):

  1. order.email_sender  — n8n ingest snapshot of the actual From:
                           on the inbound RFQ (best signal)
  2. quote.email_sender  — covers pre-snapshot legacy orders
  3. customer.email      — last-resort fallback
  4. ''                  — renders as '(unknown sender)' placeholder

Subject already lived on the same record; the header just promotes it
out of the collapsed body so it's visible without expanding. The
existing '(no subject)' / '(no body)' placeholder pattern is matched
with a new '(unknown sender)' placeholder.

Tests: 7 new (3 modal header, 4 service sender fallback chain). 101
passing total.

Co-authored-by: Orca <help@stably.ai>
2026-08-05 16:09:53 +02:00
SJCoetz
7f1603d9b0 test(mcp): cover order_items.update + quotes.update regenerate_pdf
- order_items.update happy path: patches cost_price + qty_invoiced
  + supplier_invoice_number, verifies the whitelist strips nothing
  and the row is written
- order_items.update forbidden: system-controlled fields (order,
  purchase_order, quote_item, id) are rejected
- quotes.update regenerate_pdf:true: patch is saved first, then
  the PDF endpoint is called with the freshly-persisted letterhead,
  and the response includes both the updated quote and the new PDF
  attachment metadata
- tools/list test count: 77 (was 76)

All 1385 tests pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-05 15:52:30 +02:00
SJCoetz
106af81934 feat(mcp): order_items.update for invoice reconciliation + quotes.update regenerate_pdf
Two new capabilities, both requested by the agent for the
collected-vs-invoice reconciliation workflow:

1. order_items.update — patch fields on an order_item for invoice
   reconciliation. Lets the agent compare what the supplier invoiced
   (qty_invoiced + supplier_invoice_number + cost_price) against what
   was ordered (quantity) and what was collected (qty_collected),
   then write the differences. Whitelist mirrors the quote_items.update
   pattern:

     cost_price, selling_price, quantity, markup, markup_percent,
     notes, qty_processed/assigned/collected/verified/stocked/picked/
     loaded/delivered/invoiced/cancelled, supplier_invoice_number,
     customer_invoice_number, collection_date, collected_date,
     verified_date, delivered_date, invoiced_date

   System-controlled fields (id, order, purchase_order, quote_item,
   product, created, updated) are rejected with forbidden_field so
   the agent can never accidentally reassign an item to a different
   order or PO.

2. quotes.update with regenerate_pdf:true — the agent can now
   switch letterhead (or any other header field) AND re-render the
   PDF in a single call. The patch is saved first, then the existing
   POST /api/v1/quotes/{id}/pdf route is called using the freshly-
   persisted letterhead, so the response always matches the record.
   Useful for: 'switch this quote to ISHERWOOD and send me the new
   PDF'. Without the flag, the existing 2-step workflow still works
   (quotes.update, then quotes.get_pdf).

All 1385 tests pass (was 1382; +3: regenerate_pdf happy path,
order_items.update happy path, order_items.update forbidden field).

Co-authored-by: Orca <help@stably.ai>
2026-08-05 15:52:30 +02:00
SJCoetz
f76b235e9a test(mcp): cover quotes.get_pdf, list_attachments, and the two new order attachment tools
- quotes.list_attachments: proxies to GET /api/v1/quotes/{id}/attachments
- quotes.get_pdf: proxies to /api/v1/quotes/{id}/pdf/base64 (with optional
  letterhead + regenerate query params)
- orders.add_attachment: posts multipart to /api/v1/orders/{id}/attachments/upload
- orders.list_attachments: proxies to /api/v1/orders/{id}/matched-attachments

All four tests use a stubbed global fetch (restored in finally) so
the MCP route's internal HTTP calls are deterministic and don't hit
the real server. Updated the tools/list test to include the four new
tools (76 total, was 72).

All 1382 tests pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-05 11:51:23 +02:00
SJCoetz
b3344f9f47 feat(mcp): quote PDF retrieval + order/quote attachment tools
Closes the four gaps the agent flagged for the email→quote→PDF→send
workflow:

NEW REST ROUTES
- GET  /api/v1/quotes/[id]/pdf/base64  — auto-renders the quote PDF
  (idempotent against an existing pdf_generated_at) and returns it as
  { pdf: <base64>, attachment_id, filename, size, content_type,
  letterhead }. 422 on placeholder customer / unpriced items. Used by
  the new quotes.get_pdf MCP tool to give MCP clients a way to
  download the rendered PDF — the streaming /api/v1/quotes/[id]/pdf
  endpoint is still available for the WebUI's iframe.

- POST /api/v1/orders/[id]/attachments  — uploads a file to the
  order's MATCHED QUOTE. PB has no order_attachments collection;
  orders share the quote_attachments table via their matched quote.
  201 returns the new attachment + matched_quote_id so the agent can
  confirm where the file landed.

NEW MCP TOOLS (catalog now 76, was 72)
- quotes.list_attachments   — list all attachments on a quote
  (generated PDF + original RFQ email attachments + operator uploads)
- quotes.get_pdf             — auto-render + return the PDF binary as
  base64 so the agent can save/forward/email it
- orders.add_attachment      — upload to an order (proxy to the new
  order upload route; multipart form)
- orders.list_attachments    — list attachments on an order (proxies
  the existing /api/v1/orders/[id]/matched-attachments route, which
  returns the matched quote's attachments)

The 'upload to a PDF' workflow is now: attachments.upload_for_quote
(or orders.add_attachment) → quotes.list_attachments to see what's
there (including the generated PDF) → quotes.get_pdf to download
the PDF → quotes.send_email with selectedAttachmentIds to ship it all.

WHY the existing 'attachments.upload_for_quote' was not enough:
the agent previously had no way to retrieve the rendered PDF binary
or to attach files to orders. Now it has both. The order upload goes
via the matched quote because that's the single attachment table in PB.

All 1382 tests pass (was 1378; +4 for the new tools).

Co-authored-by: Orca <help@stably.ai>
2026-08-05 11:51:23 +02:00
SJCoetz
0ac05b847b test(mcp): cover quotes.update + create_from_email unit field
- quotes.update: happy path with whitelisted fields, forbidden_field
  rejection for system-controlled fields (status/customer/company/
  quote_number/id), empty-patch rejection, missing-id rejection
- create_from_email: unit field now preserved end-to-end, result.items
  returns the actual QuoteItem array (not just a count)

Also updates the existing tools/list test (now 72 tools, was 71) and
the create_from_email mock in route.test.ts to use the new
items/items_count shape so it matches the type.

All 1379 tests pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-05 11:39:16 +02:00
SJCoetz
2acfd2d346 fix(mcp): add quotes.update + preserve unit in create_from_email
Closes the two real gaps from the agent's gap analysis (2026-08-05):

1. **quotes.update MCP tool** — was missing entirely. The quote header
   has fields (company_letterhead, quote_date, quote_reference, etc.)
   that couldn't be patched via MCP, so the agent had to pass
   letterhead at PDF-render time and couldn't persist it on the record.
   Now exposed with a strict field whitelist mirroring the
   quote_items whitelist pattern: any field outside the allowed set
   (status, customer, company, quote_number, id, created, updated, …)
   errors with forbidden_field rather than silently writing to PB.

   New catalog entry + dispatch handler in src/app/api/mcp/route.ts.
   Whitelist constant QUOTE_PATCH_FIELDS colocated with the existing
   QUOTE_ITEM_PATCH_FIELDS for reviewer discoverability.

2. **create_from_email now preserves the unit field** — extracted_items
   from the AI's RFQ parsing carries {description, quantity, unit,
   notes} but the create loop was silently dropping unit. Also the
   service returned items: <count> which made the agent believe no
   items were created when in fact stub rows existed. Now returns
   the actual QuoteItem array (with a back-compat items_count field)
   and the unit value lands on each row.

The agent's third claim (PB admin auth unavailable) is a misdiagnosis
— WFDASH uses its own AGENT_API_KEY and all writes go through the
Next.js admin client. No code change needed for that.

All 1379 tests pass. quote_items.update path unaffected. The
quotes.update path mirrors the same pattern: whitelist + reject empty
patch + call pb.collection.update.

Co-authored-by: Orca <help@stably.ai>
2026-08-05 11:39:16 +02:00
SJCoetz
c41908f4b7 feat(quote-items): CRUD via REST + MCP for AI auto-fill agents
Closes architectural gap #1 from the Giellie skill (the operator's AI
agent could ingest quotes via /api/mcp but had no way to enumerate,
add, or patch the resulting line items - every auto-price flow had to
stop and ask a human for the item IDs).

Adds:
  - GET  /api/v1/quote_items        (list w/ filter, sort, expand)
  - POST /api/v1/quote_items        (create on existing quote)
  - GET  /api/v1/quote_items/[id]   (fetch one)
  - PATCH /api/v1/quote_items/[id]  (whitelisted patch)
  - quote_items.list  MCP tool
  - quote_items.get   MCP tool
  - quote_items.create MCP tool
  - quote_items.update MCP tool

Patch whitelist on update is identical to bulk_update_quote_items:
  cost_price, selling_price, description, sku, unit, supplier, markup,
  pricing_source, pricing_notes, matched_price_list_id, user_edited
Everything else (id, quote, created, updated, quantity, is_processed)
returns 400 / MCP error with the allow-list echoed back so the agent
can self-correct.

quote_items.update does NOT enforce the already_priced skip - that's
the safety-net for bulk_update_quote_items. Single-row patches are
explicit writes.

Newly created rows have is_processed=false forced server-side; Giellie
still cannot flip the flag (architectural gap #2 unchanged - that's a
UI gate by design).

Also: removed "JEI" from quotes.company_letterhead select values on
the live PB - valid values are now ["CNL", "ISHERWOOD"]. Use the
uppercase form when setting this field.

Giellie skill doc refreshed: tool count 69 to 73, new "quote_items
CRUD" subsection, three new REST rows, architectural gap #1 marked
RESOLVED, hard rule #1 updated to cover the new endpoint, new worked
example for "add a missing line item + price it", change-log entry.

Tests: 82 passing across the three touched files (was 63 before).
Type-check: zero new errors (pre-existing 29 in
orders-service-review.test.ts unchanged).

Deployment: pending operator rebuild + redeploy. Until then
POST /api/v1/quote_items returns 404 and the new tools don't appear
in tools/list.

Co-authored-by: Orca <help@stably.ai>
2026-08-05 02:40:09 +02:00
SJCoetz
fd07b514ab fix(mcp): handle initialize/notifications/initialized/ping handshake
WFDASH /api/mcp previously only handled tools/list and tools/call,
which is fine for our internal curl-based testing but broke every
spec-compliant MCP client (Hermes, Claude Desktop, Cursor, mcp-cli).

The MCP protocol requires a three-step handshake before tools/list:
  1. client → server: initialize
  2. server → client: result with protocolVersion, capabilities, serverInfo
  3. client → server: notifications/initialized (notification, no response)

Before this fix, step 1 got HTTP 404 with error.code -32601, which
MCP clients interpret as 'this isn't an MCP server' and terminate
the session. Symptom: configured servers show 'CONFIGURED' in the
Hermes WebUI but '0 tools', with the runtime logging
'unhandled errors in a TaskGroup ... Session terminated'.

Three new handlers, each with the right response shape:

  initialize          → 200 + plain result {protocolVersion, capabilities, serverInfo}
  notifications/initialized → 204 + empty body (notification, no envelope)
  ping                → 200 + result {}

Critical: the initialize response uses a PLAIN object for result,
not the content/text envelope that our jsonRpcOk helper wraps
tools/list and tools/call results in. Using jsonRpcOk here would
have left the handshake broken in a subtler way.

Four new Vitest cases:
  - initialize returns server info (regression: 2026-08-04)
  - initialize echoes client-provided protocolVersion (forward compat)
  - notifications/initialized returns 204
  - ping returns {}

Bug report with full timeline + lessons: see
docs/bugs/2026-08-04-mcp-initialize-handshake-missing.md
(same commit series; pushed separately as the second commit).

All 46 tests pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-05 01:53:02 +02:00
SJCoetz
ff1709c2da fix(mcp): implement tools.discovery handler returning flat tool catalog
The tools.discovery tool was declared in the catalog (line 1300) but no
tools/call dispatch branch existed for it — every call fell through to
'Unknown tool: tools.discovery'. Functionality was reachable only via
the parallel GET /api/mcp endpoint, which the JSON-RPC-only MCP clients
in n8n couldn't use.

Add a real handler that returns the same `tools` array as tools/list,
wrapped in the standard JSON-RPC content envelope. Mirrors GET /api/mcp
for JSON-RPC-only clients.

Also add a Vitest case that asserts the catalog shape (array of tools,
each with name+description+inputSchema, and tools.discovery in the list).

Deployment note: this fix is in source; the live apphub.co.za server
runs a built bundle and will keep returning 'Unknown tool' until rebuilt.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 22:47:50 +02:00
SJCoetz
e132319910 fix(orders,quotes): null-safe sort comparator in archive functions
The archive sort comparator in both getOrdersArchiveData and
getQuotesArchiveData was:

  if (av === undefined) return 1;
  if (bv === undefined) return -1;
  return (av > bv ? 1 : -1) * sortDir;

PocketBase returns `null` (not `undefined`) for unset fields
like `updated`, `email_body`, etc. The strict equality check
missed nulls, and the `av > bv` comparison where one side is
null fails the production tsc check (TS strict mode rejects
`null > string`).

Production build failed with:

  ./src/lib/server/orders-service.ts:687:13
  Type error: 'av' is possibly 'null'.

Fix: use `== null` (which matches both null and undefined),
and use explicit > / < comparisons that return 0 on equality
rather than a fragile ternary that falls through.

Also fixed in the matching function in quotes-service.ts — the
same sort comparator was used in getQuotesArchiveData and would
fail the same way.

All 1331 tests pass; npm run build completes cleanly.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 20:36:50 +02:00
SJCoetz
49367558f2 ui(sidebar): rename Hermes nav entry to Giellie
The webview shortcut in the "Other" sidebar group now displays as
"Giellie" instead of "Hermes". Only the visible label changes — the
underlying /webview?src=hermes URL parameter and the ALLOWED-map
key in src/app/(app)/webview/page.tsx are untouched, since those
are internal identifiers (the URL key is what looks up the embeddable
iframe in the ALLOWED whitelist, not a user-facing string).

If you want the internal key renamed too, that's a follow-up that
needs to update both the sidebar link and the ALLOWED map in the
webview route in the same commit.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 20:29:34 +02:00
SJCoetz
3ea7c9c189 feat(quotes): move completed+all to dedicated /quotes/archive page
Parallel to the orders archive treatment. On the live PB the
'Completed' tab on /quotes held 7,849 of 8,466 quotes (93%) and
the 'All' tab was 8,454. Same shape as orders: a 4k-id IN clause
blowing past PB's filter cap, with 'Page 1 of 392' on the tab
that operators didn't actually use for active work.

This commit moves both buckets to a dedicated /quotes/archive
page so:
  - Main /quotes is fast (active workflow: new, claimed,
    pending_approval, cancelled, delivery_note, email_failed,
    problem, templates = 542 quotes vs 8,466)
  - Archive can be honest about pagination
  - The badge counts on the main page stop being dominated by
    'Completed (7,849)'

# Service layer

- getQuotesArchiveData(params) in src/lib/server/quotes-service.ts
  - view: 'completed' (default, 7,849) or 'all' (8,466)
  - Strategy: one getFullList on quotes (fields: id,status) to
    populate the matching set AND the header counts in a single
    walk, chunk by 100 ids (PB's URL/filter cap is between
    4.5-6.7 KB), fire parallel getFullList queries on quotes
    with deep expand, sort + paginate in memory
  - Search hits quote_number, quote_reference, rfq_number,
    company, customer

- /api/v1/quotes/archive thin route: page, perPage, search,
  sort, view

# Page

- /quotes/archive/page.tsx: card list with header counts
  (completed / all badges), view toggle (Completed | All),
  search input, pagination footer. Click a quote to open
  /quotes/[id] in detail.

# Main /quotes updates

- Completed + All removed from the tab strip
- Counts on the main page now exclude completed + all
- 'Archive' button in the page header takes the operator to
  /quotes/archive
- Safety useEffect: if activeTab is completed/all (e.g.
  stale URL or local state), reset to 'new'

# Tests

4 new tests in quotes-service.test.ts:
  - Default 'completed' view returns only completed quotes,
    counts header includes both
  - 'all' view returns every counted-status quote
  - Search by quote_number and quote_reference
  - Empty result when no quotes match

# Also: webview tweaks by another agent

- /webview?src=hermes label in sidebar
- Hermes URL whitelist updated
- Some header text removed (the probe status remains)

Full suite: 1331/1331 pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 20:25:13 +02:00
SJCoetz
3664eef898 feat(po): resend purchase order from sent / mail_failed / sending statuses
Work by another agent on the PO send flow. Adds a 'Resend' CTA
on the order detail page for POs that were already sent
(operator wants to send another copy to the supplier), plus
acceptance of the same flow from the modal. Includes:

- purchase-orders-service: accept 'sent' as a resend-from state
  (in addition to 'draft' and 'mail_failed')
- send-po-modal: title flips to 'Resend Purchase Order ...' when
  the PO was previously sent; 'Send' button becomes 'Resend'
- send-po-modal.test: covers the resend path
- orders/[id]/page: shows Resend button in the same sendable
  state group as Send (was draft / mail_failed, now also 'sent')
- purchase-orders pdf route: updates docstring to reflect that
  status is the outbound-email pipeline's responsibility
- stock-purchases pdf route: download URL uses file proxy for
  admin-auth compatibility

Co-authored-by: Orca <help@stably.ai>
2026-08-04 20:05:52 +02:00
SJCoetz
d33bb41a59 feat(orders): move delivered+cancelled to dedicated /orders/archive page
The 'Delivered' tab on /orders was broken \u2014 4,326 of 4,514 orders
(96%) have at least one delivered item. The old tab tried to
build a WHERE id IN (...) filter with 4,326 ids (~120 KB),
blowing past PB's ~4 KB filter cap and 400ing. This commit
moves historical orders to a dedicated page so:
  - The main /orders view is fast (22-28 active orders, not 4.5k
    historical)
  - The archive can be honest about its pagination ('Page 1 of
    217' is expected when looking for something from last month)
  - The badge counts on the main page stop being dominated by
    'Delivered (4,326)' / 'Cancelled (111)'

# Measured against the live PB

  /api/v1/orders/archive?page=1&perPage=2 \u2014 15.2s cold, 6.5 KB
  response. The 15s is the order_items.getFullList over 13,256
  items (the bottleneck; PB paginates over many round-trips).
  Per-row payload is the standard 5-6 KB for orders with deep
  expand. Subsequent pages within the same minute would be much
  faster since PB caches the order_items query.

# Service layer

- getOrdersArchiveData(params) in src/lib/server/orders-service.ts
  - Returns paginated list of orders with \u22651 item in
    (delivered, cancelled) status, plus per-status distinct
    counts for the header totals
  - Strategy: getFullList on order_items (ids + status only),
    dedupe + per-status counts in one pass, chunk the order ids
    by 100 (PB's URL/filter cap is between 4.5-6.7 KB) and fire
    parallel getFullList queries on orders with deep expand
  - Search hits order_number, company, customer, contact_name
  - Sort defaults to -created, override via the sort param

- /api/v1/orders/archive thin route: page, perPage, search, sort
  (no tab, no nocache \u2014 archive is one bucket, not a tab split)

# Page

- /orders/archive/page.tsx: card list with header counts
  (delivered / cancelled badges), search input, pagination
  footer. Click an order to open /orders/[id] in detail.

# Main /orders updates

- Delivered + Cancelled removed from the tab strip (passed
  tabKeys=['new','processing','collection_pool','collected'] to
  ItemStatusTabs)
- Counts on the main page now exclude delivered + cancelled
- 'Archive' button in the page header takes the operator to
  /orders/archive
- Safety useEffect: if activeTab is delivered/cancelled (e.g.
  stale URL or local state), reset to 'new'

# Tests

4 new tests in orders-service.test.ts:
  - Returns orders with \u22651 delivered/cancelled item, plus counts
  - Dedupe: one order with multiple matching items counts as 1
  - Search by order_number and contact_name
  - Empty result when no orders match

Full suite: 1321/1321 pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 19:58:43 +02:00
SJCoetz
292cf2468e fix(orders): remove broken fields param + show contact_name + REP label
# Regression: orders/quotes list lost customer/company/rep data

Last commit added a `fields` parameter to the orders and quotes
list queries to trim the wire payload. Measured on a stale test
result, looked like a 16x win. Actual: PB 0.26's `fields`
parameter is a HARD ALLOWLIST of MAIN record columns only \u2014
specifying it makes PB drop the entire `expand` payload from
the response. Result: customer, company, rep, quote names
disappeared from every order/quote card.

Verified against the live PB:
  - With `fields`: expand is dropped, just relation IDs returned
  - Without `fields`: expand works, full records (55-57 KB for
    20 rows with deep expand)

Fix: remove the `fields` parameter from both list queries. The
slim-payload intent has to be paid at the schema level (cap the
unbounded text columns) rather than via PB query params.

The earlier '12x smaller' / '16x smaller' benchmarks were
measurements of the BROKEN response, not the working one. Real
wire sizes are unchanged from before the perf work \u2014 but the
other wins (server-side tab filter, combined status counts,
targeted users fetch, 60s counts cache) all still apply.

# Bonus: show contact_name on the order card

~76 of ~4.5k orders have `contact_name` set (the free-text
person the order is for, captured during email-intake when the
customer record is just the company). Added to the OrderCard
header between customer and rep, with a docstring explaining
the distinction from the customer relation and email_sender.

Added contact_name to the Order type and pinned the regression
with a test that asserts the orders list query does NOT pass
`fields` (so a future 'let's slim the payload' attempt
doesn't reintroduce the bug).

# REP label

The rep column on the order card now reads 'REP' (uppercase)
instead of 'rep' (lowercase). All 1312 tests pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 19:27:02 +02:00
SJCoetz
db1e7d6f76 perf(quotes): server-side tab filter, slim expand, combined counts + bonus bugfix
Same shape as the orders refactor \u2014 applied to the quotes page,
with a fix for a long-standing tab-count bug along the way.

# Measured against the live PB (8,466 quotes, 4,514 orders, 25,612 items)

Before:
  - 22 parallel per-status getList(1, 1) queries for the badge
    counts: 2.6s wall time (no quotes.status index)
  - 64 KB JSON response for 20 quotes with full deep-expand
    (45+ fields per quote, including unbounded email_body)
  - Page footer shows 'Page 1 of N' where N is the global count
    \u2014 'Completed' tab had 7,849 quotes = 'Page 1 of 393'

After (no PB index, just code):
  - 1 combined counts query: 138ms (19x faster)
  - 5.5 KB JSON response (12x smaller)
  - Server-side tab filter: page 1 of N reflects the tab's set
  - Cancelled tab badge now correctly counts rejected+cancelled

# Server-side read model

- getQuotesDashboardData in src/lib/server/quotes-service.ts
  - tab-scoped list + global counts in one round-trip
  - tab param drives a server-side filter (status IN (...) for
    workflow tabs, relation filter for delivery_note, is_template
    for templates, excludeTemplate for 'all')
  - pagination reflects the active tab's matching set, not the
    global ~8.5k quote count

- getQuoteStatusTabCounts: one combined getFullList with all
  17 counted statuses ORed (fields: 'status'), deduped in memory.
  Replaces 22 separate per-status scans. Cached 60s on the server
  with bypassCache option for future realtime refetches.

- /api/v1/quotes/list thin route: validates tab against
  QUOTE_TAB_ORDER, threads tab + nocache params to the service.

# Slim wire payload

- fields param on the orders list: just the columns the page reads
  + per-expand limits (quote.quote_number doesn't need
  email_body, company.company doesn't need its address field, etc.)
- Dropped the customer.company 3-level expand (the page never read
  expand.customer.expand.company \u2014 only expand.company.company,
  which is a direct relation from quote)
- searchQuotesWithItems: same fields added, with
  fetchQuoteItemsForQuotes now accepting fields

# Bonus bug: 'Cancelled' tab badge was always empty

The old getQuoteStatusCounts mapped both 'cancelled' AND 'rejected'
to the 'completed' count, so the page's 'Cancelled' tab badge
showed 0 even when 60+ rejected quotes existed. The page's
tabFilters separately grouped them under 'cancelled', so a quote
that was rejected showed up in the list but not the count.

The new QUOTE_TAB_STATUSES in the service layer is the canonical
mapping (cancelled absorbs both statuses). Page constants and
service constants now derive from the same source \u2014 no more drift.

# Index migration

scripts/migrations/2026-08-04-add-quotes-status-index.ts. Idempotent.
The live PB has no quotes.status index today (verified by hitting
/api/collections/quotes). With the index, the combined counts
query drops from 138ms to sub-10ms on the live instance.

# Tests

6 new tests in quotes-service.test.ts:
  - QUOTE_TAB_STATUSES contract (cancelled absorbs rejected,
    no empty status lists unless special-cased)
  - getQuoteStatusTabCounts buckets correctly into tabs
  - Cache hit returns the same counts on second call
  - bypassCache: true sees new state
  - getQuotesDashboardData end-to-end: tab-scoped items +
    global counts
  - Regression guard for the cancelled/rejected bug

Mock infrastructure upgrade: the quotes-service mock's where
function is now a proper recursive-descent filter parser (handles
nested || inside parens, empty quoted values). getList mock now
returns totalPages.

Full suite: 1312/1312 pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 19:01:31 +02:00
SJCoetz
720f01e5b6 perf(orders): server-side tab filter, slim expand payload, single combined count query
Three rounds of fixes for the /orders page:

#1 Correctness \u2014 server-side tab filter
- Add `tab` query param to /api/v1/orders/list; the route validates
  it against TAB_GROUP_ORDER and threads it to getOrdersDashboardData.
- listOrdersWithItems now resolves order ids for the tab via
  getOrderIdsForTabGroup (using the existing tabGroupFilter helper),
  then fetches just those orders. The footer pagination reflects
  the matching set ("Page 1 of N"), not the global 4520-order
  count ("Page 1 of 226"). The "Processing (4)" badge now
  matches what page 1 actually shows.
- Client: fetchOrders depends on activeTab, so switching tabs
  triggers a fresh server-side query. The redundant visibleOrders
  client filter is removed. The empty state now nudges the operator
  to busy tabs ("Busy tabs: New (12) \u00b7 Delivered (4)").

#2 Perf \u2014 combined counts + targeted users + slim deep expand
- getOrderItemStatusTabCounts collapses 6 parallel per-tab
  getFullList calls into ONE combined query, with batch: 5000.
  6 filter scans \u2192 1 scan; ~9x fewer internal round-trips.
  Bumped cache TTL 30s \u2192 60s.
- Replaced users.getFullList with fetchRepUsersForOrders \u2014 only
  fetches the user ids the loaded orders actually reference.
- Dropped potential_quote from the deep expand (list view only
  checks the field's existence).
- Added a migration script for the order_items.item_status index
  (scripts/migrations/2026-08-04-...). Idempotent: the live PB
  already has the index per the schema export, so the script
  no-ops on most installs; documented as the recommended manual
  step in case an older instance is missing it.

#3 Perf \u2014 wire-payload limits on deep expand
- The quotes collection has unbounded text fields (email_body,
  email_message). Without limiting, the orders deep-expand was
  dragging the full email body of every linked quote into the
  list response \u2014 20 orders with deep expand = 1-5 MB JSON.
- The orders list now passes a `fields` param with the
  `expandField.subfield` syntax PB supports: only
  `quote.quote_number`, `company.company`, `customer.customer`,
  `customer.rep.{id,name,email}` come back, not the full records.
- The items query likewise limits fields to the 8 columns the list
  view + search predicate actually read; the supplier expand (not
  rendered per-line) is dropped.

Tests: 22 new tests in orders-service.test.ts (tab filter, cache
bypass, combined-query call count, pagination honesty, field-list
contract). Full suite: 1306/1306 pass. The mock's where helper was
upgraded to support || and != / =~ / !~ operators, and the
getFullList mock now honours the filter arg.

Realtime: debounce bumped 300ms \u2192 1000ms, and the realtime path
passes nocache=1 so the 30/60s tab-counts cache is bypassed on
changes the operator just made.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 18:17:59 +02:00
SJCoetz
f819478bc0 feat(order-review): edit item description, show email body, fix duplicate key
Three review-modal polish items rolled up:

1. Persisted line items now expose a description input in edit mode
   (mirroring the existing qty / selling inputs). The save route +
   the orders service's `updateOrderItemsPrices` accept the new
   `description` field and write `description` + `po_description`
   together (rejecting a blank description per row, with a
   per-row failure entry so the operator can retry just those).

2. The source-of-truth panel now ALWAYS renders the email body, not
   only when there are no attachments. The body is collapsed by
   default and capped at `max-h-40` so the email stays a secondary
   audit block instead of pushing the operator's real work
   (line items + attachments) down the page. The toggle button is
   unchanged.

3. The chip strip and file list inside the source-of-truth panel
   were using `key={a.id}`. `orderAttachementsToQuotes` synthesizes
   every attachment with `id: order.id` (PB file URLs need
   `/files/{collectionId}/{recordId}/{filename}`), so a multi-file
   order was throwing 'Encountered two children with the same key'.
   Switched to `key={a.filename}` — unique per file in the
   multi-file field, leaves the file URL untouched.

The Order type grew `email_subject`, `email_sender`,
`email_body`, and `email_message_id`. These columns exist in the
live PB (the local `pb_schema-2.json` snapshot is reference-only
per AGENTS.md, so the drift is expected). `getOrderReviewData`
prefers the order's own `email_body` and falls back to the
related `quote.email_body` for legacy orders that pre-date the
snapshot columns — quoting the operator's outbound is better than
showing '(no body)'.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 08:51:22 +02:00
SJCoetz
69175e493d feat(orders): show resolved sales rep name on order list and sprint
The order list and order sprint pages were rendering the rep column
with a raw PocketBase record id, which the operator could not
recognize. The data layer now resolves the rep through the user's
name:

- New `resolveRepDisplayName` helper (`src/lib/order-rep.ts`) takes
  the customer record's `expand.rep`, the `customer.rep` relation
  id, the legacy `orders.rep` text snapshot, and an admin-resolved
  user map, and returns a name (or empty when only an unresolved PB
  id is present).
- The orders service now fetches the user list alongside the order
  page/counts query and resolves the rep on the way out, so the
  client receives a `repName` per row. New endpoints
  `/api/v1/orders/list` and `/api/v1/orders/[id]/review` expose
  the read model; the page and sprint calls go through them.
- The list card and the sprint table + mobile card render the
  resolved name. An opaque PB id is never displayed.

Migrates `/orders` off `pb-helpers.ts` per the data-layer
discipline, and adds a shared browser-session helper for
`Authorization: Bearer <PB token>` validation in route handlers
that serve the dashboard UI (vs. the agent API).

Co-authored-by: Orca <help@stably.ai>
2026-08-04 08:50:54 +02:00
SJCoetz
b66e1b6b6b feat(webview): probe upstream + show status badge in header
The /webview page embeds supplier portals in an iframe. When the
target sets X-Frame-Options: DENY or frame-ancestors 'none' the
browser silently renders a blank iframe with no visible signal
to the operator that the load failed — the page just looks empty
and it's not obvious whether the portal is down or whether the
operator is hitting an embed restriction.

Surface the most common cause up-front:

- Server-side HEAD probe before render: fetches the target URL
  with `redirect: "manual"` and a 5s timeout. The probe bypasses
  browser frame restrictions (it's a server-to-server call) and
  reports the raw HTTP status, including 302 redirects (counted
  as `ok` since suppliers often gate their portals behind a
  login redirect).
- Status badge in the header next to the URL: green dot +
  `up (200)` when reachable, amber dot + `HTTP <status>` for
  non-2xx, amber dot + `unreachable` on network / timeout
  failures. Title attribute carries the full probe detail.
- Banner placeholder inside the iframe container when JS is
  disabled (defensive — the existing iframe is JS-required).

The badge gives the operator an immediate "is this a portal
problem or an embed problem?" answer before they spend time
clicking around inside the iframe.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 01:42:31 +02:00
SJCoetz
5291a044ed feat(collection-confirm): in-app invoice viewer with zoom + mobile layout
The photo-strip chips on the collection-confirm page used to call
`window.open(url, "_blank")` for the supplier invoice, kicking the
operator out to a new tab to verify the invoice against the items
table. That tab switch broke the side-by-side comparison the
operator actually wants to do — look at a line on the invoice,
look at the same line in the table, look back.

Replace that flow with a floating, draggable invoice viewer
that lives on the page:

- New `InvoiceViewer` component renders the PDF in an `<iframe>`
  against the existing `/api/v1/files/order_items/<id>/` route,
  which already serves PDFs with `Content-Disposition: inline`.
- Desktop: floating box anchored to the bottom-right (720×560),
  header is draggable. Position is clamped to the viewport so
  the close button can't be dragged off-screen. State lives in
  the component; not persisted to localStorage.
- Mobile (≤ 640px): full-screen panel (`100vw × 100dvh`,
  border-radius 0). Drag affordance, grip icon, and "Viewing"
  badge are dropped — they're meaningless on touch or when the
  panel fills the screen. Layout flips live on viewport change
  via a small `useMediaQuery` hook.
- Zoom controls: + / − / Reset with discrete levels
  (50 / 75 / 100 / 125 / 150 / 200 / 300%). The % display is
  itself a click-to-reset button. Implemented as
  `transform: scale()` on the iframe with a pre-shrunk CSS box
  (`${100 / zoom}%`) and a `${zoom * 100}%` scrollable wrapper
  so scrollbars appear at higher zoom levels. CSS-resize-only
  does not work for PDF iframes — the browser's native PDF
  viewer caches the initial render size and ignores post-load
  CSS resizes, so the page content never actually re-renders.
  `transform: scale()` works around that across Chrome / Safari
  / Firefox.
- "Open in new tab" header button is preserved as an opt-in
  escape hatch (landscape invoices, full-page viewing).

The PhotoStrip no longer opens a new tab by default. Clicking a
chip calls a page-level `onOpen` handler that toggles the viewer
(open / swap / close); the matching chip is highlighted with
`aria-pressed="true"` + a primary variant so the operator knows
which invoice is open. Clicking the active chip closes the
viewer. The chip falls back to `window.open(...)` only when no
`onOpen` is passed, so the strip stays usable in isolation.

Tests: 126 pass across the collection-confirm suite. New tests
cover viewer open / close (X + Esc), drag math + drag-bail-out
on header buttons, the active-state highlight, swap-on-different
chip, the in-viewer new-tab escape hatch, every zoom level +
clamping + reset, the PDF wrapper / iframe transform math at
multiple zooms, and the desktop ↔ mobile layout flip on a
mocked viewport change.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 01:38:25 +02:00
SJCoetz
db2d43ae84 feat: web view page + sidebar link
Lightweight dashboard view surfaced under the 'Other' sidebar group
for client-facing use cases that need a stripped-down WFDash
surface (e.g. embed iframe, kiosk mode).

Co-authored-by: Orca <help@stably.ai>
2026-08-04 00:58:40 +02:00
SJCoetz
e409e28ff3 feat(order-items): below-22% margin approval workflow
Blocks order-item edits when the operator saves below the 22% markup
threshold and routes them through a manager-approval gate before the
item can be processed.

- new `order-item-margin-approval-service` saves the submitted draft,
  stamps `item_status='approval_needed'`, then fires the configured
  n8n webhook; webhook failure leaves the item blocked and returns
  `webhookFired=false`
- new POST /api/v1/order-items/[id]/request-margin-approval browser
  endpoint gates the same flow with source='order_process' |
  'order_sprint'
- new `MarginApprovalDialog` shared by both order-process and
  order-sprint process surfaces — single source of truth for the
  submit/audit-note flow
- new `approval_needed` / `approval_rejected` item statuses; the
  order-process save path now returns 'blocked' when an item is in
  approval_needed so the operator can't re-edit past the gate
- order-sprint-process-modal now uses the same dialog so the
  below-threshold flow is consistent across both entry points

Tests: 21 new (service + route + sprint modal), 1231 → 1242 passing.

Co-authored-by: Orca <help@stably.ai>
2026-08-04 00:58:33 +02:00
SJCoetz
76947a9711 chore(stock): remove Location from PDF and UI
The single office bin is the only location, so the field is
unused. Strip it from everywhere the operator sees it:

PDF (stock-item-stocktake-document.tsx):
- Drop Location column + gapMaxLocation from styles, header, rows
- Re-balance widths: Name 23% → 28%, Status 12% → 18%
  (the freed space makes Name properly readable again)

Stock list page (src/app/(app)/stock/page.tsx):
- Drop Location TableHead + TableCell
- Drop location state + input + submit-handler field from the
  New stock item modal
- Drop 'location' from the modal JSDoc field list

Stock detail page (src/app/(app)/stock/[id]/page.tsx):
- Drop the MapPin + item.location display in the header
- Drop the now-unused MapPin import from lucide-react

Fulfill-from-stock dialog (src/components/stock/fulfill-from-stock-dialog.tsx):
- Drop location from the search predicate
- Drop location from the placeholder text
- Drop the '· {item.location}' display in the row

Note: the location field stays on the StockItem type and PB
schema for backward compatibility — removing it from the type
would break any code that still references it, and removing it
from the PB schema is a backend migration. The field is just
no longer surfaced anywhere.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 19:34:56 +02:00
SJCoetz
532f1986e4 feat(stocktake-pdf): add Location column, sort by supplier name
PDF:
- Add Location column between Max and Status (4% gap on each side)
- Re-balance widths: Name 28% → 23%, Status 18% → 12% to make room
- Total still 100% (with consistent 4% gaps between data columns)
- Update JSDoc to reflect new column + sort

Service:
- Sort by expanded supplier name (with item name as secondary sort)
- Items without a supplier sort to the end
- PB-side sort becomes 'supplier,name' so the JS comparator does
  fewer swaps on large lists
- PB can't sort by an expanded relation's field, so the JS
  re-sort is what actually produces the printable grouping

Tests:
- Update mock to handle 'expand: supplier' and populate
  expand.supplier.suppliername on each row
- Update mock to handle comma-separated sort lists (PB accepts
  'supplier,name')
- Add a 'sorts items with no supplier to the end' test
- Update existing sort test to cover multi-supplier grouping

Co-authored-by: Orca <help@stably.ai>
2026-08-03 19:21:50 +02:00
SJCoetz
0cecc7208f polish(stocktake-pdf): widen SKU→Name gap so the separation is visible
The previous 2% gapSkUName was too subtle to read as a column
separator — it was being absorbed by the empty space at the end
of the SKU column. Bumping to 4% (and trimming Name from 30%
to 28% to keep the total at 100%) makes the gap clearly visible
regardless of how long the SKU text is.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 19:06:39 +02:00
SJCoetz
b506670dde polish(stocktake-pdf): status anchors right edge, gaps between columns
- Add width: 100% to table/thead/tr so the row actually fills
  the landscape A4 page width (was collapsing to ~70% of page)
- Move Status to the rightmost column with right-aligned bold
  'Out of stock' as the visual anchor operator scans for
- Drop the trailing spacer column
- Re-balance widths: Name gets the lion's share (30%), Supplier
  shrinks (11%), Current/Min/Max narrower (6/5/6%) and pushed
  further right with explicit gap columns
- Small 2% gap between SKU and Name, 4% gaps between the
  other pairs so the eye groups {SKU, Name, Supplier} as 'what'
  and {Current, Min, Max, Status} as 'how much / how urgent'

Co-authored-by: Orca <help@stably.ai>
2026-08-03 19:00:29 +02:00
SJCoetz
b84aefc2e2 feat: unify buyer task flows by supporting both customer orders and stock purchases in mark-ready API and UI, and fix PDF table layout responsiveness. 2026-08-03 18:52:30 +02:00
SJCoetz
21c54ad24e fix(stocktake-pdf): add cell padding so columns have visible gaps
The previous layout had numeric columns (Current, Min, Max —
right-aligned) flush against the Status column (left-aligned).
A row like '100In stock' read as a single mashed string
because there was no whitespace between the right edge of the
Max column and the left edge of the Status column.

Fix: add paddingRight: 8 to the three numeric columns and
paddingLeft: 8 to the Status column. Right-aligned numbers
now end 8pt before the column boundary, and the Status text
starts 8pt inside its column — visible gap between columns,
even with the Status sitting right next to Max.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 18:29:25 +02:00
SJCoetz
a35e715b21 polish(stocktake-pdf): zebra rows, drop Location, Target→Max, prominent Status, wider Name
Visual layout cleanup on the Stocktake PDF:
- Zebra-stripe alternating rows (subtle slate-50 on even rows,
  white on odd) so adjacent rows scan easily.
- Drop the Location column — one less thing to fit on the page,
  and the operator has the /stock detail page for that.
- Rename the Target column header to 'Max' (user-facing naming).
- Move the Status column to the right edge and make it bold +
  colour-coded using STOCK_STATUS_STYLES[status].hex, matching
  the on-screen badge palette.
- Widen the Name column (18%→24%) so full stock-item names read
  in one line for most rows.
- Redistribute remaining widths so the table still totals 100%
  of the landscape A4 page width.

Column widths now: SKU 10 / Name 24 / Supplier 18 / Current 9 /
Min 8 / Max 9 / Status 16 / spacer 6 (= 100%).

Co-authored-by: Orca <help@stably.ai>
2026-08-03 18:23:11 +02:00
SJCoetz
6033aba18d fix(stocktake-pdf): match /stock columns + add button on /stock page
The original Stocktake PDF columns (Name, SKU, Location, Unit,
Current qty, blank Actual, Supplier) didn't match what the
operator sees on /stock. They pointed at the wrong list — they
worked for a blank-column walk-through stocktake form, but the
user wants to print the /stock list as it appears on screen.

This rewrite makes the Stocktake PDF mirror the /stock table
column-for-column:
- SKU, Name, Supplier, Current, Min, Target, Location, Status
- Status derived via getStockStatus + STOCK_STATUS_STYLES so
  it matches the on-screen badge label
- Current qty now renders with the unit suffix (matching the
  on-screen cell)
- Target renders '—' when null/undefined/0, matching /stock

Also:
- Switched to landscape A4 to give 8 columns room (was
  portrait).
- Added a copy of the 'Download Stocktake PDF' button on the
  /stock page next to 'New stock item' — both /stock and
  /stock-orders now expose the same endpoint. Button uses the
  same plain <a target='_blank' rel='noopener'> pattern as
  the existing stock-orders buttons, with aria-hidden on the
  Download icon.
- Added a test on /stock for the new link (href, target,
  rel). 33/33 tests pass.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 18:18:58 +02:00
SJCoetz
b1c0c6030f fix(api): make list-pdf routes browser-accessible
Both new routes — GET /api/v1/stock-purchases/list-pdf and
GET /api/v1/stock-items/stocktake-pdf — were gated on
`assertAgentAuth`, which requires an `Authorization: Bearer
<AGENT_API_KEY>` header. Browser <a target='_blank'> clicks
don't send that header, so the buttons returned 401
'Unauthorized'.

The existing single-PO PDF route at
/api/v1/stock-purchases/[id]/pdf doesn't gate on
`assertAgentAuth` — it relies on the in-app session and uses
the admin PB instance. The two list PDFs are the same shape
(throwing reports, in-app origin, admin-scoped reads) so the
fix is to drop the gate. Auth now matches the single-PO PDF
and the invoicing delivery-note PDFs.

- Removed `assertAgentAuth(req)` from both routes; dropped the
  `agent-auth` import and the unused `req` parameter.
- Updated route JSDoc to describe the new auth contract and
  reference the single-PO PDF route as the precedent.
- Updated both route tests: dropped the 'returns 401 when auth
  is missing' case (no longer applicable) and the
  `AGENT_API_KEY` env-setup boilerplate. Test names updated
  to reflect the new contract — 'no auth required'.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 18:12:38 +02:00
SJCoetz
6bf8310ef6 fix(stock-purchase-send): use DASHBOARD_URL for outcomeUrl (was req.nextUrl.origin)
\`req.nextUrl.origin\` inside the Next.js process resolves to the
container bind address (e.g. \`0.0.0.0:3000\`), which the n8n
container can't reach — the v4 workflow's outcome callback
fails with \`ECONNREFUSED 0.0.0.0:3000\` and the stock PO gets
stuck on \`sending\` because the dashboard never receives the
status-flip callback.

Mirror the customer-PO route: build the callback URL from
\`process.env.DASHBOARD_URL\` (with trailing-slash trim). When
\`DASHBOARD_URL\` is unset the outcomeUrl is empty, and the
workflow's "outcomeUrl missing" branch fires cleanly.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 17:44:38 +02:00
SJCoetz
91d8363380 fix(stock-purchase-send): render auto-PDF in-process instead of HTTP self-call
The send-email route's auto-PDF block did an internal
\`fetch(/api/v1/stock-purchases/[id]/pdf)\` to render a PDF when
the operator hit Send on a stock PO without one. Cloudflare's
loopback filter rejects that self-call with a network-level
error before Next.js sees it, surfacing as 'fetch failed' in the
modal (status rolled to draft, route returned 500 with code
'pdf_failed').

Extract the PDF generation into \`generateStockPurchasePdf\` on
the service layer so the send-email route can render the PDF
in-process. Same pattern as the customer-PO flow's
\`generatePurchaseOrderPdf\`. The route stays a thin shim that
maps \`StockPurchasePdfValidationError\` to 422.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:51:07 +02:00
SJCoetz
86534f738a test(stock-orders): tighten download-button assertions + mark icons decorative
Two review follow-ups from the code-quality reviewer:
- Switch the two new PDF-button tests from getByTestId to
  getByRole('link', { name }) so visible-label regressions fail.
  Add a rel='noopener' assertion so the security contract on
  target='_blank' is locked down.
- Add aria-hidden='true' to both <Download> icons. The visible
  text already supplies each link's accessible name, but marking
  the icon decorative explicitly is more robust to future
  library behavior changes.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:43:59 +02:00
SJCoetz
1b2f4a4f52 feat(stock-orders): wrap cells + add download PDF buttons
Two UX improvements on the /stock-orders list:
- Number + Supplier cells now wrap long text instead of
  clipping. Uses whitespace-normal + break-words + max-w-[200px]
  on the cell, plus a row-level py-3 bump so wrapped cells look
  balanced with single-line rows.
- Two new outline buttons next to 'New Stock Item':
  'Download Stocktake PDF' -> /api/v1/stock-items/stocktake-pdf
  'Download Orders PDF' -> /api/v1/stock-purchases/list-pdf
  Both open the PDF in a new tab via target=_blank; the browser
  handles the download.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:40:24 +02:00
SJCoetz
e025b340b8 fix(api): use SAST date for PDF filenames + tighten list-pdf tests
Two changes:
- Filename dates now use the Africa/Johannesburg timezone rather than
  UTC, so a download generated at 00:30 SAST gets today's date
  (not yesterday's). The renderer call still uses ISO UTC for
  generatedAtIso — that's an audit timestamp, not a human-readable
  date. One 'now' is captured at the top so the two values can't
  drift across a millisecond boundary.
- The 200 tests now assert Content-Disposition (including the
  filename), Cache-Control, the service arguments, and the
  renderer arguments. vi.useFakeTimers pins the clock so the
  filename is deterministic.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:37:12 +02:00
SJCoetz
bbe3e1bd1f feat(api): GET /api/v1/stock-purchases/list-pdf + stocktake-pdf
Two list-report endpoints wired to the new PDF renderers. Both
auth via assertAgentAuth, ignore query params (always all rows),
and return application/pdf with attachment Content-Disposition.
The Stocktake PDF is sourced from the new listStockItemsForStocktake
service helper; the Orders PDF reuses the existing listStockPurchases
with perPage=200.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:29:57 +02:00
SJCoetz
907a7414b4 fix(pdf): repeat table headers on every page in list reports
Move the thead <View> out of the table and onto the page itself
with the @react-pdf/renderer 'fixed' prop, so reports that span
multiple A4 pages still label their columns. Without this, page 2+
of a long stock-orders report or stocktake would show data without
column headers — making the right-hand 'Actual' column on the
stocktake and the value columns on the orders list unreadable.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:23:12 +02:00
SJCoetz
45f1ec6bb7 feat(pdf): list-pdf documents for stock orders + stocktake
Two new @react-pdf/renderer documents backed by renderStockPurchaseListPdf
and renderStockItemStocktakePdf in render.tsx. The Orders PDF mirrors
the on-screen table; the Stocktake PDF adds a blank 'Actual' column
for the operator to fill in during the walk-through. Both inherit
the toString() → Buffer pattern so they run under the same jsdom
test setup as the other PDF renderers.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:13:14 +02:00
SJCoetz
a5567f41cf test(stock-items): assert expand: supplier on stocktake calls
The mock's getFullList is now a vi.fn so the call args can be inspected. Each test asserts expand: 'supplier' was passed, so a regression that drops the expand (e.g. a copy-paste from the dashboard read) fails fast instead of silently shipping rows without supplier names.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:08:03 +02:00
SJCoetz
88678cea49 feat(stock-items): listStockItemsForStocktake service helper
Returns active stock items sorted by name with supplier expanded,
for the new Stocktake PDF download endpoint. Distinct from the
dashboard's low-stock query: stocktake wants every SKU
alphabetically, not the under-stocked ones first.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:04:46 +02:00
SJCoetz
e75f0d6157 fix(stock-purchase-send): stop auto-flipping stock_purchase_items on success
Same operator-flow fix we made for customer POs in 79b9309: sending a
stock PO no longer auto-flips the linked stock_purchase_items from
`collection_pool` to `assigned_to_driver`. Items now stay in
`collection_pool` after the supplier email goes out; the operator
marks them ready-to-collect from the stock-order page only after the
supplier confirms, and that's the action that promotes them to
`assigned_to_driver` (so the driver-app sees them as ready).

Without this, the stock-order "PO Sent" state was invisible — the
items jumped straight to driver-ready the moment the email left,
before any supplier confirmation. Now the PO Sent → Ready to Collect
→ Assign Driver flow is observable end-to-end.

3 new tests, full suite 1210/1210 passing.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 16:04:21 +02:00
SJCoetz
690b8a2c26 fix(po-send): reject sends for POs without a generated PDF
The dashboard's send-email route fires the n8n webhook unconditionally
once pre-send validation passes. If a PO has no generated PDF (legacy
state — `documents` empty + `documents_history: [null]`), n8n tries to
download from PB with an empty filename, gets a 404, and the webhook
returns HTTP 500. The operator sees "Webhook returned HTTP 500. Status
reverted to mail_failed." with no indication of the actual cause.

Add a PDF-existence guard in `sendPurchaseOrderEmail` using the same
`documents` → `documents_history` fallback chain the route uses to
compute `latestFilename`. When both are empty / unusable, return a
`no_pdf` failure that flips the PO to `mail_failed` with a clear
operator-facing message BEFORE the webhook fires.

While here, rename the misleading `code: "no_pdf"` on the line-items
check to `code: "no_line_items"` — the old code name was wrong (it
checked for linked items, not PDFs) and would have collided with the
new `no_pdf` guard.

The new guard also filters null entries out of `documents_history`
before calling `.find()` / `.file` — the legacy `[null]` shape was
making the old route code throw.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 15:47:01 +02:00
SJCoetz
18e1d97b6c test(stock-orders): tighten total-value + edit-reset assertions
The total-value case now locates each cell by its column header so a
regression that swapped Ordered (R) and Received (R) would fail. The
edit-draft case now closes the modal after Edit and asserts
editPurchaseId resets to '', so a regression that leaked the id into
a subsequent 'New' click would fail.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 15:18:39 +02:00
SJCoetz
760f088ec9 test(stock-orders): move page tests to StockOrdersTable + add total-value case
The seven pre-existing assertions on the quick-draft modal and edit
button now exercise the new client component. New case confirms
ordered_value/received_value render in the row. Uses Intl-format
substring assertions because the currency glyph/spacing varies by
ICU version.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 15:13:12 +02:00
SJCoetz
b89a4a7fa3 fix(stock-orders): preserve header nav + sanitize error message
- Header (title, description, Reorder, + New stock order) now
  renders unconditionally, so operators can navigate away even when
  the list query throws.
- Full error is logged server-side via console.error; the user
  sees a generic 'Failed to load stock orders. Please try again.'
  message that doesn't leak PB URLs, admin env var names, or
  filter syntax.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 15:07:46 +02:00
SJCoetz
dedd5013b9 refactor(stock-orders): migrate list page to Server Component
Reads searchParams (status, page), validates both, calls
listStockPurchases via the admin PB, and renders the new
StockOrdersTable client component. Drops the legacy direct-PB
read path per AGENTS.md data-access discipline.

The old page.test.tsx is removed; its assertions are mirrored
in the new StockOrdersTable.test.tsx (next task).

Co-authored-by: Orca <help@stably.ai>
2026-08-03 15:02:59 +02:00
SJCoetz
fcb15a20e2 fix(stock-orders): keyboard a11y on pagination + soft row nav
- Disabled pagination links (Previous at page 1, Next at last page)
  now also set tabIndex=-1 and preventDefault on click, so keyboard
  users can't activate them when at the boundary. aria-disabled +
  pointer-events-none blocked only mouse clicks.
- Row click uses useRouter().push() instead of window.location.href
  for a soft navigation that preserves client state (consistent
  with the original /stock-orders page).

Co-authored-by: Orca <help@stably.ai>
2026-08-03 14:51:41 +02:00
SJCoetz
0c556a0513 feat(stock-orders): extract StockOrdersTable client component
Holds the QuickDraftModal open state, renders status filter tabs as <Link>s to ?status=..., and adds two new columns (Ordered R, Received R) showing per-row aggregates from the service layer.\n\nReplaces <Button asChild><Link/></Button> with <Link className={cn(buttonVariants(...))}> because the project's Button (built on @base-ui/react/button) doesn't support asChild. Visually identical; preserves navigation semantics.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 14:46:50 +02:00
SJCoetz
469b2c0460 fix(api): preserve auth status + guard pagination against NaN
- Catch block now preserves error.status so assertAgentAuth's 401
  surfaces as 401, not 500. Matches sibling /api/v1/stock-purchases
  pattern.
- page/perPage parsing falls back to documented defaults on
  non-numeric or zero input rather than passing NaN to the service.
- Add 2 tests covering the auth-status and pagination boundaries.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 14:38:51 +02:00
SJCoetz
8cb4e9a60c feat(api): GET /api/v1/stock-purchases/list with value aggregation
Thin wrapper around listStockPurchases that validates the status
param against STOCK_PURCHASE_STATUS_VALUES (400 on bad input) and
caps perPage at 200. Mirrors the agent-auth pattern used by the
other v1 list routes.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 14:31:22 +02:00
SJCoetz
92febfb51c feat(stock-purchases): aggregate ordered/received value on list rows
Add ordered_value and received_value to StockPurchaseListRow. Each is
Σ line.{quantity|quantity_received} × line.cost_price, rounded to 2dp.
Replaces countItemsForPurchase with summarizeItemsForPurchase so the
per-row N+1 returns all three numbers in one fetch (no extra round
trip).

Co-authored-by: Orca <help@stably.ai>
2026-08-03 14:24:30 +02:00
SJCoetz
79b93096ec fix(po-send): stop auto-flipping order_items.item_status to collection_pool
Previously, when recordPurchaseOrderSendOutcome received a "success"
outcome from the n8n workflow, it auto-flipped every linked
order_items.item_status from "po_generated" to "collection_pool".

This dropped items off the buyer-tasks PO Sent tab immediately on
send — before the supplier had even confirmed receipt. The operator
had no chance to mark items ready-to-collect manually.

New flow: send mail → items stay "po_generated" and remain visible
in buyer-tasks PO Sent → operator manually marks items ready →
items drop off buyer-tasks.

The back-link sync (purchase_orders.order_item) still runs and now
reads all items with purchase_order = poId regardless of status, so
the array stays accurate as items progress through their lifecycle.

Adds src/lib/server/purchase-orders-service.test.ts with 4 cases:
- success does NOT auto-flip linked items
- success flips PO to sent + stamps email_message_id
- success keeps the PO's order_item back-link in sync
- failure flips PO to mail_failed + stamps error (also no item writes)

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 14:10:34 +02:00
SJCoetz
aea1ab67f3 fix(po-send): push dashboardBaseUrl + outcomeUrl on n8n webhook body
The n8n Code node that posts the SMTP outcome back to the
/api/v1/purchase-orders/[id]/send-email/outcome route couldn't
read env vars at runtime (N8N_BLOCK_ENV_ACCESS_IN_NODE=true in
docker-compose), so it composed the callback URL from fields on
the webhook body. The route never pushed dashboardBaseUrl or
outcomeUrl, so n8n fell back to a relative URL, the request
died, n8n returned HTTP 500, and the route flipped the PO to
mail_failed with a misleading '[webhook] Webhook returned HTTP
500' message.

DASHBOARD_URL is already defined in .env (labelled 'used by n8n
workflows to call back into this app') — the route just never
read it. Now the route pushes both the dashboard base and a
pre-built absolute outcome URL, trimmed of trailing slashes, and
omitted (not empty) when DASHBOARD_URL is unset so the existing
'missing' branch in n8n fires clearly.

A new test file asserts all three cases: with DASHBOARD_URL,
with a trailing slash, and without the env var.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 11:23:40 +02:00
SJCoetz
faaa47a4fe test(buyer-tasks): lock wire shape of mail_failed group in po_draft
The route is a pass-through, but the smoke test guards against a
future refactor silently dropping the new emailError field — the
operator's retry affordance depends on it.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 10:55:10 +02:00
SJCoetz
010bba475c fix(buyer-tasks): pass status + email_error into SendPoModal stub
The SendPoModal renders its 'Resend' label and inline failure
banner from purchaseOrder.status / email_error, but the buyer-tasks
page stub didn't include either field. As a result, the modal
showed 'Send' and an empty banner even when the underlying PO was
mail_failed. Now the stub includes both so the operator sees the
correct affordance.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 10:53:54 +02:00
SJCoetz
8616d5dbef fix(buyer-tasks): add emailError to route test fixture
The BuyerTaskGroup type gained an emailError field in the previous
commit. This pre-existing fixture constructs a BuyerTaskGroup
literal and now needs the field to compile. No behaviour change
in the test — emailError: null matches a clean draft.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 10:52:58 +02:00
SJCoetz
c481cbeb1c feat(buyer-tasks): render mail-failed banner + Resend button
When a card's poStatus is 'mail_failed', the card now renders a
red warning row with the email_error reason and switches the
action button label to 'Resend' with the destructive colour. A
new data-po-status attribute on the button lets tests target the
state without depending on the human-readable label.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 10:51:38 +02:00
SJCoetz
5959d2a1aa fix(buyer-tasks): keep mail_failed POs visible in the PO Draft tab
The po_draft filter previously required po.status === 'draft', so
a failed send (status: 'mail_failed') caused the group to vanish
from buyer-tasks entirely. The only recovery path was the per-PO
Resend button on the order detail page, which is friction. Now
mail_failed groups stay in place so the operator can re-open the
SendPoModal and retry from the same list. po_sent is unchanged— mail_failed must not appear there.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 10:46:32 +02:00
SJCoetz
964b3d51b2 feat(buyer-tasks): surface email_error on buyer task groups
Adds an emailError field on BuyerTaskGroup so the UI can render
the send-pipeline failure reason. The value is truncated to 200
chars at the service boundary to keep the card layout bounded.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 10:31:33 +02:00
SJCoetz
4444842ef5 feat: collection-map updates, todays-stops, quote/approval rework, buyer-tasks, e2e
- Add todays-stops test and component to collection-map
- Expand collection-map sidebar and pin-model
- Rework orders/[id]/process page
- Add quotes/[id]/page and process pages
- Add quotes/approvals/[id] page
- Add buyer-tasks generate-po route
- Add quotes partial-approve and pdf routes
- Add purchase-orders [id]/pdf route
- Add e2e create-flows spec
- Add superpowers plan doc
- Update pb_schema-2.json
- Update form components (company, customer, order, quote, supplier)
- Update UI components (button, command, dialog)
- Add collection-pool test components

Co-authored-by: Orca <help@stably.ai>
2026-08-03 09:33:45 +02:00
SJCoetz
0064555f22 chore(collection-confirm): cleanup nice-to-haves from final review
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 03:04:23 +02:00
SJCoetz
d6af21193c fix(collection-confirm): scope costOverrides to current PO in dialog
Co-authored-by: Orca <help@stably.ai>
2026-08-03 02:48:17 +02:00
SJCoetz
fea67b15ba fix(collection-confirm): hoist onCostChange out of setEdit updater + preserve null rollback
Co-authored-by: Orca <help@stably.ai>
2026-08-03 02:46:28 +02:00
SJCoetz
e2896264f4 fix(collection-confirm): add route validation + server-side actor derivation
Co-authored-by: Orca <help@stably.ai>
2026-08-03 02:35:58 +02:00
SJCoetz
c14d07ecc0 test(collection-confirm): add confirm-invoice-dialog tests
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 02:32:44 +02:00
SJCoetz
dbf02e2511 fix(collection-confirm): restore Book to stock for stock rows + cost guard
Restores the 'Book to stock' action that the page rewrite in f7d3032 dropped from collection-confirm/page.tsx, and routes the cost pencil away from stock rows so the existing cost-edit endpoint (which queries order_items) can't 404 on a stock_purchase_items id.

- New POST /api/v1/collection-confirm/book-stock endpoint + route tests.
- New bookStockRows(rowIds, { actor }) service that mirrors the pre-rewire bookStockLineForRow flow per-row: ledger → cache increment → line update → auto-derive parent send→received.
- PoCard footer now switches on the row mix: stock rows → 'Book to stock'; customer rows → 'Confirm for invoicing'; mixed → both.
- ItemsTable hides the cost pencil when row.source === 'stock' (cost cell stays readable).
- Page-level handleBookStock wired through to the new endpoint with a reload on success.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 02:29:20 +02:00
SJCoetz
1edaf36023 test(collection-confirm): update page tests for PoCard layout
Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:33:31 +02:00
SJCoetz
f7d3032438 feat(collection-confirm): rewire page to use PoCard + remove Adjust Quantity
- Replace inline row rendering (ConfirmCard, QuantityDialog, NoteDialog,
  StockItemPickerDialog) with <PoCard> composition: PhotoStrip +
  ItemsTable + Confirm button.
- Cost edits dispatch POST /api/v1/order-items/{id}/cost with optimistic
  UI + rollback on failure.
- Confirm click opens ConfirmInvoiceDialog and POSTs to
  /api/v1/order-items/confirm with itemIds, invoice, costOverrides, actor.
- Keep AttachDialog + ReturnToPoolDialog component definitions per spec;
  render with open=false (no per-row buttons in PoCard layout).
- Switch load() to /api/v1/collection-confirm via fetch().
- Stock-source Book-to-stock, surplus chip, Return-to-pool, Adjust
  Quantity per-row actions are removed from the page body; PoCard is
  the primary grouping. Tests for those actions will fail and are
  scheduled for task 14.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:25:31 +02:00
SJCoetz
0df6fb1ff2 feat(collection-confirm): add PoCard composing PhotoStrip+ItemsTable
Wraps a single PO group on the collection-confirm review page.
Renders the photo strip + items table + confirm button, with the
PO number and supplier name in the header. The cost edit/read
flow stays inside ItemsTable; the parent owns onCostChange
optimistic updates and the actual confirm mutation.

Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:20:46 +02:00
SJCoetz
4310e4b211 feat(collection-confirm): add ItemsTable with inline cost edit
Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:19:14 +02:00
SJCoetz
afa3876316 feat(collection-confirm): add PhotoStrip component
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:16:09 +02:00
SJCoetz
7360e14c58 refactor(collection-confirm): extract ConfirmInvoiceDialog component
Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:09:37 +02:00
SJCoetz
3f228808ea feat(collection-confirm): add POST /api/v1/order-items/confirm route
Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:03:52 +02:00
SJCoetz
fada6f155f feat(collection-confirm): add POST /api/v1/order-items/[id]/cost route
Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:01:30 +02:00
SJCoetz
e860611980 fix(collection-confirm): log server errors and return generic message to client
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:59:02 +02:00
SJCoetz
bb10f1350b feat(collection-confirm): add GET /api/v1/collection-confirm route
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:51:37 +02:00
SJCoetz
c856db1617 fix(collection-confirm): thread null cost through appendCostNote to preserve audit on null→0
Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:46:50 +02:00
SJCoetz
47eff9a6fe feat(collection-confirm): implement confirmOrderItemsForInvoicing with createBatch
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:40:29 +02:00
SJCoetz
77d2c32df4 fix(collection-confirm): add cost_price to ConfirmRow, rename body to args
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:29:56 +02:00
SJCoetz
2997b8dcba feat(collection-confirm): implement updateOrderItemCost service
Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:23:37 +02:00
SJCoetz
8b6b83583d fix(collection-confirm): use getOrderItemsCollectionName + populate stock supplier
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:17:56 +02:00
SJCoetz
15f6ec638d fix(collection-confirm): make listCollectedItems stock leg fail-soft
Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:12:02 +02:00
SJCoetz
efe10b9474 feat(collection-confirm): add service skeleton with listCollectedItems
Co-authored-by: Orca <help@stably.ai>
2026-08-03 00:08:57 +02:00
SJCoetz
06d8294c77 refactor(collection-confirm): make buildConfirmPatch take options bag with costOverride
Co-authored-by: Orca <help@stably.ai>
2026-08-02 23:59:22 +02:00
SJCoetz
7c807f3c18 fix(collection-confirm): render cost category label correctly
Co-authored-by: Orca <help@stably.ai>
2026-08-02 23:57:06 +02:00
SJCoetz
529e08eb2a fix(collection-confirm): widen NoteEntry.body and dedup attachments within row
Co-authored-by: Orca <help@stably.ai>
2026-08-02 23:52:21 +02:00
SJCoetz
7e1f22f363 feat(collection-confirm): add appendCostNote and dedupeAttachments helpers
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-02 23:48:51 +02:00
SJCoetz
7136623331 feat(orders): expand rep on customers fetch for review modal
The customers getFullList in OrdersReviewModalMount now expands
both 'company' and 'rep'. The Review Order modal's customer
cascade reads selectedCustomer.expand.rep.name to populate the
Rep label and writes it to orders.rep on save.

No other consumer of the customer list reads c.expand.* — the
scout confirmed this is safe.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-07-31 15:31:21 +02:00
SJCoetz
5af04e4b60 test(orders): review modal cascade coverage
Two new tests for the customer -> company/rep cascade:

1. Updates Company and Rep labels when the customer changes
   - renders with customer A (company 'Atlas Corp', rep 'Riya Patel')
   - clicks the customer-search mock (now picks the next non-selected
     customer from the list)
   - asserts the labels flip to B's values and A's are gone

2. Marks the modal dirty after a customer change cascades
   - asserts the Save button is disabled at baseline
   - after customer change, asserts it's enabled (proves the dirty
     check picks up the cascaded company/rep divergence)

Also updates the CustomerSearch mock to compute the next non-selected
customer id from the list (via data-next-id) so cascade tests can
drive it without hardcoding 'cust-new'.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-07-31 15:31:07 +02:00
SJCoetz
f99ab7cf1a feat(orders): cascade company and rep from selected customer in review modal
When the operator changes the customer in the Review Order modal,
the Company and Rep labels now reactively reflect the selected
customer's expand.company.company name and expand.rep.name (with
email fallback). On save, the modal writes the new company relation
id and the new rep display name to the order — so a customer
change actually re-parents the order rather than just changing the
display.

Guards in the save body prevent two PB errors:
- company is skipped when the customer is cleared (orders.company
  is required, sending '' would 400)
- rep is skipped when the new customer has no rep, so existing
  rep values are preserved

The cascade uses useMemo derived from customerId, not a useEffect,
so the label updates in the same render as the dropdown change.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-07-31 15:30:31 +02:00
SJCoetz
d3c3e3908d feat(orders): forward company and rep in review-save route
Destructure company and rep from the request body and forward them
through updateOrderReviewFields' headerPatch. The service layer
(Task 1) already accepts and validates these fields; the route now
just plumbs them.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-07-31 15:29:43 +02:00
SJCoetz
f7b5f3677e feat(orders): persist company and rep from review-modal cascade
Extends updateOrderReviewFields' patch type to accept company
(relation id) and rep (free-text snapshot) in addition to the
existing order_number and customer. The modal cascade writes these
when the operator changes the customer; the service now carries
them through to the PB update.

The order_number collision check is unchanged — it only runs for
order_number changes, so the new fields are unaffected.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-07-31 15:29:10 +02:00
SJCoetz
2cb6491654 feat(stock-orders): show SKU in line table on stock-order detail
Adds a 'SKU' column between Description and Ordered in the lines
table on /stock-orders/[id]. The column reads from
line.expand.stock_item.sku (the relation was already accessible via
the type, but the page was not expanding it on the fetch).

Falls back to an em-dash when expand is missing (e.g. an item whose
stock_item was deleted) so the row never renders an empty cell.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-07-31 14:20:17 +02:00
SJCoetz
e3295e3c13 chore(stock-orders): suppress set-state-in-effect lint on edit-mode seed effect
The seeding useEffect copies line qty/cost into the per-line edit
buffers when the targeted draft loads (or when the target changes).
The setState is intentional — the buffer is mirrored from the parent
draft's authoritative data — and the same suppress pattern is used
in src/app/(app)/collection-confirm/page.tsx and elsewhere.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-07-31 14:07:06 +02:00
SJCoetz
7b3601eab2 test(stock-orders): Edit button row coverage
Asserts the Edit button appears on draft rows only, and that clicking
it opens the modal with the right editPurchaseId. The mock stops
forwarding the click to the row's onClick via the existing
e.stopPropagation() pattern in the implementation.

Co-authored-by: Orca <help@stably.ai>
2026-07-31 14:01:40 +02:00
SJCoetz
1d2499a17a feat(stock-orders): Edit button on draft PO rows
Adds a Pencil-icon ghost button to the trailing cell of every draft
row. Clicking it opens the QuickDraftModal in edit mode for that
purchase, scoped to that draft's lines. e.stopPropagation prevents
the row's detail-page navigation from also firing.

Co-authored-by: Orca <help@stably.ai>
2026-07-31 14:00:03 +02:00
SJCoetz
5e91a5d7c0 test(stock-orders): QuickDraftModal edit-mode coverage
Asserts the modal hides non-targeted drafts, renders qty/cost inputs
per line, PATCHes only changed fields on Save, and that remove still
works in edit mode.

Co-authored-by: Orca <help@stably.ai>
2026-07-31 13:58:05 +02:00