Files
accounted/app/api/settings/__tests__/route.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

265 lines
8.9 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
const { supabase, enqueue, enqueueMany, reset } = createQueuedMockSupabase()
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 requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/tax/deadline-generator', () => ({
didTaxFieldsChange: vi.fn().mockReturnValue(false),
regenerateTaxDeadlinesForUser: vi.fn().mockResolvedValue(undefined),
shouldRegenerateTaxDeadlines: vi.fn(
(changed: boolean, count: number) => changed || count === 0,
),
}))
import { PUT } from '../route'
import { regenerateTaxDeadlinesForUser } from '@/lib/tax/deadline-generator'
describe('PUT /api/settings', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: { company_name: 'New Name' },
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(401)
})
it('returns 403 for a viewer without write permission', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: { company_name: 'New Name' },
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(403)
})
it('updates the settings on the happy path', async () => {
enqueueMany([
{ data: { entity_type: 'enskild_firma', onboarding_complete: false } }, // fetch oldSettings
{ data: { id: 's1', company_name: 'New Name' } }, // update ... returning
{ data: null, count: 5 }, // deadlines count (has some -> no regen)
])
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: { company_name: 'New Name' },
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: { company_name: string } }>(response)
expect(status).toBe(200)
expect(body.data.company_name).toBe('New Name')
})
it('updates all three reminder thresholds', async () => {
enqueueMany([
{
data: {
entity_type: 'aktiebolag',
onboarding_complete: true,
reminder_days_level_1: 15,
reminder_days_level_2: 30,
reminder_days_level_3: 45,
},
},
{
data: {
id: 's1',
reminder_days_level_1: 7,
reminder_days_level_2: 21,
reminder_days_level_3: 35,
},
},
{ data: null, count: 5 }, // deadlines count (has some -> no regen)
])
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: {
reminder_days_level_1: 7,
reminder_days_level_2: 21,
reminder_days_level_3: 35,
},
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{
data: { reminder_days_level_1: number; reminder_days_level_2: number; reminder_days_level_3: number }
}>(response)
expect(status).toBe(200)
expect(body.data).toMatchObject({
reminder_days_level_1: 7,
reminder_days_level_2: 21,
reminder_days_level_3: 35,
})
})
it('regenerates tax deadlines when the company has none yet (self-heal)', async () => {
enqueueMany([
{ data: { entity_type: 'aktiebolag', onboarding_complete: true } }, // oldSettings
{
data: {
id: 's1',
entity_type: 'aktiebolag',
moms_period: 'quarterly',
f_skatt: true,
vat_registered: true,
pays_salaries: true,
fiscal_year_start_month: 1,
},
}, // update
{ data: null, count: 0 }, // no system deadlines -> self-heal generation
])
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: { f_skatt: true },
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(vi.mocked(regenerateTaxDeadlinesForUser)).toHaveBeenCalledOnce()
})
it('does not regenerate tax deadlines when the company already has some', async () => {
enqueueMany([
{ data: { entity_type: 'aktiebolag', onboarding_complete: true } }, // oldSettings
{ data: { id: 's1', entity_type: 'aktiebolag' } }, // update
{ data: null, count: 12 }, // already has deadlines
])
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: { company_name: 'Unchanged Tax' },
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(vi.mocked(regenerateTaxDeadlinesForUser)).not.toHaveBeenCalled()
})
it('returns 400 when reminder thresholds are not increasing', async () => {
enqueue({
data: {
reminder_days_level_1: 15,
reminder_days_level_2: 30,
reminder_days_level_3: 45,
},
})
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: {
reminder_days_level_1: 30,
reminder_days_level_2: 20,
reminder_days_level_3: 45,
},
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
expect(supabase.from).toHaveBeenCalledTimes(1)
})
it('returns 404 when the settings row does not exist', async () => {
enqueueMany([
{ data: { onboarding_complete: false } },
{ data: null, error: { code: 'PGRST116', message: 'No rows returned' } },
])
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: { reminder_days_level_1: 10 },
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(404)
})
it('blocks a vacation-year basis change while open balances exist', async () => {
enqueueMany([
{ data: { salary_vacation_year_basis: 'calendar', onboarding_complete: true } }, // oldSettings
{ data: null, count: 2 }, // open-rows count
])
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: { salary_vacation_year_basis: 'statutory_apr_mar' },
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
// The guard consumed the count result and the update never ran.
expect(supabase.from.mock.calls.map(([table]) => table)).toEqual([
'company_settings',
'employee_vacation_balances',
])
})
it('fails closed when the open-balances guard query errors', async () => {
enqueueMany([
{ data: { salary_vacation_year_basis: 'calendar', onboarding_complete: true } }, // oldSettings
{ data: null, count: null, error: { message: 'connection reset' } }, // guard query fails
])
const request = createMockRequest('/api/settings', {
method: 'PUT',
body: { salary_vacation_year_basis: 'statutory_apr_mar' },
})
const response = await PUT(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(500)
// The 500 must come from the guard, not from company_settings.update()
// swallowing the queued error: the guard query ran and no second
// company_settings query followed it.
expect(supabase.from.mock.calls.map(([table]) => table)).toEqual([
'company_settings',
'employee_vacation_balances',
])
})
})