fix: similar-sweep currency remediation, security hardening and v1 API fixes (#1215)
* 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>
This commit is contained in:
co-authored by
Claude Fable 5
parent
a43a8b03cf
commit
f24b26a139
@@ -0,0 +1,401 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { loadBankingSummary } from '../inputs'
|
||||
import { selectAtoms, formatMagnitude, buildCurrencyUncertaintyNotes } from '../atom-selection'
|
||||
import type { ComposerInputs } from '../inputs'
|
||||
|
||||
// The composer prompt is the INPUT to the model that writes a company's
|
||||
// standing agent instructions. A magnitude that is wrong here does not
|
||||
// mislead one answer, it gets baked into durable instructions. So the rule
|
||||
// these tests pin is: a number is only ever printed as "kr" when it really is
|
||||
// kronor, and a magnitude we cannot express in kronor is printed as unknown,
|
||||
// never as a confident figure and never silently dropped.
|
||||
|
||||
const { createMock } = vi.hoisted(() => ({ createMock: vi.fn() }))
|
||||
|
||||
vi.mock('../client', () => ({
|
||||
getAnthropic: () => ({ messages: { create: createMock } }),
|
||||
OPUS_MODEL: 'test-opus',
|
||||
SONNET_MODEL: 'test-sonnet',
|
||||
THINKING_BUDGET_STANDARD: 1,
|
||||
THINKING_BUDGET_DEEP: 1,
|
||||
}))
|
||||
|
||||
// sv-SE thousands separators are non-breaking spaces; build expectations the
|
||||
// same way the renderer does so the assertions are not whitespace-fragile.
|
||||
const sv = (n: number) => n.toLocaleString('sv-SE')
|
||||
|
||||
interface TxRow {
|
||||
description: string | null
|
||||
amount: number
|
||||
currency?: string | null
|
||||
amount_sek?: number | null
|
||||
exchange_rate?: number | null
|
||||
date?: string
|
||||
journal_entry_id?: string | null
|
||||
}
|
||||
|
||||
function buildSupabase(rows: TxRow[]) {
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const m of ['select', 'eq', 'gte', 'order', 'limit']) {
|
||||
chain[m] = () => chain
|
||||
}
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve({ data: rows, error: null })
|
||||
return { from: vi.fn().mockReturnValue(chain) } as never
|
||||
}
|
||||
|
||||
function tx(overrides: Partial<TxRow> & { description: string; amount: number }): TxRow {
|
||||
return {
|
||||
currency: 'SEK',
|
||||
amount_sek: null,
|
||||
exchange_rate: null,
|
||||
date: '2026-03-01',
|
||||
journal_entry_id: 'je-1',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const ATOM_INDEX = [
|
||||
{
|
||||
id: 'horizontal/swedish-vat',
|
||||
tier: 'horizontal' as const,
|
||||
title: 'Moms',
|
||||
description: 'Svensk moms.',
|
||||
sni_prefixes: [],
|
||||
trigger_signals: {},
|
||||
estimated_tokens: 100,
|
||||
version: 1,
|
||||
},
|
||||
]
|
||||
|
||||
function makeInputs(overrides: Partial<ComposerInputs> = {}): ComposerInputs {
|
||||
return {
|
||||
companyId: 'company-1',
|
||||
companyName: 'Testbolaget AB',
|
||||
entityType: 'aktiebolag',
|
||||
ticSnapshot: null,
|
||||
ticFetchedAt: null,
|
||||
companySettings: null,
|
||||
activeEmployees: null,
|
||||
sieSummary: null,
|
||||
bankingSummary: null,
|
||||
atomIndex: ATOM_INDEX,
|
||||
userIsConfirmedDirector: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function mockSelectionResponse() {
|
||||
createMock.mockResolvedValue({
|
||||
content: [
|
||||
{
|
||||
type: 'tool_use',
|
||||
name: 'compose_agent_profile',
|
||||
input: {
|
||||
horizontal_atoms: ['horizontal/swedish-vat'],
|
||||
vertical_atoms: [],
|
||||
modifier_atoms: [],
|
||||
is_multi_vertical: false,
|
||||
verification_questions: ['Vad är er vanligaste kundtyp?'],
|
||||
uncertainty_notes: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
// Runs the real prompt builder and hands back the text the model would see.
|
||||
async function renderPrompt(inputs: ComposerInputs): Promise<string> {
|
||||
mockSelectionResponse()
|
||||
await selectAtoms(inputs)
|
||||
const call = createMock.mock.calls[0][0] as { messages: { content: string }[] }
|
||||
return call.messages[0].content
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('loadBankingSummary currency handling', () => {
|
||||
it('keeps a SEK-only company on a single kr magnitude', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -300000 }),
|
||||
tx({ description: 'ACME AB faktura', amount: -112000 }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
expect(summary).not.toBeNull()
|
||||
expect(summary!.currencies).toEqual(['SEK'])
|
||||
expect(summary!.volume_rows_without_sek).toBe(0)
|
||||
expect(summary!.unconvertible_counterparties).toEqual([])
|
||||
expect(summary!.top_counterparties[0]).toMatchObject({
|
||||
name: 'ACME AB faktura',
|
||||
abs_amount: 412000,
|
||||
rows_without_sek: 0,
|
||||
by_currency: [{ currency: 'SEK', abs_amount: 412000 }],
|
||||
})
|
||||
})
|
||||
|
||||
it('never folds a foreign amount into the SEK total when no rate is stored', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -412000 }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
const hetzner = summary!.top_counterparties.find((c) => c.name === 'Hetzner Online')!
|
||||
// The 30 000 is EUR. It must not appear anywhere as a SEK amount.
|
||||
expect(hetzner.abs_amount).toBe(0)
|
||||
expect(hetzner.rows_without_sek).toBe(1)
|
||||
expect(hetzner.by_currency).toEqual([{ currency: 'EUR', abs_amount: 30000 }])
|
||||
// Monthly volume counts the SEK row only, and says how much it left out.
|
||||
expect(summary!.monthly_volume).toBe(Math.round(412000 / 12))
|
||||
expect(summary!.volume_rows_with_sek).toBe(1)
|
||||
expect(summary!.volume_rows_without_sek).toBe(1)
|
||||
expect(summary!.currencies).toEqual(['EUR', 'SEK'])
|
||||
})
|
||||
|
||||
it('uses the stored SEK equivalent for a foreign row when there is one', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR', amount_sek: -345000 }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
expect(summary!.top_counterparties[0]).toMatchObject({
|
||||
abs_amount: 345000,
|
||||
rows_without_sek: 0,
|
||||
by_currency: [{ currency: 'EUR', abs_amount: 30000 }],
|
||||
})
|
||||
expect(summary!.monthly_volume).toBe(Math.round(345000 / 12))
|
||||
})
|
||||
|
||||
it('derives the SEK equivalent from exchange_rate when amount_sek is absent', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'Hetzner Online', amount: -1000, currency: 'EUR', exchange_rate: 11.5 }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
expect(summary!.top_counterparties[0]).toMatchObject({
|
||||
abs_amount: 11500,
|
||||
rows_without_sek: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an unknown monthly volume rather than a zero when nothing converts', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'Stripe Inc', amount: -12000, currency: 'USD' }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
expect(summary!.monthly_volume).toBeNull()
|
||||
expect(summary!.volume_rows_with_sek).toBe(0)
|
||||
expect(summary!.volume_rows_without_sek).toBe(2)
|
||||
})
|
||||
|
||||
it('surfaces a rate-less counterparty that the SEK ranking would have dropped', async () => {
|
||||
// 20 SEK counterparties outrank the foreign one on the kr scale, so the
|
||||
// top-20 slice would silently swallow it.
|
||||
const rows: TxRow[] = []
|
||||
for (let i = 0; i < 20; i++) {
|
||||
rows.push(tx({ description: `Kund nummer ${String.fromCharCode(65 + i)}`, amount: 100000 + i }))
|
||||
}
|
||||
rows.push(tx({ description: 'Stripe Inc', amount: -12000, currency: 'USD' }))
|
||||
|
||||
const summary = await loadBankingSummary(buildSupabase(rows), 'company-1')
|
||||
|
||||
expect(summary!.top_counterparties.map((c) => c.name)).not.toContain('Stripe Inc')
|
||||
expect(summary!.unconvertible_counterparties.map((c) => c.name)).toEqual(['Stripe Inc'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatMagnitude', () => {
|
||||
it('renders plain SEK exactly as a bare kr figure', () => {
|
||||
expect(
|
||||
formatMagnitude({
|
||||
abs_amount: 412000,
|
||||
by_currency: [{ currency: 'SEK', abs_amount: 412000 }],
|
||||
rows_without_sek: 0,
|
||||
}),
|
||||
).toBe(`${sv(412000)} kr`)
|
||||
})
|
||||
|
||||
it('keeps each currency in its own unit and adds the SEK equivalent', () => {
|
||||
const out = formatMagnitude({
|
||||
abs_amount: 757000,
|
||||
by_currency: [
|
||||
{ currency: 'SEK', abs_amount: 412000 },
|
||||
{ currency: 'EUR', abs_amount: 30000 },
|
||||
],
|
||||
rows_without_sek: 0,
|
||||
})
|
||||
expect(out).toBe(`${sv(412000)} SEK + ${sv(30000)} EUR (motsvarar ${sv(757000)} kr)`)
|
||||
})
|
||||
|
||||
it('says the SEK value is unknown instead of printing 0 kr', () => {
|
||||
const out = formatMagnitude({
|
||||
abs_amount: 0,
|
||||
by_currency: [{ currency: 'EUR', abs_amount: 30000 }],
|
||||
rows_without_sek: 2,
|
||||
})
|
||||
expect(out).toContain(`${sv(30000)} EUR`)
|
||||
expect(out).toContain('SEK-motsvarighet OKÄND')
|
||||
// No number is ever labelled kronor here.
|
||||
expect(out).not.toMatch(/\d[\s ]*kr/)
|
||||
})
|
||||
|
||||
it('marks a partially convertible magnitude as partial', () => {
|
||||
const out = formatMagnitude({
|
||||
abs_amount: 412000,
|
||||
by_currency: [
|
||||
{ currency: 'SEK', abs_amount: 412000 },
|
||||
{ currency: 'USD', abs_amount: 12000 },
|
||||
],
|
||||
rows_without_sek: 1,
|
||||
})
|
||||
expect(out).toContain(`varav ${sv(412000)} kr har känd SEK-motsvarighet`)
|
||||
expect(out).toContain('saknar växelkurs')
|
||||
})
|
||||
})
|
||||
|
||||
describe('composer prompt rendering', () => {
|
||||
it('renders a SEK-only company exactly as before', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -300000 }),
|
||||
tx({ description: 'ACME AB faktura', amount: -112000 }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
|
||||
const prompt = await renderPrompt(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(prompt).toContain(`Snittvolym per månad: ${sv(Math.round(412000 / 12))} kr`)
|
||||
expect(prompt).toContain(`ACME AB faktura: ${sv(412000)} kr (ut, bokförd)`)
|
||||
// No caveats invented for a company that has nothing to caveat.
|
||||
expect(prompt).not.toContain('GOLV')
|
||||
expect(prompt).not.toContain('Valutor i underlaget')
|
||||
expect(prompt).not.toContain('Motparter utan känd SEK-motsvarighet')
|
||||
})
|
||||
|
||||
// KEY TEST: this is the finding. A 30 000 EUR counterparty was rendered as
|
||||
// "30 000 kr" and fed straight into durable instruction generation.
|
||||
it('does not give a multi-currency company a single misleading kr figure', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -412000 }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
|
||||
const prompt = await renderPrompt(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
// The EUR magnitude must never be labelled kronor.
|
||||
expect(prompt).not.toContain(`${sv(30000)} kr`)
|
||||
expect(prompt).toContain(`${sv(30000)} EUR`)
|
||||
expect(prompt).toContain('SEK-motsvarighet OKÄND')
|
||||
// And the volume is honestly reported as a floor.
|
||||
expect(prompt).toContain(`Snittvolym per månad: ${sv(Math.round(412000 / 12))} kr (GOLV:`)
|
||||
expect(prompt).toContain('Valutor i underlaget: EUR, SEK')
|
||||
})
|
||||
|
||||
it('keeps rate-less counterparties visible instead of dropping them at the slice', async () => {
|
||||
const rows: TxRow[] = []
|
||||
for (let i = 0; i < 20; i++) {
|
||||
rows.push(tx({ description: `Kund nummer ${String.fromCharCode(65 + i)}`, amount: 100000 + i }))
|
||||
}
|
||||
rows.push(tx({ description: 'Stripe Inc', amount: -12000, currency: 'USD' }))
|
||||
const summary = await loadBankingSummary(buildSupabase(rows), 'company-1')
|
||||
|
||||
const prompt = await renderPrompt(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(prompt).toContain('Motparter utan känd SEK-motsvarighet')
|
||||
expect(prompt).toContain(`Stripe Inc: ${sv(12000)} USD`)
|
||||
expect(prompt).not.toContain(`Stripe Inc: ${sv(12000)} kr`)
|
||||
})
|
||||
|
||||
it('states that the monthly volume is unknown when no row converts', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'Stripe Inc', amount: -12000, currency: 'USD' }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
|
||||
const prompt = await renderPrompt(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(prompt).toContain('Snittvolym per månad: OKÄND')
|
||||
expect(prompt).not.toMatch(/Snittvolym per månad: [\d\s ]+ kr/)
|
||||
})
|
||||
|
||||
it('applies the same unit rule to the SIE counterparty rollup', async () => {
|
||||
const prompt = await renderPrompt(
|
||||
makeInputs({
|
||||
sieSummary: {
|
||||
year_count: 2,
|
||||
top_accounts: [{ account: '3011', abs_amount: 900000 }],
|
||||
top_counterparties: [
|
||||
{
|
||||
name: 'Hetzner Online',
|
||||
abs_amount: 0,
|
||||
by_currency: [{ currency: 'EUR', abs_amount: 30000 }],
|
||||
rows_without_sek: 3,
|
||||
},
|
||||
],
|
||||
unconvertible_counterparties: [],
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prompt).toContain(`Hetzner Online: ${sv(30000)} EUR`)
|
||||
expect(prompt).not.toContain(`Hetzner Online: ${sv(30000)} kr`)
|
||||
// Ledger balances are genuinely SEK and keep their bare kr rendering.
|
||||
expect(prompt).toContain(`${sv(900000)} kr`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildCurrencyUncertaintyNotes', () => {
|
||||
it('returns nothing for a SEK-only company', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([tx({ description: 'ACME AB faktura', amount: -412000 })]),
|
||||
'company-1',
|
||||
)
|
||||
expect(buildCurrencyUncertaintyNotes(makeInputs({ bankingSummary: summary }))).toEqual([])
|
||||
})
|
||||
|
||||
it('flags multi-currency data and the rows left out of the volume', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -412000 }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
|
||||
const notes = buildCurrencyUncertaintyNotes(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(notes.join(' ')).toContain('flera valutor')
|
||||
expect(notes.join(' ')).toContain('golv')
|
||||
})
|
||||
|
||||
it('appends the caveats to the selection so they reach the durable profile', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -412000 }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
mockSelectionResponse()
|
||||
|
||||
const selection = await selectAtoms(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(selection.uncertainty_notes.join(' ')).toContain('flera valutor')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
employeeFieldValue,
|
||||
employeeKnownFact,
|
||||
knowsEmployeeFact,
|
||||
loadActiveEmployeeCount,
|
||||
resolveEmployeeFacts,
|
||||
type EmployeeFacts,
|
||||
} from '../employee-facts'
|
||||
import { buildKnownFacts, filterRedundantQuestions } from '../atom-selection'
|
||||
import type { ComposerInputs } from '../inputs'
|
||||
|
||||
/**
|
||||
* Both call sites used to read `company_settings.employee_count` and
|
||||
* `company_settings.has_employees`. Neither column exists: `employee_count` is
|
||||
* on `agi_declarations`, `has_employees` is in no migration at all. PostgREST
|
||||
* rejects a select whole on 42703, so the agent-onboarding page and the
|
||||
* composer got `null` for the ENTIRE settings row, and "Anställda" plus every
|
||||
* other known fact silently vanished.
|
||||
*
|
||||
* tests/schema/no-phantom-columns.test.ts proves the column names are now real.
|
||||
* This file proves the replacement reads the RIGHT ones: that a live headcount
|
||||
* wins, that an attested employer registration settles the question in both
|
||||
* directions, and above all that `pays_salaries === false` (a NOT NULL DEFAULT
|
||||
* false column whose only writer is the tax settings form) is never laundered
|
||||
* into "this company has no employees".
|
||||
*/
|
||||
|
||||
const NOTHING_KNOWN: EmployeeFacts = {
|
||||
activeEmployees: null,
|
||||
ticEmployeeRange: null,
|
||||
employerRegistered: null,
|
||||
paysSalaries: null,
|
||||
}
|
||||
|
||||
function makeInputs(overrides: Partial<ComposerInputs> = {}): ComposerInputs {
|
||||
return {
|
||||
companyId: 'company-1',
|
||||
companyName: 'Testbolaget AB',
|
||||
entityType: 'aktiebolag',
|
||||
ticSnapshot: null,
|
||||
ticFetchedAt: null,
|
||||
companySettings: null,
|
||||
activeEmployees: null,
|
||||
sieSummary: null,
|
||||
bankingSummary: null,
|
||||
atomIndex: [],
|
||||
userIsConfirmedDirector: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('resolveEmployeeFacts', () => {
|
||||
it('reports unknown when nothing is actually known', () => {
|
||||
expect(resolveEmployeeFacts(NOTHING_KNOWN)).toEqual({ kind: 'unknown' })
|
||||
expect(employeeFieldValue(NOTHING_KNOWN)).toBeNull()
|
||||
expect(knowsEmployeeFact(NOTHING_KNOWN)).toBe(false)
|
||||
})
|
||||
|
||||
it('prefers a live headcount over every weaker signal', () => {
|
||||
expect(
|
||||
resolveEmployeeFacts({
|
||||
activeEmployees: 3,
|
||||
ticEmployeeRange: '5-9',
|
||||
employerRegistered: true,
|
||||
paysSalaries: true,
|
||||
})
|
||||
).toEqual({ kind: 'count', count: 3 })
|
||||
})
|
||||
|
||||
it('falls back to the Bolagsverket interval when no employee rows exist yet', () => {
|
||||
// Every company arriving at agent onboarding has zero employee rows, so
|
||||
// zero must fall through rather than answer the question.
|
||||
expect(
|
||||
resolveEmployeeFacts({ ...NOTHING_KNOWN, activeEmployees: 0, ticEmployeeRange: '5-9' })
|
||||
).toEqual({ kind: 'range', range: '5-9' })
|
||||
expect(
|
||||
employeeFieldValue({ ...NOTHING_KNOWN, activeEmployees: 0, ticEmployeeRange: '5-9' })
|
||||
).toBe('5-9')
|
||||
})
|
||||
|
||||
it('treats a zero headcount as no evidence, not as "nej"', () => {
|
||||
expect(resolveEmployeeFacts({ ...NOTHING_KNOWN, activeEmployees: 0 })).toEqual({
|
||||
kind: 'unknown',
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts an attested employer registration in both directions', () => {
|
||||
expect(employeeFieldValue({ ...NOTHING_KNOWN, employerRegistered: true })).toBe('Ja')
|
||||
expect(employeeFieldValue({ ...NOTHING_KNOWN, employerRegistered: false })).toBe('Nej')
|
||||
})
|
||||
|
||||
it('reads pays_salaries=true as evidence but pays_salaries=false as none', () => {
|
||||
// The column is NOT NULL DEFAULT false and no onboarding step sets it, so a
|
||||
// false is indistinguishable from "never answered". Answering "Nej" from it
|
||||
// would state a fact nobody entered.
|
||||
expect(employeeFieldValue({ ...NOTHING_KNOWN, paysSalaries: true })).toBe('Ja')
|
||||
expect(employeeFieldValue({ ...NOTHING_KNOWN, paysSalaries: false })).toBeNull()
|
||||
expect(knowsEmployeeFact({ ...NOTHING_KNOWN, paysSalaries: false })).toBe(false)
|
||||
})
|
||||
|
||||
it('lets an attested registration override the pays_salaries default', () => {
|
||||
expect(
|
||||
employeeFieldValue({ ...NOTHING_KNOWN, employerRegistered: true, paysSalaries: false })
|
||||
).toBe('Ja')
|
||||
})
|
||||
})
|
||||
|
||||
describe('employeeKnownFact (composer KÄNDA FAKTA line)', () => {
|
||||
it('states a headcount when employee rows back it', () => {
|
||||
expect(employeeKnownFact({ ...NOTHING_KNOWN, activeEmployees: 2 })).toBe('Anställda: 2')
|
||||
})
|
||||
|
||||
it('does not repeat the TIC interval, which has its own line', () => {
|
||||
expect(employeeKnownFact({ ...NOTHING_KNOWN, ticEmployeeRange: '5-9' })).toBeNull()
|
||||
})
|
||||
|
||||
it('says nothing when nothing is known', () => {
|
||||
expect(employeeKnownFact(NOTHING_KNOWN)).toBeNull()
|
||||
expect(employeeKnownFact({ ...NOTHING_KNOWN, paysSalaries: false })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildKnownFacts', () => {
|
||||
it('surfaces the real settings columns that the phantom select was discarding', () => {
|
||||
const facts = buildKnownFacts(
|
||||
makeInputs({
|
||||
activeEmployees: 2,
|
||||
companySettings: {
|
||||
city: 'Göteborg',
|
||||
moms_period: 'quarterly',
|
||||
fiscal_year_start_month: 1,
|
||||
f_skatt: true,
|
||||
vat_registered: true,
|
||||
employer_registered: true,
|
||||
pays_salaries: true,
|
||||
accounting_method: 'accrual',
|
||||
},
|
||||
})
|
||||
)
|
||||
expect(facts).toContain('Anställda: 2')
|
||||
expect(facts).toContain('Arbetsgivarregistrerad: ja')
|
||||
expect(facts).toContain('Betalar ut lön: ja')
|
||||
expect(facts).toContain('Momsperiod: kvartalsvis')
|
||||
expect(facts).toContain('Säte: Göteborg')
|
||||
})
|
||||
|
||||
it('states a headcount even when the company has no company_settings row', () => {
|
||||
expect(buildKnownFacts(makeInputs({ activeEmployees: 4 }))).toContain('Anställda: 4')
|
||||
})
|
||||
|
||||
it('claims no employee fact when there is none to claim', () => {
|
||||
const facts = buildKnownFacts(makeInputs())
|
||||
expect(facts.some((f) => f.startsWith('Anställda'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('filterRedundantQuestions: the employee question', () => {
|
||||
// fallbackAtomSelection generates exactly this question for an aktiebolag.
|
||||
const QUESTION = 'Har bolaget anställda förutom dig?'
|
||||
|
||||
it('keeps the question when the employee fact is genuinely unknown', () => {
|
||||
expect(filterRedundantQuestions([QUESTION], makeInputs())).toEqual([QUESTION])
|
||||
})
|
||||
|
||||
it('keeps the question when pays_salaries is merely at its column default', () => {
|
||||
const inputs = makeInputs({
|
||||
activeEmployees: 0,
|
||||
companySettings: {
|
||||
city: null,
|
||||
moms_period: null,
|
||||
fiscal_year_start_month: null,
|
||||
f_skatt: null,
|
||||
vat_registered: null,
|
||||
employer_registered: null,
|
||||
pays_salaries: false,
|
||||
accounting_method: null,
|
||||
},
|
||||
})
|
||||
expect(filterRedundantQuestions([QUESTION], inputs)).toEqual([QUESTION])
|
||||
})
|
||||
|
||||
it('drops the question once employee rows exist', () => {
|
||||
expect(filterRedundantQuestions([QUESTION], makeInputs({ activeEmployees: 1 }))).toEqual([])
|
||||
})
|
||||
|
||||
it('drops the question when the TIC snapshot carries an employee interval', () => {
|
||||
const inputs = makeInputs({ ticSnapshot: { employeeRange: '1-4' } })
|
||||
expect(filterRedundantQuestions([QUESTION], inputs)).toEqual([])
|
||||
})
|
||||
|
||||
it('drops the question when employer registration was attested either way', () => {
|
||||
for (const employer_registered of [true, false]) {
|
||||
const inputs = makeInputs({
|
||||
companySettings: {
|
||||
city: null,
|
||||
moms_period: null,
|
||||
fiscal_year_start_month: null,
|
||||
f_skatt: null,
|
||||
vat_registered: null,
|
||||
employer_registered,
|
||||
pays_salaries: false,
|
||||
accounting_method: null,
|
||||
},
|
||||
})
|
||||
expect(filterRedundantQuestions([QUESTION], inputs)).toEqual([])
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('loadActiveEmployeeCount', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
function mockClient(result: { count: number | null; error: unknown }) {
|
||||
const eq = vi.fn()
|
||||
const chain = {
|
||||
select: vi.fn(() => chain),
|
||||
eq,
|
||||
}
|
||||
eq.mockReturnValueOnce(chain).mockReturnValueOnce(Promise.resolve(result))
|
||||
const from = vi.fn(() => chain)
|
||||
return { client: { from } as unknown as SupabaseClient, from, chain }
|
||||
}
|
||||
|
||||
it('counts only active employees for the company', async () => {
|
||||
const { client, from, chain } = mockClient({ count: 3, error: null })
|
||||
await expect(loadActiveEmployeeCount(client, 'company-1')).resolves.toBe(3)
|
||||
expect(from).toHaveBeenCalledWith('employees')
|
||||
expect(chain.select).toHaveBeenCalledWith('id', { count: 'exact', head: true })
|
||||
expect(chain.eq).toHaveBeenNthCalledWith(1, 'company_id', 'company-1')
|
||||
expect(chain.eq).toHaveBeenNthCalledWith(2, 'is_active', true)
|
||||
})
|
||||
|
||||
it('returns null (not 0) when the count cannot be read', async () => {
|
||||
const { client } = mockClient({ count: null, error: { message: 'boom' } })
|
||||
await expect(loadActiveEmployeeCount(client, 'company-1')).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -22,6 +22,7 @@ function makeInputs(overrides: Partial<ComposerInputs>): ComposerInputs {
|
||||
ticSnapshot: null,
|
||||
ticFetchedAt: null,
|
||||
companySettings: null,
|
||||
activeEmployees: null,
|
||||
sieSummary: null,
|
||||
bankingSummary: null,
|
||||
atomIndex: [],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { getAnthropic, OPUS_MODEL } from './client'
|
||||
import { AtomSelectionSchema, ATOM_SELECTION_TOOL_SCHEMA, type AtomSelection } from './schemas'
|
||||
import type { ComposerInputs } from './inputs'
|
||||
import { isSekOnlyMagnitude, type ComposerInputs, type CurrencyMagnitude } from './inputs'
|
||||
import { employeeKnownFact, knowsEmployeeFact } from './employee-facts'
|
||||
|
||||
const SYSTEM_PROMPT = `Du komponerar en specialiserad svensk bokföringsassistent åt ett företag.
|
||||
|
||||
@@ -16,10 +17,18 @@ Du får:
|
||||
- KÄNDA FAKTA från företagets inställningar: saker användaren redan har angett (momsperiod, räkenskapsår, F-skatt-status, anställda, bokföringsmetod)
|
||||
- Eventuell sammanfattning från importerad SIE-fil (topp-konton, topp-motparter, antal år)
|
||||
- Eventuell sammanfattning från bankhistorik. Varje topp-motpart har:
|
||||
- belopp i kr (abs)
|
||||
- belopp med sin valutaenhet utskriven (abs)
|
||||
- riktning: 'in' (intäkt/inbetalning), 'ut' (kostnad/utbetalning), eller 'in+ut'
|
||||
- bokföringsstatus: 'OBOKFÖRD' (minst en transaktion ej bokförd) eller 'bokförd'
|
||||
KRITISKT: ställ INTE en verifieringsfråga om en motpart där riktningen är entydig OCH alla transaktioner är bokförda. T.ex. en motpart märkt "(ut, bokförd)" är redan klassad som kostnad och redan kategoriserad. Att fråga "är detta en intäkt eller kostnad?" är fel. Fokusera frågorna på OBOKFÖRD-motparter där det finns en bokningsbeslutning kvar att fatta.
|
||||
|
||||
BELOPP OCH VALUTA (hård regel):
|
||||
- Ett belopp gäller ALLTID den enhet som står skriven. "412 000 kr" är svenska kronor. "30 000 EUR" är euro, inte kronor.
|
||||
- Addera ALDRIG belopp i olika valutor till en summa, och räkna aldrig om dem själv: du har ingen växelkurs.
|
||||
- Står det "motsvarar N kr" är N en lagrad SEK-motsvarighet och får användas som storleksordning.
|
||||
- Står det "SEK-motsvarighet OKÄND" eller "saknar växelkurs" finns INGEN känd kronsumma för de raderna. Behandla storleken som okänd, gissa aldrig fram ett kr-belopp, och nämn luckan i uncertainty_notes.
|
||||
- Ett block märkt "Motparter utan känd SEK-motsvarighet" listar motparter vars storlek vi inte kan uttrycka i kronor. De är inte små: de är omätta.
|
||||
- Om "Snittvolym per månad" saknas eller är märkt som ett golv: dra inga slutsatser om omsättningsstorlek av den.
|
||||
- Ett register över tillgängliga atomer (horizontal/vertical/modifier) med beskrivning, SNI-prefix och utlösare
|
||||
|
||||
Din uppgift:
|
||||
@@ -43,7 +52,7 @@ Din uppgift:
|
||||
|
||||
Fokusera istället på frågor vars svar du inte kan se: specifika balansposter (t.ex. "Vad gäller ALMI-beloppet, lån eller bidrag?"), arbetssätt (faktureringscadens, kund-geografi), planerade förändringar (kommande löneutbetalning, expansion, fastighetsförvärv).
|
||||
|
||||
6. Skriv 1-3 svenska uncertainty_notes till utvecklaren som granskar valet senare. Inkludera explicit notering om statuses[] visar isCeased eller red-status.
|
||||
6. Skriv 1-3 svenska uncertainty_notes till utvecklaren som granskar valet senare. Inkludera explicit notering om statuses[] visar isCeased eller red-status, och om något belopp saknar känd SEK-motsvarighet.
|
||||
|
||||
Stil i all text du skriver (verifieringsfrågor och notes): använd ALDRIG tankstreck (— eller –). Använd kommatecken, punkt, eller "till" för intervall ("2,5 till 5 miljoner"). Hård regel.
|
||||
|
||||
@@ -110,9 +119,101 @@ export async function selectAtoms(inputs: ComposerInputs): Promise<AtomSelection
|
||||
parsed.data.modifier_atoms,
|
||||
)
|
||||
|
||||
// Currency caveats are appended deterministically, not left to the model.
|
||||
// This selection becomes the company's standing agent profile, so a
|
||||
// magnitude the underlying data cannot support has to be flagged even when
|
||||
// the model failed to notice it: an explicit "unknown" is always better
|
||||
// than a confident wrong number baked into durable instructions.
|
||||
parsed.data.uncertainty_notes = [
|
||||
...parsed.data.uncertainty_notes,
|
||||
...buildCurrencyUncertaintyNotes(inputs),
|
||||
]
|
||||
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
// Deterministic notes about what the amount signals cannot tell us. Exported
|
||||
// so the stream endpoint can apply the same caveats to fallback selections,
|
||||
// which never see the model at all.
|
||||
export function buildCurrencyUncertaintyNotes(inputs: ComposerInputs): string[] {
|
||||
const notes: string[] = []
|
||||
|
||||
const bank = inputs.bankingSummary
|
||||
if (bank) {
|
||||
const foreign = bank.currencies.filter((c) => c !== 'SEK')
|
||||
if (foreign.length > 0) {
|
||||
notes.push(
|
||||
`Banksammanfattningen spänner över flera valutor (${bank.currencies.join(', ')}). Beloppen är inte en enda kr-summa: kontrollera valutan innan en storleksordning används.`,
|
||||
)
|
||||
}
|
||||
if (bank.volume_rows_without_sek > 0) {
|
||||
const total = bank.volume_rows_with_sek + bank.volume_rows_without_sek
|
||||
notes.push(
|
||||
bank.monthly_volume == null
|
||||
? `Ingen månadsvolym i kr kan anges: samtliga ${total} banktransaktioner saknar lagrad SEK-motsvarighet.`
|
||||
: `${bank.volume_rows_without_sek} av ${total} banktransaktioner saknar lagrad SEK-motsvarighet och ingår inte i snittvolymen. Volymen i kr är ett golv, inte ett facit.`,
|
||||
)
|
||||
}
|
||||
if (bank.unconvertible_counterparties.length > 0) {
|
||||
notes.push(
|
||||
`${bank.unconvertible_counterparties.length} motpart(er) kunde inte rankas i kr eftersom växelkurs saknas: ${bank.unconvertible_counterparties.map((c) => c.name).join(', ')}.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const sie = inputs.sieSummary
|
||||
if (sie) {
|
||||
const unknownRows = [...sie.top_counterparties, ...sie.unconvertible_counterparties].reduce(
|
||||
(n, c) => n + c.rows_without_sek,
|
||||
0,
|
||||
)
|
||||
if (unknownRows > 0) {
|
||||
notes.push(
|
||||
`SIE-motpartsbeloppen innehåller ${unknownRows} rad(er) i utländsk valuta utan känd SEK-motsvarighet.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return notes
|
||||
}
|
||||
|
||||
// Renders a magnitude so the number always carries its real unit.
|
||||
//
|
||||
// Plain SEK data renders exactly as before ("412 000 kr"). Anything else keeps
|
||||
// each currency in its own unit and states, in words, how much of it has a
|
||||
// known SEK equivalent. There is deliberately no path that turns a mixed or
|
||||
// rate-less magnitude into a single "kr" figure.
|
||||
export function formatMagnitude(m: CurrencyMagnitude): string {
|
||||
if (isSekOnlyMagnitude(m)) {
|
||||
return `${formatAmount(m.abs_amount)} kr`
|
||||
}
|
||||
|
||||
const native = m.by_currency
|
||||
.map((c) => `${formatAmount(c.abs_amount)} ${c.currency}`)
|
||||
.join(' + ')
|
||||
|
||||
if (m.rows_without_sek === 0) {
|
||||
return `${native} (motsvarar ${formatAmount(m.abs_amount)} kr)`
|
||||
}
|
||||
const missing = `${m.rows_without_sek} ${m.rows_without_sek === 1 ? 'transaktion' : 'transaktioner'} saknar växelkurs`
|
||||
if (m.abs_amount === 0) {
|
||||
return `${native} (SEK-motsvarighet OKÄND: ${missing}, ingen kr-summa kan anges)`
|
||||
}
|
||||
return `${native} (varav ${formatAmount(m.abs_amount)} kr har känd SEK-motsvarighet, ${missing} och ingår inte)`
|
||||
}
|
||||
|
||||
function formatAmount(value: number): string {
|
||||
return Math.round(value).toLocaleString('sv-SE')
|
||||
}
|
||||
|
||||
function counterpartyLabels(c: {
|
||||
direction: 'in' | 'out' | 'mixed'
|
||||
has_unbooked: boolean
|
||||
}): string {
|
||||
const dirLabel = c.direction === 'in' ? 'in' : c.direction === 'out' ? 'ut' : 'in+ut'
|
||||
return `${dirLabel}, ${c.has_unbooked ? 'OBOKFÖRD' : 'bokförd'}`
|
||||
}
|
||||
|
||||
// Drops questions whose answer is already settled in company_settings or
|
||||
// TIC snapshot. Each question is matched against keyword patterns:
|
||||
// keep this conservative so we never accidentally drop a legitimate
|
||||
@@ -139,7 +240,12 @@ export function filterRedundantQuestions(
|
||||
| null
|
||||
|
||||
const knowsMomsPeriod = !!s?.moms_period
|
||||
const knowsEmployees = s?.has_employees != null || s?.employee_count != null || !!tic?.employeeRange
|
||||
const knowsEmployees = knowsEmployeeFact({
|
||||
activeEmployees: inputs.activeEmployees,
|
||||
ticEmployeeRange: tic?.employeeRange ?? null,
|
||||
employerRegistered: s?.employer_registered ?? null,
|
||||
paysSalaries: s?.pays_salaries ?? null,
|
||||
})
|
||||
const knowsFiscalYear = s?.fiscal_year_start_month != null
|
||||
const knowsFSkatt = s?.f_skatt != null || tic?.registration?.fTax != null
|
||||
const knowsVatRegistered = s?.vat_registered != null || tic?.registration?.vat != null
|
||||
@@ -241,7 +347,9 @@ function buildUserPrompt(inputs: ComposerInputs): string {
|
||||
lines.push(`# SIE-sammanfattning`)
|
||||
lines.push(`Antal år: ${inputs.sieSummary.year_count}`)
|
||||
if (inputs.sieSummary.top_accounts.length > 0) {
|
||||
lines.push('Topp-konton (abs-belopp):')
|
||||
// Ledger balances: journal_entry_lines are booked in SEK by definition,
|
||||
// so a bare kr figure is correct here.
|
||||
lines.push('Topp-konton (abs-belopp, bokförda i SEK):')
|
||||
for (const a of inputs.sieSummary.top_accounts.slice(0, 20)) {
|
||||
lines.push(` ${a.account.padEnd(8)} ${Math.round(a.abs_amount).toLocaleString('sv-SE')} kr`)
|
||||
}
|
||||
@@ -249,35 +357,64 @@ function buildUserPrompt(inputs: ComposerInputs): string {
|
||||
if (inputs.sieSummary.top_counterparties.length > 0) {
|
||||
lines.push('Topp-motparter (från transaktionsbeskrivningar):')
|
||||
for (const c of inputs.sieSummary.top_counterparties.slice(0, 10)) {
|
||||
lines.push(` ${c.name}: ${Math.round(c.abs_amount).toLocaleString('sv-SE')} kr`)
|
||||
lines.push(` ${c.name}: ${formatMagnitude(c)}`)
|
||||
}
|
||||
}
|
||||
if (inputs.sieSummary.unconvertible_counterparties.length > 0) {
|
||||
lines.push('Motparter utan känd SEK-motsvarighet (växelkurs saknas, därför inte rankade ovan):')
|
||||
for (const c of inputs.sieSummary.unconvertible_counterparties) {
|
||||
lines.push(` ${c.name}: ${formatMagnitude(c)}`)
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
if (inputs.bankingSummary) {
|
||||
const bank = inputs.bankingSummary
|
||||
lines.push(`# Banktransaktioner (12 mån)`)
|
||||
if (inputs.bankingSummary.monthly_volume != null) {
|
||||
|
||||
const volumeTotal = bank.volume_rows_with_sek + bank.volume_rows_without_sek
|
||||
if (bank.monthly_volume != null) {
|
||||
// Only the rows with a known SEK value are in this figure. When some
|
||||
// rows are missing a rate the number is a floor, and saying so beats
|
||||
// printing a confident total the data cannot back.
|
||||
const caveat =
|
||||
bank.volume_rows_without_sek > 0
|
||||
? ` (GOLV: ${bank.volume_rows_without_sek} av ${volumeTotal} transaktioner saknar växelkurs och ingår inte, den verkliga volymen är högre)`
|
||||
: ''
|
||||
lines.push(
|
||||
`Snittvolym per månad: ${Math.round(inputs.bankingSummary.monthly_volume).toLocaleString('sv-SE')} kr`,
|
||||
`Snittvolym per månad: ${Math.round(bank.monthly_volume).toLocaleString('sv-SE')} kr${caveat}`,
|
||||
)
|
||||
} else if (bank.volume_rows_without_sek > 0) {
|
||||
lines.push(
|
||||
`Snittvolym per månad: OKÄND. Samtliga ${volumeTotal} transaktioner är i utländsk valuta utan lagrad växelkurs, så ingen kr-volym kan beräknas.`,
|
||||
)
|
||||
}
|
||||
lines.push(
|
||||
`Antal obokförda transaktioner: ${inputs.bankingSummary.unbooked_count}`,
|
||||
)
|
||||
if (inputs.bankingSummary.top_counterparties.length > 0) {
|
||||
lines.push(`Antal obokförda transaktioner: ${bank.unbooked_count}`)
|
||||
if (bank.currencies.length > 1) {
|
||||
lines.push(
|
||||
`Valutor i underlaget: ${bank.currencies.join(', ')}. Beloppen nedan står i sin egen valuta, addera dem inte.`,
|
||||
)
|
||||
}
|
||||
if (bank.top_counterparties.length > 0) {
|
||||
lines.push('Topp-motparter (riktning + bokföringsstatus):')
|
||||
for (const c of inputs.bankingSummary.top_counterparties.slice(0, 20)) {
|
||||
for (const c of bank.top_counterparties.slice(0, 20)) {
|
||||
// direction tells Opus whether this counterparty is a source of
|
||||
// income, a cost, or both. has_unbooked says whether there's still
|
||||
// a transaction waiting for the user to book: only those are
|
||||
// legitimate verification-question fodder.
|
||||
const dirLabel =
|
||||
c.direction === 'in' ? 'in' : c.direction === 'out' ? 'ut' : 'in+ut'
|
||||
const bookedLabel = c.has_unbooked ? 'OBOKFÖRD' : 'bokförd'
|
||||
lines.push(
|
||||
` ${c.name}: ${Math.round(c.abs_amount).toLocaleString('sv-SE')} kr (${dirLabel}, ${bookedLabel})`,
|
||||
)
|
||||
lines.push(` ${c.name}: ${formatMagnitude(c)} (${counterpartyLabels(c)})`)
|
||||
}
|
||||
}
|
||||
if (bank.unconvertible_counterparties.length > 0) {
|
||||
// These rank as 0 kr and would otherwise disappear at the slice above.
|
||||
// They are unmeasured, not small: listing them separately keeps that
|
||||
// distinction visible to the model.
|
||||
lines.push(
|
||||
'Motparter utan känd SEK-motsvarighet (växelkurs saknas, därför inte rankade ovan, storleken är omätt och inte liten):',
|
||||
)
|
||||
for (const c of bank.unconvertible_counterparties) {
|
||||
lines.push(` ${c.name}: ${formatMagnitude(c)} (${counterpartyLabels(c)})`)
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
@@ -319,7 +456,7 @@ function buildUserPrompt(inputs: ComposerInputs): string {
|
||||
// Surfaces user-settled facts in a tight bullet list the composer can scan
|
||||
// before generating questions. Anything in here is OFF-LIMITS for the
|
||||
// verification_questions list: the user already said it.
|
||||
function buildKnownFacts(inputs: ComposerInputs): string[] {
|
||||
export function buildKnownFacts(inputs: ComposerInputs): string[] {
|
||||
const out: string[] = []
|
||||
const s = inputs.companySettings
|
||||
if (s) {
|
||||
@@ -343,17 +480,12 @@ function buildKnownFacts(inputs: ComposerInputs): string[] {
|
||||
if (s.vat_registered != null) {
|
||||
out.push(`Momsregistrerad: ${s.vat_registered ? 'ja' : 'nej'}`)
|
||||
}
|
||||
if (s.has_employees != null || s.employee_count != null) {
|
||||
const ec = s.employee_count
|
||||
if (typeof ec === 'number') {
|
||||
out.push(`Anställda: ${ec}`)
|
||||
} else if (s.has_employees != null) {
|
||||
out.push(`Anställda: ${s.has_employees ? 'ja' : 'nej'}`)
|
||||
}
|
||||
}
|
||||
if (s.pays_salaries != null) {
|
||||
out.push(`Betalar ut lön: ${s.pays_salaries ? 'ja' : 'nej'}`)
|
||||
}
|
||||
if (s.employer_registered != null) {
|
||||
out.push(`Arbetsgivarregistrerad: ${s.employer_registered ? 'ja' : 'nej'}`)
|
||||
}
|
||||
if (s.accounting_method) {
|
||||
out.push(`Bokföringsmetod: ${s.accounting_method}`)
|
||||
}
|
||||
@@ -361,6 +493,15 @@ function buildKnownFacts(inputs: ComposerInputs): string[] {
|
||||
out.push(`Säte: ${s.city}`)
|
||||
}
|
||||
}
|
||||
// Outside the settings block on purpose: a live employee count is a fact even
|
||||
// for a company with no company_settings row yet.
|
||||
const employeeFact = employeeKnownFact({
|
||||
activeEmployees: inputs.activeEmployees,
|
||||
ticEmployeeRange: null,
|
||||
employerRegistered: s?.employer_registered ?? null,
|
||||
paysSalaries: s?.pays_salaries ?? null,
|
||||
})
|
||||
if (employeeFact) out.push(employeeFact)
|
||||
const tic = inputs.ticSnapshot as
|
||||
| {
|
||||
registration?: { fTax?: boolean; vat?: boolean; payroll?: boolean }
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* "Har bolaget anställda?" resolved from columns that actually exist.
|
||||
*
|
||||
* WHY THIS MODULE EXISTS
|
||||
* ----------------------
|
||||
* The agent-onboarding review card and the composer both need this fact, and
|
||||
* neither could get it: both selected `company_settings.employee_count` and
|
||||
* `company_settings.has_employees`, and neither column has ever existed.
|
||||
* `employee_count` lives on `agi_declarations` (20260414120000_salary_module);
|
||||
* `has_employees` appears in no migration at all. PostgREST answers 42703 and
|
||||
* rejects the select WHOLE, so those two names were also throwing away the real
|
||||
* columns selected beside them (city, moms_period, fiscal_year_start_month,
|
||||
* f_skatt, vat_registered, pays_salaries, accounting_method, is_sandbox).
|
||||
*
|
||||
* WHAT IS ACTUALLY KNOWABLE, strongest evidence first:
|
||||
*
|
||||
* 1. `employees` rows that are active. A row exists because a person with a
|
||||
* personnummer was entered, so a POSITIVE count is a hard fact. A zero
|
||||
* count is not the opposite fact: a company that has not opened the payroll
|
||||
* module yet also has zero rows, which is every company arriving at agent
|
||||
* onboarding. Zero is therefore never read as "nej".
|
||||
* 2. `companies.tic_snapshot.employeeRange`: Bolagsverket's registered employee
|
||||
* interval ("5-9"). Authoritative but coarse, and only as fresh as the last
|
||||
* TIC fetch.
|
||||
* 3. `company_settings.employer_registered` (nullable, 20260717151000): whether
|
||||
* the company is registered as an employer with Skatteverket. The column is
|
||||
* nullable precisely so that "nobody ever attested this" is representable
|
||||
* (DECISIONS.md 2026-07-17), so a non-null value settles the question in
|
||||
* BOTH directions.
|
||||
* 4. `company_settings.pays_salaries` (NOT NULL DEFAULT false, 20260401000000):
|
||||
* the "Betalar löner" toggle on /settings/tax. `true` is evidence. `false`
|
||||
* is NOT: the column defaults to false, no onboarding step asks, and its
|
||||
* only writer is that settings form. Reading the default as "nej" would
|
||||
* state a fact nobody entered, and would drop the composer's verification
|
||||
* question for every company that never opened tax settings.
|
||||
*
|
||||
* Being a registered employer and having employees are not the same predicate:
|
||||
* a registered employer still files nil AGI months with nobody on payroll. This
|
||||
* module therefore only ever reports a NUMBER when actual employee rows back it,
|
||||
* and otherwise reports the employer fact as a plain yes/no.
|
||||
*/
|
||||
|
||||
export interface EmployeeFacts {
|
||||
/** Employees currently flagged active. null when the count could not be read. */
|
||||
activeEmployees: number | null
|
||||
/** Bolagsverket's registered employee interval, from the TIC snapshot. */
|
||||
ticEmployeeRange: string | null
|
||||
/** Attested Skatteverket employer registration. null = never attested. */
|
||||
employerRegistered: boolean | null
|
||||
/** The "Betalar löner" toggle. `false` is a column default, not an answer. */
|
||||
paysSalaries: boolean | null
|
||||
}
|
||||
|
||||
export type EmployeeVerdict =
|
||||
| { kind: 'count'; count: number }
|
||||
| { kind: 'range'; range: string }
|
||||
| { kind: 'employer'; isEmployer: boolean }
|
||||
| { kind: 'unknown' }
|
||||
|
||||
/**
|
||||
* Count employees flagged active for a company. Mirrors how the rest of the app
|
||||
* defines "active employee" (lib/salary/create-run.ts, lib/reports/vacation-
|
||||
* liability.ts, the MCP server's headcount tools): `is_active`, with no separate
|
||||
* `employment_end` test, because deactivation sets `is_active = false`. Served
|
||||
* by the partial index `idx_employees_active (company_id, is_active)`.
|
||||
*
|
||||
* Returns null (not 0) on error, so "we could not read this" never collapses
|
||||
* into "this company has nobody".
|
||||
*/
|
||||
export async function loadActiveEmployeeCount(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<number | null> {
|
||||
const { count, error } = await supabase
|
||||
.from('employees')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
if (error) return null
|
||||
return count ?? null
|
||||
}
|
||||
|
||||
/** Pick the strongest fact available, or report that there is none. */
|
||||
export function resolveEmployeeFacts(facts: EmployeeFacts): EmployeeVerdict {
|
||||
// A live headcount beats Bolagsverket's interval: it is the figure this app
|
||||
// can act on (it is what a salary run enumerates) and it is current by
|
||||
// construction, where the snapshot is only as fresh as the last TIC fetch.
|
||||
if (facts.activeEmployees != null && facts.activeEmployees > 0) {
|
||||
return { kind: 'count', count: facts.activeEmployees }
|
||||
}
|
||||
const range = facts.ticEmployeeRange?.trim()
|
||||
if (range) return { kind: 'range', range }
|
||||
if (facts.employerRegistered === true) return { kind: 'employer', isEmployer: true }
|
||||
if (facts.paysSalaries === true) return { kind: 'employer', isEmployer: true }
|
||||
// Only an ATTESTED negative is a negative. pays_salaries === false is the
|
||||
// column default and says nothing.
|
||||
if (facts.employerRegistered === false) return { kind: 'employer', isEmployer: false }
|
||||
return { kind: 'unknown' }
|
||||
}
|
||||
|
||||
/**
|
||||
* True when we hold a fact that settles "har bolaget anställda", i.e. when the
|
||||
* composer must not generate a verification question about it.
|
||||
*/
|
||||
export function knowsEmployeeFact(facts: EmployeeFacts): boolean {
|
||||
return resolveEmployeeFacts(facts).kind !== 'unknown'
|
||||
}
|
||||
|
||||
/**
|
||||
* Value for the onboarding review card's "Anställda" row. null renders as the
|
||||
* field's placeholder rather than inventing a figure.
|
||||
*/
|
||||
export function employeeFieldValue(facts: EmployeeFacts): string | null {
|
||||
const verdict = resolveEmployeeFacts(facts)
|
||||
switch (verdict.kind) {
|
||||
case 'count':
|
||||
return String(verdict.count)
|
||||
case 'range':
|
||||
return verdict.range
|
||||
case 'employer':
|
||||
return verdict.isEmployer ? 'Ja' : 'Nej'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer KÄNDA FAKTA line, or null when nothing is known. Resolved WITHOUT
|
||||
* the TIC range: that already gets its own labelled line in the same block, and
|
||||
* stating the same interval twice invites the model to treat it as two facts.
|
||||
*/
|
||||
export function employeeKnownFact(facts: EmployeeFacts): string | null {
|
||||
const verdict = resolveEmployeeFacts({ ...facts, ticEmployeeRange: null })
|
||||
switch (verdict.kind) {
|
||||
case 'count':
|
||||
return `Anställda: ${verdict.count}`
|
||||
case 'employer':
|
||||
return `Anställda: ${verdict.isEmployer ? 'ja' : 'nej'}`
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
+259
-48
@@ -1,5 +1,6 @@
|
||||
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;
|
||||
@@ -46,18 +47,25 @@ export async function loadCompanyTicSnapshot(
|
||||
}
|
||||
}
|
||||
|
||||
// Known facts from `company_settings`: the onboarding form persists these
|
||||
// (moms_period, fiscal_year_start_month, f_skatt, employees, city). Composer
|
||||
// uses them as KNOWN inputs so it stops generating verification questions
|
||||
// about already-settled values.
|
||||
// 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
|
||||
employee_count: number | null
|
||||
has_employees: boolean | null
|
||||
employer_registered: boolean | null
|
||||
pays_salaries: boolean | null
|
||||
accounting_method: string | null
|
||||
}
|
||||
@@ -69,7 +77,7 @@ export async function loadCompanySettings(
|
||||
const { data } = await supabase
|
||||
.from('company_settings')
|
||||
.select(
|
||||
'city, moms_period, fiscal_year_start_month, f_skatt, vat_registered, employee_count, has_employees, pays_salaries, accounting_method',
|
||||
'city, moms_period, fiscal_year_start_month, f_skatt, vat_registered, employer_registered, pays_salaries, accounting_method',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
@@ -144,9 +152,162 @@ export async function loadUserDirectorship(
|
||||
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: { name: 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
|
||||
}
|
||||
|
||||
@@ -181,7 +342,9 @@ export async function loadSieSummary(
|
||||
|
||||
// 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.
|
||||
// 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,
|
||||
@@ -201,36 +364,42 @@ export async function loadSieSummary(
|
||||
// `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')
|
||||
.select('description, amount, currency, amount_sek, exchange_rate')
|
||||
.eq('company_id', companyId)
|
||||
.limit(2000)
|
||||
|
||||
const cpAgg = new Map<string, number>()
|
||||
const cpAgg = new Map<string, MagnitudeBucket>()
|
||||
if (Array.isArray(tx)) {
|
||||
for (const t of tx as { description: string | null; amount: number | string | null }[]) {
|
||||
for (const t of tx as (AmountRow & { description: string | null })[]) {
|
||||
const name = normalizeCounterparty(t.description)
|
||||
if (!name) continue
|
||||
const amt = Math.abs(Number(t.amount) || 0)
|
||||
cpAgg.set(name, (cpAgg.get(name) ?? 0) + amt)
|
||||
let bucket = cpAgg.get(name)
|
||||
if (!bucket) {
|
||||
bucket = newMagnitudeBucket()
|
||||
cpAgg.set(name, bucket)
|
||||
}
|
||||
addRowToMagnitude(bucket, t)
|
||||
}
|
||||
}
|
||||
const topCounterparties = Array.from(cpAgg.entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 10)
|
||||
.map(([name, abs_amount]) => ({ name, abs_amount }))
|
||||
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: topCounterparties,
|
||||
top_counterparties: top,
|
||||
unconvertible_counterparties: unconvertible,
|
||||
year_count: years.size,
|
||||
}
|
||||
}
|
||||
|
||||
interface BankingCounterparty {
|
||||
name: string
|
||||
abs_amount: number
|
||||
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
|
||||
@@ -246,7 +415,20 @@ interface BankingCounterparty {
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -263,9 +445,12 @@ 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, date, journal_entry_id')
|
||||
.select('description, amount, currency, amount_sek, exchange_rate, date, journal_entry_id')
|
||||
.eq('company_id', companyId)
|
||||
.gte('date', oneYearAgo())
|
||||
.order('date', { ascending: false })
|
||||
@@ -273,51 +458,70 @@ export async function loadBankingSummary(
|
||||
if (error || !Array.isArray(data) || data.length === 0) return null
|
||||
|
||||
interface Bucket {
|
||||
absAmount: number
|
||||
magnitude: MagnitudeBucket
|
||||
hasInflow: boolean
|
||||
hasOutflow: boolean
|
||||
hasUnbooked: boolean
|
||||
}
|
||||
const cpAgg = new Map<string, Bucket>()
|
||||
let totalVolume = 0
|
||||
const currencies = new Set<string>()
|
||||
let sekVolume = 0
|
||||
let volumeRowsWithSek = 0
|
||||
let volumeRowsWithoutSek = 0
|
||||
let unbookedCount = 0
|
||||
for (const t of data as {
|
||||
for (const t of data as (AmountRow & {
|
||||
description: string | null
|
||||
amount: number | string | null
|
||||
journal_entry_id: string | null
|
||||
}[]) {
|
||||
const signedAmt = Number(t.amount) || 0
|
||||
const absAmt = Math.abs(signedAmt)
|
||||
totalVolume += absAmt
|
||||
})[]) {
|
||||
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
|
||||
const prev = cpAgg.get(name) ?? {
|
||||
absAmount: 0,
|
||||
hasInflow: false,
|
||||
hasOutflow: false,
|
||||
hasUnbooked: false,
|
||||
let bucket = cpAgg.get(name)
|
||||
if (!bucket) {
|
||||
bucket = {
|
||||
magnitude: newMagnitudeBucket(),
|
||||
hasInflow: false,
|
||||
hasOutflow: false,
|
||||
hasUnbooked: false,
|
||||
}
|
||||
cpAgg.set(name, bucket)
|
||||
}
|
||||
prev.absAmount += absAmt
|
||||
if (signedAmt > 0) prev.hasInflow = true
|
||||
if (signedAmt < 0) prev.hasOutflow = true
|
||||
if (!t.journal_entry_id) prev.hasUnbooked = true
|
||||
cpAgg.set(name, prev)
|
||||
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 top: BankingCounterparty[] = Array.from(cpAgg.entries())
|
||||
.sort((a, b) => b[1].absAmount - a[1].absAmount)
|
||||
.slice(0, 20)
|
||||
.map(([name, b]) => ({
|
||||
const allCounterparties: BankingCounterparty[] = Array.from(cpAgg.entries()).map(
|
||||
([name, b]) => ({
|
||||
name,
|
||||
abs_amount: b.absAmount,
|
||||
...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,
|
||||
monthly_volume: totalVolume > 0 ? Math.round(totalVolume / 12) : null,
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -350,6 +554,10 @@ export interface ComposerInputs {
|
||||
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[]
|
||||
@@ -371,6 +579,7 @@ export async function gatherComposerInputs(
|
||||
sieSummary,
|
||||
bankingSummary,
|
||||
companySettings,
|
||||
activeEmployees,
|
||||
directorship,
|
||||
] = await Promise.all([
|
||||
loadCompanyTicSnapshot(supabase, companyId),
|
||||
@@ -378,6 +587,7 @@ export async function gatherComposerInputs(
|
||||
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 })),
|
||||
])
|
||||
|
||||
@@ -388,6 +598,7 @@ export async function gatherComposerInputs(
|
||||
ticSnapshot: snapshot,
|
||||
ticFetchedAt: fetchedAt,
|
||||
companySettings,
|
||||
activeEmployees,
|
||||
sieSummary,
|
||||
bankingSummary,
|
||||
atomIndex,
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { bokslutStep } from '../bokslut-step'
|
||||
|
||||
// fiscal_periods has no `status` column: state is is_closed + locked_at
|
||||
// (see lib/core/bookkeeping/period-service.ts and the period-lock triggers).
|
||||
// Selecting `status` made PostgREST reject the whole query, so the bokslut
|
||||
// intent never resolved a period and silently dropped the räkenskapsår from
|
||||
// the prompt. The mocked Supabase harness happily returns whatever rows the
|
||||
// test enqueues regardless of the column list, so these tests assert the
|
||||
// SELECT string itself, plus the open/locked/closed/unknown prompt branches.
|
||||
|
||||
interface QueryResult {
|
||||
data: unknown
|
||||
error: unknown
|
||||
}
|
||||
|
||||
interface RecordedSelect {
|
||||
table: string
|
||||
columns: string
|
||||
}
|
||||
|
||||
function createRecordingSupabase(results: Record<string, QueryResult>) {
|
||||
const selects: RecordedSelect[] = []
|
||||
|
||||
const buildChain = (table: string) => {
|
||||
const chain = {
|
||||
select: (columns: string) => {
|
||||
selects.push({ table, columns })
|
||||
return chain
|
||||
},
|
||||
eq: () => chain,
|
||||
order: () => chain,
|
||||
limit: () => chain,
|
||||
maybeSingle: async (): Promise<QueryResult> =>
|
||||
results[table] ?? { data: null, error: null },
|
||||
}
|
||||
return chain
|
||||
}
|
||||
|
||||
const supabase = {
|
||||
from: (table: string) => buildChain(table),
|
||||
} as unknown as SupabaseClient
|
||||
|
||||
return { supabase, selects }
|
||||
}
|
||||
|
||||
const COMPANY_ID = '22222222-2222-2222-2222-222222222222'
|
||||
const PERIOD_ID = '33333333-3333-3333-3333-333333333333'
|
||||
|
||||
function periodRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: PERIOD_ID,
|
||||
period_start: '2025-01-01',
|
||||
period_end: '2025-12-31',
|
||||
is_closed: false,
|
||||
locked_at: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
async function capture(results: Record<string, QueryResult>) {
|
||||
const { supabase, selects } = createRecordingSupabase(results)
|
||||
const captured = await bokslutStep.capture(
|
||||
{ step_id: 'accruals', fiscal_year_end: null },
|
||||
{ supabase, userId: 'user-1', companyId: COMPANY_ID },
|
||||
)
|
||||
return { captured, selects }
|
||||
}
|
||||
|
||||
function render(captured: Awaited<ReturnType<typeof bokslutStep.capture>>) {
|
||||
return bokslutStep.promptTemplate({ captured, profileSummary: null, activeMemory: [] })
|
||||
}
|
||||
|
||||
describe('bokslut.step capture', () => {
|
||||
it('selects the real fiscal_periods state columns, never a `status` column', async () => {
|
||||
const { selects } = await capture({
|
||||
fiscal_periods: { data: periodRow(), error: null },
|
||||
companies: { data: { entity_type: 'ab' }, error: null },
|
||||
})
|
||||
|
||||
const periodSelect = selects.find((s) => s.table === 'fiscal_periods')
|
||||
expect(periodSelect).toBeDefined()
|
||||
expect(periodSelect?.columns).toBe('id, period_start, period_end, is_closed, locked_at')
|
||||
// The column does not exist: requesting it makes PostgREST 400 the query.
|
||||
expect(periodSelect?.columns).not.toMatch(/\bstatus\b/)
|
||||
})
|
||||
|
||||
it('maps an unlocked, unclosed period to status open', async () => {
|
||||
const { captured } = await capture({
|
||||
fiscal_periods: { data: periodRow(), error: null },
|
||||
companies: { data: { entity_type: 'ab' }, error: null },
|
||||
})
|
||||
|
||||
expect(captured.period_lookup_failed).toBe(false)
|
||||
expect(captured.fiscal_period).toMatchObject({
|
||||
id: PERIOD_ID,
|
||||
period_start: '2025-01-01',
|
||||
period_end: '2025-12-31',
|
||||
status: 'open',
|
||||
lock_date: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('maps locked_at to status locked and is_closed to status closed', async () => {
|
||||
const { captured: locked } = await capture({
|
||||
fiscal_periods: { data: periodRow({ locked_at: '2026-02-01T10:00:00Z' }), error: null },
|
||||
companies: { data: null, error: null },
|
||||
})
|
||||
expect(locked.fiscal_period?.status).toBe('locked')
|
||||
expect(locked.fiscal_period?.lock_date).toBe('2026-02-01T10:00:00Z')
|
||||
|
||||
// is_closed wins over locked_at, same precedence as period-service.
|
||||
const { captured: closed } = await capture({
|
||||
fiscal_periods: {
|
||||
data: periodRow({ is_closed: true, locked_at: '2026-02-01T10:00:00Z' }),
|
||||
error: null,
|
||||
},
|
||||
companies: { data: null, error: null },
|
||||
})
|
||||
expect(closed.fiscal_period?.status).toBe('closed')
|
||||
})
|
||||
|
||||
it('fails closed when the period lookup errors', async () => {
|
||||
const { captured } = await capture({
|
||||
fiscal_periods: { data: null, error: { message: 'column does not exist' } },
|
||||
companies: { data: { entity_type: 'ab' }, error: null },
|
||||
})
|
||||
|
||||
expect(captured.fiscal_period).toBeNull()
|
||||
expect(captured.period_lookup_failed).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bokslut.step prompt template', () => {
|
||||
it('states the period is open without any lock warning', async () => {
|
||||
const { captured } = await capture({
|
||||
fiscal_periods: { data: periodRow(), error: null },
|
||||
companies: { data: { entity_type: 'ab' }, error: null },
|
||||
})
|
||||
const out = render(captured)
|
||||
|
||||
expect(out).toContain('Räkenskapsår: 2025-01-01 → 2025-12-31 (status: öppen)')
|
||||
expect(out).not.toContain('VARNING')
|
||||
expect(out).not.toContain('Perioden är LÅST')
|
||||
expect(out).not.toContain('Perioden är STÄNGD')
|
||||
})
|
||||
|
||||
it('tells the agent not to propose bookings in a closed period', async () => {
|
||||
const { captured } = await capture({
|
||||
fiscal_periods: { data: periodRow({ is_closed: true }), error: null },
|
||||
companies: { data: { entity_type: 'ab' }, error: null },
|
||||
})
|
||||
const out = render(captured)
|
||||
|
||||
expect(out).toContain('(status: stängd)')
|
||||
expect(out).toContain('Perioden är STÄNGD')
|
||||
expect(out).toContain('BFL 5 kap 5 §')
|
||||
expect(out).toContain('Föreslå inga bokningar')
|
||||
})
|
||||
|
||||
it('tells the agent a locked period must be unlocked first', async () => {
|
||||
const { captured } = await capture({
|
||||
fiscal_periods: { data: periodRow({ locked_at: '2026-02-01T10:00:00Z' }), error: null },
|
||||
companies: { data: { entity_type: 'ab' }, error: null },
|
||||
})
|
||||
const out = render(captured)
|
||||
|
||||
expect(out).toContain('(status: låst)')
|
||||
expect(out).toContain('Perioden är LÅST')
|
||||
expect(out).toContain('2026-02-01T10:00:00Z')
|
||||
})
|
||||
|
||||
it('never presents an unresolvable year as open', async () => {
|
||||
const { captured: errored } = await capture({
|
||||
fiscal_periods: { data: null, error: { message: 'boom' } },
|
||||
companies: { data: { entity_type: 'ab' }, error: null },
|
||||
})
|
||||
const erroredOut = render(errored)
|
||||
expect(erroredOut).toContain('uppslaget av räkenskapsåret misslyckades')
|
||||
expect(erroredOut).toContain('OKÄND')
|
||||
expect(erroredOut).toContain('Anta INTE att året är öppet')
|
||||
expect(erroredOut).not.toContain('status: öppen')
|
||||
|
||||
const { captured: missing } = await capture({
|
||||
fiscal_periods: { data: null, error: null },
|
||||
companies: { data: { entity_type: 'ab' }, error: null },
|
||||
})
|
||||
const missingOut = render(missing)
|
||||
expect(missingOut).toContain('inget räkenskapsår hittades')
|
||||
expect(missingOut).toContain('Anta INTE att året är öppet')
|
||||
expect(missingOut).not.toContain('status: öppen')
|
||||
})
|
||||
|
||||
it('exposes gnubok_list_fiscal_periods so the fail-closed instruction is actionable', () => {
|
||||
expect(bokslutStep.tools).toContain('gnubok_list_fiscal_periods')
|
||||
expect(bokslutStep.tools).toContain('gnubok_year_end_readiness')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { inboxBulkBook } from '../inbox-bulk-book'
|
||||
|
||||
// The bank leg of this sheet is what an LLM agent reads before it decides how
|
||||
// to book. A foreign magnitude printed with "SEK" is worse than a missing
|
||||
// value: the agent proceeds confidently on a number that is off by the
|
||||
// exchange rate. These tests lock the unit to the transaction's real currency.
|
||||
|
||||
const ITEM_ID = '11111111-1111-1111-1111-111111111111'
|
||||
const TX_ID = '22222222-2222-2222-2222-222222222222'
|
||||
|
||||
interface TxFixture {
|
||||
amount: number
|
||||
currency: string | null
|
||||
amount_sek: number | null
|
||||
exchange_rate: number | null
|
||||
}
|
||||
|
||||
async function renderPromptForTx(tx: TxFixture): Promise<string> {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: ITEM_ID,
|
||||
matched_transaction_id: TX_ID,
|
||||
created_journal_entry_id: null,
|
||||
created_supplier_invoice_id: null,
|
||||
extracted_data: {
|
||||
supplier: { name: 'Nordvind Molntjänst' },
|
||||
invoice: { invoiceDate: '2026-05-12', currency: tx.currency ?? 'SEK' },
|
||||
totals: { total: tx.amount, vatAmount: null },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: TX_ID,
|
||||
date: '2026-05-12',
|
||||
amount: -tx.amount,
|
||||
currency: tx.currency,
|
||||
amount_sek: tx.amount_sek == null ? null : -tx.amount_sek,
|
||||
exchange_rate: tx.exchange_rate,
|
||||
description: 'NORDVIND MOLN',
|
||||
},
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const captured = await inboxBulkBook.capture(
|
||||
{ item_ids: [ITEM_ID] },
|
||||
{
|
||||
supabase: supabase as unknown as SupabaseClient,
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
},
|
||||
)
|
||||
|
||||
return inboxBulkBook.promptTemplate({ captured, profileSummary: null, activeMemory: [] })
|
||||
}
|
||||
|
||||
describe('inbox.bulk-book bank amount rendering', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders a 500 EUR bank row in EUR and never calls it SEK', async () => {
|
||||
// amount_sek is stored, so BOTH legs are shown: the agent can reason about
|
||||
// the foreign amount and the SEK magnitude it will actually book.
|
||||
const out = await renderPromptForTx({
|
||||
amount: 500,
|
||||
currency: 'EUR',
|
||||
amount_sek: 5750,
|
||||
exchange_rate: 11.5,
|
||||
})
|
||||
|
||||
expect(out).toContain(`bank=${(500).toLocaleString('sv-SE')} EUR`)
|
||||
expect(out).toContain(`(${(5750).toLocaleString('sv-SE')} SEK)`)
|
||||
// The old rendering printed "bank=500 SEK" for exactly this row.
|
||||
expect(out).not.toContain(`bank=${(500).toLocaleString('sv-SE')} SEK`)
|
||||
})
|
||||
|
||||
it('says the SEK amount is missing instead of implying SEK when no rate is stored', async () => {
|
||||
// Neither amount_sek nor exchange_rate: there is NO known SEK value. The
|
||||
// old code multiplied by an implicit rate of 1 and labelled the result SEK.
|
||||
const out = await renderPromptForTx({
|
||||
amount: 500,
|
||||
currency: 'EUR',
|
||||
amount_sek: null,
|
||||
exchange_rate: null,
|
||||
})
|
||||
|
||||
expect(out).toContain(`bank=${(500).toLocaleString('sv-SE')} EUR`)
|
||||
expect(out).toContain('SEK-belopp saknas')
|
||||
expect(out).not.toContain(`bank=${(500).toLocaleString('sv-SE')} SEK`)
|
||||
// And the agent is told not to book that row on a number it cannot trust.
|
||||
expect(out).toContain('VÄXELKURS SAKNAS')
|
||||
})
|
||||
|
||||
it('derives the SEK amount from exchange_rate when amount_sek is absent', async () => {
|
||||
const out = await renderPromptForTx({
|
||||
amount: 500,
|
||||
currency: 'EUR',
|
||||
amount_sek: null,
|
||||
exchange_rate: 11.5,
|
||||
})
|
||||
|
||||
expect(out).toContain(`bank=${(500).toLocaleString('sv-SE')} EUR`)
|
||||
expect(out).toContain(`(${(5750).toLocaleString('sv-SE')} SEK)`)
|
||||
expect(out).not.toContain('SEK-belopp saknas')
|
||||
expect(out).not.toContain('VÄXELKURS SAKNAS')
|
||||
})
|
||||
|
||||
it('renders a plain SEK bank row unchanged', async () => {
|
||||
const out = await renderPromptForTx({
|
||||
amount: 500,
|
||||
currency: 'SEK',
|
||||
amount_sek: null,
|
||||
exchange_rate: null,
|
||||
})
|
||||
|
||||
expect(out).toContain(`bank=${(500).toLocaleString('sv-SE')} SEK`)
|
||||
// No parenthesised second leg and no foreign code on the bank part. (The
|
||||
// static MOMS instruction mentions "USD/EUR", so scan the item line only.)
|
||||
const itemLine = out.split('\n').find((l) => l.includes('item_id=')) ?? ''
|
||||
expect(itemLine).not.toContain('EUR')
|
||||
expect(itemLine).toContain('bank=500 SEK,')
|
||||
expect(out).not.toContain('SEK-belopp saknas')
|
||||
expect(out).not.toContain('VÄXELKURS SAKNAS')
|
||||
})
|
||||
|
||||
it('carries the transaction currency through capture alongside the SEK leg', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: ITEM_ID,
|
||||
matched_transaction_id: TX_ID,
|
||||
created_journal_entry_id: null,
|
||||
created_supplier_invoice_id: null,
|
||||
extracted_data: {},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: TX_ID,
|
||||
date: '2026-05-12',
|
||||
amount: -500,
|
||||
currency: 'eur',
|
||||
amount_sek: null,
|
||||
exchange_rate: null,
|
||||
description: 'NORDVIND MOLN',
|
||||
},
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const captured = await inboxBulkBook.capture(
|
||||
{ item_ids: [ITEM_ID] },
|
||||
{
|
||||
supabase: supabase as unknown as SupabaseClient,
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
},
|
||||
)
|
||||
|
||||
expect(captured.items[0].tx_amount).toBe(500)
|
||||
expect(captured.items[0].tx_currency).toBe('EUR')
|
||||
expect(captured.items[0].tx_amount_sek).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,342 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { supplierInvoiceReview } from '../supplier-invoice-review'
|
||||
|
||||
// This sheet is read by an LLM agent that decides whether to attest a supplier
|
||||
// invoice, and the "KÄNDA FAKTA" block is explicitly labelled "fråga INTE om
|
||||
// dessa". A magnitude printed there without its unit is worse than a missing
|
||||
// value: it reads as confirmation of the registered amount, so a 1 200 EUR
|
||||
// invoice gets attested on the number 1 200 and booked at SEK face value.
|
||||
// These tests lock every amount to its real currency, and keep any amount that
|
||||
// cannot be confirmed out of the "do not ask" block entirely.
|
||||
|
||||
const INVOICE_ID = '11111111-1111-1111-1111-111111111111'
|
||||
const DOC_ID = '22222222-2222-2222-2222-222222222222'
|
||||
|
||||
type Captured = Parameters<typeof supplierInvoiceReview.promptTemplate>[0]['captured']
|
||||
|
||||
const sv = (n: number) => n.toLocaleString('sv-SE')
|
||||
|
||||
interface Fixture {
|
||||
currency: string | null
|
||||
total_sek?: number | null
|
||||
vat_amount_sek?: number | null
|
||||
exchange_rate?: number | null
|
||||
// Currency the AI extraction reports for the PDF. `undefined` = the
|
||||
// extraction carries no currency at all (legacy / partial extraction).
|
||||
extractionCurrency?: string | null
|
||||
withItems?: boolean
|
||||
withRecent?: boolean
|
||||
}
|
||||
|
||||
function makeCaptured(f: Fixture): Captured {
|
||||
return {
|
||||
invoice: {
|
||||
id: INVOICE_ID,
|
||||
arrival_number: 7,
|
||||
supplier_invoice_number: 'F-2026-0042',
|
||||
invoice_date: '2026-05-12',
|
||||
due_date: '2026-06-11',
|
||||
status: 'registered',
|
||||
currency: f.currency,
|
||||
subtotal: 960,
|
||||
vat_amount: 240,
|
||||
total: 1200,
|
||||
vat_amount_sek: f.vat_amount_sek ?? null,
|
||||
total_sek: f.total_sek ?? null,
|
||||
exchange_rate: f.exchange_rate ?? null,
|
||||
vat_treatment: 'standard_25',
|
||||
reverse_charge: false,
|
||||
payment_reference: null,
|
||||
is_credit_note: false,
|
||||
document_id: DOC_ID,
|
||||
},
|
||||
supplier: {
|
||||
id: 'supplier-1',
|
||||
name: 'Nordvind Molntjänst BV',
|
||||
org_number: null,
|
||||
vat_number: 'NL123456789B01',
|
||||
country: 'NL',
|
||||
},
|
||||
items: f.withItems
|
||||
? [
|
||||
{
|
||||
description: 'Molnlagring maj',
|
||||
quantity: 1,
|
||||
unit_price: 960,
|
||||
line_total: 960,
|
||||
vat_rate: 25,
|
||||
account_number: null,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
recent_invoices_from_supplier: f.withRecent
|
||||
? [
|
||||
{
|
||||
invoice_number: 'F-2026-0031',
|
||||
invoice_date: '2026-04-12',
|
||||
total: 1100,
|
||||
total_sek: f.total_sek == null ? null : 12650,
|
||||
currency: f.currency,
|
||||
exchange_rate: f.exchange_rate ?? null,
|
||||
status: 'paid',
|
||||
},
|
||||
]
|
||||
: [],
|
||||
inbox_extraction: {
|
||||
supplier: { name: 'Nordvind Molntjänst BV', orgNumber: null, vatNumber: 'NL123456789B01' },
|
||||
// `extractionCurrency: undefined` leaves the currency key out entirely.
|
||||
invoice:
|
||||
'extractionCurrency' in f ? { currency: f.extractionCurrency } : { currency: f.currency },
|
||||
totals: { subtotal: 960, vatAmount: 240, total: 1200 },
|
||||
vatBreakdown: [{ rate: 25, base: 960, amount: 240 }],
|
||||
},
|
||||
document_extraction: null,
|
||||
}
|
||||
}
|
||||
|
||||
function render(f: Fixture): string {
|
||||
return supplierInvoiceReview.promptTemplate({
|
||||
captured: makeCaptured(f),
|
||||
profileSummary: null,
|
||||
activeMemory: [],
|
||||
})
|
||||
}
|
||||
|
||||
// The single line that states the invoice's own amount.
|
||||
function beloppLine(out: string): string {
|
||||
return out.split('\n').find((l) => l.startsWith('- Belopp:')) ?? ''
|
||||
}
|
||||
|
||||
// Everything under the "fråga INTE om dessa" header, up to the blank line that
|
||||
// closes the block. This is the text the agent is told not to question.
|
||||
function knownFactsBlock(out: string): string {
|
||||
const all = out.split('\n')
|
||||
const start = all.findIndex((l) => l.startsWith('KÄNDA FAKTA'))
|
||||
if (start === -1) return ''
|
||||
const rest = all.slice(start + 1)
|
||||
const end = rest.findIndex((l) => l === '')
|
||||
return rest.slice(0, end === -1 ? rest.length : end).join('\n')
|
||||
}
|
||||
|
||||
describe('supplier_invoice.review currency rendering', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders a 1200 EUR invoice in EUR with the SEK equivalent beside it', () => {
|
||||
const out = render({
|
||||
currency: 'EUR',
|
||||
total_sek: 13800,
|
||||
vat_amount_sek: 2760,
|
||||
exchange_rate: 11.5,
|
||||
})
|
||||
|
||||
expect(beloppLine(out)).toBe(`- Belopp: ${sv(1200)} EUR (moms ${sv(240)} EUR)`)
|
||||
expect(beloppLine(out)).not.toContain('SEK')
|
||||
expect(out).toContain(`I SEK (bokföringen sker i SEK): ${sv(13800)} SEK`)
|
||||
expect(out).toContain(`moms ${sv(2760)} SEK`)
|
||||
expect(out).toContain('växelkurs 11.5')
|
||||
})
|
||||
|
||||
it('derives the SEK leg from exchange_rate when total_sek is absent', () => {
|
||||
const out = render({ currency: 'EUR', total_sek: null, exchange_rate: 11.5 })
|
||||
|
||||
expect(out).toContain(`I SEK (bokföringen sker i SEK): ${sv(13800)} SEK`)
|
||||
expect(out).not.toContain('SEK-BELOPP SAKNAS')
|
||||
})
|
||||
|
||||
it('says the SEK amount is missing instead of implying SEK when no rate is stored', () => {
|
||||
// Neither total_sek nor exchange_rate: there is NO known SEK value. Printing
|
||||
// the face value as kronor here is precisely the bug.
|
||||
const out = render({ currency: 'EUR', total_sek: null, exchange_rate: null })
|
||||
|
||||
expect(beloppLine(out)).toBe(`- Belopp: ${sv(1200)} EUR (moms ${sv(240)} EUR)`)
|
||||
expect(out).toContain('SEK-BELOPP SAKNAS')
|
||||
expect(out).toContain(`${sv(1200)} EUR är INTE ${sv(1200)} SEK`)
|
||||
expect(out).toContain('Attestera inte på det nominella beloppet')
|
||||
})
|
||||
|
||||
it('carries the currency into the KÄNDA FAKTA block for a 1200 EUR invoice', () => {
|
||||
// The finding: the PDF total printed as a bare "1 200" three lines under a
|
||||
// labelled "Belopp: 1200 EUR", inside a block the agent is told not to
|
||||
// question. It must carry EUR.
|
||||
const out = render({
|
||||
currency: 'EUR',
|
||||
total_sek: 13800,
|
||||
vat_amount_sek: 2760,
|
||||
exchange_rate: 11.5,
|
||||
extractionCurrency: 'EUR',
|
||||
})
|
||||
const known = knownFactsBlock(out)
|
||||
|
||||
expect(known).toContain(`- Total (PDF): ${sv(1200)} EUR`)
|
||||
expect(known).toContain(`- Moms (PDF): ${sv(240)} EUR`)
|
||||
expect(known).toContain(`- Momsuppdelning: 25%: ${sv(240)} EUR`)
|
||||
// No bare magnitude anywhere in the "do not ask" block.
|
||||
expect(known).not.toMatch(new RegExp(`${sv(1200)}(?! EUR)`))
|
||||
expect(known).not.toContain(`${sv(1200)} SEK`)
|
||||
})
|
||||
|
||||
it('keeps a currency-less extracted amount OUT of the known-facts block', () => {
|
||||
// A number with no unit cannot confirm a EUR registration. Under a "fråga
|
||||
// INTE om dessa" header it reads as confirmation, so it does not belong
|
||||
// there at all: it moves to a block that tells the agent to settle it first.
|
||||
const out = render({
|
||||
currency: 'EUR',
|
||||
total_sek: 13800,
|
||||
exchange_rate: 11.5,
|
||||
extractionCurrency: null,
|
||||
})
|
||||
const known = knownFactsBlock(out)
|
||||
|
||||
// The supplier identity is still a known fact; the amounts are not.
|
||||
expect(known).toContain('- Leverantör (PDF): Nordvind Molntjänst BV')
|
||||
expect(known).not.toContain('Total (PDF)')
|
||||
expect(known).not.toContain('Moms (PDF)')
|
||||
expect(known).not.toContain('Momsuppdelning')
|
||||
|
||||
expect(out).toContain('EJ BEKRÄFTADE BELOPP')
|
||||
expect(out).toContain(`- Total (PDF): ${sv(1200)} (valuta okänd)`)
|
||||
expect(out).toContain('Extraktionen anger ingen valuta')
|
||||
expect(out).toContain('Behandla det ALDRIG som kronor')
|
||||
expect(out).toContain(`gnubok_get_document_content(document_id=${DOC_ID})`)
|
||||
// And it is never dressed up as kronor.
|
||||
expect(out).not.toContain(`Total (PDF): ${sv(1200)} SEK`)
|
||||
})
|
||||
|
||||
it('flags a genuine currency conflict between registration and extraction', () => {
|
||||
const out = render({
|
||||
currency: 'EUR',
|
||||
total_sek: 13800,
|
||||
exchange_rate: 11.5,
|
||||
extractionCurrency: 'USD',
|
||||
})
|
||||
|
||||
expect(knownFactsBlock(out)).not.toContain('Total (PDF)')
|
||||
expect(out).toContain('EJ BEKRÄFTADE BELOPP')
|
||||
expect(out).toContain('VALUTAKONFLIKT')
|
||||
expect(out).toContain('registrerad i EUR men underlaget anger USD')
|
||||
expect(out).toContain(`- Total (PDF): ${sv(1200)} USD`)
|
||||
})
|
||||
|
||||
it('renders a plain SEK invoice unchanged', () => {
|
||||
const out = render({
|
||||
currency: 'SEK',
|
||||
extractionCurrency: 'SEK',
|
||||
withItems: true,
|
||||
withRecent: true,
|
||||
})
|
||||
|
||||
expect(beloppLine(out)).toBe(`- Belopp: ${sv(1200)} SEK (moms ${sv(240)} SEK)`)
|
||||
expect(out).not.toContain('I SEK (bokföringen sker i SEK)')
|
||||
expect(out).not.toContain('SEK-BELOPP SAKNAS')
|
||||
expect(out).not.toContain('EJ BEKRÄFTADE BELOPP')
|
||||
expect(out).not.toContain('VALUTAKONFLIKT')
|
||||
expect(out).not.toContain('valuta okänd')
|
||||
// Amounts still carry their unit, and the extraction stays a known fact.
|
||||
expect(knownFactsBlock(out)).toContain(`- Total (PDF): ${sv(1200)} SEK`)
|
||||
expect(out).toContain(` • Molnlagring maj: ${sv(960)} SEK (25%)`)
|
||||
expect(out).toContain(`F-2026-0031 (2026-04-12, paid): ${sv(1100)} SEK`)
|
||||
})
|
||||
|
||||
it('labels line items and supplier history in the invoice currency, never bare', () => {
|
||||
const out = render({
|
||||
currency: 'EUR',
|
||||
total_sek: 13800,
|
||||
exchange_rate: 11.5,
|
||||
withItems: true,
|
||||
withRecent: true,
|
||||
})
|
||||
|
||||
expect(out).toContain(` • Molnlagring maj: ${sv(960)} EUR (25%)`)
|
||||
// Supplier history is what the anomaly check compares against, so the SEK
|
||||
// leg travels with it: comparing 1 100 EUR to a SEK figure says nothing.
|
||||
expect(out).toContain(`F-2026-0031 (2026-04-12, paid): ${sv(1100)} EUR (${sv(12650)} SEK)`)
|
||||
expect(out).not.toContain(`${sv(960)} SEK`)
|
||||
})
|
||||
|
||||
it('tells the agent that a foreign invoice is booked on the SEK amount', () => {
|
||||
const out = render({ currency: 'EUR', total_sek: 13800, exchange_rate: 11.5 })
|
||||
|
||||
expect(out).toContain('bokföringen sker i SEK')
|
||||
expect(out).toContain('Ett belopp utan angiven valuta är inte ett SEK-belopp')
|
||||
expect(out).toContain('Jämför i SEK när valutorna skiljer sig åt')
|
||||
})
|
||||
})
|
||||
|
||||
describe('supplier_invoice.review capture', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('threads the SEK columns and the exchange rate through capture', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
// 1. the invoice itself
|
||||
{
|
||||
data: {
|
||||
id: INVOICE_ID,
|
||||
supplier_id: 'supplier-1',
|
||||
arrival_number: 7,
|
||||
supplier_invoice_number: 'F-2026-0042',
|
||||
invoice_date: '2026-05-12',
|
||||
due_date: '2026-06-11',
|
||||
status: 'registered',
|
||||
currency: 'EUR',
|
||||
exchange_rate: 11.5,
|
||||
subtotal: 960,
|
||||
vat_amount: 240,
|
||||
vat_amount_sek: 2760,
|
||||
total: 1200,
|
||||
total_sek: 13800,
|
||||
vat_treatment: 'standard_25',
|
||||
reverse_charge: false,
|
||||
payment_reference: null,
|
||||
is_credit_note: false,
|
||||
document_id: DOC_ID,
|
||||
},
|
||||
},
|
||||
// 2. supplier
|
||||
{ data: { id: 'supplier-1', name: 'Nordvind Molntjänst BV', org_number: null, vat_number: null, country: 'NL' } },
|
||||
// 3. items
|
||||
{ data: [] },
|
||||
// 4. recent invoices from the same supplier
|
||||
{
|
||||
data: [
|
||||
{
|
||||
supplier_invoice_number: 'F-2026-0031',
|
||||
invoice_date: '2026-04-12',
|
||||
total: 1100,
|
||||
total_sek: 12650,
|
||||
currency: 'EUR',
|
||||
exchange_rate: 11.5,
|
||||
status: 'paid',
|
||||
},
|
||||
],
|
||||
},
|
||||
// 5. inbox extraction
|
||||
{ data: null },
|
||||
// 6. document extraction
|
||||
{ data: null },
|
||||
])
|
||||
|
||||
const captured = await supplierInvoiceReview.capture(
|
||||
{ supplier_invoice_id: INVOICE_ID },
|
||||
{
|
||||
supabase: supabase as unknown as SupabaseClient,
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
},
|
||||
)
|
||||
|
||||
expect(captured.invoice?.currency).toBe('EUR')
|
||||
expect(captured.invoice?.total).toBe(1200)
|
||||
expect(captured.invoice?.total_sek).toBe(13800)
|
||||
expect(captured.invoice?.vat_amount_sek).toBe(2760)
|
||||
expect(captured.invoice?.exchange_rate).toBe(11.5)
|
||||
expect(captured.recent_invoices_from_supplier[0].total_sek).toBe(12650)
|
||||
expect(captured.recent_invoices_from_supplier[0].exchange_rate).toBe(11.5)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { verifikationDraft } from '../verifikation-draft'
|
||||
|
||||
// verifikation.draft is the assistant entry point on the manual bookkeeping
|
||||
@@ -122,6 +122,217 @@ describe('verifikation.draft prompt template', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// The shared mock Supabase harnesses proxy every chained call and never look at
|
||||
// the argument, so a select() naming a column that does not exist looks
|
||||
// identical to a correct one. These tests therefore record the select strings
|
||||
// and assert against the real schema:
|
||||
// journal_entry_lines: line_description (NOT description)
|
||||
// fiscal_periods: is_closed + locked_at (NOT status / locked_through)
|
||||
type StubResult = { data?: unknown; error?: unknown; throws?: Error }
|
||||
|
||||
function createRecordingSupabase(byTable: Record<string, StubResult[]>) {
|
||||
const selects: { table: string; columns: string }[] = []
|
||||
|
||||
const chainFor = (table: string, result: StubResult): unknown => {
|
||||
const proxy: unknown = new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void, reject: (e: unknown) => void) => {
|
||||
if (result.throws) {
|
||||
reject(result.throws)
|
||||
return
|
||||
}
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||
}
|
||||
}
|
||||
return (...args: unknown[]) => {
|
||||
if (prop === 'select') selects.push({ table, columns: String(args[0] ?? '') })
|
||||
return proxy
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
return proxy
|
||||
}
|
||||
|
||||
const supabase = {
|
||||
from: (table: string) => chainFor(table, byTable[table]?.shift() ?? {}),
|
||||
}
|
||||
|
||||
return { supabase: supabase as never, selects }
|
||||
}
|
||||
|
||||
const DRAFT_ENTRY = { id: 'e1', entry_date: '2026-05-01', description: 'Inköp', status: 'draft' }
|
||||
|
||||
function stubs(overrides: Partial<Record<string, StubResult[]>> = {}): Record<string, StubResult[]> {
|
||||
return {
|
||||
journal_entries: [{ data: DRAFT_ENTRY }],
|
||||
journal_entry_lines: [
|
||||
{
|
||||
data: [
|
||||
{
|
||||
account_number: '5410',
|
||||
debit_amount: 500,
|
||||
credit_amount: null,
|
||||
line_description: 'Förbrukningsinventarier',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
company_settings: [{ data: null }],
|
||||
fiscal_periods: [{ data: { id: 'p1', is_closed: false, locked_at: null } }],
|
||||
document_attachments: [{ data: [] }],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
async function captureWith(byTable: Record<string, StubResult[]>) {
|
||||
const { supabase, selects } = createRecordingSupabase(byTable)
|
||||
const captured = await verifikationDraft.capture(
|
||||
{ journal_entry_id: 'e1' },
|
||||
{ supabase, userId: 'u1', companyId: 'c1' },
|
||||
)
|
||||
const prompt = verifikationDraft.promptTemplate({ captured, profileSummary: null, activeMemory: [] })
|
||||
return { captured, prompt, selects }
|
||||
}
|
||||
|
||||
describe('verifikation.draft capture selects columns that exist', () => {
|
||||
it('reads journal_entry_lines.line_description, not a non-existent description column', async () => {
|
||||
const { captured, selects } = await captureWith(stubs())
|
||||
|
||||
const lineSelect = selects.find((s) => s.table === 'journal_entry_lines')
|
||||
expect(lineSelect).toBeDefined()
|
||||
expect(lineSelect!.columns).toContain('line_description')
|
||||
// A bare `description` would make PostgREST reject the whole select, which
|
||||
// is what made the agent see a verifikation with zero rader.
|
||||
expect(lineSelect!.columns).not.toMatch(/(^|[\s,])description/)
|
||||
|
||||
// ...and the per-line text still reaches the prompt shape.
|
||||
expect(captured.current_lines).toEqual([
|
||||
{
|
||||
account_number: '5410',
|
||||
debit_amount: 500,
|
||||
credit_amount: null,
|
||||
description: 'Förbrukningsinventarier',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves the lock state from the real two-layer source, not fiscal_periods.status/locked_through', async () => {
|
||||
const { selects } = await captureWith(stubs())
|
||||
|
||||
// Layer 1: company-wide lock date.
|
||||
const settingsSelect = selects.find((s) => s.table === 'company_settings')
|
||||
expect(settingsSelect?.columns).toContain('bookkeeping_locked_through')
|
||||
|
||||
// Layer 2: the covering fiscal period.
|
||||
const periodSelect = selects.find((s) => s.table === 'fiscal_periods')
|
||||
expect(periodSelect).toBeDefined()
|
||||
expect(periodSelect!.columns).toContain('is_closed')
|
||||
expect(periodSelect!.columns).toContain('locked_at')
|
||||
expect(periodSelect!.columns).not.toContain('locked_through')
|
||||
expect(periodSelect!.columns).not.toContain('status')
|
||||
})
|
||||
})
|
||||
|
||||
describe('verifikation.draft period lock gate', () => {
|
||||
it('stays silent about locks for an open period', async () => {
|
||||
const { captured, prompt } = await captureWith(stubs())
|
||||
|
||||
expect(captured.period_status).toEqual({ period_id: 'p1', status: 'open', lock_date: null })
|
||||
expect(prompt).not.toContain('PERIODEN ÄR LÅST')
|
||||
expect(prompt).not.toContain('PERIODEN ÄR STÄNGD')
|
||||
expect(prompt).not.toContain('PERIODLÅSET KUNDE INTE LÄSAS')
|
||||
})
|
||||
|
||||
it('refuses a locked period (fiscal_periods.locked_at)', async () => {
|
||||
const { captured, prompt } = await captureWith(
|
||||
stubs({ fiscal_periods: [{ data: { id: 'p1', is_closed: false, locked_at: '2026-06-01T09:00:00Z' } }] }),
|
||||
)
|
||||
|
||||
expect(captured.period_status?.status).toBe('locked')
|
||||
expect(prompt).toContain('PERIODEN ÄR LÅST')
|
||||
})
|
||||
|
||||
it('refuses a date behind the company-wide lock date', async () => {
|
||||
const { captured, prompt } = await captureWith(
|
||||
stubs({ company_settings: [{ data: { bookkeeping_locked_through: '2026-06-30' } }] }),
|
||||
)
|
||||
|
||||
expect(captured.period_status?.status).toBe('locked')
|
||||
expect(captured.period_status?.lock_date).toBe('2026-06-30')
|
||||
expect(prompt).toContain('PERIODEN ÄR LÅST')
|
||||
})
|
||||
|
||||
it('refuses a closed period and does not offer to unlock it', async () => {
|
||||
const { captured, prompt } = await captureWith(
|
||||
stubs({ fiscal_periods: [{ data: { id: 'p1', is_closed: true, locked_at: '2026-06-01T09:00:00Z' } }] }),
|
||||
)
|
||||
|
||||
expect(captured.period_status?.status).toBe('closed')
|
||||
expect(prompt).toContain('PERIODEN ÄR STÄNGD')
|
||||
// A closed period cannot be unlocked (period-service rejects it), so the
|
||||
// agent must not send the user to Räkenskapsår to try.
|
||||
expect(prompt).not.toContain('låsa upp perioden')
|
||||
})
|
||||
|
||||
it('fails closed when the lock lookup errors', async () => {
|
||||
const { captured, prompt } = await captureWith(
|
||||
stubs({ company_settings: [{ throws: new Error('PostgREST 500') }] }),
|
||||
)
|
||||
|
||||
// Never 'open': an unreadable lock state must not read as postable.
|
||||
expect(captured.period_status?.status).toBe('unknown')
|
||||
expect(prompt).toContain('PERIODLÅSET KUNDE INTE LÄSAS')
|
||||
expect(prompt).toContain('utgå INTE från att perioden är öppen')
|
||||
})
|
||||
|
||||
it('renders a SOFT lookup failure as unknown, never as a real lock', async () => {
|
||||
// resolvePeriodStatusForDate does not throw on a PostgREST error result:
|
||||
// it returns { status: 'locked', lookup_failed: true } (fail-closed for
|
||||
// write gates). This surface must branch on lookup_failed: a transient DB
|
||||
// blip must not tell the user "PERIODEN ÄR LÅST ... låsa upp perioden"
|
||||
// about a lock that may not exist.
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const { captured, prompt } = await captureWith(
|
||||
stubs({ company_settings: [{ data: null, error: { message: 'connection reset' } }] }),
|
||||
)
|
||||
|
||||
expect(captured.period_status?.status).toBe('unknown')
|
||||
expect(prompt).toContain('PERIODLÅSET KUNDE INTE LÄSAS')
|
||||
expect(prompt).not.toContain('PERIODEN ÄR LÅST')
|
||||
expect(prompt).not.toContain('låsa upp perioden')
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('points a posted entry in a locked period at storno, never at an inline rewrite', async () => {
|
||||
// BFL 5 kap 5 §: inline rättelse is only legal while the period is open and
|
||||
// unlocked. Past a lock/close, storno is the only sanctioned track.
|
||||
const { prompt } = await captureWith(
|
||||
stubs({
|
||||
journal_entries: [{ data: { ...DRAFT_ENTRY, status: 'posted' } }],
|
||||
fiscal_periods: [{ data: { id: 'p1', is_closed: false, locked_at: '2026-06-01T09:00:00Z' } }],
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prompt).toContain('storno')
|
||||
expect(prompt).toContain('BFL 5 kap 5 §')
|
||||
})
|
||||
|
||||
it('does not push storno at a posted entry while the period is open', async () => {
|
||||
const { prompt } = await captureWith(
|
||||
stubs({ journal_entries: [{ data: { ...DRAFT_ENTRY, status: 'posted' } }] }),
|
||||
)
|
||||
|
||||
expect(prompt).not.toContain('BFL 5 kap 5 §')
|
||||
})
|
||||
})
|
||||
|
||||
describe('verifikation.draft capture', () => {
|
||||
it('returns an empty draft (with an underlag array) when no entry id is given', async () => {
|
||||
// The fresh-start path (Bokföring → "Skapa med assistent") passes no
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineAgentIntent } from './types'
|
||||
import { OPUS_MODEL } from '@/lib/agent/composer/client'
|
||||
import { renderAgentGroundRules } from './shared-rules'
|
||||
import type { PeriodStatusValue } from '@/lib/core/bookkeeping/period-service'
|
||||
|
||||
// bokslut.step: "Fråga [namn]" inside the year-end (bokslut) wizard.
|
||||
//
|
||||
@@ -28,11 +29,24 @@ interface CapturedBokslutStep {
|
||||
id: string | null
|
||||
period_start: string | null
|
||||
period_end: string | null
|
||||
status: string | null
|
||||
// Canonical three-value period state, derived from is_closed + locked_at
|
||||
// the same way lib/core/bookkeeping/period-service.ts derives it.
|
||||
status: PeriodStatusValue
|
||||
lock_date: string | null
|
||||
} | null
|
||||
// True when the fiscal_periods lookup itself failed. Distinct from
|
||||
// fiscal_period === null (no period row), which is the "no räkenskapsår
|
||||
// exists yet" case. Both mean the year state is UNKNOWN, never "open".
|
||||
period_lookup_failed: boolean
|
||||
entity_type: string | null
|
||||
}
|
||||
|
||||
const PERIOD_STATUS_SV: Record<PeriodStatusValue, string> = {
|
||||
open: 'öppen',
|
||||
locked: 'låst',
|
||||
closed: 'stängd',
|
||||
}
|
||||
|
||||
export const bokslutStep = defineAgentIntent<BokslutStepArgs, CapturedBokslutStep>({
|
||||
id: 'bokslut.step',
|
||||
buttonLabel: 'Fråga om detta steg',
|
||||
@@ -53,6 +67,7 @@ export const bokslutStep = defineAgentIntent<BokslutStepArgs, CapturedBokslutSte
|
||||
|
||||
tools: [
|
||||
'gnubok_year_end_readiness',
|
||||
'gnubok_list_fiscal_periods',
|
||||
'gnubok_propose_accruals',
|
||||
'gnubok_propose_annual_depreciation',
|
||||
'gnubok_propose_dispositioner',
|
||||
@@ -70,15 +85,21 @@ export const bokslutStep = defineAgentIntent<BokslutStepArgs, CapturedBokslutSte
|
||||
model: OPUS_MODEL,
|
||||
|
||||
capture: async ({ step_id, fiscal_year_end }, { supabase, companyId }) => {
|
||||
// Find the latest non-locked fiscal period (the one being closed): or
|
||||
// the one matching fiscal_year_end if supplied.
|
||||
// Find the latest fiscal period (the one being closed): or the one
|
||||
// matching fiscal_year_end if supplied.
|
||||
//
|
||||
// fiscal_periods has NO `status` column. Period state lives in
|
||||
// `is_closed` + `locked_at`, which is what period-service.ts
|
||||
// (resolvePeriodStatusForDate) and the DB period-lock triggers read.
|
||||
// Selecting a non-existent column makes PostgREST reject the whole
|
||||
// query, so the period would never resolve at all.
|
||||
let query = supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, period_start, period_end, status')
|
||||
.select('id, period_start, period_end, is_closed, locked_at')
|
||||
.eq('company_id', companyId)
|
||||
if (fiscal_year_end) query = query.eq('period_end', fiscal_year_end)
|
||||
query = query.order('period_end', { ascending: false }).limit(1)
|
||||
const { data: period } = await query.maybeSingle()
|
||||
const { data: period, error: periodError } = await query.maybeSingle()
|
||||
|
||||
const { data: company } = await supabase
|
||||
.from('companies')
|
||||
@@ -86,14 +107,28 @@ export const bokslutStep = defineAgentIntent<BokslutStepArgs, CapturedBokslutSte
|
||||
.eq('id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
const row = periodError
|
||||
? null
|
||||
: (period as {
|
||||
id: string
|
||||
period_start?: string | null
|
||||
period_end?: string | null
|
||||
is_closed?: boolean | null
|
||||
locked_at?: string | null
|
||||
} | null)
|
||||
|
||||
return {
|
||||
step_id: step_id ?? null,
|
||||
fiscal_period: period
|
||||
period_lookup_failed: !!periodError,
|
||||
fiscal_period: row
|
||||
? {
|
||||
id: (period as { id: string }).id,
|
||||
period_start: ((period as { period_start?: string | null }).period_start) ?? null,
|
||||
period_end: ((period as { period_end?: string | null }).period_end) ?? null,
|
||||
status: ((period as { status?: string | null }).status) ?? null,
|
||||
id: row.id,
|
||||
period_start: row.period_start ?? null,
|
||||
period_end: row.period_end ?? null,
|
||||
// Same precedence as resolvePeriodStatusForDate: closed wins
|
||||
// over locked, locked wins over open.
|
||||
status: row.is_closed ? 'closed' : row.locked_at ? 'locked' : 'open',
|
||||
lock_date: row.locked_at ?? null,
|
||||
}
|
||||
: null,
|
||||
entity_type: ((company as { entity_type?: string | null } | null)?.entity_type) ?? null,
|
||||
@@ -107,8 +142,29 @@ export const bokslutStep = defineAgentIntent<BokslutStepArgs, CapturedBokslutSte
|
||||
lines.push('Användaren är i bokslutsguiden och behöver hjälp.')
|
||||
if (captured.step_id) lines.push(`Aktivt steg: ${captured.step_id}`)
|
||||
if (captured.fiscal_period) {
|
||||
const period = captured.fiscal_period
|
||||
lines.push(
|
||||
`Räkenskapsår: ${captured.fiscal_period.period_start ?? '?'} → ${captured.fiscal_period.period_end ?? '?'} (status: ${captured.fiscal_period.status ?? '?'})`,
|
||||
`Räkenskapsår: ${period.period_start ?? '?'} → ${period.period_end ?? '?'} (status: ${PERIOD_STATUS_SV[period.status]})`,
|
||||
)
|
||||
if (period.status === 'closed') {
|
||||
lines.push(
|
||||
'Perioden är STÄNGD. Databasens periodlås avvisar nya bokföringsposter i perioden. Föreslå inga bokningar i räkenskapsåret: hänvisa till rättelse enligt BFL 5 kap 5 § (storno) om något behöver korrigeras.',
|
||||
)
|
||||
} else if (period.status === 'locked') {
|
||||
lines.push(
|
||||
`Perioden är LÅST${period.lock_date ? ` (låst ${period.lock_date})` : ''}. Databasens periodlås avvisar nya bokföringsposter tills en behörig användare låser upp perioden. Föreslå inga bokningar innan dess: säg att perioden måste låsas upp först.`,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Fail closed: an errored lookup or a missing period row is NOT an open
|
||||
// year. Never let the agent reason as if bokslutsposter can be booked.
|
||||
lines.push(
|
||||
captured.period_lookup_failed
|
||||
? 'VARNING: uppslaget av räkenskapsåret misslyckades (databasfel). Räkenskapsårets status är OKÄND.'
|
||||
: 'VARNING: inget räkenskapsår hittades för företaget. Räkenskapsårets status är OKÄND.',
|
||||
)
|
||||
lines.push(
|
||||
'Anta INTE att året är öppet. Kör gnubok_year_end_readiness och gnubok_list_fiscal_periods, och bekräfta räkenskapsåret med användaren INNAN du föreslår eller stagear någon bokslutspost.',
|
||||
)
|
||||
}
|
||||
if (captured.entity_type) lines.push(`Företagsform: ${captured.entity_type}`)
|
||||
|
||||
@@ -28,6 +28,12 @@ interface CapturedInboxItem {
|
||||
vat_amount: number | null
|
||||
currency: string | null
|
||||
tx_date: string | null
|
||||
// The bank transaction's own magnitude travels WITH its own currency, and the
|
||||
// SEK equivalent is a separate field that is null when the row is foreign and
|
||||
// no amount_sek/exchange_rate is stored. Never collapse the two: a foreign
|
||||
// amount labelled "SEK" reads to the agent as a SEK amount and it books on it.
|
||||
tx_amount: number | null
|
||||
tx_currency: string | null
|
||||
tx_amount_sek: number | null
|
||||
tx_description: string | null
|
||||
}
|
||||
@@ -37,8 +43,11 @@ interface CapturedInboxBulk {
|
||||
bookable_count: number
|
||||
}
|
||||
|
||||
// SEK magnitude of a (usually-SEK) bank transaction. Foreign rows are
|
||||
// normalised via their stored amount_sek/exchange_rate.
|
||||
// SEK magnitude of a bank transaction, or null when there genuinely is none.
|
||||
// Foreign rows are normalised via their stored amount_sek/exchange_rate; a
|
||||
// foreign row that carries NEITHER has no known SEK value, so we return null
|
||||
// instead of falling back to rate 1 (that returned e.g. 500 for a 500 EUR row,
|
||||
// which the sheet then printed as "500 SEK").
|
||||
function txSek(tx: {
|
||||
amount: number | null
|
||||
currency: string | null
|
||||
@@ -48,8 +57,34 @@ function txSek(tx: {
|
||||
if (tx.amount == null) return null
|
||||
const cur = String(tx.currency ?? 'SEK').toUpperCase()
|
||||
if (cur === 'SEK') return Math.abs(Number(tx.amount))
|
||||
const sek = tx.amount_sek ?? Number(tx.amount) * Number(tx.exchange_rate ?? 1)
|
||||
return Number.isFinite(sek) ? Math.abs(Number(sek)) : null
|
||||
if (tx.amount_sek != null) {
|
||||
const stored = Number(tx.amount_sek)
|
||||
return Number.isFinite(stored) ? Math.abs(stored) : null
|
||||
}
|
||||
const rate = tx.exchange_rate == null ? null : Number(tx.exchange_rate)
|
||||
if (rate == null || !Number.isFinite(rate) || rate <= 0) return null
|
||||
const sek = Number(tx.amount) * rate
|
||||
return Number.isFinite(sek) ? Math.abs(sek) : null
|
||||
}
|
||||
|
||||
// Amount of the bank transaction in ITS OWN currency (absolute value, matching
|
||||
// how txSek reports the SEK leg).
|
||||
function txOwnAmount(tx: { amount: number | null }): number | null {
|
||||
if (tx.amount == null) return null
|
||||
const n = Number(tx.amount)
|
||||
return Number.isFinite(n) ? Math.abs(n) : null
|
||||
}
|
||||
|
||||
// Renders the bank leg so the magnitude always carries its real unit: SEK rows
|
||||
// print as before, foreign rows print their own amount plus the SEK equivalent
|
||||
// when one exists, and say so explicitly when it does not.
|
||||
function formatBankAmount(it: CapturedInboxItem): string | null {
|
||||
if (it.tx_amount == null) return null
|
||||
const cur = it.tx_currency ?? 'SEK'
|
||||
const own = `${it.tx_amount.toLocaleString('sv-SE')} ${cur}`
|
||||
if (cur === 'SEK') return own
|
||||
if (it.tx_amount_sek != null) return `${own} (${it.tx_amount_sek.toLocaleString('sv-SE')} SEK)`
|
||||
return `${own} (SEK-belopp saknas: ingen växelkurs lagrad på transaktionen)`
|
||||
}
|
||||
|
||||
export const inboxBulkBook = defineAgentIntent<InboxBulkBookArgs, CapturedInboxBulk>({
|
||||
@@ -137,6 +172,8 @@ export const inboxBulkBook = defineAgentIntent<InboxBulkBookArgs, CapturedInboxB
|
||||
vat_amount: ex.totals?.vatAmount ?? null,
|
||||
currency: ex.invoice?.currency ?? null,
|
||||
tx_date: tx?.date ?? null,
|
||||
tx_amount: tx ? txOwnAmount(tx) : null,
|
||||
tx_currency: tx ? String(tx.currency ?? 'SEK').toUpperCase() : null,
|
||||
tx_amount_sek: tx ? txSek(tx) : null,
|
||||
tx_description: tx?.description ?? null,
|
||||
}
|
||||
@@ -170,7 +207,8 @@ export const inboxBulkBook = defineAgentIntent<InboxBulkBookArgs, CapturedInboxB
|
||||
if (it.merchant_name) parts.push(`leverantör=${it.merchant_name}`)
|
||||
if (it.total != null) parts.push(`belopp=${it.total.toLocaleString('sv-SE')} ${it.currency ?? 'SEK'}`)
|
||||
if (it.vat_amount != null) parts.push(`moms=${it.vat_amount.toLocaleString('sv-SE')} ${it.currency ?? 'SEK'}`)
|
||||
if (it.tx_amount_sek != null) parts.push(`bank=${it.tx_amount_sek.toLocaleString('sv-SE')} SEK`)
|
||||
const bank = formatBankAmount(it)
|
||||
if (bank) parts.push(`bank=${bank}`)
|
||||
if (it.tx_date) parts.push(`datum=${it.tx_date}`)
|
||||
lines.push(` • ${parts.join(', ')}`)
|
||||
}
|
||||
@@ -184,7 +222,10 @@ export const inboxBulkBook = defineAgentIntent<InboxBulkBookArgs, CapturedInboxB
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('Arbetssätt:')
|
||||
lines.push('- Boka via banktransaktionen (Modell B): verktyget bokför varje underlag mot dess matchade banktransaktion, som redan bär SEK-beloppet. Du behöver inte räkna om valuta.')
|
||||
lines.push('- Boka via banktransaktionen (Modell B): verktyget bokför varje underlag mot dess matchade banktransaktion. Bankraden ovan visar sitt eget belopp med sin egen valuta, och SEK-beloppet inom parentes när ett sådant finns lagrat. Står raden i SEK, eller har ett SEK-belopp inom parentes, behöver du inte räkna om valuta.')
|
||||
if (bookable.some((i) => i.tx_amount != null && (i.tx_currency ?? 'SEK') !== 'SEK' && i.tx_amount_sek == null)) {
|
||||
lines.push('- VÄXELKURS SAKNAS på minst en bankrad ovan (markerad "SEK-belopp saknas"). Det beloppet är i utländsk valuta, INTE i SEK: behandla det aldrig som ett SEK-belopp. Bulkbokför inte den raden på egen hand: säg till användaren att transaktionens växelkurs/SEK-belopp behöver fyllas i först, och bokför de övriga raderna som vanligt.')
|
||||
}
|
||||
lines.push('- GRUPPERA de bokförbara underlagen efter leverantör/typ. Samma slags kostnad → samma kategori + momsbehandling. För varje homogen grupp anropar du gnubok_bulk_book_inbox_items med gruppens item_ids, en kategori (enum) och vat_treatment.')
|
||||
lines.push('- MOMS: en utländsk tjänst (t.ex. USD/EUR-prenumeration som Cursor/Anysphere där säljaren INTE debiterat svensk moms) är omvänd skattskyldighet → vat_treatment="reverse_charge". En svensk faktura med debiterad moms → standard_25 (eller den sats kvittot visar). Gissa aldrig: utgå från valuta + om underlaget visar moms.')
|
||||
lines.push('- KOLLA HUR MOTPARTEN BOKFÖRTS FÖRUT med gnubok_query_journal({ text: "<leverantör>", limit: 5 }) innan du väljer kategori. Följ ett tydligt tidigare mönster om inte underlaget motsäger det.')
|
||||
|
||||
@@ -39,6 +39,13 @@ interface CapturedSupplierInvoiceReview {
|
||||
subtotal: number | null
|
||||
vat_amount: number | null
|
||||
total: number | null
|
||||
// The invoice's magnitudes travel WITH their own currency, and the SEK
|
||||
// legs are separate fields that stay null when no rate was ever resolved.
|
||||
// Never collapse the two: a EUR amount printed without a unit reads to the
|
||||
// agent as kronor, and it attests the booking on that number.
|
||||
vat_amount_sek: number | null
|
||||
total_sek: number | null
|
||||
exchange_rate: number | null
|
||||
vat_treatment: string | null
|
||||
reverse_charge: boolean | null
|
||||
payment_reference: string | null
|
||||
@@ -65,6 +72,10 @@ interface CapturedSupplierInvoiceReview {
|
||||
invoice_date: string | null
|
||||
total: number | null
|
||||
currency: string | null
|
||||
// Anomaly detection compares these against each other. Without a common
|
||||
// unit that comparison is meaningless, so the SEK leg travels along.
|
||||
total_sek: number | null
|
||||
exchange_rate: number | null
|
||||
status: string | null
|
||||
}[]
|
||||
// Linked inbox / document extraction so the agent doesn't re-ask for what
|
||||
@@ -73,6 +84,58 @@ interface CapturedSupplierInvoiceReview {
|
||||
document_extraction: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
// ISO code as stored, uppercased, or null when nothing usable is there. A blank
|
||||
// or absent code is NOT silently promoted to SEK: an amount whose unit we do
|
||||
// not know must be rendered as unknown, never as kronor.
|
||||
function normalizeCurrency(value: string | null | undefined): string | null {
|
||||
if (typeof value !== 'string') return null
|
||||
const code = value.trim().toUpperCase()
|
||||
return code.length === 0 ? null : code
|
||||
}
|
||||
|
||||
// "1 200 EUR", or "1 200 (valuta okänd)" when no currency code is attached.
|
||||
function formatMoney(amount: number | null | undefined, currency: string | null | undefined): string {
|
||||
if (amount == null || !Number.isFinite(Number(amount))) return '?'
|
||||
const code = normalizeCurrency(currency)
|
||||
const value = Number(amount).toLocaleString('sv-SE')
|
||||
return code ? `${value} ${code}` : `${value} (valuta okänd)`
|
||||
}
|
||||
|
||||
// SEK magnitude of an amount, or null when there genuinely is none. Mirrors
|
||||
// resolveSekAmount()'s priority (stored *_sek column, then exchange_rate) but
|
||||
// deliberately drops its legacy "assume SEK" fallback: for a reader the honest
|
||||
// answer is "no known SEK value", not the face value relabelled as kronor.
|
||||
function sekEquivalent(
|
||||
amount: number | null | undefined,
|
||||
amountSek: number | null | undefined,
|
||||
currency: string | null | undefined,
|
||||
exchangeRate: number | null | undefined,
|
||||
): number | null {
|
||||
if (amount == null || !Number.isFinite(Number(amount))) return null
|
||||
if (normalizeCurrency(currency) === 'SEK') return Number(amount)
|
||||
if (amountSek != null && Number.isFinite(Number(amountSek))) return Number(amountSek)
|
||||
const rate = exchangeRate == null ? null : Number(exchangeRate)
|
||||
if (rate != null && Number.isFinite(rate) && rate > 0) {
|
||||
return Math.round(Number(amount) * rate * 100) / 100
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// "1 200 EUR (13 800 SEK)" when a rate exists, plain "1 200 SEK" for a domestic
|
||||
// amount, and the bare foreign amount when no SEK value is known.
|
||||
function formatMoneyWithSek(
|
||||
amount: number | null | undefined,
|
||||
amountSek: number | null | undefined,
|
||||
currency: string | null | undefined,
|
||||
exchangeRate: number | null | undefined,
|
||||
): string {
|
||||
const own = formatMoney(amount, currency)
|
||||
if (amount == null) return own
|
||||
if (normalizeCurrency(currency) === 'SEK') return own
|
||||
const sek = sekEquivalent(amount, amountSek, currency, exchangeRate)
|
||||
return sek == null ? own : `${own} (${sek.toLocaleString('sv-SE')} SEK)`
|
||||
}
|
||||
|
||||
export const supplierInvoiceReview = defineAgentIntent<
|
||||
SupplierInvoiceReviewArgs,
|
||||
CapturedSupplierInvoiceReview
|
||||
@@ -114,7 +177,7 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
const { data: invoice } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select(
|
||||
'id, supplier_id, arrival_number, supplier_invoice_number, invoice_date, due_date, status, currency, subtotal, vat_amount, total, vat_treatment, reverse_charge, payment_reference, is_credit_note, document_id',
|
||||
'id, supplier_id, arrival_number, supplier_invoice_number, invoice_date, due_date, status, currency, exchange_rate, subtotal, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, reverse_charge, payment_reference, is_credit_note, document_id',
|
||||
)
|
||||
.eq('id', supplier_invoice_id)
|
||||
.eq('company_id', companyId)
|
||||
@@ -156,7 +219,7 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
supplierId
|
||||
? supabase
|
||||
.from('supplier_invoices')
|
||||
.select('supplier_invoice_number, invoice_date, total, currency, status')
|
||||
.select('supplier_invoice_number, invoice_date, total, total_sek, currency, exchange_rate, status')
|
||||
.eq('supplier_id', supplierId)
|
||||
.eq('company_id', companyId)
|
||||
.neq('id', supplier_invoice_id)
|
||||
@@ -194,6 +257,9 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
subtotal: ((invoice as { subtotal?: number | null }).subtotal) ?? null,
|
||||
vat_amount: ((invoice as { vat_amount?: number | null }).vat_amount) ?? null,
|
||||
total: ((invoice as { total?: number | null }).total) ?? null,
|
||||
vat_amount_sek: ((invoice as { vat_amount_sek?: number | null }).vat_amount_sek) ?? null,
|
||||
total_sek: ((invoice as { total_sek?: number | null }).total_sek) ?? null,
|
||||
exchange_rate: ((invoice as { exchange_rate?: number | null }).exchange_rate) ?? null,
|
||||
vat_treatment: ((invoice as { vat_treatment?: string | null }).vat_treatment) ?? null,
|
||||
reverse_charge: ((invoice as { reverse_charge?: boolean | null }).reverse_charge) ?? null,
|
||||
payment_reference:
|
||||
@@ -229,13 +295,17 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
supplier_invoice_number: string | null
|
||||
invoice_date: string | null
|
||||
total: number | null
|
||||
total_sek: number | null
|
||||
currency: string | null
|
||||
exchange_rate: number | null
|
||||
status: string | null
|
||||
}[]).map((r) => ({
|
||||
invoice_number: r.supplier_invoice_number,
|
||||
invoice_date: r.invoice_date,
|
||||
total: r.total,
|
||||
total_sek: r.total_sek ?? null,
|
||||
currency: r.currency,
|
||||
exchange_rate: r.exchange_rate ?? null,
|
||||
status: r.status,
|
||||
})),
|
||||
inbox_extraction: (inboxRow as { extracted_data?: Record<string, unknown> | null } | null)?.extracted_data ?? null,
|
||||
@@ -269,9 +339,27 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
lines.push(`- ${supplierLine.join(' ')}`)
|
||||
}
|
||||
lines.push(`- Status: ${inv.status ?? '?'} | Datum: ${inv.invoice_date ?? '?'} | Förfaller: ${inv.due_date ?? '?'}`)
|
||||
const invCurrency = normalizeCurrency(inv.currency)
|
||||
lines.push(
|
||||
`- Belopp: ${inv.total != null ? `${inv.total.toLocaleString('sv-SE')} ${inv.currency ?? 'SEK'}` : '?'} (moms ${inv.vat_amount != null ? `${inv.vat_amount.toLocaleString('sv-SE')} ${inv.currency ?? 'SEK'}` : '?'})`,
|
||||
`- Belopp: ${formatMoney(inv.total, inv.currency)} (moms ${formatMoney(inv.vat_amount, inv.currency)})`,
|
||||
)
|
||||
// A foreign invoice is booked in SEK, so the SEK leg is the number that
|
||||
// actually lands in the verifikat. Print it next to the face value when it
|
||||
// exists, and say plainly that it is missing when it does not: the one
|
||||
// thing this block must never do is let a EUR figure pass for kronor.
|
||||
if (invCurrency !== 'SEK' && inv.total != null) {
|
||||
const totalSek = sekEquivalent(inv.total, inv.total_sek, inv.currency, inv.exchange_rate)
|
||||
const vatSek = sekEquivalent(inv.vat_amount, inv.vat_amount_sek, inv.currency, inv.exchange_rate)
|
||||
if (totalSek != null) {
|
||||
lines.push(
|
||||
`- I SEK (bokföringen sker i SEK): ${totalSek.toLocaleString('sv-SE')} SEK (moms ${vatSek != null ? `${vatSek.toLocaleString('sv-SE')} SEK` : '?'})${inv.exchange_rate != null ? `, växelkurs ${inv.exchange_rate}` : ''}`,
|
||||
)
|
||||
} else {
|
||||
lines.push(
|
||||
`- SEK-BELOPP SAKNAS: ingen växelkurs är lagrad på fakturan. ${formatMoney(inv.total, inv.currency)} är INTE ${inv.total.toLocaleString('sv-SE')} SEK. Attestera inte på det nominella beloppet: växelkursen måste fyllas i först.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
lines.push(
|
||||
`- Momskod: ${inv.vat_treatment ?? '?'}${inv.reverse_charge ? ' (omvänd skattskyldighet flaggad)' : ''}`,
|
||||
)
|
||||
@@ -282,10 +370,12 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
if (captured.items.length > 0) {
|
||||
lines.push('Rader:')
|
||||
for (const it of captured.items.slice(0, 20)) {
|
||||
const total = it.line_total != null ? `${it.line_total.toLocaleString('sv-SE')}` : '?'
|
||||
// Line amounts are stored in the invoice's currency, so they carry the
|
||||
// invoice's currency code: never a bare number that reads as kronor.
|
||||
const total = formatMoney(it.line_total, inv.currency)
|
||||
const vat = it.vat_rate != null ? `${it.vat_rate}%` : '?'
|
||||
const acc = it.account_number ? ` → ${it.account_number}` : ' → (ingen kontering)'
|
||||
lines.push(` • ${it.description ?? '(beskrivning saknas)'}: ${total} ${inv.currency ?? 'SEK'} (${vat})${acc}`)
|
||||
lines.push(` • ${it.description ?? '(beskrivning saknas)'}: ${total} (${vat})${acc}`)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
@@ -293,7 +383,7 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
if (captured.recent_invoices_from_supplier.length > 0) {
|
||||
lines.push('Tidigare fakturor från samma leverantör (för anomalikontroll):')
|
||||
for (const r of captured.recent_invoices_from_supplier) {
|
||||
const amt = r.total != null ? `${r.total.toLocaleString('sv-SE')} ${r.currency ?? 'SEK'}` : '?'
|
||||
const amt = formatMoneyWithSek(r.total, r.total_sek, r.currency, r.exchange_rate)
|
||||
lines.push(` • ${r.invoice_number ?? '?'} (${r.invoice_date ?? '?'}, ${r.status ?? '?'}): ${amt}`)
|
||||
}
|
||||
lines.push('')
|
||||
@@ -301,19 +391,64 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
|
||||
const ex = captured.inbox_extraction ?? captured.document_extraction
|
||||
if (ex) {
|
||||
lines.push('KÄNDA FAKTA från AI-extraktion av underlaget: fråga INTE om dessa:')
|
||||
const supplier = (ex.supplier as { name?: string | null; orgNumber?: string | null; vatNumber?: string | null } | undefined) ?? null
|
||||
const exInvoice = (ex.invoice as { currency?: string | null } | undefined) ?? null
|
||||
const totals = (ex.totals as { total?: number | null; vatAmount?: number | null } | undefined) ?? null
|
||||
const breakdown = (ex.vatBreakdown as { rate: number; base: number; amount: number }[] | undefined) ?? []
|
||||
if (supplier?.name) lines.push(`- Leverantör (PDF): ${supplier.name}`)
|
||||
if (supplier?.orgNumber) lines.push(`- Org.nr (PDF): ${supplier.orgNumber}`)
|
||||
if (supplier?.vatNumber) lines.push(`- VAT-nr (PDF): ${supplier.vatNumber}`)
|
||||
if (totals?.total != null) lines.push(`- Total (PDF): ${totals.total.toLocaleString('sv-SE')}`)
|
||||
if (totals?.vatAmount != null) lines.push(`- Moms (PDF): ${totals.vatAmount.toLocaleString('sv-SE')}`)
|
||||
if (breakdown.length > 0) {
|
||||
lines.push(`- Momsuppdelning: ${breakdown.map((b) => `${b.rate}%: ${b.amount.toLocaleString('sv-SE')}`).join('; ')}`)
|
||||
const exCurrency = normalizeCurrency(exInvoice?.currency)
|
||||
const hasExtractedAmounts =
|
||||
totals?.total != null || totals?.vatAmount != null || breakdown.length > 0
|
||||
// An extracted amount is a KNOWN FACT only when we know its unit AND that
|
||||
// unit is the one the invoice is registered in. Anything else is half a
|
||||
// fact, and half a fact under a "fråga INTE om dessa" header reads as
|
||||
// confirmation of the registered amount: that is exactly how a 1 200 EUR
|
||||
// invoice gets attested as 1 200 SEK. Those values move to their own
|
||||
// block below, where the agent is told to settle them first.
|
||||
const amountsConfirmRegistered =
|
||||
hasExtractedAmounts && exCurrency != null && invCurrency != null && exCurrency === invCurrency
|
||||
|
||||
const renderAmountLines = (): string[] => {
|
||||
const out: string[] = []
|
||||
if (totals?.total != null) out.push(`- Total (PDF): ${formatMoney(totals.total, exCurrency)}`)
|
||||
if (totals?.vatAmount != null) out.push(`- Moms (PDF): ${formatMoney(totals.vatAmount, exCurrency)}`)
|
||||
if (breakdown.length > 0) {
|
||||
out.push(
|
||||
`- Momsuppdelning: ${breakdown.map((b) => `${b.rate}%: ${formatMoney(b.amount, exCurrency)}`).join('; ')}`,
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const known: string[] = []
|
||||
if (supplier?.name) known.push(`- Leverantör (PDF): ${supplier.name}`)
|
||||
if (supplier?.orgNumber) known.push(`- Org.nr (PDF): ${supplier.orgNumber}`)
|
||||
if (supplier?.vatNumber) known.push(`- VAT-nr (PDF): ${supplier.vatNumber}`)
|
||||
if (amountsConfirmRegistered) known.push(...renderAmountLines())
|
||||
if (known.length > 0) {
|
||||
lines.push('KÄNDA FAKTA från AI-extraktion av underlaget: fråga INTE om dessa:')
|
||||
lines.push(...known)
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
if (hasExtractedAmounts && !amountsConfirmRegistered) {
|
||||
lines.push(
|
||||
'EJ BEKRÄFTADE BELOPP från AI-extraktionen: dessa är INTE kända fakta och bekräftar INTE det registrerade beloppet ovan:',
|
||||
)
|
||||
lines.push(...renderAmountLines())
|
||||
if (exCurrency == null) {
|
||||
lines.push(
|
||||
`- Extraktionen anger ingen valuta. Fakturan är registrerad i ${invCurrency ?? 'okänd valuta'}: ett belopp utan valuta kan varken bekräfta eller motsäga det registrerade beloppet. Behandla det ALDRIG som kronor.`,
|
||||
)
|
||||
} else {
|
||||
lines.push(
|
||||
`- ⚠ VALUTAKONFLIKT: fakturan är registrerad i ${invCurrency ?? 'okänd valuta'} men underlaget anger ${exCurrency}. Attestera inte förrän det är utrett vilken valuta som gäller: ett av beloppen är fel registrerat.`,
|
||||
)
|
||||
}
|
||||
lines.push(
|
||||
`- Fastställ valuta och belopp INNAN du attesterar: läs underlaget med gnubok_get_document_content(document_id=${inv.document_id ?? '…'}), eller fråga användaren.`,
|
||||
)
|
||||
lines.push('')
|
||||
}
|
||||
lines.push('')
|
||||
} else if (inv.document_id) {
|
||||
lines.push('Underlag är bifogat men inte AI-extraherat. Använd gnubok_get_document_content för att läsa PDF/bilden om du behöver fler signaler.')
|
||||
lines.push('')
|
||||
@@ -328,10 +463,11 @@ export const supplierInvoiceReview = defineAgentIntent<
|
||||
lines.push(' - EU näringsidkare: omvänd skattskyldighet (2614/2645).')
|
||||
lines.push(' - Bygg i Sverige: omvänd skattskyldighet enligt ML 1 kap 2 § 1 st 4b.')
|
||||
lines.push(' - Tredje land: import-moms via Tullverket eller deklareras via momsdeklaration ruta 60-62.')
|
||||
lines.push('2. Avvikelse mot tidigare fakturor från samma leverantör? Beloppen i ungefär samma härad?')
|
||||
lines.push('3. Saknas obligatoriska fält (ML 17 kap 24§): fakturanummer, datum, org.nr, moms-belopp, VAT-id vid reverse charge?')
|
||||
lines.push('4. Föreslå rätt BAS-konto för varje rad (eller för hela fakturan om bara en summarad finns). Följ leverantörens historik: gnubok_query_journal({ text: "<leverantörens namn>", source_type: "supplier_invoice", limit: 5 }): när du väljer konto.')
|
||||
lines.push('5. Om du är säker, staga attestering via gnubok_approve_supplier_invoice. Annars: peka på vad som ska klargöras innan attestering.')
|
||||
lines.push('2. Valuta: bokföringen sker i SEK. Är fakturan i utländsk valuta är det SEK-beloppet ovan som bokförs, aldrig det nominella beloppet i främmande valuta. Saknas SEK-beloppet (ingen växelkurs lagrad): attestera inte, be användaren fylla i växelkursen först. Ett belopp utan angiven valuta är inte ett SEK-belopp: reda ut valutan innan du räknar på det.')
|
||||
lines.push('3. Avvikelse mot tidigare fakturor från samma leverantör? Beloppen i ungefär samma härad? Jämför i SEK när valutorna skiljer sig åt: en jämförelse mellan olika valutor säger ingenting.')
|
||||
lines.push('4. Saknas obligatoriska fält (ML 17 kap 24§): fakturanummer, datum, org.nr, moms-belopp, VAT-id vid reverse charge?')
|
||||
lines.push('5. Föreslå rätt BAS-konto för varje rad (eller för hela fakturan om bara en summarad finns). Följ leverantörens historik: gnubok_query_journal({ text: "<leverantörens namn>", source_type: "supplier_invoice", limit: 5 }): när du väljer konto.')
|
||||
lines.push('6. Om du är säker, staga attestering via gnubok_approve_supplier_invoice. Annars: peka på vad som ska klargöras innan attestering.')
|
||||
lines.push('')
|
||||
lines.push('Svara på svenska, var direkt och konkret. Ditt första svar är det första användaren ser.')
|
||||
return lines.join('\n')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineAgentIntent } from './types'
|
||||
import { SONNET_MODEL, THINKING_BUDGET_STANDARD } from '@/lib/agent/composer/client'
|
||||
import { renderAgentGroundRules } from './shared-rules'
|
||||
import { resolvePeriodStatusForDate } from '@/lib/core/bookkeeping/period-service'
|
||||
|
||||
// verifikation.draft: "Fråga om denna verifikation" on the journal entry
|
||||
// creation/draft surfaces (Bokföring → "Skapa med assistent", the Ny
|
||||
@@ -34,9 +35,14 @@ interface CapturedVerifikationDraft {
|
||||
credit_amount: number | null
|
||||
description: string | null
|
||||
}[]
|
||||
// Lock state for the entry's date, resolved through the canonical
|
||||
// resolvePeriodStatusForDate (company-wide bookkeeping_locked_through +
|
||||
// the covering fiscal_period's is_closed/locked_at): the same two layers the
|
||||
// DB triggers enforce. `'unknown'` means the lookup failed and the agent must
|
||||
// fail closed rather than treat the period as open.
|
||||
period_status: {
|
||||
period_id: string | null
|
||||
status: string | null
|
||||
status: 'open' | 'locked' | 'closed' | 'unknown' | null
|
||||
lock_date: string | null
|
||||
} | null
|
||||
description_hint: string | null
|
||||
@@ -118,27 +124,51 @@ export const verifikationDraft = defineAgentIntent<
|
||||
description: ((e as { description?: string | null }).description) ?? null,
|
||||
status: ((e as { status?: string | null }).status) ?? null,
|
||||
}
|
||||
// The per-line free text lives in `line_description`; there is no
|
||||
// `description` column on journal_entry_lines. Asking for one made
|
||||
// PostgREST reject the whole select, so every entry looked like it had
|
||||
// zero rader and the agent reasoned about the verifikation from nothing.
|
||||
const { data: rows } = await supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('account_number, debit_amount, credit_amount, description')
|
||||
.select('account_number, debit_amount, credit_amount, line_description')
|
||||
.eq('journal_entry_id', journal_entry_id)
|
||||
.order('id', { ascending: true })
|
||||
lines = (rows ?? []) as CapturedVerifikationDraft['current_lines']
|
||||
lines = ((rows ?? []) as {
|
||||
account_number: string | null
|
||||
debit_amount: number | null
|
||||
credit_amount: number | null
|
||||
line_description: string | null
|
||||
}[]).map((r) => ({
|
||||
account_number: r.account_number ?? null,
|
||||
debit_amount: r.debit_amount ?? null,
|
||||
credit_amount: r.credit_amount ?? null,
|
||||
description: r.line_description ?? null,
|
||||
}))
|
||||
const entryDate = entry?.entry_date ?? null
|
||||
if (entryDate) {
|
||||
const { data: period } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, status, locked_through')
|
||||
.eq('company_id', companyId)
|
||||
.lte('period_start', entryDate)
|
||||
.gte('period_end', entryDate)
|
||||
.maybeSingle()
|
||||
if (period) {
|
||||
periodStatus = {
|
||||
period_id: (period as { id: string }).id,
|
||||
status: ((period as { status?: string | null }).status) ?? null,
|
||||
lock_date: ((period as { locked_through?: string | null }).locked_through) ?? null,
|
||||
}
|
||||
// fiscal_periods has no `status`/`locked_through` columns: lock state
|
||||
// is company_settings.bookkeeping_locked_through plus the period's
|
||||
// is_closed/locked_at. Go through resolvePeriodStatusForDate so this
|
||||
// surface reads the exact same source of truth as the DB triggers,
|
||||
// the MCP server and the v1 REST period gate.
|
||||
try {
|
||||
const resolved = await resolvePeriodStatusForDate(supabase, companyId, entryDate)
|
||||
// A soft lookup failure surfaces as { status: 'locked',
|
||||
// lookup_failed: true }: the right fail-closed verdict for a write
|
||||
// gate, but the wrong words for a human. Rendering it as a real
|
||||
// lock produces "lås upp perioden under Räkenskapsår" advice for a
|
||||
// lock that may not exist, so map it to the 'unknown' wording
|
||||
// instead (bokslut-step handles its equivalent the same way).
|
||||
periodStatus = resolved.lookup_failed
|
||||
? { period_id: null, status: 'unknown', lock_date: null }
|
||||
: {
|
||||
period_id: resolved.period_id,
|
||||
status: resolved.status,
|
||||
lock_date: resolved.lock_date,
|
||||
}
|
||||
} catch {
|
||||
// Fail closed: an unreadable period must never be presented as open.
|
||||
periodStatus = { period_id: null, status: 'unknown', lock_date: null }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,14 +276,32 @@ export const verifikationDraft = defineAgentIntent<
|
||||
}
|
||||
|
||||
if (captured.period_status) {
|
||||
const periodState = captured.period_status.status
|
||||
lines.push('')
|
||||
lines.push(
|
||||
`Period: ${captured.period_status.period_id ?? '?'} (status ${captured.period_status.status ?? '?'}${
|
||||
captured.period_status.lock_date ? `, låst t.o.m. ${captured.period_status.lock_date}` : ''
|
||||
`Period: ${captured.period_status.period_id ?? '?'} (status ${periodState ?? '?'}${
|
||||
captured.period_status.lock_date ? `, lås: ${captured.period_status.lock_date}` : ''
|
||||
})`,
|
||||
)
|
||||
if (captured.period_status.status === 'locked' || captured.period_status.status === 'closed') {
|
||||
if (periodState === 'closed') {
|
||||
lines.push('PERIODEN ÄR STÄNGD: ingenting får bokföras på detta datum, och en stängd period kan inte låsas upp. Vägled användaren att flytta verifikationsdatumet till en öppen period.')
|
||||
} else if (periodState === 'locked') {
|
||||
lines.push('PERIODEN ÄR LÅST: ett utkast kan inte bokföras här. Vägled användaren att ändra verifikationsdatumet till en öppen period (utkast redigeras fritt), eller att låsa upp perioden under Bokföring → Räkenskapsår om datumet måste stå kvar.')
|
||||
} else if (periodState === 'unknown') {
|
||||
// Fail closed: the lock lookup failed, so we cannot claim the period is
|
||||
// open. Posting into a locked period is blocked by DB triggers anyway;
|
||||
// the agent must not promise the user that it will go through.
|
||||
lines.push('PERIODLÅSET KUNDE INTE LÄSAS: utgå INTE från att perioden är öppen. Be användaren kontrollera periodlåset under Bokföring → Räkenskapsår innan något bokförs på detta datum.')
|
||||
} else if (periodState === 'open' && captured.period_status.period_id === null) {
|
||||
lines.push('INGET RÄKENSKAPSÅR TÄCKER DATUMET: periodlåset gick inte att avgöra. Kontrollera att verifikationsdatumet ligger inom ett upplagt räkenskapsår innan du föreslår bokföring.')
|
||||
}
|
||||
if (
|
||||
captured.entry?.status === 'posted' &&
|
||||
(periodState === 'locked' || periodState === 'closed' || periodState === 'unknown')
|
||||
) {
|
||||
// BFL 5 kap 5 §: inline rättelse is only legal in an open, unlocked
|
||||
// period. Past a lock/close, storno is the only sanctioned path.
|
||||
lines.push('Verifikationen är dessutom redan BOKFÖRD och perioden är inte bevisligen öppen: enligt BFL 5 kap 5 § är storno (omföring i en öppen period) då enda tillåtna rättelsevägen. Föreslå aldrig att rader, belopp eller datum skrivs om i det bokförda verifikatet.')
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
|
||||
Reference in New Issue
Block a user