Files
accounted/app/api/reports/general-ledger/xlsx/route.ts
T
Jakob Wennberg f266c386f3 chore: repo-wide bloat sweep, remove dead code and fold duplicate helpers (#2150)
* chore: repo-wide bloat sweep, remove dead code and fold duplicate helpers

Remove 33 dead files, ~270 unreferenced exports/types, 13 dead i18n
namespaces and 4 unused dependencies; fold byte-identical helper copies
into one canonical home each (lib/utils chunk/sleep/utcDateStamp,
lib/dates/iso, lib/invariants/uuid, lib/xml/escape, lib/reports/sru/format,
lib/pdf/number-text, lib/browser/panel-request, lib/api/v1/body +
v1ValidationError rolled out to ~55 v1 routes, booking-template schemas).

No behaviour change: v1 bodies and status codes, MCP tool schemas, DB
writes and money math are untouched. Naive ore rounding was deliberately
not swapped for roundOre; see DECISIONS.md 2026-09-02 for the full list
of things left alone on purpose.

tsc, lint, 19588 unit tests and check:guards green; antipattern baseline
ratcheted (naive-ore-round 622 -> 620, hand-rolled-invariant 115 -> 113).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(transactions): import RawTransaction from @/types after the ingest re-export removal

CI's type ratchet (check:types, full tsconfig) caught the one test file
that still imported the type through lib/transactions/ingest.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 11:51:16 +02:00

178 lines
5.7 KiB
TypeScript

import { NextResponse } from 'next/server'
import { generateGeneralLedger } from '@/lib/reports/general-ledger'
import { withRouteContext } from '@/lib/api/with-route-context'
import { parseDimensionFilterParams, dimensionFilterDisclosure, dimensionFilterFileSuffix } from '@/lib/reports/dimension-filter'
import { parseReportDateRange, type DateRange } from '@/lib/reports/date-range'
import {
reportToWorkbook,
textColumn,
currencyColumn,
dateColumn,
xlsxFilename,
parseCellDate,
} from '@/lib/reports/xlsx-export'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
interface FlatRow {
account_number: string
account_name: string
date: Date | string
voucher: string
description: string
source_type: string
debit: number
credit: number
balance: number
}
export const GET = withRouteContext('report.general_ledger.xlsx', async (request, { supabase, companyId }) => {
const { searchParams } = new URL(request.url)
const periodId = searchParams.get('period_id')
const accountFrom = searchParams.get('account_from') || undefined
const accountTo = searchParams.get('account_to') || undefined
if (!periodId) {
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
}
const { data: companyRow } = await supabase
.from('company_settings')
.select('company_name')
.eq('company_id', companyId)
.single()
const dimFilter = parseDimensionFilterParams(searchParams)
if (!dimFilter.ok) {
return NextResponse.json({ error: dimFilter.error }, { status: 400 })
}
// Validate the optional date sub-range against the fiscal period bounds.
const { data: period } = await supabase
.from('fiscal_periods')
.select('period_start, period_end')
.eq('id', periodId)
.eq('company_id', companyId)
.single()
let range: DateRange = {}
if (period) {
const parsed = parseReportDateRange(searchParams, period)
if (!parsed.ok) {
return NextResponse.json({ error: parsed.error }, { status: 400 })
}
range = parsed.range
}
try {
const report = await generateGeneralLedger(supabase, companyId, periodId, accountFrom, accountTo, {
dimensions: dimFilter.dimensions,
fromDate: range.fromDate,
toDate: range.toDate,
})
// Flatten accounts + their lines into a single sheet. Each account contributes
// an opening-balance row, its lines (with running balance), and a closing
// row: matching how huvudbok is read in Fortnox/Visma.
const rows: FlatRow[] = []
for (const acc of report.accounts) {
rows.push({
account_number: acc.account_number,
account_name: acc.account_name,
date: '',
voucher: '',
description: 'Ingående balans',
source_type: '',
debit: 0,
credit: 0,
balance: acc.opening_balance,
})
for (const line of acc.lines) {
rows.push({
account_number: acc.account_number,
account_name: acc.account_name,
// Preserve the original ISO string in the cell if parsing fails (avoids
// NaN dates polluting the workbook).
date: parseCellDate(line.date) ?? line.date,
voucher: `${line.voucher_series}${line.voucher_number}`,
description: line.description,
source_type: line.source_type,
debit: line.debit,
credit: line.credit,
balance: line.balance,
})
}
rows.push({
account_number: acc.account_number,
account_name: acc.account_name,
date: '',
voucher: '',
description: 'Utgående balans',
source_type: '',
debit: acc.total_debit,
credit: acc.total_credit,
balance: acc.closing_balance,
})
}
// Partial-view disclosure: a filtered huvudbok starts balance accounts
// at zero IB (opening balances cannot be dimension-scoped): the export
// must say so or a project-filtered ledger reads as a full one.
const disclosure = dimensionFilterDisclosure(dimFilter.dimensions)
if (disclosure) {
rows.unshift({
account_number: disclosure,
account_name: '',
date: null as unknown as Date,
voucher: '',
description: 'Ingående balanser ingår inte i filtrerad vy',
source_type: '',
debit: null as unknown as number,
credit: null as unknown as number,
balance: null as unknown as number,
})
}
const buffer = reportToWorkbook<FlatRow>([
{
name: 'Huvudbok',
columns: [
textColumn('Konto'),
textColumn('Kontonamn'),
dateColumn('Datum'),
textColumn('Verifikat'),
textColumn('Beskrivning'),
textColumn('Källa'),
currencyColumn('Debet'),
currencyColumn('Kredit'),
currencyColumn('Saldo'),
],
rows,
mapRow: (r) => [
r.account_number,
r.account_name,
r.date instanceof Date ? r.date : null,
r.voucher,
r.description,
r.source_type,
r.debit,
r.credit,
r.balance,
],
},
])
const filename = xlsxFilename(`huvudbok${dimensionFilterFileSuffix(dimFilter.dimensions)}`, companyRow?.company_name ?? '', report.period.end)
return new NextResponse(new Uint8Array(buffer), {
headers: {
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Disposition': `attachment; filename="${filename}"`,
},
})
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? getUserErrorMessage(err) : 'Kunde inte generera huvudbok' },
{ status: 500 }
)
}
})