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:
co-authored by
Claude Opus 4.8
parent
db8983ba9e
commit
43925bc2d3
@@ -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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, {
|
||||
|
||||
Reference in New Issue
Block a user