Files
accounted/lib/salary/agi/generate-declaration.ts
T
MattssonandClaude Fable 5 f24b26a139 fix: similar-sweep currency remediation, security hardening and v1 API fixes (#1215)
* fix(security): gate replace_sie_import behind owner/admin membership

The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no
company_members lookup, no auth.uid() reference and no unauthorized raise,
while setting gnubok.allow_delete to disarm the BFL immutability and
retention triggers. Any caller holding a company_id and an import id could
hard delete another tenant's verifikationer. Confirmed live in production.

Applies the same fail closed owner/admin guard that undo_sie_import already
carries (migration 20260624120000), resolving the actor from
COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then
revokes EXECUTE from PUBLIC and anon. search_path and the raised
statement_timeout are restated, since CREATE OR REPLACE drops settings that
are not repeated.

userId is a required parameter on replaceSIEImport: the service client has a
NULL auth.uid(), so a caller without an explicit actor now fails to compile
rather than hitting the closed gate at runtime.

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

* fix(security): validate arcim OAuth callback state server side

The callback route is skipAuth and decoded the state parameter as plain
base64url JSON, trusting consentId and provider from it. A one time code was
minted at flow start and never read. An unauthenticated attacker who learned
a consent id could run an OAuth flow on their own provider account and post
the callback with a forged state, landing their tokens on another tenant's
consent, so the victim's next migration imported the attacker's ledger.

State is now an opaque randomBytes(32) pointer to a provider_otc row,
consumed by a single atomic UPDATE guarded on used_at IS NULL and
expires_at, so a replay loses the row lock race and updates nothing.
provider is read from provider_consents rather than trusted from the client.
provider_otc already existed for exactly this purpose and was never wired up.

Also scopes getConsent to an owning company, closing a cross tenant status
oracle where the preview and migrate paths echoed a consent's status before
the scoped check ran.

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

* fix(security): scope documents storage to company_id (phase A)

The documents bucket policies matched on auth.uid(), and upload keys were
documents/{userId}/..., so company membership was never consulted. Removing a
member revoked nothing: their session still authenticated and they kept
direct Storage read access to every receipt, supplier invoice and bank
statement they had uploaded. The same bug was fixed for sie-files in
20260416120000; this bucket was left behind.

Phase A is additive. Company scoped policies are added alongside the
uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and
reads accept either layout so nothing breaks mid migration. Phase C, which
drops the old policies, is gated on the backfill reporting zero remaining
legacy prefix objects.

The policy compares the company segment as text rather than casting to uuid
the way sie-files does: this bucket holds keys whose second segment is not a
uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix
qual runs before the cast, so a planner reordering would raise 22P02 and fail
the whole query instead of filtering the row out.

deleteDocument now removes both candidate keys. Removing only the stored
pointer would leave a readable orphan copy of a document the user asked to
erase.

The backfill script is included but has never been run. It defaults to dry
run, refuses .env.local by name, and verifies each copy is readable and
SHA-256 identical before repointing the row.

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

* fix(security): enforce events:read scope and membership on /api/events

This was the only one of the three validateApiKey call sites with no
downstream guard: v1 and the MCP server both check scope and re-verify
company membership, this route did neither. An events:read scope existed and
was documented as gating the endpoint but was never called, so a legacy key
falling back to DEFAULT_SCOPES read the full log. The bound company id went
straight from the api_keys row into a service role query, so a key whose user
had been removed from the company kept reading.

Adds the scope check before any database access, re-verifies company_members
with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead
of ignoring it, applies minimisePayload so the pull surface can never return
a wider payload than the push surface, and replaces the three flat error
strings with the canonical envelope.

Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is
gated on mutations in with-api-v1, so a read gets the same treatment as every
other v1 read endpoint.

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

* perf(bookkeeping): sweep remaining journal_entries!inner embeds

A previous refactor removed this pattern from lib/reports and introduced
fetchEntryLines, but the class was never swept. Seventeen sites remained and
had become the top application consumer of production database time:
measured across the resulting query shapes, 32,694 calls and 25,848 seconds
of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at
7,962ms against the 8s statement_timeout, which surfaced to users as 500s on
the booking path.

PostgREST compiles an embed with filters on the embedded side into a
correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops
Postgres reordering the join, so each query walked the whole
journal_entry_lines table across all tenants. Driving from the entries side
instead turns that into two indexed round trips.

Converted sites keep their existing shape: the helper reattaches the parent
entry under the same key the embed produced. Several conversions also remove
a latent silent truncation where an unpaginated query was capped at
PostgREST's 1000 row ceiling.

Two deliberate exceptions. The free text ilike legs of the MCP display query
stay on the embed, because each is capped at legLimit and that cap drives the
truncation contract the tool reports, while the helper is unbounded. The
accounts route moves to the existing get_account_usage_counts RPC instead,
since its embed was a head count and the helper returns rows.

commitEntry's write path is untouched: the change there is confined to the
read query of the pre-commit dimension rule check.

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

* fix(api): anchor v1 list cursors on created_at

Page two returned page one, forever, while still advertising a fresh
next_cursor. The three routes sorted by and encoded a Postgres date column,
which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor
timestamp as full ISO-8601 and returned null, so the keyset filter was never
applied and has_more never went false. An integrator syncing verifikat looped
on the newest rows indefinitely.

The transactions route already solved this and its comment names the trap;
the fix was never ported. All three now order and encode on created_at with
an id tie break, matching the transactions keyset predicate exactly.
ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change
sort semantics on the route that currently works.

Default ordering therefore moves from business date to insert order. Every
business date is still on the row, and the invoices list gains date_from and
date_to filters so a date range is still reachable; the other two already had
them.

The tests use an in-memory PostgREST that actually evaluates the filters,
because the repo's pass-through mock cannot catch this class of bug: the bug
is that the filter is never sent. They walk to exhaustion with a hard
iteration cap, so an unterminated walk fails instead of hanging.

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

* fix(api): separate dry run from commit in the idempotency hash

The request hash was built from url.pathname, which excludes the query
string, so a dry run and its commit hashed identically. Following the flow
documented in dry-run.ts, re-issuing the request with the same
Idempotency-Key returned the cached preview with Idempotent-Replayed set and
wrote nothing, while reporting 200. An agent or integrator saw success for a
write that never happened.

dry_run is folded into the hash only when true, not as an unconditional
boolean. Including it as false would change the hash of every ordinary write,
and with a 24h idempotency TTL any key in flight across the deploy would fail
the request_hash comparison and 409 on a legitimate retry. Both hash call
sites now go through one shared helper so they cannot drift into a permanent
cache miss, and dry run responses are no longer stored at all.

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

* ci: install the Bedrock SDK out of tree in the compliance review

The Swedish accounting compliance gate had failed ten consecutive runs and so
was posting nothing. With --no-package-lock npm discarded the lockfile and
re-resolved the whole tree from package.json, floating @hookform/resolvers to
5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0.

Installing into the parent of the checkout resolves only that one package, so
an unrelated peer conflict can never take the gate down again. Node still
finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH
would not have worked, as it is CommonJS only. --legacy-peer-deps was
rejected because it masks future genuine peer conflicts and still reifies the
full tree.

The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that
package.json and check:guards enforce after the streaming outage. That drift
went unnoticed because the pin guard only inspects package.json and the
lockfile, never workflow files.

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

* build(docker): generate crontabs from vercel.json

vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were
byte identical to each other. Self hosted deployments therefore never sent
recurring invoices, never dispatched webhooks and never cleaned up
idempotency keys. tax-deadlines also ran once a year on 2 January instead of
daily, and documents/verify weekly instead of daily.

Extension crons are included rather than excluded. The Dockerfile copies the
whole tree before building, so every extension cron route is compiled into
the image regardless of the enabled preset, and each returns 200 when its
extension is unconfigured, so curl -sf logs no failure. Two such entries were
already present in the crontab for extensions absent from the preset, which
settles the intent.

documents/verify is treated as drift rather than a self hosted concession:
the weekly cadence was present in the hosted crontab too, and the run is
capped at 200 documents walking a nulls-first queue, so weekly drains the
integrity queue seven times slower on a check that exists for BFL retention.

webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day
on self hosted. A gentler tick would silently stretch the first retry, since
the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line
place to change that.

A parity test asserts the path sets match minus a documented exclusion list,
and ratchets three cron routes that are currently scheduled nowhere so they
are named rather than silently rotting.

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

* chore(observability): add a provider agnostic error sink

There is no error tracking in this codebase: logs go to console and Vercel
retention and nowhere else, nothing alerts on the 16 cron jobs, and seven
code comments across lib, app, components and extensions asserted that Sentry
captures errors when Sentry is not a dependency. The two most recent bug
fixes on this repo were both discovered by customer email.

This adds the sink, not a vendor. No dependency is taken: the interface has a
no-op default and a registration point, so behaviour is unchanged until an
adapter is registered. Releases are tagged from the build id already inlined
by next.config.ts.

Redaction moved out of lib/logger.ts into a leaf module that both the logger
and the sink import, so there is one denylist and no path from application
data to a third party can skip the personnummer regex, including direct sink
calls that bypass the logger. That matters here because these logs carry
personnummer and financial data.

verifyCronSecret now reports its own 401s, which covers all 16 jobs without
touching a route file and catches the case where CRON_SECRET is rotated
without updating the scheduler and every job silently 401s forever. The
threshold is one failure rather than the backup alert's three: suppressing
the first occurrence is precisely how an outage stays invisible.

The seven misleading comments are corrected to describe what the code
actually does, including the two cases that still are not covered: the client
side one, since the sink is server side, and a warn level call that is not
forwarded.

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

* fix: remediate the 2026-07-26 similar-sweep findings across all surfaces

Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with
one agent per finding; every behavioural fix carries a regression test proven
to fail at HEAD. Full status, corrections to the sweep, refusals and open
decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md.

Structural roots closed:
- resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking
  1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING
- ledger-line-amount.ts: journal_entry_lines.currency labels the document,
  not the amount; SQL pre-filter decoy proven and fixed
- sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the
  exploitable salary payslip-line PATCH and KPI preferences sinks fixed
- tests/schema: migration-replay phantom-column guard (13k+ refs, closed
  CHECK sets, onConflict targets); found 28 real defects, all fixed, all
  four baselines now empty
- three new ratchet guards: sek-labelled-amount, cross-extension-import,
  ungated-extension-route

Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap),
RC input VAT mismatch wired on web + both MCP callers, missing-underlag
resource delegates to the shared RPC predicate, push-notifications consent
polarity fail-closed, deadlines undo honours requested state, silent-failure
and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/
Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites
with isSwedishUserMessage extended.

