feat(woo): selectable revenue accounts per VAT rate in the bulk order sweep (#1908)

* feat(woo): selectable revenue accounts per VAT rate in the bulk order sweep

The bulk sweep hardcoded the revenue side to the standard 3001-series, so
a store selling both goods and services could not route tjansteordrar to
its own revenue accounts (user request, follow-up to #1900). The bulk
dialog now has a "bokforingsmall" section: per-VAT-rate revenue account
inputs, shown only for rates present in the selection, prefilled with the
effective defaults; only diffs from the default map are sent.

Server side, BulkBookWebshopOrdersSchema gains an optional
revenue_accounts map (class 3 accounts only) that buildOrderBookingLines
routes each rate bucket's revenue line through; output VAT accounts stay
derived from the rate and are not overridable. User-chosen accounts are
never auto-created: the route verifies them against the company chart up
front and aborts the whole sweep with
WEBSHOP_ORDER_REVENUE_ACCOUNT_UNKNOWN naming the offenders, while
accounts in the closed prefill set keep riding the existing chart
repair. No hardcoded varor/tjanster preset on purpose: BAS 2026 has no
standard 30xx goods/services subdivision (see DECISIONS.md).

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

* fix(woo): harden the bulk revenue template per skeptic and review findings

Three findings from the adversarial review of the revenue-template
commit, fixed in one pass:

- Build breaker: revenueAccountByRate was typed Partial<Record<...>>,
  making Object.values() return (string | undefined)[] and failing the
  production build's type-check (Vitest and ESLint both miss it). Typed
  as Record<number, string>; only truthy strings are ever inserted.

- 3740 template collision (two skeptics, independently): choosing 3740
  as a revenue account passed the class-3 gate, skipped the chart guard
  (it is in the closed prefill set), and made the residual bound read
  the templated revenue line instead of the residual, so a mangled
  gift-card order the sweep must refuse could book a ~499 kr gap as
  "oresavrundning" in an immutable verifikat. 3740 is now banned by the
  schema and the dialog mirror, and the residual line is identified
  structurally (always the last line) instead of by account lookup,
  which also fixes the pre-existing misdiagnosis when 3740 is used as
  payment_account.

- Rate-classification guard (Swedish accounting review): output VAT
  books 2611/2621/2631 per rate regardless of template, but a custom
  account counts toward ruta 05 only when configured for that rate
  (explicit momssats, rate-mapped treatment, or rate-conforming
  30x1/2/3 number + name, i.e. exactly inferDomesticSalesRate, now
  exported and reused). A mismatched pair is refused up front with
  WEBSHOP_ORDER_REVENUE_ACCOUNT_RATE_MISMATCH naming the offenders;
  default-set accounts are valid only for the rate they are the default
  for; rate-0 buckets are exempt (no output VAT, legitimate momsfri/
  export accounts).

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

* fix(woo): explicit momssats wins over name inference in the revenue-template guard

Two Swedish accounting review findings on the rate-classification guard:

- Precedence: the OR check let number+name inference qualify an account
  whose explicit default_vat_rate says a DIFFERENT rate (6%-configured
  account passing a 25% slot on its name). The guard now resolves ONE
  effective rate exactly like fetchDynamicVatAccounts does (explicit
  momssats, then rate-mapped treatment, inference only when nothing is
  configured) and compares that.

- Rate 0 slots no longer skip the check entirely: an account whose
  resolved rate is TAXABLE contradicts the 0% bucket and is refused,
  while unconfigured momsfri/export/EU accounts stay accepted (no
  contradicting configuration required, not positive proof of 0%).

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 21:04:06 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 85e039035d
commit d035d283ef
11 changed files with 773 additions and 13 deletions
@@ -279,6 +279,372 @@ describe('POST /api/webshop-orders/bulk-book', () => {
expect(input.lines[0].account_number).toBe('1580')
})
it('routes revenue through the revenue template and keeps VAT derived', async () => {
enqueue({
data: [
makeOrderRow(),
makeOrderRow({
id: ORDER_2,
order_number: '1002',
external_id: 'x2',
total: 112,
total_tax: 12,
total_sek: 112,
vat_breakdown: [{ rate: 12, net: 100, tax: 12 }],
}),
],
})
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3041',
account_name: 'Försäljning tjänster',
is_active: true,
default_vat_rate: 0.25,
default_vat_treatment: null,
},
],
}) // chart check
enqueue({ data: [{ id: ORDER_1 }] }) // claim order 1
enqueue({ data: [{ id: ORDER_2 }] }) // claim order 2
const { status, body } = await parseJsonResponse<BulkResponse>(
await postBulk({
order_ids: [ORDER_1, ORDER_2],
revenue_accounts: { '25': '3041' },
}),
)
expect(status).toBe(200)
expect(body.data.booked_count).toBe(2)
const firstLines = (
mockCreateDraftEntry.mock.calls[0][3] as {
lines: { account_number: string; credit_amount: number }[]
}
).lines
// 25% revenue re-routed to the chosen account; VAT stays on 2611.
expect(firstLines.find((l) => l.account_number === '3041')?.credit_amount).toBe(400)
expect(firstLines.some((l) => l.account_number === '3001')).toBe(false)
expect(firstLines.find((l) => l.account_number === '2611')?.credit_amount).toBe(100)
// The 12% order is untouched by a 25%-only template.
const secondLines = (
mockCreateDraftEntry.mock.calls[1][3] as {
lines: { account_number: string; credit_amount: number }[]
}
).lines
expect(secondLines.find((l) => l.account_number === '3002')?.credit_amount).toBe(100)
})
it('aborts the whole sweep when a template account is not active in the chart', async () => {
enqueue({ data: [makeOrderRow()] })
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3041',
account_name: 'Försäljning tjänster',
is_active: false,
default_vat_rate: 0.25,
default_vat_treatment: null,
},
],
}) // chart check
const { status, body } = await parseJsonResponse<{
error: { code: string; details?: { accounts?: string[] } }
}>(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '25': '3041' },
}),
)
expect(status).toBe(422)
expect(body.error.code).toBe('WEBSHOP_ORDER_REVENUE_ACCOUNT_UNKNOWN')
expect(body.error.details?.accounts).toEqual(['3041'])
// Nothing may book on a template the user has to fix first.
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
})
it('returns 400 for a non-class-3 revenue-template account', async () => {
const { status } = await parseJsonResponse(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '25': '1930' },
}),
)
expect(status).toBe(400)
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
})
it('returns 400 for 3740 as a revenue-template account (residual guard integrity)', async () => {
// Skeptic counterexample: a 3740 revenue line would be found first by an
// account-keyed residual lookup and let a mangled order book its gap as
// öresavrundning. The schema bans it outright.
const { status } = await parseJsonResponse(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '25': '3740' },
}),
)
expect(status).toBe(400)
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
})
it('refuses a default-set account templated onto the wrong rate', async () => {
// 3002 is the 12% default; routing 25% revenue to it would book a
// taxable 25% sale on a 12% account while VAT still books 2611.
enqueue({ data: [makeOrderRow()] })
enqueue({ data: [] }) // store settings
const { status, body } = await parseJsonResponse<{
error: { code: string; details?: { accounts?: unknown[] } }
}>(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '25': '3002' },
}),
)
expect(status).toBe(422)
expect(body.error.code).toBe('WEBSHOP_ORDER_REVENUE_ACCOUNT_RATE_MISMATCH')
expect(body.error.details?.accounts).toEqual([{ rate: 25, account: '3002' }])
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
})
it('refuses a custom account not configured for the rate (ruta 05 integrity)', async () => {
// Swedish accounting review finding: an account with no momssats, no
// treatment and no rate-conforming name drops the sale's base out of
// ruta 05 while the VAT books ruta 10. The sweep refuses and names it.
enqueue({ data: [makeOrderRow()] })
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3051',
account_name: 'Försäljning tjänster',
is_active: true,
default_vat_rate: null,
default_vat_treatment: null,
},
],
}) // chart check
const { status, body } = await parseJsonResponse<{
error: { code: string; details?: { accounts?: unknown[] } }
}>(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '25': '3051' },
}),
)
expect(status).toBe(422)
expect(body.error.code).toBe('WEBSHOP_ORDER_REVENUE_ACCOUNT_RATE_MISMATCH')
expect(body.error.details?.accounts).toEqual([{ rate: 25, account: '3051' }])
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
})
it('refuses when an explicit momssats contradicts the rate, despite a conforming name', async () => {
// Swedish review finding: explicit configuration must take precedence
// over number+name inference, mirroring fetchDynamicVatAccounts. An
// account set to 6% never qualifies for a 25% slot on its name alone.
enqueue({ data: [makeOrderRow()] })
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3041',
account_name: 'Försäljning tjänster 25 % moms',
is_active: true,
default_vat_rate: 0.06,
default_vat_treatment: null,
},
],
}) // chart check
const { status, body } = await parseJsonResponse<{
error: { code: string }
}>(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '25': '3041' },
}),
)
expect(status).toBe(422)
expect(body.error.code).toBe('WEBSHOP_ORDER_REVENUE_ACCOUNT_RATE_MISMATCH')
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
})
it('refuses a rate-0 slot for an account explicitly configured as taxable', async () => {
// Swedish review finding: rate 0 carries no VAT amount, but a taxable-
// configured account in the 0% slot still distorts the ruta 05 base.
enqueue({
data: [
makeOrderRow({
total: 500,
total_sek: 500,
total_tax: 0,
vat_breakdown: [{ rate: 0, net: 500, tax: 0 }],
}),
],
})
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3051',
account_name: 'Försäljning varor',
is_active: true,
default_vat_rate: 0.25,
default_vat_treatment: null,
},
],
}) // chart check
const { status, body } = await parseJsonResponse<{
error: { code: string }
}>(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '0': '3051' },
}),
)
expect(status).toBe(422)
expect(body.error.code).toBe('WEBSHOP_ORDER_REVENUE_ACCOUNT_RATE_MISMATCH')
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
})
it('accepts an unconfigured momsfri account in the rate-0 slot', async () => {
// Export/EU/momsfri accounts are usually unconfigured; only a resolved
// TAXABLE rate contradicts the 0% slot.
enqueue({
data: [
makeOrderRow({
total: 500,
total_sek: 500,
total_tax: 0,
vat_breakdown: [{ rate: 0, net: 500, tax: 0 }],
}),
],
})
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3105',
account_name: 'Försäljning varor till land utanför EU',
is_active: true,
default_vat_rate: null,
default_vat_treatment: null,
},
],
}) // chart check
enqueue({ data: [{ id: ORDER_1 }] }) // claim
const { status, body } = await parseJsonResponse<BulkResponse>(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '0': '3105' },
}),
)
expect(status).toBe(200)
expect(body.data.booked_count).toBe(1)
const lines = (
mockCreateDraftEntry.mock.calls[0][3] as {
lines: { account_number: string; credit_amount: number }[]
}
).lines
expect(lines.find((l) => l.account_number === '3105')?.credit_amount).toBe(500)
})
it('accepts a custom account qualified by its rate-conforming number and name', async () => {
// No explicit momssats, but 3041 + a name naming exactly "25 % moms"
// is what the ruta 05 report logic itself accepts (inferDomesticSalesRate).
enqueue({ data: [makeOrderRow()] })
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3041',
account_name: 'Försäljning tjänster 25 % moms',
is_active: true,
default_vat_rate: null,
default_vat_treatment: null,
},
],
}) // chart check
enqueue({ data: [{ id: ORDER_1 }] }) // claim
const { status, body } = await parseJsonResponse<BulkResponse>(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '25': '3041' },
}),
)
expect(status).toBe(200)
expect(body.data.booked_count).toBe(1)
})
it('still bounds the residual when the revenue is templated (mangled order)', async () => {
// Skeptic scenario, post-fix: gift-card order whose gross (500) exceeds
// its VAT breakdown (0.80 + 0.20). The residual line is identified
// structurally (last line), so the templated revenue line can never
// shadow it and the order is refused, exactly as without a template.
enqueue({
data: [
makeOrderRow({
total: 500,
total_sek: 500,
total_tax: 0.2,
vat_breakdown: [{ rate: 25, net: 0.8, tax: 0.2 }],
}),
],
})
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3041',
account_name: 'Försäljning tjänster',
is_active: true,
default_vat_rate: 0.25,
default_vat_treatment: null,
},
],
}) // chart check
const { status, body } = await parseJsonResponse<BulkResponse>(
await postBulk({
order_ids: [ORDER_1],
revenue_accounts: { '25': '3041' },
}),
)
expect(status).toBe(200)
expect(body.data.results[0].error?.code).toBe('WEBSHOP_ORDER_RESIDUAL_TOO_LARGE')
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
})
it('composes the revenue template with the payment_account override', async () => {
enqueue({ data: [makeOrderRow()] })
enqueue({ data: [] }) // store settings
enqueue({
data: [
{
account_number: '3041',
account_name: 'Försäljning tjänster',
is_active: true,
default_vat_rate: 0.25,
default_vat_treatment: null,
},
],
}) // chart check
enqueue({ data: [{ id: ORDER_1 }] }) // claim
const { status } = await parseJsonResponse(
await postBulk({
order_ids: [ORDER_1],
payment_account: '1930',
revenue_accounts: { '25': '3041' },
}),
)
expect(status).toBe(200)
const lines = (
mockCreateDraftEntry.mock.calls[0][3] as {
lines: { account_number: string; debit_amount: number; credit_amount: number }[]
}
).lines
expect(lines[0]).toMatchObject({ account_number: '1930', debit_amount: 500 })
expect(lines.find((l) => l.account_number === '3041')?.credit_amount).toBe(400)
})
it('reports per-order failure without aborting the batch (guard failure)', async () => {
enqueue({
data: [
+135 -4
View File
@@ -12,8 +12,15 @@ import {
orderBookingDescription,
resolvePaymentAccount,
unsupportedVatRates,
DEFAULT_REVENUE_ACCOUNT_BY_RATE,
ROUNDING_ACCOUNT,
WEBSHOP_PREFILL_ACCOUNTS,
} from '@/lib/webshop-orders/booking-lines'
import { inferDomesticSalesRate } from '@/lib/reports/vat-revenue-accounts'
import {
defaultRateForVatTreatment,
isAccountVatTreatment,
} from '@/lib/vat/account-vat-treatment'
import {
assertOrderBookable,
bookOrderThroughEngine,
@@ -92,7 +99,9 @@ function failureFromError(err: unknown): BulkBookFailure {
* Book N selected webshop order/refund rows in one sweep, each with the
* standard order template: payment account (per-store payment-method mapping,
* or the optional payment_account override) against revenue + output VAT per
* rate from the row's own vat_breakdown.
* rate from the row's own vat_breakdown. The optional revenue_accounts map
* (the "bokföringsmall") routes the revenue side per rate to a chosen class 3
* account instead of the standard 3001-series; VAT accounts stay derived.
*
* Deliberately NOT a samlingsverifikation: every order books as its OWN
* verifikat through the exact same flow as POST /api/webshop-orders/[id]/book
@@ -116,7 +125,22 @@ export const POST = withRouteContext(
async (request, { supabase, user, companyId, log, requestId }) => {
const validation = await validateBody(request, BulkBookWebshopOrdersSchema)
if (!validation.success) return validation.response
const { order_ids, payment_account } = validation.data
const { order_ids, payment_account, revenue_accounts } = validation.data
// Revenue template: rate-keyed map for buildOrderBookingLines. The JSON
// keys are strings ('25'); the builder keys by numeric rate. Typed as a
// full Record (only truthy strings are ever inserted) so Object.values
// stays string[] under the build's type-check.
const revenueAccountByRate: Record<number, string> = {}
for (const [rate, account] of Object.entries(revenue_accounts ?? {})) {
if (account) revenueAccountByRate[Number(rate)] = account
}
const revenueTemplatePairs = Object.entries(revenueAccountByRate).map(
([rate, account]) => ({ rate: Number(rate), account }),
)
const revenueTemplateAccounts = [
...new Set(revenueTemplatePairs.map((p) => p.account)),
]
// Dedupe but keep the caller's order for the result list.
const ids = [...new Set(order_ids)]
@@ -163,6 +187,105 @@ export const POST = withRouteContext(
(s) => s.platform === order.platform && s.store_scope === order.store_scope,
) ?? null
// Revenue-template accounts are user-chosen, so they are never
// auto-created (ensureWebshopPrefillAccounts only repairs our own closed
// prefill set; accounts in that set are exempt from the existence check
// for the same reason). Verify up front that every chosen account exists
// and is active in the company's chart, and abort the WHOLE sweep
// otherwise: a typo would fail every order on the same
// AccountsNotInChartError anyway, and one loud refusal naming the
// accounts beats fifty per-order engine errors. A lookup failure aborts
// too, same doctrine as the settings fetch above.
const chartCheckedAccounts = revenueTemplateAccounts.filter(
(account) => !WEBSHOP_PREFILL_ACCOUNTS.includes(account),
)
const chartRowByAccount = new Map<
string,
{
account_name: string
default_vat_rate: number | string | null
default_vat_treatment: string | null
}
>()
if (chartCheckedAccounts.length > 0) {
const { data: chartRows, error: chartError } = await supabase
.from('chart_of_accounts')
.select(
'account_number, account_name, is_active, default_vat_rate, default_vat_treatment',
)
.eq('company_id', companyId)
.in('account_number', chartCheckedAccounts)
if (chartError) {
log.error('bulk-book chart lookup failed; aborting sweep', chartError)
return NextResponse.json(
{ error: getErrorMessage(chartError, { context: 'transaction' }) },
{ status: 500 },
)
}
for (const row of chartRows ?? []) {
if (!row.is_active) continue
chartRowByAccount.set(row.account_number as string, {
account_name: (row.account_name as string) ?? '',
default_vat_rate: row.default_vat_rate as number | string | null,
default_vat_treatment: row.default_vat_treatment as string | null,
})
}
const unknownAccounts = chartCheckedAccounts.filter(
(account) => !chartRowByAccount.has(account),
)
if (unknownAccounts.length > 0) {
return errorResponseFromCode('WEBSHOP_ORDER_REVENUE_ACCOUNT_UNKNOWN', log, {
requestId,
details: { accounts: unknownAccounts },
})
}
}
// Rate-classification guard (Swedish accounting review + skeptic
// finding): output VAT books on 2611/2621/2631 per rate regardless of
// the template, and the momsdeklaration counts a custom account toward
// ruta 05 only when the account resolves to that rate. The effective
// rate mirrors fetchDynamicVatAccounts EXACTLY, precedence included: an
// explicit momssats always wins, then a rate-mapped treatment, and
// number+name inference only when nothing is configured, so an account
// explicitly set to 6% can never pass a 25% slot on its name alone
// (review finding). A mismatched choice would silently drop the sale's
// base out of ruta 05 while its VAT lands in ruta 10-12, so the sweep
// refuses it and points at the fix. Rate 0 buckets carry no output VAT
// and span legitimate momsfri/export/EU accounts (usually unconfigured),
// so they only refuse an account whose resolved rate CONTRADICTS 0%
// (review finding). Accounts from our own default set are checked
// statically: each is valid only for the rate it is the default for.
const mismatchedAccounts: { rate: number; account: string }[] = []
for (const { rate, account } of revenueTemplatePairs) {
if (WEBSHOP_PREFILL_ACCOUNTS.includes(account)) {
if (DEFAULT_REVENUE_ACCOUNT_BY_RATE[rate] !== account) {
mismatchedAccounts.push({ rate, account })
}
continue
}
const row = chartRowByAccount.get(account)
if (!row) continue // unreachable: the existence guard above returned
const expected = rate / 100
const configured =
row.default_vat_rate === null ? null : Number(row.default_vat_rate)
const effective = isAccountVatTreatment(row.default_vat_treatment)
? (configured ?? defaultRateForVatTreatment(row.default_vat_treatment, 3))
: (configured ?? inferDomesticSalesRate(account, row.account_name))
const mismatch =
rate === 0
? effective !== null && effective !== 0
: effective !== expected
if (mismatch) mismatchedAccounts.push({ rate, account })
}
if (mismatchedAccounts.length > 0) {
return errorResponseFromCode(
'WEBSHOP_ORDER_REVENUE_ACCOUNT_RATE_MISMATCH',
log,
{ requestId, details: { accounts: mismatchedAccounts } },
)
}
// Sequential on purpose: each order is its own draft -> claim -> commit
// round trip through the engine, and voucher numbers are assigned
// atomically per commit. Parallelizing would only contend on the same
@@ -271,6 +394,7 @@ export const POST = withRouteContext(
order: resolvedOrder,
settings,
paymentAccount: payment_account,
revenueAccounts: revenueAccountByRate,
})
} catch (err) {
// buildOrderBookingLines throws only on an unresolved SEK amount,
@@ -289,8 +413,15 @@ export const POST = withRouteContext(
// MAX_RESIDUAL_SEK means the gross total and the VAT breakdown
// disagree (gift-card redemptions, mangled orders); in the single
// dialog the user sees the fat 3740 line and stops, so the sweep must
// refuse instead of booking the gap as "öresavrundning".
const residualLine = lines.find((l) => l.account_number === ROUNDING_ACCOUNT)
// refuse instead of booking the gap as "öresavrundning". The residual
// is identified structurally as the LAST line: the builder appends it
// after every bucket line, and find-by-account would read the wrong
// line whenever an earlier line also sits on 3740 (e.g. a 3740
// payment_account, or historically a 3740 template account before the
// schema banned it), silently disarming this guard (skeptic finding).
const lastLine = lines[lines.length - 1]
const residualLine =
lastLine.account_number === ROUNDING_ACCOUNT ? lastLine : undefined
const residualAbs = residualLine
? Math.max(residualLine.debit_amount || 0, residualLine.credit_amount || 0)
: 0