fix(import): SIE bulk-delete on service client + provider/reporting/b… (#724)

* fix(import): SIE bulk-delete on service client + provider/reporting/banking fixes

Rebuilt branch onto main as a single commit.

- import: run SIE bulk-delete RPCs on the service client to escape the 8s
  statement_timeout; undo_sie_import now takes an explicit actor (p_user_id)
  so its owner/admin gate works when auth.uid() is NULL on the service
  client (migration 20260624120000) + pg-real regression test
- providers: distinguish missing Fortnox license from expired connection;
  provider_consent_tokens PK regression test
- reports: include unmapped BAS expense groups in the income statement
- enable-banking: reconnect closed/expired bank sessions in place
- bookkeeping: surface linked invoices as underlag on the verifikat view
- scripts: track BL cleanup/diagnostic tooling; data files (*.csv) are
  git-ignored and consentId is now a required arg with no silent default

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

* fix(import): add Cache-Control header to journal entry references response

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-06-14 23:40:26 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent db8983ba9e
commit 43925bc2d3
37 changed files with 2456 additions and 1152 deletions
+64 -18
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 } from 'lucide-react'
import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock, MessageSquare, Pencil, Check, X, Copy, ChevronDown, CalendarClock, FileText, Link2 } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -27,6 +27,7 @@ import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { JournalEntry, JournalEntryLine } from '@/types'
import type { UnderlagReference } from '@/lib/core/bookkeeping/journal-entry-references'
export default function JournalEntryDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
@@ -46,6 +47,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
const [isCommitting, setIsCommitting] = useState(false)
const [isLastInSeries, setIsLastInSeries] = useState(false)
const [attachmentCount, setAttachmentCount] = useState(0)
const [references, setReferences] = useState<UnderlagReference[]>([])
const [editingNotes, setEditingNotes] = useState(false)
const [notesValue, setNotesValue] = useState('')
const [savingNotes, setSavingNotes] = useState(false)
@@ -54,16 +56,27 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
setIsLoading(true)
setError(null)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${id}/chain`)
if (!res.ok) {
const { error: msg } = await res.json()
const [chainRes, refsRes] = await Promise.all([
fetch(`/api/bookkeeping/journal-entries/${id}/chain`),
fetch(`/api/bookkeeping/journal-entries/${id}/references`),
])
if (!chainRes.ok) {
const { error: msg } = await chainRes.json()
setError(msg || t('error_load_failed'))
return
}
const { data } = await res.json()
const { data } = await chainRes.json()
setEntry(data.entry)
setChain(data.chain)
setIsLastInSeries(data.is_last_in_series ?? false)
// Underlag references (linked invoices) — best-effort; the verifikat still
// renders if this fails, it just falls back to documents-only.
if (refsRes.ok) {
const { data: refData } = await refsRes.json()
setReferences(refData?.references ?? [])
} else {
setReferences([])
}
} catch {
setError(t('error_load_failed'))
} finally {
@@ -405,19 +418,27 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
<CardTitle className="text-sm font-medium text-muted-foreground">{t('attachments_title')}</CardTitle>
</CardHeader>
<CardContent className="text-sm">
<div className="flex items-center gap-2">
{attachmentCount > 0 ? (
<>
<Paperclip className="h-4 w-4 text-muted-foreground" />
<span>{t('attachments_count', { count: attachmentCount })}</span>
</>
) : (
<>
<AlertTriangle className="h-4 w-4 text-warning-foreground" />
<span className="text-muted-foreground">{t('no_attachments')}</span>
</>
)}
</div>
{attachmentCount === 0 && references.length === 0 ? (
<div className="flex items-center gap-2">
<AlertTriangle className="h-4 w-4 text-warning-foreground" />
<span className="text-muted-foreground">{t('no_attachments')}</span>
</div>
) : (
<div className="space-y-1">
{attachmentCount > 0 && (
<div className="flex items-center gap-2">
<Paperclip className="h-4 w-4 text-muted-foreground" />
<span>{t('attachments_count', { count: attachmentCount })}</span>
</div>
)}
{references.length > 0 && (
<div className="flex items-center gap-2">
<Link2 className="h-4 w-4 text-muted-foreground" />
<span>{t('references_count', { count: references.length })}</span>
</div>
)}
</div>
)}
</CardContent>
</Card>
</div>
@@ -569,6 +590,31 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
<CardTitle className="text-sm font-medium">{t('attachments_title')}</CardTitle>
</CardHeader>
<CardContent>
{references.length > 0 && (
<div className="mb-4 space-y-2">
<div>
<h4 className="text-sm font-medium">{t('references_title')}</h4>
<p className="text-xs text-muted-foreground">{t('references_subtitle')}</p>
</div>
<ul className="space-y-1">
{references.map((ref) => (
<li key={`${ref.type}-${ref.id}`}>
<Link
href={ref.type === 'invoice' ? `/invoices/${ref.id}` : `/supplier-invoices/${ref.id}`}
className="flex items-center gap-2 text-sm py-1.5 px-2 rounded bg-muted/50 hover:bg-secondary/60 transition-colors"
>
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="truncate">
{ref.type === 'invoice'
? t('reference_invoice', { number: ref.number })
: t('reference_supplier_invoice', { number: ref.number })}
</span>
</Link>
</li>
))}
</ul>
</div>
)}
<JournalEntryAttachments
journalEntryId={entry.id}
onCountChange={setAttachmentCount}
@@ -0,0 +1,30 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getJournalEntryUnderlagReferences } from '@/lib/core/bookkeeping/journal-entry-references'
/**
* GET /api/bookkeeping/journal-entries/[id]/references
*
* Resolves the verifikation's followable underlag references — the linked
* customer / supplier invoices that identify the affärshändelse. Lets the
* verifikat view make the verifieringskedja traceable from the verifikat side,
* not only from the invoice side (BFL 5 kap 7§ — hänvisning till underlag;
* BFNAR 2013:2). Read-only.
*
* An id that doesn't belong to the active company resolves to no references
* (every underlying query is company-scoped), so this neither leaks nor 404s.
*
* Marked private, no-store: the payload carries invoice numbers (financial
* data), so no shared proxy / CDN may cache it across users or companies.
*/
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'journal_entry.references',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await params
const references = await getJournalEntryUnderlagReferences(supabase, companyId, id)
return NextResponse.json(
{ data: { references } },
{ headers: { 'Cache-Control': 'private, no-store' } },
)
},
)
@@ -34,7 +34,7 @@ function makeRequest(params: Record<string, string>) {
function mockChain(result: { data?: unknown; error?: unknown }) {
const chain: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'single', 'update', 'order', 'limit']) {
for (const m of ['select', 'eq', 'in', 'single', 'update', 'order', 'limit']) {
chain[m] = vi.fn().mockReturnValue(chain)
}
chain.single = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
@@ -49,12 +49,14 @@ export async function GET(request: Request) {
try {
const supabase = await createServiceClient()
// Fetch connection details for logging before updating
// Fetch connection details for logging before updating. Match by
// oauth_state across pending/expired/error so an in-place reconnect
// (which stays 'expired' during the round-trip) is also handled.
const { data: pendingConn } = await supabase
.from('bank_connections')
.select('id, user_id, bank_name')
.eq('oauth_state', state)
.eq('status', 'pending')
.in('status', ['pending', 'expired', 'error'])
.single()
if (pendingConn) {
@@ -66,9 +68,16 @@ export async function GET(request: Request) {
error_description: errorDescription,
})
// If the bank reports a session-expiry during authorization itself,
// mark the row 'expired' (not generic 'error') so the settings panel
// surfaces the reconnect button rather than a dead-end error state.
const isSessionExpiry = /session.?expired|expired.?session|closed.?session|session.?closed|invalid.?session|session.?not.?found/i.test(
`${error} ${errorDescription ?? ''}`
)
await supabase
.from('bank_connections')
.update({ status: 'error', error_message: errorMessage, oauth_state: null })
.update({ status: isSessionExpiry ? 'expired' : 'error', error_message: errorMessage, oauth_state: null })
.eq('id', pendingConn.id)
// Include bank name and error code in redirect so the UI can offer PSU type retry
@@ -102,12 +111,16 @@ export async function GET(request: Request) {
const supabase = await createServiceClient()
try {
// Look up pending connection by oauth_state (CSRF-safe)
// Look up the connection awaiting this callback by oauth_state (CSRF-safe).
// oauth_state is a single-use random token cleared after use, so it uniquely
// identifies the row regardless of status. Accept 'expired'/'error' too: an
// in-place reconnect keeps the row in 'expired' during the round-trip (so
// the nightly stale-'pending' cleanup can't delete an established row).
const { data: pendingConnection, error: findError } = await supabase
.from('bank_connections')
.select('id, user_id, company_id')
.eq('oauth_state', state)
.eq('status', 'pending')
.in('status', ['pending', 'expired', 'error'])
.single()
if (findError || !pendingConnection) {
@@ -278,7 +291,7 @@ export async function GET(request: Request) {
.from('bank_connections')
.update({ status: 'error', error_message: error instanceof Error ? error.message : 'Connection failed', oauth_state: null })
.eq('oauth_state', state)
.eq('status', 'pending')
.in('status', ['pending', 'expired', 'error'])
} catch (cleanupError) {
console.error('[enable-banking] Callback cleanup failed', {
cleanupError: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
@@ -2,7 +2,7 @@ import { createClient, type SupabaseClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { syncAccountTransactions } from '@/extensions/general/enable-banking/lib/sync'
import { runReconciliation } from '@/lib/reconciliation/bank-reconciliation'
import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/extensions/general/enable-banking/lib/api-client'
import { isConsentExpiringSoon, getDaysUntilExpiry, SessionExpiredError } from '@/extensions/general/enable-banking/lib/api-client'
import { getEmailService } from '@/lib/email/service'
import {
generateConsentExpiryEmailHtml,
@@ -266,10 +266,19 @@ export const GET = withCronContext('cron.bank_sync', async (_request, ctx) => {
lastSyncedAt: connection.last_synced_at,
})
// Persist error status on sync failure
// A dead PSD2 session (closed/expired/invalid consent) is a re-auth
// condition, not a transient failure — flip it to 'expired' (same state
// the consent-elapsed branch uses) so the UI offers a reconnect instead
// of a retry. Other errors stay 'error'.
const isSessionDead = error instanceof SessionExpiredError
const failureStatus = isSessionDead ? 'expired' : 'error'
const failureMessage = isSessionDead
? 'Bankanslutningen har löpt ut. Förnya anslutningen för att fortsätta synka.'
: message
await supabase
.from('bank_connections')
.update({ status: 'error', error_message: message })
.update({ status: failureStatus, error_message: failureMessage })
.eq('id', connection.id)
results.push({
@@ -279,7 +288,7 @@ export const GET = withCronContext('cron.bank_sync', async (_request, ctx) => {
imported: 0,
duplicates: 0,
errors: 1,
status: 'error',
status: failureStatus,
})
}
}
+2 -2
View File
@@ -16,10 +16,10 @@ export const DELETE = withRouteContext(
'sie_import.undo',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const { supabase, companyId, user, log, requestId } = ctx
const opLog = log.child({ sieImportId: id })
const result = await undoSIEImport(supabase, companyId!, id)
const result = await undoSIEImport(supabase, companyId!, id, user.id)
if (!result.success) {
return errorResponseFromCode('SIE_UNDO_FAILED', opLog, {