f24b26a139
* fix(security): gate replace_sie_import behind owner/admin membership The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no company_members lookup, no auth.uid() reference and no unauthorized raise, while setting gnubok.allow_delete to disarm the BFL immutability and retention triggers. Any caller holding a company_id and an import id could hard delete another tenant's verifikationer. Confirmed live in production. Applies the same fail closed owner/admin guard that undo_sie_import already carries (migration 20260624120000), resolving the actor from COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then revokes EXECUTE from PUBLIC and anon. search_path and the raised statement_timeout are restated, since CREATE OR REPLACE drops settings that are not repeated. userId is a required parameter on replaceSIEImport: the service client has a NULL auth.uid(), so a caller without an explicit actor now fails to compile rather than hitting the closed gate at runtime. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): validate arcim OAuth callback state server side The callback route is skipAuth and decoded the state parameter as plain base64url JSON, trusting consentId and provider from it. A one time code was minted at flow start and never read. An unauthenticated attacker who learned a consent id could run an OAuth flow on their own provider account and post the callback with a forged state, landing their tokens on another tenant's consent, so the victim's next migration imported the attacker's ledger. State is now an opaque randomBytes(32) pointer to a provider_otc row, consumed by a single atomic UPDATE guarded on used_at IS NULL and expires_at, so a replay loses the row lock race and updates nothing. provider is read from provider_consents rather than trusted from the client. provider_otc already existed for exactly this purpose and was never wired up. Also scopes getConsent to an owning company, closing a cross tenant status oracle where the preview and migrate paths echoed a consent's status before the scoped check ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): scope documents storage to company_id (phase A) The documents bucket policies matched on auth.uid(), and upload keys were documents/{userId}/..., so company membership was never consulted. Removing a member revoked nothing: their session still authenticated and they kept direct Storage read access to every receipt, supplier invoice and bank statement they had uploaded. The same bug was fixed for sie-files in 20260416120000; this bucket was left behind. Phase A is additive. Company scoped policies are added alongside the uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and reads accept either layout so nothing breaks mid migration. Phase C, which drops the old policies, is gated on the backfill reporting zero remaining legacy prefix objects. The policy compares the company segment as text rather than casting to uuid the way sie-files does: this bucket holds keys whose second segment is not a uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix qual runs before the cast, so a planner reordering would raise 22P02 and fail the whole query instead of filtering the row out. deleteDocument now removes both candidate keys. Removing only the stored pointer would leave a readable orphan copy of a document the user asked to erase. The backfill script is included but has never been run. It defaults to dry run, refuses .env.local by name, and verifies each copy is readable and SHA-256 identical before repointing the row. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): enforce events:read scope and membership on /api/events This was the only one of the three validateApiKey call sites with no downstream guard: v1 and the MCP server both check scope and re-verify company membership, this route did neither. An events:read scope existed and was documented as gating the endpoint but was never called, so a legacy key falling back to DEFAULT_SCOPES read the full log. The bound company id went straight from the api_keys row into a service role query, so a key whose user had been removed from the company kept reading. Adds the scope check before any database access, re-verifies company_members with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead of ignoring it, applies minimisePayload so the pull surface can never return a wider payload than the push surface, and replaces the three flat error strings with the canonical envelope. Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is gated on mutations in with-api-v1, so a read gets the same treatment as every other v1 read endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf(bookkeeping): sweep remaining journal_entries!inner embeds A previous refactor removed this pattern from lib/reports and introduced fetchEntryLines, but the class was never swept. Seventeen sites remained and had become the top application consumer of production database time: measured across the resulting query shapes, 32,694 calls and 25,848 seconds of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at 7,962ms against the 8s statement_timeout, which surfaced to users as 500s on the booking path. PostgREST compiles an embed with filters on the embedded side into a correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops Postgres reordering the join, so each query walked the whole journal_entry_lines table across all tenants. Driving from the entries side instead turns that into two indexed round trips. Converted sites keep their existing shape: the helper reattaches the parent entry under the same key the embed produced. Several conversions also remove a latent silent truncation where an unpaginated query was capped at PostgREST's 1000 row ceiling. Two deliberate exceptions. The free text ilike legs of the MCP display query stay on the embed, because each is capped at legLimit and that cap drives the truncation contract the tool reports, while the helper is unbounded. The accounts route moves to the existing get_account_usage_counts RPC instead, since its embed was a head count and the helper returns rows. commitEntry's write path is untouched: the change there is confined to the read query of the pre-commit dimension rule check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): anchor v1 list cursors on created_at Page two returned page one, forever, while still advertising a fresh next_cursor. The three routes sorted by and encoded a Postgres date column, which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor timestamp as full ISO-8601 and returned null, so the keyset filter was never applied and has_more never went false. An integrator syncing verifikat looped on the newest rows indefinitely. The transactions route already solved this and its comment names the trap; the fix was never ported. All three now order and encode on created_at with an id tie break, matching the transactions keyset predicate exactly. ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change sort semantics on the route that currently works. Default ordering therefore moves from business date to insert order. Every business date is still on the row, and the invoices list gains date_from and date_to filters so a date range is still reachable; the other two already had them. The tests use an in-memory PostgREST that actually evaluates the filters, because the repo's pass-through mock cannot catch this class of bug: the bug is that the filter is never sent. They walk to exhaustion with a hard iteration cap, so an unterminated walk fails instead of hanging. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): separate dry run from commit in the idempotency hash The request hash was built from url.pathname, which excludes the query string, so a dry run and its commit hashed identically. Following the flow documented in dry-run.ts, re-issuing the request with the same Idempotency-Key returned the cached preview with Idempotent-Replayed set and wrote nothing, while reporting 200. An agent or integrator saw success for a write that never happened. dry_run is folded into the hash only when true, not as an unconditional boolean. Including it as false would change the hash of every ordinary write, and with a 24h idempotency TTL any key in flight across the deploy would fail the request_hash comparison and 409 on a legitimate retry. Both hash call sites now go through one shared helper so they cannot drift into a permanent cache miss, and dry run responses are no longer stored at all. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: install the Bedrock SDK out of tree in the compliance review The Swedish accounting compliance gate had failed ten consecutive runs and so was posting nothing. With --no-package-lock npm discarded the lockfile and re-resolved the whole tree from package.json, floating @hookform/resolvers to 5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0. Installing into the parent of the checkout resolves only that one package, so an unrelated peer conflict can never take the gate down again. Node still finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH would not have worked, as it is CommonJS only. --legacy-peer-deps was rejected because it masks future genuine peer conflicts and still reifies the full tree. The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that package.json and check:guards enforce after the streaming outage. That drift went unnoticed because the pin guard only inspects package.json and the lockfile, never workflow files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * build(docker): generate crontabs from vercel.json vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were byte identical to each other. Self hosted deployments therefore never sent recurring invoices, never dispatched webhooks and never cleaned up idempotency keys. tax-deadlines also ran once a year on 2 January instead of daily, and documents/verify weekly instead of daily. Extension crons are included rather than excluded. The Dockerfile copies the whole tree before building, so every extension cron route is compiled into the image regardless of the enabled preset, and each returns 200 when its extension is unconfigured, so curl -sf logs no failure. Two such entries were already present in the crontab for extensions absent from the preset, which settles the intent. documents/verify is treated as drift rather than a self hosted concession: the weekly cadence was present in the hosted crontab too, and the run is capped at 200 documents walking a nulls-first queue, so weekly drains the integrity queue seven times slower on a check that exists for BFL retention. webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day on self hosted. A gentler tick would silently stretch the first retry, since the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line place to change that. A parity test asserts the path sets match minus a documented exclusion list, and ratchets three cron routes that are currently scheduled nowhere so they are named rather than silently rotting. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(observability): add a provider agnostic error sink There is no error tracking in this codebase: logs go to console and Vercel retention and nowhere else, nothing alerts on the 16 cron jobs, and seven code comments across lib, app, components and extensions asserted that Sentry captures errors when Sentry is not a dependency. The two most recent bug fixes on this repo were both discovered by customer email. This adds the sink, not a vendor. No dependency is taken: the interface has a no-op default and a registration point, so behaviour is unchanged until an adapter is registered. Releases are tagged from the build id already inlined by next.config.ts. Redaction moved out of lib/logger.ts into a leaf module that both the logger and the sink import, so there is one denylist and no path from application data to a third party can skip the personnummer regex, including direct sink calls that bypass the logger. That matters here because these logs carry personnummer and financial data. verifyCronSecret now reports its own 401s, which covers all 16 jobs without touching a route file and catches the case where CRON_SECRET is rotated without updating the scheduler and every job silently 401s forever. The threshold is one failure rather than the backup alert's three: suppressing the first occurrence is precisely how an outage stays invisible. The seven misleading comments are corrected to describe what the code actually does, including the two cases that still are not covered: the client side one, since the sink is server side, and a warn level call that is not forwarded. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: remediate the 2026-07-26 similar-sweep findings across all surfaces Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with one agent per finding; every behavioural fix carries a regression test proven to fail at HEAD. Full status, corrections to the sweep, refusals and open decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md. Structural roots closed: - resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking 1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING - ledger-line-amount.ts: journal_entry_lines.currency labels the document, not the amount; SQL pre-filter decoy proven and fixed - sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the exploitable salary payslip-line PATCH and KPI preferences sinks fixed - tests/schema: migration-replay phantom-column guard (13k+ refs, closed CHECK sets, onConflict targets); found 28 real defects, all fixed, all four baselines now empty - three new ratchet guards: sek-labelled-amount, cross-extension-import, ungated-extension-route Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap), RC input VAT mismatch wired on web + both MCP callers, missing-underlag resource delegates to the shared RPC predicate, push-notifications consent polarity fail-closed, deadlines undo honours requested state, silent-failure and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/ Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites with isSwedishUserMessage extended. Also includes the parallel session's MCP invoice tools (update_invoice, recurring schedules, invoice deliveries) which share files with the sweep work and are verified green together. 13 new migrations are NOT applied anywhere; they apply via branch merge. 20260726120000 backfills 1247 supplier-invoice rows. pg tests for new DDL are written but unrun (no local Postgres). Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0 errors, check:guards passing, MCP payload 57475/57500. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): rename replace_sie_import migration off main's 20260726090000 version origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping our replace_sie_import migration on the same version would abort the Supabase apply with a schema_migrations_pkey duplicate at merge time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate pre-publish deep-review findings across all slices A 13-agent review of the full branch diff surfaced 1 critical, 5 high and ~45 further findings; this commit resolves them in one pass: - replace_sie_import / undo_sie_import: p_user_id honored only for service_role callers; any other caller is pinned to auth.uid() (impersonation gate bypass), authz raise errcode 42501 mapped to a Swedish 403 in the route, new caller-guard migration for undo - bulk_book_transactions refuses homogeneous non-SEK batches instead of writing foreign magnitudes into SEK ledger columns - credit-note cap trigger: company-match on credited_invoice_id, no cross-tenant figures in exception text - link_voucher RPCs resolve NULL invoice currency as SEK end to end - personal-number ciphertext CHECK split into NOT VALID + VALIDATE - same-currency foreign settlements clear 1510 at booking rate and book realized diff to 3960/7960; rate-less foreign write paths refuse - receivables revaluation covers partially_paid and outstanding amounts - period lock guard paginates candidates past the PostgREST 1000 cap - documents: service-client storage removals after authz, dual-layout reads in integrity cron and archive export, backfill delete-source sweep actually deletes with hash verification and shared-key grouping - invoice matching normalizes NULL/lowercase currencies (regression), duplicate candidates stop claiming amount matches they never ran - match-invoice aborts on any booking failure (no paid-without-verifikat) - refresh-exchange-rate reverts on concurrent booking (TOCTOU window) - KPI preferences upsert arbiter aligned to the company-scoped constraint - personnummer_last4 stripped from all salary responses incl. MCP tools - worked-hours batch restores destroyed rows on conflict and error paths - MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit on tag_journal_lines overflow, auto_send schedules stage as high risk - observability sink redacts emails/IBANs/API keys and keeps redacted stacks in prod; assorted small guards (safe-return-to /@, dry_run=True, cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings call removed) Full dispositions, deferred items and hand-verified accounting numbers are documented in the PR body and DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(personnummer): implement masking and encryption for personal numbers with tests * fix(review): address CI and compliance-bot findings for PR #1215 pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role GUC, so both service-role simulations (runAsServiceRole and the invoice-delivery test's local helper) never satisfied auth.role() = 'service_role' and every legitimate p_user_id path failed closed; the shared helper now sets both GUC shapes plus SET LOCAL ROLE with a fail-loud sanity check, and the delivery test reuses it. The link-voucher migration had recreated both RPCs from pre-rewrite file text, reintroducing the NULL-unsafe membership pattern the null-safe-tenant-guards ratchet bans; both guards now use public.caller_is_company_member() with all currency changes preserved. Compliance bots: the customers export now emits the standard masked form instead of raw AES-256-GCM ciphertext in the Org-/personnummer column, and maskCustomerRow returns a non-round-trippable placeholder on decrypt failure instead of 500ing the list. MCP parity: gnubok_lock_period's staging pre-check now runs the exact countUnbookedInPeriod the commit path enforces (exported from period-service; local mirror deleted), and gnubok_agi_status resolves AGI state run-scoped so a correction run no longer renders as already filed. Declined with evidence: PR-Agent's opening-balances null-zeroing concern (all mergeable columns are NOT NULL with defaults per 20260713101000). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): address codex review findings on PR #1215 - restore 20260726140000 to its preview-recorded content and restate the NULL-safe tenant guard under 20260727130000: a recorded migration version never re-runs, so the in-place edit could not reach the preview branch - replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap warning texts and update the pinned test expectations - drop the em dash in the fiscal-periods route comment - strip trailing whitespace in import-existing.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): raise timeout on real PDF render tests renderToBuffer does real @react-pdf layout work and exceeds the 5s default when the full suite saturates the CPU; tests pass in isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
617 lines
24 KiB
TypeScript
617 lines
24 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import type { SourceSignals } from './schemas'
|
|
import { loadActiveEmployeeCount } from './employee-facts'
|
|
|
|
// Atom registry index row: the metadata-only shape the composer sees when
|
|
// picking a loadout. We never send full atom bodies to the Opus call;
|
|
// metadata is enough for selection.
|
|
export interface AtomRegistryIndexRow {
|
|
id: string
|
|
tier: 'horizontal' | 'vertical' | 'modifier'
|
|
title: string
|
|
description: string
|
|
sni_prefixes: string[]
|
|
trigger_signals: Record<string, unknown>
|
|
estimated_tokens: number
|
|
version: number
|
|
}
|
|
|
|
export async function loadAtomRegistryIndex(
|
|
supabase: SupabaseClient,
|
|
): Promise<AtomRegistryIndexRow[]> {
|
|
const { data, error } = await supabase
|
|
.from('agent_atom_registry')
|
|
.select('id, tier, title, description, sni_prefixes, trigger_signals, estimated_tokens, version')
|
|
.eq('is_active', true)
|
|
.is('parent_atom_id', null) // top-level skills only; reference children are load-on-demand
|
|
.order('id')
|
|
if (error) throw new Error(`Failed to load agent_atom_registry: ${error.message}`)
|
|
return (data ?? []) as AtomRegistryIndexRow[]
|
|
}
|
|
|
|
export async function loadCompanyTicSnapshot(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
): Promise<{ snapshot: Record<string, unknown> | null; fetchedAt: string | null; name: string; entityType: string }> {
|
|
const { data, error } = await supabase
|
|
.from('companies')
|
|
.select('name, entity_type, tic_snapshot, tic_snapshot_fetched_at')
|
|
.eq('id', companyId)
|
|
.single()
|
|
if (error) throw new Error(`Failed to load company ${companyId}: ${error.message}`)
|
|
return {
|
|
snapshot: (data?.tic_snapshot as Record<string, unknown> | null) ?? null,
|
|
fetchedAt: (data?.tic_snapshot_fetched_at as string | null) ?? null,
|
|
name: data?.name ?? '',
|
|
entityType: data?.entity_type ?? '',
|
|
}
|
|
}
|
|
|
|
// Known facts from `company_settings`: the settings forms persist these
|
|
// (moms_period, fiscal_year_start_month, f_skatt, employer facts, city).
|
|
// Composer uses them as KNOWN inputs so it stops generating verification
|
|
// questions about already-settled values.
|
|
//
|
|
// Employees are NOT in here as a headcount: this select used to name
|
|
// `employee_count` and `has_employees`, neither of which exists on
|
|
// company_settings, which made PostgREST reject the whole select (42703) and
|
|
// left every field below null too. The employer facts that do exist are
|
|
// `employer_registered` (nullable: null = never attested) and `pays_salaries`;
|
|
// lib/agent/composer/employee-facts.ts turns them plus the live `employees`
|
|
// count into the derived answer.
|
|
export interface CompanySettingsForComposer {
|
|
city: string | null
|
|
moms_period: string | null
|
|
fiscal_year_start_month: number | null
|
|
f_skatt: boolean | null
|
|
vat_registered: boolean | null
|
|
employer_registered: boolean | null
|
|
pays_salaries: boolean | null
|
|
accounting_method: string | null
|
|
}
|
|
|
|
export async function loadCompanySettings(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
): Promise<CompanySettingsForComposer | null> {
|
|
const { data } = await supabase
|
|
.from('company_settings')
|
|
.select(
|
|
'city, moms_period, fiscal_year_start_month, f_skatt, vat_registered, employer_registered, pays_salaries, accounting_method',
|
|
)
|
|
.eq('company_id', companyId)
|
|
.maybeSingle()
|
|
return (data ?? null) as CompanySettingsForComposer | null
|
|
}
|
|
|
|
// Whether the currently-onboarding user is a confirmed director / signatory
|
|
// at this company per BankID CompanyRoles. When true, the narrative is safe
|
|
// to use second-person ownership voice ("Du driver…"); when false (manual-
|
|
// orgnr signup, accountant-on-behalf-of, etc.) the narrative falls back to
|
|
// neutral third-person ("Coredination AB är…") so we don't put words about
|
|
// ownership in the user's mouth.
|
|
//
|
|
// We match the user's enrichment row against this company's org_number.
|
|
// `companyId` is the Accounted UUID: we need to read the orgnr from
|
|
// `companies` to do the match. Cheap (single SELECT each) and only runs once
|
|
// per agent build.
|
|
//
|
|
// Director-like positions per Bolagsverket: 'ceo', 'boardMember', 'chairman',
|
|
// 'externalSignatory'. Deputy positions ('deputyBoardMember') and external
|
|
// auditors are intentionally excluded: they don't run the company day-to-day.
|
|
const DIRECTOR_POSITION_TYPES = new Set([
|
|
'ceo',
|
|
'boardMember',
|
|
'chairman',
|
|
'externalSignatory',
|
|
// Lowercase variants in case TIC normalises differently
|
|
'CEO',
|
|
'BoardMember',
|
|
'Chairman',
|
|
'ExternalSignatory',
|
|
])
|
|
|
|
export async function loadUserDirectorship(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
): Promise<{ confirmedDirector: boolean }> {
|
|
// Read this company's org_number: the BankID CompanyRoles row keys on
|
|
// companyRegistrationNumber, not the Accounted company UUID.
|
|
const { data: companyRow } = await supabase
|
|
.from('companies')
|
|
.select('org_number')
|
|
.eq('id', companyId)
|
|
.single()
|
|
const orgNumber = (companyRow?.org_number as string | null)?.replace(/[\s-]/g, '')
|
|
if (!orgNumber) return { confirmedDirector: false }
|
|
|
|
// Read the active user's enrichment row. Composer runs inside the user's
|
|
// request context (RLS-scoped client), so .maybeSingle() only sees the row
|
|
// for the authenticated user: no need to join through company_members.
|
|
const { data: enrichmentRow } = await supabase
|
|
.from('bankid_enrichment')
|
|
.select('company_roles')
|
|
.maybeSingle()
|
|
const roles = (enrichmentRow?.company_roles ?? []) as Array<{
|
|
companyRegistrationNumber?: string
|
|
positionTypes?: string[]
|
|
positionEnd?: string | null
|
|
}>
|
|
if (!Array.isArray(roles) || roles.length === 0) return { confirmedDirector: false }
|
|
|
|
const match = roles.find(
|
|
(r) => r.companyRegistrationNumber?.replace(/[\s-]/g, '') === orgNumber,
|
|
)
|
|
if (!match) return { confirmedDirector: false }
|
|
|
|
// Position must be a director-type AND not already ended.
|
|
const nowIso = new Date().toISOString()
|
|
if (match.positionEnd && match.positionEnd < nowIso) return { confirmedDirector: false }
|
|
const positions = match.positionTypes ?? []
|
|
const isDirector = positions.some((p) => DIRECTOR_POSITION_TYPES.has(p))
|
|
return { confirmedDirector: isDirector }
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Currency-aware magnitudes
|
|
// ---------------------------------------------------------------------------
|
|
//
|
|
// `transactions.amount` is denominated in `transactions.currency`, not in SEK.
|
|
// The SEK value of a foreign row lives in `amount_sek` (written at ingest) or
|
|
// is derivable from `exchange_rate`; a foreign row carrying neither has no
|
|
// known SEK value at all. Adding raw `amount` across rows and labelling the
|
|
// total "kr" therefore invents a magnitude out of thin air.
|
|
//
|
|
// That matters more here than in an ordinary report: these summaries are the
|
|
// input to the model that writes the company's standing agent instructions, so
|
|
// a wrong magnitude is baked into durable instructions rather than misleading
|
|
// one answer. Every rollup below therefore carries three things instead of one
|
|
// number: the SEK total of the rows whose SEK value is actually known, the
|
|
// native total per currency (covering every row), and the count of rows
|
|
// deliberately left out of the SEK total.
|
|
export interface CurrencyMagnitude {
|
|
// SEK total of the rows with a known SEK value. 0 when no row has one, so
|
|
// always read `rows_without_sek` before treating this as the magnitude.
|
|
//
|
|
// Named `abs_amount` (not `abs_amount_sek`) because `SourceSignals` persists
|
|
// this shape in `agent_profiles.source_signals`; renaming would silently
|
|
// change what older snapshots mean.
|
|
abs_amount: number
|
|
// Native totals per currency, covering EVERY row including the ones with no
|
|
// SEK equivalent. SEK first, then descending. Amounts in different
|
|
// currencies are never added together.
|
|
by_currency: { currency: string; abs_amount: number }[]
|
|
// Rows with a foreign amount and neither `amount_sek` nor a usable
|
|
// `exchange_rate`. These are NOT part of `abs_amount`.
|
|
rows_without_sek: number
|
|
}
|
|
|
|
interface AmountRow {
|
|
amount: number | string | null
|
|
currency?: string | null
|
|
amount_sek?: number | string | null
|
|
exchange_rate?: number | string | null
|
|
}
|
|
|
|
function toFiniteNumber(value: unknown): number | null {
|
|
if (value == null || value === '') return null
|
|
const n = Number(value)
|
|
return Number.isFinite(n) ? n : null
|
|
}
|
|
|
|
function rowCurrency(row: AmountRow): string {
|
|
const raw = typeof row.currency === 'string' ? row.currency.trim().toUpperCase() : ''
|
|
return raw.length > 0 ? raw : 'SEK'
|
|
}
|
|
|
|
// SEK value of one row, or null when there genuinely is none. Mirrors the
|
|
// resolution order used when booking (lib/bookkeeping/currency-utils.ts) but
|
|
// deliberately drops its final fallback: that one returns the raw foreign
|
|
// amount when no rate is stored, which for a summary reads as "500 EUR is
|
|
// 500 kr". For this input a missing rate must read as unknown.
|
|
function rowSekAmount(row: AmountRow): number | null {
|
|
const amount = toFiniteNumber(row.amount)
|
|
if (amount == null) return null
|
|
if (rowCurrency(row) === 'SEK') return Math.abs(amount)
|
|
const stored = toFiniteNumber(row.amount_sek)
|
|
if (stored != null) return Math.abs(stored)
|
|
const rate = toFiniteNumber(row.exchange_rate)
|
|
if (rate == null || rate <= 0) return null
|
|
return Math.abs(amount * rate)
|
|
}
|
|
|
|
interface MagnitudeBucket {
|
|
sek: number
|
|
native: Map<string, number>
|
|
rowsWithoutSek: number
|
|
}
|
|
|
|
function newMagnitudeBucket(): MagnitudeBucket {
|
|
return { sek: 0, native: new Map(), rowsWithoutSek: 0 }
|
|
}
|
|
|
|
// Folds one row into a bucket and returns its SEK value (null when unknown).
|
|
// Rows with no usable `amount` at all are skipped rather than counted as a
|
|
// currency gap: they are missing data, not a missing exchange rate.
|
|
function addRowToMagnitude(bucket: MagnitudeBucket, row: AmountRow): number | null {
|
|
const amount = toFiniteNumber(row.amount)
|
|
if (amount == null) return null
|
|
const currency = rowCurrency(row)
|
|
bucket.native.set(currency, (bucket.native.get(currency) ?? 0) + Math.abs(amount))
|
|
const sek = rowSekAmount(row)
|
|
if (sek == null) {
|
|
bucket.rowsWithoutSek++
|
|
} else {
|
|
bucket.sek += sek
|
|
}
|
|
return sek
|
|
}
|
|
|
|
function finalizeMagnitude(bucket: MagnitudeBucket): CurrencyMagnitude {
|
|
const by_currency = Array.from(bucket.native.entries())
|
|
.map(([currency, abs_amount]) => ({
|
|
currency,
|
|
abs_amount: Math.round(abs_amount * 100) / 100,
|
|
}))
|
|
.sort((a, b) => {
|
|
if (a.currency === b.currency) return 0
|
|
if (a.currency === 'SEK') return -1
|
|
if (b.currency === 'SEK') return 1
|
|
return b.abs_amount - a.abs_amount
|
|
})
|
|
return {
|
|
abs_amount: Math.round(bucket.sek * 100) / 100,
|
|
by_currency,
|
|
rows_without_sek: bucket.rowsWithoutSek,
|
|
}
|
|
}
|
|
|
|
// True when the whole magnitude is plain SEK with nothing unresolved, i.e. the
|
|
// only case where it may be rendered as a single "kr" figure.
|
|
export function isSekOnlyMagnitude(m: CurrencyMagnitude): boolean {
|
|
return m.rows_without_sek === 0 && m.by_currency.every((c) => c.currency === 'SEK')
|
|
}
|
|
|
|
// Ranking key for magnitudes with no usable SEK total: the largest single
|
|
// currency total. Ordering only, never rendered, so it never implies that
|
|
// amounts in different currencies are comparable money.
|
|
function largestNativeTotal(m: CurrencyMagnitude): number {
|
|
return m.by_currency.reduce((max, c) => (c.abs_amount > max ? c.abs_amount : max), 0)
|
|
}
|
|
|
|
// Splits a counterparty rollup into a SEK-ranked top list plus the ones whose
|
|
// magnitude cannot be expressed in SEK and would otherwise vanish at the
|
|
// slice (they rank as 0 kr). The second list is what keeps "no stored exchange
|
|
// rate" visible instead of silently excluded.
|
|
function rankCounterparties<T extends CurrencyMagnitude & { name: string }>(
|
|
rows: T[],
|
|
topLimit: number,
|
|
unconvertibleLimit: number,
|
|
): { top: T[]; unconvertible: T[] } {
|
|
const ranked = [...rows].sort((a, b) => b.abs_amount - a.abs_amount)
|
|
const top = ranked.slice(0, topLimit)
|
|
const inTop = new Set(top.map((r) => r.name))
|
|
const unconvertible = ranked
|
|
.filter((r) => r.rows_without_sek > 0 && !inTop.has(r.name))
|
|
.sort((a, b) => largestNativeTotal(b) - largestNativeTotal(a))
|
|
.slice(0, unconvertibleLimit)
|
|
return { top, unconvertible }
|
|
}
|
|
|
|
interface CounterpartyMagnitude extends CurrencyMagnitude {
|
|
name: string
|
|
}
|
|
|
|
interface SieSummary {
|
|
top_accounts: { account: string; abs_amount: number }[]
|
|
top_counterparties: CounterpartyMagnitude[]
|
|
// Counterparties left out of the SEK ranking because no row carries a SEK
|
|
// equivalent. Rendered in their own labelled block so they stay visible.
|
|
unconvertible_counterparties: CounterpartyMagnitude[]
|
|
year_count: number
|
|
}
|
|
|
|
// Build a coarse SIE summary from the most-recent imported SIE for the
|
|
// company. Used by the composer as a verticality signal (e.g. a top-spend
|
|
// account 1465, alcohol inventory, strongly suggests restaurang).
|
|
//
|
|
// Returns null when no SIE has been imported. The composer must still work
|
|
// without SIE data; TIC sniCodes carry most of the signal on their own.
|
|
export async function loadSieSummary(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
): Promise<SieSummary | null> {
|
|
const { data: imports, error: importsErr } = await supabase
|
|
.from('sie_imports')
|
|
.select('id, fiscal_year_start, fiscal_year_end')
|
|
.eq('company_id', companyId)
|
|
.eq('status', 'completed')
|
|
.order('created_at', { ascending: false })
|
|
.limit(20)
|
|
if (importsErr) return null
|
|
if (!imports || imports.length === 0) return null
|
|
|
|
// Fiscal-year span across all completed imports (approximate).
|
|
const years = new Set(
|
|
imports.map((r: { fiscal_year_start: string | null }) => {
|
|
const v = r.fiscal_year_start
|
|
return v ? v.slice(0, 4) : ''
|
|
}),
|
|
)
|
|
years.delete('')
|
|
|
|
// Top-20 account magnitudes across journal_entry_lines for the company.
|
|
// Cheaper than aggregating SIE line-items directly because the lines have
|
|
// already landed in journal_entry_lines after import. These are genuinely
|
|
// SEK: journal_entry_lines.debit/credit are the booked SEK amounts, with any
|
|
// foreign original kept separately in currency/amount_in_currency.
|
|
const { data: lines, error: linesErr } = await supabase.rpc('agent_top_accounts_for_company', {
|
|
p_company_id: companyId,
|
|
p_limit: 20,
|
|
})
|
|
|
|
// RPC is optional: if it doesn't exist yet, fall back to an inline group-by.
|
|
// Either way, we tolerate missing data and return what we have.
|
|
let topAccounts: { account: string; abs_amount: number }[] = []
|
|
if (!linesErr && Array.isArray(lines)) {
|
|
topAccounts = (lines as { account_number: string; abs_amount: number }[]).map((l) => ({
|
|
account: l.account_number,
|
|
abs_amount: Number(l.abs_amount) || 0,
|
|
}))
|
|
}
|
|
|
|
// Coarse counterparty rollup off the bank-statement description string.
|
|
// `transactions.description` is the raw text from the bank (not
|
|
// normalized) so this is a noisy signal. The composer treats it as a hint
|
|
// alongside TIC sniCodes, which carry the strong industry signal.
|
|
//
|
|
// currency/amount_sek/exchange_rate come along because `amount` alone does
|
|
// not say what unit it is in: see the CurrencyMagnitude note above.
|
|
const { data: tx } = await supabase
|
|
.from('transactions')
|
|
.select('description, amount, currency, amount_sek, exchange_rate')
|
|
.eq('company_id', companyId)
|
|
.limit(2000)
|
|
|
|
const cpAgg = new Map<string, MagnitudeBucket>()
|
|
if (Array.isArray(tx)) {
|
|
for (const t of tx as (AmountRow & { description: string | null })[]) {
|
|
const name = normalizeCounterparty(t.description)
|
|
if (!name) continue
|
|
let bucket = cpAgg.get(name)
|
|
if (!bucket) {
|
|
bucket = newMagnitudeBucket()
|
|
cpAgg.set(name, bucket)
|
|
}
|
|
addRowToMagnitude(bucket, t)
|
|
}
|
|
}
|
|
const allCounterparties: CounterpartyMagnitude[] = Array.from(cpAgg.entries()).map(
|
|
([name, bucket]) => ({ name, ...finalizeMagnitude(bucket) }),
|
|
)
|
|
const { top, unconvertible } = rankCounterparties(allCounterparties, 10, 5)
|
|
|
|
return {
|
|
top_accounts: topAccounts,
|
|
top_counterparties: top,
|
|
unconvertible_counterparties: unconvertible,
|
|
year_count: years.size,
|
|
}
|
|
}
|
|
|
|
interface BankingCounterparty extends CounterpartyMagnitude {
|
|
// 'in' → money coming in (income / refund / loan disbursement)
|
|
// 'out' → money going out (cost / supplier payment / repayment)
|
|
// 'mixed' → both directions present (rare: typically transfers or
|
|
// returns). The composer should not assume a category from
|
|
// mixed counterparties.
|
|
direction: 'in' | 'out' | 'mixed'
|
|
// True when at least one transaction for this counterparty still has
|
|
// journal_entry_id IS NULL. Composer should only generate verification
|
|
// questions about counterparties where this is true: the others are
|
|
// already settled and re-asking wastes the user's time.
|
|
has_unbooked: boolean
|
|
}
|
|
|
|
interface BankingSummary {
|
|
top_counterparties: BankingCounterparty[]
|
|
// Counterparties whose amounts include rows with no stored SEK equivalent
|
|
// and that did not survive the SEK ranking. Kept so "we do not know what
|
|
// this is worth in kronor" stays visible instead of silently excluded.
|
|
unconvertible_counterparties: BankingCounterparty[]
|
|
// Average monthly SEK volume over the window, counting ONLY rows whose SEK
|
|
// value is known. null when no row has one: there is then no honest kr
|
|
// figure to state at all.
|
|
monthly_volume: number | null
|
|
// Coverage behind `monthly_volume`. When rows_without_sek > 0 the figure is
|
|
// a floor, not the real volume, and the renderer has to say so.
|
|
volume_rows_with_sek: number
|
|
volume_rows_without_sek: number
|
|
// Every currency seen in the window, e.g. ['EUR', 'SEK'].
|
|
currencies: string[]
|
|
unbooked_count: number
|
|
}
|
|
|
|
// POC: re-use transactions table for banking counterparties. A first-class
|
|
// Enable Banking summary lives behind the enable-banking extension and is
|
|
// post-POC.
|
|
//
|
|
// Booking-aware: each rolled-up counterparty carries `direction` (sign of
|
|
// the transactions) and `has_unbooked` (any row without journal_entry_id).
|
|
// Both signals exist to keep the composer from asking dumb questions:
|
|
// "is this a cost or an income?" when the sign is clearly negative,
|
|
// "how should this be booked?" when there's no unbooked transaction left.
|
|
export async function loadBankingSummary(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
): Promise<BankingSummary | null> {
|
|
// currency/amount_sek/exchange_rate are part of the magnitude, not optional
|
|
// decoration: without them `amount` is a bare number with no unit, and the
|
|
// rollup below would sum EUR into a total labelled "kr".
|
|
const { data, error } = await supabase
|
|
.from('transactions')
|
|
.select('description, amount, currency, amount_sek, exchange_rate, date, journal_entry_id')
|
|
.eq('company_id', companyId)
|
|
.gte('date', oneYearAgo())
|
|
.order('date', { ascending: false })
|
|
.limit(5000)
|
|
if (error || !Array.isArray(data) || data.length === 0) return null
|
|
|
|
interface Bucket {
|
|
magnitude: MagnitudeBucket
|
|
hasInflow: boolean
|
|
hasOutflow: boolean
|
|
hasUnbooked: boolean
|
|
}
|
|
const cpAgg = new Map<string, Bucket>()
|
|
const currencies = new Set<string>()
|
|
let sekVolume = 0
|
|
let volumeRowsWithSek = 0
|
|
let volumeRowsWithoutSek = 0
|
|
let unbookedCount = 0
|
|
for (const t of data as (AmountRow & {
|
|
description: string | null
|
|
journal_entry_id: string | null
|
|
})[]) {
|
|
if (!t.journal_entry_id) unbookedCount++
|
|
|
|
const signedAmt = toFiniteNumber(t.amount)
|
|
if (signedAmt != null) {
|
|
currencies.add(rowCurrency(t))
|
|
const sek = rowSekAmount(t)
|
|
if (sek == null) {
|
|
volumeRowsWithoutSek++
|
|
} else {
|
|
sekVolume += sek
|
|
volumeRowsWithSek++
|
|
}
|
|
}
|
|
|
|
const name = normalizeCounterparty(t.description)
|
|
if (!name) continue
|
|
let bucket = cpAgg.get(name)
|
|
if (!bucket) {
|
|
bucket = {
|
|
magnitude: newMagnitudeBucket(),
|
|
hasInflow: false,
|
|
hasOutflow: false,
|
|
hasUnbooked: false,
|
|
}
|
|
cpAgg.set(name, bucket)
|
|
}
|
|
addRowToMagnitude(bucket.magnitude, t)
|
|
// Direction reads off the sign, which is currency-independent.
|
|
if (signedAmt != null && signedAmt > 0) bucket.hasInflow = true
|
|
if (signedAmt != null && signedAmt < 0) bucket.hasOutflow = true
|
|
if (!t.journal_entry_id) bucket.hasUnbooked = true
|
|
}
|
|
const allCounterparties: BankingCounterparty[] = Array.from(cpAgg.entries()).map(
|
|
([name, b]) => ({
|
|
name,
|
|
...finalizeMagnitude(b.magnitude),
|
|
direction: b.hasInflow && b.hasOutflow ? 'mixed' : b.hasInflow ? 'in' : 'out',
|
|
has_unbooked: b.hasUnbooked,
|
|
}),
|
|
)
|
|
const { top, unconvertible } = rankCounterparties(allCounterparties, 20, 10)
|
|
|
|
return {
|
|
top_counterparties: top,
|
|
unconvertible_counterparties: unconvertible,
|
|
monthly_volume: sekVolume > 0 ? Math.round(sekVolume / 12) : null,
|
|
volume_rows_with_sek: volumeRowsWithSek,
|
|
volume_rows_without_sek: volumeRowsWithoutSek,
|
|
currencies: Array.from(currencies).sort(),
|
|
unbooked_count: unbookedCount,
|
|
}
|
|
}
|
|
|
|
function oneYearAgo(): string {
|
|
const d = new Date()
|
|
d.setFullYear(d.getFullYear() - 1)
|
|
return d.toISOString().slice(0, 10)
|
|
}
|
|
|
|
// Cheap counterparty extraction from a bank-statement description. Strips
|
|
// reference numbers, dates, and common suffixes; truncates to ~40 chars.
|
|
// Post-POC: replace with the matcher in lib/transactions/.
|
|
function normalizeCounterparty(raw: string | null | undefined): string | null {
|
|
if (!raw) return null
|
|
const cleaned = raw
|
|
.replace(/\b\d{4,}\b/g, ' ') // strip long digit runs (refs)
|
|
.replace(/[/*:|]/g, ' ')
|
|
.replace(/\s+/g, ' ')
|
|
.trim()
|
|
.slice(0, 40)
|
|
return cleaned.length >= 3 ? cleaned : null
|
|
}
|
|
|
|
// Composite input for the Opus selection call.
|
|
export interface ComposerInputs {
|
|
companyId: string
|
|
companyName: string
|
|
entityType: string
|
|
ticSnapshot: Record<string, unknown> | null
|
|
ticFetchedAt: string | null
|
|
companySettings: CompanySettingsForComposer | null
|
|
// Employees currently flagged active in the payroll module. null when the
|
|
// count could not be read, which must not be read as "nobody": see
|
|
// lib/agent/composer/employee-facts.ts.
|
|
activeEmployees: number | null
|
|
sieSummary: SieSummary | null
|
|
bankingSummary: BankingSummary | null
|
|
atomIndex: AtomRegistryIndexRow[]
|
|
// True when BankID CompanyRoles confirms the active user holds a
|
|
// director-like position at this company. Controls whether the narrative
|
|
// uses second-person ownership voice ("Du driver…") or neutral
|
|
// third-person ("Coredination AB är…"). Default false so unknown users
|
|
// never get the presumptive voice.
|
|
userIsConfirmedDirector: boolean
|
|
}
|
|
|
|
export async function gatherComposerInputs(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
): Promise<ComposerInputs> {
|
|
const [
|
|
{ snapshot, fetchedAt, name, entityType },
|
|
atomIndex,
|
|
sieSummary,
|
|
bankingSummary,
|
|
companySettings,
|
|
activeEmployees,
|
|
directorship,
|
|
] = await Promise.all([
|
|
loadCompanyTicSnapshot(supabase, companyId),
|
|
loadAtomRegistryIndex(supabase),
|
|
loadSieSummary(supabase, companyId).catch(() => null),
|
|
loadBankingSummary(supabase, companyId).catch(() => null),
|
|
loadCompanySettings(supabase, companyId).catch(() => null),
|
|
loadActiveEmployeeCount(supabase, companyId).catch(() => null),
|
|
loadUserDirectorship(supabase, companyId).catch(() => ({ confirmedDirector: false })),
|
|
])
|
|
|
|
return {
|
|
companyId,
|
|
companyName: name,
|
|
entityType,
|
|
ticSnapshot: snapshot,
|
|
ticFetchedAt: fetchedAt,
|
|
companySettings,
|
|
activeEmployees,
|
|
sieSummary,
|
|
bankingSummary,
|
|
atomIndex,
|
|
userIsConfirmedDirector: directorship.confirmedDirector,
|
|
}
|
|
}
|
|
|
|
export function inputsToSourceSignals(inputs: ComposerInputs): SourceSignals {
|
|
return {
|
|
tic: inputs.ticSnapshot,
|
|
sie_summary: inputs.sieSummary,
|
|
banking_summary: inputs.bankingSummary,
|
|
atom_registry_version: inputs.atomIndex.reduce((acc, a) => acc + a.version, 0),
|
|
}
|
|
}
|