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>
141 lines
5.1 KiB
TypeScript
141 lines
5.1 KiB
TypeScript
import { clsx, type ClassValue } from "clsx"
|
|
import { twMerge } from "tailwind-merge"
|
|
import { format as formatDateFns, parseISO } from "date-fns"
|
|
|
|
export function cn(...inputs: ClassValue[]) {
|
|
return twMerge(clsx(inputs))
|
|
}
|
|
|
|
export function formatCurrency(amount: number, currency: string = 'SEK'): string {
|
|
return new Intl.NumberFormat('sv-SE', {
|
|
style: 'currency',
|
|
currency,
|
|
minimumFractionDigits: 0,
|
|
maximumFractionDigits: 2,
|
|
}).format(amount)
|
|
}
|
|
|
|
export function formatDate(date: Date | string): string {
|
|
// parseISO interprets bare 'yyyy-MM-dd' as local midnight, not UTC midnight.
|
|
// Using new Date() would shift the displayed day by one in timezones west of
|
|
// UTC for bare date strings — that's an off-by-one we don't want for
|
|
// accounting data.
|
|
const d = typeof date === 'string' ? parseISO(date) : date
|
|
return formatDateFns(d, 'yyyy-MM-dd')
|
|
}
|
|
|
|
/**
|
|
* Date + time for audit / metadata displays: `2026-05-11 14:30`. ISO-ordered
|
|
* and locale-independent (sortable, unambiguous), matching `formatDate`'s
|
|
* accounting convention. Use for "created at" / "last synced" timestamps. For
|
|
* date-only accounting values use `formatDate`; for friendly long-form metadata
|
|
* dates use `formatDateLong`.
|
|
*/
|
|
export function formatDateTime(date: Date | string): string {
|
|
const d = typeof date === 'string' ? parseISO(date) : date
|
|
return formatDateFns(d, 'yyyy-MM-dd HH:mm')
|
|
}
|
|
|
|
/**
|
|
* Bare amount with sv-SE grouping and exactly two decimals, no currency symbol:
|
|
* `1234.5` → `1 234,50`. Use in table cells / inputs where the column header or
|
|
* surrounding context already conveys "kr" and `formatCurrency`'s symbol would
|
|
* be noise. Stays sv-SE in both locales (Swedish accounting convention, not a
|
|
* UI string) — same rule as `formatCurrency`. When you need the SEK symbol, use
|
|
* `formatCurrency`.
|
|
*/
|
|
export function formatAmount(amount: number): string {
|
|
return new Intl.NumberFormat('sv-SE', {
|
|
minimumFractionDigits: 2,
|
|
maximumFractionDigits: 2,
|
|
}).format(amount)
|
|
}
|
|
|
|
/**
|
|
* Whole-krona amount, no decimals, sv-SE grouping: `1234.56` → `1 235`. For
|
|
* compact KPI tiles and rounded summaries.
|
|
*
|
|
* NOTE: not for statutory output. INK2 / NE-bilaga / SRU require *truncation*
|
|
* (`Math.trunc`) per SFL 22:1, not rounding — use the dedicated SRU formatter
|
|
* for those surfaces.
|
|
*/
|
|
export function formatWholeKr(amount: number): string {
|
|
return new Intl.NumberFormat('sv-SE', {
|
|
minimumFractionDigits: 0,
|
|
maximumFractionDigits: 0,
|
|
}).format(amount)
|
|
}
|
|
|
|
/**
|
|
* Long-form date for metadata/audit contexts (e.g. "9 maj 2026" / "May 9, 2026").
|
|
* Use formatDate for transaction/voucher/invoice dates that need to align in tables.
|
|
*
|
|
* The locale arg is the UI language ('sv' | 'en'); default 'sv' keeps existing
|
|
* server-side callers (logs, audit) Swedish without churn. For client UI use
|
|
* the useFormat() hook which pulls the active locale from next-intl.
|
|
*/
|
|
export function formatDateLong(date: Date | string, locale: string = 'sv'): string {
|
|
const d = typeof date === 'string' ? parseISO(date) : date
|
|
const intlLocale = locale === 'en' ? 'en-US' : 'sv-SE'
|
|
return d.toLocaleDateString(intlLocale, {
|
|
day: 'numeric',
|
|
month: 'short',
|
|
year: 'numeric',
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Today's date in Europe/Stockholm, labelled for the bookkeeping agent's system
|
|
* prompt — e.g. "2026-05-27 (onsdag)".
|
|
*
|
|
* Date granularity (no clock time) is deliberate: the agent system prompt is
|
|
* cached (cache_control ttl=1h) and this string sits inside the cached prefix,
|
|
* so a full timestamp would bust the cache on every request while the value
|
|
* actually changes at most once a day. Stockholm time zone — not the server's
|
|
* UTC — so "idag" is right for Swedish users near midnight, where a UTC date can
|
|
* read a day behind.
|
|
*/
|
|
export function swedishToday(now: Date = new Date()): string {
|
|
const date = new Intl.DateTimeFormat('sv-SE', {
|
|
timeZone: 'Europe/Stockholm',
|
|
year: 'numeric',
|
|
month: '2-digit',
|
|
day: '2-digit',
|
|
}).format(now)
|
|
const weekday = new Intl.DateTimeFormat('sv-SE', {
|
|
timeZone: 'Europe/Stockholm',
|
|
weekday: 'long',
|
|
}).format(now)
|
|
return `${date} (${weekday})`
|
|
}
|
|
|
|
export function formatOrgNumber(orgNumber: string): string {
|
|
// Format Swedish org number: XXXXXX-XXXX
|
|
const cleaned = orgNumber.replace(/\D/g, '')
|
|
if (cleaned.length === 10) {
|
|
return `${cleaned.slice(0, 6)}-${cleaned.slice(6)}`
|
|
}
|
|
return orgNumber
|
|
}
|
|
|
|
export function getCompanyDisplayName(settings: { company_name?: string | null }): string {
|
|
return settings.company_name?.trim() || ''
|
|
}
|
|
|
|
export function getCompanyPrimaryName(settings: { company_name?: string | null }): string {
|
|
return settings.company_name?.trim() || ''
|
|
}
|
|
|
|
export function generateInvoiceNumber(): string {
|
|
const year = new Date().getFullYear()
|
|
const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
|
|
return `${year}-${random}`
|
|
}
|
|
|
|
// Shared FX-rate validator — keeps UI, RPC (>= 100000 / <= 0), and the
|
|
// invoices/supplier_invoices CHECK constraints in sync. Single source
|
|
// of truth for the 0 < rate < 100000 bound.
|
|
export function isValidExchangeRate(rate: number | null | undefined): rate is number {
|
|
return rate != null && rate > 0 && rate < 100000
|
|
}
|