Files
accounted/lib/reports/__tests__/kpi-aggregates.test.ts
T
Mattsson 288915c152 Fix/fdb fr usrs (#1125)
* 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>
2026-07-23 16:16:55 +02:00

205 lines
7.1 KiB
TypeScript

import { describe, it, expect, vi } from 'vitest'
import {
fetchKpiAggregates,
buildOpeningBalances,
buildTrialBalanceRows,
type KpiAggregates,
} from '../kpi-aggregates'
function emptyAgg(overrides: Partial<KpiAggregates> = {}): KpiAggregates {
return { tb: [], tb_ex_year_end: [], ob: [], monthly: [], ...overrides }
}
describe('fetchKpiAggregates', () => {
it('calls the RPC with the expected args and coerces numbers', async () => {
const rpc = vi.fn().mockResolvedValue({
data: {
tb: [{ account_number: '1930', debit: '125.5', credit: 0 }],
tb_ex_year_end: [{ account_number: '3001', debit: null, credit: 100 }],
ob: [],
monthly: [{ year: 2026, month: '2', income: '10.25', expenses: undefined }],
},
error: null,
})
const supabase = { rpc } as never
const agg = await fetchKpiAggregates(supabase, 'company-1', 'period-1', 'ob-1')
expect(rpc).toHaveBeenCalledWith('get_kpi_report_aggregates', {
p_company_id: 'company-1',
p_fiscal_period_id: 'period-1',
p_ob_entry_id: 'ob-1',
})
expect(agg.tb).toEqual([{ account_number: '1930', debit: 125.5, credit: 0 }])
expect(agg.tb_ex_year_end).toEqual([{ account_number: '3001', debit: 0, credit: 100 }])
expect(agg.ob).toEqual([])
expect(agg.monthly).toEqual([{ year: 2026, month: 2, income: 10.25, expenses: 0 }])
})
it('defaults missing sections to empty arrays', async () => {
const rpc = vi.fn().mockResolvedValue({ data: {}, error: null })
const supabase = { rpc } as never
const agg = await fetchKpiAggregates(supabase, 'company-1', 'period-1', null)
expect(agg).toEqual(emptyAgg())
expect(rpc).toHaveBeenCalledWith('get_kpi_report_aggregates', {
p_company_id: 'company-1',
p_fiscal_period_id: 'period-1',
p_ob_entry_id: null,
})
})
it('throws a prefixed error when the RPC fails', async () => {
const rpc = vi.fn().mockResolvedValue({ data: null, error: { message: 'boom' } })
const supabase = { rpc } as never
await expect(
fetchKpiAggregates(supabase, 'company-1', 'period-1', null)
).rejects.toThrow('get_kpi_report_aggregates failed: boom')
})
})
describe('buildOpeningBalances', () => {
it('OB-entry path (priorRows null): additive accumulation with Number coercion', () => {
const agg = emptyAgg({
ob: [
{ account_number: '1930', debit: 5000, credit: 0 },
// A duplicate account accumulates additively, mirroring the
// per-line loop in opening-balances.ts lines 57-62.
{ account_number: '1930', debit: 250.5, credit: 0 },
{ account_number: '2010', debit: 0, credit: 5250.5 },
],
})
const balances = buildOpeningBalances(agg, null)
expect(balances.get('1930')).toEqual({ debit: 5250.5, credit: 0 })
expect(balances.get('2010')).toEqual({ debit: 0, credit: 5250.5 })
expect(balances.size).toBe(2)
})
it('fallback path: uses priorRows with Number()||0 coercion, ignoring the ob section', () => {
const agg = emptyAgg({
ob: [{ account_number: '9999', debit: 1, credit: 1 }],
})
// compute_prior_opening_balances returns numerics that may arrive as
// strings through PostgREST: mirrors opening-balances.ts lines 77-86.
const balances = buildOpeningBalances(agg, [
{ account_number: '1930', debit: '1500.25', credit: '0' },
{ account_number: '2440', debit: 'not-a-number', credit: 300 },
])
expect(balances.get('1930')).toEqual({ debit: 1500.25, credit: 0 })
expect(balances.get('2440')).toEqual({ debit: 0, credit: 300 })
expect(balances.has('9999')).toBe(false)
})
it('empty inputs produce an empty map in both shapes', () => {
expect(buildOpeningBalances(emptyAgg(), null).size).toBe(0)
expect(buildOpeningBalances(emptyAgg(), []).size).toBe(0)
})
})
describe('buildTrialBalanceRows', () => {
const accountMap = new Map<string, { name: string; class: number }>([
['1930', { name: 'Företagskonto', class: 1 }],
['3001', { name: 'Försäljning 25%', class: 3 }],
])
it('merges opening and period accounts and computes IB + period = UB', () => {
const opening = new Map([
['1930', { debit: 5000, credit: 0 }],
// Account only in opening: must still get a row.
['2081', { debit: 0, credit: 25000 }],
])
const periodSums = [
{ account_number: '1930', debit: 12500, credit: 3000 },
// Account only in period: must still get a row.
{ account_number: '3001', debit: 0, credit: 10000 },
]
const rows = buildTrialBalanceRows(opening, periodSums, accountMap)
expect(rows.map((r) => r.account_number)).toEqual(['1930', '2081', '3001'])
expect(rows[0]).toEqual({
account_number: '1930',
account_name: 'Företagskonto',
account_class: 1,
opening_debit: 5000,
opening_credit: 0,
period_debit: 12500,
period_credit: 3000,
closing_debit: 17500,
closing_credit: 3000,
})
expect(rows[1]).toMatchObject({
account_number: '2081',
opening_credit: 25000,
period_debit: 0,
period_credit: 0,
closing_credit: 25000,
})
expect(rows[2]).toMatchObject({
account_number: '3001',
account_name: 'Försäljning 25%',
account_class: 3,
opening_debit: 0,
period_credit: 10000,
closing_credit: 10000,
})
})
it('falls back to "Konto <n>" naming and first-digit class for unknown accounts', () => {
const rows = buildTrialBalanceRows(
new Map(),
[
{ account_number: '2611', debit: 0, credit: 2500 },
{ account_number: 'X99', debit: 1, credit: 0 },
],
accountMap
)
const unknown = rows.find((r) => r.account_number === '2611')!
expect(unknown.account_name).toBe('Konto 2611')
expect(unknown.account_class).toBe(2)
// parseInt(n[0]) || 0 fallback: non-numeric first char lands class 0,
// same as trial-balance.ts line 306.
const weird = rows.find((r) => r.account_number === 'X99')!
expect(weird.account_name).toBe('Konto X99')
expect(weird.account_class).toBe(0)
})
it('rounds all six amount fields with Math.round(x * 100) / 100', () => {
const opening = new Map([['1930', { debit: 0.1, credit: 0 }]])
const rows = buildTrialBalanceRows(
opening,
[{ account_number: '1930', debit: 0.2, credit: 0.005 }],
accountMap
)
// 0.1 + 0.2 = 0.30000000000000004 raw: closing must land on 0.3 exactly.
expect(rows[0].opening_debit).toBe(0.1)
expect(rows[0].period_debit).toBe(0.2)
expect(rows[0].closing_debit).toBe(0.3)
expect(rows[0].period_credit).toBe(0.01)
expect(rows[0].closing_credit).toBe(0.01)
})
it('sorts rows by account_number with localeCompare', () => {
const rows = buildTrialBalanceRows(
new Map(),
[
{ account_number: '8999', debit: 1, credit: 0 },
{ account_number: '1510', debit: 1, credit: 0 },
{ account_number: '2440', debit: 1, credit: 0 },
],
accountMap
)
expect(rows.map((r) => r.account_number)).toEqual(['1510', '2440', '8999'])
})
it('returns no rows when both inputs are empty', () => {
expect(buildTrialBalanceRows(new Map(), [], accountMap)).toEqual([])
})
})