Files
accounted/app/api/deadlines/[id]/__tests__/route.test.ts
T
Jakob WennbergandClaude Fable 5 3c0bf3f584 feat(deadlines): gate F-skatt reminders on debited preliminary tax + durable dismissal (#1057)
* 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>

* 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>
2026-07-17 15:48:25 +02:00

157 lines
5.5 KiB
TypeScript

/**
* Tests for /api/deadlines/[id] — validated PUT and count-checked DELETE.
*/
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 requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { PUT, DELETE } from '../route'
const idParams = { params: Promise.resolve({ id: 'deadline-1' }) }
function createCapturingSupabase(
results: { data?: unknown; error?: unknown; count?: number | null }[]
) {
let idx = 0
const makeBuilder = () => {
const result = results[idx++] ?? { data: null, error: null, count: null }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const b: any = {}
for (const m of ['select', 'eq', 'update', 'delete', 'single', 'maybeSingle']) {
b[m] = () => b
}
b.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null, count: result.count ?? null })
return b
}
return { from: () => makeBuilder() }
}
beforeEach(() => {
vi.clearAllMocks()
requireWriteMock.mockResolvedValue({ ok: true })
})
function auth(supabase: unknown) {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
}
describe('PUT /api/deadlines/[id]', () => {
it('rejects a malformed body (bad due_date) with 400', async () => {
auth(createCapturingSupabase([]))
const req = createMockRequest('/api/deadlines/deadline-1', {
method: 'PUT',
body: { due_date: 'banana' },
})
const { status } = await parseJsonResponse(await PUT(req, idParams))
expect(status).toBe(400)
})
it('rejects an empty body with 400', async () => {
auth(createCapturingSupabase([]))
const req = createMockRequest('/api/deadlines/deadline-1', { method: 'PUT', body: {} })
const { status } = await parseJsonResponse(await PUT(req, idParams))
expect(status).toBe(400)
})
it('maps zero-rows to 404', async () => {
auth(createCapturingSupabase([{ error: { code: 'PGRST116', message: 'no rows' } }]))
const req = createMockRequest('/api/deadlines/deadline-1', {
method: 'PUT',
body: { title: 'Momsdeklaration Q3' },
})
const { status } = await parseJsonResponse(await PUT(req, idParams))
expect(status).toBe(404)
})
it('updates the deadline', async () => {
auth(createCapturingSupabase([{ data: { id: 'deadline-1', title: 'Momsdeklaration Q3' } }]))
const req = createMockRequest('/api/deadlines/deadline-1', {
method: 'PUT',
body: { title: 'Momsdeklaration Q3' },
})
const { status, body } = await parseJsonResponse<{ data: { title: string } }>(
await PUT(req, idParams)
)
expect(status).toBe(200)
expect(body.data.title).toBe('Momsdeklaration Q3')
})
})
describe('DELETE /api/deadlines/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
expect(res.status).toBe(401)
})
it('returns 404 instead of phantom success when no row matches', async () => {
// First result: the source lookup finds nothing.
auth(createCapturingSupabase([{ data: null }]))
const { status } = await parseJsonResponse(
await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
)
expect(status).toBe(404)
})
it('hard-deletes a user-created deadline', async () => {
auth(createCapturingSupabase([
{ data: { id: 'deadline-1', source: 'user' } },
{ count: 1 },
]))
const { status, body } = await parseJsonResponse<{ success: boolean; dismissed?: boolean }>(
await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.dismissed).toBeUndefined()
})
it('dismisses a system deadline instead of deleting it', async () => {
// A hard-deleted system row is recreated by the nightly backfill cron;
// the route must soft-dismiss so the opt-out is durable.
auth(createCapturingSupabase([
{ data: { id: 'deadline-1', source: 'system' } },
{ data: [{ id: 'deadline-1' }] },
]))
const { status, body } = await parseJsonResponse<{ success: boolean; dismissed?: boolean }>(
await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.dismissed).toBe(true)
})
it('returns 404 when the system row vanished before the dismissal landed', async () => {
// Concurrent regeneration can delete the row between lookup and update;
// a phantom "dismissed" success would persist nothing.
auth(createCapturingSupabase([
{ data: { id: 'deadline-1', source: 'system' } },
{ data: [] },
]))
const { status } = await parseJsonResponse(
await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
)
expect(status).toBe(404)
})
})