Files
accounted/app/api/reports/kpi/route.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

205 lines
7.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateIncomeStatement } from '@/lib/reports/income-statement'
import { generateTrialBalance } from '@/lib/reports/trial-balance'
import { generateARLedger } from '@/lib/reports/ar-ledger'
import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown'
import {
calculateCashPosition,
calculateGrossMargin,
calculateExpenseRatio,
calculateAvgPaymentDays,
calculateVatLiability,
} from '@/lib/reports/kpi'
import { mergeWithDefaults } from '@/lib/reports/kpi-definitions'
import { requireCompanyId } from '@/lib/company/context'
import { parseDimensionFilterParams } from '@/lib/reports/dimension-filter'
import type { KPIReport, KPIPreferences } from '@/types'
export async function GET(request: Request) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const companyId = await requireCompanyId(supabase, user.id)
const { searchParams } = new URL(request.url)
const periodId = searchParams.get('period_id')
if (!periodId) {
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
}
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('*')
.eq('id', periodId)
.eq('company_id', companyId)
.single()
if (periodError || !period) {
return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 })
}
// Dimension filter applies to the P&L-side KPIs only (net result, revenue/
// expenses, months, expense composition). Balance-side KPIs (cash, VAT,
// receivables) and supplier/invoice aggregates stay company-wide — a
// dimension-scoped "cash position" would be silently wrong, not filtered.
// The KPI view hides those tiles when a filter is active.
const dimFilter = parseDimensionFilterParams(searchParams)
if (!dimFilter.ok) {
return NextResponse.json({ error: dimFilter.error }, { status: 400 })
}
const dimensions = dimFilter.dimensions
// Load user preferences for account overrides
const { data: prefsData } = await supabase
.from('extension_data')
.select('value')
.eq('company_id', companyId)
.eq('extension_id', 'core/kpi')
.eq('key', 'preferences')
.single()
const preferences = mergeWithDefaults(
(prefsData?.value as Partial<KPIPreferences>) ?? {}
)
const [
incomeStatement,
trialBalanceResult,
arLedger,
monthlyBreakdown,
paidInvoicesResult,
topSuppliersResult,
filteredTrialBalance,
] = await Promise.all([
generateIncomeStatement(supabase, companyId, periodId, { dimensions }),
generateTrialBalance(supabase, companyId, periodId),
generateARLedger(supabase, companyId),
generateMonthlyBreakdown(supabase, companyId, periodId, { dimensions }),
supabase
.from('invoices')
.select('invoice_date, paid_at')
.eq('company_id', companyId)
.eq('status', 'paid')
.not('paid_at', 'is', null),
supabase
.from('supplier_invoices')
.select('supplier_id, total_sek, total, supplier:suppliers(id, name)')
.eq('company_id', companyId)
.gte('invoice_date', period.period_start)
.lte('invoice_date', period.period_end)
.neq('status', 'credited'),
// Second, dimension-scoped TB only when filtered — feeds the expense
// composition (classes 4–7, P&L) without touching the unfiltered TB the
// balance-side KPIs read.
dimensions
? generateTrialBalance(supabase, companyId, periodId, { dimensions })
: Promise.resolve(null),
])
// Cash position — use account overrides if set
const cashOverrides = preferences.accountOverrides['cashPosition']
let cashPosition: number
if (cashOverrides && cashOverrides.length > 0) {
const cashRows = trialBalanceResult.rows.filter((r) =>
cashOverrides.includes(r.account_number)
)
cashPosition = Math.round(
cashRows.reduce((sum, r) => sum + (r.closing_debit - r.closing_credit), 0) * 100
) / 100
} else {
cashPosition = calculateCashPosition(trialBalanceResult.rows)
}
// VAT liability — use account overrides if set
const vatLiability = calculateVatLiability(
trialBalanceResult.rows,
preferences.accountOverrides['vatLiability']
)
// Avg payment days from paid invoices
const paidInvoices = (paidInvoicesResult.data ?? []).map((inv) => ({
invoice_date: inv.invoice_date as string,
paid_at: inv.paid_at as string,
}))
// Expense composition by BAS class (4-7). Expense accounts have a debit
// normal balance, so amount = closing_debit - closing_credit. Negative
// values (rare reclassifications) are clamped to 0 so the donut renders
// sensibly.
const expenseComposition = (filteredTrialBalance ?? trialBalanceResult).rows.reduce(
(acc, r) => {
if (r.account_class < 4 || r.account_class > 7) return acc
const amount = r.closing_debit - r.closing_credit
if (amount <= 0) return acc
if (r.account_class === 4) acc.class4 += amount
else if (r.account_class === 5) acc.class5 += amount
else if (r.account_class === 6) acc.class6 += amount
else if (r.account_class === 7) acc.class7 += amount
return acc
},
{ class4: 0, class5: 0, class6: 0, class7: 0 }
)
// Top suppliers by spend within the fiscal period. Sum total_sek to avoid
// mixing currencies. Drop FX invoices without a SEK conversion (total_sek
// null) — they would otherwise inflate a supplier's total with raw
// foreign-currency amounts.
type SupplierInvoiceRow = {
supplier_id: string | null
total_sek: number | null
total: number | null
supplier: { id: string; name: string } | { id: string; name: string }[] | null
}
if (topSuppliersResult.error) {
// Surface the failure rather than silently rendering an empty chart that
// matches the legitimate "no supplier invoices" empty state.
console.error('[kpi] topSuppliersResult error:', topSuppliersResult.error)
}
const supplierTotals = new Map<string, { name: string; total: number }>()
for (const row of (topSuppliersResult.data ?? []) as SupplierInvoiceRow[]) {
if (!row.supplier_id) continue
const supplier = Array.isArray(row.supplier) ? row.supplier[0] : row.supplier
if (!supplier?.name) continue
const amount = row.total_sek ?? null
if (amount == null) continue
const existing = supplierTotals.get(row.supplier_id)
if (existing) existing.total += amount
else supplierTotals.set(row.supplier_id, { name: supplier.name, total: amount })
}
const topSuppliers = Array.from(supplierTotals.entries())
.map(([supplier_id, v]) => ({
supplier_id,
supplier_name: v.name,
total: Math.round(v.total * 100) / 100,
}))
.sort((a, b) => b.total - a.total)
.slice(0, 7)
const report: KPIReport = {
netResult: incomeStatement.net_result,
cashPosition,
outstandingReceivables: arLedger.total_outstanding,
overdueReceivables: arLedger.total_overdue,
vatLiability,
totalRevenue: incomeStatement.total_revenue,
totalExpenses: incomeStatement.total_expenses,
grossMargin: calculateGrossMargin(incomeStatement),
expenseRatio: calculateExpenseRatio(incomeStatement),
avgPaymentDays: calculateAvgPaymentDays(paidInvoices),
periodComplete: period.is_closed,
months: monthlyBreakdown.months,
period: { start: period.period_start, end: period.period_end },
expenseComposition: {
class4: Math.round(expenseComposition.class4 * 100) / 100,
class5: Math.round(expenseComposition.class5 * 100) / 100,
class6: Math.round(expenseComposition.class6 * 100) / 100,
class7: Math.round(expenseComposition.class7 * 100) / 100,
},
topSuppliers,
}
return NextResponse.json({ data: report })
}