New base
This commit is contained in:
@@ -4,7 +4,8 @@
|
||||
"mcp__ide__getDiagnostics",
|
||||
"Bash(grep:*)",
|
||||
"Bash(xargs:*)",
|
||||
"Bash(ls:*)"
|
||||
"Bash(ls:*)",
|
||||
"Bash(find:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,379 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import {
|
||||
getSchablonavdragSummary,
|
||||
groupMileageEntriesByMonth,
|
||||
formatMonthKey,
|
||||
SCHABLONAVDRAG_RATES,
|
||||
} from '@/lib/tax/schablonavdrag'
|
||||
import SchablonavdragSettings from '@/components/settings/SchablonavdragSettings'
|
||||
import MileageEntry from '@/components/transactions/MileageEntry'
|
||||
import {
|
||||
Loader2,
|
||||
Home,
|
||||
Car,
|
||||
Plus,
|
||||
Trash2,
|
||||
Calendar,
|
||||
MapPin,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
} from 'lucide-react'
|
||||
import type {
|
||||
CompanySettings,
|
||||
SchablonavdragSettings as SchablonavdragSettingsType,
|
||||
MileageEntry as MileageEntryType,
|
||||
CreateMileageEntryInput,
|
||||
} from '@/types'
|
||||
|
||||
export default function DeductionsPage() {
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const supabase = createClient()
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [settings, setSettings] = useState<CompanySettings | null>(null)
|
||||
const [mileageEntries, setMileageEntries] = useState<MileageEntryType[]>([])
|
||||
const [showAddForm, setShowAddForm] = useState(false)
|
||||
const [expandedMonths, setExpandedMonths] = useState<Set<string>>(new Set())
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [])
|
||||
|
||||
async function fetchData() {
|
||||
setIsLoading(true)
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
if (!user) {
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch settings
|
||||
const { data: settingsData } = await supabase
|
||||
.from('company_settings')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
setSettings(settingsData)
|
||||
|
||||
// Fetch mileage entries for current year
|
||||
const startOfYear = new Date(new Date().getFullYear(), 0, 1).toISOString().split('T')[0]
|
||||
const { data: entries } = await supabase
|
||||
.from('mileage_entries')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.gte('date', startOfYear)
|
||||
.order('date', { ascending: false })
|
||||
|
||||
setMileageEntries(entries || [])
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
async function handleSaveSettings(newSettings: SchablonavdragSettingsType) {
|
||||
if (!settings) return
|
||||
|
||||
const { error } = await supabase
|
||||
.from('company_settings')
|
||||
.update({ schablonavdrag_settings: newSettings })
|
||||
.eq('id', settings.id)
|
||||
|
||||
if (error) {
|
||||
throw error
|
||||
}
|
||||
|
||||
setSettings({
|
||||
...settings,
|
||||
schablonavdrag_settings: newSettings,
|
||||
} as CompanySettings & { schablonavdrag_settings: SchablonavdragSettingsType })
|
||||
}
|
||||
|
||||
async function handleAddMileageEntry(entry: CreateMileageEntryInput) {
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
if (!user) return
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('mileage_entries')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
date: entry.date,
|
||||
distance_km: entry.distance_km,
|
||||
purpose: entry.purpose,
|
||||
from_location: entry.from_location || null,
|
||||
to_location: entry.to_location || null,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
throw error
|
||||
}
|
||||
|
||||
setMileageEntries([data, ...mileageEntries])
|
||||
setShowAddForm(false)
|
||||
}
|
||||
|
||||
async function handleDeleteMileageEntry(id: string) {
|
||||
const { error } = await supabase.from('mileage_entries').delete().eq('id', id)
|
||||
|
||||
if (error) {
|
||||
toast({
|
||||
title: 'Fel',
|
||||
description: 'Kunde inte ta bort körningen',
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setMileageEntries(mileageEntries.filter((e) => e.id !== id))
|
||||
toast({
|
||||
title: 'Borttaget',
|
||||
description: 'Körningen har tagits bort',
|
||||
})
|
||||
}
|
||||
|
||||
function toggleMonth(monthKey: string) {
|
||||
const newExpanded = new Set(expandedMonths)
|
||||
if (newExpanded.has(monthKey)) {
|
||||
newExpanded.delete(monthKey)
|
||||
} else {
|
||||
newExpanded.add(monthKey)
|
||||
}
|
||||
setExpandedMonths(newExpanded)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Get schablonavdrag settings
|
||||
const schablonavdragSettings = ((settings as CompanySettings & { schablonavdrag_settings?: SchablonavdragSettingsType })?.schablonavdrag_settings) || {
|
||||
hemmakontor_enabled: false,
|
||||
bil_enabled: false,
|
||||
}
|
||||
|
||||
// Calculate summary
|
||||
const currentYear = new Date().getFullYear()
|
||||
const currentMonth = new Date().getMonth() + 1
|
||||
const summary = getSchablonavdragSummary(
|
||||
schablonavdragSettings,
|
||||
mileageEntries,
|
||||
currentYear,
|
||||
currentMonth
|
||||
)
|
||||
|
||||
// Group mileage entries by month
|
||||
const entriesByMonth = groupMileageEntriesByMonth(mileageEntries)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Schablonavdrag</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Hantera dina schablonmässiga avdrag för hemmakontor och bilkostnader
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Summary cards */}
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{/* Total deduction */}
|
||||
<Card className="bg-gradient-to-br from-success/10 via-success/5 to-background border-success/20">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
Totalt avdrag {currentYear}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold text-success">
|
||||
{formatCurrency(summary.total_deduction)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Hemmakontor */}
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
|
||||
<Home className="h-4 w-4" />
|
||||
Hemmakontor
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{summary.hemmakontor.enabled ? formatCurrency(summary.hemmakontor.deduction) : '-'}
|
||||
</div>
|
||||
{summary.hemmakontor.enabled && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{summary.hemmakontor.months_active} månader
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Bilkostnader */}
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
|
||||
<Car className="h-4 w-4" />
|
||||
Bilkostnader
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{summary.mileage.enabled ? formatCurrency(summary.mileage.total_deduction) : '-'}
|
||||
</div>
|
||||
{summary.mileage.enabled && summary.mileage.total_km > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{summary.mileage.total_km.toFixed(0)} km loggade
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="settings" className="space-y-6">
|
||||
<TabsList>
|
||||
<TabsTrigger value="settings">Inställningar</TabsTrigger>
|
||||
<TabsTrigger value="mileage" disabled={!schablonavdragSettings.bil_enabled}>
|
||||
Körjournal
|
||||
{schablonavdragSettings.bil_enabled && mileageEntries.length > 0 && (
|
||||
<Badge variant="secondary" className="ml-2">
|
||||
{mileageEntries.length}
|
||||
</Badge>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Settings tab */}
|
||||
<TabsContent value="settings">
|
||||
<SchablonavdragSettings
|
||||
settings={schablonavdragSettings}
|
||||
onSave={handleSaveSettings}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* Mileage log tab */}
|
||||
<TabsContent value="mileage" className="space-y-6">
|
||||
{/* Add new entry button/form */}
|
||||
{showAddForm ? (
|
||||
<MileageEntry onSave={handleAddMileageEntry} onCancel={() => setShowAddForm(false)} />
|
||||
) : (
|
||||
<Button onClick={() => setShowAddForm(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Ny körning
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Entries list grouped by month */}
|
||||
{mileageEntries.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<Car className="mx-auto h-12 w-12 text-muted-foreground/50" />
|
||||
<h3 className="mt-4 text-lg font-medium">Ingen körning loggad</h3>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
Börja logga dina tjänsteresor för att få milersättning
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{Array.from(entriesByMonth.entries()).map(([monthKey, monthData]) => (
|
||||
<Card key={monthKey}>
|
||||
<CardHeader
|
||||
className="cursor-pointer"
|
||||
onClick={() => toggleMonth(monthKey)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="text-base">
|
||||
{formatMonthKey(monthKey)}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{monthData.entries.length} körningar · {monthData.totalKm.toFixed(0)} km
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-lg font-medium text-success">
|
||||
{formatCurrency(monthData.totalDeduction)}
|
||||
</span>
|
||||
{expandedMonths.has(monthKey) ? (
|
||||
<ChevronUp className="h-5 w-5" />
|
||||
) : (
|
||||
<ChevronDown className="h-5 w-5" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{expandedMonths.has(monthKey) && (
|
||||
<CardContent className="pt-0">
|
||||
<div className="space-y-3">
|
||||
{monthData.entries.map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="flex items-start justify-between p-3 rounded-lg border bg-muted/30"
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Calendar className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span>{formatDate(entry.date)}</span>
|
||||
<Badge variant="secondary">
|
||||
{Number(entry.distance_km).toFixed(1)} km
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-sm">{entry.purpose}</p>
|
||||
{(entry.from_location || entry.to_location) && (
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<MapPin className="h-3 w-3" />
|
||||
{entry.from_location && entry.to_location
|
||||
? `${entry.from_location} → ${entry.to_location}`
|
||||
: entry.from_location || entry.to_location}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-medium text-success">
|
||||
{formatCurrency(Number(entry.total_deduction))}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive"
|
||||
onClick={() => handleDeleteMileageEntry(entry.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -119,8 +119,8 @@ export default function InvoicesPage() {
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-12 w-12 rounded-lg bg-primary/10 flex items-center justify-center">
|
||||
<Receipt className="h-6 w-6 text-primary" />
|
||||
<div className="h-12 w-12 rounded-lg bg-muted flex items-center justify-center">
|
||||
<Receipt className="h-6 w-6 text-muted-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Totalt antal</p>
|
||||
@@ -132,8 +132,8 @@ export default function InvoicesPage() {
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-12 w-12 rounded-lg bg-warning/10 flex items-center justify-center">
|
||||
<Clock className="h-6 w-6 text-warning" />
|
||||
<div className="h-12 w-12 rounded-lg bg-muted flex items-center justify-center">
|
||||
<Clock className="h-6 w-6 text-muted-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Obetalda</p>
|
||||
@@ -149,11 +149,11 @@ export default function InvoicesPage() {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="bg-gradient-to-br from-success/5 to-transparent border-success/20">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-12 w-12 rounded-lg bg-success/10 flex items-center justify-center">
|
||||
<Send className="h-6 w-6 text-success" />
|
||||
<div className="h-12 w-12 rounded-lg bg-muted flex items-center justify-center">
|
||||
<Send className="h-6 w-6 text-muted-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Att få in</p>
|
||||
|
||||
@@ -42,8 +42,8 @@ export default async function DashboardLayout({
|
||||
companyName={settings.company_name || 'Min verksamhet'}
|
||||
entityType={entityType}
|
||||
/>
|
||||
<main id="main-content" className="pb-20 md:pb-0 md:pl-60" role="main">
|
||||
<div className="max-w-4xl mx-auto px-6 py-10 md:py-12">
|
||||
<main id="main-content" className="pb-20 md:pb-0 md:pl-[232px]" role="main">
|
||||
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
import Link from 'next/link'
|
||||
import { notFound } from 'next/navigation'
|
||||
import { ArrowLeft, BookOpen, BarChart3, FileDown, Cog } from 'lucide-react'
|
||||
import { getModuleBySlug, CATEGORY_LABELS, type ModuleCategory } from '@/lib/modules-data'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { ModuleToggle } from '@/components/modules/ModuleToggle'
|
||||
|
||||
const CATEGORY_META: Record<ModuleCategory, {
|
||||
icon: typeof BookOpen
|
||||
color: string
|
||||
bgColor: string
|
||||
borderColor: string
|
||||
}> = {
|
||||
bokforing: {
|
||||
icon: BookOpen,
|
||||
color: 'text-primary',
|
||||
bgColor: 'bg-primary/8',
|
||||
borderColor: 'border-primary/10',
|
||||
},
|
||||
rapport: {
|
||||
icon: BarChart3,
|
||||
color: 'text-accent',
|
||||
bgColor: 'bg-accent/8',
|
||||
borderColor: 'border-accent/10',
|
||||
},
|
||||
import: {
|
||||
icon: FileDown,
|
||||
color: 'text-success',
|
||||
bgColor: 'bg-success/8',
|
||||
borderColor: 'border-success/10',
|
||||
},
|
||||
operativ: {
|
||||
icon: Cog,
|
||||
color: 'text-muted-foreground',
|
||||
bgColor: 'bg-muted/60',
|
||||
borderColor: 'border-border',
|
||||
},
|
||||
}
|
||||
|
||||
export default async function ModuleDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ sector: string; module: string }>
|
||||
}) {
|
||||
const { sector: sectorSlug, module: moduleSlug } = await params
|
||||
const result = getModuleBySlug(sectorSlug, moduleSlug)
|
||||
|
||||
if (!result) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
const { sector, module: mod } = result
|
||||
const SectorIcon = sector.icon
|
||||
const catMeta = CATEGORY_META[mod.cat]
|
||||
const CatIcon = catMeta.icon
|
||||
|
||||
return (
|
||||
<div className="space-y-8 stagger-enter">
|
||||
{/* Navigation */}
|
||||
<div>
|
||||
<Link
|
||||
href={`/modules/${sectorSlug}`}
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
{sector.name}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Header */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start gap-5">
|
||||
<div className={`flex items-center justify-center w-12 h-12 rounded-xl ${catMeta.bgColor} ring-1 ${catMeta.borderColor}`}>
|
||||
<CatIcon className={`h-6 w-6 ${catMeta.color}`} strokeWidth={1.5} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h1 className="font-display text-2xl font-semibold tracking-tight">
|
||||
{mod.name}
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{mod.desc}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Badges */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
className={`${catMeta.bgColor} ${catMeta.color} border-transparent`}
|
||||
>
|
||||
{CATEGORY_LABELS[mod.cat]}
|
||||
</Badge>
|
||||
<Badge variant="secondary" className="gap-1.5">
|
||||
<SectorIcon className="h-3 w-3" strokeWidth={1.5} />
|
||||
{sector.name}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Separator */}
|
||||
<div className="h-px bg-border" />
|
||||
|
||||
{/* Long description */}
|
||||
<div className="prose prose-sm max-w-none">
|
||||
<div className="rounded-xl border border-border bg-card p-6 space-y-4">
|
||||
{mod.longDesc.split('. Nyckelfunktioner: ').map((part, i) => {
|
||||
if (i === 0) {
|
||||
return (
|
||||
<div key={i}>
|
||||
<h2 className="text-base font-semibold text-foreground mt-0 mb-2">
|
||||
Beskrivning
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed m-0">
|
||||
{part}{mod.longDesc.includes('Nyckelfunktioner') ? '' : ''}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div key={i}>
|
||||
<h2 className="text-base font-semibold text-foreground mt-0 mb-2">
|
||||
Nyckelfunktioner
|
||||
</h2>
|
||||
<ul className="space-y-1.5 m-0 p-0 list-none">
|
||||
{part.split('; ').map((feature, j) => (
|
||||
<li
|
||||
key={j}
|
||||
className="flex items-start gap-2 text-sm text-muted-foreground"
|
||||
>
|
||||
<span className="mt-1.5 h-1.5 w-1.5 rounded-full bg-primary/40 flex-shrink-0" />
|
||||
{feature.replace(/,\s*$/, '')}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Toggle */}
|
||||
<ModuleToggle sectorSlug={sectorSlug} moduleSlug={moduleSlug} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import Link from 'next/link'
|
||||
import { notFound } from 'next/navigation'
|
||||
import { ArrowLeft, BookOpen, BarChart3, FileDown, Cog, ChevronRight } from 'lucide-react'
|
||||
import { getSectorBySlug, CATEGORY_LABELS, type ModuleCategory } from '@/lib/modules-data'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
|
||||
const CATEGORY_ORDER: ModuleCategory[] = ['bokforing', 'rapport', 'import', 'operativ']
|
||||
|
||||
const CATEGORY_META: Record<ModuleCategory, {
|
||||
icon: typeof BookOpen
|
||||
color: string
|
||||
bgColor: string
|
||||
borderColor: string
|
||||
}> = {
|
||||
bokforing: {
|
||||
icon: BookOpen,
|
||||
color: 'text-primary',
|
||||
bgColor: 'bg-primary/8',
|
||||
borderColor: 'border-primary/10',
|
||||
},
|
||||
rapport: {
|
||||
icon: BarChart3,
|
||||
color: 'text-accent',
|
||||
bgColor: 'bg-accent/8',
|
||||
borderColor: 'border-accent/10',
|
||||
},
|
||||
import: {
|
||||
icon: FileDown,
|
||||
color: 'text-success',
|
||||
bgColor: 'bg-success/8',
|
||||
borderColor: 'border-success/10',
|
||||
},
|
||||
operativ: {
|
||||
icon: Cog,
|
||||
color: 'text-muted-foreground',
|
||||
bgColor: 'bg-muted/60',
|
||||
borderColor: 'border-border',
|
||||
},
|
||||
}
|
||||
|
||||
export default async function SectorPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ sector: string }>
|
||||
}) {
|
||||
const { sector: slug } = await params
|
||||
const sector = getSectorBySlug(slug)
|
||||
|
||||
if (!sector) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
const Icon = sector.icon
|
||||
const grouped = CATEGORY_ORDER.map((cat) => ({
|
||||
cat,
|
||||
label: CATEGORY_LABELS[cat],
|
||||
meta: CATEGORY_META[cat],
|
||||
modules: sector.modules.filter((m) => m.cat === cat),
|
||||
})).filter((g) => g.modules.length > 0)
|
||||
|
||||
const totalModules = sector.modules.length
|
||||
|
||||
return (
|
||||
<div className="space-y-10 stagger-enter">
|
||||
{/* Navigation */}
|
||||
<div>
|
||||
<Link
|
||||
href="/modules"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
Alla branscher
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Hero header */}
|
||||
<div className="relative">
|
||||
<div className="flex items-start gap-5">
|
||||
<div className="flex items-center justify-center w-14 h-14 rounded-2xl bg-primary/8 text-primary ring-1 ring-primary/10">
|
||||
<Icon className="h-7 w-7" strokeWidth={1.5} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h1 className="font-display text-2xl font-semibold tracking-tight">
|
||||
{sector.name}
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{sector.description}
|
||||
</p>
|
||||
<div className="flex items-center gap-3 mt-3">
|
||||
<Badge variant="secondary" className="tabular-nums">
|
||||
{totalModules} moduler
|
||||
</Badge>
|
||||
<Badge variant="secondary" className="tabular-nums">
|
||||
{grouped.length} kategorier
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Separator */}
|
||||
<div className="h-px bg-border" />
|
||||
|
||||
{/* Category sections */}
|
||||
<div className="space-y-10">
|
||||
{grouped.map((group) => {
|
||||
const CatIcon = group.meta.icon
|
||||
return (
|
||||
<section key={group.cat}>
|
||||
{/* Category header */}
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className={`flex items-center justify-center w-8 h-8 rounded-lg ${group.meta.bgColor}`}>
|
||||
<CatIcon className={`h-4 w-4 ${group.meta.color}`} strokeWidth={1.5} />
|
||||
</div>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<h2 className="text-sm font-semibold text-foreground">
|
||||
{group.label}
|
||||
</h2>
|
||||
<span className="text-xs text-muted-foreground/60 tabular-nums">
|
||||
{group.modules.length}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Module cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
{group.modules.map((mod) => (
|
||||
<Link
|
||||
key={mod.slug}
|
||||
href={`/modules/${slug}/${mod.slug}`}
|
||||
className={`group relative flex items-center gap-3 rounded-xl border ${group.meta.borderColor} bg-card px-4 py-3.5 transition-all duration-200 hover:shadow-[var(--shadow-md)] hover:border-primary/20 hover:-translate-y-px`}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-foreground group-hover:text-primary transition-colors duration-200">
|
||||
{mod.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground/70 mt-0.5 line-clamp-1">
|
||||
{mod.desc}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="h-3.5 w-3.5 text-muted-foreground/30 flex-shrink-0 transition-all duration-200 group-hover:text-primary/60 group-hover:translate-x-0.5" />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import Link from 'next/link'
|
||||
import { Layers } from 'lucide-react'
|
||||
import { sectors } from '@/lib/modules-data'
|
||||
|
||||
export default function ModulesPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h1 className="font-display text-2xl font-semibold tracking-tight">
|
||||
Företagsmoduler
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Välj din bransch för att se anpassade moduler och funktioner.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
|
||||
<Link
|
||||
href="/modules/alla"
|
||||
className="group flex items-center gap-3.5 rounded-xl border border-accent/20 bg-accent/5 px-4 py-3.5 transition-all duration-200 hover:border-accent/40 hover:bg-accent/10"
|
||||
>
|
||||
<div className="flex items-center justify-center w-10 h-10 rounded-lg bg-accent/12 text-accent shrink-0 transition-transform duration-200 group-hover:scale-105">
|
||||
<Layers className="h-5 w-5" strokeWidth={1.5} />
|
||||
</div>
|
||||
<span className="text-sm font-medium text-accent truncate">
|
||||
Visa alla
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
{sectors.map((sector) => {
|
||||
const Icon = sector.icon
|
||||
return (
|
||||
<Link
|
||||
key={sector.slug}
|
||||
href={`/modules/${sector.slug}`}
|
||||
className="group flex items-center gap-3.5 rounded-xl border border-border/50 bg-card px-4 py-3.5 transition-all duration-200 hover:border-border hover:bg-secondary/50 hover:shadow-sm"
|
||||
>
|
||||
<div className="flex items-center justify-center w-10 h-10 rounded-lg bg-muted/60 text-muted-foreground shrink-0 transition-all duration-200 group-hover:bg-primary/10 group-hover:text-primary group-hover:scale-105">
|
||||
<Icon className="h-5 w-5" strokeWidth={1.5} />
|
||||
</div>
|
||||
<span className="text-sm font-medium text-foreground/80 truncate transition-colors duration-200 group-hover:text-foreground">
|
||||
{sector.name}
|
||||
</span>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -122,13 +122,6 @@ export default async function DashboardPage() {
|
||||
(inv) => inv.status === 'overdue'
|
||||
).length
|
||||
|
||||
// Fetch mileage entries for schablonavdrag
|
||||
const { data: mileageEntries } = await supabase
|
||||
.from('mileage_entries')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.gte('date', startOfYear.split('T')[0])
|
||||
|
||||
// Fetch bank balance (if connected)
|
||||
const { data: bankConnections } = await supabase
|
||||
.from('bank_connections')
|
||||
@@ -225,7 +218,6 @@ export default async function DashboardPage() {
|
||||
unpaidVatTotal,
|
||||
overdueInvoicesCount: overdueCount,
|
||||
bankBalance,
|
||||
mileageEntries: mileageEntries || [],
|
||||
deadlines: (deadlines || []) as Deadline[],
|
||||
receiptQueue,
|
||||
}}
|
||||
|
||||
@@ -1,344 +1 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
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 { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import {
|
||||
Camera,
|
||||
Receipt,
|
||||
Check,
|
||||
Clock,
|
||||
AlertCircle,
|
||||
ArrowRight,
|
||||
} from 'lucide-react'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import ReceiptDashboard from '@/components/receipts/ReceiptDashboard'
|
||||
import ReceiptReviewView from '@/components/receipts/ReceiptReviewView'
|
||||
import TransactionMatcher from '@/components/receipts/TransactionMatcher'
|
||||
import type { Receipt as ReceiptType, ReceiptLineItem, ReceiptQueueSummary, ConfirmLineItemInput } from '@/types'
|
||||
|
||||
type ViewMode = 'dashboard' | 'list' | 'review' | 'match'
|
||||
type ListFilter = 'all' | 'pending' | 'confirmed'
|
||||
|
||||
export default function ReceiptsPage() {
|
||||
const router = useRouter()
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('dashboard')
|
||||
const [listFilter, setListFilter] = useState<ListFilter>('all')
|
||||
|
||||
const [receipts, setReceipts] = useState<(ReceiptType & { line_items: ReceiptLineItem[] })[]>([])
|
||||
const [summary, setSummary] = useState<ReceiptQueueSummary | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
// Selected receipt for review/match
|
||||
const [selectedReceipt, setSelectedReceipt] = useState<(ReceiptType & { line_items: ReceiptLineItem[] }) | null>(null)
|
||||
|
||||
// Fetch receipts and summary
|
||||
const fetchData = useCallback(async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const [receiptsRes, queueRes] = await Promise.all([
|
||||
fetch('/api/receipts'),
|
||||
fetch('/api/receipts/queue'),
|
||||
])
|
||||
|
||||
const [receiptsData, queueData] = await Promise.all([
|
||||
receiptsRes.json(),
|
||||
queueRes.json(),
|
||||
])
|
||||
|
||||
if (receiptsData.data) {
|
||||
setReceipts(receiptsData.data)
|
||||
}
|
||||
|
||||
if (queueData.data?.summary) {
|
||||
setSummary(queueData.data.summary)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Fetch error:', error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
// Filter receipts based on tab
|
||||
const filteredReceipts = receipts.filter((r) => {
|
||||
if (listFilter === 'pending') return r.status === 'extracted'
|
||||
if (listFilter === 'confirmed') return r.status === 'confirmed'
|
||||
return true
|
||||
})
|
||||
|
||||
// Handle scan receipt
|
||||
const handleScanReceipt = () => {
|
||||
router.push('/receipts/scan')
|
||||
}
|
||||
|
||||
// Handle view receipt queue
|
||||
const handleViewReceiptQueue = () => {
|
||||
setListFilter('pending')
|
||||
setViewMode('list')
|
||||
}
|
||||
|
||||
// Handle view transaction queue
|
||||
const handleViewTransactionQueue = () => {
|
||||
router.push('/transactions?filter=unmatched')
|
||||
}
|
||||
|
||||
// Handle receipt selection for review
|
||||
const handleSelectReceipt = (receipt: ReceiptType & { line_items: ReceiptLineItem[] }) => {
|
||||
setSelectedReceipt(receipt)
|
||||
if (receipt.status === 'extracted') {
|
||||
setViewMode('review')
|
||||
} else {
|
||||
setViewMode('match')
|
||||
}
|
||||
}
|
||||
|
||||
// Handle confirm receipt
|
||||
const handleConfirmReceipt = async (data: {
|
||||
line_items: ConfirmLineItemInput[]
|
||||
representation_persons?: number
|
||||
representation_purpose?: string
|
||||
}) => {
|
||||
if (!selectedReceipt) return
|
||||
|
||||
const response = await fetch(`/api/receipts/${selectedReceipt.id}/confirm`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
await fetchData()
|
||||
setSelectedReceipt(null)
|
||||
setViewMode('dashboard')
|
||||
} else {
|
||||
const errorData = await response.json()
|
||||
throw new Error(errorData.error || 'Kunde inte bekräfta kvitto')
|
||||
}
|
||||
}
|
||||
|
||||
// Handle match receipt to transaction
|
||||
const handleMatchReceipt = async (transactionId: string, confidence: number) => {
|
||||
if (!selectedReceipt) return
|
||||
|
||||
const response = await fetch(`/api/receipts/${selectedReceipt.id}/match`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ transaction_id: transactionId, match_confidence: confidence }),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
await fetchData()
|
||||
setSelectedReceipt(null)
|
||||
setViewMode('dashboard')
|
||||
}
|
||||
}
|
||||
|
||||
// Render receipt review view
|
||||
if (viewMode === 'review' && selectedReceipt) {
|
||||
return (
|
||||
<ReceiptReviewView
|
||||
receipt={selectedReceipt}
|
||||
onConfirm={handleConfirmReceipt}
|
||||
onCancel={() => {
|
||||
setSelectedReceipt(null)
|
||||
setViewMode('dashboard')
|
||||
}}
|
||||
onFindMatches={() => setViewMode('match')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Render transaction matcher
|
||||
if (viewMode === 'match' && selectedReceipt) {
|
||||
return (
|
||||
<TransactionMatcher
|
||||
receipt={selectedReceipt}
|
||||
onMatch={handleMatchReceipt}
|
||||
onSkip={() => {
|
||||
setSelectedReceipt(null)
|
||||
setViewMode('dashboard')
|
||||
}}
|
||||
onClose={() => {
|
||||
setSelectedReceipt(null)
|
||||
setViewMode('dashboard')
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Render main page
|
||||
return (
|
||||
<div className="container max-w-4xl mx-auto p-4 space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Kvittohantering</h1>
|
||||
<Button onClick={handleScanReceipt}>
|
||||
<Camera className="mr-2 h-4 w-4" />
|
||||
Skanna kvitto
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Dashboard or List view toggle */}
|
||||
<Tabs
|
||||
value={viewMode === 'list' ? 'list' : 'dashboard'}
|
||||
onValueChange={(v) => setViewMode(v as ViewMode)}
|
||||
>
|
||||
<TabsList>
|
||||
<TabsTrigger value="dashboard">Översikt</TabsTrigger>
|
||||
<TabsTrigger value="list">Alla kvitton</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
{viewMode === 'dashboard' && (
|
||||
<>
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Skeleton className="h-24" />
|
||||
<Skeleton className="h-24" />
|
||||
</div>
|
||||
<Skeleton className="h-32" />
|
||||
<Skeleton className="h-24" />
|
||||
</div>
|
||||
) : summary ? (
|
||||
<ReceiptDashboard
|
||||
summary={summary}
|
||||
onScanReceipt={handleScanReceipt}
|
||||
onViewReceiptQueue={handleViewReceiptQueue}
|
||||
onViewTransactionQueue={handleViewTransactionQueue}
|
||||
/>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="pt-4 text-center py-8">
|
||||
<AlertCircle className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
|
||||
<p>Kunde inte ladda data</p>
|
||||
<Button variant="outline" className="mt-4" onClick={fetchData}>
|
||||
Försök igen
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{viewMode === 'list' && (
|
||||
<>
|
||||
{/* List filters */}
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant={listFilter === 'all' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setListFilter('all')}
|
||||
>
|
||||
Alla
|
||||
</Button>
|
||||
<Button
|
||||
variant={listFilter === 'pending' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setListFilter('pending')}
|
||||
>
|
||||
<Clock className="mr-1 h-3 w-3" />
|
||||
Att granska
|
||||
</Button>
|
||||
<Button
|
||||
variant={listFilter === 'confirmed' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setListFilter('confirmed')}
|
||||
>
|
||||
<Check className="mr-1 h-3 w-3" />
|
||||
Bekräftade
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Receipt list */}
|
||||
{isLoading ? (
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="h-24" />
|
||||
))}
|
||||
</div>
|
||||
) : filteredReceipts.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="pt-4 text-center py-8">
|
||||
<Receipt className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
|
||||
<p className="text-muted-foreground">Inga kvitton hittades</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{filteredReceipts.map((receipt) => (
|
||||
<Card
|
||||
key={receipt.id}
|
||||
className="cursor-pointer hover:border-primary/50 transition-colors"
|
||||
onClick={() => handleSelectReceipt(receipt)}
|
||||
>
|
||||
<CardContent className="pt-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-start gap-3">
|
||||
{receipt.image_url ? (
|
||||
<img
|
||||
src={receipt.image_url}
|
||||
alt="Receipt"
|
||||
className="h-16 w-12 object-cover rounded"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-16 w-12 bg-muted rounded flex items-center justify-center">
|
||||
<Receipt className="h-6 w-6 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="font-medium">{receipt.merchant_name || 'Okänt kvitto'}</p>
|
||||
{receipt.receipt_date && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{formatDate(receipt.receipt_date)}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-1 mt-1">
|
||||
<Badge
|
||||
variant={
|
||||
receipt.status === 'confirmed'
|
||||
? 'default'
|
||||
: receipt.status === 'extracted'
|
||||
? 'secondary'
|
||||
: receipt.status === 'error'
|
||||
? 'destructive'
|
||||
: 'outline'
|
||||
}
|
||||
>
|
||||
{receipt.status === 'confirmed' && 'Bekräftat'}
|
||||
{receipt.status === 'extracted' && 'Att granska'}
|
||||
{receipt.status === 'processing' && 'Analyserar...'}
|
||||
{receipt.status === 'pending' && 'Väntar'}
|
||||
{receipt.status === 'error' && 'Fel'}
|
||||
</Badge>
|
||||
{receipt.matched_transaction_id && (
|
||||
<Badge variant="outline">Kopplat</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-bold">
|
||||
{formatCurrency(receipt.total_amount || 0, receipt.currency)}
|
||||
</p>
|
||||
<ArrowRight className="h-4 w-4 text-muted-foreground mt-2 ml-auto" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export { default } from '@/extensions/receipt-ocr/pages/ReceiptsPage'
|
||||
|
||||
@@ -1,157 +1 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import ReceiptCamera from '@/components/receipts/ReceiptCamera'
|
||||
import ReceiptReviewView from '@/components/receipts/ReceiptReviewView'
|
||||
import TransactionMatcher from '@/components/receipts/TransactionMatcher'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import type { Receipt, ReceiptLineItem, ConfirmLineItemInput } from '@/types'
|
||||
|
||||
type PageState = 'camera' | 'uploading' | 'review' | 'match' | 'done'
|
||||
|
||||
export default function ScanReceiptPage() {
|
||||
const router = useRouter()
|
||||
const [pageState, setPageState] = useState<PageState>('camera')
|
||||
const [uploadError, setUploadError] = useState<string | null>(null)
|
||||
const [receipt, setReceipt] = useState<(Receipt & { line_items: ReceiptLineItem[] }) | null>(null)
|
||||
|
||||
// Handle image capture
|
||||
const handleCapture = async (imageData: string, mimeType: string) => {
|
||||
setPageState('uploading')
|
||||
setUploadError(null)
|
||||
|
||||
try {
|
||||
// Convert base64 to blob
|
||||
const byteCharacters = atob(imageData)
|
||||
const byteNumbers = new Array(byteCharacters.length)
|
||||
for (let i = 0; i < byteCharacters.length; i++) {
|
||||
byteNumbers[i] = byteCharacters.charCodeAt(i)
|
||||
}
|
||||
const byteArray = new Uint8Array(byteNumbers)
|
||||
const blob = new Blob([byteArray], { type: mimeType })
|
||||
|
||||
// Create form data
|
||||
const formData = new FormData()
|
||||
formData.append('image', blob, 'receipt.jpg')
|
||||
|
||||
// Upload and analyze
|
||||
const response = await fetch('/api/receipts/upload', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (response.ok && data.data) {
|
||||
setReceipt(data.data)
|
||||
setPageState('review')
|
||||
} else {
|
||||
setUploadError(data.error || 'Kunde inte analysera kvittot')
|
||||
setPageState('camera')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Upload error:', error)
|
||||
setUploadError('Nätverksfel. Försök igen.')
|
||||
setPageState('camera')
|
||||
}
|
||||
}
|
||||
|
||||
// Handle close/cancel
|
||||
const handleClose = () => {
|
||||
router.push('/receipts')
|
||||
}
|
||||
|
||||
// Handle confirm receipt
|
||||
const handleConfirm = async (data: {
|
||||
line_items: ConfirmLineItemInput[]
|
||||
representation_persons?: number
|
||||
representation_purpose?: string
|
||||
}) => {
|
||||
if (!receipt) return
|
||||
|
||||
const response = await fetch(`/api/receipts/${receipt.id}/confirm`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
const updatedData = await response.json()
|
||||
setReceipt(updatedData.data)
|
||||
setPageState('match')
|
||||
} else {
|
||||
const errorData = await response.json()
|
||||
throw new Error(errorData.error || 'Kunde inte bekräfta kvitto')
|
||||
}
|
||||
}
|
||||
|
||||
// Handle match to transaction
|
||||
const handleMatch = async (transactionId: string, confidence: number) => {
|
||||
if (!receipt) return
|
||||
|
||||
const response = await fetch(`/api/receipts/${receipt.id}/match`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ transaction_id: transactionId, match_confidence: confidence }),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
router.push('/receipts')
|
||||
}
|
||||
}
|
||||
|
||||
// Handle skip matching
|
||||
const handleSkipMatch = () => {
|
||||
router.push('/receipts')
|
||||
}
|
||||
|
||||
// Render uploading state
|
||||
if (pageState === 'uploading') {
|
||||
return (
|
||||
<div className="fixed inset-0 bg-background z-50 flex flex-col items-center justify-center">
|
||||
<Loader2 className="h-12 w-12 animate-spin text-primary mb-4" />
|
||||
<p className="text-lg font-medium">Analyserar kvitto...</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
AI läser av artiklar och belopp
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Render review view
|
||||
if (pageState === 'review' && receipt) {
|
||||
return (
|
||||
<ReceiptReviewView
|
||||
receipt={receipt}
|
||||
onConfirm={handleConfirm}
|
||||
onCancel={handleClose}
|
||||
onFindMatches={() => setPageState('match')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Render match view
|
||||
if (pageState === 'match' && receipt) {
|
||||
return (
|
||||
<TransactionMatcher
|
||||
receipt={receipt}
|
||||
onMatch={handleMatch}
|
||||
onSkip={handleSkipMatch}
|
||||
onClose={handleClose}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Render camera (default)
|
||||
return (
|
||||
<>
|
||||
{uploadError && (
|
||||
<div className="fixed top-4 left-4 right-4 z-[60] bg-destructive text-destructive-foreground p-3 rounded-lg text-sm">
|
||||
{uploadError}
|
||||
</div>
|
||||
)}
|
||||
<ReceiptCamera onCapture={handleCapture} onClose={handleClose} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
export { default } from '@/extensions/receipt-ocr/pages/scan/ScanReceiptPage'
|
||||
|
||||
@@ -6,7 +6,9 @@ import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Download, FileText, TrendingUp, Scale, AlertCircle, Receipt, Briefcase } from 'lucide-react'
|
||||
import { Download, FileText, FileDown, TrendingUp, Scale, AlertCircle, Receipt, Briefcase } from 'lucide-react'
|
||||
import { NEDeclarationView } from '@/extensions/ne-bilaga/NEDeclarationView'
|
||||
import { SRUExportView } from '@/extensions/sru-export/SRUExportView'
|
||||
import type {
|
||||
FiscalPeriod,
|
||||
TrialBalanceRow,
|
||||
@@ -14,7 +16,6 @@ import type {
|
||||
BalanceSheetReport,
|
||||
VatDeclaration,
|
||||
VatPeriodType,
|
||||
NEDeclaration,
|
||||
} from '@/types'
|
||||
|
||||
function formatAmount(amount: number): string {
|
||||
@@ -25,9 +26,11 @@ export default function ReportsPage() {
|
||||
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
|
||||
const [selectedPeriod, setSelectedPeriod] = useState('')
|
||||
const [activeTab, setActiveTab] = useState('trial-balance')
|
||||
const [entityType, setEntityType] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetchPeriods()
|
||||
fetchEntityType()
|
||||
}, [])
|
||||
|
||||
async function fetchPeriods() {
|
||||
@@ -39,13 +42,27 @@ export default function ReportsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchEntityType() {
|
||||
try {
|
||||
const res = await fetch('/api/settings')
|
||||
const { data } = await res.json()
|
||||
if (data?.entity_type) {
|
||||
setEntityType(data.entity_type)
|
||||
}
|
||||
} catch {
|
||||
// Ignore - entity type is optional for tab visibility
|
||||
}
|
||||
}
|
||||
|
||||
const isEnskildFirma = entityType === 'enskild_firma'
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Rapporter</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Saldobalans, resultaträkning, balansräkning, momsdeklaration, NE-bilaga och SIE-export
|
||||
Saldobalans, resultaträkning, balansräkning, momsdeklaration, NE-bilaga, SRU-export och SIE-export
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -97,9 +114,15 @@ export default function ReportsPage() {
|
||||
<Receipt className="h-4 w-4 mr-1" />
|
||||
Momsdeklaration
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="ne-declaration">
|
||||
<Briefcase className="h-4 w-4 mr-1" />
|
||||
NE-bilaga
|
||||
{isEnskildFirma && (
|
||||
<TabsTrigger value="ne-declaration">
|
||||
<Briefcase className="h-4 w-4 mr-1" />
|
||||
NE-bilaga
|
||||
</TabsTrigger>
|
||||
)}
|
||||
<TabsTrigger value="sru-export">
|
||||
<FileDown className="h-4 w-4 mr-1" />
|
||||
SRU-export
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
@@ -115,8 +138,13 @@ export default function ReportsPage() {
|
||||
<TabsContent value="vat-declaration">
|
||||
<VatDeclarationView />
|
||||
</TabsContent>
|
||||
<TabsContent value="ne-declaration">
|
||||
<NEDeclarationView periodId={selectedPeriod} />
|
||||
{isEnskildFirma && (
|
||||
<TabsContent value="ne-declaration">
|
||||
<NEDeclarationView periodId={selectedPeriod} />
|
||||
</TabsContent>
|
||||
)}
|
||||
<TabsContent value="sru-export">
|
||||
<SRUExportView periodId={selectedPeriod} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
) : (
|
||||
@@ -870,287 +898,3 @@ function VatRutaRow({
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function NEDeclarationView({ periodId }: { periodId: string }) {
|
||||
const [data, setData] = useState<NEDeclaration | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const fetchDeclaration = async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`/api/reports/ne-declaration?period_id=${periodId}`)
|
||||
const result = await res.json()
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
} else {
|
||||
setData(result.data)
|
||||
}
|
||||
} catch {
|
||||
setError('Kunde inte hämta NE-bilaga')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const downloadSRU = () => {
|
||||
window.open(`/api/reports/ne-declaration?period_id=${periodId}&format=sru`, '_blank')
|
||||
}
|
||||
|
||||
// NE ruta labels
|
||||
const rutaLabels: Record<string, string> = {
|
||||
R1: 'Försäljning med moms (25%)',
|
||||
R2: 'Momsfria intäkter',
|
||||
R3: 'Bil/bostadsförmån',
|
||||
R4: 'Ränteintäkter',
|
||||
R5: 'Varuinköp',
|
||||
R6: 'Övriga kostnader',
|
||||
R7: 'Lönekostnader',
|
||||
R8: 'Räntekostnader',
|
||||
R9: 'Avskrivningar fastighet',
|
||||
R10: 'Avskrivningar övriga tillgångar',
|
||||
R11: 'Årets resultat',
|
||||
}
|
||||
|
||||
// Categorize rutor
|
||||
const revenueRutor = ['R1', 'R2', 'R3', 'R4'] as const
|
||||
const expenseRutor = ['R5', 'R6', 'R7', 'R8', 'R9', 'R10'] as const
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Info card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">NE-bilaga (Enskild firma)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
NE-bilagan används för att deklarera resultat från enskild näringsverksamhet.
|
||||
Uppgifterna hämtas från bokföringen för valt räkenskapsår.
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={fetchDeclaration} disabled={loading}>
|
||||
{loading ? 'Laddar...' : 'Hämta NE-bilaga'}
|
||||
</Button>
|
||||
{data && (
|
||||
<Button variant="outline" onClick={downloadSRU}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Ladda ner SRU-fil
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{error && (
|
||||
<Card>
|
||||
<CardContent className="p-8 text-center text-destructive">
|
||||
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
|
||||
{error}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{data && (
|
||||
<>
|
||||
{/* Warnings */}
|
||||
{data.warnings.length > 0 && (
|
||||
<Card className="border-orange-200 bg-orange-50">
|
||||
<CardContent className="py-4">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-orange-600 mt-0.5" />
|
||||
<div>
|
||||
{data.warnings.map((warning, i) => (
|
||||
<p key={i} className="text-sm text-orange-800">{warning}</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Company info */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>
|
||||
{data.companyInfo.companyName}
|
||||
</CardTitle>
|
||||
<Badge className="bg-blue-100 text-blue-800">
|
||||
{data.fiscalYear.name}
|
||||
</Badge>
|
||||
</div>
|
||||
{data.companyInfo.orgNumber && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Org.nr: {data.companyInfo.orgNumber}
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
{/* Revenue section */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Intäkter</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<table className="w-full text-sm">
|
||||
<tbody>
|
||||
{revenueRutor.map((ruta) => {
|
||||
const value = data.rutor[ruta]
|
||||
const breakdown = data.breakdown[ruta]
|
||||
return (
|
||||
<NEDeclarationRow
|
||||
key={ruta}
|
||||
ruta={ruta}
|
||||
label={rutaLabels[ruta]}
|
||||
amount={value}
|
||||
accounts={breakdown?.accounts || []}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="border-t-2 font-semibold">
|
||||
<td className="py-2">Summa intäkter</td>
|
||||
<td className="py-2 text-right">
|
||||
{formatAmount(
|
||||
data.rutor.R1 + data.rutor.R2 + data.rutor.R3 + data.rutor.R4
|
||||
)} kr
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Expenses section */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Kostnader</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<table className="w-full text-sm">
|
||||
<tbody>
|
||||
{expenseRutor.map((ruta) => {
|
||||
const value = data.rutor[ruta]
|
||||
const breakdown = data.breakdown[ruta]
|
||||
return (
|
||||
<NEDeclarationRow
|
||||
key={ruta}
|
||||
ruta={ruta}
|
||||
label={rutaLabels[ruta]}
|
||||
amount={value}
|
||||
accounts={breakdown?.accounts || []}
|
||||
isExpense
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="border-t-2 font-semibold">
|
||||
<td className="py-2">Summa kostnader</td>
|
||||
<td className="py-2 text-right">
|
||||
-{formatAmount(
|
||||
data.rutor.R5 + data.rutor.R6 + data.rutor.R7 +
|
||||
data.rutor.R8 + data.rutor.R9 + data.rutor.R10
|
||||
)} kr
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Result */}
|
||||
<Card className="border-2">
|
||||
<CardContent className="py-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<span className="font-mono text-xs bg-muted px-1 rounded mr-2">R11</span>
|
||||
<span className="font-bold text-xl">Årets resultat</span>
|
||||
</div>
|
||||
<span
|
||||
className={`text-2xl font-bold ${
|
||||
data.rutor.R11 >= 0 ? 'text-green-600' : 'text-red-600'
|
||||
}`}
|
||||
>
|
||||
{formatAmount(data.rutor.R11)} kr
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
|
||||
{!data && !loading && !error && (
|
||||
<Card>
|
||||
<CardContent className="p-8 text-center text-muted-foreground">
|
||||
Klicka "Hämta NE-bilaga" för att generera deklarationsunderlaget.
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NEDeclarationRow({
|
||||
ruta,
|
||||
label,
|
||||
amount,
|
||||
accounts,
|
||||
isExpense,
|
||||
}: {
|
||||
ruta: string
|
||||
label: string
|
||||
amount: number
|
||||
accounts: Array<{ accountNumber: string; accountName: string; amount: number }>
|
||||
isExpense?: boolean
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
|
||||
// Don't show rows with zero values
|
||||
if (amount === 0 && accounts.length === 0) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<tr
|
||||
className="border-b cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => accounts.length > 0 && setExpanded(!expanded)}
|
||||
>
|
||||
<td className="py-2">
|
||||
<span className="font-mono text-xs bg-muted px-1 rounded mr-2">{ruta}</span>
|
||||
{label}
|
||||
{accounts.length > 0 && (
|
||||
<span className="text-xs text-muted-foreground ml-2">
|
||||
({accounts.length} konton)
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
{isExpense && amount > 0 ? '-' : ''}{formatAmount(Math.abs(amount))} kr
|
||||
</td>
|
||||
</tr>
|
||||
{expanded && accounts.length > 0 && (
|
||||
<tr>
|
||||
<td colSpan={2} className="py-2 pl-8 bg-muted/30">
|
||||
<table className="w-full text-xs">
|
||||
<tbody>
|
||||
{accounts.map((acc) => (
|
||||
<tr key={acc.accountNumber}>
|
||||
<td className="py-1 font-mono">{acc.accountNumber}</td>
|
||||
<td className="py-1">{acc.accountName}</td>
|
||||
<td className="py-1 text-right">
|
||||
{isExpense && acc.amount > 0 ? '-' : ''}{formatAmount(Math.abs(acc.amount))} kr
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
} from 'lucide-react'
|
||||
import type { CompanySettings, BankConnection } from '@/types'
|
||||
import { BankSelector, type Bank } from '@/components/banking/BankSelector'
|
||||
import { NotificationSettings } from '@/components/settings/NotificationSettings'
|
||||
import { NotificationSettings } from '@/extensions/push-notifications/NotificationSettings'
|
||||
import { CalendarFeedSettings } from '@/components/settings/CalendarFeedSettings'
|
||||
|
||||
export default function SettingsPage() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateChatResponse } from '@/lib/ai/chatbot/chain'
|
||||
import { CHATBOT_CONFIG } from '@/lib/ai/chatbot/config'
|
||||
import { generateChatResponse } from '@/extensions/ai-chat/chatbot/chain'
|
||||
import { CHATBOT_CONFIG } from '@/extensions/ai-chat/chatbot/config'
|
||||
import type { ChatMessage, ChatRequest } from '@/types/chat'
|
||||
|
||||
// Simple in-memory rate limiting (per user)
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { streamChatResponse } from '@/lib/ai/chatbot/chain'
|
||||
import { CHATBOT_CONFIG } from '@/lib/ai/chatbot/config'
|
||||
import { streamChatResponse } from '@/extensions/ai-chat/chatbot/chain'
|
||||
import { CHATBOT_CONFIG } from '@/extensions/ai-chat/chatbot/config'
|
||||
import type { ChatMessage, ChatRequest, SourceReference } from '@/types/chat'
|
||||
|
||||
// Simple in-memory rate limiting (per user)
|
||||
@@ -1,14 +1,14 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateNEDeclaration } from '@/lib/reports/ne-declaration'
|
||||
import { generateNEDeclaration } from '@/extensions/ne-bilaga/ne-engine'
|
||||
import {
|
||||
generateSRUFile,
|
||||
sruFileToString,
|
||||
getSRUFilename,
|
||||
} from '@/lib/reports/sru-generator'
|
||||
} from '@/extensions/sru-export/lib/sru-generator'
|
||||
|
||||
/**
|
||||
* GET /api/reports/ne-declaration
|
||||
* GET /api/extensions/ne-bilaga
|
||||
*
|
||||
* Generate NE declaration (NE-bilaga) for enskild firma.
|
||||
*
|
||||
@@ -1,18 +1,22 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { loadExtensions } from '@/lib/extensions/loader'
|
||||
import {
|
||||
sendTaxDeadlineNotifications,
|
||||
sendInvoiceNotifications,
|
||||
} from '@/lib/push/notification-scheduler'
|
||||
} from '@/extensions/push-notifications/notification-scheduler'
|
||||
|
||||
/**
|
||||
* GET /api/push/cron
|
||||
* GET /api/extensions/push-notifications/cron
|
||||
* Daily cron job to send push notifications
|
||||
* Runs at 09:00 every day
|
||||
*
|
||||
* Vercel Cron: "0 9 * * *"
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
// 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
|
||||
@@ -0,0 +1,61 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getSettings, saveSettings } from '@/extensions/push-notifications'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/push-notifications/settings
|
||||
* Get the current user's push-notification 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/push-notifications/settings
|
||||
* Update the current user's push-notification 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()
|
||||
|
||||
const allowedKeys = [
|
||||
'periodLockedEnabled',
|
||||
'periodYearClosedEnabled',
|
||||
'invoiceSentEnabled',
|
||||
'receiptExtractedEnabled',
|
||||
'receiptMatchedEnabled',
|
||||
]
|
||||
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 })
|
||||
}
|
||||
+4
-4
@@ -1,9 +1,9 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getVapidPublicKey } from '@/lib/push/web-push'
|
||||
import { getVapidPublicKey } from '@/extensions/push-notifications/notification-sender'
|
||||
|
||||
/**
|
||||
* GET /api/push/subscribe
|
||||
* GET /api/extensions/push-notifications/subscribe
|
||||
* Get the VAPID public key for client-side subscription
|
||||
*/
|
||||
export async function GET() {
|
||||
@@ -20,7 +20,7 @@ export async function GET() {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/push/subscribe
|
||||
* POST /api/extensions/push-notifications/subscribe
|
||||
* Save a new push subscription
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
@@ -96,7 +96,7 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/push/subscribe
|
||||
* DELETE /api/extensions/push-notifications/subscribe
|
||||
* Remove a push subscription
|
||||
*/
|
||||
export async function DELETE(request: Request) {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { findTransactionMatches } from '@/lib/receipts/receipt-matcher'
|
||||
import { findTransactionMatches } from '@/extensions/receipt-ocr/lib/receipt-matcher'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { Receipt, Transaction } from '@/types'
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { analyzeReceipt } from '@/extensions/receipt-ocr/lib/receipt-analyzer'
|
||||
import { processLineItems } from '@/extensions/receipt-ocr/lib/receipt-categorizer'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getSRUCoverage } from '@/extensions/sru-export/sru-engine'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/sru-export/coverage
|
||||
*
|
||||
* Returns SRU code coverage stats: how many accounts have SRU codes vs total,
|
||||
* and a list of accounts missing codes.
|
||||
*/
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const coverage = await getSRUCoverage(user.id)
|
||||
return NextResponse.json({ data: coverage })
|
||||
} catch (err) {
|
||||
console.error('Error fetching SRU coverage:', err)
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to fetch SRU coverage' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { aggregateBalancesBySRU } from '@/extensions/sru-export/sru-engine'
|
||||
import {
|
||||
generateGenericSRU,
|
||||
getGenericSRUFilename,
|
||||
sruFileToString,
|
||||
validateSRUFile,
|
||||
SRU_CODE_DESCRIPTIONS,
|
||||
} from '@/extensions/sru-export/sru-generator'
|
||||
import type { SRUFormType } from '@/extensions/sru-export/sru-generator'
|
||||
import type { EntityType } from '@/types'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/sru-export
|
||||
*
|
||||
* Generate SRU export from chart_of_accounts sru_code mappings.
|
||||
*
|
||||
* Query parameters:
|
||||
* - period_id: Fiscal period ID (required)
|
||||
* - format: 'json' (default) or 'sru' for downloadable file
|
||||
*/
|
||||
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 periodId = searchParams.get('period_id')
|
||||
const format = searchParams.get('format') || 'json'
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'period_id is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
// Fetch company settings to determine entity type
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('entity_type, company_name, org_number')
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
if (!settings) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Company settings not found. Complete onboarding first.' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Determine form type from entity type
|
||||
const formType: SRUFormType = settings.entity_type === 'aktiebolag' ? 'INK2' : 'NE'
|
||||
|
||||
// Fetch fiscal period for date range
|
||||
const { data: period } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('*')
|
||||
.eq('id', periodId)
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Fiscal period not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Aggregate balances by SRU code
|
||||
const sruBalances = await aggregateBalancesBySRU(user.id, periodId)
|
||||
|
||||
if (format === 'sru') {
|
||||
// Generate and return SRU file
|
||||
const sruFile = generateGenericSRU({
|
||||
formType,
|
||||
orgNumber: settings.org_number,
|
||||
companyName: settings.company_name || 'Okänt företag',
|
||||
fiscalYearStart: period.period_start,
|
||||
fiscalYearEnd: period.period_end,
|
||||
sruBalances,
|
||||
})
|
||||
|
||||
const validation = validateSRUFile(sruFile)
|
||||
if (!validation.isValid) {
|
||||
return NextResponse.json(
|
||||
{ error: 'SRU validation failed', details: validation.errors },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
const sruContent = sruFileToString(sruFile)
|
||||
const filename = getGenericSRUFilename(formType, settings.org_number, period.period_start)
|
||||
|
||||
return new NextResponse(sruContent, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Default: return JSON preview
|
||||
const balancesArray = Array.from(sruBalances.values())
|
||||
.sort((a, b) => a.sruCode.localeCompare(b.sruCode))
|
||||
.map((b) => ({
|
||||
sruCode: b.sruCode,
|
||||
description: SRU_CODE_DESCRIPTIONS[b.sruCode] || `SRU ${b.sruCode}`,
|
||||
amount: b.amount,
|
||||
accounts: b.accounts,
|
||||
}))
|
||||
|
||||
const warnings: string[] = []
|
||||
if (!period.is_closed) {
|
||||
warnings.push('Räkenskapsåret är inte stängt. Siffrorna kan ändras.')
|
||||
}
|
||||
if (balancesArray.length === 0) {
|
||||
warnings.push('Inga konton med SRU-koder har bokförda poster i denna period.')
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
formType,
|
||||
entityType: settings.entity_type as EntityType,
|
||||
companyName: settings.company_name,
|
||||
orgNumber: settings.org_number,
|
||||
fiscalYear: {
|
||||
id: period.id,
|
||||
name: period.name,
|
||||
start: period.period_start,
|
||||
end: period.period_end,
|
||||
},
|
||||
balances: balancesArray,
|
||||
warnings,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Error generating SRU export:', err)
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to generate SRU export' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
+61
-62
@@ -8,85 +8,84 @@ html, :root {
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: 40 30% 97% !important;
|
||||
--foreground: 30 10% 15% !important;
|
||||
--card: 40 40% 99% !important;
|
||||
--card-foreground: 30 10% 15% !important;
|
||||
--popover: 40 40% 99% !important;
|
||||
--popover-foreground: 30 10% 15% !important;
|
||||
--primary: 28 40% 35% !important;
|
||||
--primary-foreground: 40 40% 99% !important;
|
||||
--secondary: 35 25% 93% !important;
|
||||
--secondary-foreground: 30 10% 15% !important;
|
||||
--muted: 35 15% 91% !important;
|
||||
--muted-foreground: 30 8% 45% !important;
|
||||
--accent: 18 45% 55% !important;
|
||||
--accent-foreground: 40 40% 99% !important;
|
||||
--destructive: 0 45% 55% !important;
|
||||
--destructive-foreground: 40 40% 99% !important;
|
||||
--border: 35 20% 88% !important;
|
||||
--input: 35 20% 88% !important;
|
||||
--ring: 28 40% 35% !important;
|
||||
--background: 220 14% 96% !important;
|
||||
--foreground: 224 12% 13% !important;
|
||||
--card: 0 0% 100% !important;
|
||||
--card-foreground: 224 12% 13% !important;
|
||||
--popover: 0 0% 100% !important;
|
||||
--popover-foreground: 224 12% 13% !important;
|
||||
--primary: 222 47% 35% !important;
|
||||
--primary-foreground: 0 0% 100% !important;
|
||||
--secondary: 220 13% 93% !important;
|
||||
--secondary-foreground: 224 12% 13% !important;
|
||||
--muted: 218 12% 91% !important;
|
||||
--muted-foreground: 218 8% 46% !important;
|
||||
--accent: 213 72% 50% !important;
|
||||
--accent-foreground: 0 0% 100% !important;
|
||||
--destructive: 0 68% 50% !important;
|
||||
--destructive-foreground: 0 0% 100% !important;
|
||||
--border: 218 14% 89% !important;
|
||||
--input: 218 14% 89% !important;
|
||||
--ring: 222 47% 35% !important;
|
||||
}
|
||||
}
|
||||
|
||||
:root {
|
||||
/* Nordic Warmth Color Palette */
|
||||
/* Inspired by Swedish nature: forest, stone, linen, birch */
|
||||
/* Clean Slate — Modern ERP Palette */
|
||||
|
||||
--background: 40 30% 97%; /* Warm paper white */
|
||||
--foreground: 30 10% 15%; /* Soft charcoal, not harsh black */
|
||||
--background: 220 14% 96%; /* Cool off-white #F2F4F7 */
|
||||
--foreground: 224 12% 13%; /* Deep slate #1D2029 */
|
||||
|
||||
--card: 40 40% 99%; /* Natural white with warmth */
|
||||
--card-foreground: 30 10% 15%;
|
||||
--card: 0 0% 100%; /* Pure white */
|
||||
--card-foreground: 224 12% 13%;
|
||||
|
||||
--popover: 40 40% 99%;
|
||||
--popover-foreground: 30 10% 15%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 224 12% 13%;
|
||||
|
||||
/* Primary - Leather Brown (warm, dark) */
|
||||
--primary: 28 40% 35%; /* Dark leather brown */
|
||||
--primary-foreground: 40 40% 99%;
|
||||
/* Primary — Refined navy-blue */
|
||||
--primary: 222 47% 35%; /* #304D83 */
|
||||
--primary-foreground: 0 0% 100%;
|
||||
|
||||
/* Secondary - Warm Linen */
|
||||
--secondary: 35 25% 93%; /* Soft linen/oat */
|
||||
--secondary-foreground: 30 10% 15%;
|
||||
/* Secondary — Cool pale gray */
|
||||
--secondary: 220 13% 93%; /* #EBEDF1 */
|
||||
--secondary-foreground: 224 12% 13%;
|
||||
|
||||
/* Muted - Stone */
|
||||
--muted: 35 15% 91%; /* Warm stone gray */
|
||||
--muted-foreground: 30 8% 45%; /* Soft warm gray */
|
||||
/* Muted — Neutral gray */
|
||||
--muted: 218 12% 91%; /* #E3E6EB */
|
||||
--muted-foreground: 218 8% 46%; /* #6B7280 */
|
||||
|
||||
/* Accent - Terracotta */
|
||||
--accent: 18 45% 55%; /* Muted terracotta/clay */
|
||||
--accent-foreground: 40 40% 99%;
|
||||
/* Accent — Clear blue for interactive highlights */
|
||||
--accent: 213 72% 50%; /* #2373D8 */
|
||||
--accent-foreground: 0 0% 100%;
|
||||
|
||||
/* Destructive - Muted Rose */
|
||||
--destructive: 0 45% 55%; /* Soft dusty rose */
|
||||
--destructive-foreground: 40 40% 99%;
|
||||
/* Destructive — Clean red */
|
||||
--destructive: 0 68% 50%; /* #D63232 */
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
|
||||
/* Borders & Input - Soft warm line */
|
||||
--border: 35 20% 88%;
|
||||
--input: 35 20% 88%;
|
||||
--ring: 28 40% 35%;
|
||||
/* Borders & Input */
|
||||
--border: 218 14% 89%; /* #DEE1E7 */
|
||||
--input: 218 14% 89%;
|
||||
--ring: 222 47% 35%;
|
||||
|
||||
/* Radius - Subtle, refined */
|
||||
/* Radius */
|
||||
--radius: 0.5rem;
|
||||
|
||||
/* Success - Forest green */
|
||||
--success: 150 30% 40%;
|
||||
--success-foreground: 40 40% 99%;
|
||||
/* Success — Clean green */
|
||||
--success: 152 48% 38%; /* #329460 */
|
||||
--success-foreground: 0 0% 100%;
|
||||
|
||||
/* Warning - Warm honey */
|
||||
--warning: 38 70% 55%;
|
||||
--warning-foreground: 30 10% 15%;
|
||||
/* Warning — Clear amber */
|
||||
--warning: 38 92% 50%; /* #F59E0B */
|
||||
--warning-foreground: 224 12% 13%;
|
||||
|
||||
/* Custom tokens */
|
||||
--font-display: var(--font-fraunces), Georgia, serif;
|
||||
--font-body: var(--font-geist-sans), system-ui, sans-serif;
|
||||
|
||||
/* Refined shadows */
|
||||
--shadow-sm: 0 1px 2px rgba(30, 25, 20, 0.04);
|
||||
--shadow-md: 0 4px 12px rgba(30, 25, 20, 0.06);
|
||||
--shadow-lg: 0 12px 40px rgba(30, 25, 20, 0.08);
|
||||
/* Shadows — cool-toned */
|
||||
--shadow-sm: 0 1px 2px rgba(15, 23, 42, 0.04);
|
||||
--shadow-md: 0 4px 12px rgba(15, 23, 42, 0.06);
|
||||
--shadow-lg: 0 12px 40px rgba(15, 23, 42, 0.08);
|
||||
|
||||
/* Animation */
|
||||
--ease-out: cubic-bezier(0.25, 0.46, 0.45, 0.94);
|
||||
@@ -151,7 +150,7 @@ body {
|
||||
h1, h2, h3 {
|
||||
font-family: var(--font-display);
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.02em;
|
||||
letter-spacing: -0.015em;
|
||||
font-optical-sizing: auto;
|
||||
}
|
||||
|
||||
@@ -244,13 +243,13 @@ h1, h2, h3 {
|
||||
|
||||
/* Refined hover effects */
|
||||
.hover-lift {
|
||||
transition: transform var(--duration-base) var(--ease-out),
|
||||
box-shadow var(--duration-base) var(--ease-out);
|
||||
transition: transform var(--duration-fast) var(--ease-out),
|
||||
box-shadow var(--duration-fast) var(--ease-out);
|
||||
}
|
||||
|
||||
.hover-lift:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: var(--shadow-lg);
|
||||
transform: translateY(-1px);
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
/* Soft focus states */
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ export const metadata: Metadata = {
|
||||
};
|
||||
|
||||
export const viewport: Viewport = {
|
||||
themeColor: "#1a1a1a",
|
||||
themeColor: "#304D83",
|
||||
width: "device-width",
|
||||
initialScale: 1,
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user