Files
accounted/components/extensions/general/InvoiceInboxWorkspace.tsx
T
f53725b20a Agent v1 bundle: TIC v2 onboarding, in-app assistant gating, sidebar nav, MCP fixes (#584)
* fix(sie-import): accept tab as field separator (Bollbok exports)

The SIE 4 spec allows either space or tab between fields, but
splitSIELine() only treated space (0x20) as a separator. Bollbok
exports tab-separated lines for every record except #RAR, which
silently swallowed all #IB / #UB / #KONTO / #KTYP / #VER / #TRANS
records — imports appeared empty even though the file was well-formed.

Also adds a parser-side diagnostic that emits a warning when raw #IB
or #VER lines are present in the input but parsing produced none. The
previous silent failure is how this bug stayed hidden; the warning
gives the import preview something visible to surface next time.

Verified against two real reproducer files (Sean / Erik Hellqvist):
  erik h 2025.SE (UTF-8): 166 accounts, 66 IB, 4 UB, 11 RES, 95 vouchers, 198 TRANS.
  erik h 2026.SE (CP437): 166 accounts, 66 IB, 4 UB, 0 vouchers.
Both now parse with zero warnings/errors.

Tests:
  + 8 Bollbok-shape tab-separated fixtures (2025 + 2026 quoting variants).
  + 4 silent-failure diagnostic-warning tests.
  All 74 sie-parser tests pass; 155/155 in lib/import; 64/64 downstream callers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sie-import): address PR #513 review — strip #KTYP quotes, suppress redundant aggregate warning

Two non-blocking P2 findings from Greptile review on PR #513:

1. #KTYP handler stored fields[2] directly, so Bollbok 2026 exports
   (#KTYP\t1510\t"T") stored '"T"' with literal quotes instead of 'T'.
   Latent defect — accountType is unused downstream today, but my tab-
   separator fix made the quoted-value path reachable. Now routes through
   parseStringField so both Bollbok 2025 (unquoted T) and 2026 (quoted "T")
   land as 'T'.

2. The aggregate "kontrollera fältavskiljare och teckenkodning" warning
   fired alongside per-record 'error'-severity issues for malformed #IB /
   #VER records, producing a misleading hint when the parser had already
   pinpointed the structural problem. Now suppressed when an error-severity
   issue with the same tag already exists.

Test coverage:
  + accountType asserted to be 'T' (not '"T"') in both 2025 + 2026 shapes.
  + VER aggregate-warning test now uses #VER lines without { } blocks
    (silent loss, no per-record error) — the canonical case the diagnostic
    is designed for.
  + New suppression test: bare #VER produces per-record errors AND the
    aggregate warning is absent.

75/75 sie-parser tests pass; 156/156 in lib/import.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* wip: agent chat + composer + memory + document extraction

In-progress work on this branch beyond the SIE-import fixes:
- Specialized accountant agent (composer + intents + chat loop)
- Persistent agent_conversations/messages, agent_profiles, agent_memory
- /chat surface + /onboarding/agent + /settings/agent-memory
- document-extraction extension with status hooks
- MCP server staging refactor + new skills (atoms, bank reconciliation,
  customer onboarding, kreditfaktura)
- pending_operations rejection feedback (category + reason) + realtime
- TIC company profile cached snapshot on companies
- 17 migrations (all additive — see prior conversation analysis)

Parked while branch waits for review/merge. Migrations are already
applied to prod.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(tic): migrate company-data client from api-core v1 to Lens v2

Swaps the seven TIC company-data endpoints we call from the api-core
paths (`/datasets/companies/{companyId}/...`, `/search/companies`) to
the Lens equivalents (`/companies/{id}/...`, `/search-public/companies`).
Hard cutover; proxy pattern preserved.

Schema shifts handled inside the extension so consumers (TicWorkspace,
Step2CompanyDetails) don't need changes:

- `/companies/{id}/bank-accounts` now returns Bankgirot only — map to
  the existing `{ type, accountNumber, bic }` shape, drop terminated.
- `/companies/{id}/industries` returns a discriminated array — filter
  to `companyIndustryCodeType === 'sni2007'` to preserve v1 behavior.
- `/companies/{id}/phone-numbers` renamed the field to
  `phoneNumberFormatted` (fall back to `e164PhoneNumber`).
- `/companies/{id}/documents` replaces `/financial-report-summaries`;
  filter `type === 'annualReport'` and read nested
  `financialReportMetadata` to rebuild the legacy summary shape.
- `isCeased` is now a top-level boolean; `activityStatus` is an enum.
  Translate enum -> 'ceased' for the workspace's existing check.

BankID identity flow (id.tic.io) is untouched — separate TIC product.

Note: deploy gated on the TIC proxy being flipped to lens-api.tic.io
with an `x-api-key` Lens key.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(tic): expose v2 onboarding & workspace data

Adds six new Lens (v2) fetchers on top of the migration that already
landed in this branch, surfacing the data through /lookup and /profile.

New fetchers in lib/tic-client.ts:
- getFiscalYears          /companies/{id}/fiscal-years
- getAccountingPeriods    /companies/{id}/accounting-periods
- getPayrolls             /companies/{id}/payrolls
- getSignatory            /companies/{id}/signatory
- getRepresentatives      /companies/{id}/representatives
- getCompanyStatus        /companies/{id}/status

/lookup gains a fiscalYear field (current fiscal-year configuration)
so onboarding Step 2 can skip manual MM-DD entry. CompanyLookupResult
extended with optional fiscalYear; consumers without it keep working.

/profile gains five new sections on TICCompanyProfile:
- fiscalYear + fiscalYearHistory   current + deduped period list
- signatory                        firmateckning descriptions
- board + representatives          board-composition summary + active
                                   officers (positionEnd in future)
- payrolls                         payroll2 array newest-first, with
                                   deviation vs annual-report
- statuses                         current+historical status entries
                                   with red/yellow/green/neutral color

TicWorkspace renders the new data as four cards (Status, Fiscal year +
Signatory, Board + Representatives, Payroll history) plus a Badge
mapping for the traffic-light status color.

Tests: 52 -> 60 passing. Added unit tests for the new fetchers' v2
paths, fiscal-year auto-fill in /lookup, and full v2 profile coverage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(onboarding,agent): lean on TIC v2 to skip Steps 1 & 3 and sharpen Opus

Three small wins that unlock more of the v2 cutover. No new endpoints — the
data was already in the snapshot, just not flowing where it should.

Step 1 (entity_type) — deep-link path only:
- /lookup now returns `legalEntityType` and `registrationDate` (added to
  CompanyLookupResult).
- /onboarding/page.tsx does a server-side /lookup prefetch when
  ?org_number= is present (BankID picker path), maps "AB"/"EF" to the
  EntityType enum, and seeds Step 1's radio. Falls through silently for
  unsupported codes (HB, KB, …) and on TIC errors.
- WelcomeOnboarding hydrates ticLookup state from the server prefetch so
  Step 2's debounced client fetch and Step 3's first-year inference both
  have data on first render — no flash.

Step 3 (is_first_fiscal_year) — every path:
- deriveFirstYearDefaults() parses ticLookup.registrationDate and returns
  { isFirstFiscalYear, firstYearStart } when registered <12 months ago.
  Step 3's initialData picks it up; the user only confirms the end date.
- Settings value wins when present so existing users with a saved choice
  don't get overridden.

Composer prompt:
- redactTic allowlist was the bottleneck — it stripped beneficialOwners,
  signatory, board, representatives, payrolls, statuses, fiscalYear
  before Opus ever saw the JSON. Existing filterRedundantQuestions
  ownership logic was effectively dead because the data path was severed.
  Expanded allowlist to include those v2 sections; kept bankAccounts/
  email/phone/fiscalYearHistory/financialReports out (token cost > signal).
- SYSTEM_PROMPT now documents each v2 section and the rules Opus should
  apply: payroll signal switches from "registration.payroll" to "actual
  payrolls[] filings" (kills the false-positive swedish-payroll selection
  for newly registered employers); beneficialOwners[] becomes the
  authoritative ownership source (single owner → FMB modifier; multiple →
  multi-owner); statuses[] isCeased/red triggers an uncertainty_note.

Tests: 4112 unchanged. Build: green. No schema or migration changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent): onboarding polish + composer signal fixes from first-run feedback

UX:
- AgentOnboarding: drop the 10s "Hoppa över — fortsätt med standardval"
  escape hatch. The fallback path runs automatically on timeout; the
  manual skip just teased users into a degraded build.
- ReviewCard step 2 title: "Stämma av detaljerna" → "Stäm av detaljerna"
  (imperative form matches the rest of the steps).
- Drop em-dashes from user-visible Swedish strings in AgentOnboarding +
  ReviewCard (fallback labels, subtitles, placeholder, error message,
  final CTA). Em-dashes survive in code comments only.
- "Fråga min revisor" → "Fråga min assistent" everywhere it surfaced:
  AgentTrigger, AgentSparkleButton, ReviewCard preview, ReviewCard
  fallback comment, general.help intent buttonLabel + prompt text.
- AgentTrigger / AgentSparkleButton / EmptyState.AgentHelpLink /
  TransactionInboxCard ask-button all gated on identity.isVerified.
  Pre-onboarding users no longer see the floating FAB or per-page
  Sparkle buttons. AgentSheetProvider.identity gained an isVerified
  field; (dashboard)/layout.tsx selects agent_profiles.verified_at and
  passes it through.

TIC verksamhetsbeskrivning:
- tic/index.ts /profile: /companies/{id}/purposes returns every
  historical verksamhetsföremål filing. Picking [0] was returning the
  oldest "äga och förvalta" holding-company boilerplate for companies
  whose later filings narrowed the purpose ("tillhandahålla
  företagskrediter och finansiella teknologilösningar"). Sort the
  array by lastUpdatedAtUtc desc and take the most recent non-empty
  purpose.

Composer banking signal:
- loadBankingSummary now reads journal_entry_id alongside
  description/amount/date and returns per-counterparty `direction`
  ('in' | 'out' | 'mixed') and `has_unbooked` (any row not yet booked).
  Aggregate `unbooked_count` accompanies the rollup.
- buildUserPrompt emits each counterparty as
  `Name: 12 345 kr (ut, OBOKFÖRD)` so Opus can tell income from cost
  on sight and tell which counterparties are still open questions.
- SYSTEM_PROMPT now explicitly forbids verification questions about
  counterparties whose direction is unambiguous AND status is 'bokförd'.
  Should kill the regressions from the first agent build:
  * "Konsult, J 98 565 kr — intäkt eller kostnad?" when the amount is
    clearly negative.
  * "ALMI AB 493 000 kr — lån eller bidrag?" when the transaction is
    already categorized.

Tests: 4112 unchanged. Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent,ui): representation needs deltagare+syfte, drop duplicate doc icon

Representation booking:
- transaction-categorization prompt now requires the agent to capture
  participants (name + company) AND purpose before staging a
  representation categorization. SKV's representationsregler + ML 8 kap
  require the verifikation to document who attended and what the
  meeting was about; without that the avdrag is denied and the post
  should be booked as non-deductible / personalkostnad.
- The agent confirms back in plain text (audit trail in the chat),
  writes the deltagare + syfte to gnubok_remember_fact (long-term),
  THEN stages. Saknas deltagare/syfte: explicitly tell the user the
  avdrag won't go through and offer the non-deductible alternative.
- Known gap (followup, not this commit): the staged op's journal entry
  description doesn't yet carry the deltagare text. Until we add a
  `notes` field to gnubok_categorize_transaction, the audit trail
  lives in chat + agent_memory only.

TransactionInboxCard duplicate attachment indicator:
- Drop the FileCheck2 "open document" button from the trailing slot.
  TransactionAttachmentIndicator (Paperclip) next to the description
  already opens the underlag on click. Two icons doing the same thing
  was noise. Cleaned up the unused state (isOpeningDoc, hasAttachment,
  handleOpenAttachment) and dropped now-unused imports (FileCheck2,
  useToast).

Tests: 4112. Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(agent,nav): notes on verifikation + redesigned sidebar

Audit-trail notes for representation:
- gnubok_categorize_transaction gains an optional `notes` string.
  Threaded through stagePendingOperation → commitCategorizeTransaction →
  createTransactionJournalEntry, which now appends notes to the entry's
  description (capped at 500 chars). The verifikation an external auditor
  reads now carries deltagare + syfte directly — not just chat history /
  agent_memory.
