Files
accounted/lib/dashboard/__tests__/nav-flags.test.ts
T
4ac7b45c8a perf(layout): dashboard layout in two waves, nav flags as one RPC, local JWT verification (#1946)
The dashboard layout runs on every hard load, hard refresh, company switch
and the 16 router.refresh() sites, and loading.tsx cannot paint until it
resolves. It cost ~20 network calls in 4 sequential waves: a third
getUser() round trip to Supabase Auth (after the proxy's and the route
guard's), the company resolution, then 16 reads including four limit-1
probes whose only job is to decide whether to render the Webshop and
Körjournal nav rows, and an entitlements read that itself ran two waves.

- lib/auth/claims.ts: claimsPinned/userFromClaims extracted from
  require-auth.ts (unchanged) so the dashboard request context shares the
  exact pinning + mapping. getDashboardAuthContext verifies the JWT locally
  and falls back to getUser() only when claims are missing, unpinned or
  unverifiable: the proxy already performed the per-request revocation
  check before the layout runs (same semantics approved for routes on
  2026-07-23).
- Wave 1 (user-keyed, parallel with the company resolution): team
  membership, profile, user preferences and the memberships join, which
  now also supplies the active company's row and role, so the separate
  companies and company_members reads are gone.
- Wave 2 (company-keyed): settings, agent profile, the switcher's settings
  names, entitlements in ONE wave (getCompanyEntitlements takes the
  team_id the join already carries and runs the grants read alongside
  config + subscription), and get_dashboard_nav_flags().
- supabase/migrations/20260826120000_get_dashboard_nav_flags.sql:
  SECURITY INVOKER, STABLE, EXECUTE for authenticated only; RLS applies
  inside. lib/dashboard/nav-flags.ts wraps it with the pre-RPC four-probe
  fallback on PGRST202/42883/42501 (self-hosted not yet migrated, deploy
  ordering) and degrades to hidden rows on any other error.
- tests/pg/dashboard-nav-flags-rpc.pg.test.ts (6): fresh company, active vs
  pending WooCommerce, active Shopify, mileage trips, RLS for a member of
  another company, EXECUTE grants. Unit tests for the wrapper (RPC row,
  single-object payload, each fallback code, other errors) and for the
  entitlements teamId option.

~20 calls / 4 waves -> ~12 calls / 2 waves, 0 auth network calls.

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-26 15:14:49 +02:00

55 lines
2.4 KiB
TypeScript

import { describe, it, expect, vi } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { getDashboardNavFlags } from '../nav-flags'
function makeSupabase(
rpcResult: { data?: unknown; error?: { code?: string; message?: string } | null },
probes: Record<string, unknown[]> = {},
) {
const from = vi.fn((table: string) => {
const chain: Record<string, unknown> = {}
const self: unknown = new Proxy(chain, {
get: (_t, prop) => {
if (prop === 'then') {
return (resolve: (v: unknown) => void) => resolve({ data: probes[table] ?? [], error: null })
}
return () => self
},
})
return self
})
const rpc = vi.fn(async () => ({ data: rpcResult.data ?? null, error: rpcResult.error ?? null }))
return { supabase: { from, rpc } as unknown as SupabaseClient, from, rpc }
}
describe('getDashboardNavFlags', () => {
it('reads both flags from the RPC row and never touches the tables', async () => {
const { supabase, from, rpc } = makeSupabase({ data: [{ has_webshop: true, has_mileage_trips: false }] })
expect(await getDashboardNavFlags(supabase, 'c1')).toEqual({ hasWebshop: true, hasMileageTrips: false })
expect(rpc).toHaveBeenCalledWith('get_dashboard_nav_flags', { p_company_id: 'c1' })
expect(from).not.toHaveBeenCalled()
})
it('accepts a single-object payload and treats null flags as false', async () => {
const { supabase } = makeSupabase({ data: { has_webshop: null, has_mileage_trips: true } })
expect(await getDashboardNavFlags(supabase, 'c1')).toEqual({ hasWebshop: false, hasMileageTrips: true })
})
it.each(['PGRST202', '42883', '42501'])('falls back to the four probes when the RPC is unavailable (%s)', async (code) => {
const { supabase, from } = makeSupabase({ error: { code } }, { webshop_orders: [{ id: 'o1' }] })
expect(await getDashboardNavFlags(supabase, 'c1')).toEqual({ hasWebshop: true, hasMileageTrips: false })
expect(from.mock.calls.map((c) => c[0]).sort()).toEqual([
'mileage_trips',
'shopify_connections',
'webshop_orders',
'woocommerce_connections',
])
})
it('degrades to hidden rows on any other error instead of probing', async () => {
const { supabase, from } = makeSupabase({ error: { code: '57014', message: 'timeout' } })
expect(await getDashboardNavFlags(supabase, 'c1')).toEqual({ hasWebshop: false, hasMileageTrips: false })
expect(from).not.toHaveBeenCalled()
})
})