Also includes the parallel session's MCP invoice tools (update_invoice,
recurring schedules, invoice deliveries) which share files with the sweep
work and are verified green together.

13 new migrations are NOT applied anywhere; they apply via branch merge.
20260726120000 backfills 1247 supplier-invoice rows. pg tests for new
DDL are written but unrun (no local Postgres).

Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0
errors, check:guards passing, MCP payload 57475/57500.

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

* fix(migrations): rename replace_sie_import migration off main's 20260726090000 version

origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping
our replace_sie_import migration on the same version would abort the Supabase
apply with a schema_migrations_pkey duplicate at merge time.

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

* fix(review): remediate pre-publish deep-review findings across all slices

A 13-agent review of the full branch diff surfaced 1 critical, 5 high and
~45 further findings; this commit resolves them in one pass:

- replace_sie_import / undo_sie_import: p_user_id honored only for
  service_role callers; any other caller is pinned to auth.uid()
  (impersonation gate bypass), authz raise errcode 42501 mapped to a
  Swedish 403 in the route, new caller-guard migration for undo
- bulk_book_transactions refuses homogeneous non-SEK batches instead of
  writing foreign magnitudes into SEK ledger columns
- credit-note cap trigger: company-match on credited_invoice_id, no
  cross-tenant figures in exception text
