Files
accounted/app/api/reports/sie-export/route.ts
T
Jakob Wennberg ddbe9b1379 fix(reports): always emit compulsory #FORMAT PC8 in SIE export (#1466)
#FORMAT is a compulsory record in every SIE type and PC8 is its only
legal value. We only emitted it when the caller opted into cp437 byte
encoding, so the default UTF-8 download had no #FORMAT line and strict
importers (Visma Spiris) rejected the file with 'Etiketten #FORMAT
saknas i filen'. Cloud exporters (Fortnox, Bokio) ship UTF-8 bytes with
#FORMAT PC8 and importers detect the real encoding from the bytes, so
the tag is now unconditional.

Also formats #ORGNR as nnnnnn-nnnn per spec; company_settings stores
the org number without a hyphen.

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 15:04:07 +02:00

61 lines
2.1 KiB
TypeScript

import { NextResponse } from 'next/server'
import { generateSIEExport, encodeSIEToCP437 } from '@/lib/reports/sie-export'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
export const GET = withRouteContext(
'report.sie_export',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const { searchParams } = new URL(request.url)
const periodId = searchParams.get('period_id')
const excludeClosing = searchParams.get('exclude_closing') === 'true'
const useCP437 = searchParams.get('encoding') === 'cp437'
if (!periodId) {
return errorResponseFromCode('REPORT_PERIOD_REQUIRED', log, { requestId })
}
const opLog = log.child({ periodId })
const { data: company } = await supabase
.from('company_settings')
.select('company_name, org_number')
.eq('company_id', companyId)
.single()
if (!company) {
return errorResponseFromCode('SIE_EXPORT_COMPANY_NOT_FOUND', opLog, { requestId })
}
try {
const sieContent = await generateSIEExport(supabase, companyId!, {
fiscal_period_id: periodId,
company_name: company.company_name || 'Unknown',
org_number: company.org_number,
exclude_year_end_closing: excludeClosing,
})
const body = useCP437 ? Buffer.from(encodeSIEToCP437(sieContent)) : sieContent
const contentType = useCP437 ? 'application/octet-stream' : 'text/plain; charset=utf-8'
return new NextResponse(body, {
status: 200,
headers: {
'Content-Type': contentType,
'Content-Disposition': `attachment; filename="export_${periodId}.se"`,
'X-Request-Id': requestId,
},
})
} catch (err) {
opLog.error('sie export generation failed', err as Error)
return errorResponseFromCode('SIE_EXPORT_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
})
}
},
)