Files
accounted/app/api/reports/vat-declaration/settlement-proposal/route.ts
T
Jakob WennbergandClaude Fable 5 2774e01258 feat(vat): book the momsrapport as an editable settlement verifikat (#980) (#983)
* 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>
2026-07-11 20:16:57 +02:00

84 lines
3.0 KiB
TypeScript

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' },
})
}
},
)