New Base func
This commit is contained in:
@@ -1,21 +1,32 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import JournalEntryList from '@/components/bookkeeping/JournalEntryList'
|
||||
import JournalEntryForm from '@/components/bookkeeping/JournalEntryForm'
|
||||
import ChartOfAccounts from '@/components/bookkeeping/ChartOfAccounts'
|
||||
import { Lock } from 'lucide-react'
|
||||
|
||||
export default function BookkeepingPage() {
|
||||
const [refreshKey, setRefreshKey] = useState(0)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Bokföring</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Verifikationer, kontoplan och manuella bokföringsorder
|
||||
</p>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Bokföring</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Verifikationer, kontoplan och manuella bokföringsorder
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/bookkeeping/year-end">
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Årsbokslut
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="journal">
|
||||
|
||||
@@ -0,0 +1,699 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { SuccessAnimation } from '@/components/ui/success-animation'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
AlertTriangle,
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
Loader2,
|
||||
Lock,
|
||||
BookOpen,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
} from 'lucide-react'
|
||||
import type {
|
||||
FiscalPeriod,
|
||||
YearEndValidation,
|
||||
YearEndPreview,
|
||||
YearEndResult,
|
||||
} from '@/types'
|
||||
|
||||
function formatAmount(amount: number): string {
|
||||
return amount.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})
|
||||
}
|
||||
|
||||
const STEP_LABELS = ['Välj period', 'Validering', 'Förhandsgranskning', 'Genomför']
|
||||
|
||||
export default function YearEndPage() {
|
||||
const { toast } = useToast()
|
||||
|
||||
const [step, setStep] = useState(0)
|
||||
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
|
||||
const [selectedPeriodId, setSelectedPeriodId] = useState('')
|
||||
const [validation, setValidation] = useState<YearEndValidation | null>(null)
|
||||
const [preview, setPreview] = useState<YearEndPreview | null>(null)
|
||||
const [result, setResult] = useState<YearEndResult | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [loadingPeriods, setLoadingPeriods] = useState(true)
|
||||
const [executing, setExecuting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showConfirmDialog, setShowConfirmDialog] = useState(false)
|
||||
const [showLinesDetail, setShowLinesDetail] = useState(false)
|
||||
const [showSuccess, setShowSuccess] = useState(false)
|
||||
|
||||
const selectedPeriod = periods.find((p) => p.id === selectedPeriodId)
|
||||
|
||||
useEffect(() => {
|
||||
fetchPeriods()
|
||||
}, [])
|
||||
|
||||
async function fetchPeriods() {
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/fiscal-periods')
|
||||
const { data } = await res.json()
|
||||
const allPeriods: FiscalPeriod[] = data || []
|
||||
setPeriods(allPeriods)
|
||||
// Pre-select first open period
|
||||
const openPeriod = allPeriods.find((p) => !p.is_closed)
|
||||
if (openPeriod) {
|
||||
setSelectedPeriodId(openPeriod.id)
|
||||
}
|
||||
} catch {
|
||||
toast({ title: 'Fel', description: 'Kunde inte hämta räkenskapsår', variant: 'destructive' })
|
||||
} finally {
|
||||
setLoadingPeriods(false)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchValidationAndPreview = useCallback(async () => {
|
||||
if (!selectedPeriodId) return
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
setValidation(null)
|
||||
setPreview(null)
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/bookkeeping/fiscal-periods/${selectedPeriodId}/year-end`)
|
||||
const json = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
setError(json.error || 'Kunde inte validera perioden')
|
||||
return
|
||||
}
|
||||
|
||||
setValidation(json.data.validation)
|
||||
setPreview(json.data.preview)
|
||||
} catch {
|
||||
setError('Nätverksfel vid validering')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [selectedPeriodId])
|
||||
|
||||
async function executeYearEnd() {
|
||||
setShowConfirmDialog(false)
|
||||
setExecuting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/bookkeeping/fiscal-periods/${selectedPeriodId}/year-end`, {
|
||||
method: 'POST',
|
||||
})
|
||||
const json = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
setError(json.error || 'Årsbokslut misslyckades')
|
||||
toast({ title: 'Fel', description: json.error || 'Årsbokslut misslyckades', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
|
||||
setResult(json.data)
|
||||
setShowSuccess(true)
|
||||
} catch {
|
||||
setError('Nätverksfel vid genomförande')
|
||||
toast({ title: 'Fel', description: 'Nätverksfel vid genomförande', variant: 'destructive' })
|
||||
} finally {
|
||||
setExecuting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function goToStep(nextStep: number) {
|
||||
if (nextStep === 1 && !validation) {
|
||||
fetchValidationAndPreview()
|
||||
}
|
||||
setStep(nextStep)
|
||||
}
|
||||
|
||||
function getPeriodStatus(period: FiscalPeriod) {
|
||||
if (period.is_closed) return { label: 'Stängd', variant: 'secondary' as const }
|
||||
if (period.locked_at) return { label: 'Låst', variant: 'outline' as const }
|
||||
return { label: 'Öppen', variant: 'default' as const }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Årsbokslut</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Stäng räkenskapsåret och generera ingående balanser
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/bookkeeping">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Bokföring
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Step indicator */}
|
||||
<div className="flex items-center gap-2">
|
||||
{STEP_LABELS.map((label, i) => (
|
||||
<div key={label} className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div
|
||||
className={`flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium ${
|
||||
i < step
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: i === step
|
||||
? 'bg-primary text-primary-foreground ring-2 ring-primary/30'
|
||||
: 'bg-muted text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
{i < step ? <CheckCircle2 className="h-4 w-4" /> : i + 1}
|
||||
</div>
|
||||
<span
|
||||
className={`text-sm hidden sm:inline ${
|
||||
i === step ? 'font-medium' : 'text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
{i < STEP_LABELS.length - 1 && (
|
||||
<div className={`h-px w-8 ${i < step ? 'bg-primary' : 'bg-border'}`} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Error banner */}
|
||||
{error && (
|
||||
<Card className="border-destructive">
|
||||
<CardContent className="flex items-center gap-3 py-4">
|
||||
<AlertCircle className="h-5 w-5 text-destructive flex-shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Step 0: Period Selection */}
|
||||
{step === 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Välj räkenskapsår att stänga</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{loadingPeriods ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
) : periods.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Inga räkenskapsår hittades. Skapa ett räkenskapsår först.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
{periods.map((period) => {
|
||||
const status = getPeriodStatus(period)
|
||||
const isSelected = period.id === selectedPeriodId
|
||||
return (
|
||||
<button
|
||||
key={period.id}
|
||||
onClick={() => setSelectedPeriodId(period.id)}
|
||||
disabled={period.is_closed}
|
||||
className={`w-full flex items-center justify-between rounded-lg border p-4 text-left transition-colors ${
|
||||
isSelected
|
||||
? 'border-primary bg-primary/5'
|
||||
: period.is_closed
|
||||
? 'border-border bg-muted/50 opacity-60 cursor-not-allowed'
|
||||
: 'border-border hover:border-primary/50 hover:bg-muted/30'
|
||||
}`}
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium">{period.name}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{period.period_start} – {period.period_end}
|
||||
</p>
|
||||
</div>
|
||||
<Badge variant={status.variant}>{status.label}</Badge>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={() => goToStep(1)}
|
||||
disabled={!selectedPeriodId || (selectedPeriod?.is_closed ?? false)}
|
||||
>
|
||||
Nästa
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Step 1: Validation */}
|
||||
{step === 1 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Validering — {selectedPeriod?.name}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{loading ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-6 w-3/4" />
|
||||
<Skeleton className="h-6 w-1/2" />
|
||||
<Skeleton className="h-6 w-2/3" />
|
||||
</div>
|
||||
) : validation ? (
|
||||
<>
|
||||
{/* Ready indicator */}
|
||||
<div
|
||||
className={`flex items-center gap-3 rounded-lg p-4 ${
|
||||
validation.ready
|
||||
? 'bg-green-50 dark:bg-green-950/20'
|
||||
: 'bg-red-50 dark:bg-red-950/20'
|
||||
}`}
|
||||
>
|
||||
{validation.ready ? (
|
||||
<CheckCircle2 className="h-6 w-6 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<AlertCircle className="h-6 w-6 text-red-600 dark:text-red-400" />
|
||||
)}
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{validation.ready
|
||||
? 'Perioden är redo för årsbokslut'
|
||||
: 'Perioden kan inte stängas ännu'}
|
||||
</p>
|
||||
{!validation.ready && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Åtgärda felen nedan innan du kan fortsätta
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Errors */}
|
||||
{validation.errors.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-red-600 dark:text-red-400">Fel som måste åtgärdas</p>
|
||||
{validation.errors.map((err, i) => (
|
||||
<div key={i} className="flex items-start gap-2 text-sm">
|
||||
<AlertCircle className="h-4 w-4 text-red-500 mt-0.5 flex-shrink-0" />
|
||||
<span>{err}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Warnings */}
|
||||
{validation.warnings.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-amber-600 dark:text-amber-400">Varningar</p>
|
||||
{validation.warnings.map((warn, i) => (
|
||||
<div key={i} className="flex items-start gap-2 text-sm">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-500 mt-0.5 flex-shrink-0" />
|
||||
<span>{warn}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Details */}
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div className="rounded-lg border p-3">
|
||||
<p className="text-muted-foreground">Utkast kvar</p>
|
||||
<p className="text-lg font-medium">{validation.draftCount}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border p-3">
|
||||
<p className="text-muted-foreground">Saldobalans</p>
|
||||
<p className="text-lg font-medium">
|
||||
{validation.trialBalanceBalanced ? 'Balanserad' : 'Obalanserad'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Voucher gaps */}
|
||||
{validation.voucherGaps.length > 0 && (
|
||||
<div className="rounded-lg border p-3">
|
||||
<p className="text-sm font-medium mb-2">Verifikationsnummerluckor</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{validation.voucherGaps.map((gap, i) => (
|
||||
<Badge key={i} variant="outline">
|
||||
{gap.gap_start}–{gap.gap_end}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={() => setStep(0)}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={fetchValidationAndPreview} disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Validera igen
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => goToStep(2)}
|
||||
disabled={!validation?.ready}
|
||||
>
|
||||
Nästa
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Step 2: Preview */}
|
||||
{step === 2 && preview && (
|
||||
<div className="space-y-4">
|
||||
{/* Net result highlight */}
|
||||
<Card>
|
||||
<CardContent className="py-6">
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-muted-foreground mb-1">Årets resultat</p>
|
||||
<p
|
||||
className={`text-4xl font-bold tracking-tight ${
|
||||
preview.netResult >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'
|
||||
}`}
|
||||
>
|
||||
{formatAmount(preview.netResult)} kr
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
Bokförs på {preview.closingAccount} — {preview.closingAccountName}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Result account summary */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Resultatkonton som nollställs</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Konto</TableHead>
|
||||
<TableHead>Namn</TableHead>
|
||||
<TableHead className="text-right">Belopp</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{preview.resultAccountSummary.map((account) => (
|
||||
<TableRow key={account.account_number}>
|
||||
<TableCell className="font-mono">{account.account_number}</TableCell>
|
||||
<TableCell>{account.account_name}</TableCell>
|
||||
<TableCell className="text-right font-mono">
|
||||
{formatAmount(account.amount)} kr
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Closing journal lines (expandable) */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<button
|
||||
onClick={() => setShowLinesDetail(!showLinesDetail)}
|
||||
className="flex items-center justify-between w-full"
|
||||
>
|
||||
<CardTitle>Bokslutsverifikation ({preview.closingLines.length} rader)</CardTitle>
|
||||
{showLinesDetail ? (
|
||||
<ChevronUp className="h-5 w-5 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronDown className="h-5 w-5 text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
</CardHeader>
|
||||
{showLinesDetail && (
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Konto</TableHead>
|
||||
<TableHead>Beskrivning</TableHead>
|
||||
<TableHead className="text-right">Debet</TableHead>
|
||||
<TableHead className="text-right">Kredit</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{preview.closingLines.map((line, i) => (
|
||||
<TableRow key={i}>
|
||||
<TableCell className="font-mono">{line.account_number}</TableCell>
|
||||
<TableCell>{line.line_description}</TableCell>
|
||||
<TableCell className="text-right font-mono">
|
||||
{line.debit_amount > 0 ? formatAmount(line.debit_amount) : ''}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono">
|
||||
{line.credit_amount > 0 ? formatAmount(line.credit_amount) : ''}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{/* Totals row */}
|
||||
<TableRow className="font-medium border-t-2">
|
||||
<TableCell colSpan={2}>Summa</TableCell>
|
||||
<TableCell className="text-right font-mono">
|
||||
{formatAmount(
|
||||
preview.closingLines.reduce((sum, l) => sum + l.debit_amount, 0)
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono">
|
||||
{formatAmount(
|
||||
preview.closingLines.reduce((sum, l) => sum + l.credit_amount, 0)
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={() => setStep(1)}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={() => goToStep(3)}>
|
||||
Nästa
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step 3: Execute */}
|
||||
{step === 3 && !result && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Genomför årsbokslut</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Följande åtgärder kommer att genomföras:
|
||||
</p>
|
||||
<ul className="space-y-2 text-sm">
|
||||
<li className="flex items-start gap-2">
|
||||
<BookOpen className="h-4 w-4 mt-0.5 text-muted-foreground flex-shrink-0" />
|
||||
Bokslutsverifikation skapas med {preview?.closingLines.length} rader
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<Lock className="h-4 w-4 mt-0.5 text-muted-foreground flex-shrink-0" />
|
||||
Perioden {selectedPeriod?.name} låses och stängs permanent
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<ArrowRight className="h-4 w-4 mt-0.5 text-muted-foreground flex-shrink-0" />
|
||||
Nytt räkenskapsår skapas med ingående balanser
|
||||
</li>
|
||||
</ul>
|
||||
{preview && (
|
||||
<div className="pt-2 border-t">
|
||||
<p className="text-sm">
|
||||
Årets resultat:{' '}
|
||||
<span className="font-medium">
|
||||
{formatAmount(preview.netResult)} kr
|
||||
</span>{' '}
|
||||
→ {preview.closingAccount} ({preview.closingAccountName})
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertTriangle className="h-5 w-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-amber-800 dark:text-amber-200">
|
||||
Denna åtgärd kan inte ångras
|
||||
</p>
|
||||
<p className="text-sm text-amber-700 dark:text-amber-300 mt-1">
|
||||
Perioden stängs permanent enligt Bokföringslagen. Säkerställ att alla bokföringar
|
||||
är korrekta innan du fortsätter.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={() => setStep(2)}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => setShowConfirmDialog(true)}
|
||||
disabled={executing}
|
||||
>
|
||||
{executing && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Genomför årsbokslut
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Step 3: Success state */}
|
||||
{step === 3 && result && (
|
||||
<Card>
|
||||
<CardContent className="py-8">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="flex justify-center">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-green-100 dark:bg-green-950/30">
|
||||
<CheckCircle2 className="h-8 w-8 text-green-600 dark:text-green-400" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold">Årsbokslutet är genomfört</h2>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{selectedPeriod?.name} har stängts och ett nytt räkenskapsår har skapats.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 max-w-md mx-auto text-left">
|
||||
<div className="flex items-center justify-between rounded-lg border p-3 text-sm">
|
||||
<span className="text-muted-foreground">Bokslutsverifikation</span>
|
||||
<Link
|
||||
href="/bookkeeping"
|
||||
className="text-primary hover:underline font-medium"
|
||||
>
|
||||
Visa
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex items-center justify-between rounded-lg border p-3 text-sm">
|
||||
<span className="text-muted-foreground">Period stängd</span>
|
||||
<Badge variant="secondary">
|
||||
<Lock className="mr-1 h-3 w-3" />
|
||||
Stängd
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between rounded-lg border p-3 text-sm">
|
||||
<span className="text-muted-foreground">Nytt räkenskapsår</span>
|
||||
<span className="font-medium">{result.nextPeriod.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between rounded-lg border p-3 text-sm">
|
||||
<span className="text-muted-foreground">Ingående balanser</span>
|
||||
<Badge variant="default">
|
||||
<CheckCircle2 className="mr-1 h-3 w-3" />
|
||||
Skapade
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4">
|
||||
<Button asChild>
|
||||
<Link href="/bookkeeping">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka till bokföring
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Confirmation dialog */}
|
||||
<Dialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Bekräfta årsbokslut</DialogTitle>
|
||||
<DialogDescription>
|
||||
Är du säker på att du vill stänga <strong>{selectedPeriod?.name}</strong>?
|
||||
Denna åtgärd kan inte ångras. Perioden kommer att stängas permanent.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{preview && (
|
||||
<div className="rounded-lg border p-3 text-sm">
|
||||
<p>
|
||||
Årets resultat:{' '}
|
||||
<span className="font-medium">{formatAmount(preview.netResult)} kr</span>
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
Bokförs på {preview.closingAccount} — {preview.closingAccountName}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setShowConfirmDialog(false)}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={executeYearEnd}>
|
||||
Stäng perioden
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Success animation overlay */}
|
||||
<SuccessAnimation
|
||||
show={showSuccess}
|
||||
title="Årsbokslut genomfört!"
|
||||
description={`${selectedPeriod?.name} har stängts`}
|
||||
variant="celebration"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { syncAccountTransactions } from '@/lib/banking/sync-transactions'
|
||||
import type { Transaction } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
interface StoredAccount {
|
||||
uid: string
|
||||
@@ -63,18 +68,38 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
// Update connection with new account balances and sync timestamp
|
||||
const syncedAt = new Date().toISOString()
|
||||
await supabase
|
||||
.from('bank_connections')
|
||||
.update({
|
||||
accounts,
|
||||
last_synced_at: new Date().toISOString(),
|
||||
last_synced_at: syncedAt,
|
||||
})
|
||||
.eq('id', connection.id)
|
||||
|
||||
// Emit event with newly synced transactions
|
||||
if (totalImported > 0) {
|
||||
const { data: syncedTransactions } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.eq('bank_connection_id', connection.id)
|
||||
.gte('created_at', fromDate)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(totalImported)
|
||||
|
||||
if (syncedTransactions && syncedTransactions.length > 0) {
|
||||
await eventBus.emit({
|
||||
type: 'transaction.synced',
|
||||
payload: { transactions: syncedTransactions as Transaction[], userId: user.id },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
imported: totalImported,
|
||||
duplicates: totalDuplicates,
|
||||
last_synced_at: new Date().toISOString(),
|
||||
last_synced_at: syncedAt,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Sync error:', error)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { closePeriod } from '@/lib/core/bookkeeping/period-service'
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
try {
|
||||
const period = await closePeriod(user.id, id)
|
||||
return NextResponse.json({ data: period })
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to close period' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { lockPeriod } from '@/lib/core/bookkeeping/period-service'
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
try {
|
||||
const period = await lockPeriod(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 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
validateYearEndReadiness,
|
||||
previewYearEndClosing,
|
||||
executeYearEndClosing,
|
||||
} from '@/lib/core/bookkeeping/year-end-service'
|
||||
|
||||
/**
|
||||
* 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()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const [validation, preview] = await Promise.all([
|
||||
validateYearEndReadiness(user.id, id),
|
||||
previewYearEndClosing(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 })
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await executeYearEndClosing(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 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { CreateCustomerInput } from '@/types'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { CreateCustomerInput, Customer } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
@@ -60,5 +64,10 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'customer.created',
|
||||
payload: { customer: data as Customer, userId: user.id },
|
||||
})
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getSettings, saveSettings } from '@/extensions/ai-categorization'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/ai-categorization/settings
|
||||
* Get the current user's ai-categorization extension settings
|
||||
*/
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const settings = await getSettings(user.id)
|
||||
return NextResponse.json({ data: settings })
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/extensions/ai-categorization/settings
|
||||
* Update the current user's ai-categorization extension settings
|
||||
*/
|
||||
export async function PATCH(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
// Validate setting keys
|
||||
const allowedKeys = [
|
||||
'autoSuggestEnabled',
|
||||
'confidenceThreshold',
|
||||
'providerModel',
|
||||
]
|
||||
const filtered: Record<string, unknown> = {}
|
||||
for (const key of allowedKeys) {
|
||||
if (key in body) {
|
||||
filtered[key] = body[key]
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(filtered).length === 0) {
|
||||
return NextResponse.json({ error: 'No valid settings provided' }, { status: 400 })
|
||||
}
|
||||
|
||||
const settings = await saveSettings(user.id, filtered)
|
||||
return NextResponse.json({ data: settings })
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { categorizeTransactions } from '@/extensions/ai-categorization'
|
||||
import type { CategorizationSuggestion } from '@/extensions/ai-categorization/categorizer'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/ai-categorization/suggestions?transaction_ids=id1,id2,...
|
||||
* Fetch pre-computed AI suggestions for given transaction IDs
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const idsParam = searchParams.get('transaction_ids')
|
||||
|
||||
if (!idsParam) {
|
||||
return NextResponse.json({ error: 'transaction_ids is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const transactionIds = idsParam.split(',').filter(Boolean).slice(0, 50)
|
||||
|
||||
// Read stored suggestions from extension_data
|
||||
const keys = transactionIds.map((id) => `suggestion:${id}`)
|
||||
|
||||
const { data: records } = await supabase
|
||||
.from('extension_data')
|
||||
.select('key, value')
|
||||
.eq('user_id', user.id)
|
||||
.eq('extension_id', 'ai-categorization')
|
||||
.in('key', keys)
|
||||
|
||||
const suggestions: Record<string, CategorizationSuggestion> = {}
|
||||
if (records) {
|
||||
for (const record of records) {
|
||||
const txId = record.key.replace('suggestion:', '')
|
||||
suggestions[txId] = record.value as unknown as CategorizationSuggestion
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ suggestions })
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/extensions/ai-categorization/suggestions
|
||||
* Trigger on-demand AI categorization for given transaction IDs
|
||||
*/
|
||||
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 body = await request.json()
|
||||
const { transaction_ids } = body
|
||||
|
||||
if (!Array.isArray(transaction_ids) || transaction_ids.length === 0) {
|
||||
return NextResponse.json({ error: 'transaction_ids is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const ids = transaction_ids.slice(0, 50)
|
||||
|
||||
try {
|
||||
const suggestions = await categorizeTransactions(user.id, ids)
|
||||
|
||||
// Group by transaction ID
|
||||
const grouped: Record<string, CategorizationSuggestion> = {}
|
||||
for (const s of suggestions) {
|
||||
grouped[s.transactionId] = s
|
||||
}
|
||||
|
||||
return NextResponse.json({ suggestions: grouped })
|
||||
} catch (error) {
|
||||
console.error('[ai-categorization] On-demand categorization failed:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'AI categorization failed' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getSettings, saveSettings } from '@/extensions/receipt-ocr'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/receipt-ocr/settings
|
||||
* Get the current user's receipt-ocr extension settings
|
||||
*/
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const settings = await getSettings(user.id)
|
||||
return NextResponse.json({ data: settings })
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/extensions/receipt-ocr/settings
|
||||
* Update the current user's receipt-ocr extension settings
|
||||
*/
|
||||
export async function PATCH(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
// Validate setting keys
|
||||
const allowedKeys = [
|
||||
'autoOcrEnabled',
|
||||
'autoMatchEnabled',
|
||||
'autoMatchThreshold',
|
||||
'ocrConfidenceThreshold',
|
||||
]
|
||||
const filtered: Record<string, unknown> = {}
|
||||
for (const key of allowedKeys) {
|
||||
if (key in body) {
|
||||
filtered[key] = body[key]
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(filtered).length === 0) {
|
||||
return NextResponse.json({ error: 'No valid settings provided' }, { status: 400 })
|
||||
}
|
||||
|
||||
const settings = await saveSettings(user.id, filtered)
|
||||
return NextResponse.json({ data: settings })
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoice/pdf-template'
|
||||
import { sendEmail, isResendConfigured } from '@/lib/email/resend'
|
||||
@@ -10,6 +12,8 @@ import {
|
||||
} from '@/lib/email/invoice-templates'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
@@ -154,6 +158,11 @@ export async function POST(
|
||||
// Don't fail the request - the email was sent successfully
|
||||
}
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'invoice.sent',
|
||||
payload: { invoice: invoice as Invoice, userId: user.id },
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Fakturan har skickats till ${customer.email}`,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { CreateInvoiceInput, Invoice } from '@/types'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { CreateInvoiceInput, Invoice, CreditNote } from '@/types'
|
||||
import { getVatRules, calculateVat, calculateTotal } from '@/lib/invoice/vat-rules'
|
||||
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
|
||||
import {
|
||||
@@ -8,6 +10,8 @@ import {
|
||||
createCreditNoteJournalEntry,
|
||||
} from '@/lib/bookkeeping/invoice-entries'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
interface CreateCreditNoteInput {
|
||||
credited_invoice_id: string
|
||||
reason?: string
|
||||
@@ -189,6 +193,11 @@ export async function POST(request: Request) {
|
||||
console.error('Failed to create invoice journal entry:', err)
|
||||
// Don't fail the invoice creation
|
||||
}
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'invoice.created',
|
||||
payload: { invoice: completeInvoice as Invoice, userId: user.id },
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: completeInvoice })
|
||||
@@ -316,6 +325,11 @@ async function createCreditNote(
|
||||
} catch (err) {
|
||||
console.error('Failed to create credit note journal entry:', err)
|
||||
}
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'credit_note.created',
|
||||
payload: { creditNote: completeCreditNote as CreditNote, userId },
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: completeCreditNote })
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { ConfirmReceiptInput } from '@/types'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { ConfirmReceiptInput, Receipt, ReceiptLineItem } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
/**
|
||||
* POST /api/receipts/[id]/confirm
|
||||
@@ -104,5 +108,28 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Failed to update receipt' }, { status: 500 })
|
||||
}
|
||||
|
||||
// Calculate business/private totals from line items
|
||||
const lineItems = ((updatedReceipt as unknown as Receipt).line_items || []) as ReceiptLineItem[]
|
||||
let businessTotal = 0
|
||||
let privateTotal = 0
|
||||
for (const item of lineItems) {
|
||||
if (item.is_business === true) {
|
||||
businessTotal += item.line_total
|
||||
} else if (item.is_business === false) {
|
||||
privateTotal += item.line_total
|
||||
}
|
||||
}
|
||||
|
||||
// Emit receipt.confirmed event
|
||||
await eventBus.emit({
|
||||
type: 'receipt.confirmed',
|
||||
payload: {
|
||||
receipt: updatedReceipt as unknown as Receipt,
|
||||
businessTotal: Math.round(businessTotal * 100) / 100,
|
||||
privateTotal: Math.round(privateTotal * 100) / 100,
|
||||
userId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: updatedReceipt })
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { findTransactionMatches } from '@/lib/receipts/receipt-matcher'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { Receipt, Transaction } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
/**
|
||||
* POST /api/receipts/[id]/match
|
||||
* Find potential transaction matches for a receipt
|
||||
@@ -100,7 +104,7 @@ export async function PATCH(
|
||||
// Verify receipt ownership
|
||||
const { data: receipt, error: receiptError } = await supabase
|
||||
.from('receipts')
|
||||
.select('id')
|
||||
.select('*, line_items:receipt_line_items(*)')
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
@@ -112,7 +116,7 @@ export async function PATCH(
|
||||
// Verify transaction ownership
|
||||
const { data: transaction, error: txError } = await supabase
|
||||
.from('transactions')
|
||||
.select('id')
|
||||
.select('*')
|
||||
.eq('id', transaction_id)
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
@@ -145,6 +149,18 @@ export async function PATCH(
|
||||
console.error('Transaction update error:', updateTxError)
|
||||
}
|
||||
|
||||
// Emit receipt.matched event
|
||||
await eventBus.emit({
|
||||
type: 'receipt.matched',
|
||||
payload: {
|
||||
receipt: receipt as unknown as Receipt,
|
||||
transaction: transaction as Transaction,
|
||||
confidence: match_confidence || 0,
|
||||
autoMatched: false,
|
||||
userId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
receipt_id: id,
|
||||
|
||||
@@ -2,6 +2,10 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { analyzeReceipt } from '@/lib/receipts/receipt-analyzer'
|
||||
import { processLineItems } from '@/lib/receipts/receipt-categorizer'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
/**
|
||||
* POST /api/receipts/upload
|
||||
@@ -157,6 +161,17 @@ export async function POST(request: Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// Emit receipt.extracted event
|
||||
await eventBus.emit({
|
||||
type: 'receipt.extracted',
|
||||
payload: {
|
||||
receipt: completeReceipt,
|
||||
documentId: null,
|
||||
confidence: extraction.confidence,
|
||||
userId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: completeReceipt })
|
||||
} catch (analysisError) {
|
||||
console.error('Receipt analysis error:', analysisError)
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { buildMappingResultFromCategory } from '@/lib/bookkeeping/category-mapping'
|
||||
import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
|
||||
import { saveUserMappingRule } from '@/lib/bookkeeping/mapping-engine'
|
||||
import type { Transaction, TransactionCategory, EntityType } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
interface CategorizeRequest {
|
||||
is_business: boolean
|
||||
category?: TransactionCategory
|
||||
@@ -199,6 +203,16 @@ export async function POST(
|
||||
)
|
||||
}
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'transaction.categorized',
|
||||
payload: {
|
||||
transaction: transaction as Transaction,
|
||||
account: mappingResult.debit_account,
|
||||
taxCode: mappingResult.vat_lines[0]?.account_number || '',
|
||||
userId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
journal_entry_created: journalEntryCreated,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getSuggestedCategories, type SuggestedCategory } from '@/lib/transactions/category-suggestions'
|
||||
import { getSuggestedCategories, mergeAiSuggestions, type SuggestedCategory } from '@/lib/transactions/category-suggestions'
|
||||
import type { Transaction, TransactionCategory } from '@/types'
|
||||
|
||||
/**
|
||||
@@ -61,15 +61,40 @@ export async function POST(request: Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch pre-computed AI suggestions for these transactions
|
||||
const aiKeys = ids.map((id: string) => `suggestion:${id}`)
|
||||
const { data: aiRecords } = await supabase
|
||||
.from('extension_data')
|
||||
.select('key, value')
|
||||
.eq('user_id', user.id)
|
||||
.eq('extension_id', 'ai-categorization')
|
||||
.in('key', aiKeys)
|
||||
|
||||
const aiSuggestionsMap: Record<string, { category: string; basAccount: string; confidence: number; reasoning: string }> = {}
|
||||
if (aiRecords) {
|
||||
for (const record of aiRecords) {
|
||||
const txId = record.key.replace('suggestion:', '')
|
||||
aiSuggestionsMap[txId] = record.value as { category: string; basAccount: string; confidence: number; reasoning: string }
|
||||
}
|
||||
}
|
||||
|
||||
// Generate suggestions for each transaction
|
||||
const suggestions: Record<string, SuggestedCategory[]> = {}
|
||||
|
||||
for (const tx of transactions) {
|
||||
suggestions[tx.id] = getSuggestedCategories(
|
||||
let result = getSuggestedCategories(
|
||||
tx as Transaction,
|
||||
mappingRules || [],
|
||||
categoryHistory
|
||||
)
|
||||
|
||||
// Merge AI suggestions if available
|
||||
const aiSuggestion = aiSuggestionsMap[tx.id]
|
||||
if (aiSuggestion) {
|
||||
result = mergeAiSuggestions(result, [aiSuggestion])
|
||||
}
|
||||
|
||||
suggestions[tx.id] = result
|
||||
}
|
||||
|
||||
return NextResponse.json({ suggestions })
|
||||
|
||||
Reference in New Issue
Block a user