288915c152
* fix(invoices): return attachment filename in delivery history summaries The 20260723003000 hardening dropped attachment_filename from list_invoice_delivery_summaries, so the delivery history UI always fell back to the generic "faktura.pdf" label. Recreate the RPC with the filename included: it is derived from company name, customer name, invoice number, and date, all already visible to every company member, so the minimization boundary is unchanged. Addresses stay masked and message content, BCC, and checksums stay server-side. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): surface own-account transfer legs in match-to-voucher by default The second (incoming) leg of a transfer between two of the company's own bank accounts was hidden in the 'Matcha mot befintlig verifikation' dialog because the voucher counted as 'already matched' once its outgoing leg was linked, even though the incoming account's line had no settling transaction. Users read the empty default list as 'the app won't let me link this'. get_account_gl_lines_for_matching now counts links per settlement account: a transaction provably on another cash account no longer marks the voucher as matched for the requested account, so the unsettled transfer leg surfaces by default (and auto-selects on an exact match). Same-account N:1 stays behind the 'Visa aven matchade verifikationer' opt-in, and transactions without a resolvable cash account conservatively keep counting everywhere. get_unlinked_gl_lines is deliberately untouched (feeds auto-reconcile). Companion guard: mark_entry_as_opening_balance now refuses entries with linked bank transactions, since half-settled transfer vouchers became reachable in the reconciliation view's unmatched table where 'Mark som IB' renders; re-tagging one would strand its transaction against a movement- excluded entry. getReconciliationStatus counts unmatched GL lines with the account-scoped RPC so the status card agrees with the table. Fixes #1026 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * perf(api): cut prod p95 latency via local JWT auth, single-RT company resolution, and report aggregate RPCs Baseline 2026-07-23 (487 prod samples): p50 160ms, p95 480ms, 13% of requests over 300ms. Target: p95 under 300ms. - requireAuth: verify JWTs locally via getClaims (ES256/JWKS) instead of a second network getUser per request; getUser fallback keeps HS256 self-hosted and existing test mocks working; middleware still revocation-checks every /api request - resolve_active_company RPC (20260723161000): one round trip replaces 2-3 queries in getActiveCompanyId and middleware; PGRST202/42501 fall back to the legacy query path - arsredovisning build-data: ~33 sequential round trips down to ~7, output byte-identical (snapshot-proven) - currency rate route: stop bypassing the exchange_rates cache (missing supabase arg caused an external Riksbanken call on every request) - document.get: parallelize row fetch, signed URL and audit event - list_company_accounts RPC (20260723170000): accounts list in one round trip instead of paging past PostgREST's 1000-row cap - vat-declaration route: drop a dead sequential company_settings query - get_kpi_report_aggregates RPC (20260723180000): KPI report's three full-period line scans collapsed into one aggregate call; dimension- filtered path unchanged - lint: fix 9 baseline errors, downgrade 4 react-hooks compiler rules to warn, zero the eslint baseline ratchet All four gates green: lint 0 errors, 9163 tests, check:guards, build. Migrations applied idempotently to staging only; prod receives them via Supabase branching on merge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): resolve PR review findings across auth, VAT declaration, and IB retag - requireAuth getClaims fast path: pin iss (project URL) and aud ('authenticated'), log every fallback to getUser (ASVS V9.1 finding) - remove the ignored accountingMethod parameter from calculateVatDeclaration and the dead company_settings.accounting_method reads in xlsx/pdf/eskd routes; v1 API keeps accepting the query param but documents it as a no-op - close the mark_entry_as_opening_balance TOCTOU race with a transactions trigger (20260723190000, FOR KEY SHARE on journal_entries) + pg tests; applied to staging and smoke-verified both directions - re-add the 42501 tenant guard to branch-local migration 20260723160000 (function body had silently reverted to the pre-20260619130100 definition) - document the buildK3Noter tbFullRows full-TB contract (uppskjuten skatt opening balance per BFNAR 2012:1 ch.29) - add KPI VAT-liability test covering reduced-rate output accounts 2621/2631 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(db): use NULL-safe caller_is_company_member in opening-balance retag guard The re-added tenant guard carried the pre-20260703180000 raw NOT IN (SELECT user_company_ids()) pattern, which the null-safe-tenant-guards ratchet blocks. Staging re-synced. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
301 lines
11 KiB
TypeScript
301 lines
11 KiB
TypeScript
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { NextResponse } from 'next/server'
|
|
import {
|
|
generateIncomeStatement,
|
|
buildIncomeStatementFromRows,
|
|
} from '@/lib/reports/income-statement'
|
|
import { generateTrialBalance } from '@/lib/reports/trial-balance'
|
|
import { generateARLedger, type ARLedgerReport } from '@/lib/reports/ar-ledger'
|
|
import {
|
|
generateMonthlyBreakdown,
|
|
assembleMonthlyBreakdown,
|
|
type MonthlyBreakdown,
|
|
} from '@/lib/reports/monthly-breakdown'
|
|
import {
|
|
fetchKpiAggregates,
|
|
buildOpeningBalances,
|
|
buildTrialBalanceRows,
|
|
} from '@/lib/reports/kpi-aggregates'
|
|
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
|
import {
|
|
calculateCashPosition,
|
|
calculateGrossMargin,
|
|
calculateExpenseRatio,
|
|
calculateAvgPaymentDays,
|
|
calculateVatLiability,
|
|
} from '@/lib/reports/kpi'
|
|
import { mergeWithDefaults } from '@/lib/reports/kpi-definitions'
|
|
import { parseDimensionFilterParams } from '@/lib/reports/dimension-filter'
|
|
import type {
|
|
KPIReport,
|
|
KPIPreferences,
|
|
IncomeStatementReport,
|
|
TrialBalanceRow,
|
|
} from '@/types'
|
|
|
|
export const GET = withRouteContext('report.kpi', async (request, { supabase, companyId }) => {
|
|
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
|
|
|
|
// The company-wide queries both paths share. Factories, not promises, so
|
|
// each Promise.all issues them inside its own single round-trip wave.
|
|
const prefsQuery = () =>
|
|
supabase
|
|
.from('extension_data')
|
|
.select('value')
|
|
.eq('company_id', companyId)
|
|
.eq('extension_id', 'core/kpi')
|
|
.eq('key', 'preferences')
|
|
.single()
|
|
const paidInvoicesQuery = () =>
|
|
supabase
|
|
.from('invoices')
|
|
.select('invoice_date, paid_at')
|
|
.eq('company_id', companyId)
|
|
.eq('status', 'paid')
|
|
.not('paid_at', 'is', null)
|
|
const topSuppliersQuery = () =>
|
|
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')
|
|
|
|
let prefsValue: unknown
|
|
let incomeStatement: IncomeStatementReport
|
|
let trialBalanceResult: { rows: TrialBalanceRow[] }
|
|
let arLedger: ARLedgerReport
|
|
let monthlyBreakdown: MonthlyBreakdown
|
|
let paidInvoicesResult: { data: Array<{ invoice_date: string; paid_at: string }> | null }
|
|
let topSuppliersResult: { data: unknown[] | null; error: unknown }
|
|
let filteredTrialBalance: { rows: TrialBalanceRow[] } | null
|
|
|
|
if (dimensions) {
|
|
// Dimension-filtered path: the legacy generators, unchanged. The second,
|
|
// dimension-scoped TB feeds the expense composition (classes 4-7, P&L)
|
|
// without touching the unfiltered TB the balance-side KPIs read.
|
|
const [prefsRes, is, tb, ar, mb, paid, sup, filteredTb] = await Promise.all([
|
|
prefsQuery(),
|
|
generateIncomeStatement(supabase, companyId, periodId, { dimensions }),
|
|
generateTrialBalance(supabase, companyId, periodId),
|
|
generateARLedger(supabase, companyId),
|
|
generateMonthlyBreakdown(supabase, companyId, periodId, { dimensions }),
|
|
paidInvoicesQuery(),
|
|
topSuppliersQuery(),
|
|
generateTrialBalance(supabase, companyId, periodId, { dimensions }),
|
|
])
|
|
prefsValue = prefsRes.data?.value
|
|
incomeStatement = is
|
|
trialBalanceResult = tb
|
|
arLedger = ar
|
|
monthlyBreakdown = mb
|
|
paidInvoicesResult = paid
|
|
topSuppliersResult = sup
|
|
filteredTrialBalance = filteredTb
|
|
} else {
|
|
// Hot path (no dimension filter): one Promise.all round trip. The
|
|
// get_kpi_report_aggregates RPC replaces three full journal-line scans
|
|
// (unfiltered TB, income-statement TB, monthly breakdown) with a single
|
|
// SQL pass; the pure builders below reproduce the legacy merge/rounding.
|
|
const obEntryId: string | null = period.opening_balance_entry_id ?? null
|
|
const [agg, priorResult, accounts, prefsRes, ar, paid, sup] = await Promise.all([
|
|
fetchKpiAggregates(supabase, companyId, periodId, obEntryId),
|
|
// Opening balances without an OB entry fall back to the server-side
|
|
// prior-period aggregate, exactly like getOpeningBalances.
|
|
obEntryId
|
|
? Promise.resolve(null)
|
|
: supabase.rpc('compute_prior_opening_balances', {
|
|
p_company_id: companyId,
|
|
p_period_start: period.period_start,
|
|
}),
|
|
fetchAllRows<{
|
|
account_number: string
|
|
account_name: string
|
|
account_class: number
|
|
}>(({ from, to }) =>
|
|
supabase
|
|
.from('chart_of_accounts')
|
|
.select('account_number, account_name, account_class')
|
|
.eq('company_id', companyId)
|
|
.order('account_number', { ascending: true })
|
|
.range(from, to)
|
|
),
|
|
prefsQuery(),
|
|
generateARLedger(supabase, companyId),
|
|
paidInvoicesQuery(),
|
|
topSuppliersQuery(),
|
|
])
|
|
|
|
if (priorResult?.error) {
|
|
// Mirrors the fallback branch of lib/reports/opening-balances.ts.
|
|
throw new Error(priorResult.error.message)
|
|
}
|
|
|
|
const accountMap = new Map<string, { name: string; class: number }>()
|
|
for (const acc of accounts) {
|
|
accountMap.set(acc.account_number, {
|
|
name: acc.account_name,
|
|
class: acc.account_class,
|
|
})
|
|
}
|
|
|
|
const openingBalances = buildOpeningBalances(
|
|
agg,
|
|
obEntryId ? null : (priorResult?.data ?? [])
|
|
)
|
|
trialBalanceResult = { rows: buildTrialBalanceRows(openingBalances, agg.tb, accountMap) }
|
|
const rowsExYearEnd = buildTrialBalanceRows(openingBalances, agg.tb_ex_year_end, accountMap)
|
|
incomeStatement = buildIncomeStatementFromRows(rowsExYearEnd)
|
|
monthlyBreakdown = assembleMonthlyBreakdown(
|
|
period.period_start,
|
|
period.period_end,
|
|
agg.monthly.map((m) => ({
|
|
year: m.year,
|
|
month0: m.month - 1,
|
|
income: m.income,
|
|
expenses: m.expenses,
|
|
}))
|
|
)
|
|
prefsValue = prefsRes.data?.value
|
|
arLedger = ar
|
|
paidInvoicesResult = paid
|
|
topSuppliersResult = sup
|
|
filteredTrialBalance = null
|
|
}
|
|
|
|
const preferences = mergeWithDefaults(
|
|
(prefsValue as Partial<KPIPreferences>) ?? {}
|
|
)
|
|
|
|
// 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 })
|
|
})
|