Files
accounted/lib/reports/avgifter-basis.ts
T
Jakob WennbergandClaude Opus 4.8 f8504f3bd0 fix: audit batch — pagination truncation, MFA/dead-code cleanup, mark-paid fail-closed (#841)
* fix(reports): paginate 8 more report/ledger queries (1000-row truncation)

Raw .select() without fetchAllRows() silently caps at PostgREST's 1000-row
limit, producing wrong statutory output for high-volume companies. Following
#806 (trial-balance/VAT), wrap the remaining offenders in
fetchAllRows + a stable .order('id') + dedupeBy:

- ink2-engine / ne-engine: INK2 & NE-bilaga tax declarations under-counted
- ar-reconciliation (1510/1513), supplier-reconciliation (2440): phantom
  "Ej avstämd" gaps
- full-archive-export: 7-year DR archive (added a unique total order so rows
  are not silently skipped/duplicated across pages)
- avgifter-basis, currency-revaluation, vat-declaration

Adds a regression guard test asserting >1000 ledger lines are summed, not
truncated at 1000.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): close extension-dispatcher MFA gap, scope /api/events to API key, sweep dead code

Security/correctness:
- ext/[...path] dispatcher now uses requireAuth() instead of inline
  supabase.auth.getUser(), enforcing MFA (AAL2) on hosted across the whole
  enabled-extension surface (banking sync, document upload/booking, supplier
  invoices, migration). Ratchets antipatterns-baseline raw-route-auth 168->165.
- /api/events now filters by the API key's bound company_id instead of the
  user's active company (was a cross-company read with a scoped key).
- enable-banking OAuth callback calls ensureInitialized() at module load so
  the PSD2 consent audit event (ASVS V16 / GDPR Art.30) isn't dropped on a
  cold-start instance.

Dead-code sweep (all confirmed zero importers):
- delete lib/tax/calculator.ts, lib/salary/engangsskatt.ts (+test),
  lib/email/resend.ts, lib/salary/salary-transaction-matcher.ts,
  lib/webhooks/diff.ts, lib/salary/effective-values.ts,
  lib/bookkeeping/template-prompt.ts
- trim unused lib/vat/eu-countries.ts helpers (keep EU_COUNTRIES)
- remove dead getAutomaticStatus() and the abandoned Activepieces CSP entry

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(invoices): fail closed when a payment journal entry doesn't post

Three mark-paid paths (legacy route, v1 API, agent commit) diverged on the
"mark paid but the JE failed" case — two would flip the invoice to paid (or
leave an orphaned posted voucher) with no booking, silently diverging the GL
from the AR/AP sub-ledger. Unify on fail-closed:

- legacy + v1 + agent commitMarkInvoicePaid: never mark paid without a posted
  voucher; on a null/failed JE return INVOICE_PAID_BOOK_FAILED before any
  state mutation (v1 mirrors the match-invoice strict mode).
- agent path: add the .in('status',[...]).select('id') CAS guard and cancel
  the orphaned voucher (cancelOrphanedPaymentEntry) on a lost race or update
  error, matching the web route.
- legacy route: cancel the orphan on a non-race update error too (was only
  handled on the race branch).
- supplier mark-paid: stop swallowing a failed supplier_invoice_payments
  insert — that row drives the reversal amount in payment-sync; roll back the
  status flip and cancel the voucher instead.
- pending-ops orchestrator: error-check the terminal 'committed' write so an
  op stranded in 'committing' (the expire sweep only targets 'pending') is at
  least logged loudly.

Adds a guard test for the legacy fail-closed path. Full unit suite green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(ci): unblock core build + address compliance-review findings

- avgifter-basis.ts: fix the core-build TypeScript error — PostgREST's
  type-level select parser models the salary_run embed as an array, which
  wasn't assignable to the object-typed generic. Type it `unknown` (rows are
  read via an explicit cast), making it robust across postgrest-js versions.
- /api/events: add a non-null companyId guard before the event_log query
  (defense-in-depth for the API-key-bound scope) — addresses ASVS V8.2.1 /
  ISO A.5.15.
- supplier mark-paid: add a CAS guard (.eq('status', newStatus)) to the
  payment-insert-failure rollback so a concurrent settlement can't be
  clobbered — addresses ASVS V2.3.
- dispatcher: add an AAL2 regression test asserting a non-MFA session is
  rejected (403) and the extension handler never runs — addresses the
  GDPR Art.32 review ask for the single extension chokepoint.

Verified deletions are safe: effective-values.ts was a dead duplicate — the
live AGI/payslip path inlines the same `?? override` coalescing
(generate-declaration.ts), so AGI correctness is unaffected.

