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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Emil <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-05-28 11:27:01 +02:00
committed by GitHub
co-authored by Claude Opus 4.7 Emil
parent a9b43ebeb7
commit f53725b20a
243 changed files with 48104 additions and 1543 deletions
+61
View File
@@ -0,0 +1,61 @@
'use client'
import { MessageCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { getAvatarUrl } from './avatars'
interface Props {
avatarId: string | null | undefined
size?: 'xs' | 'sm' | 'md' | 'lg'
className?: string
alt?: string
}
// Renders the agent's avatar — either the chosen dicebear SVG from the
// AVATAR_OPTIONS registry, or a fallback MessageCircle glyph on a dark circle
// when no avatar is set yet (free tier / older profiles).
//
// `next/image` is intentionally NOT used: avatars are tiny remote SVGs from
// the dicebear CDN, and adding the domain to next.config just to render a
// 28px image is overkill. Browser caches the SVG forever via the seed-keyed
// URL.
export default function AgentAvatar({ avatarId, size = 'sm', className, alt }: Props) {
const url = getAvatarUrl(avatarId)
const dim = SIZES[size]
const altText = alt ?? 'Avatar'
if (!url) {
return (
<span
className={cn(
'inline-flex items-center justify-center rounded-full bg-foreground text-background shrink-0',
dim.box,
className,
)}
aria-label={altText}
>
<MessageCircle className={dim.icon} />
</span>
)
}
// eslint-disable-next-line @next/next/no-img-element
return (
<img
src={url}
alt={altText}
className={cn(
'rounded-full shrink-0 bg-secondary object-cover',
dim.box,
className,
)}
/>
)
}
const SIZES = {
xs: { box: 'h-5 w-5', icon: 'h-2.5 w-2.5' },
sm: { box: 'h-8 w-8', icon: 'h-3.5 w-3.5' },
md: { box: 'h-10 w-10', icon: 'h-4 w-4' },
lg: { box: 'h-14 w-14', icon: 'h-5 w-5' },
}
File diff suppressed because it is too large Load Diff
+108
View File
@@ -0,0 +1,108 @@
'use client'
import { useEffect, useState } from 'react'
import { X, Expand } from 'lucide-react'
import Link from 'next/link'
import AgentChat from './AgentChat'
import AgentAvatar from './AgentAvatar'
import { useAgentSheet } from './AgentSheetProvider'
// Undimmed non-modal side sheet — sits above the page on a hairline border +
// shadow, but the page underneath stays fully interactive. Plan §3b.
//
// The sheet is a thin wrapper around AgentChat: it owns the title bar, close
// button, and "expand to /chat/[id]" affordance. All message rendering and
// streaming live in AgentChat so the full-page chat view can reuse them.
interface Props {
intentId: string
intentArgs?: Record<string, unknown>
contextRef?: string
seedUserMessage?: string
onClose: () => void
}
export default function AgentSheet({
intentId,
intentArgs,
contextRef,
seedUserMessage,
onClose,
}: Props) {
const [conversationId, setConversationId] = useState<string | null>(null)
const { identity } = useAgentSheet()
const agentName = identity.displayName?.trim() || null
const sheetTitle = intentToTitle(intentId, agentName)
// Esc closes the sheet.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
return (
<div
role="dialog"
aria-label={sheetTitle}
// z-[60] sits above the mobile bottom nav (z-50) so on phones the sheet
// covers the full screen including where the nav would otherwise show.
className="fixed inset-y-0 right-0 z-[60] flex w-full max-w-[480px] flex-col border-l border-border bg-background shadow-lg"
style={{
// iOS notch / Android cutout — the sheet top edge needs to clear the
// status bar. Bottom is handled inside the form below.
paddingTop: 'env(safe-area-inset-top, 0px)',
}}
>
<header className="flex items-center gap-3 border-b border-border px-5 py-4">
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName ?? 'Assistent'} />
<h2 className="font-display text-lg tracking-tight truncate">{sheetTitle}</h2>
<div className="ml-auto flex items-center gap-1">
{conversationId && (
<Link
href={`/chat/${conversationId}`}
onClick={onClose}
className="h-9 w-9 inline-flex items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label="Öppna i fullskärm"
title="Öppna i fullskärm"
>
<Expand className="h-4 w-4" />
</Link>
)}
<button
onClick={onClose}
className="h-9 w-9 inline-flex items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label="Stäng"
>
<X className="h-4 w-4" />
</button>
</div>
</header>
<AgentChat
intentId={intentId}
intentArgs={intentArgs}
contextRef={contextRef}
seedUserMessage={seedUserMessage}
onConversationIdChange={(id) => setConversationId(id)}
/>
</div>
)
}
function intentToTitle(intentId: string, agentName: string | null): string {
switch (intentId) {
case 'general.help':
return agentName ? `Fråga ${agentName}` : 'Fråga din assistent'
case 'transaction.categorization':
return 'Hjälp med transaktion'
case 'invoice.draft':
return 'Hjälp med faktura'
case 'supplier_invoice.review':
return 'Granska leverantörsfaktura'
default:
return agentName ? `Fråga ${agentName}` : 'Fråga din assistent'
}
}
+103
View File
@@ -0,0 +1,103 @@
'use client'
import { createContext, useCallback, useContext, useMemo, useState } from 'react'
import AgentSheet from './AgentSheet'
export interface AgentIdentity {
displayName: string | null
avatarId: string | null
// True only after the user has completed Phase B verification in
// /onboarding/agent. Consumers (AgentTrigger, page-level Sparkle
// buttons) should hide themselves when this is false so the FAB
// doesn't pop up before the agent build flow has run.
isVerified: boolean
}
// Provider exposes a single imperative function: openAgentSheet({...}). Any
// client component (top-nav button, transaction row "Fråga om" button, etc.)
// calls it to bring the sheet up with a specific intent + capture args.
//
// The sheet itself manages its own message list, streaming state, and
// dismissal. The provider just owns "what is open" and re-opens or replaces
// the panel when called again.
export interface OpenAgentSheetArgs {
intentId: string
// Intent-specific args passed to the server's intent.capture() — e.g.
// { transaction_id: '...' } for transaction.categorization.
intentArgs?: Record<string, unknown>
// Optional ref persisted on agent_conversations.context_ref so the UI can
// surface a back-pointer ("om transaktion 12 mar / 1 240 kr") later.
contextRef?: string
// Pre-populated first user message. When set, the chat skips the intent's
// promptTemplate and sends this verbatim instead. Used by /chat empty-state
// suggestion chips to give the user a one-click starting prompt.
seedUserMessage?: string
}
interface AgentSheetContextValue {
openAgentSheet: (args: OpenAgentSheetArgs) => void
closeAgentSheet: () => void
isOpen: boolean
// Agent name + avatar — set once from the server-loaded agent_profile
// and exposed through context so the trigger / chat headers can render
// them without their own fetches. Null when the user hasn't verified a
// profile yet (free tier or pre-onboarding).
identity: AgentIdentity
}
const AgentSheetContext = createContext<AgentSheetContextValue | null>(null)
interface AgentSheetProviderProps {
children: React.ReactNode
identity?: AgentIdentity
}
export function AgentSheetProvider({ children, identity }: AgentSheetProviderProps) {
const [activeArgs, setActiveArgs] = useState<OpenAgentSheetArgs | null>(null)
const openAgentSheet = useCallback((args: OpenAgentSheetArgs) => {
setActiveArgs(args)
}, [])
const closeAgentSheet = useCallback(() => {
setActiveArgs(null)
}, [])
const resolvedIdentity: AgentIdentity =
identity ?? { displayName: null, avatarId: null, isVerified: false }
const value = useMemo<AgentSheetContextValue>(
() => ({
openAgentSheet,
closeAgentSheet,
isOpen: activeArgs !== null,
identity: resolvedIdentity,
}),
[openAgentSheet, closeAgentSheet, activeArgs, resolvedIdentity],
)
return (
<AgentSheetContext.Provider value={value}>
{children}
{activeArgs && (
<AgentSheet
key={`${activeArgs.intentId}:${activeArgs.contextRef ?? ''}:${activeArgs.seedUserMessage ?? ''}`}
intentId={activeArgs.intentId}
intentArgs={activeArgs.intentArgs}
contextRef={activeArgs.contextRef}
seedUserMessage={activeArgs.seedUserMessage}
onClose={closeAgentSheet}
/>
)}
</AgentSheetContext.Provider>
)
}
export function useAgentSheet(): AgentSheetContextValue {
const ctx = useContext(AgentSheetContext)
if (!ctx) {
throw new Error('useAgentSheet must be used inside <AgentSheetProvider>')
}
return ctx
}
+62
View File
@@ -0,0 +1,62 @@
'use client'
import { MessageCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useAgentSheet } from './AgentSheetProvider'
interface Props {
intentId: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
intentArgs?: Record<string, any>
contextRef?: string
// Override the auto-derived "Fråga [namn]" label when the page wants
// something more contextual (e.g. "Förklara denna siffra"). Most surfaces
// should leave this unset.
label?: string
size?: 'sm' | 'default' | 'lg'
variant?: 'outline' | 'default' | 'ghost' | 'secondary'
className?: string
}
// Single source of truth for the in-page "Fråga [namn]" affordance. Every
// page-header button across the dashboard (invoice form, supplier invoice,
// bookkeeping, year-end, VAT report, KPI, …) routes through this component
// so they share the same icon size, label format, spacing, and resolved
// agent name. The transaction-row icon button stays separate — it's a
// different UX (icon-only, ghost) embedded inside a row's action group.
export default function AgentSparkleButton({
intentId,
intentArgs,
contextRef,
label,
size = 'sm',
variant = 'outline',
className,
}: Props) {
const { openAgentSheet, identity } = useAgentSheet()
// Same gate as AgentTrigger — hide all "Fråga …" affordances until the
// user has finished /onboarding/agent.
if (!identity.isVerified) return null
const name = identity.displayName?.trim() || 'min assistent'
const resolvedLabel = label ?? `Fråga ${name}`
return (
<Button
type="button"
variant={variant}
size={size}
className={cn('shrink-0', className)}
onClick={() =>
openAgentSheet({
intentId,
intentArgs,
contextRef,
})
}
>
<MessageCircle className="mr-2 h-4 w-4" />
{resolvedLabel}
</Button>
)
}
+79
View File
@@ -0,0 +1,79 @@
'use client'
import { useAgentSheet } from './AgentSheetProvider'
import { usePathname } from 'next/navigation'
import AgentAvatar from './AgentAvatar'
import { routeToIntent } from '@/lib/agent/intents/route-mapping'
// Floating trigger sits above the page bottom-right, opens the AgentSheet when
// clicked. Hidden when the sheet is already open so the icon doesn't double up.
//
// Route-aware: routeToIntent(pathname) picks the right intent + intentArgs so
// clicking the FAB on /invoices/abc-123 opens invoice.draft with that invoice
// id (rather than the page-agnostic general.help with just the URL). The
// label suffix renders "Fråga Anna om denna faktura" so the user can tell at
// a glance that the agent is going to know which entity they're on.
//
// Reads the agent's display_name + avatar_id from the AgentSheet context so
// the button reads "Fråga Anna" (with Anna's face) rather than the generic
// "Fråga min assistent".
//
// Page-specific triggers (e.g. "Granska med assistent" on a supplier invoice)
// still call useAgentSheet() directly from their own buttons because they
// know exactly which entity to pass. (Per-transaction help is reached from
// Dokumentinkorgen, not a transactions-page row button.)
export default function AgentTrigger() {
const { openAgentSheet, isOpen, identity } = useAgentSheet()
const pathname = usePathname()
if (isOpen) return null
// The /chat surface IS the chat — a floating "Fråga …" pill on top of it
// is redundant and overlaps the input. Suppress while the user is here.
if (pathname?.startsWith('/chat')) return null
// The verifikation editor is a dense regulatory surface (debits/credits,
// BAS codes, period locks) — a floating "Fråga … om denna verifikation"
// pill on top of it adds noise without earning its place. Suppress on
// /bookkeeping/[id] specifically; /bookkeeping (list), /bookkeeping/new,
// and /bookkeeping/year-end still get the FAB.
{
const segs = pathname?.split('/').filter(Boolean) ?? []
if (segs[0] === 'bookkeeping' && segs[1] && segs[1] !== 'year-end' && segs[1] !== 'new') {
return null
}
}
// Pre-onboarding: no agent_profile.verified_at yet. The FAB would lead
// into a generic chat with no specialization. Better to hide it until
// the user has finished /onboarding/agent.
if (!identity.isVerified) return null
const name = identity.displayName?.trim() || 'min assistent'
const dispatch = routeToIntent(pathname)
const labelText = dispatch.labelSuffix
? `Fråga ${name} ${dispatch.labelSuffix}`
: `Fråga ${name}`
return (
<button
onClick={() =>
openAgentSheet({
intentId: dispatch.intentId,
intentArgs: dispatch.intentArgs,
contextRef: dispatch.contextRef,
})
}
// Mobile: sit above the bottom nav (h-16 = 64px) AND the iOS home
// indicator (env(safe-area-inset-bottom)). Desktop: standard 20px lift,
// no mobile nav to worry about.
className="fixed right-4 z-30 flex h-12 max-w-[calc(100vw-2rem)] items-center gap-2 rounded-full bg-foreground pl-2 pr-4 text-background shadow-lg hover:bg-foreground/90 transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 bottom-[calc(env(safe-area-inset-bottom,0px)+5rem)] md:bottom-4"
aria-label={labelText}
>
<AgentAvatar
avatarId={identity.avatarId}
size="sm"
className="ring-2 ring-background/20 shrink-0"
alt={name}
/>
<span className="text-sm font-medium truncate">{labelText}</span>
</button>
)
}
File diff suppressed because it is too large Load Diff
+66
View File
@@ -0,0 +1,66 @@
'use client'
import { useMemo } from 'react'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import AgentChat, { normalizeStoredMessages } from './AgentChat'
import AgentAvatar from './AgentAvatar'
import { useAgentSheet } from './AgentSheetProvider'
interface Props {
conversationId: string
intentId: string
contextRef: string | null
title: string
rawMessages: { role: string; content: unknown; hidden?: boolean }[]
}
// Full-page conversation view. Wraps AgentChat with a header that shows the
// title (or intent label). AgentChat handles the streaming + input + render.
export default function ChatConversationView({
conversationId,
intentId,
contextRef,
title,
rawMessages,
}: Props) {
const initialMessages = useMemo(() => normalizeStoredMessages(rawMessages), [rawMessages])
const { identity } = useAgentSheet()
return (
<>
<header className="flex items-center gap-3 border-b border-border px-5 py-4 shrink-0">
{/* Mobile-only back-to-list arrow. On desktop the sidebar is always
visible so a back button would be redundant. */}
<Link
href="/chat"
className="md:hidden inline-flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors -ml-1"
aria-label="Tillbaka till konversationer"
>
<ArrowLeft className="h-4 w-4" />
</Link>
<AgentAvatar
avatarId={identity.avatarId}
size="sm"
alt={identity.displayName ?? 'Assistent'}
/>
<div className="min-w-0">
<h1 className="font-display text-lg tracking-tight truncate">{title}</h1>
{contextRef && (
<p className="text-xs text-muted-foreground truncate">{contextRef}</p>
)}
</div>
</header>
<div className="flex-1 min-h-0">
<AgentChat
intentId={intentId}
contextRef={contextRef ?? undefined}
initialConversationId={conversationId}
initialMessages={initialMessages}
scrollerClassName="px-6 py-8"
/>
</div>
</>
)
}
+66
View File
@@ -0,0 +1,66 @@
'use client'
import { ArrowUpRight } from 'lucide-react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { useAgentSheet } from './AgentSheetProvider'
import AgentAvatar from './AgentAvatar'
// Tiny client component for /chat empty state. Reads the agent identity from
// the provider so it can show the user's chosen avatar + name above the
// "starta en konversation" CTA.
//
// The three suggestion chips below the headline give users a one-click way
// in. They navigate to /chat/new?intent=…&prompt=… which mounts AgentChat
// inline and swaps to /chat/[id] once the conversation is created — so the
// flow stays full-screen instead of opening a slide-in sheet.
const SUGGESTIONS: { label: string; prompt: string }[] = [
{
label: 'Vad är min största utgiftspost den här månaden?',
prompt: 'Vad är min största utgiftspost den här månaden? Visa de fem största kategorierna.',
},
{
label: 'Hur ser min momsrapport ut för senaste perioden?',
prompt: 'Hur ser min momsrapport ut för den senaste perioden? Vad blir moms att betala eller få tillbaka, och ser något ovanligt ut?',
},
{
label: 'När är min nästa skatte- eller momsdeadline?',
prompt: 'När är min nästa skatte- eller momsdeadline, och vad behöver jag göra inför den?',
},
]
export default function ChatEmptyState() {
const { identity } = useAgentSheet()
const name = identity.displayName?.trim() || 'din assistent'
// Hidden on mobile — the sidebar IS the page when no conversation is open.
// On desktop, fills the right pane with a centered prompt.
return (
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
<p className="text-muted-foreground max-w-md mb-6">
Välj en konversation till vänster, eller starta en ny om något har dykt upp.
</p>
<div className="flex flex-col gap-2 w-full max-w-md mb-6">
{SUGGESTIONS.map((s) => (
<Link
key={s.label}
href={`/chat/new?intent=general.help&prompt=${encodeURIComponent(s.prompt)}`}
className="group flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 text-left text-sm transition-colors hover:border-foreground/30 hover:bg-secondary/30"
>
<span className="flex-1 text-muted-foreground group-hover:text-foreground transition-colors">
{s.label}
</span>
<ArrowUpRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground/60 group-hover:text-foreground transition-colors" />
</Link>
))}
</div>
<Button size="lg" variant="outline" asChild>
<Link href="/chat/new?intent=general.help">Eller skriv din egen fråga</Link>
</Button>
</div>
)
}
+57
View File
@@ -0,0 +1,57 @@
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
import AgentChat from './AgentChat'
import AgentAvatar from './AgentAvatar'
import { useAgentSheet } from './AgentSheetProvider'
// Phase C entry surface. Lands here from ReviewCard's "kör" after Phase B
// verify succeeds. Renders AgentChat in fresh-start mode — no
// initialConversationId, no initialMessages — so the auto-fire effect
// kicks the first invoke. As soon as /api/agent/invoke emits the
// conversation event, the URL swaps to /chat/[id] so reload / share /
// browser-back all work like any other conversation.
//
// Plan refs: §7 Phase C.
export default function ChatIntakeStarter() {
const router = useRouter()
const { identity } = useAgentSheet()
const agentName = identity.displayName?.trim() || 'Din assistent'
// Lock the swap to the first id we see — defensive guard against the
// AgentChat callback firing twice during React 19 Strict Mode reruns.
const [swapped, setSwapped] = useState(false)
return (
<>
<header className="flex items-center gap-3 border-b border-border px-5 py-4 shrink-0">
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName} />
<div className="min-w-0">
<h1 className="font-display text-lg tracking-tight truncate">{agentName} är redo</h1>
<p className="text-xs text-muted-foreground">
Några frågor för att lära känna din verksamhet — svara i din egen takt, du kan avsluta när du vill.
</p>
</div>
</header>
<div className="flex-1 min-h-0">
<AgentChat
intentId="onboarding.intake"
initialMessages={[]}
initialConversationId={null}
onFirstTurnComplete={(id) => {
// Wait for the greeting to finish streaming AND persist before
// swapping the URL. Swapping on the early `conversation` event
// unmounts AgentChat mid-stream, so the greeting is never saved
// and /chat/[id] hydrates empty — the bug where the chat lands
// blank and only shows the intro on a later visit.
if (swapped) return
setSwapped(true)
router.replace(`/chat/${id}`)
}}
scrollerClassName="px-6 py-8"
/>
</div>
</>
)
}
+54
View File
@@ -0,0 +1,54 @@
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
import AgentChat from './AgentChat'
import AgentAvatar from './AgentAvatar'
import { useAgentSheet } from './AgentSheetProvider'
// Inline starter used by suggestion chips and ⌘K. Mirrors ChatIntakeStarter
// but accepts any intent + seed so we don't fork the intake-specific
// onboarding path. When AgentChat emits the new conversation_id, the URL
// is swapped to /chat/[id] so reload / share / browser-back all work.
export default function ChatNewStarter({
intentId,
seedUserMessage,
}: {
intentId: string
seedUserMessage?: string
}) {
const router = useRouter()
const { identity } = useAgentSheet()
const agentName = identity.displayName?.trim() || 'Din assistent'
const [swapped, setSwapped] = useState(false)
return (
<>
<header className="flex items-center gap-3 border-b border-border px-5 py-4 shrink-0">
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName} />
<div className="min-w-0">
<h1 className="font-display text-lg tracking-tight truncate">{agentName}</h1>
<p className="text-xs text-muted-foreground truncate">Ny konversation</p>
</div>
</header>
<div className="flex-1 min-h-0">
<AgentChat
intentId={intentId}
seedUserMessage={seedUserMessage}
initialMessages={[]}
initialConversationId={null}
onFirstTurnComplete={(id) => {
// Wait for the first turn to finish before swapping the URL —
// otherwise the unmount aborts the in-flight stream and
// /chat/[id] hydrates with only the user message.
if (swapped) return
setSwapped(true)
router.replace(`/chat/${id}`)
}}
scrollerClassName="px-6 py-8"
/>
</div>
</>
)
}
+347
View File
@@ -0,0 +1,347 @@
'use client'
import { useEffect, useMemo, useState, useTransition } from 'react'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { Pin, PinOff, Archive, Search, X, PanelLeftOpen, PanelLeftClose } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useAgentSheet } from './AgentSheetProvider'
import AgentAvatar from './AgentAvatar'
interface ConversationRow {
id: string
intent_id: string
context_ref: string | null
title: string | null
pinned: boolean
archived: boolean
last_message_at: string | null
last_message_preview: string | null
created_at: string
}
interface Props {
initialConversations: ConversationRow[]
}
// Time buckets for date grouping. Computed once per render against now().
// Mirrors the Idag / Igår / Denna vecka / Äldre pattern users know from
// Mail and iMessage.
type DateBucket = 'pinned' | 'today' | 'yesterday' | 'thisWeek' | 'older'
const BUCKET_LABELS: Record<DateBucket, string> = {
pinned: 'Fästade',
today: 'Idag',
yesterday: 'Igår',
thisWeek: 'Denna vecka',
older: 'Äldre',
}
function bucketFor(c: ConversationRow): DateBucket {
if (c.pinned) return 'pinned'
const when = c.last_message_at ?? c.created_at
if (!when) return 'older'
const t = new Date(when)
const now = new Date()
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000)
const weekStart = new Date(todayStart.getTime() - 6 * 24 * 60 * 60 * 1000)
if (t >= todayStart) return 'today'
if (t >= yesterdayStart) return 'yesterday'
if (t >= weekStart) return 'thisWeek'
return 'older'
}
// Compact relative-time label shown to the right of each row. Locale-tuned
// to feel native in Swedish without going full date-fns.
function relativeTime(iso: string | null | undefined): string {
if (!iso) return ''
const t = new Date(iso).getTime()
const now = Date.now()
const diffMin = Math.round((now - t) / 60000)
if (diffMin < 1) return 'nu'
if (diffMin < 60) return `${diffMin} min`
const diffHr = Math.round(diffMin / 60)
if (diffHr < 24) return `${diffHr} h`
const diffDay = Math.round(diffHr / 24)
if (diffDay < 7) return `${diffDay} d`
return new Date(iso).toLocaleDateString('sv-SE', { month: 'short', day: 'numeric' })
}
export default function ChatSidebar({ initialConversations }: Props) {
const router = useRouter()
const pathname = usePathname()
const { openAgentSheet, identity } = useAgentSheet()
const agentName = identity.displayName?.trim() || null
const [conversations, setConversations] = useState<ConversationRow[]>(initialConversations)
const [query, setQuery] = useState('')
const [, startTransition] = useTransition()
// Collapsed by default; persisted across reloads so power users keep
// their preference. Hidden behind a thin rail when collapsed so the
// conversation pane runs nearly edge-to-edge.
const [collapsed, setCollapsed] = useState(true)
useEffect(() => {
const stored = localStorage.getItem('gnubok:chat-sidebar-collapsed')
if (stored === 'false') setCollapsed(false)
}, [])
const toggleCollapsed = () => {
setCollapsed(c => {
const next = !c
try { localStorage.setItem('gnubok:chat-sidebar-collapsed', next ? 'true' : 'false') } catch {}
return next
})
}
const activeId = pathname?.startsWith('/chat/') ? pathname.split('/')[2] : null
const isConversationOpen = !!activeId
const filtered = useMemo(() => {
const q = query.trim().toLowerCase()
if (!q) return conversations
return conversations.filter((c) => {
return (
(c.title ?? '').toLowerCase().includes(q) ||
(c.last_message_preview ?? '').toLowerCase().includes(q) ||
(c.context_ref ?? '').toLowerCase().includes(q) ||
c.intent_id.toLowerCase().includes(q)
)
})
}, [conversations, query])
// Group filtered into ordered buckets, preserving the sort order already
// applied server-side (pinned first, then last_message_at desc).
const grouped = useMemo(() => {
const buckets: Record<DateBucket, ConversationRow[]> = {
pinned: [],
today: [],
yesterday: [],
thisWeek: [],
older: [],
}
for (const c of filtered) buckets[bucketFor(c)].push(c)
const order: DateBucket[] = ['pinned', 'today', 'yesterday', 'thisWeek', 'older']
return order
.map((b) => ({ bucket: b, rows: buckets[b] }))
.filter((g) => g.rows.length > 0)
}, [filtered])
async function togglePin(id: string, current: boolean) {
setConversations((prev) =>
prev.map((c) => (c.id === id ? { ...c, pinned: !current } : c)),
)
await fetch(`/api/agent/conversations/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pinned: !current }),
})
}
async function archive(id: string) {
setConversations((prev) => prev.filter((c) => c.id !== id))
await fetch(`/api/agent/conversations/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ archived: true }),
})
if (activeId === id) startTransition(() => router.push('/chat'))
}
// Collapsed rail (desktop only). Mobile keeps the existing behavior where
// the sidebar IS the page when no conversation is open, so the rail is
// hidden below md. On desktop the rail keeps a thin column with toggle
// + new-chat buttons so the conversation pane runs near-edge-to-edge.
const railAside = collapsed ? (
<aside
className="hidden md:flex md:w-12 flex-col items-center border-r border-border bg-card/40 shrink-0 py-3 gap-2"
aria-label="Konversationer (hopfälld)"
>
<button
type="button"
onClick={toggleCollapsed}
aria-label="Visa konversationer"
title="Visa konversationer"
className="inline-flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
>
<PanelLeftOpen className="h-4 w-4" />
</button>
<div className="h-px w-6 bg-border" />
<button
type="button"
onClick={() => openAgentSheet({ intentId: 'general.help' })}
aria-label="Ny konversation"
title="Ny konversation"
className="inline-flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors text-lg"
>
+
</button>
</aside>
) : null
return (
<>
{railAside}
<aside
className={cn(
'flex-col border-r border-border bg-card/40 shrink-0',
// Mobile: sidebar IS the page when no conversation; hidden otherwise.
isConversationOpen ? 'hidden' : 'flex w-full',
// Desktop: hidden if collapsed (rail takes its place); else 320px.
collapsed ? 'md:hidden' : 'md:flex md:w-80',
)}
>
<div className="border-b border-border px-5 py-4 space-y-3">
<div className="flex items-center gap-2">
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName ?? 'Assistent'} />
<div className="flex-1 min-w-0">
<h2 className="font-display text-base tracking-tight truncate">
{agentName ?? 'Din assistent'}
</h2>
<p className="text-[11px] text-muted-foreground">Konversationer</p>
</div>
<button
onClick={toggleCollapsed}
aria-label="Dölj konversationer"
title="Dölj konversationer"
className="hidden md:inline-flex h-8 w-8 items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
>
<PanelLeftClose className="h-4 w-4" />
</button>
<button
onClick={() => openAgentSheet({ intentId: 'general.help' })}
className="text-xs uppercase tracking-wider text-muted-foreground hover:text-foreground transition-colors"
>
+ Ny
</button>
</div>
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Sök…"
className="w-full rounded-md border border-border bg-background pl-8 pr-7 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
{query.length > 0 && (
<button
type="button"
onClick={() => setQuery('')}
aria-label="Rensa sökning"
className="absolute right-1 top-1/2 -translate-y-1/2 inline-flex h-8 w-8 items-center justify-center rounded text-muted-foreground hover:bg-secondary hover:text-foreground"
>
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto">
{grouped.length === 0 ? (
<div className="p-6 text-sm text-muted-foreground">
{conversations.length === 0
? 'Inga konversationer ännu. Klicka på + Ny för att börja.'
: 'Inga träffar.'}
</div>
) : (
grouped.map(({ bucket, rows }) => (
<section key={bucket} className="py-2">
<p className="px-4 pb-1 text-[10px] uppercase tracking-wider text-muted-foreground">
{BUCKET_LABELS[bucket]}
</p>
<ul>
{rows.map((c) => (
<li key={c.id}>
<Link
href={`/chat/${c.id}`}
className={cn(
'group flex items-start gap-2 px-4 py-2 hover:bg-secondary/60 transition-colors border-l-2',
activeId === c.id
? 'bg-secondary/50 border-foreground'
: 'border-transparent',
)}
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<p className="text-sm font-medium truncate flex-1 min-w-0">
{c.title ?? intentLabel(c.intent_id)}
</p>
<p className="text-[11px] text-muted-foreground tabular-nums shrink-0">
{relativeTime(c.last_message_at ?? c.created_at)}
</p>
</div>
<p className="text-xs text-muted-foreground line-clamp-1 mt-0.5">
{c.last_message_preview ?? intentLabel(c.intent_id)}
</p>
</div>
{/* Always-visible action icons. Touch-friendly, no
hover-only invisibility on mobile. */}
<div className="flex flex-col gap-1 shrink-0 -mr-1">
<button
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
void togglePin(c.id, c.pinned)
}}
title={c.pinned ? 'Avfäst' : 'Fäst'}
aria-label={c.pinned ? 'Avfäst konversation' : 'Fäst konversation'}
className={cn(
'inline-flex h-8 w-8 items-center justify-center rounded transition-colors',
c.pinned
? 'text-foreground'
: 'text-muted-foreground/50 hover:text-foreground hover:bg-secondary',
)}
>
{c.pinned ? (
<Pin className="h-3 w-3" fill="currentColor" />
) : (
<PinOff className="h-3 w-3" />
)}
</button>
<button
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
void archive(c.id)
}}
title="Arkivera"
aria-label="Arkivera konversation"
className="inline-flex h-8 w-8 items-center justify-center rounded text-muted-foreground/50 hover:text-foreground hover:bg-secondary transition-colors"
>
<Archive className="h-3 w-3" />
</button>
</div>
</Link>
</li>
))}
</ul>
</section>
))
)}
</div>
</aside>
</>
)
}
function intentLabel(intentId: string): string {
switch (intentId) {
case 'general.help':
return 'Fråga din assistent'
case 'transaction.categorization':
return 'Hjälp med transaktion'
case 'invoice.draft':
return 'Hjälp med faktura'
case 'supplier_invoice.review':
return 'Granska leverantörsfaktura'
case 'vat.review':
return 'Granska moms­deklaration'
case 'bokslut.step':
return 'Hjälp med bokslut'
case 'verifikation.draft':
return 'Hjälp med verifikation'
case 'kpi.explain':
return 'Förklara nyckeltal'
default:
return intentId
}
}
+42
View File
@@ -0,0 +1,42 @@
// Avatar registry for the specialized accountant agent.
//
// We use the dicebear "notionists" style — clean line illustrations that
// match the editorial monochrome brand without the cartoony feel of most
// avatar libraries. 8 hand-picked seeds give distinct faces without being
// overwhelming. The user picks one during Phase B review; the choice is
// persisted as agent_profiles.avatar_id.
//
// URLs are served by dicebear's free CDN. They're public SVGs derived from
// the seed only — no user data leaves gnubok. If we ever need fully offline
// generation, swap to @dicebear/core npm package and render server-side.
export interface AvatarOption {
id: string
label: string
url: string
}
// Build URL from seed. Public dicebear CDN. ?radius=50 rounds the bounding
// box; ?backgroundColor=transparent keeps the editorial paper-white feel.
function dicebearNotionists(seed: string): string {
return `https://api.dicebear.com/9.x/notionists/svg?seed=${encodeURIComponent(seed)}&radius=50&backgroundColor=f5f3ed`
}
// Eight neutral seeds — names chosen to produce visibly different faces.
// Labels are just for the picker tooltip; the user names the agent
// themselves in the adjacent text field.
export const AVATAR_OPTIONS: readonly AvatarOption[] = [
{ id: 'notionists-1', label: 'Linn', url: dicebearNotionists('linn-revisor-1') },
{ id: 'notionists-2', label: 'Erik', url: dicebearNotionists('erik-revisor-2') },
{ id: 'notionists-3', label: 'Maja', url: dicebearNotionists('maja-revisor-3') },
{ id: 'notionists-4', label: 'Anders', url: dicebearNotionists('anders-revisor-4') },
{ id: 'notionists-5', label: 'Karin', url: dicebearNotionists('karin-revisor-5') },
{ id: 'notionists-6', label: 'Johan', url: dicebearNotionists('johan-revisor-6') },
{ id: 'notionists-7', label: 'Eva', url: dicebearNotionists('eva-revisor-7') },
{ id: 'notionists-8', label: 'Per', url: dicebearNotionists('per-revisor-8') },
]
export function getAvatarUrl(avatarId: string | null | undefined): string | null {
if (!avatarId) return null
return AVATAR_OPTIONS.find((a) => a.id === avatarId)?.url ?? null
}
@@ -20,6 +20,9 @@ import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
interface Props {
onApply: (lines: FormLine[], description: string) => void
entityType?: EntityType
/** Prefill the "total amount" field when the caller already knows it (e.g.
* booking from an underlag with a known total). The user can still edit it. */
defaultAmount?: number
}
const SCOPE_ICONS = {
@@ -28,7 +31,7 @@ const SCOPE_ICONS = {
company: Building2,
} as const
export default function BookingTemplatePicker({ onApply, entityType }: Props) {
export default function BookingTemplatePicker({ onApply, entityType, defaultAmount }: Props) {
const { toast } = useToast()
const [open, setOpen] = useState(false)
const [templates, setTemplates] = useState<BookingTemplateLibrary[]>([])
@@ -38,6 +41,15 @@ export default function BookingTemplatePicker({ onApply, entityType }: Props) {
const [amount, setAmount] = useState('')
const [selectedId, setSelectedId] = useState<string | null>(null)
// Prefill the amount from the caller's known total each time the picker
// opens. Only when provided — callers without a known amount (e.g. the
// journal-entry form) keep the blank-then-type behaviour.
useEffect(() => {
if (open && defaultAmount != null && defaultAmount > 0) {
setAmount(String(Math.round(defaultAmount * 100) / 100))
}
}, [open, defaultAmount])
const fetchTemplates = useCallback(async (signal?: AbortSignal) => {
setIsLoading(true)
try {
+279
View File
@@ -0,0 +1,279 @@
'use client'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import {
Receipt,
ArrowLeftRight,
Users,
Wallet,
Building2,
BookOpen,
BarChart3,
Upload,
Package,
ClipboardCheck,
HandCoins,
Wand2,
Inbox,
TrendingUp,
Settings,
HelpCircle,
ArrowRight,
type LucideIcon,
} from 'lucide-react'
import { cn } from '@/lib/utils'
type Entry = {
id: string
label: string
hint?: string
icon: LucideIcon
href: string
keywords?: string
}
const ACTION_ENTRIES: Entry[] = [
{ id: 'new-invoice', label: 'Ny faktura', hint: 'Skapa & skicka faktura', icon: Receipt, href: '/invoices/new', keywords: 'fakturera ny invoice send create' },
{ id: 'book-transaction', label: 'Boka transaktion', hint: 'Gå till transaktionsinkorgen', icon: ArrowLeftRight, href: '/transactions', keywords: 'transaktion bokför kategorisera categorize' },
{ id: 'new-customer', label: 'Lägg till kund', icon: Users, href: '/customers', keywords: 'kund customer ny lägg till' },
{ id: 'new-supplier-invoice', label: 'Skapa leverantörsfaktura', icon: Wallet, href: '/supplier-invoices/new', keywords: 'leverantörsfaktura supplier invoice ny' },
{ id: 'reports', label: 'Visa resultaträkning', hint: 'Rapporter', icon: BarChart3, href: '/reports', keywords: 'rapport resultat balans report' },
]
const PAGE_ENTRIES: Entry[] = [
{ id: 'kunder', label: 'Kunder', icon: Users, href: '/customers' },
{ id: 'leverantörer', label: 'Leverantörer', icon: Building2, href: '/suppliers' },
{ id: 'leverantörsfakturor', label: 'Leverantörsfakturor', icon: Wallet, href: '/supplier-invoices' },
{ id: 'bokföring', label: 'Bokföring', icon: BookOpen, href: '/bookkeeping', keywords: 'verifikat journal ledger' },
{ id: 'anläggningstillgångar', label: 'Anläggningstillgångar', icon: Package, href: '/assets', keywords: 'tillgångar assets' },
{ id: 'rapporter', label: 'Rapporter', icon: BarChart3, href: '/reports' },
{ id: 'importera', label: 'Importera', icon: Upload, href: '/import' },
{ id: 'granskning', label: 'Granskning', icon: ClipboardCheck, href: '/pending', keywords: 'pending review' },
{ id: 'löner', label: 'Löner', icon: HandCoins, href: '/salary' },
{ id: 'anställda', label: 'Anställda', icon: Users, href: '/salary/employees' },
{ id: 'dokumentinkorg', label: 'Dokumentinkorg', icon: Inbox, href: '/e/general/invoice-inbox' },
{ id: 'nyckeltal', label: 'Nyckeltal', icon: TrendingUp, href: '/kpi' },
{ id: 'inställningar', label: 'Inställningar', icon: Settings, href: '/settings' },
{ id: 'hjälp', label: 'Hjälp', icon: HelpCircle, href: '/help' },
]
function matches(entry: Entry, q: string): boolean {
const hay = `${entry.label} ${entry.hint ?? ''} ${entry.keywords ?? ''}`.toLowerCase()
return q.split(/\s+/).filter(Boolean).every(t => hay.includes(t))
}
export default function CommandPalette() {
const router = useRouter()
const [open, setOpen] = useState(false)
const [query, setQuery] = useState('')
const [activeIndex, setActiveIndex] = useState(0)
const inputRef = useRef<HTMLInputElement>(null)
function handleOpenChange(next: boolean) {
setOpen(next)
if (!next) {
setQuery('')
setActiveIndex(0)
}
}
// Global ⌘K / Ctrl+K
useEffect(() => {
function onKey(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault()
setOpen(prev => !prev)
}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [])
useEffect(() => {
if (!open) return
const raf = requestAnimationFrame(() => inputRef.current?.focus())
return () => cancelAnimationFrame(raf)
}, [open])
const q = query.trim().toLowerCase()
const filteredActions = useMemo(
() => (q ? ACTION_ENTRIES.filter(e => matches(e, q)) : ACTION_ENTRIES),
[q],
)
const filteredPages = useMemo(
() => (q ? PAGE_ENTRIES.filter(e => matches(e, q)) : PAGE_ENTRIES.slice(0, 6)),
[q],
)
const annaFallback: Entry | null = q && filteredActions.length === 0 && filteredPages.length === 0
? {
id: 'anna-fallback',
label: `Fråga Anna: "${query.trim()}"`,
icon: Wand2,
href: `/chat?prompt=${encodeURIComponent(query.trim())}`,
}
: q
? {
id: 'anna-followup',
label: `Fråga Anna istället: "${query.trim()}"`,
icon: Wand2,
href: `/chat?prompt=${encodeURIComponent(query.trim())}`,
}
: null
const flatEntries: Entry[] = [
...(annaFallback && filteredActions.length === 0 && filteredPages.length === 0 ? [annaFallback] : []),
...filteredActions,
...filteredPages,
...(annaFallback && (filteredActions.length > 0 || filteredPages.length > 0) ? [annaFallback] : []),
]
function commit(entry: Entry) {
setOpen(false)
router.push(entry.href)
}
function onInputKey(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setActiveIndex(i => Math.min(flatEntries.length - 1, i + 1))
} else if (e.key === 'ArrowUp') {
e.preventDefault()
setActiveIndex(i => Math.max(0, i - 1))
} else if (e.key === 'Enter') {
e.preventDefault()
const target = flatEntries[activeIndex]
if (target) commit(target)
}
}
return (
<DialogPrimitive.Root open={open} onOpenChange={handleOpenChange}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay
className="fixed inset-0 z-50 bg-black/40 backdrop-blur-[2px] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
/>
<DialogPrimitive.Content
aria-label="Snabbkommandon"
className="fixed left-[50%] top-[20%] z-50 w-[calc(100vw-2rem)] max-w-xl translate-x-[-50%] rounded-xl border border-border bg-card data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
>
<DialogPrimitive.Title className="sr-only">Snabbkommandon</DialogPrimitive.Title>
<DialogPrimitive.Description className="sr-only">
Sök efter sidor och åtgärder, eller fråga Anna.
</DialogPrimitive.Description>
<div className="px-4 py-3 border-b border-border">
<input
ref={inputRef}
value={query}
onChange={e => { setQuery(e.target.value); setActiveIndex(0) }}
onKeyDown={onInputKey}
placeholder="Sök eller skriv vad du vill göra…"
aria-label="Sök eller skriv vad du vill göra"
className="w-full bg-transparent text-base placeholder:text-muted-foreground outline-none"
/>
</div>
<div className="max-h-[60vh] overflow-y-auto py-1.5" role="listbox">
{filteredActions.length > 0 && (
<Section title="Åtgärder">
{filteredActions.map((entry) => {
const idx = flatEntries.indexOf(entry)
return (
<Row
key={entry.id}
entry={entry}
active={idx === activeIndex}
onSelect={() => commit(entry)}
onHover={() => setActiveIndex(idx)}
/>
)
})}
</Section>
)}
{filteredPages.length > 0 && (
<Section title="Sidor">
{filteredPages.map((entry) => {
const idx = flatEntries.indexOf(entry)
return (
<Row
key={entry.id}
entry={entry}
active={idx === activeIndex}
onSelect={() => commit(entry)}
onHover={() => setActiveIndex(idx)}
/>
)
})}
</Section>
)}
{annaFallback && (
<Section title="Anna">
<Row
entry={annaFallback}
active={flatEntries.indexOf(annaFallback) === activeIndex}
onSelect={() => commit(annaFallback)}
onHover={() => setActiveIndex(flatEntries.indexOf(annaFallback))}
/>
</Section>
)}
{flatEntries.length === 0 && (
<div className="px-4 py-8 text-center text-sm text-muted-foreground">
Inget hittades. Tryck Enter eller börja om.
</div>
)}
</div>
<div className="px-4 py-2 border-t border-border flex items-center justify-between text-[11px] text-muted-foreground">
<span>↑↓ navigera · Enter välj · Esc stäng</span>
<span className="font-mono">⌘K</span>
</div>
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
)
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<div className="mb-1.5 last:mb-0">
<p className="px-4 pt-2 pb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground">{title}</p>
<div>{children}</div>
</div>
)
}
function Row({
entry,
active,
onSelect,
onHover,
}: {
entry: Entry
active: boolean
onSelect: () => void
onHover: () => void
}) {
const Icon = entry.icon
return (
<button
type="button"
role="option"
aria-selected={active}
onMouseEnter={onHover}
onFocus={onHover}
onClick={onSelect}
className={cn(
'w-full text-left flex items-center gap-3 px-4 py-2 text-sm transition-colors',
active ? 'bg-secondary text-foreground' : 'text-foreground hover:bg-secondary/60',
)}
>
<Icon className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<span className="flex-1 truncate">{entry.label}</span>
{entry.hint && <span className="text-xs text-muted-foreground">{entry.hint}</span>}
{active && <ArrowRight className="h-3.5 w-3.5 text-muted-foreground" />}
</button>
)
}
+38
View File
@@ -0,0 +1,38 @@
import Link from 'next/link'
import { MessageCircle, ArrowRight } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
interface Props {
companyName: string
}
// Renders above the dashboard when the active company has no verified
// agent_profile yet. Mounted from the dashboard server component which
// already does the existence check, so this component itself doesn't fetch.
//
// Single CTA, no dismiss — building the agent is part of onboarding and
// once verified it disappears on its own.
export default function AgentSetupBanner({ companyName }: Props) {
return (
<Link
href="/onboarding/agent"
className="group block rounded-lg border border-border bg-card hover:bg-secondary/60 transition-colors duration-150 mb-8"
>
<div className="flex items-center gap-4 p-5">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-foreground text-background shrink-0">
<MessageCircle className="h-4 w-4" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-display text-lg tracking-tight">Bygg din bokföringsassistent</p>
<Badge variant="secondary" className="uppercase tracking-wider">Beta</Badge>
</div>
<p className="text-sm text-muted-foreground mt-1">
Skräddarsy en hjälp som kan ditt företag — laddas på under en halv minut för {companyName}.
</p>
</div>
<ArrowRight className="h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors shrink-0" />
</div>
</Link>
)
}
+131 -3
View File
@@ -4,6 +4,7 @@ import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { cn, formatCurrency } from '@/lib/utils'
import { UpcomingDeadlinesWidget } from '@/components/deadlines/UpcomingDeadlinesWidget'
import { TaxTodoWidget } from '@/components/deadlines/TaxTodoWidget'
@@ -17,8 +18,11 @@ import {
CheckCircle2,
FileWarning,
Clock,
ArrowRight,
MessageCircle,
} from 'lucide-react'
import type { Deadline, ReceiptQueueSummary, OnboardingProgress } from '@/types'
import { getBranding } from '@/lib/branding/service'
const setupFreshStartKey = (companyId: string) => `erp_setup_fresh_start:${companyId}`
@@ -42,9 +46,16 @@ interface DashboardContentProps {
staleUncategorizedCount: number
}
onboardingProgress?: OnboardingProgress
/**
* False until the company has a verified agent_profile. When false the hero
* slot shows a build-assistant prompt instead of the next-best-action card,
* so existing/migrated users are nudged to build the assistant without a
* full-screen onboarding takeover.
*/
agentBuilt?: boolean
}
export default function DashboardContent({ companyId, summary, onboardingProgress }: DashboardContentProps) {
export default function DashboardContent({ companyId, summary, onboardingProgress, agentBuilt = true }: DashboardContentProps) {
const [showAllAlerts, setShowAllAlerts] = useState(false)
const t = useTranslations('dashboard')
@@ -226,8 +237,125 @@ export default function DashboardContent({ companyId, summary, onboardingProgres
: 0
const todoCount = summary.uncategorizedCount + summary.overdueInvoicesCount + pendingReceiptsCount + passedDeadlinesCount
const slim = getBranding().navDensity === 'slim'
// Pick the single most-urgent next action so the launchpad surfaces one
// unambiguous CTA. Order matches the friction we actually want to remove
// first: stale → overdue → uncategorized → unpaid → all clear.
const nextBestAction = (() => {
if (summary.staleUncategorizedCount > 0) {
return {
href: '/transactions',
title: 'Gamla transaktioner väntar',
body: `${summary.staleUncategorizedCount} transaktion${summary.staleUncategorizedCount === 1 ? '' : 'er'} äldre än 14 dagar saknar bokföring.`,
cta: 'Bokför nu',
tone: 'destructive' as const,
icon: Clock,
}
}
if (summary.overdueInvoicesCount > 0) {
return {
href: '/invoices?status=unpaid',
title: 'Förfallna fakturor',
body: `${summary.overdueInvoicesCount} st · ${formatCurrency(summary.unpaidInvoicesTotal)}`,
cta: 'Gå till fakturor',
tone: 'destructive' as const,
icon: Receipt,
}
}
if (summary.uncategorizedCount > 0) {
return {
href: '/transactions',
title: 'Transaktioner att bokföra',
body: `${summary.uncategorizedCount} obokförd${summary.uncategorizedCount === 1 ? '' : 'a'} transaktion${summary.uncategorizedCount === 1 ? '' : 'er'}.`,
cta: 'Bokför nu',
tone: 'primary' as const,
icon: ArrowLeftRight,
}
}
if (summary.unpaidInvoicesCount > 0) {
return {
href: '/invoices?status=unpaid',
title: 'Obetalda fakturor',
body: `${summary.unpaidInvoicesCount} st · ${formatCurrency(summary.unpaidInvoicesTotal)}`,
cta: 'Visa fakturor',
tone: 'primary' as const,
icon: Receipt,
}
}
return {
href: '/invoices/new',
title: 'Allt är ikapp',
body: 'Inga obokförda transaktioner och inga obetalda fakturor. Skicka nästa faktura?',
cta: 'Skapa faktura',
tone: 'neutral' as const,
icon: CheckCircle2,
}
})()
return (
<div className="stagger-enter space-y-8">
{!agentBuilt ? (
/* Build-assistant hero — shown until the company has a verified
agent_profile. Takes the hero slot so existing/migrated users get a
clear prompt instead of a full-screen onboarding takeover. */
<section>
<Link href="/onboarding/agent" className="block group">
<Card className="transition-colors hover:border-primary/50">
<CardContent className="p-6 flex items-center gap-5">
<div className="flex-shrink-0 h-10 w-10 rounded-lg flex items-center justify-center bg-foreground text-background">
<MessageCircle className="h-5 w-5" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-display text-xl leading-tight">Bygg din bokföringsassistent</p>
<Badge variant="secondary" className="uppercase tracking-wider">Beta</Badge>
</div>
<p className="text-sm text-muted-foreground mt-1">
Några frågor om din verksamhet kalibrerar en assistent som föreslår bokföring åt dig.
</p>
</div>
<div className="hidden sm:flex items-center gap-1.5 text-sm font-medium text-foreground group-hover:translate-x-0.5 transition-transform">
<span>Kom igång</span>
<ArrowRight className="h-4 w-4" />
</div>
</CardContent>
</Card>
</Link>
</section>
) : slim ? (
/* Next best action — single hero card */
<section>
<Link href={nextBestAction.href} className="block group">
<Card className={cn(
'transition-colors',
nextBestAction.tone === 'destructive' && 'border-destructive/30 hover:bg-destructive/[0.03]',
nextBestAction.tone === 'primary' && 'hover:border-primary/50',
nextBestAction.tone === 'neutral' && 'hover:border-primary/30',
)}>
<CardContent className="p-6 flex items-center gap-5">
<div className={cn(
'flex-shrink-0 h-10 w-10 rounded-lg flex items-center justify-center',
nextBestAction.tone === 'destructive' && 'bg-destructive/10 text-destructive',
nextBestAction.tone === 'primary' && 'bg-secondary text-foreground',
nextBestAction.tone === 'neutral' && 'bg-secondary text-foreground',
)}>
<nextBestAction.icon className="h-5 w-5" />
</div>
<div className="flex-1 min-w-0">
<p className="font-display text-xl leading-tight">{nextBestAction.title}</p>
<p className="text-sm text-muted-foreground mt-1">{nextBestAction.body}</p>
</div>
<div className="flex items-center gap-1.5 text-sm font-medium text-foreground group-hover:translate-x-0.5 transition-transform">
<span>{nextBestAction.cta}</span>
<ArrowRight className="h-4 w-4" />
</div>
</CardContent>
</Card>
</Link>
</section>
) : null}
{/* Key metrics — 4 compact cards */}
<section>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
@@ -345,8 +473,8 @@ export default function DashboardContent({ companyId, summary, onboardingProgres
</div>
</section>
{/* Alerts */}
{alertItems.length > 0 && (
{/* Att hantera — hidden in slim mode; the hero card already surfaces the top action */}
{!slim && alertItems.length > 0 && (
<section id="alerts-section">
<h2 className="font-display text-lg font-medium mb-4">{t('alerts_title')}</h2>
<div id="alerts-list" className="grid gap-4 md:grid-cols-2">
File diff suppressed because it is too large Load Diff
+8 -4
View File
@@ -5,8 +5,8 @@ import type { ReactNode } from 'react'
/**
* Picks the dashboard chrome container based on route. Extension workspaces
* (/e/*) want the full viewport for file viewers and dashboards; everything
* else gets the centered max-w-5xl card.
* (/e/*) and the /chat app shell want the full viewport for their own
* multi-pane layouts; everything else gets the centered max-w-5xl card.
*
* Lives in a client component because the parent (dashboard) layout is
* shared across all dashboard routes. Server-side pathname checks done in
@@ -22,9 +22,13 @@ export function MainContainer({
children: ReactNode
}) {
const pathname = usePathname()
const isExtensionWorkspace = pathname.startsWith('/e/')
// Full-bleed routes own their own padding + multi-pane layout. They
// shouldn't sit inside max-w-5xl or any horizontal padding — that's what
// causes a visible gap between the dashboard sidebar and the chat-sidebar
// pane on wide viewports.
const isFullBleed = pathname.startsWith('/e/') || pathname.startsWith('/chat')
return isExtensionWorkspace ? (
return isFullBleed ? (
<div key={companyId ?? ''} className="h-full">{children}</div>
) : (
<div
+87 -6
View File
@@ -50,6 +50,42 @@ function logError(message: string, extra?: Record<string, unknown>) {
}).catch(() => {})
}
// Parse TIC v2's `startMonthDay` ("MM-DD" — e.g. "07-01") into a month
// number 1–12. Returns null on missing / malformed input so the caller
// can fall through to the manual picker default.
function parseStartMonthDay(value: string | null | undefined): number | null {
if (!value) return null
const match = /^(\d{1,2})-\d{1,2}$/.exec(value)
if (!match) return null
const month = Number(match[1])
if (!Number.isInteger(month) || month < 1 || month > 12) return null
return month
}
// Derive the Step-3 first-year defaults from TIC's `registrationDate`.
// A company is treated as "first year" when registered less than 12 months
// ago — fits BFL's 6-18 month opening-period window comfortably. Returns
// both the toggle state and a seeded `first_year_start` (always the 1st of
// the registration month, the format Step 3's date inputs expect).
function deriveFirstYearDefaults(registrationDate: number | null | undefined): {
isFirstFiscalYear: boolean
firstYearStart: string | undefined
} {
if (!registrationDate || !Number.isFinite(registrationDate)) {
return { isFirstFiscalYear: false, firstYearStart: undefined }
}
const regDate = new Date(registrationDate)
if (Number.isNaN(regDate.getTime())) {
return { isFirstFiscalYear: false, firstYearStart: undefined }
}
const monthsAgo =
(Date.now() - regDate.getTime()) / (1000 * 60 * 60 * 24 * 30.44)
if (monthsAgo >= 12) return { isFirstFiscalYear: false, firstYearStart: undefined }
const year = regDate.getUTCFullYear()
const month = String(regDate.getUTCMonth() + 1).padStart(2, '0')
return { isFirstFiscalYear: true, firstYearStart: `${year}-${month}-01` }
}
interface WelcomeOnboardingProps {
firstName?: string | null
teamId: string
@@ -57,6 +93,15 @@ interface WelcomeOnboardingProps {
hasExistingCompanies?: boolean
/** Pre-fill Step 2 org_number when the picker routed here via ?org_number=. */
initialOrgNumber?: string
/** Mapped from a TIC `legalEntityType`. Pre-selects Step 1's radio. */
initialEntityType?: EntityType
/** Legal name from CompanyRoles. Pre-fills Step 2's company_name field. */
initialLegalName?: string
/** Set when the orgnr came from BankID CompanyRoles. Step 2 treats the
* field as pre-verified — skips the client-side Lens `/lookup` since
* CompanyRoles already confirms the company exists. Cleared the moment
* the user edits the orgnr. */
preverifiedOrgNumber?: string
}
export default function WelcomeOnboarding({
@@ -65,6 +110,9 @@ export default function WelcomeOnboarding({
skipWelcome,
hasExistingCompanies,
initialOrgNumber,
initialEntityType,
initialLegalName,
preverifiedOrgNumber,
}: WelcomeOnboardingProps) {
const router = useRouter()
const { toast } = useToast()
@@ -74,9 +122,17 @@ export default function WelcomeOnboarding({
const [started, setStarted] = useState(skipWelcome ?? false)
const [isSaving, setIsSaving] = useState(false)
const [currentStep, setCurrentStep] = useState(1)
const [settings, setSettings] = useState<Partial<CompanySettings>>(
initialOrgNumber ? { org_number: initialOrgNumber } : {},
)
// Seed settings with what BankID CompanyRoles already told us. address /
// F-skatt / VAT come later — user types address in Step 2 and confirms
// F-skatt/VAT in Step 4. We deliberately don't pre-fetch from Lens to
// preserve the 3000/mo budget for the manual-orgnr path.
const [settings, setSettings] = useState<Partial<CompanySettings>>(() => {
const seed: Partial<CompanySettings> = {}
if (initialOrgNumber) seed.org_number = initialOrgNumber
if (initialEntityType) seed.entity_type = initialEntityType
if (initialLegalName) seed.company_name = initialLegalName
return seed
})
const ticEnabled = ENABLED_EXTENSION_IDS.has('tic')
const [ticLookup, setTicLookup] = useState<CompanyLookupResult | null>(null)
@@ -144,6 +200,7 @@ export default function WelcomeOnboarding({
endDate: periodResult.endStr,
name: periodResult.periodName,
},
ticLookup,
})
if (result.error || !result.companyId) {
@@ -299,24 +356,48 @@ export default function WelcomeOnboarding({
entityType={settings.entity_type as EntityType}
ticEnabled={ticEnabled}
onTicLookup={setTicLookup}
preverifiedOrgNumber={preverifiedOrgNumber}
onNext={(data) => handleNext(data)}
onBack={handleBack}
isSaving={isSaving}
/>
)}
{currentStep === 3 && (
{currentStep === 3 && (() => {
// Derive both first-year defaults from TIC's registrationDate
// (null-safe — returns { false, undefined } for established
// companies and for missing registrationDate).
const firstYearDefaults = deriveFirstYearDefaults(
ticLookup?.registrationDate,
)
return (
<Step3TaxRegistration
initialData={{
f_skatt: settings.f_skatt ?? (ticLookup ? ticLookup.registration.fTax : undefined),
fiscal_year_start_month: settings.fiscal_year_start_month ?? undefined,
// Prefer the user's previously-saved value, then fall back
// to TIC's v2 `fiscalYear.startMonthDay` (e.g. "07-01" →
// start month 7). Parsing the MM-DD lets us skip the
// manual end-month picker for the ~95% of companies that
// have a registered fiscal year in Bolagsverket.
fiscal_year_start_month:
settings.fiscal_year_start_month
?? parseStartMonthDay(ticLookup?.fiscalYear?.startMonthDay)
?? undefined,
// Companies registered <12 months ago land in their first
// fiscal year — pre-check the toggle and seed the start
// date so the user only confirms the end date.
is_first_fiscal_year:
settings.is_first_fiscal_year ?? firstYearDefaults.isFirstFiscalYear,
first_year_start:
settings.first_year_start ?? firstYearDefaults.firstYearStart,
}}
entityType={settings.entity_type as EntityType}
onNext={(data) => handleNext(data)}
onBack={handleBack}
isSaving={isSaving}
/>
)}
)
})()}
{currentStep === 4 && (
<Step4VatAccounting
@@ -18,13 +18,16 @@ import { useToast } from '@/components/ui/use-toast'
import { Loader2, Plus, Trash2, AlertTriangle, Search, Check } from 'lucide-react'
import { cn, formatCurrency } from '@/lib/utils'
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import BookingTemplatePicker from '@/components/bookkeeping/BookingTemplatePicker'
import { ActivateAccountsDialog } from '@/components/bookkeeping/ActivateAccountsDialog'
import { useCompany } from '@/contexts/CompanyContext'
import {
useSubmitWithAccountActivation,
throwOnStructuredError,
} from '@/lib/hooks/use-submit-with-account-activation'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
import type { BASAccount, FiscalPeriod, InvoiceExtractionResult } from '@/types'
interface InboxItem {
@@ -40,6 +43,19 @@ interface PickerTransaction {
description: string
amount: number
currency: string | null
amount_sek?: number | null
exchange_rate?: number | null
}
// SEK magnitude of a (usually-SEK) bank transaction. Foreign rows are
// normalised via their stored amount_sek/exchange_rate so ranking against the
// underlag's SEK value is apples-to-apples.
function txSekAmount(tx: PickerTransaction): number {
const cur = (tx.currency ?? 'SEK').toUpperCase()
if (cur === 'SEK') return Math.abs(tx.amount)
return Math.abs(
resolveSekAmount(tx.amount, tx.amount_sek ?? null, tx.currency, tx.exchange_rate ?? null),
)
}
interface FormLine {
@@ -116,21 +132,31 @@ function buildPrefillLines(
return lines
}
function rankByAmount(
// Rank candidates by closeness to the underlag's SEK value. `targetSek` is the
// document total already converted to SEK (the bank charge for a 216 USD
// receipt is ~2 109 kr, not 216) — ranking against the raw foreign total used
// to bury the real match far down the list. Null target → leave order intact.
function rankBySekCloseness(
rows: PickerTransaction[],
target: number | null
targetSek: number | null
): PickerTransaction[] {
if (target == null) return rows
const abs = Math.abs(target)
return [...rows].sort((a, b) => {
const da = Math.abs(Math.abs(a.amount) - abs)
const db = Math.abs(Math.abs(b.amount) - abs)
return da - db
})
if (targetSek == null) return rows
const abs = Math.abs(targetSek)
return [...rows].sort((a, b) => Math.abs(txSekAmount(a) - abs) - Math.abs(txSekAmount(b) - abs))
}
export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess }: Props) {
const { toast } = useToast()
const { company } = useCompany()
// Underlag total + currency. Booking happens in SEK, so a foreign total needs
// an FX rate to rank/compare against the (SEK) bank transactions.
const targetAmount = item.extracted_data?.totals?.total ?? null
const targetCurrency = (item.extracted_data?.invoice?.currency ?? 'SEK').toUpperCase()
// SEK per unit of the underlag currency (e.g. ~9.8 for USD). null = SEK,
// pending, or unsupported.
const [fxRate, setFxRate] = useState<number | null>(null)
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
const [accounts, setAccounts] = useState<BASAccount[]>([])
const [entryDate, setEntryDate] = useState<string>(
@@ -168,13 +194,50 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, item.id])
// Fetch the underlag's SEK rate for a foreign-currency document so candidate
// transactions can be ranked against the SEK-equivalent total (and not the
// raw foreign number). SEK / unsupported currencies skip the fetch.
useEffect(() => {
if (!open) return
setFxRate(null)
if (targetCurrency === 'SEK' || !['EUR', 'USD', 'GBP', 'NOK', 'DKK'].includes(targetCurrency)) {
return
}
let cancelled = false
const invoiceDate = item.extracted_data?.invoice?.invoiceDate
const dateParam = invoiceDate ? `&date=${invoiceDate}` : ''
fetch(`/api/currency/rate?currency=${targetCurrency}${dateParam}`)
.then((r) => (r.ok ? r.json() : null))
.then((body) => {
if (cancelled) return
const rate = body?.data?.rate
if (typeof rate === 'number' && rate > 0) setFxRate(rate)
})
.catch(() => { /* leave null — ranking falls back to face amounts */ })
return () => { cancelled = true }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, targetCurrency, item.id])
// SEK-equivalent of the underlag total — the anchor for ranking candidates.
const targetSek = useMemo(() => {
if (targetAmount == null) return null
if (targetCurrency === 'SEK') return targetAmount
if (fxRate != null) return Math.round(targetAmount * fxRate * 100) / 100
return null
}, [targetAmount, targetCurrency, fxRate])
// When the user picks a transaction (or the toggle changes), re-derive
// the prefilled amounts so foreign-currency invoices follow the SEK
// figure on the actual bank movement.
// figure on the actual bank movement. Normalised to SEK — a foreign bank
// row is booked at its SEK value, never its face amount.
const selectedTransactionAmount = useMemo(() => {
if (!selectedTransactionId) return null
const tx = transactions.find((t) => t.id === selectedTransactionId)
return tx?.amount ?? null
if (!tx) return null
const cur = (tx.currency ?? 'SEK').toUpperCase()
return cur === 'SEK'
? tx.amount
: resolveSekAmount(tx.amount, tx.amount_sek ?? null, tx.currency, tx.exchange_rate ?? null)
}, [selectedTransactionId, transactions])
useEffect(() => {
@@ -237,7 +300,6 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
if (!open) return
let cancelled = false
setIsLoadingTransactions(true)
const targetAmount = item.extracted_data?.totals?.total ?? null
;(async () => {
try {
const res = await fetch('/api/transactions?unmatched=true')
@@ -250,8 +312,11 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
description: t.description,
amount: t.amount,
currency: t.currency || 'SEK',
amount_sek: t.amount_sek ?? null,
exchange_rate: t.exchange_rate ?? null,
}))
setTransactions(rankByAmount(rows, targetAmount))
// Ranking happens in a memo (it depends on the async FX rate).
setTransactions(rows)
} catch (err) {
console.error('[book-direct] fetch transactions failed:', err)
} finally {
@@ -259,13 +324,30 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
}
})()
return () => { cancelled = true }
}, [open, item.extracted_data?.totals?.total])
}, [open])
// FX-aware ranking by closeness to the underlag's SEK value.
const rankedTransactions = useMemo(
() => rankBySekCloseness(transactions, targetSek),
[transactions, targetSek],
)
const filteredTransactions = useMemo(() => {
const term = txSearch.trim().toLowerCase()
if (!term) return transactions
return transactions.filter((t) => (t.description || '').toLowerCase().includes(term))
}, [transactions, txSearch])
if (!term) return rankedTransactions
return rankedTransactions.filter((t) => (t.description || '').toLowerCase().includes(term))
}, [rankedTransactions, txSearch])
// Pin the already-selected/matched transaction to the top so it's always
// visible — otherwise a correct match that ranks past the rendered cap looks
// unselected and the user re-picks it. The pinned row carries a "Matchad"
// badge when it's the one matched in the inbox.
const displayedTransactions = useMemo(() => {
if (!selectedTransactionId) return filteredTransactions
const sel = filteredTransactions.find((t) => t.id === selectedTransactionId)
if (!sel) return filteredTransactions
return [sel, ...filteredTransactions.filter((t) => t.id !== selectedTransactionId)]
}, [filteredTransactions, selectedTransactionId])
const totals = useMemo(() => {
const debit = lines.reduce((sum, l) => sum + (parseFloat(l.debit_amount) || 0), 0)
@@ -292,6 +374,27 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
setLines((prev) => prev.length <= 2 ? prev : prev.filter((_, i) => i !== idx))
}, [])
// Replace the line set with a booking template's computed rows. The picker
// hands back JournalEntryForm-shaped lines; we keep only the three fields
// book-direct posts. A meaningful supplier description is preserved — the
// template name only fills an empty field.
const handleTemplateApply = useCallback(
(
templateLines: Array<{ account_number: string; debit_amount: string; credit_amount: string }>,
templateDescription: string,
) => {
setLines(
templateLines.map((l) => ({
account_number: l.account_number,
debit_amount: l.debit_amount,
credit_amount: l.credit_amount,
})),
)
setDescription((prev) => (prev.trim() ? prev : templateDescription))
},
[],
)
const disabledReason = useMemo(() => {
if (isSubmitting) return null
if (!entryDate) return 'Välj datum'
@@ -366,9 +469,6 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
}
}, [canSubmit, runSubmit, toast, onSuccess, onOpenChange])
const targetAmount = item.extracted_data?.totals?.total ?? null
const targetCurrency = item.extracted_data?.invoice?.currency ?? 'SEK'
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
@@ -465,8 +565,11 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
</p>
) : (
<ul className="divide-y">
{filteredTransactions.slice(0, 30).map((tx) => {
{displayedTransactions.slice(0, 30).map((tx) => {
const isSelected = selectedTransactionId === tx.id
const isInboxMatch = item.matched_transaction_id === tx.id
const cur = (tx.currency || 'SEK').toUpperCase()
const sek = txSekAmount(tx)
return (
<li key={tx.id}>
<button
@@ -488,17 +591,31 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
) : null}
</span>
<div className="min-w-0 flex-1">
<p className="truncate">{tx.description}</p>
<div className="flex items-center gap-1.5 min-w-0">
<p className="truncate">{tx.description}</p>
{isInboxMatch && (
<Badge variant="secondary" className="shrink-0 text-[10px] px-1.5 py-0">
Matchad
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground tabular-nums">{tx.date}</p>
</div>
<span
className={cn(
'tabular-nums text-sm shrink-0',
tx.amount < 0 ? 'text-destructive' : 'text-foreground'
<div className="text-right shrink-0">
<span
className={cn(
'tabular-nums text-sm block',
tx.amount < 0 ? 'text-destructive' : 'text-foreground'
)}
>
{formatCurrency(tx.amount, tx.currency || 'SEK')}
</span>
{cur !== 'SEK' && (
<span className="text-[11px] text-muted-foreground tabular-nums">
≈ {formatCurrency(sek, 'SEK')}
</span>
)}
>
{formatCurrency(tx.amount, tx.currency || 'SEK')}
</span>
</div>
</button>
</li>
)
@@ -627,16 +744,27 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
</table>
</div>
<div className="flex items-center justify-between gap-3">
<Button
type="button"
variant="ghost"
size="sm"
onClick={addLine}
disabled={isSubmitting}
>
<Plus className="h-3.5 w-3.5 mr-1.5" />
Lägg till rad
</Button>
<div className="flex items-center gap-2">
<Button
type="button"
variant="ghost"
size="sm"
onClick={addLine}
disabled={isSubmitting}
>
<Plus className="h-3.5 w-3.5 mr-1.5" />
Lägg till rad
</Button>
<BookingTemplatePicker
onApply={handleTemplateApply}
entityType={company?.entity_type}
defaultAmount={
selectedTransactionAmount != null
? Math.abs(selectedTransactionAmount)
: targetSek ?? undefined
}
/>
</div>
{totals.balanced ? (
<Badge variant="success" className="text-[11px]">
Balanserad
@@ -30,6 +30,8 @@ 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'
@@ -94,6 +96,24 @@ 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.
@@ -150,12 +170,16 @@ function WorkspaceSkeleton() {
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).
const [filter, setFilter] = useState<'all' | 'needs_action' | 'done' | 'error'>('all')
// 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
@@ -179,6 +203,9 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
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.
@@ -188,7 +215,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
const fetchItems = useCallback(async () => {
try {
const res = await fetch('/api/extensions/ext/invoice-inbox/items?limit=50')
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) {
@@ -263,19 +290,44 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
// ── 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
const isErr = item.status === 'error'
const isDone =
!!item.created_supplier_invoice_id ||
!!item.matched_transaction_id ||
!!item.created_journal_entry_id
const needsAction = !isErr && !isDone
if (filter === 'error' && !isErr) return false
if (filter === 'done' && !isDone) return false
if (filter === 'needs_action' && !needsAction) return false
// 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
@@ -672,14 +724,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
/>
</div>
<div className="flex flex-wrap gap-1">
{(
[
{ key: 'all', label: 'Alla' },
{ key: 'needs_action', label: 'Behöver åtgärd' },
{ key: 'done', label: 'Bearbetade' },
{ key: 'error', label: 'Fel' },
] as const
).map((pill) => (
{pills.map((pill) => (
<button
key={pill.key}
type="button"
@@ -692,6 +737,16 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
)}
>
{pill.label}
{pill.count > 0 && (
<span
className={cn(
'ml-1 tabular-nums',
filter === pill.key ? 'opacity-80' : 'opacity-50'
)}
>
{pill.count}
</span>
)}
</button>
))}
</div>
@@ -761,7 +816,9 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
)
) : filteredItems.length === 0 ? (
<div className="p-6 text-center text-xs text-muted-foreground">
Inga poster matchar filtret.
{filter === 'todo'
? 'Inget att åtgärda — allt är bearbetat.'
: 'Inga poster matchar filtret.'}
</div>
) : (
<ul>
@@ -824,6 +881,35 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
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)])
@@ -864,6 +950,17 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
}}
/>
)}
{selected && (
<TransactionMatchPicker
open={matchPickerOpen}
onClose={() => setMatchPickerOpen(false)}
inboxItemId={selected.id}
extractedData={selected.extracted_data}
onMatched={async () => {
await Promise.all([fetchItems(), handleSelect(selected.id)])
}}
/>
)}
</div>
)
}
@@ -890,10 +987,11 @@ function InboxRow({
}) {
const amount = pickAmount(item)
const supplierName = pickSupplierName(item)
const isErrored = item.status === 'error'
const isProcessed = !!item.created_supplier_invoice_id
const isLinkedToTransaction = !isProcessed && !!item.matched_transaction_id
const isPlaceholder = !!item.isPlaceholder
const status = deriveInboxStatus(item)
const isErrored = status === 'error'
const isBooked = status === 'booked'
const isLinkedToTransaction = status === 'linked'
return (
<li
@@ -943,13 +1041,13 @@ function InboxRow({
: (supplierName ?? item.email_subject ?? 'Okänt dokument')}
</span>
{isErrored && (
<AlertTriangle className="h-3 w-3 text-destructive shrink-0" />
<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" />
)}
{isProcessed && (
<Check className="h-3 w-3 text-emerald-600 shrink-0" />
{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">
@@ -977,7 +1075,7 @@ function InboxRow({
// ── Document preview pane ────────────────────────────────────
// (placed below the row so editors can fold the row cleanly)
function DocumentPreview({
export function DocumentPreview({
docUrl,
docMime,
isProcessing = false,
@@ -1262,6 +1360,9 @@ function FieldsRail({
accountingMethod,
onDelete,
onBookDirect,
onMatchTransaction,
onUnmatchTransaction,
onAskAssistant,
isDeleting,
onFieldsUpdated,
onRetryRequested,
@@ -1270,6 +1371,9 @@ function FieldsRail({
accountingMethod: AccountingMethod
onDelete: () => void
onBookDirect: () => void
onMatchTransaction: () => void
onUnmatchTransaction: () => Promise<void>
onAskAssistant?: (transactionId: string) => void
isDeleting: boolean
onFieldsUpdated: (data: InvoiceExtractionResult) => void
onRetryRequested: () => Promise<void>
@@ -1278,9 +1382,11 @@ function FieldsRail({
const data = item.extracted_data
const isProcessed = !!item.created_supplier_invoice_id
const isBookedDirectly = !isProcessed && !!item.created_journal_entry_id
const isLinkedToTransaction =
!isProcessed && !isBookedDirectly && !!item.matched_transaction_id
const isResolved = isProcessed || isBookedDirectly || isLinkedToTransaction
// "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
@@ -1431,43 +1537,79 @@ function FieldsRail({
</Button>
</Link>
) : isLinkedToTransaction && item.matched_transaction_id ? (
<Link href={`/transactions?highlight=${item.matched_transaction_id}`} className="block">
<Button variant="default" size="sm" className="w-full">
<ArrowRight className="h-3.5 w-3.5 mr-1.5" />
Bokför transaktionen
</Button>
</Link>
) : accountingMethod === 'cash' ? (
<>
<Button
variant="default"
size="sm"
className="w-full"
onClick={onBookDirect}
>
Bokför direkt
</Button>
<Link href={`/supplier-invoices/new?inbox_item_id=${item.id}`} className="block">
<Button variant="outline" size="sm" className="w-full">
Skapa leverantörsfaktura
{/* 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>
</Link>
</>
) : (
<>
<Link href={`/supplier-invoices/new?inbox_item_id=${item.id}`} className="block">
<Button variant="default" size="sm" className="w-full">
Skapa leverantörsfaktura
</Button>
</Link>
)}
<Button
variant="outline"
size="sm"
className="w-full"
onClick={onBookDirect}
>
Bokför direkt
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
@@ -1519,7 +1661,7 @@ function FieldsRail({
// ── Extracted fields list ────────────────────────────────────
function emptyExtraction(): InvoiceExtractionResult {
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' },
@@ -1595,7 +1737,7 @@ function buildPatchBody(key: FieldKey, raw: string, currency: string) {
return { [group]: { [name]: trimmed === '' ? null : trimmed } }
}
function EditableFieldsList({
export function EditableFieldsList({
itemId,
data,
disabled,
@@ -23,7 +23,13 @@ import {
Mail,
Phone,
Settings,
AlertTriangle,
CalendarRange,
ShieldCheck,
Users,
Receipt,
} from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import Link from 'next/link'
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
import type { TICCompanyProfile } from '@/extensions/general/tic/lib/tic-types'
@@ -38,6 +44,31 @@ function formatPercent(value: number | null): string {
return `${value.toFixed(1)} %`
}
function formatSek(value: number | null): string {
if (value === null || value === undefined) return '—'
return `${value.toLocaleString('sv-SE')} kr`
}
function formatIsoDate(iso: string | null): string {
if (!iso) return '—'
return iso.slice(0, 10)
}
function statusColorToVariant(
color: 'red' | 'yellow' | 'green' | 'neutral' | null
): 'destructive' | 'warning' | 'success' | 'secondary' {
switch (color) {
case 'red':
return 'destructive'
case 'yellow':
return 'warning'
case 'green':
return 'success'
default:
return 'secondary'
}
}
function toMs(epoch: number): number {
// TIC returns epoch seconds; Date() expects milliseconds
return epoch < 1e12 ? epoch * 1000 : epoch
@@ -388,6 +419,214 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
</Card>
</div>
{/* Status entries — most recent first; usually 1-3 rows */}
{profile.statuses.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldCheck className="h-4 w-4" />
{t('status_section')}
</CardTitle>
</CardHeader>
<CardContent>
<ul className="space-y-2">
{profile.statuses.slice(0, 6).map((status, i) => (
<li key={i} className="flex items-center justify-between gap-3 text-sm">
<div className="flex items-center gap-2">
<Badge variant={statusColorToVariant(status.color)}>
{status.description ?? status.code ?? '—'}
</Badge>
{status.isCeased && (
<span className="text-xs text-muted-foreground">
{t('deregistered')}
</span>
)}
</div>
<span className="text-xs text-muted-foreground tabular-nums">
{formatIsoDate(status.statusDate)}
</span>
</li>
))}
</ul>
</CardContent>
</Card>
)}
{/* Fiscal year + signatory side-by-side */}
{(profile.fiscalYear || profile.signatory.length > 0) && (
<div className="grid gap-6 md:grid-cols-2">
{profile.fiscalYear && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<CalendarRange className="h-4 w-4" />
{t('fiscal_year_section')}
</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm">
<p className="font-mono tabular-nums">
{t('fiscal_year_current', {
start: profile.fiscalYear.startMonthDay ?? '—',
end: profile.fiscalYear.endMonthDay ?? '—',
})}
</p>
{profile.fiscalYearHistory.length > 1 && (
<p className="text-xs text-muted-foreground">
{t('fiscal_year_changed', { n: profile.fiscalYearHistory.length - 1 })}
</p>
)}
</CardContent>
</Card>
)}
{profile.signatory.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('signatory_section')}</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-sm">
{profile.signatory.map((s, i) => (
<p key={i} className="text-muted-foreground whitespace-pre-line">
{s.description}
</p>
))}
</CardContent>
</Card>
)}
</div>
)}
{/* Board summary + representatives */}
{(profile.board || profile.representatives.length > 0) && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Users className="h-4 w-4" />
{t('board_section')}
</CardTitle>
{profile.board && (
<CardDescription className="flex flex-wrap items-center gap-x-3 gap-y-1">
{profile.board.numberOfBoardMembers !== null && (
<span>
{t('board_summary_members', { n: profile.board.numberOfBoardMembers })}
</span>
)}
{profile.board.numberOfDeputyBoardMembers !== null && profile.board.numberOfDeputyBoardMembers > 0 && (
<span>
{t('board_summary_deputies', { n: profile.board.numberOfDeputyBoardMembers })}
</span>
)}
{profile.board.hasVacancy && (
<Badge variant="warning" className="gap-1">
<AlertTriangle className="h-3 w-3" />
{t('board_vacancy')}
</Badge>
)}
{profile.board.missingCEODate && (
<span className="text-warning">
{t('board_missing_ceo', { date: formatIsoDate(profile.board.missingCEODate) })}
</span>
)}
{profile.board.missingAuditor && (
<span className="text-warning">
{t('board_missing_auditor', { date: formatIsoDate(profile.board.missingAuditor) })}
</span>
)}
</CardDescription>
)}
</CardHeader>
<CardContent>
{profile.representatives.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>{t('col_name')}</TableHead>
<TableHead>{t('col_position')}</TableHead>
<TableHead>{t('col_since')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{profile.representatives.slice(0, 12).map((p, i) => (
<TableRow key={i}>
<TableCell className="text-sm">{p.name ?? '—'}</TableCell>
<TableCell className="text-sm">
{p.positionDescription ?? p.positionType ?? '—'}
</TableCell>
<TableCell className="text-xs tabular-nums text-muted-foreground">
{formatIsoDate(p.positionStart)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="text-sm text-muted-foreground">{t('board_no_representatives')}</p>
)}
</CardContent>
</Card>
)}
{/* Payroll history — payroll2 array, newest first */}
{profile.payrolls.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Receipt className="h-4 w-4" />
{t('payroll_section')}
</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>{t('col_payroll_period')}</TableHead>
<TableHead className="text-right">{t('col_payroll_employees')}</TableHead>
<TableHead className="text-right">{t('col_payroll_tax')}</TableHead>
<TableHead className="text-right">{t('col_payroll_personnel_costs')}</TableHead>
<TableHead className="text-right">{t('col_payroll_deviation')}</TableHead>
<TableHead className="text-right">{t('col_payroll_late_fees')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{profile.payrolls.slice(0, 10).map((p, i) => (
<TableRow key={i}>
<TableCell className="font-mono tabular-nums text-xs">
{p.periodStart && p.periodEnd
? `${formatIsoDate(p.periodStart)} – ${formatIsoDate(p.periodEnd)}`
: '—'}
</TableCell>
<TableCell className="text-right text-sm tabular-nums">
{p.numberOfEmployees !== null ? p.numberOfEmployees.toFixed(0) : '—'}
</TableCell>
<TableCell className="text-right text-sm tabular-nums">
{formatSek(p.sumPayrollTax)}
</TableCell>
<TableCell className="text-right text-sm tabular-nums">
{formatSek(p.calculatedPersonnelCosts)}
</TableCell>
<TableCell
className={`text-right text-sm tabular-nums ${
p.deviation !== null && Math.abs(p.deviation) > 0.1
? 'text-warning'
: 'text-muted-foreground'
}`}
>
{p.deviation !== null ? `${(p.deviation * 100).toFixed(1)} %` : '—'}
</TableCell>
<TableCell
className={`text-right text-sm tabular-nums ${
(p.numberOfLateFeesForPeriod ?? 0) > 0 ? 'text-destructive' : 'text-muted-foreground'
}`}
>
{p.numberOfLateFeesForPeriod ?? 0}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
)}
{/* Financial reports table */}
{profile.financialReports.length > 0 && (
<Card>
+464
View File
@@ -0,0 +1,464 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { createClient } from '@/lib/supabase/client'
import { useCompany } from '@/contexts/CompanyContext'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { useToast } from '@/components/ui/use-toast'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import { Loader2, Search } from 'lucide-react'
import { Input } from '@/components/ui/input'
import {
amountVarianceForMatch,
calculateMatchConfidence,
calculateMerchantSimilarity,
} from '@/lib/documents/core-receipt-matcher'
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
import type { InvoiceExtractionResult } from '@/types'
// TransactionMatchPicker
//
// Opens from the InvoiceInboxWorkspace FieldsRail when the user clicks
// "Matcha mot transaktion" on an inbox item whose matched_transaction_id is
// null. Lists *uncategorised* transactions only — matching points an underlag
// at the bank payment you're about to book, so already-booked rows are out of
// scope (and surfacing them would invite a double-booking via "Bokför
// manuellt"). Two modes:
// • Suggested (no search): every uncategorised company transaction, scored
// via lib/documents/core-receipt-matcher and sorted best-first. No date
// window — over-fetching is cheap for a manual picker and a hard window
// silently dropped late payments out of the candidate set.
// • Search (≥2 chars): the same uncategorised set across ALL dates, narrowed
// server-side by description/merchant. This is the fix for "not all
// transactions come up to search for" — the old client-only filter could
// only see the windowed rows already fetched.
// Amounts are compared currency-aware (see scoring memo): same-currency raw,
// otherwise normalised to SEK via the underlag's FX rate. User picks one →
// POST /items/:id/match-transaction → onMatched callback.
interface RawTransaction {
id: string
date: string
description: string | null
merchant_name: string | null
amount: number
currency: string | null
amount_sek: number | null
exchange_rate: number | null
}
interface CandidateTransaction {
id: string
date: string
description: string | null
merchant_name: string | null
amount: number
currency: string
/** SEK-equivalent for non-SEK transactions, for the "≈ … kr" hint. */
amountSek: number | null
confidence: number
reasons: string[]
}
interface Props {
open: boolean
onClose: () => void
inboxItemId: string
extractedData: InvoiceExtractionResult | null
onMatched: (transactionId: string) => void
}
// Currencies the /api/currency/rate endpoint (Riksbanken) can resolve. Used
// to normalise a foreign-currency underlag total into SEK so it can be
// compared against SEK bank charges.
const SUPPORTED_FX = ['EUR', 'USD', 'GBP', 'NOK', 'DKK']
// Date tolerance used only for *ranking* candidates (not for filtering — there
// is no longer a date window). Far wider than the receipt matcher's tight ±3d
// default so a payment landing weeks or months after the invoice still earns
// partial date credit and the true match floats to the top, instead of every
// candidate collapsing to "Svag match".
const MATCH_DATE_TOLERANCE_DAYS = 120
// Minimum characters before a keystroke flips the picker into server-side
// search mode. Below this we stay on the scored suggestions and just narrow
// them client-side for instant feedback.
const SEARCH_MIN_CHARS = 2
export default function TransactionMatchPicker({
open,
onClose,
inboxItemId,
extractedData,
onMatched,
}: Props) {
const supabase = useMemo(() => createClient(), [])
const { company } = useCompany()
const { toast } = useToast()
// Starts true so the first paint after opening shows skeletons, not a flash
// of the empty state before the fetch effect runs.
const [loading, setLoading] = useState(true)
const [rawRows, setRawRows] = useState<RawTransaction[]>([])
const [search, setSearch] = useState('')
const [debouncedSearch, setDebouncedSearch] = useState('')
const [matchingId, setMatchingId] = useState<string | null>(null)
// SEK per unit of the underlag currency (e.g. ~11.5 for EUR). null = SEK
// underlag, fetch pending, or unsupported/failed — amount matching then
// falls back to same-currency-only.
const [fxRate, setFxRate] = useState<number | null>(null)
// ── Underlag (receipt) facts pulled from extracted_data ──────
const rawInvoiceDate = extractedData?.invoice?.invoiceDate ?? null
const hasInvoiceDate = useMemo(() => {
if (!rawInvoiceDate) return false
return !Number.isNaN(new Date(rawInvoiceDate).getTime())
}, [rawInvoiceDate])
// Default to today if no date was extracted so scoring still has an anchor.
const invoiceDate = useMemo(() => {
if (!rawInvoiceDate) return new Date()
const parsed = new Date(rawInvoiceDate)
return Number.isNaN(parsed.getTime()) ? new Date() : parsed
}, [rawInvoiceDate])
const total = extractedData?.totals?.total ?? null
const receiptCurrency = (extractedData?.invoice?.currency ?? 'SEK').toUpperCase()
const supplier = extractedData?.supplier?.name ?? null
// SEK value of the underlag total. For a SEK underlag that's the total
// itself; for a foreign one it needs the fetched FX rate.
const receiptSek = useMemo(() => {
if (total == null) return null
if (receiptCurrency === 'SEK') return total
if (fxRate != null) return Math.round(total * fxRate * 100) / 100
return null
}, [total, receiptCurrency, fxRate])
// True when the underlag is in a foreign currency we can't price right now —
// amount matching is unavailable, so we say so instead of mis-ranking.
const amountMatchUnavailable =
total != null && receiptCurrency !== 'SEK' && receiptSek == null
// ── Reset transient state each time the dialog opens ─────────
useEffect(() => {
if (!open) return
setSearch('')
setDebouncedSearch('')
setRawRows([])
setLoading(true)
}, [open])
// ── Debounce the search term feeding the server query ────────
useEffect(() => {
const t = setTimeout(() => setDebouncedSearch(search), 300)
return () => clearTimeout(t)
}, [search])
// ── Fetch the underlag's FX rate (foreign currency only) ─────
useEffect(() => {
if (!open) return
setFxRate(null)
if (receiptCurrency === 'SEK' || !SUPPORTED_FX.includes(receiptCurrency)) return
let cancelled = false
const dateParam = hasInvoiceDate && rawInvoiceDate ? `&date=${rawInvoiceDate}` : ''
fetch(`/api/currency/rate?currency=${receiptCurrency}${dateParam}`)
.then((r) => (r.ok ? r.json() : null))
.then((body) => {
if (cancelled) return
const rate = body?.data?.rate
if (typeof rate === 'number' && rate > 0) setFxRate(rate)
})
.catch(() => {
/* leave null — cross-currency amount signal simply drops out */
})
return () => {
cancelled = true
}
}, [open, receiptCurrency, hasInvoiceDate, rawInvoiceDate])
// ── Fetch candidate rows (suggested vs search mode) ──────────
useEffect(() => {
if (!open) return
if (!company) return // provider still hydrating
let cancelled = false
setLoading(true)
;(async () => {
// Strip PostgREST filter-DSL structural chars before interpolating into
// `.or()`. Commas separate OR-conditions and parentheses group nested
// filters, so leaving them in would let a search term inject a synthetic
// clause (e.g. "Acme,company_id.neq.…"). `%` and `\` are LIKE wildcards/
// escapes we also drop. `.` is safe — it stays inside the ilike value.
const safe = debouncedSearch.trim().replace(/[%,()\\]/g, ' ').trim()
const searchMode = safe.length >= SEARCH_MIN_CHARS
// Defense-in-depth: RLS only narrows to "any company the user belongs
// to". Multi-tenant users (consultants) would otherwise see other
// companies' transactions. Filter to the active company explicitly.
// Uncategorised only (journal_entry_id IS NULL) in both modes — see the
// component header. The search just adds a server-side name filter so
// matches outside the suggested set still surface.
let query = supabase
.from('transactions')
.select(
'id, date, description, merchant_name, amount, currency, amount_sek, exchange_rate',
)
.eq('company_id', company.id)
.is('journal_entry_id', null)
if (searchMode) {
query = query
.or(`description.ilike.%${safe}%,merchant_name.ilike.%${safe}%`)
.order('date', { ascending: false })
.limit(100)
} else {
// Recent first; scoring floats the best match up regardless of date.
query = query.order('date', { ascending: false }).limit(300)
}
const { data, error } = await query
if (cancelled) return
if (error) {
toast({
title: 'Kunde inte hämta transaktioner',
description: error.message,
variant: 'destructive',
})
setRawRows([])
setLoading(false)
return
}
setRawRows((data ?? []) as RawTransaction[])
setLoading(false)
})()
return () => {
cancelled = true
}
}, [open, supabase, company, debouncedSearch, toast])
// ── Score + sort (currency-aware) ────────────────────────────
const candidates = useMemo<CandidateTransaction[]>(() => {
const scored = rawRows.map((tx) => {
const txCurrency = (tx.currency ?? 'SEK').toUpperCase()
const txSek =
txCurrency === 'SEK'
? tx.amount
: resolveSekAmount(tx.amount, tx.amount_sek, tx.currency, tx.exchange_rate)
// Currency-aware variance — null when uncomparable, which makes the
// matcher drop the amount signal instead of matching 750 EUR to 750 SEK.
const amountVariance = amountVarianceForMatch(
total,
receiptCurrency,
receiptSek,
tx.amount,
txCurrency,
txSek,
)
const dateVariance = Math.abs(
(new Date(tx.date).getTime() - invoiceDate.getTime()) / (1000 * 60 * 60 * 24),
)
const merchant = tx.merchant_name || tx.description || ''
const similarity = supplier ? calculateMerchantSimilarity(supplier, merchant) : 0
const { confidence, matchReasons } = calculateMatchConfidence(
dateVariance,
amountVariance,
similarity,
MATCH_DATE_TOLERANCE_DAYS,
)
return {
id: tx.id,
date: tx.date,
description: tx.description ?? null,
merchant_name: tx.merchant_name ?? null,
amount: tx.amount,
currency: txCurrency,
amountSek: txCurrency === 'SEK' ? null : Math.round(txSek * 100) / 100,
confidence,
reasons: matchReasons,
}
})
scored.sort((a, b) => b.confidence - a.confidence)
return scored
}, [rawRows, invoiceDate, total, receiptCurrency, receiptSek, supplier])
// Instant client-side narrowing while the debounced server query catches up.
const filtered = useMemo(() => {
const q = search.trim().toLowerCase()
if (!q) return candidates
return candidates.filter((c) => {
const hay = `${c.description ?? ''} ${c.merchant_name ?? ''}`.toLowerCase()
return hay.includes(q)
})
}, [candidates, search])
// Any typed text counts as "searching" for labelling/empty-state purposes
// (1 char narrows the suggested set client-side; ≥2 also hits the server).
const hasSearchText = search.trim().length > 0
async function handlePick(transactionId: string) {
setMatchingId(transactionId)
try {
const res = await fetch(
`/api/extensions/ext/invoice-inbox/items/${inboxItemId}/match-transaction`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transaction_id: transactionId }),
},
)
const json = (await res.json().catch(() => ({}))) as { error?: string }
if (!res.ok) {
toast({
title: 'Kunde inte matcha',
description: json.error ?? `HTTP ${res.status}`,
variant: 'destructive',
})
return
}
onMatched(transactionId)
onClose()
} finally {
setMatchingId(null)
}
}
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Matcha mot transaktion</DialogTitle>
<DialogDescription>
Välj banktransaktionen som hör till underlaget.
</DialogDescription>
</DialogHeader>
{/* Underlag reference — what we're matching against, so a currency or
amount mismatch with a candidate is obvious at a glance. */}
{(total != null || supplier) && (
<div className="rounded-md border bg-muted/30 px-3 py-2 text-xs flex items-center gap-x-3 gap-y-1 flex-wrap">
<span className="text-muted-foreground shrink-0">Underlag</span>
{supplier && <span className="font-medium truncate">{supplier}</span>}
{total != null && (
<span className="tabular-nums font-medium shrink-0">
{formatCurrency(total, receiptCurrency)}
{receiptSek != null && receiptCurrency !== 'SEK' && (
<span className="text-muted-foreground font-normal">
{' '}
≈ {formatCurrency(receiptSek, 'SEK')}
</span>
)}
</span>
)}
{hasInvoiceDate && rawInvoiceDate && (
<span className="text-muted-foreground tabular-nums shrink-0">
{formatDate(rawInvoiceDate)}
</span>
)}
</div>
)}
{amountMatchUnavailable && (
<p className="text-[11px] text-muted-foreground -mt-1">
Växelkurs saknas för {receiptCurrency} — kandidaterna rankas på datum
och leverantör, inte belopp.
</p>
)}
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Sök i alla transaktioner…"
className="pl-9"
/>
</div>
<div className="flex items-center justify-between px-1 text-[11px] text-muted-foreground">
<span>{hasSearchText ? 'Sökresultat' : 'Föreslagna matchningar'}</span>
{!loading && <span className="tabular-nums">{filtered.length} st</span>}
</div>
<div className="max-h-[55vh] overflow-y-auto -mx-6 px-6 divide-y">
{loading ? (
<div className="space-y-3 py-3">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-12 w-full" />
))}
</div>
) : filtered.length === 0 ? (
<p className="py-6 text-sm text-muted-foreground text-center">
{hasSearchText
? `Inga okategoriserade transaktioner matchar "${search.trim()}".`
: 'Inga okategoriserade transaktioner att matcha mot.'}
</p>
) : (
filtered.map((c) => {
const tier =
c.confidence >= 0.8 ? 'success' : c.confidence >= 0.5 ? 'warning' : 'outline'
const tierLabel =
c.confidence >= 0.8
? 'Stark match'
: c.confidence >= 0.5
? 'Möjlig match'
: 'Svag match'
const isMatching = matchingId === c.id
return (
<button
key={c.id}
type="button"
onClick={() => void handlePick(c.id)}
disabled={!!matchingId}
className={cn(
'w-full text-left flex items-center gap-3 py-3 hover:bg-muted/50 transition-colors px-2 -mx-2 rounded',
matchingId && !isMatching && 'opacity-50',
)}
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 min-w-0">
<span className="text-sm font-medium truncate">
{c.merchant_name ?? c.description ?? 'Okänd transaktion'}
</span>
<Badge variant={tier} className="shrink-0 text-[10px]">
{tierLabel}
</Badge>
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">
<span>{formatDate(c.date)}</span>
{c.reasons.length > 0 && (
<>
<span>·</span>
<span className="truncate">{c.reasons.join(' · ')}</span>
</>
)}
</div>
</div>
<div className="text-right shrink-0">
<p className="text-sm font-medium tabular-nums">
{formatCurrency(c.amount, c.currency)}
</p>
{c.amountSek != null && (
<p className="text-[11px] text-muted-foreground tabular-nums">
≈ {formatCurrency(c.amountSek, 'SEK')}
</p>
)}
</div>
{isMatching && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
</button>
)
})
)}
</div>
</DialogContent>
</Dialog>
)
}
+13 -166
View File
@@ -1,15 +1,15 @@
'use client'
import { useState, useTransition } from 'react'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import Link from 'next/link'
import { Building2, ArrowRight, Loader2, Plus, Check, AlertTriangle } from 'lucide-react'
import { Building2, ArrowRight, Loader2, Plus, AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useToast } from '@/components/ui/use-toast'
import { switchCompany, createCompanyFromTicRole } from '@/lib/company/actions'
import { switchCompany } from '@/lib/company/actions'
import { mapEntityType } from '@/lib/company-lookup/entity-type-map'
import type { CompanyLookupResult, EnrichmentCompanyRole } from '@/lib/company-lookup/types'
import type { EnrichmentCompanyRole } from '@/lib/company-lookup/types'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
@@ -39,7 +39,6 @@ interface BankIdCompanyPickerProps {
type SetupState =
| { kind: 'idle' }
| { kind: 'opening'; companyId: string }
| { kind: 'creating'; orgNumber: string; step: 'lookup' | 'provision' }
// Swedish legal entity names (Aktiebolag, Enskild firma, etc.) are statutory
// terms — kept in Swedish in both locales.
@@ -79,12 +78,11 @@ export default function BankIdCompanyPicker({
const { toast } = useToast()
const t = useTranslations('select_company')
const [setup, setSetup] = useState<SetupState>({ kind: 'idle' })
const [isPending, startTransition] = useTransition()
const hour = new Date().getHours()
const greeting = hour < 5 ? t('greeting_night') : hour < 10 ? t('greeting_morning') : hour < 14 ? t('greeting_hello') : hour < 18 ? t('greeting_afternoon') : t('greeting_evening')
const busy = setup.kind !== 'idle' || isPending
const busy = setup.kind !== 'idle'
async function handleOpenMember(companyId: string) {
if (busy) return
@@ -98,167 +96,16 @@ export default function BankIdCompanyPicker({
window.location.assign('/')
}
async function handleCreateFromTic(role: EnrichmentCompanyRole) {
// BankID picker no longer one-click-provisions. Every pick routes to the
// onboarding wizard with the orgnr (and entity_type via the server-side
// CompanyRoles match in /onboarding) pre-filled. F-skatt / VAT / address
// are confirmed by the user in Steps 2-4 instead of being auto-fetched
// from TIC — costs us ~1 Lens call per signup but avoids any TIC budget
// spend (companyRoles is on the Identity API, which is a separate quota).
function handleCreateFromTic(role: EnrichmentCompanyRole) {
if (busy) return
const orgNumber = role.companyRegistrationNumber.replace(/[\s-]/g, '')
const mapped = mapEntityType(role.legalEntityType)
if (!mapped) {
// Entity type isn't supported end-to-end — route to manual wizard with
// the org number pre-filled.
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
return
}
setSetup({ kind: 'creating', orgNumber, step: 'lookup' })
let lookup: CompanyLookupResult | null = null
try {
const res = await fetch(
`/api/extensions/ext/tic/lookup?org_number=${encodeURIComponent(orgNumber)}`,
{ method: 'GET' },
)
if (res.ok) {
const json = await res.json()
lookup = (json?.data as CompanyLookupResult | undefined) ?? null
}
} catch {
// Network/parse failure — fall through to the lookup-missing branch below.
}
// Without a lookup we don't know the company's VAT/F-skatt status.
// Defaulting those to false for a momsregistrerat bolag would silently
// create a company that issues invoices without moms — ML 17 kap violation.
// Route to the manual wizard with the known fields pre-filled instead.
if (!lookup) {
toast({
title: t('toast_lookup_failed_title'),
description: t('toast_lookup_failed_description'),
})
setSetup({ kind: 'idle' })
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
return
}
// Block provisioning for companies that are avregistrerade/likviderade.
// Under BFL 2 kap, bokföringsskyldighet ends when a company is struck off.
if (lookup.isCeased) {
toast({
title: t('toast_company_ceased_title'),
description: t('toast_company_ceased_description'),
variant: 'destructive',
})
setSetup({ kind: 'idle' })
return
}
setSetup({ kind: 'creating', orgNumber, step: 'provision' })
startTransition(async () => {
const result = await createCompanyFromTicRole({
teamId,
orgNumber,
legalName: role.legalName,
legalEntityType: role.legalEntityType,
lookup,
})
if (result.error === 'lookup_missing') {
// Extremely unlikely (we just verified lookup above) but if it happens,
// the same fallback applies.
setSetup({ kind: 'idle' })
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
return
}
if (result.error === 'org_number_exists') {
toast({
title: t('toast_company_exists_title'),
description: t('toast_company_exists_description'),
variant: 'destructive',
})
setSetup({ kind: 'idle' })
return
}
if (result.error === 'company_ceased') {
// Belt-and-suspenders: we already check lookup.isCeased client-side
// above, but the server-side guard catches any race where TIC's
// cached result differs between the two calls.
toast({
title: t('toast_company_ceased_title'),
description: t('toast_company_ceased_description'),
variant: 'destructive',
})
setSetup({ kind: 'idle' })
return
}
if (result.error === 'org_number_invalid') {
toast({
title: t('toast_org_invalid_title'),
description: t('toast_org_invalid_description'),
variant: 'destructive',
})
setSetup({ kind: 'idle' })
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
return
}
if (result.error || !result.companyId) {
toast({
title: t('toast_create_failed_title'),
description: result.error ?? t('toast_create_failed_description'),
variant: 'destructive',
})
setSetup({ kind: 'idle' })
return
}
toast({ title: t('toast_welcome_title'), description: t('toast_company_ready') })
window.location.assign('/')
})
}
// Progress card while creating
if (setup.kind === 'creating') {
const lookupDone = setup.step === 'provision'
return (
<div className="stagger-enter">
<header className="mb-10">
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">
{greeting}{firstName ? `, ${firstName}` : ''}
</h1>
<p className="text-muted-foreground text-sm mt-1.5">{t('setting_up')}</p>
</header>
<div className="max-w-lg rounded-xl border bg-card p-6" style={{ boxShadow: 'var(--shadow-md)' }}>
<div className="flex items-start gap-3">
<Building2 className="h-5 w-5 text-muted-foreground mt-0.5" />
<div className="flex-1">
<p className="font-medium text-sm">{t('org_nr_prefix', { orgNumber: setup.orgNumber })}</p>
<ul className="mt-3 space-y-2 text-sm">
<li className="flex items-center gap-2">
{lookupDone
? <Check className="h-4 w-4 text-sage" />
: <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
<span className={cn(!lookupDone && 'text-muted-foreground')}>
{t('progress_lookup')}
</span>
</li>
<li className="flex items-center gap-2">
{lookupDone
? <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
: <span className="h-4 w-4 inline-block rounded-full border border-border" />}
<span className={cn(!lookupDone && 'text-muted-foreground/50')}>
{t('progress_provision')}
</span>
</li>
</ul>
</div>
</div>
</div>
</div>
)
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
}
return (
+123 -22
View File
@@ -9,8 +9,10 @@ import {
FileText,
Landmark,
ArrowRightLeft,
MessageCircle,
ShieldCheck,
} from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { cn } from '@/lib/utils'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import { getBranding } from '@/lib/branding/service'
@@ -21,16 +23,23 @@ interface NewUserChecklistProps {
onFreshStart: () => void
className?: string
/**
* Whether the active user already has a Skatteverket OAuth connection.
* When true the Skatteverket step renders as completed instead of as a CTA.
* Per-step completion flags. The render flips each step from CTA to a
* compact "done" card when its corresponding flag is true so the user
* sees their progress without having to remember what they finished.
*/
hasBookkeepingImported?: boolean
hasBankConnected?: boolean
hasSkatteverketConnected?: boolean
hasAgentBuilt?: boolean
}
export default function NewUserChecklist({
onFreshStart,
className,
hasBookkeepingImported,
hasBankConnected,
hasSkatteverketConnected,
hasAgentBuilt,
}: NewUserChecklistProps) {
const t = useTranslations('new_user_checklist')
const hasMigration = ENABLED_EXTENSION_IDS.has('arcim-migration')
@@ -40,9 +49,11 @@ export default function NewUserChecklist({
return (
<div className={cn('min-h-[75vh] flex flex-col items-center justify-center px-4 sm:px-0 stagger-enter', className)}>
<div className="w-full max-w-2xl">
{/* Header */}
{/* Header — centered welcome. Data-import steps lead; building the
assistant is the last step so a user coming from another system
brings their books in first. */}
<div className="text-center mb-8 md:mb-12">
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">
<h1 className="font-display text-2xl md:text-3xl tracking-tight">
{t('welcome', { appName: branding.appName.toLowerCase() })}
</h1>
<p className="text-muted-foreground text-sm md:text-base leading-relaxed max-w-md mx-auto mt-3">
@@ -53,19 +64,30 @@ export default function NewUserChecklist({
{/* Step 1: Migrate bookkeeping */}
<div className="mb-6 md:mb-8">
<div className="flex items-center gap-3 mb-4">
<span className="h-7 w-7 rounded-full bg-foreground text-background flex items-center justify-center text-xs font-semibold flex-shrink-0 tabular-nums">
1
<span className={cn(
'h-7 w-7 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 tabular-nums',
hasBookkeepingImported
? 'bg-secondary text-foreground'
: 'bg-foreground text-background',
)}>
{hasBookkeepingImported ? <CheckCircle2 className="h-4 w-4" /> : '1'}
</span>
<h2 className="font-display text-base font-medium tracking-tight">
<h2 className="font-display text-base tracking-tight">
{t('step1_title')}
</h2>
</div>
{hasBookkeepingImported ? (
<div className="ml-0 sm:ml-10 p-4 sm:p-5 rounded-lg border border-border bg-secondary/40">
<p className="text-sm text-foreground font-medium">{t('step1_done_title')}</p>
<p className="text-xs sm:text-sm text-muted-foreground mt-1">{t('step1_done_description')}</p>
</div>
) : (
<div className="space-y-3 ml-0 sm:ml-10">
{hasMigration && (
<Link
href="/import?mode=migration"
className="group block p-4 sm:p-5 rounded-xl border border-primary/20 bg-primary/[0.02] hover:bg-primary/[0.05] hover:border-primary/40 transition-all duration-150 active:scale-[0.99]"
className="group block p-4 sm:p-5 rounded-lg border border-border bg-secondary/40 hover:bg-secondary/60 hover:border-primary/40 transition-colors duration-150"
>
<div className="flex items-start gap-3 sm:gap-4">
<div className="p-2 sm:p-2.5 rounded-lg bg-primary/[0.08] group-hover:bg-primary/[0.12] transition-colors flex-shrink-0">
@@ -85,9 +107,14 @@ export default function NewUserChecklist({
{ name: 'Bokio', logo: '/logos/bokio.png' },
{ name: 'Björn Lundén', logo: '/logos/bjornlunden.png' },
{ name: 'Briox', logo: '/logos/Briox_logo.png' },
{ name: 'SIE4-fil', logo: null },
] as const).map(provider => (
<div key={provider.name} className="flex items-center gap-1 sm:gap-1.5 rounded border border-border/60 bg-muted/30 px-1.5 sm:px-2 py-0.5 sm:py-1">
<img src={provider.logo} alt={provider.name} className="h-3.5 w-3.5 sm:h-4 sm:w-4 shrink-0 rounded-sm object-contain" />
<div key={provider.name} className="flex items-center gap-1 sm:gap-1.5 rounded border border-border bg-muted/30 px-1.5 sm:px-2 py-0.5 sm:py-1">
{provider.logo ? (
<img src={provider.logo} alt={provider.name} className="h-3.5 w-3.5 sm:h-4 sm:w-4 shrink-0 rounded-sm object-contain" />
) : (
<FileText className="h-3.5 w-3.5 sm:h-4 sm:w-4 shrink-0 text-muted-foreground" />
)}
<span className="text-[10px] sm:text-[11px] font-medium text-muted-foreground">{provider.name}</span>
</div>
))}
@@ -100,7 +127,7 @@ export default function NewUserChecklist({
<Link
href="/import?mode=sie"
className="group block p-4 sm:p-5 rounded-xl border border-border/60 hover:border-primary/40 hover:bg-primary/[0.02] transition-all duration-150 active:scale-[0.99]"
className="group block p-4 sm:p-5 rounded-lg border border-border hover:border-primary/40 hover:bg-primary/[0.02] transition-colors duration-150"
>
<div className="flex items-start gap-3 sm:gap-4">
<div className="p-2 sm:p-2.5 rounded-lg bg-muted/60 group-hover:bg-primary/[0.08] transition-colors flex-shrink-0">
@@ -118,23 +145,35 @@ export default function NewUserChecklist({
</div>
</Link>
</div>
)}
</div>
{/* Step 2: Connect bank */}
<div className="mb-6 md:mb-8">
<div className="flex items-center gap-3 mb-4">
<span className="h-7 w-7 rounded-full bg-foreground text-background flex items-center justify-center text-xs font-semibold flex-shrink-0 tabular-nums">
2
<span className={cn(
'h-7 w-7 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 tabular-nums',
hasBankConnected
? 'bg-secondary text-foreground'
: 'bg-foreground text-background',
)}>
{hasBankConnected ? <CheckCircle2 className="h-4 w-4" /> : '2'}
</span>
<h2 className="font-display text-base font-medium tracking-tight">
<h2 className="font-display text-base tracking-tight">
{t('step2_title')}
</h2>
</div>
<div className="ml-0 sm:ml-10">
{hasBankConnected ? (
<div className="p-4 sm:p-5 rounded-lg border border-border bg-secondary/40">
<p className="text-sm text-foreground font-medium">Bank kopplad</p>
<p className="text-xs sm:text-sm text-muted-foreground mt-1">Transaktioner synkas automatiskt.</p>
</div>
) : (
<Link
href={hasBanking ? '/import?mode=psd2' : '/import?mode=bank'}
className="group block p-4 sm:p-5 rounded-xl border border-border/60 hover:border-primary/40 hover:bg-primary/[0.02] transition-all duration-150 active:scale-[0.99]"
className="group block p-4 sm:p-5 rounded-lg border border-border hover:border-primary/40 hover:bg-primary/[0.02] transition-colors duration-150"
>
<div className="flex items-start gap-3 sm:gap-4">
<div className="p-2 sm:p-2.5 rounded-lg bg-muted/60 group-hover:bg-primary/[0.08] transition-colors flex-shrink-0">
@@ -153,6 +192,7 @@ export default function NewUserChecklist({
<ArrowRight className="h-4 w-4 text-muted-foreground/40 group-hover:text-primary/60 mt-1 flex-shrink-0 transition-colors" />
</div>
</Link>
)}
</div>
</div>
@@ -168,14 +208,14 @@ export default function NewUserChecklist({
<span className={cn(
'h-7 w-7 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 tabular-nums',
hasSkatteverketConnected
? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
? 'bg-secondary text-foreground'
: 'bg-foreground text-background',
)}>
{hasSkatteverketConnected
? <CheckCircle2 className="h-4 w-4" />
: '3'}
</span>
<h2 className="font-display text-base font-medium tracking-tight">
<h2 className="font-display text-base tracking-tight">
{t('step3_title')}
</h2>
<span className="text-xs text-muted-foreground">{t('optional_suffix')}</span>
@@ -183,13 +223,13 @@ export default function NewUserChecklist({
<div className="ml-0 sm:ml-10">
{hasSkatteverketConnected ? (
<div className="block p-4 sm:p-5 rounded-xl border border-emerald-500/30 bg-emerald-500/[0.04]">
<div className="block p-4 sm:p-5 rounded-lg border border-border bg-secondary/40">
<div className="flex items-start gap-3 sm:gap-4">
<div className="p-2 sm:p-2.5 rounded-lg bg-emerald-500/[0.10] flex-shrink-0">
<FileCheck className="h-4 w-4 sm:h-5 sm:w-5 text-emerald-700 dark:text-emerald-400" />
<div className="p-2 sm:p-2.5 rounded-lg bg-background flex-shrink-0">
<FileCheck className="h-4 w-4 sm:h-5 sm:w-5 text-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-sm sm:text-base text-emerald-900 dark:text-emerald-200">
<p className="font-medium text-sm sm:text-base text-foreground">
{t('skatteverket_connected_title')}
</p>
<p className="text-xs sm:text-sm text-muted-foreground mt-1 sm:mt-1.5 leading-relaxed">
@@ -205,7 +245,7 @@ export default function NewUserChecklist({
// skatteverket.se; <Link> would route via Next's client
// router which doesn't follow cross-origin redirects.
href="/api/extensions/ext/skatteverket/authorize?return_to=/"
className="group block p-4 sm:p-5 rounded-xl border border-border/60 hover:border-primary/40 hover:bg-primary/[0.02] transition-all duration-150 active:scale-[0.99]"
className="group block p-4 sm:p-5 rounded-lg border border-border hover:border-primary/40 hover:bg-primary/[0.02] transition-colors duration-150"
>
<div className="flex items-start gap-3 sm:gap-4">
<div className="p-2 sm:p-2.5 rounded-lg bg-muted/60 group-hover:bg-primary/[0.08] transition-colors flex-shrink-0">
@@ -227,6 +267,67 @@ export default function NewUserChecklist({
</div>
)}
{/* Build the assistant — always the last step, so a user migrating
from another system brings their books in first. */}
<div className="mb-8 md:mb-12">
<div className="flex items-center gap-3 mb-4">
<span className={cn(
'h-7 w-7 rounded-full flex items-center justify-center text-xs font-semibold flex-shrink-0 tabular-nums',
hasAgentBuilt
? 'bg-secondary text-foreground'
: 'bg-foreground text-background',
)}>
{hasAgentBuilt ? <CheckCircle2 className="h-4 w-4" /> : (hasSkatteverket ? '4' : '3')}
</span>
<h2 className="font-display text-base tracking-tight">
Skapa din assistent
</h2>
</div>
<div className="ml-0 sm:ml-10">
{hasAgentBuilt ? (
<div className="p-4 sm:p-5 rounded-lg border border-border bg-secondary/40">
<div className="flex items-start gap-3 sm:gap-4">
<div className="p-2 sm:p-2.5 rounded-lg bg-background flex-shrink-0">
<MessageCircle className="h-4 w-4 sm:h-5 sm:w-5 text-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-sm sm:text-base text-foreground">
Assistenten är klar
</p>
<p className="text-xs sm:text-sm text-muted-foreground mt-1 sm:mt-1.5 leading-relaxed">
Du kan börja chatta direkt. Justera tonalitet och kunskap i Inställningar &gt; Assistentens minne.
</p>
</div>
</div>
</div>
) : (
<Link
href="/onboarding/agent"
className="group block p-4 sm:p-5 rounded-lg border border-border hover:border-primary/40 hover:bg-primary/[0.02] transition-colors duration-150"
>
<div className="flex items-start gap-3 sm:gap-4">
<div className="p-2 sm:p-2.5 rounded-lg bg-muted/60 group-hover:bg-primary/[0.08] transition-colors flex-shrink-0">
<MessageCircle className="h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground group-hover:text-primary transition-colors" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-medium group-hover:text-primary transition-colors text-sm sm:text-base">
Bygg din bokföringsassistent
</p>
<Badge variant="secondary" className="uppercase tracking-wider">Beta</Badge>
</div>
<p className="text-xs sm:text-sm text-muted-foreground mt-1 sm:mt-1.5 leading-relaxed">
Några frågor om din verksamhet kalibrerar tonalitet, signatur och vad assistenten kan. Ju mer du delar, desto bättre förstår den dig.
</p>
</div>
<ArrowRight className="h-4 w-4 text-muted-foreground/40 group-hover:text-primary/60 mt-1 flex-shrink-0 transition-colors" />
</div>
</Link>
)}
</div>
</div>
{/* Escape hatch */}
<div className="space-y-5">
<div className="flex items-center gap-4">
@@ -41,6 +41,12 @@ interface Step2Props {
onBack: () => void
isSaving: boolean
orgNumberLocked?: boolean
// Orgnr we already trust without a Lens call — typically because it came
// from BankID CompanyRoles which confirms the user has a director role at
// this company. When set and the form's orgnr matches, Step 2 skips the
// debounced `/lookup` to avoid burning a Lens call on something we know
// exists. The guard clears as soon as the user edits the field.
preverifiedOrgNumber?: string | null
}
export default function Step2CompanyDetails({
@@ -52,6 +58,7 @@ export default function Step2CompanyDetails({
onBack,
isSaving,
orgNumberLocked,
preverifiedOrgNumber,
}: Step2Props) {
const t = useTranslations('onboarding')
const {
@@ -78,6 +85,14 @@ export default function Step2CompanyDetails({
const [orgNumberExists, setOrgNumberExists] = useState(false)
const abortRef = useRef<AbortController | null>(null)
const dupAbortRef = useRef<AbortController | null>(null)
// Tracks an orgnr that's been pre-verified (BankID CompanyRoles match) so
// the client-side Lens lookup is skipped for that exact value. Cleared
// (set to null) the moment the user edits the org number — a different
// orgnr is no longer covered by the BankID confirmation and needs a real
// lookup.
const prefetchedForOrgRef = useRef<string | null>(
preverifiedOrgNumber ? normalizeOrgNumber(preverifiedOrgNumber) : null,
)
const orgNumber = watch('org_number')
@@ -117,6 +132,17 @@ export default function Step2CompanyDetails({
return
}
// Server already fetched this orgnr (BankID deep-link). Don't burn a
// second TIC call to re-confirm what we already have in `initialLookup`.
// Once the user edits the field, normalizeOrgNumber(orgNumber) will
// diverge from the prefetched value and the lookup re-arms.
const normalized = normalizeOrgNumber(orgNumber)
if (prefetchedForOrgRef.current && normalized === prefetchedForOrgRef.current) {
return
}
// Any subsequent edit invalidates the prefetched-match guard for good.
prefetchedForOrgRef.current = null
setLookupError(null)
setLookupDone(null)
+34
View File
@@ -0,0 +1,34 @@
'use client'
import { useRouter } from 'next/navigation'
import NewUserChecklist from './NewUserChecklist'
interface Props {
companyId: string
hasBookkeepingImported: boolean
hasBankConnected: boolean
hasSkatteverketConnected: boolean
}
// Thin client wrapper around NewUserChecklist, shown only to a genuinely empty
// company (no data, no assistant). The data-import steps lead and building the
// assistant is the last step; the "I'm starting fresh" escape hatch forwards
// straight to /onboarding/agent for users with no books to bring in.
export default function WelcomeGate({
companyId: _companyId,
hasBookkeepingImported,
hasBankConnected,
hasSkatteverketConnected,
}: Props) {
const router = useRouter()
return (
<NewUserChecklist
hasBookkeepingImported={hasBookkeepingImported}
hasBankConnected={hasBankConnected}
hasSkatteverketConnected={hasSkatteverketConnected}
hasAgentBuilt={false}
onFreshStart={() => router.push('/onboarding/agent')}
/>
)
}
@@ -0,0 +1,291 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Check, Loader2, Circle, AlertTriangle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { cn } from '@/lib/utils'
import ReviewCard from './ReviewCard'
type StepId = 'tic' | 'select' | 'narrative' | 'finalize'
type StepStatus = 'pending' | 'in_progress' | 'success' | 'fallback' | 'error'
interface StepConfig {
id: StepId
label: string
fallbackLabel?: string
}
const STEPS: StepConfig[] = [
{ id: 'tic', label: 'Hämtar uppgifter', fallbackLabel: 'Inga företagsuppgifter, fortsätter ändå' },
{ id: 'select', label: 'Identifierar din verksamhet', fallbackLabel: 'Använder standardval' },
{ id: 'narrative', label: 'Sammanfattar', fallbackLabel: 'Standardsammanfattning' },
{ id: 'finalize', label: 'Klar' },
]
interface InitialFields {
entity_type_label: string
sni_codes: { code: string; name: string }[]
purpose: string | null
city: string | null
fiscal_period: string | null
vat_period: string | null
f_skatt: string | null
employees: string | null
}
interface ProfilePayload {
company_id: string
horizontal_atoms: string[]
vertical_atoms: string[]
modifier_atoms: string[]
is_multi_vertical: boolean
profile_summary: string
verification_questions: string[]
uncertainty_notes: string[]
composer_model: string
composed_at: string
}
interface Props {
companyId: string
companyName: string
firstName: string | null
initialFields: InitialFields
atomTitles: Record<string, string>
alreadyVerified: boolean
existingSummary: string | null
}
export default function AgentOnboarding({
companyId,
companyName,
firstName,
initialFields,
atomTitles,
alreadyVerified,
existingSummary,
}: Props) {
const router = useRouter()
const [phase, setPhase] = useState<'building' | 'review' | 'done'>(
alreadyVerified ? 'review' : 'building',
)
const [statuses, setStatuses] = useState<Record<StepId, StepStatus>>({
tic: 'pending',
select: 'pending',
narrative: 'pending',
finalize: 'pending',
})
// Hydrate from props during the initial render so we don't flash an empty
// ReviewCard for already-verified profiles.
const [profile, setProfile] = useState<ProfilePayload | null>(() => {
if (alreadyVerified && existingSummary) {
return {
company_id: companyId,
horizontal_atoms: [],
vertical_atoms: [],
modifier_atoms: [],
is_multi_vertical: false,
profile_summary: existingSummary,
verification_questions: [],
uncertainty_notes: [],
composer_model: '',
composed_at: '',
}
}
return null
})
const [errorMessage, setErrorMessage] = useState<string | null>(null)
const setStatus = useCallback((id: StepId, status: StepStatus) => {
setStatuses((prev) => ({ ...prev, [id]: status }))
}, [])
// No started-ref guard: React 19 Strict Mode runs this effect twice in dev.
// The first invocation's cleanup aborts its fetch; the second invocation
// makes the request that actually completes. The stream endpoint is
// idempotent (it upserts agent_profiles on company_id), so a transient
// duplicate call during Strict Mode rerun is safe.
useEffect(() => {
if (alreadyVerified) return
const controller = new AbortController()
void runStream(companyId, controller.signal, {
setStatus,
onProfile: (p) => setProfile(p),
onError: (msg) => setErrorMessage(msg),
onComplete: () => setPhase('review'),
})
return () => {
controller.abort()
}
}, [companyId, alreadyVerified, setStatus])
if (phase === 'review' || phase === 'done') {
return (
<ReviewCard
companyId={companyId}
companyName={companyName}
initialFields={initialFields}
atomTitles={atomTitles}
profile={profile}
onVerified={() => router.push('/chat/intake')}
/>
)
}
return (
<div className="w-full">
<header className="mb-10 text-center">
<p className="text-sm uppercase tracking-wider text-muted-foreground">
{firstName ? `${firstName}, ` : ''}ett ögonblick
</p>
<h1 className="font-display text-3xl md:text-4xl tracking-tight mt-2">
Vi bygger din bokföringsassistent
</h1>
<p className="text-muted-foreground mt-3 text-balance">
Skräddarsyr för {companyName}. Tar oftast under en halv minut.
</p>
</header>
<Card className="border-border">
<CardContent className="p-6 md:p-8">
<ol className="space-y-4">
{STEPS.map((step) => (
<StepRow key={step.id} step={step} status={statuses[step.id]} />
))}
</ol>
{errorMessage && (
<div className="mt-6 flex items-start gap-3 rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm">
<AlertTriangle className="h-4 w-4 mt-0.5 text-destructive shrink-0" />
<div>
<p className="font-medium">Något gick fel</p>
<p className="text-muted-foreground mt-1">{errorMessage}</p>
<Button
variant="outline"
size="sm"
className="mt-3"
onClick={() => window.location.reload()}
>
Försök igen
</Button>
</div>
</div>
)}
</CardContent>
</Card>
</div>
)
}
function StepRow({ step, status }: { step: StepConfig; status: StepStatus }) {
return (
<li className="flex items-start gap-3">
<span className="mt-0.5 shrink-0">
{status === 'success' && <Check className="h-4 w-4 text-success" />}
{status === 'fallback' && <Check className="h-4 w-4 text-warning" />}
{status === 'in_progress' && <Loader2 className="h-4 w-4 animate-spin text-foreground" />}
{status === 'pending' && <Circle className="h-4 w-4 text-muted-foreground/50" />}
{status === 'error' && <AlertTriangle className="h-4 w-4 text-destructive" />}
</span>
<span
className={cn(
'text-sm leading-6',
status === 'pending' && 'text-muted-foreground',
status === 'fallback' && 'text-muted-foreground',
)}
>
{status === 'fallback' && step.fallbackLabel ? step.fallbackLabel : step.label}
</span>
</li>
)
}
async function runStream(
companyId: string,
signal: AbortSignal,
cbs: {
setStatus: (id: StepId, status: StepStatus) => void
onProfile: (p: ProfilePayload) => void
onError: (msg: string) => void
onComplete: () => void
},
): Promise<void> {
let response: Response
try {
response = await fetch('/api/agent/onboarding/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ company_id: companyId }),
signal,
})
} catch (err) {
if (signal.aborted) return
cbs.onError(err instanceof Error ? err.message : 'Kunde inte starta byggsekvensen.')
return
}
if (!response.ok || !response.body) {
cbs.onError(`HTTP ${response.status}: kunde inte starta byggsekvensen.`)
return
}
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
let newlineIdx: number
while ((newlineIdx = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, newlineIdx).trim()
buffer = buffer.slice(newlineIdx + 1)
if (!line) continue
try {
const event = JSON.parse(line) as
| { step: StepId; status: StepStatus }
| { step: 'finalize'; status: 'success'; profile: ProfilePayload }
| { step: 'error'; status: 'error'; message: string }
| { step: 'prewarm'; status: StepStatus }
if (event.step === 'error') {
cbs.onError(event.message || 'Okänt fel under byggsekvensen.')
continue
}
if (event.step === 'prewarm') {
// Pre-warm runs after finalize — surface nothing in the UI; the
// user has already moved to Phase B by then.
continue
}
cbs.setStatus(event.step, event.status as StepStatus)
if (event.step === 'finalize' && 'profile' in event) {
cbs.onProfile(event.profile)
cbs.onComplete()
}
} catch {
// Malformed JSON line — keep reading.
}
}
}
} catch (err) {
if (!signal.aborted) {
cbs.onError(err instanceof Error ? err.message : 'Streamen avbröts.')
}
} finally {
try {
reader.releaseLock()
} catch {
// Already released
}
}
}
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More