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>
186 lines
6.4 KiB
TypeScript
186 lines
6.4 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { roundOre } from '@/lib/money'
|
|
import type { TrialBalanceRow } from '@/types'
|
|
|
|
/**
|
|
* Client-side companion for the get_kpi_report_aggregates RPC
|
|
* (supabase/migrations/20260723180000_kpi_report_aggregates_rpc.sql).
|
|
*
|
|
* The KPI route used to scan every journal line of the fiscal period three
|
|
* times through PostgREST (unfiltered trial balance, income-statement trial
|
|
* balance with excludeYearEndClosing, monthly breakdown) and aggregate in
|
|
* JS. The RPC returns the three pre-summed shapes in one round trip; the
|
|
* builders here reproduce the exact merge/rounding semantics of the legacy
|
|
* generators so the report JSON stays identical.
|
|
*/
|
|
|
|
export interface AccountSums {
|
|
account_number: string
|
|
debit: number
|
|
credit: number
|
|
}
|
|
|
|
export interface KpiMonthlyBucket {
|
|
year: number
|
|
/** Calendar month 1-12 (SQL EXTRACT). Callers convert to 0-based before
|
|
* handing buckets to assembleMonthlyBreakdown. */
|
|
month: number
|
|
income: number
|
|
expenses: number
|
|
}
|
|
|
|
export interface KpiAggregates {
|
|
tb: AccountSums[]
|
|
tb_ex_year_end: AccountSums[]
|
|
ob: AccountSums[]
|
|
monthly: KpiMonthlyBucket[]
|
|
}
|
|
|
|
function toAccountSums(rows: unknown[] | null | undefined): AccountSums[] {
|
|
return (rows ?? []).map((r) => {
|
|
const row = r as { account_number?: unknown; debit?: unknown; credit?: unknown }
|
|
return {
|
|
account_number: String(row.account_number ?? ''),
|
|
debit: Number(row.debit) || 0,
|
|
credit: Number(row.credit) || 0,
|
|
}
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Fetch the KPI aggregates in one round trip. Throws on RPC failure (the
|
|
* route surfaces it as a 500 via withRouteContext; matches the
|
|
* get_vat_declaration_totals precedent in lib/reports/vat-declaration.ts).
|
|
*/
|
|
export async function fetchKpiAggregates(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
fiscalPeriodId: string,
|
|
obEntryId: string | null
|
|
): Promise<KpiAggregates> {
|
|
const { data, error } = await supabase.rpc('get_kpi_report_aggregates', {
|
|
p_company_id: companyId,
|
|
p_fiscal_period_id: fiscalPeriodId,
|
|
p_ob_entry_id: obEntryId,
|
|
})
|
|
if (error) {
|
|
throw new Error(`get_kpi_report_aggregates failed: ${error.message}`)
|
|
}
|
|
|
|
const payload = (data ?? {}) as {
|
|
tb?: unknown[]
|
|
tb_ex_year_end?: unknown[]
|
|
ob?: unknown[]
|
|
monthly?: unknown[]
|
|
}
|
|
|
|
return {
|
|
tb: toAccountSums(payload.tb),
|
|
tb_ex_year_end: toAccountSums(payload.tb_ex_year_end),
|
|
ob: toAccountSums(payload.ob),
|
|
monthly: (payload.monthly ?? []).map((r) => {
|
|
const row = r as { year?: unknown; month?: unknown; income?: unknown; expenses?: unknown }
|
|
return {
|
|
year: Number(row.year) || 0,
|
|
month: Number(row.month) || 0,
|
|
income: Number(row.income) || 0,
|
|
expenses: Number(row.expenses) || 0,
|
|
}
|
|
}),
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Build the opening-balance map for the fiscal period.
|
|
*
|
|
* Pass `priorRows: null` when the period has an opening-balance entry: the
|
|
* balances then come from the RPC's `ob` section, mirroring the OB-entry
|
|
* branch of getOpeningBalances (lib/reports/opening-balances.ts lines
|
|
* 57-62: additive accumulation with Number()||0 coercion). Otherwise pass
|
|
* the rows returned by the compute_prior_opening_balances RPC, mirroring
|
|
* the fallback branch (lines 77-86: per-row set with Number()||0).
|
|
*/
|
|
export function buildOpeningBalances(
|
|
agg: KpiAggregates,
|
|
priorRows:
|
|
| Array<{ account_number: string; debit: number | string; credit: number | string }>
|
|
| null
|
|
): Map<string, { debit: number; credit: number }> {
|
|
const balances = new Map<string, { debit: number; credit: number }>()
|
|
|
|
if (priorRows === null) {
|
|
for (const line of agg.ob) {
|
|
const existing = balances.get(line.account_number) || { debit: 0, credit: 0 }
|
|
existing.debit += Number(line.debit) || 0
|
|
existing.credit += Number(line.credit) || 0
|
|
balances.set(line.account_number, existing)
|
|
}
|
|
} else {
|
|
for (const row of priorRows) {
|
|
balances.set(row.account_number, {
|
|
debit: Number(row.debit) || 0,
|
|
credit: Number(row.credit) || 0,
|
|
})
|
|
}
|
|
}
|
|
|
|
return balances
|
|
}
|
|
|
|
/**
|
|
* Assemble TrialBalanceRow[] from pre-summed per-account period activity.
|
|
*
|
|
* Pinned to the row-building tail of generateTrialBalance
|
|
* (lib/reports/trial-balance.ts lines 287-322, which is read-only): merged
|
|
* key set of opening + period accounts, `Konto <n>` /
|
|
* `parseInt(n[0]) || 0` fallback for accounts missing from the chart,
|
|
* öre rounding on all six amount fields, and a final localeCompare sort.
|
|
* Rounding goes through roundOre (the antipattern guard forbids new raw
|
|
* Math.round(x * 100) / 100): identical to the source expression except
|
|
* within float epsilon of half-öre boundaries. Keep the two in sync if
|
|
* the source ever changes.
|
|
*/
|
|
export function buildTrialBalanceRows(
|
|
openingBalances: Map<string, { debit: number; credit: number }>,
|
|
periodSums: AccountSums[],
|
|
accountMap: Map<string, { name: string; class: number }>
|
|
): TrialBalanceRow[] {
|
|
const periodBalances = new Map<string, { debit: number; credit: number }>()
|
|
for (const sums of periodSums) {
|
|
const existing = periodBalances.get(sums.account_number) || { debit: 0, credit: 0 }
|
|
existing.debit += Number(sums.debit) || 0
|
|
existing.credit += Number(sums.credit) || 0
|
|
periodBalances.set(sums.account_number, existing)
|
|
}
|
|
|
|
// Merge account numbers from both opening and period
|
|
const allAccountNumbers = new Set([...openingBalances.keys(), ...periodBalances.keys()])
|
|
|
|
// Build rows: IB + period = UB
|
|
const rows: TrialBalanceRow[] = []
|
|
for (const accountNumber of allAccountNumbers) {
|
|
const opening = openingBalances.get(accountNumber) || { debit: 0, credit: 0 }
|
|
const periodActivity = periodBalances.get(accountNumber) || { debit: 0, credit: 0 }
|
|
const accountInfo = accountMap.get(accountNumber) || {
|
|
name: `Konto ${accountNumber}`,
|
|
class: parseInt(accountNumber[0]) || 0,
|
|
}
|
|
|
|
rows.push({
|
|
account_number: accountNumber,
|
|
account_name: accountInfo.name,
|
|
account_class: accountInfo.class,
|
|
opening_debit: roundOre(opening.debit),
|
|
opening_credit: roundOre(opening.credit),
|
|
period_debit: roundOre(periodActivity.debit),
|
|
period_credit: roundOre(periodActivity.credit),
|
|
closing_debit: roundOre(opening.debit + periodActivity.debit),
|
|
closing_credit: roundOre(opening.credit + periodActivity.credit),
|
|
})
|
|
}
|
|
|
|
rows.sort((a, b) => a.account_number.localeCompare(b.account_number))
|
|
|
|
return rows
|
|
}
|