Logs/improved logging (#398)

* feat(mcp): add create_transactions tool with /pending approval gate

New MCP tool gnubok_create_transactions stages 1–10 transactions per call
as pending_operations of type create_transaction (risk: medium). Each item
becomes its own card on /pending; on confirm, the executor inserts the row
into transactions with import_source='mcp' so MCP-staged ingestion is
distinguishable from PSD2 sync. Designed for skill workflows that pull
external data (e.g., Airtable) and want the user to gate the writes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(bas): strip concatenated group headers from corrupted account names

A chart-data import bug had glued the next group's header onto the last
account in each preceding group across all eight bas-data class files
(e.g. account 2670 read "Utgående moms på försäljning inom EU, OSS 27
PERSONALENS SKATTER, AVGIFTER OCH LÖNEAVDRAG"). The corrupted names
surface in transaction dropdowns, ledgers, SIE exports and årsredovisning,
and risk VAT miscategorization on the OSS (2670) and blandad-verksamhet
(6999) accounts specifically.

- Cleans 69 account_name and 64 description fields across class-1..8 files
- Adds a regression test asserting no name contains a concatenated header
- Ships an idempotent safety-net migration that updates already-seeded
  chart_of_accounts rows, gated on the corrupted string so user
  customizations are preserved

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(errors): add structured error codes and handling for various operations

- Introduced a new structured error registry in `structured-errors.ts` to standardize error handling across the application.
- Added Swedish and English messages for various error scenarios, including validation, authorization, and bookkeeping errors.
- Implemented a client-side error toast in `use-error-toast.ts` to display user-friendly error messages with remediation hints.
- Created a wrapper for recording operation outcomes in `record-operation.ts`, enhancing audit capabilities for operations.
- Developed a provider call wrapper in `with-provider-call.ts` to handle external HTTP calls with structured logging and error mapping.
- Added a new SQL migration to extend the processing history with new event types and aggregate types for better operational telemetry.

* Refactor supplier API routes to use context-based logging and error handling

- Replaced direct Supabase client usage in GET and POST routes with context-based approach using `withRouteContext`.
- Enhanced error handling to provide structured error responses for supplier creation and listing.
- Updated logging to include request IDs for better traceability.
- Introduced new error codes for supplier-related operations.
- Refactored tax deadlines cron job to utilize context and improved error handling.
- Updated ESLint configuration to enforce logging practices across API and lib directories.
- Enhanced arcim migration extension with structured error handling and logging.
- Added classification for provider errors to improve user-facing error messages.
- Introduced request ID in extension context for better log correlation.

* fix(route-context): update DynamicParams type for improved type safety in route handlers

* feat(transactions): add 'create_transaction' operation to PendingOperationType

* fix(route): ensure companyId is non-nullable in loadAndDeriveAbsence function

* fix(route-context): ensure companyId is always non-null by short-circuiting with COMPANY_CONTEXT_MISSING

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This commit is contained in:
Mattsson
2026-05-06 11:12:02 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 94f15b9c6c
commit 5725c25bf1
102 changed files with 7887 additions and 5245 deletions
+2 -1
View File
@@ -15,6 +15,7 @@ import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialo
import CorrectionChain from '@/components/bookkeeping/CorrectionChain'
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'
export default function JournalEntryDetailPage({ params }: { params: Promise<{ id: string }> }) {
@@ -89,7 +90,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
})
router.push('/bookkeeping')
} else {
toast({ title: 'Kunde inte radera', description: result.error, variant: 'destructive' })
toast({ title: 'Kunde inte radera', description: getErrorMessage(result, { context: 'journal_entry' }), variant: 'destructive' })
setShowDeleteConfirm(false)
}
} catch {
+2 -1
View File
@@ -8,6 +8,7 @@ import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { Plus, Search, Users, Lock } from 'lucide-react'
import CustomerForm from '@/components/customers/CustomerForm'
import { EmptyCustomers } from '@/components/ui/empty-state'
@@ -82,7 +83,7 @@ export default function CustomersPage() {
if (!response.ok) {
toast({
title: 'Kunde inte skapa kund',
description: result.error || 'Försök igen.',
description: getErrorMessage(result, { context: 'customer' }),
variant: 'destructive',
})
} else {
+5 -4
View File
@@ -9,6 +9,7 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { ArrowLeft, CheckCircle, CreditCard, FileText, Trash2 } from 'lucide-react'
import Link from 'next/link'
import { AccountNumber } from '@/components/ui/account-number'
@@ -78,7 +79,7 @@ export default function ExpenseDetailPage() {
const res = await fetch(`/api/supplier-invoices/${params.id}/approve`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte godkänna', description: result.error, variant: 'destructive' })
toast({ title: 'Kunde inte godkänna', description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: 'Godkänd', description: 'Utgiften har godkänts' })
fetchInvoice()
@@ -95,7 +96,7 @@ export default function ExpenseDetailPage() {
})
const result = await res.json()
if (!res.ok) {
toast({ title: 'Betalning misslyckades', description: result.error, variant: 'destructive' })
toast({ title: 'Betalning misslyckades', description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({
title: result.status === 'paid' ? 'Betald' : 'Delbetalning registrerad',
@@ -119,7 +120,7 @@ export default function ExpenseDetailPage() {
const res = await fetch(`/api/supplier-invoices/${params.id}/credit`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte kreditera', description: result.error, variant: 'destructive' })
toast({ title: 'Kunde inte kreditera', description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: 'Kreditfaktura registrerad' })
fetchInvoice()
@@ -138,7 +139,7 @@ export default function ExpenseDetailPage() {
const res = await fetch(`/api/supplier-invoices/${params.id}`, { method: 'DELETE' })
const result = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte ta bort', description: result.error, variant: 'destructive' })
toast({ title: 'Kunde inte ta bort', description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: 'Borttagen' })
router.push('/expenses')
+1 -1
View File
@@ -227,7 +227,7 @@ export default function NewExpensePage() {
const result = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte skapa leverantör', description: result.error, variant: 'destructive' })
toast({ title: 'Kunde inte skapa leverantör', description: getErrorMessage(result, { context: 'supplier' }), variant: 'destructive' })
} else {
const created = result.data as Supplier
setSuppliers((prev) => [...prev, created].sort((a, b) => a.name.localeCompare(b.name)))
+32 -16
View File
@@ -6,6 +6,7 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/com
import { Progress } from '@/components/ui/progress'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { ArrowLeftRight, ArrowRightLeft, FileText, ArrowLeft, Landmark, Loader2, Info, ChevronRight, Scale } from 'lucide-react'
import { cn } from '@/lib/utils'
import { createClient } from '@/lib/supabase/client'
@@ -362,24 +363,39 @@ function SIEImportWizard() {
const data = await res.json()
if (!res.ok) {
const type = data.error as typeof errorType
if (type === 'duplicate' || type === 'duplicate_period') {
setErrorType(type)
setError(data.message)
if (data.importId) {
setDuplicateImportId(data.importId)
const code = data?.error?.code as string | undefined
const message = getErrorMessage(data)
const details = (data?.error?.details ?? {}) as {
importId?: string
errors?: string[]
warnings?: string[]
}
if (code === 'SIE_DUPLICATE_FILE' || code === 'SIE_DUPLICATE_PERIOD') {
const isPeriod = code === 'SIE_DUPLICATE_PERIOD'
setErrorType(isPeriod ? 'duplicate_period' : 'duplicate')
setError(message)
if (details.importId) {
setDuplicateImportId(details.importId)
}
toast({ title: type === 'duplicate' ? 'Filen har redan importerats' : 'Överlappande räkenskapsår', description: data.message, variant: 'destructive' })
} else if (type === 'validation') {
toast({
title: isPeriod ? 'Överlappande räkenskapsår' : 'Filen har redan importerats',
description: message,
variant: 'destructive',
})
} else if (code === 'SIE_PARSE_VALIDATION_FAILED') {
setErrorType('validation')
setError(data.message || 'SIE-filen innehåller valideringsfel.')
setValidationErrors(data.errors || [])
setValidationWarnings(data.warnings || [])
toast({ title: 'Valideringsfel i SIE-filen', description: `${(data.errors || []).length} fel hittades som måste åtgärdas.`, variant: 'destructive' })
setError(message)
setValidationErrors(details.errors || [])
setValidationWarnings(details.warnings || [])
toast({
title: 'Valideringsfel i SIE-filen',
description: `${(details.errors || []).length} fel hittades som måste åtgärdas.`,
variant: 'destructive',
})
} else {
setErrorType('parse')
setError(data.message || data.error || 'Kunde inte tolka filen.')
toast({ title: 'Kunde inte läsa filen', description: data.message || data.error || 'Kontrollera att filen är en giltig SIE-fil.', variant: 'destructive' })
setError(message)
toast({ title: 'Kunde inte läsa filen', description: message, variant: 'destructive' })
}
return
}
@@ -433,7 +449,7 @@ function SIEImportWizard() {
const data = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte ersätta import', description: data.error || 'Ett fel uppstod', variant: 'destructive' })
toast({ title: 'Kunde inte ersätta import', description: getErrorMessage(data), variant: 'destructive' })
return
}
@@ -498,7 +514,7 @@ function SIEImportWizard() {
const data = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte skapa konton', description: data.error || 'Försök igen.', variant: 'destructive' })
toast({ title: 'Kunde inte skapa konton', description: getErrorMessage(data), variant: 'destructive' })
return
}
+1 -1
View File
@@ -209,7 +209,7 @@ export default function NewInvoicePage() {
if (!response.ok) {
toast({
title: 'Kunde inte skapa kund',
description: result.error || 'Försök igen.',
description: getErrorMessage(result, { context: 'customer' }),
variant: 'destructive',
})
} else {
+27
View File
@@ -26,6 +26,7 @@ const operationLabels: Record<string, { label: string; icon: typeof ArrowLeftRig
categorize_transaction: { label: 'Kategorisering', icon: ArrowLeftRight, variant: 'default' },
create_customer: { label: 'Ny kund', icon: Users, variant: 'secondary' },
create_invoice: { label: 'Ny faktura', icon: Receipt, variant: 'outline' },
create_transaction: { label: 'Ny transaktion', icon: ArrowLeftRight, variant: 'secondary' },
mark_invoice_paid: { label: 'Betald faktura', icon: Receipt, variant: 'default' },
send_invoice: { label: 'Skicka faktura', icon: Receipt, variant: 'outline' },
mark_invoice_sent: { label: 'Markera skickad', icon: Receipt, variant: 'outline' },
@@ -138,6 +139,30 @@ function InvoicePreview({ data }: { data: Record<string, unknown> }) {
)
}
function CreateTransactionPreview({ data }: { data: Record<string, unknown> }) {
const amount = data.amount as number
const currency = (data.currency as string) || 'SEK'
return (
<div className="grid grid-cols-2 gap-x-4 gap-y-1 text-sm">
<span className="text-muted-foreground">Datum</span>
<span className="font-mono">{String(data.date ?? '')}</span>
<span className="text-muted-foreground">Beskrivning</span>
<span className="truncate">{String(data.description ?? '')}</span>
<span className="text-muted-foreground">Belopp</span>
<span className="font-mono tabular-nums">
{formatCurrency(amount, currency)}
</span>
{data.external_id ? (
<>
<span className="text-muted-foreground">Extern referens</span>
<span className="font-mono text-xs truncate">{String(data.external_id)}</span>
</>
) : null}
</div>
)
}
function GenericPreview({ data }: { data: Record<string, unknown> }) {
const entries = Object.entries(data).filter(([, v]) => v != null && v !== '')
return (
@@ -162,6 +187,8 @@ function OperationPreview({ op }: { op: PendingOperation }) {
return <CustomerPreview data={op.preview_data} />
case 'create_invoice':
return <InvoicePreview data={op.preview_data} />
case 'create_transaction':
return <CreateTransactionPreview data={op.preview_data} />
default:
return <GenericPreview data={op.preview_data} />
}
@@ -9,6 +9,7 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { ArrowLeft, CheckCircle, CreditCard, FileText, Trash2, Lock, Undo2, Info } from 'lucide-react'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import Link from 'next/link'
@@ -78,7 +79,7 @@ export default function SupplierInvoiceDetailPage() {
const res = await fetch(`/api/supplier-invoices/${params.id}/approve`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: 'Godkännande misslyckades', description: result.error, variant: 'destructive' })
toast({ title: 'Godkännande misslyckades', description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: 'Godkänd', description: 'Fakturan har godkänts' })
fetchInvoice()
@@ -95,7 +96,7 @@ export default function SupplierInvoiceDetailPage() {
})
const result = await res.json()
if (!res.ok) {
toast({ title: 'Betalning misslyckades', description: result.error, variant: 'destructive' })
toast({ title: 'Betalning misslyckades', description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({
title: result.status === 'paid' ? 'Betald' : 'Delbetalning registrerad',
@@ -119,7 +120,7 @@ export default function SupplierInvoiceDetailPage() {
const res = await fetch(`/api/supplier-invoices/${params.id}/credit`, { method: 'POST' })
const result = await res.json()
if (!res.ok) {
toast({ title: 'Kreditering misslyckades', description: result.error, variant: 'destructive' })
toast({ title: 'Kreditering misslyckades', description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: 'Kreditfaktura registrerad' })
fetchInvoice()
@@ -138,7 +139,7 @@ export default function SupplierInvoiceDetailPage() {
const res = await fetch(`/api/supplier-invoices/${params.id}`, { method: 'DELETE' })
const result = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte ta bort faktura', description: result.error, variant: 'destructive' })
toast({ title: 'Kunde inte ta bort faktura', description: getErrorMessage(result, { context: 'supplier_invoice' }), variant: 'destructive' })
} else {
toast({ title: 'Borttagen' })
router.push('/supplier-invoices')
@@ -160,7 +161,7 @@ export default function SupplierInvoiceDetailPage() {
if (!res.ok) {
toast({
title: 'Kunde inte ångra kreditering',
description: result.error || 'Försök igen',
description: getErrorMessage(result, { context: 'supplier_invoice' }),
variant: 'destructive',
})
} else {
+3 -3
View File
@@ -7,6 +7,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { ArrowLeft, Edit, Trash2, FileText, Lock } from 'lucide-react'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import SupplierForm from '@/components/suppliers/SupplierForm'
@@ -70,8 +71,7 @@ export default function SupplierDetailPage() {
})
const result = await res.json()
if (!res.ok) {
const fieldErrors = result.errors?.map((e: { field: string; message: string }) => `${e.field}: ${e.message}`).join(', ')
toast({ title: 'Kunde inte uppdatera leverantör', description: fieldErrors || result.error || 'Försök igen.', variant: 'destructive' })
toast({ title: 'Kunde inte uppdatera leverantör', description: getErrorMessage(result, { context: 'supplier' }), variant: 'destructive' })
} else {
toast({ title: 'Sparat', description: 'Leverantören har uppdaterats' })
setSupplier({ ...result.data, stats: supplier?.stats })
@@ -92,7 +92,7 @@ export default function SupplierDetailPage() {
const res = await fetch(`/api/suppliers/${params.id}`, { method: 'DELETE' })
const result = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte ta bort leverantör', description: result.error, variant: 'destructive' })
toast({ title: 'Kunde inte ta bort leverantör', description: getErrorMessage(result, { context: 'supplier' }), variant: 'destructive' })
} else {
toast({ title: 'Borttagen', description: 'Leverantören har tagits bort' })
router.push('/suppliers')
+4 -4
View File
@@ -374,7 +374,7 @@ export default function TransactionsPage() {
})
const result = await response.json()
if (!response.ok) {
toast({ title: 'Fakturamatchning misslyckades', description: result.error || 'Försök igen.', variant: 'destructive' })
toast({ title: 'Fakturamatchning misslyckades', description: getErrorMessage(result, { context: 'transaction' }), variant: 'destructive' })
setIsConfirmingMatch(false)
return
}
@@ -426,7 +426,7 @@ export default function TransactionsPage() {
})
const result = await response.json()
if (!response.ok) {
toast({ title: 'Fakturamatchning misslyckades', description: result.error || 'Försök igen.', variant: 'destructive' })
toast({ title: 'Fakturamatchning misslyckades', description: getErrorMessage(result, { context: 'transaction' }), variant: 'destructive' })
return false
}
@@ -510,7 +510,7 @@ export default function TransactionsPage() {
const result = await response.json()
toast({
title: 'Kunde inte ta bort',
description: result.error || 'Försök igen.',
description: getErrorMessage(result, { context: 'transaction' }),
variant: 'destructive',
})
return
@@ -712,7 +712,7 @@ export default function TransactionsPage() {
})
const result = await response.json()
if (!response.ok) {
toast({ title: 'Kategorisering misslyckades', description: result.error || 'Försök igen.', variant: 'destructive' })
toast({ title: 'Kategorisering misslyckades', description: getErrorMessage(result, { context: 'transaction' }), variant: 'destructive' })
return null
}
setExitingIds((prev) => new Set(prev).add(id))
@@ -1,32 +1,19 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import {
previewCurrencyRevaluation,
executeCurrencyRevaluation,
} from '@/lib/bookkeeping/currency-revaluation'
import { bookkeepingErrorResponse } from '@/lib/bookkeeping/errors'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET: Preview currency revaluation for a fiscal period
*/
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
/** GET: preview currency revaluation for a fiscal period. */
export const GET = withRouteContext(
'period.fx_revaluation_preview',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ periodId: id })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const companyId = await requireCompanyId(supabase, user.id)
try {
// Fetch period to get closing date
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('*')
@@ -35,43 +22,28 @@ export async function GET(
.single()
if (periodError || !period) {
return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 })
return errorResponseFromCode('FX_PERIOD_NOT_FOUND', opLog, { requestId })
}
const preview = await previewCurrencyRevaluation(supabase, companyId, period.period_end)
return NextResponse.json({ data: preview })
} catch (err) {
const typed = bookkeepingErrorResponse(err)
if (typed) return typed
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to preview currency revaluation' },
{ status: 400 }
)
}
}
try {
const preview = await previewCurrencyRevaluation(supabase, companyId!, period.period_end)
return NextResponse.json({ data: preview })
} catch (err) {
opLog.error('fx revaluation preview failed', err as Error)
// Bookkeeping errors flow through errorResponse with their typed codes.
return errorResponse(err, opLog, { requestId })
}
},
)
/**
* POST: Execute currency revaluation for a fiscal period
*/
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
/** POST: execute currency revaluation, creating the period-end FX entry. */
export const POST = withRouteContext(
'period.fx_revaluation',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const opLog = log.child({ periodId: id })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
try {
// Fetch period to get closing date
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('*')
@@ -80,26 +52,35 @@ export async function POST(
.single()
if (periodError || !period) {
return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 })
return errorResponseFromCode('FX_PERIOD_NOT_FOUND', opLog, { requestId })
}
if (period.is_closed) {
return NextResponse.json({ error: 'Period is already closed' }, { status: 400 })
return errorResponseFromCode('FX_PERIOD_CLOSED', opLog, { requestId })
}
const result = await executeCurrencyRevaluation(supabase, companyId, period.period_end, id, user.id)
try {
const result = await executeCurrencyRevaluation(
supabase, companyId!, period.period_end, id, user.id,
)
if (!result) {
return NextResponse.json({ data: null, message: 'No foreign currency items to revalue' })
if (!result) {
return NextResponse.json({ data: null, message: 'No foreign currency items to revalue' })
}
return NextResponse.json({ data: result })
} catch (err) {
opLog.error('fx revaluation execution failed', err as Error)
// CurrencyRevaluationAlreadyExistsError + other typed errors flow through.
const fallback = errorResponse(err, opLog, { requestId })
if (fallback.status === 500) {
return errorResponseFromCode('FX_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? err.message : 'unknown' },
})
}
return fallback
}
return NextResponse.json({ data: result })
} catch (err) {
const typed = bookkeepingErrorResponse(err)
if (typed) return typed
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to execute currency revaluation' },
{ status: 400 }
)
}
}
},
{ requireWrite: true },
)
@@ -1,33 +1,37 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { lockPeriod } from '@/lib/core/bookkeeping/period-service'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
export const POST = withRouteContext(
'period.lock',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const opLog = log.child({ periodId: id })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
try {
const period = await lockPeriod(supabase, companyId, user.id, id)
return NextResponse.json({ data: period })
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to lock period' },
{ status: 400 }
)
}
}
try {
const period = await lockPeriod(supabase, companyId!, user.id, id)
return NextResponse.json({ data: period })
} catch (err) {
opLog.error('failed to lock period', err as Error)
// The service throws plain Error with messages like "Period not found"
// or "Period contains drafts" — translate to envelope codes.
const message = err instanceof Error ? err.message : ''
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', opLog, { requestId })
}
if (/already locked|already closed/i.test(message)) {
return errorResponseFromCode('PERIOD_LOCK_ALREADY_LOCKED', opLog, { requestId })
}
if (/draft/i.test(message)) {
return errorResponseFromCode('PERIOD_LOCK_HAS_DRAFTS', opLog, {
requestId,
details: { reason: message },
})
}
return errorResponse(err, opLog, { requestId })
}
},
{ requireWrite: true },
)
@@ -1,67 +1,57 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { getOpeningBalances } from '@/lib/reports/opening-balances'
import { requireCompanyId } from '@/lib/company/context'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
export const GET = withRouteContext(
'period.opening_balances',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ periodId: id })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('period_start, opening_balance_entry_id')
.eq('id', id)
.eq('company_id', companyId)
.single()
const companyId = await requireCompanyId(supabase, user.id)
const { id } = await params
if (periodError || !period) {
return errorResponseFromCode('OPENING_BAL_PERIOD_NOT_FOUND', opLog, { requestId })
}
// Fetch the fiscal period
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('period_start, opening_balance_entry_id')
.eq('id', id)
.eq('company_id', companyId)
.single()
const { balances } = await getOpeningBalances(supabase, companyId!, period)
if (periodError || !period) {
return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 })
}
const accountNumbers = Array.from(balances.keys())
// Get opening balances
const { balances } = await getOpeningBalances(supabase, companyId, period)
if (accountNumbers.length === 0) {
return NextResponse.json({ data: [] })
}
// Fetch account names for the accounts that have balances
const accountNumbers = Array.from(balances.keys())
const { data: accounts } = await supabase
.from('chart_of_accounts')
.select('account_number, account_name')
.eq('company_id', companyId)
.in('account_number', accountNumbers)
if (accountNumbers.length === 0) {
return NextResponse.json({ data: [] })
}
const accountNameMap = new Map(
(accounts || []).map((a) => [a.account_number, a.account_name]),
)
const { data: accounts } = await supabase
.from('chart_of_accounts')
.select('account_number, account_name')
.eq('company_id', companyId)
.in('account_number', accountNumbers)
const data = accountNumbers
.sort()
.map((accountNumber) => {
const bal = balances.get(accountNumber)!
const net = Math.round((bal.debit - bal.credit) * 100) / 100
return {
account_number: accountNumber,
account_name: accountNameMap.get(accountNumber) || accountNumber,
balance: net,
}
})
.filter((row) => row.balance !== 0)
const accountNameMap = new Map(
(accounts || []).map(a => [a.account_number, a.account_name])
)
// Build response with account names and net balances
const data = accountNumbers
.sort()
.map(accountNumber => {
const bal = balances.get(accountNumber)!
const net = Math.round((bal.debit - bal.credit) * 100) / 100
return {
account_number: accountNumber,
account_name: accountNameMap.get(accountNumber) || accountNumber,
balance: net,
}
})
.filter(row => row.balance !== 0)
return NextResponse.json({ data })
}
return NextResponse.json({ data })
},
)
@@ -1,72 +1,79 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import {
validateYearEndReadiness,
previewYearEndClosing,
executeYearEndClosing,
} from '@/lib/core/bookkeeping/year-end-service'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET: Validate readiness and preview year-end closing
*/
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
/** GET: validate readiness + preview the year-end entries. */
export const GET = withRouteContext(
'period.year_end_preview',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const opLog = log.child({ periodId: id })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const [validation, preview] = await Promise.all([
validateYearEndReadiness(supabase, companyId!, user.id, id),
previewYearEndClosing(supabase, companyId!, user.id, id),
])
return NextResponse.json({ data: { validation, preview } })
} catch (err) {
opLog.error('year-end preview failed', err as Error)
const message = err instanceof Error ? err.message : ''
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', opLog, { requestId })
}
return errorResponseFromCode('YEAR_END_PREVIEW_FAILED', opLog, {
requestId,
details: { reason: message },
})
}
},
)
const companyId = await requireCompanyId(supabase, user.id)
/** POST: actually run year-end closing. */
export const POST = withRouteContext(
'period.year_end',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const opLog = log.child({ periodId: id })
try {
const [validation, preview] = await Promise.all([
validateYearEndReadiness(supabase, companyId, user.id, id),
previewYearEndClosing(supabase, companyId, user.id, id),
])
return NextResponse.json({ data: { validation, preview } })
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to preview year-end' },
{ status: 400 }
)
}
}
/**
* POST: Execute year-end closing
*/
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
try {
const result = await executeYearEndClosing(supabase, companyId, user.id, id)
return NextResponse.json({ data: result })
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Failed to execute year-end closing' },
{ status: 400 }
)
}
}
try {
const result = await executeYearEndClosing(supabase, companyId!, user.id, id)
return NextResponse.json({ data: result })
} catch (err) {
opLog.error('year-end execution failed', err as Error)
const message = err instanceof Error ? err.message : ''
if (/prior.*open/i.test(message)) {
return errorResponseFromCode('YEAR_END_PRIOR_PERIOD_OPEN', opLog, {
requestId,
details: { reason: message },
})
}
if (/not balanced|unbalanced/i.test(message)) {
return errorResponseFromCode('YEAR_END_UNBALANCED_TRIAL', opLog, {
requestId,
details: { reason: message },
})
}
if (/not found/i.test(message)) {
return errorResponseFromCode('PERIOD_NOT_FOUND', opLog, { requestId })
}
// Fall through bookkeeping/Zod/etc to errorResponse, but cap to YEAR_END_FAILED.
const fallback = errorResponse(err, opLog, { requestId })
if (fallback.status === 500) {
return errorResponseFromCode('YEAR_END_FAILED', opLog, {
requestId,
details: { reason: message },
})
}
return fallback
}
},
{ requireWrite: true },
)
+125 -161
View File
@@ -1,199 +1,163 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { validateBody } from '@/lib/api/validate'
import { UpdateCustomerSchema } from '@/lib/api/schemas'
import { validateVatNumber } from '@/lib/vat/vies-client'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { createLogger } from '@/lib/logger'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
const log = createLogger('api/customers/[id]')
export const GET = withRouteContext(
'customer.get',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ customerId: id })
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const { id } = await params
const { data, error } = await supabase
.from('customers')
.select('*')
.eq('id', id)
.eq('company_id', companyId)
.single()
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const companyId = await requireCompanyId(supabase, user.id)
const { data, error } = await supabase
.from('customers')
.select('*')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (error) {
if (error.code === 'PGRST116') {
return NextResponse.json({ error: 'Customer not found' }, { status: 404 })
if (error) {
if (error.code === 'PGRST116') {
return errorResponseFromCode('CUSTOMER_NOT_FOUND', opLog, { requestId })
}
opLog.error('customer fetch failed', error)
return errorResponseFromCode('INTERNAL_ERROR', opLog, {
requestId,
details: { reason: error.message },
})
}
return NextResponse.json({ error: error.message }, { status: 500 })
}
// Fetch related invoices
const { data: invoices } = await supabase
.from('invoices')
.select('id, invoice_number, invoice_date, due_date, status, total, currency')
.eq('customer_id', id)
.eq('company_id', companyId)
.order('invoice_date', { ascending: false })
const { data: invoices } = await supabase
.from('invoices')
.select('id, invoice_number, invoice_date, due_date, status, total, currency')
.eq('customer_id', id)
.eq('company_id', companyId)
.order('invoice_date', { ascending: false })
return NextResponse.json({
data: {
...data,
invoices: invoices || [],
},
})
}
return NextResponse.json({ data: { ...data, invoices: invoices || [] } })
},
)
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const { id } = await params
export const PATCH = withRouteContext(
'customer.update',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ customerId: id })
const {
data: { user },
} = await supabase.auth.getUser()
const result = await validateBody(request, UpdateCustomerSchema, {
log: opLog,
operation: 'customer.update',
})
if (!result.success) return result.response
const body = result.data
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const updateData: Record<string, unknown> = {}
if (body.name !== undefined) updateData.name = body.name
if (body.customer_type !== undefined) updateData.customer_type = body.customer_type
if (body.email !== undefined) updateData.email = body.email
if (body.phone !== undefined) updateData.phone = body.phone
if (body.address_line1 !== undefined) updateData.address_line1 = body.address_line1
if (body.address_line2 !== undefined) updateData.address_line2 = body.address_line2
if (body.postal_code !== undefined) updateData.postal_code = body.postal_code
if (body.city !== undefined) updateData.city = body.city
if (body.country !== undefined) updateData.country = body.country
if (body.org_number !== undefined) updateData.org_number = body.org_number
if (body.vat_number !== undefined) updateData.vat_number = body.vat_number
if (body.default_payment_terms !== undefined) updateData.default_payment_terms = body.default_payment_terms
if (body.notes !== undefined) updateData.notes = body.notes
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const { data, error } = await supabase
.from('customers')
.update(updateData)
.eq('id', id)
.eq('company_id', companyId)
.select()
.single()
const companyId = await requireCompanyId(supabase, user.id)
if (error) {
if (error.code === '23505') {
return errorResponseFromCode('CUSTOMER_DUPLICATE_ORG_NUMBER', opLog, {
requestId,
details: { orgNumber: body.org_number },
})
}
opLog.error('customer update failed', error)
return errorResponseFromCode('CUSTOMER_UPDATE_FAILED', opLog, {
requestId,
details: { reason: error.message },
})
}
const result = await validateBody(request, UpdateCustomerSchema)
if (!result.success) return result.response
const body = result.data
const updateData: Record<string, unknown> = {}
if (body.name !== undefined) updateData.name = body.name
if (body.customer_type !== undefined) updateData.customer_type = body.customer_type
if (body.email !== undefined) updateData.email = body.email
if (body.phone !== undefined) updateData.phone = body.phone
if (body.address_line1 !== undefined) updateData.address_line1 = body.address_line1
if (body.address_line2 !== undefined) updateData.address_line2 = body.address_line2
if (body.postal_code !== undefined) updateData.postal_code = body.postal_code
if (body.city !== undefined) updateData.city = body.city
if (body.country !== undefined) updateData.country = body.country
if (body.org_number !== undefined) updateData.org_number = body.org_number
if (body.vat_number !== undefined) updateData.vat_number = body.vat_number
if (body.default_payment_terms !== undefined) updateData.default_payment_terms = body.default_payment_terms
if (body.notes !== undefined) updateData.notes = body.notes
const { data, error } = await supabase
.from('customers')
.update(updateData)
.eq('id', id)
.eq('company_id', companyId)
.select()
.single()
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
// Auto-validate VAT number when it changes on an EU business customer (non-blocking)
const isEuBusiness = (body.customer_type || data.customer_type) === 'eu_business'
if (body.vat_number !== undefined && isEuBusiness) {
try {
if (body.vat_number) {
const vatResult = await validateVatNumber(body.vat_number)
if (vatResult.valid) {
// Re-run VIES validation when the VAT number changes on an EU business
// customer (non-blocking).
const isEuBusiness = (body.customer_type || data.customer_type) === 'eu_business'
if (body.vat_number !== undefined && isEuBusiness) {
try {
if (body.vat_number) {
const vatResult = await validateVatNumber(body.vat_number)
const validatedAt = vatResult.valid ? new Date().toISOString() : null
await supabase
.from('customers')
.update({
vat_number_validated: true,
vat_number_validated_at: new Date().toISOString(),
vat_number_validated: vatResult.valid,
vat_number_validated_at: validatedAt,
})
.eq('id', id)
.eq('company_id', companyId)
data.vat_number_validated = true
data.vat_number_validated_at = new Date().toISOString()
data.vat_number_validated = vatResult.valid
data.vat_number_validated_at = validatedAt
} else {
await supabase
.from('customers')
.update({
vat_number_validated: false,
vat_number_validated_at: null,
})
.update({ vat_number_validated: false, vat_number_validated_at: null })
.eq('id', id)
.eq('company_id', companyId)
data.vat_number_validated = false
data.vat_number_validated_at = null
}
} else {
// VAT number cleared
await supabase
.from('customers')
.update({
vat_number_validated: false,
vat_number_validated_at: null,
})
.eq('id', id)
.eq('company_id', companyId)
data.vat_number_validated = false
data.vat_number_validated_at = null
} catch (err) {
opLog.warn('auto-VIES validation failed on customer update', err as Error)
}
} catch (err) {
log.warn('Auto-VIES validation failed on customer update:', err)
}
}
return NextResponse.json({ data })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const { id } = await params
export const DELETE = withRouteContext(
'customer.delete',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ customerId: id })
const {
data: { user },
} = await supabase.auth.getUser()
const { error, count } = await supabase
.from('customers')
.delete({ count: 'exact' })
.eq('id', id)
.eq('company_id', companyId)
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
if (error) {
if (error.code === '23503') {
return errorResponseFromCode('CUSTOMER_HAS_INVOICES', opLog, { requestId })
}
opLog.error('customer delete failed', error)
return errorResponseFromCode('CUSTOMER_DELETE_FAILED', opLog, {
requestId,
details: { reason: error.message },
})
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
if (count === 0) {
return errorResponseFromCode('CUSTOMER_NOT_FOUND', opLog, { requestId })
}
const companyId = await requireCompanyId(supabase, user.id)
const { error, count } = await supabase
.from('customers')
.delete({ count: 'exact' })
.eq('id', id)
.eq('company_id', companyId)
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
if (count === 0) {
return NextResponse.json({ error: 'Customer not found' }, { status: 404 })
}
return NextResponse.json({ success: true })
}
return NextResponse.json({ success: true })
},
{ requireWrite: true },
)
+98 -98
View File
@@ -1,113 +1,113 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { validateBody } from '@/lib/api/validate'
import { CreateCustomerSchema } from '@/lib/api/schemas'
import { validateVatNumber } from '@/lib/vat/vies-client'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { createLogger } from '@/lib/logger'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { Customer } from '@/types'
const log = createLogger('api/customers')
ensureInitialized()
export async function GET() {
const supabase = await createClient()
export const GET = withRouteContext(
'customer.list',
async (_request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const { data: { user } } = await supabase.auth.getUser()
const { data, error } = await supabase
.from('customers')
.select('*')
.eq('company_id', companyId)
.order('name', { ascending: true })
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const companyId = await requireCompanyId(supabase, user.id)
const { data, error } = await supabase
.from('customers')
.select('*')
.eq('company_id', companyId)
.order('name', { ascending: true })
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
return NextResponse.json({ data })
}
export async function POST(request: Request) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
const result = await validateBody(request, CreateCustomerSchema)
if (!result.success) return result.response
const body = result.data
const { data, error } = await supabase
.from('customers')
.insert({
user_id: user.id,
company_id: companyId,
name: body.name,
customer_type: body.customer_type,
email: body.email,
phone: body.phone,
address_line1: body.address_line1,
address_line2: body.address_line2,
postal_code: body.postal_code,
city: body.city,
country: body.country || 'Sweden',
org_number: body.org_number,
vat_number: body.vat_number,
default_payment_terms: body.default_payment_terms || 30,
notes: body.notes,
})
.select()
.single()
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
// Auto-validate VAT number for EU business customers (non-blocking)
if (body.customer_type === 'eu_business' && body.vat_number) {
try {
const vatResult = await validateVatNumber(body.vat_number)
if (vatResult.valid) {
await supabase
.from('customers')
.update({
vat_number_validated: true,
vat_number_validated_at: new Date().toISOString(),
})
.eq('id', data.id)
.eq('company_id', companyId)
data.vat_number_validated = true
data.vat_number_validated_at = new Date().toISOString()
}
} catch (err) {
log.warn('Auto-VIES validation failed on customer create:', err)
if (error) {
log.error('customer list failed', error)
return errorResponse(error, log, { requestId })
}
}
await eventBus.emit({
type: 'customer.created',
payload: { customer: data as Customer, companyId, userId: user.id },
})
return NextResponse.json({ data })
},
)
return NextResponse.json({ data })
}
export const POST = withRouteContext(
'customer.create',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const result = await validateBody(request, CreateCustomerSchema, {
log,
operation: 'customer.create',
})
if (!result.success) return result.response
const body = result.data
const { data, error } = await supabase
.from('customers')
.insert({
user_id: user.id,
company_id: companyId,
name: body.name,
customer_type: body.customer_type,
email: body.email,
phone: body.phone,
address_line1: body.address_line1,
address_line2: body.address_line2,
postal_code: body.postal_code,
city: body.city,
country: body.country || 'Sweden',
org_number: body.org_number,
vat_number: body.vat_number,
default_payment_terms: body.default_payment_terms || 30,
notes: body.notes,
})
.select()
.single()
if (error) {
if (error.code === '23505') {
return errorResponseFromCode('CUSTOMER_DUPLICATE_ORG_NUMBER', log, {
requestId,
details: { orgNumber: body.org_number },
})
}
log.error('customer insert failed', error)
return errorResponseFromCode('CUSTOMER_CREATE_FAILED', log, {
requestId,
details: { reason: error.message },
})
}
// Auto-validate VAT number for EU business customers (non-blocking).
if (body.customer_type === 'eu_business' && body.vat_number) {
try {
const vatResult = await validateVatNumber(body.vat_number)
if (vatResult.valid) {
await supabase
.from('customers')
.update({
vat_number_validated: true,
vat_number_validated_at: new Date().toISOString(),
})
.eq('id', data.id)
.eq('company_id', companyId)
data.vat_number_validated = true
data.vat_number_validated_at = new Date().toISOString()
}
} catch (err) {
log.warn('auto-VIES validation failed on customer create', err as Error, {
customerId: data.id,
})
}
}
await eventBus.emit({
type: 'customer.created',
payload: { customer: data as Customer, companyId: companyId!, userId: user.id },
})
return NextResponse.json({ data })
},
{ requireWrite: true },
)
+22 -35
View File
@@ -1,51 +1,38 @@
import { createClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { updateDeadlineStatuses } from '@/lib/deadlines/status-engine'
import { verifyCronSecret } from '@/lib/auth/cron'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET /api/deadlines/status/cron
* Daily cron job to update deadline statuses
* Runs at 06:00 every day
*
* Vercel Cron: "0 6 * * *"
* GET /api/deadlines/status/cron — daily 06:00 UTC.
* Updates deadline statuses across all companies.
*/
export async function GET(request: Request) {
const authError = verifyCronSecret(request)
if (authError) return authError
// Create a service role client for accessing all user data
export const GET = withCronContext('cron.deadlines_status', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return NextResponse.json(
{ error: 'Missing Supabase configuration' },
{ status: 500 }
)
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
try {
const result = await updateDeadlineStatuses(supabase)
const result = await updateDeadlineStatuses(supabase)
console.log(
`Deadline status cron completed: ${result.updated} updated, ` +
`${result.newlyOverdue} newly overdue, ${result.newlyActionNeeded} newly action_needed`
)
ctx.log.info('deadline status cron summary', {
updated: result.updated,
newlyOverdue: result.newlyOverdue,
newlyActionNeeded: result.newlyActionNeeded,
})
return NextResponse.json({
success: true,
updated: result.updated,
newlyOverdue: result.newlyOverdue,
newlyActionNeeded: result.newlyActionNeeded,
})
} catch (error) {
console.error('Error in deadline status cron:', error)
return NextResponse.json(
{ error: 'Failed to update deadline statuses' },
{ status: 500 }
)
}
}
return NextResponse.json({
success: true,
updated: result.updated,
newlyOverdue: result.newlyOverdue,
newlyActionNeeded: result.newlyActionNeeded,
})
})
+43 -49
View File
@@ -1,63 +1,57 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { linkToJournalEntry } from '@/lib/core/documents/document-service'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
ensureInitialized()
/**
* POST /api/documents/:id/link
* Link a document to a journal entry (verifikation)
* POST /api/documents/[id]/link — link a document to a journal entry.
*
* Request body:
* - journal_entry_id: string (required)
* - journal_entry_line_id: string (optional)
* Body: { journal_entry_id: string, journal_entry_line_id?: string }
*/
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
export const POST = withRouteContext(
'document.link',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ documentId: id })
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
const { id } = await params
try {
const body = await request.json()
const body = await request.json().catch(() => ({}))
if (!body.journal_entry_id) {
return NextResponse.json(
{ error: 'journal_entry_id is required' },
{ status: 400 }
)
return errorResponseFromCode('VALIDATION_ERROR', opLog, {
requestId,
details: { field: 'journal_entry_id', reason: 'required' },
})
}
const document = await linkToJournalEntry(
supabase,
companyId,
id,
body.journal_entry_id,
body.journal_entry_line_id
)
return NextResponse.json({ data: document })
} catch (error) {
console.error('[documents/link/POST] Link failed:', error)
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Link failed' },
{ status: 500 }
)
}
}
try {
const document = await linkToJournalEntry(
supabase,
companyId!,
id,
body.journal_entry_id,
body.journal_entry_line_id,
)
return NextResponse.json({ data: document })
} catch (err) {
opLog.error('document link failed', err as Error, {
journalEntryId: body.journal_entry_id,
})
const message = err instanceof Error ? err.message : ''
if (/journal entry not found/i.test(message)) {
return errorResponseFromCode('DOC_LINK_ENTRY_NOT_FOUND', opLog, { requestId })
}
if (/already linked/i.test(message)) {
return errorResponseFromCode('DOC_LINK_ALREADY_LINKED', opLog, { requestId })
}
return errorResponseFromCode('DOC_LINK_FAILED', opLog, {
requestId,
details: { reason: message || 'unknown' },
})
}
},
{ requireWrite: true },
)
+79 -88
View File
@@ -1,122 +1,113 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { uploadDocument, validateDocumentFile } from '@/lib/core/documents/document-service'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { DocumentUploadSource } from '@/types'
ensureInitialized()
/**
* POST /api/documents
* Upload a document to the WORM archive
* POST /api/documents — upload a document to the WORM archive.
*
* Accepts multipart/form-data with:
* - file: The document file
* - upload_source (optional): 'camera' | 'file_upload' | 'email' | ...
* - journal_entry_id (optional): Link to a journal entry
* - journal_entry_line_id (optional): Link to a journal entry line
* multipart/form-data:
* file: the document file
* upload_source (optional): 'camera' | 'file_upload' | 'email' | …
* journal_entry_id (optional)
* journal_entry_line_id (optional)
*/
export async function POST(request: Request) {
const supabase = await createClient()
export const POST = withRouteContext(
'document.upload',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
try {
const formData = await request.formData()
const file = formData.get('file') as File | null
if (!file) {
return NextResponse.json({ error: 'No file provided' }, { status: 400 })
return errorResponseFromCode('DOC_UPLOAD_NO_FILE', log, { requestId })
}
const validationError = validateDocumentFile({ size: file.size, type: file.type })
if (validationError) {
return NextResponse.json({ error: validationError }, { status: 400 })
// The validator returns a Swedish string today. Bucket the failure into
// a size or type code based on its content.
const code = /storlek|stor|MB/i.test(validationError)
? 'DOC_UPLOAD_TOO_LARGE'
: 'DOC_UPLOAD_UNSUPPORTED_TYPE'
return errorResponseFromCode(code, log, {
requestId,
details: { reason: validationError, sizeBytes: file.size, mimeType: file.type },
})
}
const uploadSource = (formData.get('upload_source') as string) || 'file_upload'
const journalEntryId = formData.get('journal_entry_id') as string | null
const journalEntryLineId = formData.get('journal_entry_line_id') as string | null
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
const buffer = await file.arrayBuffer()
try {
const uploadSource = (formData.get('upload_source') as string) || 'file_upload'
const journalEntryId = formData.get('journal_entry_id') as string | null
const journalEntryLineId = formData.get('journal_entry_line_id') as string | null
const document = await uploadDocument(supabase, user.id, companyId, {
name: file.name,
buffer,
type: file.type,
}, {
upload_source: uploadSource as import('@/types').DocumentUploadSource,
journal_entry_id: journalEntryId || undefined,
journal_entry_line_id: journalEntryLineId || undefined,
})
const buffer = await file.arrayBuffer()
return NextResponse.json({ data: document })
} catch (error) {
console.error('[documents/POST] Upload failed:', error)
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Upload failed' },
{ status: 500 }
)
}
}
const document = await uploadDocument(supabase, user.id, companyId!, {
name: file.name,
buffer,
type: file.type,
}, {
upload_source: uploadSource as DocumentUploadSource,
journal_entry_id: journalEntryId || undefined,
journal_entry_line_id: journalEntryLineId || undefined,
})
return NextResponse.json({ data: document })
} catch (err) {
opLog.error('document upload failed', err as Error)
return errorResponseFromCode('DOC_UPLOAD_STORAGE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? err.message : 'unknown' },
})
}
},
{ requireWrite: true },
)
/**
* GET /api/documents
* List documents with optional filtering
* GET /api/documents — list documents.
*
* Query params:
* - journal_entry_id: Filter by journal entry
* - current_only: If 'true', only return current versions (default: true)
* - limit: Number of results (default: 50)
* - offset: Pagination offset (default: 0)
* journal_entry_id: filter by JE
* current_only: 'false' to include older versions (default true)
* limit, offset
*/
export async function GET(request: Request) {
const supabase = await createClient()
export const GET = withRouteContext(
'document.list',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const { data: { user } } = await supabase.auth.getUser()
const { searchParams } = new URL(request.url)
const journalEntryId = searchParams.get('journal_entry_id')
const currentOnly = searchParams.get('current_only') !== 'false'
const limit = parseInt(searchParams.get('limit') || '50')
const offset = parseInt(searchParams.get('offset') || '0')
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
let query = supabase
.from('document_attachments')
.select('*', { count: 'exact' })
.eq('company_id', companyId)
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
const companyId = await requireCompanyId(supabase, user.id)
if (journalEntryId) query = query.eq('journal_entry_id', journalEntryId)
if (currentOnly) query = query.eq('is_current_version', true)
const { searchParams } = new URL(request.url)
const journalEntryId = searchParams.get('journal_entry_id')
const currentOnly = searchParams.get('current_only') !== 'false'
const limit = parseInt(searchParams.get('limit') || '50')
const offset = parseInt(searchParams.get('offset') || '0')
const { data, error, count } = await query
let query = supabase
.from('document_attachments')
.select('*', { count: 'exact' })
.eq('company_id', companyId)
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
if (error) {
log.error('document list failed', error)
return errorResponse(error, log, { requestId })
}
if (journalEntryId) {
query = query.eq('journal_entry_id', journalEntryId)
}
if (currentOnly) {
query = query.eq('is_current_version', true)
}
const { data, error, count } = await query
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
return NextResponse.json({ data, count })
}
return NextResponse.json({ data, count })
},
)
+65 -77
View File
@@ -1,34 +1,27 @@
import { createClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { verifyCronSecret } from '@/lib/auth/cron'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET /api/documents/verify/cron
* Batch integrity verification of WORM document archive
*
* Runs weekly (Sunday 03:00 UTC / 05:00 Swedish time).
* Processes up to 100 documents per run, prioritizing
* documents never checked or least recently checked.
*
* Uses service role for cross-user verification (RLS bypass).
* GET /api/documents/verify/cron — weekly Sunday 03:00 UTC.
* Spot-checks WORM archive integrity by recomputing SHA-256 for the next
* batch of documents and writing INTEGRITY_FAILURE rows to the audit log
* for any mismatches.
*/
export async function GET(request: Request) {
const authError = verifyCronSecret(request)
if (authError) return authError
export const GET = withCronContext('cron.documents_verify', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return NextResponse.json(
{ error: 'Missing Supabase configuration' },
{ status: 500 }
)
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
// Fetch up to 100 current-version documents, prioritizing unchecked/oldest
const { data: documents, error: fetchError } = await supabase
.from('document_attachments')
.select('id, user_id, company_id, storage_path, sha256_hash, file_name')
@@ -37,8 +30,8 @@ export async function GET(request: Request) {
.limit(parseInt(process.env.DOCUMENT_VERIFY_BATCH_SIZE || '500', 10))
if (fetchError) {
console.error('[doc-verify-cron] Failed to fetch documents:', fetchError)
return NextResponse.json({ error: 'Failed to fetch documents' }, { status: 500 })
ctx.log.error('failed to fetch documents for verify', fetchError)
return errorResponse(fetchError, ctx.log, { requestId: ctx.requestId })
}
if (!documents || documents.length === 0) {
@@ -47,68 +40,63 @@ export async function GET(request: Request) {
let verified = 0
let failures = 0
let errors = 0
for (const doc of documents) {
try {
// Download file from storage
const { data: fileData, error: downloadError } = await supabase.storage
.from('documents')
.download(doc.storage_path)
const summary = await ctx.forEach('document', documents, async (doc, itemCtx) => {
const { data: fileData, error: downloadError } = await supabase.storage
.from('documents')
.download(doc.storage_path)
if (downloadError || !fileData) {
console.error(`[doc-verify-cron] Download failed for ${doc.id}:`, downloadError)
errors++
continue
}
// Compute SHA-256 hash
const buffer = await fileData.arrayBuffer()
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
const computedHash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
const isValid = computedHash === doc.sha256_hash
// Update last_integrity_check_at
await supabase
.from('document_attachments')
.update({ last_integrity_check_at: new Date().toISOString() })
.eq('id', doc.id)
if (!isValid) {
// Log integrity failure to audit_log
await supabase.from('audit_log').insert({
user_id: doc.user_id,
company_id: doc.company_id,
action: 'INTEGRITY_FAILURE',
table_name: 'document_attachments',
record_id: doc.id,
description: `Integrity check failed for document "${doc.file_name}": stored hash ${doc.sha256_hash}, computed hash ${computedHash}`,
old_state: { sha256_hash: doc.sha256_hash },
new_state: { computed_hash: computedHash },
})
console.error(`[doc-verify-cron] INTEGRITY FAILURE: document ${doc.id} (${doc.file_name})`)
failures++
} else {
verified++
}
} catch (error) {
console.error(`[doc-verify-cron] Error verifying document ${doc.id}:`, error)
errors++
// Continue with other documents
if (downloadError || !fileData) {
throw new Error(downloadError?.message || 'download_failed')
}
}
console.log(
`[doc-verify-cron] Processed ${documents.length}: ${verified} verified, ${failures} failures, ${errors} errors`
)
const buffer = await fileData.arrayBuffer()
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
const computedHash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
return NextResponse.json({
processed: documents.length,
const isValid = computedHash === doc.sha256_hash
await supabase
.from('document_attachments')
.update({ last_integrity_check_at: new Date().toISOString() })
.eq('id', doc.id)
if (!isValid) {
await supabase.from('audit_log').insert({
user_id: doc.user_id,
company_id: doc.company_id,
action: 'INTEGRITY_FAILURE',
table_name: 'document_attachments',
record_id: doc.id,
description: `Integrity check failed for document "${doc.file_name}": stored hash ${doc.sha256_hash}, computed hash ${computedHash}`,
old_state: { sha256_hash: doc.sha256_hash },
new_state: { computed_hash: computedHash },
})
itemCtx.log.error('integrity failure', new Error('hash_mismatch'), {
documentId: doc.id,
fileName: doc.file_name,
storedHash: doc.sha256_hash,
computedHash,
})
failures++
} else {
verified++
}
})
ctx.log.info('document verify summary', {
processed: summary.total,
verified,
failures,
errors,
downloadErrors: summary.failed,
})
}
return NextResponse.json({
processed: summary.total,
verified,
failures,
errors: summary.failed,
})
})
+21 -32
View File
@@ -1,41 +1,30 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse } from '@/lib/errors/get-structured-error'
/**
* GET /api/events/cleanup/cron
* Daily cron job to delete event_log rows older than 30 days.
* Runs at 02:00 UTC every day.
* GET /api/events/cleanup/cron — daily 02:00 UTC.
* Removes event_log rows older than 30 days.
*/
export async function GET(request: Request) {
const authHeader = request.headers.get('authorization')
const cronSecret = process.env.CRON_SECRET
export const GET = withCronContext('cron.events_cleanup', async (_request, ctx) => {
const supabase = createServiceClient()
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const cutoff = new Date()
cutoff.setDate(cutoff.getDate() - 30)
const { error, count } = await supabase
.from('event_log')
.delete({ count: 'exact' })
.lt('created_at', cutoff.toISOString())
if (error) {
ctx.log.error('event log cleanup failed', error)
return errorResponse(error, ctx.log, { requestId: ctx.requestId })
}
try {
const supabase = await createServiceClient()
const deleted = count ?? 0
ctx.log.info('event log cleanup summary', { deleted, cutoff: cutoff.toISOString() })
const cutoff = new Date()
cutoff.setDate(cutoff.getDate() - 30)
const { error, count } = await supabase
.from('event_log')
.delete({ count: 'exact' })
.lt('created_at', cutoff.toISOString())
if (error) throw error
const deleted = count ?? 0
console.log(`Event log cleanup completed: ${deleted} events removed`)
return NextResponse.json({ success: true, deleted })
} catch (error) {
console.error('Error in event log cleanup cron:', error)
return NextResponse.json(
{ error: 'Failed to clean up event log' },
{ status: 500 }
)
}
}
return NextResponse.json({ success: true, deleted })
})
@@ -1,6 +1,7 @@
import { createClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { verifyCronSecret } from '@/lib/auth/cron'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import {
performSync,
SCHEDULE_KEY,
@@ -20,18 +21,15 @@ import type { GoogleDriveSchedule } from '@/extensions/general/cloud-backup/type
* `extension_data` carries its own `user_id` (the user who configured the
* schedule), which we use as the "actor" when writing back the sync result.
*/
export async function GET(request: Request) {
const authError = verifyCronSecret(request)
if (authError) return authError
export const GET = withCronContext('cron.cloud_backup_auto_sync', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return NextResponse.json(
{ error: 'Missing Supabase configuration' },
{ status: 500 }
)
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
@@ -45,11 +43,11 @@ export async function GET(request: Request) {
.eq('key', SCHEDULE_KEY)
if (error) {
console.error('[cloud-backup-cron] Failed to fetch schedules', {
ctx.log.error('failed to fetch schedules', error, {
message: error.message,
code: error.code,
})
return NextResponse.json({ error: 'Failed to fetch schedules' }, { status: 500 })
return errorResponse(error, ctx.log, { requestId: ctx.requestId })
}
if (!rows || rows.length === 0) {
@@ -86,9 +84,10 @@ export async function GET(request: Request) {
for (const row of candidates) {
if (Date.now() - startTime > TIME_BUDGET_MS) {
console.log(
`[cloud-backup-cron] Time budget reached after ${results.length} companies; ${candidates.length - results.length} skipped until next run`
)
ctx.log.info('time budget reached', {
processedSoFar: results.length,
skipped: candidates.length - results.length,
})
break
}
@@ -120,9 +119,8 @@ export async function GET(request: Request) {
})
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error'
console.error('[cloud-backup-cron] Sync failed for company', {
ctx.log.error('cloud backup sync failed for company', err as Error, {
companyId,
message,
})
const updated: GoogleDriveSchedule = {
@@ -133,8 +131,8 @@ export async function GET(request: Request) {
}
await saveExtensionData(supabase, companyId, userId, SCHEDULE_KEY, updated).catch(
(persistErr) => {
console.error('[cloud-backup-cron] Failed to persist failure state', persistErr)
}
ctx.log.error('failed to persist failure state', persistErr as Error, { companyId })
},
)
results.push({ companyId, status: 'error', error: message })
@@ -144,9 +142,11 @@ export async function GET(request: Request) {
const successCount = results.filter((r) => r.status === 'success').length
const errorCount = results.filter((r) => r.status === 'error').length
console.log(
`[cloud-backup-cron] Processed ${results.length} companies: ${successCount} succeeded, ${errorCount} failed`
)
ctx.log.info('cloud backup cron summary', {
processed: results.length,
succeeded: successCount,
failed: errorCount,
})
return NextResponse.json({
checked: rows.length,
@@ -156,4 +156,4 @@ export async function GET(request: Request) {
errors: errorCount,
results,
})
}
})
@@ -10,7 +10,8 @@ import {
generateConsentExpiryEmailSubject,
} from '@/lib/email/consent-notification-templates'
import { ensureInitialized } from '@/lib/init'
import { verifyCronSecret } from '@/lib/auth/cron'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { getBranding } from '@/lib/branding/service'
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
@@ -25,18 +26,15 @@ ensureInitialized()
* Prioritizes connections not synced for the longest time.
* Deduplication via external_id makes repeated runs safe.
*/
export async function GET(request: Request) {
const authError = verifyCronSecret(request)
if (authError) return authError
export const GET = withCronContext('cron.bank_sync', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return NextResponse.json(
{ error: 'Missing Supabase configuration' },
{ status: 500 }
)
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
@@ -51,7 +49,7 @@ export async function GET(request: Request) {
.select('id')
if (stalePending?.length) {
console.log(`[bank-sync-cron] Cleaned up ${stalePending.length} stale pending connections`)
ctx.log.info('cleaned up stale pending connections', { count: stalePending.length })
}
const { data: connections, error: connError } = await supabase
@@ -62,12 +60,11 @@ export async function GET(request: Request) {
.limit(50)
if (connError) {
console.error('[bank-sync-cron] Failed to fetch bank connections', {
ctx.log.error('failed to fetch bank connections', connError, {
message: connError.message,
code: connError.code,
details: connError.details,
})
return NextResponse.json({ error: 'Failed to fetch connections' }, { status: 500 })
return errorResponse(connError, ctx.log, { requestId: ctx.requestId })
}
if (!connections || connections.length === 0) {
@@ -91,7 +88,7 @@ export async function GET(request: Request) {
for (const connection of connections) {
if (Date.now() - startTime > TIME_BUDGET_MS) {
console.log(`[bank-sync-cron] Time budget reached after ${results.length} connections`)
ctx.log.info('time budget reached', { processedSoFar: results.length })
break
}
@@ -137,7 +134,10 @@ export async function GET(request: Request) {
const isFirstSync = !connection.last_synced_at
const lookbackDays = isFirstSync ? 90 : 7
if (isFirstSync) {
console.log(`[bank-sync-cron] First sync for connection ${connection.id}, using ${lookbackDays}-day lookback`)
ctx.log.info('first sync for connection — using 90-day lookback', {
connectionId: connection.id,
lookbackDays,
})
}
const fromDate = new Date(Date.now() - lookbackDays * 24 * 60 * 60 * 1000)
.toISOString()
@@ -212,16 +212,12 @@ export async function GET(request: Request) {
})
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error'
console.error('[bank-sync-cron] Sync failed for connection', {
ctx.log.error('sync failed for connection', error as Error, {
connectionId: connection.id,
userId: connection.user_id,
bankName: connection.bank_name,
sessionId: '[REDACTED]',
consentExpires: connection.consent_expires,
lastSyncedAt: connection.last_synced_at,
message,
stack: error instanceof Error ? error.stack : undefined,
name: error instanceof Error ? error.name : undefined,
})
// Persist error status on sync failure
@@ -247,7 +243,13 @@ export async function GET(request: Request) {
const totalExpiringSoon = results.filter(r => r.status === 'expiring_soon').length
const totalFailed = results.filter(r => r.status === 'error').length
console.log(`[bank-sync-cron] Processed ${results.length} connections: ${totalImported} imported, ${totalExpired} expired, ${totalExpiringSoon} expiring soon, ${totalFailed} failed`)
ctx.log.info('bank sync summary', {
processed: results.length,
totalImported,
totalExpired,
totalExpiringSoon,
totalFailed,
})
return NextResponse.json({
processed: results.length,
@@ -257,7 +259,7 @@ export async function GET(request: Request) {
totalFailed,
results,
})
}
})
/**
* Send consent expiry notification email.
@@ -316,7 +318,8 @@ async function sendConsentExpiryNotification(
.update({ last_expiry_notification_at: new Date().toISOString() })
.eq('id', connection.id as string)
} catch (error) {
// Notification failure must not break the cron job
console.error(`[bank-sync-cron] Failed to send consent expiry notification:`, error)
// Notification failure must not break the cron job — log only.
// eslint-disable-next-line no-console
console.error('[bank-sync-cron] failed to send consent expiry notification:', error)
}
}
+107 -17
View File
@@ -4,8 +4,64 @@ import { ensureInitialized } from '@/lib/init'
import { extensionRegistry } from '@/lib/extensions/registry'
import { createExtensionContext } from '@/lib/extensions/context-factory'
import { requireCompanyId } from '@/lib/company/context'
import { createLogger } from '@/lib/logger'
import type { ApiRouteDefinition } from '@/lib/extensions/types'
const dispatcherLog = createLogger('extension-dispatcher')
function generateRequestId(): string {
return `req_${crypto.randomUUID()}`
}
/**
* Wrap a Response so support staff can find the inbound request in stdout
* logs by id:
*
* 1. set the `X-Request-Id` header if missing
* 2. for JSON error envelopes (`{ error: { code, ... } }`) that came back
* without a requestId, inject one into the body so the toast can show
* `Felreferens: req_…`
*
* Non-JSON responses (HTML for OAuth callbacks, file downloads) only get the
* header — body rewriting is reserved for the canonical envelope shape.
*/
async function decorateResponse(response: Response, requestId: string): Promise<Response> {
if (!response.headers.get('X-Request-Id')) {
response.headers.set('X-Request-Id', requestId)
}
if (!response.ok) {
const contentType = response.headers.get('content-type') || ''
if (contentType.includes('application/json')) {
try {
const cloned = response.clone()
const body = await cloned.json()
if (
body &&
typeof body === 'object' &&
body.error &&
typeof body.error === 'object' &&
typeof body.error.code === 'string' &&
!body.error.requestId
) {
const augmented = {
...body,
error: { ...body.error, requestId },
}
return new NextResponse(JSON.stringify(augmented), {
status: response.status,
headers: response.headers,
})
}
} catch {
// Body wasn't valid JSON — leave it alone.
}
}
}
return response
}
ensureInitialized()
// Heavy extension routes (SIE import, migration) need up to 5 minutes
@@ -75,20 +131,31 @@ async function handleRequest(
request: Request,
{ params }: { params: Promise<{ path: string[] }> }
): Promise<Response> {
const requestId = generateRequestId()
const start = Date.now()
const segments = await params
if (!segments.path || segments.path.length < 1) {
return NextResponse.json({ error: 'Invalid extension route' }, { status: 400 })
return decorateResponse(
NextResponse.json({ error: 'Invalid extension route' }, { status: 400 }),
requestId,
)
}
const [extensionId, ...rest] = segments.path
const routePath = '/' + rest.join('/')
const method = request.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
const log = dispatcherLog.child({ requestId, extensionId, routePath, method })
// Look up extension
const extension = extensionRegistry.get(extensionId)
if (!extension || !extension.apiRoutes || extension.apiRoutes.length === 0) {
return NextResponse.json({ error: 'Extension not found' }, { status: 404 })
log.warn('extension not found')
return decorateResponse(
NextResponse.json({ error: 'Extension not found' }, { status: 404 }),
requestId,
)
}
// Per-extension feature flags. Lets us toggle a single integration off
@@ -97,9 +164,12 @@ async function handleRequest(
// render an "extension disabled" empty state.
const flag = EXTENSION_FEATURE_FLAGS[extensionId]
if (flag && process.env[flag.envVar] !== 'true') {
return NextResponse.json(
{ error: flag.disabledMessage, code: 'EXTENSION_DISABLED' },
{ status: 503 },
return decorateResponse(
NextResponse.json(
{ error: flag.disabledMessage, code: 'EXTENSION_DISABLED' },
{ status: 503 },
),
requestId,
)
}
@@ -119,7 +189,10 @@ async function handleRequest(
}
if (!matchedRoute) {
return NextResponse.json({ error: 'Route not found' }, { status: 404 })
return decorateResponse(
NextResponse.json({ error: 'Route not found' }, { status: 404 }),
requestId,
)
}
// Config sanity check: these flags are orthogonal and the combination is
@@ -129,12 +202,11 @@ async function handleRequest(
// the auth requirement would be silently dropped (skipAuth fires first
// below). Fail loudly instead of masking the mistake.
if (matchedRoute.skipAuth && matchedRoute.skipCompanyContext) {
console.error('[extension-dispatcher] route misconfigured: skipAuth + skipCompanyContext are mutually exclusive', {
extensionId,
routePath,
method,
})
return NextResponse.json({ error: 'Route misconfigured' }, { status: 500 })
log.error('route misconfigured: skipAuth + skipCompanyContext are mutually exclusive', undefined)
return decorateResponse(
NextResponse.json({ error: 'Route misconfigured' }, { status: 500 }),
requestId,
)
}
// For skipAuth routes (e.g. OAuth callbacks from external providers),
@@ -155,7 +227,9 @@ async function handleRequest(
duplex: 'half',
})
}
return matchedRoute.handler(handlerRequest)
const response = await matchedRoute.handler(handlerRequest)
log.info('extension call completed', { durationMs: Date.now() - start, status: response.status })
return decorateResponse(response, requestId)
}
// Auth check
@@ -163,7 +237,10 @@ async function handleRequest(
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
return decorateResponse(
NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
requestId,
)
}
// If path params were extracted, create a new Request with them as search params
@@ -188,14 +265,27 @@ async function handleRequest(
// /lookup during onboarding, for example) opt out of company resolution.
// Dispatch without a context — handlers that opt in must not rely on ctx.
if (matchedRoute.skipCompanyContext) {
return matchedRoute.handler(handlerRequest)
const response = await matchedRoute.handler(handlerRequest)
log.info('extension call completed', {
durationMs: Date.now() - start,
status: response.status,
userId: user.id,
})
return decorateResponse(response, requestId)
}
const companyId = await requireCompanyId(supabase, user.id)
// Build context and dispatch
const ctx = createExtensionContext(supabase, user.id, companyId, extensionId)
return matchedRoute.handler(handlerRequest, ctx)
const ctx = createExtensionContext(supabase, user.id, companyId, extensionId, requestId)
const response = await matchedRoute.handler(handlerRequest, ctx)
log.info('extension call completed', {
durationMs: Date.now() - start,
status: response.status,
userId: user.id,
companyId,
})
return decorateResponse(response, requestId)
}
export const GET = handleRequest
@@ -6,41 +6,30 @@ import {
sendInvoiceNotifications,
sendMissingUnderlagNotifications,
} from '@/extensions/general/push-notifications/notification-scheduler'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET /api/extensions/push-notifications/cron
* Daily cron job to send push notifications
* Runs at 09:00 every day
*
* Vercel Cron: "0 9 * * *"
* GET /api/extensions/push-notifications/cron — daily 09:00 UTC.
* Sends due tax, invoice and missing-underlag push notifications.
*/
export async function GET(request: Request) {
// Ensure extensions are loaded so event handlers are registered
export const GET = withCronContext('cron.push_notifications', async (_request, ctx) => {
// Ensure extensions are loaded so event handlers are registered.
loadExtensions()
// Verify cron secret for security
const authHeader = request.headers.get('authorization')
const cronSecret = process.env.CRON_SECRET
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Create a service role client for accessing all user data
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return NextResponse.json(
{ error: 'Missing Supabase configuration' },
{ status: 500 }
)
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
try {
// Send all notification types in parallel
const [taxResult, invoiceResult, underlagResult] = await Promise.all([
sendTaxDeadlineNotifications(supabase),
sendInvoiceNotifications(supabase),
@@ -50,18 +39,13 @@ export async function GET(request: Request) {
const totalSent = taxResult.sent + invoiceResult.sent + underlagResult.sent
const totalSkipped = taxResult.skipped + invoiceResult.skipped + underlagResult.skipped
console.log(
`Push notification cron completed: ${totalSent} sent, ${totalSkipped} skipped`
)
console.log(
` Tax: ${taxResult.sent} sent, ${taxResult.skipped} skipped`
)
console.log(
` Invoice: ${invoiceResult.sent} sent, ${invoiceResult.skipped} skipped`
)
console.log(
` Missing underlag: ${underlagResult.sent} sent, ${underlagResult.skipped} skipped`
)
ctx.log.info('push notification cron summary', {
totalSent,
totalSkipped,
taxSent: taxResult.sent,
invoiceSent: invoiceResult.sent,
underlagSent: underlagResult.sent,
})
return NextResponse.json({
success: true,
@@ -73,11 +57,8 @@ export async function GET(request: Request) {
missingUnderlag: underlagResult,
},
})
} catch (error) {
console.error('Error in push notification cron:', error)
return NextResponse.json(
{ error: 'Failed to send push notifications' },
{ status: 500 }
)
} catch (err) {
ctx.log.error('push notification cron failed', err as Error)
return errorResponse(err, ctx.log, { requestId: ctx.requestId })
}
}
})
+10 -20
View File
@@ -1,31 +1,21 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { cleanupExpiredIdempotencyKeys } from '@/lib/api/idempotency'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse } from '@/lib/errors/get-structured-error'
/**
* GET /api/idempotency/cleanup/cron
*
* Sweeps idempotency_keys rows past their 24h TTL. Cron runs hourly so the
* working set stays small even under heavy agent retry traffic.
* GET /api/idempotency/cleanup/cron — hourly.
* Sweeps idempotency_keys past their 24h TTL.
*/
export async function GET(request: Request) {
const authHeader = request.headers.get('authorization')
const cronSecret = process.env.CRON_SECRET
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
export const GET = withCronContext('cron.idempotency_cleanup', async (_request, ctx) => {
try {
const supabase = await createServiceClient()
const deleted = await cleanupExpiredIdempotencyKeys(supabase)
console.log(`Idempotency keys cleanup completed: ${deleted} rows removed`)
ctx.log.info('idempotency cleanup summary', { deleted })
return NextResponse.json({ success: true, deleted })
} catch (error) {
console.error('Error in idempotency cleanup cron:', error)
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Failed to clean up idempotency keys' },
{ status: 500 }
)
} catch (err) {
ctx.log.error('idempotency cleanup failed', err as Error)
return errorResponse(err, ctx.log, { requestId: ctx.requestId })
}
}
})
+121 -112
View File
@@ -1,4 +1,3 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
@@ -6,6 +5,8 @@ import { ingestTransactions, type RawTransaction } from '@/lib/transactions/inge
import { generateExternalId } from '@/lib/import/bank-file/parser'
import type { IngestOptions } from '@/types'
import { getCompanyRole } from '@/lib/auth/require-write'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { ParsedBankTransaction, BankFileFormatId } from '@/lib/import/bank-file/types'
import type { Transaction } from '@/types'
@@ -24,119 +25,127 @@ interface ExecuteRequest {
/**
* POST /api/import/bank-file/execute
*
* Executes the import of confirmed bank transactions.
* Records import in bank_file_imports, calls ingestTransactions(),
* emits transaction.synced event.
* Executes the import of confirmed bank transactions. Records the import in
* `bank_file_imports`, calls `ingestTransactions`, and emits `transaction.synced`.
*/
export async function POST(request: Request) {
const supabase = await createClient()
export const POST = withRouteContext(
'bank_file.execute',
async (request, ctx) => {
const { user, supabase, log, requestId } = ctx
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const roleCheck = await getCompanyRole(supabase, user.id)
if (!roleCheck.ok) return roleCheck.response
const { role, companyId } = roleCheck
const body: ExecuteRequest = await request.json()
const { transactions, format, filename, file_hash, skip_duplicates: _skip_duplicates = true, auto_categorize: _auto_categorize = true, settlement_account } = body
if (!transactions || transactions.length === 0) {
return NextResponse.json({ error: 'No transactions to import' }, { status: 400 })
}
try {
// Create import record
const { data: importRecord, error: importError } = await supabase
.from('bank_file_imports')
.upsert({
user_id: user.id,
company_id: companyId,
filename,
file_hash,
file_format: format,
transaction_count: transactions.length,
status: 'processing',
date_from: transactions.map(t => t.date).sort()[0] || null,
date_to: transactions.map(t => t.date).sort().reverse()[0] || null,
}, {
onConflict: 'user_id,file_hash',
})
.select()
.single()
if (importError) {
console.error('Failed to create import record:', importError)
return NextResponse.json({ error: 'Failed to create import record' }, { status: 500 })
}
// Convert parsed transactions to RawTransaction format
const rawTransactions: RawTransaction[] = transactions.map((tx, index) => ({
date: tx.date,
description: tx.description,
amount: tx.amount,
currency: tx.currency || 'SEK',
external_id: generateExternalId(tx, format, index),
reference: tx.reference || null,
import_source: format === 'camt053' ? 'camt053' : `csv_${format}`,
}))
// Run ingestion pipeline — viewers get rawInsertOnly (no categorization, no matching)
const ingestOptions: IngestOptions = {}
if (settlement_account) ingestOptions.settlementAccount = settlement_account
if (role === 'viewer') ingestOptions.rawInsertOnly = true
const ingestResult = await ingestTransactions(supabase, companyId, user.id, rawTransactions, ingestOptions)
// Update import record with results
await supabase
.from('bank_file_imports')
.update({
imported_count: ingestResult.imported,
duplicate_count: ingestResult.duplicates,
matched_count: ingestResult.auto_matched_invoices,
status: ingestResult.errors > 0 && ingestResult.imported === 0 ? 'failed' : 'completed',
error_message: ingestResult.errors > 0
? `${ingestResult.errors} transactions failed to import`
: null,
})
.eq('id', importRecord.id)
// Emit event with newly imported transactions
if (ingestResult.imported > 0 && ingestResult.transaction_ids.length > 0) {
try {
const { data: importedTransactions } = await supabase
.from('transactions')
.select('*')
.in('id', ingestResult.transaction_ids)
if (importedTransactions && importedTransactions.length > 0) {
await eventBus.emit({
type: 'transaction.synced',
payload: {
transactions: importedTransactions as Transaction[],
userId: user.id,
companyId,
},
})
}
} catch {
// Non-critical event emission
// We still call getCompanyRole because viewers are allowed through with
// rawInsertOnly behavior — `requireWrite: true` would block them.
const roleCheck = await getCompanyRole(supabase, user.id)
if (!roleCheck.ok) {
// Inject the request id for traceability and pass through.
if (!roleCheck.response.headers.get('X-Request-Id')) {
roleCheck.response.headers.set('X-Request-Id', requestId)
}
return roleCheck.response
}
const { role, companyId } = roleCheck
const body: ExecuteRequest = await request.json()
const {
transactions, format, filename, file_hash,
skip_duplicates: _skip_duplicates = true,
auto_categorize: _auto_categorize = true,
settlement_account,
} = body
if (!transactions || transactions.length === 0) {
return errorResponseFromCode('BANK_FILE_NO_TRANSACTIONS', log, { requestId })
}
return NextResponse.json({
data: {
import_id: importRecord.id,
...ingestResult,
},
})
} catch (error) {
console.error('Bank file execute error:', error)
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Import failed' },
{ status: 500 }
)
}
}
const opLog = log.child({ filename, fileHash: file_hash, txCount: transactions.length })
try {
const { data: importRecord, error: importError } = await supabase
.from('bank_file_imports')
.upsert({
user_id: user.id,
company_id: companyId,
filename,
file_hash,
file_format: format,
transaction_count: transactions.length,
status: 'processing',
date_from: transactions.map((t) => t.date).sort()[0] || null,
date_to: transactions.map((t) => t.date).sort().reverse()[0] || null,
}, { onConflict: 'user_id,file_hash' })
.select()
.single()
if (importError) {
opLog.error('failed to create bank_file_imports record', importError)
return errorResponseFromCode('BANK_FILE_IMPORT_RECORD_FAILED', opLog, {
requestId,
details: { reason: importError.message },
})
}
const rawTransactions: RawTransaction[] = transactions.map((tx, index) => ({
date: tx.date,
description: tx.description,
amount: tx.amount,
currency: tx.currency || 'SEK',
external_id: generateExternalId(tx, format, index),
reference: tx.reference || null,
import_source: format === 'camt053' ? 'camt053' : `csv_${format}`,
}))
const ingestOptions: IngestOptions = {}
if (settlement_account) ingestOptions.settlementAccount = settlement_account
if (role === 'viewer') ingestOptions.rawInsertOnly = true
const ingestResult = await ingestTransactions(supabase, companyId, user.id, rawTransactions, ingestOptions)
await supabase
.from('bank_file_imports')
.update({
imported_count: ingestResult.imported,
duplicate_count: ingestResult.duplicates,
matched_count: ingestResult.auto_matched_invoices,
status: ingestResult.errors > 0 && ingestResult.imported === 0 ? 'failed' : 'completed',
error_message: ingestResult.errors > 0
? `${ingestResult.errors} transactions failed to import`
: null,
})
.eq('id', importRecord.id)
if (ingestResult.imported > 0 && ingestResult.transaction_ids.length > 0) {
try {
const { data: importedTransactions } = await supabase
.from('transactions')
.select('*')
.in('id', ingestResult.transaction_ids)
if (importedTransactions && importedTransactions.length > 0) {
await eventBus.emit({
type: 'transaction.synced',
payload: {
transactions: importedTransactions as Transaction[],
userId: user.id,
companyId,
},
})
}
} catch (err) {
opLog.warn('transaction.synced event emission failed', err as Error)
}
}
return NextResponse.json({
data: {
import_id: importRecord.id,
...ingestResult,
},
})
} catch (err) {
opLog.error('bank file execute failed', err as Error)
return errorResponseFromCode('BANK_FILE_EXECUTE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? err.message : 'unknown' },
})
}
},
)
+80 -83
View File
@@ -1,101 +1,98 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { parseBankFile, generateFileHash, detectFileFormat } from '@/lib/import/bank-file/parser'
import { decodeFileContent } from '@/lib/import/bank-file/encoding'
import { requireCompanyId } from '@/lib/company/context'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { BankFileFormatId } from '@/lib/import/bank-file/types'
/**
* POST /api/import/bank-file/parse
*
* Accepts a bank file (CSV/XML) via FormData, auto-detects format,
* returns parsed transactions preview with duplicate detection.
* Accepts a bank file (CSV/XML) via FormData, auto-detects format, and returns
* a parsed transactions preview with duplicate detection.
*/
export async function POST(request: Request) {
const supabase = await createClient()
export const POST = withRouteContext(
'bank_file.parse',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const formData = await request.formData()
const file = formData.get('file') as File | null
const formatOverride = formData.get('format') as BankFileFormatId | null
const companyId = await requireCompanyId(supabase, user.id)
const formData = await request.formData()
const file = formData.get('file') as File | null
const formatOverride = formData.get('format') as BankFileFormatId | null
if (!file) {
return NextResponse.json({ error: 'No file provided' }, { status: 400 })
}
// Validate file size (10MB max)
if (file.size > 10 * 1024 * 1024) {
return NextResponse.json({ error: 'File too large (max 10MB)' }, { status: 400 })
}
try {
// Read and decode file content
const arrayBuffer = await file.arrayBuffer()
const content = decodeFileContent(arrayBuffer)
const fileHash = generateFileHash(content)
// Check if this exact file has been imported before
const { data: existingImport } = await supabase
.from('bank_file_imports')
.select('id, status, imported_count, created_at')
.eq('company_id', companyId)
.eq('file_hash', fileHash)
.single()
if (existingImport && existingImport.status === 'completed') {
return NextResponse.json({
error: 'duplicate',
message: `Den här filen har redan importerats (${existingImport.imported_count} transaktioner, ${new Date(existingImport.created_at).toLocaleDateString('sv-SE')})`,
}, { status: 409 })
if (!file) {
return errorResponseFromCode('BANK_FILE_NO_FILE', log, { requestId })
}
// Auto-detect or use specified format
const detectedFormat = formatOverride
? null
: detectFileFormat(content, file.name)
if (file.size > 10 * 1024 * 1024) {
return errorResponseFromCode('BANK_FILE_TOO_LARGE', log, {
requestId,
details: { sizeMb: +(file.size / 1024 / 1024).toFixed(1) },
})
}
// Parse the file
const parseResult = parseBankFile(content, file.name, formatOverride || undefined)
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
// Check for existing transactions (duplicate detection for preview)
let existingCount = 0
if (parseResult.transactions.length > 0) {
// Sample check: look for transactions with matching dates and amounts
const { count } = await supabase
.from('transactions')
.select('*', { count: 'exact', head: true })
try {
const arrayBuffer = await file.arrayBuffer()
const content = decodeFileContent(arrayBuffer)
const fileHash = generateFileHash(content)
const { data: existingImport } = await supabase
.from('bank_file_imports')
.select('id, status, imported_count, created_at')
.eq('company_id', companyId)
.gte('date', parseResult.date_from || '1970-01-01')
.lte('date', parseResult.date_to || '2099-12-31')
.eq('file_hash', fileHash)
.single()
existingCount = count || 0
if (existingImport && existingImport.status === 'completed') {
return errorResponseFromCode('BANK_FILE_DUPLICATE', opLog, {
requestId,
details: {
importId: existingImport.id,
importedCount: existingImport.imported_count,
importedAt: existingImport.created_at,
},
})
}
const detectedFormat = formatOverride
? null
: detectFileFormat(content, file.name)
const parseResult = parseBankFile(content, file.name, formatOverride || undefined)
let existingCount = 0
if (parseResult.transactions.length > 0) {
const { count } = await supabase
.from('transactions')
.select('*', { count: 'exact', head: true })
.eq('company_id', companyId)
.gte('date', parseResult.date_from || '1970-01-01')
.lte('date', parseResult.date_to || '2099-12-31')
existingCount = count || 0
}
return NextResponse.json({
data: {
parse_result: parseResult,
detected_format: detectedFormat?.id || formatOverride || null,
detected_format_name: detectedFormat?.name || parseResult.format_name,
file_hash: fileHash,
filename: file.name,
existing_transaction_count: existingCount,
headers: parseResult.format === 'generic_csv'
? content.split('\n')[0]?.split(',').map((h) => h.trim()) || []
: null,
},
})
} catch (err) {
opLog.error('bank file parse failed', err as Error)
return errorResponseFromCode('BANK_FILE_PARSE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? err.message : 'unknown' },
})
}
return NextResponse.json({
data: {
parse_result: parseResult,
detected_format: detectedFormat?.id || formatOverride || null,
detected_format_name: detectedFormat?.name || parseResult.format_name,
file_hash: fileHash,
filename: file.name,
existing_transaction_count: existingCount,
// Return first row headers for generic CSV column mapping
headers: parseResult.format === 'generic_csv'
? content.split('\n')[0]?.split(',').map(h => h.trim()) || []
: null,
},
})
} catch (error) {
console.error('Bank file parse error:', error)
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Failed to parse file' },
{ status: 500 }
)
}
}
},
)
@@ -21,6 +21,7 @@ vi.mock('@/lib/auth/require-write', () => ({
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const mockCreateJournalEntry = vi.fn()
@@ -101,7 +102,7 @@ describe('POST /api/import/opening-balance/execute', () => {
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(body.error).toContain('hittades inte')
expect((body.error as unknown as { code: string }).code).toBe('OB_PERIOD_NOT_FOUND')
})
it('returns 409 if period already has opening balances', async () => {
@@ -127,7 +128,10 @@ describe('POST /api/import/opening-balance/execute', () => {
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(409)
expect(body.existing_entry_id).toBe('entry-existing')
expect((body.error as unknown as { code: string }).code).toBe('OB_PERIOD_ALREADY_HAS_BALANCES')
expect(
(body.error as unknown as { details: { existingEntryId: string } }).details.existingEntryId,
).toBe('entry-existing')
})
it('returns 400 for unbalanced lines', async () => {
@@ -152,7 +156,7 @@ describe('POST /api/import/opening-balance/execute', () => {
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(400)
expect(body.error).toContain('balanserar inte')
expect((body.error as unknown as { code: string }).code).toBe('OB_UNBALANCED')
})
it('returns 400 for P&L accounts', async () => {
@@ -177,7 +181,7 @@ describe('POST /api/import/opening-balance/execute', () => {
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(400)
expect(body.error).toContain('Resultatkonton')
expect((body.error as unknown as { code: string }).code).toBe('OB_PNL_ACCOUNT')
})
it('creates journal entry on success', async () => {
+195 -220
View File
@@ -1,14 +1,13 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { validateBody } from '@/lib/api/validate'
import { OpeningBalanceExecuteSchema } from '@/lib/api/schemas'
import { requireWritePermission } from '@/lib/auth/require-write'
import { requireCompanyId } from '@/lib/company/context'
import { createJournalEntry } from '@/lib/bookkeeping/engine'
import { bookkeepingErrorResponse } from '@/lib/bookkeeping/errors'
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { CreateJournalEntryLineInput } from '@/types'
ensureInitialized()
@@ -16,238 +15,214 @@ ensureInitialized()
/**
* POST /api/import/opening-balance/execute
*
* Creates an opening balance journal entry from user-confirmed lines.
* Auto-activates BAS accounts not yet in the company's chart.
* Creates an opening balance journal entry from user-confirmed lines and
* auto-activates BAS accounts not yet in the company's chart.
*/
export async function POST(request: Request) {
const supabase = await createClient()
export const POST = withRouteContext(
'opening_balance.execute',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const result = await validateBody(request, OpeningBalanceExecuteSchema, {
log,
operation: 'opening_balance.execute',
})
if (!result.success) return result.response
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const { fiscal_period_id, lines } = result.data
const opLog = log.child({ fiscalPeriodId: fiscal_period_id })
const result = await validateBody(request, OpeningBalanceExecuteSchema)
if (!result.success) return result.response
const { fiscal_period_id, lines } = result.data
let companyId: string
try {
companyId = await requireCompanyId(supabase, user.id)
} catch {
return NextResponse.json({ error: 'Inget aktivt företag' }, { status: 400 })
}
try {
// 1. Verify fiscal period exists, belongs to company, and is not closed/locked
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('*')
.eq('id', fiscal_period_id)
.eq('company_id', companyId)
.single()
if (periodError || !period) {
return NextResponse.json(
{ error: 'Räkenskapsperioden hittades inte' },
{ status: 404 },
)
}
if (period.is_closed) {
return NextResponse.json(
{ error: 'Räkenskapsperioden är stängd' },
{ status: 400 },
)
}
if (period.locked_at) {
return NextResponse.json(
{ error: 'Räkenskapsperioden är låst' },
{ status: 400 },
)
}
// 2. Check if period already has opening balances
if (period.opening_balances_set) {
return NextResponse.json(
{
error: 'Räkenskapsperioden har redan ingående balanser',
existing_entry_id: period.opening_balance_entry_id,
},
{ status: 409 },
)
}
// 3. Filter out zero-amount lines and validate no P&L accounts
const validLines = lines.filter((l) => l.debit_amount > 0 || l.credit_amount > 0)
if (validLines.length < 2) {
return NextResponse.json(
{ error: 'Minst två rader med belopp krävs' },
{ status: 400 },
)
}
// Reject class 3-8 accounts
const pnlAccounts = validLines
.map((l) => l.account_number)
.filter((num) => {
const cls = parseInt(num.charAt(0), 10)
return cls >= 3 && cls <= 8
})
if (pnlAccounts.length > 0) {
return NextResponse.json(
{
error: `Resultatkonton (klass 3-8) kan inte användas i ingående balanser: ${pnlAccounts.slice(0, 5).join(', ')}`,
},
{ status: 400 },
)
}
// 4. Verify balance
let totalDebit = 0
let totalCredit = 0
for (const line of validLines) {
totalDebit = Math.round((totalDebit + line.debit_amount) * 100) / 100
totalCredit = Math.round((totalCredit + line.credit_amount) * 100) / 100
}
const diff = Math.round((totalDebit - totalCredit) * 100) / 100
if (Math.abs(diff) >= 0.01) {
return NextResponse.json(
{ error: `Debet och kredit balanserar inte — differens: ${diff.toFixed(2)} SEK` },
{ status: 400 },
)
}
// 5. Auto-activate BAS accounts not in company's chart
const accountNumbers = [...new Set(validLines.map((l) => l.account_number))]
const existingAccounts = await fetchAllRows(({ from, to }) =>
supabase
.from('chart_of_accounts')
.select('account_number')
try {
// 1. Verify fiscal period belongs to the company and is open.
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('*')
.eq('id', fiscal_period_id)
.eq('company_id', companyId)
.range(from, to),
)
.single()
const existingNumbers = new Set(existingAccounts.map((a) => a.account_number))
const accountsToActivate = accountNumbers
.filter((num) => !existingNumbers.has(num))
.map((num) => {
const ref = getBASReference(num)
if (periodError || !period) {
return errorResponseFromCode('OB_PERIOD_NOT_FOUND', opLog, { requestId })
}
if (period.is_closed) {
return errorResponseFromCode('OB_PERIOD_CLOSED', opLog, { requestId })
}
if (period.locked_at) {
return errorResponseFromCode('OB_PERIOD_LOCKED', opLog, { requestId })
}
if (period.opening_balances_set) {
return errorResponseFromCode('OB_PERIOD_ALREADY_HAS_BALANCES', opLog, {
requestId,
details: { existingEntryId: period.opening_balance_entry_id },
})
}
// 2. Filter zero-amount lines and reject P&L accounts.
const validLines = lines.filter((l) => l.debit_amount > 0 || l.credit_amount > 0)
if (validLines.length < 2) {
return errorResponseFromCode('OB_TOO_FEW_LINES', opLog, { requestId })
}
const pnlAccounts = validLines
.map((l) => l.account_number)
.filter((num) => {
const cls = parseInt(num.charAt(0), 10)
return cls >= 3 && cls <= 8
})
if (pnlAccounts.length > 0) {
return errorResponseFromCode('OB_PNL_ACCOUNT', opLog, {
requestId,
details: { accounts: pnlAccounts.slice(0, 5) },
})
}
// 3. Verify balance.
let totalDebit = 0
let totalCredit = 0
for (const line of validLines) {
totalDebit = Math.round((totalDebit + line.debit_amount) * 100) / 100
totalCredit = Math.round((totalCredit + line.credit_amount) * 100) / 100
}
const diff = Math.round((totalDebit - totalCredit) * 100) / 100
if (Math.abs(diff) >= 0.01) {
return errorResponseFromCode('OB_UNBALANCED', opLog, {
requestId,
details: { totalDebit, totalCredit, diff },
})
}
// 4. Auto-activate BAS accounts not in the company's chart.
const accountNumbers = [...new Set(validLines.map((l) => l.account_number))]
const existingAccounts = await fetchAllRows(({ from, to }) =>
supabase
.from('chart_of_accounts')
.select('account_number')
.eq('company_id', companyId)
.range(from, to),
)
const existingNumbers = new Set(existingAccounts.map((a) => a.account_number))
const accountsToActivate = accountNumbers
.filter((num) => !existingNumbers.has(num))
.map((num) => {
const ref = getBASReference(num)
if (ref) {
return {
user_id: user.id,
company_id: companyId,
account_number: ref.account_number,
account_name: ref.account_name,
account_class: ref.account_class,
account_group: ref.account_group,
account_type: ref.account_type,
normal_balance: ref.normal_balance,
plan_type: 'full_bas' as const,
is_active: true,
is_system_account: false,
description: ref.description,
sru_code: ref.sru_code,
sort_order: parseInt(ref.account_number),
}
}
const accountClass = parseInt(num.charAt(0), 10)
const accountGroup = num.substring(0, 2)
const accountType =
accountClass === 1 ? 'asset'
: accountClass === 2 ? 'liability'
: accountClass === 3 ? 'revenue'
: 'expense'
const normalBalance = accountClass <= 1 || accountClass >= 4 ? 'debit' : 'credit'
if (ref) {
return {
user_id: user.id,
company_id: companyId,
account_number: ref.account_number,
account_name: ref.account_name,
account_class: ref.account_class,
account_group: ref.account_group,
account_type: ref.account_type,
normal_balance: ref.normal_balance,
account_number: num,
account_name: `Konto ${num}`,
account_class: accountClass,
account_group: accountGroup,
account_type: accountType,
normal_balance: normalBalance,
plan_type: 'full_bas' as const,
is_active: true,
is_system_account: false,
description: ref.description,
sru_code: ref.sru_code,
sort_order: parseInt(ref.account_number),
description: `Konto ${num}`,
sru_code: null,
sort_order: parseInt(num),
}
})
if (accountsToActivate.length > 0) {
const { error: activateError } = await supabase
.from('chart_of_accounts')
.insert(accountsToActivate)
if (activateError) {
opLog.error('opening balance account activation failed', activateError)
return errorResponseFromCode('OB_ACCOUNT_ACTIVATION_FAILED', opLog, {
requestId,
details: { reason: activateError.message },
})
}
// Derive metadata from account number
const accountClass = parseInt(num.charAt(0), 10)
const accountGroup = num.substring(0, 2)
const accountType =
accountClass === 1 ? 'asset'
: accountClass === 2 ? 'liability'
: accountClass === 3 ? 'revenue'
: 'expense'
const normalBalance = accountClass <= 1 || accountClass >= 4 ? 'debit' : 'credit'
return {
user_id: user.id,
company_id: companyId,
account_number: num,
account_name: `Konto ${num}`,
account_class: accountClass,
account_group: accountGroup,
account_type: accountType,
normal_balance: normalBalance,
plan_type: 'full_bas' as const,
is_active: true,
is_system_account: false,
description: `Konto ${num}`,
sru_code: null,
sort_order: parseInt(num),
}
})
if (accountsToActivate.length > 0) {
const { error: activateError } = await supabase
.from('chart_of_accounts')
.insert(accountsToActivate)
if (activateError) {
console.error('Failed to activate accounts:', activateError)
return NextResponse.json(
{ error: 'Kunde inte aktivera konton i kontoplanen' },
{ status: 500 },
)
}
}
// 6. Create journal entry via engine
const entryLines: CreateJournalEntryLineInput[] = validLines.map((line) => ({
account_number: line.account_number,
debit_amount: line.debit_amount,
credit_amount: line.credit_amount,
line_description: `IB ${line.account_number}`,
}))
// 5. Create the opening balance journal entry.
const entryLines: CreateJournalEntryLineInput[] = validLines.map((line) => ({
account_number: line.account_number,
debit_amount: line.debit_amount,
credit_amount: line.credit_amount,
line_description: `IB ${line.account_number}`,
}))
const entry = await createJournalEntry(supabase, companyId, user.id, {
fiscal_period_id,
entry_date: period.period_start,
description: 'Ingående balanser (Excel-import)',
source_type: 'opening_balance',
voucher_series: 'A',
lines: entryLines,
})
// 7. Update fiscal period
await supabase
.from('fiscal_periods')
.update({
opening_balance_entry_id: entry.id,
opening_balances_set: true,
})
.eq('id', fiscal_period_id)
.eq('company_id', companyId)
return NextResponse.json({
data: {
success: true,
journal_entry_id: entry.id,
const entry = await createJournalEntry(supabase, companyId!, user.id, {
fiscal_period_id,
lines_created: entryLines.length,
total_debit: totalDebit,
total_credit: totalCredit,
},
})
} catch (error) {
const typed = bookkeepingErrorResponse(error)
if (typed) return typed
console.error('Opening balance execute error:', error)
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Importen misslyckades' },
{ status: 500 },
)
}
}
entry_date: period.period_start,
description: 'Ingående balanser (Excel-import)',
source_type: 'opening_balance',
voucher_series: 'A',
lines: entryLines,
})
// 6. Mark the fiscal period.
await supabase
.from('fiscal_periods')
.update({
opening_balance_entry_id: entry.id,
opening_balances_set: true,
})
.eq('id', fiscal_period_id)
.eq('company_id', companyId)
return NextResponse.json({
data: {
success: true,
journal_entry_id: entry.id,
fiscal_period_id,
lines_created: entryLines.length,
total_debit: totalDebit,
total_credit: totalCredit,
},
})
} catch (err) {
// Bookkeeping errors flow through the standard envelope; everything else
// becomes OB_EXECUTE_FAILED so the user gets a Swedish toast.
if (isBookkeepingError(err)) {
return errorResponse(err, opLog, { requestId })
}
opLog.error('opening balance execute failed', err as Error)
return errorResponseFromCode('OB_EXECUTE_FAILED', opLog, {
requestId,
details: { reason: err instanceof Error ? err.message : 'unknown' },
})
}
},
{ requireWrite: true },
)

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