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
+5
View File
@@ -11,6 +11,11 @@ jobs:
with:
node-version: 20
- run: npm ci
- name: Verify skill bodies are in sync with the seed migration
# Fails if a .claude/skills/**/SKILL.md changed without regenerating the
# seed migration (npm run skills:generate). Keeps prod skill content from
# silently drifting out of sync. No DB needed — reads files + manifest.
run: npm run skills:check
- name: Reset extensions config
run: echo '{"extensions":[]}' > extensions.config.json
- run: npm run setup:extensions
+2
View File
@@ -66,3 +66,5 @@ supabase/.temp/
# The empty defaults in lib/extensions/_generated/ are committed so core compiles
# out of the box without running the generator.
supabase/.branches/
scripts\remap-krister-bas96-to-bas2025.ts
+4
View File
File diff suppressed because one or more lines are too long
+3 -1
View File
@@ -137,12 +137,14 @@ export default function BookkeepingPage() {
<PageHeader
title={t('title')}
action={
<Button variant="outline" asChild className="w-full sm:w-auto">
<div className="flex gap-2 w-full sm:w-auto">
<Button variant="outline" asChild className="w-full sm:w-auto">
<Link href="/bookkeeping/year-end">
<Lock className="mr-2 h-4 w-4" />
{t('year_end')}
</Link>
</Button>
</div>
}
/>
+16 -7
View File
@@ -16,6 +16,7 @@ import {
} from '@/components/ui/select'
import { Skeleton } from '@/components/ui/skeleton'
import { ArrowLeft, Lock } from 'lucide-react'
import AgentSparkleButton from '@/components/agent/AgentSparkleButton'
import { cn } from '@/lib/utils'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
@@ -200,14 +201,22 @@ export default function YearEndPage() {
return (
<div className="space-y-8">
<div className="flex items-center justify-between">
<div className="flex items-center justify-between gap-3 flex-wrap">
<h1 className="font-display text-3xl md:text-4xl tracking-tight">Årsbokslut</h1>
<Button variant="outline" asChild>
<Link href="/bookkeeping">
<ArrowLeft className="mr-2 h-4 w-4" />
Bokföring
</Link>
</Button>
<div className="flex gap-2">
<AgentSparkleButton
intentId="bokslut.step"
intentArgs={{ step_id: null }}
contextRef="bokslut:overview"
size="default"
/>
<Button variant="outline" asChild>
<Link href="/bookkeeping">
<ArrowLeft className="mr-2 h-4 w-4" />
Bokföring
</Link>
</Button>
</div>
</div>
{periods === null && !periodsError && (
+65
View File
@@ -0,0 +1,65 @@
import { createClient } from '@/lib/supabase/server'
import { notFound, redirect } from 'next/navigation'
import { getActiveCompanyId } from '@/lib/company/context'
import ChatConversationView from '@/components/agent/ChatConversationView'
export const dynamic = 'force-dynamic'
interface PageProps {
params: Promise<{ id: string }>
}
// /chat/[id] — server-renders the conversation row + ordered messages, then
// hydrates the client AgentChat with them so the user can continue typing
// against the existing conversation_id. The agent loop on the server picks
// up via /api/agent/invoke with conversation_id supplied.
export default async function ChatConversationPage({ params }: PageProps) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const companyId = await getActiveCompanyId(supabase, user.id)
if (!companyId) redirect('/onboarding')
const { data: conversation } = await supabase
.from('agent_conversations')
.select('id, intent_id, context_ref, title, pinned, archived, last_message_at')
.eq('id', id)
.eq('company_id', companyId)
.maybeSingle()
if (!conversation) notFound()
const { data: messages } = await supabase
.from('agent_messages')
.select('role, content, hidden, created_at')
.eq('conversation_id', id)
.order('created_at', { ascending: true })
return (
<ChatConversationView
conversationId={id}
intentId={conversation.intent_id}
contextRef={conversation.context_ref}
title={conversation.title ?? intentLabel(conversation.intent_id)}
rawMessages={(messages ?? []) as { role: string; content: unknown; hidden?: boolean }[]}
/>
)
}
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'
default:
return intentId
}
}
+24
View File
@@ -0,0 +1,24 @@
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { getActiveCompanyId } from '@/lib/company/context'
import ChatIntakeStarter from '@/components/agent/ChatIntakeStarter'
export const dynamic = 'force-dynamic'
// /chat/intake — Phase C bootstrap surface. ReviewCard navigates here after
// Phase B "kör" succeeds. The client component mounts AgentChat with
// intent='onboarding.intake' in fresh-start mode; AgentChat auto-fires the
// first invoke which creates the conversation row, and we swap the URL to
// /chat/[id] when the new id streams back.
//
// Plan ref: dev_docs/specialized-agent-plan.md §7 Phase C.
export default async function ChatIntakePage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const companyId = await getActiveCompanyId(supabase, user.id)
if (!companyId) redirect('/onboarding')
return <ChatIntakeStarter />
}
+54
View File
@@ -0,0 +1,54 @@
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { getActiveCompanyId } from '@/lib/company/context'
import ChatSidebar from '@/components/agent/ChatSidebar'
export const dynamic = 'force-dynamic'
// Two-pane chat layout: sidebar with conversations on the left, active
// conversation (or empty state) in the main panel. Both /chat and /chat/[id]
// share this layout so the sidebar doesn't unmount on conversation switches.
export default async function ChatLayout({ children }: { children: React.ReactNode }) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const companyId = await getActiveCompanyId(supabase, user.id)
if (!companyId) redirect('/onboarding')
// Block the chat surface until the agent is built. Without this a user
// who deep-links to /chat (bookmark, ⌘K, "+ Ny" elsewhere) lands on an
// empty conversations list with no Anna to talk to. The home route at /
// renders NewUserChecklist for the same state, so we forward there
// instead of duplicating the welcome screen here.
const { data: agent } = await supabase
.from('agent_profiles')
.select('verified_at')
.eq('company_id', companyId)
.maybeSingle()
if (!agent?.verified_at) redirect('/')
const { data: conversations } = await supabase
.from('agent_conversations')
.select(
'id, intent_id, context_ref, title, pinned, archived, last_message_at, last_message_preview, created_at',
)
.eq('company_id', companyId)
.eq('archived', false)
.order('pinned', { ascending: false })
.order('last_message_at', { ascending: false, nullsFirst: false })
.limit(100)
return (
// MainContainer hands /chat a full-bleed h-full wrapper, so we don't
// need negative margins to break out of any chrome padding.
//
// dvh handles mobile browser chrome shrinking on scroll. Mobile: subtract
// the bottom nav (h-16 = 64px) + safe-area-inset-bottom so the chat
// pane fills the visible viewport exactly. Desktop: full viewport.
<div className="flex h-[calc(100dvh-4rem-env(safe-area-inset-bottom,0px))] md:h-screen">
<ChatSidebar initialConversations={conversations ?? []} />
<div className="flex-1 min-w-0 flex flex-col bg-background">{children}</div>
</div>
)
}
+36
View File
@@ -0,0 +1,36 @@
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { getActiveCompanyId } from '@/lib/company/context'
import ChatNewStarter from '@/components/agent/ChatNewStarter'
import { getIntent } from '@/lib/agent/intents/registry'
export const dynamic = 'force-dynamic'
interface PageProps {
searchParams: Promise<{ intent?: string; prompt?: string }>
}
// /chat/new — generic conversation bootstrap. Reads ?intent= and ?prompt=
// from the URL and mounts AgentChat in fresh mode; AgentChat creates the
// conversation server-side on first invoke and the client swaps the URL
// to /chat/[id] when the id streams back. Mirrors /chat/intake but with
// caller-chosen intent/seed, so suggestion chips and ⌘K can route here
// inline instead of opening the slide-in sheet.
export default async function ChatNewPage({ searchParams }: PageProps) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const companyId = await getActiveCompanyId(supabase, user.id)
if (!companyId) redirect('/onboarding')
const sp = await searchParams
const requested = typeof sp.intent === 'string' && sp.intent.trim() ? sp.intent.trim() : 'general.help'
// Validate against the registry — a bogus ?intent= would otherwise render the
// chat shell and then fail at invoke with a 400, which reads as "Anna is broken"
// rather than "bad link". Fall back to general help instead.
const intent = getIntent(requested) ? requested : 'general.help'
const prompt = typeof sp.prompt === 'string' ? sp.prompt : ''
return <ChatNewStarter intentId={intent} seedUserMessage={prompt} />
}
+10
View File
@@ -0,0 +1,10 @@
import ChatEmptyState from '@/components/agent/ChatEmptyState'
export const dynamic = 'force-dynamic'
// Empty state for /chat. The sidebar (in the layout) shows the list; this
// view appears when no specific conversation is selected. Offers an obvious
// entry to start a fresh general.help conversation.
export default function ChatIndexPage() {
return <ChatEmptyState />
}
+7 -1
View File
@@ -30,6 +30,7 @@ import CustomerForm from '@/components/customers/CustomerForm'
import { BankDetailsSetupDialog } from '@/components/invoices/BankDetailsSetupDialog'
import { FirstInvoiceLogoPrompt } from '@/components/invoices/FirstInvoiceLogoPrompt'
import { useCompany } from '@/contexts/CompanyContext'
import AgentSparkleButton from '@/components/agent/AgentSparkleButton'
import {
ROT_WORK_TYPES,
RUT_WORK_TYPES,
@@ -599,7 +600,7 @@ export default function NewInvoicePage() {
<Button variant="ghost" size="icon" onClick={() => router.back()} aria-label={t('back')}>
<ArrowLeft className="h-5 w-5" />
</Button>
<div>
<div className="flex-1 min-w-0">
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">
{titleText}
{numberPreview && (
@@ -610,6 +611,11 @@ export default function NewInvoicePage() {
</h1>
<p className="text-muted-foreground">{subtitleText}</p>
</div>
<AgentSparkleButton
intentId="invoice.draft"
intentArgs={{ customer_id: watchCustomerId ?? null }}
contextRef={watchCustomerId ? `customer:${watchCustomerId}` : 'invoice:new'}
/>
</div>
{hasBankDetails === false && (
+7 -5
View File
@@ -83,11 +83,13 @@ export default function KpiPage() {
<div className="space-y-8">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">{t('title')}</h1>
<KPISettingsDialog
preferences={preferences}
onSave={handleSavePreferences}
saving={isSavingPrefs}
/>
<div className="flex gap-2">
<KPISettingsDialog
preferences={preferences}
onSave={handleSavePreferences}
saving={isSavingPrefs}
/>
</div>
</div>
<FiscalYearSelector
+95 -59
View File
@@ -4,6 +4,9 @@ import { headers } from 'next/headers'
import DashboardNav from '@/components/dashboard/DashboardNav'
import { MainContainer } from '@/components/dashboard/MainContainer'
import CompanyTabSync from '@/components/dashboard/CompanyTabSync'
import { AgentSheetProvider } from '@/components/agent/AgentSheetProvider'
import AgentTrigger from '@/components/agent/AgentTrigger'
import CommandPalette from '@/components/common/CommandPalette'
import { SandboxBanner } from '@/components/dashboard/SandboxBanner'
import { getExtensionNavItems } from '@/lib/extensions/sectors'
import { CompanyProvider } from '@/contexts/CompanyContext'
@@ -84,26 +87,28 @@ export default async function DashboardLayout({
isSandbox: false,
}}
>
<CompanyTabSync />
<div className="min-h-screen bg-background">
<DashboardNav
companyName={getBranding().appName.toLowerCase()}
entityType="enskild_firma"
uncategorizedTransactionCount={0}
pendingOperationsCount={0}
isSandbox={false}
extensionNavItems={getExtensionNavItems()}
/>
<main
id="main-content"
className="safe-area-main-padding md:!pb-0 md:pl-64"
role="main"
>
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
{children}
</div>
</main>
</div>
<AgentSheetProvider>
<CompanyTabSync />
<div className="min-h-screen bg-background">
<DashboardNav
companyName={getBranding().appName.toLowerCase()}
entityType="enskild_firma"
uncategorizedTransactionCount={0}
pendingOperationsCount={0}
isSandbox={false}
extensionNavItems={getExtensionNavItems()}
/>
<main
id="main-content"
className="safe-area-main-padding md:!pb-0 md:pl-64"
role="main"
>
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
{children}
</div>
</main>
</div>
</AgentSheetProvider>
</CompanyProvider>
)
}
@@ -136,27 +141,35 @@ export default async function DashboardLayout({
return (
<CompanyProvider value={companyContextValue}>
<CompanyTabSync />
<div className="min-h-screen bg-background">
<DashboardNav
companyName={getBranding().appName.toLowerCase()}
entityType="enskild_firma"
uncategorizedTransactionCount={0}
pendingOperationsCount={0}
isSandbox={false}
extensionNavItems={getExtensionNavItems()}
/>
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-64" role="main">
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
{children}
</div>
</main>
</div>
<AgentSheetProvider>
<CompanyTabSync />
<div className="min-h-screen bg-background">
<DashboardNav
companyName={getBranding().appName.toLowerCase()}
entityType="enskild_firma"
uncategorizedTransactionCount={0}
pendingOperationsCount={0}
isSandbox={false}
extensionNavItems={getExtensionNavItems()}
/>
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-64" role="main">
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
{children}
</div>
</main>
</div>
</AgentSheetProvider>
</CompanyProvider>
)
}
const [{ data: settings }, { count: uncategorizedCount }, { count: pendingOpsCount }] = await Promise.all([
const [
{ data: settings },
{ count: uncategorizedCount },
{ count: pendingOpsCount },
{ data: agentProfileIdentity },
{ data: userProfile },
] = await Promise.all([
supabase
.from('company_settings')
.select('company_name, onboarding_complete, entity_type, is_sandbox')
@@ -172,6 +185,17 @@ export default async function DashboardLayout({
.select('*', { count: 'exact', head: true })
.eq('company_id', companyId)
.eq('status', 'pending'),
// Agent identity — name + avatar — surfaced on the FAB and chat
// surfaces. Null when no agent_profile exists yet (banner CTA path).
supabase
.from('agent_profiles')
.select('display_name, avatar_id, verified_at')
.eq('company_id', companyId)
.maybeSingle(),
// The signed-in user's profile — shown in the bottom-left account
// popover (full_name + initial) so it's clear which user is logged
// in, distinct from the active company shown at the top.
supabase.from('profiles').select('full_name').eq('id', user.id).maybeSingle(),
])
// If onboarding incomplete, still render the dashboard — the page component
@@ -203,28 +227,40 @@ export default async function DashboardLayout({
return (
<CompanyProvider value={companyContextValue}>
<CompanyTabSync />
<div className="min-h-screen bg-background">
{/* Skip to content link for keyboard/screen reader users */}
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[100] focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-lg focus:text-sm focus:font-medium"
>
Hoppa till innehåll
</a>
{isSandbox && <SandboxBanner />}
<DashboardNav
companyName={settings?.company_name || 'Min verksamhet'}
entityType={entityType}
uncategorizedTransactionCount={uncategorizedCount ?? 0}
pendingOperationsCount={pendingOpsCount ?? 0}
isSandbox={isSandbox}
extensionNavItems={getExtensionNavItems()}
/>
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-64" role="main">
<MainContainer companyId={companyId}>{children}</MainContainer>
</main>
</div>
<AgentSheetProvider
identity={{
displayName: agentProfileIdentity?.display_name ?? null,
avatarId: agentProfileIdentity?.avatar_id ?? null,
isVerified: Boolean(agentProfileIdentity?.verified_at),
}}
>
<CompanyTabSync />
<div className="min-h-screen bg-background">
{/* Skip to content link for keyboard/screen reader users */}
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[100] focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-lg focus:text-sm focus:font-medium"
>
Hoppa till innehåll
</a>
{isSandbox && <SandboxBanner />}
<DashboardNav
companyName={settings?.company_name || 'Min verksamhet'}
entityType={entityType}
uncategorizedTransactionCount={uncategorizedCount ?? 0}
pendingOperationsCount={pendingOpsCount ?? 0}
isSandbox={isSandbox}
extensionNavItems={getExtensionNavItems()}
userName={userProfile?.full_name ?? null}
userEmail={user.email ?? null}
/>
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-64" role="main">
<MainContainer companyId={companyId}>{children}</MainContainer>
</main>
<AgentTrigger />
<CommandPalette />
</div>
</AgentSheetProvider>
</CompanyProvider>
)
}
+37
View File
@@ -2,12 +2,18 @@ import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { cookies } from 'next/headers'
import DashboardContent from '@/components/dashboard/DashboardContent'
import WelcomeGate from '@/components/onboarding/WelcomeGate'
import { getActiveCompanyId } from '@/lib/company/context'
import { getDisplayTotal } from '@/lib/invoices/rounding'
import type { Deadline, ReceiptQueueSummary, OnboardingProgress } from '@/types'
export const dynamic = 'force-dynamic'
// Home route = Översikt (DashboardContent). The agent chat has its own nav
// entry at /chat, so / no longer forwards there. New users who haven't built
// their assistant yet get WelcomeGate (the build-agent checklist) instead of
// the dashboard; once the agent is verified, / renders the normal Översikt.
export default async function DashboardPage() {
const supabase = await createClient()
@@ -76,6 +82,7 @@ export default async function DashboardPage() {
{ count: staleUncategorizedCount },
{ count: uncategorizedCount },
{ count: skatteverketTokenCount },
{ data: agentProfile },
{ data: noDocRequiredEntries },
] = await Promise.all([
supabase.from('company_settings').select('*').eq('company_id', companyId).single(),
@@ -106,6 +113,7 @@ export default async function DashboardPage() {
// carry the active company_id; either filter would work — we use user_id
// because that's what the token-store reads/writes against.
supabase.from('skatteverket_tokens').select('*', { count: 'exact', head: true }).eq('user_id', user.id),
supabase.from('agent_profiles').select('verified_at').eq('company_id', companyId).maybeSingle(),
supabase.from('journal_entry_no_doc_required').select('journal_entry_id').eq('company_id', companyId),
])
@@ -114,6 +122,34 @@ export default async function DashboardPage() {
redirect('/onboarding')
}
const agentBuilt = Boolean(agentProfile?.verified_at)
// "Has the company already been used?" Any real business data means we must
// NOT hijack the dashboard with the full-screen onboarding gate — existing
// and migrated users get the normal Översikt with a build-assistant prompt
// in the hero slot (see DashboardContent's agentBuilt branch) instead.
const hasData =
(transactionCount || 0) > 0 ||
(sieImportCount || 0) > 0 ||
(invoiceCount || 0) > 0 ||
(receiptCount || 0) > 0 ||
(customerCount || 0) > 0 ||
(postedEntriesCount || 0) > 0
// Only a genuinely empty company without an assistant sees the full
// onboarding checklist (where building the assistant is the last step).
// Everyone else falls through to the dashboard below.
if (!agentBuilt && !hasData) {
return (
<WelcomeGate
companyId={companyId}
hasBookkeepingImported={(sieImportCount || 0) > 0}
hasBankConnected={(transactionCount || 0) > 0}
hasSkatteverketConnected={(skatteverketTokenCount || 0) > 0}
/>
)
}
const onboardingProgress: OnboardingProgress = {
hasCustomers: (customerCount || 0) > 0,
hasInvoices: (invoiceCount || 0) > 0,
@@ -252,6 +288,7 @@ export default async function DashboardPage() {
return (
<DashboardContent
companyId={companyId}
agentBuilt={agentBuilt}
summary={{
ytd: ytdTotals,
mtd: mtdTotals,
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Download, FileSpreadsheet, AlertCircle, ChevronDown, ChevronRight, ArrowRight } from 'lucide-react'
import AgentSparkleButton from '@/components/agent/AgentSparkleButton'
import { formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { AccountNumber } from '@/components/ui/account-number'
@@ -1352,7 +1353,7 @@ function VatDeclarationView() {
return (
<div className="space-y-4">
<div className="flex justify-end">
<div className="flex justify-end gap-2">
<Button
variant="outline"
size="sm"
@@ -1361,6 +1362,11 @@ function VatDeclarationView() {
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
<AgentSparkleButton
intentId="vat.review"
intentArgs={{ period_type: periodType, year, period }}
contextRef={`vat:${year}-${periodType}-${period}`}
/>
</div>
{/* Period selection */}
<Card>
@@ -0,0 +1,8 @@
import { redirect } from 'next/navigation'
// Merged into the "Assistenten" tab. Kept as a permanent redirect so existing
// links (e.g. AgentChat's "what I remember" affordance) and old bookmarks land
// in the right place.
export default function AgentMemorySettingsPage() {
redirect('/settings/assistant')
}
@@ -0,0 +1,7 @@
import { redirect } from 'next/navigation'
// Merged into the "Assistenten" tab (Kompetens view). Kept as a permanent
// redirect for old links.
export default function AgentSkillsSettingsPage() {
redirect('/settings/assistant?view=skills')
}
@@ -0,0 +1,43 @@
'use client'
import { useSearchParams, useRouter } from 'next/navigation'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { AgentMemoryPanel } from '@/components/settings/AgentMemoryPanel'
import { AgentSkillsPanel } from '@/components/settings/AgentSkillsPanel'
// "Assistenten" — what the assistant remembers about this company (Minne,
// editable) and the domain knowledge it ships with (Kompetens, read-only).
// A toggle keeps both one click away instead of stacked, so the competence
// view isn't buried below the memory list.
type View = 'memory' | 'skills'
export default function AssistantSettingsPage() {
const searchParams = useSearchParams()
const router = useRouter()
const view: View = searchParams.get('view') === 'skills' ? 'skills' : 'memory'
function setView(next: string) {
// 'memory' is the default — keep its URL clean (no query string).
router.replace(next === 'skills' ? '/settings/assistant?view=skills' : '/settings/assistant', {
scroll: false,
})
}
return (
<Tabs value={view} onValueChange={setView} className="space-y-6">
<TabsList>
<TabsTrigger value="memory">Minne</TabsTrigger>
<TabsTrigger value="skills">Kompetens</TabsTrigger>
</TabsList>
{/* Radix unmounts the inactive panel, so each panel's data is fetched
lazily the first time its tab is opened. */}
<TabsContent value="memory">
<AgentMemoryPanel />
</TabsContent>
<TabsContent value="skills">
<AgentSkillsPanel />
</TabsContent>
</Tabs>
)
}
@@ -0,0 +1,7 @@
import { redirect } from 'next/navigation'
// Företagsprofil (TIC-snapshot Bolagsuppgifter) now lives as a section on the
// Företag tab. Kept as a permanent redirect for old bookmarks and deep links.
export default function CompanyProfileSettingsPage() {
redirect('/settings/company')
}
@@ -4,6 +4,7 @@ import { useRouter } from 'next/navigation'
import { CompanyDangerZone } from '@/components/settings/CompanyDangerZone'
import { CompanyInfoForm } from '@/components/settings/CompanyInfoForm'
import { CompanyMembersSection } from '@/components/settings/CompanyMembersSection'
import { CompanyProfileSection } from '@/components/settings/CompanyProfileSection'
import { FiscalPeriodEditor } from '@/components/settings/FiscalPeriodEditor'
import { LogoUpload } from '@/components/settings/LogoUpload'
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
@@ -60,6 +61,8 @@ export default function CompanySettingsPage() {
<FiscalPeriodEditor />
<CompanyProfileSection />
<CompanyDangerZone />
</div>
)
+2
View File
@@ -14,6 +14,8 @@ const TAB_TO_ROUTE: Record<string, string> = {
team: '/settings/team',
banking: '/settings/banking',
templates: '/settings/templates',
'agent-memory': '/settings/assistant',
assistant: '/settings/assistant',
account: '/settings/account',
api: '/settings/api',
}
+4 -39
View File
@@ -1,42 +1,7 @@
'use client'
import { useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { useSearchParams, useRouter } from 'next/navigation'
import { useToast } from '@/components/ui/use-toast'
import { SkatteverketConnectPanel } from '@/components/settings/SkatteverketConnectPanel'
import { redirect } from 'next/navigation'
// Skatteverket-anslutningen ligger numera som en sektion under Skatt-fliken.
// Behålls som permanent omdirigering för gamla bokmärken och djuplänkar.
export default function SkatteverketSettingsPage() {
const t = useTranslations('settings_skatteverket')
const searchParams = useSearchParams()
const router = useRouter()
const { toast } = useToast()
useEffect(() => {
const connected = searchParams.get('skv_connected')
const error = searchParams.get('skv_error')
if (connected === 'true') {
toast({
title: t('connected_title'),
description: t('connected_description'),
})
router.replace('/settings/skatteverket')
} else if (error) {
let msg: string
try { msg = decodeURIComponent(error) } catch { msg = error }
toast({
title: t('connect_failed_title'),
description: msg,
variant: 'destructive',
})
router.replace('/settings/skatteverket')
}
}, [searchParams, router, toast, t])
return (
<div className="space-y-8">
<SkatteverketConnectPanel />
</div>
)
redirect('/settings/tax')
}
+61 -3
View File
@@ -1,13 +1,65 @@
'use client'
import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { useSearchParams, useRouter } from 'next/navigation'
import { TaxSettingsForm } from '@/components/settings/TaxSettingsForm'
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
import { SkatteverketConnectPanel } from '@/components/settings/SkatteverketConnectPanel'
import { useSettings } from '@/components/settings/useSettings'
import { useToast } from '@/components/ui/use-toast'
import { useCompany } from '@/contexts/CompanyContext'
import { createClient } from '@/lib/supabase/client'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import type { CompanySettings } from '@/types'
export default function TaxSettingsPage() {
const { settings, isLoading, updateSettings } = useSettings()
const { company } = useCompany()
const t = useTranslations('settings_skatteverket')
const searchParams = useSearchParams()
const router = useRouter()
const { toast } = useToast()
const [isSandbox, setIsSandbox] = useState(false)
const hasSkatteverketExtension = ENABLED_EXTENSION_IDS.has('skatteverket')
// Sandbox companies don't connect to the real Skatteverket — hide the panel,
// matching the old Skatteverket tab's visibility gate.
useEffect(() => {
if (!company?.id) return
const supabase = createClient()
supabase
.from('company_settings')
.select('is_sandbox')
.eq('company_id', company.id)
.single()
.then(({ data }) => {
if (data?.is_sandbox) setIsSandbox(true)
})
}, [company?.id])
// Skatteverket OAuth callback — the connect flow returns to /settings/tax with
// a status query param (returnTo set in SkatteverketConnectPanel).
useEffect(() => {
const connected = searchParams.get('skv_connected')
const error = searchParams.get('skv_error')
if (connected === 'true') {
toast({ title: t('connected_title'), description: t('connected_description') })
router.replace('/settings/tax')
} else if (error) {
let msg: string
try {
msg = decodeURIComponent(error)
} catch {
msg = error
}
toast({ title: t('connect_failed_title'), description: msg, variant: 'destructive' })
router.replace('/settings/tax')
}
}, [searchParams, router, toast, t])
if (isLoading || !settings) return <SettingsLoadingSkeleton />
@@ -36,9 +88,15 @@ export default function TaxSettingsPage() {
}
}
const showSkatteverket = hasSkatteverketExtension && !isSandbox
return (
<SettingsFormWrapper onSave={handleSave} className="space-y-0">
<TaxSettingsForm settings={settings} />
</SettingsFormWrapper>
<div className="space-y-8">
<SettingsFormWrapper onSave={handleSave} className="space-y-0">
<TaxSettingsForm settings={settings} />
</SettingsFormWrapper>
{showSkatteverket && <SkatteverketConnectPanel />}
</div>
)
}
+1 -1
View File
@@ -235,7 +235,7 @@ export default function SkattekontoPage() {
ansluta med BankID i inställningarna.
</p>
<Button asChild>
<Link href="/settings/skatteverket">
<Link href="/settings/tax">
<ExternalLink className="mr-2 h-4 w-4" />
Anslut Skatteverket
</Link>
@@ -13,6 +13,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { ArrowLeft, CheckCircle, CreditCard, FileText, Trash2, Lock, Undo2, Info } from 'lucide-react'
import AgentSparkleButton from '@/components/agent/AgentSparkleButton'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { formatDate } from '@/lib/utils'
import Link from 'next/link'
@@ -243,6 +244,12 @@ export default function SupplierInvoiceDetailPage() {
{/* Actions */}
<div className="flex flex-wrap gap-2">
<AgentSparkleButton
intentId="supplier_invoice.review"
intentArgs={{ supplier_invoice_id: invoice.id }}
contextRef={`supplier_invoice:${invoice.id}`}
size="default"
/>
{invoice.status === 'registered' && !invoice.is_credit_note && (
<>
<Button
+46 -8
View File
@@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import AiFilledIndicator from '@/components/ui/ai-filled-indicator'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
@@ -23,7 +24,7 @@ import { cn, formatCurrency } from '@/lib/utils'
import { useUnsavedChanges } from '@/lib/hooks/use-unsaved-changes'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import BankTransactionPicker from '@/components/transactions/BankTransactionPicker'
import { ArrowLeft, Plus, Trash2, ChevronDown, Loader2, Lock, AlertCircle, Sparkles, Link2 } from 'lucide-react'
import { ArrowLeft, Plus, Trash2, ChevronDown, Loader2, Lock, AlertCircle, MessageCircle, Link2 } from 'lucide-react'
import type { Supplier, BASAccount, VatTreatment, EntityType, InvoiceExtractionResult } from '@/types'
interface LineItem {
@@ -274,6 +275,28 @@ export default function NewSupplierInvoicePage() {
const watchedCurrency = watch('currency')
const watchedPaidPrivately = watch('paid_with_private_funds')
const watchedReverseCharge = watch('reverse_charge')
// Watched values used to decide whether the AI-filled indicator should
// still be visible. Once the user edits a field, its value no longer
// matches what the extractor wrote, and the dot fades out.
const watchedInvoiceNumber = watch('supplier_invoice_number')
const watchedInvoiceDate = watch('invoice_date')
const watchedDueDate = watch('due_date')
const watchedPaymentReference = watch('payment_reference')
// Returns true when the field currently matches whatever the AI wrote
// when the form first loaded. Edits diverge it, hiding the dot.
function stillFromAi(value: string | null | undefined, original: string | null | undefined): boolean {
if (!original) return false
return (value ?? '') === (original ?? '')
}
const aiFlags = {
invoiceNumber: stillFromAi(watchedInvoiceNumber, originalExtracted?.invoice?.invoiceNumber ?? null),
invoiceDate: stillFromAi(watchedInvoiceDate, originalExtracted?.invoice?.invoiceDate ?? null),
dueDate: stillFromAi(watchedDueDate, originalExtracted?.invoice?.dueDate ?? null),
paymentReference: stillFromAi(
watchedPaymentReference,
originalExtracted?.invoice?.paymentReference ?? null,
),
}
const isEF = entityType === 'enskild_firma'
@@ -414,8 +437,8 @@ export default function NewSupplierInvoicePage() {
// Auto-fetch Riksbanken exchange rate when currency switches to non-SEK and
// the user hasn't typed a custom rate yet. Re-fetches when the invoice
// date changes too. Never overwrites a user-entered rate.
const watchedInvoiceDate = watch('invoice_date')
// date changes too. Never overwrites a user-entered rate. Reuses the
// watchedInvoiceDate declared above for the AI-filled-indicator flag.
// The "user has manually edited the rate" flag is scoped *per currency*.
// Switching from EUR (rate 11.8 edited by hand) to USD must re-fetch — the
// EUR rate is meaningless for a USD invoice. Tracking last-fetched currency
@@ -968,7 +991,7 @@ export default function NewSupplierInvoicePage() {
<CardContent className="py-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div className="flex items-start gap-3">
<Sparkles className="h-5 w-5 text-primary shrink-0 mt-0.5" />
<MessageCircle className="h-5 w-5 text-primary shrink-0 mt-0.5" />
<div>
<p className="text-sm font-medium">
{t('ai_suggested_supplier', { name: extractedData?.supplier?.name ?? '' })}
@@ -1054,7 +1077,10 @@ export default function NewSupplierInvoicePage() {
/>
</div>
<div className="space-y-2">
<Label>{t('supplier_invoice_number_label')}<RequiredMark /></Label>
<div className="flex items-center justify-between">
<Label>{t('supplier_invoice_number_label')}<RequiredMark /></Label>
<AiFilledIndicator active={aiFlags.invoiceNumber} label="AI-fyllt" />
</div>
{(() => {
const { ref: rhfRef, ...rest } = register('supplier_invoice_number')
return (
@@ -1075,17 +1101,29 @@ export default function NewSupplierInvoicePage() {
watchedPaidPrivately ? 'sm:grid-cols-1' : 'sm:grid-cols-3',
)}>
<div className="space-y-2">
<Label>{t('invoice_date_label')}<RequiredMark /></Label>
<div className="flex items-center justify-between">
<Label>{t('invoice_date_label')}<RequiredMark /></Label>
<AiFilledIndicator active={aiFlags.invoiceDate} label="AI-fyllt" />
</div>
<Input type="date" {...register('invoice_date')} />
</div>
{!watchedPaidPrivately && (
<>
<div className="space-y-2">
<Label>{t('due_date_label')}<RequiredMark /></Label>
<div className="flex items-center justify-between">
<Label>{t('due_date_label')}<RequiredMark /></Label>
<AiFilledIndicator active={aiFlags.dueDate} label="AI-fyllt" />
</div>
<Input type="date" {...register('due_date')} />
</div>
<div className="space-y-2">
<Label>{t('payment_reference_label')}</Label>
<div className="flex items-center justify-between">
<Label>{t('payment_reference_label')}</Label>
<AiFilledIndicator
active={aiFlags.paymentReference}
label="AI-fyllt"
/>
</div>
<Input placeholder={t('payment_reference_placeholder')} {...register('payment_reference')} />
</div>
</>
+8 -8
View File
@@ -437,9 +437,13 @@ export default function TransactionsPage() {
return () => { cancelled = true }
}, [])
// Auto-open categorize panel when arriving via /transactions?highlight=<id>
// (used by the inbox "Bokför transaktionen" link). Runs once per distinct
// highlight id so closing the panel doesn't re-trigger it.
// Scroll the targeted row into view when arriving via
// /transactions?highlight=<id>. Callers are inbox "Öppna transaktionen",
// payment-booking dialog, and supplier-invoice cross-link — all "go look
// at this row", not "start booking". The legacy auto-open-template-picker
// behavior was removed in v5: booking happens in the inbox workspace now.
// Runs once per distinct highlight id so closing/scrolling away doesn't
// re-trigger it.
useEffect(() => {
if (!highlightId) return
if (handledHighlightRef.current === highlightId) return
@@ -459,11 +463,6 @@ export default function TransactionsPage() {
}
})
})
if (tx.is_business === null && !tx.journal_entry_id) {
setTemplatePickerTransaction(tx)
setTemplatePickerOpen(true)
}
}, [highlightId, transactions])
// Auto-fetch suggestions when transactions load
@@ -1995,6 +1994,7 @@ export default function TransactionsPage() {
</div>
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,111 @@
import { describe, it, expect, vi } from 'vitest'
import { findCompanyRoleByOrgNumber } from '../page'
import type { EnrichmentCompanyRole } from '@/lib/company-lookup/types'
// `findCompanyRoleByOrgNumber` replaces the old prefetchLookup at /onboarding.
// It reads bankid_enrichment.company_roles (populated by TIC Identity API at
// BankID-completion time) and matches the role by orgnr. This costs zero
// Lens calls — Identity API is on a different TIC product/quota. These tests
// pin the behaviour because regressing this would silently re-add Lens spend
// to every BankID signup.
function makeRole(overrides: Partial<EnrichmentCompanyRole> = {}): EnrichmentCompanyRole {
return {
companyId: 12345,
companyRegistrationNumber: '5560125790',
legalName: 'Acme AB',
legalEntityType: 'Aktiebolag',
positionTypes: ['boardMember'],
positionDescriptions: ['Styrelseledamot'],
positionStart: '2020-01-01',
positionEnd: null,
companyStatus: 'isActive',
...overrides,
}
}
function mockSupabase(rolesData: EnrichmentCompanyRole[] | null) {
return {
from: vi.fn().mockReturnValue({
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
maybeSingle: vi.fn().mockResolvedValue({
data: rolesData === null ? null : { company_roles: rolesData },
error: null,
}),
}),
}),
}),
}
}
describe('findCompanyRoleByOrgNumber', () => {
it('returns the matching role for a clean 10-digit orgnr', async () => {
const supabase = mockSupabase([
makeRole({ companyRegistrationNumber: '5560125790', legalName: 'Acme AB' }),
makeRole({ companyRegistrationNumber: '5567890123', legalName: 'Other AB' }),
])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await findCompanyRoleByOrgNumber(supabase as any, 'user-1', '5560125790')
expect(result).toEqual({ legalName: 'Acme AB', legalEntityType: 'Aktiebolag' })
})
it('matches orgnrs with hyphens stripped (TIC returns "556012-5790")', async () => {
// CompanyRoles may carry the orgnr in formatted form; the function under
// test cleans the registered form before comparing to the cleaned input.
const supabase = mockSupabase([
makeRole({ companyRegistrationNumber: '556012-5790', legalName: 'Acme AB' }),
])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await findCompanyRoleByOrgNumber(supabase as any, 'user-1', '5560125790')
expect(result).toEqual({ legalName: 'Acme AB', legalEntityType: 'Aktiebolag' })
})
it('returns null when no enrichment row exists (user signed up without BankID)', async () => {
const supabase = mockSupabase(null)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await findCompanyRoleByOrgNumber(supabase as any, 'user-1', '5560125790')
expect(result).toBeNull()
})
it('returns null when enrichment row has an empty company_roles array', async () => {
const supabase = mockSupabase([])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await findCompanyRoleByOrgNumber(supabase as any, 'user-1', '5560125790')
expect(result).toBeNull()
})
it('returns null when none of the roles match the requested orgnr', async () => {
const supabase = mockSupabase([
makeRole({ companyRegistrationNumber: '5567890123', legalName: 'Other AB' }),
])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await findCompanyRoleByOrgNumber(supabase as any, 'user-1', '5560125790')
expect(result).toBeNull()
})
it('preserves the TIC `legalEntityType` exactly so mapEntityType can classify v2 strings', async () => {
// Important: TIC v2 returns full Swedish names like "Aktiebolag" and
// "Enskild firma" (not the v1 "AB"/"EF" abbreviations). The canonical
// mapEntityType in lib/company-lookup/entity-type-map.ts handles both
// sets — but only if we pass the raw string through unchanged.
const supabase = mockSupabase([
makeRole({ companyRegistrationNumber: '8001011231', legalEntityType: 'Enskild firma' }),
])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await findCompanyRoleByOrgNumber(supabase as any, 'user-1', '8001011231')
expect(result?.legalEntityType).toBe('Enskild firma')
})
})
+252
View File
@@ -0,0 +1,252 @@
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { headers } from 'next/headers'
import { getActiveCompanyId } from '@/lib/company/context'
import { ensureTicSnapshot } from '@/lib/agent/composer/tic-fetch'
import AgentOnboarding from '@/components/onboarding/agent/AgentOnboarding'
export const dynamic = 'force-dynamic'
// /onboarding/agent — Phase A (real-timed build) and Phase B (review) of the
// specialized accountant agent build sequence.
//
// Plan refs: dev_docs/specialized-agent-plan.md §7 (Build-sequence UX),
// §15 Phase 2 (Build-sequence UX).
export default async function AgentOnboardingPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const companyId = await getActiveCompanyId(supabase, user.id)
if (!companyId) redirect('/onboarding')
// Trigger the TIC live-fetch + cache before the field-resolving query
// below. ensureTicSnapshot is fast on cache-hit (single SELECT) and
// best-effort on miss — it never throws. Phase A still runs through the
// streaming endpoint; this just lets the initial Phase B render show the
// SNI/verksamhetsbeskrivning when the user returns to the page after
// stream completion.
const hdrs = await headers()
const cookieHeader = hdrs.get('cookie') ?? ''
const host = hdrs.get('host') ?? 'localhost:3000'
const proto = hdrs.get('x-forwarded-proto') ?? (host.startsWith('localhost') ? 'http' : 'https')
const origin = `${proto}://${host}`
// upgradeV1: this is the one place the v2-only sections (statuses,
// beneficialOwners, payrolls, …) materially drive the composer, and it's
// a deliberate once-per-company action — safe to spend the TIC calls to
// bring a pre-v2 snapshot up to date.
await ensureTicSnapshot({ supabase, companyId, cookieHeader, origin, upgradeV1: true })
// Fetch the small handful of fields we render directly into Phase B so the
// user sees real values (not "Laddar…") the moment the stream finishes.
// company_settings is a separate fetch because it carries the onboarding-
// form data (moms_period, fiscal_year_start_month, f_skatt, city, …) that
// never makes it onto `companies` proper.
const [{ data: company }, { data: profile }, { data: existingProfile }, { data: settings }] =
await Promise.all([
supabase
.from('companies')
.select('name, entity_type, org_number, tic_snapshot')
.eq('id', companyId)
.single(),
supabase.from('profiles').select('full_name').eq('id', user.id).single(),
supabase
.from('agent_profiles')
.select('company_id, profile_summary, verified_at')
.eq('company_id', companyId)
.maybeSingle(),
supabase
.from('company_settings')
.select(
'city, address_line1, postal_code, f_skatt, vat_registered, moms_period, fiscal_year_start_month, employee_count, has_employees',
)
.eq('company_id', companyId)
.maybeSingle(),
])
if (!company) redirect('/onboarding')
const firstName = profile?.full_name?.split(' ')[0] ?? null
// Pre-render-friendly snapshot of company info — used to seed Phase B fields
// before the stream completes so the layout doesn't jump.
const initialFields = buildInitialFields(company, settings)
// Atom titles — slug-derived labels look ugly ("Konsult It",
// "Single Shareholder Ab Fmb"). Fetch the registry titles once and pass them
// to the review card so chips render as authored.
const { data: atomRows } = await supabase
.from('agent_atom_registry')
.select('id, title')
.eq('is_active', true)
.is('parent_atom_id', null) // skill titles only; reference children never appear as profile chips
const atomTitles: Record<string, string> = {}
for (const row of (atomRows ?? []) as { id: string; title: string }[]) {
atomTitles[row.id] = row.title
}
return (
<AgentOnboarding
companyId={companyId}
companyName={company.name}
firstName={firstName}
initialFields={initialFields}
atomTitles={atomTitles}
alreadyVerified={Boolean(existingProfile?.verified_at)}
existingSummary={existingProfile?.profile_summary ?? null}
/>
)
}
interface InitialFields {
entity_type_label: string
// Multiple SNI codes — most companies have one but some are
// multi-vertical (e.g. konsult + lagerförsäljning).
sni_codes: { code: string; name: string }[]
// Verksamhetsbeskrivning (purpose) from Bolagsverket via TIC.
purpose: string | null
city: string | null
fiscal_period: string | null
vat_period: string | null
f_skatt: string | null
employees: string | null
}
interface CompanySettingsForPhaseB {
city: string | null
address_line1: string | null
postal_code: string | null
f_skatt: boolean | null
vat_registered: boolean | null
moms_period: string | null
fiscal_year_start_month: number | null
employee_count: number | null
has_employees: boolean | null
}
function buildInitialFields(
company: {
name: string
entity_type: string
org_number: string | null
tic_snapshot: Record<string, unknown> | null
},
settings: CompanySettingsForPhaseB | null,
): InitialFields {
const tic = (company.tic_snapshot ?? null) as Record<string, unknown> | null
const entityLabel =
company.entity_type === 'aktiebolag'
? 'AB'
: company.entity_type === 'enskild_firma'
? 'Enskild firma'
: company.entity_type
// Tier the resolution: TIC snapshot (if cached) wins because it's the
// authoritative Bolagsverket data; company_settings is the user-entered
// fallback from onboarding. Either can be missing.
let sniCodes: { code: string; name: string }[] = []
let purpose: string | null = null
let city: string | null = null
let fSkatt: string | null = null
let vatPeriod: string | null = null
let fiscalPeriod: string | null = null
let employees: string | null = null
if (tic) {
const sni = (tic.sniCodes as { code: string; name: string }[] | undefined) ?? []
if (Array.isArray(sni)) sniCodes = sni
const tp = tic.purpose
if (typeof tp === 'string' && tp.trim().length > 0) purpose = tp.trim()
const addr = tic.address as { city: string | null } | null
if (addr?.city) city = addr.city
const reg = tic.registration as { fTax?: boolean } | undefined
if (reg) fSkatt = reg.fTax ? 'Aktivt' : 'Saknas'
if (tic.employeeRange) employees = tic.employeeRange as string
// v2 caches `fiscalYear` (current fiscal-year configuration) on the
// snapshot. Prefer it over the user-entered value below so onboarding
// can show the registered fiscal period from Bolagsverket without
// making the user re-enter it.
const ticFiscal = tic.fiscalYear as { startMonthDay?: string | null } | null
const startMonth = parseTicStartMonth(ticFiscal?.startMonthDay)
if (startMonth != null) fiscalPeriod = fiscalYearLabel(startMonth)
}
if (settings) {
if (!city && settings.city) city = settings.city
if (!fSkatt && settings.f_skatt != null) {
fSkatt = settings.f_skatt ? 'Aktivt' : 'Saknas'
}
if (settings.moms_period) {
vatPeriod = momsPeriodLabel(settings.moms_period)
}
// settings.fiscal_year_start_month is the user-confirmed value — only
// overwrite the TIC-derived label if the user has explicitly set it
// (i.e. when there was no TIC fiscalYear AND they entered it manually).
if (!fiscalPeriod && settings.fiscal_year_start_month != null) {
fiscalPeriod = fiscalYearLabel(settings.fiscal_year_start_month)
}
if (!employees && settings.employee_count != null) {
employees = String(settings.employee_count)
} else if (!employees && settings.has_employees != null) {
employees = settings.has_employees ? 'Ja' : 'Nej'
}
}
return {
entity_type_label: entityLabel,
sni_codes: sniCodes,
purpose,
city,
fiscal_period: fiscalPeriod,
vat_period: vatPeriod,
f_skatt: fSkatt,
employees,
}
}
// Parse TIC v2's `startMonthDay` ("MM-DD") into a month number 1-12. Returns
// null when the field is missing or malformed so the caller falls back to
// company_settings.fiscal_year_start_month.
function parseTicStartMonth(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
}
function momsPeriodLabel(period: string): string {
switch (period) {
case 'monthly':
return 'Månadsmoms'
case 'quarterly':
return 'Kvartalsmoms'
case 'yearly':
return 'Årsmoms'
default:
return period
}
}
// "fiscal_year_start_month=1" → "januari–december".
function fiscalYearLabel(startMonth: number): string {
const months = [
'januari',
'februari',
'mars',
'april',
'maj',
'juni',
'juli',
'augusti',
'september',
'oktober',
'november',
'december',
]
if (startMonth < 1 || startMonth > 12) return ''
const startIdx = startMonth - 1
const endIdx = (startIdx + 11) % 12
return `${months[startIdx]}–${months[endIdx]}`
}

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