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
+1
View File
@@ -1242,3 +1242,4 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
[2026-08-25] Ranged income statement sums period movements, not closing balances (skeptic refutation on PR #1909): with from_date > period_start the trial balance rolls pre-range P&L activity into opening columns, so closing-column sums are year-to-date mislabeled as the range (July revenue reported as Jan-Jul). generateIncomeStatement now passes periodMovements to buildIncomeStatementFromRows whenever fromDate is set, matching the resultatrapport convention; full-period behavior is byte-identical. from_date was also dropped from the v1 balance-sheet routes (a balansräkning is a cumulative position; ÅRL 3 kap): as_of/to_date only, matching the MCP tool.
[2026-08-25] Issue #1870: skattekonto AGI seed reverted 2730 -> 2731 (salary side kept on 2731), not the alternative of moving SALARY_ACCOUNTS.AVGIFTER_LIABILITY to 2730: BAS 2026 defines 2731 as exactly the reported-but-unpaid arbetsgivaravgift liability (the accrual account is 2940), and the salary module's whole-krona/ore-residual logic (PR #1609, 2026-08-14 decisions) is built around 2731. The 20260519160000 migration's rationale mislabeled 2731 as the accrual account; a one-sided flip either way reintroduces the split. Historical 2730 debits since 2026-05-19 are left for per-company reclass verifikat, not repaired in-migration.
[2026-08-25] The marketplace entry for the Accounted plugin is a git-subdir source (public repo URL + path claude-plugin), not the relative path ./claude-plugin: relative sources only resolve when the whole marketplace repo is cloned (Claude Code), while Claude.ai's Add-marketplace backend fetches the manifest and resolves each plugin source as a repository, which surfaced as 'Repository not accessible' on a public repo. git-subdir is also the form the plugin-directory catalog uses for monorepos.
[2026-08-25] Woo bulk revenue template = per-rate account choice, no hardcoded varor/tjanster preset: BAS 2026 has no standard 30xx goods/services subdivision (3040-series is company-specific), so presets would invent accounts; chosen accounts are validated against the company chart instead, and only diffs from the 3001-series default are sent.
@@ -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
+118 -5
View File
@@ -18,6 +18,8 @@ import { Label } from '@/components/ui/label'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import {
DEFAULT_REVENUE_ACCOUNT_BY_RATE,
ROUNDING_ACCOUNT,
resolveBookingWarnings,
resolvePaymentAccount,
unsupportedVatRates,
@@ -50,9 +52,11 @@ interface BulkOrderBookingDialogProps {
* Book N selected orders with the standard order template in one sweep
* (confirm up front, convention 10). Each order still becomes its own
* verifikat server-side via the same flow as the single-order dialog; this
* dialog only chooses the payment counter-account policy: per-store mapping
* (default) or one explicit account for the whole selection. Partial failure
* is surfaced per order in a result list instead of aborting the batch.
* dialog chooses two sweep-wide policies: the payment counter-account
* (per-store mapping by default, or one explicit account) and the revenue
* template (revenue account per VAT rate, standard 3001-series by default).
* Partial failure is surfaced per order in a result list instead of
* aborting the batch.
*/
export default function BulkOrderBookingDialog({
open,
@@ -67,6 +71,8 @@ export default function BulkOrderBookingDialog({
const [overrideEnabled, setOverrideEnabled] = useState(false)
const [overrideAccount, setOverrideAccount] = useState('')
const [revenueEnabled, setRevenueEnabled] = useState(false)
const [revenueAccounts, setRevenueAccounts] = useState<Record<number, string>>({})
const [submitting, setSubmitting] = useState(false)
const [results, setResults] = useState<BulkBookOrderResult[] | null>(null)
@@ -132,6 +138,22 @@ export default function BulkOrderBookingDialog({
return Array.from(groups.values()).sort((a, b) => a.label.localeCompare(b.label))
}, [bookableOrders, settingsFor])
// The VAT rates actually present in the bookable selection, highest first,
// with order counts: the revenue template only offers inputs for rates a
// revenue line will actually book on.
const ratesPresent = useMemo(() => {
const counts = new Map<number, number>()
for (const order of bookableOrders) {
const rates = new Set(order.vat_breakdown.map((b) => b.rate))
for (const rate of rates) {
counts.set(rate, (counts.get(rate) ?? 0) + 1)
}
}
return Array.from(counts.entries())
.sort(([a], [b]) => b - a)
.map(([rate, count]) => ({ rate, count }))
}, [bookableOrders])
// Advisory VAT warnings stay per order, not an anonymous count: the user
// must be able to tell WHICH orders deserve the single-dialog review.
const warningOrderNumbers = useMemo(
@@ -148,11 +170,15 @@ export default function BulkOrderBookingDialog({
? accountGroups[0].account
: null
// Reset per open so a second sweep starts clean.
// Reset per open so a second sweep starts clean. The revenue inputs
// prefill with the effective defaults (prefill-plus-override editor
// pattern): the user edits from what would book, not from blank fields.
useEffect(() => {
if (open) {
setOverrideEnabled(false)
setOverrideAccount(uniformAccount ?? '')
setRevenueEnabled(false)
setRevenueAccounts({ ...DEFAULT_REVENUE_ACCOUNT_BY_RATE })
setSubmitting(false)
setResults(null)
}
@@ -161,8 +187,34 @@ export default function BulkOrderBookingDialog({
}, [open])
const overrideValid = ACCOUNT_NUMBER_RE.test(overrideAccount)
// A revenue-template account must be class 3 and never 3740 (schema
// mirror: 3740 is the rounding account the residual guard keys on).
const revenueAccountValid = (value: string) =>
ACCOUNT_NUMBER_RE.test(value) && value.startsWith('3') && value !== ROUNDING_ACCOUNT
const revenueAllValid = ratesPresent.every(({ rate }) =>
revenueAccountValid(revenueAccounts[rate] ?? ''),
)
const canConfirm =
!submitting && bookableOrders.length > 0 && (!overrideEnabled || overrideValid)
!submitting &&
bookableOrders.length > 0 &&
(!overrideEnabled || overrideValid) &&
(!revenueEnabled || revenueAllValid)
// Only DIFFS from the default map are sent (store-diffs convention). An
// untouched default (e.g. 3004) must ride the default path server-side,
// where our closed prefill set is auto-added to a fresh chart; sending it
// explicitly would be a semantic no-op that changes nothing but intent.
const revenueDiffs = useMemo(() => {
if (!revenueEnabled) return null
const diffs: Record<string, string> = {}
for (const { rate } of ratesPresent) {
const chosen = revenueAccounts[rate]
if (chosen && chosen !== DEFAULT_REVENUE_ACCOUNT_BY_RATE[rate]) {
diffs[String(rate)] = chosen
}
}
return Object.keys(diffs).length > 0 ? diffs : null
}, [revenueEnabled, ratesPresent, revenueAccounts])
async function handleConfirm() {
if (!canConfirm) return
@@ -176,6 +228,7 @@ export default function BulkOrderBookingDialog({
...(overrideEnabled && overrideValid
? { payment_account: overrideAccount }
: {}),
...(revenueDiffs ? { revenue_accounts: revenueDiffs } : {}),
}),
})
if (!response.ok) {
@@ -340,6 +393,66 @@ export default function BulkOrderBookingDialog({
</div>
)}
</div>
{/* Revenue template (bokföringsmall): revenue account per VAT
rate present in the selection. Static rows show the effective
accounts (convention 10); the checkbox swaps them for inputs
prefilled with the same defaults. VAT accounts are derived
from the rate and deliberately not editable here. */}
<div className="space-y-2">
<label className="flex items-center gap-2 text-[12.5px] text-muted-foreground">
<Checkbox
checked={revenueEnabled}
onCheckedChange={(v) => setRevenueEnabled(v === true)}
/>
{t('bulk_revenue_label')}
</label>
<ul className="space-y-1">
{ratesPresent.map(({ rate, count }) => {
const value = revenueAccounts[rate] ?? ''
const valid = revenueAccountValid(value)
return (
<li
key={rate}
className="flex items-center justify-between gap-4 text-sm"
>
<span className="truncate">
{t('bulk_revenue_rate', { rate })}
</span>
{revenueEnabled ? (
<span className="flex flex-col items-end gap-1">
<Input
value={value}
onChange={(e) =>
setRevenueAccounts((prev) => ({
...prev,
[rate]: e.target.value.trim(),
}))
}
inputMode="numeric"
maxLength={4}
className="w-28 tabular-nums"
aria-label={t('bulk_revenue_rate_aria', { rate })}
aria-invalid={!valid}
/>
{!valid && (
<span className="text-xs text-destructive" role="alert">
{t('invalid_revenue_account')}
</span>
)}
</span>
) : (
<span className="tabular-nums text-muted-foreground">
{DEFAULT_REVENUE_ACCOUNT_BY_RATE[rate]}
{' · '}
{t('bulk_group_count', { count })}
</span>
)}
</li>
)
})}
</ul>
</div>
</>
)}
+33
View File
@@ -1630,6 +1630,24 @@ export const BookWebshopOrderSchema = z.object({
* through the same server-side flow as the single-order endpoint (never one
* combined journal write). Max 50 = one orders-page of selection.
*/
/**
* Revenue account for the bulk revenue template: class 3 only, and never
* 3740. The template routes the revenue side of the sweep; a non-revenue
* account here would put sales on a balance or cost account with no
* reviewing user per line. 3740 (öresavrundning) is excluded because the
* bulk route bounds the rounding residual by that account: a templated
* revenue line on 3740 would both misbook real revenue as rounding and
* blind that guard (skeptic finding). Orders needing an off-class-3 revenue
* leg go through the single-order dialog, which is fully line-editable.
*/
const webshopRevenueAccount = accountNumber
.refine((n) => n.startsWith('3'), {
message: 'Intäktskontot måste vara ett konto i klass 3 (3000-3999)',
})
.refine((n) => n !== '3740', {
message: 'Öresavrundningskontot 3740 kan inte användas som intäktskonto',
})
export const BulkBookWebshopOrdersSchema = z.object({
order_ids: z.array(uuid).min(1).max(50),
/**
@@ -1637,6 +1655,21 @@ export const BulkBookWebshopOrdersSchema = z.object({
* account instead of the per-store payment-method mapping.
*/
payment_account: accountNumber.optional(),
/**
* Optional revenue template: revenue account per Swedish VAT rate, keyed
* by the rate as a string. A missing rate falls back to the standard
* 3001-series map. Output VAT accounts are never overridable: they are
* derived from the rate.
*/
revenue_accounts: z
.object({
'25': webshopRevenueAccount.optional(),
'12': webshopRevenueAccount.optional(),
'6': webshopRevenueAccount.optional(),
'0': webshopRevenueAccount.optional(),
})
.strict()
.optional(),
})
export const CreateInvoiceFromWebshopOrderSchema = z.object({
+14
View File
@@ -3921,6 +3921,20 @@ const WEBSHOP_ORDERS: Record<string, StructuredErrorEntry> = {
message_en:
'The order has a VAT rate that is not a Swedish rate (25/12/6/0 %), for example foreign OSS VAT. Book the order individually and review the lines.',
},
WEBSHOP_ORDER_REVENUE_ACCOUNT_RATE_MISMATCH: {
httpStatus: 422,
message_sv:
'Ett valt intäktskonto är inte upplagt för momssatsen det ska ta emot, så försäljningen skulle falla ur momsdeklarationens ruta 05. Ange kontots momssats i kontoplanen (eller välj ett konto för rätt sats) och försök igen.',
message_en:
'A chosen revenue account is not configured for the VAT rate it would receive, so the sale would drop out of ruta 05 in the VAT declaration. Set the account VAT rate in the chart of accounts (or pick an account for the right rate) and try again.',
},
WEBSHOP_ORDER_REVENUE_ACCOUNT_UNKNOWN: {
httpStatus: 422,
message_sv:
'Ett valt intäktskonto finns inte i kontoplanen eller är inaktivt. Lägg till eller aktivera kontot under Kontoplan och försök igen.',
message_en:
'A chosen revenue account is not in the chart of accounts or is inactive. Add or activate the account in the chart of accounts and try again.',
},
WEBSHOP_ORDER_RESIDUAL_TOO_LARGE: {
httpStatus: 422,
message_sv:
+8 -1
View File
@@ -17,7 +17,14 @@ const DOMESTIC_SALES_RATE_BY_SUFFIX: Record<string, number> = { '1': 0.25, '2':
const CONTRADICTING_ACCOUNT_NAME =
/momsfri|momsfritt|utan moms|omvänd|\bvmb\b|vinstmarginal|export|utanför|eu-land|unionsintern|\boss\b|\b0\s*%/i
function inferDomesticSalesRate(accountNumber: string, accountName: string): number | null {
/**
* Infer the domestic-sales VAT rate a class 3 account represents from its
* number pattern (30x1/30x2/30x3) and a rate-naming account name. Exported
* for the webshop bulk sweep's revenue-template guard, which must accept an
* account for a rate exactly when this report logic would count it toward
* ruta 05 for that rate.
*/
export function inferDomesticSalesRate(accountNumber: string, accountName: string): number | null {
const accountMatch = /^30\d([123])$/.exec(accountNumber)
if (!accountMatch || CONTRADICTING_ACCOUNT_NAME.test(accountName)) return null
const expectedRate = DOMESTIC_SALES_RATE_BY_SUFFIX[accountMatch[1]]
@@ -260,6 +260,74 @@ describe('buildOrderBookingLines', () => {
expect(sumDebits(lines)).toBe(sumCredits(lines))
})
it('routes revenue per rate through a revenue template, VAT untouched', () => {
const lines = buildOrderBookingLines({
order: makeOrder({
total: 612,
total_tax: 87,
total_sek: 612,
vat_breakdown: [
{ rate: 25, net: 300, tax: 75 },
{ rate: 12, net: 100, tax: 12 },
{ rate: 6, net: 100, tax: 6 },
{ rate: 0, net: 19, tax: 0 },
],
}),
settings,
revenueAccounts: { 25: '3041', 12: '3042', 6: '3043', 0: '3100' },
})
expect(lineFor(lines, '3041')?.credit_amount).toBe(300)
expect(lineFor(lines, '3042')?.credit_amount).toBe(100)
expect(lineFor(lines, '3043')?.credit_amount).toBe(100)
expect(lineFor(lines, '3100')?.credit_amount).toBe(19)
// The default accounts must not appear when every rate is templated.
for (const account of ['3001', '3002', '3003', '3004']) {
expect(lineFor(lines, account)).toBeUndefined()
}
// VAT accounts are always derived from the rate, never templated.
expect(lineFor(lines, '2611')?.credit_amount).toBe(75)
expect(lineFor(lines, '2621')?.credit_amount).toBe(12)
expect(lineFor(lines, '2631')?.credit_amount).toBe(6)
expect(sumDebits(lines)).toBe(sumCredits(lines))
})
it('falls back to the default revenue account for rates not in the template', () => {
const lines = buildOrderBookingLines({
order: makeOrder({
total: 537,
total_tax: 87,
total_sek: 537,
vat_breakdown: [
{ rate: 25, net: 300, tax: 75 },
{ rate: 12, net: 100, tax: 12 },
],
}),
settings,
revenueAccounts: { 25: '3041' },
})
expect(lineFor(lines, '3041')?.credit_amount).toBe(300)
expect(lineFor(lines, '3002')?.credit_amount).toBe(100)
expect(sumDebits(lines)).toBe(sumCredits(lines))
})
it('mirrors refunds through the revenue template (debit the chosen account)', () => {
const lines = buildOrderBookingLines({
order: makeOrder({
row_type: 'refund',
total: -500,
total_tax: -100,
total_sek: -500,
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
}),
settings,
revenueAccounts: { 25: '3041' },
})
expect(lineFor(lines, '1930')).toMatchObject({ debit_amount: 0, credit_amount: 500 })
expect(lineFor(lines, '3041')).toMatchObject({ debit_amount: 400, credit_amount: 0 })
expect(lineFor(lines, '2611')).toMatchObject({ debit_amount: 100, credit_amount: 0 })
expect(sumDebits(lines)).toBe(sumCredits(lines))
})
it('throws when a non-SEK order has no resolved SEK amount', () => {
expect(() =>
buildOrderBookingLines({
+22 -3
View File
@@ -40,14 +40,24 @@ export const DEFAULT_PAYMENT_ACCOUNT = '1686'
/** BAS 2026 name for DEFAULT_PAYMENT_ACCOUNT; used when adding it to a chart. */
export const DEFAULT_PAYMENT_ACCOUNT_NAME = 'Fordringar för kontokort och kuponger'
/** Revenue account per Swedish VAT rate (BAS 2026). */
const REVENUE_ACCOUNT_BY_RATE: Record<number, string> = {
/**
* Default revenue account per Swedish VAT rate: the standard BAS 2026
* "Försäljning inom Sverige" accounts. Exported so the bulk dialog can
* prefill its per-rate revenue pickers with the effective defaults. BAS 2026
* has no standard goods/services subdivision of 30xx (such a split, e.g. an
* own 3040-series, is company-specific), which is why the revenue template
* is a per-rate account choice against the company's own chart rather than
* a hardcoded varor/tjänster preset.
*/
export const DEFAULT_REVENUE_ACCOUNT_BY_RATE: Readonly<Record<number, string>> = {
25: '3001',
12: '3002',
6: '3003',
0: '3004',
}
const REVENUE_ACCOUNT_BY_RATE = DEFAULT_REVENUE_ACCOUNT_BY_RATE
/** Output VAT account per rate. */
const VAT_ACCOUNT_BY_RATE: Record<number, string> = {
25: '2611',
@@ -207,6 +217,12 @@ export interface OrderBookingLinesInput {
settings?: WebshopStoreSettings | null
/** Explicit override of the payment counter-account (dialog edit). */
paymentAccount?: string
/**
* Revenue template: revenue account per Swedish VAT rate. A rate not in
* the map falls back to DEFAULT_REVENUE_ACCOUNT_BY_RATE. Only the revenue
* side is templated; output VAT accounts are always derived from the rate.
*/
revenueAccounts?: Partial<Record<number, string>>
}
/**
@@ -217,6 +233,7 @@ export function buildOrderBookingLines({
order,
settings,
paymentAccount,
revenueAccounts,
}: OrderBookingLinesInput): CreateJournalEntryLineInput[] {
const isSek = order.currency.toUpperCase() === 'SEK'
const rate = isSek ? 1 : order.exchange_rate
@@ -287,7 +304,9 @@ export function buildOrderBookingLines({
}
for (const bucket of breakdown) {
const revenueAccount =
REVENUE_ACCOUNT_BY_RATE[bucket.rate] ?? REVENUE_ACCOUNT_BY_RATE[25]
revenueAccounts?.[bucket.rate] ??
REVENUE_ACCOUNT_BY_RATE[bucket.rate] ??
REVENUE_ACCOUNT_BY_RATE[25]
const vatAccount = VAT_ACCOUNT_BY_RATE[bucket.rate] ?? VAT_ACCOUNT_BY_RATE[25]
pushSigned(revenueAccount, round(bucket.net))
pushSigned(vatAccount, round(bucket.tax))
+4
View File
@@ -6315,6 +6315,10 @@
"bulk_no_method": "No payment method",
"bulk_group_count": "{count, plural, one {# order} other {# orders}}",
"bulk_override_label": "Book all against the same payment account",
"bulk_revenue_label": "Choose revenue accounts (booking template)",
"bulk_revenue_rate": "Sales {rate}% VAT",
"bulk_revenue_rate_aria": "Revenue account for {rate}% VAT",
"invalid_revenue_account": "Enter a class 3 revenue account (not 3740), e.g. 3041.",
"bulk_confirm": "Book {count, plural, one {# order} other {# orders}}",
"bulk_error_title": "Booking failed",
"bulk_success_title": "Done",
+4
View File
@@ -6315,6 +6315,10 @@
"bulk_no_method": "Utan betalsätt",
"bulk_group_count": "{count, plural, one {# order} other {# ordrar}}",
"bulk_override_label": "Bokför alla mot samma betalkonto",
"bulk_revenue_label": "Välj intäktskonton (bokföringsmall)",
"bulk_revenue_rate": "Försäljning {rate} % moms",
"bulk_revenue_rate_aria": "Intäktskonto för {rate} % moms",
"invalid_revenue_account": "Ange ett intäktskonto i klass 3 (inte 3740), t.ex. 3041.",
"bulk_confirm": "Bokför {count, plural, one {# order} other {# ordrar}}",
"bulk_error_title": "Bokföringen misslyckades",
"bulk_success_title": "Klart",