Merge pull request #1 from erp-mafia/code-quality-improvements
Code quality improvements
This commit is contained in:
@@ -16,7 +16,12 @@
|
||||
"Bash(python3:*)",
|
||||
"Bash(git -C /Users/jakobwennberg/erp-base status --porcelain)",
|
||||
"Bash(__NEW_LINE_421a23f44da9923d__ echo '=== Checking which index exports are used ===' grep -r @/components/calendar /Users/jakobwennberg/erp-base/app --include=*.tsx --include=*.ts 2)",
|
||||
"Bash(/dev/null __NEW_LINE_421a23f44da9923d__ echo -e '\\\\n=== Checking which calendar deadline components are directly imported ===' grep -rE \"DeadlineList|DeadlineCard|DeadlineForm|DeadlineFilters|PaymentSummaryCard|TaxTodoWidget|UpcomingDeadlinesWidget\" /Users/jakobwennberg/erp-base --include=*.tsx --include=*.ts)"
|
||||
"Bash(/dev/null __NEW_LINE_421a23f44da9923d__ echo -e '\\\\n=== Checking which calendar deadline components are directly imported ===' grep -rE \"DeadlineList|DeadlineCard|DeadlineForm|DeadlineFilters|PaymentSummaryCard|TaxTodoWidget|UpcomingDeadlinesWidget\" /Users/jakobwennberg/erp-base --include=*.tsx --include=*.ts)",
|
||||
"Bash(npm run build:*)",
|
||||
"Bash(npx supabase:*)",
|
||||
"Bash(curl:*)",
|
||||
"Bash(npx tsc:*)",
|
||||
"Bash(findstr:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
nul
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
|
||||
@@ -298,7 +298,7 @@ All defined in `lib/events/types.ts`:
|
||||
|
||||
### Scope
|
||||
|
||||
Only test business logic in `lib/`. No component tests, no API route tests, no E2E tests.
|
||||
Test business logic in `lib/` and API routes in `app/api/`. No component tests, no E2E tests.
|
||||
|
||||
### Framework
|
||||
|
||||
@@ -334,6 +334,14 @@ mockResult({ data: makeTransaction(), error: null })
|
||||
- Test error paths (missing fiscal period, unbalanced entries)
|
||||
- Verify events are emitted correctly
|
||||
|
||||
### API Route Tests
|
||||
|
||||
- Colocated `__tests__/` directories alongside route files (e.g., `app/api/invoices/__tests__/route.test.ts`)
|
||||
- Mock `@/lib/supabase/server`, `@/lib/init`, and lib functions — do NOT re-test lib business logic
|
||||
- Use `createMockRequest()`, `parseJsonResponse()`, `createMockRouteParams()` from `tests/helpers.ts`
|
||||
- Use `createQueuedMockSupabase()` for routes with multiple sequential Supabase calls
|
||||
- Test: auth (401), validation (400), not found (404), errors (500), happy path, non-blocking journal entry failures
|
||||
|
||||
### Reference Tests
|
||||
|
||||
- `lib/bookkeeping/__tests__/engine.test.ts` — Balance validation
|
||||
@@ -498,3 +506,6 @@ NEXT_PUBLIC_APP_URL # App base URL
|
||||
NEXT_PUBLIC_VAPID_PUBLIC_KEY # Web push public key
|
||||
VAPID_PRIVATE_KEY # Web push private key
|
||||
```
|
||||
|
||||
## Other
|
||||
We should never create a nul file
|
||||
|
||||
@@ -1,35 +1,74 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createServerClient } from '@supabase/ssr'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams, origin } = new URL(request.url)
|
||||
const code = searchParams.get('code')
|
||||
const token_hash = searchParams.get('token_hash')
|
||||
const type = searchParams.get('type')
|
||||
const next = searchParams.get('next') ?? '/'
|
||||
|
||||
if (code) {
|
||||
const supabase = await createClient()
|
||||
const { error } = await supabase.auth.exchangeCodeForSession(code)
|
||||
// Collect cookies that Supabase sets during auth so we can
|
||||
// explicitly forward them on the redirect response.
|
||||
const pendingCookies: { name: string; value: string; options: Record<string, unknown> }[] = []
|
||||
|
||||
if (!error) {
|
||||
// Check if user has completed onboarding
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (user) {
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('onboarding_complete')
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
if (!settings?.onboarding_complete) {
|
||||
return NextResponse.redirect(`${origin}/onboarding`)
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.redirect(`${origin}${next}`)
|
||||
const supabase = createServerClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
||||
{
|
||||
cookies: {
|
||||
getAll() {
|
||||
return request.cookies.getAll()
|
||||
},
|
||||
setAll(cookiesToSet) {
|
||||
pendingCookies.length = 0
|
||||
cookiesToSet.forEach((cookie) => pendingCookies.push(cookie))
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
let authenticated = false
|
||||
|
||||
// Handle PKCE flow (code exchange)
|
||||
if (code) {
|
||||
const { error } = await supabase.auth.exchangeCodeForSession(code)
|
||||
authenticated = !error
|
||||
}
|
||||
// Handle token hash flow (email verification / magic link)
|
||||
else if (token_hash && type) {
|
||||
const { error } = await supabase.auth.verifyOtp({
|
||||
token_hash,
|
||||
type: type as 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email',
|
||||
})
|
||||
authenticated = !error
|
||||
}
|
||||
|
||||
// Return the user to an error page with instructions
|
||||
return NextResponse.redirect(`${origin}/login?error=auth_error`)
|
||||
if (authenticated) {
|
||||
let redirectPath = next
|
||||
|
||||
// Check if user has completed onboarding
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (user) {
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('onboarding_complete')
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
if (!settings?.onboarding_complete) {
|
||||
redirectPath = '/onboarding'
|
||||
}
|
||||
}
|
||||
|
||||
// Create redirect and explicitly set auth cookies on the response
|
||||
const response = NextResponse.redirect(new URL(redirectPath, origin))
|
||||
for (const { name, value, options } of pendingCookies) {
|
||||
response.cookies.set({ name, value, ...options })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
// Authentication failed — redirect to login with error
|
||||
return NextResponse.redirect(new URL('/login?error=auth_error', origin))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { redirect, notFound } from 'next/navigation'
|
||||
import { getExtensionDefinition } from '@/lib/extensions/sectors'
|
||||
import ExtensionWorkspaceLoader from '@/components/extensions/ExtensionWorkspaceLoader'
|
||||
|
||||
export default async function ExtensionWorkspacePage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ sector: string; slug: string }>
|
||||
}) {
|
||||
const { sector, slug } = await params
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) redirect('/login')
|
||||
|
||||
const definition = getExtensionDefinition(sector, slug)
|
||||
if (!definition) notFound()
|
||||
|
||||
// Check toggle
|
||||
const { data: toggle } = await supabase
|
||||
.from('extension_toggles')
|
||||
.select('enabled')
|
||||
.eq('user_id', user.id)
|
||||
.eq('sector_slug', sector)
|
||||
.eq('extension_slug', slug)
|
||||
.single()
|
||||
|
||||
if (!toggle?.enabled) redirect('/extensions')
|
||||
|
||||
return (
|
||||
<ExtensionWorkspaceLoader
|
||||
sector={sector}
|
||||
slug={slug}
|
||||
definition={definition}
|
||||
userId={user.id}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { notFound } from 'next/navigation'
|
||||
import { getExtensionDefinition, getSector } from '@/lib/extensions/sectors'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import CategoryBadge from '@/components/extensions/CategoryBadge'
|
||||
import ExtensionToggleButton from '@/components/extensions/ExtensionToggleButton'
|
||||
import Link from 'next/link'
|
||||
|
||||
export default async function ExtensionDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ sector: string; extension: string }>
|
||||
}) {
|
||||
const { sector: sectorSlug, extension: extensionSlug } = await params
|
||||
|
||||
const definition = getExtensionDefinition(sectorSlug, extensionSlug)
|
||||
if (!definition) notFound()
|
||||
|
||||
const sector = getSector(sectorSlug as any)
|
||||
const Icon = resolveIcon(definition.icon)
|
||||
|
||||
const dataPatternLabels: Record<string, string> = {
|
||||
core: 'Använder bokföringsdata',
|
||||
manual: 'Manuell inmatning',
|
||||
both: 'Bokföringsdata + manuell inmatning',
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Breadcrumb */}
|
||||
<nav className="flex items-center gap-1.5 text-sm text-muted-foreground mb-6">
|
||||
<Link href="/extensions" className="hover:text-foreground transition-colors">
|
||||
Tillägg
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<Link
|
||||
href={`/extensions/${sectorSlug}`}
|
||||
className="hover:text-foreground transition-colors"
|
||||
>
|
||||
{sector?.name ?? sectorSlug}
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<span className="text-foreground">{definition.name}</span>
|
||||
</nav>
|
||||
|
||||
{/* Header with toggle */}
|
||||
<div className="flex items-start justify-between gap-4 mb-8">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-xl bg-primary/10 flex-shrink-0">
|
||||
<Icon className="h-7 w-7 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{definition.name}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">{definition.description}</p>
|
||||
<div className="mt-2">
|
||||
<CategoryBadge category={definition.category} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ExtensionToggleButton sectorSlug={sectorSlug} extensionSlug={extensionSlug} />
|
||||
</div>
|
||||
|
||||
{/* Details */}
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold mb-2">Beskrivning</h2>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">
|
||||
{definition.longDescription}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold mb-2">Datakälla</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{dataPatternLabels[definition.dataPattern]}
|
||||
</p>
|
||||
{definition.readsCoreTables && definition.readsCoreTables.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Läser från: {definition.readsCoreTables.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { notFound } from 'next/navigation'
|
||||
import { getSector } from '@/lib/extensions/sectors'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import ExtensionCard from '@/components/extensions/ExtensionCard'
|
||||
import Link from 'next/link'
|
||||
|
||||
export default async function SectorExtensionsPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ sector: string }>
|
||||
}) {
|
||||
const { sector: sectorSlug } = await params
|
||||
const sector = getSector(sectorSlug as any)
|
||||
|
||||
if (!sector) notFound()
|
||||
|
||||
const Icon = resolveIcon(sector.icon)
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Breadcrumb */}
|
||||
<nav className="flex items-center gap-1.5 text-sm text-muted-foreground mb-6">
|
||||
<Link href="/extensions" className="hover:text-foreground transition-colors">
|
||||
Tillägg
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<span className="text-foreground">{sector.name}</span>
|
||||
</nav>
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-start gap-4 mb-8">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary/10 flex-shrink-0">
|
||||
<Icon className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{sector.name}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">{sector.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Extensions grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{sector.extensions.map(ext => (
|
||||
<ExtensionCard key={ext.slug} extension={ext} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { SECTORS } from '@/lib/extensions/sectors'
|
||||
import ExtensionCard from '@/components/extensions/ExtensionCard'
|
||||
import SectorCard from '@/components/extensions/SectorCard'
|
||||
|
||||
export default function ExtensionsPage() {
|
||||
const generalSector = SECTORS.find(s => s.slug === 'general')
|
||||
const industrySectors = SECTORS.filter(s => s.slug !== 'general')
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-xl font-semibold tracking-tight">Tillägg</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Utöka ditt bokföringssystem med verktyg och branschspecifika funktioner.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* General extensions */}
|
||||
{generalSector && (
|
||||
<section className="mb-10">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-4">
|
||||
{generalSector.name}
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{generalSector.extensions.map(ext => (
|
||||
<ExtensionCard key={ext.slug} extension={ext} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Industry sectors */}
|
||||
<section>
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-4">
|
||||
Branschverktyg
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
|
||||
{industrySectors.map(sector => (
|
||||
<SectorCard key={sector.slug} sector={sector} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { getVatTreatmentLabel } from '@/lib/invoice/vat-rules'
|
||||
import { getVatTreatmentLabel } from '@/lib/invoices/vat-rules'
|
||||
import { Loader2, ArrowLeft, AlertTriangle } from 'lucide-react'
|
||||
import type { Invoice, InvoiceItem, Customer } from '@/types'
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { getVatTreatmentLabel } from '@/lib/invoice/vat-rules'
|
||||
import { getVatTreatmentLabel } from '@/lib/invoices/vat-rules'
|
||||
import {
|
||||
Loader2,
|
||||
ArrowLeft,
|
||||
|
||||
@@ -16,7 +16,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { getVatRules, getVatTreatmentLabel, getAvailableVatRates } from '@/lib/invoice/vat-rules'
|
||||
import { getVatRules, getVatTreatmentLabel, getAvailableVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye } from 'lucide-react'
|
||||
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
|
||||
|
||||
@@ -29,6 +29,12 @@ export default async function DashboardLayout({
|
||||
|
||||
const entityType = (settings.entity_type as EntityType) || 'enskild_firma'
|
||||
|
||||
const { data: enabledToggles } = await supabase
|
||||
.from('extension_toggles')
|
||||
.select('sector_slug, extension_slug')
|
||||
.eq('user_id', user.id)
|
||||
.eq('enabled', true)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
{/* Skip to content link for keyboard/screen reader users */}
|
||||
@@ -41,6 +47,7 @@ export default async function DashboardLayout({
|
||||
<DashboardNav
|
||||
companyName={settings.company_name || 'Min verksamhet'}
|
||||
entityType={entityType}
|
||||
enabledExtensions={enabledToggles || []}
|
||||
/>
|
||||
<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">
|
||||
|
||||
@@ -1 +1 @@
|
||||
export { default } from '@/extensions/receipt-ocr/pages/ReceiptsPage'
|
||||
export { default } from '@/extensions/general/receipt-ocr/pages/ReceiptsPage'
|
||||
|
||||
@@ -1 +1 @@
|
||||
export { default } from '@/extensions/receipt-ocr/pages/scan/ScanReceiptPage'
|
||||
export { default } from '@/extensions/general/receipt-ocr/pages/scan/ScanReceiptPage'
|
||||
|
||||
@@ -23,9 +23,14 @@ import {
|
||||
LogOut,
|
||||
Bell,
|
||||
Calendar,
|
||||
Sun,
|
||||
Moon,
|
||||
Monitor,
|
||||
Palette,
|
||||
} from 'lucide-react'
|
||||
import { useTheme } from 'next-themes'
|
||||
import type { CompanySettings, BankConnection } from '@/types'
|
||||
import { NotificationSettings } from '@/extensions/push-notifications/NotificationSettings'
|
||||
import { NotificationSettings } from '@/extensions/general/push-notifications/NotificationSettings'
|
||||
import { CalendarFeedSettings } from '@/components/settings/CalendarFeedSettings'
|
||||
|
||||
export default function SettingsPage() {
|
||||
@@ -41,6 +46,12 @@ export default function SettingsPage() {
|
||||
const [isSyncing, setIsSyncing] = useState(false)
|
||||
const [isConnecting, setIsConnecting] = useState(false)
|
||||
const [hasBankingExtension, setHasBankingExtension] = useState(false)
|
||||
const { theme, setTheme } = useTheme()
|
||||
const [mounted, setMounted] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
@@ -311,6 +322,10 @@ export default function SettingsPage() {
|
||||
<Calendar className="mr-2 h-4 w-4" />
|
||||
Kalender
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="appearance">
|
||||
<Palette className="mr-2 h-4 w-4" />
|
||||
Utseende
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="account">
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
Konto
|
||||
@@ -625,6 +640,103 @@ export default function SettingsPage() {
|
||||
<CalendarFeedSettings />
|
||||
</TabsContent>
|
||||
|
||||
{/* Appearance settings */}
|
||||
<TabsContent value="appearance">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Utseende</CardTitle>
|
||||
<CardDescription>
|
||||
Välj hur applikationen ska se ut
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{mounted && (
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{/* Light */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTheme('light')}
|
||||
className={`group relative rounded-lg border-2 p-4 text-left transition-colors ${
|
||||
theme === 'light'
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/40'
|
||||
}`}
|
||||
>
|
||||
<div className="mb-3 flex h-20 items-end gap-1.5 rounded-md border bg-white p-2">
|
||||
<div className="h-full w-3 rounded-sm bg-[hsl(222,47%,35%)]" />
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<div className="h-2 w-3/4 rounded-sm bg-[hsl(220,14%,96%)]" />
|
||||
<div className="h-2 w-1/2 rounded-sm bg-[hsl(220,14%,96%)]" />
|
||||
<div className="h-2 w-2/3 rounded-sm bg-[hsl(220,14%,96%)]" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Sun className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Ljust</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Dark */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTheme('dark')}
|
||||
className={`group relative rounded-lg border-2 p-4 text-left transition-colors ${
|
||||
theme === 'dark'
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/40'
|
||||
}`}
|
||||
>
|
||||
<div className="mb-3 flex h-20 items-end gap-1.5 rounded-md border bg-[hsl(222,16%,10%)] p-2">
|
||||
<div className="h-full w-3 rounded-sm bg-[hsl(222,50%,55%)]" />
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<div className="h-2 w-3/4 rounded-sm bg-[hsl(220,12%,20%)]" />
|
||||
<div className="h-2 w-1/2 rounded-sm bg-[hsl(220,12%,20%)]" />
|
||||
<div className="h-2 w-2/3 rounded-sm bg-[hsl(220,12%,20%)]" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Moon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Mörkt</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* System */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTheme('system')}
|
||||
className={`group relative rounded-lg border-2 p-4 text-left transition-colors ${
|
||||
theme === 'system'
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/40'
|
||||
}`}
|
||||
>
|
||||
<div className="mb-3 flex h-20 overflow-hidden rounded-md border">
|
||||
<div className="flex flex-1 items-end gap-1 bg-white p-2">
|
||||
<div className="h-full w-2 rounded-sm bg-[hsl(222,47%,35%)]" />
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<div className="h-2 w-3/4 rounded-sm bg-[hsl(220,14%,96%)]" />
|
||||
<div className="h-2 w-1/2 rounded-sm bg-[hsl(220,14%,96%)]" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-1 items-end gap-1 bg-[hsl(222,16%,10%)] p-2">
|
||||
<div className="h-full w-2 rounded-sm bg-[hsl(222,50%,55%)]" />
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<div className="h-2 w-3/4 rounded-sm bg-[hsl(220,12%,20%)]" />
|
||||
<div className="h-2 w-1/2 rounded-sm bg-[hsl(220,12%,20%)]" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Monitor className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">System</span>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* Account settings */}
|
||||
<TabsContent value="account">
|
||||
<Card>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useMemo, Suspense } from 'react'
|
||||
import { useState, useEffect, Suspense } from 'react'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import type { CompanySettings, EntityType, MomsPeriod } from '@/types'
|
||||
@@ -13,13 +12,18 @@ import Step1EntityType from '@/components/onboarding/Step1EntityType'
|
||||
import Step2CompanyDetails from '@/components/onboarding/Step2CompanyDetails'
|
||||
import Step3TaxRegistration from '@/components/onboarding/Step3TaxRegistration'
|
||||
import Step4PreliminaryTax from '@/components/onboarding/Step4PreliminaryTax'
|
||||
import Step6ConnectBank from '@/components/onboarding/Step6ConnectBank'
|
||||
import Step5ConnectBank from '@/components/onboarding/Step6ConnectBank'
|
||||
import Step6SectorSelection from '@/components/onboarding/Step2SectorSelection'
|
||||
import Step7ExtensionSuggestions from '@/components/onboarding/Step3ExtensionSuggestions'
|
||||
|
||||
const STEP_TITLES = [
|
||||
'Verksamhetsform',
|
||||
'Företagsuppgifter',
|
||||
'Skatteregistrering',
|
||||
'F-skatt',
|
||||
'Anslut bank',
|
||||
'Bransch',
|
||||
'Tillägg',
|
||||
]
|
||||
|
||||
export default function OnboardingPage() {
|
||||
@@ -40,8 +44,9 @@ function OnboardingPageContent() {
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [currentStep, setCurrentStep] = useState(1)
|
||||
const [settings, setSettings] = useState<Partial<CompanySettings>>({})
|
||||
const [sectorSlug, setSectorSlug] = useState<string | null>(null)
|
||||
|
||||
const totalSteps = 5
|
||||
const totalSteps = 7
|
||||
const stepTitles = STEP_TITLES
|
||||
|
||||
// Load existing settings on mount
|
||||
@@ -63,6 +68,9 @@ function OnboardingPageContent() {
|
||||
if (data) {
|
||||
setSettings(data)
|
||||
setCurrentStep(data.onboarding_step || 1)
|
||||
if ((data as Record<string, unknown>).sector_slug) {
|
||||
setSectorSlug((data as Record<string, unknown>).sector_slug as string)
|
||||
}
|
||||
}
|
||||
|
||||
setIsLoading(false)
|
||||
@@ -74,13 +82,13 @@ function OnboardingPageContent() {
|
||||
// Handle bank_connected callback from PSD2 flow
|
||||
useEffect(() => {
|
||||
if (searchParams.get('bank_connected') === 'true') {
|
||||
saveSettings({ onboarding_complete: true }).then((success) => {
|
||||
toast({
|
||||
title: 'Bank ansluten!',
|
||||
description: 'Din bank har kopplats.',
|
||||
})
|
||||
saveSettings({}, 6).then((success) => {
|
||||
if (success) {
|
||||
toast({
|
||||
title: 'Bank ansluten!',
|
||||
description: 'Din bank är kopplad och profilen är redo.',
|
||||
})
|
||||
router.push('/')
|
||||
setCurrentStep(6)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -249,18 +257,6 @@ function OnboardingPageContent() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleComplete = async () => {
|
||||
const success = await saveSettings({ onboarding_complete: true })
|
||||
|
||||
if (success) {
|
||||
toast({
|
||||
title: 'Välkommen!',
|
||||
description: 'Din profil är nu redo.',
|
||||
})
|
||||
router.push('/')
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
@@ -271,6 +267,41 @@ function OnboardingPageContent() {
|
||||
|
||||
const progressPercent = ((currentStep - 1) / (totalSteps - 1)) * 100
|
||||
|
||||
const handleSectorNext = async (data: { sector_slug: string | null }) => {
|
||||
setSectorSlug(data.sector_slug)
|
||||
const nextStep = currentStep + 1
|
||||
const settingsUpdate: Partial<CompanySettings> = {}
|
||||
if (data.sector_slug) {
|
||||
;(settingsUpdate as Record<string, unknown>).sector_slug = data.sector_slug
|
||||
}
|
||||
const success = await saveSettings(settingsUpdate, nextStep)
|
||||
if (success) {
|
||||
setCurrentStep(nextStep)
|
||||
}
|
||||
}
|
||||
|
||||
const handleExtensionsNext = async (data: { enabled_extensions: { sector_slug: string; extension_slug: string }[] }) => {
|
||||
// Insert extension toggles if any were selected
|
||||
if (data.enabled_extensions.length > 0) {
|
||||
try {
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (user) {
|
||||
const rows = data.enabled_extensions.map(ext => ({
|
||||
user_id: user.id,
|
||||
sector_slug: ext.sector_slug,
|
||||
extension_slug: ext.extension_slug,
|
||||
enabled: true,
|
||||
}))
|
||||
await supabase.from('extension_toggles').upsert(rows, {
|
||||
onConflict: 'user_id,sector_slug,extension_slug',
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to save extension toggles:', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const renderSteps = () => (
|
||||
<>
|
||||
{currentStep === 1 && (
|
||||
@@ -327,7 +358,7 @@ function OnboardingPageContent() {
|
||||
)}
|
||||
|
||||
{currentStep === 5 && (
|
||||
<Step6ConnectBank
|
||||
<Step5ConnectBank
|
||||
initialData={{
|
||||
bank_name: settings.bank_name ?? undefined,
|
||||
clearing_number: settings.clearing_number ?? undefined,
|
||||
@@ -337,10 +368,30 @@ function OnboardingPageContent() {
|
||||
}}
|
||||
onComplete={async (data) => {
|
||||
if (data) {
|
||||
await saveSettings({ ...data, onboarding_complete: true })
|
||||
} else {
|
||||
await saveSettings({ onboarding_complete: true })
|
||||
await saveSettings(data, 6)
|
||||
}
|
||||
setCurrentStep(6)
|
||||
}}
|
||||
onBack={handleBack}
|
||||
onSkip={() => setCurrentStep(6)}
|
||||
isSaving={isSaving}
|
||||
/>
|
||||
)}
|
||||
|
||||
{currentStep === 6 && (
|
||||
<Step6SectorSelection
|
||||
onNext={handleSectorNext}
|
||||
onBack={handleBack}
|
||||
isSaving={isSaving}
|
||||
/>
|
||||
)}
|
||||
|
||||
{currentStep === 7 && (
|
||||
<Step7ExtensionSuggestions
|
||||
sectorSlug={sectorSlug}
|
||||
onNext={async (data) => {
|
||||
await handleExtensionsNext(data)
|
||||
await saveSettings({ onboarding_complete: true }, totalSteps)
|
||||
toast({
|
||||
title: 'Välkommen!',
|
||||
description: 'Din profil är nu redo.',
|
||||
@@ -348,7 +399,6 @@ function OnboardingPageContent() {
|
||||
router.push('/')
|
||||
}}
|
||||
onBack={handleBack}
|
||||
onSkip={handleComplete}
|
||||
isSaving={isSaving}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
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 from = searchParams.get('from')
|
||||
const to = searchParams.get('to')
|
||||
const dateFrom = searchParams.get('date_from')
|
||||
const dateTo = searchParams.get('date_to')
|
||||
const groupBy = searchParams.get('group_by')
|
||||
|
||||
if (!from || !to) {
|
||||
return NextResponse.json(
|
||||
{ error: 'from and to account numbers are required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Get posted journal entries within date range
|
||||
let entriesQuery = supabase
|
||||
.from('journal_entries')
|
||||
.select('id, entry_date')
|
||||
.eq('user_id', user.id)
|
||||
.eq('status', 'posted')
|
||||
|
||||
if (dateFrom) {
|
||||
entriesQuery = entriesQuery.gte('entry_date', dateFrom)
|
||||
}
|
||||
if (dateTo) {
|
||||
entriesQuery = entriesQuery.lte('entry_date', dateTo)
|
||||
}
|
||||
|
||||
const { data: entries, error: entriesError } = await entriesQuery
|
||||
|
||||
if (entriesError) {
|
||||
return NextResponse.json({ error: entriesError.message }, { status: 500 })
|
||||
}
|
||||
|
||||
if (!entries || entries.length === 0) {
|
||||
return NextResponse.json({ totals: [], monthly: groupBy === 'month' ? [] : undefined })
|
||||
}
|
||||
|
||||
const entryIds = entries.map((e) => e.id)
|
||||
const entryDateMap = new Map(entries.map((e) => [e.id, e.entry_date]))
|
||||
|
||||
// Fetch lines in batches to avoid URL length limits
|
||||
const batchSize = 200
|
||||
const allLines: Array<{
|
||||
journal_entry_id: string
|
||||
account_number: string
|
||||
debit_amount: number
|
||||
credit_amount: number
|
||||
}> = []
|
||||
|
||||
for (let i = 0; i < entryIds.length; i += batchSize) {
|
||||
const batch = entryIds.slice(i, i + batchSize)
|
||||
const { data: lines, error: linesError } = await supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('journal_entry_id, account_number, debit_amount, credit_amount')
|
||||
.in('journal_entry_id', batch)
|
||||
.gte('account_number', from)
|
||||
.lte('account_number', to)
|
||||
|
||||
if (linesError) {
|
||||
return NextResponse.json({ error: linesError.message }, { status: 500 })
|
||||
}
|
||||
if (lines) {
|
||||
allLines.push(...lines)
|
||||
}
|
||||
}
|
||||
|
||||
// Aggregate by account
|
||||
const accountTotals = new Map<string, { debit: number; credit: number }>()
|
||||
|
||||
for (const line of allLines) {
|
||||
const existing = accountTotals.get(line.account_number) || { debit: 0, credit: 0 }
|
||||
existing.debit += Number(line.debit_amount) || 0
|
||||
existing.credit += Number(line.credit_amount) || 0
|
||||
accountTotals.set(line.account_number, existing)
|
||||
}
|
||||
|
||||
const totals = Array.from(accountTotals.entries())
|
||||
.map(([account_number, bal]) => ({
|
||||
account_number,
|
||||
debit: Math.round(bal.debit * 100) / 100,
|
||||
credit: Math.round(bal.credit * 100) / 100,
|
||||
net: Math.round((bal.debit - bal.credit) * 100) / 100,
|
||||
}))
|
||||
.sort((a, b) => a.account_number.localeCompare(b.account_number))
|
||||
|
||||
// Monthly grouping
|
||||
if (groupBy === 'month') {
|
||||
const monthlyMap = new Map<string, Map<string, { debit: number; credit: number }>>()
|
||||
|
||||
for (const line of allLines) {
|
||||
const entryDate = entryDateMap.get(line.journal_entry_id)
|
||||
if (!entryDate) continue
|
||||
const month = entryDate.slice(0, 7)
|
||||
if (!monthlyMap.has(month)) {
|
||||
monthlyMap.set(month, new Map())
|
||||
}
|
||||
const monthAccounts = monthlyMap.get(month)!
|
||||
const existing = monthAccounts.get(line.account_number) || { debit: 0, credit: 0 }
|
||||
existing.debit += Number(line.debit_amount) || 0
|
||||
existing.credit += Number(line.credit_amount) || 0
|
||||
monthAccounts.set(line.account_number, existing)
|
||||
}
|
||||
|
||||
const monthlyFlat = Array.from(monthlyMap.entries())
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.flatMap(([month, accounts]) =>
|
||||
Array.from(accounts.entries()).map(([account_number, bal]) => ({
|
||||
month,
|
||||
account_number,
|
||||
debit: Math.round(bal.debit * 100) / 100,
|
||||
credit: Math.round(bal.credit * 100) / 100,
|
||||
net: Math.round((bal.debit - bal.credit) * 100) / 100,
|
||||
}))
|
||||
)
|
||||
|
||||
return NextResponse.json({ totals, monthly: monthlyFlat })
|
||||
}
|
||||
|
||||
return NextResponse.json({ totals })
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
createMockRouteParams,
|
||||
makeJournalEntry,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
// Mock dependencies before imports
|
||||
const mockCreateClient = vi.fn()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => mockCreateClient(),
|
||||
}))
|
||||
|
||||
const mockReverseEntry = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/engine', () => ({
|
||||
reverseEntry: (...args: unknown[]) => mockReverseEntry(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
describe('POST /api/bookkeeping/journal-entries/[id]/reverse', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: mockUser } }) },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: null } }) },
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries/entry-1/reverse', {
|
||||
method: 'POST',
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
|
||||
const { status, body } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(401)
|
||||
expect(body).toEqual({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
it('returns reversed entry on success', async () => {
|
||||
const reversalEntry = makeJournalEntry({
|
||||
id: 'reversal-1',
|
||||
reverses_id: 'entry-1',
|
||||
source_type: 'storno',
|
||||
})
|
||||
mockReverseEntry.mockResolvedValue(reversalEntry)
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries/entry-1/reverse', {
|
||||
method: 'POST',
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual(reversalEntry)
|
||||
expect(mockReverseEntry).toHaveBeenCalledWith('user-1', 'entry-1')
|
||||
})
|
||||
|
||||
it('returns 400 when engine throws', async () => {
|
||||
mockReverseEntry.mockRejectedValue(new Error('Entry already reversed'))
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries/entry-1/reverse', {
|
||||
method: 'POST',
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Entry already reversed')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
makeJournalEntry,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
// Mock dependencies
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
const mockCreateJournalEntry = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/engine', () => ({
|
||||
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
describe('GET /api/bookkeeping/journal-entries', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries')
|
||||
const response = await GET(request)
|
||||
const { status, body } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(401)
|
||||
expect(body).toEqual({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
it('returns entries list', async () => {
|
||||
const entries = [makeJournalEntry(), makeJournalEntry()]
|
||||
enqueue({ data: entries, error: null, count: 2 })
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries')
|
||||
const response = await GET(request)
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown[]; count: number }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual(entries)
|
||||
expect(body.count).toBe(2)
|
||||
})
|
||||
|
||||
it('passes filters to query', async () => {
|
||||
enqueue({ data: [], error: null, count: 0 })
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
||||
searchParams: {
|
||||
period_id: 'period-1',
|
||||
status: 'posted',
|
||||
date_from: '2024-01-01',
|
||||
date_to: '2024-12-31',
|
||||
limit: '10',
|
||||
offset: '5',
|
||||
},
|
||||
})
|
||||
const response = await GET(request)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(mockSupabase.from).toHaveBeenCalledWith('journal_entries')
|
||||
})
|
||||
|
||||
it('returns 500 on database error', async () => {
|
||||
enqueue({ data: null, error: { message: 'DB error' } })
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries')
|
||||
const response = await GET(request)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error).toBe('DB error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/bookkeeping/journal-entries', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
||||
method: 'POST',
|
||||
body: {},
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(401)
|
||||
expect(body).toEqual({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
it('creates journal entry and returns it', async () => {
|
||||
const entry = makeJournalEntry()
|
||||
mockCreateJournalEntry.mockResolvedValue(entry)
|
||||
|
||||
const input = {
|
||||
fiscal_period_id: 'period-1',
|
||||
entry_date: '2024-06-15',
|
||||
description: 'Test entry',
|
||||
source_type: 'manual',
|
||||
lines: [
|
||||
{ account_number: '1930', debit_amount: 1000, credit_amount: 0 },
|
||||
{ account_number: '3001', debit_amount: 0, credit_amount: 1000 },
|
||||
],
|
||||
}
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
||||
method: 'POST',
|
||||
body: input,
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual(entry)
|
||||
expect(mockCreateJournalEntry).toHaveBeenCalledWith('user-1', input)
|
||||
})
|
||||
|
||||
it('returns 400 when engine throws', async () => {
|
||||
mockCreateJournalEntry.mockRejectedValue(new Error('Unbalanced entry'))
|
||||
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
fiscal_period_id: 'period-1',
|
||||
entry_date: '2024-06-15',
|
||||
description: 'Bad entry',
|
||||
source_type: 'manual',
|
||||
lines: [{ account_number: '1930', debit_amount: 1000, credit_amount: 0 }],
|
||||
},
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Unbalanced entry')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
const { sector, slug } = await params
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const extensionId = `${sector}/${slug}`
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const key = searchParams.get('key')
|
||||
|
||||
let query = supabase
|
||||
.from('extension_data')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.eq('extension_id', extensionId)
|
||||
|
||||
const prefix = searchParams.get('prefix')
|
||||
|
||||
if (key) {
|
||||
query = query.eq('key', key)
|
||||
} else if (prefix) {
|
||||
query = query.ilike('key', `${prefix}%`)
|
||||
}
|
||||
|
||||
const { data, error } = await query
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
const { sector, slug } = await params
|
||||
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 { key, value } = body
|
||||
|
||||
if (!key) {
|
||||
return NextResponse.json({ error: 'key is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const extensionId = `${sector}/${slug}`
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('extension_data')
|
||||
.upsert(
|
||||
{
|
||||
user_id: user.id,
|
||||
extension_id: extensionId,
|
||||
key,
|
||||
value,
|
||||
},
|
||||
{ onConflict: 'user_id,extension_id,key' }
|
||||
)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
const { sector, slug } = await params
|
||||
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 key = searchParams.get('key')
|
||||
|
||||
if (!key) {
|
||||
return NextResponse.json({ error: 'key query parameter is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const extensionId = `${sector}/${slug}`
|
||||
|
||||
const { error } = await supabase
|
||||
.from('extension_data')
|
||||
.delete()
|
||||
.eq('user_id', user.id)
|
||||
.eq('extension_id', extensionId)
|
||||
.eq('key', key)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
const { sector, slug } = await params
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const extensionId = `${sector}/${slug}`
|
||||
|
||||
const { data } = await supabase
|
||||
.from('extension_data')
|
||||
.select('value')
|
||||
.eq('user_id', user.id)
|
||||
.eq('extension_id', extensionId)
|
||||
.eq('key', 'settings')
|
||||
.single()
|
||||
|
||||
return NextResponse.json({ data: data?.value ?? {} })
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
const { sector, slug } = await params
|
||||
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 extensionId = `${sector}/${slug}`
|
||||
|
||||
// Get existing settings and merge
|
||||
const { data: existing } = await supabase
|
||||
.from('extension_data')
|
||||
.select('value')
|
||||
.eq('user_id', user.id)
|
||||
.eq('extension_id', extensionId)
|
||||
.eq('key', 'settings')
|
||||
.single()
|
||||
|
||||
const mergedSettings = { ...(existing?.value ?? {}), ...body }
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('extension_data')
|
||||
.upsert(
|
||||
{
|
||||
user_id: user.id,
|
||||
extension_id: extensionId,
|
||||
key: 'settings',
|
||||
value: mergedSettings,
|
||||
},
|
||||
{ onConflict: 'user_id,extension_id,key' }
|
||||
)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: data.value })
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getSettings, saveSettings } from '@/extensions/ai-categorization'
|
||||
import { getSettings, saveSettings } from '@/extensions/general/ai-categorization'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/ai-categorization/settings
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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'
|
||||
import { categorizeTransactions } from '@/extensions/general/ai-categorization'
|
||||
import type { CategorizationSuggestion } from '@/extensions/general/ai-categorization/categorizer'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/ai-categorization/suggestions?transaction_ids=id1,id2,...
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateChatResponse } from '@/extensions/ai-chat/chatbot/chain'
|
||||
import { CHATBOT_CONFIG } from '@/extensions/ai-chat/chatbot/config'
|
||||
import { generateChatResponse } from '@/extensions/general/ai-chat/chatbot/chain'
|
||||
import { CHATBOT_CONFIG } from '@/extensions/general/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 '@/extensions/ai-chat/chatbot/chain'
|
||||
import { CHATBOT_CONFIG } from '@/extensions/ai-chat/chatbot/config'
|
||||
import { streamChatResponse } from '@/extensions/general/ai-chat/chatbot/chain'
|
||||
import { CHATBOT_CONFIG } from '@/extensions/general/ai-chat/chatbot/config'
|
||||
import type { ChatMessage, ChatRequest, SourceReference } from '@/types/chat'
|
||||
|
||||
// Simple in-memory rate limiting (per user)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createSession, getAccountBalance, type AccountInfo } from '@/extensions/enable-banking/lib/api-client'
|
||||
import type { StoredAccount } from '@/extensions/enable-banking/types'
|
||||
import { createSession, getAccountBalance, type AccountInfo } from '@/extensions/general/enable-banking/lib/api-client'
|
||||
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/enable-banking/callback
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { syncAccountTransactions } from '@/extensions/enable-banking/lib/sync'
|
||||
import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/extensions/enable-banking/lib/api-client'
|
||||
import type { StoredAccount } from '@/extensions/enable-banking/types'
|
||||
import { syncAccountTransactions } from '@/extensions/general/enable-banking/lib/sync'
|
||||
import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/extensions/general/enable-banking/lib/api-client'
|
||||
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/enable-banking/sync/cron
|
||||
|
||||
@@ -4,7 +4,7 @@ import { loadExtensions } from '@/lib/extensions/loader'
|
||||
import {
|
||||
sendTaxDeadlineNotifications,
|
||||
sendInvoiceNotifications,
|
||||
} from '@/extensions/push-notifications/notification-scheduler'
|
||||
} from '@/extensions/general/push-notifications/notification-scheduler'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/push-notifications/cron
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getSettings, saveSettings } from '@/extensions/push-notifications'
|
||||
import { getSettings, saveSettings } from '@/extensions/general/push-notifications'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/push-notifications/settings
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getVapidPublicKey } from '@/extensions/push-notifications/notification-sender'
|
||||
import { getVapidPublicKey } from '@/extensions/general/push-notifications/notification-sender'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/push-notifications/subscribe
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user