- transaction-categorization prompt updated: representation flow now
  REQUIRES the agent to pass deltagare+syfte via the notes parameter.
  Without it the booking is non-deductible / personalkostnad per SKV.

DashboardNav redesign:
- Top section: flat, no header — Hem (/chat), Underlag (was
  Dokumentinkorg), Transaktioner, Granskning. Always visible; the inline
  badge on /pending shows the count when there are pending ops.
- Mid section: four collapsible dropdowns (Försäljning, Inköp,
  Redovisning, Personal). Each auto-expands when the active route lives
  inside it. KPI moved from main to Redovisning. Extension nav items
  (TIC workspace, etc.) fold into Redovisning.
- Bottom-left: new account popover (DropdownMenu, opens upward) holding
  CompanySwitcher, Inställningar, Hjälp, Support, Logga ut. Replaces
  the old top company-switcher card + the bottom Support/Logout block.
- Mobile drawer mirrors the new structure: top items as flat list,
  same four dropdown groups, separate "Tillägg" section when
  extensions exist, "Mitt konto" section at the bottom.
- i18n: invoice_inbox label renamed "Dokumentinkorg" → "Underlag"
  ("Documents" in en). New keys: mitt_konto, group_extensions.

Tests: 4112. Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(nav): unhide Leverantörer under Inköp

The /suppliers entry existed in navItems but was marked hidden — leftover
from when the supplier list lived elsewhere in the IA. Removing the
hidden flag puts Leverantörer in the Inköp dropdown alongside
Leverantörsfakturor.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(nav): CompanySwitcher back to top-left, user account moves bottom-left

The previous pass collapsed both concepts into the bottom popover. They
mean different things: the company is the org context everything below
operates against (top-of-sidebar, scannable); the user is the
account-holder (bottom-of-sidebar, where settings/logout live).

- (dashboard)/layout.tsx: fetch profiles.full_name alongside the
  existing identity queries; pass userName + userEmail into
  DashboardNav.
- DashboardNav: restore CompanySwitcher at the top of the sidebar
  (pre-redesign placement). Bottom-left popover trigger now shows the
  signed-in user's name + single-letter initial (accountInitial helper
  falls back to email's first char, then "?"). Popover header carries
  full name + email; items unchanged (Inställningar, Hjälp, Support,
  Logga ut). CompanySwitcher removed from inside the popover — nested
  dropdowns were awkward and the top placement is where it belongs.

Tests: 4112. Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(pending): trim the agent context strip

The row-level AgentContextStrip on /pending was rendering the model
name (eu.anthropic.claude-sonnet-4-6) and the full atoms array
(horizontal/swedish-vat, vertical/konsult-it, …) inline, which made
each row 60–80 chars of mostly-the-same metadata. Reviewers never
scan that text; they scan amounts and decide approve/reject.

