Files
accounted/tests/pg/resolve-active-company-rpc.pg.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

175 lines
7.5 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import { getPool, getClient, withUserContext } from './setup'
import { insertAuthUser, insertCompany, insertCompanyMember, seedCompany } from './fixtures'
// Validates migration 20260723161000_resolve_active_company_rpc:
// 1. resolve_active_company() mirrors the JS resolution exactly: validated
// preference wins, else earliest non-archived membership by
// company_members.created_at, else NULL.
// 2. used_fallback is true exactly when the validated preference is
// absent (middleware's write-back condition).
// 3. NULL auth.uid() (service-role clients) returns ZERO rows by design.
// 4. EXECUTE is granted to authenticated only, not anon.
// 5. Divergence guard: it never disagrees with
// current_active_company_id(), which RLS reads.
const RESOLVE = `SELECT r.company_id::text AS company_id, r.locale, r.used_fallback
FROM public.resolve_active_company() r`
type ResolveRow = { company_id: string | null; locale: string | null; used_fallback: boolean }
async function setPrefs(
userId: string,
activeCompanyId: string | null,
locale?: string,
): Promise<void> {
if (locale === undefined) {
await getPool().query(
`INSERT INTO public.user_preferences (user_id, active_company_id)
VALUES ($1, $2)
ON CONFLICT (user_id) DO UPDATE SET active_company_id = EXCLUDED.active_company_id`,
[userId, activeCompanyId],
)
return
}
await getPool().query(
`INSERT INTO public.user_preferences (user_id, active_company_id, locale)
VALUES ($1, $2, $3)
ON CONFLICT (user_id) DO UPDATE
SET active_company_id = EXCLUDED.active_company_id, locale = EXCLUDED.locale`,
[userId, activeCompanyId, locale],
)
}
describe('resolve_active_company()', () => {
it('resolves a valid preference with used_fallback false and the default locale', async () => {
const { userId, companyId } = await seedCompany()
await setPrefs(userId, companyId)
await withUserContext(userId, async (client) => {
const res = await client.query<ResolveRow>(RESOLVE)
expect(res.rows).toHaveLength(1)
expect(res.rows[0].company_id).toBe(companyId)
expect(res.rows[0].used_fallback).toBe(false)
// locale column is NOT NULL DEFAULT 'sv' (20260521120000): a prefs row
// always carries a locale.
expect(res.rows[0].locale).toBe('sv')
})
})
it('falls back to the first membership with used_fallback true and null locale when there is no prefs row', async () => {
const { userId, companyId } = await seedCompany()
await withUserContext(userId, async (client) => {
const res = await client.query<ResolveRow>(RESOLVE)
expect(res.rows).toHaveLength(1)
expect(res.rows[0].company_id).toBe(companyId)
expect(res.rows[0].used_fallback).toBe(true)
expect(res.rows[0].locale).toBeNull()
})
})
it('orders the fallback by company_members.created_at ASC, not insertion order', async () => {
const userId = await insertAuthUser()
const firstInserted = await insertCompany({ createdBy: userId, name: 'First Inserted AB' })
const backdated = await insertCompany({ createdBy: userId, name: 'Backdated AB' })
await insertCompanyMember({ companyId: firstInserted, userId })
await insertCompanyMember({ companyId: backdated, userId })
// Backdate the SECOND membership: it must win despite later insertion.
await getPool().query(
`UPDATE public.company_members SET created_at = now() - interval '1 day'
WHERE company_id = $1 AND user_id = $2`,
[backdated, userId],
)
await withUserContext(userId, async (client) => {
const res = await client.query<ResolveRow>(RESOLVE)
expect(res.rows[0].company_id).toBe(backdated)
expect(res.rows[0].used_fallback).toBe(true)
})
})
it('ignores a preference pointing at an archived company and falls back', async () => {
const userId = await insertAuthUser()
const archived = await insertCompany({ createdBy: userId, name: 'Archived AB' })
const alive = await insertCompany({ createdBy: userId, name: 'Alive AB' })
await insertCompanyMember({ companyId: archived, userId })
await insertCompanyMember({ companyId: alive, userId })
await getPool().query(`UPDATE public.companies SET archived_at = now() WHERE id = $1`, [
archived,
])
await setPrefs(userId, archived)
await withUserContext(userId, async (client) => {
const res = await client.query<ResolveRow>(RESOLVE)
expect(res.rows[0].company_id).toBe(alive)
expect(res.rows[0].used_fallback).toBe(true)
})
})
it('ignores a preference pointing at a company the user is not a member of', async () => {
const { companyId: foreignCompany } = await seedCompany() // someone else's
const { userId, companyId: ownCompany } = await seedCompany()
await setPrefs(userId, foreignCompany)
await withUserContext(userId, async (client) => {
const res = await client.query<ResolveRow>(RESOLVE)
expect(res.rows[0].company_id).toBe(ownCompany)
expect(res.rows[0].used_fallback).toBe(true)
})
})
it('returns one row with a null company_id but the stored locale for a user with prefs and zero memberships', async () => {
const userId = await insertAuthUser()
await setPrefs(userId, null, 'en')
await withUserContext(userId, async (client) => {
const res = await client.query<ResolveRow>(RESOLVE)
expect(res.rows).toHaveLength(1)
expect(res.rows[0].company_id).toBeNull()
expect(res.rows[0].locale).toBe('en')
expect(res.rows[0].used_fallback).toBe(true)
})
})
it('returns ZERO rows when auth.uid() is NULL (service-role clients)', async () => {
const client = await getClient()
try {
await client.query('BEGIN')
// A claims object with no `sub`: auth.uid() resolves to NULL, the
// shape a service-role/backend connection presents.
await client.query(`SELECT set_config('request.jwt.claims', $1, true)`, [
JSON.stringify({ role: 'authenticated' }),
])
await client.query(`SET LOCAL ROLE authenticated`)
const res = await client.query<ResolveRow>(RESOLVE)
expect(res.rows).toHaveLength(0)
await client.query('ROLLBACK')
} catch (err) {
await client.query('ROLLBACK').catch(() => {})
throw err
} finally {
client.release()
}
})
it('grants EXECUTE to authenticated but not anon', async () => {
const res = await getPool().query<{ anon_can: boolean; authenticated_can: boolean }>(
`SELECT
has_function_privilege('anon', 'public.resolve_active_company()', 'EXECUTE') AS anon_can,
has_function_privilege('authenticated', 'public.resolve_active_company()', 'EXECUTE') AS authenticated_can`,
)
expect(res.rows[0].anon_can).toBe(false)
expect(res.rows[0].authenticated_can).toBe(true)
})
it('never diverges from current_active_company_id(), which RLS reads', async () => {
// Stale-pref scenario: the most divergence-prone shape (pref set, but
// membership on the preferred company is gone).
const { companyId: foreignCompany } = await seedCompany()
const { userId } = await seedCompany()
await setPrefs(userId, foreignCompany)
await withUserContext(userId, async (client) => {
const res = await client.query<{ agrees: boolean }>(
`SELECT (SELECT r.company_id FROM public.resolve_active_company() r)
IS NOT DISTINCT FROM public.current_active_company_id() AS agrees`,
)
expect(res.rows[0].agrees).toBe(true)
})
})
})