feat(deadlines): årsstämma replaces bokslut + moms_yearly auto-complete + EU-sales suggestion (#1059)

* 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>

* feat(deadlines): statutory arsstamma replaces bokslut, moms_yearly auto-complete, EU-sales suggestion

- Replace the non-statutory 'bokslut' deadline (3 months after FY end, no
  legal basis, off-by-one month math for broken FYs) with the statutory
  arsstamma deadline: within 6 months of FY end per ABL 7 kap. 10 par.,
  the corporate act that gates the arsredovisning filing chain. Migration
  deletes pending bokslut rows; the backfill cron generates arsstamma rows.
- Complete moms_yearly on Skatteverket submission/kvittens: the yearly
  branch previously returned null with a stale comment claiming annual VAT
  has no deadline type, leaving yearly filers with an eternally open row.
  The fiscal-year tax_period label is derived from company settings.
- Add /api/settings/eu-trade-signal + a tax-settings callout: companies
  with booked EU sales (3108/3308/3107, last 15 months) but EU-trade/PS
  flags off are prompted to confirm the periodisk sammanstallning
  obligation (SFL 35 kap., 1 250 kr late fee per report). Suggestion only,
  never auto-enables.

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 17:02:49 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent da4d5a39ae
commit 05b954ac1d
17 changed files with 297 additions and 45 deletions
@@ -217,6 +217,25 @@ describe('VAT kvittenser cron', () => {
)
})
it('yearly picker params complete the moms_yearly deadline with the fiscal-year label', async () => {
mockCreateClient.mockReturnValueOnce(
stubHappyTables({ ...LOCKED_STATE, periodType: 'yearly', period: 12 }),
)
mockSkvRequest.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ kvittensnummer: 'KV-999' }),
} as any)
await GET(makeRequest())
// Calendar FY (company_settings unstubbed → default start month 1):
// the moms_yearly tax_period is the plain year label.
expect(mockCompleteTaxDeadline).toHaveBeenCalledWith(
expect.anything(), 'comp-1', ['moms_yearly'], '2026', 'confirmed',
)
})
it('legacy state without picker params still flips status but skips the deadline', async () => {
const { periodType: _pt, year: _y, period: _p, ...legacyState } = LOCKED_STATE
mockCreateClient.mockReturnValueOnce(stubHappyTables(legacyState))
@@ -192,20 +192,30 @@ export async function GET(request: Request) {
// carries the picker params (written by the one-click chain; states
// persisted by the older step-by-step routes lack them).
if (state.periodType && state.year && state.period) {
const taxPeriod =
state.periodType === 'monthly'
? `${state.year}-${String(state.period).padStart(2, '0')}`
: state.periodType === 'quarterly'
? `${state.year}-Q${state.period}`
: null
let taxPeriod: string | null = null
let deadlineTypes: ('moms_monthly' | 'moms_quarterly' | 'moms_yearly')[] = [
'moms_monthly',
'moms_quarterly',
]
if (state.periodType === 'monthly') {
taxPeriod = `${state.year}-${String(state.period).padStart(2, '0')}`
} else if (state.periodType === 'quarterly') {
taxPeriod = `${state.year}-Q${state.period}`
} else if (state.periodType === 'yearly') {
// moms_yearly rows carry the generator's fiscal-year label:
// `YYYY` for calendar FYs, `YYYY-1/YYYY` for broken ones.
const { data: fySettings } = await supabase
.from('company_settings')
.select('fiscal_year_start_month')
.eq('company_id', companyId)
.maybeSingle()
const startMonth = fySettings?.fiscal_year_start_month ?? 1
const yearNum = Number(state.year)
taxPeriod = startMonth === 1 ? `${yearNum}` : `${yearNum - 1}/${yearNum}`
deadlineTypes = ['moms_yearly']
}
if (taxPeriod) {
await completeTaxDeadline(
supabase,
companyId,
['moms_monthly', 'moms_quarterly'],
taxPeriod,
'confirmed'
)
await completeTaxDeadline(supabase, companyId, deadlineTypes, taxPeriod, 'confirmed')
}
}
@@ -0,0 +1,61 @@
/**
* Tests for /api/settings/eu-trade-signal — ledger-derived EU sales signal.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const fetchEntryLinesMock = vi.fn()
vi.mock('@/lib/bookkeeping/entry-lines', () => ({
fetchEntryLines: (...args: unknown[]) => fetchEntryLinesMock(...args),
}))
import { GET } from '../route'
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/settings/eu-trade-signal', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/api/settings/eu-trade-signal'), {})
expect(res.status).toBe(401)
})
it('reports EU sales when the ledger has postings on the PS accounts', async () => {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: {}, error: null })
fetchEntryLinesMock.mockResolvedValue([{ account_number: '3308' }])
const { status, body } = await parseJsonResponse<{ data: { has_eu_sales: boolean } }>(
await GET(createMockRequest('/api/settings/eu-trade-signal'), {})
)
expect(status).toBe(200)
expect(body.data.has_eu_sales).toBe(true)
})
it('reports no EU sales for an empty result', async () => {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: {}, error: null })
fetchEntryLinesMock.mockResolvedValue([])
const { status, body } = await parseJsonResponse<{ data: { has_eu_sales: boolean } }>(
await GET(createMockRequest('/api/settings/eu-trade-signal'), {})
)
expect(status).toBe(200)
expect(body.data.has_eu_sales).toBe(false)
})
})
+43
View File
@@ -0,0 +1,43 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
/**
* Accounts whose postings indicate EU B2B sales: 3108 goods, 3308 services,
* 3107 triangulation. Same set the periodisk sammanställning report keys on.
*/
const EU_SALES_ACCOUNTS = ['3108', '3308', '3107']
/** How far back to look for EU sales postings. */
const LOOKBACK_MONTHS = 15
/**
* GET /api/settings/eu-trade-signal
*
* Derived suggestion signal for the tax settings page: companies with EU
* sales in the ledger have a statutory periodisk sammanställning obligation
* (SFL 35 kap.), but the driving settings flags are opt-in and easily left
* off. The settings UI uses this to prompt the user to confirm EU trade and
* PS registration; it never flips the flags itself.
*/
export const GET = withRouteContext(
'settings.eu_trade_signal',
async (_request, { supabase, companyId }) => {
const since = new Date()
since.setMonth(since.getMonth() - LOOKBACK_MONTHS)
const sinceStr = since.toISOString().split('T')[0]
const lines = await fetchEntryLines<{ account_number: string }>({
supabase,
lineColumns: 'account_number',
filterEntries: (q: EntryLinesQuery) =>
q
.eq('company_id', companyId)
.in('status', ['posted', 'reversed'])
.gte('entry_date', sinceStr),
filterLines: (q: EntryLinesQuery) => q.in('account_number', EU_SALES_ACCOUNTS),
})
return NextResponse.json({ data: { has_eu_sales: lines.length > 0 } })
},
)