Files
accounted/lib/reports/general-ledger.ts
T
Jakob WennbergandClaude Fable 5 01dbef4015 feat(dimensions): PR4 reports — dimension-filtered P&L + Resultat per projekt/kostnadsställe (#862)
* feat(dimensions): PR4 reports — dimension-filtered P&L everywhere + Resultat per projekt/kostnadsställe

The Project P&L milestone of the dimensions plan (dev_docs §7 PR4).

One choke point lights up everything: generateTrialBalance gains
options.dimensions (SIE dim → code map) pushed down as jsonb containment
(dimensions @>, served by idx_jel_dimensions_gin) on both line queries, with
company-wide opening balances dropped when filtered (they cannot be
dimension-scoped; P&L-safe by whitelist). Resultatrapport, resultaträkning,
huvudbok, monthly-breakdown and the TB drill-down inherit the filter; the
KPI route filters only its P&L-side inputs (income statement, months,
expense composition) — never cash/VAT.

New report lib/reports/dimension-pnl.ts — "Resultat per projekt/
kostnadsställe" (Fortnox Resultatrapport projekt): value-as-column matrix
over one dimension with an explicit "(Utan dimension)" bucket computed as
the residual against the same trial-balance pass resultatrapport uses, so
every row and the Totalt column reconcile with the unfiltered
resultatrapport by construction. Registered in REPORT_CATALOG (visible only
when dimensions_enabled), slug-routed view + xlsx export.

UI: DimensionFilter (dimension + value picker, persistent "Filtrerad — ej
fullständig rapport" chip) mounts in FocusedReport for catalog entries
flagged dimensions: true; huvudbok rows show line dim codes.

Statutory exclusion pinned by TEST, not convention:
lib/reports/__tests__/dimension-statutory-guard.test.ts fails if the filter
parser leaks into balance sheet, balansrapport, kassaflöde, VAT, SIE or
full-archive routes/generators, or if the catalog whitelist widens.

MCP: new gnubok_get_dimension_pnl (reports:read); dimensions filter arg on
get_trial_balance/get_income_statement/get_general_ledger with
resolve-don't-select (names → registry codes, resolution echoes);
query_journal totals fixed to aggregate the FULL match set (was silently
slice-scoped while claiming otherwise) with an honest totals_scope field,
plus group_by / group_by_dimension aggregation.

Also: voucher-detail dim-6 badge now uses the registry name instead of the
non-standard "PR" abbreviation (#859 review follow-up).

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

* fix(dimensions): address #862 review — export disclosure, prior-column suppression, period-label honesty, route hardening

- Filtered XLSX/PDF exports now carry the partial-view disclosure past the
  file boundary (BFNAR 2013:2): filename suffix (-dim6-p001), a
  "Filtrerad … — ej fullständig rapport" row on every sheet, and a header
  note/title line in the PDFs.
- Resultatrapport drops the prior-year column when a dimension filter is
  active — project codes are time-limited under K2/K3, so "this code last
  year" may be a different project (same rule as narrowed date ranges).
- dimension-pnl no longer accepts fromDate: the matrix is cumulative from
  period_start by design (closing-balance semantics), and the period label
  now states exactly that instead of echoing a lower bound that was never
  applied. Routes/MCP tool updated to toDate-only.
- dimension-pnl routes 404 on an unknown/foreign period id and cap dim_no
  to 4 digits (matching the MCP tool's PostgREST-path guard, which the
  generator now also enforces itself).
- Statutory-guard test's generateTrialBalance call-site scan is paren-aware
  instead of a 300-char window; added fully-untagged and injection-guard
  test cases.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:20:47 +02:00

234 lines
8.2 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { getOpeningBalances } from './opening-balances'
export interface GeneralLedgerLine {
date: string
voucher_series: string
voucher_number: number
journal_entry_id: string
description: string
source_type: string
debit: number
credit: number
balance: number
/** SIE dim → code tags on the line; omitted when untagged. */
dimensions?: Record<string, string>
}
export interface GeneralLedgerAccount {
account_number: string
account_name: string
opening_balance: number
lines: GeneralLedgerLine[]
closing_balance: number
total_debit: number
total_credit: number
}
export interface GeneralLedgerReport {
accounts: GeneralLedgerAccount[]
period: { start: string; end: string }
}
/**
* Generate general ledger (huvudbok) for a fiscal period.
* BFL 5 kap. 1 § — systematisk ordning: all transactions grouped by account.
*
* Uses joined queries with pagination to handle any number of entries.
* Avoids the broken .in(entryIds) pattern that silently truncated at 1000 rows.
*
* Opening balances use the opening_balance_entry set by year-end closing
* when available; falls back to summing prior-period entries.
*
* The account range filter (accountFrom/accountTo) is applied post-hoc
* during result building, not in the queries. Opening balances are computed
* for all accounts — the wasted Map entries for filtered-out accounts are
* trivially cheap compared to the cost of the queries themselves.
*/
export async function generateGeneralLedger(
supabase: SupabaseClient,
companyId: string,
periodId: string,
accountFrom?: string,
accountTo?: string,
options?: {
/** SIE dim → code filter ({"6":"P001"}). Opening balances are dropped
* when set — they are company-wide and cannot be dimension-scoped. */
dimensions?: Record<string, string>
}
): Promise<GeneralLedgerReport> {
const dimensionFilter =
options?.dimensions && Object.keys(options.dimensions).length > 0
? options.dimensions
: undefined
// Get fiscal period dates and opening_balance_entry_id
const { data: period } = await supabase
.from('fiscal_periods')
.select('period_start, period_end, opening_balance_entry_id')
.eq('id', periodId)
.eq('company_id', companyId)
.single()
if (!period) {
return { accounts: [], period: { start: '', end: '' } }
}
// ── Opening balances (IB) ──────────────────────────────────────
const { balances: openingByAccount, obEntryId } = await getOpeningBalances(
supabase, companyId, period
)
// Convert to net balance (debit - credit) for GL running balance
const openingBalances = new Map<string, number>()
if (!dimensionFilter) {
for (const [accNum, { debit, credit }] of openingByAccount) {
openingBalances.set(accNum, debit - credit)
}
}
// ── Period lines via joined query (excluding OB entry) ─────────
// Race condition note: if year-end closing runs concurrently and creates
// the OB entry between the period query and this query, the entry could
// be missed. The window is sub-second and the consequence is a single
// stale report — acceptable.
// Supabase types !inner joins as arrays; for many-to-one (line → entry)
// it returns a single object at runtime. Cast via `as any` on the query.
const rawLines = await fetchAllRows<{
id: string
account_number: string
debit_amount: number
credit_amount: number
journal_entry_id: string
dimensions: Record<string, string> | null
journal_entries: {
entry_date: string
voucher_number: number
voucher_series: string
description: string
source_type: string
}
}>(({ from, to }) => {
let query = supabase
.from('journal_entry_lines')
.select('id, account_number, debit_amount, credit_amount, journal_entry_id, dimensions, journal_entries!inner(entry_date, voucher_number, voucher_series, description, source_type, company_id, fiscal_period_id, status)')
.eq('journal_entries.company_id', companyId)
.eq('journal_entries.fiscal_period_id', periodId)
.in('journal_entries.status', ['posted', 'reversed'])
if (dimensionFilter) {
// jsonb containment (@>) — served by idx_jel_dimensions_gin.
query = query.contains('dimensions', dimensionFilter)
}
if (obEntryId) {
query = query.neq('journal_entry_id', obEntryId)
}
// Stable total order on the line PK — paging is only correct with a
// deterministic order, else rows duplicate/skip across pages and balances
// double or accounts vanish (see fetch-all.ts ordering invariant). The
// report re-sorts lines per account below, so this order is invisible.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return query.order('id', { ascending: true }).range(from, to) as any
}, { dedupeBy: (r) => r.id })
if (rawLines.length === 0 && openingBalances.size === 0) {
return { accounts: [], period: { start: period.period_start, end: period.period_end } }
}
// Fetch account names
const accounts = await fetchAllRows<{ account_number: string; account_name: string }>(({ from, to }) =>
supabase
.from('chart_of_accounts')
.select('account_number, account_name')
.eq('company_id', companyId)
.order('account_number', { ascending: true })
.range(from, to)
)
const accountNameMap = new Map<string, string>()
for (const acc of accounts) {
accountNameMap.set(acc.account_number, acc.account_name)
}
// Group lines by account
const accountLines = new Map<string, GeneralLedgerLine[]>()
for (const line of rawLines) {
const entry = line.journal_entries
const accNum = line.account_number
if (!accountLines.has(accNum)) {
accountLines.set(accNum, [])
}
const hasDims = line.dimensions && Object.keys(line.dimensions).length > 0
accountLines.get(accNum)!.push({
date: entry.entry_date,
voucher_series: entry.voucher_series || 'A',
voucher_number: entry.voucher_number,
journal_entry_id: line.journal_entry_id,
description: entry.description || '',
source_type: entry.source_type || '',
debit: Math.round((Number(line.debit_amount) || 0) * 100) / 100,
credit: Math.round((Number(line.credit_amount) || 0) * 100) / 100,
balance: 0, // computed below
...(hasDims ? { dimensions: line.dimensions as Record<string, string> } : {}),
})
}
// Include accounts that have opening balance but no period lines
for (const [accNum, balance] of openingBalances) {
if (!accountLines.has(accNum) && Math.abs(balance) > 0.005) {
accountLines.set(accNum, [])
}
}
// Build account summaries
const result: GeneralLedgerAccount[] = []
for (const [accNum, accLines] of accountLines) {
// Apply optional account range filter
if (accountFrom && accNum < accountFrom) continue
if (accountTo && accNum > accountTo) continue
// Sort by date, then voucher number
accLines.sort((a, b) => {
const dateCompare = a.date.localeCompare(b.date)
if (dateCompare !== 0) return dateCompare
return a.voucher_number - b.voucher_number
})
const opening = Math.round((openingBalances.get(accNum) || 0) * 100) / 100
let runningBalance = opening
for (const line of accLines) {
runningBalance += line.debit - line.credit
line.balance = Math.round(runningBalance * 100) / 100
}
const totalDebit = accLines.reduce((sum, l) => sum + l.debit, 0)
const totalCredit = accLines.reduce((sum, l) => sum + l.credit, 0)
result.push({
account_number: accNum,
account_name: accountNameMap.get(accNum) || `Konto ${accNum}`,
opening_balance: opening,
lines: accLines,
closing_balance: Math.round((opening + totalDebit - totalCredit) * 100) / 100,
total_debit: Math.round(totalDebit * 100) / 100,
total_credit: Math.round(totalCredit * 100) / 100,
})
}
// Sort by account number
result.sort((a, b) => a.account_number.localeCompare(b.account_number))
return {
accounts: result,
period: { start: period.period_start, end: period.period_end },
}
}