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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tests: 4112 unchanged. Build: green.

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

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

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

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

Tests: 4112. Build: green.

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

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

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

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

Tests: 4112. Build: green.

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

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

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

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

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

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

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

Tests: 4112. Build: green.

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

* fix(pending): trim the agent context strip

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

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

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

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

Two regressions surfaced in real usage. Both are systemic.

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

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

Tests: 4112. Build: green.

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

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

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

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

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

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

Three pre-ship quality wins.

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

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

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

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

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

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

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

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

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

Tests: 4112. Build: green.

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

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

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

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

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

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

Tests: 4112. Build: green.

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

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

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

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

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

Build: green.

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

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

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

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

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

Tests: 4112. Build: green.

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

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

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

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

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

Build: green.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* wip: bundle in-progress branch work

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

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

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

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

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

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

PR #584 went red on three things:

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

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

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

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

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

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

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

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

---------

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

2762 lines
101 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client'
import React, { useState, useEffect, useCallback } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from "@/components/ui/skeleton"
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'
import { useCompany } from '@/contexts/CompanyContext'
import { FiscalYearSelector } from '@/components/common/FiscalYearSelector'
import { ReportDateRange, type DateRangeValue } from '@/components/common/ReportDateRange'
import { ReportsNav } from '@/components/reports/ReportsNav'
import { NEDeclarationView } from '@/components/reports/NEDeclarationView'
import { PeriodiskSammanstallningView } from '@/components/reports/PeriodiskSammanstallningView'
import { INK2DeclarationView } from '@/components/reports/INK2DeclarationView'
import { BankReconciliationView } from '@/components/reports/BankReconciliationView'
import { TrialBalanceChart } from '@/components/reports/TrialBalanceChart'
import { VatCompositionChart } from '@/components/reports/VatCompositionChart'
import { SkatteverketPanel } from '@/components/reports/SkatteverketPanel'
import { IncomeExpenseChart } from '@/components/reports/IncomeExpenseChart'
import { useReportRowExpansion } from '@/components/reports/ReportRowExpansion'
import type {
ReportSourceLine,
ReportSourceFetcher,
} from '@/lib/reports/source-lines'
import type { MonthlyDataPoint } from '@/components/reports/IncomeExpenseChart'
import type {
TrialBalanceRow,
IncomeStatementReport,
BalanceSheetReport,
ResultatrapportReport,
BalansrapportReport,
VatDeclaration,
VatPeriodType,
} from '@/types'
function formatAmount(amount: number): string {
return amount.toLocaleString('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
/**
* Build a report API query string with the period and optional date range.
* Omitting from/to lets the API fall back to full-period behaviour, which
* keeps URLs (and the matching caches) identical for the "Hela året" preset.
*/
function reportQuery(periodId: string, range?: DateRangeValue): string {
const params = new URLSearchParams({ period_id: periodId })
if (range?.fromDate) params.set('from_date', range.fromDate)
if (range?.toDate) params.set('to_date', range.toDate)
return params.toString()
}
// Breadcrumb trail for drill-down navigation
interface DrillDownStep {
tab: string
label: string
accountNumber?: string
}
const TAB_LABEL_KEYS: Record<string, string> = {
'resultatrapport': 'name_resultatrapport',
'balansrapport': 'name_balansrapport',
'trial-balance': 'name_trial_balance',
'income-statement': 'name_income_statement',
'balance-sheet': 'name_balance_sheet',
'huvudbok': 'name_huvudbok',
}
const DATE_RANGE_TABS = new Set([
'resultatrapport',
'balansrapport',
'income-statement',
'balance-sheet',
])
export default function ReportsPage() {
const router = useRouter()
const [selectedPeriod, setSelectedPeriod] = useState('')
const [selectedPeriodBounds, setSelectedPeriodBounds] = useState<{ start: string; end: string } | null>(null)
const [dateRange, setDateRange] = useState<DateRangeValue>({})
const [activeTab, setActiveTab] = useState('resultatrapport')
const [isLoadingInit, setIsLoadingInit] = useState(true)
const { company } = useCompany()
const t = useTranslations('reports')
// Drill-down state: when navigating from a report to the GL for a specific account
const [glAccountFilter, setGlAccountFilter] = useState<string | null>(null)
const [drillDownTrail, setDrillDownTrail] = useState<DrillDownStep[]>([])
const navigateToAccount = useCallback((accountNumber: string) => {
setDrillDownTrail((prev) => [
...prev,
{ tab: activeTab, label: TAB_LABEL_KEYS[activeTab] ? t(TAB_LABEL_KEYS[activeTab]) : activeTab },
])
setGlAccountFilter(accountNumber)
setActiveTab('huvudbok')
}, [activeTab, t])
const handleTabChange = useCallback((tab: string) => {
// Kassaflödesanalys lives on its own route; route there instead of swapping tabs.
if (tab === 'kassaflodesanalys') {
router.push('/reports/kassaflodesanalys')
return
}
// Årsredovisning is an editable document (narrative + signatures) and lives
// on its own route under the year-end flow. Forward the active period so
// the page opens directly on the right fiscal year.
if (tab === 'arsredovisning') {
router.push(
selectedPeriod
? `/bookkeeping/year-end/arsredovisning?period=${selectedPeriod}`
: '/bookkeeping/year-end/arsredovisning',
)
return
}
// Manual tab change clears drill-down state
setActiveTab(tab)
setGlAccountFilter(null)
setDrillDownTrail([])
}, [router, selectedPeriod])
const navigateBack = useCallback((stepIndex: number) => {
const step = drillDownTrail[stepIndex]
setActiveTab(step.tab)
setGlAccountFilter(null)
setDrillDownTrail(drillDownTrail.slice(0, stepIndex))
}, [drillDownTrail])
// Period list is loaded by FiscalYearSelector; isLoadingInit flips to false
// via its onReady callback once the initial fetch completes.
const isEnskildFirma = company?.entity_type === 'enskild_firma'
const isAktiebolag = company?.entity_type === 'aktiebolag'
return (
<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>
</div>
<div className="flex flex-col sm:flex-row sm:items-end gap-6">
<FiscalYearSelector
value={selectedPeriod || null}
onChange={(id, period) => {
setSelectedPeriod(id || '')
setSelectedPeriodBounds(
period ? { start: period.period_start, end: period.period_end } : null,
)
// Reset the range so the new period's stored preset re-resolves
// against the new bounds (avoids stale dates from the prior year).
setDateRange({})
}}
includeAllOption={false}
hideFuturePeriods
onReady={() => setIsLoadingInit(false)}
/>
{DATE_RANGE_TABS.has(activeTab) && selectedPeriodBounds && (
<ReportDateRange
periodStart={selectedPeriodBounds.start}
periodEnd={selectedPeriodBounds.end}
value={dateRange}
onChange={setDateRange}
/>
)}
</div>
<p className="text-sm text-muted-foreground">
{t('sie_moved_hint')}{' '}
<Link href="/import?view=export#sie-export" className="text-foreground underline underline-offset-4 decoration-muted-foreground/40 hover:decoration-foreground">
{t('sie_moved_link')}
</Link>
.
</p>
{isLoadingInit ? (
<div className="space-y-6">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{[1, 2, 3, 4].map((i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-3 w-16" />
<div className="rounded-lg border p-1 space-y-1">
<Skeleton className="h-8" />
<Skeleton className="h-8" />
<Skeleton className="h-8" />
</div>
</div>
))}
</div>
<Card>
<CardContent className="p-6 space-y-4">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-64" />
</CardContent>
</Card>
</div>
) : (
<>
{selectedPeriod ? (
<>
{/* Drill-down breadcrumb */}
{drillDownTrail.length > 0 && (
<nav className="flex items-center gap-1.5 text-sm">
{drillDownTrail.map((step, i) => (
<React.Fragment key={i}>
<button
onClick={() => navigateBack(i)}
className="text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4 decoration-muted-foreground/40"
>
{step.label}
</button>
<ArrowRight className="h-3.5 w-3.5 text-muted-foreground/60 shrink-0" />
</React.Fragment>
))}
<span className="font-medium">
{t('name_huvudbok')} {glAccountFilter && `— ${glAccountFilter}`}
</span>
</nav>
)}
<div className="flex flex-col sm:flex-row gap-6 sm:gap-8">
<ReportsNav
active={activeTab}
onChange={handleTabChange}
entityType={company?.entity_type}
/>
<div className="flex-1 min-w-0">
{activeTab === 'resultatrapport' && (
<ResultatrapportView periodId={selectedPeriod} dateRange={dateRange} onNavigateToAccount={navigateToAccount} />
)}
{activeTab === 'balansrapport' && (
<BalansrapportView periodId={selectedPeriod} dateRange={dateRange} onNavigateToAccount={navigateToAccount} />
)}
{activeTab === 'trial-balance' && (
<TrialBalanceView periodId={selectedPeriod} onNavigateToAccount={navigateToAccount} />
)}
{activeTab === 'income-statement' && (
<IncomeStatementView periodId={selectedPeriod} dateRange={dateRange} onNavigateToAccount={navigateToAccount} />
)}
{activeTab === 'balance-sheet' && (
<BalanceSheetView periodId={selectedPeriod} dateRange={dateRange} onNavigateToAccount={navigateToAccount} />
)}
{activeTab === 'vat-declaration' && <VatDeclarationView />}
{activeTab === 'periodisk-sammanstallning' && <PeriodiskSammanstallningView />}
{isEnskildFirma && activeTab === 'ne-declaration' && (
<NEDeclarationView periodId={selectedPeriod} />
)}
{isAktiebolag && activeTab === 'ink2-declaration' && (
<INK2DeclarationView periodId={selectedPeriod} />
)}
{activeTab === 'huvudbok' && (
<GeneralLedgerView periodId={selectedPeriod} initialAccountFilter={glAccountFilter} />
)}
{activeTab === 'grundbok' && <JournalRegisterView periodId={selectedPeriod} />}
{activeTab === 'kundreskontra' && <ARLedgerView periodId={selectedPeriod} />}
{activeTab === 'supplier-ledger' && <SupplierLedgerView periodId={selectedPeriod} />}
{activeTab === 'bank-reconciliation' && <BankReconciliationView />}
</div>
</div>
</>
) : (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Inget räkenskapsår valt. Skapa ett räkenskapsår under Inställningar.
</CardContent>
</Card>
)}
</>
)}
</div>
)
}
function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string; onNavigateToAccount: (account: string) => void }) {
const [data, setData] = useState<{
rows: TrialBalanceRow[]
totalDebit: number
totalCredit: number
isBalanced: boolean
} | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [viewMode, setViewMode] = useState<'simplified' | 'detailed'>('simplified')
useEffect(() => {
setLoading(true)
setError(null)
fetch(`/api/reports/trial-balance?period_id=${periodId}`)
.then((res) => res.json())
.then((result) => {
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
setLoading(false)
})
.catch(() => {
setError('Kunde inte hämta saldobalans')
setLoading(false)
})
}, [periodId])
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar saldobalans...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data || data.rows.length === 0) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Inga bokförda verifikationer i denna period.
</CardContent>
</Card>
)
}
function getNetBalance(row: TrialBalanceRow, type: 'opening' | 'period' | 'closing'): number {
let debit: number, credit: number
if (type === 'opening') {
debit = row.opening_debit; credit = row.opening_credit
} else if (type === 'period') {
debit = row.period_debit; credit = row.period_credit
} else {
debit = row.closing_debit; credit = row.closing_credit
}
// Credit-normal accounts (liabilities/equity class 2, revenue class 3): positive when credit > debit
// Debit-normal accounts (assets class 1, expenses class 4-9): positive when debit > credit
const creditNormal = row.account_class === 2 || row.account_class === 3
return Math.round((creditNormal ? credit - debit : debit - credit) * 100) / 100
}
function formatSigned(amount: number): string {
if (amount === 0) return ''
return amount < 0
? `−${formatAmount(Math.abs(amount))}`
: formatAmount(amount)
}
return (
<div className="space-y-4">
<div className="flex justify-end">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/trial-balance/xlsx?period_id=${periodId}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
<TrialBalanceChart rows={data.rows} />
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Saldobalans</CardTitle>
<div className="flex items-center gap-3">
<div className="flex items-center gap-0.5 rounded-md border p-0.5">
<button
onClick={() => setViewMode('simplified')}
className={`px-3 py-1 text-xs rounded-sm transition-colors ${
viewMode === 'simplified'
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:text-foreground'
}`}
>
Förenklad
</button>
<button
onClick={() => setViewMode('detailed')}
className={`px-3 py-1 text-xs rounded-sm transition-colors ${
viewMode === 'detailed'
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:text-foreground'
}`}
>
Detaljerad
</button>
</div>
{data.isBalanced ? (
<Badge className="bg-success/10 text-success">Balanserad</Badge>
) : (
<Badge variant="destructive">Ej balanserad</Badge>
)}
</div>
</div>
</CardHeader>
<CardContent>
<div className="overflow-x-auto -mx-2 px-2">
{viewMode === 'simplified' ? (
<table className="w-full text-sm min-w-[500px]">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="border-b text-left">
<th className="py-2 w-8"></th>
<th className="py-2 w-20">Konto</th>
<th className="py-2">Namn</th>
<th className="py-2 w-32 text-right">Ingående saldo</th>
<th className="py-2 w-32 text-right">Förändring</th>
<th className="py-2 w-32 text-right">Utgående saldo</th>
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<TrialBalanceSimplifiedRow
key={row.account_number}
row={row}
periodId={periodId}
onNavigateToAccount={onNavigateToAccount}
getNetBalance={getNetBalance}
formatSigned={formatSigned}
/>
))}
</tbody>
</table>
) : (
<table className="w-full text-sm min-w-[600px]">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="border-b text-left">
<th className="py-2 w-8"></th>
<th className="py-2 w-20">Konto</th>
<th className="py-2">Namn</th>
<th className="py-2 w-28 text-right">Period debet</th>
<th className="py-2 w-28 text-right">Period kredit</th>
<th className="py-2 w-28 text-right">Saldo debet</th>
<th className="py-2 w-28 text-right">Saldo kredit</th>
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<TrialBalanceDetailedRow
key={row.account_number}
row={row}
periodId={periodId}
onNavigateToAccount={onNavigateToAccount}
/>
))}
</tbody>
<tfoot>
<tr className="font-semibold border-t-2">
<td className="py-2"></td>
<td colSpan={2} className="py-2">Summa</td>
<td className="py-2 text-right">
{formatAmount(data.rows.reduce((s, r) => s + r.period_debit, 0))}
</td>
<td className="py-2 text-right">
{formatAmount(data.rows.reduce((s, r) => s + r.period_credit, 0))}
</td>
<td className={`py-2 text-right ${data.isBalanced ? 'text-success' : 'text-destructive'}`}>
{formatAmount(data.totalDebit)}
</td>
<td className={`py-2 text-right ${data.isBalanced ? 'text-success' : 'text-destructive'}`}>
{formatAmount(data.totalCredit)}
</td>
</tr>
</tfoot>
</table>
)}
</div>
</CardContent>
</Card>
</div>
)
}
// Lazy fetcher for a TB account's source lines. Memoised at the row level so
// repeated toggling never refetches.
function makeTrialBalanceFetcher(accountNumber: string, periodId: string): ReportSourceFetcher {
return async () => {
const res = await fetch(
`/api/reports/trial-balance/account/${encodeURIComponent(accountNumber)}/sources?fiscal_period_id=${encodeURIComponent(periodId)}`
)
const json = await res.json()
if (!res.ok) throw new Error(json.error || 'Kunde inte hämta verifikat')
const lines: ReportSourceLine[] = json.data?.lines || []
return { lines, next_cursor: json.data?.next_cursor ?? null }
}
}
function TrialBalanceSimplifiedRow({
row,
periodId,
onNavigateToAccount,
getNetBalance,
formatSigned,
}: {
row: TrialBalanceRow
periodId: string
onNavigateToAccount: (account: string) => void
getNetBalance: (row: TrialBalanceRow, type: 'opening' | 'period' | 'closing') => number
formatSigned: (amount: number) => string
}) {
const fetcher = React.useMemo(
() => makeTrialBalanceFetcher(row.account_number, periodId),
[row.account_number, periodId]
)
const { Toggle, Panel } = useReportRowExpansion(fetcher, `tb-${row.account_number}`)
const ob = getNetBalance(row, 'opening')
const ch = getNetBalance(row, 'period')
const cb = getNetBalance(row, 'closing')
return (
<>
<tr className="border-b last:border-0 hover:bg-muted/50 transition-colors">
<td className="py-2" onClick={(e) => e.stopPropagation()}>
<Toggle />
</td>
<td
className="py-2 cursor-pointer"
onClick={() => onNavigateToAccount(row.account_number)}
>
<AccountNumber number={row.account_number} name={row.account_name} />
</td>
<td
className="py-2 cursor-pointer"
onClick={() => onNavigateToAccount(row.account_number)}
>
{row.account_name}
</td>
<td className={`py-2 text-right tabular-nums ${ob < 0 ? 'text-destructive' : ''}`}>
{formatSigned(ob)}
</td>
<td className={`py-2 text-right tabular-nums ${ch < 0 ? 'text-destructive' : ''}`}>
{formatSigned(ch)}
</td>
<td className={`py-2 text-right tabular-nums font-medium ${cb < 0 ? 'text-destructive' : ''}`}>
{formatSigned(cb)}
</td>
</tr>
<Panel colSpan={6} />
</>
)
}
function TrialBalanceDetailedRow({
row,
periodId,
onNavigateToAccount,
}: {
row: TrialBalanceRow
periodId: string
onNavigateToAccount: (account: string) => void
}) {
const fetcher = React.useMemo(
() => makeTrialBalanceFetcher(row.account_number, periodId),
[row.account_number, periodId]
)
const { Toggle, Panel } = useReportRowExpansion(fetcher, `tb-det-${row.account_number}`)
return (
<>
<tr className="border-b last:border-0 hover:bg-muted/50 transition-colors">
<td className="py-2" onClick={(e) => e.stopPropagation()}>
<Toggle />
</td>
<td
className="py-2 cursor-pointer"
onClick={() => onNavigateToAccount(row.account_number)}
>
<AccountNumber number={row.account_number} name={row.account_name} />
</td>
<td
className="py-2 cursor-pointer"
onClick={() => onNavigateToAccount(row.account_number)}
>
{row.account_name}
</td>
<td className="py-2 text-right">
{row.period_debit > 0 ? formatAmount(row.period_debit) : ''}
</td>
<td className="py-2 text-right">
{row.period_credit > 0 ? formatAmount(row.period_credit) : ''}
</td>
<td className="py-2 text-right">
{row.closing_debit > 0 ? formatAmount(row.closing_debit) : ''}
</td>
<td className="py-2 text-right">
{row.closing_credit > 0 ? formatAmount(row.closing_credit) : ''}
</td>
</tr>
<Panel colSpan={7} />
</>
)
}
function IncomeStatementView({ periodId, dateRange, onNavigateToAccount }: { periodId: string; dateRange: DateRangeValue; onNavigateToAccount: (account: string) => void }) {
const t = useTranslations('reports')
const [data, setData] = useState<IncomeStatementReport | null>(null)
const [monthlyData, setMonthlyData] = useState<MonthlyDataPoint[]>([])
const [monthlyLoading, setMonthlyLoading] = useState(false)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const reportQs = reportQuery(periodId, dateRange)
useEffect(() => {
setLoading(true)
setError(null)
setMonthlyLoading(true)
fetch(`/api/reports/income-statement?${reportQs}`)
.then((res) => res.json())
.then((result) => {
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
setLoading(false)
})
.catch(() => {
setError('Kunde inte hämta resultaträkning')
setLoading(false)
})
// Monthly breakdown is full-period by design (it IS the per-month view),
// so the date range only affects the headline numbers above the chart.
fetch(`/api/reports/monthly-breakdown?period_id=${periodId}`)
.then((res) => res.json())
.then((result) => {
if (result.data?.months) {
setMonthlyData(result.data.months)
}
setMonthlyLoading(false)
})
.catch(() => {
setMonthlyLoading(false)
})
}, [periodId, reportQs])
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar resultaträkning...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Ingen data för denna period.
</CardContent>
</Card>
)
}
return (
<div className="space-y-4">
<div className="flex justify-end gap-2">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/income-statement/pdf?${reportQs}`, '_blank')}
>
<Download className="h-4 w-4 mr-2" />
{t('download_pdf')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/income-statement/xlsx?${reportQs}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
{!monthlyLoading && monthlyData.length > 0 && (
<IncomeExpenseChart months={monthlyData} />
)}
{/* Revenue */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Rörelseintäkter</CardTitle>
</CardHeader>
<CardContent>
<ReportSectionTable sections={data.revenue_sections} onNavigateToAccount={onNavigateToAccount} />
<div className="flex justify-between font-semibold pt-2 border-t mt-2">
<span>Summa rörelseintäkter</span>
<span>{formatAmount(data.total_revenue)} kr</span>
</div>
</CardContent>
</Card>
{/* Expenses */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Rörelsekostnader</CardTitle>
</CardHeader>
<CardContent>
<ReportSectionTable sections={data.expense_sections} negate onNavigateToAccount={onNavigateToAccount} />
<div className="flex justify-between font-semibold pt-2 border-t mt-2">
<span>Summa rörelsekostnader</span>
<span>-{formatAmount(data.total_expenses)} kr</span>
</div>
</CardContent>
</Card>
{/* Operating result */}
<Card>
<CardContent className="py-4">
<div className="flex justify-between font-bold text-lg">
<span>Rörelseresultat</span>
<span className={data.total_revenue - data.total_expenses >= 0 ? 'text-success' : 'text-destructive'}>
{formatAmount(data.total_revenue - data.total_expenses)} kr
</span>
</div>
</CardContent>
</Card>
{/* Financial items */}
{data.financial_sections.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-lg">Finansiella poster</CardTitle>
</CardHeader>
<CardContent>
<ReportSectionTable sections={data.financial_sections} onNavigateToAccount={onNavigateToAccount} />
<div className="flex justify-between font-semibold pt-2 border-t mt-2">
<span>Summa finansiella poster</span>
<span>{formatAmount(data.total_financial)} kr</span>
</div>
</CardContent>
</Card>
)}
{/* Net result */}
<Card className="border-2">
<CardContent className="py-4">
<div className="flex justify-between font-bold text-xl">
<span>Årets resultat</span>
<span className={data.net_result >= 0 ? 'text-success' : 'text-destructive'}>
{formatAmount(data.net_result)} kr
</span>
</div>
</CardContent>
</Card>
</div>
)
}
function BalanceSheetView({ periodId, dateRange, onNavigateToAccount }: { periodId: string; dateRange: DateRangeValue; onNavigateToAccount: (account: string) => void }) {
const t = useTranslations('reports')
const [data, setData] = useState<BalanceSheetReport | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const reportQs = reportQuery(periodId, dateRange)
useEffect(() => {
setLoading(true)
setError(null)
fetch(`/api/reports/balance-sheet?${reportQs}`)
.then((res) => res.json())
.then((result) => {
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
setLoading(false)
})
.catch(() => {
setError('Kunde inte hämta balansräkning')
setLoading(false)
})
}, [periodId, reportQs])
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar balansräkning...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Ingen data för denna period.
</CardContent>
</Card>
)
}
const isBalanced = Math.abs(data.total_assets - data.total_equity_liabilities) < 0.01
return (
<div className="space-y-4">
<div className="flex justify-end gap-2">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/balance-sheet/pdf?${reportQs}`, '_blank')}
>
<Download className="h-4 w-4 mr-2" />
{t('download_pdf')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/balance-sheet/xlsx?${reportQs}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
{/* Assets */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Tillgångar</CardTitle>
</CardHeader>
<CardContent>
<ReportSectionTable sections={data.asset_sections} onNavigateToAccount={onNavigateToAccount} />
<div className="flex justify-between font-semibold pt-2 border-t mt-2">
<span>Summa tillgångar</span>
<span>{formatAmount(data.total_assets)} kr</span>
</div>
</CardContent>
</Card>
{/* Equity and liabilities */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Eget kapital och skulder</CardTitle>
</CardHeader>
<CardContent>
<ReportSectionTable sections={data.equity_liability_sections} onNavigateToAccount={onNavigateToAccount} />
<div className="flex justify-between font-semibold pt-2 border-t mt-2">
<span>Summa eget kapital och skulder</span>
<span>{formatAmount(data.total_equity_liabilities)} kr</span>
</div>
</CardContent>
</Card>
{/* Balance check */}
<Card className="border-2">
<CardContent className="py-4">
<div className="flex justify-between items-center">
<span className="font-bold text-lg">Balanscheck</span>
{isBalanced ? (
<Badge className="bg-success/10 text-success text-base px-3 py-1">
Balanserar
</Badge>
) : (
<div className="text-right">
<Badge variant="destructive" className="text-base px-3 py-1">
Balanserar ej
</Badge>
<p className="text-sm text-destructive mt-1">
Differens: {formatAmount(Math.abs(data.total_assets - data.total_equity_liabilities))} kr
</p>
</div>
)}
</div>
</CardContent>
</Card>
</div>
)
}
function ResultatrapportView({ periodId, dateRange, onNavigateToAccount }: { periodId: string; dateRange: DateRangeValue; onNavigateToAccount: (account: string) => void }) {
const t = useTranslations('reports')
const [data, setData] = useState<ResultatrapportReport | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const reportQs = reportQuery(periodId, dateRange)
useEffect(() => {
setLoading(true)
setError(null)
fetch(`/api/reports/resultatrapport?${reportQs}`)
.then((res) => res.json())
.then((result) => {
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
setLoading(false)
})
.catch(() => {
setError('Kunde inte hämta resultatrapport')
setLoading(false)
})
}, [periodId, reportQs])
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar resultatrapport...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data || data.groups.length === 0) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Inga bokförda intäkter eller kostnader i denna period.
</CardContent>
</Card>
)
}
const hasPrior = data.prior_period !== null
const colCount = 4
return (
<div className="space-y-4">
<div className="flex items-center justify-end gap-2 flex-wrap">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/resultatrapport/pdf?${reportQs}`, '_blank')}
>
<Download className="h-4 w-4 mr-2" />
{t('download_pdf')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/resultatrapport/xlsx?${reportQs}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
<Card>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-[11px] uppercase tracking-wider text-muted-foreground">
<th className="text-left font-medium px-4 py-2 w-20">Konto</th>
<th className="text-left font-medium px-4 py-2">Kontonamn</th>
<th className="text-right font-medium px-4 py-2 w-32 tabular-nums">Innevarande</th>
<th className="text-right font-medium px-4 py-2 w-32 tabular-nums">Föregående</th>
</tr>
</thead>
<tbody>
{data.groups.map((group) => (
<React.Fragment key={group.class}>
<tr className="bg-muted/30">
<td colSpan={colCount} className="px-4 py-2 text-[12px] font-semibold text-muted-foreground">
{group.class_label}
</td>
</tr>
{group.rows.map((row) => (
<tr
key={row.account_number}
className="border-b last:border-0 cursor-pointer hover:bg-muted/50 transition-colors"
onClick={() => onNavigateToAccount(row.account_number)}
>
<td className="px-4 py-1.5">
<AccountNumber number={row.account_number} name={row.account_name} />
</td>
<td className="px-4 py-1.5">{row.account_name}</td>
<td className="px-4 py-1.5 text-right tabular-nums">{formatAmount(row.current_period)}</td>
<td className="px-4 py-1.5 text-right tabular-nums text-muted-foreground">
{hasPrior ? formatAmount(row.prior_period) : '—'}
</td>
</tr>
))}
<tr className="border-b font-medium">
<td colSpan={2} className="px-4 py-1.5 text-right text-muted-foreground">
Summa
</td>
<td className="px-4 py-1.5 text-right tabular-nums">{formatAmount(group.subtotal_current)}</td>
<td className="px-4 py-1.5 text-right tabular-nums text-muted-foreground">
{hasPrior ? formatAmount(group.subtotal_prior) : '—'}
</td>
</tr>
</React.Fragment>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
<Card className="border-2">
<CardContent className="py-4">
<div className="grid gap-x-6 items-baseline grid-cols-[1fr_auto_auto]">
<span className="font-bold text-lg">Beräknat resultat</span>
<span className={`tabular-nums font-bold text-lg w-32 text-right ${data.net_result_current >= 0 ? 'text-success' : 'text-destructive'}`}>
{formatAmount(data.net_result_current)} kr
</span>
<span className="tabular-nums text-base text-muted-foreground w-32 text-right">
{hasPrior ? `${formatAmount(data.net_result_prior)} kr` : '—'}
</span>
</div>
</CardContent>
</Card>
</div>
)
}
function BalansrapportView({ periodId, dateRange, onNavigateToAccount }: { periodId: string; dateRange: DateRangeValue; onNavigateToAccount: (account: string) => void }) {
const t = useTranslations('reports')
const [data, setData] = useState<BalansrapportReport | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const reportQs = reportQuery(periodId, dateRange)
useEffect(() => {
setLoading(true)
setError(null)
fetch(`/api/reports/balansrapport?${reportQs}`)
.then((res) => res.json())
.then((result) => {
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
setLoading(false)
})
.catch(() => {
setError('Kunde inte hämta balansrapport')
setLoading(false)
})
}, [periodId, reportQs])
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar balansrapport...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data || data.groups.length === 0) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Inga balansposter i denna period.
</CardContent>
</Card>
)
}
return (
<div className="space-y-4">
<div className="flex justify-end gap-2">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/balansrapport/pdf?${reportQs}`, '_blank')}
>
<Download className="h-4 w-4 mr-2" />
{t('download_pdf')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/balansrapport/xlsx?${reportQs}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
<Card>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-[11px] uppercase tracking-wider text-muted-foreground">
<th className="text-left font-medium px-4 py-2 w-20">Konto</th>
<th className="text-left font-medium px-4 py-2">Kontonamn</th>
<th className="text-right font-medium px-4 py-2 w-32 tabular-nums">Ingående balans</th>
<th className="text-right font-medium px-4 py-2 w-32 tabular-nums">Förändring</th>
<th className="text-right font-medium px-4 py-2 w-32 tabular-nums">Utgående balans</th>
</tr>
</thead>
<tbody>
{data.groups.map((group) => (
<React.Fragment key={group.class}>
<tr className="bg-muted/30">
<td colSpan={5} className="px-4 py-2 text-[12px] font-semibold text-muted-foreground">
{group.class_label}
</td>
</tr>
{group.rows.map((row) => (
<tr
key={row.account_number}
className="border-b last:border-0 cursor-pointer hover:bg-muted/50 transition-colors"
onClick={() => onNavigateToAccount(row.account_number)}
>
<td className="px-4 py-1.5">
<AccountNumber number={row.account_number} name={row.account_name} />
</td>
<td className="px-4 py-1.5">{row.account_name}</td>
<td className="px-4 py-1.5 text-right tabular-nums text-muted-foreground">{formatAmount(row.ib)}</td>
<td className="px-4 py-1.5 text-right tabular-nums text-muted-foreground">{formatAmount(row.period_change)}</td>
<td className="px-4 py-1.5 text-right tabular-nums">{formatAmount(row.ub)}</td>
</tr>
))}
<tr className="border-b font-medium">
<td colSpan={2} className="px-4 py-1.5 text-right text-muted-foreground">
Summa
</td>
<td className="px-4 py-1.5 text-right tabular-nums text-muted-foreground">{formatAmount(group.subtotal_ib)}</td>
<td className="px-4 py-1.5 text-right tabular-nums text-muted-foreground">
{formatAmount(group.subtotal_ub - group.subtotal_ib)}
</td>
<td className="px-4 py-1.5 text-right tabular-nums">{formatAmount(group.subtotal_ub)}</td>
</tr>
</React.Fragment>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
<Card className="border-2">
<CardContent className="py-4 space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Summa tillgångar</span>
<span className="tabular-nums">{formatAmount(data.total_assets_ub)} kr</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Summa eget kapital, reserver, avsättningar och skulder</span>
<span className="tabular-nums">{formatAmount(data.total_equity_liabilities_ub)} kr</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Beräknat resultat (ej bokslutsjusterat)</span>
<span className="tabular-nums">{formatAmount(data.beraknat_resultat)} kr</span>
</div>
<div className="flex justify-between items-center pt-2 border-t">
<span className="font-bold text-lg">Balanscheck</span>
{data.is_balanced ? (
<Badge className="bg-success/10 text-success text-base px-3 py-1">
Balanserar
</Badge>
) : (
<Badge variant="destructive" className="text-base px-3 py-1">
Balanserar ej
</Badge>
)}
</div>
</CardContent>
</Card>
</div>
)
}
function ReportSectionTable({
sections,
negate,
onNavigateToAccount,
}: {
sections: { title: string; rows: { account_number: string; account_name: string; amount: number }[]; subtotal: number }[]
negate?: boolean
onNavigateToAccount?: (account: string) => void
}) {
if (sections.length === 0) {
return <p className="text-sm text-muted-foreground">Inga poster.</p>
}
return (
<div className="space-y-3">
{sections.map((section) => (
<div key={section.title}>
<h4 className="text-sm font-semibold text-muted-foreground mb-1">{section.title}</h4>
<div className="overflow-x-auto -mx-2 px-2"><table className="w-full text-sm min-w-[400px]">
<tbody>
{section.rows.map((row) => (
<tr
key={row.account_number}
className={`border-b last:border-0 ${onNavigateToAccount ? 'cursor-pointer hover:bg-muted/50 transition-colors' : ''}`}
onClick={onNavigateToAccount ? () => onNavigateToAccount(row.account_number) : undefined}
>
<td className="py-1 w-16"><AccountNumber number={row.account_number} name={row.account_name} /></td>
<td className="py-1">{row.account_name}</td>
<td className="py-1 text-right w-28">
{negate ? `-${formatAmount(row.amount)}` : formatAmount(row.amount)} kr
</td>
</tr>
))}
</tbody>
</table></div>
<div className="flex justify-between text-sm font-medium border-t pt-1 mt-1">
<span>{section.title}</span>
<span>
{negate ? `-${formatAmount(section.subtotal)}` : formatAmount(section.subtotal)} kr
</span>
</div>
</div>
))}
</div>
)
}
function VatDeclarationView() {
const currentYear = new Date().getFullYear()
const currentMonth = new Date().getMonth() + 1
const currentQuarter = Math.ceil(currentMonth / 3)
const [periodType, setPeriodType] = useState<VatPeriodType>('quarterly')
const [year, setYear] = useState(currentYear)
const [period, setPeriod] = useState(currentQuarter)
const [data, setData] = useState<VatDeclaration | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
// Generate year options (last 5 years)
const yearOptions = Array.from({ length: 5 }, (_, i) => currentYear - i)
// Generate period options based on type
const getPeriodOptions = () => {
switch (periodType) {
case 'monthly':
return [
{ value: 1, label: 'Januari' },
{ value: 2, label: 'Februari' },
{ value: 3, label: 'Mars' },
{ value: 4, label: 'April' },
{ value: 5, label: 'Maj' },
{ value: 6, label: 'Juni' },
{ value: 7, label: 'Juli' },
{ value: 8, label: 'Augusti' },
{ value: 9, label: 'September' },
{ value: 10, label: 'Oktober' },
{ value: 11, label: 'November' },
{ value: 12, label: 'December' },
]
case 'quarterly':
return [
{ value: 1, label: 'Kvartal 1 (jan-mar)' },
{ value: 2, label: 'Kvartal 2 (apr-jun)' },
{ value: 3, label: 'Kvartal 3 (jul-sep)' },
{ value: 4, label: 'Kvartal 4 (okt-dec)' },
]
case 'yearly':
return [{ value: 1, label: 'Helår' }]
default:
return []
}
}
// Reset period when type changes
useEffect(() => {
if (periodType === 'monthly') {
setPeriod(currentMonth)
} else if (periodType === 'quarterly') {
setPeriod(currentQuarter)
} else {
setPeriod(1)
}
}, [periodType, currentMonth, currentQuarter])
const fetchDeclaration = async () => {
setLoading(true)
setError(null)
try {
const res = await fetch(
`/api/reports/vat-declaration?periodType=${periodType}&year=${year}&period=${period}`
)
const result = await res.json()
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
} catch {
setError('Kunde inte hämta momsdeklaration')
} finally {
setLoading(false)
}
}
return (
<div className="space-y-4">
<div className="flex justify-end gap-2">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/vat-declaration/xlsx?periodType=${periodType}&year=${year}&period=${period}`, '_blank')}
>
<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>
<CardHeader>
<CardTitle className="text-lg">Välj period</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap items-end gap-4">
<div>
<Label>Periodicitet</Label>
<select
value={periodType}
onChange={(e) => setPeriodType(e.target.value as VatPeriodType)}
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
>
<option value="monthly">Månadsvis</option>
<option value="quarterly">Kvartalsvis</option>
<option value="yearly">Årsvis</option>
</select>
</div>
<div>
<Label>År</Label>
<select
value={year}
onChange={(e) => setYear(parseInt(e.target.value))}
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
>
{yearOptions.map((y) => (
<option key={y} value={y}>
{y}
</option>
))}
</select>
</div>
<div>
<Label>Period</Label>
<select
value={period}
onChange={(e) => setPeriod(parseInt(e.target.value))}
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
>
{getPeriodOptions().map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
<Button onClick={fetchDeclaration} disabled={loading}>
{loading ? 'Laddar...' : 'Hämta'}
</Button>
</div>
</CardContent>
</Card>
{error && (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)}
{data && (
<>
<VatCompositionChart rutor={data.rutor} />
{/* Summary */}
<Card className="border-2">
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Momsdeklaration - {data.period.start} till {data.period.end}</CardTitle>
<Badge
variant={
data.rutor.ruta49 > 0
? 'warning'
: data.rutor.ruta49 < 0
? 'success'
: 'secondary'
}
>
{data.rutor.ruta49 > 0
? `Att betala: ${formatAmount(data.rutor.ruta49)} kr`
: data.rutor.ruta49 < 0
? `Att återfå: ${formatAmount(Math.abs(data.rutor.ruta49))} kr`
: 'Ingen moms'}
</Badge>
</div>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground mb-4">
Baserat på {data.invoiceCount} fakturor och {data.transactionCount} transaktioner
</div>
<div className="grid md:grid-cols-2 gap-6">
{/* Utgående moms */}
<div>
<h4 className="font-semibold mb-3">Utgående moms (försäljning)</h4>
<div><table className="w-full text-sm">
<tbody>
{data.rutor.ruta05 > 0 && (
<VatRutaRow
ruta="05"
label="Momspliktig försäljning"
amount={data.rutor.ruta05}
baseAmount={0}
periodType={periodType}
year={year}
period={period}
/>
)}
<VatRutaRow
ruta="10"
label="Utgående moms 25%"
amount={data.rutor.ruta10}
baseAmount={data.breakdown.invoices.base25}
periodType={periodType}
year={year}
period={period}
/>
<VatRutaRow
ruta="11"
label="Utgående moms 12%"
amount={data.rutor.ruta11}
baseAmount={data.breakdown.invoices.base12}
periodType={periodType}
year={year}
period={period}
/>
<VatRutaRow
ruta="12"
label="Utgående moms 6%"
amount={data.rutor.ruta12}
baseAmount={data.breakdown.invoices.base6}
periodType={periodType}
year={year}
period={period}
/>
<VatRutaRow
ruta="39"
label="Tjänster EU (omvänd skattskyldighet)"
amount={0}
baseAmount={data.rutor.ruta39}
noVat
periodType={periodType}
year={year}
period={period}
/>
<VatRutaRow
ruta="40"
label="Export utanför EU"
amount={0}
baseAmount={data.rutor.ruta40}
noVat
periodType={periodType}
year={year}
period={period}
/>
</tbody>
<tfoot>
<tr className="border-t-2 font-semibold">
<td className="py-2">Summa utgående</td>
<td className="py-2 text-right">
{formatAmount(
data.rutor.ruta10 + data.rutor.ruta11 + data.rutor.ruta12 +
data.rutor.ruta30 + data.rutor.ruta31 + data.rutor.ruta32
)} kr
</td>
</tr>
</tfoot>
</table></div>
{/* Omvänd skattskyldighet (inköp) */}
{(data.rutor.ruta20 > 0 || data.rutor.ruta21 > 0 || data.rutor.ruta22 > 0 || data.rutor.ruta23 > 0 || data.rutor.ruta24 > 0 ||
data.rutor.ruta30 > 0 || data.rutor.ruta31 > 0 || data.rutor.ruta32 > 0) && (
<>
<h4 className="font-semibold mb-3 mt-6">Omvänd skattskyldighet (inköp)</h4>
<div><table className="w-full text-sm">
<tbody>
<VatRutaRow ruta="20" label="Inköp av varor från annat EU-land" amount={0} baseAmount={data.rutor.ruta20} noVat periodType={periodType} year={year} period={period} />
<VatRutaRow ruta="21" label="Inköp av tjänster från annat EU-land" amount={0} baseAmount={data.rutor.ruta21} noVat periodType={periodType} year={year} period={period} />
<VatRutaRow ruta="22" label="Inköp av tjänster utanför EU" amount={0} baseAmount={data.rutor.ruta22} noVat periodType={periodType} year={year} period={period} />
<VatRutaRow ruta="23" label="Inköp av varor i Sverige" amount={0} baseAmount={data.rutor.ruta23} noVat periodType={periodType} year={year} period={period} />
<VatRutaRow ruta="24" label="Övriga inköp av tjänster i Sverige" amount={0} baseAmount={data.rutor.ruta24} noVat periodType={periodType} year={year} period={period} />
<VatRutaRow ruta="30" label="Utgående moms 25% (omvänd)" amount={data.rutor.ruta30} baseAmount={0} periodType={periodType} year={year} period={period} />
<VatRutaRow ruta="31" label="Utgående moms 12% (omvänd)" amount={data.rutor.ruta31} baseAmount={0} periodType={periodType} year={year} period={period} />
<VatRutaRow ruta="32" label="Utgående moms 6% (omvänd)" amount={data.rutor.ruta32} baseAmount={0} periodType={periodType} year={year} period={period} />
</tbody>
</table></div>
</>
)}
</div>
{/* Ingående moms */}
<div>
<h4 className="font-semibold mb-3">Ingående moms (avdragsgill)</h4>
<div><table className="w-full text-sm">
<tbody>
<VatRutaRow
ruta="48"
label="Ingående moms att dra av"
amount={data.rutor.ruta48}
baseAmount={0}
periodType={periodType}
year={year}
period={period}
/>
{data.breakdown.transactions.ruta48 > 0 && (
<tr className="text-muted-foreground">
<td className="py-1 pl-6 text-xs">- från transaktioner</td>
<td className="py-1 text-right text-xs">
{formatAmount(data.breakdown.transactions.ruta48)} kr
</td>
</tr>
)}
{data.breakdown.receipts.ruta48 > 0 && (
<tr className="text-muted-foreground">
<td className="py-1 pl-6 text-xs">- från kvitton</td>
<td className="py-1 text-right text-xs">
{formatAmount(data.breakdown.receipts.ruta48)} kr
</td>
</tr>
)}
</tbody>
<tfoot>
<tr className="border-t-2 font-semibold">
<td className="py-2">Summa ingående</td>
<td className="py-2 text-right">{formatAmount(data.rutor.ruta48)} kr</td>
</tr>
</tfoot>
</table></div>
</div>
</div>
{/* Net result */}
<div className="mt-6 pt-4 border-t-2">
<div className="flex justify-between items-center">
<div>
<span className="font-mono text-xs bg-muted px-1 rounded mr-2">49</span>
<span className="font-bold text-lg">
{data.rutor.ruta49 >= 0 ? 'Moms att betala' : 'Moms att återfå'}
</span>
</div>
<span
className={`text-xl font-bold ${
data.rutor.ruta49 > 0
? 'text-orange-600'
: data.rutor.ruta49 < 0
? 'text-success'
: ''
}`}
>
{formatAmount(Math.abs(data.rutor.ruta49))} kr
</span>
</div>
</div>
</CardContent>
</Card>
</>
)}
{/* Skatteverket integration panel */}
<SkatteverketPanel
periodType={periodType}
year={year}
period={period}
hasData={data !== null}
rutor={data?.rutor ?? null}
/>
{!data && !loading && !error && (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Välj period och klicka &quot;Hämta&quot; för att se momsdeklaration.
</CardContent>
</Card>
)}
</div>
)
}
function makeVatFetcher(ruta: string, periodType: VatPeriodType, year: number, period: number): ReportSourceFetcher {
return async () => {
const res = await fetch(
`/api/reports/vat-declaration/ruta/${encodeURIComponent(ruta)}/sources?periodType=${periodType}&year=${year}&period=${period}`
)
const json = await res.json()
if (!res.ok) throw new Error(json.error || 'Kunde inte hämta verifikat')
const lines: ReportSourceLine[] = json.data?.lines || []
return { lines, next_cursor: json.data?.next_cursor ?? null }
}
}
function VatRutaRow({
ruta,
label,
amount,
baseAmount,
noVat,
periodType,
year,
period,
}: {
ruta: string
label: string
amount: number
baseAmount: number
noVat?: boolean
periodType?: VatPeriodType
year?: number
period?: number
}) {
const canDrill = periodType !== undefined && year !== undefined && period !== undefined
const fetcher = React.useMemo(
() => (canDrill ? makeVatFetcher(ruta, periodType!, year!, period!) : null),
[canDrill, ruta, periodType, year, period]
)
// Hooks must be called unconditionally — provide a noop fetcher when drill
// is disabled. The early-return for zero rows lives below the hooks.
const expansion = useReportRowExpansion(
fetcher ?? (async () => ({ lines: [], next_cursor: null })),
`vat-${ruta}`
)
// Don't show rows with zero values
if (baseAmount === 0 && amount === 0) return null
return (
<>
<tr className="border-b">
<td className="py-2">
{canDrill && (
<span className="inline-block align-middle mr-1">
<expansion.Toggle />
</span>
)}
<span className="font-mono text-xs bg-muted px-1 rounded mr-2">{ruta}</span>
{label}
</td>
<td className="py-2 text-right tabular-nums">{noVat ? `${formatAmount(baseAmount)} kr` : `${formatAmount(amount)} kr`}</td>
</tr>
{!noVat && baseAmount > 0 && (
<tr className="text-muted-foreground">
<td className="py-1 pl-6 text-xs">Underlag</td>
<td className="py-1 text-right text-xs tabular-nums">{formatAmount(baseAmount)} kr</td>
</tr>
)}
{canDrill && <expansion.Panel colSpan={2} />}
</>
)
}
interface SupplierLedgerData {
ledger: {
entries: {
supplier_id: string
supplier_name: string
current: number
days_1_30: number
days_31_60: number
days_61_90: number
days_90_plus: number
total_outstanding: number
}[]
total_outstanding: number
total_current: number
total_overdue: number
unpaid_count: number
unconverted_fx_count: number
}
reconciliation: {
supplier_ledger_total: number
account_2440_balance: number
difference: number
is_reconciled: boolean
unconverted_fx_count: number
} | null
}
function SupplierLedgerView({ periodId }: { periodId: string }) {
const [data, setData] = useState<SupplierLedgerData | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const fetchData = async () => {
setLoading(true)
setError(null)
try {
const res = await fetch(`/api/reports/supplier-ledger?period_id=${periodId}`)
const result = await res.json()
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
} catch {
setError('Kunde inte hämta leverantörsreskontra')
} finally {
setLoading(false)
}
}
useEffect(() => {
if (periodId) fetchData()
}, [periodId])
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar leverantörsreskontra...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data || !data.ledger) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Ingen data tillgänglig.
</CardContent>
</Card>
)
}
const { ledger, reconciliation } = data
return (
<div className="space-y-4">
<div className="flex justify-end">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/supplier-ledger/xlsx?period_id=${periodId}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
{/* Summary cards */}
<div className="grid md:grid-cols-3 gap-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm text-muted-foreground">Totalt utestående</CardTitle>
</CardHeader>
<CardContent>
<p className="font-display text-2xl font-medium tabular-nums">{formatAmount(ledger.total_outstanding)} kr</p>
<p className="text-xs text-muted-foreground">{ledger.unpaid_count} fakturor</p>
{ledger.unconverted_fx_count > 0 && (
<p className="mt-1 text-xs text-muted-foreground">
{ledger.unconverted_fx_count} faktura i utländsk valuta utan växelkurs är inte med i totalen.
</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm text-muted-foreground">Ej förfallet</CardTitle>
</CardHeader>
<CardContent>
<p className="font-display text-2xl font-medium tabular-nums text-success">{formatAmount(ledger.total_current)} kr</p>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm text-muted-foreground">Förfallet</CardTitle>
</CardHeader>
<CardContent>
<p className="font-display text-2xl font-medium tabular-nums text-destructive">{formatAmount(ledger.total_overdue)} kr</p>
</CardContent>
</Card>
</div>
{/* Aging table */}
{ledger.entries.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Ålderfördelning per leverantör</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto -mx-2 px-2"><table className="w-full text-sm min-w-[500px]">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="border-b text-left">
<th className="py-2 w-8"></th>
<th className="py-2">Leverantör</th>
<th className="py-2 text-right">Ej förfallet</th>
<th className="py-2 text-right">1-30 dagar</th>
<th className="py-2 text-right">31-60 dagar</th>
<th className="py-2 text-right">61-90 dagar</th>
<th className="py-2 text-right">90+ dagar</th>
<th className="py-2 text-right font-semibold">Totalt</th>
</tr>
</thead>
<tbody>
{ledger.entries.map((entry) => (
<SupplierLedgerRow key={entry.supplier_id} entry={entry} />
))}
</tbody>
<tfoot>
<tr className="font-semibold border-t-2">
<td className="py-2"></td>
<td className="py-2">Summa</td>
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.current, 0))}</td>
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_1_30, 0))}</td>
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_31_60, 0))}</td>
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_61_90, 0))}</td>
<td className="py-2 text-right text-destructive">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_90_plus, 0))}</td>
<td className="py-2 text-right">{formatAmount(ledger.total_outstanding)}</td>
</tr>
</tfoot>
</table></div>
</CardContent>
</Card>
)}
{/* Reconciliation */}
{reconciliation && (
<Card className="border-2">
<CardHeader>
<CardTitle>Avstämning mot <AccountNumber number="2440" /></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span>Leverantörsreskontra (summa utestående)</span>
<span className="font-mono">{formatAmount(reconciliation.supplier_ledger_total)} kr</span>
</div>
<div className="flex justify-between">
<span><AccountNumber number="2440" /> saldo (huvudbok)</span>
<span className="font-mono">{formatAmount(reconciliation.account_2440_balance)} kr</span>
</div>
<div className="flex justify-between pt-2 border-t font-semibold">
<span>Differens</span>
<span className={reconciliation.is_reconciled ? 'text-success' : 'text-destructive'}>
{formatAmount(reconciliation.difference)} kr
</span>
</div>
<div className="pt-2 space-y-2">
{reconciliation.is_reconciled ? (
<Badge className="bg-success/10 text-success">Avstämd</Badge>
) : (
<Badge variant="destructive">Ej avstämd - kontrollera bokföring</Badge>
)}
{reconciliation.unconverted_fx_count > 0 && (
<p className="text-xs text-muted-foreground">
{reconciliation.unconverted_fx_count} leverantörsfaktura i utländsk valuta saknar växelkurs — differensen kan bero på saknade kursuppgifter snarare än felbokning.
</p>
)}
</div>
</div>
</CardContent>
</Card>
)}
</div>
)
}
function makeSupplierFetcher(supplierId: string): ReportSourceFetcher {
return async () => {
const res = await fetch(
`/api/reports/supplier-ledger/supplier/${encodeURIComponent(supplierId)}/invoices`
)
const json = await res.json()
if (!res.ok) throw new Error(json.error || 'Kunde inte hämta leverantörsfakturor')
const lines: ReportSourceLine[] = json.data?.lines || []
return { lines, next_cursor: json.data?.next_cursor ?? null }
}
}
function SupplierLedgerRow({
entry,
}: {
entry: {
supplier_id: string
supplier_name: string
current: number
days_1_30: number
days_31_60: number
days_61_90: number
days_90_plus: number
total_outstanding: number
}
}) {
const fetcher = React.useMemo(
() => makeSupplierFetcher(entry.supplier_id),
[entry.supplier_id]
)
const { Toggle, Panel } = useReportRowExpansion(fetcher, `sup-${entry.supplier_id}`)
return (
<>
<tr className="border-b last:border-0 hover:bg-muted/30 transition-colors">
<td className="py-2"><Toggle /></td>
<td className="py-2">{entry.supplier_name}</td>
<td className="py-2 text-right tabular-nums">{entry.current > 0 ? formatAmount(entry.current) : ''}</td>
<td className="py-2 text-right tabular-nums">{entry.days_1_30 > 0 ? formatAmount(entry.days_1_30) : ''}</td>
<td className="py-2 text-right tabular-nums">{entry.days_31_60 > 0 ? formatAmount(entry.days_31_60) : ''}</td>
<td className="py-2 text-right tabular-nums">{entry.days_61_90 > 0 ? formatAmount(entry.days_61_90) : ''}</td>
<td className="py-2 text-right tabular-nums text-destructive">{entry.days_90_plus > 0 ? formatAmount(entry.days_90_plus) : ''}</td>
<td className="py-2 text-right tabular-nums font-semibold">{formatAmount(entry.total_outstanding)}</td>
</tr>
<Panel colSpan={8} />
</>
)
}
// --- General Ledger (Huvudbok) ---
interface GeneralLedgerData {
accounts: {
account_number: string
account_name: string
opening_balance: number
lines: {
date: string
voucher_series: string
voucher_number: number
journal_entry_id: string
description: string
source_type: string
debit: number
credit: number
balance: number
}[]
closing_balance: number
total_debit: number
total_credit: number
}[]
period: { start: string; end: string }
}
function GeneralLedgerView({ periodId, initialAccountFilter }: { periodId: string; initialAccountFilter: string | null }) {
const [data, setData] = useState<GeneralLedgerData | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [accountFrom, setAccountFrom] = useState('')
const [accountTo, setAccountTo] = useState('')
const fetchData = useCallback(async (fromOverride?: string, toOverride?: string) => {
const from = fromOverride ?? accountFrom
const to = toOverride ?? accountTo
setLoading(true)
setError(null)
try {
const params = new URLSearchParams({ period_id: periodId })
if (from) params.set('account_from', from)
if (to) params.set('account_to', to)
const res = await fetch(`/api/reports/general-ledger?${params}`)
const result = await res.json()
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
} catch {
setError('Kunde inte hämta huvudbok')
} finally {
setLoading(false)
}
}, [periodId, accountFrom, accountTo])
// When initialAccountFilter changes (drill-down from another report), apply it
useEffect(() => {
if (initialAccountFilter) {
setAccountFrom(initialAccountFilter)
setAccountTo(initialAccountFilter)
fetchData(initialAccountFilter, initialAccountFilter)
} else {
fetchData()
}
}, [periodId, initialAccountFilter])
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar huvudbok...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data || data.accounts.length === 0) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Inga bokförda verifikationer i denna period.
</CardContent>
</Card>
)
}
return (
<div className="space-y-4">
<div className="flex justify-end">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/general-ledger/xlsx?period_id=${periodId}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
{/* Account range filter */}
<Card>
<CardContent className="pt-6">
<div className="flex flex-wrap items-end gap-4">
<div>
<Label>Konto från</Label>
<input
type="text"
value={accountFrom}
onChange={(e) => setAccountFrom(e.target.value)}
placeholder="t.ex. 1510"
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
/>
</div>
<div>
<Label>Konto till</Label>
<input
type="text"
value={accountTo}
onChange={(e) => setAccountTo(e.target.value)}
placeholder="t.ex. 1519"
className="w-full mt-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
/>
</div>
<Button onClick={() => fetchData()} variant="outline">
Filtrera
</Button>
</div>
</CardContent>
</Card>
{data.period.start && (
<p className="text-sm text-muted-foreground">
Period: {data.period.start} — {data.period.end} | {data.accounts.length} konton
</p>
)}
{data.accounts.map((account) => (
<Card key={account.account_number}>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-base">
<AccountNumber number={account.account_number} name={account.account_name} showName />
</CardTitle>
<span className="text-sm text-muted-foreground">
IB: {formatAmount(account.opening_balance)} kr
</span>
</div>
</CardHeader>
<CardContent>
<div className="overflow-x-auto -mx-2 px-2"><table className="w-full text-sm min-w-[500px]">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="border-b text-left">
<th className="py-2 w-16">Ver.nr</th>
<th className="py-2 w-24">Datum</th>
<th className="py-2">Beskrivning</th>
<th className="py-2 w-24 text-right">Debet</th>
<th className="py-2 w-24 text-right">Kredit</th>
<th className="py-2 w-28 text-right">Saldo</th>
</tr>
</thead>
<tbody>
{account.lines.map((line, i) => (
<tr key={i} className="border-b last:border-0">
<td className="py-1.5 font-mono text-xs">
<Link
href={`/bookkeeping/${line.journal_entry_id}`}
className="text-foreground underline underline-offset-4 decoration-muted-foreground/40 hover:decoration-foreground transition-colors"
>
{formatVoucher(line)}
</Link>
</td>
<td className="py-1.5">{line.date}</td>
<td className="py-1.5 truncate max-w-[200px]">{line.description}</td>
<td className="py-1.5 text-right">
{line.debit > 0 ? formatAmount(line.debit) : ''}
</td>
<td className="py-1.5 text-right">
{line.credit > 0 ? formatAmount(line.credit) : ''}
</td>
<td className="py-1.5 text-right font-mono">{formatAmount(line.balance)}</td>
</tr>
))}
</tbody>
<tfoot>
<tr className="font-semibold border-t-2">
<td colSpan={3} className="py-2">Summa / Utgående balans</td>
<td className="py-2 text-right">{formatAmount(account.total_debit)}</td>
<td className="py-2 text-right">{formatAmount(account.total_credit)}</td>
<td className="py-2 text-right font-mono">{formatAmount(account.closing_balance)}</td>
</tr>
</tfoot>
</table></div>
</CardContent>
</Card>
))}
</div>
)
}
// --- Journal Register (Grundbok) ---
interface JournalRegisterData {
entries: {
voucher_series: string
voucher_number: number
date: string
description: string
source_type: string
status: string
lines: {
account_number: string
account_name: string
debit: number
credit: number
}[]
total_debit: number
total_credit: number
}[]
total_entries: number
total_debit: number
total_credit: number
period: { start: string; end: string }
}
function JournalRegisterView({ periodId }: { periodId: string }) {
const [data, setData] = useState<JournalRegisterData | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [expandedEntries, setExpandedEntries] = useState<Set<number>>(new Set())
const fetchData = async () => {
setLoading(true)
setError(null)
setExpandedEntries(new Set())
try {
const res = await fetch(`/api/reports/journal-register?period_id=${periodId}`)
const result = await res.json()
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
} catch {
setError('Kunde inte hämta grundbok')
} finally {
setLoading(false)
}
}
useEffect(() => {
if (periodId) fetchData()
}, [periodId])
const toggleEntry = (index: number) => {
setExpandedEntries((prev) => {
const next = new Set(prev)
if (next.has(index)) {
next.delete(index)
} else {
next.add(index)
}
return next
})
}
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar grundbok...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data || data.entries.length === 0) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Inga bokförda verifikationer i denna period.
</CardContent>
</Card>
)
}
return (
<div className="space-y-4">
<div className="flex justify-end">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/journal-register/xlsx?period_id=${periodId}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
{data.period.start && (
<p className="text-sm text-muted-foreground">
Period: {data.period.start} — {data.period.end} | {data.total_entries} verifikationer
</p>
)}
<Card>
<CardHeader>
<CardTitle>Grundbok (registreringsordning)</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto -mx-2 px-2"><table className="w-full text-sm min-w-[500px]">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="border-b text-left">
<th className="py-2 w-8"></th>
<th className="py-2 w-16">Ver.nr</th>
<th className="py-2 w-24">Datum</th>
<th className="py-2">Beskrivning</th>
<th className="py-2 w-24">Typ</th>
<th className="py-2 w-24 text-right">Debet</th>
<th className="py-2 w-24 text-right">Kredit</th>
</tr>
</thead>
<tbody>
{data.entries.map((entry, index) => {
const isExpanded = expandedEntries.has(index)
const isReversed = entry.status === 'reversed'
return (
<React.Fragment key={index}>
<tr
className={`border-b cursor-pointer hover:bg-muted/50 ${isReversed ? 'line-through opacity-60' : ''}`}
onClick={() => toggleEntry(index)}
>
<td className="py-2">
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</td>
<td className="py-2 font-mono text-xs">
{formatVoucher(entry)}
</td>
<td className="py-2">{entry.date}</td>
<td className="py-2">
{entry.description}
{isReversed && (
<Badge variant="outline" className="ml-2 text-xs">Makulerad</Badge>
)}
</td>
<td className="py-2 text-xs text-muted-foreground">{entry.source_type}</td>
<td className="py-2 text-right">{formatAmount(entry.total_debit)}</td>
<td className="py-2 text-right">{formatAmount(entry.total_credit)}</td>
</tr>
{isExpanded && entry.lines.map((line, lineIndex) => (
<tr key={`${index}-${lineIndex}`} className="bg-muted/30 border-b last:border-0">
<td></td>
<td></td>
<td className="py-1"><AccountNumber number={line.account_number} name={line.account_name} size="sm" /></td>
<td className="py-1 text-muted-foreground">{line.account_name}</td>
<td></td>
<td className="py-1 text-right">
{line.debit > 0 ? formatAmount(line.debit) : ''}
</td>
<td className="py-1 text-right">
{line.credit > 0 ? formatAmount(line.credit) : ''}
</td>
</tr>
))}
</React.Fragment>
)
})}
</tbody>
<tfoot>
<tr className="font-semibold border-t-2">
<td colSpan={5} className="py-2">Summa</td>
<td className="py-2 text-right">{formatAmount(data.total_debit)}</td>
<td className="py-2 text-right">{formatAmount(data.total_credit)}</td>
</tr>
</tfoot>
</table></div>
</CardContent>
</Card>
</div>
)
}
// --- AR Ledger (Kundreskontra) ---
interface ARLedgerData {
ledger: {
entries: {
customer_id: string
customer_name: string
invoices: {
invoice_id: string
invoice_number: string
invoice_date: string
due_date: string
total: number
paid_amount: number
outstanding: number
outstanding_sek: number | null
days_overdue: number
currency: string
}[]
current: number
days_1_30: number
days_31_60: number
days_61_90: number
days_90_plus: number
total_outstanding: number
}[]
total_outstanding: number
total_current: number
total_overdue: number
unpaid_count: number
unconverted_fx_count: number
}
reconciliation: {
ar_ledger_total: number
account_1510_balance: number
difference: number
is_reconciled: boolean
unconverted_fx_count: number
} | null
}
// Inner expansion row component for AR ledger.
// Fetches per-customer invoices (with journal_entry_id) and renders each as a
// link to /bookkeeping/[id] when posted, /invoices/[id] when still draft.
function ARCustomerInvoiceRows({
customerId,
invoices,
}: {
customerId: string
invoices: {
invoice_id: string
invoice_number: string
invoice_date: string
due_date: string
total: number
paid_amount: number
outstanding: number
outstanding_sek: number | null
days_overdue: number
currency: string
}[]
}) {
// ARCustomerInvoiceRows is mounted lazily — only when a customer is
// expanded, so initial state matches "still loading" and resets on
// unmount. No synchronous setState in the effect is needed.
const [enriched, setEnriched] = useState<Record<string, { journal_entry_id: string; voucher_series: string; voucher_number: number } | undefined>>({})
const [loaded, setLoaded] = useState(false)
useEffect(() => {
let cancelled = false
fetch(`/api/reports/ar-ledger/customer/${encodeURIComponent(customerId)}/invoices`)
.then((r) => r.json())
.then((json) => {
if (cancelled) return
const map: typeof enriched = {}
for (const line of json.data?.lines || []) {
if (line.invoice_id && line.journal_entry_id) {
map[line.invoice_id] = {
journal_entry_id: line.journal_entry_id,
voucher_series: line.voucher_series,
voucher_number: line.voucher_number,
}
}
}
setEnriched(map)
})
.catch(() => { /* fail silently; rows still render without verifikat link */ })
.finally(() => { if (!cancelled) setLoaded(true) })
return () => { cancelled = true }
}, [customerId])
const loading = !loaded
return (
<>
{invoices.map((inv) => {
const entry = enriched[inv.invoice_id]
const targetHref = entry?.journal_entry_id
? `/bookkeeping/${entry.journal_entry_id}`
: `/invoices/${inv.invoice_id}`
return (
<tr key={inv.invoice_id} className="bg-muted/30 border-b last:border-0">
<td></td>
<td className="py-1 text-xs" colSpan={2}>
<Link href={targetHref} className="font-mono hover:underline underline-offset-4">
{inv.invoice_number || '(utkast)'}
</Link>
{entry && (
<span className="ml-2 text-muted-foreground font-mono">
{formatVoucher(entry)}
</span>
)}
<span className="text-muted-foreground ml-2 tabular-nums">{formatDate(inv.invoice_date)}</span>
<span className="text-muted-foreground ml-2 tabular-nums">förfaller {formatDate(inv.due_date)}</span>
</td>
<td className="py-1 text-right text-xs text-muted-foreground" colSpan={2}>
{inv.days_overdue > 0 ? `${inv.days_overdue} dagar förfallen` : 'Ej förfallen'}
</td>
<td className="py-1 text-right text-xs text-muted-foreground">
{inv.paid_amount > 0 ? `Betalt: ${formatAmount(inv.paid_amount)}` : ''}
</td>
<td></td>
<td className="py-1 text-right text-xs font-medium tabular-nums">
{formatAmount(inv.outstanding)} {inv.currency}
</td>
</tr>
)
})}
{loading && (
<tr className="bg-muted/30">
<td></td>
<td colSpan={7} className="py-1 text-[10px] text-muted-foreground">Letar verifikat…</td>
</tr>
)}
</>
)
}
function ARLedgerView({ periodId }: { periodId: string }) {
const [data, setData] = useState<ARLedgerData | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [expandedCustomers, setExpandedCustomers] = useState<Set<string>>(new Set())
const fetchData = async () => {
setLoading(true)
setError(null)
try {
const res = await fetch(`/api/reports/ar-ledger?period_id=${periodId}`)
const result = await res.json()
if (result.error) {
setError(result.error)
} else {
setData(result.data)
}
} catch {
setError('Kunde inte hämta kundreskontra')
} finally {
setLoading(false)
}
}
useEffect(() => {
if (periodId) fetchData()
}, [periodId])
const toggleCustomer = (customerId: string) => {
setExpandedCustomers((prev) => {
const next = new Set(prev)
if (next.has(customerId)) {
next.delete(customerId)
} else {
next.add(customerId)
}
return next
})
}
if (loading) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Laddar kundreskontra...
</CardContent>
</Card>
)
}
if (error) {
return (
<Card>
<CardContent className="p-8 text-center text-destructive">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
{error}
</CardContent>
</Card>
)
}
if (!data || !data.ledger) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
Ingen data tillgänglig.
</CardContent>
</Card>
)
}
const { ledger, reconciliation } = data
return (
<div className="space-y-4">
<div className="flex justify-end">
<Button
variant="outline"
size="sm"
onClick={() => window.open(`/api/reports/ar-ledger/xlsx?period_id=${periodId}`, '_blank')}
>
<FileSpreadsheet className="h-4 w-4 mr-2" />
Ladda ner Excel
</Button>
</div>
{/* Summary cards */}
<div className="grid md:grid-cols-3 gap-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm text-muted-foreground">Totalt utestående</CardTitle>
</CardHeader>
<CardContent>
<p className="font-display text-2xl font-medium tabular-nums">{formatAmount(ledger.total_outstanding)} kr</p>
<p className="text-xs text-muted-foreground">{ledger.unpaid_count} fakturor</p>
{ledger.unconverted_fx_count > 0 && (
<p className="mt-1 text-xs text-muted-foreground">
{ledger.unconverted_fx_count} faktura i utländsk valuta utan växelkurs är inte med i totalen.
</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm text-muted-foreground">Ej förfallet</CardTitle>
</CardHeader>
<CardContent>
<p className="font-display text-2xl font-medium tabular-nums text-success">{formatAmount(ledger.total_current)} kr</p>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm text-muted-foreground">Förfallet</CardTitle>
</CardHeader>
<CardContent>
<p className="font-display text-2xl font-medium tabular-nums text-destructive">{formatAmount(ledger.total_overdue)} kr</p>
</CardContent>
</Card>
</div>
{/* Aging table with expandable invoice details */}
{ledger.entries.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Ålderfördelning per kund</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto -mx-2 px-2"><table className="w-full text-sm min-w-[500px]">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="border-b text-left">
<th className="py-2 w-8"></th>
<th className="py-2">Kund</th>
<th className="py-2 text-right">Ej förfallet</th>
<th className="py-2 text-right">1-30 dagar</th>
<th className="py-2 text-right">31-60 dagar</th>
<th className="py-2 text-right">61-90 dagar</th>
<th className="py-2 text-right">90+ dagar</th>
<th className="py-2 text-right font-semibold">Totalt</th>
</tr>
</thead>
<tbody>
{ledger.entries.map((entry) => {
const isExpanded = expandedCustomers.has(entry.customer_id)
return (
<React.Fragment key={entry.customer_id}>
<tr
className="border-b cursor-pointer hover:bg-muted/50"
onClick={() => toggleCustomer(entry.customer_id)}
>
<td className="py-2">
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</td>
<td className="py-2">{entry.customer_name}</td>
<td className="py-2 text-right">{entry.current > 0 ? formatAmount(entry.current) : ''}</td>
<td className="py-2 text-right">{entry.days_1_30 > 0 ? formatAmount(entry.days_1_30) : ''}</td>
<td className="py-2 text-right">{entry.days_31_60 > 0 ? formatAmount(entry.days_31_60) : ''}</td>
<td className="py-2 text-right">{entry.days_61_90 > 0 ? formatAmount(entry.days_61_90) : ''}</td>
<td className="py-2 text-right text-destructive">{entry.days_90_plus > 0 ? formatAmount(entry.days_90_plus) : ''}</td>
<td className="py-2 text-right font-semibold">{formatAmount(entry.total_outstanding)}</td>
</tr>
{isExpanded && (
<ARCustomerInvoiceRows
customerId={entry.customer_id}
invoices={entry.invoices}
/>
)}
</React.Fragment>
)
})}
</tbody>
<tfoot>
<tr className="font-semibold border-t-2">
<td className="py-2"></td>
<td className="py-2">Summa</td>
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.current, 0))}</td>
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_1_30, 0))}</td>
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_31_60, 0))}</td>
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_61_90, 0))}</td>
<td className="py-2 text-right text-destructive">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_90_plus, 0))}</td>
<td className="py-2 text-right">{formatAmount(ledger.total_outstanding)}</td>
</tr>
</tfoot>
</table></div>
</CardContent>
</Card>
)}
{/* Reconciliation */}
{reconciliation && (
<Card className="border-2">
<CardHeader>
<CardTitle>Avstämning mot <AccountNumber number="1510" /></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span>Kundreskontra (summa utestående)</span>
<span className="font-mono">{formatAmount(reconciliation.ar_ledger_total)} kr</span>
</div>
<div className="flex justify-between">
<span>Kundfordringar (<AccountNumber number="1510" /> + <AccountNumber number="1513" />) saldo</span>
<span className="font-mono">{formatAmount(reconciliation.account_1510_balance)} kr</span>
</div>
<div className="flex justify-between pt-2 border-t font-semibold">
<span>Differens</span>
<span className={reconciliation.is_reconciled ? 'text-success' : 'text-destructive'}>
{formatAmount(reconciliation.difference)} kr
</span>
</div>
<div className="pt-2 space-y-2">
{reconciliation.is_reconciled ? (
<Badge className="bg-success/10 text-success">Avstämd</Badge>
) : (
<Badge variant="destructive">Ej avstämd - kontrollera bokföring</Badge>
)}
{reconciliation.unconverted_fx_count > 0 && (
<p className="text-xs text-muted-foreground">
{reconciliation.unconverted_fx_count} kundfaktura i utländsk valuta saknar växelkurs — differensen kan bero på saknade kursuppgifter snarare än felbokning.
</p>
)}
</div>
</div>
</CardContent>
</Card>
)}
</div>
)
}