0b86901a2b
* feat(lib): add canonical money + format + fetch primitives (audit Tier 0) Foundation for post-audit cleanup: shared primitives so subsequent refactors import one helper instead of reinventing (the duplication the audit found). - lib/money.ts: canonical roundOre/ORE_TOLERANCE (+ equalOre/isZeroOre/sumOre); lib/bokslut/rounding.ts re-exports for back-compat - lib/utils.ts: formatAmount, formatWholeKr, formatDateTime - lib/hooks/use-fetch.ts: generic client fetch hook (abort, bilingual errors, refetch) - components/common/DataState.tsx: loading/error/empty wrapper over Skeleton/EmptyState - messages: common.retry / common.load_error (sv+en) - tests: 16 tests incl. the 1.005 half-ore case and locale-robust format assertions Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * ci(guards): ratchet against new MFA-bypassing routes and naive ore-rounding Adds scripts/checks/no-new-antipatterns.mjs + committed baseline. Fails CI only when a PR ADDS a route hand-rolling supabase.auth.getUser() (which skips MFA AAL2 enforcement) or a new Math.round(x*100)/100. Baseline: 178 raw-auth routes, 668 naive rounds — ratchets down as the A1 (route-auth) and D1 (rounding) migrations land. Wired into core-build.yml; green at baseline. Note: scripts/ is gitignored (.gitignore:70 '/scripts') yet tracks 39 files via force-add; these two were force-added to match that existing pattern. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(api,errors): enforce MFA on journal-entry mutation routes via withRouteContext (A1) Migrates the 4 journal-entry mutation routes (commit, correct, reverse, recordate) off hand-rolled supabase.auth.getUser() onto withRouteContext, which enforces MFA AAL2 (requireAuth) + non-viewer role (requireWrite) and routes thrown errors through the canonical errorResponse envelope. Fixes audit finding A1 for the most compliance-critical mutations and folds in C8 for these routes (drops bookkeepingErrorResponse; they now emit message_en). Also fixes a latent bug: errorResponse()/extractBookkeepingDetails only handled 11 of 15 typed bookkeeping errors, so MeaninglessCorrection / NoOpenPeriodForDate / TargetPeriodClosed / TargetPeriodLocked silently degraded to a generic 500 (affecting existing v1 callers too). Adds the 4 missing registry codes + extract cases -> correct 400/409. Behavior change: untyped engine throws now return the canonical 500 envelope instead of 400+raw-string; typed errors keep their status (verified against the registry). Tests updated to the realistic typed-error contract + a 403 write-gate test on commit. Updates .claude/rules/api-routes.md to prescribe withRouteContext. Ratchets the antipattern guard 178 -> 174. Full unit suite green (5023); tsc: no new errors. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(api): enforce MFA on salary run authorization routes via withRouteContext (A1) Migrates the salary-run lifecycle write routes (approve, paid, revert) — the highest-PII A1 surface — off hand-rolled supabase.auth.getUser() onto withRouteContext (enforces MFA AAL2 + non-viewer role). Explicit { error } returns are preserved unchanged (passed through the wrapper); only auth changes, so no error-shape regression. Salary unit suite green (8). Ratchets the antipattern guard 174 -> 171. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * review: address PR #646 bot findings - guard: match withRouteContext/requireAuth at the CALL site (withRouteContext[<(]), not a bare import — closes the false-negative greptile flagged. It surfaced app/api/sandbox/seed (hand-rolled getUser; the loose regex had matched a code comment). Switched that route to requireAuth() — the documented stopgap for routes that can't use withRouteContext (it runs before a company exists; anonymous users, so MFA is a no-op but the auth path is now consistent). Guard stays at 171. - money.test: add the negative half-ore case roundOre(-1.005) === -1 to lock the rounding direction against regressions. - use-fetch: document keep-previous-data + deferred-loading (effect-tick) semantics. - structured-errors: drop the BFL 5 kap. 5 § citation from MEANINGLESS_CORRECTION per the swedish-compliance bot (5 § governs correction procedure, not the no-op precondition). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * review: enrich wrapper error logging + document sandbox GDPR controls (PR #646) - with-route-context: log unhandled errors and route errorResponse through the resolved { userId, companyId } logger, not just { requestId, operation } — closes the OWASP V16 audit-trail finding for all 82+ routes using the wrapper. Documented in the JSDoc. - sandbox/seed: document the GDPR Art.32 compensating controls for the anonymous write path (anonymous-only, /24 rate limit, synthetic demo data, own-company RLS scope). No functional change — the flagged behaviour is pre-existing by design; this records the reasoning inline. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
113 lines
4.1 KiB
TypeScript
113 lines
4.1 KiB
TypeScript
'use client'
|
|
|
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
import { useLocale } from 'next-intl'
|
|
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
|
|
|
/**
|
|
* Canonical client data-fetching hook.
|
|
*
|
|
* Replaces the hand-rolled `useState(loading)` + `useState(error)` + `useEffect`
|
|
* + bare `fetch()` block repeated across ~85 components. Gives every caller the
|
|
* same behaviour for free:
|
|
*
|
|
* - cancels the in-flight request on unmount / url change (AbortController), so
|
|
* a slow response can't land after the component moved on (no stale state,
|
|
* no "set state on unmounted component" races);
|
|
* - routes errors through the bilingual `getErrorMessage()` using the active
|
|
* UI locale, so error copy is consistent and localized;
|
|
* - exposes `refetch()` for retry / post-mutation refresh.
|
|
*
|
|
* Behaviour notes (intentional):
|
|
* - `data` is NOT cleared on `refetch()` or url change — it keeps the previous
|
|
* result while the new request is in flight (keep-previous-data), so lists
|
|
* don't blank out on refresh. Read `loading` to show a pending indicator.
|
|
* - When `url`/`enabled` start inactive and later become active, `loading`
|
|
* flips true on the effect tick, not synchronously on the activating render.
|
|
* Pair with `DataState` (which branches on `loading` first) to avoid a flash.
|
|
*
|
|
* Response convention: the JSON body is returned as-is, typed as `T`. Most
|
|
* Accounted routes wrap payloads as `{ data: ... }`, so the common usage is
|
|
* `useFetch<{ data: Account[] }>(...)` then read `result.data?.data`. Pass
|
|
* `select` to unwrap/transform at the hook boundary instead.
|
|
*
|
|
* @example
|
|
* const { data, loading, error, refetch } = useFetch<Account[]>(
|
|
* '/api/bookkeeping/accounts',
|
|
* { select: (body) => body.data ?? [] },
|
|
* )
|
|
*/
|
|
export interface UseFetchOptions<T, R> {
|
|
/** Skip the request until true (e.g. waiting on a dependency). Default true. */
|
|
enabled?: boolean
|
|
/** Transform/unwrap the parsed JSON body before it reaches `data`. */
|
|
select?: (body: T) => R
|
|
/** Extra `fetch` init (headers, etc.). The AbortController signal is merged in. */
|
|
init?: Omit<RequestInit, 'signal'>
|
|
}
|
|
|
|
export interface UseFetchResult<R> {
|
|
data: R | null
|
|
loading: boolean
|
|
error: string | null
|
|
/** Re-run the request. Safe to call from event handlers. */
|
|
refetch: () => void
|
|
}
|
|
|
|
export function useFetch<T = unknown, R = T>(
|
|
url: string | null,
|
|
options: UseFetchOptions<T, R> = {},
|
|
): UseFetchResult<R> {
|
|
const { enabled = true, select, init } = options
|
|
const locale = useLocale() as ErrorLocale
|
|
|
|
// Keep select/init out of the effect deps without re-running on every render.
|
|
const selectRef = useRef(select)
|
|
selectRef.current = select
|
|
const initRef = useRef(init)
|
|
initRef.current = init
|
|
|
|
const active = enabled && url != null
|
|
const [data, setData] = useState<R | null>(null)
|
|
const [loading, setLoading] = useState<boolean>(active)
|
|
const [error, setError] = useState<string | null>(null)
|
|
const [nonce, setNonce] = useState(0)
|
|
|
|
const refetch = useCallback(() => setNonce((n) => n + 1), [])
|
|
|
|
useEffect(() => {
|
|
if (!active || url == null) {
|
|
setLoading(false)
|
|
return
|
|
}
|
|
|
|
const controller = new AbortController()
|
|
setLoading(true)
|
|
setError(null)
|
|
|
|
;(async () => {
|
|
try {
|
|
const res = await fetch(url, { ...initRef.current, signal: controller.signal })
|
|
const body = await res.json().catch(() => null)
|
|
if (!res.ok) {
|
|
throw new Error(
|
|
getErrorMessage(body ?? { error: res.statusText }, { locale, statusCode: res.status }),
|
|
)
|
|
}
|
|
if (controller.signal.aborted) return
|
|
const transform = selectRef.current
|
|
setData((transform ? transform(body as T) : (body as unknown as R)))
|
|
} catch (err) {
|
|
if (controller.signal.aborted || (err as Error)?.name === 'AbortError') return
|
|
setError(getErrorMessage(err, { locale }))
|
|
} finally {
|
|
if (!controller.signal.aborted) setLoading(false)
|
|
}
|
|
})()
|
|
|
|
return () => controller.abort()
|
|
}, [url, active, nonce, locale])
|
|
|
|
return { data, loading, error, refetch }
|
|
}
|