Now the strip shows only the conversation deep-link
(Konversation #<short id>) — the one piece that's actually useful for
diving into context. Model + atoms remain available in agent_metadata
for debugging surfaces; they're just not in the list view.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent): shared ground rules + paragraph breaks after tool calls

Two regressions surfaced in real usage. Both are systemic.

Shared agent ground rules:
- /chat surface (general.help) was happily inventing four-digit BAS
  account numbers ("Debet 6212 - Molntjänster…", "Kredit 2614 - Ingående
  moms…") and proposing booking decisions on invoices it had never
  seen, with no follow-up questions about currency/scope/etc.
- transaction-categorization had those rules baked into its prompt;
  general-help / bokslut-step / invoice-draft / supplier-invoice-review
  / verifikation-draft / vat-review never inherited them.
- Extracted lib/agent/intents/shared-rules.ts with five cross-cutting
  rules: underlag first (check inbox + ask user to upload to
  Dokumentinkorgen when missing), ask follow-ups when ambiguous, never
  write four-digit BAS account numbers in chat (category names only),
  cite atoms / load skills (don't guess), check counterparty history
  before proposing.
- Injected renderAgentGroundRules() into all six intents above.
  transaction-categorization left alone — it has more detailed inline
  rules tied to its specific underlag-flow.

Paragraph break after tool calls:
- text_delta from the model often resumes after a tool call without a
  leading newline ("kategoriseras." → gnubok_query_journal runs → "Inget
  historik hittades…" appended directly). Markdown rendered the
  concatenation as one paragraph.
- AgentChat text_delta handler now inserts \n\n when (a) the buffer
  ends with text content, (b) the incoming delta starts with text
  content, (c) at least one tool call has run, and (d) the buffer
  doesn't already end with a blank line.

Tests: 4112. Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(nav): default-open dropdown groups; closing is per-user

Dropdowns started collapsed which meant first-time users had to open
each group to discover what's inside. Inverted the state: default open,
user can collapse, active route still forces a group open.

- manualExpanded → manualCollapsed (semantics flip)
- toggleGroup unchanged externally; flips the bit
- isGroupExpanded returns !manualCollapsed[g] || hasActiveChild

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(agent): rate-safe v1→v2 TIC upgrade, counterparty defaults, profile settings

Three pre-ship quality wins.

Rate-limit-safe TIC v2 upgrade:
- The /profile endpoint fans out to ~13 Lens calls; the account has a
  ~3000/mo ceiling. Force-refreshing every pre-v2 (v1) snapshot across
  the customer base would blow the budget.
- ensureTicSnapshot gains an `upgradeV1` flag. A cached snapshot still
  inside the 7-day window is re-fetched only when (a) the caller passes
  upgradeV1 AND (b) the snapshot is v1-shaped (missing the v2-only
  `statuses` key). Gated to the two agent-onboarding call sites — a
  deliberate, once-per-company action and the only consumer of the v2
  sections. Workspace + signup keep the natural 7-day staleness, so the
  v1→v2 migration is lazy and bounded to companies actually building an
  agent.

Known-counterparty defaults (shared-rules):
- Agent now proposes a sensible default for well-known counterparties
  instead of asking the same question monthly: Almi → lån, Tillväxtverket/
  Vinnova/EU-stöd → bidrag, Skatteverket → skatt/avgift or återbäring,
  Bolagsverket → avgift, Försäkringskassan → ersättning, EF private
  withdrawal → eget uttag. Stated as an assumption the user can correct,
  not a hard rule — underlag/history still wins.

Företagsprofil settings page:
- New /settings/agent-profile (Företagsprofil / "Company profile"):
  view + edit the agent's company profile after onboarding — assistant
  name + avatar, the profile summary the agent reasons from, and a
  read-only chip view of loaded specialities (atoms). Backed by the
  existing GET/PATCH /api/agent/profile.
- New GET /api/agent/atom-titles?ids= resolves atom slugs → human titles
  for the chips (registry is globally-readable reference data).
- Added to SettingsSidebar; i18n keys agent_profile (sv "Företagsprofil"
  / en "Company profile").

Note: /chat already redirects unverified users to / (chat layout guard),
and / renders WelcomeGate → /onboarding/agent. No redirect work needed.
AgentSetupBanner.tsx is orphaned dead code (WelcomeGate superseded it).

Tests: 4112. Build: green. Both new routes compile.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(nav,agent): Hem=Översikt + separate Assistent button; memory dedup

Nav restructure:
- "Hem" now points to / (Översikt dashboard) again, not /chat. The agent
  chat gets its own top-level nav entry "Assistent" (Sparkles icon) → /chat.
  Mobile bottom nav mirrors this (Hem / Assistent / Transaktioner).
- / restored to render DashboardContent (the Översikt) for built-agent
  users instead of redirecting to /chat. Users who haven't built their
  assistant yet still get WelcomeGate (the build-agent checklist); once
  verified, / shows the dashboard. Chat is reachable anytime via its nav
  entry. Restored main's dashboard data-fetch; added an agent_profiles
  verified_at probe to drive the WelcomeGate branch.
- i18n: nav.assistant ("Assistent" / "Assistant").

agent_memory dedup (gnubok_remember_fact):
- The agent re-remembers the same fact constantly (e.g. "Vercel = omvänd
  skattskyldighet" on every Vercel categorization), which would bloat
  agent_memory with paraphrases over months.
- Before insert, compare the incoming fact against the 300 most-recent
  active memories by word-set Jaccard similarity (lowercased, punctuation-
  stripped, stopwords dropped). A near-duplicate (≥0.82) is treated as
  already-known: bump its relevance toward the new score + refresh
  updated_at instead of writing a new row. Embedding-free, zero added
  latency beyond one bounded SELECT.

Tests: 4112. Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent,nav): företagsprofil=Bolagsuppgifter, avatar nav icon, dedupe greeting

Företagsprofil settings page (the right content this time):
- Replaced the agent atoms/summary panel with CompanyProfileView — a
  read-only "Bolagsuppgifter" view of the cached TIC company snapshot
  (name, org-nr, form, address, F-skatt/Moms/Arbetsgivare, SNI, bank,
  verksamhet, employees, latest financials, status traffic-lights,
  fiscal year, firmateckning, företrädare). Server component reads the
  companies.tic_snapshot column directly — no extension import, stays
  inside the core-build boundary.
- Route renamed /settings/agent-profile → /settings/company-profile.
  Removed the old AgentProfilePanel + the now-unused /api/agent/atom-titles
  endpoint.

"Assistent" nav icon = the agent's chosen avatar:
- DashboardNav reads agent identity from AgentSheetProvider and renders
  the onboarding-chosen avatar for the /chat ("Assistent") entry across
  desktop sidebar, mobile drawer, and mobile bottom nav. Falls back to
  the Sparkles glyph pre-onboarding (no avatar yet).

Nav cleanup:
- Dropped the beta badge from Underlag.
- Filtered the TIC workspace (/e/general/tic, "Företagsprofil") out of
  the nav — the same Bolagsuppgifter now lives under Inställningar →
  Företagsprofil, so it shouldn't appear in two places.

Doubled intake greeting fix:
- /chat/intake fires an invoke with no conversation_id, then swaps the
  URL to /chat/[id] the instant the `conversation` event lands — which
  can beat the greeting being persisted. /chat/[id] then hydrated with 0
  messages and, because the auto-fire guard keyed on (id && messages>0),
  fired a SECOND invoke on the same conversation → two greetings.
  Guard now keys on conversation-id presence alone: a set id means
  resume, never bootstrap. Closes the race.

Tests: 4112. Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent): paragraph-break-after-tool split words mid-stream

The earlier "insert \n\n when text resumes after a tool call" heuristic
re-evaluated on EVERY text_delta (any delta not starting/ending with
whitespace, once a tool had run). Streaming deltas arrive in sub-word
chunks, so it injected breaks between fragments of the same word:
"minnes\n\nno\n\nterna", "kund\n\nrep\n\nresentation".

Replace the per-delta heuristic with a consume-once ref:
- tool_use sets breakBeforeNextTextRef = true
- the next text_delta consumes it: prepends \n\n exactly once (only when
  the buffer has content, doesn't already end in whitespace, and the
  delta doesn't start with whitespace), then clears the flag

So the break fires once per tool→text resume, never mid-word.

Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent): much shorter replies, representation headcount + VAT cap, dot separator

Brevity (system-prompt Svarsformat — affects every reply):
- Hard "korthet är regel nummer ett": aim for 2-4 sentences, lead with
  the answer/action, no warm-up ("Här är vad som gäller…"), don't derive
  VAT in prose, don't restate what the approval card shows, one question
  at a time. The agent was writing textbook-length essays.

Representation rule now in shared-rules (so verifikation-draft, vat-review,
etc. all get it — previously only transaction-categorization had it, which
is why the verifikation flow guessed 25% VAT and skipped the cap):
- Require ANTAL deltagare (headcount), not just one name — the moms
  deduction is per person (underlag cap 300 kr/person ex moms).
- Use the receipt's ACTUAL VAT rate (usually 12% on food), never assume
  25%.
- Meal representation isn't income-tax deductible (post-2017); whole cost
  booked as non-deductible representation.

Verifikation description separator:
- createTransactionJournalEntry appended notes with an em-dash
  ("Utlägg Eatnam — Deltagare:…"), violating house style. Switched to a
  middle dot " · ". journal_entries has no separate notes column — the
  description IS the BFL verifikationstext / audit field, so deltagare +
  syfte correctly live there.

Tests: 4112. Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(settings): tidy Bolagsuppgifter — no status colours, clean firmateckning

From first-look feedback on the Företagsprofil page:

- Status: dropped the coloured traffic-light badges (red/yellow/green).
  Per the design system semantic colour is data-only, never chrome, so
  status now renders as plain label + date. Also filtered to dated
  entries only — Bolagsverket emits flags like "Har aldrig varit verksam"
  with no date that read as noise next to the real status. Ceased status
  gets muted destructive text (the one chrome colour the system keeps).

- Firmateckning: the source text carries ">" list markers and crams
  several rules onto one line, and repeats "Firman tecknas av styrelsen"
  across rows. cleanSignatory() strips the markers, normalises whitespace,
  splits run-on "Firman tecknas …" clauses onto separate lines, and the
  render dedupes — so each rule reads as its own sentence.

Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(mcp): inbox items expose all terminal links + processed flag

The Eatnam receipt was booked against its bank transaction (so the inbox
row had matched_transaction_id + created_journal_entry_id set), yet the
agent reported it as loose/unmatched and a duplicate risk. Root cause:
gnubok_list_inbox_items only selected and returned matched_supplier_id +
created_supplier_invoice_id — the supplier-invoice path. The
transaction-match and direct-journal-entry paths were invisible, so any
receipt cleared via /transactions looked unprocessed.

- list_inbox_items now selects + returns matched_transaction_id and
  created_journal_entry_id alongside the supplier fields, plus a derived
  `processed` boolean (true when ANY of the three terminal links is set).
- New unprocessed_only=true input filters to items with no terminal link
  — the "what still needs handling" view that prevents the agent from
  flagging already-booked docs as duplicates. (Fetches a wider window
  then filters client-side so limit applies post-filter.)
- Description updated to document the processed semantics, within the
  280-char tool-description budget.

The DB linkage itself already worked: /transactions attach-document sets
matched_transaction_id, and commitCategorizeTransaction stamps
created_journal_entry_id. This was purely a read/surface gap.

Tests: 4112 (+ MCP description guard). Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(mcp): repair stage-but-never-commit tools + consolidate tool surface

- post_annual_depreciation AND reverse_entry were never in the pending_operations operation_type CHECK, so both staged then died with check_violation at INSERT. Add the CHECK migration, a commitPostAnnualDepreciation executor (reusing commitAnnualPostings), risk tier, and the PendingOperationType union member.
- Salary tools de-risked: calculate_salary_run calls runSalaryCalculation() directly (no self-fetch/forged cookie); create_salary_run uses a transactional create-run helper with compensating delete; generate_agi actually generates + persists the declaration.
- import_sie parses + validates at stage time with a content-rich preview (company, fiscal year, voucher/account counts, balance) instead of a blind byte count.
- batch-match-invoices passed user.id where companyId was expected (silently matched zero).
- VAT report+widget merged behind render_ui; gnubok_search_tools ranks by relevance; gnubok_feedback readOnlyHint corrected; tools/list instruction text fixed; income decision-tree + GL/query_journal cross-refs added.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(agent): load skill atom bodies from the DB so they survive the build

Skill bodies were read from disk at runtime (.claude/skills/**/SKILL.md); on Vercel the dynamic readFile path isn't traced into the lambda and on Docker .claude/ is excluded, so atoms loaded EMPTY in production — a despecialized agent. Inline the bodies into agent_atom_registry instead:
- Migration adds body + mcp_exposed columns; a build-time generator (scripts/generate-skill-bodies.ts) emits a deterministic dollar-quoted seed migration with a content-hash manifest + --check CI guard.
- Read sites (mcp-server atoms.ts, chat system-prompt.ts, composer prewarm) read body from the DB, with a dev-only disk fallback. mcp_exposed curates which atoms the MCP exposes (swarm-* never become atoms).
- The seed script + generator share scripts/lib/atom-discovery.ts; estimated_tokens now reflects SKILL.md only.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(agent): safe the in-app assistant — gating, FAB de-confliction, rate limit, friendly errors

- Hide all agent entry points until verified_at: the Assistent nav tab (sidebar + mobile) and the agent-memory settings tab now match the floating FAB's gate.
- FAB de-confliction: /kpi -> kpi.explain and /bookkeeping/year-end -> bokslut.step so the floating button opens the SAME assistant as the page button (no two-agents-on-one-page).
- Generous per-user rate limit (30/min, 1000/day) on /api/agent/invoke, /onboarding/stream, /composer via a new agent_rate_counters table + check_and_increment_agent_quota RPC; fails open. Bounds runaway Bedrock spend without touching normal users.
- Friendly errors: Bedrock 429/timeout/5xx normalized to Swedish (friendlyModelError) in run-turn + the invoke route; the chat client surfaces the server's friendly message instead of a raw HTTP status.
- /chat/new validates ?intent= against the registry so bad deep-links fall back to general.help instead of rendering a broken-looking error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent): keep /chat read-only — redirect categorization + swap the "categorize" suggestion for a VAT-report question

general.help (the /chat assistant) is read-only, but it still gave per-transaction bokföringsförslag in prose and asked "godkänner du dessa?" — an analysis the user can't act on (no write tool, no per-tx underlag). Strengthen the prompt to redirect categorization/bokföring to the per-transaction flow (open the transaction -> "Fråga om denna transaktion", where the agent sees the underlag and stages a real ApprovalCard); a short overview is still allowed. Add a guard test locking in no-write-tools + the redirect language. Swap the /chat empty-state "Hjälp mig kategorisera" chip (which lured users into exactly this dead-end) for a VAT-report question the read-only assistant can actually answer.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(pending): declutter the review queue rows + header

Fold the conversation deep-link onto the actor label (drop the separate
"Konversation #xxxx" strip and its icon), hide the quick-pick when there's
only one operation type (it duplicated "Markera alla"), and drop the "(0)"
from the disabled bulk-approve button.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(vat): enhance VAT handling by integrating document validation and improving error messaging

* feat(settings): add assistant knowledge surface + consolidate settings tabs

Expose the agent's skill atoms (agent_atom_registry) in a read-only surface
beside the existing memory view, and tighten the settings tab bar from 14 to
10 tabs.

- New GET /api/agent/skills + AgentSkillsPanel: lists active, mcp_exposed
  atoms grouped by tier (Kärnkompetens / bransch / bolagssituation), flags
  which are active for the company from agent_profiles, and lazy-loads each
  SKILL.md body on expand.
- New /settings/assistant tab with a Minne/Kompetens toggle (?view=skills);
  /settings/agent-memory and /settings/agent-skills redirect into it.
- Merge Företagsprofil (TIC snapshot) into the Företag tab via
  CompanyProfileSection; /settings/company-profile redirects.
- Merge Skatteverket-anslutningen into the Skatt tab — OAuth returnTo and the
  callback toast now target /settings/tax; /settings/skatteverket redirects.
- Drop the Säkerhetsbackup tab (already under Importera/Exportera).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(inbox): keep booked underlag out of the unmatched queue + widen match window

- categorize: after booking an inbox underlag onto a verifikat, backfill the
  inbox row's matched_transaction_id + created_journal_entry_id so it stops
  showing as unmatched (mirrors the /attach-document paperclip path).
- TransactionMatchPicker: bias the candidate window forward (60d before →
  180d after the invoice date) so late payments aren't dropped before scoring,
  and widen the ranking date tolerance to 120d so the true match floats to the
  top instead of collapsing to "Svag match". Fix "okatigoriserade" typo.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* wip: bundle in-progress branch work + agent onboarding chat optimizations

Captures the uncommitted work-in-progress on this branch so it lives on the
remote. Heterogeneous changeset — bundled as one commit since the work was
already entangled across files.

Headline change in this commit (from this session):
- Remove the double interview in agent onboarding. Phase B's verification-
  question form stepper is gone — the Phase C chat (onboarding.intake) now
  owns the entire interview and reads the composer's verification_questions
  server-side as its question bank.
- ReviewCard collapses from 3 steps to 2 (meet → review-and-confirm) with
  value-first ordering: profile + "vad jag kan hjälpa dig med" + facts +
  optional seed note. CTA reads "Möt {namn}" to signal the chat follows.
- ChatIntakeStarter handoff subcopy updated to match reality (assistant
  greets first; user can leave anytime).
- Stamp agent_profiles.intake_completed_at server-side in
  app/api/agent/invoke/route.ts on the first user-typed reply in any
  onboarding.intake conversation (idempotent IS NULL guard, best-effort).
  Closes the previously dead-write column and unlocks the opportunistic-
  follow-up hook the migration anticipated.

Plus in-progress branch work being carried forward (not introduced here):
agent runtime + intent prompts, composer + atom-discovery scripts, MCP
server skills surface, onboarding flow components, dashboard/inbox tweaks,
two new agent_atom_registry migrations, additional agent-chat tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(agent): drop inline "Fråga assistenten" affordances — rely on the FAB

The bottom-right "Fråga {namn}" FAB (AgentTrigger) is already route-aware
and picks the right intent per page, so duplicating it as inline page-
header buttons and empty-state links is noise. Removed:

- EmptyState `agentHelp` link ("Eller fråga {namn} hur du kommer igång")
  + the AgentHelpLink component + agent_default_name/agent_ask_link i18n
  keys + the agentHelp props on EmptyInvoices/EmptyCustomers/EmptyTransactions.
- AgentSparkleButton on /bookkeeping (verifikation.draft) and /kpi
  (kpi.explain) page headers.

The FAB stays — when verified, it appears on those routes and routes to
the right intent automatically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent): gate the last two ungated "Fråga assistenten" affordances

Both surfaces previously called useAgentSheet directly without checking
identity.isVerified, so they appeared pre-onboarding (everywhere else the
FAB / sparkle buttons / /chat / Assistent nav are all gated on verified_at).

- Settings page header: remove the "Fråga {namn}" pill entirely. The FAB
  covers /settings routes route-aware (settings.help) — no need for a
  duplicate inline trigger.
- Invoice inbox transaction picker: hide the "Fråga assistenten" button
  when the agent isn't built. Done at the parent (InvoiceInboxWorkspace)
  by passing onAskAssistant only when identity.isVerified is true; the
  child renders the button only when the callback is present.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(tic,onboarding,agent): single-call TIC lookup + director-aware narrative voice

- TIC: collapse the company lookup from 6 endpoint calls to 1
  (search-public already exposes sniCodes, bank accounts, emails, phones,
  and registration flags). Derive fiscal-year MM-DD from
  mostRecentFinancialSummary; newly-registered companies fall through to
  the client's first-year defaults.
- Onboarding: BankID picker no longer auto-provisions companies. Every
  pick routes through the wizard with orgnr (and entity_type via the
  CompanyRoles match) prefilled; F-skatt/VAT/address get confirmed in
  steps 2-4 instead of being auto-fetched. createCompanyFromOnboarding
  reuses CompanyLookupResult and adds a defensive top-level catch so
  server-action errors surface to the UI instead of being redacted.
- Agent composer: loadUserDirectorship() checks BankID CompanyRoles for
  a director-like position (ceo/boardMember/chairman/externalSignatory,
  active) before the narrative uses second-person ownership voice
  ("Du driver…"); unknown users get neutral third-person voice so we
  never put ownership words in the user's mouth.

Tests cover loadUserDirectorship, narrative voice, tic-fetch path,
onboarding page, and updated TIC client + lookup/profile suites.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tic): extend agent-onboarding TIC budget to 10s + backfill stranded org_numbers

The 5s TIC fetch timeout aborted client-side before the upstream Lens
fan-out (~13 calls) could complete, but the in-flight upstream calls
still counted against quota — actions.ts already documents ~530 wasted
calls from this in May. Same bug still applied to the agent-onboarding
stream path. Adds an optional `timeoutMs` to `ensureTicSnapshot` so
deliberate wait-screen callers (agent onboarding stream) can run with
10s while background/dev callers stay on the conservative 5s default.

Page-level server fetch (page.tsx) intentionally stays at 5s to avoid
blocking TTFB without a visible progress affordance.

Backfill migration mirrors `company_settings.org_number` to
`companies.org_number` for the 105 cases where it's safe (after dedup
+ conflict filtering). 56 of those are on active companies — unblocks
duplicate guards, SIE/SRU exports, and TIC fallback chain. Zero TIC
API calls — pure data move. Idempotent.