next build: exit 0. Full unit suite: 6147 passing. ESLint clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 14:34:23 +02:00

149 lines
4.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
/**
* Arbetsgivaravgiftsunderlag — Employer contribution basis report.
*
* Monthly breakdown by avgifter rate category:
* - Standard (31.42%)
* - Reduced 65+ (10.21%)
* - Youth (20.81%, Apr 2026–Sep 2027)
* - Växa-stöd (10.21%)
*
* Used for reconciling against AGI filings (Ruta 060-062)
* and verifying correct avgifter calculations per social-charges.md.
*
* Per BFL: Part of räkenskapsinformation, 7-year retention.
*/
export interface AvgifterBasisRow {
periodYear: number
periodMonth: number
category: string
categoryLabel: string
rate: number
basis: number // Underlag (sum of avgifter_basis for employees in this category)
amount: number // Avgift (basis × rate)
employeeCount: number
}
export interface AvgifterBasisReport {
rows: AvgifterBasisRow[]
totals: {
totalBasis: number
totalAmount: number
}
year: number
}
const CATEGORY_LABELS: Record<string, string> = {
standard: 'Standard (31,42%)',
reduced_65plus: 'Reducerad 67+ (10,21%)',
youth: 'Ungdomsrabatt (20,81%)',
vaxa_stod: 'Växa-stöd (10,21%)',
exempt: 'Undantagen (0%)',
}
/**
* Generate avgifter basis report for a year.
*/
export async function generateAvgifterBasis(
supabase: SupabaseClient,
companyId: string,
year: number
): Promise<AvgifterBasisReport> {
const r = (x: number) => Math.round(x * 100) / 100
// Load all salary run employees for booked runs this year.
// Paginated with a stable id order: a multi-year/high-headcount company can
// exceed PostgREST's 1000-row cap, and a silent truncation here would
// under-report the arbetsgivaravgifter basis reconciled against AGI filings.
const runEmployees = await fetchAllRows<{
id: string
avgifter_basis: number
avgifter_amount: number
avgifter_rate: number
// PostgREST's type-level select parser models an embedded resource as an
// array, so keep this `unknown` (the rows are read via an explicit cast
// below) to stay assignable regardless of postgrest-js version.
salary_run: unknown
}>(({ from, to }) =>
supabase
.from('salary_run_employees')
.select(`
id,
avgifter_basis,
avgifter_amount,
avgifter_rate,
salary_run:salary_runs!inner(period_year, period_month, status)
`)
.eq('company_id', companyId)
.order('id', { ascending: true })
.range(from, to)
, { dedupeBy: (e) => e.id })
// Filter to booked runs for the year
const bookedForYear = runEmployees.filter(sre => {
const run = sre.salary_run as unknown as { period_year: number; period_month: number; status: string } | null
return run && run.period_year === year && run.status === 'booked'
})
// Group by month + rate category
const grouped = new Map<string, {
periodYear: number
periodMonth: number
category: string
rate: number
basis: number
amount: number
count: number
}>()
for (const sre of bookedForYear) {
const run = sre.salary_run as unknown as { period_year: number; period_month: number }
const category = rateToCategory(sre.avgifter_rate)
const key = `${run.period_month}-${category}`
const current = grouped.get(key) || {
periodYear: year,
periodMonth: run.period_month,
category,
rate: sre.avgifter_rate,
basis: 0,
amount: 0,
count: 0,
}
current.basis += sre.avgifter_basis
current.amount += sre.avgifter_amount
current.count++
grouped.set(key, current)
}
const rows: AvgifterBasisRow[] = Array.from(grouped.values())
.map(g => ({
periodYear: g.periodYear,
periodMonth: g.periodMonth,
category: g.category,
categoryLabel: CATEGORY_LABELS[g.category] || g.category,
rate: g.rate,
basis: r(g.basis),
amount: r(g.amount),
employeeCount: g.count,
}))
.sort((a, b) => a.periodMonth - b.periodMonth || a.category.localeCompare(b.category))
const totals = {
totalBasis: r(rows.reduce((s, row) => s + row.basis, 0)),
totalAmount: r(rows.reduce((s, row) => s + row.amount, 0)),
}
return { rows, totals, year }
}
function rateToCategory(rate: number): string {
if (rate === 0) return 'exempt'
if (rate <= 0.1022) return 'reduced_65plus' // 10.21% ± rounding
if (rate <= 0.2082) return 'youth' // 20.81%
return 'standard' // 31.42%
}