Files
accounted/app/api/reports/vat-declaration/route.ts
T
Mattsson e11f70b347 Bug/gh issues fiz (#1103)
* refactor: optimize page loading and data fetching

* fix: resolve recurring production runtime errors

* feat: add MCP company and customer updates

* fix: handle year-end tax adjustments

* feat: harden annual report compliance

* fix: expand invoice logo and font support

* fix: sanitize API route error responses

* fix: sanitize user-facing error messages

* feat: persist onboarding and tax assessment notices

* fix: reduce cloud backup audit churn

* feat: refine invoice editor layout

* fix: show saved tax adjustments in INK2

* fix: complete annual report API mappings

* docs: record operational safeguards and decisions

* fix: harden annual report review findings

* fix: adjust column span for description based on VAT registration

* New css class name
2026-07-21 23:00:15 +02:00

115 lines
3.9 KiB
TypeScript

import { NextResponse } from 'next/server'
import {
calculateVatDeclaration,
formatPeriodLabel,
} from '@/lib/reports/vat-declaration'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { VatPeriodType, AccountingMethod } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* GET /api/reports/vat-declaration
*
* Query parameters:
* periodType: 'monthly' | 'quarterly' | 'yearly'
* year: number (e.g., 2025)
* period: number (1-12 for monthly, 1-4 for quarterly, 1 for yearly)
*/
export const GET = withRouteContext(
'report.vat_declaration',
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')
// For yearly (helårsmoms) the period is the räkenskapsår, not the calendar
// year; the client passes the selected fiscal period so an extended year is
// covered in full. Ignored for monthly/quarterly (calendar periods).
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)) {
return errorResponseFromCode('VAT_REPORT_INVALID_PERIOD', log, {
requestId,
details: { received: periodStr },
})
}
if (periodType === 'monthly' && (period < 1 || period > 12)) {
return errorResponseFromCode('VAT_REPORT_INVALID_PERIOD', log, {
requestId,
details: { periodType, received: period, allowed: '1-12' },
})
}
if (periodType === 'quarterly' && (period < 1 || period > 4)) {
return errorResponseFromCode('VAT_REPORT_INVALID_PERIOD', log, {
requestId,
details: { periodType, received: period, allowed: '1-4' },
})
}
if (periodType === 'yearly' && period !== 1) {
return errorResponseFromCode('VAT_REPORT_INVALID_PERIOD', log, {
requestId,
details: { periodType, received: period, allowed: '1' },
})
}
const { data: settings } = await supabase
.from('company_settings')
.select('accounting_method')
.eq('company_id', companyId)
.single()
const accountingMethod = (settings?.accounting_method as AccountingMethod) || 'accrual'
try {
const declaration = await calculateVatDeclaration(
supabase, companyId!, periodType, year, period, accountingMethod,
{ fiscalPeriodId },
)
return NextResponse.json({
data: {
...declaration,
// For yearly the authoritative span is declaration.period.start/end
// (the räkenskapsår). The label stays a coarse "Helår {year}".
periodLabel: formatPeriodLabel(periodType, year, period),
},
})
} catch (err) {
log.error('vat declaration calculation failed', err as Error, {
periodType,
year,
period,
})
return errorResponseFromCode('VAT_REPORT_GENERATION_FAILED', log, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
)