Also sweeps a pre-existing SSRF guard on the stream route's origin
derivation that was sitting unstaged in the working tree — it lives in
the same diff hunks as the TIC budget change and couldn't be split cleanly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* wip: bundle in-progress branch work

Sweep up uncommitted agent/MCP/RLS work-in-progress so the branch is fully
backed up to origin. Not reviewed in detail — committed as-is to preserve
working state alongside the TIC fixes in the previous commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent): tag the "Bygg din bokföringsassistent" CTA as Beta

Adds a Beta badge next to the assistant-setup heading on the dashboard
banner, dashboard inline card, and onboarding checklist row. Also drops
the stale "Gratis i 30 dagar" subline from the dashboard card.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(build,migrations): PendingOperationType salary ops + resolve migration version collisions

PR #584 went red on three things:

1. core-only build / Vercel: `lib/pending-operations/commit.ts:2666` switched on
   'create_salary_run' and 'generate_agi' but `PendingOperationType` was missing
   both literals. Add them to the union.

2. Supabase preview: migration version 20260526120000 collided with main's
   newly-merged 20260526120000_fix_replace_sie_import_hard_delete.sql.
   Bump the branch's pair to 20260526120050 / 20260526120051 — still ahead of
   20260526120100_restvardeavskrivning so ordering is preserved.

3. 20260527170000 was used twice on this branch
   (_agent_rls_with_check + _journal_entry_no_doc_required). Bump the second
   to 20260527170100 so the pair stays orderable and Supabase doesn't choke
   on the duplicate schema_migrations PK.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ci): reword comment so core-only guard stops flagging it

