feat(deadlines): gate AGI on employer registration + stop completing AGI at XML generation (#1062)

* feat(deadlines): gate F-skatt reminders on debited preliminary tax, add durable dismissal

The f_skatt deadline was gated on the F-skatt approval flag (DB default
true), giving nearly every company 12 monthly payment reminders for a tax
Skatteverket may not have debited at all (64% of all system deadline rows,
one lifetime completion). Approval carries no recurring obligation; the
monthly duty is payment of debiterad preliminarskatt and exists only while
the debited amount is > 0 (SFL 62 kap. 4-5 par., 55 kap. 2 par.).

- Gate the f_skatt deadline on preliminary_tax_monthly > 0 (field already
  collected at onboarding, previously unread) and retitle it as a payment.
- Storforetag keep the 12th in August (January-only 17th, 62 kap. 3 par.).
- Declare the prod-only preliminary_tax_monthly column in a migration so
  installs built purely from migrations stop failing tax-settings saves.
- Add deadlines.dismissed_at: DELETE on a system deadline now soft-dismisses
  it durably (hard deletes were resurrected by the nightly backfill within
  24h); generator, backfill, and every read surface respect it.
- Prune upcoming f_skatt rows for companies with no debited amount.

Closes part of #1028.

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

* feat(deadlines): gate AGI on employer registration, stop completing AGI deadline at XML generation

The arbetsgivardeklaration deadline was gated on pays_salaries, which is
wrong in both directions: a registered employer must file AGI every month
including nil months (SFL 26 kap. 3 par.), and companies actively running
payroll with the flag off got no AGI reminders at all (each missed monthly
filing risks a forseningsavgift).

- New company_settings.employer_registered (nullable, no default) gates
  AGI and the storforetag skatteinbetalning row; pays_salaries remains a
  fallback for rows saved before the flag existed and keeps its UI meaning.
- Migration backfills employer_registered=true from pays_salaries=true and
  from actual payroll activity (salary_runs).
- New employer_seasonal flag: sasongsregistrerade file only for payment
  months plus a December nil declaration, so only the December-period row
  is generated.
- Settings UI: registration + seasonal checkboxes (sv/en strings).
- AGI XML generation no longer auto-completes the deadline as submitted:
  SFL 26 kap. deems the obligation satisfied only when the declaration has
  come in to Skatteverket. The Skatteverket extension's kvittens reconcile
  remains the confirming path; manual filers tick the deadline themselves.

Part of #1028.

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

* fix(deadlines): include dismissed_at in DeadlineForm payload

The Deadline type gained the required dismissed_at field; the form's
submit payload literal must carry it for the Omit<Deadline, ...> shape.

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

* fix(deadlines): make system-deadline dismissal atomic

Constrain the dismiss update to source='system' and verify a row was
actually updated: a concurrent regeneration can delete the row between
lookup and update, and the route must not report a phantom success.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-07-17 16:04:05 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 3c0bf3f584
commit da4d5a39ae
14 changed files with 183 additions and 21 deletions
+2
View File
@@ -1467,6 +1467,8 @@ export const UpdateSettingsSchema = z.object({
tax_contact_email: z.string().email().nullable().optional().or(z.literal('')),
fiscal_year_start_month: z.number().int().min(1).max(12).optional(),
preliminary_tax_monthly: z.number().nullable().optional(),
employer_registered: z.boolean().nullable().optional(),
employer_seasonal: z.boolean().optional(),
bank_name: z.string().max(100, 'Banknamn får vara max 100 tecken').optional(),
clearing_number: z.string().regex(/^\d{4,5}$/, 'Clearingnummer måste vara 4-5 siffror').optional().or(z.literal('')),
account_number: z.string().regex(/^\d{6,12}$/, 'Kontonummer måste vara 6-12 siffror').optional().or(z.literal('')),
+7 -12
View File
@@ -31,7 +31,6 @@ import {
} from './xml-generator'
import type { AGIEmployeeData, AGICompanyData, AGITotals } from './xml-generator'
import { eventBus } from '@/lib/events'
import { completeTaxDeadline } from '@/lib/deadlines/complete-tax-deadline'
import type { Logger } from '@/lib/logger'
// Strict runtime validation of the joined salary_run_employees row. Without
@@ -659,17 +658,13 @@ export async function generateAgiDeclaration(
opLog.warn('agi.generated emit failed', err as Error)
}
// 11. Auto-complete the arbetsgivardeklaration deadline for this period
// (Skatteförfarandelagen: AGI generation satisfies the filing
// obligation).
const period = `${run.period_year}-${String(run.period_month).padStart(2, '0')}`
await completeTaxDeadline(
supabase,
companyId,
['arbetsgivardeklaration'],
period,
'submitted'
)
// 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,
+33
View File
@@ -14,6 +14,8 @@ function makeSettings(overrides: Partial<CompanySettingsForDeadlines> = {}): Com
preliminary_tax_monthly: 5000,
vat_registered: true,
pays_salaries: false,
employer_registered: null,
employer_seasonal: false,
fiscal_year_start_month: 1,
vat_taxable_base_over_40m: false,
vat_has_eu_trade: false,
@@ -102,6 +104,27 @@ describe('monthly tax and employer deadlines', () => {
expect(dates[7].day).toBe(12)
})
it('gates AGI on employer registration with pays_salaries as legacy fallback', () => {
const config = getConfig('arbetsgivardeklaration')
// Never attested: fall back to pays_salaries.
expect(config.condition(makeSettings({ pays_salaries: true }))).toBe(true)
expect(config.condition(makeSettings({ pays_salaries: false }))).toBe(false)
// Attested registration wins over pays_salaries in both directions: a
// registered employer must file monthly even with zero salaries.
expect(config.condition(makeSettings({ employer_registered: true }))).toBe(true)
expect(config.condition(makeSettings({ employer_registered: false, pays_salaries: true }))).toBe(false)
})
it('generates only the December-period AGI row for seasonal employers', () => {
const dates = getConfig('arbetsgivardeklaration').generateDates(2026, makeSettings({
employer_registered: true,
employer_seasonal: true,
}))
expect(dates).toHaveLength(1)
// December period, declared 17 January the following year.
expect(dates[0]).toMatchObject({ day: 17, month: 0, year: 2027, period: '2026-12' })
})
it('uses the 26th for AGI when the VAT taxable base is above SEK 40 million', () => {
const dates = getConfig('arbetsgivardeklaration').generateDates(2026, makeSettings({
pays_salaries: true,
@@ -137,6 +160,16 @@ describe('storföretag tax payment deadline', () => {
pays_salaries: true,
vat_taxable_base_over_40m: true,
}))).toBe(true)
// Same registration gate as AGI: attested registration wins.
expect(config.condition(makeSettings({
employer_registered: true,
vat_taxable_base_over_40m: true,
}))).toBe(true)
expect(config.condition(makeSettings({
employer_registered: false,
pays_salaries: true,
vat_taxable_base_over_40m: true,
}))).toBe(false)
})
it('is due the 12th of the following month, the 17th in January', () => {
@@ -15,6 +15,8 @@ const SETTINGS: CompanySettingsForDeadlines = {
preliminary_tax_monthly: 5000,
vat_registered: true,
pays_salaries: true,
employer_registered: null,
employer_seasonal: false,
fiscal_year_start_month: 1,
vat_taxable_base_over_40m: false,
vat_has_eu_trade: false,
+17 -5
View File
@@ -16,6 +16,10 @@ export interface CompanySettingsForDeadlines {
preliminary_tax_monthly: number | null
vat_registered: boolean
pays_salaries: boolean
// null = never attested; the generator falls back to pays_salaries so
// rows saved before the registration flag existed keep their deadlines.
employer_registered: boolean | null
employer_seasonal: boolean
fiscal_year_start_month: number // 1-12
vat_taxable_base_over_40m: boolean
vat_has_eu_trade: boolean
@@ -211,8 +215,14 @@ export const TAX_DEADLINE_CONFIGS: TaxDeadlineConfig[] = [
},
},
// Arbetsgivardeklaration (monthly, any employer with employees: AB or EF)
// Per Skatteförfarandelagen: every employer paying salary must file AGI monthly.
// Arbetsgivardeklaration (monthly). A REGISTERED employer must file AGI
// every month, including nil months (SFL 26 kap. 3 §): the gate is
// registration, not whether salaries were paid, with pays_salaries as a
// fallback for settings saved before the registration flag existed.
// Säsongsregistrerade employers file only for months with payments plus a
// December nil declaration when nothing was paid all year, so they get
// only the December-period row; payment months are handled by the salary
// flow itself.
// The filing day is keyed to the VAT taxable base, not a separate employer
// measure (SFL 26 kap.): above SEK 40M the whole skattedeklaration (AGI and
// VAT) is due the 26th of the following month; otherwise the 12th (17th in
@@ -221,14 +231,15 @@ export const TAX_DEADLINE_CONFIGS: TaxDeadlineConfig[] = [
{
type: 'arbetsgivardeklaration',
titleTemplate: 'Arbetsgivardeklaration {periodLabel}',
description: 'Arbetsgivardeklaration för arbetsgivare med anställda',
condition: (s) => s.pays_salaries,
description: 'Arbetsgivardeklaration för registrerade arbetsgivare',
condition: (s) => s.employer_registered ?? s.pays_salaries,
priority: 'important',
linkedReportType: null,
generateDates: (year, settings) => {
const storforetag = settings.vat_registered && settings.vat_taxable_base_over_40m
const instances: DeadlineInstance[] = []
for (let month = 0; month < 12; month++) {
if (settings.employer_seasonal && month !== 11) continue
const deadlineMonth = (month + 1) % 12
const deadlineYear = month === 11 ? year + 1 : year
const day = storforetag
@@ -255,7 +266,8 @@ export const TAX_DEADLINE_CONFIGS: TaxDeadlineConfig[] = [
type: 'skatteinbetalning',
titleTemplate: 'Betala skatt och arbetsgivaravgifter {periodLabel}',
description: 'Inbetalning av avdragen skatt och arbetsgivaravgifter för företag med beskattningsunderlag över 40 miljoner kronor',
condition: (s) => s.pays_salaries && s.vat_registered && s.vat_taxable_base_over_40m,
condition: (s) =>
(s.employer_registered ?? s.pays_salaries) && s.vat_registered && s.vat_taxable_base_over_40m,
priority: 'important',
linkedReportType: null,
generateDates: (year) => {
+5 -1
View File
@@ -25,6 +25,8 @@ export const TAX_RELEVANT_FIELDS = [
'preliminary_tax_monthly',
'vat_registered',
'pays_salaries',
'employer_registered',
'employer_seasonal',
'fiscal_year_start_month',
'vat_taxable_base_over_40m',
'vat_has_eu_trade',
@@ -35,7 +37,7 @@ export const TAX_RELEVANT_FIELDS = [
] as const
export const DEADLINE_SETTINGS_SELECT =
'company_id, entity_type, moms_period, f_skatt, preliminary_tax_monthly, vat_registered, pays_salaries, fiscal_year_start_month, vat_taxable_base_over_40m, vat_has_eu_trade, vat_filing_method, periodisk_sammanstallning_enabled, periodisk_sammanstallning_period, periodisk_sammanstallning_filing_method' as const
'company_id, entity_type, moms_period, f_skatt, preliminary_tax_monthly, vat_registered, pays_salaries, employer_registered, employer_seasonal, fiscal_year_start_month, vat_taxable_base_over_40m, vat_has_eu_trade, vat_filing_method, periodisk_sammanstallning_enabled, periodisk_sammanstallning_period, periodisk_sammanstallning_filing_method' as const
/**
* Check if any tax-relevant fields changed
@@ -70,6 +72,8 @@ export function toDeadlineSettings(
preliminary_tax_monthly: settings.preliminary_tax_monthly ?? null,
vat_registered: settings.vat_registered ?? false,
pays_salaries: settings.pays_salaries ?? false,
employer_registered: settings.employer_registered ?? null,
employer_seasonal: settings.employer_seasonal ?? false,
fiscal_year_start_month: settings.fiscal_year_start_month ?? 1,
vat_taxable_base_over_40m: settings.vat_taxable_base_over_40m ?? false,
vat_has_eu_trade: settings.vat_has_eu_trade ?? false,