Add/stripe connect transactions (#1139)

* fix(mcp-oauth): allow ChatGPT connector callbacks and resume OAuth after login

Add chatgpt.com/connector/oauth/* (per-instance) and the legacy
chatgpt.com/connector_platform_oauth_redirect to the built-in OAuth
redirect allowlist so ChatGPT MCP connectors can register and authorize.

Fix the login page dropping the ?next= destination: an OAuth-initiated
visit that required login previously ended on the dashboard and the
connection flow silently died. Login now resumes to the sanitized next
path (hard navigation, since the consent page is route-handler HTML),
carries it through the MFA step-up as returnTo, and /mfa/verify
hard-navigates for /api/ destinations.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(transactions): dedup incoming feed rows against booked hand-entered twins

Users who bookkeep via MCP/chat first and connect their bank afterwards got
the same movement twice: the synced row's external_id lives in a different
namespace, the free-form manual title never text-bridges the bank's raw
string, and the cross-channel mirror deliberately excluded manual/mcp rows.

Extend the mirror with a booked-hand-entered track: an incoming feed row is
skipped when a BOOKED manual/mcp row shares its (date, ore) bucket count-
symmetrically. Gates beyond the feed-vs-feed mirror: stored row must be
booked (staged rows never consume an import), currencies must not contradict
(bucket key is date+ore only), the cash-account guard applies to the count
exactly as to consumption, and symmetry uses the Layer-1-unmatched incoming
count so an already-stored row cannot inflate it. Consumption stamps the
batch cash_account_id onto an account-unbound hand row, so one hand row can
never consume feed rows on other accounts in later syncs.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(bookkeeping): inline verifikat rattelse (strike lines + text/date edit)

Second sanctioned correction track under BFL 5 kap 5/9 pp, Fortnox-style:
strike lines inside a posted verifikat with replacements in the same
voucher, and correct description/entry_date without an andringsverifikat.
Envelope: posted entries, open unlocked periods, company lock date,
same-period date moves, structural/FX/doc-linked lines excluded, and a
reconciliation guard preserving per-account net on bank/reskontra sides of
externally linked entries. Every rattelse writes an immutable who/when row
(journal_entry_rattelse_log, WORM, archived as rakenskapsinformation) and
struck originals render struck-through in the verifikat; list rows and the
detail header carry a Rattad marker. CLAUDE.md hard rule 1 and the
swedish-accounting-compliance skill are amended to state the two-track
rule. Staging carries the DDL; prod gets it on merge.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat: live saldo in booking form, prior-year window comparison, hideable assistant FAB

- Manual journal entry: saldo column now shows before -> after computed
  from the typed debit/credit amounts (direction feedback while booking)
- Resultatrapport: a narrowed date range now compares against the same
  window shifted one year back (#862), merged across fiscal periods for
  brutet rakenskapsar; P&L rows report window activity instead of
  rolled-forward YTD closing
- Assistant FAB: per-user hide toggle (user_preferences.hide_assistant_fab,
  settings > assistant), sidebar entry unaffected; collapsed sessions keep
  their reopen handle

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(stripe): sync balance transactions as a bank feed on 1686

Import the connected Stripe balance into the transactions inbox, opt-in
per connection (transaction_sync_enabled on stripe_connections):

- Balance transactions map to feed rows with the two-row gross+fee split
  and frozen external_id formats (stripe_{acct}_{txn} / _fee), dated on
  created, bound to a provisioned "Stripe-saldo" cash account on 1686 so
  booking settles against the clearing account by construction.
- Double-booking protection: settled payment-link charges import
  pre-linked to their settlement entry; payout rows import pre-linked to
  the payout entry; processPayoutPaidEvent claims the payout's fee rows
  at booking time (linkPayoutFeedRows, idempotent from both directions).
- Cursor last_balance_txn_synced_at with 24h overlap; first run
  backfills 90 days floored at the day after the company lock date.
- Nightly cron /api/extensions/stripe/transactions/cron (03:30),
  transaction-sync toggle route, "Synka nu" covers both feeds, settings
  panel toggle with last-synced/backfill note, sv+en strings.
- Migration 20260723200000 (applied to staging).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(transactions): offer match-to-voucher on unbooked history rows

Unbooked transactions with is_business already set (e.g. left behind when
a voucher was removed without a full uncategorize) land in the history
list instead of the inbox, where the match-against-existing-voucher
action did not exist, leaving them with no path back to voucher
matching. Add the same menu item to the history list for unbooked rows.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(transactions): enhance ownership checks and error handling in journal entry routes

---------

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Mattsson
2026-07-24 01:16:20 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent be9d630347
commit d840257c0c
55 changed files with 23207 additions and 125 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ Accounted exposes its bookkeeping engine as an MCP server for Claude Desktop/Cod
**MCP extension** (`extensions/general/mcp-server/`): 90+ tools covering transactions, categorization, customers/suppliers, invoices, accounts, fiscal periods, reports (trial balance, GL, BS, IS, AR/supplier ledger, VAT, KPI), reconciliation, salary runs, AGI, year-end, document upload, and loadable skills. JSON-RPC 2.0. Endpoint: `/api/extensions/ext/mcp-server/mcp`.
**OAuth 2.1** for Claude connectors: `.well-known/oauth-protected-resource` + `.well-known/oauth-authorization-server` discovery; `/api/mcp-oauth/authorize`, `/token` (PKCE), `/register`. Stateless AES-256-GCM auth codes (`lib/auth/oauth-codes.ts`). Single-use via `oauth_used_codes`. Allowlist: `claude.ai/api/*`, `claude.com/api/*`, `localhost`.
**OAuth 2.1** for Claude and ChatGPT connectors: `.well-known/oauth-protected-resource` + `.well-known/oauth-authorization-server` discovery; `/api/mcp-oauth/authorize`, `/token` (PKCE), `/register`. Stateless AES-256-GCM auth codes (`lib/auth/oauth-codes.ts`). Single-use via `oauth_used_codes`. Allowlist: `claude.ai/api/*`, `claude.com/api/*`, `chatgpt.com/connector/oauth/*`, `chatgpt.com/connector_platform_oauth_redirect`, `localhost`.
**npm package** (`packages/gnubok-mcp`): Stdio-to-HTTP bridge; users run `npx gnubok-mcp` with API key.
@@ -47,7 +47,11 @@ A verifikation must contain:
Verifikationer must be numbered in a systematisk serie without gaps. If a verifikation is corrected, the original must be preserved and the correction linked.
### Rättelse (BFL 5 kap 5§)
A rättelse of a bokföringspost must be documented so that both the original and the corrected post are visible. You cannot simply overwrite. Implement as: new correcting verifikation referencing the original.
A rättelse of a bokföringspost must be documented so that both the original and the corrected post are visible, and it must be recorded when the rättelse was made and who made it. You can never silently overwrite. BFL permits two tracks:
1. **Särskild rättelsepost** (storno + correcting verifikation referencing the original): always allowed, and the only track once the period is locked/closed or the bokföring has been relied upon (filed declarations, bokslut).
2. **Rättelse in the same verifikat** (strike-and-replace of lines, or correcting the verifikation's text/date per BFL 5 kap 9 §): allowed while the period is open and unlocked, provided the original remains readable (struck lines stay visible) and who/when is recorded immutably. Fortnox and Visma implement this track; in Accounted it is the `correct_entry_metadata` / `correct_entry_lines_inline` RPC envelope logging to `journal_entry_rattelse_log`.
A correction path that erases the original without a trace violates the law under both tracks.
### Arkivering (BFL 7 kap)
- Räkenskapsinformation must be preserved for 7 years after the end of the calendar year the räkenskapsår ended
@@ -90,11 +90,12 @@ Every verifikation must have an underlag (kvitto, faktura, bankutdrag, avtal, et
### Multiple verification series
BFL allows multiple verification series (e.g., "A" for supplier invoices, "B" for customer invoices, "K" for bank). Each series must have unbroken numbering within the räkenskapsår. This is common in practice and your software should support it.
### Rättelser (5 kap 5§)
- An incorrect bokföringspost must be corrected with a new verifikation
- The original post must remain visible (no overwriting)
- The correcting post must reference the original
- Implement as: rättelsepost with a link/reference to the original verifikation
### Rättelser (5 kap 5§ and 5 kap 9§)
- The original post must remain visible (no silent overwriting), and it must be recorded when the rättelse was made and who made it
- Two permitted tracks:
1. **Särskild rättelsepost**: a correcting verifikation with a link/reference to the original. Always allowed; the only track once the period is locked/closed or the bokföring has been relied upon (filed declarations, bokslut)
2. **Rättelse in the same verifikat**: strike-and-replace of lines with the struck originals kept readable, or correction of the verifikation's text/date (5 kap 9 §). Allowed in open, unlocked periods with an immutable who/when trail. This is the track Fortnox/Visma expose as "ändra verifikat"
- When rättelse happens through a särskild rättelsepost, it must be easy to become aware of the rättelse when inspecting the corrected post ("utan svårighet gå att få kännedom om rättelsen")
## 5. Avslutning av bokföringen (BFL 6 kap)
+1 -1
View File
File diff suppressed because one or more lines are too long
+10 -1
View File
File diff suppressed because one or more lines are too long
+25 -1
View File
@@ -16,6 +16,7 @@ import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-messag
import { isBankIdEnabled } from '@/lib/auth/bankid'
import { getBranding } from '@/lib/branding/service'
import { detectWebmailHint } from '@/lib/auth/webmail-search'
import { safeReturnTo } from '@/lib/auth/safe-return-to'
import { AuthPageSkeleton } from '@/components/auth/AuthPageSkeleton'
const branding = getBranding()
@@ -50,6 +51,10 @@ function LoginPageContent() {
const searchParams = useSearchParams()
const callbackError = searchParams.get('error')
const callbackFlow = searchParams.get('flow')
// Post-login destination, set e.g. by the MCP OAuth authorize endpoint
// (/login?next=/api/mcp-oauth/authorize?...). Sanitized to a same-origin
// relative path; '/' means no explicit destination.
const nextPath = safeReturnTo(searchParams.get('next'), '/')
const supabase = createClient()
const bankIdEnabled = isBankIdEnabled()
const tAuth = useTranslations('auth')
@@ -131,6 +136,13 @@ function LoginPageContent() {
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
}
if (nextPath !== '/') {
// An explicit destination (e.g. the MCP OAuth consent page, raw
// HTML from a route handler) outranks the company picker.
window.location.assign(nextPath)
return
}
// Always land on the picker after BankID login so the user sees
// fresh CompanyRoles fetched during this session's enrichment.
router.push('/select-company')
@@ -175,7 +187,11 @@ function LoginPageContent() {
const { data: aal } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
if (aal?.nextLevel === 'aal2' && aal?.currentLevel === 'aal1') {
router.push('/mfa/verify')
router.push(
nextPath === '/'
? '/mfa/verify'
: `/mfa/verify?returnTo=${encodeURIComponent(nextPath)}`
)
return
}
@@ -203,6 +219,14 @@ function LoginPageContent() {
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
}
if (nextPath !== '/') {
// Full navigation: the destination can be a route handler that
// returns raw HTML (the MCP OAuth consent page), which the client
// router cannot render.
window.location.assign(nextPath)
return
}
router.push('/')
router.refresh()
} catch (error) {
+7
View File
@@ -138,6 +138,13 @@ function MfaVerifyContent() {
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
}
if (returnTo.startsWith('/api/')) {
// Route-handler destinations (e.g. the MCP OAuth consent page)
// return raw HTML the client router cannot render: hard-navigate.
window.location.assign(returnTo)
return
}
router.push(returnTo)
router.refresh()
} catch {
+223 -4
View File
@@ -8,7 +8,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { AccountNumber } from '@/components/ui/account-number'
import { Textarea } from '@/components/ui/textarea'
import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock, MessageSquare, Pencil, Check, X, Copy, ChevronDown, CalendarClock, FileText, Link2, RotateCcw } from 'lucide-react'
import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock, MessageSquare, Pencil, Check, X, Copy, ChevronDown, CalendarClock, FileText, Link2, RotateCcw, Scissors, PenLine } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -23,6 +23,8 @@ import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttach
import JournalEntryStatusBadge, { useSourceTypeLabels } from '@/components/bookkeeping/JournalEntryStatusBadge'
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
import CorrectOpeningBalanceDialog from '@/components/bookkeeping/CorrectOpeningBalanceDialog'
import StrikeLinesDialog from '@/components/bookkeeping/StrikeLinesDialog'
import CorrectMetadataDialog from '@/components/bookkeeping/CorrectMetadataDialog'
import EditDraftEntryDialog from '@/components/bookkeeping/EditDraftEntryDialog'
import RecordateEntryDialog from '@/components/bookkeeping/RecordateEntryDialog'
import AgentSparkleButton from '@/components/agent/AgentSparkleButton'
@@ -37,6 +39,29 @@ import { fetchDimensions, type DimensionDto } from '@/components/dimensions/type
import type { JournalEntry, JournalEntryLine } from '@/types'
import type { UnderlagReference } from '@/lib/core/bookkeeping/journal-entry-references'
// Snapshot of a struck line, as stored in journal_entry_rattelse_log.
type StruckLineSnapshot = {
id: string
account_number: string
debit_amount: number | string
credit_amount: number | string
line_description: string | null
sort_order: number
}
type RattelseLogRow = {
id: string
rattelse_type: 'metadata' | 'lines'
old_description: string | null
new_description: string | null
old_entry_date: string | null
new_entry_date: string | null
struck_lines: StruckLineSnapshot[] | null
added_lines: StruckLineSnapshot[] | null
actor: string | null
created_at: string
}
export default function JournalEntryDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
const router = useRouter()
@@ -50,6 +75,9 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
const [error, setError] = useState<string | null>(null)
const [showCorrection, setShowCorrection] = useState(false)
const [showCorrectIB, setShowCorrectIB] = useState(false)
const [showStrikeLines, setShowStrikeLines] = useState(false)
const [showCorrectMetadata, setShowCorrectMetadata] = useState(false)
const [rattelseLog, setRattelseLog] = useState<RattelseLogRow[]>([])
const [showEdit, setShowEdit] = useState(false)
const [showRecordate, setShowRecordate] = useState(false)
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
@@ -96,15 +124,20 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
setIsLoading(true)
setError(null)
try {
const [chainRes, refsRes, retagRes] = await Promise.all([
const [chainRes, refsRes, retagRes, rattelseRes] = await Promise.all([
fetch(`/api/bookkeeping/journal-entries/${id}/chain`),
fetch(`/api/bookkeeping/journal-entries/${id}/references`),
fetch(`/api/bookkeeping/journal-entries/${id}/retag-log`),
fetch(`/api/bookkeeping/journal-entries/${id}/rattelse-log`),
])
if (retagRes.ok) {
const retagPayload = await retagRes.json()
setRetagLog(Array.isArray(retagPayload.data) ? retagPayload.data : [])
}
if (rattelseRes.ok) {
const rattelsePayload = await rattelseRes.json()
setRattelseLog(Array.isArray(rattelsePayload.data) ? rattelsePayload.data : [])
}
if (!chainRes.ok) {
const { error: msg } = await chainRes.json()
setError(msg || t('error_load_failed'))
@@ -277,6 +310,37 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
// correction (or the original) and corrects that one.
const canCorrect = entry.status === 'posted' && entry.source_type !== 'storno'
// Inline rättelse (strike lines in the same verifikat) keeps structural
// entry types on their dedicated flows: storno mirrors its original, IB
// feeds opening_balance_entry_id, year-end feeds dispositions. The RPC
// enforces the same rule server-side; this just hides the dead menu item.
const canInlineRattelse =
entry.status === 'posted' &&
!['storno', 'opening_balance', 'year_end', 'vat_settlement'].includes(entry.source_type)
// Struck lines (from the immutable rättelse log) render inline in the
// lines table with strikethrough, Fortnox-style: the original stays
// visible per BFL 5 kap 5 § even though it no longer counts.
const struckDisplayLines = rattelseLog
.filter((r) => r.rattelse_type === 'lines')
.flatMap((r) =>
(r.struck_lines ?? []).map((s) => ({ ...s, struck_at: r.created_at }))
)
// Live and struck lines interleaved by original position.
const displayRows: Array<
| { kind: 'live'; line: JournalEntryLine }
| { kind: 'struck'; line: StruckLineSnapshot & { struck_at: string } }
> = [
...lines.map((l) => ({ kind: 'live' as const, line: l })),
...struckDisplayLines.map((s) => ({ kind: 'struck' as const, line: s })),
].sort(
(a, b) =>
(a.line.sort_order ?? 0) - (b.line.sort_order ?? 0) ||
// On a sort_order tie the struck original renders above its replacement.
(a.kind === 'struck' ? -1 : 0) - (b.kind === 'struck' ? -1 : 0)
)
// An opening-balance verifikat must be corrected through the IB-aware flow
// (storno + rebook + relink the period's opening_balance_entry_id), never the
// generic "Rätta rader": that books a `correction` entry but leaves the
@@ -343,6 +407,11 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
{formatVoucher(entry)}
</h1>
<JournalEntryStatusBadge entry={entry} />
{rattelseLog.length > 0 && (
<Badge variant="outline" className="text-xs font-normal" title={t('rattelse_history_title')}>
Rättad
</Badge>
)}
</div>
<p className="text-muted-foreground">{entry.description}</p>
</div>
@@ -411,6 +480,17 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{canInlineRattelse && (
<DropdownMenuItem onClick={() => setShowStrikeLines(true)}>
<Scissors className="mr-2 h-4 w-4" />
{t('strike_lines')}
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => setShowCorrectMetadata(true)}>
<PenLine className="mr-2 h-4 w-4" />
{t('correct_metadata')}
</DropdownMenuItem>
{canInlineRattelse && <DropdownMenuSeparator />}
<DropdownMenuItem onClick={() => setShowCorrection(true)}>
<Pencil className="mr-2 h-4 w-4" />
{t('correct_lines')}
@@ -643,7 +723,34 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
</tr>
</thead>
<tbody>
{lines.map((line) => {
{displayRows.map((row) => {
if (row.kind === 'struck') {
const s = row.line
return (
<tr key={`struck-${s.id}`} className="border-b last:border-0 text-muted-foreground">
<td className="py-2 line-through decoration-muted-foreground/70">
<AccountNumber number={s.account_number} showName />
</td>
<td className="py-2">
<span className="line-through decoration-muted-foreground/70">
{s.line_description || ''}
</span>
<span className="ml-2 no-underline text-xs">
{t('struck_marker', { date: formatDate(s.struck_at) })}
</span>
</td>
<td className="py-2 text-right tabular-nums line-through decoration-muted-foreground/70">
{Number(s.debit_amount) > 0 &&
Number(s.debit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</td>
<td className="py-2 text-right tabular-nums line-through decoration-muted-foreground/70">
{Number(s.credit_amount) > 0 &&
Number(s.credit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</td>
</tr>
)
}
const line = row.line
const hasForeignCurrency = line.currency && line.currency !== 'SEK' && line.amount_in_currency != null
return (
<tr key={line.id} className="border-b last:border-0">
@@ -709,7 +816,32 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
{/* Mobile cards */}
<div className="sm:hidden space-y-2">
{lines.map((line) => {
{displayRows.map((row) => {
if (row.kind === 'struck') {
const s = row.line
return (
<div key={`struck-${s.id}`} className="flex items-center justify-between py-2 border-b last:border-0 gap-2 text-muted-foreground">
<div className="min-w-0 flex-1">
<div className="text-sm line-through decoration-muted-foreground/70">
<AccountNumber number={s.account_number} showName />
</div>
{s.line_description && (
<p className="text-xs truncate line-through decoration-muted-foreground/70">{s.line_description}</p>
)}
<p className="text-xs">{t('struck_marker', { date: formatDate(s.struck_at) })}</p>
</div>
<div className="text-right shrink-0 text-sm tabular-nums line-through decoration-muted-foreground/70">
{Number(s.debit_amount) > 0 && (
<p>{Number(s.debit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} D</p>
)}
{Number(s.credit_amount) > 0 && (
<p>{Number(s.credit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} K</p>
)}
</div>
</div>
)
}
const line = row.line
const hasForeignCurrency = line.currency && line.currency !== 'SEK' && line.amount_in_currency != null
return (
<div key={line.id} className="flex items-center justify-between py-2 border-b last:border-0 gap-2">
@@ -818,6 +950,69 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
</Card>
)}
{/* Rättelsehistorik (BFL 5 kap 5 § / 9 §): the immutable who/when trail
behind inline rättelser. Stays Swedish (voucher detail surface). */}
{rattelseLog.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">{t('rattelse_history_title')}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{rattelseLog.map((row) => (
<div key={row.id} className="text-sm border-b last:border-0 pb-3 last:pb-0">
<div className="flex items-center justify-between gap-3">
<span className="text-muted-foreground tabular-nums">{formatDate(row.created_at)}</span>
<span className="text-xs text-muted-foreground">
{row.rattelse_type === 'metadata' ? t('rattelse_kind_metadata') : t('rattelse_kind_lines')}
</span>
</div>
{row.rattelse_type === 'metadata' ? (
<div className="space-y-0.5">
{row.old_description !== row.new_description && (
<p>
<span className="text-muted-foreground line-through">{row.old_description}</span>
{' → '}
<span>{row.new_description}</span>
</p>
)}
{row.old_entry_date !== row.new_entry_date && (
<p className="tabular-nums">
<span className="text-muted-foreground line-through">{formatDate(row.old_entry_date || '')}</span>
{' → '}
<span>{formatDate(row.new_entry_date || '')}</span>
</p>
)}
</div>
) : (
<div className="space-y-0.5">
{(row.struck_lines ?? []).map((s) => (
<p key={s.id} className="tabular-nums text-muted-foreground">
<span className="line-through decoration-muted-foreground/70">
{s.account_number}
{' '}
{Number(s.debit_amount) > 0
? `${Number(s.debit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} D`
: `${Number(s.credit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} K`}
</span>
</p>
))}
{(row.added_lines ?? []).map((a) => (
<p key={a.id} className="tabular-nums">
{a.account_number}
{' '}
{Number(a.debit_amount) > 0
? `${Number(a.debit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} D`
: `${Number(a.credit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} K`}
</p>
))}
</div>
)}
</div>
))}
</CardContent>
</Card>
)}
{/* Dimension retag history (dimensions plan PR6): the immutable
before/after trail. Stays Swedish (voucher detail surface). */}
{dimensionsEnabled && retagLog.length > 0 && (
@@ -861,6 +1056,30 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
onRetagged={fetchData}
/>
{/* Inline rättelse dialogs (strike lines / metadata) */}
{showStrikeLines && entry && (
<StrikeLinesDialog
entry={entry}
open={showStrikeLines}
onOpenChange={setShowStrikeLines}
onCorrected={() => {
setShowStrikeLines(false)
fetchData()
}}
/>
)}
{showCorrectMetadata && entry && (
<CorrectMetadataDialog
entry={entry}
open={showCorrectMetadata}
onOpenChange={setShowCorrectMetadata}
onCorrected={() => {
setShowCorrectMetadata(false)
fetchData()
}}
/>
)}
{/* Correction dialog */}
{showCorrection && entry && (
<CorrectionEntryDialog
+6 -4
View File
@@ -170,9 +170,11 @@ export default async function DashboardLayout({
// select returns exactly the caller's companies, letting non-active rows
// show company_settings.company_name instead of the frozen companies.name.
supabase.from('company_settings').select('company_id, company_name'),
// Per-user UI state (nav collapse/fold state): server-rendered so the
// sidebar width is right on first paint, no post-hydration jump.
supabase.from('user_preferences').select('ui_state').eq('user_id', user.id).maybeSingle(),
// Per-user UI state (nav collapse/fold state), server-rendered so the
// sidebar width is right on first paint, plus the hide-assistant-FAB
// preference (Inställningar → Assistenten). Batched here so it costs no
// extra round-trip on the dashboard critical path.
supabase.from('user_preferences').select('ui_state, hide_assistant_fab').eq('user_id', user.id).maybeSingle(),
])
// company_id -> current display name for every company the user belongs to.
@@ -316,7 +318,7 @@ export default async function DashboardLayout({
<main id="main-content" className={MAIN_PANEL_CLASS} role="main">
<MainContainer companyId={companyId}>{children}</MainContainer>
</main>
<AgentTrigger />
<AgentTrigger hidden={userPrefs?.hide_assistant_fab === true} />
<LazyCommandPalette />
<SettingsHotkey />
{settingsModal}
+1
View File
@@ -2467,6 +2467,7 @@ export default function TransactionsPage() {
onOpenMatchDialog={openMatchDialog}
onOpenCategoryDialog={openCategoryDialog}
onOpenAttachDocument={openAttachDocumentDialog}
onOpenMatchVoucher={openMatchVoucherDialog}
onDelete={handleDeleteTransaction}
onSkvBokfor={handleSkvBokfor}
onSkvMatch={r => setSkvMatchTarget(r)}
@@ -0,0 +1,148 @@
/**
* Tests for POST /api/bookkeeping/journal-entries/[id]/correct-metadata
* (metadata rättelse of a posted verifikat via the audited RPC).
*
* Covers: 401, validation 400 (empty body / blank description / bad date),
* rule-violation 409 passthrough (Swedish RPC messages verbatim), tenant
* guard 403, unexpected RPC failure 500, and the happy path.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
const { supabase, reset } = createQueuedMockSupabase()
const rpcMock = vi.fn()
;(supabase as { rpc?: unknown }).rpc = rpcMock
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { POST } from '../route'
const params = () => createMockRouteParams({ id: 'entry-1' })
function makeRequest(body: unknown) {
return createMockRequest('/api/bookkeeping/journal-entries/entry-1/correct-metadata', {
method: 'POST',
body,
})
}
describe('POST /api/bookkeeping/journal-entries/[id]/correct-metadata', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(makeRequest({ description: 'Rättad text' }), params())
expect(response.status).toBe(401)
expect(rpcMock).not.toHaveBeenCalled()
})
it.each([
['empty body', {}],
['blank description', { description: ' ' }],
['bad date', { entry_date: 'inte-ett-datum' }],
])('rejects invalid body (%s) with 400', async (_label, body) => {
const response = await POST(makeRequest(body), params())
expect(response.status).toBe(400)
expect(rpcMock).not.toHaveBeenCalled()
})
it('passes rule violations through as 409 with the Swedish message', async () => {
rpcMock.mockResolvedValue({
data: null,
error: { code: 'P0001', message: 'Perioden är stängd eller låst — använd rättelseverifikat (storno).' },
})
const response = await POST(makeRequest({ description: 'Rättad text' }), params())
const { body } = await parseJsonResponse<{ error: string }>(response)
expect(response.status).toBe(409)
expect(body.error).toContain('låst')
})
it('maps the tenant guard (42501) to 403', async () => {
rpcMock.mockResolvedValue({
data: null,
error: { code: '42501', message: 'unauthorized: caller is not a member of company company-1' },
})
const response = await POST(makeRequest({ description: 'Rättad text' }), params())
expect(response.status).toBe(403)
})
it('returns 500 on unexpected RPC failure', async () => {
rpcMock.mockResolvedValue({ data: null, error: { code: '57P01', message: 'connection refused' } })
const response = await POST(makeRequest({ description: 'Rättad text' }), params())
expect(response.status).toBe(500)
})
it('corrects description and date via the RPC with the caller as actor (happy path)', async () => {
rpcMock.mockResolvedValue({
data: {
changed: true,
log_id: 'log-1',
old_description: 'Gamal text',
new_description: 'Rättad text',
old_entry_date: '2026-07-01',
new_entry_date: '2026-07-05',
},
error: null,
})
const response = await POST(
makeRequest({ description: 'Rättad text', entry_date: '2026-07-05' }),
params(),
)
const { body } = await parseJsonResponse<{ data: { changed: boolean; log_id: string } }>(response)
expect(response.status).toBe(200)
expect(body.data.changed).toBe(true)
expect(rpcMock).toHaveBeenCalledWith('correct_entry_metadata', {
p_company_id: 'company-1',
p_entry_id: 'entry-1',
p_description: 'Rättad text',
p_entry_date: '2026-07-05',
p_user_id: 'user-1',
})
})
it('sends null for omitted fields (description-only edit)', async () => {
rpcMock.mockResolvedValue({ data: { changed: true, log_id: 'log-2' }, error: null })
const response = await POST(makeRequest({ description: 'Bara texten' }), params())
expect(response.status).toBe(200)
expect(rpcMock).toHaveBeenCalledWith(
'correct_entry_metadata',
expect.objectContaining({ p_description: 'Bara texten', p_entry_date: null }),
)
})
})
@@ -0,0 +1,52 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { CorrectEntryMetadataSchema } from '@/lib/api/schemas'
import { getErrorMessage } from '@/lib/errors/get-error-message'
/**
* POST /api/bookkeeping/journal-entries/[id]/correct-metadata
*
* Metadata rättelse (BFL 5 kap 9 §): correct the description and/or the
* entry date (within the same fiscal period) of a POSTED verifikat, without
* a rättelseverifikation. The correct_entry_metadata RPC enforces everything
* (posted status, open/unlocked period, company lock date, same-period date,
* writer role) and writes the immutable journal_entry_rattelse_log row
* before the carve-out UPDATE. Cross-period date moves stay on the
* recordate (storno) flow.
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'bookkeeping.journal_entry.correct_metadata',
async (request, { supabase, companyId, user, log }, { params }) => {
const { id } = await params
const validation = await validateBody(request, CorrectEntryMetadataSchema)
if (!validation.success) return validation.response
const { description, entry_date } = validation.data
const { data, error } = await supabase.rpc('correct_entry_metadata', {
p_company_id: companyId,
p_entry_id: id,
p_description: description ?? null,
p_entry_date: entry_date ?? null,
p_user_id: user.id,
})
if (error) {
// Rule violations are plain RAISE EXCEPTION (P0001) with user-facing
// Swedish messages: surface verbatim as 409. Tenant guard raises 42501.
if (error.code === 'P0001') {
return NextResponse.json({ error: getErrorMessage(error) }, { status: 409 })
}
if (error.code === '42501') {
return NextResponse.json({ error: getErrorMessage(error) }, { status: 403 })
}
log.error('correct_entry_metadata failed', new Error(error.message), { entryId: id })
return NextResponse.json({ error: 'Kunde inte rätta verifikationen' }, { status: 500 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)
@@ -0,0 +1,114 @@
/**
* Tests for GET /api/bookkeeping/journal-entries/[id]/rattelse-log
* (the immutable inline rättelse history, BFL 5 kap 5 § / 9 §).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET } from '../route'
const params = () => createMockRouteParams({ id: 'entry-1' })
const makeGet = () =>
createMockRequest('/api/bookkeeping/journal-entries/entry-1/rattelse-log', { method: 'GET' })
describe('GET /api/bookkeeping/journal-entries/[id]/rattelse-log', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await GET(makeGet(), params())
expect(response.status).toBe(401)
})
it('returns 404 when the entry belongs to another company', async () => {
enqueue({ data: null, error: null }) // ownership check finds nothing
const response = await GET(makeGet(), params())
const { body } = await parseJsonResponse<{ error: string }>(response)
expect(response.status).toBe(404)
expect(body.error).toContain('hittades inte')
})
it('returns the rättelse rows newest first', async () => {
enqueue({ data: { id: 'entry-1' }, error: null }) // ownership check
enqueue({
data: [
{
id: 'log-2',
rattelse_type: 'lines',
old_description: null,
new_description: null,
old_entry_date: null,
new_entry_date: null,
struck_lines: [
{ id: 'line-1', account_number: '5410', debit_amount: 500, credit_amount: 0, line_description: null, sort_order: 1 },
],
added_lines: [
{ id: 'line-9', account_number: '5420', debit_amount: 500, credit_amount: 0, line_description: null, sort_order: 3 },
],
actor: 'user-1',
created_at: '2026-07-23T12:00:00Z',
},
{
id: 'log-1',
rattelse_type: 'metadata',
old_description: 'Gamal text',
new_description: 'Rättad text',
old_entry_date: '2026-07-01',
new_entry_date: '2026-07-01',
struck_lines: null,
added_lines: null,
actor: 'user-1',
created_at: '2026-07-22T12:00:00Z',
},
],
error: null,
})
const response = await GET(makeGet(), params())
const { body } = await parseJsonResponse<{ data: { id: string; rattelse_type: string }[] }>(response)
expect(response.status).toBe(200)
expect(body.data).toHaveLength(2)
expect(body.data[0].id).toBe('log-2')
expect(body.data[0].rattelse_type).toBe('lines')
})
it('returns 500 with a Swedish message when the query fails', async () => {
enqueue({ data: { id: 'entry-1' }, error: null }) // ownership check
enqueue({ data: null, error: { message: 'boom' } })
const response = await GET(makeGet(), params())
const { body } = await parseJsonResponse<{ error: string }>(response)
expect(response.status).toBe(500)
expect(body.error).toContain('historik')
})
})
@@ -0,0 +1,46 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
/**
* GET /api/bookkeeping/journal-entries/[id]/rattelse-log
*
* The entry's inline rättelse history (BFL 5 kap 5 § / 9 §): the immutable
* who/when trail behind every metadata edit and line strike, newest first.
* Struck lines render with strikethrough in the verifikat detail view from
* the struck_lines snapshots here.
*/
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'bookkeeping.journal_entry.rattelse_log',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await params
// Ownership gate: 404 for entries outside the caller's company, so the
// empty-log response cannot be used to probe entry existence cross-tenant.
const { data: entry, error: entryError } = await supabase
.from('journal_entries')
.select('id')
.eq('id', id)
.eq('company_id', companyId)
.maybeSingle()
if (entryError) {
return NextResponse.json({ error: 'Kunde inte hämta rättelsehistorik' }, { status: 500 })
}
if (!entry) {
return NextResponse.json({ error: 'Verifikatet hittades inte' }, { status: 404 })
}
const { data, error } = await supabase
.from('journal_entry_rattelse_log')
.select('id, rattelse_type, old_description, new_description, old_entry_date, new_entry_date, struck_lines, added_lines, actor, created_at')
.eq('company_id', companyId)
.eq('journal_entry_id', id)
.order('created_at', { ascending: false })
if (error) {
return NextResponse.json({ error: 'Kunde inte hämta rättelsehistorik' }, { status: 500 })
}
return NextResponse.json({ data: data ?? [] })
},
)
@@ -0,0 +1,171 @@
/**
* Tests for POST /api/bookkeeping/journal-entries/[id]/strike-lines
* (inline line rättelse of a posted verifikat via the audited RPC).
*
* Covers: 401, validation 400 (empty rättelse / bad account / bad uuid),
* rule-violation 409 passthrough (Swedish RPC messages verbatim), tenant
* guard 403, unexpected RPC failure 500, the happy path (incl. BAS account
* backfill before the RPC) and the strike-only path.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
const { supabase, reset } = createQueuedMockSupabase()
const rpcMock = vi.fn()
;(supabase as { rpc?: unknown }).rpc = rpcMock
const backfillMock = vi.fn().mockResolvedValue([])
vi.mock('@/lib/bookkeeping/account-backfill', () => ({
backfillStandardBASAccounts: (...args: unknown[]) => backfillMock(...args),
}))
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { POST } from '../route'
const LINE_ID = '11111111-1111-4111-8111-111111111111'
const params = () => createMockRouteParams({ id: 'entry-1' })
function makeRequest(body: unknown) {
return createMockRequest('/api/bookkeeping/journal-entries/entry-1/strike-lines', {
method: 'POST',
body,
})
}
describe('POST /api/bookkeeping/journal-entries/[id]/strike-lines', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
backfillMock.mockResolvedValue([])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(makeRequest({ strike_line_ids: [LINE_ID] }), params())
expect(response.status).toBe(401)
expect(rpcMock).not.toHaveBeenCalled()
})
it.each([
['empty rättelse', { strike_line_ids: [], lines: [] }],
['bad line id', { strike_line_ids: ['not-a-uuid'] }],
['bad account number', { lines: [{ account_number: '19', debit_amount: 100 }] }],
['negative amount', { lines: [{ account_number: '1930', debit_amount: -5 }] }],
])('rejects invalid body (%s) with 400', async (_label, body) => {
const response = await POST(makeRequest(body), params())
expect(response.status).toBe(400)
expect(rpcMock).not.toHaveBeenCalled()
})
it('passes rule violations through as 409 with the Swedish message', async () => {
rpcMock.mockResolvedValue({
data: null,
error: { code: 'P0001', message: 'Verifikationen balanserar inte efter rättelsen (debet 100.00, kredit 0.00).' },
})
const response = await POST(makeRequest({ strike_line_ids: [LINE_ID] }), params())
const { body } = await parseJsonResponse<{ error: string }>(response)
expect(response.status).toBe(409)
expect(body.error).toContain('balanserar')
})
it('maps the tenant guard (42501) to 403', async () => {
rpcMock.mockResolvedValue({
data: null,
error: { code: '42501', message: 'unauthorized: caller is not a member of company company-1' },
})
const response = await POST(makeRequest({ strike_line_ids: [LINE_ID] }), params())
expect(response.status).toBe(403)
})
it('returns 500 on unexpected RPC failure', async () => {
rpcMock.mockResolvedValue({ data: null, error: { code: '57P01', message: 'connection refused' } })
const response = await POST(makeRequest({ strike_line_ids: [LINE_ID] }), params())
expect(response.status).toBe(500)
})
it('strikes and replaces via the RPC, backfilling BAS accounts first (happy path)', async () => {
rpcMock.mockResolvedValue({
data: { log_id: 'log-1', struck_count: 1, added_count: 1, total_debit: 500, total_credit: 500 },
error: null,
})
const response = await POST(
makeRequest({
strike_line_ids: [LINE_ID],
lines: [{ account_number: '5420', debit_amount: 500, line_description: 'Programvara' }],
}),
params(),
)
const { body } = await parseJsonResponse<{ data: { struck_count: number; added_count: number } }>(response)
expect(response.status).toBe(200)
expect(body.data.struck_count).toBe(1)
expect(body.data.added_count).toBe(1)
expect(backfillMock).toHaveBeenCalledWith(supabase, 'company-1', 'user-1', ['5420'])
expect(rpcMock).toHaveBeenCalledWith('correct_entry_lines_inline', {
p_company_id: 'company-1',
p_entry_id: 'entry-1',
p_strike_line_ids: [LINE_ID],
p_new_lines: [
{
account_number: '5420',
debit_amount: 500,
credit_amount: 0,
line_description: 'Programvara',
dimensions: {},
},
],
p_user_id: 'user-1',
})
})
it('accepts a strike-only rättelse without new lines (skips backfill)', async () => {
rpcMock.mockResolvedValue({
data: { log_id: 'log-2', struck_count: 2, added_count: 0, total_debit: 100, total_credit: 100 },
error: null,
})
const response = await POST(
makeRequest({ strike_line_ids: [LINE_ID, '22222222-2222-4222-8222-222222222222'] }),
params(),
)
expect(response.status).toBe(200)
expect(backfillMock).not.toHaveBeenCalled()
expect(rpcMock).toHaveBeenCalledWith(
'correct_entry_lines_inline',
expect.objectContaining({ p_new_lines: [] }),
)
})
})
@@ -0,0 +1,75 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { StrikeLinesSchema } from '@/lib/api/schemas'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { backfillStandardBASAccounts } from '@/lib/bookkeeping/account-backfill'
/**
* POST /api/bookkeeping/journal-entries/[id]/strike-lines
*
* Inline line rättelse (BFL 5 kap 5 §): strike lines inside a POSTED
* verifikat and add replacement lines in the same verifikat, without a
* rättelseverifikation. The correct_entry_lines_inline RPC enforces the full
* envelope (posted status, open/unlocked period, company lock date, effective
* balance to the öre, ≥2 remaining lines, writer role) and snapshots the
* struck originals to the immutable journal_entry_rattelse_log. Past a
* lock/close, the storno correction flow remains the only path.
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'bookkeeping.journal_entry.strike_lines',
async (request, { supabase, companyId, user, log }, { params }) => {
const { id } = await params
const validation = await validateBody(request, StrikeLinesSchema)
if (!validation.success) return validation.response
const { strike_line_ids, lines } = validation.data
// Seed standard BAS accounts the replacement lines reference but the
// company chart lacks (same courtesy as the engine/storno flow); unknown
// numbers stay missing and fail the RPC's chart check with a clear error.
const accountNumbers = [...new Set(lines.map((l) => l.account_number))]
if (accountNumbers.length > 0) {
await backfillStandardBASAccounts(supabase, companyId, user.id, accountNumbers)
}
const { data, error } = await supabase.rpc('correct_entry_lines_inline', {
p_company_id: companyId,
p_entry_id: id,
p_strike_line_ids: strike_line_ids,
p_new_lines: lines.map((l) => ({
account_number: l.account_number,
debit_amount: l.debit_amount,
credit_amount: l.credit_amount,
line_description: l.line_description ?? null,
dimensions: l.dimensions ?? {},
})),
p_user_id: user.id,
})
if (error) {
// Rule violations are plain RAISE EXCEPTION (P0001) with user-facing
// Swedish messages: surface verbatim as 409. Tenant guard raises 42501.
if (error.code === 'P0001') {
return NextResponse.json({ error: getErrorMessage(error) }, { status: 409 })
}
if (error.code === '42501') {
return NextResponse.json({ error: getErrorMessage(error) }, { status: 403 })
}
// Defensive: the RPC pre-checks document links, but if the RESTRICT FK
// still fires (racing attachment), surface the same guidance.
if (error.code === '23503') {
return NextResponse.json(
{ error: 'En rad som ska strykas har ett kopplat underlag — använd rättelseverifikat (storno).' },
{ status: 409 },
)
}
log.error('correct_entry_lines_inline failed', new Error(error.message), { entryId: id })
return NextResponse.json({ error: 'Kunde inte rätta verifikationen' }, { status: 500 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)
@@ -0,0 +1,83 @@
/**
* Tests for GET /api/bookkeeping/journal-entries/rattelse-flags
* (which entries carry inline rättelser, for the list "Rättad" marker).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
parseJsonResponse,
} from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET } from '../route'
const makeGet = (ids: string) =>
createMockRequest(`/api/bookkeeping/journal-entries/rattelse-flags?ids=${ids}`, { method: 'GET' })
describe('GET /api/bookkeeping/journal-entries/rattelse-flags', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await GET(makeGet('a'), undefined as never)
expect(response.status).toBe(401)
})
it('returns an empty list without querying when no ids are given', async () => {
const response = await GET(makeGet(''), undefined as never)
const { body } = await parseJsonResponse<{ data: string[] }>(response)
expect(response.status).toBe(200)
expect(body.data).toEqual([])
})
it('rejects more than 200 ids with 400', async () => {
const ids = Array.from({ length: 201 }, (_, i) => `id-${i}`).join(',')
const response = await GET(makeGet(ids), undefined as never)
expect(response.status).toBe(400)
})
it('returns the distinct entry ids that have rättelser', async () => {
enqueue({
data: [
{ journal_entry_id: 'entry-1' },
{ journal_entry_id: 'entry-1' },
{ journal_entry_id: 'entry-3' },
],
error: null,
})
const response = await GET(makeGet('entry-1,entry-2,entry-3'), undefined as never)
const { body } = await parseJsonResponse<{ data: string[] }>(response)
expect(response.status).toBe(200)
expect(body.data.sort()).toEqual(['entry-1', 'entry-3'])
})
it('returns 500 with a Swedish message when the query fails', async () => {
enqueue({ data: null, error: { message: 'boom' } })
const response = await GET(makeGet('entry-1'), undefined as never)
expect(response.status).toBe(500)
})
})
@@ -0,0 +1,38 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
/**
* GET /api/bookkeeping/journal-entries/rattelse-flags?ids=a,b,c
*
* Which of the given entries have inline rättelser (rows in
* journal_entry_rattelse_log). Drives the "Rättad" marker in the voucher
* list so a rättelse is discoverable without opening the verifikat
* (BFL 5 kap 5 §: the correction must be easy to become aware of).
* Capped at 200 ids per request (one list page).
*/
export const GET = withRouteContext(
'bookkeeping.journal_entries.rattelse_flags',
async (request, { supabase, companyId }) => {
const idsParam = new URL(request.url).searchParams.get('ids') ?? ''
const ids = idsParam.split(',').map((s) => s.trim()).filter(Boolean)
if (ids.length === 0) {
return NextResponse.json({ data: [] })
}
if (ids.length > 200) {
return NextResponse.json({ error: 'Högst 200 verifikat per anrop.' }, { status: 400 })
}
const { data, error } = await supabase
.from('journal_entry_rattelse_log')
.select('journal_entry_id')
.eq('company_id', companyId)
.in('journal_entry_id', ids)
if (error) {
return NextResponse.json({ error: 'Kunde inte hämta rättelsemarkeringar' }, { status: 500 })
}
return NextResponse.json({ data: [...new Set((data ?? []).map((r) => r.journal_entry_id))] })
},
)
@@ -0,0 +1,167 @@
/**
* Tests for the nightly Stripe balance-transaction sync cron: auth, config
* short-circuit, per-connection processing with capability gating, and
* isolated per-connection failures.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const verifyCronSecret = vi.fn<(request: Request) => Response | null>(() => null)
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: (request: Request) => verifyCronSecret(request),
}))
const connectionsResult: { data: unknown; error: unknown } = { data: null, error: null }
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(() => ({
from: vi.fn(() => {
const chain: Record<string, unknown> = {}
for (const method of ['select', 'eq', 'order', 'limit']) {
chain[method] = vi.fn(() => chain)
}
chain.then = (resolve: (v: unknown) => unknown) =>
Promise.resolve(connectionsResult).then(resolve)
return chain
}),
})),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
hasCapability: vi.fn(),
}))
vi.mock('@/extensions/general/stripe/lib/transaction-sync', () => ({
syncStripeBalanceTransactions: vi.fn(),
}))
import { hasCapability } from '@/lib/entitlements/has-capability'
import { syncStripeBalanceTransactions } from '@/extensions/general/stripe/lib/transaction-sync'
import { GET } from '../route'
function cronRequest(): Request {
return new Request('http://localhost:3000/api/extensions/stripe/transactions/cron')
}
function makeConnection(id: string, companyId: string) {
return {
id,
company_id: companyId,
user_id: 'user-1',
stripe_account_id: `acct_${id}`,
status: 'active',
transaction_sync_enabled: true,
last_balance_txn_synced_at: null,
}
}
beforeEach(() => {
vi.clearAllMocks()
verifyCronSecret.mockReturnValue(null)
connectionsResult.data = null
connectionsResult.error = null
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', 'https://example.supabase.co')
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'service-role-key')
vi.stubEnv('STRIPE_SECRET_KEY', 'sk_test_123')
vi.stubEnv('STRIPE_CONNECT_CLIENT_ID', 'ca_123')
vi.mocked(hasCapability).mockResolvedValue(true)
vi.mocked(syncStripeBalanceTransactions).mockResolvedValue({
fetched: 3,
imported: 2,
duplicates: 1,
linked: 1,
errors: 0,
})
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('GET /api/extensions/stripe/transactions/cron', () => {
it('rejects requests without a valid cron secret', async () => {
verifyCronSecret.mockReturnValue(
new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 }),
)
const response = await GET(cronRequest())
expect(response.status).toBe(401)
expect(vi.mocked(syncStripeBalanceTransactions)).not.toHaveBeenCalled()
})
it('no-ops when Stripe Connect is not configured', async () => {
vi.stubEnv('STRIPE_CONNECT_CLIENT_ID', '')
const response = await GET(cronRequest())
const json = await response.json()
expect(response.status).toBe(200)
expect(json).toEqual({ message: 'Stripe Connect not configured', processed: 0 })
})
it('no-ops when no connection has transaction sync enabled', async () => {
connectionsResult.data = []
const response = await GET(cronRequest())
const json = await response.json()
expect(json.processed).toBe(0)
expect(vi.mocked(syncStripeBalanceTransactions)).not.toHaveBeenCalled()
})
it('syncs entitled connections and aggregates totals', async () => {
connectionsResult.data = [
makeConnection('conn-1', 'company-1'),
makeConnection('conn-2', 'company-2'),
]
const response = await GET(cronRequest())
const json = await response.json()
expect(response.status).toBe(200)
expect(vi.mocked(syncStripeBalanceTransactions)).toHaveBeenCalledTimes(2)
expect(json.processed).toBe(2)
expect(json.imported).toBe(4)
expect(json.linked).toBe(2)
expect(json.results).toEqual([
{ connectionId: 'conn-1', imported: 2, duplicates: 1, linked: 1, status: 'synced' },
{ connectionId: 'conn-2', imported: 2, duplicates: 1, linked: 1, status: 'synced' },
])
})
it('skips connections whose company lacks the stripe_payments capability', async () => {
connectionsResult.data = [
makeConnection('conn-1', 'company-1'),
makeConnection('conn-2', 'company-2'),
]
vi.mocked(hasCapability).mockImplementation(async (_sb, companyId) =>
companyId !== 'company-1',
)
const response = await GET(cronRequest())
const json = await response.json()
expect(vi.mocked(syncStripeBalanceTransactions)).toHaveBeenCalledTimes(1)
expect(json.processed).toBe(1)
expect(json.results[0].connectionId).toBe('conn-2')
})
it('isolates a failing connection and keeps processing the rest', async () => {
connectionsResult.data = [
makeConnection('conn-1', 'company-1'),
makeConnection('conn-2', 'company-2'),
]
vi.mocked(syncStripeBalanceTransactions)
.mockRejectedValueOnce(new Error('stripe boom'))
.mockResolvedValueOnce({ fetched: 1, imported: 1, duplicates: 0, linked: 0, errors: 0 })
const response = await GET(cronRequest())
const json = await response.json()
expect(response.status).toBe(200)
expect(json.processed).toBe(2)
expect(json.results).toEqual([
{ connectionId: 'conn-1', imported: 0, duplicates: 0, linked: 0, status: 'error' },
{ connectionId: 'conn-2', imported: 1, duplicates: 0, linked: 0, status: 'synced' },
])
})
})
@@ -0,0 +1,130 @@
import { createClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { hasCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { syncStripeBalanceTransactions } from '@/extensions/general/stripe/lib/transaction-sync'
import type { StripeConnection } from '@/extensions/general/stripe/types'
export const maxDuration = 300
/**
* GET /api/extensions/stripe/transactions/cron
* Nightly balance-transaction sync for connections that opted in
* (transaction_sync_enabled): imports the connected Stripe balance into the
* transactions inbox as a bank-style feed on the 1686 cash account.
*
* Read-only against Stripe, and it never posts to the journal: rows land
* unbooked (or pre-linked to entries the deterministic settle/payout flows
* already created); booking stays a human decision. Idempotent via the
* (company_id, external_id) unique index, so overlapping windows and re-runs
* are no-ops. Unlike the 15-minute event sync, this does not emit events, so
* no ensureInitialized() is needed.
*/
export const GET = withCronContext('cron.stripe_transaction_sync', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
if (!process.env.STRIPE_SECRET_KEY || !process.env.STRIPE_CONNECT_CLIENT_ID) {
return NextResponse.json({ message: 'Stripe Connect not configured', processed: 0 })
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
const { data: connections, error: connError } = await supabase
.from('stripe_connections')
.select('*')
.eq('status', 'active')
.eq('transaction_sync_enabled', true)
.order('last_balance_txn_synced_at', { ascending: true, nullsFirst: true })
.limit(50)
if (connError) {
ctx.log.error('failed to fetch stripe connections', connError, {
message: connError.message,
code: connError.code,
})
return errorResponse(connError, ctx.log, { requestId: ctx.requestId })
}
if (!connections || connections.length === 0) {
return NextResponse.json({ message: 'No connections with transaction sync enabled', processed: 0 })
}
const startTime = Date.now()
const TIME_BUDGET_MS = 240_000 // leave a minute of margin inside maxDuration
// Shared with syncStripeBalanceTransactions: it stops between ingest chunks
// and persists its cursor, so a truncated connection resumes next night.
const deadlineMs = startTime + TIME_BUDGET_MS
const results: Array<{
connectionId: string
imported: number
duplicates: number
linked: number
status: 'synced' | 'revoked' | 'error'
}> = []
for (const connection of connections as StripeConnection[]) {
if (Date.now() >= deadlineMs) {
ctx.log.info('time budget reached', { processedSoFar: results.length })
break
}
if (!(await hasCapability(supabase, connection.company_id, CAPABILITY.stripe_payments))) {
ctx.log.info('skip: capability not entitled', { companyId: connection.company_id })
continue
}
try {
const summary = await syncStripeBalanceTransactions(supabase, connection, ctx.log, deadlineMs)
if (summary.deadlineReached) {
ctx.log.info('connection stopped early on time budget; remaining rows resume next run', {
connectionId: connection.id,
})
}
results.push({
connectionId: connection.id,
imported: summary.imported,
duplicates: summary.duplicates,
linked: summary.linked,
status: summary.revoked ? 'revoked' : 'synced',
})
} catch (error) {
ctx.log.error('stripe transaction sync failed for connection', error as Error, {
connectionId: connection.id,
companyId: connection.company_id,
})
results.push({
connectionId: connection.id,
imported: 0,
duplicates: 0,
linked: 0,
status: 'error',
})
}
}
const totals = results.reduce(
(acc, r) => ({
imported: acc.imported + r.imported,
linked: acc.linked + r.linked,
}),
{ imported: 0, linked: 0 },
)
ctx.log.info('stripe transaction sync summary', {
processed: results.length,
totalImported: totals.imported,
totalLinked: totals.linked,
failed: results.filter((r) => r.status === 'error').length,
})
return NextResponse.json({ processed: results.length, ...totals, results })
})
@@ -0,0 +1,111 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
import { GET, PATCH } from '../route'
beforeEach(() => {
vi.clearAllMocks()
})
function unauthed() {
requireAuthMock.mockResolvedValue({
user: null,
supabase: null,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
function authedForGet(row: { hide_assistant_fab: boolean } | null) {
const maybeSingle = vi.fn().mockResolvedValue({ data: row, error: null })
const supabase = {
from: vi.fn(() => ({
select: vi.fn(() => ({
eq: vi.fn(() => ({ maybeSingle })),
})),
})),
}
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
return { supabase }
}
function authedForPatch(upsertError: { message: string } | null = null) {
const upsert = vi.fn().mockResolvedValue({ error: upsertError })
const supabase = { from: vi.fn(() => ({ upsert })) }
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
return { upsert }
}
function patchRequest(body: unknown) {
return new Request('http://localhost/api/user/preferences', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
describe('GET /api/user/preferences', () => {
it('returns 401 when unauthenticated', async () => {
unauthed()
const res = await GET()
expect(res.status).toBe(401)
})
it('returns the stored preference', async () => {
authedForGet({ hide_assistant_fab: true })
const res = await GET()
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ hide_assistant_fab: true })
})
it('defaults to false when no preferences row exists', async () => {
authedForGet(null)
const res = await GET()
const { body } = await parseJsonResponse<{ data: unknown }>(res)
expect(body.data).toEqual({ hide_assistant_fab: false })
})
})
describe('PATCH /api/user/preferences', () => {
it('returns 401 when unauthenticated', async () => {
unauthed()
const res = await PATCH(patchRequest({ hide_assistant_fab: true }))
expect(res.status).toBe(401)
})
it('rejects an invalid body with 400', async () => {
authedForPatch()
const res = await PATCH(patchRequest({ hide_assistant_fab: 'yes' }))
expect(res.status).toBe(400)
})
it('rejects unknown keys with 400', async () => {
authedForPatch()
const res = await PATCH(patchRequest({ hide_assistant_fab: true, locale: 'en' }))
expect(res.status).toBe(400)
})
it('upserts the preference for the authenticated user', async () => {
const { upsert } = authedForPatch()
const res = await PATCH(patchRequest({ hide_assistant_fab: true }))
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ hide_assistant_fab: true })
expect(upsert).toHaveBeenCalledWith(
{ user_id: 'user-1', hide_assistant_fab: true },
{ onConflict: 'user_id' }
)
})
it('returns 500 when the upsert fails', async () => {
authedForPatch({ message: 'boom' })
const res = await PATCH(patchRequest({ hide_assistant_fab: false }))
expect(res.status).toBe(500)
})
})
+58
View File
@@ -0,0 +1,58 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
// User-level UI preferences (not company-scoped), stored on user_preferences.
// Mirrors the /api/user/locale pattern: requireAuth directly because these
// must work even when the user has no active company.
const BodySchema = z
.object({
hide_assistant_fab: z.boolean(),
})
.strict()
export async function GET() {
const { user, supabase, error } = await requireAuth()
if (error) return error
const { data } = await supabase
.from('user_preferences')
.select('hide_assistant_fab')
.eq('user_id', user.id)
.maybeSingle()
return NextResponse.json({
data: { hide_assistant_fab: data?.hide_assistant_fab ?? false },
})
}
export async function PATCH(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const parsed = BodySchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid preferences' }, { status: 400 })
}
const { error: upsertError } = await supabase
.from('user_preferences')
.upsert(
{ user_id: user.id, hide_assistant_fab: parsed.data.hide_assistant_fab },
{ onConflict: 'user_id' }
)
if (upsertError) {
return NextResponse.json({ error: 'Could not save preference' }, { status: 500 })
}
return NextResponse.json({ data: parsed.data })
}
+7 -1
View File
@@ -26,12 +26,18 @@ import { CAPABILITY } from '@/lib/entitlements/keys'
// row-level "Fråga [namn]" button in TransactionInboxCard, and the matching
// "Fråga assistenten" in Dokumentinkorgen: both passing a transaction_id the
// pathname-only FAB can't know.)
export default function AgentTrigger() {
export default function AgentTrigger({ hidden = false }: { hidden?: boolean }) {
const { openAgentSheet, expandAgentSheet, isOpen, collapsed, identity } = useAgentSheet()
const pathname = usePathname()
const router = useRouter()
const hasAi = useCapability(CAPABILITY.ai)
// User opt-out (Inställningar → Assistenten): the sidebar entry stays, the
// floating button goes. A collapsed session keeps its reopen handle even
// when hidden: it's the only way back to a minimized conversation, and its
// existence implies the user is actively using the assistant right now.
if (hidden && !collapsed) return null
// Sheet open AND visible → hide the FAB so the icon doesn't double up. When
// the session is merely collapsed we KEEP the FAB: it's the handle that
// brings the minimized conversation back.
@@ -0,0 +1,142 @@
'use client'
import { useState, useEffect } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { JournalEntry } from '@/types'
interface Props {
entry: JournalEntry
open: boolean
onOpenChange: (open: boolean) => void
onCorrected: () => void
}
/**
* Metadata rättelse (BFL 5 kap 9 §): correct the verifikationstext and/or
* the date (within the same fiscal period) of a posted verifikat without an
* ändringsverifikation. Who/when is recorded in the immutable rättelse log
* and shown in the verifikat's history. Stays Swedish (verifikat surface,
* .claude/rules/i18n.md).
*/
export default function CorrectMetadataDialog({ entry, open, onOpenChange, onCorrected }: Props) {
const { toast } = useToast()
const [description, setDescription] = useState('')
const [entryDate, setEntryDate] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
useEffect(() => {
if (open) {
setDescription(entry.description || '')
setEntryDate(entry.entry_date?.slice(0, 10) || '')
}
}, [open, entry.id]) // eslint-disable-line react-hooks/exhaustive-deps
const descriptionChanged = description.trim() !== (entry.description || '')
const dateChanged = entryDate !== (entry.entry_date?.slice(0, 10) || '')
const hasChange = (descriptionChanged && description.trim().length > 0) || (dateChanged && entryDate.length > 0)
async function handleSubmit() {
if (!hasChange) return
setIsSubmitting(true)
try {
const payload: { description?: string; entry_date?: string } = {}
if (descriptionChanged && description.trim().length > 0) payload.description = description.trim()
if (dateChanged && entryDate.length > 0) payload.entry_date = entryDate
const res = await fetch(`/api/bookkeeping/journal-entries/${entry.id}/correct-metadata`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
const result = await res.json()
if (!res.ok) {
const error = new Error('Failed to correct metadata') as Error & { body?: unknown; status?: number }
error.body = result
error.status = res.status
throw error
}
toast({
title: 'Verifikationen rättad',
description: 'Ändringen har loggats i verifikatets rättelsehistorik.',
})
onOpenChange(false)
onCorrected()
} catch (err) {
const anyErr = err as { body?: unknown; status?: number }
toast({
title: 'Kunde inte rätta verifikationen',
description: getErrorMessage(anyErr.body ?? err, { context: 'journal_entry', statusCode: anyErr.status }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Ändra text eller datum</DialogTitle>
</DialogHeader>
<div className="rounded-lg bg-muted/50 border p-3 text-sm text-muted-foreground">
<p>
Verifikationstexten och datumet kan rättas utan ändringsverifikation. Rättelsen loggas
med vem och när, och det gamla värdet förblir synligt i rättelsehistoriken. Datumet kan
bara flyttas inom samma bokföringsperiod: använd &quot;Flytta till annat datum&quot; för att
byta period. Om månaden redan är momsdeklarerad kan en datumflytt påverka den inlämnade
deklarationen.
</p>
</div>
<div className="space-y-4">
<div className="space-y-1">
<Label htmlFor="rattelse-description">Verifikationstext</Label>
<Input
id="rattelse-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
maxLength={500}
/>
</div>
<div className="space-y-1">
<Label htmlFor="rattelse-date">Datum</Label>
<Input
id="rattelse-date"
type="date"
value={entryDate}
onChange={(e) => setEntryDate(e.target.value)}
disabled={['storno', 'opening_balance', 'year_end'].includes(entry.source_type)}
/>
{['storno', 'opening_balance', 'year_end'].includes(entry.source_type) && (
<p className="text-xs text-muted-foreground">
Datumet på den här verifikationstypen kan inte ändras.
</p>
)}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
Avbryt
</Button>
<Button onClick={handleSubmit} disabled={!hasChange || isSubmitting}>
{isSubmitting ? 'Rättar...' : 'Spara rättelse'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+47 -6
View File
@@ -34,6 +34,7 @@ import {
} from '@/lib/hooks/use-submit-with-account-activation'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { formatCurrency } from '@/lib/utils'
import { roundOre } from '@/lib/money'
import { formatVoucher, resolveDefaultSeriesForSource } from '@/lib/bookkeeping/voucher-series-resolver'
import { useUnsavedChanges } from '@/lib/hooks/use-unsaved-changes'
import { useCompany } from '@/contexts/CompanyContext'
@@ -357,8 +358,9 @@ export default function JournalEntryForm({
)
// Fetch per-account saldo as of entryDate for the accounts currently on the
// form. Balances are reference-only ("saldo before this entry"): they ignore
// the draft lines the user is typing, by design.
// form. The fetched value is always "saldo before this entry"; the render
// layer adds the typed draft amounts on top (draftDeltas) so the column
// shows where the account is heading.
useEffect(() => {
if (!accountsKey) {
setAccountBalances({})
@@ -414,6 +416,22 @@ export default function JournalEntryForm({
}
}, [accountsKey, entryDate])
// What the typed-but-unposted rows would do to each account's saldo. The
// /account-balances convention is debit-positive for every class, so
// delta = debit - credit encodes direction without needing the account type:
// rendering "before -> after" gives instant feedback on whether the chosen
// side increases or decreases the account.
const draftDeltas = useMemo(() => {
const deltas: Record<string, number> = {}
for (const l of lines) {
if (!/^\d{4}$/.test(l.account_number)) continue
const delta = (parseFloat(l.debit_amount) || 0) - (parseFloat(l.credit_amount) || 0)
if (delta === 0) continue
deltas[l.account_number] = roundOre((deltas[l.account_number] ?? 0) + delta)
}
return deltas
}, [lines])
// New rows inherit the current header default (a row without a per-row
// override follows the header (see setHeaderDimension).
const makeBlankLine = useCallback(
@@ -1446,9 +1464,24 @@ export default function JournalEntryForm({
{accountBalances[line.account_number] === null || accountBalances[line.account_number] === undefined ? (
<Skeleton className="h-3 w-20" />
) : (
<span>
{t('saldo_label')} {formatCurrency(accountBalances[line.account_number] as number)}
</span>
(() => {
const bal = accountBalances[line.account_number] as number
const delta = draftDeltas[line.account_number]
if (!delta) {
return (
<span>
{t('saldo_label')} {formatCurrency(bal)}
</span>
)
}
const after = roundOre(bal + delta)
return (
<span>
{t('saldo_label')} {formatCurrency(bal)}{' '}
<span className="text-foreground">→ {formatCurrency(after)}</span>
</span>
)
})()
)}
</div>
)}
@@ -1579,7 +1612,15 @@ export default function JournalEntryForm({
if (bal === null || bal === undefined) {
return <Skeleton className="h-4 w-20 ml-auto" />
}
return formatCurrency(bal)
const delta = draftDeltas[line.account_number]
if (!delta) return formatCurrency(bal)
const after = roundOre(bal + delta)
return (
<span className="inline-flex flex-col items-end leading-tight">
<span className="text-[11px]">{formatCurrency(bal)}</span>
<span className="text-foreground">→ {formatCurrency(after)}</span>
</span>
)
})()}
</td>
<td className="py-1.5">
+32 -1
View File
@@ -103,6 +103,10 @@ export default function JournalEntryList() {
const [count, setCount] = useState(0)
const [page, setPage] = useState(0)
const [attachmentCounts, setAttachmentCounts] = useState<Record<string, number>>({})
// Entries with inline rättelser (journal_entry_rattelse_log rows): drives
// the "Rättad" marker so a rättelse is discoverable from the list
// (BFL 5 kap 5 §), not only on the detail page.
const [rattelseFlags, setRattelseFlags] = useState<Set<string>>(new Set())
const [noDocRequired, setNoDocRequired] = useState<Map<string, string | null>>(new Map())
const [showMissingOnly, setShowMissingOnly] = useState(false)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
@@ -212,6 +216,23 @@ export default function JournalEntryList() {
}
}, [])
const fetchRattelseFlags = useCallback(async (entryIds: string[]) => {
if (entryIds.length === 0) {
setRattelseFlags(new Set())
return
}
try {
const res = await fetch(
`/api/bookkeeping/journal-entries/rattelse-flags?ids=${entryIds.join(',')}`
)
if (!res.ok) return
const { data } = await res.json()
setRattelseFlags(new Set((data || []) as string[]))
} catch {
// Non-critical: silently ignore
}
}, [])
const fetchNoDocRequired = useCallback(async () => {
try {
const res = await fetch('/api/bookkeeping/no-doc-required')
@@ -371,9 +392,10 @@ export default function JournalEntryList() {
}
setLoading(false)
// Fetch attachment counts for the loaded entries
// Fetch attachment counts + rättelse markers for the loaded entries
const ids = loadedEntries.map((e: JournalEntry) => e.id)
fetchAttachmentCounts(ids)
fetchRattelseFlags(ids)
}
// Cheap count-only query for the "Utkast" badge, all years, so the badge
@@ -1103,6 +1125,15 @@ export default function JournalEntryList() {
{(entry.status === 'reversed' || entry.status === 'draft' || entry.source_type === 'storno' || entry.source_type === 'correction') && (
<JournalEntryStatusBadge entry={entry} showStatus={entry.status === 'reversed' || entry.status === 'draft'} />
)}
{rattelseFlags.has(entry.id) && (
<Badge
variant="outline"
className="text-xs font-normal shrink-0"
title={t('rattelse_badge_tooltip')}
>
{t('rattelse_badge')}
</Badge>
)}
</span>
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums rr-mask')}>
@@ -0,0 +1,357 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import { AccountNumber } from '@/components/ui/account-number'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { changeCorrectionLineAccount, getSelectableCorrectionCatalog } from '@/lib/bookkeeping/correction-line-account'
import { loadBasCatalog, type CatalogAccount } from '@/lib/bookkeeping/bas-catalog-client'
import { Loader2, Plus, Trash2 } from 'lucide-react'
import type { JournalEntry, JournalEntryLine, BASAccount } from '@/types'
interface NewLine {
account_number: string
debit_amount: string
credit_amount: string
line_description: string
}
interface Props {
entry: JournalEntry
open: boolean
onOpenChange: (open: boolean) => void
onCorrected: () => void
}
/**
* Inline line rättelse (BFL 5 kap 5 §): strike lines in a posted verifikat
* and add replacement lines in the SAME verifikat, without an
* ändringsverifikation. The struck originals stay visible (strikethrough)
* in the verifikat via the immutable rättelse log. Stays Swedish
* (verifikat surface, .claude/rules/i18n.md).
*/
export default function StrikeLinesDialog({ entry, open, onOpenChange, onCorrected }: Props) {
const { toast } = useToast()
const t = useTranslations('journal_detail')
const [accounts, setAccounts] = useState<BASAccount[]>([])
const [catalog, setCatalog] = useState<CatalogAccount[]>([])
const [accountsStatus, setAccountsStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const [strikeIds, setStrikeIds] = useState<Set<string>>(new Set())
const [newLines, setNewLines] = useState<NewLine[]>([])
const [isSubmitting, setIsSubmitting] = useState(false)
const activeAccounts = useMemo(
() => accounts.filter((account) => account.is_active),
[accounts],
)
const selectableCatalog = useMemo(
() => getSelectableCorrectionCatalog(accounts, catalog),
[accounts, catalog],
)
const originalLines = ((entry.lines || []) as JournalEntryLine[])
.slice()
.sort((a, b) => a.sort_order - b.sort_order)
useEffect(() => {
if (open) {
setStrikeIds(new Set())
setNewLines([])
void fetchAccounts()
}
}, [open, entry.id]) // eslint-disable-line react-hooks/exhaustive-deps
async function fetchAccounts() {
setAccountsStatus('loading')
try {
const [res, basCatalog] = await Promise.all([
fetch('/api/bookkeeping/accounts?active=false'),
loadBasCatalog(),
])
if (!res.ok) throw new Error(`accounts ${res.status}`)
const { data } = await res.json()
setAccounts(data || [])
setCatalog(basCatalog)
setAccountsStatus('ready')
} catch {
setAccounts([])
setCatalog([])
setAccountsStatus('error')
}
}
const toggleStrike = (lineId: string) => {
setStrikeIds((prev) => {
const next = new Set(prev)
if (next.has(lineId)) next.delete(lineId)
else next.add(lineId)
return next
})
}
const updateNewLine = (index: number, field: keyof NewLine, value: string) => {
setNewLines((prev) => prev.map((l, i) => (i === index ? { ...l, [field]: value } : l)))
}
const updateNewLineAccount = (index: number, accountNumber: string) => {
setNewLines((prev) => prev.map((line, lineIndex) => (
lineIndex === index
? changeCorrectionLineAccount(line, accountNumber, [...accounts, ...catalog])
: line
)))
}
const addNewLine = () => {
setNewLines((prev) => [...prev, { account_number: '', debit_amount: '', credit_amount: '', line_description: '' }])
}
const removeNewLine = (index: number) => {
setNewLines((prev) => prev.filter((_, i) => i !== index))
}
// Effective verifikat after the rättelse: remaining original lines + new lines.
const remaining = originalLines.filter((l) => !strikeIds.has(l.id))
const remainingDebit = remaining.reduce((sum, l) => sum + (Number(l.debit_amount) || 0), 0)
const remainingCredit = remaining.reduce((sum, l) => sum + (Number(l.credit_amount) || 0), 0)
const newDebit = newLines.reduce((sum, l) => sum + (parseFloat(l.debit_amount) || 0), 0)
const newCredit = newLines.reduce((sum, l) => sum + (parseFloat(l.credit_amount) || 0), 0)
const totalDebit = Math.round((remainingDebit + newDebit) * 100) / 100
const totalCredit = Math.round((remainingCredit + newCredit) * 100) / 100
const isBalanced = totalDebit === totalCredit && totalDebit > 0
const newLinesValid = newLines.every((l) => {
const debit = parseFloat(l.debit_amount) || 0
const credit = parseFloat(l.credit_amount) || 0
return l.account_number.length === 4 && debit >= 0 && credit >= 0 && (debit > 0) !== (credit > 0)
})
const hasChange = strikeIds.size > 0 || newLines.length > 0
const effectiveCount = remaining.length + newLines.length
const canSubmit = hasChange && newLinesValid && isBalanced && effectiveCount >= 2
async function handleSubmit() {
if (!canSubmit) return
setIsSubmitting(true)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${entry.id}/strike-lines`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
strike_line_ids: [...strikeIds],
lines: newLines.map((l) => ({
account_number: l.account_number,
debit_amount: parseFloat(l.debit_amount) || 0,
credit_amount: parseFloat(l.credit_amount) || 0,
line_description: l.line_description || undefined,
})),
}),
})
const result = await res.json()
if (!res.ok) {
const error = new Error('Failed to strike lines') as Error & { body?: unknown; status?: number }
error.body = result
error.status = res.status
throw error
}
toast({
title: 'Verifikationen rättad',
description: 'De strukna raderna visas överstrukna i verifikatet.',
})
onOpenChange(false)
onCorrected()
} catch (err) {
const anyErr = err as { body?: unknown; status?: number }
toast({
title: 'Kunde inte rätta verifikationen',
description: getErrorMessage(anyErr.body ?? err, { context: 'journal_entry', statusCode: anyErr.status }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Stryk rader i verifikatet</DialogTitle>
</DialogHeader>
<div className="rounded-lg bg-muted/50 border p-3 text-sm text-muted-foreground">
<p className="font-medium text-foreground mb-1">Rättelse i samma verifikat</p>
<p>
Felaktiga rader stryks och ersätts direkt i verifikatet, utan ändringsverifikation.
De strukna raderna förblir synliga (överstrukna) och rättelsen loggas med vem och när,
enligt bokföringslagen. Fungerar bara i öppna, olåsta perioder. Om månaden redan är
momsdeklarerad kan en ändring av momskonton påverka den inlämnade deklarationen.
</p>
</div>
{/* Original lines with strike checkboxes */}
<div className="space-y-1">
<p className="text-sm font-medium">Markera rader som ska strykas</p>
<div className="rounded-lg border divide-y">
{originalLines.map((line) => {
const struck = strikeIds.has(line.id)
// FX lines carry conversion data replacements cannot reproduce;
// the RPC rejects striking them, so the checkbox is disabled.
const isForeign = !!line.currency && line.currency !== 'SEK'
return (
<label
key={line.id}
className={`flex items-center gap-3 px-3 py-2 text-sm transition-colors ${isForeign ? 'opacity-60' : 'cursor-pointer hover:bg-secondary/60'}`}
title={isForeign ? 'Rader i utländsk valuta rättas med ändringsverifikat' : undefined}
>
<Checkbox
checked={struck}
disabled={isForeign}
onCheckedChange={() => toggleStrike(line.id)}
/>
<span className={`flex-1 min-w-0 ${struck ? 'line-through text-muted-foreground' : ''}`}>
<AccountNumber number={line.account_number} showName />
{line.line_description && (
<span className="text-muted-foreground ml-2">{line.line_description}</span>
)}
</span>
<span className={`tabular-nums shrink-0 ${struck ? 'line-through text-muted-foreground' : ''}`}>
{Number(line.debit_amount) > 0
? `${Number(line.debit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} D`
: `${Number(line.credit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} K`}
</span>
</label>
)
})}
</div>
</div>
{/* Replacement lines */}
<div className="space-y-2">
<div className="space-y-1">
<p className="text-sm font-medium">Ersättningsrader</p>
<p className="text-xs text-muted-foreground">
Lägg till de rader som ska gälla i stället. Verifikationen måste balansera efter rättelsen.
</p>
</div>
{accountsStatus !== 'ready' && (
<div className="flex items-center justify-between gap-3 rounded-lg border bg-muted/50 p-3 text-sm text-muted-foreground">
<span className="flex items-center gap-2">
{accountsStatus === 'loading' && <Loader2 className="h-4 w-4 animate-spin" />}
{accountsStatus === 'loading' ? t('accounts_loading') : t('accounts_load_failed')}
</span>
{accountsStatus === 'error' && (
<Button variant="outline" size="sm" onClick={() => void fetchAccounts()}>
{t('accounts_retry')}
</Button>
)}
</div>
)}
<div className="space-y-2">
{newLines.map((line, index) => (
<div key={index} className="space-y-2 sm:space-y-0 sm:grid sm:grid-cols-[1fr_1fr_120px_120px_auto] sm:gap-2 sm:items-start border-b sm:border-0 pb-3 sm:pb-0 last:border-0">
<div className="grid grid-cols-[1fr_auto] sm:contents gap-2">
<AccountCombobox
value={line.account_number}
accounts={activeAccounts}
catalog={selectableCatalog}
onChange={(v) => updateNewLineAccount(index, v)}
disabled={accountsStatus !== 'ready'}
/>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 min-h-[44px] min-w-[44px] sm:order-last"
onClick={() => removeNewLine(index)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<Input
value={line.line_description}
onChange={(e) => updateNewLine(index, 'line_description', e.target.value)}
placeholder="Beskrivning"
className="h-8"
/>
<div className="grid grid-cols-2 gap-2 sm:contents">
<Input
type="number"
value={line.debit_amount}
onChange={(e) => updateNewLine(index, 'debit_amount', e.target.value)}
placeholder="Debet"
className="h-8 text-right"
min={0}
step="0.01"
/>
<Input
type="number"
value={line.credit_amount}
onChange={(e) => updateNewLine(index, 'credit_amount', e.target.value)}
placeholder="Kredit"
className="h-8 text-right"
min={0}
step="0.01"
/>
</div>
</div>
))}
</div>
<Button variant="outline" size="sm" onClick={addNewLine}>
<Plus className="h-4 w-4 mr-1" />
Lägg till rad
</Button>
</div>
{/* Effective balance after the rättelse */}
<div className="flex justify-end gap-6 text-sm pt-2 border-t">
<div>
<span className="text-muted-foreground mr-2">Debet efter rättelse:</span>
<span className={!isBalanced ? 'text-destructive font-medium' : 'font-medium'}>
{totalDebit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</span>
</div>
<div>
<span className="text-muted-foreground mr-2">Kredit efter rättelse:</span>
<span className={!isBalanced ? 'text-destructive font-medium' : 'font-medium'}>
{totalCredit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</span>
</div>
</div>
{hasChange && !isBalanced && (
<p className="text-sm text-destructive">
Debet och kredit måste vara lika och större än 0 efter rättelsen.
</p>
)}
{hasChange && isBalanced && effectiveCount < 2 && (
<p className="text-sm text-destructive">
Verifikationen måste ha minst två rader efter rättelsen. Använd Återför (storno) för att
makulera hela verifikatet.
</p>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
Avbryt
</Button>
<Button onClick={handleSubmit} disabled={!canSubmit || isSubmitting}>
{isSubmitting ? 'Rättar...' : 'Rätta verifikatet'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+12 -2
View File
@@ -781,8 +781,18 @@ export function ResultatrapportView({ periodId, dateRange, dimensionFilter = nul
<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>
<th
className="text-right font-medium px-4 py-2 w-32 tabular-nums"
title={`${data.period.start} till ${data.period.end}`}
>
Innevarande
</th>
<th
className="text-right font-medium px-4 py-2 w-32 tabular-nums"
title={hasPrior ? `${data.prior_period!.start} till ${data.prior_period!.end}` : undefined}
>
Föregående
</th>
</tr>
</thead>
<tbody>
@@ -1,7 +1,11 @@
'use client'
import { useEffect, useState } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Card, CardContent } from '@/components/ui/card'
import { Switch } from '@/components/ui/switch'
import { AgentMemoryPanel } from '@/components/settings/AgentMemoryPanel'
import { AgentSkillsPanel } from '@/components/settings/AgentSkillsPanel'
import { AgentKnowledgePanel } from '@/components/agent-knowledge/AgentKnowledgePanel'
@@ -31,24 +35,92 @@ export function AssistantSettingsContent() {
}
return (
<Tabs value={view} onValueChange={setView} className="space-y-6">
<TabsList>
<TabsTrigger value="knowledge">Kunskap</TabsTrigger>
<TabsTrigger value="memory">Minne</TabsTrigger>
<TabsTrigger value="skills">Kompetens</TabsTrigger>
</TabsList>
<div className="space-y-8">
<Tabs value={view} onValueChange={setView} className="space-y-6">
<TabsList>
<TabsTrigger value="knowledge">Kunskap</TabsTrigger>
<TabsTrigger value="memory">Minne</TabsTrigger>
<TabsTrigger value="skills">Kompetens</TabsTrigger>
</TabsList>
{/* Radix unmounts the inactive panel, so each panel's data is fetched
lazily the first time its tab is opened. */}
<TabsContent value="knowledge">
<AgentKnowledgePanel />
</TabsContent>
<TabsContent value="memory">
<AgentMemoryPanel />
</TabsContent>
<TabsContent value="skills">
<AgentSkillsPanel />
</TabsContent>
</Tabs>
{/* Radix unmounts the inactive panel, so each panel's data is fetched
lazily the first time its tab is opened. */}
<TabsContent value="knowledge">
<AgentKnowledgePanel />
</TabsContent>
<TabsContent value="memory">
<AgentMemoryPanel />
</TabsContent>
<TabsContent value="skills">
<AgentSkillsPanel />
</TabsContent>
</Tabs>
<FabVisibilityCard />
</div>
)
}
// Per-user toggle for the floating assistant button bottom-right. The value
// lives on user_preferences (server-rendered into the dashboard layout), so
// a successful save triggers router.refresh() to make the button react
// immediately instead of on next navigation.
function FabVisibilityCard() {
const t = useTranslations('settings_assistant')
const router = useRouter()
// null = not yet loaded (switch disabled meanwhile)
const [hideFab, setHideFab] = useState<boolean | null>(null)
const [saving, setSaving] = useState(false)
useEffect(() => {
let cancelled = false
fetch('/api/user/preferences')
.then((res) => res.json())
.then((body) => {
if (!cancelled) setHideFab(Boolean(body?.data?.hide_assistant_fab))
})
.catch(() => {
if (!cancelled) setHideFab(false)
})
return () => {
cancelled = true
}
}, [])
async function handleToggle(showFab: boolean) {
const nextHide = !showFab
const previous = hideFab
setHideFab(nextHide)
setSaving(true)
try {
const res = await fetch('/api/user/preferences', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ hide_assistant_fab: nextHide }),
})
if (!res.ok) throw new Error('save failed')
router.refresh()
} catch {
setHideFab(previous)
} finally {
setSaving(false)
}
}
return (
<Card>
<CardContent className="p-6 flex items-center justify-between gap-4">
<div className="space-y-1">
<p className="text-sm font-medium">{t('fab_title')}</p>
<p className="text-sm text-muted-foreground">{t('fab_description')}</p>
</div>
<Switch
checked={hideFab === null ? true : !hideFab}
onCheckedChange={handleToggle}
disabled={hideFab === null || saving}
aria-label={t('fab_title')}
/>
</CardContent>
</Card>
)
}
@@ -23,6 +23,7 @@ import {
FileText,
Landmark,
Link2,
FileSearch,
Loader2,
MoreHorizontal,
Paperclip,
@@ -55,6 +56,11 @@ interface TransactionHistoryListProps {
onOpenCategoryDialog: (transaction: TransactionWithInvoice) => void
/** Open the attach-underlag dialog (pin an inbox doc / fresh upload). */
onOpenAttachDocument?: (transaction: TransactionWithInvoice) => void
/** Open the match-against-existing-voucher dialog. Unbooked rows can end up
* here (not in the inbox) when is_business is already set, e.g. after a
* voucher was removed without a full uncategorize; without this item such
* rows have no path back to voucher matching. */
onOpenMatchVoucher?: (transaction: TransactionWithInvoice) => void
onDelete?: (id: string) => void
onSkvBokfor?: (row: StoredSkattekontoTransaction) => void
onSkvMatch?: (row: StoredSkattekontoTransaction) => void
@@ -78,6 +84,7 @@ export default function TransactionHistoryList({
onOpenMatchDialog,
onOpenCategoryDialog,
onOpenAttachDocument,
onOpenMatchVoucher,
onDelete,
onSkvBokfor,
onSkvMatch,
@@ -203,6 +210,7 @@ export default function TransactionHistoryList({
onOpenMatchDialog={onOpenMatchDialog}
onOpenCategoryDialog={onOpenCategoryDialog}
onOpenAttachDocument={onOpenAttachDocument}
onOpenMatchVoucher={onOpenMatchVoucher}
onDelete={onDelete}
/>
) : (
@@ -243,6 +251,7 @@ function BankHistoryRow({
onOpenMatchDialog,
onOpenCategoryDialog,
onOpenAttachDocument,
onOpenMatchVoucher,
onDelete,
}: {
transaction: TransactionWithInvoice
@@ -250,6 +259,7 @@ function BankHistoryRow({
onOpenMatchDialog: (transaction: TransactionWithInvoice) => void
onOpenCategoryDialog: (transaction: TransactionWithInvoice) => void
onOpenAttachDocument?: (transaction: TransactionWithInvoice) => void
onOpenMatchVoucher?: (transaction: TransactionWithInvoice) => void
onDelete?: (id: string) => void
}) {
const t = useTranslations('tx_history')
@@ -275,8 +285,11 @@ function BankHistoryRow({
const hasJeDoc = jeStatus === 'has'
const missingUnderlag = isBooked && !transaction.document_id && jeStatus === 'missing'
const showAttachItem = canWrite && !!onOpenAttachDocument
// Same affordance as the inbox card: an unbooked row may need to be linked
// to an already-booked voucher (e.g. the other leg of a transfer).
const showMatchVoucherItem = canWrite && !isBooked && !!onOpenMatchVoucher
const showOverflowMenu =
hasInvoiceMatch || (canDelete && !!onDelete) || (isBooked && canWrite) || showAttachItem
hasInvoiceMatch || (canDelete && !!onDelete) || (isBooked && canWrite) || showAttachItem || showMatchVoucherItem
const isPrivate = transaction.is_business === false
const categoryLabel =
@@ -394,6 +407,12 @@ function BankHistoryRow({
})}
</DropdownMenuItem>
)}
{showMatchVoucherItem && (
<DropdownMenuItem onSelect={() => onOpenMatchVoucher!(transaction)}>
<FileSearch className="h-3.5 w-3.5" />
{t('match_voucher')}
</DropdownMenuItem>
)}
{/* Attach underlag: available on both booked rows (the route
propagates the doc onto the verifikation) and unbooked. */}
{showAttachItem && (
@@ -413,7 +432,7 @@ function BankHistoryRow({
)}
{canDelete && onDelete && (
<>
{(hasInvoiceMatch || showAttachItem) && <DropdownMenuSeparator />}
{(hasInvoiceMatch || showAttachItem || showMatchVoucherItem) && <DropdownMenuSeparator />}
<DropdownMenuItem
onSelect={() => onDelete(transaction.id)}
className="text-destructive focus:text-destructive"

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