feat(webshop-orders): Orders page with per-store, per-payment-method booking (#1525)
* feat(webshop-orders): schema, types and error codes for the orders surface webshop_orders (order/refund rows, financial-freeze trigger, member select/update RLS, no DELETE) + webshop_store_settings (per-store payment method -> account map), source_type 'webshop_order', multi-store index drop, customer_country, and a one-time woo cursor reset so the switch-over backfills and cross-marks existing feed rows. Tables classified in the full-archive export; pg-real coverage for RLS, freeze and CHECK. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(webshop-orders): core service (ingest, booking lines) upsertWebshopOrders: two-phase order/refund upsert with FX enrichment, legacy-feed cross-marking, frozen-row protection and field-wise jsonb comparisons (Postgres does not preserve object key order). Booking-line builder: per-rate VAT split with SIGNED buckets (discounts book as revenue reductions), refund mirroring, 3740 residual, per-store account prefill, and advisory export/EU + OSS warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(webshop-orders): API routes for list, booking, invoicing and mapping Booking is draft -> atomic claim -> commit (conditional link-back closes the concurrent double-book race; a lost claim cancels the voucher-free draft). Legacy-feed guard honors transactions.is_ignored on both the book and create-invoice paths. Invoice conversion reuses buildInvoiceWriteData for an unnumbered draft with dominant-rate fallback and drift-safe unit prices. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(webshop-orders): Orders page, booking/invoice dialogs and gated nav /orders lists per-store orders with status tabs (server-side filters), exception chips and one action per row. Booking dialog prefills from the per-store payment-method mapping with an opt-in remember; invoice dialog converts to a draft kundfaktura. The Order nav item renders only for companies with an active WooCommerce connection or existing order rows (Shopify deliberately excluded until its sync writes webshop_orders). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(woocommerce): switch the order sync to webshop_orders, multi-store The sync maps rich wc/v3 payloads (billing, line/shipping/fee taxes, refund allocations with parent-prorated VAT fallback) and upserts order rows instead of transactions-inbox rows; already-imported feed rows stay bookable and get cross-marked. Multi-store: several active connections per company, per-store panel cards with the account-mapping editor. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(webshop-orders): decision log entries and ratchet baseline Baseline moves DOWN only: naive-ore-round 638 -> 637 via roundOre adoption; hand-rolled invariants stay at 115 (ACCOUNT_NUMBER_RE imported, not inlined). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(webshop-orders): resolve PR #1525 review findings and CI failures Review batch (Superagent, CodeRabbit, Swedish compliance review): - Mutual-exclusion claims: booking guards invoice_id, invoice link-back guards journal_entry_id AND treats zero matched rows as the conflict it is (409 + rollback), closing both TOCTOU races. - Freeze v2 migration (20260812124858): the link columns themselves are protected: invoice links immutable, journal links clearable only while the entry is still a draft (the booking rollback path). - Scraped orgnr no longer auto-written to customers.org_number; rate fallback applies only on single-VAT-bucket orders; refunds get their own WEBSHOP_ORDER_REFUND_NOT_CONVERTIBLE code; VAT advisories outrank the invoice-mode hint in the booking dialog. - Ingest compares every synced field (billing corrections no longer drop as unchanged); sync guards absent refunds arrays; /sync aggregates per-store results; panel disables all cards while a request runs; orders page separates load failure from empty; account field explains itself. CI: regenerated skills/accounted-api; pg tests restructured for transaction-abort/rollback semantics + freeze-link coverage; unresolvable- expression ceiling 375 -> 378 with documented reason (partial-update payloads in ingest, shapes covered by unit tests). Declined: CodeRabbit docstring-coverage advisory (house style: comments only where the code cannot say it). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
89cfa82f2f
commit
c35b2547fb
@@ -0,0 +1,284 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { seedCompany, insertDraftJournalEntry } from './fixtures'
|
||||
|
||||
/**
|
||||
* Covers migrations 20260811073315_webshop_orders,
|
||||
* 20260811073333_webshop_store_settings and
|
||||
* 20260811073416_journal_source_type_webshop_order:
|
||||
* 1. RLS: members read/update their company's rows, cannot INSERT
|
||||
* (sync is service-role only) and cannot DELETE; outsiders see nothing.
|
||||
* 2. (company_id, external_id) unique index.
|
||||
* 3. Financial freeze trigger: booked rows reject money-field updates but
|
||||
* accept status/refund-summary updates.
|
||||
* 4. journal_entries.source_type accepts 'webshop_order'.
|
||||
* 5. webshop_store_settings RLS + upsert key.
|
||||
*/
|
||||
|
||||
// Rows persist across pg-real runs; unique external ids per run.
|
||||
const uniqueExternalId = (label: string) =>
|
||||
`woo_test-${label}-${randomUUID()}.example.se_order_1001`
|
||||
|
||||
async function insertOrderRow(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
externalId?: string
|
||||
journalEntryId?: string | null
|
||||
}): Promise<string> {
|
||||
const { rows } = await getPool().query(
|
||||
`INSERT INTO public.webshop_orders
|
||||
(company_id, user_id, platform, store_scope, row_type, external_id,
|
||||
platform_order_id, order_number, status, is_paid, order_date, paid_date,
|
||||
currency, total, total_tax, total_sek, exchange_rate, vat_breakdown,
|
||||
payment_method, journal_entry_id)
|
||||
VALUES ($1, $2, 'woocommerce', 'butik.example.se', 'order', $3,
|
||||
'1001', '1001', 'processing', true, '2026-08-01', '2026-08-01',
|
||||
'SEK', 500.00, 100.00, 500.00, 1, '[{"rate":25,"net":400,"tax":100}]'::jsonb,
|
||||
'swish', $4)
|
||||
RETURNING id`,
|
||||
[
|
||||
params.companyId,
|
||||
params.userId,
|
||||
params.externalId ?? uniqueExternalId('order'),
|
||||
params.journalEntryId ?? null,
|
||||
],
|
||||
)
|
||||
return rows[0].id as string
|
||||
}
|
||||
|
||||
describe('webshop_orders RLS', () => {
|
||||
it('a member reads and updates own-company rows but cannot delete', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const rowId = await insertOrderRow({ companyId, userId })
|
||||
|
||||
await withUserContext(userId, async (client) => {
|
||||
const read = await client.query(
|
||||
`SELECT status, payment_method FROM public.webshop_orders WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(read.rows).toEqual([{ status: 'processing', payment_method: 'swish' }])
|
||||
|
||||
// Member UPDATE works (the booking route writes back journal_entry_id).
|
||||
const updated = await client.query(
|
||||
`UPDATE public.webshop_orders SET status = 'completed' WHERE id = $1`,
|
||||
[rowId],
|
||||
)
|
||||
expect(updated.rowCount).toBe(1)
|
||||
|
||||
// No DELETE policy: order rows are accounting underlag.
|
||||
const del = await client.query(
|
||||
`DELETE FROM public.webshop_orders WHERE id = $1`,
|
||||
[rowId],
|
||||
)
|
||||
expect(del.rowCount).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
it('a member cannot INSERT (the sync path is service-role only)', async () => {
|
||||
// Own withUserContext block: an RLS rejection aborts the transaction, so
|
||||
// the failing statement must be the block's last.
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await withUserContext(userId, async (client) => {
|
||||
await expect(
|
||||
client.query(
|
||||
`INSERT INTO public.webshop_orders
|
||||
(company_id, user_id, platform, store_scope, external_id,
|
||||
platform_order_id, order_number, status, order_date, currency, total)
|
||||
VALUES ($1, $2, 'woocommerce', 'butik.example.se', $3,
|
||||
'9', '9', 'pending', '2026-08-01', 'SEK', 100.00)`,
|
||||
[companyId, userId, uniqueExternalId('member-insert')],
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i)
|
||||
})
|
||||
})
|
||||
|
||||
it('a non-member sees nothing and cannot update foreign rows', async () => {
|
||||
const { userId: ownerId, companyId } = await seedCompany()
|
||||
const rowId = await insertOrderRow({ companyId, userId: ownerId })
|
||||
const { userId: outsiderId } = await seedCompany()
|
||||
|
||||
await withUserContext(outsiderId, async (client) => {
|
||||
const read = await client.query(
|
||||
`SELECT id FROM public.webshop_orders WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(read.rows).toHaveLength(0)
|
||||
|
||||
const update = await client.query(
|
||||
`UPDATE public.webshop_orders SET status = 'hacked' WHERE id = $1`,
|
||||
[rowId],
|
||||
)
|
||||
expect(update.rowCount).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
it('(company_id, external_id) is unique per company but not across companies', async () => {
|
||||
const { userId: userA, companyId: companyA } = await seedCompany()
|
||||
const { userId: userB, companyId: companyB } = await seedCompany()
|
||||
const externalId = uniqueExternalId('dedup')
|
||||
|
||||
await insertOrderRow({ companyId: companyA, userId: userA, externalId })
|
||||
await expect(
|
||||
insertOrderRow({ companyId: companyA, userId: userA, externalId }),
|
||||
).rejects.toMatchObject({ code: '23505' })
|
||||
|
||||
// Another company may carry the same external id (scope is per company).
|
||||
const other = await insertOrderRow({ companyId: companyB, userId: userB, externalId })
|
||||
expect(other).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('webshop_orders financial freeze', () => {
|
||||
it('rejects money-field updates once booked, allows status updates', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertDraftJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
sourceType: 'webshop_order',
|
||||
})
|
||||
const rowId = await insertOrderRow({ companyId, userId, journalEntryId: entryId })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.webshop_orders SET total = 600.00 WHERE id = $1`,
|
||||
[rowId],
|
||||
),
|
||||
).rejects.toThrow(/financial fields are frozen/i)
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.webshop_orders SET paid_date = '2026-08-02' WHERE id = $1`,
|
||||
[rowId],
|
||||
),
|
||||
).rejects.toThrow(/financial fields are frozen/i)
|
||||
|
||||
// Non-financial fields keep syncing on frozen rows.
|
||||
const ok = await getPool().query(
|
||||
`UPDATE public.webshop_orders
|
||||
SET status = 'refunded', refunded_total = 500.00,
|
||||
remote_changed_after_freeze = true
|
||||
WHERE id = $1`,
|
||||
[rowId],
|
||||
)
|
||||
expect(ok.rowCount).toBe(1)
|
||||
})
|
||||
|
||||
it('leaves unbooked rows fully mutable', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const rowId = await insertOrderRow({ companyId, userId })
|
||||
const ok = await getPool().query(
|
||||
`UPDATE public.webshop_orders SET total = 750.00, total_sek = 750.00 WHERE id = $1`,
|
||||
[rowId],
|
||||
)
|
||||
expect(ok.rowCount).toBe(1)
|
||||
})
|
||||
|
||||
it('allows unlinking while the entry is still a draft (booking rollback path)', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const draftId = await insertDraftJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
sourceType: 'webshop_order',
|
||||
})
|
||||
const rowId = await insertOrderRow({ companyId, userId, journalEntryId: draftId })
|
||||
const ok = await getPool().query(
|
||||
`UPDATE public.webshop_orders SET journal_entry_id = NULL WHERE id = $1`,
|
||||
[rowId],
|
||||
)
|
||||
expect(ok.rowCount).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects clearing the journal link once the entry is posted', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const postedId = await insertDraftJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
sourceType: 'webshop_order',
|
||||
status: 'posted',
|
||||
voucherNumber: 4711,
|
||||
})
|
||||
const rowId = await insertOrderRow({ companyId, userId, journalEntryId: postedId })
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.webshop_orders SET journal_entry_id = NULL WHERE id = $1`,
|
||||
[rowId],
|
||||
),
|
||||
).rejects.toThrow(/journal link is immutable/i)
|
||||
})
|
||||
})
|
||||
|
||||
describe('journal_entries source_type webshop_order', () => {
|
||||
it('accepts webshop_order (CHECK constraint expanded)', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertDraftJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
sourceType: 'webshop_order',
|
||||
})
|
||||
const { rows } = await getPool().query(
|
||||
`SELECT source_type FROM public.journal_entries WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
expect(rows).toEqual([{ source_type: 'webshop_order' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('webshop_store_settings', () => {
|
||||
it('members insert/read/update their mapping; outsiders see nothing', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const storeScope = `butik-${randomUUID()}.example.se`
|
||||
|
||||
// withUserContext ROLLS BACK, so the duplicate-key assertion below needs
|
||||
// a persistent seed row inserted via the pool.
|
||||
await getPool().query(
|
||||
`INSERT INTO public.webshop_store_settings
|
||||
(company_id, user_id, platform, store_scope, payment_method_account_map)
|
||||
VALUES ($1, $2, 'woocommerce', $3, '{"swish":{"mode":"book","account":"1930"}}'::jsonb)`,
|
||||
[companyId, userId, storeScope],
|
||||
)
|
||||
|
||||
await withUserContext(userId, async (client) => {
|
||||
const memberScope = `butik-member-${randomUUID()}.example.se`
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO public.webshop_store_settings
|
||||
(company_id, user_id, platform, store_scope, payment_method_account_map)
|
||||
VALUES ($1, $2, 'woocommerce', $3, '{"swish":{"mode":"book","account":"1930"}}'::jsonb)
|
||||
RETURNING id`,
|
||||
[companyId, userId, memberScope],
|
||||
)
|
||||
expect(inserted.rows).toHaveLength(1)
|
||||
|
||||
const updated = await client.query(
|
||||
`UPDATE public.webshop_store_settings
|
||||
SET payment_method_account_map = '{"swish":{"mode":"book","account":"1580"}}'::jsonb
|
||||
WHERE company_id = $1 AND store_scope = $2`,
|
||||
[companyId, storeScope],
|
||||
)
|
||||
expect(updated.rowCount).toBe(1)
|
||||
})
|
||||
|
||||
// Duplicate (company, platform, store_scope) rejected: upsert key.
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.webshop_store_settings
|
||||
(company_id, user_id, platform, store_scope)
|
||||
VALUES ($1, $2, 'woocommerce', $3)`,
|
||||
[companyId, userId, storeScope],
|
||||
),
|
||||
).rejects.toMatchObject({ code: '23505' })
|
||||
|
||||
const { userId: outsiderId } = await seedCompany()
|
||||
await withUserContext(outsiderId, async (client) => {
|
||||
const read = await client.query(
|
||||
`SELECT id FROM public.webshop_store_settings WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(read.rows).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -12,7 +12,8 @@ const uniqueStore = (label: string) => 'https://' + label + '-' + randomUUID() +
|
||||
* Covers migration 20260806170000_woocommerce_connections:
|
||||
* 1. RLS: members insert and read their own company's connection,
|
||||
* non-members see nothing and cannot insert for a foreign company.
|
||||
* 2. One ACTIVE connection per company (partial unique index).
|
||||
* 2. Multiple ACTIVE connections per company (multi-store: the
|
||||
* one-active-per-company index was dropped in 20260811073422).
|
||||
* 3. One store actively connected to at most one company.
|
||||
* 4. No DELETE policy: a member DELETE silently affects zero rows.
|
||||
*/
|
||||
@@ -66,20 +67,19 @@ describe('woocommerce_connections RLS', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('only one ACTIVE connection per company is allowed', async () => {
|
||||
it('a company may hold several ACTIVE connections (multi-store)', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.woocommerce_connections (company_id, user_id, store_url, status)
|
||||
VALUES ($1, $2, $3, 'active')`,
|
||||
[companyId, userId, uniqueStore('store-one')],
|
||||
)
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.woocommerce_connections (company_id, user_id, store_url, status)
|
||||
VALUES ($1, $2, $3, 'active')`,
|
||||
[companyId, userId, uniqueStore('store-two')],
|
||||
),
|
||||
).rejects.toMatchObject({ code: '23505' }) // unique_violation
|
||||
const second = await getPool().query(
|
||||
`INSERT INTO public.woocommerce_connections (company_id, user_id, store_url, status)
|
||||
VALUES ($1, $2, $3, 'active') RETURNING id`,
|
||||
[companyId, userId, uniqueStore('store-two')],
|
||||
)
|
||||
expect(second.rows).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('a store may be actively connected to at most one company', async () => {
|
||||
|
||||
@@ -92,8 +92,13 @@ const KNOWN_STALE_ON_CONFLICT: Record<string, string> = {}
|
||||
*
|
||||
* Baseline 2026-08-06: 370 (158 dynamic-payload, 120 dynamic-select,
|
||||
* 47 dynamic-logical, 38 spread-payload, 5 dynamic-column, 2 computed key).
|
||||
*
|
||||
* 2026-08-12 +3: lib/webshop-orders/ingest.ts builds partial UPDATE payloads
|
||||
* at runtime (frozen rows get safe fields only; unfrozen rows get optional
|
||||
* parent/legacy links). Writing the shapes as inline literals would need one
|
||||
* variant per key combination; the row shapes are covered by ingest.test.ts.
|
||||
*/
|
||||
const UNRESOLVED_CEILING = 375
|
||||
const UNRESOLVED_CEILING = 378
|
||||
|
||||
/**
|
||||
* Floor on statically resolved column references. Guards the guard: if a change
|
||||
|
||||
Reference in New Issue
Block a user