The "Check no core imports from extensions" step greps for the literal
\`from '@/extensions/\` across lib/, app/api/, components/. A comment in
lib/agent/composer/tic-fetch.ts quoted the exact pattern verbatim to
explain *why* the file does a self-fetch instead of importing the TIC
extension directly — which the grep matched even though no actual
import exists.

Rewrite the line to keep the same meaning without the literal pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Emil <emilmattsson14@gmail.com>
2026-05-28 11:27:01 +02:00

1936 lines
73 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client'
import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
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 { useToast } from '@/components/ui/use-toast'
import {
Inbox,
Upload,
Mail,
FileText,
Copy,
RotateCcw,
Trash2,
Check,
Loader2,
AlertTriangle,
ArrowRight,
Plus,
Link2,
Search,
Circle,
X,
} from 'lucide-react'
import Link from 'next/link'
import { cn, formatCurrency } from '@/lib/utils'
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
import type { InvoiceExtractionResult } from '@/types'
import BookDirectlyDialog from '@/components/extensions/general/BookDirectlyDialog'
import TransactionMatchPicker from '@/components/inbox/TransactionMatchPicker'
import { useAgentSheet } from '@/components/agent/AgentSheetProvider'
type AccountingMethod = 'accrual' | 'cash'
// ── Types ────────────────────────────────────────────────────
interface InboxItem {
id: string
status: 'received' | 'error'
source: 'email' | 'upload'
created_at: string
email_from: string | null
email_subject: string | null
email_received_at: string | null
document_id: string | null
extracted_data: InvoiceExtractionResult | null
matched_supplier_id: string | null
matched_transaction_id: string | null
created_supplier_invoice_id: string | null
created_journal_entry_id: string | null
error_message: string | null
// True when AI extraction was skipped — either because the upload caller
// passed skip_extraction=true (MCP/agent path) or because the server's
// page-count gate skipped a PDF above the auto-extract limit (issue #553).
// Distinct from status='error' (extraction failed) and from extracted_data
// having empty fields (extraction ran but found nothing).
extraction_skipped: boolean
// Set client-side only while a manual upload is in flight. Replaced by a
// real server-side row once the AI extraction completes.
isPlaceholder?: boolean
fileName?: string
}
interface InboxAddress {
address: string
local_part: string
status: string
}
// ── Helpers ──────────────────────────────────────────────────
function timeAgo(iso: string): string {
const ms = Date.now() - new Date(iso).getTime()
const min = Math.floor(ms / 60000)
if (min < 1) return 'nyss'
if (min < 60) return `${min} min sedan`
const h = Math.floor(min / 60)
if (h < 24) return `${h} h sedan`
const d = Math.floor(h / 24)
if (d < 30) return `${d} d sedan`
return new Date(iso).toLocaleDateString('sv-SE')
}
function pickAmount(item: InboxItem): number | null {
return item.extracted_data?.totals?.total ?? null
}
function pickCurrency(item: InboxItem): string {
return item.extracted_data?.invoice?.currency ?? 'SEK'
}
function pickSupplierName(item: InboxItem): string | null {
return item.extracted_data?.supplier?.name ?? null
}
// Lifecycle stage of an inbox item. Single source of truth shared by the list
// filter, the count pills, and the row icons so they never drift apart.
//
// Precedence mirrors the FieldsRail: a booked item (supplier invoice OR a
// direct journal entry) is done and drops out of the active inbox. A
// matched-but-unbooked item is "linked" — it STAYS in the inbox as its own
// category because the bank payment still needs booking (a document attached
// to a transaction is not the same as a booked one). An extraction failure is
// "error"; everything else needs a first action.
type InboxStatus = 'needs_action' | 'linked' | 'booked' | 'error'
function deriveInboxStatus(item: InboxItem): InboxStatus {
if (item.created_supplier_invoice_id || item.created_journal_entry_id) return 'booked'
if (item.matched_transaction_id) return 'linked'
if (item.status === 'error') return 'error'
return 'needs_action'
}
// ── Skeleton ─────────────────────────────────────────────────
// Mirrors the live layout (top bar + 3-pane card) so the transition from
// the route-level loading.tsx to data-loaded content has no visible reflow.
// Keep in sync with app/(dashboard)/e/[sector]/[slug]/loading.tsx.
function WorkspaceSkeleton() {
return (
<div className="h-[calc(100vh-1px)] p-4 md:p-6">
<div className="h-full flex flex-col rounded-lg border bg-card overflow-hidden">
<header className="flex items-center justify-between gap-4 border-b px-4 py-2.5">
<div className="flex items-center gap-2 min-w-0">
<Skeleton className="h-4 w-4 shrink-0" />
<Skeleton className="h-4 w-32 shrink-0" />
<Skeleton className="hidden md:block h-3 w-56" />
</div>
<Skeleton className="h-8 w-28 shrink-0" />
</header>
<div className="flex-1 grid grid-cols-1 md:grid-cols-[240px_minmax(0,1fr)_320px] lg:grid-cols-[280px_minmax(0,1fr)_340px] min-h-0">
<aside className="border-r overflow-hidden bg-muted/20 pt-3">
<div className="px-3 pb-3 space-y-2 border-b">
<Skeleton className="h-8 w-full" />
<div className="flex flex-wrap gap-1">
<Skeleton className="h-5 w-10 rounded-full" />
<Skeleton className="h-5 w-24 rounded-full" />
<Skeleton className="h-5 w-20 rounded-full" />
<Skeleton className="h-5 w-8 rounded-full" />
</div>
</div>
<ul>
{Array.from({ length: 7 }).map((_, i) => (
<li key={i} className="border-b px-3 py-2 flex flex-col gap-1.5">
<div className="flex items-center gap-2">
<Skeleton className="h-3 w-3 shrink-0" />
<Skeleton className="h-3.5 flex-1 max-w-[180px]" />
</div>
<div className="flex items-center justify-between gap-2">
<Skeleton className="h-3 w-16" />
<Skeleton className="h-3 w-12" />
</div>
</li>
))}
</ul>
</aside>
<main className="overflow-hidden bg-muted/10 hidden md:block" />
<aside className="border-l overflow-hidden hidden md:block" />
</div>
</div>
</div>
)
}
// ── Main component ───────────────────────────────────────────
export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
const { toast } = useToast()
const fileInputRef = useRef<HTMLInputElement | null>(null)
const { openAgentSheet, identity } = useAgentSheet()
const [items, setItems] = useState<InboxItem[]>([])
const [isLoading, setIsLoading] = useState(true)
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
// booked underlag drop out of the default view while attached-but-unbooked
// ones stay visible.
const [filter, setFilter] = useState<'todo' | 'linked' | 'booked' | 'error' | 'all'>('todo')
const [searchTerm, setSearchTerm] = useState('')
// Bulk selection. Items linked to a supplier invoice are skipped at delete
// time (server returns 409); we still allow them to be selected so the
// user can see the "X skipped" toast and learn the rule.
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [isBulkDeleting, setIsBulkDeleting] = useState(false)
// Onboarding card visibility. Hides when all three steps are complete or
// the user dismissed it. Persisted to localStorage so refresh doesn't
// revive a dismissed card.
const [onboardingDismissed, setOnboardingDismissed] = useState(false)
// Multi-file upload progress. Null when no queue is running. Reflects the
// sequential progress through a batch ({ total, done }) so the button can
// show "Laddar X av N…".
const [uploadQueue, setUploadQueue] = useState<{ total: number; done: number } | null>(null)
const [selected, setSelected] = useState<InboxItem | null>(null)
const [docUrl, setDocUrl] = useState<string | null>(null)
const [docMime, setDocMime] = useState<string | null>(null)
const [inboxAddress, setInboxAddress] = useState<InboxAddress | null>(null)
const [isUploading, setIsUploading] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [isRotating, setIsRotating] = useState(false)
const [isDragging, setIsDragging] = useState(false)
const [bookDirectOpen, setBookDirectOpen] = useState(false)
// Match-to-bank-transaction picker (opens when user clicks "Matcha mot
// transaktion" on an unmatched inbox item).
const [matchPickerOpen, setMatchPickerOpen] = useState(false)
// Cash method users see "Bokför direkt" as the primary CTA; accrual users
// see "Skapa leverantörsfaktura". Defaults to 'accrual' until we've read
// the company settings so we don't flicker the CTA order on first paint.
const [accountingMethod, setAccountingMethod] = useState<AccountingMethod>('accrual')
// ── Data loading ───────────────────────────────────────────
const fetchItems = useCallback(async () => {
try {
const res = await fetch('/api/extensions/ext/invoice-inbox/items?limit=500')
const json = await res.json()
if (res.ok) setItems(json.data?.items ?? [])
} catch (err) {
console.error('[invoice-inbox] fetchItems failed:', err)
} finally {
setIsLoading(false)
}
}, [])
const fetchInboxAddress = useCallback(async () => {
try {
const res = await fetch('/api/extensions/ext/invoice-inbox/inbox/address')
if (res.ok) {
const { data } = await res.json()
setInboxAddress(data)
}
} catch {
// 404 / 503 are expected when no address provisioned yet
}
}, [])
useEffect(() => {
fetchItems()
fetchInboxAddress()
// Resolve the company's bookkeeping method — drives CTA hierarchy.
fetch('/api/settings')
.then((r) => (r.ok ? r.json() : null))
.then((body) => {
const method = body?.data?.accounting_method
if (method === 'cash' || method === 'accrual') {
setAccountingMethod(method)
}
})
.catch(() => { /* keep 'accrual' default */ })
}, [fetchItems, fetchInboxAddress])
// Read the onboarding-dismissed flag from localStorage after mount
// (SSR-safe — no window access during initial render).
useEffect(() => {
if (typeof window === 'undefined') return
try {
setOnboardingDismissed(
window.localStorage.getItem('gnubok.inbox.onboarding.dismissed') === '1'
)
} catch {
// private browsing — keep default (show card)
}
}, [])
const handleDismissOnboarding = useCallback(() => {
try {
window.localStorage.setItem('gnubok.inbox.onboarding.dismissed', '1')
} catch {
// ignore; in-memory state is enough for this session
}
setOnboardingDismissed(true)
}, [])
// Onboarding card visibility — derived from real progress so a user who
// already has a working inbox flow never sees the guide. Once they finish
// all three steps, the card auto-hides on next render.
const hasInboxAddress = !!inboxAddress
const hasAnyItem = items.length > 0
const hasResolvedItem = items.some(
(it) =>
!!it.created_supplier_invoice_id ||
!!it.matched_transaction_id ||
!!it.created_journal_entry_id
)
const showOnboarding =
!onboardingDismissed && !(hasInboxAddress && hasAnyItem && hasResolvedItem)
// ── List filter + search (client-side over the fetched list) ─
// Per-status counts for the filter pills. Computed once over the full list.
const statusCounts = useMemo(() => {
const counts = { todo: 0, linked: 0, booked: 0, error: 0, all: items.length }
for (const item of items) {
const status = deriveInboxStatus(item)
if (status !== 'booked') counts.todo += 1
if (status === 'linked') counts.linked += 1
if (status === 'booked') counts.booked += 1
if (status === 'error') counts.error += 1
}
return counts
}, [items])
// Pills, in order. The error pill only appears when there's something errored
// (or it's the active filter) — keeps the happy-path inbox uncluttered.
const pills = useMemo(() => {
const list: { key: typeof filter; label: string; count: number }[] = [
{ key: 'todo', label: 'Att göra', count: statusCounts.todo },
{ key: 'linked', label: 'Kopplade', count: statusCounts.linked },
{ key: 'booked', label: 'Bokförda', count: statusCounts.booked },
]
if (statusCounts.error > 0 || filter === 'error') {
list.push({ key: 'error', label: 'Fel', count: statusCounts.error })
}
list.push({ key: 'all', label: 'Alla', count: statusCounts.all })
return list
}, [statusCounts, filter])
const filteredItems = useMemo(() => {
const term = searchTerm.trim().toLowerCase()
return items.filter((item) => {
// Status filter. "todo" is the active inbox — everything except booked.
const status = deriveInboxStatus(item)
if (filter === 'todo' && status === 'booked') return false
if (filter === 'linked' && status !== 'linked') return false
if (filter === 'booked' && status !== 'booked') return false
if (filter === 'error' && status !== 'error') return false
// 'all' → no status narrowing
// Search filter — supplier name, email subject/from, placeholder filename
if (term === '') return true
const haystack = [
item.extracted_data?.supplier?.name,
item.email_subject,
item.email_from,
item.fileName,
]
.filter((v): v is string => !!v)
.join(' ')
.toLowerCase()
return haystack.includes(term)
})
}, [items, filter, searchTerm])
// ── Selection ──────────────────────────────────────────────
const handleSelect = useCallback(async (id: string) => {
setSelectedId(id)
setSelected(null)
setDocUrl(null)
setDocMime(null)
// 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
// + the preview content update are enough feedback that the tap took.
try {
const res = await fetch(`/api/extensions/ext/invoice-inbox/items/${id}`)
const json = await res.json()
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
}
}
} catch (err) {
toast({
title: 'Kunde inte ladda dokumentet',
description: err instanceof Error ? err.message : 'Försök igen.',
variant: 'destructive',
})
}
}, [toast])
// ── Upload ─────────────────────────────────────────────────
// `autoSelect`: jump the detail pane to the new placeholder/row. Useful
// for a one-off drop (user expects to see what just landed). Harmful in
// a multi-file queue (selection yanks around as each file processes).
const uploadFile = useCallback(async (
file: File,
options: { autoSelect: boolean } = { autoSelect: true },
) => {
// Optimistic placeholder — gives the user an immediate visual response
// for the 3–8s while extraction runs. Removed once the real row arrives.
const tempId = `temp-${crypto.randomUUID()}`
const placeholder: InboxItem = {
id: tempId,
status: 'received',
source: 'upload',
created_at: new Date().toISOString(),
email_from: null,
email_subject: null,
email_received_at: null,
document_id: null,
extracted_data: null,
matched_supplier_id: null,
matched_transaction_id: null,
created_supplier_invoice_id: null,
created_journal_entry_id: null,
error_message: null,
extraction_skipped: false,
isPlaceholder: true,
fileName: file.name,
}
setItems((prev) => [placeholder, ...prev])
if (options.autoSelect) {
setSelectedId(tempId)
setSelected(placeholder)
}
setIsUploading(true)
try {
const fd = new FormData()
fd.append('file', file)
const res = await fetch('/api/extensions/ext/invoice-inbox/upload', {
method: 'POST',
body: fd,
})
const json = await res.json()
if (!res.ok) throw new Error(json.error ?? 'Uppladdning misslyckades')
if (json.data?.extraction_skipped) {
const pages = json.data?.page_count
toast({
title: 'Dokument uppladdat',
description: pages
? `Stort dokument (${pages} sidor) — AI-tolkning skippad. Du kan koppla det till en transaktion eller skapa leverantörsfaktura manuellt.`
: 'AI-tolkning skippad. Du kan koppla dokumentet till en transaktion eller skapa leverantörsfaktura manuellt.',
})
} else {
toast({ title: 'Dokument uppladdat', description: file.name })
}
setItems((prev) => prev.filter((it) => it.id !== tempId))
await fetchItems()
if (options.autoSelect && json.data?.inbox_item_id) {
await handleSelect(json.data.inbox_item_id)
}
} catch (err) {
setItems((prev) => prev.filter((it) => it.id !== tempId))
if (options.autoSelect) {
setSelectedId((prev) => (prev === tempId ? null : prev))
setSelected((prev) => (prev?.id === tempId ? null : prev))
}
toast({
title: 'Uppladdning misslyckades',
description: err instanceof Error ? err.message : 'Försök igen.',
variant: 'destructive',
})
} finally {
setIsUploading(false)
}
}, [fetchItems, handleSelect, toast])
// Sequential queue — running multiple extractions concurrently would
// hammer pdfjs on slow boxes. Per-file placeholder rows + the queue
// counter on the upload button surface progress.
const uploadFiles = useCallback(async (files: File[]) => {
if (files.length === 0) return
if (files.length === 1) {
// Single-file drop: keep the historic behavior of jumping the detail
// pane to the new item. Skip the queue counter — it would just flash.
await uploadFile(files[0], { autoSelect: true })
return
}
setUploadQueue({ total: files.length, done: 0 })
try {
for (const file of files) {
await uploadFile(file, { autoSelect: false })
setUploadQueue((q) => (q ? { ...q, done: q.done + 1 } : null))
}
} finally {
setUploadQueue(null)
}
}, [uploadFile])
const handleFileInputChange = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files ?? [])
if (files.length > 0) await uploadFiles(files)
if (fileInputRef.current) fileInputRef.current.value = ''
}, [uploadFiles])
const handleDrop = useCallback(async (e: React.DragEvent) => {
e.preventDefault()
setIsDragging(false)
const files = Array.from(e.dataTransfer.files ?? [])
if (files.length > 0) await uploadFiles(files)
}, [uploadFiles])
// ── Delete ─────────────────────────────────────────────────
const handleDelete = useCallback(async (id: string) => {
if (!confirm('Ta bort dokumentet ur inkorgen?')) return
setIsDeleting(true)
try {
const res = await fetch(`/api/extensions/ext/invoice-inbox/items/${id}`, {
method: 'DELETE',
})
const json = await res.json()
if (!res.ok) throw new Error(json.error ?? 'Kunde inte ta bort')
toast({ title: 'Borttagen' })
if (selectedId === id) {
setSelectedId(null)
setSelected(null)
}
await fetchItems()
} catch (err) {
toast({
title: 'Kunde inte ta bort',
description: err instanceof Error ? err.message : 'Försök igen.',
variant: 'destructive',
})
} finally {
setIsDeleting(false)
}
}, [fetchItems, selectedId, toast])
const toggleSelected = useCallback((id: string) => {
setSelectedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}, [])
const clearSelection = useCallback(() => setSelectedIds(new Set()), [])
const handleBulkDelete = useCallback(async () => {
if (selectedIds.size === 0) return
if (!confirm(`Ta bort ${selectedIds.size} poster ur inkorgen?`)) return
// Skip items that the server would 409 on, surface the count to the user.
const targets = items.filter((it) => selectedIds.has(it.id))
const deletable = targets.filter(
(it) => !it.created_supplier_invoice_id && !it.created_journal_entry_id
)
const skipped = targets.length - deletable.length
setIsBulkDeleting(true)
try {
const results = await Promise.allSettled(
deletable.map((it) =>
fetch(`/api/extensions/ext/invoice-inbox/items/${it.id}`, { method: 'DELETE' })
.then(async (res) => {
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'fail')
})
)
)
const failed = results.filter((r) => r.status === 'rejected').length
const succeeded = deletable.length - failed
const parts: string[] = []
if (succeeded > 0) parts.push(`${succeeded} borttagna`)
if (skipped > 0) parts.push(`${skipped} kopplade till leverantörsfaktura — hoppade över`)
if (failed > 0) parts.push(`${failed} misslyckades`)
toast({
title: 'Bulkborttagning klar',
description: parts.join(' · '),
variant: failed > 0 ? 'destructive' : 'default',
})
clearSelection()
// If the currently-selected item was deleted, clear the rail.
if (selectedId && deletable.some((it) => it.id === selectedId)) {
setSelectedId(null)
setSelected(null)
}
await fetchItems()
} finally {
setIsBulkDeleting(false)
}
}, [selectedIds, items, selectedId, fetchItems, toast, clearSelection])
// ── 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
setIsRotating(true)
try {
const res = await fetch('/api/extensions/ext/invoice-inbox/inbox/rotate', {
method: 'POST',
})
const json = await res.json()
if (!res.ok) throw new Error(json.error ?? 'Rotation misslyckades')
setInboxAddress(json.data)
toast({ title: 'Ny adress skapad', description: json.data.address })
} catch (err) {
toast({
title: 'Rotation misslyckades',
description: err instanceof Error ? err.message : 'Försök igen.',
variant: 'destructive',
})
} finally {
setIsRotating(false)
}
}, [toast, inboxAddress])
// ── Render ─────────────────────────────────────────────────
if (isLoading) return <WorkspaceSkeleton />
return (
<div
className="min-h-[calc(100vh-1px)] xl:h-[calc(100vh-1px)] p-4 md:p-6"
onDragOver={(e) => { e.preventDefault(); if (!isDragging) setIsDragging(true) }}
onDragLeave={(e) => {
// only clear when leaving the workspace itself, not children
if (e.currentTarget === e.target) setIsDragging(false)
}}
onDrop={handleDrop}
>
<div className="xl:h-full flex flex-col rounded-lg border bg-card xl:overflow-hidden shadow-sm">
{/* Top bar */}
<header className="flex items-center justify-between gap-4 border-b px-4 py-2.5 flex-wrap">
<div className="flex items-center gap-2 min-w-0">
<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"
>
<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>
</>
) : (
<Button
variant="outline"
size="sm"
onClick={handleRotateAddress}
disabled={isRotating}
className="ml-2 shrink-0 h-7 text-xs"
>
{isRotating ? (
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
) : (
<Mail className="h-3.5 w-3.5 mr-1.5" />
)}
Aktivera inkorgsadress
</Button>
)}
</div>
<div className="flex items-center gap-2 shrink-0">
<input
ref={fileInputRef}
type="file"
multiple
accept="application/pdf,image/jpeg,image/png,image/heic,image/heif,image/webp"
className="hidden"
onChange={handleFileInputChange}
/>
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
disabled={isUploading}
>
{isUploading ? (
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
) : (
<Plus className="h-3.5 w-3.5 mr-1.5" />
)}
{uploadQueue
? `Laddar ${Math.min(uploadQueue.done + 1, uploadQueue.total)} av ${uploadQueue.total}…`
: isUploading
? 'Laddar…'
: 'Ladda upp'}
</Button>
</div>
</header>
{/* Three-section body. Below xl (iPad portrait/landscape + phone) the
sections stack vertically as a single scrollable feed. With the app
sidebar eating ~256px, even iPad landscape (1024–1180px viewport)
has only ~570px of workspace — too tight for 3 panes. At xl+ they
sit side-by-side as three panes. */}
<div className="xl:flex-1 grid grid-cols-1 xl:grid-cols-[280px_minmax(0,1fr)_340px] xl:min-h-0 xl:overflow-hidden">
{/* List — flows naturally below xl; bounded with internal scroll at xl+ */}
<aside className="border-b xl:border-b-0 xl:border-r bg-muted/20 pt-3 xl:overflow-y-auto xl:block">
{items.length > 0 && (
<div className="px-3 pb-3 space-y-2 border-b">
<div className="relative">
<Search className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
<Input
placeholder="Sök i inkorgen…"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8 h-8 text-xs"
/>
</div>
<div className="flex flex-wrap gap-1">
{pills.map((pill) => (
<button
key={pill.key}
type="button"
onClick={() => setFilter(pill.key)}
className={cn(
'text-[11px] px-2 py-0.5 rounded-full border transition-colors',
filter === pill.key
? 'bg-primary text-primary-foreground border-primary'
: 'bg-background text-muted-foreground border-border hover:text-foreground'
)}
>
{pill.label}
{pill.count > 0 && (
<span
className={cn(
'ml-1 tabular-nums',
filter === pill.key ? 'opacity-80' : 'opacity-50'
)}
>
{pill.count}
</span>
)}
</button>
))}
</div>
</div>
)}
{selectedIds.size > 0 && (
<div className="sticky top-0 z-10 flex items-center justify-between gap-2 border-b bg-background/95 backdrop-blur px-3 py-2 text-xs">
<span className="font-medium">{selectedIds.size} valda</span>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-7 text-xs"
onClick={clearSelection}
disabled={isBulkDeleting}
>
Avmarkera
</Button>
<Button
variant="destructive"
size="sm"
className="h-7 text-xs"
onClick={handleBulkDelete}
disabled={isBulkDeleting}
>
{isBulkDeleting ? (
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
) : (
<Trash2 className="h-3 w-3 mr-1" />
)}
Ta bort
</Button>
</div>
</div>
)}
{items.length === 0 ? (
// On desktop the preview pane is always visible alongside this
// column, so showing the onboarding card here would duplicate it.
// On mobile the layout is a master-detail toggle and the user is
// stuck on the list view until they pick a row — without a card
// here they'd have no way to reach the explainer at all. So:
// compact card on mobile only, quiet empty state on desktop.
showOnboarding ? (
<>
<div className="xl:hidden">
<OnboardingCard
hasInboxAddress={hasInboxAddress}
hasAnyItem={hasAnyItem}
hasResolvedItem={hasResolvedItem}
onActivateInbox={handleRotateAddress}
onUploadClick={() => fileInputRef.current?.click()}
onDismiss={handleDismissOnboarding}
isActivating={isRotating}
compact
/>
</div>
<div className="hidden xl:block p-6 text-center text-sm text-muted-foreground">
<Inbox className="h-6 w-6 mx-auto mb-2 opacity-50" />
Inkorgen är tom.
</div>
</>
) : (
<div className="p-6 text-center text-sm text-muted-foreground">
<Inbox className="h-6 w-6 mx-auto mb-2 opacity-50" />
Inkorgen är tom.
</div>
)
) : filteredItems.length === 0 ? (
<div className="p-6 text-center text-xs text-muted-foreground">
{filter === 'todo'
? 'Inget att åtgärda — allt är bearbetat.'
: 'Inga poster matchar filtret.'}
</div>
) : (
<ul>
{filteredItems.map((item) => (
<InboxRow
key={item.id}
item={item}
selected={item.id === selectedId}
onClick={() => handleSelect(item.id)}
isChecked={selectedIds.has(item.id)}
onToggleChecked={() => toggleSelected(item.id)}
anyChecked={selectedIds.size > 0}
/>
))}
</ul>
)}
</aside>
{/* Document preview (hero) */}
<main
className="xl:overflow-hidden bg-muted/10 relative xl:block min-h-[55vh] xl:min-h-0"
>
{selected ? (
<DocumentPreview docUrl={docUrl} docMime={docMime} isProcessing={!!selected.isPlaceholder} />
) : showOnboarding ? (
<div className="h-full flex items-center justify-center px-4 py-6">
<OnboardingCard
hasInboxAddress={hasInboxAddress}
hasAnyItem={hasAnyItem}
hasResolvedItem={hasResolvedItem}
onActivateInbox={handleRotateAddress}
onUploadClick={() => fileInputRef.current?.click()}
onDismiss={handleDismissOnboarding}
isActivating={isRotating}
/>
</div>
) : (
<EmptyPreview
onUploadClick={() => fileInputRef.current?.click()}
onActivateInbox={inboxAddress ? null : handleRotateAddress}
isActivating={isRotating}
/>
)}
{isDragging && (
<div className="absolute inset-0 bg-primary/5 border-2 border-dashed border-primary rounded-md m-4 flex items-center justify-center pointer-events-none">
<p className="text-sm font-medium text-primary">Släpp filen för att ladda upp</p>
</div>
)}
</main>
{/* Fields rail. Below xl it stacks below the preview as part of the
single vertical feed (top border for separation). At xl+ it's the
third pane with a left border. */}
<aside
className="border-t xl:border-t-0 xl:border-l xl:overflow-y-auto pt-4 xl:block pb-4"
>
{selected ? (
<FieldsRail
item={selected}
accountingMethod={accountingMethod}
onDelete={() => handleDelete(selected.id)}
onBookDirect={() => setBookDirectOpen(true)}
onMatchTransaction={() => setMatchPickerOpen(true)}
onUnmatchTransaction={async () => {
const targetId = selected.id
const res = await fetch(
`/api/extensions/ext/invoice-inbox/items/${targetId}/unmatch-transaction`,
{ method: 'POST' },
)
if (!res.ok) {
const json = await res.json().catch(() => ({}))
toast({
title: 'Kunde inte avbryta matchningen',
description: json.error ?? `HTTP ${res.status}`,
variant: 'destructive',
})
return
}
await Promise.all([fetchItems(), handleSelect(targetId)])
}}
onAskAssistant={
identity.isVerified
? (transactionId) => {
openAgentSheet({
intentId: 'transaction.categorization',
intentArgs: { transaction_id: transactionId },
contextRef: `transaction:${transactionId}`,
})
}
: undefined
}
isDeleting={isDeleting}
onRetryRequested={async () => {
await Promise.all([fetchItems(), handleSelect(selected.id)])
}}
onFieldsUpdated={(nextData) => {
// Guard against stale closure: if the user navigated to a
// different item between sending the PATCH and the response
// arriving, the captured `selected` is no longer the
// currently-selected one. Without the id check we'd write
// item A's payload onto item B's row.
const targetId = selected.id
setSelected((prev) =>
prev?.id === targetId ? { ...prev, extracted_data: nextData } : prev
)
setItems((prev) =>
prev.map((it) =>
it.id === targetId ? { ...it, extracted_data: nextData } : it
)
)
}}
/>
) : (
<div className="p-6 text-center text-sm text-muted-foreground">
Välj en post för att se extraherade fält.
</div>
)}
</aside>
</div>
</div>
{selected && (
<BookDirectlyDialog
open={bookDirectOpen}
onOpenChange={setBookDirectOpen}
item={selected}
onSuccess={async () => {
await Promise.all([fetchItems(), handleSelect(selected.id)])
}}
/>
)}
{selected && (
<TransactionMatchPicker
open={matchPickerOpen}
onClose={() => setMatchPickerOpen(false)}
inboxItemId={selected.id}
extractedData={selected.extracted_data}
onMatched={async () => {
await Promise.all([fetchItems(), handleSelect(selected.id)])
}}
/>
)}
</div>
)
}
// ── List row ─────────────────────────────────────────────────
function InboxRow({
item,
selected,
onClick,
isChecked,
onToggleChecked,
anyChecked,
}: {
item: InboxItem
selected: boolean
onClick: () => void
isChecked: boolean
onToggleChecked: () => void
/** True when bulk-select mode is active anywhere in the list — keeps the
checkbox visible (otherwise it's hover-only on desktop). */
anyChecked: boolean
}) {
const amount = pickAmount(item)
const supplierName = pickSupplierName(item)
const isPlaceholder = !!item.isPlaceholder
const status = deriveInboxStatus(item)
const isErrored = status === 'error'
const isBooked = status === 'booked'
const isLinkedToTransaction = status === 'linked'
return (
<li
className={cn(
'group flex items-stretch border-b transition-colors',
selected ? 'bg-background border-l-2 border-l-primary' : 'hover:bg-background',
isErrored && !selected && 'bg-destructive/[0.03]'
)}
>
{!isPlaceholder && (
<div
className={cn(
'flex items-center pl-2.5 pr-1.5 transition-opacity',
// Always visible on touch (no hover), or when any selection is active.
anyChecked ? 'opacity-100' : 'md:opacity-0 md:group-hover:opacity-100 opacity-100'
)}
onClick={(e) => e.stopPropagation()}
>
<Checkbox
checked={isChecked}
onCheckedChange={onToggleChecked}
aria-label="Markera post"
className="h-3.5 w-3.5"
/>
</div>
)}
<button
type="button"
onClick={onClick}
disabled={isPlaceholder}
className={cn(
'flex-1 text-left px-3 py-2 flex flex-col gap-0.5 min-w-0',
isPlaceholder && 'cursor-default'
)}
>
<div className="flex items-center gap-2 min-w-0">
{isPlaceholder ? (
<Loader2 className="h-3 w-3 text-muted-foreground shrink-0 animate-spin" />
) : item.source === 'email' ? (
<Mail className="h-3 w-3 text-muted-foreground shrink-0" />
) : (
<Upload className="h-3 w-3 text-muted-foreground shrink-0" />
)}
<span className="text-sm font-medium truncate flex-1 min-w-0">
{isPlaceholder
? (item.fileName ?? 'Nytt dokument')
: (supplierName ?? item.email_subject ?? 'Okänt dokument')}
</span>
{isErrored && (
<AlertTriangle className="h-3 w-3 text-destructive shrink-0" aria-label="Fel vid bearbetning" />
)}
{isLinkedToTransaction && (
<Link2 className="h-3 w-3 text-emerald-600 shrink-0" aria-label="Kopplad till transaktion" />
)}
{isBooked && (
<Check className="h-3 w-3 text-emerald-600 shrink-0" aria-label="Bokförd" />
)}
</div>
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
{isPlaceholder ? (
<span className="italic">Tolkar dokument med AI…</span>
) : item.extraction_skipped ? (
<span className="flex items-center gap-1.5 min-w-0">
<Badge variant="outline" className="font-normal">Inte AI-tolkad</Badge>
<span className="truncate">{timeAgo(item.email_received_at ?? item.created_at)}</span>
</span>
) : (
<span className="truncate">{timeAgo(item.email_received_at ?? item.created_at)}</span>
)}
{!isPlaceholder && amount != null && (
<span className="tabular-nums shrink-0">
{formatCurrency(amount, pickCurrency(item))}
</span>
)}
</div>
</button>
</li>
)
}
// ── Document preview pane ────────────────────────────────────
// (placed below the row so editors can fold the row cleanly)
export function DocumentPreview({
docUrl,
docMime,
isProcessing = false,
}: {
docUrl: string | null
docMime: string | null
isProcessing?: boolean
}) {
if (isProcessing) {
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>Tolkar dokument med AI…</span>
</div>
)
}
if (!docUrl) {
return (
<div className="h-full flex items-center justify-center text-sm text-muted-foreground">
<FileText className="h-5 w-5 mr-2" />
Inget underlag bifogat
</div>
)
}
return (
<div className="h-full w-full p-4 flex items-start justify-center overflow-hidden">
{docMime?.startsWith('image/') ? (
// Image: frame hugs the image, capped at the parent's visible box.
<div className="max-h-full max-w-3xl bg-background rounded-md border shadow-sm overflow-hidden flex">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={docUrl}
alt="Underlag"
className="block max-h-[calc(100vh-9rem)] max-w-full w-auto h-auto object-contain"
/>
</div>
) : (
// PDF: iframe needs explicit height — frame fills the available pane.
<div className="h-full w-full max-w-3xl bg-background rounded-md border shadow-sm overflow-hidden">
<iframe src={docUrl} className="w-full h-full border-0" title="Underlag" />
</div>
)}
</div>
)
}
// ── Empty preview state ──────────────────────────────────────
// ── Onboarding card ──────────────────────────────────────────
interface OnboardingCardProps {
hasInboxAddress: boolean
hasAnyItem: boolean
hasResolvedItem: boolean
onActivateInbox: () => void
onUploadClick: () => void
onDismiss: () => void
isActivating: boolean
compact?: boolean
}
function OnboardingCard({
hasInboxAddress,
hasAnyItem,
hasResolvedItem,
onActivateInbox,
onUploadClick,
onDismiss,
isActivating,
compact = false,
}: OnboardingCardProps) {
const steps = [
{
done: hasInboxAddress,
title: 'Aktivera din inkorgsadress',
hint: 'Få en unik e-postadress som leverantörer kan skicka fakturor och kvitton till.',
},
{
done: hasAnyItem,
title: 'Ladda upp eller maila in ett underlag',
hint: 'gnubok tolkar fakturan eller kvittot åt dig och fyller i fält automatiskt.',
},
{
done: hasResolvedItem,
title: 'Matcha mot en transaktion eller bokför',
hint: 'Eller skapa en manuell transaktion om underlaget saknar bankhändelse.',
},
]
// First incomplete step drives the active CTA. Falls back to -1 if all done
// (the parent should have hidden the card by then, but guard anyway).
const currentStep = steps.findIndex((s) => !s.done)
return (
<div
className={cn(
'relative rounded-xl border bg-card shadow-sm',
compact ? 'mx-3 my-3 p-4 text-xs' : 'max-w-md mx-auto p-6'
)}
>
<button
type="button"
onClick={onDismiss}
aria-label="Dölj guide"
className="absolute top-2 right-2 h-7 w-7 flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors"
>
<X className="h-3.5 w-3.5" />
</button>
<div className={cn('space-y-1', compact ? 'pr-6' : 'pr-8')}>
<div className="flex items-center gap-2 flex-wrap">
<h2
className={cn(
'font-display font-medium tracking-tight',
compact ? 'text-sm' : 'text-lg'
)}
>
Så funkar dokumentinkorgen
</h2>
<Badge variant="secondary" className="text-[10px] uppercase tracking-wider">
Beta
</Badge>
</div>
<p className={cn('text-muted-foreground', compact ? 'text-[11px]' : 'text-xs')}>
Underlagen samlas här — från mail eller filuppladdning — och kan
matchas mot bankhändelser eller bokföras direkt.
</p>
<p className={cn('text-muted-foreground', compact ? 'text-[11px]' : 'text-xs')}>
Gratis under beta för Open-användare. Ingår senare i Pro-planen.{' '}
<a
href="https://www.gnubok.se/priser"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
Se priser →
</a>
</p>
</div>
<ol className={cn('space-y-2.5', compact ? 'mt-3' : 'mt-5')}>
{steps.map((step, i) => {
const isDone = step.done
const isCurrent = !isDone && i === currentStep
return (
<li
key={step.title}
className={cn('flex items-start gap-2.5', compact && 'gap-2')}
>
<span className="shrink-0 mt-0.5">
{isDone ? (
<Check className={cn('text-emerald-600', compact ? 'h-3.5 w-3.5' : 'h-4 w-4')} />
) : isCurrent ? (
<span
className={cn(
'inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground font-medium',
compact ? 'h-3.5 w-3.5 text-[9px]' : 'h-4 w-4 text-[10px]'
)}
>
{i + 1}
</span>
) : (
<Circle className={cn('text-muted-foreground/40', compact ? 'h-3.5 w-3.5' : 'h-4 w-4')} />
)}
</span>
<div className="min-w-0">
<p
className={cn(
'font-medium',
isDone ? 'text-muted-foreground line-through decoration-muted-foreground/40' : 'text-foreground',
compact ? 'text-xs' : 'text-sm'
)}
>
{step.title}
</p>
{!isDone && (
<p
className={cn(
'text-muted-foreground mt-0.5',
compact ? 'text-[11px]' : 'text-xs'
)}
>
{step.hint}
</p>
)}
</div>
</li>
)
})}
</ol>
{/* CTA matches the current step. No CTA for step 3 — it requires the user to pick a row. */}
{currentStep === 0 && (
<Button
size={compact ? 'sm' : 'default'}
className={cn('w-full mt-4', compact && 'h-8 text-xs')}
onClick={onActivateInbox}
disabled={isActivating}
>
{isActivating ? (
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
) : (
<Mail className="h-3.5 w-3.5 mr-1.5" />
)}
Aktivera inkorgsadress
</Button>
)}
{currentStep === 1 && (
<div className={cn('mt-4 space-y-2', compact && 'mt-3')}>
<Button
size={compact ? 'sm' : 'default'}
className={cn('w-full', compact && 'h-8 text-xs')}
onClick={onUploadClick}
>
<Upload className="h-3.5 w-3.5 mr-1.5" />
Ladda upp en fil
</Button>
<p className={cn('text-center text-muted-foreground', compact ? 'text-[10px]' : 'text-[11px]')}>
…eller maila underlagen till din inkorgsadress.
</p>
</div>
)}
{currentStep === 2 && (
<p
className={cn(
'mt-4 text-center italic text-muted-foreground',
compact ? 'text-[11px]' : 'text-xs'
)}
>
Välj en post i listan för att matcha eller bokföra.
</p>
)}
</div>
)
}
function EmptyPreview({
onUploadClick,
onActivateInbox,
isActivating,
}: {
onUploadClick: () => void
onActivateInbox: (() => void) | null
isActivating: boolean
}) {
return (
<div className="h-full flex flex-col items-center justify-center text-center px-6 gap-3">
<Inbox className="h-10 w-10 text-muted-foreground/40" />
<div>
<p className="text-sm font-medium">
{onActivateInbox ? 'Aktivera din inkorgsadress' : 'Välj ett dokument från listan'}
</p>
<p className="text-xs text-muted-foreground mt-1">
{onActivateInbox
? 'Ditt bolag får en unik e-postadress som leverantörer kan skicka fakturor till.'
: 'Eller dra och släpp en fil var som helst på sidan för att ladda upp.'}
</p>
</div>
<div className="flex gap-2">
{onActivateInbox && (
<Button size="sm" onClick={onActivateInbox} disabled={isActivating}>
{isActivating ? (
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
) : (
<Mail className="h-3.5 w-3.5 mr-1.5" />
)}
Aktivera inkorgsadress
</Button>
)}
<Button variant="outline" size="sm" onClick={onUploadClick}>
<Plus className="h-3.5 w-3.5 mr-1.5" />
Ladda upp en fil
</Button>
</div>
</div>
)
}
// ── Fields rail ──────────────────────────────────────────────
function FieldsRail({
item,
accountingMethod,
onDelete,
onBookDirect,
onMatchTransaction,
onUnmatchTransaction,
onAskAssistant,
isDeleting,
onFieldsUpdated,
onRetryRequested,
}: {
item: InboxItem
accountingMethod: AccountingMethod
onDelete: () => void
onBookDirect: () => void
onMatchTransaction: () => void
onUnmatchTransaction: () => Promise<void>
onAskAssistant?: (transactionId: string) => void
isDeleting: boolean
onFieldsUpdated: (data: InvoiceExtractionResult) => void
onRetryRequested: () => Promise<void>
}) {
const { toast } = useToast()
const data = item.extracted_data
const isProcessed = !!item.created_supplier_invoice_id
const isBookedDirectly = !isProcessed && !!item.created_journal_entry_id
// "Resolved" now means a journal entry exists — matched_transaction_id alone
// is not resolved, it's the prerequisite for booking against that tx.
const isLinkedToTransaction = !isProcessed && !isBookedDirectly && !!item.matched_transaction_id
const isResolved = isProcessed || isBookedDirectly
const [isUnmatchingTx, setIsUnmatchingTx] = useState(false)
const [isRetrying, setIsRetrying] = useState(false)
// Surface a quiet hint when extraction caught a supplier name but no existing
// supplier matched. The actual creation flow lives on the leverantörsfaktura
// form (Skapa & välj), so we don't render a separate button here.
const extractedSupplierName = data?.supplier?.name?.trim() || null
const showNoMatchHint =
!isResolved &&
!item.matched_supplier_id &&
!!extractedSupplierName
const handleRetry = async () => {
setIsRetrying(true)
try {
const res = await fetch(
`/api/extensions/ext/invoice-inbox/items/${item.id}/retry-extraction`,
{ method: 'POST' },
)
const json = await res.json().catch(() => ({}))
if (!res.ok) {
toast({
title: 'Tolkning misslyckades',
description: json.error || 'Försök igen om en stund.',
variant: 'destructive',
})
return
}
toast({ title: 'Tolkning lyckades' })
await onRetryRequested()
} finally {
setIsRetrying(false)
}
}
return (
<div className="flex flex-col h-full">
{/* Email metadata */}
{item.source === 'email' && (item.email_from || item.email_subject) && (
<div className="border-b px-4 py-3 text-xs space-y-1">
{item.email_from && (
<div className="flex gap-2">
<span className="text-muted-foreground w-14 shrink-0">Från</span>
<span className="truncate">{item.email_from}</span>
</div>
)}
{item.email_subject && (
<div className="flex gap-2">
<span className="text-muted-foreground w-14 shrink-0">Ämne</span>
<span className="truncate">{item.email_subject}</span>
</div>
)}
{item.email_received_at && (
<div className="flex gap-2">
<span className="text-muted-foreground w-14 shrink-0">Mottaget</span>
<span>{new Date(item.email_received_at).toLocaleString('sv-SE')}</span>
</div>
)}
</div>
)}
{item.error_message && (
<div className="border-b border-destructive/30 bg-destructive/5 px-4 py-3 text-xs space-y-2">
<div className="flex items-start gap-2">
<AlertTriangle className="h-3.5 w-3.5 text-destructive shrink-0 mt-0.5" />
<div>
<p className="font-medium">Fel vid bearbetning</p>
<p className="text-muted-foreground mt-0.5">{item.error_message}</p>
</div>
</div>
{item.document_id && (
<Button
variant="outline"
size="sm"
className="w-full h-7 text-xs"
onClick={handleRetry}
disabled={isRetrying}
>
{isRetrying ? (
<Loader2 className="h-3 w-3 mr-1.5 animate-spin" />
) : (
<RotateCcw className="h-3 w-3 mr-1.5" />
)}
Försök igen
</Button>
)}
</div>
)}
{/* Hint only — creation happens on the leverantörsfaktura form via "Skapa & välj" */}
{showNoMatchHint && (
<div className="border-b bg-muted/30 px-4 py-2 text-xs text-muted-foreground">
Ingen leverantör matchade{' '}
<span className="text-foreground font-medium">{extractedSupplierName}</span>
{' — leverantören skapas när du klickar Skapa leverantörsfaktura.'}
</div>
)}
{/* Skipped-extraction hint: explains the empty fields and points the
user to the manual paths (transaction link or supplier invoice). */}
{item.extraction_skipped && !isResolved && (
<div className="border-b bg-muted/30 px-4 py-2 text-xs text-muted-foreground">
AI-tolkning skippades p.g.a. dokumentets storlek (fler än 3 sidor).
Du kan koppla dokumentet till en transaktion eller skapa
leverantörsfaktura manuellt.
</div>
)}
{/* Extracted fields */}
<div className="flex-1 overflow-y-auto px-4 py-3">
<h3 className="text-xs uppercase tracking-wide text-muted-foreground font-medium mb-3">
Extraherade fält
</h3>
{item.isPlaceholder ? (
<div className="space-y-2">
<div className="text-xs text-muted-foreground italic flex items-center gap-2 mb-2">
<Loader2 className="h-3 w-3 animate-spin" />
Tolkar dokument med AI…
</div>
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="h-8 w-full" />
))}
</div>
) : (
<EditableFieldsList
itemId={item.id}
data={data ?? emptyExtraction()}
disabled={isResolved}
onUpdated={onFieldsUpdated}
/>
)}
</div>
{/* Actions — hidden while AI extraction is in flight */}
{!item.isPlaceholder && (
<div className="border-t px-4 py-3 space-y-2">
{isProcessed && item.created_supplier_invoice_id ? (
<Link href={`/supplier-invoices/${item.created_supplier_invoice_id}`} className="block">
<Button variant="default" size="sm" className="w-full">
<ArrowRight className="h-3.5 w-3.5 mr-1.5" />
Öppna leverantörsfaktura
</Button>
</Link>
) : isBookedDirectly && item.created_journal_entry_id ? (
<Link href={`/bookkeeping/${item.created_journal_entry_id}`} className="block">
<Button variant="default" size="sm" className="w-full">
<ArrowRight className="h-3.5 w-3.5 mr-1.5" />
Öppna verifikation
</Button>
</Link>
) : isLinkedToTransaction && item.matched_transaction_id ? (
<>
{/* Matched-to-tx state: show the bridge to booking. The user
picks one of two actions — book themselves with the
deterministic dialog, or hand off to the assistant. */}
<div className="rounded-md border border-success/30 bg-success/5 px-3 py-2 text-xs">
<div className="flex items-center gap-1.5 text-success font-medium mb-1">
<Link2 className="h-3 w-3" />
Matchad mot transaktion
</div>
<Link
href={`/transactions?highlight=${item.matched_transaction_id}`}
className="text-muted-foreground hover:text-foreground hover:underline"
>
Öppna transaktionen →
</Link>
</div>
{onAskAssistant && (
<Button
variant="default"
size="sm"
className="w-full"
onClick={() => onAskAssistant(item.matched_transaction_id!)}
>
Fråga assistenten
</Button>
)}
<Button
variant="outline"
size="sm"
className="w-full"
onClick={onBookDirect}
>
Bokför manuellt
</Button>
<button
type="button"
onClick={async () => {
setIsUnmatchingTx(true)
try {
await onUnmatchTransaction()
} finally {
setIsUnmatchingTx(false)
}
}}
disabled={isUnmatchingTx}
className="w-full text-xs text-muted-foreground hover:text-foreground hover:underline pt-1"
>
{isUnmatchingTx ? 'Avbryter…' : 'Avbryt matchning'}
</button>
</>
) : (
<>
{/* Unmatched state: the canonical next step is to find the bank
transaction this underlag belongs to. "Skapa leverantörs-
faktura" stays as an escape hatch for users who want
supplier-invoice tracking (accrual flow). The old "Bokför
direkt" escape hatch was removed — its label was unclear
and the deterministic-book-without-bank-tx use case is
covered by "Matcha mot transaktion" → "Bokför manuellt"
(matched state). */}
<Button
variant="default"
size="sm"
className="w-full"
onClick={onMatchTransaction}
>
Matcha mot transaktion
</Button>
<Link href={`/supplier-invoices/new?inbox_item_id=${item.id}`} className="block">
<Button variant="outline" size="sm" className="w-full">
Skapa leverantörsfaktura
</Button>
</Link>
</>
)}
<Button
variant="ghost"
size="sm"
className="w-full"
onClick={onDelete}
disabled={isDeleting || isResolved}
title={
isProcessed
? 'Kopplad till leverantörsfaktura — kan inte tas bort'
: isBookedDirectly
? 'Bokförd — kan inte tas bort'
: isLinkedToTransaction
? 'Kopplad till transaktion — koppla loss innan borttagning'
: undefined
}
>
{isDeleting ? (
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5 mr-1.5" />
)}
Ta bort
</Button>
{isProcessed && (
<Badge variant="secondary" className="w-full justify-center text-[10px]">
<Check className="h-2.5 w-2.5 mr-1" />
Bearbetad
</Badge>
)}
{isBookedDirectly && (
<Badge variant="secondary" className="w-full justify-center text-[10px]">
<Check className="h-2.5 w-2.5 mr-1" />
Bokförd
</Badge>
)}
{isLinkedToTransaction && (
<Badge variant="secondary" className="w-full justify-center text-[10px]">
<Link2 className="h-2.5 w-2.5 mr-1" />
Kopplad till transaktion
</Badge>
)}
</div>
)}
</div>
)
}
// ── Extracted fields list ────────────────────────────────────
export function emptyExtraction(): InvoiceExtractionResult {
return {
supplier: { name: null, orgNumber: null, vatNumber: null, address: null, bankgiro: null, plusgiro: null },
invoice: { invoiceNumber: null, invoiceDate: null, dueDate: null, paymentReference: null, currency: 'SEK' },
lineItems: [],
totals: { subtotal: null, vatAmount: null, total: null },
vatBreakdown: [],
confidence: 0,
}
}
// Inline edit + debounced auto-save. The field set mirrors the
// UpdateExtractedDataSchema in extensions/general/invoice-inbox/index.ts.
type FieldKey =
| 'supplier.name'
| 'supplier.orgNumber'
| 'supplier.vatNumber'
| 'supplier.bankgiro'
| 'supplier.plusgiro'
| 'invoice.invoiceNumber'
| 'invoice.paymentReference'
| 'invoice.invoiceDate'
| 'invoice.dueDate'
| 'invoice.currency'
| 'totals.total'
| 'totals.vatAmount'
interface FieldDef {
key: FieldKey
label: string
type: 'text' | 'date' | 'number'
inputMode?: 'numeric' | 'decimal'
}
const FIELD_DEFS: FieldDef[] = [
{ key: 'supplier.name', label: 'Leverantör', type: 'text' },
{ key: 'supplier.orgNumber', label: 'Org.nr', type: 'text' },
{ key: 'supplier.vatNumber', label: 'VAT-nr', type: 'text' },
{ key: 'invoice.currency', label: 'Valuta', type: 'text' },
{ key: 'totals.total', label: 'Totalt', type: 'number', inputMode: 'decimal' },
{ key: 'totals.vatAmount', label: 'Moms', type: 'number', inputMode: 'decimal' },
{ key: 'supplier.bankgiro', label: 'Bankgiro', type: 'text' },
{ key: 'supplier.plusgiro', label: 'Plusgiro', type: 'text' },
{ key: 'invoice.invoiceNumber', label: 'Fakturanr', type: 'text' },
{ key: 'invoice.paymentReference', label: 'OCR/Referens', type: 'text' },
{ key: 'invoice.invoiceDate', label: 'Fakturadatum', type: 'date' },
{ key: 'invoice.dueDate', label: 'Förfallodatum', type: 'date' },
]
function readField(data: InvoiceExtractionResult, key: FieldKey): string {
const [group, name] = key.split('.') as [keyof InvoiceExtractionResult, string]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const value = (data[group] as any)?.[name]
if (value == null) return ''
return String(value)
}
function buildPatchBody(key: FieldKey, raw: string, currency: string) {
const [group, name] = key.split('.')
const trimmed = raw.trim()
if (group === 'totals') {
const num = trimmed === '' ? null : Number(trimmed.replace(',', '.'))
if (num != null && !Number.isFinite(num)) return null
return { totals: { [name]: num } }
}
if (group === 'invoice' && (name === 'invoiceDate' || name === 'dueDate')) {
const value = trimmed === '' ? null : trimmed
return { invoice: { [name]: value } }
}
if (group === 'invoice' && name === 'currency') {
return { invoice: { currency: trimmed === '' ? currency : trimmed.toUpperCase() } }
}
return { [group]: { [name]: trimmed === '' ? null : trimmed } }
}
export function EditableFieldsList({
itemId,
data,
disabled,
onUpdated,
}: {
itemId: string
data: InvoiceExtractionResult
disabled: boolean
onUpdated: (data: InvoiceExtractionResult) => void
}) {
const { toast } = useToast()
const [drafts, setDrafts] = useState<Record<FieldKey, string>>(() =>
Object.fromEntries(FIELD_DEFS.map((f) => [f.key, readField(data, f.key)])) as Record<FieldKey, string>
)
const timersRef = useRef<Partial<Record<FieldKey, ReturnType<typeof setTimeout>>>>({})
// Last-known server values per field. Used to detect when the server
// normalises a value (currency upper-cased, whitespace trimmed) so we can
// pick up the canonical value into the input without clobbering an
// in-progress edit.
const lastServerRef = useRef<Record<FieldKey, string>>(
Object.fromEntries(FIELD_DEFS.map((f) => [f.key, readField(data, f.key)])) as Record<FieldKey, string>
)
// Reset drafts when the user switches to a different inbox item.
useEffect(() => {
const seeded = Object.fromEntries(
FIELD_DEFS.map((f) => [f.key, readField(data, f.key)])
) as Record<FieldKey, string>
setDrafts(seeded)
lastServerRef.current = seeded
return () => {
for (const t of Object.values(timersRef.current)) {
if (t) clearTimeout(t)
}
timersRef.current = {}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [itemId])
// Re-seed drafts when the server returns normalised values (e.g. uppercased
// currency, trimmed strings). Only update fields where the local draft
// matches the previous server value — i.e. the user hasn't typed anything
// newer that we'd otherwise clobber.
useEffect(() => {
let dirty = false
const next: Record<FieldKey, string> = { ...lastServerRef.current }
setDrafts((prev) => {
const updated = { ...prev }
for (const f of FIELD_DEFS) {
const newServer = readField(data, f.key)
const prevServer = lastServerRef.current[f.key]
if (newServer !== prevServer) {
next[f.key] = newServer
// Only sync into the input if the user hadn't started a new edit.
if (prev[f.key] === prevServer) {
updated[f.key] = newServer
dirty = true
}
}
}
return dirty ? updated : prev
})
lastServerRef.current = next
}, [data])
const currency = data.invoice?.currency ?? 'SEK'
const persist = useCallback(
async (key: FieldKey, raw: string) => {
const body = buildPatchBody(key, raw, currency)
if (!body) {
toast({ variant: 'destructive', title: 'Ogiltigt värde' })
setDrafts((prev) => ({ ...prev, [key]: readField(data, key) }))
return
}
try {
const res = await fetch(
`/api/extensions/ext/invoice-inbox/items/${itemId}/fields`,
{
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}
)
const json = await res.json()
if (!res.ok) {
// 409 means the item is already linked to a supplier invoice and
// the server has rejected the edit. Surface the specific Swedish
// message ("Posten är redan kopplad…") instead of the generic
// fallback so the user understands why the field locked.
const isConflict = res.status === 409
toast({
variant: 'destructive',
title: isConflict ? 'Posten är låst' : 'Kunde inte spara',
description: json.error ?? 'Försök igen',
})
setDrafts((prev) => ({ ...prev, [key]: readField(data, key) }))
return
}
if (json.data?.extracted_data) {
onUpdated(json.data.extracted_data as InvoiceExtractionResult)
}
} catch (err) {
toast({
variant: 'destructive',
title: 'Nätverksfel',
description: err instanceof Error ? err.message : 'Kunde inte spara',
})
setDrafts((prev) => ({ ...prev, [key]: readField(data, key) }))
}
},
[itemId, currency, data, onUpdated, toast]
)
const onChange = useCallback(
(key: FieldKey, raw: string) => {
setDrafts((prev) => ({ ...prev, [key]: raw }))
const existing = timersRef.current[key]
if (existing) clearTimeout(existing)
timersRef.current[key] = setTimeout(() => {
timersRef.current[key] = undefined
if (raw === readField(data, key)) return
void persist(key, raw)
}, 800)
},
[data, persist]
)
const onBlur = useCallback(
(key: FieldKey) => {
const pending = timersRef.current[key]
if (pending) {
clearTimeout(pending)
timersRef.current[key] = undefined
const raw = drafts[key]
if (raw !== readField(data, key)) void persist(key, raw)
}
},
[data, drafts, persist]
)
const vatRows = useMemo(() => data.vatBreakdown ?? [], [data.vatBreakdown])
return (
<div className="space-y-2">
{FIELD_DEFS.map((f) => (
<div key={f.key} className="flex flex-col gap-0.5">
<label
htmlFor={`field-${f.key}`}
className="text-[10px] uppercase tracking-wide text-muted-foreground/80"
>
{f.label}
</label>
<Input
id={`field-${f.key}`}
type={f.type}
inputMode={f.inputMode}
value={drafts[f.key]}
onChange={(e) => onChange(f.key, e.target.value)}
onBlur={() => onBlur(f.key)}
disabled={disabled}
placeholder="—"
className={cn(
'h-8 text-sm border-transparent bg-transparent px-2 -mx-2 hover:border-border focus-visible:border-ring',
drafts[f.key] === '' && 'text-muted-foreground/50 italic'
)}
/>
</div>
))}
{vatRows.length > 0 && (
<div className="pt-2 border-t mt-3">
<p className="text-[10px] uppercase tracking-wide text-muted-foreground/80 mb-1.5">
Momsfördelning
</p>
<div className="space-y-1">
{vatRows.map((row, i) => (
<div key={i} className="text-xs flex justify-between">
<span className="text-muted-foreground">{row.rate}%</span>
<span className="tabular-nums">
{formatCurrency(row.base, currency)} +{' '}
{formatCurrency(row.amount, currency)}
</span>
</div>
))}
</div>
</div>
)}
{disabled && (
<p className="text-[10px] text-muted-foreground/70 pt-2">
Posten är kopplad till en leverantörsfaktura — fälten kan inte ändras.
</p>
)}
</div>
)
}