fix: OAuth callback redirect and timeout resilience (#43)

* fix: include reversed entries in all reports (general ledger, trial balance, VAT, SIE, NE, INK2)

Reversed entries (storno) must appear alongside their original posted entries
in reports for a complete audit trail. Previously, filtering by status='posted'
excluded them, causing discrepancies when corrections had been made.

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

* feat: semi-manual invoice payment booking with editable journal lines

When marking an invoice as paid, users now see a dialog where they can:
- Choose which bank/cash account the payment goes to (1910, 1920, 1930, etc.)
- Review and edit the proposed journal entry lines before committing
- The happy path remains fast — lines are pre-filled correctly

Implementation:
- Pure proposePaymentLines() function for line computation (accrual + cash)
- PaymentBookingDialog with AccountCombobox, balance validation, date picker
- API accepts optional custom lines, falls back to auto-generation without them
- 18 tests (8 unit + 10 API) all passing

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

* fix: address Greptile review — validation fallback, balance check, error handling

- P1: Return 400 on invalid body instead of silently falling back to
  auto-generated lines (split JSON parse from schema validation)
- P1: Add server-side balance check for custom lines before committing
  (debit must equal credit, totalDebit > 0)
- P2: Wrap PaymentBookingDialog init() in try/catch with toast on
  failure and auto-close instead of silent empty state
- Add 2 new tests: unbalanced lines → 400, invalid schema → 400

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

* fix: OAuth callback redirect for local dev and timeout resilience

- Pass redirectUri dynamically from NEXT_PUBLIC_APP_URL so OAuth
  callbacks work on localhost (not just production)
- Encode consentId/provider in OAuth state (base64url JSON) so the
  callback doesn't depend on session storage
- Add skipAuth flag to extension API routes for OAuth callbacks
  (external provider redirects have no user session cookie)
- Wrap AbortError in descriptive timeout messages in arcim-client
- Make preview endpoint resilient to partial failures (company info
  and SIE fetch are individually non-blocking)
- Simplify login page (remove unused magic link auth mode)

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

* fix: create journal entry before marking invoice as paid

Move journal entry creation before the invoice status update so that
if accounting fails, the invoice is not permanently marked paid without
a corresponding entry. Previously the error was silently swallowed.

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

* fix: update mark-paid tests for journal-first ordering

Reorder mock queue to match new flow (settings before update), update
failure test to expect 500 instead of silent success, add try-catch
with proper error response in route handler.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-03-17 17:31:04 +01:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 8976cd812d
commit bac49b6ee6
7 changed files with 265 additions and 283 deletions
+39 -19
View File
@@ -71,6 +71,45 @@ async function handleRequest(
return NextResponse.json({ error: 'Extension not found' }, { status: 404 })
}
// Match route BEFORE auth so we can check skipAuth (e.g. OAuth callbacks)
let matchedRoute: ApiRouteDefinition | null = null
let extractedParams: Record<string, string> = {}
for (const route of extension.apiRoutes) {
if (route.method !== method) continue
const routeParams = matchPath(route.path, routePath)
if (routeParams !== null) {
matchedRoute = route
extractedParams = routeParams
break
}
}
if (!matchedRoute) {
return NextResponse.json({ error: 'Route not found' }, { status: 404 })
}
// For skipAuth routes (e.g. OAuth callbacks from external providers),
// skip user auth, toggle check, and AI consent — dispatch immediately
if (matchedRoute.skipAuth) {
let handlerRequest = request
if (Object.keys(extractedParams).length > 0) {
const url = new URL(request.url)
for (const [key, value] of Object.entries(extractedParams)) {
url.searchParams.set(`_${key}`, value)
}
handlerRequest = new Request(url.toString(), {
method: request.method,
headers: request.headers,
body: request.body,
// @ts-expect-error -- duplex needed for streaming body
duplex: 'half',
})
}
return matchedRoute.handler(handlerRequest)
}
// Auth check
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
@@ -97,25 +136,6 @@ async function handleRequest(
}
}
// Find matching route (supports :param patterns)
let matchedRoute: ApiRouteDefinition | null = null
let extractedParams: Record<string, string> = {}
for (const route of extension.apiRoutes) {
if (route.method !== method) continue
const params = matchPath(route.path, routePath)
if (params !== null) {
matchedRoute = route
extractedParams = params
break
}
}
if (!matchedRoute) {
return NextResponse.json({ error: 'Route not found' }, { status: 404 })
}
// If path params were extracted, create a new Request with them as search params
let handlerRequest = request
if (Object.keys(extractedParams).length > 0) {
@@ -114,10 +114,10 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
// Fetch invoice
enqueue({ data: invoice, error: null })
// Fetch company settings (now before update due to journal-first ordering)
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
// Update invoice status
enqueue({ data: null, error: null })
// Fetch company settings
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
mockCreateInvoicePaymentJournalEntry.mockResolvedValue({ id: 'je-1' })
@@ -154,8 +154,8 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
})
enqueue({ data: invoice, error: null })
enqueue({ data: null, error: null })
enqueue({ data: { accounting_method: 'cash', entity_type: 'enskild_firma' }, error: null })
enqueue({ data: null, error: null })
mockCreateInvoiceCashEntry.mockResolvedValue({ id: 'je-2' })
@@ -178,25 +178,19 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
)
})
it('returns success with null journal_entry_id when journal entry creation fails', async () => {
it('returns 500 when journal entry creation fails (invoice not marked paid)', async () => {
const invoice = makeInvoice({ id: 'inv-1', status: 'sent', total: 12500 })
enqueue({ data: invoice, error: null })
enqueue({ data: null, error: null })
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
mockCreateInvoicePaymentJournalEntry.mockRejectedValue(new Error('Period locked'))
mockCreateInvoicePaymentJournalEntry.mockRejectedValueOnce(new Error('Period locked'))
const request = createMockRequest('/api/invoices/inv-1/mark-paid', { method: 'POST' })
const response = await POST(request, createMockRouteParams({ id: 'inv-1' }))
const { status, body } = await parseJsonResponse<{
success: boolean
journal_entry_id: string | null
}>(response)
const { status } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.journal_entry_id).toBeNull()
expect(status).toBe(500)
})
it('uses custom lines when provided instead of auto-generating', async () => {
@@ -204,10 +198,10 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
// Fetch invoice
enqueue({ data: invoice, error: null })
// Fetch company settings (before update — journal-first ordering)
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
// Update invoice status
enqueue({ data: null, error: null })
// Fetch company settings
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
mockFindFiscalPeriod.mockResolvedValue('fp-1')
mockCreateJournalEntry.mockResolvedValue({ id: 'je-custom' })
@@ -253,10 +247,6 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
// Fetch invoice
enqueue({ data: invoice, error: null })
// Update invoice status
enqueue({ data: null, error: null })
// Fetch company settings
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
const unbalancedLines = [
{ account_number: '1920', debit_amount: 12500, credit_amount: 0 },
@@ -309,8 +299,8 @@ describe('POST /api/invoices/[id]/mark-paid', () => {
})
enqueue({ data: invoice, error: null })
enqueue({ data: null, error: null })
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
enqueue({ data: null, error: null })
mockCreateInvoicePaymentJournalEntry.mockResolvedValue({ id: 'je-auto' })
+77 -69
View File
@@ -79,7 +79,83 @@ export async function POST(
const now = new Date().toISOString()
const paymentDate = bodyPaymentDate || now.split('T')[0]
// Update status to paid
// Fetch accounting method
const { data: settings } = await supabase
.from('company_settings')
.select('accounting_method, entity_type')
.eq('user_id', user.id)
.single()
const accountingMethod = settings?.accounting_method || 'accrual'
const entityType = (settings?.entity_type as EntityType) || 'enskild_firma'
// Create journal entry FIRST — only mark paid if accounting succeeds
const isRealInvoice = !invoice.document_type || invoice.document_type === 'invoice'
let journalEntryId: string | null = null
if (isRealInvoice) {
try {
if (customLines) {
// Server-side balance validation — never commit imbalanced entries
const totalDebit = customLines.reduce((s, l) => s + l.debit_amount, 0)
const totalCredit = customLines.reduce((s, l) => s + l.credit_amount, 0)
if (Math.round((totalDebit - totalCredit) * 100) !== 0 || totalDebit <= 0) {
return NextResponse.json(
{ error: 'Verifikationsraderna är inte balanserade (debet ≠ kredit)' },
{ status: 400 }
)
}
// User-provided lines from PaymentBookingDialog
const fiscalPeriodId = await findFiscalPeriod(supabase, user.id, paymentDate)
if (!fiscalPeriodId) {
return NextResponse.json(
{ error: 'Ingen öppen räkenskapsperiod för betalningsdatumet' },
{ status: 400 }
)
}
const sourceType = accountingMethod === 'accrual' ? 'invoice_paid' : 'invoice_cash_payment'
const input: CreateJournalEntryInput = {
fiscal_period_id: fiscalPeriodId,
entry_date: paymentDate,
description: `Betalning faktura ${invoice.invoice_number}`,
source_type: sourceType,
source_id: invoice.id,
lines: customLines,
}
const journalEntry = await createJournalEntry(supabase, user.id, input)
journalEntryId = journalEntry?.id ?? null
} else if (accountingMethod === 'accrual') {
// Faktureringsmetoden: clear receivable (Debit 1930, Credit 1510)
const journalEntry = await createInvoicePaymentJournalEntry(
supabase,
user.id,
invoice as Invoice,
paymentDate,
exchangeRateDifference
)
journalEntryId = journalEntry?.id ?? null
} else {
// Kontantmetoden: combined revenue entry (Debit 1930, Credit 30xx, Credit 26xx)
const journalEntry = await createInvoiceCashEntry(
supabase,
user.id,
invoice as Invoice,
paymentDate,
entityType
)
journalEntryId = journalEntry?.id ?? null
}
} catch (err) {
console.error('Failed to create payment journal entry:', err)
return NextResponse.json(
{ error: 'Kunde inte bokföra betalningen' },
{ status: 500 }
)
}
}
// Update status to paid — only after journal entry succeeds
const { error: updateError } = await supabase
.from('invoices')
.update({
@@ -94,74 +170,6 @@ export async function POST(
return NextResponse.json({ error: 'Kunde inte uppdatera status' }, { status: 500 })
}
// Fetch accounting method
const { data: settings } = await supabase
.from('company_settings')
.select('accounting_method, entity_type')
.eq('user_id', user.id)
.single()
const accountingMethod = settings?.accounting_method || 'accrual'
const entityType = (settings?.entity_type as EntityType) || 'enskild_firma'
// Only create journal entries for real invoices (not proformas or delivery notes)
const isRealInvoice = !invoice.document_type || invoice.document_type === 'invoice'
let journalEntryId: string | null = null
if (isRealInvoice) {
try {
if (customLines) {
// Server-side balance validation — never commit imbalanced entries
const totalDebit = customLines.reduce((s, l) => s + l.debit_amount, 0)
const totalCredit = customLines.reduce((s, l) => s + l.credit_amount, 0)
if (Math.round((totalDebit - totalCredit) * 100) !== 0 || totalDebit <= 0) {
return NextResponse.json(
{ error: 'Verifikationsraderna är inte balanserade (debet ≠ kredit)' },
{ status: 400 }
)
}
// User-provided lines from PaymentBookingDialog
const fiscalPeriodId = await findFiscalPeriod(supabase, user.id, paymentDate)
if (fiscalPeriodId) {
const sourceType = accountingMethod === 'accrual' ? 'invoice_paid' : 'invoice_cash_payment'
const input: CreateJournalEntryInput = {
fiscal_period_id: fiscalPeriodId,
entry_date: paymentDate,
description: `Betalning faktura ${invoice.invoice_number}`,
source_type: sourceType,
source_id: invoice.id,
lines: customLines,
}
const journalEntry = await createJournalEntry(supabase, user.id, input)
journalEntryId = journalEntry?.id ?? null
}
} else if (accountingMethod === 'accrual') {
// Faktureringsmetoden: clear receivable (Debit 1930, Credit 1510)
const journalEntry = await createInvoicePaymentJournalEntry(
supabase,
user.id,
invoice as Invoice,
paymentDate,
exchangeRateDifference
)
journalEntryId = journalEntry?.id ?? null
} else {
// Kontantmetoden: combined revenue entry (Debit 1930, Credit 30xx, Credit 26xx)
const journalEntry = await createInvoiceCashEntry(
supabase,
user.id,
invoice as Invoice,
paymentDate,
entityType
)
journalEntryId = journalEntry?.id ?? null
}
} catch (err) {
console.error('Failed to create payment journal entry on mark-paid:', err)
}
}
return NextResponse.json({
success: true,
status: 'paid',