* feat(vat): book the momsrapport as an editable settlement verifikat (#980) Adds a "Bokfor momsrapporten" card under the VAT declaration that builds an editable verifikat proposal from the report and books it through the ordinary journal entry form: - lib/reports/vat-settlement.ts: proposal builder. Clears each 26xx account at exact ore, books the net on 2650 (att betala) or 1650 (att aterfa) at the filed whole-krona amount (buildFiledAmounts, oretal faller bort per SFL 22 kap 1 par), balances the gap on 3740. Surfaces existing vat_settlement entries in the period so the UI can warn before a double booking. - GET /api/reports/vat-declaration/settlement-proposal: same period params as the sibling report routes. - VatBookingCard (reports view): fetches the proposal, warns when the period already has a posted settlement or draft, and opens the JournalEntryForm (bare, prefilled, source_type vat_settlement) in a dialog so every line is editable before committing. Booking uses the existing engine path: balance validation, period locks, voucher series per source type. - vat_settlement entries are excluded from the declaration projection (calculateVatDeclaration via new shared fetchVatAccountTotals, and the MCP computeVatReport for parity): a pure-projection report would otherwise read zero, and a later Skatteverket submission would file zeros, the moment the settlement is booked. No migration needed: the vat_settlement source type shipped in 20260708100000. Closes #980 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(vat): block re-booking a settled period, fail loud on lookup errors (CodeRabbit) The proposal is not delta-aware (it re-clears the FULL period), so a second booking while a posted settlement exists would corrupt the 26xx balances: disable "Skapa verifikat" until that verifikat is annulled (storno restores the balances). And since the existing-settlement lookup now gates that button, a swallowed query error would silently re-enable it: throw instead. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
5d7127a38a
commit
2774e01258
@@ -0,0 +1,140 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
const mockSupabase = {
|
||||
auth: { getUser: vi.fn() },
|
||||
from: vi.fn(),
|
||||
}
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/reports/vat-settlement', () => ({
|
||||
buildVatSettlementProposal: vi.fn(),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { buildVatSettlementProposal } from '@/lib/reports/vat-settlement'
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
function makeProposal() {
|
||||
return {
|
||||
period: { type: 'quarterly', year: 2026, period: 1, start: '2026-01-01', end: '2026-03-31' },
|
||||
period_label: 'Kvartal 1 2026',
|
||||
entry_date: '2026-03-31',
|
||||
description: 'Momsredovisning Kvartal 1 2026',
|
||||
lines: [
|
||||
{ account_number: '2611', debit_amount: 2500.75, credit_amount: 0 },
|
||||
{ account_number: '2641', debit_amount: 0, credit_amount: 1000.5 },
|
||||
{
|
||||
account_number: '2650', debit_amount: 0, credit_amount: 1500,
|
||||
line_description: 'Moms att betala',
|
||||
},
|
||||
{
|
||||
account_number: '3740', debit_amount: 0, credit_amount: 0.25,
|
||||
line_description: 'Öres- och kronutjämning',
|
||||
},
|
||||
],
|
||||
filed_net: 1500,
|
||||
rounding_amount: 0.25,
|
||||
is_empty: false,
|
||||
existing_entries: [],
|
||||
}
|
||||
}
|
||||
|
||||
describe('GET /api/reports/vat-declaration/settlement-proposal', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: mockUser as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: null,
|
||||
})
|
||||
vi.mocked(buildVatSettlementProposal).mockResolvedValue(makeProposal() as never)
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: null as never,
|
||||
supabase: mockSupabase as never,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const req = new Request(
|
||||
'http://localhost/api/reports/vat-declaration/settlement-proposal?periodType=quarterly&year=2026&period=1',
|
||||
)
|
||||
const res = await GET(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(401)
|
||||
expect(buildVatSettlementProposal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when period params are missing', async () => {
|
||||
const req = new Request('http://localhost/api/reports/vat-declaration/settlement-proposal')
|
||||
const res = await GET(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(400)
|
||||
expect(buildVatSettlementProposal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 for an invalid period type', async () => {
|
||||
const req = new Request(
|
||||
'http://localhost/api/reports/vat-declaration/settlement-proposal?periodType=weekly&year=2026&period=1',
|
||||
)
|
||||
const res = await GET(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 for an out-of-range period', async () => {
|
||||
const req = new Request(
|
||||
'http://localhost/api/reports/vat-declaration/settlement-proposal?periodType=quarterly&year=2026&period=5',
|
||||
)
|
||||
const res = await GET(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(400)
|
||||
expect(buildVatSettlementProposal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('happy path: returns the proposal', async () => {
|
||||
const req = new Request(
|
||||
'http://localhost/api/reports/vat-declaration/settlement-proposal?periodType=quarterly&year=2026&period=1',
|
||||
)
|
||||
const res = await GET(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data.filed_net).toBe(1500)
|
||||
expect(json.data.lines).toHaveLength(4)
|
||||
expect(buildVatSettlementProposal).toHaveBeenCalledWith(
|
||||
mockSupabase, 'company-1', 'quarterly', 2026, 1, { fiscalPeriodId: undefined },
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards the fiscal period for yearly VAT', async () => {
|
||||
const req = new Request(
|
||||
'http://localhost/api/reports/vat-declaration/settlement-proposal?periodType=yearly&year=2026&period=1&fiscal_period_id=fp-1',
|
||||
)
|
||||
const res = await GET(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(buildVatSettlementProposal).toHaveBeenCalledWith(
|
||||
mockSupabase, 'company-1', 'yearly', 2026, 1, { fiscalPeriodId: 'fp-1' },
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 500 when the builder fails', async () => {
|
||||
vi.mocked(buildVatSettlementProposal).mockRejectedValue(new Error('boom'))
|
||||
const req = new Request(
|
||||
'http://localhost/api/reports/vat-declaration/settlement-proposal?periodType=quarterly&year=2026&period=1',
|
||||
)
|
||||
const res = await GET(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(500)
|
||||
const json = await res.json()
|
||||
expect(json.error.code).toBe('VAT_REPORT_GENERATION_FAILED')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { buildVatSettlementProposal } from '@/lib/reports/vat-settlement'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { VatPeriodType } from '@/types'
|
||||
|
||||
/**
|
||||
* GET /api/reports/vat-declaration/settlement-proposal
|
||||
*
|
||||
* Builds the momsredovisning verifikat proposal for a VAT period (issue #980):
|
||||
* the editable lines that clear the period's 26xx accounts to 2650/1650. The
|
||||
* proposal is computed from the same ledger projection as the momsrapport;
|
||||
* booking happens separately through POST /api/bookkeeping/journal-entries
|
||||
* with source_type 'vat_settlement' once the user has reviewed the lines.
|
||||
*
|
||||
* Query parameters (same shape as /api/reports/vat-declaration):
|
||||
* periodType: 'monthly' | 'quarterly' | 'yearly'
|
||||
* year: number (e.g., 2026)
|
||||
* period: number (1-12 monthly, 1-4 quarterly, 1 yearly)
|
||||
* fiscal_period_id: optional; yearly only (räkenskapsår bounds)
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'report.vat_settlement_proposal',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodType = searchParams.get('periodType') as VatPeriodType | null
|
||||
const yearStr = searchParams.get('year')
|
||||
const periodStr = searchParams.get('period')
|
||||
const fiscalPeriodId = searchParams.get('fiscal_period_id') ?? undefined
|
||||
|
||||
if (!periodType || !yearStr || !periodStr) {
|
||||
return errorResponseFromCode('VAT_REPORT_MISSING_PARAMS', log, { requestId })
|
||||
}
|
||||
|
||||
if (!['monthly', 'quarterly', 'yearly'].includes(periodType)) {
|
||||
return errorResponseFromCode('VAT_REPORT_INVALID_PERIOD_TYPE', log, {
|
||||
requestId,
|
||||
details: { received: periodType },
|
||||
})
|
||||
}
|
||||
|
||||
const year = parseInt(yearStr, 10)
|
||||
const period = parseInt(periodStr, 10)
|
||||
|
||||
if (isNaN(year) || year < 2000 || year > 2100) {
|
||||
return errorResponseFromCode('VAT_REPORT_INVALID_YEAR', log, {
|
||||
requestId,
|
||||
details: { received: yearStr },
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
isNaN(period) ||
|
||||
(periodType === 'monthly' && (period < 1 || period > 12)) ||
|
||||
(periodType === 'quarterly' && (period < 1 || period > 4)) ||
|
||||
(periodType === 'yearly' && period !== 1)
|
||||
) {
|
||||
return errorResponseFromCode('VAT_REPORT_INVALID_PERIOD', log, {
|
||||
requestId,
|
||||
details: { periodType, received: periodStr },
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const proposal = await buildVatSettlementProposal(
|
||||
supabase, companyId!, periodType, year, period, { fiscalPeriodId },
|
||||
)
|
||||
return NextResponse.json({ data: proposal })
|
||||
} catch (err) {
|
||||
log.error('vat settlement proposal failed', err as Error, {
|
||||
periodType,
|
||||
year,
|
||||
period,
|
||||
})
|
||||
return errorResponseFromCode('VAT_REPORT_GENERATION_FAILED', log, {
|
||||
requestId,
|
||||
details: { reason: err instanceof Error ? err.message : 'unknown' },
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user