feat(woo): mark an order as already booked outside the integration (#1895)

* feat(woo): mark an order as already booked outside the integration

Orders booked by hand before the store was connected sat under Att
bokfora forever: the only exits were the book and create-invoice routes.

- Migration: manually_booked_at/_by + optional
  manually_booked_journal_entry_id on webshop_orders (informational link,
  no financial freeze; the mark produced no accounting objects).
- POST/DELETE /api/webshop-orders/[id]/mark-booked: mark with optional
  posted-verifikat reference (validated per company), conditional claim
  against concurrent booking/invoicing; unmark is a plain revert.
- book and create-invoice routes refuse marked rows (409
  WEBSHOP_ORDER_MANUALLY_BOOKED) and exclude them in their atomic claims.
- List route: booked/unbooked filters treat a manual mark as a closed
  exit, so marked rows leave the Att bokfora tab and join Bokforda.
- Orders page: row overflow menu with Markera som bokford / Angra
  markering, MarkOrderBookedDialog with a searchable candidate list of
  posted entries near the order date, muted status text linking to the
  referenced verifikat.

Fixes #1879

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

* fix(woo): close skeptic findings on the manual-booked mark

- mark-booked applies the same open-twin gate as book/create-invoice:
  an OPEN legacy feed transaction blocks the mark (409
  WEBSHOP_ORDER_LEGACY_TRANSACTION_OPEN); ignored or booked feed rows
  unlock it, so no open path to a duplicate remains.
- ingest treats manually marked rows as frozen for drift purposes:
  remote financial deltas set remote_changed_after_freeze (same badge as
  booked rows) instead of silently refreshing the row under the user's
  assertion.
- re-marking with a journal_entry_id updates the informational link
  instead of silently dropping it.
- dialog: candidate amount computed from the returned lines (the list
  API does not return total_amount), newest-first ordering, cap hint.

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

* chore(migrations): bump webshop manual-booking migration past freshly merged 20260825120000

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

* fix(woo): resolve PR review findings in one pass

- freeze v3 migration: financial fields are frozen at the DB level while
  a row is manually marked as booked (review finding: the mark's freeze
  lived only in ingest.ts, so any other write path could silently mutate
  a marked row); unmark stays the escape hatch. pg test added.
- pass the active locale to getErrorMessage in the orders page and
  MarkOrderBookedDialog (CodeRabbit: English users got Swedish errors).

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-08-25 14:23:56 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent cd46d936f3
commit 1f9578ca76
20 changed files with 1231 additions and 22 deletions
+8
View File
@@ -1630,6 +1630,14 @@ export const CreateInvoiceFromWebshopOrderSchema = z.object({
customer_id: uuid.optional(),
})
/**
* Mark a webshop order as booked/handled outside the integration, with an
* optional reference to the existing (posted) verifikat that covers it.
*/
export const MarkWebshopOrderBookedSchema = z.object({
journal_entry_id: uuid.optional(),
})
/** {"<payment_method>": {mode:'book', account:'1930'} | {mode:'invoice'}} */
export const WebshopStoreSettingsUpdateSchema = z.object({
platform: WebshopPlatformSchema,
+19
View File
@@ -3880,6 +3880,25 @@ const WEBSHOP_ORDERS: Record<string, StructuredErrorEntry> = {
message_en:
'The order has no customer data. Choose an existing customer to invoice.',
},
WEBSHOP_ORDER_MANUALLY_BOOKED: {
httpStatus: 409,
message_sv:
'Ordern är markerad som bokförd utanför integrationen. Ångra markeringen först om du vill bokföra eller fakturera den härifrån.',
message_en:
'The order is marked as booked outside the integration. Undo the mark first if you want to book or invoice it from here.',
},
WEBSHOP_ORDER_MARK_ENTRY_NOT_FOUND: {
httpStatus: 404,
message_sv: 'Verifikatet som ordern skulle kopplas till hittades inte.',
message_en: 'The journal entry to link the order to was not found.',
},
WEBSHOP_ORDER_MARK_ENTRY_NOT_POSTED: {
httpStatus: 409,
message_sv:
'Verifikatet är inte bokfört. Ordern kan bara kopplas till ett bokfört verifikat.',
message_en:
'The journal entry is not posted. The order can only be linked to a posted entry.',
},
}
const NODE_SYSTEM: Record<string, StructuredErrorEntry> = {
@@ -56,6 +56,7 @@ function existingRow(overrides: Record<string, unknown> = {}) {
external_id: 'woo_butik.example.se_order_1001',
journal_entry_id: null,
invoice_id: null,
manually_booked_at: null,
legacy_transaction_id: null,
remote_changed_after_freeze: false,
total: 500,
@@ -253,6 +254,24 @@ describe('upsertWebshopOrders', () => {
expect(update).not.toHaveProperty('paid_date')
})
it('flags a manually marked row whose financials drifted instead of updating them (#1879)', async () => {
mock.enqueueMany([
{ data: [existingRow({ manually_booked_at: '2026-08-10T00:00:00Z' })] },
{ data: [] },
{ data: null }, // safe-field update
])
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [
makeUpsert({ total: 600, status: 'completed' }),
])
expect(result.frozenFlagged).toBe(1)
const update = mock.findCall('webshop_orders', 'update')![0] as Record<string, unknown>
expect(update.remote_changed_after_freeze).toBe(true)
expect(update).not.toHaveProperty('total')
expect(update).not.toHaveProperty('line_items')
})
it('leaves total_sek null when the exchange rate cannot resolve', async () => {
mock.enqueueMany([
{ data: [] },
+18 -3
View File
@@ -53,6 +53,7 @@ type ExistingRow = Pick<
| 'external_id'
| 'journal_entry_id'
| 'invoice_id'
| 'manually_booked_at'
| 'legacy_transaction_id'
| 'remote_changed_after_freeze'
| 'total'
@@ -86,8 +87,22 @@ function chunk<T>(items: T[], size: number): T[][] {
return out
}
function isFrozen(row: Pick<ExistingRow, 'journal_entry_id' | 'invoice_id'>): boolean {
return row.journal_entry_id !== null || row.invoice_id !== null
/**
* Rows whose financials must not be silently refreshed. Booked/invoiced rows
* are frozen by the DB trigger; manually marked rows (#1879) are treated the
* same APPLICATION-side: the user asserted "this row is covered by verifikat
* X", so a remote financial delta must surface as remote_changed_after_freeze
* (the same badge booked rows get) instead of mutating the row under that
* assertion and hiding the incremental business event forever.
*/
function isFrozen(
row: Pick<ExistingRow, 'journal_entry_id' | 'invoice_id' | 'manually_booked_at'>,
): boolean {
return (
row.journal_entry_id !== null ||
row.invoice_id !== null ||
row.manually_booked_at !== null
)
}
/**
@@ -231,7 +246,7 @@ export async function upsertWebshopOrders(
const { data: existingData, error: existingError } = await supabase
.from('webshop_orders')
.select(
'id, external_id, journal_entry_id, invoice_id, legacy_transaction_id, remote_changed_after_freeze, total, total_tax, total_sek, exchange_rate, currency, order_date, paid_date, is_paid, payment_method, payment_method_title, gateway_reference, order_number, status, refunded_total, store_label, connection_id, customer_name, customer_company, customer_email, customer_orgnr, customer_country, vat_breakdown, line_items',
'id, external_id, journal_entry_id, invoice_id, manually_booked_at, legacy_transaction_id, remote_changed_after_freeze, total, total_tax, total_sek, exchange_rate, currency, order_date, paid_date, is_paid, payment_method, payment_method_title, gateway_reference, order_number, status, refunded_total, store_label, connection_id, customer_name, customer_company, customer_email, customer_orgnr, customer_country, vat_breakdown, line_items',
)
.eq('company_id', companyId)
.in('external_id', lookupIds)