Files
accounted/lib/tax/__tests__/deadline-generator.test.ts
T
Jakob WennbergandClaude Opus 4.8 5ac560ce41 fix: generate tax deadlines for the installed base + correct 2893 label carryover (#1029)
* fix(bookkeeping): refresh correction line description on account change

When editing an ändringsverifikation, CorrectionEntryDialog pre-filled each
line's description from the original entry but never re-derived it when the
user changed the account, so a description carried over from the old account
(e.g. 2393 "Lån från närstående personer, långfristig del") stayed stale on
the newly chosen account (e.g. 2893, the kortfristig account). The regular
JournalEntryForm already auto-fills on account change; this mirrors it.

The refresh is guarded: it only overwrites the description when it is empty or
still equals the previously selected account's name, so a memo the user typed
themselves is preserved. Logic is extracted into a pure, unit-tested helper.

Note: the wrong text on an already-posted correction cannot be repaired (line
descriptions of posted verifikat are immutable per BFL / migration 017); this
prevents recurrence on future corrections.

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

* fix(deadlines): generate tax deadlines for the installed base

Automatic tax deadlines only regenerated when a tax-relevant settings field
changed value (didTaxFieldsChange). Companies fill those fields once at
onboarding, so a later save changed nothing and generated nothing; the annual
cron was the only unconditional trigger. As a result only ~5 of ~776 real
companies had any system deadlines, and the /deadlines empty state told users
to "check the tax settings" that were already complete.

- Settings save now also regenerates when the company has zero system
  deadlines yet (safe first-time backfill; cannot reset is_completed/status).
  Decision extracted into shouldRegenerateTaxDeadlines() with tests.
- The empty-state banner gets a "Generera nu" action wired to the existing
  /api/tax-deadlines/generate route (previously it had no caller). New sv/en
  strings.
- generateNewYearDeadlines (annual cron) paginates company_settings via
  fetchAllRows: a plain .select() silently caps at 1000 rows, leaving
  companies beyond the cap without next-year deadlines.
- scripts/backfill-tax-deadlines.ts: one-off that reruns the real generator
  for non-sandbox companies with zero system deadlines.

Known gap (follow-up): moms_period='yearly' has no deadline config, so annual
VAT filers get no momsdeklaration deadline yet.

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

* fix(deadlines): address review feedback + fix settings-route test

- settings/route.ts: fail safe when the system-deadline count query errors.
  A null count on error was treated as 0, which would trigger a
  delete+regenerate and reset is_completed/status on a transient failure;
  now a count error keeps the self-heal off (CodeRabbit, Major).
- Update app/api/settings/__tests__/route.test.ts (added on main via the
  withRouteContext refactor) for the extra deadline-count query and the new
  shouldRegenerateTaxDeadlines export; add self-heal / no-regen cases.
- Soften the "no deadlines created" copy: zero generated rows can also mean
  no applicable obligations (or the moms_yearly gap), not just incomplete
  settings (CodeRabbit, Minor).

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-07-16 15:55:41 +02:00

132 lines
4.4 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { generateTaxDeadlinesForUser, shouldRegenerateTaxDeadlines } from '../deadline-generator'
import type { CompanySettingsForDeadlines } from '../deadline-config'
const SETTINGS: CompanySettingsForDeadlines = {
entity_type: 'aktiebolag',
moms_period: 'monthly',
f_skatt: true,
vat_registered: true,
pays_salaries: true,
fiscal_year_start_month: 1,
}
// Future year so generated dates are never skipped as "in the past".
const FUTURE_YEAR = new Date().getFullYear() + 1
/**
* Recording mock: captures the order of insert/delete operations and the
* insert payload, so the tests can assert the insert-first/delete-after
* ordering that prevents regeneration failures from wiping deadlines.
*/
function makeRecordingSupabase(opts: { insertError?: { code: string; message: string } } = {}) {
const calls: string[] = []
let insertPayload: Array<Record<string, unknown>> | null = null
const from = vi.fn(() => {
const chain: Record<string, ReturnType<typeof vi.fn>> = {}
const self = () => chain
chain.insert = vi.fn((rows: Array<Record<string, unknown>>) => {
calls.push('insert')
insertPayload = rows
return {
select: vi.fn(async () =>
opts.insertError
? { data: null, error: opts.insertError }
: { data: rows.map((_, i) => ({ id: `new-${i}` })), error: null }
),
}
})
chain.delete = vi.fn(() => {
calls.push('delete')
return chain
})
chain.eq = vi.fn(self)
chain.gte = vi.fn(self)
chain.lte = vi.fn(self)
chain.not = vi.fn((...args: unknown[]) => {
calls.push(`not(${String(args[2]).slice(0, 20)}…)`)
return chain
})
chain.select = vi.fn(async () => ({ data: [{ id: 'old-1' }, { id: 'old-2' }], error: null }))
return chain
})
return {
supabase: { from } as unknown as SupabaseClient,
calls,
getInsertPayload: () => insertPayload,
}
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('generateTaxDeadlinesForUser', () => {
it('inserts replacement rows before deleting the old set', async () => {
const { supabase, calls } = makeRecordingSupabase()
const result = await generateTaxDeadlinesForUser(supabase, 'company-1', SETTINGS, [FUTURE_YEAR])
expect(calls[0]).toBe('insert')
expect(calls[1]).toBe('delete')
expect(result.created).toBeGreaterThan(0)
expect(result.deleted).toBe(2)
})
it('excludes the newly inserted rows from the delete', async () => {
const { supabase, calls } = makeRecordingSupabase()
await generateTaxDeadlinesForUser(supabase, 'company-1', SETTINGS, [FUTURE_YEAR])
expect(calls.some((c) => c.startsWith('not('))).toBe(true)
})
it('builds rows owned by company_id, without a user_id field', async () => {
const { supabase, getInsertPayload } = makeRecordingSupabase()
await generateTaxDeadlinesForUser(supabase, 'company-1', SETTINGS, [FUTURE_YEAR])
const rows = getInsertPayload()
expect(rows).not.toBeNull()
for (const row of rows!) {
expect(row.company_id).toBe('company-1')
expect('user_id' in row).toBe(false)
expect(row.source).toBe('system')
expect(row.is_auto_generated).toBe(true)
}
})
it('does not delete existing deadlines when the insert fails', async () => {
const { supabase, calls } = makeRecordingSupabase({
insertError: { code: '23502', message: 'null value in column "user_id"' },
})
await expect(
generateTaxDeadlinesForUser(supabase, 'company-1', SETTINGS, [FUTURE_YEAR])
).rejects.toMatchObject({ code: '23502' })
expect(calls).toContain('insert')
expect(calls).not.toContain('delete')
})
})
describe('shouldRegenerateTaxDeadlines', () => {
it('regenerates when a tax-relevant field changed', () => {
expect(shouldRegenerateTaxDeadlines(true, 42)).toBe(true)
})
it('regenerates when the company has no system deadlines yet, even with no field change', () => {
// The reported bug: settings were filled at onboarding, so a later save with
// no tax-field change never generated deadlines and the page stayed empty.
expect(shouldRegenerateTaxDeadlines(false, 0)).toBe(true)
})
it('does not regenerate when nothing changed and deadlines already exist', () => {
// Avoid clobbering existing status/progress on unrelated settings saves.
expect(shouldRegenerateTaxDeadlines(false, 12)).toBe(false)
})
})