- link_voucher RPCs resolve NULL invoice currency as SEK end to end
- personal-number ciphertext CHECK split into NOT VALID + VALIDATE
- same-currency foreign settlements clear 1510 at booking rate and book
  realized diff to 3960/7960; rate-less foreign write paths refuse
- receivables revaluation covers partially_paid and outstanding amounts
- period lock guard paginates candidates past the PostgREST 1000 cap
- documents: service-client storage removals after authz, dual-layout
  reads in integrity cron and archive export, backfill delete-source
  sweep actually deletes with hash verification and shared-key grouping
- invoice matching normalizes NULL/lowercase currencies (regression),
  duplicate candidates stop claiming amount matches they never ran
- match-invoice aborts on any booking failure (no paid-without-verifikat)
- refresh-exchange-rate reverts on concurrent booking (TOCTOU window)
- KPI preferences upsert arbiter aligned to the company-scoped constraint
- personnummer_last4 stripped from all salary responses incl. MCP tools
- worked-hours batch restores destroyed rows on conflict and error paths
- MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit
  on tag_journal_lines overflow, auto_send schedules stage as high risk
- observability sink redacts emails/IBANs/API keys and keeps redacted
  stacks in prod; assorted small guards (safe-return-to /@, dry_run=True,
  cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings
  call removed)

Full dispositions, deferred items and hand-verified accounting numbers
are documented in the PR body and DECISIONS.md.

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

* feat(personnummer): implement masking and encryption for personal numbers with tests

* fix(review): address CI and compliance-bot findings for PR #1215

pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role
GUC, so both service-role simulations (runAsServiceRole and the
invoice-delivery test's local helper) never satisfied auth.role() =
'service_role' and every legitimate p_user_id path failed closed; the
shared helper now sets both GUC shapes plus SET LOCAL ROLE with a
fail-loud sanity check, and the delivery test reuses it. The link-voucher
migration had recreated both RPCs from pre-rewrite file text,
reintroducing the NULL-unsafe membership pattern the
null-safe-tenant-guards ratchet bans; both guards now use
public.caller_is_company_member() with all currency changes preserved.

Compliance bots: the customers export now emits the standard masked form
instead of raw AES-256-GCM ciphertext in the Org-/personnummer column,
and maskCustomerRow returns a non-round-trippable placeholder on decrypt
failure instead of 500ing the list. MCP parity: gnubok_lock_period's
staging pre-check now runs the exact countUnbookedInPeriod the commit
path enforces (exported from period-service; local mirror deleted), and
gnubok_agi_status resolves AGI state run-scoped so a correction run no
longer renders as already filed.

Declined with evidence: PR-Agent's opening-balances null-zeroing concern
(all mergeable columns are NOT NULL with defaults per 20260713101000).

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

* fix(review): address codex review findings on PR #1215

- restore 20260726140000 to its preview-recorded content and restate the
  NULL-safe tenant guard under 20260727130000: a recorded migration version
  never re-runs, so the in-place edit could not reach the preview branch
- replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap
  warning texts and update the pinned test expectations
- drop the em dash in the fiscal-periods route comment
- strip trailing whitespace in import-existing.test.ts

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

* test(reports): raise timeout on real PDF render tests

renderToBuffer does real @react-pdf layout work and exceeds the 5s
default when the full suite saturates the CPU; tests pass in isolation.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 03:34:56 +02:00

691 lines
27 KiB
TypeScript

/**
* Shared AGI XML generation + persistence orchestration.
*
* Both the internal dashboard route (`GET /api/salary/runs/{id}/agi/xml`)
* and the v1 public route (`POST /api/v1/companies/{companyId}/salary-runs/{id}/generate-agi`)
* call this helper. It loads the salary run + employees + per-day absence
* records, builds the Skatteverket AGI XML, upserts the agi_declarations
* row (correction-aware), updates `salary_runs.agi_generated_at`, emits
* `agi.generated`, and auto-completes the `arbetsgivardeklaration` deadline
* for the period.
*
* Returns a discriminated result so callers can wrap it in their own
* response envelope (internal uses raw `Response`; v1 uses the JSON `ok`
* envelope with `xml` embedded as a string field).
*
* Per agi-filing.md:
* - FK570 (specifikationsnummer) MUST stay consistent per employee
* - Corrections resubmit with same FK570: a different number = a new record
* - XML is räkenskapsinformation; stored for 7-year retention per BFL 7 kap
* - Filing deadline: the 12th of the following month (17th in Jan/Aug for
* companies ≤ 40 MSEK turnover)
*/
import type { SupabaseClient } from '@supabase/supabase-js'
import { z } from 'zod'
import {
generateAGIXml,
buildIndividuppgifterSnapshot,
AGIIncompleteDataError,
AGIPayloadTooLargeError,
} from './xml-generator'
import type { AGIEmployeeData, AGICompanyData, AGITotals } from './xml-generator'
import { eventBus } from '@/lib/events'
import type { Logger } from '@/lib/logger'
// Strict runtime validation of the joined salary_run_employees row. Without
// this, columns added by recent migrations (removed_from_agi,
// benefits_adjusted, vaxa_stod_eligible, employment_start,
// housing_benefit_type) reaching the mapper as null/undefined would silently
// fall back to Boolean(undefined) = false and mis-emit regulatory flags.
// Zod produces an explicit error instead.
const EmployeeJoinSchema = z
.object({
personnummer: z.string().min(1, 'employee.personnummer saknas'),
specification_number: z.number().int().min(1, 'employee.specification_number måste vara ≥ 1'),
f_skatt_status: z.string(),
monthly_salary: z.number().nullable().optional(),
vaxa_stod_eligible: z.boolean().nullable().optional(),
employment_start: z.string().nullable().optional(),
housing_benefit_type: z.enum(['smahus', 'ej_smahus']).nullable().optional(),
})
.passthrough()
const LineItemSchema = z
.object({
item_type: z.string(),
amount: z.number().nullable().optional(),
quantity: z.number().nullable().optional(),
})
.passthrough()
const SalaryRunEmployeeRowSchema = z
.object({
employee_id: z.string().uuid(),
// Per-run snapshot of the monthly salary (authoritative for this run; the
// engine reads it, not the employee master). Used for the FK499
// sjuklönekostnad daily-rate below.
monthly_salary: z.number().nullable().optional(),
gross_salary: z.number(),
tax_withheld: z.number(),
tax_withheld_override: z.number().nullable().optional(),
avgifter_basis: z.number(),
avgifter_basis_override: z.number().nullable().optional(),
avgifter_amount: z.number(),
avgifter_amount_override: z.number().nullable().optional(),
avgifter_rate: z.number(),
avgifter_category: z.string().nullable().optional(),
removed_from_agi: z.boolean().nullable().optional(),
benefits_adjusted: z.boolean().nullable().optional(),
sick_days: z.number().nullable().optional(),
vab_days: z.number().nullable().optional(),
parental_days: z.number().nullable().optional(),
employee: EmployeeJoinSchema.nullable(),
line_items: z.array(LineItemSchema).nullable().optional(),
})
.passthrough()
type SalaryRunEmployeeRow = z.infer<typeof SalaryRunEmployeeRowSchema>
const ELIGIBLE_STATUSES = ['review', 'approved', 'paid', 'booked', 'corrected'] as const
export interface GenerateAgiDeclarationArgs {
supabase: SupabaseClient
companyId: string
userId: string
/** Falls back into AGI contactEmail when company_settings + profile both have none. */
userEmail: string | null
salaryRunId: string
log: Logger
requestId: string
}
export type GenerateAgiDeclarationResult =
| {
ok: true
xml: string
agiDeclarationId: string
periodYear: number
periodMonth: number
employeeCount: number
isCorrection: boolean
totals: AGITotals
orgNumber: string
}
| {
ok: false
code: string
details?: unknown
status?: number
}
function sumLineItemAmounts(
lineItems: Array<Record<string, unknown>>,
types: string[],
): number {
return lineItems
.filter((li) => types.includes(li.item_type as string))
.reduce((sum, li) => sum + ((li.amount as number) || 0), 0)
}
export async function generateAgiDeclaration(
args: GenerateAgiDeclarationArgs,
): Promise<GenerateAgiDeclarationResult> {
const { supabase, companyId, userId, userEmail, salaryRunId, log, requestId } = args
const opLog = log.child({ salaryRunId })
// 1. Run + status precheck.
const { data: run, error: runError } = await supabase
.from('salary_runs')
.select('*')
.eq('id', salaryRunId)
.eq('company_id', companyId)
.single()
if (runError || !run) {
return { ok: false, code: 'SALARY_RUN_NOT_FOUND' }
}
if (!ELIGIBLE_STATUSES.includes((run.status as typeof ELIGIBLE_STATUSES[number]))) {
return {
ok: false,
code: 'AGI_GENERATE_NOT_BOOKABLE',
details: { current_status: run.status, eligible_statuses: ELIGIBLE_STATUSES },
}
}
// 2. Company + settings + profile (for contact info).
const { data: company } = await supabase
.from('companies')
.select('name, org_number')
.eq('id', companyId)
.single()
if (!company) {
return { ok: false, code: 'COMPANY_NOT_FOUND' }
}
const { data: settings } = await supabase
.from('company_settings')
.select('company_name, org_number, phone, email')
.eq('company_id', companyId)
.single()
const { data: profile } = await supabase
.from('profiles')
.select('full_name, email')
.eq('id', userId)
.single()
// 3. Roster + line items + per-day absence.
const { data: runEmployees } = await supabase
.from('salary_run_employees')
.select(
'*, employee:employees(personnummer, specification_number, f_skatt_status, monthly_salary, vaxa_stod_eligible, employment_start, housing_benefit_type), line_items:salary_line_items(*)',
)
.eq('salary_run_id', salaryRunId)
// An empty roster is valid: a registered employer must file a
// nolldeklaration (HU-only, no individuppgifter) for months without payroll.
// Only a genuine query failure (null) is treated as an error here.
if (!runEmployees) {
return { ok: false, code: 'SALARY_RUN_NO_EMPLOYEES' }
}
// 4. Build AGI input shapes.
// Employer name on the arbetsgivardeklaration follows the current company
// name (company_settings.company_name), not the frozen onboarding companies.name.
const companyName = settings?.company_name || company.name
const companyData: AGICompanyData = {
orgNumber: (settings?.org_number || company.org_number || '').trim(),
companyName,
periodYear: run.period_year,
periodMonth: run.period_month,
contactName: (profile?.full_name || companyName || '').trim(),
contactPhone: (settings?.phone || '').trim(),
contactEmail: (settings?.email || profile?.email || userEmail || '').trim(),
}
// Load per-day absence (VAB + parental only: sick days go to FK separately).
const periodStart = `${run.period_year}-${String(run.period_month).padStart(2, '0')}-01`
const periodEndDate = new Date(Date.UTC(run.period_year, run.period_month, 0))
const periodEnd = periodEndDate.toISOString().slice(0, 10)
const employeeIds = (runEmployees as Array<{ employee_id: string }>)
.map((sre) => sre.employee_id)
.filter(Boolean)
const absenceByEmployee = new Map<
string,
Array<{
date: string
type: 'vab' | 'parental'
hours: number
specifikationsnummer: number
}>
>()
if (employeeIds.length > 0) {
const { data: absenceRows } = await supabase
.from('salary_absence_days')
.select('employee_id, absence_date, absence_type, hours, franvaro_specifikationsnummer')
.eq('company_id', companyId)
.in('absence_type', ['vab', 'parental'])
.gte('absence_date', periodStart)
.lte('absence_date', periodEnd)
.in('employee_id', employeeIds)
for (const row of (absenceRows ?? []) as Array<{
employee_id: string
absence_date: string
absence_type: 'vab' | 'parental'
hours: number
franvaro_specifikationsnummer: number | null
}>) {
// Row should always have a number for vab/parental (trigger assigns
// on insert + backfill migration covers existing data). Defensive
// fallback: skip rows missing the number rather than emit a bogus 0,
// which would collide with Skatteverket's unique key.
if (row.franvaro_specifikationsnummer == null) continue
const list = absenceByEmployee.get(row.employee_id) ?? []
list.push({
date: row.absence_date,
type: row.absence_type,
hours: Number(row.hours ?? 8),
specifikationsnummer: row.franvaro_specifikationsnummer,
})
absenceByEmployee.set(row.employee_id, list)
}
}
// Validate the joined rows up-front so a malformed Supabase response
// (missing column, wrong type, null specification_number, …) surfaces as
// a clean AGIIncompleteDataError instead of silently emitting wrong
// flags later. See SalaryRunEmployeeRowSchema definition above.
const parsedRows: SalaryRunEmployeeRow[] = (runEmployees as unknown[]).map((raw, idx) => {
const parsed = SalaryRunEmployeeRowSchema.safeParse(raw)
if (!parsed.success) {
const fields = parsed.error.issues.map((iss) => iss.path.join('.')).join(', ')
throw new AGIIncompleteDataError(
`salary_run_employees rad ${idx} har ogiltig form (saknar/felaktiga fält: ${fields}). ` +
'Detta blockerar AGI-generering eftersom Skatteverket annars skulle få bogus värden ' +
'(till exempel emitterade flaggor eller specifikationsnummer = 0).',
['salary_run_employees'],
)
}
return parsed.data
})
// Cutoff for the Växa-stöd FK062/FK063 split: pre-2024-05-01 hires get the
// legacy "första anställda"-flag (FK062); 2024-05-01 and later get the
// utvidgat växa-stöd flag (FK063). Cutoff from Skatteverket spec (Prop.
// 2023/24:80, RAML revisionshistorik 1.19).
const VAXA_STOD_FK063_CUTOFF = '2024-05-01'
const employeeData: AGIEmployeeData[] = parsedRows.map((sre) => {
const emp = sre.employee
const lineItems = (sre.line_items ?? []) as Array<{ item_type: string; amount?: number | null; quantity?: number | null }>
const benefitCar = sumLineItemAmounts(lineItems, ['benefit_car'])
const benefitFuel = sumLineItemAmounts(lineItems, ['benefit_fuel'])
const benefitHousing = sumLineItemAmounts(lineItems, ['benefit_housing'])
// FK015 kostförmån has its own field: never fold into FK012.
// Skatteverket cross-checks the krona-amount against the PBB-schablon.
const benefitMeals = sumLineItemAmounts(lineItems, ['benefit_meals'])
// FK012 SkatteplOvrigaFormanerUlagAG is the catch-all for taxable
// benefits without their own FK code (bike, wellness, "other") PLUS
// the krona-amount for housing (since FK041/FK043 carry only the flag).
const benefitOther = sumLineItemAmounts(lineItems, [
'benefit_bike',
'benefit_wellness',
'benefit_other',
]) + benefitHousing
// Default housing type: if the employee got a housing benefit line
// item but no housing_benefit_type is set, treat as 'ej_smahus' (the
// more common case). NULL with no benefit line item → no flag emitted.
let housingBenefit: 'smahus' | 'ej_smahus' | undefined
if (benefitHousing > 0) {
housingBenefit = emp?.housing_benefit_type ?? 'ej_smahus'
}
const absenceEvents = absenceByEmployee.get(sre.employee_id)
let vaxaStod: 'forsta_anstalld' | 'vaxa_stod' | undefined
if (emp?.vaxa_stod_eligible) {
vaxaStod =
emp.employment_start && emp.employment_start < VAXA_STOD_FK063_CUTOFF
? 'forsta_anstalld'
: 'vaxa_stod'
}
// Växa-stöd (employment-start-gated relief, 10.21 % avgifter) and the
// ungdomsrabatt (age-gated relief, 'youth' avgifter_category) are
// distinct statutory programs and must not be claimed for the same
// employee in the same period. Catching this at generation time
// avoids emitting an FK062/FK063 flag inconsistent with the FK061
// category total.
if (vaxaStod && sre.avgifter_category === 'youth') {
throw new AGIIncompleteDataError(
`Anställd ${emp?.specification_number ?? '?'}: kan inte kombinera växa-stöd ` +
'(FK062/FK063) med ungdomsrabatt (avgifter_category="youth"): programmen är ömsesidigt uteslutande. ' +
'Välj ett av dem under anställdas inställningar.',
['vaxa_stod_eligible', 'avgifter_category'],
)
}
const isFSkatt = emp?.f_skatt_status === 'f_skatt'
// Honor advanced-mode per-employee overrides set during review.
const effectiveTax = sre.tax_withheld_override ?? sre.tax_withheld
const effectiveAvgifterBasis = sre.avgifter_basis_override ?? sre.avgifter_basis
return {
personnummer: emp?.personnummer ?? '',
specificationNumber: emp?.specification_number ?? 0,
removed: Boolean(sre.removed_from_agi),
grossSalary: sre.gross_salary,
taxWithheld: effectiveTax,
avgifterBasis: effectiveAvgifterBasis,
fSkattPayment: isFSkatt ? sre.gross_salary : undefined,
// F-skatt payees: cash goes to FK131 and benefits to the ej-UlagSA
// variants (FK132/FK133/FK134/FK137/FK138/FK139). Regular employees
// get FK011 + FK012/FK013/FK015/FK018/FK041/FK043.
benefitsExcludedFromSAUnderlag: isFSkatt ? true : undefined,
benefitCar: benefitCar > 0 ? benefitCar : undefined,
benefitFuel: benefitFuel > 0 ? benefitFuel : undefined,
benefitMeals: benefitMeals > 0 ? benefitMeals : undefined,
housingBenefit,
benefitOther: benefitOther > 0 ? benefitOther : undefined,
benefitsAdjusted: Boolean(sre.benefits_adjusted),
vaxaStod,
sickDays: (sre.sick_days ?? 0) > 0 ? (sre.sick_days ?? 0) : undefined,
vabDays: (sre.vab_days ?? 0) > 0 ? (sre.vab_days ?? 0) : undefined,
parentalDays:
(sre.parental_days ?? 0) > 0 ? (sre.parental_days ?? 0) : undefined,
absenceEvents: absenceEvents && absenceEvents.length > 0 ? absenceEvents : undefined,
}
},
)
// Drop individuppgifter with nothing to report. An employee who took 0 kr
// and had no benefits, tax or absence this month is simply omitted (you
// only file an IU for a person who received something). This yields a clean
// HU-only nolldeklaration for a full nollkörning, and omits zero-paid
// employees in a mixed run. Borttag (removed) tombstones are always kept.
.filter(
(e) =>
e.removed === true ||
(e.grossSalary ?? 0) > 0 ||
(e.taxWithheld ?? 0) > 0 ||
(e.fSkattPayment ?? 0) > 0 ||
(e.benefitCar ?? 0) > 0 ||
(e.benefitFuel ?? 0) > 0 ||
(e.benefitMeals ?? 0) > 0 ||
(e.benefitOther ?? 0) > 0 ||
e.housingBenefit !== undefined ||
(e.sickDays ?? 0) > 0 ||
(e.vabDays ?? 0) > 0 ||
(e.parentalDays ?? 0) > 0 ||
(e.absenceEvents?.length ?? 0) > 0,
)
// 5. Build totals: avgifter by category (with rate-heuristic fallback for legacy runs).
// Removed-from-AGI rows (FK205 borttag) are tombstones: they must not
// contribute to FK497/FK487/FK499 because the prior submission's amounts
// remain on file at Skatteverket; the borttag just removes the IU itself.
const activeEmployees = parsedRows.filter((sre) => !sre.removed_from_agi)
const avgifterByCategory: AGITotals['avgifterByCategory'] = {}
for (const sre of activeEmployees) {
const dbCategory = sre.avgifter_category ?? null
const category = dbCategory
? dbCategory === 'reduced_65plus'
? 'reduced65plus'
: dbCategory === 'vaxa_stod'
? 'standard'
: dbCategory
: sre.avgifter_rate <= 0.1022
? 'reduced65plus'
: sre.avgifter_rate <= 0.2082
? 'youth'
: 'standard'
const cat = (avgifterByCategory as Record<string, { basis: number; amount: number }>)[
category
] || { basis: 0, amount: 0 }
cat.basis += sre.avgifter_basis_override ?? sre.avgifter_basis
cat.amount += sre.avgifter_amount_override ?? sre.avgifter_amount
;(avgifterByCategory as Record<string, { basis: number; amount: number }>)[category] = cat
}
const totalAvgifterAmount = Object.values(avgifterByCategory).reduce(
(sum, cat) => sum + (cat?.amount ?? 0),
0,
)
// FK499 sjuklönekostnad: sum of paid sjuklön (days 2-14) across all
// employees. Day 1 is karens (unpaid); day 15+ is Försäkringskassan.
const calcParams = ((run.calculation_params as Record<string, unknown>) ?? {}) as {
sjuklonRate?: number
sjuklon_rate?: number
}
const sjuklonRate = calcParams.sjuklonRate ?? calcParams.sjuklon_rate ?? 0.8
let totalSjuklonekostnad = 0
for (const sre of activeEmployees) {
const monthly = sre.monthly_salary ?? 0
if (!monthly) continue
const dailyRate = monthly / 21
const lineItems = (sre.line_items ?? []) as Array<{ item_type: string; amount?: number | null; quantity?: number | null }>
for (const li of lineItems) {
if (li.item_type === 'sick_day2_14') {
const days = li.quantity ?? 0
totalSjuklonekostnad += dailyRate * sjuklonRate * days
}
}
}
// FK497 SummaSkatteavdr must equal the sum of FK001 on active IUs (not
// run.total_tax, which includes removed rows). Same for FK487.
// Coalesce override → computed so manual jämkning/FoU adjustments flow
// into the filed declaration.
const totalTax = activeEmployees.reduce(
(sum, sre) => sum + ((sre.tax_withheld_override ?? sre.tax_withheld) || 0),
0,
)
const totals: AGITotals = {
totalTax: Math.round(totalTax * 100) / 100,
totalAvgifterBasis: activeEmployees.reduce(
(s, e) => s + ((e.avgifter_basis_override ?? e.avgifter_basis) || 0),
0,
),
totalAvgifterAmount: Math.round(totalAvgifterAmount * 100) / 100,
totalSjuklonekostnad: Math.round(totalSjuklonekostnad * 100) / 100,
avgifterByCategory,
}
// Soft AGI deadline check: warn (but don't block) when generating for a
// future period or one whose Skatteverket correction window is clearly
// past. Filing deadline is the 12th (17th in Jan/Aug for small employers)
// of the month after the period; SKV accepts corrections for a long time
// after, but a period > 13 months in the past is almost certainly a
// misclick. Surface via the logger so it lands in the audit log. These are
// warn-level and carry no alert flag, so they do not reach the observability
// sink (lib/observability); they are a breadcrumb, not a page.
{
const now = new Date()
const currentYM = now.getUTCFullYear() * 100 + (now.getUTCMonth() + 1)
const periodYM = run.period_year * 100 + run.period_month
if (periodYM > currentYM) {
opLog.warn('AGI generated for future period', {
companyId,
periodYear: run.period_year,
periodMonth: run.period_month,
})
} else if (currentYM - periodYM > 13) {
opLog.warn('AGI generated for period > 13 months past', {
companyId,
periodYear: run.period_year,
periodMonth: run.period_month,
})
}
}
// 6. Existing AGI determines correction status. Use `.maybeSingle()`
// because the lookup must tolerate the no-row case without throwing:
// that's the FIRST-time generation path. `.single()` would surface a
// PGRST116 row-not-found error and abort what should be a clean insert.
const { data: existingAgi } = await supabase
.from('agi_declarations')
.select('id')
.eq('company_id', companyId)
.eq('period_year', run.period_year)
.eq('period_month', run.period_month)
.maybeSingle()
const isCorrection = !!existingAgi
// 7. Generate XML.
let xml: string
try {
xml = generateAGIXml(companyData, employeeData, totals, isCorrection)
} catch (err) {
if (err instanceof AGIIncompleteDataError) {
return {
ok: false,
code: 'AGI_INCOMPLETE_DATA',
details: { missing_fields: err.missingFields, message: err.message },
}
}
if (err instanceof AGIPayloadTooLargeError) {
return {
ok: false,
code: 'AGI_PAYLOAD_TOO_LARGE',
details: {
message: err.message,
size_bytes: err.sizeBytes,
limit_bytes: err.limitBytes,
},
status: 413,
}
}
throw err
}
const individuppgifter = buildIndividuppgifterSnapshot(employeeData)
// 8. UPSERT agi_declarations.
let agiDeclarationId: string
if (existingAgi) {
const { error: updErr } = await supabase
.from('agi_declarations')
.update({
xml_content: xml,
individuppgifter,
total_gross: run.total_gross,
total_tax: run.total_tax,
total_avgifter_basis: totals.totalAvgifterBasis,
// Use the per-category sum that drives the XML rather than the
// run-level denormalised total. Both should agree, but a
// round-then-sum vs sum-then-round can produce öre drift; the
// agi_declarations row should align with what was actually
// serialised into the XML (which Skatteverket sees).
total_avgifter: totals.totalAvgifterAmount,
employee_count: employeeData.length,
is_correction: true,
salary_run_id: run.id,
})
.eq('id', existingAgi.id)
if (updErr) {
return { ok: false, code: 'DATABASE_ERROR', details: updErr }
}
agiDeclarationId = existingAgi.id as string
} else {
const { data: inserted, error: insErr } = await supabase
.from('agi_declarations')
.insert({
company_id: companyId,
user_id: userId,
salary_run_id: run.id,
period_year: run.period_year,
period_month: run.period_month,
xml_content: xml,
individuppgifter,
total_gross: run.total_gross,
total_tax: run.total_tax,
total_avgifter_basis: totals.totalAvgifterBasis,
// Use the per-category sum that drives the XML rather than the
// run-level denormalised total. Both should agree, but a
// round-then-sum vs sum-then-round can produce öre drift; the
// agi_declarations row should align with what was actually
// serialised into the XML (which Skatteverket sees).
total_avgifter: totals.totalAvgifterAmount,
employee_count: employeeData.length,
})
.select('id')
.single()
if (insErr) {
// Concurrent-call race: two :generate-agi requests for the same
// (company, period) reached the INSERT branch simultaneously. The
// earlier read of `existingAgi` returned null for both, but the
// first INSERT wins and the second hits the unique constraint.
// Postgres error 23505 is the unique-violation code; recover by
// re-fetching the now-existing row and treating this call as a
// correction (the second caller's XML supersedes the first).
if ((insErr as { code?: string }).code === '23505') {
const { data: nowExisting, error: refetchErr } = await supabase
.from('agi_declarations')
.select('id')
.eq('company_id', companyId)
.eq('period_year', run.period_year)
.eq('period_month', run.period_month)
.maybeSingle()
if (refetchErr || !nowExisting) {
return { ok: false, code: 'DATABASE_ERROR', details: refetchErr || insErr }
}
const { error: raceUpdErr } = await supabase
.from('agi_declarations')
.update({
xml_content: xml,
individuppgifter,
total_gross: run.total_gross,
total_tax: run.total_tax,
total_avgifter_basis: totals.totalAvgifterBasis,
// Use the per-category sum that drives the XML rather than the
// run-level denormalised total. Both should agree, but a
// round-then-sum vs sum-then-round can produce öre drift; the
// agi_declarations row should align with what was actually
// serialised into the XML (which Skatteverket sees).
total_avgifter: totals.totalAvgifterAmount,
employee_count: employeeData.length,
is_correction: true,
salary_run_id: run.id,
})
.eq('id', nowExisting.id)
if (raceUpdErr) {
return { ok: false, code: 'DATABASE_ERROR', details: raceUpdErr }
}
agiDeclarationId = nowExisting.id as string
opLog.warn('agi_declarations insert raced; recovered via update', {
companyId,
periodYear: run.period_year,
periodMonth: run.period_month,
})
// Note: the caller-facing `isCorrection` flag (set above based on
// the pre-INSERT existingAgi lookup) reports `false` even though
// the database state is now technically a correction. Edge case
// limited to the race window; the agi_declarations row is
// correctly marked is_correction=true and the next call will
// see it.
} else {
return { ok: false, code: 'DATABASE_ERROR', details: insErr }
}
} else if (!inserted) {
return { ok: false, code: 'DATABASE_ERROR', details: insErr }
} else {
agiDeclarationId = inserted.id as string
}
}
// 9. Stamp generation timestamp on salary_runs.
await supabase
.from('salary_runs')
.update({ agi_generated_at: new Date().toISOString() })
.eq('id', salaryRunId)
// 10. Emit agi.generated (best-effort: never block the success path).
try {
await eventBus.emit({
type: 'agi.generated',
payload: {
agiId: agiDeclarationId,
periodYear: run.period_year,
periodMonth: run.period_month,
userId,
companyId,
},
})
} catch (err) {
opLog.warn('agi.generated emit failed', err as Error)
}
// NOTE: generating the XML deliberately does NOT complete the
// arbetsgivardeklaration deadline. SFL 26 kap. deems the obligation
// satisfied only when the declaration has come in to Skatteverket; the
// Skatteverket extension confirms the deadline on kvittens receipt
// (agi-kvittens-reconcile), and manual filers tick it off themselves.
// Completing here made a generated-but-never-filed AGI silently sail
// past its statutory date.
opLog.info('AGI declaration generated', {
requestId,
salaryRunId,
agiDeclarationId,
isCorrection,
employeeCount: employeeData.length,
})
return {
ok: true,
xml,
agiDeclarationId,
periodYear: run.period_year,
periodMonth: run.period_month,
employeeCount: employeeData.length,
isCorrection,
totals,
orgNumber: companyData.orgNumber,
}
}