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
+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>
</>
)}