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
@@ -555,7 +555,18 @@ function ConnectStep({
|
||||
const h = 700
|
||||
const left = window.screenX + (window.outerWidth - w) / 2
|
||||
const top = window.screenY + (window.outerHeight - h) / 2
|
||||
window.open(authUrl, 'arcim-oauth', `width=${w},height=${h},left=${left},top=${top}`)
|
||||
const popup = window.open(authUrl, 'arcim-oauth', `width=${w},height=${h},left=${left},top=${top}`)
|
||||
if (!popup) {
|
||||
// Popup blocked: with the return value discarded, a blocked
|
||||
// popup looked exactly like a successful one (nothing opens,
|
||||
// nothing is said, the user clicks again). Fall back to the
|
||||
// full-page flow instead. The callback already supports it:
|
||||
// with no window.opener it redirects to
|
||||
// /import?migration=connected&consentId=..., which
|
||||
// handleOAuthReturn consumes and resumes the wizard at the
|
||||
// preview step. Same treatment as SkatteverketConnectPanel.
|
||||
window.location.href = authUrl
|
||||
}
|
||||
}}
|
||||
>
|
||||
Logga in i {providerName}
|
||||
@@ -1929,8 +1940,13 @@ export default function ArcimMigrationWorkspace(_props: WorkspaceComponentProps)
|
||||
} else {
|
||||
// The pre-opened popup was blocked or closed; retrying here is a
|
||||
// long shot (the activation may be gone) but strictly better than
|
||||
// dropping the flow.
|
||||
window.open(data.authUrl, 'arcim-oauth', `width=${w},height=${h},left=${left},top=${top}`)
|
||||
// dropping the flow. If the retry is blocked too, take the same
|
||||
// full-page fallback as the first-connect button rather than leaving
|
||||
// "Återanslut" looking like it worked.
|
||||
const retry = window.open(data.authUrl, 'arcim-oauth', `width=${w},height=${h},left=${left},top=${top}`)
|
||||
if (!retry) {
|
||||
window.location.href = data.authUrl
|
||||
}
|
||||
}
|
||||
setAuthUrl(data.authUrl)
|
||||
} else {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState, useEffect } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -18,6 +19,7 @@ import { Loader2 } from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { InvoiceExtractionResult, VatTreatment } from '@/types'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { summarizeUnderlagTotals } from './bulk-book-inbox-totals'
|
||||
|
||||
// Minimal shape the dialog needs from the workspace's inbox items.
|
||||
interface BulkBookInboxItem {
|
||||
@@ -84,6 +86,7 @@ function isBookable(it: BulkBookInboxItem): boolean {
|
||||
|
||||
export default function BulkBookInboxDialog({ open, onOpenChange, items, onSuccess }: Props) {
|
||||
const { toast } = useToast()
|
||||
const t = useTranslations('inbox_bulk_book')
|
||||
const [category, setCategory] = useState<string>('')
|
||||
const [vatTreatment, setVatTreatment] = useState<VatTreatment>('standard_25')
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
@@ -109,10 +112,23 @@ export default function BulkBookInboxDialog({ open, onOpenChange, items, onSucce
|
||||
if (open) setVatTreatment('standard_25')
|
||||
}, [open])
|
||||
|
||||
const totalSek = useMemo(
|
||||
() => bookable.reduce((s, it) => s + (it.extracted_data?.totals?.total ?? 0), 0),
|
||||
[bookable],
|
||||
)
|
||||
// Underlag subtotals, split per currency. This used to be a single scalar
|
||||
// named `totalSek` that summed `totals.total` across the selection and was
|
||||
// rendered with formatCurrency()'s SEK default, so a mixed batch added 100
|
||||
// EUR to 100 SEK and stamped "kr" on the result: a figure the user approved
|
||||
// against that matched no belopp at all (BFL 5 kap 7 §). The split is honest
|
||||
// in both directions: a homogeneous EUR batch now reads in EUR too.
|
||||
//
|
||||
// Deliberately NOT a submit gate, unlike the mixed-currency dead end in
|
||||
// components/transactions/BulkBookDialog.tsx. That dialog builds ONE
|
||||
// samlingsverifikation, which must sit in a single redovisningsvaluta (BFL 4
|
||||
// kap 6 §). This route books one verifikat PER underlag off its matched bank
|
||||
// transaction's own settled amount (see lib/transactions/categorize-core.ts),
|
||||
// so a EUR invoice paid by a SEK bank line is booked correctly and a mixed
|
||||
// selection yields a set of individually correct verifikat. Blocking it would
|
||||
// refuse a legal everyday batch. See bulk-book-inbox-totals.ts.
|
||||
const underlagTotals = useMemo(() => summarizeUnderlagTotals(bookable), [bookable])
|
||||
const isMixedCurrency = underlagTotals.length > 1
|
||||
|
||||
const submit = async () => {
|
||||
if (!category || bookable.length === 0) return
|
||||
@@ -226,12 +242,29 @@ export default function BulkBookInboxDialog({ open, onOpenChange, items, onSucce
|
||||
)}
|
||||
</div>
|
||||
|
||||
{totalSek > 0 && (
|
||||
{!isMixedCurrency && underlagTotals.length === 1 && (
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
Underlagens summa: {formatCurrency(totalSek)}
|
||||
{t('total_label', {
|
||||
amount: formatCurrency(underlagTotals[0]!.total, underlagTotals[0]!.currency),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{isMixedCurrency && (
|
||||
<div className="rounded-md border border-border bg-secondary/40 p-3 text-xs text-muted-foreground">
|
||||
<p className="font-medium text-foreground">{t('mixed_currency_totals_label')}</p>
|
||||
<ul className="mt-2 space-y-1">
|
||||
{underlagTotals.map(({ currency, total }) => (
|
||||
<li key={currency} className="flex items-center justify-between tabular-nums">
|
||||
<span className="font-mono">{currency}</span>
|
||||
<span className="text-foreground">{formatCurrency(total, currency)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-2">{t('mixed_currency_note')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{skippedNote && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Hoppas över: {skippedNote}.
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import AiFilledIndicator from '@/components/ui/ai-filled-indicator'
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -37,6 +39,8 @@ import {
|
||||
import Link from 'next/link'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { fetchWithTimeout } from '@/lib/http/fetch-with-timeout'
|
||||
import { copyInboxAddress, type AddressCopyState } from '@/components/extensions/general/inbox-address-copy'
|
||||
import { useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||
@@ -87,6 +91,20 @@ interface InboxAddress {
|
||||
status: string
|
||||
}
|
||||
|
||||
// How far the underlag behind the selected row got.
|
||||
//
|
||||
// `none` is the only state that may claim "Inget underlag bifogat": it means the
|
||||
// row carries no document_id at all. A failed or hung metadata read is `error`,
|
||||
// never `none`: the document exists (the row points at it), we just could not
|
||||
// load it, and telling the user their underlag is missing invites a duplicate
|
||||
// upload or the conclusion that the receipt is gone (BFL 7 kap 2 § retention).
|
||||
type DocumentLoadState = 'none' | 'loading' | 'ready' | 'error'
|
||||
|
||||
// A signed-URL lookup is one indexed row plus a storage sign call: seconds at
|
||||
// worst, even on a cold start. 15s leaves several times that headroom while
|
||||
// still ending the spinner instead of leaving it turning forever.
|
||||
const DOCUMENT_FETCH_TIMEOUT_MS = 15_000
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────
|
||||
|
||||
function timeAgo(iso: string): string {
|
||||
@@ -204,11 +222,16 @@ function WorkspaceSkeleton() {
|
||||
|
||||
export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
const { toast } = useToast()
|
||||
const t = useTranslations('inbox_workspace')
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const { openAgentSheet, identity } = useAgentSheet()
|
||||
|
||||
const [items, setItems] = useState<InboxItem[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
// The list read failed (non-2xx, unparseable body, or network). Kept apart
|
||||
// from "the list is empty": with no list at all we know nothing about the
|
||||
// inbox and must not render an authoritative "Inkorgen är tom".
|
||||
const [itemsLoadFailed, setItemsLoadFailed] = useState(false)
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null)
|
||||
// List filter + search (client-side over the already-fetched items list).
|
||||
// Defaults to 'todo': the active inbox (everything not yet booked), so
|
||||
@@ -232,7 +255,16 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
const [selected, setSelected] = useState<InboxItem | null>(null)
|
||||
const [docUrl, setDocUrl] = useState<string | null>(null)
|
||||
const [docMime, setDocMime] = useState<string | null>(null)
|
||||
const [docState, setDocState] = useState<DocumentLoadState>('none')
|
||||
// Which selection the in-flight document read belongs to. The user can click
|
||||
// another row while it is running, and a late resolution must not paint its
|
||||
// outcome (a URL, or an error) onto the row that is now selected.
|
||||
const docRequestRef = useRef<string | null>(null)
|
||||
const [inboxAddress, setInboxAddress] = useState<InboxAddress | null>(null)
|
||||
// We asked for the inbox address and did not get an answer we can trust
|
||||
// (5xx, network, unparseable). Distinct from a 404, which honestly means no
|
||||
// address is provisioned yet.
|
||||
const [addressLoadFailed, setAddressLoadFailed] = useState(false)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [isRotating, setIsRotating] = useState(false)
|
||||
@@ -259,21 +291,27 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
try {
|
||||
const res = await fetch('/api/extensions/ext/invoice-inbox/items?limit=500')
|
||||
const json = await res.json()
|
||||
if (res.ok) {
|
||||
const serverItems: InboxItem[] = json.data?.items ?? []
|
||||
// Preserve optimistic upload placeholders that haven't resolved to a
|
||||
// server row yet. A refetch can now fire mid-upload (a realtime event
|
||||
// from an unrelated booking), and a wholesale replace would briefly
|
||||
// drop the in-flight placeholder. Placeholders carry a `temp-` id that
|
||||
// never collides with a real row, and uploadFile() removes its own
|
||||
// placeholder before its fetchItems(), so this never duplicates.
|
||||
setItems((prev) => {
|
||||
const pending = prev.filter((it) => it.isPlaceholder)
|
||||
return pending.length > 0 ? [...pending, ...serverItems] : serverItems
|
||||
})
|
||||
if (!res.ok) {
|
||||
// No list came back, so we cannot say anything about the inbox: the
|
||||
// list column renders the failure instead of "Inkorgen är tom".
|
||||
setItemsLoadFailed(true)
|
||||
return
|
||||
}
|
||||
const serverItems: InboxItem[] = json.data?.items ?? []
|
||||
// Preserve optimistic upload placeholders that haven't resolved to a
|
||||
// server row yet. A refetch can now fire mid-upload (a realtime event
|
||||
// from an unrelated booking), and a wholesale replace would briefly
|
||||
// drop the in-flight placeholder. Placeholders carry a `temp-` id that
|
||||
// never collides with a real row, and uploadFile() removes its own
|
||||
// placeholder before its fetchItems(), so this never duplicates.
|
||||
setItems((prev) => {
|
||||
const pending = prev.filter((it) => it.isPlaceholder)
|
||||
return pending.length > 0 ? [...pending, ...serverItems] : serverItems
|
||||
})
|
||||
setItemsLoadFailed(false)
|
||||
} catch (err) {
|
||||
console.error('[invoice-inbox] fetchItems failed:', err)
|
||||
setItemsLoadFailed(true)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
@@ -285,9 +323,20 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
if (res.ok) {
|
||||
const { data } = await res.json()
|
||||
setInboxAddress(data)
|
||||
setAddressLoadFailed(false)
|
||||
return
|
||||
}
|
||||
// 404 is the honest "no inbox provisioned yet" answer, so the activate
|
||||
// button is the right thing to offer. Anything else (503 without an
|
||||
// inbound domain, 500, an HTML error page) leaves us not knowing whether
|
||||
// an address exists, and offering "Aktivera inkorgsadress" there is not
|
||||
// just wrong copy: handleRotateAddress skips its confirm dialog when
|
||||
// inboxAddress is null, so one click would silently retire a live address
|
||||
// that suppliers and forwarding rules already point at.
|
||||
setInboxAddress(null)
|
||||
setAddressLoadFailed(res.status !== 404)
|
||||
} catch {
|
||||
// 404 / 503 are expected when no address provisioned yet
|
||||
setAddressLoadFailed(true)
|
||||
}
|
||||
}, [])
|
||||
|
||||
@@ -366,8 +415,13 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
!!it.matched_transaction_id ||
|
||||
!!it.created_journal_entry_id
|
||||
)
|
||||
// The list read failed and left us with nothing: we do not know whether the
|
||||
// inbox is empty. A failed refetch that still has rows on screen is not this.
|
||||
const itemsUnknown = itemsLoadFailed && !hasAnyItem
|
||||
// Never coach "ladda upp ditt första underlag" off a list we could not read:
|
||||
// that step may well be done already.
|
||||
const showOnboarding =
|
||||
!onboardingDismissed && !(hasInboxAddress && hasAnyItem && hasResolvedItem)
|
||||
!onboardingDismissed && !itemsUnknown && !(hasInboxAddress && hasAnyItem && hasResolvedItem)
|
||||
|
||||
// ── List filter + search (client-side over the fetched list) ─
|
||||
|
||||
@@ -427,11 +481,58 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
|
||||
// ── Selection ──────────────────────────────────────────────
|
||||
|
||||
// Resolve the signed URL for a row's underlag. Every exit sets docState, so
|
||||
// the preview pane always says which of the four situations it is in: no
|
||||
// document, still loading, ready, or "we could not load it". The pane must
|
||||
// never fall back to "Inget underlag bifogat" for a row that has a
|
||||
// document_id, which is what the old silent catch produced.
|
||||
const loadDocument = useCallback(async (itemId: string, documentId: string | null) => {
|
||||
docRequestRef.current = itemId
|
||||
setDocUrl(null)
|
||||
setDocMime(null)
|
||||
if (!documentId) {
|
||||
setDocState('none')
|
||||
return
|
||||
}
|
||||
setDocState('loading')
|
||||
try {
|
||||
const res = await fetchWithTimeout(
|
||||
`/api/documents/${documentId}`,
|
||||
{ method: 'GET' },
|
||||
{ timeoutMs: DOCUMENT_FETCH_TIMEOUT_MS, description: `document ${documentId}` },
|
||||
)
|
||||
if (docRequestRef.current !== itemId) return
|
||||
if (!res.ok) {
|
||||
setDocState('error')
|
||||
return
|
||||
}
|
||||
const { data } = await res.json()
|
||||
if (docRequestRef.current !== itemId) return
|
||||
const url: string | null = data?.download_url ?? null
|
||||
if (!url) {
|
||||
// The document row exists but no signed URL came back: still a load
|
||||
// failure, not an absent underlag.
|
||||
setDocState('error')
|
||||
return
|
||||
}
|
||||
setDocUrl(url)
|
||||
setDocMime(data?.mime_type ?? null)
|
||||
setDocState('ready')
|
||||
} catch {
|
||||
// Timeout, offline, or an unparseable body. The document itself is
|
||||
// untouched, so the retry in the preview pane is the whole recovery.
|
||||
if (docRequestRef.current !== itemId) return
|
||||
setDocState('error')
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleSelect = useCallback(async (id: string) => {
|
||||
setSelectedId(id)
|
||||
setSelected(null)
|
||||
setDocUrl(null)
|
||||
setDocMime(null)
|
||||
setDocState('none')
|
||||
docRequestRef.current = id
|
||||
// Intentionally no auto-scroll: in the vertical-stack layout (below xl)
|
||||
// scrolling the preview into view pushes the list off-screen, and the
|
||||
// user has no obvious way back to pick another item. The row-highlight
|
||||
@@ -443,19 +544,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
if (!res.ok) throw new Error(json.error ?? 'Kunde inte hämta posten')
|
||||
const item = json.data as InboxItem
|
||||
setSelected(item)
|
||||
|
||||
if (item.document_id) {
|
||||
try {
|
||||
const docRes = await fetch(`/api/documents/${item.document_id}`)
|
||||
if (docRes.ok) {
|
||||
const { data } = await docRes.json()
|
||||
setDocUrl(data.download_url ?? null)
|
||||
setDocMime(data.mime_type ?? null)
|
||||
}
|
||||
} catch {
|
||||
// Preview is optional
|
||||
}
|
||||
}
|
||||
await loadDocument(id, item.document_id)
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Kunde inte ladda dokumentet',
|
||||
@@ -463,7 +552,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}, [toast])
|
||||
}, [toast, loadDocument])
|
||||
|
||||
// ── Upload ─────────────────────────────────────────────────
|
||||
|
||||
@@ -678,14 +767,17 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
|
||||
// ── Inbox address ──────────────────────────────────────────
|
||||
|
||||
const handleCopyAddress = useCallback(() => {
|
||||
if (!inboxAddress) return
|
||||
navigator.clipboard.writeText(inboxAddress.address).catch(() => {})
|
||||
toast({ title: 'Adress kopierad' })
|
||||
}, [inboxAddress, toast])
|
||||
|
||||
const handleRotateAddress = useCallback(async () => {
|
||||
if (inboxAddress && !confirm('Skapa en ny inkorgsadress? Den gamla slutar att fungera.')) return
|
||||
// Confirm whenever an address may already exist: either we hold one, or the
|
||||
// read failed and we cannot rule one out. Rotating retires the old address,
|
||||
// and suppliers plus forwarding rules already point at it, so the one case
|
||||
// that must never skip this dialog is the one where we are unsure.
|
||||
if (
|
||||
(inboxAddress || addressLoadFailed) &&
|
||||
!confirm('Skapa en ny inkorgsadress? Den gamla slutar att fungera.')
|
||||
) {
|
||||
return
|
||||
}
|
||||
setIsRotating(true)
|
||||
try {
|
||||
const res = await fetch('/api/extensions/ext/invoice-inbox/inbox/rotate', {
|
||||
@@ -694,6 +786,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error ?? 'Rotation misslyckades')
|
||||
setInboxAddress(json.data)
|
||||
setAddressLoadFailed(false)
|
||||
toast({ title: 'Ny adress skapad', description: json.data.address })
|
||||
} catch (err) {
|
||||
toast({
|
||||
@@ -704,7 +797,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
} finally {
|
||||
setIsRotating(false)
|
||||
}
|
||||
}, [toast, inboxAddress])
|
||||
}, [toast, inboxAddress, addressLoadFailed])
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────
|
||||
|
||||
@@ -727,33 +820,21 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
<Inbox className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<h1 className="font-medium text-sm shrink-0">Dokumentinkorg</h1>
|
||||
{inboxAddress ? (
|
||||
<>
|
||||
<span className="text-muted-foreground text-xs shrink-0">·</span>
|
||||
<code className="font-mono text-xs text-muted-foreground truncate min-w-0">
|
||||
{inboxAddress.address}
|
||||
</code>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-foreground shrink-0"
|
||||
onClick={handleCopyAddress}
|
||||
title="Kopiera adress"
|
||||
<InboxAddressBar
|
||||
address={inboxAddress.address}
|
||||
onRotate={handleRotateAddress}
|
||||
isRotating={isRotating}
|
||||
/>
|
||||
) : addressLoadFailed ? (
|
||||
// We do not know whether an address exists, so we offer a retry
|
||||
// rather than an activate button that would rotate a live address.
|
||||
<div role="status" aria-live="polite" className="min-w-0">
|
||||
<AttnLine
|
||||
action={{ label: t('retry'), onClick: () => { void fetchInboxAddress() } }}
|
||||
>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-foreground shrink-0"
|
||||
onClick={handleRotateAddress}
|
||||
disabled={isRotating}
|
||||
title="Rotera till ny adress"
|
||||
>
|
||||
{isRotating ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
{t('address_load_failed')}
|
||||
</AttnLine>
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -911,7 +992,22 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!hasAnyItem ? (
|
||||
{itemsUnknown ? (
|
||||
// The list read failed. "Inkorgen är tom" would be a claim we
|
||||
// cannot back: a mailed-in invoice may be sitting there unread.
|
||||
<div className="p-6 text-center text-sm text-muted-foreground space-y-2">
|
||||
<AlertTriangle className="h-5 w-5 mx-auto text-attn" />
|
||||
<p>{t('items_load_failed')}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
onClick={() => { void fetchItems() }}
|
||||
>
|
||||
{t('retry')}
|
||||
</Button>
|
||||
</div>
|
||||
) : !hasAnyItem ? (
|
||||
// On desktop the preview pane is always visible alongside this
|
||||
// column, so showing the onboarding card here would duplicate it.
|
||||
// Below xl the panes stack into one feed, so the sibling preview
|
||||
@@ -977,7 +1073,13 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
)}
|
||||
>
|
||||
{selected ? (
|
||||
<DocumentPreview docUrl={docUrl} docMime={docMime} isProcessing={!!selected.isPlaceholder} />
|
||||
<DocumentPreview
|
||||
docUrl={docUrl}
|
||||
docMime={docMime}
|
||||
isProcessing={!!selected.isPlaceholder}
|
||||
loadState={docState}
|
||||
onRetry={() => { void loadDocument(selected.id, selected.document_id) }}
|
||||
/>
|
||||
) : showOnboarding ? (
|
||||
<div className="h-full flex items-center justify-center px-4 py-6">
|
||||
<OnboardingCard
|
||||
@@ -993,7 +1095,9 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
) : (
|
||||
<EmptyPreview
|
||||
onUploadClick={() => fileInputRef.current?.click()}
|
||||
onActivateInbox={inboxAddress ? null : handleRotateAddress}
|
||||
// Only offer activation when we know there is nothing to retire:
|
||||
// a failed address read is not a "you have no address yet".
|
||||
onActivateInbox={inboxAddress || addressLoadFailed ? null : handleRotateAddress}
|
||||
isActivating={isRotating}
|
||||
/>
|
||||
)}
|
||||
@@ -1131,6 +1235,94 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
|
||||
}
|
||||
|
||||
|
||||
// ── Inbox address bar ────────────────────────────────────────
|
||||
// The address plus its copy and rotate controls. Owns the copy state so the
|
||||
// header can report an honest outcome: a clipboard write rejects for ordinary
|
||||
// reasons (insecure context, a blocking Permissions-Policy, a document that
|
||||
// lost focus) and the previous handler swallowed that and said "Adress
|
||||
// kopierad" anyway. The user then waits for supplier invoices at an address
|
||||
// they never captured, which is unrecoverable in the sense that matters: no
|
||||
// invoice ever arrives and nothing explains why.
|
||||
//
|
||||
// Treatment mirrors CopyBlock in components/settings/ApiKeysPanel.tsx: icon
|
||||
// swap for the state, one ochre AttnLine on failure, live region always
|
||||
// mounted. No toast on any path, so nothing here can be evicted by (or evict)
|
||||
// another toast under TOAST_LIMIT = 1.
|
||||
|
||||
function InboxAddressBar({
|
||||
address,
|
||||
onRotate,
|
||||
isRotating,
|
||||
}: {
|
||||
address: string
|
||||
onRotate: () => void
|
||||
isRotating: boolean
|
||||
}) {
|
||||
const t = useTranslations('inbox_workspace')
|
||||
const [copyState, setCopyState] = useState<AddressCopyState>('idle')
|
||||
|
||||
async function handleCopy() {
|
||||
// The clipboard write is the first await, so the click's user activation
|
||||
// still holds when it runs.
|
||||
const next = await copyInboxAddress(address)
|
||||
setCopyState(next)
|
||||
if (next === 'copied') setTimeout(() => setCopyState('idle'), 2000)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-w-0">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="text-muted-foreground text-xs shrink-0">·</span>
|
||||
<code
|
||||
className={cn(
|
||||
'select-all font-mono text-xs text-muted-foreground min-w-0',
|
||||
// With no clipboard, reading the address off the screen is the only
|
||||
// way to get it: show it whole instead of ellipsised.
|
||||
copyState === 'failed' ? 'break-all' : 'truncate',
|
||||
)}
|
||||
>
|
||||
{address}
|
||||
</code>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-foreground shrink-0"
|
||||
onClick={handleCopy}
|
||||
aria-label={t('copy_address')}
|
||||
title={t('copy_address')}
|
||||
>
|
||||
{copyState === 'copied' ? (
|
||||
<Check className="h-3.5 w-3.5 text-success" />
|
||||
) : copyState === 'failed' ? (
|
||||
<AlertTriangle className="h-3.5 w-3.5 text-attn" />
|
||||
) : (
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-foreground shrink-0"
|
||||
onClick={onRotate}
|
||||
disabled={isRotating}
|
||||
title="Rotera till ny adress"
|
||||
>
|
||||
{isRotating ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
{/* Always mounted so the sentence is announced when it appears, not
|
||||
merely inserted. */}
|
||||
<div role="status" aria-live="polite">
|
||||
{copyState === 'failed' && (
|
||||
<AttnLine className="mt-1">{t('copy_address_failed')}</AttnLine>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── List row ─────────────────────────────────────────────────
|
||||
|
||||
function InboxRow({
|
||||
@@ -1244,11 +1436,19 @@ export function DocumentPreview({
|
||||
docUrl,
|
||||
docMime,
|
||||
isProcessing = false,
|
||||
loadState,
|
||||
onRetry,
|
||||
}: {
|
||||
docUrl: string | null
|
||||
docMime: string | null
|
||||
isProcessing?: boolean
|
||||
/** Omitted by callers that only ever hold a resolved URL. */
|
||||
loadState?: DocumentLoadState
|
||||
onRetry?: () => void
|
||||
}) {
|
||||
const t = useTranslations('inbox_workspace')
|
||||
const state: DocumentLoadState = loadState ?? (docUrl ? 'ready' : 'none')
|
||||
|
||||
if (isProcessing) {
|
||||
return (
|
||||
<div className="h-full flex flex-col items-center justify-center gap-3 text-sm text-muted-foreground">
|
||||
@@ -1257,6 +1457,29 @@ export function DocumentPreview({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (state === 'loading') {
|
||||
return (
|
||||
<div className="h-full flex flex-col items-center justify-center gap-3 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
<span>{t('document_loading')}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (state === 'error' || (state === 'ready' && !docUrl)) {
|
||||
// The row points at a stored document: say that it could not be shown, not
|
||||
// that there is nothing attached.
|
||||
return (
|
||||
<div className="h-full flex flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground">
|
||||
<AlertTriangle className="h-5 w-5 text-attn" />
|
||||
<span>{t('document_load_failed')}</span>
|
||||
{onRetry && (
|
||||
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={onRetry}>
|
||||
{t('retry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!docUrl) {
|
||||
return (
|
||||
<div className="h-full flex items-center justify-center text-sm text-muted-foreground">
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Coverage for the per-currency totalling behind the "Bokför valda" underlag
|
||||
* dialog. The dialog itself is never rendered here (Vitest runs in the `node`
|
||||
* environment, no component tests in this repo), which is exactly why the rule
|
||||
* was extracted into a pure module.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
normalizeUnderlagCurrency,
|
||||
summarizeUnderlagTotals,
|
||||
type UnderlagTotalsItem,
|
||||
} from '../bulk-book-inbox-totals'
|
||||
import type { InvoiceExtractionResult } from '@/types'
|
||||
|
||||
/** Minimal extraction shaped like the real one; only the read fields matter. */
|
||||
function item(total: number | null, currency?: string | null): UnderlagTotalsItem {
|
||||
return {
|
||||
extracted_data: {
|
||||
supplier: { name: null, orgNumber: null, vatNumber: null, address: null, bankgiro: null, plusgiro: null },
|
||||
// `currency` is typed non-nullable on InvoiceExtractionResult, but rows
|
||||
// written before the field existed really do arrive without it, so the
|
||||
// cast reproduces the shape the dialog actually receives at runtime.
|
||||
invoice: {
|
||||
invoiceNumber: null,
|
||||
invoiceDate: null,
|
||||
dueDate: null,
|
||||
paymentReference: null,
|
||||
currency: currency as string,
|
||||
},
|
||||
lineItems: [],
|
||||
totals: { subtotal: null, vatAmount: null, total },
|
||||
vatBreakdown: [],
|
||||
confidence: 1,
|
||||
} as InvoiceExtractionResult,
|
||||
}
|
||||
}
|
||||
|
||||
describe('normalizeUnderlagCurrency', () => {
|
||||
it('passes through a well-formed code, uppercased', () => {
|
||||
expect(normalizeUnderlagCurrency('EUR')).toBe('EUR')
|
||||
expect(normalizeUnderlagCurrency('eur')).toBe('EUR')
|
||||
expect(normalizeUnderlagCurrency(' usd ')).toBe('USD')
|
||||
})
|
||||
|
||||
it('treats a missing currency as SEK (legacy extractions predate the field)', () => {
|
||||
expect(normalizeUnderlagCurrency(null)).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency(undefined)).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency('')).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency(' ')).toBe('SEK')
|
||||
})
|
||||
|
||||
it('falls back to SEK on a malformed code rather than letting Intl throw', () => {
|
||||
// formatCurrency() -> Intl.NumberFormat raises RangeError on these, and the
|
||||
// value comes from AI extraction of a PDF, so it is not trustworthy input.
|
||||
expect(normalizeUnderlagCurrency('Euro')).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency('kr')).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency('12')).toBe('SEK')
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeUnderlagTotals: single-currency selections still work', () => {
|
||||
it('sums a plain SEK selection into one entry', () => {
|
||||
const totals = summarizeUnderlagTotals([
|
||||
item(1000, 'SEK'),
|
||||
item(250.5, 'SEK'),
|
||||
item(99.25, 'SEK'),
|
||||
])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 1349.75 }])
|
||||
})
|
||||
|
||||
it('keeps a homogeneous foreign selection in its own currency, not SEK', () => {
|
||||
// The old code rendered this through formatCurrency() with the SEK
|
||||
// default, so 3 000 EUR read as "3 000 kr".
|
||||
const totals = summarizeUnderlagTotals([item(1000, 'EUR'), item(2000, 'EUR')])
|
||||
expect(totals).toEqual([{ currency: 'EUR', total: 3000 }])
|
||||
})
|
||||
|
||||
it('rounds to öre with Math.round(x * 100) / 100, never toFixed', () => {
|
||||
const totals = summarizeUnderlagTotals([item(0.1, 'SEK'), item(0.2, 'SEK')])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 0.3 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeUnderlagTotals: a legacy NULL + SEK batch is NOT a currency mix', () => {
|
||||
it('groups a missing currency with SEK instead of reporting two currencies', () => {
|
||||
const totals = summarizeUnderlagTotals([
|
||||
item(500, null),
|
||||
item(300, 'SEK'),
|
||||
item(200, undefined),
|
||||
item(100, ''),
|
||||
])
|
||||
expect(totals).toHaveLength(1)
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 1100 }])
|
||||
})
|
||||
|
||||
it('does not split lowercase sek away from SEK', () => {
|
||||
const totals = summarizeUnderlagTotals([item(10, 'sek'), item(20, 'SEK')])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 30 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeUnderlagTotals: mixed selections report per-currency subtotals', () => {
|
||||
it('never collapses two currencies into one scalar', () => {
|
||||
const totals = summarizeUnderlagTotals([
|
||||
item(100, 'SEK'),
|
||||
item(100, 'EUR'),
|
||||
item(50, 'SEK'),
|
||||
])
|
||||
expect(totals).toEqual([
|
||||
{ currency: 'EUR', total: 100 },
|
||||
{ currency: 'SEK', total: 150 },
|
||||
])
|
||||
// The old scalar would have been 250, a number denominated in nothing.
|
||||
expect(totals.reduce((s, t) => s + t.total, 0)).not.toBe(totals[0]!.total)
|
||||
})
|
||||
|
||||
it('sorts by currency code so the list is stable across renders', () => {
|
||||
const totals = summarizeUnderlagTotals([item(1, 'USD'), item(1, 'EUR'), item(1, 'SEK')])
|
||||
expect(totals.map((t) => t.currency)).toEqual(['EUR', 'SEK', 'USD'])
|
||||
})
|
||||
|
||||
it('separates a legacy NULL (SEK) from a genuine foreign underlag', () => {
|
||||
const totals = summarizeUnderlagTotals([item(400, null), item(600, 'EUR')])
|
||||
expect(totals).toEqual([
|
||||
{ currency: 'EUR', total: 600 },
|
||||
{ currency: 'SEK', total: 400 },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeUnderlagTotals: items without an extracted amount', () => {
|
||||
it('returns an empty list when nothing was extracted', () => {
|
||||
expect(summarizeUnderlagTotals([])).toEqual([])
|
||||
expect(summarizeUnderlagTotals([{ extracted_data: null }])).toEqual([])
|
||||
expect(summarizeUnderlagTotals([item(null, 'SEK')])).toEqual([])
|
||||
})
|
||||
|
||||
it('skips a null total instead of counting it as zero in that currency', () => {
|
||||
const totals = summarizeUnderlagTotals([item(null, 'EUR'), item(100, 'SEK')])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 100 }])
|
||||
})
|
||||
|
||||
it('ignores a non-finite total rather than poisoning the subtotal with NaN', () => {
|
||||
const totals = summarizeUnderlagTotals([item(Number.NaN, 'SEK'), item(100, 'SEK')])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 100 }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { copyInboxAddress } from '@/components/extensions/general/inbox-address-copy'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('copyInboxAddress', () => {
|
||||
it('reports copied and forwards the exact address on success', async () => {
|
||||
const writeText = vi.fn(async () => undefined)
|
||||
vi.stubGlobal('navigator', { clipboard: { writeText } })
|
||||
|
||||
await expect(copyInboxAddress('faktura-a1b2c3@inbox.gnubok.se')).resolves.toBe('copied')
|
||||
expect(writeText).toHaveBeenCalledWith('faktura-a1b2c3@inbox.gnubok.se')
|
||||
})
|
||||
|
||||
it('reports failed when the write is rejected, never copied', async () => {
|
||||
// The regression guard. The old handler swallowed this rejection in an empty
|
||||
// catch and then showed "Adress kopierad" anyway, so the user walked away
|
||||
// believing they had the inbox address and waited for invoices at an address
|
||||
// they never captured.
|
||||
vi.stubGlobal('navigator', {
|
||||
clipboard: {
|
||||
writeText: vi.fn(async () => {
|
||||
throw new DOMException('Write permission denied.', 'NotAllowedError')
|
||||
}),
|
||||
},
|
||||
})
|
||||
|
||||
const state = await copyInboxAddress('faktura-a1b2c3@inbox.gnubok.se')
|
||||
expect(state).toBe('failed')
|
||||
expect(state).not.toBe('copied')
|
||||
})
|
||||
|
||||
it('reports failed on a non-Error rejection', async () => {
|
||||
vi.stubGlobal('navigator', {
|
||||
clipboard: { writeText: vi.fn(() => Promise.reject('nope')) },
|
||||
})
|
||||
|
||||
await expect(copyInboxAddress('faktura-a1b2c3@inbox.gnubok.se')).resolves.toBe('failed')
|
||||
})
|
||||
|
||||
it('reports failed when the Clipboard API is missing (insecure context)', async () => {
|
||||
// No API means no programmatic fallback either: the header must keep the
|
||||
// address visible and selectable instead of claiming a copy.
|
||||
vi.stubGlobal('navigator', {})
|
||||
|
||||
const state = await copyInboxAddress('faktura-a1b2c3@inbox.gnubok.se')
|
||||
expect(state).toBe('failed')
|
||||
expect(state).not.toBe('copied')
|
||||
})
|
||||
|
||||
it('reports failed when clipboard exists but writeText does not', async () => {
|
||||
vi.stubGlobal('navigator', { clipboard: { read: vi.fn() } })
|
||||
|
||||
await expect(copyInboxAddress('faktura-a1b2c3@inbox.gnubok.se')).resolves.toBe('failed')
|
||||
})
|
||||
|
||||
it('does not throw when there is no navigator at all', async () => {
|
||||
vi.stubGlobal('navigator', undefined)
|
||||
|
||||
await expect(copyInboxAddress('faktura-a1b2c3@inbox.gnubok.se')).resolves.toBe('failed')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Pure per-currency totalling for the "Bokför valda" underlag dialog.
|
||||
*
|
||||
* Lives outside BulkBookInboxDialog.tsx (a `'use client'` component) so the
|
||||
* rule below can be unit tested: this repo runs Vitest in the `node`
|
||||
* environment and never renders components, so logic embedded in JSX is
|
||||
* unverifiable by construction.
|
||||
*
|
||||
* # Why this exists
|
||||
*
|
||||
* The dialog used to reduce the whole selection to ONE scalar
|
||||
* (`bookable.reduce((s, it) => s + (it.extracted_data?.totals?.total ?? 0), 0)`)
|
||||
* and render it through `formatCurrency()`, which defaults to SEK. Both halves
|
||||
* of that are wrong the moment the underlag are not all SEK:
|
||||
*
|
||||
* 1. It adds 100 EUR to 100 SEK as if they were one unit, so the figure the
|
||||
* user approves against corresponds to no real belopp (BFL 5 kap 7 §
|
||||
* requires a verifikation to state the belopp of the affärshändelse; a
|
||||
* cross-currency sum is not one).
|
||||
* 2. Even for a homogeneous non-SEK selection it stamped "kr" on a total
|
||||
* denominated in something else, so three 1 000 EUR invoices read as
|
||||
* "3 000 kr".
|
||||
*
|
||||
* # Why this is a display fix and NOT a submit block
|
||||
*
|
||||
* Unlike `components/transactions/BulkBookDialog.tsx`, this dialog does not
|
||||
* build a samlingsverifikation. `POST /items/bulk-book` runs
|
||||
* `bulkBookMatchedInboxItems`, which loops the selection and calls
|
||||
* `categorizeMatchedTransaction` per item: ONE verifikat per underlag, and the
|
||||
* booked belopp is read off that item's matched bank transaction, never off
|
||||
* `extracted_data.totals.total` (see the header of
|
||||
* `lib/transactions/categorize-core.ts`: "Booking is always in SEK off the bank
|
||||
* transaction's own amount"). A EUR invoice settled by the bank in SEK is
|
||||
* therefore booked correctly and legally, and a selection mixing SEK and EUR
|
||||
* underlag produces a set of individually correct SEK verifikat.
|
||||
*
|
||||
* So there is no BFL 4 kap 6 § redovisningsvaluta conflict to refuse here, and
|
||||
* blocking the submit would break a legitimate everyday flow (a batch of
|
||||
* receipts where some suppliers invoice in EUR). The honest fix is to stop
|
||||
* presenting the misleading scalar and show what is actually true: a subtotal
|
||||
* per currency, plus a note that the booking follows the bank amount.
|
||||
*/
|
||||
import type { InvoiceExtractionResult } from '@/types'
|
||||
|
||||
/** The subset of an inbox item this module needs. */
|
||||
export interface UnderlagTotalsItem {
|
||||
extracted_data: InvoiceExtractionResult | null
|
||||
}
|
||||
|
||||
export interface UnderlagCurrencyTotal {
|
||||
/** ISO 4217 code, uppercased. */
|
||||
currency: string
|
||||
total: number
|
||||
}
|
||||
|
||||
function round2(n: number): number {
|
||||
return Math.round(n * 100) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve an underlag's currency to a code that is safe to both group by and
|
||||
* hand to `Intl.NumberFormat`.
|
||||
*
|
||||
* A missing/blank currency normalizes to 'SEK'. This matters for correctness,
|
||||
* not just tidiness: `extracted_data.invoice.currency` is produced by document
|
||||
* extraction and older rows predate the field, so an un-normalized
|
||||
* `new Set(items.map(i => i.extracted_data?.invoice?.currency))` would split a
|
||||
* legacy `null`/`undefined` underlag away from its SEK siblings and report a
|
||||
* currency mix that does not exist. `pickCurrency()` in
|
||||
* InvoiceInboxWorkspace.tsx and `emptyExtraction()` both already read a missing
|
||||
* currency as SEK, so this keeps the dialog consistent with the list behind it.
|
||||
*
|
||||
* Anything that is not a plausible 3-letter code also falls back to 'SEK':
|
||||
* `formatCurrency` throws a RangeError on a malformed code, and this value
|
||||
* comes from AI extraction of a PDF, so it cannot be trusted to be well formed.
|
||||
* Crashing the approval dialog on a junk code would be strictly worse than
|
||||
* grouping it with the default.
|
||||
*/
|
||||
export function normalizeUnderlagCurrency(currency: string | null | undefined): string {
|
||||
const code = currency?.trim().toUpperCase()
|
||||
return code && /^[A-Z]{3}$/.test(code) ? code : 'SEK'
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtotal the selection per currency, sorted by currency code.
|
||||
*
|
||||
* Items whose extraction produced no total contribute nothing (they are not
|
||||
* counted as a 0 in some currency), so a selection with no extracted amounts
|
||||
* yields an empty array and the caller renders nothing: the same "no figure to
|
||||
* show" outcome the old `totalSek > 0` gate produced.
|
||||
*
|
||||
* A result of length > 1 means the selection genuinely spans currencies and
|
||||
* the caller must not render a combined scalar.
|
||||
*/
|
||||
export function summarizeUnderlagTotals(items: UnderlagTotalsItem[]): UnderlagCurrencyTotal[] {
|
||||
const byCurrency = new Map<string, number>()
|
||||
for (const item of items) {
|
||||
const total = item.extracted_data?.totals?.total
|
||||
if (total == null || !Number.isFinite(total)) continue
|
||||
const currency = normalizeUnderlagCurrency(item.extracted_data?.invoice?.currency)
|
||||
byCurrency.set(currency, round2((byCurrency.get(currency) ?? 0) + total))
|
||||
}
|
||||
return Array.from(byCurrency.entries())
|
||||
.map(([currency, total]) => ({ currency, total }))
|
||||
.sort((a, b) => a.currency.localeCompare(b.currency))
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { copyToClipboard } from '@/lib/browser/copy-to-clipboard'
|
||||
|
||||
/**
|
||||
* Copy state for the inbox address in the workspace header.
|
||||
*
|
||||
* `idle` claims nothing, `copied` is only reachable after the clipboard write
|
||||
* resolved, and `failed` means the address is NOT on the clipboard.
|
||||
*/
|
||||
export type AddressCopyState = 'idle' | 'copied' | 'failed'
|
||||
|
||||
/**
|
||||
* Copy the document-inbox address and report which state the header must show.
|
||||
*
|
||||
* Why this exists as its own function: the previous handler fired
|
||||
* `navigator.clipboard.writeText(...).catch(() => {})` and then showed
|
||||
* "Adress kopierad" unconditionally, so an insecure context, a blocking
|
||||
* Permissions-Policy or a document that had lost focus produced a success
|
||||
* message with an empty clipboard. The user then waits for supplier invoices at
|
||||
* an address they never captured, and nothing in the UI ever contradicts that.
|
||||
*
|
||||
* `unavailable` (no Clipboard API at all) and `failed` (the write was rejected)
|
||||
* collapse into one UI state on purpose: from the user's side both mean the
|
||||
* address is not on the clipboard and manual selection is the only way to get
|
||||
* it. The distinction only matters for logging, which this surface does not do.
|
||||
*
|
||||
* Call this as the first `await` in the click handler: a clipboard write issued
|
||||
* after another await runs outside the click's transient user activation and is
|
||||
* rejected on that ground alone.
|
||||
*/
|
||||
export async function copyInboxAddress(
|
||||
address: string,
|
||||
): Promise<Exclude<AddressCopyState, 'idle'>> {
|
||||
const result = await copyToClipboard(address)
|
||||
return result === 'copied' ? 'copied' : 'failed'
|
||||
}
|
||||
Reference in New Issue
Block a user