Fix/chrome pdf preview csp (#572)
* feat: add option to exclude year-end closing entries in SIE export and related reports * delete docs * fix: allow Chrome's PDF viewer in verifikat document preview The /api/documents/:id/inline route shipped with `object-src 'none'` in its CSP, which blocked Chrome's built-in PDF viewer (it renders inline PDFs via an internal <embed>). Users on Chrome saw "Det här innehållet har blockerats" when expanding a PDF attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own viewer) were unaffected, and JPGs worked because <img> isn't subject to object-src. Drops the CSP for this route to the minimum needed for embeddability: `frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the fixed Content-Type from the handler already block MIME confusion; X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(auth): add webmail deep link to email confirmation screens Mirrors Stripe's signup UX: after asking the user to verify their email, detect their webmail provider from the domain and show a button that opens the inbox in a new tab. Gmail gets a from:<sender> search pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly. Unknown / custom domains fall back to the existing copy. Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM (default noreply@gnubok.se) so white-label installs can match their Supabase Auth SMTP config. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(auth): unblock first-time password set for BankID users with MFA Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session is required" whenever a TOTP factor is enrolled. BankID magic-link logins produce AAL1, and middleware skips MFA enforcement for bankid_linked users, so they had no path to AAL2 — leaving them unable to set a backup password or disable MFA without going through the email-recovery escape hatch. - /api/account/password: branch on app_metadata.has_password. First-time set writes via service.auth.admin.updateUserById (no existing credential to protect, AAL2 guard does not apply). Change-password keeps the user-session updateUser so AAL2 still fires for credential rotation. - /mfa/verify: accept a safeReturnTo query param and route there after successful verify, so step-up flows can land back where they came from. - SecuritySettings: detect the AAL2 error from both change-password and mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account instead of toasting a dead-end error. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Add tests and rounding utility for öre precision in bokslut calculations - Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations. - Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries. - Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency. - Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies. - Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios. * fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility * fix: enhance security by rejecting data URIs in safeReturnTo function tests * fix: improve rounding logic in roundOre function and add customer_type migration * fix: add customer_type column to customers and enforce CHECK constraint --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
0087b7be3f
commit
32d9978f1b
@@ -39,6 +39,7 @@ All branding can be set via env vars. Public ones use `NEXT_PUBLIC_BRANDING_*` (
|
||||
| `BRANDING_SUPPORT_EMAIL` | `supportEmail` | `support@gnubok.se` |
|
||||
| `BRANDING_PRIVACY_EMAIL` | `privacyEmail` | `privacy@gnubok.se` |
|
||||
| `BRANDING_SECURITY_EMAIL` | `securityEmail` | `security@arcim.io` |
|
||||
| `NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM` | `authEmailFrom` — From address Supabase Auth sends verification / reset emails from. Used to pre-populate the `from:` query on the "open in Gmail" button after signup. Set to whatever you configured in your Supabase Auth SMTP. | `noreply@gnubok.se` |
|
||||
| `NEXT_PUBLIC_APP_URL` | `appUrl` | `https://app.gnubok.se` |
|
||||
| `NEXT_PUBLIC_BRANDING_LOGO_PATH` | `logoPath` | `/gnubokiceon-removebg-preview.png` |
|
||||
| `NEXT_PUBLIC_BRANDING_FAVICON_PATH` | `faviconPath` | `/favicon.ico` |
|
||||
|
||||
+27
-12
@@ -9,12 +9,13 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, Mail, ArrowLeft, KeyRound } from 'lucide-react'
|
||||
import { Loader2, Mail, ArrowLeft, KeyRound, ExternalLink } from 'lucide-react'
|
||||
import Image from 'next/image'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { isBankIdEnabled } from '@/lib/auth/bankid'
|
||||
import { BankIdAuth } from '@/components/auth/BankIdAuth'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { detectWebmailHint } from '@/lib/auth/webmail-search'
|
||||
|
||||
const branding = getBranding()
|
||||
import type { BankIdResult } from '@/components/auth/BankIdAuth'
|
||||
@@ -249,6 +250,8 @@ function LoginPageContent() {
|
||||
|
||||
// Email sent confirmation screen
|
||||
if (isEmailSent) {
|
||||
const webmailHint = detectWebmailHint(email, branding.authEmailFrom)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-b from-background to-primary/[0.03] p-4">
|
||||
<div className="w-full max-w-sm animate-slide-up space-y-8">
|
||||
@@ -279,17 +282,29 @@ function LoginPageContent() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full text-muted-foreground"
|
||||
onClick={() => {
|
||||
setIsEmailSent(false)
|
||||
setShowResetPassword(false)
|
||||
}}
|
||||
>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
{tCommon('back')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
{webmailHint && (
|
||||
<Button className="w-full" asChild>
|
||||
<a href={webmailHint.url} target="_blank" rel="noopener noreferrer">
|
||||
{tAuth(webmailHint.hasSearch ? 'open_webmail_search' : 'open_webmail_inbox', {
|
||||
provider: webmailHint.name,
|
||||
})}
|
||||
<ExternalLink className="ml-2 h-4 w-4" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full text-muted-foreground"
|
||||
onClick={() => {
|
||||
setIsEmailSent(false)
|
||||
setShowResetPassword(false)
|
||||
}}
|
||||
>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
{tCommon('back')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useState, useEffect, useRef, Suspense } from 'react'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -10,8 +10,17 @@ import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, ShieldCheck, LogOut } from 'lucide-react'
|
||||
import { SupportLink } from '@/components/ui/support-link'
|
||||
import { safeReturnTo } from '@/lib/auth/safe-return-to'
|
||||
|
||||
export default function MfaVerifyPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<MfaVerifyContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
function MfaVerifyContent() {
|
||||
const t = useTranslations('mfa')
|
||||
const tCommon = useTranslations('common')
|
||||
const [code, setCode] = useState('')
|
||||
@@ -23,8 +32,15 @@ export default function MfaVerifyPage() {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const { toast } = useToast()
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const supabase = createClient()
|
||||
|
||||
// Step-up landing target. Set by callers that need AAL2 to do something
|
||||
// sensitive (set/change password, unenroll MFA, etc.) — /api/account/password
|
||||
// and SecuritySettings redirect here when GoTrue rejects with "AAL2 session
|
||||
// is required". Falls back to the dashboard for direct visits.
|
||||
const returnTo = safeReturnTo(searchParams.get('returnTo'), '/')
|
||||
|
||||
useEffect(() => {
|
||||
async function loadFactor() {
|
||||
const { data } = await supabase.auth.mfa.listFactors()
|
||||
@@ -122,7 +138,7 @@ export default function MfaVerifyPage() {
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
}
|
||||
|
||||
router.push('/')
|
||||
router.push(returnTo)
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast({
|
||||
|
||||
@@ -9,13 +9,14 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, Mail, ArrowLeft } from 'lucide-react'
|
||||
import { Loader2, Mail, ArrowLeft, ExternalLink } from 'lucide-react'
|
||||
import Image from 'next/image'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { isBankIdEnabled } from '@/lib/auth/bankid'
|
||||
import { BankIdAuth } from '@/components/auth/BankIdAuth'
|
||||
import type { BankIdResult } from '@/components/auth/BankIdAuth'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { detectWebmailHint } from '@/lib/auth/webmail-search'
|
||||
|
||||
const branding = getBranding()
|
||||
|
||||
@@ -355,6 +356,8 @@ function RegisterPageContent() {
|
||||
}
|
||||
|
||||
if (isRegistered) {
|
||||
const webmailHint = detectWebmailHint(email, branding.authEmailFrom)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-b from-background to-primary/[0.03] p-4">
|
||||
<div className="w-full max-w-sm animate-slide-up space-y-8">
|
||||
@@ -380,12 +383,24 @@ function RegisterPageContent() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button variant="ghost" className="w-full text-muted-foreground" asChild>
|
||||
<Link href="/login">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
{t('back_to_login')}
|
||||
</Link>
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
{webmailHint && (
|
||||
<Button className="w-full" asChild>
|
||||
<a href={webmailHint.url} target="_blank" rel="noopener noreferrer">
|
||||
{t(webmailHint.hasSearch ? 'open_webmail_search' : 'open_webmail_inbox', {
|
||||
provider: webmailHint.name,
|
||||
})}
|
||||
<ExternalLink className="ml-2 h-4 w-4" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" className="w-full text-muted-foreground" asChild>
|
||||
<Link href="/login">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
{t('back_to_login')}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
'use client'
|
||||
|
||||
import { use, useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { ArrowLeft, Loader2, Lock } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
assessJamkningEligibility,
|
||||
computeJamkningAmount,
|
||||
} from '@/lib/bokslut/assets/jamkning'
|
||||
import type { Asset, FiscalPeriod, VatTreatment } from '@/types'
|
||||
|
||||
interface PeriodOption {
|
||||
id: string
|
||||
name: string
|
||||
period_start: string
|
||||
period_end: string
|
||||
is_closed: boolean
|
||||
locked_at: string | null
|
||||
}
|
||||
|
||||
const VAT_TREATMENT_OPTIONS: { value: VatTreatment; label: string; rate: number | null }[] = [
|
||||
{ value: 'standard_25', label: 'Standard 25 %', rate: 0.25 },
|
||||
{ value: 'reduced_12', label: 'Reducerad 12 %', rate: 0.12 },
|
||||
{ value: 'reduced_6', label: 'Reducerad 6 %', rate: 0.06 },
|
||||
{ value: 'reverse_charge', label: 'Omvänd skattskyldighet', rate: null },
|
||||
{ value: 'export', label: 'Export (utanför EU)', rate: null },
|
||||
{ value: 'exempt', label: 'Momsfri', rate: null },
|
||||
]
|
||||
|
||||
function round2(n: number): number {
|
||||
return Math.round(n * 100) / 100
|
||||
}
|
||||
|
||||
export default function DisposeAssetPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = use(params)
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
|
||||
const [asset, setAsset] = useState<Asset | null>(null)
|
||||
const [periods, setPeriods] = useState<PeriodOption[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
// Form state
|
||||
const [disposalDate, setDisposalDate] = useState<string>(() => new Date().toISOString().slice(0, 10))
|
||||
const [proceeds, setProceeds] = useState<string>('')
|
||||
const [vatTreatment, setVatTreatment] = useState<VatTreatment>('standard_25')
|
||||
const [vatAmount, setVatAmount] = useState<string>('')
|
||||
const [vatAutoCalc, setVatAutoCalc] = useState(true)
|
||||
const [periodId, setPeriodId] = useState<string>('')
|
||||
const [proceedsAccount, setProceedsAccount] = useState<string>('1930')
|
||||
|
||||
// Jämkning state
|
||||
const [jamkningEnabled, setJamkningEnabled] = useState(false)
|
||||
const [originalInputVat, setOriginalInputVat] = useState<string>('')
|
||||
|
||||
// Load asset + periods
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
Promise.all([
|
||||
fetch(`/api/assets`).then((r) => r.json()),
|
||||
fetch('/api/bookkeeping/fiscal-periods').then((r) => r.json()),
|
||||
])
|
||||
.then(([assetsRes, periodsRes]) => {
|
||||
if (cancelled) return
|
||||
const assets: Asset[] = assetsRes.data ?? []
|
||||
const found = assets.find((a) => a.id === id) ?? null
|
||||
setAsset(found)
|
||||
const periodList: PeriodOption[] = (periodsRes.data ?? []).map((p: FiscalPeriod) => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
period_start: p.period_start,
|
||||
period_end: p.period_end,
|
||||
is_closed: p.is_closed,
|
||||
locked_at: p.locked_at,
|
||||
}))
|
||||
setPeriods(periodList)
|
||||
setLoading(false)
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
toast({
|
||||
title: 'Kunde inte ladda',
|
||||
description: 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
setLoading(false)
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [id, toast])
|
||||
|
||||
// Auto-select matching fiscal period when disposalDate changes.
|
||||
useEffect(() => {
|
||||
if (!disposalDate || periods.length === 0) return
|
||||
const match = periods.find(
|
||||
(p) => disposalDate >= p.period_start && disposalDate <= p.period_end,
|
||||
)
|
||||
if (match && match.id !== periodId) setPeriodId(match.id)
|
||||
}, [disposalDate, periods, periodId])
|
||||
|
||||
// Derived: VAT rate from treatment
|
||||
const selectedVatOpt = VAT_TREATMENT_OPTIONS.find((o) => o.value === vatTreatment)
|
||||
const proceedsNum = Number(proceeds) || 0
|
||||
const computedVat = useMemo(() => {
|
||||
if (!selectedVatOpt || selectedVatOpt.rate === null) return 0
|
||||
// Standard convention: proceeds is GROSS (incl VAT).
|
||||
// vat = gross × rate / (1 + rate)
|
||||
return round2((proceedsNum * selectedVatOpt.rate) / (1 + selectedVatOpt.rate))
|
||||
}, [proceedsNum, selectedVatOpt])
|
||||
|
||||
// Auto-fill VAT amount when auto-calc is on.
|
||||
useEffect(() => {
|
||||
if (vatAutoCalc) {
|
||||
if (selectedVatOpt && selectedVatOpt.rate !== null) {
|
||||
setVatAmount(String(computedVat))
|
||||
} else {
|
||||
setVatAmount('0')
|
||||
}
|
||||
}
|
||||
}, [computedVat, selectedVatOpt, vatAutoCalc])
|
||||
|
||||
// Jämkning eligibility — derived from asset + disposal date.
|
||||
const eligibility = useMemo(() => {
|
||||
if (!asset) return null
|
||||
return assessJamkningEligibility({
|
||||
basAssetAccount: asset.bas_asset_account,
|
||||
basExpenseAccount: asset.bas_expense_account,
|
||||
category: asset.category,
|
||||
acquisitionDate: asset.acquisition_date,
|
||||
disposalDate,
|
||||
})
|
||||
}, [asset, disposalDate])
|
||||
|
||||
// Auto-enable jämkning toggle when disposal falls within the correction period.
|
||||
useEffect(() => {
|
||||
if (eligibility?.withinCorrectionPeriod && !jamkningEnabled) {
|
||||
setJamkningEnabled(true)
|
||||
}
|
||||
}, [eligibility?.withinCorrectionPeriod, jamkningEnabled])
|
||||
|
||||
const originalInputVatNum = Number(originalInputVat) || 0
|
||||
const jamkningAmount = useMemo(() => {
|
||||
if (!jamkningEnabled || !eligibility) return 0
|
||||
return computeJamkningAmount({
|
||||
originalInputVat: originalInputVatNum,
|
||||
totalCorrectionMonths: eligibility.totalCorrectionMonths,
|
||||
remainingMonths: eligibility.remainingMonths,
|
||||
disposalEvent: 'triggers_jamkning',
|
||||
})
|
||||
}, [jamkningEnabled, eligibility, originalInputVatNum])
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
if (!asset || !periodId) return
|
||||
setSubmitting(true)
|
||||
const vatNum = Number(vatAmount) || 0
|
||||
const body: Record<string, unknown> = {
|
||||
disposed_at: disposalDate,
|
||||
disposed_proceeds: proceedsNum,
|
||||
fiscal_period_id: periodId,
|
||||
proceeds_account: proceedsAccount,
|
||||
}
|
||||
if (vatNum > 0) {
|
||||
body.proceeds_vat = vatNum
|
||||
body.vat_treatment = vatTreatment
|
||||
}
|
||||
if (jamkningEnabled && jamkningAmount > 0 && eligibility) {
|
||||
body.jamkning_amount = jamkningAmount
|
||||
body.jamkning_remaining_months = eligibility.remainingMonths
|
||||
body.jamkning_total_months = eligibility.totalCorrectionMonths
|
||||
body.jamkning_original_input_vat = originalInputVatNum
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/assets/${id}/dispose`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const json = await res.json()
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: 'Avyttring misslyckades',
|
||||
description: getErrorMessage(json?.error ?? json) || 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: 'Tillgång avyttrad',
|
||||
description: 'Verifikat skapat.',
|
||||
})
|
||||
router.push('/assets')
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Avyttring misslyckades',
|
||||
description: getErrorMessage(err),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}, [
|
||||
asset,
|
||||
disposalDate,
|
||||
eligibility,
|
||||
id,
|
||||
jamkningAmount,
|
||||
jamkningEnabled,
|
||||
originalInputVatNum,
|
||||
periodId,
|
||||
proceedsAccount,
|
||||
proceedsNum,
|
||||
router,
|
||||
toast,
|
||||
vatAmount,
|
||||
vatTreatment,
|
||||
])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader title="Avyttra tillgång" />
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-3">
|
||||
<Skeleton className="h-6 w-1/3" />
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!asset) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader title="Avyttra tillgång" />
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<p>Tillgången kunde inte hittas.</p>
|
||||
<div className="mt-4">
|
||||
<Link href="/assets">
|
||||
<Button variant="secondary">
|
||||
<ArrowLeft className="mr-1 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (asset.disposed_at) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader title="Avyttra tillgång" />
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<p className="mb-4">
|
||||
Tillgången är redan avyttrad ({formatDate(asset.disposed_at)}).
|
||||
</p>
|
||||
<Link href="/assets">
|
||||
<Button variant="secondary">
|
||||
<ArrowLeft className="mr-1 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const netProceeds = round2(proceedsNum - (Number(vatAmount) || 0))
|
||||
const isVatLineTreatment = selectedVatOpt?.rate !== null
|
||||
const selectedPeriod = periods.find((p) => p.id === periodId)
|
||||
const periodLocked = selectedPeriod
|
||||
? selectedPeriod.is_closed || selectedPeriod.locked_at !== null
|
||||
: false
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Avyttra tillgång"
|
||||
action={
|
||||
<Link href="/assets">
|
||||
<Button variant="secondary">
|
||||
<ArrowLeft className="mr-1 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{asset.name}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6 pt-0 space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Anskaffningsvärde</span>
|
||||
<span className="tabular-nums">{formatCurrency(Number(asset.acquisition_cost))}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Anskaffat</span>
|
||||
<span className="tabular-nums">{formatDate(asset.acquisition_date)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Konton (BAS)</span>
|
||||
<span className="tabular-nums">
|
||||
{asset.bas_asset_account} / {asset.bas_accumulated_account} / {asset.bas_expense_account}
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Avyttringsuppgifter</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6 pt-0 space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="disposalDate">Avyttringsdatum</Label>
|
||||
<Input
|
||||
id="disposalDate"
|
||||
type="date"
|
||||
value={disposalDate}
|
||||
onChange={(e) => setDisposalDate(e.target.value)}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="period">Räkenskapsperiod</Label>
|
||||
<Select value={periodId} onValueChange={setPeriodId}>
|
||||
<SelectTrigger id="period">
|
||||
<SelectValue placeholder="Välj period" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{periods.map((p) => {
|
||||
const locked = p.is_closed || p.locked_at !== null
|
||||
return (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
{locked ? ' (låst)' : ''}
|
||||
</SelectItem>
|
||||
)
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{periodLocked && (
|
||||
<p className="text-xs text-destructive">
|
||||
Vald period är låst eller stängd — välj en öppen period.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="proceeds">Erhållet belopp (inkl. moms)</Label>
|
||||
<Input
|
||||
id="proceeds"
|
||||
inputMode="decimal"
|
||||
value={proceeds}
|
||||
onChange={(e) => setProceeds(e.target.value)}
|
||||
placeholder="0,00"
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="proceedsAccount">Mottagarkonto</Label>
|
||||
<Input
|
||||
id="proceedsAccount"
|
||||
value={proceedsAccount}
|
||||
onChange={(e) => setProceedsAccount(e.target.value)}
|
||||
placeholder="1930"
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Moms vid avyttring (ML 3 kap 3 §)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6 pt-0 space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="vatTreatment">Momsbehandling</Label>
|
||||
<Select
|
||||
value={vatTreatment}
|
||||
onValueChange={(v) => setVatTreatment(v as VatTreatment)}
|
||||
>
|
||||
<SelectTrigger id="vatTreatment">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{VAT_TREATMENT_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="vatAmount">Utgående moms</Label>
|
||||
<Input
|
||||
id="vatAmount"
|
||||
inputMode="decimal"
|
||||
value={vatAmount}
|
||||
onChange={(e) => {
|
||||
setVatAutoCalc(false)
|
||||
setVatAmount(e.target.value)
|
||||
}}
|
||||
placeholder="0,00"
|
||||
disabled={!isVatLineTreatment}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
{isVatLineTreatment && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Switch
|
||||
checked={vatAutoCalc}
|
||||
onCheckedChange={setVatAutoCalc}
|
||||
aria-label="Räkna ut moms automatiskt"
|
||||
/>
|
||||
<span>Räkna ut moms automatiskt</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md bg-secondary/40 p-3 text-xs space-y-1">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Brutto</span>
|
||||
<span className="tabular-nums">{formatCurrency(proceedsNum)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Moms</span>
|
||||
<span className="tabular-nums">{formatCurrency(Number(vatAmount) || 0)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between font-medium">
|
||||
<span>Netto</span>
|
||||
<span className="tabular-nums">{formatCurrency(netProceeds)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Jämkning av ingående moms (ML 8a kap)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6 pt-0 space-y-4">
|
||||
{eligibility?.withinCorrectionPeriod ? (
|
||||
<Badge variant="warning">
|
||||
Inom korrigeringstid ({eligibility.remainingMonths} mån kvar av{' '}
|
||||
{eligibility.totalCorrectionMonths})
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">Utanför korrigeringstid — ingen jämkning behövs</Badge>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
id="jamkningEnabled"
|
||||
checked={jamkningEnabled}
|
||||
onCheckedChange={setJamkningEnabled}
|
||||
disabled={!eligibility?.withinCorrectionPeriod}
|
||||
/>
|
||||
<Label htmlFor="jamkningEnabled" className="cursor-pointer">
|
||||
Bokför jämkning
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{jamkningEnabled && eligibility?.withinCorrectionPeriod && (
|
||||
<div className="space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="originalInputVat">Ursprungligt ingående momsavdrag</Label>
|
||||
<Input
|
||||
id="originalInputVat"
|
||||
inputMode="decimal"
|
||||
value={originalInputVat}
|
||||
onChange={(e) => setOriginalInputVat(e.target.value)}
|
||||
placeholder="0,00"
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Korrigeringstid</Label>
|
||||
<div className="rounded-md border border-border bg-secondary/40 px-3 py-2 text-sm tabular-nums">
|
||||
{eligibility.totalCorrectionMonths} mån
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Återstående månader</Label>
|
||||
<div className="rounded-md border border-border bg-secondary/40 px-3 py-2 text-sm tabular-nums">
|
||||
{eligibility.remainingMonths} mån
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Beräknad jämkning</Label>
|
||||
<div className="rounded-md border border-border bg-secondary/40 px-3 py-2 text-sm tabular-nums font-medium">
|
||||
{formatCurrency(jamkningAmount)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Jämkningen bokförs som kredit på 2641 (återförd ingående moms) och debet på
|
||||
förlustkontot för tillgångsklassen.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Link href="/assets">
|
||||
<Button variant="secondary" disabled={submitting}>
|
||||
Avbryt
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={
|
||||
!canWrite ||
|
||||
submitting ||
|
||||
!periodId ||
|
||||
periodLocked ||
|
||||
proceedsNum < 0 ||
|
||||
(proceeds !== '' && Number.isNaN(proceedsNum))
|
||||
}
|
||||
title={!canWrite ? 'Endast användare med skrivrättigheter kan avyttra tillgångar.' : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-1 h-4 w-4" />}
|
||||
{submitting && <Loader2 className="mr-1 h-4 w-4 animate-spin" />}
|
||||
Avyttra
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
@@ -116,6 +117,7 @@ export default function AssetsPage() {
|
||||
<TableHead className="text-right">{t('th_acquisition_cost')}</TableHead>
|
||||
<TableHead>{t('th_useful_life')}</TableHead>
|
||||
<TableHead>{t('th_status')}</TableHead>
|
||||
<TableHead className="text-right">{t('th_actions')}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -136,11 +138,25 @@ export default function AssetsPage() {
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{asset.disposed_at ? (
|
||||
<Badge variant="secondary">{t('status_disposed')}</Badge>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Badge variant="secondary">{t('status_disposed')}</Badge>
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
{formatDate(asset.disposed_at)}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<Badge variant="success">{t('status_active')}</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{!asset.disposed_at && (
|
||||
<Link href={`/assets/${asset.id}/dispose`}>
|
||||
<Button variant="ghost" size="sm">
|
||||
{t('action_dispose')}
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Textarea } from '@/components/ui/textarea'
|
||||
import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock, MessageSquare, Pencil, Check, X, Copy } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
|
||||
import JournalEntryStatusBadge, { useSourceTypeLabels } from '@/components/bookkeeping/JournalEntryStatusBadge'
|
||||
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
|
||||
@@ -92,7 +93,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
const posted = result.data
|
||||
toast({
|
||||
title: t('toast_posted_title'),
|
||||
description: t('toast_posted_description', { voucher: `${posted?.voucher_series ?? ''}${posted?.voucher_number ?? ''}` }),
|
||||
description: t('toast_posted_description', { voucher: formatVoucher(posted ?? {}) }),
|
||||
})
|
||||
await fetchData()
|
||||
} else {
|
||||
@@ -116,7 +117,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
title: wasDraft ? t('toast_delete_draft_title') : t('toast_delete_entry_title'),
|
||||
description: wasDraft
|
||||
? t('toast_delete_draft_description')
|
||||
: t('toast_delete_entry_description', { voucher: `${result.data?.voucher_series ?? ''}${result.data?.voucher_number ?? ''}` }),
|
||||
: t('toast_delete_entry_description', { voucher: formatVoucher(result.data ?? {}) }),
|
||||
})
|
||||
router.push('/bookkeeping')
|
||||
} else {
|
||||
@@ -201,7 +202,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight font-mono">
|
||||
{entry.voucher_series}{entry.voucher_number}
|
||||
{formatVoucher(entry)}
|
||||
</h1>
|
||||
<JournalEntryStatusBadge entry={entry} />
|
||||
</div>
|
||||
@@ -290,7 +291,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t('field_source_voucher')}</span>
|
||||
<span className="font-mono tabular-nums">
|
||||
{entry.source_voucher_series}{entry.source_voucher_number}
|
||||
{formatVoucher({ voucher_series: entry.source_voucher_series, voucher_number: entry.source_voucher_number })}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -587,7 +588,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
warningText={
|
||||
entry?.status === 'draft'
|
||||
? t('delete_warning_draft')
|
||||
: t('delete_warning_entry', { voucher: `${entry?.voucher_series ?? ''}${entry?.voucher_number ?? ''}` })
|
||||
: t('delete_warning_entry', { voucher: entry ? formatVoucher(entry) : '' })
|
||||
}
|
||||
confirmLabel={t('delete_confirm_label')}
|
||||
>
|
||||
|
||||
@@ -13,6 +13,7 @@ import { FiscalYearSelector } from '@/components/common/FiscalYearSelector'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Lock, Loader2, Copy } from 'lucide-react'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import type { JournalEntry, JournalEntryLine } from '@/types'
|
||||
|
||||
interface CopyPrefill {
|
||||
@@ -87,7 +88,7 @@ export default function BookkeepingPage() {
|
||||
})
|
||||
setCopyPrefill({
|
||||
sourceId: copyFromId,
|
||||
sourceVoucherLabel: `${data.voucher_series ?? ''}${data.voucher_number ?? ''}`,
|
||||
sourceVoucherLabel: formatVoucher(data),
|
||||
lines,
|
||||
description: data.description || '',
|
||||
notes: data.notes || '',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -13,10 +13,12 @@ import { Textarea } from '@/components/ui/textarea'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { ArrowLeft, FileDown, Plus, ExternalLink, Loader2, Save, CheckCircle2 } from 'lucide-react'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { FiscalYearSelector } from '@/components/common/FiscalYearSelector'
|
||||
import type { ArsredovisningData } from '@/lib/bokslut/arsredovisning/types'
|
||||
import type { SignatureRequest } from '@/lib/bokslut/arsredovisning/signature-service'
|
||||
|
||||
export default function ArsredovisningPage() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const periodId = searchParams.get('period')
|
||||
const { toast } = useToast()
|
||||
@@ -205,14 +207,33 @@ export default function ArsredovisningPage() {
|
||||
if (!periodId) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader title="Årsredovisning" />
|
||||
<PageHeader
|
||||
title="Årsredovisning"
|
||||
description="Förhandsgranska och ladda ner årsredovisningen för valt räkenskapsår."
|
||||
/>
|
||||
<Card>
|
||||
<CardContent className="p-6 text-muted-foreground">
|
||||
Saknar periodparameter. Öppna sidan från bokslutet via{' '}
|
||||
<Link href="/bookkeeping/year-end" className="text-primary hover:underline">
|
||||
/bookkeeping/year-end
|
||||
</Link>
|
||||
.
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Välj räkenskapsår</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Välj det räkenskapsår du vill se årsredovisningen för. Du kan
|
||||
förhandsgranska och ladda ner PDF-utkastet utan att stänga året — det
|
||||
fullständiga bokslutet görs sedan via{' '}
|
||||
<Link href="/bookkeeping/year-end" className="text-foreground underline underline-offset-4 decoration-muted-foreground/40 hover:decoration-foreground">
|
||||
Bokslut
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<FiscalYearSelector
|
||||
value={null}
|
||||
onChange={(id) => {
|
||||
if (id) router.replace(`/bookkeeping/year-end/arsredovisning?period=${id}`)
|
||||
}}
|
||||
includeAllOption={false}
|
||||
hideFuturePeriods
|
||||
label={null}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -254,7 +275,11 @@ export default function ArsredovisningPage() {
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title={`Årsredovisning ${data.fiscal_period.name}`}
|
||||
description={`${data.company.name} · ${data.company.org_number}`}
|
||||
description={
|
||||
data.company.org_number
|
||||
? `${data.company.name} · ${data.company.org_number}`
|
||||
: data.company.name
|
||||
}
|
||||
action={
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={`/bookkeeping/year-end?period=${periodId}`}>
|
||||
@@ -264,12 +289,25 @@ export default function ArsredovisningPage() {
|
||||
}
|
||||
/>
|
||||
|
||||
{data.accounting_framework === 'k3' && (
|
||||
<Card>
|
||||
<CardContent className="p-4 text-sm">
|
||||
<p className="font-medium">Årsredovisning enligt K3 (BFNAR 2012:1)</p>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Dokumentet innehåller kassaflödesanalys, förändring av eget kapital och
|
||||
utökade noter (uppskjuten skatt, redovisningsprinciper, materiella
|
||||
anläggningstillgångar) — krav som följer K3 men inte K2.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Förvaltningsberättelse — narrativ</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Texten nedan visas i PDF:en. Förändringar är lokala till denna sida tills
|
||||
vidare; en framtida version kommer att spara dem mellan sessioner.
|
||||
Texten nedan visas i PDF:en. Klicka på <strong>Spara texten</strong> nedan
|
||||
för att behålla ändringarna mellan sessioner.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
|
||||
@@ -0,0 +1,997 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { ArrowLeft, ArrowRight, Loader2, Lock, Plus, Trash2 } from 'lucide-react'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import {
|
||||
PERIODISERING_TEMPLATES,
|
||||
type PeriodiseringTemplate,
|
||||
} from '@/lib/bokslut/accruals/templates'
|
||||
import type { AccrualsProposal } from '@/lib/bokslut/accruals/types'
|
||||
import type {
|
||||
PeriodiseringSuggestion,
|
||||
PeriodiseringConfidence,
|
||||
} from '@/lib/bokslut/accruals/auto-detect'
|
||||
import type { FiscalPeriod } from '@/types'
|
||||
|
||||
type Step = 'vacation' | 'audit' | 'auto' | 'manual' | 'review'
|
||||
|
||||
const STEP_ORDER: Step[] = ['vacation', 'audit', 'auto', 'manual', 'review']
|
||||
const STEP_LABELS: Record<Step, string> = {
|
||||
vacation: 'Semester',
|
||||
audit: 'Revisionsarvode',
|
||||
auto: 'Auto-detektering',
|
||||
manual: 'Manuella tillägg',
|
||||
review: 'Granska & posta',
|
||||
}
|
||||
|
||||
interface PeriodOption {
|
||||
id: string
|
||||
name: string
|
||||
period_start: string
|
||||
period_end: string
|
||||
}
|
||||
|
||||
type ProposalResponse = AccrualsProposal & { autoDetected: PeriodiseringSuggestion[] }
|
||||
|
||||
interface AuditState {
|
||||
enabled: boolean
|
||||
amount: string
|
||||
liabilityAccount: '2991' | '2992'
|
||||
}
|
||||
|
||||
interface AutoState {
|
||||
/** key = source_invoice_id + '|' + source_type, value = accepted */
|
||||
selections: Record<string, boolean>
|
||||
}
|
||||
|
||||
interface ManualEntry {
|
||||
id: string
|
||||
templateKind: PeriodiseringTemplate['kind']
|
||||
amount: string
|
||||
description: string
|
||||
/** Editable accounts (pre-filled from template). */
|
||||
primaryAccount: string
|
||||
secondaryAccount: string
|
||||
}
|
||||
|
||||
function uid() {
|
||||
return Math.random().toString(36).slice(2, 10)
|
||||
}
|
||||
|
||||
function suggestionKey(s: PeriodiseringSuggestion): string {
|
||||
return `${s.source_invoice_id}|${s.source_type}`
|
||||
}
|
||||
|
||||
function confidenceVariant(c: PeriodiseringConfidence): 'success' | 'secondary' | 'outline' {
|
||||
if (c === 'high') return 'success'
|
||||
if (c === 'medium') return 'secondary'
|
||||
return 'outline'
|
||||
}
|
||||
|
||||
function confidenceLabel(c: PeriodiseringConfidence): string {
|
||||
if (c === 'high') return 'Hög säkerhet'
|
||||
if (c === 'medium') return 'Medel säkerhet'
|
||||
return 'Låg säkerhet'
|
||||
}
|
||||
|
||||
export default function PeriodiseringWizardPage() {
|
||||
const searchParams = useSearchParams()
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
|
||||
const [periods, setPeriods] = useState<PeriodOption[] | null>(null)
|
||||
const [periodsError, setPeriodsError] = useState<string | null>(null)
|
||||
const [selectedPeriodId, setSelectedPeriodId] = useState<string | null>(
|
||||
searchParams.get('period') ?? null,
|
||||
)
|
||||
|
||||
const [step, setStep] = useState<Step>('vacation')
|
||||
const [proposal, setProposal] = useState<ProposalResponse | null>(null)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const [vacationAccepted, setVacationAccepted] = useState(true)
|
||||
const [auditState, setAuditState] = useState<AuditState>({
|
||||
enabled: false,
|
||||
amount: '',
|
||||
liabilityAccount: '2992',
|
||||
})
|
||||
const [autoState, setAutoState] = useState<AutoState>({ selections: {} })
|
||||
const [manualEntries, setManualEntries] = useState<ManualEntry[]>([])
|
||||
|
||||
const [posting, setPosting] = useState(false)
|
||||
const [postError, setPostError] = useState<string | null>(null)
|
||||
const [postSummary, setPostSummary] = useState<{ created: number; skipped: number } | null>(null)
|
||||
|
||||
// ---- Load eligible periods ----
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const load = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/fiscal-periods')
|
||||
if (!res.ok) {
|
||||
if (!cancelled) setPeriodsError('Kunde inte hämta perioder')
|
||||
return
|
||||
}
|
||||
const { data } = (await res.json()) as { data: FiscalPeriod[] }
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
const eligible = (data ?? []).filter(
|
||||
(p) => !p.is_closed && !p.closing_entry_id && p.period_end <= today,
|
||||
)
|
||||
eligible.sort((a, b) => a.period_start.localeCompare(b.period_start))
|
||||
if (cancelled) return
|
||||
setPeriods(eligible)
|
||||
if (!selectedPeriodId && eligible.length > 0) {
|
||||
setSelectedPeriodId(eligible[0].id)
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setPeriodsError('Kunde inte hämta perioder')
|
||||
}
|
||||
}
|
||||
void load()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [selectedPeriodId])
|
||||
|
||||
// ---- Fetch accruals snapshot once period chosen ----
|
||||
useEffect(() => {
|
||||
if (!selectedPeriodId) return
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
setLoadError(null)
|
||||
setProposal(null)
|
||||
fetch(`/api/bookkeeping/fiscal-periods/${selectedPeriodId}/accruals`)
|
||||
.then(async (res) => {
|
||||
const body = await res.json()
|
||||
if (cancelled) return
|
||||
if (!res.ok) {
|
||||
setLoadError(body?.error?.message ?? 'Kunde inte ladda periodiseringar')
|
||||
return
|
||||
}
|
||||
const data = body.data as ProposalResponse
|
||||
setProposal(data)
|
||||
// Default-check all high-confidence suggestions.
|
||||
const initial: Record<string, boolean> = {}
|
||||
for (const s of data.autoDetected ?? []) {
|
||||
initial[suggestionKey(s)] = s.confidence === 'high'
|
||||
}
|
||||
setAutoState({ selections: initial })
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoadError('Kunde inte ladda periodiseringar')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [selectedPeriodId])
|
||||
|
||||
const vacationProposal = useMemo(
|
||||
() => proposal?.proposals.find((p) => p.kind === 'vacation_liability_change') ?? null,
|
||||
[proposal],
|
||||
)
|
||||
|
||||
const currentStepIndex = STEP_ORDER.indexOf(step)
|
||||
const progressValue = ((currentStepIndex + 1) / STEP_ORDER.length) * 100
|
||||
const showWizard = selectedPeriodId !== null && (periods?.length ?? 0) > 0 && !loading && !loadError
|
||||
|
||||
// ---- Manual entry editing helpers ----
|
||||
const addManualFromTemplate = useCallback((template: PeriodiseringTemplate) => {
|
||||
const primary =
|
||||
template.prepaid_account ?? template.deferred_account ?? template.accrued_account ?? ''
|
||||
const secondary =
|
||||
template.expense_account ?? template.revenue_account ?? ''
|
||||
setManualEntries((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: uid(),
|
||||
templateKind: template.kind,
|
||||
amount: '',
|
||||
description: '',
|
||||
primaryAccount: primary,
|
||||
secondaryAccount: secondary,
|
||||
},
|
||||
])
|
||||
}, [])
|
||||
|
||||
const updateManual = useCallback((id: string, patch: Partial<ManualEntry>) => {
|
||||
setManualEntries((prev) => prev.map((m) => (m.id === id ? { ...m, ...patch } : m)))
|
||||
}, [])
|
||||
|
||||
const removeManual = useCallback((id: string) => {
|
||||
setManualEntries((prev) => prev.filter((m) => m.id !== id))
|
||||
}, [])
|
||||
|
||||
// ---- Final post ----
|
||||
const handlePost = useCallback(async () => {
|
||||
if (!selectedPeriodId) return
|
||||
setPosting(true)
|
||||
setPostError(null)
|
||||
try {
|
||||
const items: unknown[] = []
|
||||
if (vacationProposal && vacationAccepted) {
|
||||
items.push({ kind: 'vacation_liability_change' })
|
||||
}
|
||||
if (auditState.enabled) {
|
||||
const amount = parseFloat(auditState.amount)
|
||||
if (Number.isFinite(amount) && amount > 0) {
|
||||
items.push({
|
||||
kind: 'audit_fee',
|
||||
amount,
|
||||
liability_account: auditState.liabilityAccount,
|
||||
})
|
||||
}
|
||||
}
|
||||
for (const s of proposal?.autoDetected ?? []) {
|
||||
if (!autoState.selections[suggestionKey(s)]) continue
|
||||
if (s.source_type === 'supplier_invoice') {
|
||||
items.push({
|
||||
kind: 'manual_prepaid_expense',
|
||||
amount: s.periodisering_amount,
|
||||
expense_account: '5800', // safe fallback; user can override in manual list
|
||||
prepaid_account: s.suggested_prepaid_account ?? '1710',
|
||||
description: s.source_label,
|
||||
})
|
||||
} else {
|
||||
items.push({
|
||||
kind: 'deferred_revenue',
|
||||
amount: s.periodisering_amount,
|
||||
revenue_account: '3001',
|
||||
deferred_account: s.suggested_deferred_account ?? '2970',
|
||||
description: s.source_label,
|
||||
})
|
||||
}
|
||||
}
|
||||
for (const m of manualEntries) {
|
||||
const amount = parseFloat(m.amount)
|
||||
if (!Number.isFinite(amount) || amount <= 0) continue
|
||||
if (!m.description.trim()) continue
|
||||
const tpl = PERIODISERING_TEMPLATES.find((t) => t.kind === m.templateKind)
|
||||
if (!tpl) continue
|
||||
switch (tpl.side) {
|
||||
case 'prepaid':
|
||||
items.push({
|
||||
kind: 'manual_prepaid_expense',
|
||||
amount,
|
||||
expense_account: m.secondaryAccount,
|
||||
prepaid_account: m.primaryAccount,
|
||||
description: m.description,
|
||||
})
|
||||
break
|
||||
case 'accrued':
|
||||
items.push({
|
||||
kind: 'manual_accrued_expense',
|
||||
amount,
|
||||
expense_account: m.secondaryAccount,
|
||||
accrued_account: m.primaryAccount,
|
||||
description: m.description,
|
||||
})
|
||||
break
|
||||
case 'deferred_revenue':
|
||||
items.push({
|
||||
kind: 'deferred_revenue',
|
||||
amount,
|
||||
revenue_account: m.secondaryAccount,
|
||||
deferred_account: m.primaryAccount,
|
||||
description: m.description,
|
||||
})
|
||||
break
|
||||
case 'accrued_interest':
|
||||
items.push({
|
||||
kind: 'accrued_interest',
|
||||
amount,
|
||||
expense_account: m.secondaryAccount,
|
||||
accrued_account: m.primaryAccount,
|
||||
description: m.description,
|
||||
})
|
||||
break
|
||||
case 'accrued_utility':
|
||||
items.push({
|
||||
kind: 'accrued_utility',
|
||||
amount,
|
||||
expense_account: m.secondaryAccount,
|
||||
accrued_account: m.primaryAccount,
|
||||
description: m.description,
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
toast({
|
||||
title: 'Inga periodiseringar att bokföra',
|
||||
description: 'Markera minst en post innan du postar.',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/bookkeeping/fiscal-periods/${selectedPeriodId}/accruals`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ items }),
|
||||
})
|
||||
const body = await res.json()
|
||||
if (!res.ok) {
|
||||
setPostError(body?.error?.message ?? 'Kunde inte bokföra periodiseringarna')
|
||||
return
|
||||
}
|
||||
const created = body.data?.created?.length ?? 0
|
||||
const skipped = body.data?.skipped?.length ?? 0
|
||||
setPostSummary({ created, skipped })
|
||||
toast({
|
||||
title: `${created} verifikation${created === 1 ? '' : 'er'} bokförd${created === 1 ? '' : 'a'}`,
|
||||
description: skipped > 0 ? `${skipped} hoppades över (redan postade).` : undefined,
|
||||
})
|
||||
} catch (err) {
|
||||
setPostError(err instanceof Error ? err.message : 'Okänt fel')
|
||||
} finally {
|
||||
setPosting(false)
|
||||
}
|
||||
}, [
|
||||
selectedPeriodId,
|
||||
vacationProposal,
|
||||
vacationAccepted,
|
||||
auditState,
|
||||
autoState,
|
||||
manualEntries,
|
||||
proposal,
|
||||
toast,
|
||||
])
|
||||
|
||||
const closingYear = useMemo(() => {
|
||||
if (!proposal) return null
|
||||
return proposal.fiscalPeriod.period_end.slice(0, 4)
|
||||
}, [proposal])
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="font-display text-3xl md:text-4xl tracking-tight">
|
||||
{closingYear ? `Periodisering — Bokslut ${closingYear}` : 'Periodisering'}
|
||||
</h1>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/bookkeeping/year-end">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" /> Tillbaka till bokslut
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{periods === null && !periodsError && (
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-2">
|
||||
<Skeleton className="h-6 w-1/3" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{periodsError && (
|
||||
<Card>
|
||||
<CardContent className="p-6 text-destructive">{periodsError}</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{periods !== null && periods.length === 0 && (
|
||||
<EmptyState
|
||||
icon={Lock}
|
||||
title="Inga perioder att periodisera"
|
||||
description="Periodiseringar görs efter att räkenskapsperiodens slutdatum har passerat. Det finns ingen sådan öppen period."
|
||||
/>
|
||||
)}
|
||||
|
||||
{loadError && (
|
||||
<Card>
|
||||
<CardContent className="p-6 text-destructive">{loadError}</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{loading && (
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-2">
|
||||
<Skeleton className="h-6 w-1/3" />
|
||||
<Skeleton className="h-20 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{showWizard && proposal && (
|
||||
<>
|
||||
<Card>
|
||||
<CardContent className="p-4 space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="sm:hidden text-primary font-medium">
|
||||
Steg {currentStepIndex + 1}/{STEP_ORDER.length}: {STEP_LABELS[step]}
|
||||
</span>
|
||||
{STEP_ORDER.map((s, i) => (
|
||||
<span
|
||||
key={s}
|
||||
className={cn(
|
||||
'hidden sm:inline',
|
||||
i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{STEP_LABELS[s]}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<Progress value={progressValue} className="h-2" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{step === 'vacation' && (
|
||||
<VacationStep
|
||||
proposal={vacationProposal}
|
||||
accepted={vacationAccepted}
|
||||
onChange={setVacationAccepted}
|
||||
onNext={() => setStep('audit')}
|
||||
/>
|
||||
)}
|
||||
{step === 'audit' && (
|
||||
<AuditStep
|
||||
state={auditState}
|
||||
onChange={setAuditState}
|
||||
onBack={() => setStep('vacation')}
|
||||
onNext={() => setStep('auto')}
|
||||
/>
|
||||
)}
|
||||
{step === 'auto' && (
|
||||
<AutoStep
|
||||
suggestions={proposal.autoDetected ?? []}
|
||||
selections={autoState.selections}
|
||||
onToggle={(key, val) =>
|
||||
setAutoState({ selections: { ...autoState.selections, [key]: val } })
|
||||
}
|
||||
onBack={() => setStep('audit')}
|
||||
onNext={() => setStep('manual')}
|
||||
/>
|
||||
)}
|
||||
{step === 'manual' && (
|
||||
<ManualStep
|
||||
entries={manualEntries}
|
||||
onAdd={addManualFromTemplate}
|
||||
onUpdate={updateManual}
|
||||
onRemove={removeManual}
|
||||
onBack={() => setStep('auto')}
|
||||
onNext={() => setStep('review')}
|
||||
/>
|
||||
)}
|
||||
{step === 'review' && (
|
||||
<ReviewStep
|
||||
vacationProposal={vacationProposal}
|
||||
vacationAccepted={vacationAccepted}
|
||||
auditState={auditState}
|
||||
suggestions={proposal.autoDetected ?? []}
|
||||
selections={autoState.selections}
|
||||
manualEntries={manualEntries}
|
||||
postError={postError}
|
||||
postSummary={postSummary}
|
||||
posting={posting}
|
||||
canWrite={canWrite}
|
||||
onBack={() => setStep('manual')}
|
||||
onPost={handlePost}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Step components
|
||||
// ============================================================
|
||||
|
||||
function VacationStep({
|
||||
proposal,
|
||||
accepted,
|
||||
onChange,
|
||||
onNext,
|
||||
}: {
|
||||
proposal: AccrualsProposal['proposals'][number] | null
|
||||
accepted: boolean
|
||||
onChange: (v: boolean) => void
|
||||
onNext: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Steg 1: Semesterlöneskuld</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Justering av 2920 mot 7090 plus 31,42 % sociala avgifter (2940 / 7519).
|
||||
Saldot rullas vidare till nästa år.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{proposal ? (
|
||||
<div className="flex items-start justify-between gap-4 rounded-md border border-border p-4">
|
||||
<div className="flex-1 space-y-2">
|
||||
<p className="text-sm font-medium">{proposal.label}</p>
|
||||
<p className="text-xs text-muted-foreground">{proposal.description}</p>
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<Checkbox
|
||||
id="accept-vacation"
|
||||
checked={accepted}
|
||||
onCheckedChange={(c) => onChange(Boolean(c))}
|
||||
/>
|
||||
<Label htmlFor="accept-vacation" className="text-sm cursor-pointer select-none">
|
||||
Boka denna justering
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
<p className="font-display text-2xl tabular-nums shrink-0">
|
||||
{formatCurrency(proposal.amount)}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground italic">
|
||||
Ingen justering behövs — semesterlöneskulden ligger redan rätt.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={onNext}>
|
||||
Nästa <ArrowRight className="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AuditStep({
|
||||
state,
|
||||
onChange,
|
||||
onBack,
|
||||
onNext,
|
||||
}: {
|
||||
state: AuditState
|
||||
onChange: (s: AuditState) => void
|
||||
onBack: () => void
|
||||
onNext: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Steg 2: Revisions- / bokslutsarvode</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Periodisera arvode för revision (2992) eller bokslut (2991). Posten
|
||||
vänds första dagen i nästa räkenskapsår när fakturan kommer.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="audit-enabled"
|
||||
checked={state.enabled}
|
||||
onCheckedChange={(c) => onChange({ ...state, enabled: Boolean(c) })}
|
||||
/>
|
||||
<Label htmlFor="audit-enabled" className="text-sm cursor-pointer select-none">
|
||||
Periodisera arvode för detta bokslut
|
||||
</Label>
|
||||
</div>
|
||||
{state.enabled && (
|
||||
<div className="grid grid-cols-2 gap-4 rounded-md border border-border p-4">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Belopp (kr)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
value={state.amount}
|
||||
onChange={(e) => onChange({ ...state, amount: e.target.value })}
|
||||
className="tabular-nums h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Konto</Label>
|
||||
<select
|
||||
className="border border-border rounded-md h-9 text-sm px-2 w-full bg-background"
|
||||
value={state.liabilityAccount}
|
||||
onChange={(e) =>
|
||||
onChange({ ...state, liabilityAccount: e.target.value as '2991' | '2992' })
|
||||
}
|
||||
>
|
||||
<option value="2992">2992 — Revision</option>
|
||||
<option value="2991">2991 — Bokslut</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={onNext}>
|
||||
Nästa <ArrowRight className="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AutoStep({
|
||||
suggestions,
|
||||
selections,
|
||||
onToggle,
|
||||
onBack,
|
||||
onNext,
|
||||
}: {
|
||||
suggestions: PeriodiseringSuggestion[]
|
||||
selections: Record<string, boolean>
|
||||
onToggle: (key: string, val: boolean) => void
|
||||
onBack: () => void
|
||||
onNext: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Steg 3: Auto-detekterade periodiseringar</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Fakturor (kund och leverantör) i den stängda perioden vars beskrivning
|
||||
innehåller en datumintervall som sträcker sig in i nästa räkenskapsår.
|
||||
Granska och bekräfta — högst säkra förslag är förvalda.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{suggestions.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground italic">
|
||||
Inga fakturor med tydlig datumintervall hittades. Du kan ändå lägga
|
||||
till manuella periodiseringar i nästa steg.
|
||||
</p>
|
||||
)}
|
||||
{suggestions.map((s) => {
|
||||
const key = suggestionKey(s)
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className="flex items-start gap-3 rounded-md border border-border p-3"
|
||||
>
|
||||
<Checkbox
|
||||
id={`auto-${key}`}
|
||||
checked={!!selections[key]}
|
||||
onCheckedChange={(c) => onToggle(key, Boolean(c))}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Label
|
||||
htmlFor={`auto-${key}`}
|
||||
className="text-sm font-medium cursor-pointer select-none"
|
||||
>
|
||||
{s.source_label}
|
||||
</Label>
|
||||
<Badge variant={confidenceVariant(s.confidence)}>
|
||||
{confidenceLabel(s.confidence)}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{s.reason}</p>
|
||||
<div className="flex items-center gap-4 pt-1 text-xs">
|
||||
<span className="text-muted-foreground">
|
||||
{s.source_type === 'supplier_invoice'
|
||||
? 'Förutbetald kostnad → 1710'
|
||||
: 'Förutbetald intäkt → 2970'}
|
||||
</span>
|
||||
<span className="ml-auto font-display tabular-nums text-base">
|
||||
{formatCurrency(s.periodisering_amount)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={onNext}>
|
||||
Nästa <ArrowRight className="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ManualStep({
|
||||
entries,
|
||||
onAdd,
|
||||
onUpdate,
|
||||
onRemove,
|
||||
onBack,
|
||||
onNext,
|
||||
}: {
|
||||
entries: ManualEntry[]
|
||||
onAdd: (t: PeriodiseringTemplate) => void
|
||||
onUpdate: (id: string, patch: Partial<ManualEntry>) => void
|
||||
onRemove: (id: string) => void
|
||||
onBack: () => void
|
||||
onNext: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Steg 4: Manuella periodiseringar</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Använd mallarna nedan för vanliga fall, eller hoppa direkt till granskning.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
{PERIODISERING_TEMPLATES.map((t) => (
|
||||
<Button
|
||||
key={t.kind}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onAdd(t)}
|
||||
className="justify-start text-left h-auto py-2 px-3"
|
||||
>
|
||||
<Plus className="mr-2 h-3.5 w-3.5 shrink-0" />
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block font-medium">{t.name}</span>
|
||||
<span className="block text-xs text-muted-foreground truncate">{t.hint}</span>
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{entries.length > 0 && (
|
||||
<div className="space-y-3 pt-2">
|
||||
{entries.map((entry) => (
|
||||
<ManualEntryEditor
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
onChange={(patch) => onUpdate(entry.id, patch)}
|
||||
onRemove={() => onRemove(entry.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={onNext}>
|
||||
Granska <ArrowRight className="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ManualEntryEditor({
|
||||
entry,
|
||||
onChange,
|
||||
onRemove,
|
||||
}: {
|
||||
entry: ManualEntry
|
||||
onChange: (patch: Partial<ManualEntry>) => void
|
||||
onRemove: () => void
|
||||
}) {
|
||||
const template = PERIODISERING_TEMPLATES.find((t) => t.kind === entry.templateKind)
|
||||
if (!template) return null
|
||||
const primaryLabel =
|
||||
template.side === 'prepaid'
|
||||
? '17xx-konto'
|
||||
: template.side === 'deferred_revenue'
|
||||
? '29xx-konto (deferred)'
|
||||
: '29xx-konto'
|
||||
const secondaryLabel =
|
||||
template.side === 'deferred_revenue' ? 'Intäktskonto' : 'Kostnadskonto'
|
||||
|
||||
return (
|
||||
<div className="rounded-md border border-border p-3 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm font-medium">{template.name}</p>
|
||||
<Button variant="ghost" size="sm" onClick={onRemove} className="h-7 px-2">
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Belopp (kr)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
value={entry.amount}
|
||||
onChange={(e) => onChange({ amount: e.target.value })}
|
||||
className="tabular-nums h-8"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{primaryLabel}</Label>
|
||||
<Input
|
||||
value={entry.primaryAccount}
|
||||
onChange={(e) => onChange({ primaryAccount: e.target.value })}
|
||||
className="tabular-nums h-8"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">{secondaryLabel}</Label>
|
||||
<Input
|
||||
value={entry.secondaryAccount}
|
||||
onChange={(e) => onChange({ secondaryAccount: e.target.value })}
|
||||
className="tabular-nums h-8"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1 col-span-2">
|
||||
<Label className="text-xs">Beskrivning</Label>
|
||||
<Input
|
||||
value={entry.description}
|
||||
onChange={(e) => onChange({ description: e.target.value })}
|
||||
placeholder="t.ex. Försäkring 2026"
|
||||
className="h-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ReviewStep({
|
||||
vacationProposal,
|
||||
vacationAccepted,
|
||||
auditState,
|
||||
suggestions,
|
||||
selections,
|
||||
manualEntries,
|
||||
postError,
|
||||
postSummary,
|
||||
posting,
|
||||
canWrite,
|
||||
onBack,
|
||||
onPost,
|
||||
}: {
|
||||
vacationProposal: AccrualsProposal['proposals'][number] | null
|
||||
vacationAccepted: boolean
|
||||
auditState: AuditState
|
||||
suggestions: PeriodiseringSuggestion[]
|
||||
selections: Record<string, boolean>
|
||||
manualEntries: ManualEntry[]
|
||||
postError: string | null
|
||||
postSummary: { created: number; skipped: number } | null
|
||||
posting: boolean
|
||||
canWrite: boolean
|
||||
onBack: () => void
|
||||
onPost: () => void
|
||||
}) {
|
||||
const auditAmount = parseFloat(auditState.amount)
|
||||
const auditValid = auditState.enabled && Number.isFinite(auditAmount) && auditAmount > 0
|
||||
const selectedSuggestions = suggestions.filter((s) => selections[suggestionKey(s)])
|
||||
const validManual = manualEntries.filter(
|
||||
(m) => Number.isFinite(parseFloat(m.amount)) && parseFloat(m.amount) > 0 && m.description.trim(),
|
||||
)
|
||||
|
||||
const totalCount =
|
||||
(vacationProposal && vacationAccepted ? 1 : 0) +
|
||||
(auditValid ? 1 : 0) +
|
||||
selectedSuggestions.length +
|
||||
validManual.length
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Steg 5: Granska & posta</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{totalCount === 0
|
||||
? 'Inga periodiseringar valda. Gå tillbaka och välj minst en.'
|
||||
: `${totalCount} periodisering${totalCount === 1 ? '' : 'ar'} kommer att bokföras som separata verifikationer.`}
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{vacationProposal && vacationAccepted && (
|
||||
<ReviewLine label={vacationProposal.label} amount={vacationProposal.amount} note="Rullas vidare" />
|
||||
)}
|
||||
{auditValid && (
|
||||
<ReviewLine
|
||||
label={
|
||||
auditState.liabilityAccount === '2991'
|
||||
? 'Beräknat arvode för bokslut'
|
||||
: 'Beräknat arvode för revision'
|
||||
}
|
||||
amount={auditAmount}
|
||||
note="Vänds 1 januari"
|
||||
/>
|
||||
)}
|
||||
{selectedSuggestions.map((s) => (
|
||||
<ReviewLine
|
||||
key={suggestionKey(s)}
|
||||
label={`Auto: ${s.source_label}`}
|
||||
amount={s.periodisering_amount}
|
||||
note={s.source_type === 'supplier_invoice' ? 'Förutbetald kostnad' : 'Förutbetald intäkt'}
|
||||
/>
|
||||
))}
|
||||
{validManual.map((m) => {
|
||||
const tpl = PERIODISERING_TEMPLATES.find((t) => t.kind === m.templateKind)
|
||||
return (
|
||||
<ReviewLine
|
||||
key={m.id}
|
||||
label={`${tpl?.name ?? 'Periodisering'}: ${m.description}`}
|
||||
amount={parseFloat(m.amount)}
|
||||
note={tpl?.name}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{postError && (
|
||||
<Card>
|
||||
<CardContent className="p-4 text-sm text-destructive">{postError}</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{postSummary && (
|
||||
<Card>
|
||||
<CardContent className="p-4 text-sm">
|
||||
{postSummary.created} verifikation{postSummary.created === 1 ? '' : 'er'} bokförd
|
||||
{postSummary.created === 1 ? '' : 'a'}.
|
||||
{postSummary.skipped > 0 && ` ${postSummary.skipped} hoppades över (redan postade).`}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onBack} disabled={posting}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onPost}
|
||||
disabled={!canWrite || posting || totalCount === 0 || postSummary !== null}
|
||||
title={!canWrite ? 'Endast användare med skrivrättigheter kan posta periodiseringar.' : undefined}
|
||||
>
|
||||
{!canWrite ? (
|
||||
<>
|
||||
<Lock className="mr-2 h-4 w-4" /> Posta alla
|
||||
</>
|
||||
) : posting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Bokför…
|
||||
</>
|
||||
) : (
|
||||
'Posta alla'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ReviewLine({ label, amount, note }: { label: string; amount: number; note?: string }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4 rounded-md border border-border px-3 py-2">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium truncate">{label}</p>
|
||||
{note && <p className="text-xs text-muted-foreground">{note}</p>}
|
||||
</div>
|
||||
<p className="font-display text-base tabular-nums shrink-0">{formatCurrency(amount)}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -477,7 +477,7 @@ function SIEImportWizard() {
|
||||
|
||||
toast({
|
||||
title: 'Import ersatt',
|
||||
description: `${data.cancelledEntries} verifikation${data.cancelledEntries === 1 ? '' : 'er'} makulerades. Importerar ny fil...`,
|
||||
description: `${data.deletedEntries} verifikation${data.deletedEntries === 1 ? '' : 'er'} raderades. Importerar ny fil...`,
|
||||
})
|
||||
|
||||
// Clear error state and re-trigger the file upload
|
||||
|
||||
@@ -20,7 +20,7 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye, Landmark, Lock } from 'lucide-react'
|
||||
import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye, Landmark, Lock, AlertTriangle } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
|
||||
import { InvoiceReviewContent } from '@/components/invoices/InvoiceReviewContent'
|
||||
@@ -30,6 +30,13 @@ import CustomerForm from '@/components/customers/CustomerForm'
|
||||
import { BankDetailsSetupDialog } from '@/components/invoices/BankDetailsSetupDialog'
|
||||
import { FirstInvoiceLogoPrompt } from '@/components/invoices/FirstInvoiceLogoPrompt'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import {
|
||||
ROT_WORK_TYPES,
|
||||
RUT_WORK_TYPES,
|
||||
ROT_MAX,
|
||||
RUT_MAX,
|
||||
computeDeduction,
|
||||
} from '@/lib/invoices/rot-rut-rules'
|
||||
import type { Customer, Currency, CreateInvoiceInput, CreateCustomerInput, InvoiceDocumentType } from '@/types'
|
||||
|
||||
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
|
||||
@@ -54,6 +61,12 @@ export default function NewInvoicePage() {
|
||||
unit: z.string().min(1, t('validation_unit_required')),
|
||||
unit_price: z.number().min(0, t('validation_price_positive')),
|
||||
vat_rate: z.number().min(0).max(25),
|
||||
// ROT/RUT-avdrag per line. Optional — null means "no deduction".
|
||||
deduction_type: z.enum(['rot', 'rut']).nullable().optional(),
|
||||
labor_hours: z.number().nonnegative().nullable().optional(),
|
||||
work_type: z.string().nullable().optional(),
|
||||
housing_designation: z.string().nullable().optional(),
|
||||
apartment_number: z.string().nullable().optional(),
|
||||
})
|
||||
return z.object({
|
||||
customer_id: z.string().min(1, t('validation_customer_required')),
|
||||
@@ -65,6 +78,10 @@ export default function NewInvoicePage() {
|
||||
your_reference: z.string().optional(),
|
||||
our_reference: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
// Invoice-level ROT/RUT claim info. Personnummer is plaintext on
|
||||
// the wire; the API encrypts it before storage.
|
||||
deduction_personnummer: z.string().optional(),
|
||||
deduction_housing_designation: z.string().optional(),
|
||||
items: z.array(itemSchema).min(1, t('validation_min_one_row')),
|
||||
})
|
||||
}, [t])
|
||||
@@ -112,7 +129,18 @@ export default function NewInvoicePage() {
|
||||
due_date: '',
|
||||
currency: 'SEK',
|
||||
document_type: 'invoice' as InvoiceDocumentType,
|
||||
items: [{ description: '', quantity: 1, unit: 'st', unit_price: 0, vat_rate: 25 }],
|
||||
items: [{
|
||||
description: '',
|
||||
quantity: 1,
|
||||
unit: 'st',
|
||||
unit_price: 0,
|
||||
vat_rate: 25,
|
||||
deduction_type: null,
|
||||
labor_hours: null,
|
||||
work_type: null,
|
||||
housing_designation: null,
|
||||
apartment_number: null,
|
||||
}],
|
||||
},
|
||||
})
|
||||
|
||||
@@ -320,10 +348,33 @@ export default function NewInvoicePage() {
|
||||
}
|
||||
const total = subtotal + vatAmount
|
||||
|
||||
// ROT/RUT-avdrag live preview. Computed client-side for instant feedback;
|
||||
// the API recomputes server-side as the source of truth. Skipped for
|
||||
// non-invoice document types (proformas and delivery notes don't book
|
||||
// a deduction).
|
||||
const isInvoiceDoc = watchDocumentType === 'invoice'
|
||||
const deductionByKind = { rot: 0, rut: 0 }
|
||||
if (isInvoiceDoc) {
|
||||
for (const item of watchItems) {
|
||||
if (!item.deduction_type) continue
|
||||
const amount = computeDeduction({
|
||||
unit_price: item.unit_price || 0,
|
||||
quantity: item.quantity || 0,
|
||||
deduction_type: item.deduction_type,
|
||||
})
|
||||
if (item.deduction_type === 'rot') deductionByKind.rot += amount
|
||||
else deductionByKind.rut += amount
|
||||
}
|
||||
}
|
||||
const deductionTotal = Math.round((deductionByKind.rot + deductionByKind.rut) * 100) / 100
|
||||
const hasAnyDeduction = deductionTotal > 0
|
||||
const hasAnyRotLine = isInvoiceDoc && watchItems.some((i) => i.deduction_type === 'rot')
|
||||
const toPay = Math.round((total - deductionTotal) * 100) / 100
|
||||
|
||||
async function onSubmit(data: FormData) {
|
||||
setPendingData(data)
|
||||
// Re-fetch the preview right before review so the displayed number
|
||||
// reflects any concurrent invoice creations.
|
||||
// reflects any concurrent invoice creations. Skip for delivery notes.
|
||||
if (data.document_type !== 'delivery_note') {
|
||||
try {
|
||||
const r = await fetch(`/api/invoices/next-number?document_type=${encodeURIComponent(data.document_type)}`)
|
||||
@@ -370,11 +421,37 @@ export default function NewInvoicePage() {
|
||||
if (!pendingData) return
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Privacy by default: ROT/RUT line fields and the invoice-level
|
||||
// personnummer / housing designation are only sent to the API when the
|
||||
// user actually claims a deduction. Defaults are pre-instantiated as
|
||||
// null in the form state, but null personal-data fields shouldn't ride
|
||||
// along on every regular invoice.
|
||||
const anyDeduction = pendingData.items.some((i) => i.deduction_type)
|
||||
const sanitizedItems = pendingData.items.map((item) => {
|
||||
if (item.deduction_type) return item
|
||||
const {
|
||||
deduction_type: _dt,
|
||||
labor_hours: _lh,
|
||||
work_type: _wt,
|
||||
housing_designation: _hd,
|
||||
apartment_number: _an,
|
||||
...rest
|
||||
} = item
|
||||
return rest
|
||||
})
|
||||
const sanitizedPayload: CreateInvoiceInput = {
|
||||
...(pendingData as CreateInvoiceInput),
|
||||
items: sanitizedItems as CreateInvoiceInput['items'],
|
||||
...(anyDeduction
|
||||
? {}
|
||||
: { deduction_personnummer: undefined, deduction_housing_designation: undefined }),
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/invoices', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(pendingData as CreateInvoiceInput),
|
||||
body: JSON.stringify(sanitizedPayload),
|
||||
})
|
||||
|
||||
const result = await response.json()
|
||||
@@ -707,6 +784,117 @@ export default function NewInvoicePage() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* ROT/RUT-avdrag per-row controls. Only shown on real
|
||||
invoices — proformas and delivery notes have no
|
||||
deduction model. Collapsed to a tiny segmented
|
||||
toggle by default; selecting ROT or RUT reveals the
|
||||
work-type picker. */}
|
||||
{isInvoiceDoc && (
|
||||
<div className="md:col-span-12 mt-2 md:mt-3">
|
||||
<Controller
|
||||
name={`items.${index}.deduction_type`}
|
||||
control={control}
|
||||
render={({ field }) => {
|
||||
const value = field.value ?? 'none'
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">Skattereduktion:</span>
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={(v) => {
|
||||
const next = v === 'none' ? null : (v as 'rot' | 'rut')
|
||||
field.onChange(next)
|
||||
if (next === null) {
|
||||
setValue(`items.${index}.work_type`, null)
|
||||
setValue(`items.${index}.labor_hours`, null)
|
||||
setValue(`items.${index}.housing_designation`, null)
|
||||
setValue(`items.${index}.apartment_number`, null)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-32">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">Ingen</SelectItem>
|
||||
<SelectItem value="rot">ROT (30%)</SelectItem>
|
||||
<SelectItem value="rut">RUT (50%)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{watchItems[index]?.deduction_type && (
|
||||
<>
|
||||
<Controller
|
||||
name={`items.${index}.work_type`}
|
||||
control={control}
|
||||
render={({ field: workField }) => {
|
||||
const opts =
|
||||
watchItems[index]?.deduction_type === 'rot'
|
||||
? ROT_WORK_TYPES
|
||||
: RUT_WORK_TYPES
|
||||
return (
|
||||
<Select
|
||||
value={workField.value ?? ''}
|
||||
onValueChange={(v) => workField.onChange(v || null)}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-56">
|
||||
<SelectValue placeholder="Välj arbetstyp" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{opts.map((w) => (
|
||||
<SelectItem key={w.code} value={w.code}>
|
||||
{w.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.5"
|
||||
inputMode="decimal"
|
||||
placeholder="Arbetstimmar"
|
||||
className="h-8 w-32 text-right tabular-nums"
|
||||
{...register(`items.${index}.labor_hours`, {
|
||||
valueAsNumber: true,
|
||||
setValueAs: (v) =>
|
||||
v === '' || Number.isNaN(v) ? null : Number(v),
|
||||
})}
|
||||
/>
|
||||
{(() => {
|
||||
const amt = computeDeduction({
|
||||
unit_price: watchItems[index]?.unit_price || 0,
|
||||
quantity: watchItems[index]?.quantity || 0,
|
||||
deduction_type: watchItems[index]?.deduction_type,
|
||||
})
|
||||
return amt > 0 ? (
|
||||
<span className="text-xs tabular-nums text-muted-foreground">
|
||||
−{formatCurrency(amt, watchCurrency)}
|
||||
</span>
|
||||
) : null
|
||||
})()}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
{/* Labor-only disclosure (Skatteverket fakturamodellen).
|
||||
30%/50% applies to the full line total — the seller
|
||||
must ensure the line is 100% labor; material has
|
||||
to be invoiced separately. */}
|
||||
{watchItems[index]?.deduction_type && (
|
||||
<div className="mt-2 flex items-start gap-2 text-xs text-warning-foreground">
|
||||
<AlertTriangle className="h-3.5 w-3.5 mt-0.5 text-warning shrink-0" />
|
||||
<p>
|
||||
Skatteverket kräver att endast arbetskostnad ingår i ROT/RUT-grundlaget. Material ska faktureras separat. Sätt endast skattereduktion på rader som är 100% arbete.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mobile summary row */}
|
||||
<div className="flex justify-between text-sm pt-1 border-t border-border/40 md:hidden">
|
||||
<span className="text-muted-foreground">{t('row_label', { index: index + 1 })}</span>
|
||||
@@ -721,7 +909,18 @@ export default function NewInvoicePage() {
|
||||
variant="outline"
|
||||
className="w-full md:w-auto"
|
||||
onClick={() =>
|
||||
append({ description: '', quantity: 1, unit: 'st', unit_price: 0, vat_rate: availableRates[0]?.rate ?? 25 })
|
||||
append({
|
||||
description: '',
|
||||
quantity: 1,
|
||||
unit: 'st',
|
||||
unit_price: 0,
|
||||
vat_rate: availableRates[0]?.rate ?? 25,
|
||||
deduction_type: null,
|
||||
labor_hours: null,
|
||||
work_type: null,
|
||||
housing_designation: null,
|
||||
apartment_number: null,
|
||||
})
|
||||
}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
@@ -731,6 +930,59 @@ export default function NewInvoicePage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ROT/RUT-avdrag claim info. Surfaces only when any item has
|
||||
a deduction_type set — keeps the form quiet for the 90%+
|
||||
of users who don't sell ROT/RUT-eligible services. */}
|
||||
{isInvoiceDoc && hasAnyDeduction && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Underlag för skattereduktion</CardTitle>
|
||||
<CardDescription>
|
||||
ROT/RUT-avdrag begärs hos Skatteverket via fakturamodellen. Kunden behöver godkänna utbetalningen, så uppgifterna måste matcha köparen exakt.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deduction_personnummer">
|
||||
Personnummer<RequiredMark />
|
||||
</Label>
|
||||
<Input
|
||||
id="deduction_personnummer"
|
||||
placeholder="ÅÅÅÅMMDD-NNNN"
|
||||
autoComplete="off"
|
||||
{...register('deduction_personnummer')}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Krypteras innan lagring. Endast de fyra sista siffrorna visas på fakturan.
|
||||
</p>
|
||||
</div>
|
||||
{hasAnyRotLine && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deduction_housing_designation">
|
||||
Fastighetsbeteckning<RequiredMark />
|
||||
</Label>
|
||||
<Input
|
||||
id="deduction_housing_designation"
|
||||
placeholder="t.ex. Stockholm Vasastan 1:23"
|
||||
{...register('deduction_housing_designation')}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Krävs för ROT-avdrag (RUT behöver inte detta fält).
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{(deductionByKind.rot > ROT_MAX || deductionByKind.rut > RUT_MAX) && (
|
||||
<div className="rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
|
||||
Fakturans avdrag överstiger årstaket
|
||||
{deductionByKind.rot > ROT_MAX && ` (ROT ${ROT_MAX.toLocaleString('sv-SE')} kr)`}
|
||||
{deductionByKind.rut > RUT_MAX && ` (RUT ${RUT_MAX.toLocaleString('sv-SE')} kr)`}
|
||||
. Kunden behöver kontrollera sitt återstående utrymme själv.
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Notes */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -881,11 +1133,23 @@ export default function NewInvoicePage() {
|
||||
<span>{formatCurrency(0, watchCurrency)}</span>
|
||||
</div>
|
||||
)}
|
||||
{hasAnyDeduction && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Skattereduktion ROT/RUT</span>
|
||||
<span className="tabular-nums">−{formatCurrency(deductionTotal, watchCurrency)}</span>
|
||||
</div>
|
||||
)}
|
||||
<Separator />
|
||||
<div className="flex justify-between font-bold text-lg">
|
||||
<span>{t('total_label')}</span>
|
||||
<span>{formatCurrency(total, watchCurrency)}</span>
|
||||
<span>{hasAnyDeduction ? 'Att betala' : t('total_label')}</span>
|
||||
<span>{formatCurrency(hasAnyDeduction ? toPay : total, watchCurrency)}</span>
|
||||
</div>
|
||||
{hasAnyDeduction && (
|
||||
<div className="flex justify-between text-xs text-muted-foreground">
|
||||
<span>Totalt inkl. moms</span>
|
||||
<span className="tabular-nums">{formatCurrency(total, watchCurrency)}</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -907,8 +1171,12 @@ export default function NewInvoicePage() {
|
||||
<div className="md:hidden fixed left-0 right-0 z-40 bg-card/98 backdrop-blur-sm border-t border-border/40 px-5 py-3" style={{ bottom: 'calc(4rem + env(safe-area-inset-bottom, 0px))' }}>
|
||||
<div className="max-w-5xl mx-auto flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">{t('total_label')}</p>
|
||||
<p className="text-lg font-bold tabular-nums">{formatCurrency(total, watchCurrency)}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{hasAnyDeduction ? 'Att betala' : t('total_label')}
|
||||
</p>
|
||||
<p className="text-lg font-bold tabular-nums">
|
||||
{formatCurrency(hasAnyDeduction ? toPay : total, watchCurrency)}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
|
||||
@@ -23,7 +23,7 @@ import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { invoiceNumberDisplay } from '@/lib/invoices/display'
|
||||
import { getDisplayTotal } from '@/lib/invoices/rounding'
|
||||
import { Plus, Search, Receipt, Lock, Repeat } from 'lucide-react'
|
||||
import { Plus, Search, Receipt, Lock, Repeat, FileText } from 'lucide-react'
|
||||
import { EmptyInvoices } from '@/components/ui/empty-state'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
@@ -151,6 +151,12 @@ export default function InvoicesPage() {
|
||||
title={t('title')}
|
||||
action={
|
||||
<div className="flex gap-2">
|
||||
<Link href="/invoices/quotes">
|
||||
<Button variant="secondary">
|
||||
<FileText className="mr-2 h-4 w-4" />
|
||||
Offerter
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/invoices/recurring">
|
||||
<Button variant="secondary">
|
||||
<Repeat className="mr-2 h-4 w-4" />
|
||||
|
||||
@@ -117,7 +117,7 @@ export default async function DashboardLayout({
|
||||
] = await Promise.all([
|
||||
supabase.from('companies').select('*').eq('id', companyId).single(),
|
||||
supabase.from('company_members').select('role').eq('company_id', companyId).eq('user_id', user.id).single(),
|
||||
supabase.from('company_members').select('company_id, role, companies:company_id(id, name, org_number, entity_type, created_by, team_id, archived_at, created_at, updated_at)').eq('user_id', user.id),
|
||||
supabase.from('company_members').select('company_id, role, companies:company_id(id, name, org_number, entity_type, accounting_framework, created_by, team_id, archived_at, created_at, updated_at)').eq('user_id', user.id),
|
||||
])
|
||||
|
||||
if (!companyRow || !memberRow) {
|
||||
|
||||
@@ -381,26 +381,29 @@ function GenericPreview({ data }: { data: Record<string, unknown> }) {
|
||||
}
|
||||
|
||||
function OperationPreview({ op }: { op: PendingOperation }) {
|
||||
switch (op.operation_type) {
|
||||
case 'categorize_transaction':
|
||||
return <CategorizePreview data={op.preview_data} />
|
||||
case 'create_customer':
|
||||
return <CustomerPreview data={op.preview_data} />
|
||||
case 'create_invoice':
|
||||
return <InvoicePreview data={op.preview_data} />
|
||||
case 'create_transaction':
|
||||
return <CreateTransactionPreview data={op.preview_data} />
|
||||
case 'create_voucher':
|
||||
return <VoucherPreview data={op.preview_data} />
|
||||
case 'correct_entry':
|
||||
return <CorrectEntryPreview data={op.preview_data} />
|
||||
case 'attach_document_to_transaction':
|
||||
return <AttachDocumentPreview data={op.preview_data} params={op.params} />
|
||||
case 'match_transaction_invoice':
|
||||
return <MatchTransactionInvoicePreview data={op.preview_data} />
|
||||
default:
|
||||
return <GenericPreview data={op.preview_data} />
|
||||
}
|
||||
const body = (() => {
|
||||
switch (op.operation_type) {
|
||||
case 'categorize_transaction':
|
||||
return <CategorizePreview data={op.preview_data} />
|
||||
case 'create_customer':
|
||||
return <CustomerPreview data={op.preview_data} />
|
||||
case 'create_invoice':
|
||||
return <InvoicePreview data={op.preview_data} />
|
||||
case 'create_transaction':
|
||||
return <CreateTransactionPreview data={op.preview_data} />
|
||||
case 'create_voucher':
|
||||
return <VoucherPreview data={op.preview_data} />
|
||||
case 'correct_entry':
|
||||
return <CorrectEntryPreview data={op.preview_data} />
|
||||
case 'attach_document_to_transaction':
|
||||
return <AttachDocumentPreview data={op.preview_data} params={op.params} />
|
||||
case 'match_transaction_invoice':
|
||||
return <MatchTransactionInvoicePreview data={op.preview_data} />
|
||||
default:
|
||||
return <GenericPreview data={op.preview_data} />
|
||||
}
|
||||
})()
|
||||
return body
|
||||
}
|
||||
|
||||
type SourceFilter = 'all' | 'agent' | 'high_risk'
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useEffect, useState, useCallback } from 'react'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { FiscalYearSelector } from '@/components/common/FiscalYearSelector'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/info-tooltip'
|
||||
import { ArrowLeft, Download, FileSpreadsheet, AlertTriangle, CheckCircle2 } from 'lucide-react'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import type { KassaflodesanalysReport } from '@/lib/reports/kassaflodesanalys'
|
||||
|
||||
function formatAmount(n: number): string {
|
||||
return n.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})
|
||||
}
|
||||
|
||||
interface CashRowProps {
|
||||
label: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
function CashRow({ label, amount }: CashRowProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between py-1.5 text-sm">
|
||||
<span className="text-foreground">{label}</span>
|
||||
<span className="tabular-nums text-right">{formatAmount(amount)}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface SubtotalRowProps {
|
||||
label: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
function SubtotalRow({ label, amount }: SubtotalRowProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between border-t border-border pt-3 mt-2 text-sm font-medium">
|
||||
<span>{label}</span>
|
||||
<span className="tabular-nums text-right">{formatAmount(amount)}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function KassaflodesanalysClient() {
|
||||
const [selectedPeriod, setSelectedPeriod] = useState<string | null>(null)
|
||||
const [report, setReport] = useState<KassaflodesanalysReport | null>(null)
|
||||
const [isLoadingPeriods, setIsLoadingPeriods] = useState(true)
|
||||
const [isLoadingReport, setIsLoadingReport] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const loadReport = useCallback(async (periodId: string) => {
|
||||
setIsLoadingReport(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`/api/reports/kassaflodesanalys?period_id=${periodId}`)
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body.error || 'Kunde inte hämta kassaflödesanalys')
|
||||
}
|
||||
const { data } = await res.json()
|
||||
setReport(data)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Okänt fel')
|
||||
setReport(null)
|
||||
} finally {
|
||||
setIsLoadingReport(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPeriod) {
|
||||
loadReport(selectedPeriod)
|
||||
} else {
|
||||
setReport(null)
|
||||
}
|
||||
}, [selectedPeriod, loadReport])
|
||||
|
||||
const handleDownloadPdf = useCallback(() => {
|
||||
if (!selectedPeriod) return
|
||||
window.location.href = `/api/reports/kassaflodesanalys/pdf?period_id=${selectedPeriod}`
|
||||
}, [selectedPeriod])
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<Link
|
||||
href="/reports"
|
||||
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" />
|
||||
Rapporter
|
||||
</Link>
|
||||
<PageHeader title="Kassaflödesanalys" />
|
||||
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
|
||||
<FiscalYearSelector
|
||||
value={selectedPeriod}
|
||||
onChange={(id) => setSelectedPeriod(id)}
|
||||
includeAllOption={false}
|
||||
hideFuturePeriods
|
||||
onReady={() => setIsLoadingPeriods(false)}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleDownloadPdf}
|
||||
disabled={!report || isLoadingReport}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Ladda ner PDF
|
||||
</Button>
|
||||
<TooltipProvider delayDuration={300}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span>
|
||||
<Button variant="outline" disabled>
|
||||
<FileSpreadsheet className="mr-2 h-4 w-4" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Snart tillgänglig</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Indirekt metod enligt BFNAR 2012:1 kap 7. Totalsumman ska överensstämma
|
||||
med förändringen i likvida medel (kontoklass 19) under perioden.
|
||||
</p>
|
||||
|
||||
{isLoadingPeriods ? (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-48" />
|
||||
<Skeleton className="h-32" />
|
||||
<Skeleton className="h-32" />
|
||||
</div>
|
||||
) : !selectedPeriod ? (
|
||||
<EmptyState
|
||||
title="Välj räkenskapsår"
|
||||
description="Välj ett räkenskapsår ovan för att generera kassaflödesanalys."
|
||||
/>
|
||||
) : isLoadingReport ? (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-48" />
|
||||
<Skeleton className="h-32" />
|
||||
<Skeleton className="h-32" />
|
||||
</div>
|
||||
) : error ? (
|
||||
<Card className="border-destructive/40">
|
||||
<CardContent className="p-6 text-sm text-destructive">{error}</CardContent>
|
||||
</Card>
|
||||
) : report ? (
|
||||
<div className="space-y-6">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Period: {formatDate(report.period_start)} – {formatDate(report.period_end)}
|
||||
</p>
|
||||
|
||||
{/* Section 1: Löpande verksamhet */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Den löpande verksamheten
|
||||
</h2>
|
||||
<CardTitle className="text-base">
|
||||
Kassaflöde från löpande verksamhet
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-1">
|
||||
<CashRow
|
||||
label="Resultat efter finansiella poster"
|
||||
amount={report.lopande.resultat_efter_finansiella_poster}
|
||||
/>
|
||||
<CashRow label="Avskrivningar" amount={report.lopande.avskrivningar} />
|
||||
<CashRow
|
||||
label="Övriga ej-kassaflödespåverkande poster"
|
||||
amount={report.lopande.ovriga_ej_kassaflodesposter}
|
||||
/>
|
||||
<CashRow
|
||||
label="Förändring av kortfristiga fordringar"
|
||||
amount={report.lopande.delta_kortfristiga_fordringar}
|
||||
/>
|
||||
<CashRow
|
||||
label="Förändring av varulager"
|
||||
amount={report.lopande.delta_varulager}
|
||||
/>
|
||||
<CashRow
|
||||
label="Förändring av kortfristiga skulder"
|
||||
amount={report.lopande.delta_kortfristiga_skulder}
|
||||
/>
|
||||
<CashRow label="Betald inkomstskatt" amount={report.lopande.skatt_betald} />
|
||||
<SubtotalRow
|
||||
label="Summa kassaflöde löpande verksamhet"
|
||||
amount={report.lopande.total}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Section 2: Investeringsverksamhet */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Investeringsverksamheten
|
||||
</h2>
|
||||
<CardTitle className="text-base">
|
||||
Kassaflöde från investeringsverksamhet
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-1">
|
||||
<CashRow
|
||||
label="Förvärv av anläggningstillgångar"
|
||||
amount={report.investerings.forvarv_anlaggningar}
|
||||
/>
|
||||
<CashRow
|
||||
label="Avyttring av anläggningstillgångar"
|
||||
amount={report.investerings.avyttring_anlaggningar}
|
||||
/>
|
||||
<SubtotalRow
|
||||
label="Summa kassaflöde investeringsverksamhet"
|
||||
amount={report.investerings.total}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Section 3: Finansieringsverksamhet */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Finansieringsverksamheten
|
||||
</h2>
|
||||
<CardTitle className="text-base">
|
||||
Kassaflöde från finansieringsverksamhet
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-1">
|
||||
<CashRow
|
||||
label="Förändring av lån (långfristiga skulder)"
|
||||
amount={report.finansierings.delta_lan}
|
||||
/>
|
||||
<CashRow label="Utdelningar" amount={report.finansierings.utdelningar} />
|
||||
<CashRow label="Nyemission" amount={report.finansierings.nyemission} />
|
||||
<SubtotalRow
|
||||
label="Summa kassaflöde finansieringsverksamhet"
|
||||
amount={report.finansierings.total}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Total */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-between text-base font-medium">
|
||||
<span className="font-display text-lg">Årets kassaflöde</span>
|
||||
<span className="font-display text-lg tabular-nums">
|
||||
{formatAmount(report.total_cash_flow)}
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Reconciliation banner */}
|
||||
<Card
|
||||
className={
|
||||
report.reconciliation.is_reconciled
|
||||
? 'border-success/40 bg-success/5'
|
||||
: 'border-destructive/60 bg-destructive/5'
|
||||
}
|
||||
>
|
||||
<CardContent className="p-6 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{report.reconciliation.is_reconciled ? (
|
||||
<CheckCircle2 className="h-5 w-5 text-success" />
|
||||
) : (
|
||||
<AlertTriangle className="h-5 w-5 text-destructive" />
|
||||
)}
|
||||
<span className="font-medium">
|
||||
{report.reconciliation.is_reconciled
|
||||
? 'Avstämning OK — kassaflödet stämmer med 19xx'
|
||||
: 'Avstämning misslyckades — kontrollera bokföringen'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-1 text-sm">
|
||||
<CashRow
|
||||
label="Ingående saldo (19xx)"
|
||||
amount={report.reconciliation.opening_cash_1xxx}
|
||||
/>
|
||||
<CashRow
|
||||
label="Utgående saldo (19xx)"
|
||||
amount={report.reconciliation.closing_cash_1xxx}
|
||||
/>
|
||||
<CashRow
|
||||
label="Faktisk förändring i likvida medel"
|
||||
amount={report.reconciliation.delta_actual}
|
||||
/>
|
||||
<CashRow
|
||||
label="Beräknad förändring (summa kassaflöden)"
|
||||
amount={report.reconciliation.delta_calculated}
|
||||
/>
|
||||
{!report.reconciliation.is_reconciled && (
|
||||
<div className="flex items-center justify-between border-t border-destructive/40 pt-2 mt-2 text-sm font-medium text-destructive">
|
||||
<span>Avvikelse</span>
|
||||
<span className="tabular-nums text-right">
|
||||
{formatAmount(report.reconciliation.mismatch_amount)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { KassaflodesanalysClient } from './KassaflodesanalysClient'
|
||||
|
||||
// NOTE: The xlsx download button on this page is intentionally disabled.
|
||||
// Plan item #4 (Excel export for all reports) introduces a shared
|
||||
// `reportToWorkbook` helper and adds `/api/reports/kassaflodesanalys/xlsx`.
|
||||
// Once that helper lands, enable the button and point it at that endpoint.
|
||||
|
||||
export default function KassaflodesanalysPage() {
|
||||
return <KassaflodesanalysClient />
|
||||
}
|
||||
+498
-110
@@ -2,14 +2,16 @@
|
||||
|
||||
import React, { useState, useEffect, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Download, AlertCircle, ChevronDown, ChevronRight, ArrowRight } from 'lucide-react'
|
||||
import { Download, FileSpreadsheet, AlertCircle, ChevronDown, ChevronRight, ArrowRight } from 'lucide-react'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { FiscalYearSelector } from '@/components/common/FiscalYearSelector'
|
||||
@@ -22,6 +24,11 @@ import { TrialBalanceChart } from '@/components/reports/TrialBalanceChart'
|
||||
import { VatCompositionChart } from '@/components/reports/VatCompositionChart'
|
||||
import { SkatteverketPanel } from '@/components/reports/SkatteverketPanel'
|
||||
import { IncomeExpenseChart } from '@/components/reports/IncomeExpenseChart'
|
||||
import { useReportRowExpansion } from '@/components/reports/ReportRowExpansion'
|
||||
import type {
|
||||
ReportSourceLine,
|
||||
ReportSourceFetcher,
|
||||
} from '@/lib/reports/source-lines'
|
||||
import type { MonthlyDataPoint } from '@/components/reports/IncomeExpenseChart'
|
||||
import type {
|
||||
TrialBalanceRow,
|
||||
@@ -54,6 +61,7 @@ const TAB_LABEL_KEYS: Record<string, string> = {
|
||||
}
|
||||
|
||||
export default function ReportsPage() {
|
||||
const router = useRouter()
|
||||
const [selectedPeriod, setSelectedPeriod] = useState('')
|
||||
const [activeTab, setActiveTab] = useState('resultatrapport')
|
||||
const [isLoadingInit, setIsLoadingInit] = useState(true)
|
||||
@@ -74,11 +82,27 @@ export default function ReportsPage() {
|
||||
}, [activeTab, t])
|
||||
|
||||
const handleTabChange = useCallback((tab: string) => {
|
||||
// Kassaflödesanalys lives on its own route; route there instead of swapping tabs.
|
||||
if (tab === 'kassaflodesanalys') {
|
||||
router.push('/reports/kassaflodesanalys')
|
||||
return
|
||||
}
|
||||
// Årsredovisning is an editable document (narrative + signatures) and lives
|
||||
// on its own route under the year-end flow. Forward the active period so
|
||||
// the page opens directly on the right fiscal year.
|
||||
if (tab === 'arsredovisning') {
|
||||
router.push(
|
||||
selectedPeriod
|
||||
? `/bookkeeping/year-end/arsredovisning?period=${selectedPeriod}`
|
||||
: '/bookkeeping/year-end/arsredovisning',
|
||||
)
|
||||
return
|
||||
}
|
||||
// Manual tab change clears drill-down state
|
||||
setActiveTab(tab)
|
||||
setGlAccountFilter(null)
|
||||
setDrillDownTrail([])
|
||||
}, [])
|
||||
}, [router, selectedPeriod])
|
||||
|
||||
const navigateBack = useCallback((stepIndex: number) => {
|
||||
const step = drillDownTrail[stepIndex]
|
||||
@@ -300,6 +324,16 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/trial-balance/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
<TrialBalanceChart rows={data.rows} />
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -342,6 +376,7 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
<table className="w-full text-sm min-w-[500px]">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b text-left">
|
||||
<th className="py-2 w-8"></th>
|
||||
<th className="py-2 w-20">Konto</th>
|
||||
<th className="py-2">Namn</th>
|
||||
<th className="py-2 w-32 text-right">Ingående saldo</th>
|
||||
@@ -350,38 +385,23 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.rows.map((row) => {
|
||||
const ob = getNetBalance(row, 'opening')
|
||||
const ch = getNetBalance(row, 'period')
|
||||
const cb = getNetBalance(row, 'closing')
|
||||
return (
|
||||
<tr
|
||||
key={row.account_number}
|
||||
className="border-b last:border-0 cursor-pointer hover:bg-muted/50 transition-colors"
|
||||
onClick={() => onNavigateToAccount(row.account_number)}
|
||||
>
|
||||
<td className="py-2">
|
||||
<AccountNumber number={row.account_number} name={row.account_name} />
|
||||
</td>
|
||||
<td className="py-2">{row.account_name}</td>
|
||||
<td className={`py-2 text-right tabular-nums ${ob < 0 ? 'text-destructive' : ''}`}>
|
||||
{formatSigned(ob)}
|
||||
</td>
|
||||
<td className={`py-2 text-right tabular-nums ${ch < 0 ? 'text-destructive' : ''}`}>
|
||||
{formatSigned(ch)}
|
||||
</td>
|
||||
<td className={`py-2 text-right tabular-nums font-medium ${cb < 0 ? 'text-destructive' : ''}`}>
|
||||
{formatSigned(cb)}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
{data.rows.map((row) => (
|
||||
<TrialBalanceSimplifiedRow
|
||||
key={row.account_number}
|
||||
row={row}
|
||||
periodId={periodId}
|
||||
onNavigateToAccount={onNavigateToAccount}
|
||||
getNetBalance={getNetBalance}
|
||||
formatSigned={formatSigned}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<table className="w-full text-sm min-w-[600px]">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b text-left">
|
||||
<th className="py-2 w-8"></th>
|
||||
<th className="py-2 w-20">Konto</th>
|
||||
<th className="py-2">Namn</th>
|
||||
<th className="py-2 w-28 text-right">Period debet</th>
|
||||
@@ -392,32 +412,17 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.rows.map((row) => (
|
||||
<tr
|
||||
<TrialBalanceDetailedRow
|
||||
key={row.account_number}
|
||||
className="border-b last:border-0 cursor-pointer hover:bg-muted/50 transition-colors"
|
||||
onClick={() => onNavigateToAccount(row.account_number)}
|
||||
>
|
||||
<td className="py-2">
|
||||
<AccountNumber number={row.account_number} name={row.account_name} />
|
||||
</td>
|
||||
<td className="py-2">{row.account_name}</td>
|
||||
<td className="py-2 text-right">
|
||||
{row.period_debit > 0 ? formatAmount(row.period_debit) : ''}
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
{row.period_credit > 0 ? formatAmount(row.period_credit) : ''}
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
{row.closing_debit > 0 ? formatAmount(row.closing_debit) : ''}
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
{row.closing_credit > 0 ? formatAmount(row.closing_credit) : ''}
|
||||
</td>
|
||||
</tr>
|
||||
row={row}
|
||||
periodId={periodId}
|
||||
onNavigateToAccount={onNavigateToAccount}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="font-semibold border-t-2">
|
||||
<td className="py-2"></td>
|
||||
<td colSpan={2} className="py-2">Summa</td>
|
||||
<td className="py-2 text-right">
|
||||
{formatAmount(data.rows.reduce((s, r) => s + r.period_debit, 0))}
|
||||
@@ -441,6 +446,127 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Lazy fetcher for a TB account's source lines. Memoised at the row level so
|
||||
// repeated toggling never refetches.
|
||||
function makeTrialBalanceFetcher(accountNumber: string, periodId: string): ReportSourceFetcher {
|
||||
return async () => {
|
||||
const res = await fetch(
|
||||
`/api/reports/trial-balance/account/${encodeURIComponent(accountNumber)}/sources?fiscal_period_id=${encodeURIComponent(periodId)}`
|
||||
)
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error || 'Kunde inte hämta verifikat')
|
||||
const lines: ReportSourceLine[] = json.data?.lines || []
|
||||
return { lines, next_cursor: json.data?.next_cursor ?? null }
|
||||
}
|
||||
}
|
||||
|
||||
function TrialBalanceSimplifiedRow({
|
||||
row,
|
||||
periodId,
|
||||
onNavigateToAccount,
|
||||
getNetBalance,
|
||||
formatSigned,
|
||||
}: {
|
||||
row: TrialBalanceRow
|
||||
periodId: string
|
||||
onNavigateToAccount: (account: string) => void
|
||||
getNetBalance: (row: TrialBalanceRow, type: 'opening' | 'period' | 'closing') => number
|
||||
formatSigned: (amount: number) => string
|
||||
}) {
|
||||
const fetcher = React.useMemo(
|
||||
() => makeTrialBalanceFetcher(row.account_number, periodId),
|
||||
[row.account_number, periodId]
|
||||
)
|
||||
const { Toggle, Panel } = useReportRowExpansion(fetcher, `tb-${row.account_number}`)
|
||||
|
||||
const ob = getNetBalance(row, 'opening')
|
||||
const ch = getNetBalance(row, 'period')
|
||||
const cb = getNetBalance(row, 'closing')
|
||||
|
||||
return (
|
||||
<>
|
||||
<tr className="border-b last:border-0 hover:bg-muted/50 transition-colors">
|
||||
<td className="py-2" onClick={(e) => e.stopPropagation()}>
|
||||
<Toggle />
|
||||
</td>
|
||||
<td
|
||||
className="py-2 cursor-pointer"
|
||||
onClick={() => onNavigateToAccount(row.account_number)}
|
||||
>
|
||||
<AccountNumber number={row.account_number} name={row.account_name} />
|
||||
</td>
|
||||
<td
|
||||
className="py-2 cursor-pointer"
|
||||
onClick={() => onNavigateToAccount(row.account_number)}
|
||||
>
|
||||
{row.account_name}
|
||||
</td>
|
||||
<td className={`py-2 text-right tabular-nums ${ob < 0 ? 'text-destructive' : ''}`}>
|
||||
{formatSigned(ob)}
|
||||
</td>
|
||||
<td className={`py-2 text-right tabular-nums ${ch < 0 ? 'text-destructive' : ''}`}>
|
||||
{formatSigned(ch)}
|
||||
</td>
|
||||
<td className={`py-2 text-right tabular-nums font-medium ${cb < 0 ? 'text-destructive' : ''}`}>
|
||||
{formatSigned(cb)}
|
||||
</td>
|
||||
</tr>
|
||||
<Panel colSpan={6} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function TrialBalanceDetailedRow({
|
||||
row,
|
||||
periodId,
|
||||
onNavigateToAccount,
|
||||
}: {
|
||||
row: TrialBalanceRow
|
||||
periodId: string
|
||||
onNavigateToAccount: (account: string) => void
|
||||
}) {
|
||||
const fetcher = React.useMemo(
|
||||
() => makeTrialBalanceFetcher(row.account_number, periodId),
|
||||
[row.account_number, periodId]
|
||||
)
|
||||
const { Toggle, Panel } = useReportRowExpansion(fetcher, `tb-det-${row.account_number}`)
|
||||
|
||||
return (
|
||||
<>
|
||||
<tr className="border-b last:border-0 hover:bg-muted/50 transition-colors">
|
||||
<td className="py-2" onClick={(e) => e.stopPropagation()}>
|
||||
<Toggle />
|
||||
</td>
|
||||
<td
|
||||
className="py-2 cursor-pointer"
|
||||
onClick={() => onNavigateToAccount(row.account_number)}
|
||||
>
|
||||
<AccountNumber number={row.account_number} name={row.account_name} />
|
||||
</td>
|
||||
<td
|
||||
className="py-2 cursor-pointer"
|
||||
onClick={() => onNavigateToAccount(row.account_number)}
|
||||
>
|
||||
{row.account_name}
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
{row.period_debit > 0 ? formatAmount(row.period_debit) : ''}
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
{row.period_credit > 0 ? formatAmount(row.period_credit) : ''}
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
{row.closing_debit > 0 ? formatAmount(row.closing_debit) : ''}
|
||||
</td>
|
||||
<td className="py-2 text-right">
|
||||
{row.closing_credit > 0 ? formatAmount(row.closing_credit) : ''}
|
||||
</td>
|
||||
</tr>
|
||||
<Panel colSpan={7} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
function IncomeStatementView({ periodId, onNavigateToAccount }: { periodId: string; onNavigateToAccount: (account: string) => void }) {
|
||||
const t = useTranslations('reports')
|
||||
const [data, setData] = useState<IncomeStatementReport | null>(null)
|
||||
@@ -515,7 +641,7 @@ function IncomeStatementView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -524,6 +650,14 @@ function IncomeStatementView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
{t('download_pdf')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/income-statement/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{!monthlyLoading && monthlyData.length > 0 && (
|
||||
@@ -661,7 +795,7 @@ function BalanceSheetView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -670,6 +804,14 @@ function BalanceSheetView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
{t('download_pdf')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/balance-sheet/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Assets */}
|
||||
@@ -783,10 +925,11 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
}
|
||||
|
||||
const hasPrior = data.prior_period !== null
|
||||
const colCount = 4
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<div className="flex items-center justify-end gap-2 flex-wrap">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -795,6 +938,14 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
{t('download_pdf')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/resultatrapport/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
@@ -813,7 +964,7 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
{data.groups.map((group) => (
|
||||
<React.Fragment key={group.class}>
|
||||
<tr className="bg-muted/30">
|
||||
<td colSpan={4} className="px-4 py-2 text-[12px] font-semibold text-muted-foreground">
|
||||
<td colSpan={colCount} className="px-4 py-2 text-[12px] font-semibold text-muted-foreground">
|
||||
{group.class_label}
|
||||
</td>
|
||||
</tr>
|
||||
@@ -852,7 +1003,7 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
|
||||
<Card className="border-2">
|
||||
<CardContent className="py-4">
|
||||
<div className="grid grid-cols-[1fr_auto_auto] gap-x-6 items-baseline">
|
||||
<div className="grid gap-x-6 items-baseline grid-cols-[1fr_auto_auto]">
|
||||
<span className="font-bold text-lg">Beräknat resultat</span>
|
||||
<span className={`tabular-nums font-bold text-lg w-32 text-right ${data.net_result_current >= 0 ? 'text-success' : 'text-destructive'}`}>
|
||||
{formatAmount(data.net_result_current)} kr
|
||||
@@ -925,7 +1076,7 @@ function BalansrapportView({ periodId, onNavigateToAccount }: { periodId: string
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -934,6 +1085,14 @@ function BalansrapportView({ periodId, onNavigateToAccount }: { periodId: string
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
{t('download_pdf')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/balansrapport/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
@@ -1149,6 +1308,16 @@ function VatDeclarationView() {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/vat-declaration/xlsx?periodType=${periodType}&year=${year}&period=${period}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
{/* Period selection */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -1250,31 +1419,42 @@ function VatDeclarationView() {
|
||||
<div><table className="w-full text-sm">
|
||||
<tbody>
|
||||
{data.rutor.ruta05 > 0 && (
|
||||
<tr className="border-b">
|
||||
<td className="py-2">
|
||||
<span className="font-mono text-xs bg-muted px-1 rounded mr-2">05</span>
|
||||
Momspliktig försäljning
|
||||
</td>
|
||||
<td className="py-2 text-right">{formatAmount(data.rutor.ruta05)} kr</td>
|
||||
</tr>
|
||||
<VatRutaRow
|
||||
ruta="05"
|
||||
label="Momspliktig försäljning"
|
||||
amount={data.rutor.ruta05}
|
||||
baseAmount={0}
|
||||
periodType={periodType}
|
||||
year={year}
|
||||
period={period}
|
||||
/>
|
||||
)}
|
||||
<VatRutaRow
|
||||
ruta="10"
|
||||
label="Utgående moms 25%"
|
||||
amount={data.rutor.ruta10}
|
||||
baseAmount={data.breakdown.invoices.base25}
|
||||
periodType={periodType}
|
||||
year={year}
|
||||
period={period}
|
||||
/>
|
||||
<VatRutaRow
|
||||
ruta="11"
|
||||
label="Utgående moms 12%"
|
||||
amount={data.rutor.ruta11}
|
||||
baseAmount={data.breakdown.invoices.base12}
|
||||
periodType={periodType}
|
||||
year={year}
|
||||
period={period}
|
||||
/>
|
||||
<VatRutaRow
|
||||
ruta="12"
|
||||
label="Utgående moms 6%"
|
||||
amount={data.rutor.ruta12}
|
||||
baseAmount={data.breakdown.invoices.base6}
|
||||
periodType={periodType}
|
||||
year={year}
|
||||
period={period}
|
||||
/>
|
||||
<VatRutaRow
|
||||
ruta="39"
|
||||
@@ -1282,6 +1462,9 @@ function VatDeclarationView() {
|
||||
amount={0}
|
||||
baseAmount={data.rutor.ruta39}
|
||||
noVat
|
||||
periodType={periodType}
|
||||
year={year}
|
||||
period={period}
|
||||
/>
|
||||
<VatRutaRow
|
||||
ruta="40"
|
||||
@@ -1289,6 +1472,9 @@ function VatDeclarationView() {
|
||||
amount={0}
|
||||
baseAmount={data.rutor.ruta40}
|
||||
noVat
|
||||
periodType={periodType}
|
||||
year={year}
|
||||
period={period}
|
||||
/>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
@@ -1311,14 +1497,14 @@ function VatDeclarationView() {
|
||||
<h4 className="font-semibold mb-3 mt-6">Omvänd skattskyldighet (inköp)</h4>
|
||||
<div><table className="w-full text-sm">
|
||||
<tbody>
|
||||
<VatRutaRow ruta="20" label="Inköp av varor från annat EU-land" amount={0} baseAmount={data.rutor.ruta20} noVat />
|
||||
<VatRutaRow ruta="21" label="Inköp av tjänster från annat EU-land" amount={0} baseAmount={data.rutor.ruta21} noVat />
|
||||
<VatRutaRow ruta="22" label="Inköp av tjänster utanför EU" amount={0} baseAmount={data.rutor.ruta22} noVat />
|
||||
<VatRutaRow ruta="23" label="Inköp av varor i Sverige" amount={0} baseAmount={data.rutor.ruta23} noVat />
|
||||
<VatRutaRow ruta="24" label="Övriga inköp av tjänster i Sverige" amount={0} baseAmount={data.rutor.ruta24} noVat />
|
||||
<VatRutaRow ruta="30" label="Utgående moms 25% (omvänd)" amount={data.rutor.ruta30} baseAmount={0} />
|
||||
<VatRutaRow ruta="31" label="Utgående moms 12% (omvänd)" amount={data.rutor.ruta31} baseAmount={0} />
|
||||
<VatRutaRow ruta="32" label="Utgående moms 6% (omvänd)" amount={data.rutor.ruta32} baseAmount={0} />
|
||||
<VatRutaRow ruta="20" label="Inköp av varor från annat EU-land" amount={0} baseAmount={data.rutor.ruta20} noVat periodType={periodType} year={year} period={period} />
|
||||
<VatRutaRow ruta="21" label="Inköp av tjänster från annat EU-land" amount={0} baseAmount={data.rutor.ruta21} noVat periodType={periodType} year={year} period={period} />
|
||||
<VatRutaRow ruta="22" label="Inköp av tjänster utanför EU" amount={0} baseAmount={data.rutor.ruta22} noVat periodType={periodType} year={year} period={period} />
|
||||
<VatRutaRow ruta="23" label="Inköp av varor i Sverige" amount={0} baseAmount={data.rutor.ruta23} noVat periodType={periodType} year={year} period={period} />
|
||||
<VatRutaRow ruta="24" label="Övriga inköp av tjänster i Sverige" amount={0} baseAmount={data.rutor.ruta24} noVat periodType={periodType} year={year} period={period} />
|
||||
<VatRutaRow ruta="30" label="Utgående moms 25% (omvänd)" amount={data.rutor.ruta30} baseAmount={0} periodType={periodType} year={year} period={period} />
|
||||
<VatRutaRow ruta="31" label="Utgående moms 12% (omvänd)" amount={data.rutor.ruta31} baseAmount={0} periodType={periodType} year={year} period={period} />
|
||||
<VatRutaRow ruta="32" label="Utgående moms 6% (omvänd)" amount={data.rutor.ruta32} baseAmount={0} periodType={periodType} year={year} period={period} />
|
||||
</tbody>
|
||||
</table></div>
|
||||
</>
|
||||
@@ -1330,13 +1516,15 @@ function VatDeclarationView() {
|
||||
<h4 className="font-semibold mb-3">Ingående moms (avdragsgill)</h4>
|
||||
<div><table className="w-full text-sm">
|
||||
<tbody>
|
||||
<tr className="border-b">
|
||||
<td className="py-2">
|
||||
<span className="font-mono text-xs bg-muted px-1 rounded mr-2">48</span>
|
||||
Ingående moms att dra av
|
||||
</td>
|
||||
<td className="py-2 text-right">{formatAmount(data.rutor.ruta48)} kr</td>
|
||||
</tr>
|
||||
<VatRutaRow
|
||||
ruta="48"
|
||||
label="Ingående moms att dra av"
|
||||
amount={data.rutor.ruta48}
|
||||
baseAmount={0}
|
||||
periodType={periodType}
|
||||
year={year}
|
||||
period={period}
|
||||
/>
|
||||
{data.breakdown.transactions.ruta48 > 0 && (
|
||||
<tr className="text-muted-foreground">
|
||||
<td className="py-1 pl-6 text-xs">- från transaktioner</td>
|
||||
@@ -1411,19 +1599,49 @@ function VatDeclarationView() {
|
||||
)
|
||||
}
|
||||
|
||||
function makeVatFetcher(ruta: string, periodType: VatPeriodType, year: number, period: number): ReportSourceFetcher {
|
||||
return async () => {
|
||||
const res = await fetch(
|
||||
`/api/reports/vat-declaration/ruta/${encodeURIComponent(ruta)}/sources?periodType=${periodType}&year=${year}&period=${period}`
|
||||
)
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error || 'Kunde inte hämta verifikat')
|
||||
const lines: ReportSourceLine[] = json.data?.lines || []
|
||||
return { lines, next_cursor: json.data?.next_cursor ?? null }
|
||||
}
|
||||
}
|
||||
|
||||
function VatRutaRow({
|
||||
ruta,
|
||||
label,
|
||||
amount,
|
||||
baseAmount,
|
||||
noVat,
|
||||
periodType,
|
||||
year,
|
||||
period,
|
||||
}: {
|
||||
ruta: string
|
||||
label: string
|
||||
amount: number
|
||||
baseAmount: number
|
||||
noVat?: boolean
|
||||
periodType?: VatPeriodType
|
||||
year?: number
|
||||
period?: number
|
||||
}) {
|
||||
const canDrill = periodType !== undefined && year !== undefined && period !== undefined
|
||||
const fetcher = React.useMemo(
|
||||
() => (canDrill ? makeVatFetcher(ruta, periodType!, year!, period!) : null),
|
||||
[canDrill, ruta, periodType, year, period]
|
||||
)
|
||||
// Hooks must be called unconditionally — provide a noop fetcher when drill
|
||||
// is disabled. The early-return for zero rows lives below the hooks.
|
||||
const expansion = useReportRowExpansion(
|
||||
fetcher ?? (async () => ({ lines: [], next_cursor: null })),
|
||||
`vat-${ruta}`
|
||||
)
|
||||
|
||||
// Don't show rows with zero values
|
||||
if (baseAmount === 0 && amount === 0) return null
|
||||
|
||||
@@ -1431,17 +1649,23 @@ function VatRutaRow({
|
||||
<>
|
||||
<tr className="border-b">
|
||||
<td className="py-2">
|
||||
{canDrill && (
|
||||
<span className="inline-block align-middle mr-1">
|
||||
<expansion.Toggle />
|
||||
</span>
|
||||
)}
|
||||
<span className="font-mono text-xs bg-muted px-1 rounded mr-2">{ruta}</span>
|
||||
{label}
|
||||
</td>
|
||||
<td className="py-2 text-right">{noVat ? `${formatAmount(baseAmount)} kr` : `${formatAmount(amount)} kr`}</td>
|
||||
<td className="py-2 text-right tabular-nums">{noVat ? `${formatAmount(baseAmount)} kr` : `${formatAmount(amount)} kr`}</td>
|
||||
</tr>
|
||||
{!noVat && baseAmount > 0 && (
|
||||
<tr className="text-muted-foreground">
|
||||
<td className="py-1 pl-6 text-xs">Underlag</td>
|
||||
<td className="py-1 text-right text-xs">{formatAmount(baseAmount)} kr</td>
|
||||
<td className="py-1 text-right text-xs tabular-nums">{formatAmount(baseAmount)} kr</td>
|
||||
</tr>
|
||||
)}
|
||||
{canDrill && <expansion.Panel colSpan={2} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1535,6 +1759,16 @@ function SupplierLedgerView({ periodId }: { periodId: string }) {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/supplier-ledger/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
{/* Summary cards */}
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<Card>
|
||||
@@ -1579,6 +1813,7 @@ function SupplierLedgerView({ periodId }: { periodId: string }) {
|
||||
<div className="overflow-x-auto -mx-2 px-2"><table className="w-full text-sm min-w-[500px]">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b text-left">
|
||||
<th className="py-2 w-8"></th>
|
||||
<th className="py-2">Leverantör</th>
|
||||
<th className="py-2 text-right">Ej förfallet</th>
|
||||
<th className="py-2 text-right">1-30 dagar</th>
|
||||
@@ -1590,19 +1825,12 @@ function SupplierLedgerView({ periodId }: { periodId: string }) {
|
||||
</thead>
|
||||
<tbody>
|
||||
{ledger.entries.map((entry) => (
|
||||
<tr key={entry.supplier_id} className="border-b last:border-0">
|
||||
<td className="py-2">{entry.supplier_name}</td>
|
||||
<td className="py-2 text-right">{entry.current > 0 ? formatAmount(entry.current) : ''}</td>
|
||||
<td className="py-2 text-right">{entry.days_1_30 > 0 ? formatAmount(entry.days_1_30) : ''}</td>
|
||||
<td className="py-2 text-right">{entry.days_31_60 > 0 ? formatAmount(entry.days_31_60) : ''}</td>
|
||||
<td className="py-2 text-right">{entry.days_61_90 > 0 ? formatAmount(entry.days_61_90) : ''}</td>
|
||||
<td className="py-2 text-right text-destructive">{entry.days_90_plus > 0 ? formatAmount(entry.days_90_plus) : ''}</td>
|
||||
<td className="py-2 text-right font-semibold">{formatAmount(entry.total_outstanding)}</td>
|
||||
</tr>
|
||||
<SupplierLedgerRow key={entry.supplier_id} entry={entry} />
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="font-semibold border-t-2">
|
||||
<td className="py-2"></td>
|
||||
<td className="py-2">Summa</td>
|
||||
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.current, 0))}</td>
|
||||
<td className="py-2 text-right">{formatAmount(ledger.entries.reduce((s, e) => s + e.days_1_30, 0))}</td>
|
||||
@@ -1659,6 +1887,54 @@ function SupplierLedgerView({ periodId }: { periodId: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
function makeSupplierFetcher(supplierId: string): ReportSourceFetcher {
|
||||
return async () => {
|
||||
const res = await fetch(
|
||||
`/api/reports/supplier-ledger/supplier/${encodeURIComponent(supplierId)}/invoices`
|
||||
)
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error || 'Kunde inte hämta leverantörsfakturor')
|
||||
const lines: ReportSourceLine[] = json.data?.lines || []
|
||||
return { lines, next_cursor: json.data?.next_cursor ?? null }
|
||||
}
|
||||
}
|
||||
|
||||
function SupplierLedgerRow({
|
||||
entry,
|
||||
}: {
|
||||
entry: {
|
||||
supplier_id: string
|
||||
supplier_name: string
|
||||
current: number
|
||||
days_1_30: number
|
||||
days_31_60: number
|
||||
days_61_90: number
|
||||
days_90_plus: number
|
||||
total_outstanding: number
|
||||
}
|
||||
}) {
|
||||
const fetcher = React.useMemo(
|
||||
() => makeSupplierFetcher(entry.supplier_id),
|
||||
[entry.supplier_id]
|
||||
)
|
||||
const { Toggle, Panel } = useReportRowExpansion(fetcher, `sup-${entry.supplier_id}`)
|
||||
return (
|
||||
<>
|
||||
<tr className="border-b last:border-0 hover:bg-muted/30 transition-colors">
|
||||
<td className="py-2"><Toggle /></td>
|
||||
<td className="py-2">{entry.supplier_name}</td>
|
||||
<td className="py-2 text-right tabular-nums">{entry.current > 0 ? formatAmount(entry.current) : ''}</td>
|
||||
<td className="py-2 text-right tabular-nums">{entry.days_1_30 > 0 ? formatAmount(entry.days_1_30) : ''}</td>
|
||||
<td className="py-2 text-right tabular-nums">{entry.days_31_60 > 0 ? formatAmount(entry.days_31_60) : ''}</td>
|
||||
<td className="py-2 text-right tabular-nums">{entry.days_61_90 > 0 ? formatAmount(entry.days_61_90) : ''}</td>
|
||||
<td className="py-2 text-right tabular-nums text-destructive">{entry.days_90_plus > 0 ? formatAmount(entry.days_90_plus) : ''}</td>
|
||||
<td className="py-2 text-right tabular-nums font-semibold">{formatAmount(entry.total_outstanding)}</td>
|
||||
</tr>
|
||||
<Panel colSpan={8} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// --- General Ledger (Huvudbok) ---
|
||||
|
||||
interface GeneralLedgerData {
|
||||
@@ -1758,6 +2034,16 @@ function GeneralLedgerView({ periodId, initialAccountFilter }: { periodId: strin
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/general-ledger/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
{/* Account range filter */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
@@ -1827,7 +2113,7 @@ function GeneralLedgerView({ periodId, initialAccountFilter }: { periodId: strin
|
||||
href={`/bookkeeping/${line.journal_entry_id}`}
|
||||
className="text-foreground underline underline-offset-4 decoration-muted-foreground/40 hover:decoration-foreground transition-colors"
|
||||
>
|
||||
{line.voucher_series}{line.voucher_number}
|
||||
{formatVoucher(line)}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="py-1.5">{line.date}</td>
|
||||
@@ -1957,6 +2243,16 @@ function JournalRegisterView({ periodId }: { periodId: string }) {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/journal-register/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
{data.period.start && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Period: {data.period.start} — {data.period.end} | {data.total_entries} verifikationer
|
||||
@@ -1999,7 +2295,7 @@ function JournalRegisterView({ periodId }: { periodId: string }) {
|
||||
)}
|
||||
</td>
|
||||
<td className="py-2 font-mono text-xs">
|
||||
{entry.voucher_series}{entry.voucher_number}
|
||||
{formatVoucher(entry)}
|
||||
</td>
|
||||
<td className="py-2">{entry.date}</td>
|
||||
<td className="py-2">
|
||||
@@ -2086,6 +2382,102 @@ interface ARLedgerData {
|
||||
} | null
|
||||
}
|
||||
|
||||
// Inner expansion row component for AR ledger.
|
||||
// Fetches per-customer invoices (with journal_entry_id) and renders each as a
|
||||
// link to /bookkeeping/[id] when posted, /invoices/[id] when still draft.
|
||||
function ARCustomerInvoiceRows({
|
||||
customerId,
|
||||
invoices,
|
||||
}: {
|
||||
customerId: string
|
||||
invoices: {
|
||||
invoice_id: string
|
||||
invoice_number: string
|
||||
invoice_date: string
|
||||
due_date: string
|
||||
total: number
|
||||
paid_amount: number
|
||||
outstanding: number
|
||||
outstanding_sek: number | null
|
||||
days_overdue: number
|
||||
currency: string
|
||||
}[]
|
||||
}) {
|
||||
// ARCustomerInvoiceRows is mounted lazily — only when a customer is
|
||||
// expanded, so initial state matches "still loading" and resets on
|
||||
// unmount. No synchronous setState in the effect is needed.
|
||||
const [enriched, setEnriched] = useState<Record<string, { journal_entry_id: string; voucher_series: string; voucher_number: number } | undefined>>({})
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch(`/api/reports/ar-ledger/customer/${encodeURIComponent(customerId)}/invoices`)
|
||||
.then((r) => r.json())
|
||||
.then((json) => {
|
||||
if (cancelled) return
|
||||
const map: typeof enriched = {}
|
||||
for (const line of json.data?.lines || []) {
|
||||
if (line.invoice_id && line.journal_entry_id) {
|
||||
map[line.invoice_id] = {
|
||||
journal_entry_id: line.journal_entry_id,
|
||||
voucher_series: line.voucher_series,
|
||||
voucher_number: line.voucher_number,
|
||||
}
|
||||
}
|
||||
}
|
||||
setEnriched(map)
|
||||
})
|
||||
.catch(() => { /* fail silently; rows still render without verifikat link */ })
|
||||
.finally(() => { if (!cancelled) setLoaded(true) })
|
||||
return () => { cancelled = true }
|
||||
}, [customerId])
|
||||
const loading = !loaded
|
||||
|
||||
return (
|
||||
<>
|
||||
{invoices.map((inv) => {
|
||||
const entry = enriched[inv.invoice_id]
|
||||
const targetHref = entry?.journal_entry_id
|
||||
? `/bookkeeping/${entry.journal_entry_id}`
|
||||
: `/invoices/${inv.invoice_id}`
|
||||
return (
|
||||
<tr key={inv.invoice_id} className="bg-muted/30 border-b last:border-0">
|
||||
<td></td>
|
||||
<td className="py-1 text-xs" colSpan={2}>
|
||||
<Link href={targetHref} className="font-mono hover:underline underline-offset-4">
|
||||
{inv.invoice_number || '(utkast)'}
|
||||
</Link>
|
||||
{entry && (
|
||||
<span className="ml-2 text-muted-foreground font-mono">
|
||||
{formatVoucher(entry)}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-muted-foreground ml-2 tabular-nums">{formatDate(inv.invoice_date)}</span>
|
||||
<span className="text-muted-foreground ml-2 tabular-nums">förfaller {formatDate(inv.due_date)}</span>
|
||||
</td>
|
||||
<td className="py-1 text-right text-xs text-muted-foreground" colSpan={2}>
|
||||
{inv.days_overdue > 0 ? `${inv.days_overdue} dagar förfallen` : 'Ej förfallen'}
|
||||
</td>
|
||||
<td className="py-1 text-right text-xs text-muted-foreground">
|
||||
{inv.paid_amount > 0 ? `Betalt: ${formatAmount(inv.paid_amount)}` : ''}
|
||||
</td>
|
||||
<td></td>
|
||||
<td className="py-1 text-right text-xs font-medium tabular-nums">
|
||||
{formatAmount(inv.outstanding)} {inv.currency}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
{loading && (
|
||||
<tr className="bg-muted/30">
|
||||
<td></td>
|
||||
<td colSpan={7} className="py-1 text-[10px] text-muted-foreground">Letar verifikat…</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ARLedgerView({ periodId }: { periodId: string }) {
|
||||
const [data, setData] = useState<ARLedgerData | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
@@ -2161,6 +2553,16 @@ function ARLedgerView({ periodId }: { periodId: string }) {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => window.open(`/api/reports/ar-ledger/xlsx?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<FileSpreadsheet className="h-4 w-4 mr-2" />
|
||||
Ladda ner Excel
|
||||
</Button>
|
||||
</div>
|
||||
{/* Summary cards */}
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<Card>
|
||||
@@ -2239,26 +2641,12 @@ function ARLedgerView({ periodId }: { periodId: string }) {
|
||||
<td className="py-2 text-right text-destructive">{entry.days_90_plus > 0 ? formatAmount(entry.days_90_plus) : ''}</td>
|
||||
<td className="py-2 text-right font-semibold">{formatAmount(entry.total_outstanding)}</td>
|
||||
</tr>
|
||||
{isExpanded && entry.invoices.map((inv) => (
|
||||
<tr key={inv.invoice_id} className="bg-muted/30 border-b last:border-0">
|
||||
<td></td>
|
||||
<td className="py-1 text-xs" colSpan={2}>
|
||||
<span className="font-mono">{inv.invoice_number}</span>
|
||||
<span className="text-muted-foreground ml-2 tabular-nums">{formatDate(inv.invoice_date)}</span>
|
||||
<span className="text-muted-foreground ml-2 tabular-nums">förfaller {formatDate(inv.due_date)}</span>
|
||||
</td>
|
||||
<td className="py-1 text-right text-xs text-muted-foreground" colSpan={2}>
|
||||
{inv.days_overdue > 0 ? `${inv.days_overdue} dagar förfallen` : 'Ej förfallen'}
|
||||
</td>
|
||||
<td className="py-1 text-right text-xs text-muted-foreground">
|
||||
{inv.paid_amount > 0 ? `Betalt: ${formatAmount(inv.paid_amount)}` : ''}
|
||||
</td>
|
||||
<td></td>
|
||||
<td className="py-1 text-right text-xs font-medium">
|
||||
{formatAmount(inv.outstanding)} {inv.currency}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{isExpanded && (
|
||||
<ARCustomerInvoiceRows
|
||||
customerId={entry.customer_id}
|
||||
invoices={entry.invoices}
|
||||
/>
|
||||
)}
|
||||
</React.Fragment>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -13,6 +13,12 @@ const LINE_ITEM_TYPE_LABELS: Record<SalaryLineItemType, string> = {
|
||||
monthly_salary: 'Månadslön',
|
||||
hourly_salary: 'Timlön',
|
||||
overtime: 'Övertid',
|
||||
overtime_50: 'Övertid 50 %',
|
||||
overtime_100: 'Övertid 100 %',
|
||||
ob_weekday_evening: 'OB vardag kväll',
|
||||
ob_weekend: 'OB helg',
|
||||
ob_night: 'OB natt',
|
||||
ob_holiday: 'OB helgdag',
|
||||
bonus: 'Bonus',
|
||||
commission: 'Provision',
|
||||
gross_deduction_pension: 'Bruttoavdrag — pension',
|
||||
|
||||
@@ -1,21 +1,34 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
|
||||
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
|
||||
import { PeriodLockingSettings } from '@/components/settings/PeriodLockingSettings'
|
||||
import { VoucherSeriesManager } from '@/components/settings/VoucherSeriesManager'
|
||||
import { VoucherSeriesPerSourceTypeForm } from '@/components/settings/VoucherSeriesPerSourceTypeForm'
|
||||
import { PeriodiseringAutoDetectToggle } from '@/components/settings/PeriodiseringAutoDetectToggle'
|
||||
import { AccountingFrameworkForm } from '@/components/settings/AccountingFrameworkForm'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { ExternalLink } from 'lucide-react'
|
||||
import type { CompanySettings } from '@/types'
|
||||
import type { AccountingFramework, CompanySettings } from '@/types'
|
||||
|
||||
const SERIES_OPTIONS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
|
||||
|
||||
export default function BookkeepingSettingsPage() {
|
||||
const t = useTranslations('settings_bookkeeping')
|
||||
const { settings, isLoading, updateSettings } = useSettings()
|
||||
const { company } = useCompany()
|
||||
// Local mirror of the company-level accounting_framework so the K2/K3
|
||||
// selector can reflect its own saves without waiting for the layout to
|
||||
// re-render through the server. Falls back to k2 (matches the column
|
||||
// default) until the company row is loaded.
|
||||
const [framework, setFramework] = useState<AccountingFramework>(
|
||||
company?.accounting_framework ?? 'k2',
|
||||
)
|
||||
|
||||
if (isLoading || !settings) return <SettingsLoadingSkeleton />
|
||||
|
||||
@@ -39,8 +52,19 @@ export default function BookkeepingSettingsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
// K2/K3 selector is only meaningful for AB. EF stays on EF rules and never
|
||||
// picks a framework. Use the company row (source of truth) since
|
||||
// company_settings.entity_type can be stale on legacy data.
|
||||
const isAktiebolag = company?.entity_type === 'aktiebolag'
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{isAktiebolag && (
|
||||
<AccountingFrameworkForm
|
||||
current={framework}
|
||||
onSaved={(next) => setFramework(next)}
|
||||
/>
|
||||
)}
|
||||
<SettingsFormWrapper onSave={handleSave} className="space-y-8">
|
||||
{/* Accounting method */}
|
||||
<section className="space-y-4">
|
||||
@@ -95,11 +119,24 @@ export default function BookkeepingSettingsPage() {
|
||||
</div>
|
||||
</SettingsFormWrapper>
|
||||
|
||||
{/* Voucher series — per-source-type mapping */}
|
||||
<div className="border-t border-border/8 pt-8">
|
||||
<VoucherSeriesPerSourceTypeForm
|
||||
settings={settings}
|
||||
onSettingsUpdated={updateSettings}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Voucher series — read-only display */}
|
||||
<div className="border-t border-border/8 pt-8">
|
||||
<VoucherSeriesManager defaultSeries={settings.default_voucher_series || 'A'} />
|
||||
</div>
|
||||
|
||||
{/* Periodisering auto-detect toggle */}
|
||||
<div className="border-t border-border/8 pt-8">
|
||||
<PeriodiseringAutoDetectToggle />
|
||||
</div>
|
||||
|
||||
{/* Cross-links */}
|
||||
<div className="border-t border-border/8 pt-8 space-y-3">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
|
||||
@@ -14,6 +14,7 @@ const TAB_TO_ROUTE: Record<string, string> = {
|
||||
team: '/settings/team',
|
||||
banking: '/settings/banking',
|
||||
templates: '/settings/templates',
|
||||
'approval-rules': '/settings/approval-rules',
|
||||
account: '/settings/account',
|
||||
api: '/settings/api',
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
} from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import {
|
||||
Copy,
|
||||
ExternalLink,
|
||||
@@ -517,7 +518,10 @@ function TransactionTable({
|
||||
<p className="mt-1 text-xs text-warning">
|
||||
Möjlig dublett av{' '}
|
||||
{row.match_suggestion.voucher_series && row.match_suggestion.voucher_number
|
||||
? `${row.match_suggestion.voucher_series}${row.match_suggestion.voucher_number}`
|
||||
? formatVoucher({
|
||||
voucher_series: row.match_suggestion.voucher_series,
|
||||
voucher_number: row.match_suggestion.voucher_number,
|
||||
})
|
||||
: 'utkast'}{' '}
|
||||
({row.match_suggestion.entry_date})
|
||||
</p>
|
||||
@@ -647,9 +651,7 @@ function MatchDialog({
|
||||
<TableRow key={c.journal_entry_id}>
|
||||
<TableCell className="tabular-nums">{c.entry_date}</TableCell>
|
||||
<TableCell className="tabular-nums">
|
||||
{c.voucher_series && c.voucher_number
|
||||
? `${c.voucher_series}${c.voucher_number}`
|
||||
: '–'}
|
||||
{formatVoucher(c)}
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[260px] truncate">
|
||||
{c.description}
|
||||
|
||||
@@ -22,6 +22,14 @@ interface InvoiceData {
|
||||
reminderLevel: number
|
||||
alreadyResponded: boolean
|
||||
previousResponse: 'marked_paid' | 'disputed' | null
|
||||
// Dröjsmålsränta + lagstadgad påminnelseavgift (Räntelagen §6, Lag 1981:739).
|
||||
// Default to 0 for older reminders sent before the surcharge feature shipped.
|
||||
interestAmount: number
|
||||
interestRate: number
|
||||
interestFromDate: string | null
|
||||
interestDays: number | null
|
||||
reminderFee: number
|
||||
totalDue: number
|
||||
}
|
||||
|
||||
export default function InvoiceActionPage({ params }: { params: Promise<{ token: string }> }) {
|
||||
@@ -179,13 +187,46 @@ export default function InvoiceActionPage({ params }: { params: Promise<{ token:
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-destructive/5 border border-destructive/15 rounded-lg p-4">
|
||||
<p className="text-sm text-destructive mb-1">
|
||||
<div className="bg-destructive/5 border border-destructive/15 rounded-lg p-4 space-y-3">
|
||||
<p className="text-sm text-destructive">
|
||||
Förfallen med {daysOverdue} dagar
|
||||
</p>
|
||||
<p className="text-2xl font-bold text-destructive">
|
||||
{formatCurrency(invoice.total, invoice.currency)}
|
||||
|
||||
{(invoice.interestAmount > 0 || invoice.reminderFee > 0) && (
|
||||
<div className="space-y-1 text-sm tabular-nums">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Ursprungligt belopp</span>
|
||||
<span>{formatCurrency(invoice.total, invoice.currency)}</span>
|
||||
</div>
|
||||
{invoice.interestAmount > 0 && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">
|
||||
Dröjsmålsränta
|
||||
{invoice.interestRate > 0 && invoice.interestDays != null
|
||||
? ` (${(invoice.interestRate * 100).toLocaleString('sv-SE', { maximumFractionDigits: 2 })}% per år, ${invoice.interestDays} dagar)`
|
||||
: ''}
|
||||
</span>
|
||||
<span>{formatCurrency(invoice.interestAmount, invoice.currency)}</span>
|
||||
</div>
|
||||
)}
|
||||
{invoice.reminderFee > 0 && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Påminnelseavgift</span>
|
||||
<span>{formatCurrency(invoice.reminderFee, invoice.currency)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="border-t border-destructive/20 pt-2 mt-2" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-2xl font-bold text-destructive tabular-nums">
|
||||
{formatCurrency(invoice.totalDue || invoice.total, invoice.currency)}
|
||||
</p>
|
||||
{(invoice.interestAmount > 0 || invoice.reminderFee > 0) && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Att betala (inkl. dröjsmålsränta och påminnelseavgift)
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
|
||||
@@ -12,8 +12,10 @@ import { POST } from '../route'
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
const mockCreateServiceClient = vi.mocked(createServiceClient)
|
||||
|
||||
type AuthMetadata = Record<string, unknown>
|
||||
|
||||
function mockUserClient(opts: {
|
||||
user: { id: string } | null
|
||||
user: { id: string; app_metadata?: AuthMetadata } | null
|
||||
updateUserError?: { message: string; status?: number; code?: string } | null
|
||||
}) {
|
||||
const updateUser = vi.fn().mockResolvedValue({
|
||||
@@ -33,12 +35,24 @@ function mockUserClient(opts: {
|
||||
}
|
||||
|
||||
function mockService(opts: {
|
||||
priorAppMetadata?: Record<string, unknown>
|
||||
updateUserByIdError?: Error | null
|
||||
priorAppMetadata?: AuthMetadata
|
||||
// Returned-error from admin.updateUserById when called with { password }
|
||||
passwordSetError?: { message: string; status?: number; code?: string } | null
|
||||
// Thrown error from admin.updateUserById when called with { app_metadata }
|
||||
flagFlipError?: Error | null
|
||||
}) {
|
||||
const updateUserById = opts.updateUserByIdError
|
||||
? vi.fn().mockRejectedValue(opts.updateUserByIdError)
|
||||
: vi.fn().mockResolvedValue({ data: {}, error: null })
|
||||
const updateUserById = vi
|
||||
.fn()
|
||||
.mockImplementation((_id: string, args: Record<string, unknown>) => {
|
||||
if ('password' in args) {
|
||||
return Promise.resolve({
|
||||
data: {},
|
||||
error: opts.passwordSetError ?? null,
|
||||
})
|
||||
}
|
||||
if (opts.flagFlipError) return Promise.reject(opts.flagFlipError)
|
||||
return Promise.resolve({ data: {}, error: null })
|
||||
})
|
||||
|
||||
const getUserById = vi.fn().mockResolvedValue({
|
||||
data: { user: { app_metadata: opts.priorAppMetadata ?? {} } },
|
||||
@@ -54,6 +68,18 @@ function mockService(opts: {
|
||||
|
||||
const STRONG_PASSWORD = 'StrongP@ssword1'
|
||||
|
||||
function flagFlipCall(updateUserById: ReturnType<typeof vi.fn>) {
|
||||
return updateUserById.mock.calls.find(
|
||||
([, args]) => args && typeof args === 'object' && 'app_metadata' in args,
|
||||
)
|
||||
}
|
||||
|
||||
function passwordSetCall(updateUserById: ReturnType<typeof vi.fn>) {
|
||||
return updateUserById.mock.calls.find(
|
||||
([, args]) => args && typeof args === 'object' && 'password' in args,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
@@ -72,8 +98,8 @@ describe('POST /api/account/password', () => {
|
||||
})
|
||||
|
||||
it('returns 400 when password is too weak', async () => {
|
||||
mockUserClient({ user: { id: 'user-1' } })
|
||||
mockService({})
|
||||
mockUserClient({ user: { id: 'user-1', app_metadata: { has_password: true } } })
|
||||
mockService({ priorAppMetadata: { has_password: true } })
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
@@ -83,65 +109,187 @@ describe('POST /api/account/password', () => {
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 when Supabase rejects the password update', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1' },
|
||||
updateUserError: { message: 'Password too similar to old', status: 400 },
|
||||
})
|
||||
const { updateUserById } = mockService({})
|
||||
describe('first-time set (has_password !== true)', () => {
|
||||
it('writes the password via admin API and flips the flag', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: {
|
||||
id: 'user-1',
|
||||
app_metadata: { has_password: false, bankid_linked: true },
|
||||
},
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: false, bankid_linked: true },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('Password too similar')
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
// Flag should NOT be flipped on a failed password update
|
||||
expect(updateUserById).not.toHaveBeenCalled()
|
||||
})
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
it('flips app_metadata.has_password to true on success and preserves siblings', async () => {
|
||||
const { updateUser } = mockUserClient({ user: { id: 'user-1' } })
|
||||
const { getUserById, updateUserById } = mockService({
|
||||
priorAppMetadata: { bankid_linked: true, provider: 'email' },
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
// Did NOT go through the user session — that path would fail with AAL2.
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
// Password set via admin
|
||||
expect(passwordSetCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{ password: STRONG_PASSWORD },
|
||||
])
|
||||
// Flag flipped, siblings preserved
|
||||
expect(flagFlipCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{
|
||||
app_metadata: {
|
||||
has_password: true,
|
||||
bankid_linked: true,
|
||||
},
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
it('treats unset has_password as first-time set', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1' /* no app_metadata */ },
|
||||
})
|
||||
const { updateUserById } = mockService({})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
expect(passwordSetCall(updateUserById)).toBeDefined()
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data?: { ok: boolean } }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(getUserById).toHaveBeenCalledWith('user-1')
|
||||
expect(updateUserById).toHaveBeenCalledWith('user-1', {
|
||||
app_metadata: {
|
||||
bankid_linked: true,
|
||||
provider: 'email',
|
||||
has_password: true,
|
||||
},
|
||||
|
||||
it('returns 400 and skips flag flip when the admin password set fails', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: false } },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: false },
|
||||
passwordSetError: { message: 'Password too weak', status: 400 },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('Password too weak')
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
expect(flagFlipCall(updateUserById)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('still returns success when the flag flip fails after admin password set', async () => {
|
||||
mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: false } },
|
||||
})
|
||||
mockService({
|
||||
priorAppMetadata: { has_password: false },
|
||||
flagFlipError: new Error('admin down'),
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('still returns success when the flag flip fails (password is set; logged)', async () => {
|
||||
mockUserClient({ user: { id: 'user-1' } })
|
||||
mockService({ updateUserByIdError: new Error('admin down') })
|
||||
describe('change-password (has_password === true)', () => {
|
||||
it('writes via the user session so Supabase enforces AAL2', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: true, provider: 'email' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
// Used user session, NOT admin API for the password itself
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(passwordSetCall(updateUserById)).toBeUndefined()
|
||||
// Flag is still flipped (idempotent) with siblings preserved
|
||||
expect(flagFlipCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{
|
||||
app_metadata: {
|
||||
has_password: true,
|
||||
provider: 'email',
|
||||
},
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('returns 400 and skips flag flip when Supabase rejects the password update', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
updateUserError: { message: 'Password too similar to old', status: 400 },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: true },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('Password too similar')
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(flagFlipCall(updateUserById)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('surfaces the AAL2 error verbatim so the client can step up via /mfa/verify', async () => {
|
||||
mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
updateUserError: {
|
||||
message:
|
||||
'AAL2 session is required to update email or password when MFA is enabled',
|
||||
status: 422,
|
||||
},
|
||||
})
|
||||
mockService({ priorAppMetadata: { has_password: true } })
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('AAL2')
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data?: { ok: boolean } }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -23,12 +23,25 @@ const SetPasswordSchema = z.object({
|
||||
/**
|
||||
* POST /api/account/password
|
||||
*
|
||||
* Server-routed password set/change. Wraps `supabase.auth.updateUser({ password })`
|
||||
* on the user's own session, then flips `app_metadata.has_password = true` via the
|
||||
* service client (clients can't write app_metadata).
|
||||
* Server-routed password set/change, then flips `app_metadata.has_password =
|
||||
* true` via the service client (clients can't write app_metadata).
|
||||
*
|
||||
* Two paths depending on whether the user already has a real password:
|
||||
*
|
||||
* - First-time set (`app_metadata.has_password !== true`): write via the
|
||||
* admin API. BankID-only users — and legacy users whose `has_password`
|
||||
* flag was set to false by the backfill — sit at AAL1 with a TOTP factor
|
||||
* enrolled, and `updateUser` on the user session would be rejected with
|
||||
* "AAL2 session is required to update email or password when MFA is
|
||||
* enabled". Setting an initial password has no existing credential to
|
||||
* protect, so bypassing AAL2 is safe.
|
||||
*
|
||||
* - Change-password (`app_metadata.has_password === true`): write via the
|
||||
* user session so Supabase's AAL2 guard still fires. A stolen AAL1
|
||||
* cookie must not be able to rotate a known password.
|
||||
*
|
||||
* This route is the single write path for setting a password. SecuritySettings,
|
||||
* the reset-password page, and the new /account/set-password page all funnel
|
||||
* the reset-password page, and the /account/set-password page all funnel
|
||||
* through here so the flag stays in sync — see lib/auth/has-password.ts.
|
||||
*
|
||||
* If the password update succeeds but the flag write fails, we log and still
|
||||
@@ -49,11 +62,29 @@ export async function POST(request: Request) {
|
||||
if (!result.success) return result.response
|
||||
const { password } = result.data
|
||||
|
||||
const { error: updateError } = await supabase.auth.updateUser({ password })
|
||||
const isFirstTimeSet = user.app_metadata?.has_password !== true
|
||||
const service = createServiceClient()
|
||||
|
||||
let updateError:
|
||||
| { message?: string; status?: number; code?: string }
|
||||
| null
|
||||
| undefined = null
|
||||
|
||||
if (isFirstTimeSet) {
|
||||
const { error } = await service.auth.admin.updateUserById(user.id, {
|
||||
password,
|
||||
})
|
||||
updateError = error
|
||||
} else {
|
||||
const { error } = await supabase.auth.updateUser({ password })
|
||||
updateError = error
|
||||
}
|
||||
|
||||
if (updateError) {
|
||||
log.warn('updateUser({password}) failed', {
|
||||
log.warn('password update failed', {
|
||||
userId: user.id,
|
||||
code: (updateError as { code?: string }).code,
|
||||
isFirstTimeSet,
|
||||
code: updateError.code,
|
||||
status: updateError.status,
|
||||
})
|
||||
return NextResponse.json(
|
||||
@@ -69,7 +100,6 @@ export async function POST(request: Request) {
|
||||
// Read-merge-write so we don't wipe sibling app_metadata keys.
|
||||
// updateUserById replaces app_metadata wholesale (see lib/auth/has-password.ts
|
||||
// and the comment in app/api/account/delete/route.ts).
|
||||
const service = createServiceClient()
|
||||
let flagWriteOk = false
|
||||
try {
|
||||
const { data: u } = await service.auth.admin.getUserById(user.id)
|
||||
@@ -87,7 +117,7 @@ export async function POST(request: Request) {
|
||||
// banner will show once more and a retry will succeed.
|
||||
}
|
||||
|
||||
log.info('password set', { userId: user.id, flagWriteOk })
|
||||
log.info('password set', { userId: user.id, isFirstTimeSet, flagWriteOk })
|
||||
|
||||
return NextResponse.json({ data: { ok: true } })
|
||||
}
|
||||
|
||||
@@ -5,15 +5,87 @@ import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { disposeAsset } from '@/lib/bokslut/assets/asset-service'
|
||||
|
||||
const DisposeAssetSchema = z.object({
|
||||
disposed_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
disposed_proceeds: z.number().nonnegative(),
|
||||
proceeds_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
fiscal_period_id: z.string().uuid(),
|
||||
// accumulated_depreciation is intentionally NOT accepted from the client —
|
||||
// disposeAsset sums depreciation_schedules server-side so callers cannot
|
||||
// inflate the book-value calculation.
|
||||
})
|
||||
const VAT_TREATMENTS = [
|
||||
'standard_25',
|
||||
'reduced_12',
|
||||
'reduced_6',
|
||||
'reverse_charge',
|
||||
'export',
|
||||
'exempt',
|
||||
] as const
|
||||
|
||||
const DisposeAssetSchema = z
|
||||
.object({
|
||||
disposed_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
/** Gross proceeds (INCL VAT when applicable). */
|
||||
disposed_proceeds: z.number().nonnegative(),
|
||||
proceeds_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
fiscal_period_id: z.string().uuid(),
|
||||
/** Output VAT on the proceeds. Defaults to 0 (sale was momsfri). */
|
||||
proceeds_vat: z.number().nonnegative().optional(),
|
||||
/** Required when proceeds_vat > 0 so the engine can resolve a 26xx account. */
|
||||
vat_treatment: z.enum(VAT_TREATMENTS).optional(),
|
||||
/** Precomputed jämkning amount (ML 8a kap 7 §). Caller supplies; engine
|
||||
* books a 2641 credit + loss-account debit. */
|
||||
jamkning_amount: z.number().nonnegative().optional(),
|
||||
/** Audit metadata. */
|
||||
jamkning_remaining_months: z.number().int().nonnegative().optional(),
|
||||
jamkning_total_months: z.number().int().positive().optional(),
|
||||
jamkning_original_input_vat: z.number().nonnegative().optional(),
|
||||
// accumulated_depreciation is intentionally NOT accepted from the client —
|
||||
// disposeAsset sums depreciation_schedules server-side so callers cannot
|
||||
// inflate the book-value calculation.
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
// VAT consistency: if a treatment that produces a VAT line is selected,
|
||||
// the VAT amount must equal 25%/12%/6% of the net proceeds. Tolerance is
|
||||
// ±0.50 kr to handle rounding on item prices.
|
||||
if (value.proceeds_vat && value.proceeds_vat > 0) {
|
||||
if (!value.vat_treatment) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['vat_treatment'],
|
||||
message: 'vat_treatment krävs när proceeds_vat > 0.',
|
||||
})
|
||||
return
|
||||
}
|
||||
const rate = vatRateFromTreatment(value.vat_treatment)
|
||||
if (rate === null) {
|
||||
// Treatments without a VAT line must carry 0 VAT.
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['proceeds_vat'],
|
||||
message: `proceeds_vat måste vara 0 för momsbehandling "${value.vat_treatment}".`,
|
||||
})
|
||||
return
|
||||
}
|
||||
// Expected: proceeds_gross = net × (1 + rate), so net = gross / (1 + rate)
|
||||
// and vat = gross - net = gross × rate / (1 + rate).
|
||||
const expectedVat = (value.disposed_proceeds * rate) / (1 + rate)
|
||||
if (Math.abs(expectedVat - value.proceeds_vat) > 0.5) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['proceeds_vat'],
|
||||
message: `proceeds_vat ska vara ~${Math.round(expectedVat * 100) / 100} kr för momsbehandling "${value.vat_treatment}" på ${value.disposed_proceeds} kr brutto.`,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function vatRateFromTreatment(t: (typeof VAT_TREATMENTS)[number]): number | null {
|
||||
switch (t) {
|
||||
case 'standard_25':
|
||||
return 0.25
|
||||
case 'reduced_12':
|
||||
return 0.12
|
||||
case 'reduced_6':
|
||||
return 0.06
|
||||
case 'reverse_charge':
|
||||
case 'export':
|
||||
case 'exempt':
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'assets.dispose',
|
||||
|
||||
@@ -3,40 +3,66 @@ import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { K3ComponentSchema } from '@/lib/api/schemas'
|
||||
import { getAsset, updateAsset } from '@/lib/bokslut/assets/asset-service'
|
||||
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
|
||||
import type { DepreciationMethod } from '@/types'
|
||||
|
||||
const DEPRECIATION_METHODS: readonly DepreciationMethod[] = [
|
||||
'linear',
|
||||
'declining_balance_30',
|
||||
'declining_balance_20',
|
||||
'restvardesavskrivning_25',
|
||||
] as const
|
||||
|
||||
// Engine only implements linear today — reject declining_balance methods on
|
||||
// both create and update until the engine grows them. The DB enum keeps the
|
||||
// other methods reserved for a future phase.
|
||||
const SUPPORTED_DEPRECIATION_METHODS: readonly DepreciationMethod[] = ['linear'] as const
|
||||
const UpdateAssetSchema = z
|
||||
.object({
|
||||
name: z.string().min(1).optional(),
|
||||
notes: z.string().nullable().optional(),
|
||||
salvage_value: z.number().nonnegative().optional(),
|
||||
useful_life_months: z.number().int().positive().optional(),
|
||||
depreciation_method: z
|
||||
.enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]])
|
||||
.optional(),
|
||||
restvarde_target: z.number().nonnegative().nullable().optional(),
|
||||
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
// K3 component depreciation. Accepting `null` lets the caller clear an
|
||||
// existing breakdown (the engine then falls back to depreciation_method).
|
||||
// Per-component validation runs whenever the field is set to a non-null
|
||||
// value; the cross-sum check needs acquisition_cost so it's deferred to
|
||||
// updateAsset() which can read the existing row.
|
||||
k3_components: z.array(K3ComponentSchema).nullable().optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
// Enforce the method/target biconditional when EITHER field is supplied.
|
||||
// We can't see the existing row from a zod refinement, so the
|
||||
// application-level updateAsset() carries the cross-row check; here we
|
||||
// only catch the obviously inconsistent combinations within a single
|
||||
// PATCH body.
|
||||
const hasMethod = value.depreciation_method !== undefined
|
||||
const hasTarget = value.restvarde_target !== undefined
|
||||
if (!hasMethod && !hasTarget) return
|
||||
|
||||
const UpdateAssetSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
notes: z.string().nullable().optional(),
|
||||
salvage_value: z.number().nonnegative().optional(),
|
||||
useful_life_months: z.number().int().positive().optional(),
|
||||
depreciation_method: z
|
||||
.enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]])
|
||||
.optional()
|
||||
.refine(
|
||||
(m) => m === undefined || (SUPPORTED_DEPRECIATION_METHODS as readonly string[]).includes(m),
|
||||
{
|
||||
message:
|
||||
'Only "linear" depreciation is supported by the engine today. ' +
|
||||
'Declining-balance methods are reserved for a future phase.',
|
||||
},
|
||||
),
|
||||
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
})
|
||||
const isRestvarde = value.depreciation_method === 'restvardesavskrivning_25'
|
||||
const targetIsSet = value.restvarde_target !== null && value.restvarde_target !== undefined
|
||||
|
||||
if (hasMethod && isRestvarde && hasTarget && !targetIsSet) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message: 'restvarde_target krävs när avskrivningsmetoden är restvärdeavskrivning (25 %).',
|
||||
})
|
||||
}
|
||||
if (hasMethod && !isRestvarde && hasTarget && targetIsSet) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message: 'restvarde_target får bara anges för restvärdeavskrivning (25 %).',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'assets.get',
|
||||
@@ -62,6 +88,51 @@ export const PATCH = withRouteContext(
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const validation = await validateBody(request, UpdateAssetSchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
// K3 component depreciation gating + cross-sum check.
|
||||
// The Zod refinement cannot see the existing asset's acquisition_cost,
|
||||
// so we do both the framework check and the sum validation here at
|
||||
// route level before delegating to updateAsset().
|
||||
if (validation.data.k3_components !== undefined && validation.data.k3_components !== null) {
|
||||
const [{ data: company }, existing] = await Promise.all([
|
||||
supabase
|
||||
.from('companies')
|
||||
.select('accounting_framework')
|
||||
.eq('id', companyId)
|
||||
.single(),
|
||||
getAsset(supabase, companyId, id),
|
||||
])
|
||||
if (!company || company.accounting_framework !== 'k3') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'K3_REQUIRED_FOR_COMPONENTS',
|
||||
message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).',
|
||||
},
|
||||
},
|
||||
{ status: 422 },
|
||||
)
|
||||
}
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 })
|
||||
}
|
||||
const { errors } = validateComponents({
|
||||
acquisition_cost: Number(existing.acquisition_cost),
|
||||
k3_components: validation.data.k3_components,
|
||||
})
|
||||
if (errors.length > 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'INVALID_K3_COMPONENTS',
|
||||
message: errors.join(' '),
|
||||
},
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const asset = await updateAsset(supabase, companyId, id, validation.data)
|
||||
return NextResponse.json({ data: asset })
|
||||
|
||||
+102
-15
@@ -3,7 +3,9 @@ import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { K3ComponentSchema } from '@/lib/api/schemas'
|
||||
import { createAsset, listAssets } from '@/lib/bokslut/assets/asset-service'
|
||||
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
|
||||
import type { AssetCategory, DepreciationMethod } from '@/types'
|
||||
|
||||
const ASSET_CATEGORIES: readonly AssetCategory[] = [
|
||||
@@ -17,18 +19,16 @@ const ASSET_CATEGORIES: readonly AssetCategory[] = [
|
||||
'other_tangible',
|
||||
] as const
|
||||
|
||||
// The DB enum keeps all three methods so future phases can add support
|
||||
// without a migration, but the engine only implements linear today. Reject
|
||||
// the unsupported methods at create to avoid silently producing wrong
|
||||
// (linear) numbers under a misleading method label.
|
||||
// All four depreciation methods are now implemented by the engine. The DB
|
||||
// CHECK constraint mirrors this list (see
|
||||
// 20260526120100_restvardeavskrivning.sql).
|
||||
const DEPRECIATION_METHODS: readonly DepreciationMethod[] = [
|
||||
'linear',
|
||||
'declining_balance_30',
|
||||
'declining_balance_20',
|
||||
'restvardesavskrivning_25',
|
||||
] as const
|
||||
|
||||
const SUPPORTED_DEPRECIATION_METHODS: readonly DepreciationMethod[] = ['linear'] as const
|
||||
|
||||
const CreateAssetSchema = z
|
||||
.object({
|
||||
name: z.string().min(1),
|
||||
@@ -41,18 +41,21 @@ const CreateAssetSchema = z
|
||||
useful_life_months: z.number().int().positive(),
|
||||
depreciation_method: z
|
||||
.enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]])
|
||||
.optional()
|
||||
.refine(
|
||||
(m) => m === undefined || (SUPPORTED_DEPRECIATION_METHODS as readonly string[]).includes(m),
|
||||
{
|
||||
message:
|
||||
'Only "linear" depreciation is supported by the engine today. ' +
|
||||
'Declining-balance methods are reserved for a future phase.',
|
||||
},
|
||||
),
|
||||
.optional(),
|
||||
// Restvärde-target floor for restvärdeavskrivning. Required iff
|
||||
// depreciation_method = 'restvardesavskrivning_25'. The DB CHECK enforces
|
||||
// the same biconditional; we mirror it in the API for an early, Swedish
|
||||
// error message rather than a Postgres check_violation surfacing.
|
||||
restvarde_target: z.number().nonnegative().nullable().optional(),
|
||||
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
// K3 component depreciation (BFNAR 2012:1 ch.17.4). Only meaningful for
|
||||
// companies with accounting_framework='k3' — the route handler rejects
|
||||
// K3_REQUIRED_FOR_COMPONENTS for K2 companies. When present, the engine
|
||||
// dispatches to per-component linear depreciation instead of the
|
||||
// asset-level depreciation_method.
|
||||
k3_components: z.array(K3ComponentSchema).nullable().optional(),
|
||||
notes: z.string().optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
@@ -60,8 +63,70 @@ const CreateAssetSchema = z
|
||||
// outside the legitimate range for the asset category so the chart stays
|
||||
// BAS-aligned and INK2R mappings continue to work.
|
||||
validateBasOverrides(value, ctx)
|
||||
validateRestvardeTarget(value, ctx)
|
||||
validateK3Components(value, ctx)
|
||||
})
|
||||
|
||||
function validateK3Components(
|
||||
value: {
|
||||
acquisition_cost: number
|
||||
k3_components?: { name: string; cost: number; useful_life_months: number; salvage_value?: number }[] | null
|
||||
},
|
||||
ctx: z.RefinementCtx,
|
||||
): void {
|
||||
if (value.k3_components === undefined || value.k3_components === null) return
|
||||
const { errors } = validateComponents({
|
||||
acquisition_cost: value.acquisition_cost,
|
||||
k3_components: value.k3_components,
|
||||
})
|
||||
for (const message of errors) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['k3_components'],
|
||||
message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function validateRestvardeTarget(
|
||||
value: {
|
||||
depreciation_method?: DepreciationMethod
|
||||
restvarde_target?: number | null
|
||||
acquisition_cost?: number
|
||||
},
|
||||
ctx: z.RefinementCtx,
|
||||
): void {
|
||||
const isRestvarde = value.depreciation_method === 'restvardesavskrivning_25'
|
||||
const hasTarget = value.restvarde_target !== undefined && value.restvarde_target !== null
|
||||
if (isRestvarde && !hasTarget) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message: 'restvarde_target krävs när avskrivningsmetoden är restvärdeavskrivning (25 %).',
|
||||
})
|
||||
}
|
||||
if (!isRestvarde && hasTarget) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message: 'restvarde_target får bara anges för restvärdeavskrivning (25 %).',
|
||||
})
|
||||
}
|
||||
if (
|
||||
isRestvarde &&
|
||||
hasTarget &&
|
||||
value.acquisition_cost !== undefined &&
|
||||
(value.restvarde_target as number) >= value.acquisition_cost
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message:
|
||||
'restvarde_target måste vara lägre än anskaffningsvärdet — annars finns inget kvar att skriva av.',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function validateBasOverrides(
|
||||
value: {
|
||||
category: AssetCategory
|
||||
@@ -151,6 +216,28 @@ export const POST = withRouteContext(
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
const validation = await validateBody(request, CreateAssetSchema)
|
||||
if (!validation.success) return validation.response
|
||||
// K3_REQUIRED_FOR_COMPONENTS: K3 component depreciation is only
|
||||
// meaningful when the company applies the K3 framework. Reject the
|
||||
// write with 422 (Unprocessable Entity) rather than silently dropping
|
||||
// the field so the user knows their input was discarded.
|
||||
if (validation.data.k3_components !== undefined && validation.data.k3_components !== null) {
|
||||
const { data: company } = await supabase
|
||||
.from('companies')
|
||||
.select('accounting_framework')
|
||||
.eq('id', companyId)
|
||||
.single()
|
||||
if (!company || company.accounting_framework !== 'k3') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'K3_REQUIRED_FOR_COMPONENTS',
|
||||
message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).',
|
||||
},
|
||||
},
|
||||
{ status: 422 },
|
||||
)
|
||||
}
|
||||
}
|
||||
try {
|
||||
const asset = await createAsset(supabase, companyId, user.id, validation.data)
|
||||
return NextResponse.json({ data: asset })
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const mockCreateClient = vi.fn()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => mockCreateClient(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
const mockBuildAccrualsProposal = vi.fn()
|
||||
const mockDetectPeriodisering = vi.fn()
|
||||
vi.mock('@/lib/bokslut/accruals/accrual-detector', async () => {
|
||||
const actual =
|
||||
(await vi.importActual('@/lib/bokslut/accruals/accrual-detector')) as Record<string, unknown>
|
||||
return {
|
||||
...actual,
|
||||
buildAccrualsProposal: (...args: unknown[]) => mockBuildAccrualsProposal(...args),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/bokslut/accruals/auto-detect', () => ({
|
||||
detectPeriodisering: (...args: unknown[]) => mockDetectPeriodisering(...args),
|
||||
}))
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: mockUser } }) },
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/bookkeeping/fiscal-periods/[id]/accruals', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: null } }) },
|
||||
})
|
||||
const { GET } = await import('../route')
|
||||
const res = await GET(
|
||||
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
|
||||
createMockRouteParams({ id: 'period-1' }),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns the snapshot plus autoDetected suggestions', async () => {
|
||||
mockBuildAccrualsProposal.mockResolvedValue({
|
||||
fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
|
||||
proposals: [],
|
||||
})
|
||||
mockDetectPeriodisering.mockResolvedValue([
|
||||
{
|
||||
source_invoice_id: 'sup-1',
|
||||
source_type: 'supplier_invoice',
|
||||
original_amount: 12000,
|
||||
periodisering_amount: 6000,
|
||||
parsed_start: '2025-07-01',
|
||||
parsed_end: '2026-06-30',
|
||||
confidence: 'high',
|
||||
reason: 'Mock reason',
|
||||
source_label: 'Test Supplier',
|
||||
suggested_prepaid_account: '1710',
|
||||
suggested_deferred_account: null,
|
||||
},
|
||||
])
|
||||
const { GET } = await import('../route')
|
||||
const res = await GET(
|
||||
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
|
||||
createMockRouteParams({ id: 'period-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { autoDetected: unknown[] } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.autoDetected).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('still returns the snapshot when auto-detect throws', async () => {
|
||||
mockBuildAccrualsProposal.mockResolvedValue({
|
||||
fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
|
||||
proposals: [],
|
||||
})
|
||||
mockDetectPeriodisering.mockRejectedValue(new Error('boom'))
|
||||
const { GET } = await import('../route')
|
||||
const res = await GET(
|
||||
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
|
||||
createMockRouteParams({ id: 'period-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { autoDetected: unknown[] } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.autoDetected).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -6,11 +6,15 @@ import { validateBody } from '@/lib/api/validate'
|
||||
import { createJournalEntry } from '@/lib/bookkeeping/engine'
|
||||
import {
|
||||
buildAccrualsProposal,
|
||||
proposeAccruedInterest,
|
||||
proposeAccruedUtility,
|
||||
proposeAuditFee,
|
||||
proposeManualAccrued,
|
||||
proposeManualPrepaid,
|
||||
proposeRevenueDeferral,
|
||||
proposeVacationLiabilityChange,
|
||||
} from '@/lib/bokslut/accruals/accrual-detector'
|
||||
import { detectPeriodisering } from '@/lib/bokslut/accruals/auto-detect'
|
||||
import type { AccrualProposal } from '@/lib/bokslut/accruals/types'
|
||||
import type { JournalEntry } from '@/types'
|
||||
|
||||
@@ -20,8 +24,18 @@ export const GET = withRouteContext(
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
try {
|
||||
const proposal = await buildAccrualsProposal(supabase, companyId, id)
|
||||
return NextResponse.json({ data: proposal })
|
||||
// Run the two independent scans in parallel so the wizard's first
|
||||
// paint isn't gated on the slower auto-detect query.
|
||||
const [proposal, autoDetected] = await Promise.all([
|
||||
buildAccrualsProposal(supabase, companyId, id),
|
||||
detectPeriodisering(supabase, companyId, id).catch((err) => {
|
||||
// Auto-detect is best-effort — a malformed invoice description
|
||||
// shouldn't break the rest of the preflight. Log + return empty.
|
||||
log.warn('auto-detect failed', { error: (err as Error)?.message })
|
||||
return []
|
||||
}),
|
||||
])
|
||||
return NextResponse.json({ data: { ...proposal, autoDetected } })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : ''
|
||||
if (/not found/i.test(message)) {
|
||||
@@ -32,6 +46,19 @@ export const GET = withRouteContext(
|
||||
},
|
||||
)
|
||||
|
||||
// Defense-in-depth on caller-supplied account numbers. The wizard sends
|
||||
// accounts from a closed template list, but the API accepts them as plain
|
||||
// strings so we constrain the BAS class per accrual kind:
|
||||
// - cost accounts (5xxx-8xxx) for expense legs
|
||||
// - revenue accounts (3xxx) for revenue legs
|
||||
// - 17xx for förutbetalda kostnader (prepaid)
|
||||
// - 29xx for upplupna poster (accrued / deferred)
|
||||
// Anything outside these ranges is rejected with 400 before reaching the
|
||||
// engine — keeps a compromised browser session from posting arbitrary
|
||||
// balance-sheet hits.
|
||||
const EXPENSE_ACCOUNT_RE = /^[5-8]\d{3}$/
|
||||
const REVENUE_ACCOUNT_RE = /^3\d{3}$/
|
||||
|
||||
const PostItemSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('vacation_liability_change') }),
|
||||
z.object({
|
||||
@@ -42,14 +69,35 @@ const PostItemSchema = z.discriminatedUnion('kind', [
|
||||
z.object({
|
||||
kind: z.literal('manual_prepaid_expense'),
|
||||
amount: z.number().positive(),
|
||||
expense_account: z.string().regex(/^\d{4}$/),
|
||||
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
|
||||
prepaid_account: z.string().regex(/^17\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('manual_accrued_expense'),
|
||||
amount: z.number().positive(),
|
||||
expense_account: z.string().regex(/^\d{4}$/),
|
||||
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
|
||||
accrued_account: z.string().regex(/^29\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('deferred_revenue'),
|
||||
amount: z.number().positive(),
|
||||
revenue_account: z.string().regex(REVENUE_ACCOUNT_RE),
|
||||
deferred_account: z.string().regex(/^29\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('accrued_interest'),
|
||||
amount: z.number().positive(),
|
||||
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
|
||||
accrued_account: z.string().regex(/^29\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('accrued_utility'),
|
||||
amount: z.number().positive(),
|
||||
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
|
||||
accrued_account: z.string().regex(/^29\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
@@ -132,6 +180,33 @@ export const POST = withRouteContext(
|
||||
closingDate: period.period_end,
|
||||
})
|
||||
break
|
||||
case 'deferred_revenue':
|
||||
proposal = proposeRevenueDeferral({
|
||||
amount: item.amount,
|
||||
revenueAccount: item.revenue_account,
|
||||
deferredAccount: item.deferred_account,
|
||||
description: item.description,
|
||||
closingDate: period.period_end,
|
||||
})
|
||||
break
|
||||
case 'accrued_interest':
|
||||
proposal = proposeAccruedInterest({
|
||||
amount: item.amount,
|
||||
expenseAccount: item.expense_account,
|
||||
accruedAccount: item.accrued_account,
|
||||
description: item.description,
|
||||
closingDate: period.period_end,
|
||||
})
|
||||
break
|
||||
case 'accrued_utility':
|
||||
proposal = proposeAccruedUtility({
|
||||
amount: item.amount,
|
||||
expenseAccount: item.expense_account,
|
||||
accruedAccount: item.accrued_account,
|
||||
description: item.description,
|
||||
closingDate: period.period_end,
|
||||
})
|
||||
break
|
||||
}
|
||||
if (!proposal) continue
|
||||
|
||||
@@ -199,6 +274,15 @@ async function findExistingAccrualEntry(
|
||||
case 'manual_accrued_expense':
|
||||
pattern = `Periodisering: Upplupen kostnad: ${escapeLike(item.description)}%`
|
||||
break
|
||||
case 'deferred_revenue':
|
||||
pattern = `Periodisering: Förutbetald intäkt: ${escapeLike(item.description)}%`
|
||||
break
|
||||
case 'accrued_interest':
|
||||
pattern = `Periodisering: Upplupen ränta: ${escapeLike(item.description)}%`
|
||||
break
|
||||
case 'accrued_utility':
|
||||
pattern = `Periodisering: Upplupen förbrukning: ${escapeLike(item.description)}%`
|
||||
break
|
||||
}
|
||||
|
||||
const { data } = await supabase
|
||||
|
||||
@@ -3,6 +3,7 @@ import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { buildArsredovisningData } from '@/lib/bokslut/arsredovisning/build-data'
|
||||
import { ArsredovisningPDF } from '@/lib/bokslut/arsredovisning/arsredovisning-pdf'
|
||||
import { ArsredovisningK3PDF } from '@/lib/bokslut/arsredovisning/arsredovisning-k3-pdf'
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'period.arsredovisning_pdf',
|
||||
@@ -14,7 +15,15 @@ export const GET = withRouteContext(
|
||||
// inside buildArsredovisningData. The URL stays clean — no narrative
|
||||
// text in query params, access logs, or browser history.
|
||||
const data = await buildArsredovisningData(supabase, companyId, id)
|
||||
const pdfBuffer = await renderToBuffer(ArsredovisningPDF({ data }))
|
||||
// Dispatch on the framework recorded in the data. K3 documents need
|
||||
// the additional kassaflöde + equity-changes pages + richer noter
|
||||
// that ArsredovisningK3PDF renders. K2 (the default) keeps the
|
||||
// existing template byte-for-byte unchanged.
|
||||
const PdfComponent =
|
||||
data.accounting_framework === 'k3'
|
||||
? ArsredovisningK3PDF
|
||||
: ArsredovisningPDF
|
||||
const pdfBuffer = await renderToBuffer(PdfComponent({ data }))
|
||||
// "-utkast" suffix mirrors the existing PDF routes; the file becomes
|
||||
// "fastställd" only after the signature flow records all signatures.
|
||||
// Sanitize the dynamic segment so a stray quote / newline in the date
|
||||
|
||||
@@ -13,7 +13,10 @@ import {
|
||||
} from '@/lib/bokslut/reserves/periodiseringsfond-service'
|
||||
import { proposeOveravskrivningar } from '@/lib/bokslut/reserves/overavskrivningar-service'
|
||||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||||
import { buildDispositionsProposal } from '@/lib/bokslut/dispositions-proposal-builder'
|
||||
import {
|
||||
buildDispositionsProposal,
|
||||
buildLatentTaxProposal,
|
||||
} from '@/lib/bokslut/dispositions-proposal-builder'
|
||||
import type { ProposedDisposition } from '@/lib/bokslut/types'
|
||||
import type { JournalEntry } from '@/types'
|
||||
|
||||
@@ -45,6 +48,9 @@ const DISPOSITION_ORDER: Record<string, number> = {
|
||||
periodiseringsfond_avsattning: 2,
|
||||
sarskild_loneskatt: 3,
|
||||
bolagsskatt: 4,
|
||||
// K3 only — posts last because it depends on the closing 21xx balance,
|
||||
// which only stabilises once avsättning / återföring have been applied.
|
||||
uppskjuten_skatt: 5,
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
@@ -112,6 +118,11 @@ const ItemSchema = z.discriminatedUnion('kind', [
|
||||
.enum(['machinery_equipment', 'building', 'immaterial', 'group'])
|
||||
.optional(),
|
||||
}),
|
||||
// K3 only — uppskjuten skatt provision. Server recomputes the amount from
|
||||
// current 2240 + 21xx state so the client cannot override it.
|
||||
z.object({
|
||||
kind: z.literal('uppskjuten_skatt'),
|
||||
}),
|
||||
])
|
||||
|
||||
const PostBodySchema = z.object({
|
||||
@@ -260,6 +271,15 @@ async function computeProposal(
|
||||
additionalAmount: item.additionalAmount,
|
||||
category: item.category,
|
||||
})
|
||||
case 'uppskjuten_skatt':
|
||||
// Server-only: recompute from current TB (which already reflects any
|
||||
// 21xx postings that committed earlier in this batch). The client
|
||||
// sends no amount — the calculator owns the K3 split.
|
||||
return buildLatentTaxProposal({
|
||||
supabase,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,10 @@ export async function GET(request: Request) {
|
||||
const dateFrom = searchParams.get('date_from')
|
||||
const dateTo = searchParams.get('date_to')
|
||||
const sortDate = searchParams.get('sort_date') // 'asc' | 'desc'
|
||||
// 'series' optional filter — single uppercase letter A–Z. Ignored if any
|
||||
// other value is passed (defense against trivial injection / typos).
|
||||
const seriesRaw = searchParams.get('series')
|
||||
const seriesFilter = seriesRaw && /^[A-Z]$/.test(seriesRaw) ? seriesRaw : null
|
||||
// 'date_desc' (default) | 'date_asc' | 'voucher_asc' | 'voucher_desc'
|
||||
// sort_by overrides sort_date when present. sort_date is kept for backwards
|
||||
// compatibility with older clients.
|
||||
@@ -69,8 +73,18 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
const rows = data ?? []
|
||||
const entries = rows.map((r: { entry: unknown }) => r.entry)
|
||||
const count = rows.length > 0 ? Number((rows[0] as { total_count: number | string }).total_count) : 0
|
||||
let entries = rows.map((r: { entry: unknown }) => r.entry) as Array<{ voucher_series?: string }>
|
||||
let count = rows.length > 0 ? Number((rows[0] as { total_count: number | string }).total_count) : 0
|
||||
|
||||
// The list_fiscal_period_entries_with_related RPC doesn't accept a series
|
||||
// filter, so post-filter here. Recompute count from the filtered set so
|
||||
// the paginator stays consistent; consequence: when a series filter is
|
||||
// applied, the cross-period follow-up surfacing is still on but the
|
||||
// visible total drops to the matching subset.
|
||||
if (seriesFilter) {
|
||||
entries = entries.filter((e) => (e?.voucher_series ?? 'A') === seriesFilter)
|
||||
count = entries.length
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: entries, count })
|
||||
}
|
||||
@@ -115,6 +129,10 @@ export async function GET(request: Request) {
|
||||
query = query.lte('entry_date', dateTo)
|
||||
}
|
||||
|
||||
if (seriesFilter) {
|
||||
query = query.eq('voucher_series', seriesFilter)
|
||||
}
|
||||
|
||||
const { data, error, count } = await query
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { getActiveCompanyId, requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { AccountingFrameworkSchema } from '@/lib/api/schemas'
|
||||
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
|
||||
const log = createLogger('api/company/current')
|
||||
|
||||
// BAS 2026 accounts required for K3's uppskjuten skatt (latent tax) entries.
|
||||
// Both rows carry k2_excluded=true in lib/bookkeeping/bas-data so they are
|
||||
// NOT seeded by seed_chart_of_accounts() for K2 companies. When a company
|
||||
// opts into K3 we backfill them here so the engine can resolve them by
|
||||
// account_number when the first latent-tax entry is posted.
|
||||
const K3_LATENT_TAX_ACCOUNTS = ['2240', '8940'] as const
|
||||
|
||||
/**
|
||||
* GET /api/company/current
|
||||
@@ -34,3 +49,143 @@ export async function GET() {
|
||||
{ headers: { 'Cache-Control': 'private, no-store' } },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Body shape for PATCH /api/company/current.
|
||||
*
|
||||
* Currently only carries `accounting_framework` (K2 / K3). Adding more
|
||||
* companies-level fields here is fine but anything that belongs on
|
||||
* company_settings should go to /api/settings instead.
|
||||
*/
|
||||
const PatchBodySchema = z.object({
|
||||
accounting_framework: AccountingFrameworkSchema.optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* PATCH /api/company/current
|
||||
*
|
||||
* Updates company-level fields (in the `companies` table) for the active
|
||||
* company. Separate from /api/settings (which writes to `company_settings`)
|
||||
* because the columns live on different tables.
|
||||
*
|
||||
* Currently scoped to `accounting_framework` (K2 / K3) — only meaningful for
|
||||
* entity_type='aktiebolag'. The handler rejects K3 for non-AB to prevent
|
||||
* impossible chart-of-accounts states downstream.
|
||||
*/
|
||||
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 writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const validation = await validateBody(request, PatchBodySchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
const updates: Record<string, unknown> = {}
|
||||
|
||||
if (validation.data.accounting_framework !== undefined) {
|
||||
// Only AB can opt in to K3 — EF stays on the simpler EF rules and never
|
||||
// touches K2/K3. Fetch the entity_type before applying.
|
||||
const { data: company } = await supabase
|
||||
.from('companies')
|
||||
.select('entity_type')
|
||||
.eq('id', companyId)
|
||||
.single()
|
||||
if (!company) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Företaget kunde inte hittas' },
|
||||
{ status: 404 },
|
||||
)
|
||||
}
|
||||
if (
|
||||
validation.data.accounting_framework === 'k3'
|
||||
&& company.entity_type !== 'aktiebolag'
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'K3 (BFNAR 2012:1) gäller endast aktiebolag.' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
updates.accounting_framework = validation.data.accounting_framework
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
// Nothing to write — surface the current row so the client can refresh
|
||||
// its local state without a no-op write.
|
||||
const { data } = await supabase
|
||||
.from('companies')
|
||||
.select('id, accounting_framework, entity_type')
|
||||
.eq('id', companyId)
|
||||
.single()
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('companies')
|
||||
.update(updates)
|
||||
.eq('id', companyId)
|
||||
.select('id, accounting_framework, entity_type')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// When opting in to K3, ensure the two latent-tax (uppskjuten skatt)
|
||||
// accounts exist in the company's chart of accounts. The base seed skips
|
||||
// them for K2 companies via k2_excluded=true, so without this backfill
|
||||
// the engine cannot resolve account_id for the first latent-tax post.
|
||||
// Wrapped in try/catch so a CoA insert failure does not block the
|
||||
// framework update — the user can still re-trigger the seed later.
|
||||
// The reverse switch (K3 → K2) intentionally keeps the rows for audit
|
||||
// history; the legal record of past K3 postings must remain intact.
|
||||
if (data.accounting_framework === 'k3') {
|
||||
try {
|
||||
const rows = K3_LATENT_TAX_ACCOUNTS.map(accountNumber => {
|
||||
const basRef = getBASReference(accountNumber)
|
||||
if (!basRef) return null
|
||||
return {
|
||||
user_id: user.id,
|
||||
company_id: companyId,
|
||||
account_number: basRef.account_number,
|
||||
account_name: basRef.account_name,
|
||||
account_class: basRef.account_class,
|
||||
account_group: basRef.account_group,
|
||||
account_type: basRef.account_type,
|
||||
normal_balance: basRef.normal_balance,
|
||||
sru_code: basRef.sru_code,
|
||||
k2_excluded: basRef.k2_excluded,
|
||||
plan_type: 'full_bas',
|
||||
is_active: true,
|
||||
is_system_account: true,
|
||||
description: basRef.description,
|
||||
}
|
||||
}).filter((row): row is NonNullable<typeof row> => row !== null)
|
||||
|
||||
if (rows.length > 0) {
|
||||
const { error: seedError } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.upsert(rows, { onConflict: 'company_id,account_number', ignoreDuplicates: true })
|
||||
if (seedError) {
|
||||
log.error('Failed to seed K3 latent-tax accounts', {
|
||||
companyId,
|
||||
error: seedError.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('Unexpected error seeding K3 latent-tax accounts', {
|
||||
companyId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import {
|
||||
parseJsonResponse,
|
||||
createMockRouteParams,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
import { DELETE } from '../route'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
eventBus.clear()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
// Reset write-permission mock to default ok
|
||||
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
function makeReq() {
|
||||
return new Request('http://localhost/api/documents/doc-1', { method: 'DELETE' })
|
||||
}
|
||||
|
||||
describe('DELETE /api/documents/[id]', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
expect(body).toEqual({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
it('returns 403 when caller has read-only role', async () => {
|
||||
vi.mocked(requireWritePermission).mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{ error: 'Du har endast läsbehörighet i detta företag.' },
|
||||
{ status: 403 },
|
||||
),
|
||||
})
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 404 when document not found in company', async () => {
|
||||
enqueue({ data: null, error: null }) // doc lookup
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error).toContain('hittades inte')
|
||||
})
|
||||
|
||||
it('returns 409 with BFL message when doc is linked to a journal entry', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'doc-1',
|
||||
file_name: 'kvitto.pdf',
|
||||
storage_path: 'documents/user-1/kvitto.pdf',
|
||||
journal_entry_id: 'je-99',
|
||||
user_id: 'user-1',
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toContain('Bokföringslagen')
|
||||
expect(body.error).toContain('7 kap')
|
||||
})
|
||||
|
||||
it('deletes the row, removes Storage file, and emits document.deleted on unlinked doc', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'doc-1',
|
||||
file_name: 'kvitto.pdf',
|
||||
storage_path: 'documents/user-1/kvitto.pdf',
|
||||
journal_entry_id: null,
|
||||
user_id: 'user-1',
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
enqueue({ data: null, error: null }) // delete
|
||||
|
||||
const handler = vi.fn()
|
||||
eventBus.on('document.deleted', handler)
|
||||
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string; deleted: boolean } }>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ id: 'doc-1', deleted: true })
|
||||
|
||||
expect(mockSupabase.storage.from).toHaveBeenCalledWith('documents')
|
||||
const storageBucket = mockSupabase.storage.from.mock.results[0]?.value
|
||||
expect(storageBucket.remove).toHaveBeenCalledWith(['documents/user-1/kvitto.pdf'])
|
||||
|
||||
expect(handler).toHaveBeenCalledOnce()
|
||||
expect(handler).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
document: expect.objectContaining({ id: 'doc-1', file_name: 'kvitto.pdf' }),
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 409 with BFL message when DB trigger blocks deletion (defense-in-depth)', async () => {
|
||||
// Caller bypasses the application-layer check (e.g. race condition).
|
||||
// The block_document_deletion() trigger raises with "Bokföringslagen" in the
|
||||
// message; the service maps it to a 409.
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'doc-1',
|
||||
file_name: 'kvitto.pdf',
|
||||
storage_path: 'documents/user-1/kvitto.pdf',
|
||||
journal_entry_id: null,
|
||||
user_id: 'user-1',
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
enqueue({
|
||||
data: null,
|
||||
error: { message: 'Cannot delete document linked to a posted journal entry (Bokföringslagen)' },
|
||||
})
|
||||
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toContain('Bokföringslagen')
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,8 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { deleteDocument } from '@/lib/core/documents/document-service'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -66,3 +68,45 @@ export async function GET(
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/documents/:id
|
||||
* Remove an uploaded document. Only permitted when the document is not yet
|
||||
* linked to a journal entry — once linked, it is räkenskapsinformation under
|
||||
* BFL 7 kap 2§ and must be retained for 7 years. For linked docs the caller
|
||||
* should use POST /api/documents/:id/versions to supersede via a new version.
|
||||
*/
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const result = await deleteDocument(supabase, companyId, id)
|
||||
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.message }, { status: result.status })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { id: result.document.id, deleted: true } })
|
||||
} catch (error) {
|
||||
console.error('[documents/DELETE] Failed to delete document:', error)
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : 'Failed to delete document' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
/**
|
||||
* POST /api/import/sie/[id]/replace
|
||||
*
|
||||
* Replace a completed SIE import by cancelling its entries, allowing the user
|
||||
* to re-import corrected data for the same fiscal period.
|
||||
* Replace a completed SIE import by hard-deleting its entries, allowing the
|
||||
* user to re-import corrected data for the same fiscal period.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'sie_import.replace',
|
||||
@@ -25,7 +25,7 @@ export const POST = withRouteContext(
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, cancelledEntries: result.cancelledEntries })
|
||||
return NextResponse.json({ success: true, deletedEntries: result.deletedEntries })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
@@ -39,6 +39,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue('mock-pdf-element'),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createInvoiceJournalEntry } from '@/lib/bookkeeping/invoice-entries'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
@@ -134,13 +135,16 @@ export async function POST(
|
||||
// The DB status flip already happened above, but the in-memory `invoice`
|
||||
// is stale and still reads 'draft' — override here so the archived
|
||||
// underlag isn't stamped "UTKAST – inte en giltig faktura".
|
||||
const renderableInvoice = { ...(invoice as Invoice), status: 'sent' as const }
|
||||
const { branding } = prepareInvoicePdfRender(settings as CompanySettings)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: { ...(invoice as Invoice), status: 'sent' as const },
|
||||
invoice: renderableInvoice,
|
||||
customer: invoice.customer as Customer,
|
||||
items,
|
||||
company: settings as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings } from '@/types'
|
||||
|
||||
@@ -66,6 +67,7 @@ export async function GET(
|
||||
|
||||
try {
|
||||
// Generate PDF
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: invoice as Invoice,
|
||||
@@ -73,6 +75,7 @@ export async function GET(
|
||||
items,
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue('mock-pdf-element'),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import {
|
||||
generateInvoiceEmailHtml,
|
||||
@@ -93,6 +94,7 @@ export const POST = withRouteContext(
|
||||
const isFreshAllocation = !invoice.invoice_number
|
||||
if (isFreshAllocation) {
|
||||
try {
|
||||
const preflight = prepareInvoicePdfRender(company as CompanySettings)
|
||||
await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: { ...(invoice as Invoice), invoice_number: 'F-PREVIEW' },
|
||||
@@ -100,6 +102,7 @@ export const POST = withRouteContext(
|
||||
items,
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding: preflight.branding,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
@@ -121,13 +124,16 @@ export const POST = withRouteContext(
|
||||
// the in-memory copy: the DB flip happens after email delivery (line
|
||||
// ~185), but if we render with the stale 'draft' status the customer
|
||||
// receives a PDF stamped "UTKAST – inte en giltig faktura".
|
||||
const renderableInvoice = { ...(invoice as Invoice), status: 'sent' as const }
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: { ...(invoice as Invoice), status: 'sent' as const },
|
||||
invoice: renderableInvoice,
|
||||
customer,
|
||||
items,
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export const GET = withRouteContext(
|
||||
|
||||
const url = new URL(request.url)
|
||||
const documentType = url.searchParams.get('document_type') ?? 'invoice'
|
||||
if (!['invoice', 'proforma', 'delivery_note'].includes(documentType)) {
|
||||
if (!['invoice', 'proforma', 'delivery_note', 'quote'].includes(documentType)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid document_type', requestId },
|
||||
{ status: 400 },
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getVatRules } from '@/lib/invoices/vat-rules'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings, InvoiceDocumentType } from '@/types'
|
||||
@@ -167,6 +168,7 @@ export async function POST(request: Request) {
|
||||
} as Invoice
|
||||
|
||||
try {
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: previewInvoice,
|
||||
@@ -174,6 +176,7 @@ export async function POST(request: Request) {
|
||||
items: invoiceItems,
|
||||
company: company as CompanySettings,
|
||||
isPreview: true,
|
||||
branding,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -120,6 +120,11 @@ export async function GET(request: Request) {
|
||||
sent_at,
|
||||
response_type,
|
||||
action_token_used,
|
||||
interest_amount,
|
||||
interest_rate,
|
||||
interest_from_date,
|
||||
interest_days,
|
||||
reminder_fee,
|
||||
invoice:invoices(
|
||||
id,
|
||||
invoice_number,
|
||||
@@ -159,6 +164,11 @@ export async function GET(request: Request) {
|
||||
const customerData = invoice.customer
|
||||
const customer = Array.isArray(customerData) ? customerData[0] : customerData
|
||||
|
||||
const interestAmount = Number(reminder.interest_amount ?? 0)
|
||||
const reminderFee = Number(reminder.reminder_fee ?? 0)
|
||||
const totalDue =
|
||||
Math.round((Number(invoice.total) + interestAmount + reminderFee) * 100) / 100
|
||||
|
||||
return NextResponse.json({
|
||||
invoiceNumber: invoice.invoice_number,
|
||||
invoiceDate: invoice.invoice_date,
|
||||
@@ -168,6 +178,15 @@ export async function GET(request: Request) {
|
||||
customerName: customer?.name,
|
||||
reminderLevel: reminder.reminder_level,
|
||||
alreadyResponded: reminder.action_token_used,
|
||||
previousResponse: reminder.response_type
|
||||
previousResponse: reminder.response_type,
|
||||
// Dröjsmålsränta + lagstadgad påminnelseavgift surfaced to the
|
||||
// customer-facing action page. Numeric defaults preserve back-compat
|
||||
// for old reminders sent before the surcharge feature shipped.
|
||||
interestAmount,
|
||||
interestRate: reminder.interest_rate !== null ? Number(reminder.interest_rate) : 0,
|
||||
interestFromDate: reminder.interest_from_date,
|
||||
interestDays: reminder.interest_days,
|
||||
reminderFee,
|
||||
totalDue,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,6 +8,16 @@ import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
|
||||
import { createCreditNoteJournalEntry } from '@/lib/bookkeeping/invoice-entries'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import {
|
||||
computeDeduction,
|
||||
computeInvoiceDeductionTotal,
|
||||
validateInvoice as validateRotRut,
|
||||
} from '@/lib/invoices/rot-rut-rules'
|
||||
import {
|
||||
encryptPersonnummer,
|
||||
extractLast4,
|
||||
validatePersonnummer,
|
||||
} from '@/lib/salary/personnummer'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
@@ -135,6 +145,51 @@ export const POST = withRouteContext(
|
||||
}
|
||||
const total = documentType === 'delivery_note' ? 0 : subtotal + vatAmount
|
||||
|
||||
// ROT/RUT-avdrag: validate prerequisites and compute the per-item +
|
||||
// invoice-level deduction. Computed server-side (never trusted from
|
||||
// the client) so a tampered request can't expand the 1513 receivable.
|
||||
// Skipped entirely for proformas, delivery notes, and quotes — those
|
||||
// documents don't post journal entries and have no deduction model.
|
||||
let deductionTotal = 0
|
||||
let deductionPersonnummerEncrypted: string | null = null
|
||||
let deductionPersonnummerLast4: string | null = null
|
||||
if (documentType === 'invoice') {
|
||||
const housingProvided = !!invoiceInput.deduction_housing_designation?.trim()
|
||||
const personnummerRaw = invoiceInput.deduction_personnummer?.trim() || ''
|
||||
const personnummerProvided = personnummerRaw.length > 0
|
||||
|
||||
const validateInput = invoiceInput.items.map((item) => ({
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
deduction_type: item.deduction_type ?? null,
|
||||
labor_hours: item.labor_hours ?? null,
|
||||
housing_designation: item.housing_designation ?? null,
|
||||
}))
|
||||
const validation = validateRotRut(validateInput, personnummerProvided, housingProvided)
|
||||
if (validation.errors.length > 0) {
|
||||
return errorResponseFromCode('INVOICE_CREATE_ROT_RUT_VALIDATION', log, {
|
||||
requestId,
|
||||
details: { errors: validation.errors, warnings: validation.warnings },
|
||||
})
|
||||
}
|
||||
|
||||
// Compute and (when present) encrypt the personnummer. The plaintext
|
||||
// value never touches the DB — only the AES-256-GCM ciphertext + the
|
||||
// last four digits go into invoices columns.
|
||||
deductionTotal = computeInvoiceDeductionTotal(validateInput)
|
||||
if (personnummerProvided) {
|
||||
const pnValid = validatePersonnummer(personnummerRaw)
|
||||
if (!pnValid.valid) {
|
||||
return errorResponseFromCode('INVOICE_CREATE_ROT_RUT_PERSONNUMMER_INVALID', log, {
|
||||
requestId,
|
||||
details: { error: pnValid.error },
|
||||
})
|
||||
}
|
||||
deductionPersonnummerEncrypted = encryptPersonnummer(personnummerRaw)
|
||||
deductionPersonnummerLast4 = extractLast4(personnummerRaw)
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueRates = new Set(invoiceInput.items.map((item) => item.vat_rate ?? vatRules.rate))
|
||||
const isMixedRate = uniqueRates.size > 1
|
||||
|
||||
@@ -182,13 +237,14 @@ export const POST = withRouteContext(
|
||||
vat_amount_sek: documentType === 'delivery_note' ? null : vatAmountSek,
|
||||
total,
|
||||
total_sek: documentType === 'delivery_note' ? null : totalSek,
|
||||
// Initialize remaining_amount to total for real invoices so the open-
|
||||
// invoice queries (InvoicePicker, AR ledger, supplier matching) treat
|
||||
// newly-created invoices as fully unpaid. The DB default is 0 — without
|
||||
// this, brand-new fakturor look settled and disappear from match
|
||||
// candidate lists. Proformas and delivery notes have no payment
|
||||
// obligation, so they keep the 0 default.
|
||||
remaining_amount: documentType === 'invoice' ? total : 0,
|
||||
// Initialize remaining_amount to total - deduction for real invoices
|
||||
// so the open-invoice queries (InvoicePicker, AR ledger, supplier
|
||||
// matching) treat newly-created invoices as fully unpaid for the
|
||||
// CUSTOMER's share — the Skatteverket portion is on 1513 and will be
|
||||
// cleared when the agency pays out, not by the customer payment.
|
||||
// Proformas, delivery notes and quotes have no payment obligation,
|
||||
// so they keep the 0 default.
|
||||
remaining_amount: documentType === 'invoice' ? total - deductionTotal : 0,
|
||||
vat_treatment: vatRules.treatment,
|
||||
vat_rate: documentType === 'delivery_note' ? 0 : (isMixedRate ? null : (uniqueRates.values().next().value ?? vatRules.rate)),
|
||||
moms_ruta: vatRules.momsRuta,
|
||||
@@ -197,6 +253,9 @@ export const POST = withRouteContext(
|
||||
our_reference: invoiceInput.our_reference,
|
||||
notes: invoiceInput.notes,
|
||||
document_type: documentType,
|
||||
deduction_total: deductionTotal,
|
||||
deduction_personnummer_encrypted: deductionPersonnummerEncrypted,
|
||||
deduction_personnummer_last4: deductionPersonnummerLast4,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
@@ -213,6 +272,18 @@ export const POST = withRouteContext(
|
||||
const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate
|
||||
const lineTotal = item.quantity * item.unit_price
|
||||
const itemVat = documentType === 'delivery_note' ? 0 : Math.round(lineTotal * itemRate / 100 * 100) / 100
|
||||
// ROT/RUT deduction is recomputed server-side so a tampered client
|
||||
// can't expand the 1513 receivable beyond the rules. Non-invoice
|
||||
// document types never carry deduction_type (rules above strip them
|
||||
// implicitly because validateRotRut isn't invoked).
|
||||
const deductionType = documentType === 'invoice' ? (item.deduction_type ?? null) : null
|
||||
const deductionAmount = deductionType
|
||||
? computeDeduction({
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
deduction_type: deductionType,
|
||||
})
|
||||
: 0
|
||||
return {
|
||||
invoice_id: invoice.id,
|
||||
sort_order: index,
|
||||
@@ -223,6 +294,12 @@ export const POST = withRouteContext(
|
||||
line_total: lineTotal,
|
||||
vat_rate: itemRate,
|
||||
vat_amount: itemVat,
|
||||
deduction_type: deductionType,
|
||||
deduction_amount: deductionAmount,
|
||||
labor_hours: documentType === 'invoice' ? (item.labor_hours ?? null) : null,
|
||||
work_type: documentType === 'invoice' ? (item.work_type ?? null) : null,
|
||||
housing_designation: documentType === 'invoice' ? (item.housing_designation ?? null) : null,
|
||||
apartment_number: documentType === 'invoice' ? (item.apartment_number ?? null) : null,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -296,7 +373,7 @@ export const POST = withRouteContext(
|
||||
.eq('id', invoice.id)
|
||||
.single()
|
||||
|
||||
// Emit event only for real invoices (proformas / delivery notes are informational).
|
||||
// Emit event only for real invoices (proformas / delivery notes / quotes are informational).
|
||||
if (completeInvoice && documentType === 'invoice') {
|
||||
await eventBus.emit({
|
||||
type: 'invoice.created',
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/bookkeeping/currency-utils', () => ({
|
||||
resolveSekAmount: vi.fn((amount: number) => amount),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
interface QueryResult {
|
||||
data: unknown
|
||||
error: unknown
|
||||
}
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string } | null,
|
||||
customer: { id: string; name: string } | null,
|
||||
invoicesResult: QueryResult,
|
||||
entriesResult: QueryResult
|
||||
) {
|
||||
let invoiceCallNum = 0
|
||||
let entryCallNum = 0
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
},
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'customers') {
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: customer, error: null }),
|
||||
}
|
||||
}
|
||||
if (table === 'invoices') {
|
||||
invoiceCallNum += 1
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
order: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: QueryResult) => void) => resolve(invoicesResult),
|
||||
}
|
||||
}
|
||||
// journal_entries
|
||||
entryCallNum += 1
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: QueryResult) => void) => resolve(entriesResult),
|
||||
}
|
||||
}),
|
||||
_stats: () => ({ invoiceCallNum, entryCallNum }),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/ar-ledger/customer/[customerId]/invoices', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(null, null, { data: [], error: null }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/ar-ledger/customer/cust-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when customer is unknown', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, null, { data: [], error: null }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/ar-ledger/customer/cust-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('happy path: returns invoices with linked journal entries', async () => {
|
||||
const invoices = [
|
||||
{
|
||||
id: 'inv-1',
|
||||
invoice_number: '2026-001',
|
||||
invoice_date: '2026-05-01',
|
||||
due_date: '2026-06-01',
|
||||
total: 1250,
|
||||
paid_amount: 0,
|
||||
currency: 'SEK',
|
||||
exchange_rate: null,
|
||||
remaining_amount: 1250,
|
||||
notes: null,
|
||||
},
|
||||
]
|
||||
const entries = [
|
||||
{
|
||||
id: 'je-1',
|
||||
voucher_number: 22,
|
||||
voucher_series: 'A',
|
||||
description: 'Faktura 2026-001',
|
||||
source_id: 'inv-1',
|
||||
},
|
||||
]
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(
|
||||
{ id: 'user-1' },
|
||||
{ id: 'cust-1', name: 'Acme AB' },
|
||||
{ data: invoices, error: null },
|
||||
{ data: entries, error: null }
|
||||
) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/ar-ledger/customer/cust-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' }))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
customer_id: string
|
||||
customer_name: string
|
||||
lines: Array<{
|
||||
invoice_id: string
|
||||
voucher_number: number
|
||||
journal_entry_id: string
|
||||
outstanding: number
|
||||
}>
|
||||
}
|
||||
}
|
||||
|
||||
expect(body.data.customer_id).toBe('cust-1')
|
||||
expect(body.data.customer_name).toBe('Acme AB')
|
||||
expect(body.data.lines).toHaveLength(1)
|
||||
expect(body.data.lines[0].invoice_id).toBe('inv-1')
|
||||
expect(body.data.lines[0].journal_entry_id).toBe('je-1')
|
||||
expect(body.data.lines[0].voucher_number).toBe(22)
|
||||
expect(body.data.lines[0].outstanding).toBe(1250)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
|
||||
import type { ReportSourceLine } from '@/lib/reports/source-lines'
|
||||
|
||||
/**
|
||||
* GET /api/reports/ar-ledger/customer/[customerId]/invoices
|
||||
*
|
||||
* Returns the invoices that contribute to a customer's outstanding balance.
|
||||
* Each row exposes the registration journal entry (if any) via
|
||||
* `journal_entry_id`, so the UI can link directly to `/bookkeeping/[id]`.
|
||||
*
|
||||
* If an invoice has no posted registration entry yet (still draft), the
|
||||
* `journal_entry_id` is null and the UI must fall back to `/invoices/[id]`.
|
||||
*/
|
||||
const PAGE_LIMIT = 500
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ customerId: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const { customerId } = await params
|
||||
|
||||
// Verify customer belongs to the company.
|
||||
const { data: customer } = await supabase
|
||||
.from('customers')
|
||||
.select('id, name')
|
||||
.eq('id', customerId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!customer) {
|
||||
return NextResponse.json({ error: 'Kund saknas' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Pull this customer's outstanding invoices. Mirrors the filter in
|
||||
// `generateARLedger` so the UI sees the same set the aggregate is built
|
||||
// from.
|
||||
const { data, error } = await supabase
|
||||
.from('invoices')
|
||||
.select(`
|
||||
id,
|
||||
invoice_number,
|
||||
invoice_date,
|
||||
due_date,
|
||||
total,
|
||||
paid_amount,
|
||||
currency,
|
||||
exchange_rate,
|
||||
remaining_amount,
|
||||
notes
|
||||
`)
|
||||
.eq('company_id', companyId)
|
||||
.eq('customer_id', customerId)
|
||||
.in('status', ['sent', 'overdue', 'credited'])
|
||||
.order('invoice_date', { ascending: true })
|
||||
.limit(PAGE_LIMIT)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// For each invoice, find the registration journal entry (source_type =
|
||||
// 'invoice_created', source_id = invoice.id). We batch them to keep this
|
||||
// a single DB roundtrip.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const invoices = (data || []) as any[]
|
||||
const ids = invoices.map((i) => i.id)
|
||||
const entryMap = new Map<
|
||||
string,
|
||||
{ id: string; voucher_number: number; voucher_series: string; description: string | null }
|
||||
>()
|
||||
|
||||
if (ids.length > 0) {
|
||||
const { data: entries } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id, voucher_number, voucher_series, description, source_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('source_type', 'invoice_created')
|
||||
.in('source_id', ids)
|
||||
.in('status', ['posted', 'reversed'])
|
||||
|
||||
for (const e of entries || []) {
|
||||
entryMap.set(e.source_id, {
|
||||
id: e.id,
|
||||
voucher_number: e.voucher_number,
|
||||
voucher_series: e.voucher_series || 'A',
|
||||
description: e.description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Shape each invoice as a ReportSourceLine. The "debit" column carries
|
||||
// the outstanding SEK amount (it's a receivable on 1510); "credit" is 0
|
||||
// unless the invoice is fully a credit note.
|
||||
const lines: (ReportSourceLine & {
|
||||
invoice_id: string
|
||||
invoice_number: string | null
|
||||
outstanding: number
|
||||
outstanding_sek: number | null
|
||||
currency: string
|
||||
paid_amount: number
|
||||
due_date: string
|
||||
})[] = invoices.map((inv) => {
|
||||
const entry = entryMap.get(inv.id)
|
||||
const paidAmount = Number(inv.paid_amount) || 0
|
||||
const total = Number(inv.total) || 0
|
||||
const outstanding = Math.round((total - paidAmount) * 100) / 100
|
||||
const isFx = inv.currency && inv.currency !== 'SEK'
|
||||
const hasRate = inv.exchange_rate != null && Number(inv.exchange_rate) > 0
|
||||
const outstandingSek =
|
||||
isFx && !hasRate
|
||||
? null
|
||||
: resolveSekAmount(outstanding, null, inv.currency, inv.exchange_rate)
|
||||
|
||||
return {
|
||||
journal_entry_id: entry?.id ?? '',
|
||||
voucher_number: entry?.voucher_number ?? 0,
|
||||
voucher_series: entry?.voucher_series ?? 'A',
|
||||
date: inv.invoice_date || '',
|
||||
description:
|
||||
entry?.description ?? `Faktura ${inv.invoice_number || '(utkast)'}`,
|
||||
debit: outstandingSek ?? outstanding,
|
||||
credit: 0,
|
||||
invoice_id: inv.id,
|
||||
invoice_number: inv.invoice_number,
|
||||
outstanding,
|
||||
outstanding_sek: outstandingSek,
|
||||
currency: inv.currency || 'SEK',
|
||||
paid_amount: paidAmount,
|
||||
due_date: inv.due_date,
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
customer_id: customer.id,
|
||||
customer_name: customer.name,
|
||||
lines,
|
||||
next_cursor: null,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateARLedger } from '@/lib/reports/ar-ledger'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface AgingRow {
|
||||
customer_name: string
|
||||
current: number
|
||||
days_1_30: number
|
||||
days_31_60: number
|
||||
days_61_90: number
|
||||
days_90_plus: number
|
||||
total_outstanding: number
|
||||
}
|
||||
|
||||
interface InvoiceRow {
|
||||
customer_name: string
|
||||
invoice_number: string
|
||||
invoice_date: Date | string
|
||||
due_date: Date | string
|
||||
total: number
|
||||
paid_amount: number
|
||||
outstanding: number
|
||||
outstanding_sek: number | null
|
||||
days_overdue: number
|
||||
currency: string
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const asOfDate = searchParams.get('as_of_date') || undefined
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const ledger = await generateARLedger(supabase, companyId, asOfDate)
|
||||
|
||||
const agingRows: AgingRow[] = ledger.entries.map((e) => ({
|
||||
customer_name: e.customer_name,
|
||||
current: e.current,
|
||||
days_1_30: e.days_1_30,
|
||||
days_31_60: e.days_31_60,
|
||||
days_61_90: e.days_61_90,
|
||||
days_90_plus: e.days_90_plus,
|
||||
total_outstanding: e.total_outstanding,
|
||||
}))
|
||||
|
||||
const invoiceRows: InvoiceRow[] = []
|
||||
for (const e of ledger.entries) {
|
||||
for (const inv of e.invoices) {
|
||||
invoiceRows.push({
|
||||
customer_name: e.customer_name,
|
||||
invoice_number: inv.invoice_number,
|
||||
invoice_date: toDate(inv.invoice_date) ?? inv.invoice_date,
|
||||
due_date: toDate(inv.due_date) ?? inv.due_date,
|
||||
total: inv.total,
|
||||
paid_amount: inv.paid_amount,
|
||||
outstanding: inv.outstanding,
|
||||
outstanding_sek: inv.outstanding_sek,
|
||||
days_overdue: inv.days_overdue,
|
||||
currency: inv.currency,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const buffer = reportToWorkbook([
|
||||
{
|
||||
name: 'Åldersfördelning',
|
||||
columns: [
|
||||
textColumn('Kund'),
|
||||
currencyColumn('Ej förfallet'),
|
||||
currencyColumn('1-30 dagar'),
|
||||
currencyColumn('31-60 dagar'),
|
||||
currencyColumn('61-90 dagar'),
|
||||
currencyColumn('90+ dagar'),
|
||||
currencyColumn('Totalt utestående'),
|
||||
],
|
||||
rows: agingRows,
|
||||
mapRow: (r) => [
|
||||
r.customer_name,
|
||||
r.current,
|
||||
r.days_1_30,
|
||||
r.days_31_60,
|
||||
r.days_61_90,
|
||||
r.days_90_plus,
|
||||
r.total_outstanding,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Fakturor',
|
||||
columns: [
|
||||
textColumn('Kund'),
|
||||
textColumn('Fakturanr'),
|
||||
dateColumn('Fakturadatum'),
|
||||
dateColumn('Förfallodatum'),
|
||||
currencyColumn('Totalt'),
|
||||
currencyColumn('Betalt'),
|
||||
currencyColumn('Utestående'),
|
||||
currencyColumn('Utestående (SEK)'),
|
||||
integerColumn('Dagar förfallet'),
|
||||
textColumn('Valuta'),
|
||||
],
|
||||
rows: invoiceRows,
|
||||
mapRow: (r) => [
|
||||
r.customer_name,
|
||||
r.invoice_number,
|
||||
r.invoice_date instanceof Date ? r.invoice_date : null,
|
||||
r.due_date instanceof Date ? r.due_date : null,
|
||||
r.total,
|
||||
r.paid_amount,
|
||||
r.outstanding,
|
||||
r.outstanding_sek,
|
||||
r.days_overdue,
|
||||
r.currency,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'kundreskontra',
|
||||
companyRow?.company_name ?? '',
|
||||
asOfDate ?? new Date().toISOString().slice(0, 10),
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera kundreskontra' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateBalanceSheet } from '@/lib/reports/balance-sheet'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
section: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
amount: number
|
||||
isSubtotal: boolean
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateBalanceSheet(supabase, companyId, periodId)
|
||||
|
||||
// Flatten nested sections into a single tabular view, mirroring how the
|
||||
// PDF lays them out: each section's rows followed by a subtotal line, with
|
||||
// grand totals at the end. The "Sektion" column keeps the grouping queryable.
|
||||
const assetRows: FlatRow[] = []
|
||||
for (const s of report.asset_sections) {
|
||||
for (const r of s.rows) {
|
||||
assetRows.push({
|
||||
section: s.title,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
amount: r.amount,
|
||||
isSubtotal: false,
|
||||
})
|
||||
}
|
||||
assetRows.push({
|
||||
section: s.title,
|
||||
account_number: '',
|
||||
account_name: `Summa ${s.title}`,
|
||||
amount: s.subtotal,
|
||||
isSubtotal: true,
|
||||
})
|
||||
}
|
||||
assetRows.push({
|
||||
section: 'Tillgångar',
|
||||
account_number: '',
|
||||
account_name: 'Summa tillgångar',
|
||||
amount: report.total_assets,
|
||||
isSubtotal: true,
|
||||
})
|
||||
|
||||
const equityRows: FlatRow[] = []
|
||||
for (const s of report.equity_liability_sections) {
|
||||
for (const r of s.rows) {
|
||||
equityRows.push({
|
||||
section: s.title,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
amount: r.amount,
|
||||
isSubtotal: false,
|
||||
})
|
||||
}
|
||||
equityRows.push({
|
||||
section: s.title,
|
||||
account_number: '',
|
||||
account_name: `Summa ${s.title}`,
|
||||
amount: s.subtotal,
|
||||
isSubtotal: true,
|
||||
})
|
||||
}
|
||||
equityRows.push({
|
||||
section: 'Eget kapital och skulder',
|
||||
account_number: '',
|
||||
account_name: 'Summa eget kapital och skulder',
|
||||
amount: report.total_equity_liabilities,
|
||||
isSubtotal: true,
|
||||
})
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Tillgångar',
|
||||
columns: [
|
||||
textColumn('Sektion'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Belopp'),
|
||||
],
|
||||
rows: assetRows,
|
||||
mapRow: (r) => [r.section, r.account_number, r.account_name, r.amount],
|
||||
},
|
||||
{
|
||||
name: 'Eget kapital och skulder',
|
||||
columns: [
|
||||
textColumn('Sektion'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Belopp'),
|
||||
],
|
||||
rows: equityRows,
|
||||
mapRow: (r) => [r.section, r.account_number, r.account_name, r.amount],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('balansrakning', companyRow?.company_name ?? '', period.period_end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera balansräkning' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateBalansrapport } from '@/lib/reports/balansrapport'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
group: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
ib: number
|
||||
period_change: number
|
||||
ub: number
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateBalansrapport(supabase, companyId, periodId)
|
||||
|
||||
const rows: FlatRow[] = []
|
||||
for (const g of report.groups) {
|
||||
for (const r of g.rows) {
|
||||
rows.push({
|
||||
group: g.class_label,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
ib: r.ib,
|
||||
period_change: r.period_change,
|
||||
ub: r.ub,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
group: g.class_label,
|
||||
account_number: '',
|
||||
account_name: `Summa ${g.class_label}`,
|
||||
ib: g.subtotal_ib,
|
||||
period_change: Math.round((g.subtotal_ub - g.subtotal_ib) * 100) / 100,
|
||||
ub: g.subtotal_ub,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
group: 'Beräknat resultat',
|
||||
account_number: '',
|
||||
account_name: 'Beräknat resultat',
|
||||
ib: 0,
|
||||
period_change: report.beraknat_resultat,
|
||||
ub: report.beraknat_resultat,
|
||||
})
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Balansrapport',
|
||||
columns: [
|
||||
textColumn('Grupp'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('IB'),
|
||||
currencyColumn('Periodförändring'),
|
||||
currencyColumn('UB'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.group,
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.ib,
|
||||
r.period_change,
|
||||
r.ub,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'balansrapport',
|
||||
companyRow?.company_name ?? '',
|
||||
report.period.end,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera balansrapport' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateGeneralLedger } from '@/lib/reports/general-ledger'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
account_number: string
|
||||
account_name: string
|
||||
date: Date | string
|
||||
voucher: string
|
||||
description: string
|
||||
source_type: string
|
||||
debit: number
|
||||
credit: number
|
||||
balance: number
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | string {
|
||||
// Preserve original ISO string in the cell if parsing fails (avoids NaN
|
||||
// dates polluting the workbook).
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? s : d
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
const accountFrom = searchParams.get('account_from') || undefined
|
||||
const accountTo = searchParams.get('account_to') || undefined
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateGeneralLedger(supabase, companyId, periodId, accountFrom, accountTo)
|
||||
|
||||
// Flatten accounts + their lines into a single sheet. Each account contributes
|
||||
// an opening-balance row, its lines (with running balance), and a closing
|
||||
// row — matching how huvudbok is read in Fortnox/Visma.
|
||||
const rows: FlatRow[] = []
|
||||
for (const acc of report.accounts) {
|
||||
rows.push({
|
||||
account_number: acc.account_number,
|
||||
account_name: acc.account_name,
|
||||
date: '',
|
||||
voucher: '',
|
||||
description: 'Ingående balans',
|
||||
source_type: '',
|
||||
debit: 0,
|
||||
credit: 0,
|
||||
balance: acc.opening_balance,
|
||||
})
|
||||
for (const line of acc.lines) {
|
||||
rows.push({
|
||||
account_number: acc.account_number,
|
||||
account_name: acc.account_name,
|
||||
date: toDate(line.date),
|
||||
voucher: `${line.voucher_series}${line.voucher_number}`,
|
||||
description: line.description,
|
||||
source_type: line.source_type,
|
||||
debit: line.debit,
|
||||
credit: line.credit,
|
||||
balance: line.balance,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
account_number: acc.account_number,
|
||||
account_name: acc.account_name,
|
||||
date: '',
|
||||
voucher: '',
|
||||
description: 'Utgående balans',
|
||||
source_type: '',
|
||||
debit: acc.total_debit,
|
||||
credit: acc.total_credit,
|
||||
balance: acc.closing_balance,
|
||||
})
|
||||
}
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Huvudbok',
|
||||
columns: [
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
dateColumn('Datum'),
|
||||
textColumn('Verifikat'),
|
||||
textColumn('Beskrivning'),
|
||||
textColumn('Källa'),
|
||||
currencyColumn('Debet'),
|
||||
currencyColumn('Kredit'),
|
||||
currencyColumn('Saldo'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.date instanceof Date ? r.date : null,
|
||||
r.voucher,
|
||||
r.description,
|
||||
r.source_type,
|
||||
r.debit,
|
||||
r.credit,
|
||||
r.balance,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('huvudbok', companyRow?.company_name ?? '', report.period.end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera huvudbok' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import type { IncomeStatementSection } from '@/types'
|
||||
|
||||
interface FlatRow {
|
||||
section: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
function flatten(
|
||||
sections: IncomeStatementSection[],
|
||||
groupLabel: string,
|
||||
groupTotalLabel: string,
|
||||
groupTotal: number,
|
||||
): FlatRow[] {
|
||||
const rows: FlatRow[] = []
|
||||
for (const s of sections) {
|
||||
for (const r of s.rows) {
|
||||
rows.push({
|
||||
section: s.title,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
amount: r.amount,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
section: s.title,
|
||||
account_number: '',
|
||||
account_name: `Summa ${s.title}`,
|
||||
amount: s.subtotal,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
section: groupLabel,
|
||||
account_number: '',
|
||||
account_name: groupTotalLabel,
|
||||
amount: groupTotal,
|
||||
})
|
||||
return rows
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateIncomeStatement(supabase, companyId, periodId)
|
||||
|
||||
const revenueRows = flatten(
|
||||
report.revenue_sections,
|
||||
'Rörelseintäkter',
|
||||
'Summa rörelseintäkter',
|
||||
report.total_revenue,
|
||||
)
|
||||
const expenseRows = flatten(
|
||||
report.expense_sections,
|
||||
'Rörelsekostnader',
|
||||
'Summa rörelsekostnader',
|
||||
report.total_expenses,
|
||||
)
|
||||
const financialRows = flatten(
|
||||
report.financial_sections,
|
||||
'Finansiella poster',
|
||||
'Summa finansiella poster',
|
||||
report.total_financial,
|
||||
)
|
||||
|
||||
const summaryRows: FlatRow[] = [
|
||||
{
|
||||
section: 'Sammanfattning',
|
||||
account_number: '',
|
||||
account_name: 'Rörelseresultat',
|
||||
amount: Math.round((report.total_revenue - report.total_expenses) * 100) / 100,
|
||||
},
|
||||
{
|
||||
section: 'Sammanfattning',
|
||||
account_number: '',
|
||||
account_name: 'Årets resultat',
|
||||
amount: report.net_result,
|
||||
},
|
||||
]
|
||||
|
||||
const columns = [
|
||||
textColumn('Sektion'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Belopp'),
|
||||
]
|
||||
const mapRow = (r: FlatRow) => [r.section, r.account_number, r.account_name, r.amount]
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{ name: 'Intäkter', columns, rows: revenueRows, mapRow },
|
||||
{ name: 'Kostnader', columns, rows: expenseRows, mapRow },
|
||||
{ name: 'Finansiella poster', columns, rows: financialRows, mapRow },
|
||||
{ name: 'Sammanfattning', columns, rows: summaryRows, mapRow },
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'resultatrakning',
|
||||
companyRow?.company_name ?? '',
|
||||
period.period_end,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera resultaträkning' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateJournalRegister } from '@/lib/reports/journal-register'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
voucher: string
|
||||
date: Date | null
|
||||
description: string
|
||||
source_type: string
|
||||
status: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
debit: number
|
||||
credit: number
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateJournalRegister(supabase, companyId, periodId)
|
||||
|
||||
// Flatten: one row per (entry, line). Voucher metadata repeats so the
|
||||
// file is filterable in Excel without losing context.
|
||||
const rows: FlatRow[] = []
|
||||
for (const entry of report.entries) {
|
||||
const voucherLabel = `${entry.voucher_series}${entry.voucher_number}`
|
||||
for (const line of entry.lines) {
|
||||
rows.push({
|
||||
voucher: voucherLabel,
|
||||
date: toDate(entry.date),
|
||||
description: entry.description,
|
||||
source_type: entry.source_type,
|
||||
status: entry.status,
|
||||
account_number: line.account_number,
|
||||
account_name: line.account_name,
|
||||
debit: line.debit,
|
||||
credit: line.credit,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Grundbok',
|
||||
columns: [
|
||||
textColumn('Verifikat'),
|
||||
dateColumn('Datum'),
|
||||
textColumn('Beskrivning'),
|
||||
textColumn('Källa'),
|
||||
textColumn('Status'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Debet'),
|
||||
currencyColumn('Kredit'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.voucher,
|
||||
r.date,
|
||||
r.description,
|
||||
r.source_type,
|
||||
r.status,
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.debit,
|
||||
r.credit,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('grundbok', companyRow?.company_name ?? '', report.period.end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera grundbok' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { generateKassaflodesanalys } from '@/lib/reports/kassaflodesanalys'
|
||||
import { KassaflodesanalysPDF } from '@/lib/reports/kassaflodesanalys-pdf-template'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!companyRow) {
|
||||
return NextResponse.json({ error: 'Företagsinställningar saknas' }, { status: 404 })
|
||||
}
|
||||
// An identifiable period is part of räkenskapsinformation (BFL 7 kap). Refuse
|
||||
// to render a PDF that can't be archived with the period it refers to.
|
||||
if (!period) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
'Räkenskapsperioden kunde inte läsas. Välj en befintlig period innan du genererar PDF.',
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateKassaflodesanalys(supabase, companyId, periodId)
|
||||
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
KassaflodesanalysPDF({
|
||||
report,
|
||||
company: companyRow as CompanySettings,
|
||||
generatedAt: new Date().toISOString(),
|
||||
})
|
||||
)
|
||||
|
||||
const filename = `kassaflodesanalys-${report.period_start}.pdf`
|
||||
|
||||
return new Response(new Uint8Array(pdfBuffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera kassaflödesanalys' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateKassaflodesanalys } from '@/lib/reports/kassaflodesanalys'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await generateKassaflodesanalys(supabase, companyId, periodId)
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to generate kassaflödesanalys' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||||
import { generateTrialBalance } from '@/lib/reports/trial-balance'
|
||||
import { generateARLedger } from '@/lib/reports/ar-ledger'
|
||||
import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown'
|
||||
import {
|
||||
calculateCashPosition,
|
||||
calculateGrossMargin,
|
||||
calculateExpenseRatio,
|
||||
calculateAvgPaymentDays,
|
||||
} from '@/lib/reports/kpi'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
percentColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface KpiKv {
|
||||
label: string
|
||||
value: number | null
|
||||
}
|
||||
|
||||
interface MonthRow {
|
||||
label: string
|
||||
income: number
|
||||
expenses: number
|
||||
net: number
|
||||
}
|
||||
|
||||
interface CompositionRow {
|
||||
klass: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
interface SupplierRow {
|
||||
supplier_name: string
|
||||
total: number
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end, is_closed')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
try {
|
||||
const [
|
||||
incomeStatement,
|
||||
trialBalanceResult,
|
||||
arLedger,
|
||||
monthlyBreakdown,
|
||||
paidInvoicesResult,
|
||||
topSuppliersResult,
|
||||
] = await Promise.all([
|
||||
generateIncomeStatement(supabase, companyId, periodId),
|
||||
generateTrialBalance(supabase, companyId, periodId),
|
||||
generateARLedger(supabase, companyId),
|
||||
generateMonthlyBreakdown(supabase, companyId, periodId),
|
||||
supabase
|
||||
.from('invoices')
|
||||
.select('invoice_date, paid_at')
|
||||
.eq('company_id', companyId)
|
||||
.eq('status', 'paid')
|
||||
.not('paid_at', 'is', null),
|
||||
supabase
|
||||
.from('supplier_invoices')
|
||||
.select('supplier_id, total_sek, total, supplier:suppliers(id, name)')
|
||||
.eq('company_id', companyId)
|
||||
.gte('invoice_date', period.period_start)
|
||||
.lte('invoice_date', period.period_end)
|
||||
.neq('status', 'credited'),
|
||||
])
|
||||
|
||||
const cashPosition = calculateCashPosition(trialBalanceResult.rows)
|
||||
const vatOutputAccounts = ['2611', '2621', '2631']
|
||||
const vatInputAccounts = ['2641', '2645']
|
||||
const outputVat = trialBalanceResult.rows
|
||||
.filter((r) => vatOutputAccounts.includes(r.account_number))
|
||||
.reduce((sum, r) => sum + (r.closing_credit - r.closing_debit), 0)
|
||||
const inputVat = trialBalanceResult.rows
|
||||
.filter((r) => vatInputAccounts.includes(r.account_number))
|
||||
.reduce((sum, r) => sum + (r.closing_debit - r.closing_credit), 0)
|
||||
const vatLiability = Math.round((outputVat - inputVat) * 100) / 100
|
||||
|
||||
const paidInvoices = (paidInvoicesResult.data ?? []).map((inv) => ({
|
||||
invoice_date: inv.invoice_date as string,
|
||||
paid_at: inv.paid_at as string,
|
||||
}))
|
||||
|
||||
// Expense composition by BAS class (mirrors KPI JSON route logic).
|
||||
const expenseComposition = trialBalanceResult.rows.reduce(
|
||||
(acc, r) => {
|
||||
if (r.account_class < 4 || r.account_class > 7) return acc
|
||||
const amount = r.closing_debit - r.closing_credit
|
||||
if (amount <= 0) return acc
|
||||
if (r.account_class === 4) acc.class4 += amount
|
||||
else if (r.account_class === 5) acc.class5 += amount
|
||||
else if (r.account_class === 6) acc.class6 += amount
|
||||
else if (r.account_class === 7) acc.class7 += amount
|
||||
return acc
|
||||
},
|
||||
{ class4: 0, class5: 0, class6: 0, class7: 0 },
|
||||
)
|
||||
|
||||
type SupplierInvoiceRow = {
|
||||
supplier_id: string | null
|
||||
total_sek: number | null
|
||||
total: number | null
|
||||
supplier: { id: string; name: string } | { id: string; name: string }[] | null
|
||||
}
|
||||
const supplierTotals = new Map<string, { name: string; total: number }>()
|
||||
for (const row of (topSuppliersResult.data ?? []) as SupplierInvoiceRow[]) {
|
||||
if (!row.supplier_id) continue
|
||||
const supplier = Array.isArray(row.supplier) ? row.supplier[0] : row.supplier
|
||||
if (!supplier?.name) continue
|
||||
const amount = row.total_sek ?? null
|
||||
if (amount == null) continue
|
||||
const existing = supplierTotals.get(row.supplier_id)
|
||||
if (existing) existing.total += amount
|
||||
else supplierTotals.set(row.supplier_id, { name: supplier.name, total: amount })
|
||||
}
|
||||
const topSuppliers = Array.from(supplierTotals.values())
|
||||
.map((v) => ({
|
||||
supplier_name: v.name,
|
||||
total: Math.round(v.total * 100) / 100,
|
||||
}))
|
||||
.sort((a, b) => b.total - a.total)
|
||||
.slice(0, 7)
|
||||
|
||||
// Sheet 1: scalar KPIs, label + value. Currency by default; percent rows
|
||||
// are split into a separate sheet so the formatting is unambiguous.
|
||||
const currencyKpis: KpiKv[] = [
|
||||
{ label: 'Årets resultat', value: incomeStatement.net_result },
|
||||
{ label: 'Likvida medel', value: cashPosition },
|
||||
{ label: 'Utestående kundfordringar', value: arLedger.total_outstanding },
|
||||
{ label: 'Förfallna kundfordringar', value: arLedger.total_overdue },
|
||||
{ label: 'Momsskuld (ruta 49)', value: vatLiability },
|
||||
{ label: 'Totala intäkter', value: incomeStatement.total_revenue },
|
||||
{ label: 'Totala kostnader', value: incomeStatement.total_expenses },
|
||||
]
|
||||
|
||||
const percentKpis: KpiKv[] = [
|
||||
// calculateGrossMargin returns percentage as `25.5` (i.e. percent units).
|
||||
// The xlsx percent format expects fractional values (0.255 → 25.50%).
|
||||
// Divide by 100 so the displayed value matches the in-app KPI tile.
|
||||
{ label: 'Bruttomarginal', value: scaleToFraction(calculateGrossMargin(incomeStatement)) },
|
||||
{ label: 'Kostnadsandel', value: scaleToFraction(calculateExpenseRatio(incomeStatement)) },
|
||||
]
|
||||
|
||||
const integerKpis: KpiKv[] = [
|
||||
{ label: 'Genomsnittliga betaldagar', value: calculateAvgPaymentDays(paidInvoices) },
|
||||
]
|
||||
|
||||
const monthRows: MonthRow[] = monthlyBreakdown.months
|
||||
|
||||
const compositionRows: CompositionRow[] = [
|
||||
{ klass: '4 — Material/varor', amount: Math.round(expenseComposition.class4 * 100) / 100 },
|
||||
{ klass: '5 — Externa kostnader', amount: Math.round(expenseComposition.class5 * 100) / 100 },
|
||||
{ klass: '6 — Externa kostnader', amount: Math.round(expenseComposition.class6 * 100) / 100 },
|
||||
{ klass: '7 — Personalkostnader', amount: Math.round(expenseComposition.class7 * 100) / 100 },
|
||||
]
|
||||
|
||||
const supplierRows: SupplierRow[] = topSuppliers
|
||||
|
||||
const buffer = reportToWorkbook([
|
||||
{
|
||||
name: 'Nyckeltal (kr)',
|
||||
columns: [textColumn('Nyckeltal'), currencyColumn('Värde')],
|
||||
rows: currencyKpis,
|
||||
mapRow: (r) => [r.label, r.value],
|
||||
},
|
||||
{
|
||||
name: 'Nyckeltal (%)',
|
||||
columns: [textColumn('Nyckeltal'), percentColumn('Värde')],
|
||||
rows: percentKpis,
|
||||
mapRow: (r) => [r.label, r.value],
|
||||
},
|
||||
{
|
||||
name: 'Nyckeltal (övrigt)',
|
||||
columns: [textColumn('Nyckeltal'), integerColumn('Värde')],
|
||||
rows: integerKpis,
|
||||
mapRow: (r) => [r.label, r.value],
|
||||
},
|
||||
{
|
||||
name: 'Månadsbrytning',
|
||||
columns: [
|
||||
textColumn('Månad'),
|
||||
currencyColumn('Intäkter'),
|
||||
currencyColumn('Kostnader'),
|
||||
currencyColumn('Netto'),
|
||||
],
|
||||
rows: monthRows,
|
||||
mapRow: (m) => [m.label, m.income, m.expenses, m.net],
|
||||
},
|
||||
{
|
||||
name: 'Kostnadssammansättning',
|
||||
columns: [textColumn('Kontoklass'), currencyColumn('Belopp')],
|
||||
rows: compositionRows,
|
||||
mapRow: (r) => [r.klass, r.amount],
|
||||
},
|
||||
{
|
||||
name: 'Topp leverantörer',
|
||||
columns: [textColumn('Leverantör'), currencyColumn('Totalt')],
|
||||
rows: supplierRows,
|
||||
mapRow: (r) => [r.supplier_name, r.total],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('nyckeltal', companyRow?.company_name ?? '', period.period_end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera nyckeltalsrapport' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function scaleToFraction(value: number | null): number | null {
|
||||
return value === null ? null : Math.round(value) / 100
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
try {
|
||||
const breakdown = await generateMonthlyBreakdown(supabase, companyId, periodId)
|
||||
|
||||
const buffer = reportToWorkbook([
|
||||
{
|
||||
name: 'Månadsbrytning',
|
||||
columns: [
|
||||
textColumn('Månad'),
|
||||
currencyColumn('Intäkter'),
|
||||
currencyColumn('Kostnader'),
|
||||
currencyColumn('Netto'),
|
||||
],
|
||||
rows: breakdown.months,
|
||||
mapRow: (m) => [m.label, m.income, m.expenses, m.net],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'manadsbrytning',
|
||||
companyRow?.company_name ?? '',
|
||||
period?.period_end ?? new Date().toISOString().slice(0, 10),
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera månadsbrytning' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateResultatrapport } from '@/lib/reports/resultatrapport'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
group: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
current_period: number
|
||||
prior_period: number
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateResultatrapport(supabase, companyId, periodId)
|
||||
|
||||
const rows: FlatRow[] = []
|
||||
for (const g of report.groups) {
|
||||
for (const r of g.rows) {
|
||||
rows.push({
|
||||
group: g.class_label,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
current_period: r.current_period,
|
||||
prior_period: r.prior_period,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
group: g.class_label,
|
||||
account_number: '',
|
||||
account_name: `Summa ${g.class_label}`,
|
||||
current_period: g.subtotal_current,
|
||||
prior_period: g.subtotal_prior,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
group: 'Resultat',
|
||||
account_number: '',
|
||||
account_name: 'Årets resultat',
|
||||
current_period: report.net_result_current,
|
||||
prior_period: report.net_result_prior,
|
||||
})
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Resultatrapport',
|
||||
columns: [
|
||||
textColumn('Grupp'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Aktuell period'),
|
||||
currencyColumn('Föregående period'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.group,
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.current_period,
|
||||
r.prior_period,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'resultatrapport',
|
||||
companyRow?.company_name ?? '',
|
||||
report.period.end,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera resultatrapport' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { generateSalaryJournal } from '@/lib/reports/salary-journal'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const year = parseInt(searchParams.get('year') || new Date().getFullYear().toString())
|
||||
const monthFrom = searchParams.get('month_from') ? parseInt(searchParams.get('month_from')!) : undefined
|
||||
const monthTo = searchParams.get('month_to') ? parseInt(searchParams.get('month_to')!) : undefined
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateSalaryJournal(supabase, companyId, year, monthFrom, monthTo)
|
||||
|
||||
const buffer = reportToWorkbook([
|
||||
{
|
||||
name: 'Lönejournal',
|
||||
columns: [
|
||||
textColumn('Anställd'),
|
||||
textColumn('Personnr (4)'),
|
||||
textColumn('Anställning'),
|
||||
integerColumn('År'),
|
||||
integerColumn('Månad'),
|
||||
dateColumn('Utbetalningsdatum'),
|
||||
currencyColumn('Bruttolön'),
|
||||
currencyColumn('Skatt'),
|
||||
currencyColumn('Nettolön'),
|
||||
currencyColumn('Arbetsgivaravgifter'),
|
||||
currencyColumn('Semesterlönereservation'),
|
||||
currencyColumn('Semesterskuld avgifter'),
|
||||
currencyColumn('Total arbetsgivarkostnad'),
|
||||
integerColumn('Sjukdagar'),
|
||||
integerColumn('VAB-dagar'),
|
||||
integerColumn('Föräldradagar'),
|
||||
integerColumn('Semesterdagar uttagna'),
|
||||
textColumn('Status'),
|
||||
],
|
||||
rows: report.rows,
|
||||
mapRow: (r) => [
|
||||
r.employeeName,
|
||||
r.personnummerLast4,
|
||||
r.employmentType,
|
||||
r.periodYear,
|
||||
r.periodMonth,
|
||||
toDate(r.paymentDate),
|
||||
r.grossSalary,
|
||||
r.taxWithheld,
|
||||
r.netSalary,
|
||||
r.avgifterAmount,
|
||||
r.vacationAccrual,
|
||||
r.vacationAccrualAvgifter,
|
||||
r.totalEmployerCost,
|
||||
r.sickDays,
|
||||
r.vabDays,
|
||||
r.parentalDays,
|
||||
r.vacationDaysTaken,
|
||||
r.salaryRunStatus,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
// Use the period's last month-end as the filename anchor. For full-year
|
||||
// reports this is `YYYY-12-31`; for narrowed month ranges we approximate
|
||||
// with the end month's last day (good enough for filename ordering).
|
||||
const endMonth = monthTo ?? 12
|
||||
const periodAnchor = `${year}-${String(endMonth).padStart(2, '0')}-31`
|
||||
const filename = xlsxFilename(
|
||||
'lonejournal',
|
||||
companyRow?.company_name ?? '',
|
||||
periodAnchor,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera lönejournal' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/bookkeeping/currency-utils', () => ({
|
||||
resolveSekAmount: vi.fn((amount: number) => amount),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
interface QueryResult {
|
||||
data: unknown
|
||||
error: unknown
|
||||
}
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string } | null,
|
||||
supplier: { id: string; name: string } | null,
|
||||
invoicesResult: QueryResult,
|
||||
entriesResult: QueryResult
|
||||
) {
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
},
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'suppliers') {
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: supplier, error: null }),
|
||||
}
|
||||
}
|
||||
if (table === 'supplier_invoices') {
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
order: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: QueryResult) => void) => resolve(invoicesResult),
|
||||
}
|
||||
}
|
||||
// journal_entries
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: QueryResult) => void) => resolve(entriesResult),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/supplier-ledger/supplier/[supplierId]/invoices', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(null, null, { data: [], error: null }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/supplier-ledger/supplier/sup-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when supplier is unknown', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, null, { data: [], error: null }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/supplier-ledger/supplier/sup-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('happy path: returns supplier invoices with journal entries', async () => {
|
||||
const invoices = [
|
||||
{
|
||||
id: 'si-1',
|
||||
supplier_invoice_number: 'INV-7',
|
||||
invoice_date: '2026-05-10',
|
||||
due_date: '2026-06-10',
|
||||
total: 2500,
|
||||
paid_amount: 0,
|
||||
remaining_amount: 2500,
|
||||
currency: 'SEK',
|
||||
exchange_rate: null,
|
||||
registration_journal_entry_id: 'je-3',
|
||||
},
|
||||
]
|
||||
const entries = [
|
||||
{
|
||||
id: 'je-3',
|
||||
voucher_number: 33,
|
||||
voucher_series: 'B',
|
||||
description: 'Leverantörsfaktura INV-7',
|
||||
entry_date: '2026-05-10',
|
||||
},
|
||||
]
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(
|
||||
{ id: 'user-1' },
|
||||
{ id: 'sup-1', name: 'Office Supply AB' },
|
||||
{ data: invoices, error: null },
|
||||
{ data: entries, error: null }
|
||||
) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/supplier-ledger/supplier/sup-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' }))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
supplier_id: string
|
||||
supplier_name: string
|
||||
lines: Array<{
|
||||
supplier_invoice_id: string
|
||||
journal_entry_id: string
|
||||
voucher_number: number
|
||||
credit: number
|
||||
}>
|
||||
}
|
||||
}
|
||||
|
||||
expect(body.data.supplier_id).toBe('sup-1')
|
||||
expect(body.data.supplier_name).toBe('Office Supply AB')
|
||||
expect(body.data.lines).toHaveLength(1)
|
||||
expect(body.data.lines[0].supplier_invoice_id).toBe('si-1')
|
||||
expect(body.data.lines[0].journal_entry_id).toBe('je-3')
|
||||
expect(body.data.lines[0].voucher_number).toBe(33)
|
||||
expect(body.data.lines[0].credit).toBe(2500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
|
||||
import type { ReportSourceLine } from '@/lib/reports/source-lines'
|
||||
|
||||
/**
|
||||
* GET /api/reports/supplier-ledger/supplier/[supplierId]/invoices
|
||||
*
|
||||
* Returns the supplier invoices behind a supplier's outstanding balance.
|
||||
* Each row's `journal_entry_id` points at the registration journal entry
|
||||
* (when posted) so the UI can link to `/bookkeeping/[id]`.
|
||||
*/
|
||||
const PAGE_LIMIT = 500
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ supplierId: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const { supplierId } = await params
|
||||
|
||||
const { data: supplier } = await supabase
|
||||
.from('suppliers')
|
||||
.select('id, name')
|
||||
.eq('id', supplierId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!supplier) {
|
||||
return NextResponse.json({ error: 'Leverantör saknas' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Mirror `generateSupplierLedger`'s filter: registered/approved/partially
|
||||
// paid/overdue invoices that still have an outstanding balance.
|
||||
const { data, error } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select(`
|
||||
id,
|
||||
supplier_invoice_number,
|
||||
invoice_date,
|
||||
due_date,
|
||||
total,
|
||||
paid_amount,
|
||||
remaining_amount,
|
||||
currency,
|
||||
exchange_rate,
|
||||
registration_journal_entry_id
|
||||
`)
|
||||
.eq('company_id', companyId)
|
||||
.eq('supplier_id', supplierId)
|
||||
.in('status', ['registered', 'approved', 'partially_paid', 'overdue'])
|
||||
.order('invoice_date', { ascending: true })
|
||||
.limit(PAGE_LIMIT)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const invoices = (data || []) as any[]
|
||||
|
||||
// Pull the registration entries in one batch to get voucher numbers.
|
||||
const entryIds = invoices
|
||||
.map((i) => i.registration_journal_entry_id)
|
||||
.filter((id): id is string => !!id)
|
||||
const entryMap = new Map<
|
||||
string,
|
||||
{ voucher_number: number; voucher_series: string; description: string | null; entry_date: string }
|
||||
>()
|
||||
if (entryIds.length > 0) {
|
||||
const { data: entries } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id, voucher_number, voucher_series, description, entry_date')
|
||||
.eq('company_id', companyId)
|
||||
.in('id', entryIds)
|
||||
.in('status', ['posted', 'reversed'])
|
||||
for (const e of entries || []) {
|
||||
entryMap.set(e.id, {
|
||||
voucher_number: e.voucher_number,
|
||||
voucher_series: e.voucher_series || 'A',
|
||||
description: e.description,
|
||||
entry_date: e.entry_date,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const lines: (ReportSourceLine & {
|
||||
supplier_invoice_id: string
|
||||
supplier_invoice_number: string
|
||||
remaining_sek: number | null
|
||||
currency: string
|
||||
paid_amount: number
|
||||
due_date: string
|
||||
})[] = invoices.map((inv) => {
|
||||
const entry = inv.registration_journal_entry_id
|
||||
? entryMap.get(inv.registration_journal_entry_id)
|
||||
: undefined
|
||||
|
||||
const remaining = Number(inv.remaining_amount) || 0
|
||||
const isFx = inv.currency && inv.currency !== 'SEK'
|
||||
const hasRate = inv.exchange_rate != null && Number(inv.exchange_rate) > 0
|
||||
const remainingSek =
|
||||
isFx && !hasRate
|
||||
? null
|
||||
: resolveSekAmount(remaining, null, inv.currency, inv.exchange_rate)
|
||||
|
||||
return {
|
||||
journal_entry_id: inv.registration_journal_entry_id || '',
|
||||
voucher_number: entry?.voucher_number ?? 0,
|
||||
voucher_series: entry?.voucher_series ?? 'A',
|
||||
date: inv.invoice_date || entry?.entry_date || '',
|
||||
description:
|
||||
entry?.description ??
|
||||
`Leverantörsfaktura ${inv.supplier_invoice_number || ''}`,
|
||||
debit: 0,
|
||||
// For an unpaid AP entry, the open balance is a credit on 2440.
|
||||
credit: remainingSek ?? remaining,
|
||||
supplier_invoice_id: inv.id,
|
||||
supplier_invoice_number: inv.supplier_invoice_number || '',
|
||||
remaining_sek: remainingSek,
|
||||
currency: inv.currency || 'SEK',
|
||||
paid_amount: Number(inv.paid_amount) || 0,
|
||||
due_date: inv.due_date,
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
supplier_id: supplier.id,
|
||||
supplier_name: supplier.name,
|
||||
lines,
|
||||
next_cursor: null,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateSupplierLedger } from '@/lib/reports/supplier-ledger'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface AgingRow {
|
||||
supplier_name: string
|
||||
current: number
|
||||
days_1_30: number
|
||||
days_31_60: number
|
||||
days_61_90: number
|
||||
days_90_plus: number
|
||||
total_outstanding: number
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const asOfDate = searchParams.get('as_of_date') || undefined
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const ledger = await generateSupplierLedger(supabase, companyId, asOfDate)
|
||||
|
||||
const rows: AgingRow[] = ledger.entries.map((e) => ({
|
||||
supplier_name: e.supplier_name,
|
||||
current: e.current,
|
||||
days_1_30: e.days_1_30,
|
||||
days_31_60: e.days_31_60,
|
||||
days_61_90: e.days_61_90,
|
||||
days_90_plus: e.days_90_plus,
|
||||
total_outstanding: e.total_outstanding,
|
||||
}))
|
||||
|
||||
const buffer = reportToWorkbook<AgingRow>([
|
||||
{
|
||||
name: 'Leverantörsreskontra',
|
||||
columns: [
|
||||
textColumn('Leverantör'),
|
||||
currencyColumn('Ej förfallet'),
|
||||
currencyColumn('1-30 dagar'),
|
||||
currencyColumn('31-60 dagar'),
|
||||
currencyColumn('61-90 dagar'),
|
||||
currencyColumn('90+ dagar'),
|
||||
currencyColumn('Totalt utestående'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.supplier_name,
|
||||
r.current,
|
||||
r.days_1_30,
|
||||
r.days_31_60,
|
||||
r.days_61_90,
|
||||
r.days_90_plus,
|
||||
r.total_outstanding,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'leverantorsreskontra',
|
||||
companyRow?.company_name ?? '',
|
||||
asOfDate ?? new Date().toISOString().slice(0, 10),
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera leverantörsreskontra' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
interface AuthShape {
|
||||
auth: { getUser: ReturnType<typeof vi.fn> }
|
||||
from: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string } | null,
|
||||
account: { account_number: string; account_name: string } | null,
|
||||
linesResult: { data: unknown; error: unknown }
|
||||
): AuthShape {
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
},
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'chart_of_accounts') {
|
||||
const chain = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: account, error: null }),
|
||||
}
|
||||
return chain
|
||||
}
|
||||
// journal_entry_lines
|
||||
const chain = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
gte: vi.fn().mockReturnThis(),
|
||||
lte: vi.fn().mockReturnThis(),
|
||||
order: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
or: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: unknown) => void) => resolve(linesResult),
|
||||
}
|
||||
return chain
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/trial-balance/account/[accountNumber]/sources', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(null, null, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/trial-balance/account/1930/sources',
|
||||
{ searchParams: { fiscal_period_id: 'period-1' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ accountNumber: '1930' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when fiscal_period_id is missing', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, null, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/trial-balance/account/1930/sources'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ accountNumber: '1930' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when account is unknown for the company', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, null, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/trial-balance/account/9999/sources',
|
||||
{ searchParams: { fiscal_period_id: 'period-1' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ accountNumber: '9999' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('happy path: returns mapped lines for an account', async () => {
|
||||
const linesData = [
|
||||
{
|
||||
debit_amount: 1250,
|
||||
credit_amount: 0,
|
||||
journal_entry_id: 'je-1',
|
||||
journal_entries: {
|
||||
id: 'je-1',
|
||||
voucher_number: 7,
|
||||
voucher_series: 'A',
|
||||
entry_date: '2026-05-02',
|
||||
description: 'Provision',
|
||||
status: 'posted',
|
||||
company_id: 'company-1',
|
||||
fiscal_period_id: 'period-1',
|
||||
},
|
||||
},
|
||||
{
|
||||
debit_amount: 0,
|
||||
credit_amount: 700,
|
||||
journal_entry_id: 'je-2',
|
||||
journal_entries: {
|
||||
id: 'je-2',
|
||||
voucher_number: 8,
|
||||
voucher_series: 'A',
|
||||
entry_date: '2026-05-03',
|
||||
description: 'Återbet',
|
||||
status: 'posted',
|
||||
company_id: 'company-1',
|
||||
fiscal_period_id: 'period-1',
|
||||
},
|
||||
},
|
||||
]
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(
|
||||
{ id: 'user-1' },
|
||||
{ account_number: '1930', account_name: 'Företagskonto' },
|
||||
{ data: linesData, error: null }
|
||||
) as never
|
||||
)
|
||||
|
||||
const req = createMockRequest(
|
||||
'/api/reports/trial-balance/account/1930/sources',
|
||||
{ searchParams: { fiscal_period_id: 'period-1' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ accountNumber: '1930' }))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
account_number: string
|
||||
account_name: string
|
||||
lines: Array<{ voucher_number: number; debit: number; credit: number; journal_entry_id: string }>
|
||||
next_cursor: string | null
|
||||
}
|
||||
}
|
||||
|
||||
expect(body.data.account_number).toBe('1930')
|
||||
expect(body.data.account_name).toBe('Företagskonto')
|
||||
expect(body.data.lines).toHaveLength(2)
|
||||
expect(body.data.lines[0].voucher_number).toBe(7)
|
||||
expect(body.data.lines[0].debit).toBe(1250)
|
||||
expect(body.data.lines[0].journal_entry_id).toBe('je-1')
|
||||
expect(body.data.lines[1].credit).toBe(700)
|
||||
expect(body.data.next_cursor).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { ReportSourceLine } from '@/lib/reports/source-lines'
|
||||
|
||||
/**
|
||||
* GET /api/reports/trial-balance/account/[accountNumber]/sources
|
||||
*
|
||||
* Returns the journal entry lines for one account in a fiscal period,
|
||||
* ordered by entry date then voucher number ASC. Used by the trial balance
|
||||
* drilldown UI to show the verifikat behind an aggregated row.
|
||||
*
|
||||
* Pagination uses an opaque cursor of `<entry_date>|<voucher_number>` for
|
||||
* the last seen row; pass it back as `cursor` to continue.
|
||||
*/
|
||||
const PAGE_LIMIT = 500
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ accountNumber: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const { accountNumber } = await params
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const fiscalPeriodId = searchParams.get('fiscal_period_id')
|
||||
const cursor = searchParams.get('cursor')
|
||||
|
||||
if (!fiscalPeriodId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'fiscal_period_id is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Look up account name (and verify account belongs to the company)
|
||||
const { data: account } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.select('account_number, account_name')
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_number', accountNumber)
|
||||
.maybeSingle()
|
||||
|
||||
if (!account) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Konto saknas' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Pull all lines on this account in this period. We rely on the same
|
||||
// join+filter pattern as `generateTrialBalance`. Pagination is server-side
|
||||
// via cursor so even an account with tens of thousands of rows stays cheap.
|
||||
let query = supabase
|
||||
.from('journal_entry_lines')
|
||||
.select(`
|
||||
debit_amount,
|
||||
credit_amount,
|
||||
journal_entry_id,
|
||||
journal_entries!inner(
|
||||
id,
|
||||
voucher_number,
|
||||
voucher_series,
|
||||
entry_date,
|
||||
description,
|
||||
status,
|
||||
company_id,
|
||||
fiscal_period_id
|
||||
)
|
||||
`)
|
||||
.eq('account_number', accountNumber)
|
||||
.eq('journal_entries.company_id', companyId)
|
||||
.eq('journal_entries.fiscal_period_id', fiscalPeriodId)
|
||||
.in('journal_entries.status', ['posted', 'reversed'])
|
||||
.order('entry_date', { foreignTable: 'journal_entries', ascending: true })
|
||||
.order('voucher_number', { foreignTable: 'journal_entries', ascending: true })
|
||||
.limit(PAGE_LIMIT + 1)
|
||||
|
||||
if (cursor) {
|
||||
// Cursor format: <iso-date>|<voucher_number>
|
||||
const [cursorDate, cursorVoucher] = cursor.split('|')
|
||||
const cursorVoucherNum = parseInt(cursorVoucher, 10)
|
||||
if (!cursorDate || isNaN(cursorVoucherNum)) {
|
||||
return NextResponse.json({ error: 'Invalid cursor' }, { status: 400 })
|
||||
}
|
||||
// Filter for rows strictly after the cursor (date>cur OR same date & voucher>cur).
|
||||
// Supabase doesn't expose tuple compare, so use an `or()` clause.
|
||||
query = query.or(
|
||||
`entry_date.gt.${cursorDate},and(entry_date.eq.${cursorDate},voucher_number.gt.${cursorVoucherNum})`,
|
||||
{ foreignTable: 'journal_entries' }
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await query
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const rows = (data || []) as any[]
|
||||
|
||||
const lines: ReportSourceLine[] = rows
|
||||
.slice(0, PAGE_LIMIT)
|
||||
.map((row) => ({
|
||||
journal_entry_id: row.journal_entries.id,
|
||||
voucher_number: row.journal_entries.voucher_number,
|
||||
voucher_series: row.journal_entries.voucher_series || 'A',
|
||||
date: row.journal_entries.entry_date,
|
||||
description: row.journal_entries.description || '',
|
||||
debit: Math.round((Number(row.debit_amount) || 0) * 100) / 100,
|
||||
credit: Math.round((Number(row.credit_amount) || 0) * 100) / 100,
|
||||
}))
|
||||
|
||||
// If we got more than PAGE_LIMIT rows back, the next cursor points at the
|
||||
// last delivered row so the next call resumes from after it.
|
||||
let next_cursor: string | null = null
|
||||
if (rows.length > PAGE_LIMIT && lines.length > 0) {
|
||||
const last = lines[lines.length - 1]
|
||||
next_cursor = `${last.date}|${last.voucher_number}`
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
account_number: account.account_number,
|
||||
account_name: account.account_name,
|
||||
lines,
|
||||
next_cursor,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateTrialBalance } from '@/lib/reports/trial-balance'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import type { TrialBalanceRow } from '@/types'
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateTrialBalance(supabase, companyId, periodId)
|
||||
|
||||
const buffer = reportToWorkbook<TrialBalanceRow>([
|
||||
{
|
||||
name: 'Saldobalans',
|
||||
columns: [
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
integerColumn('Klass'),
|
||||
currencyColumn('IB Debet'),
|
||||
currencyColumn('IB Kredit'),
|
||||
currencyColumn('Period Debet'),
|
||||
currencyColumn('Period Kredit'),
|
||||
currencyColumn('UB Debet'),
|
||||
currencyColumn('UB Kredit'),
|
||||
],
|
||||
rows: report.rows,
|
||||
mapRow: (r) => [
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.account_class,
|
||||
r.opening_debit,
|
||||
r.opening_credit,
|
||||
r.period_debit,
|
||||
r.period_credit,
|
||||
r.closing_debit,
|
||||
r.closing_credit,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('saldobalans', companyRow?.company_name ?? '', period.period_end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera saldobalans' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string } | null,
|
||||
linesResult: { data: unknown; error: unknown }
|
||||
) {
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
},
|
||||
from: vi.fn().mockImplementation(() => ({
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
gte: vi.fn().mockReturnThis(),
|
||||
lte: vi.fn().mockReturnThis(),
|
||||
order: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
or: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: null, error: null }),
|
||||
then: (resolve: (v: unknown) => void) => resolve(linesResult),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/vat-declaration/ruta/[ruta]/sources', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(null, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/vat-declaration/ruta/10/sources',
|
||||
{ searchParams: { periodType: 'monthly', year: '2026', period: '5' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ ruta: '10' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when period params are missing', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/vat-declaration/ruta/10/sources'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ ruta: '10' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when ruta has no underlying BAS accounts', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/vat-declaration/ruta/99/sources',
|
||||
{ searchParams: { periodType: 'monthly', year: '2026', period: '5' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ ruta: '99' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('happy path: returns mapped lines for ruta10', async () => {
|
||||
const linesData = [
|
||||
{
|
||||
account_number: '2611',
|
||||
debit_amount: 0,
|
||||
credit_amount: 250,
|
||||
journal_entries: {
|
||||
id: 'je-1',
|
||||
voucher_number: 12,
|
||||
voucher_series: 'A',
|
||||
entry_date: '2026-05-12',
|
||||
description: 'Faktura 1001',
|
||||
status: 'posted',
|
||||
company_id: 'company-1',
|
||||
},
|
||||
},
|
||||
]
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, { data: linesData, error: null }) as never
|
||||
)
|
||||
|
||||
const req = createMockRequest(
|
||||
'/api/reports/vat-declaration/ruta/10/sources',
|
||||
{ searchParams: { periodType: 'monthly', year: '2026', period: '5' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ ruta: '10' }))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
ruta: string
|
||||
lines: Array<{ voucher_number: number; credit: number }>
|
||||
}
|
||||
}
|
||||
|
||||
expect(body.data.ruta).toBe('ruta10')
|
||||
expect(body.data.lines).toHaveLength(1)
|
||||
expect(body.data.lines[0].voucher_number).toBe(12)
|
||||
expect(body.data.lines[0].credit).toBe(250)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
ACCOUNT_RUTA,
|
||||
calculatePeriodDates,
|
||||
} from '@/lib/reports/vat-declaration'
|
||||
import type { ReportSourceLine } from '@/lib/reports/source-lines'
|
||||
import type { VatDeclarationRutor, VatPeriodType } from '@/types'
|
||||
|
||||
/**
|
||||
* GET /api/reports/vat-declaration/ruta/[ruta]/sources
|
||||
*
|
||||
* Returns the journal entry lines that contribute to a single ruta on the
|
||||
* VAT declaration. The mapping ruta → BAS accounts is the inverse of
|
||||
* `ACCOUNT_RUTA` in `lib/reports/vat-declaration.ts`.
|
||||
*
|
||||
* Period can be specified either via:
|
||||
* ?periodType=monthly|quarterly|yearly&year=2026&period=5
|
||||
* ?fiscal_period_id=<uuid>
|
||||
*
|
||||
* The periodType form mirrors the way the main VAT report is fetched.
|
||||
*/
|
||||
const PAGE_LIMIT = 500
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ ruta: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const { ruta: rutaParam } = await params
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const cursor = searchParams.get('cursor')
|
||||
|
||||
// Normalise ruta param to the keyof VatDeclarationRutor (`ruta10`, `ruta48`).
|
||||
const rutaKey = (
|
||||
rutaParam.startsWith('ruta') ? rutaParam : `ruta${rutaParam}`
|
||||
) as keyof VatDeclarationRutor
|
||||
|
||||
// Invert ACCOUNT_RUTA: which BAS accounts feed this ruta?
|
||||
const accountsForRuta = Object.entries(ACCOUNT_RUTA)
|
||||
.filter(([, m]) => m.box === rutaKey)
|
||||
.map(([acc]) => acc)
|
||||
|
||||
if (accountsForRuta.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: `Ruta ${rutaParam} har inga underliggande konton` },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Resolve the period — either by fiscal_period_id or periodType/year/period.
|
||||
let start: string | null = null
|
||||
let end: string | null = null
|
||||
const fiscalPeriodId = searchParams.get('fiscal_period_id')
|
||||
if (fiscalPeriodId) {
|
||||
const { data: period } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', fiscalPeriodId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Period saknas' }, { status: 404 })
|
||||
}
|
||||
start = period.period_start
|
||||
end = period.period_end
|
||||
} else {
|
||||
const periodType = searchParams.get('periodType') as VatPeriodType | null
|
||||
const yearStr = searchParams.get('year')
|
||||
const periodStr = searchParams.get('period')
|
||||
if (!periodType || !yearStr || !periodStr) {
|
||||
return NextResponse.json(
|
||||
{ error: 'periodType/year/period or fiscal_period_id is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
const year = parseInt(yearStr, 10)
|
||||
const periodNum = parseInt(periodStr, 10)
|
||||
if (isNaN(year) || isNaN(periodNum)) {
|
||||
return NextResponse.json({ error: 'Invalid period' }, { status: 400 })
|
||||
}
|
||||
const dates = calculatePeriodDates(periodType, year, periodNum)
|
||||
start = dates.start
|
||||
end = dates.end
|
||||
}
|
||||
|
||||
let query = supabase
|
||||
.from('journal_entry_lines')
|
||||
.select(`
|
||||
account_number,
|
||||
debit_amount,
|
||||
credit_amount,
|
||||
journal_entries!inner(
|
||||
id,
|
||||
voucher_number,
|
||||
voucher_series,
|
||||
entry_date,
|
||||
description,
|
||||
status,
|
||||
company_id
|
||||
)
|
||||
`)
|
||||
.in('account_number', accountsForRuta)
|
||||
.eq('journal_entries.company_id', companyId)
|
||||
.in('journal_entries.status', ['posted', 'reversed'])
|
||||
.gte('journal_entries.entry_date', start)
|
||||
.lte('journal_entries.entry_date', end)
|
||||
.order('entry_date', { foreignTable: 'journal_entries', ascending: true })
|
||||
.order('voucher_number', { foreignTable: 'journal_entries', ascending: true })
|
||||
.limit(PAGE_LIMIT + 1)
|
||||
|
||||
if (cursor) {
|
||||
const [cursorDate, cursorVoucher] = cursor.split('|')
|
||||
const cursorVoucherNum = parseInt(cursorVoucher, 10)
|
||||
if (!cursorDate || isNaN(cursorVoucherNum)) {
|
||||
return NextResponse.json({ error: 'Invalid cursor' }, { status: 400 })
|
||||
}
|
||||
query = query.or(
|
||||
`entry_date.gt.${cursorDate},and(entry_date.eq.${cursorDate},voucher_number.gt.${cursorVoucherNum})`,
|
||||
{ foreignTable: 'journal_entries' }
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await query
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const rows = (data || []) as any[]
|
||||
|
||||
const lines: ReportSourceLine[] = rows
|
||||
.slice(0, PAGE_LIMIT)
|
||||
.map((row) => ({
|
||||
journal_entry_id: row.journal_entries.id,
|
||||
voucher_number: row.journal_entries.voucher_number,
|
||||
voucher_series: row.journal_entries.voucher_series || 'A',
|
||||
date: row.journal_entries.entry_date,
|
||||
description: row.journal_entries.description || '',
|
||||
debit: Math.round((Number(row.debit_amount) || 0) * 100) / 100,
|
||||
credit: Math.round((Number(row.credit_amount) || 0) * 100) / 100,
|
||||
}))
|
||||
|
||||
let next_cursor: string | null = null
|
||||
if (rows.length > PAGE_LIMIT && lines.length > 0) {
|
||||
const last = lines[lines.length - 1]
|
||||
next_cursor = `${last.date}|${last.voucher_number}`
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
ruta: rutaKey,
|
||||
lines,
|
||||
next_cursor,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
calculateVatDeclaration,
|
||||
formatPeriodLabel,
|
||||
} from '@/lib/reports/vat-declaration'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import {
|
||||
VAT_RUTA_LABELS,
|
||||
type VatPeriodType,
|
||||
type VatDeclarationRutor,
|
||||
type AccountingMethod,
|
||||
} from '@/types'
|
||||
|
||||
interface RutaRow {
|
||||
ruta: string
|
||||
label: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodType = searchParams.get('periodType') as VatPeriodType | null
|
||||
const yearStr = searchParams.get('year')
|
||||
const periodStr = searchParams.get('period')
|
||||
|
||||
if (!periodType || !yearStr || !periodStr) {
|
||||
return NextResponse.json(
|
||||
{ error: 'periodType, year, and period are required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
if (!['monthly', 'quarterly', 'yearly'].includes(periodType)) {
|
||||
return NextResponse.json({ error: 'Invalid periodType' }, { status: 400 })
|
||||
}
|
||||
|
||||
const year = parseInt(yearStr, 10)
|
||||
const period = parseInt(periodStr, 10)
|
||||
if (isNaN(year) || isNaN(period)) {
|
||||
return NextResponse.json({ error: 'Invalid year or period' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: settings }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('accounting_method')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
const accountingMethod = (settings?.accounting_method as AccountingMethod) || 'accrual'
|
||||
|
||||
try {
|
||||
const declaration = await calculateVatDeclaration(
|
||||
supabase, companyId, periodType, year, period, accountingMethod,
|
||||
)
|
||||
|
||||
const rows: RutaRow[] = (Object.keys(declaration.rutor) as (keyof VatDeclarationRutor)[]).map(
|
||||
(key) => ({
|
||||
ruta: key.replace(/^ruta/, 'Ruta '),
|
||||
label: VAT_RUTA_LABELS[key],
|
||||
amount: declaration.rutor[key],
|
||||
}),
|
||||
)
|
||||
|
||||
const buffer = reportToWorkbook<RutaRow>([
|
||||
{
|
||||
name: `Moms ${formatPeriodLabel(periodType, year, period)}`,
|
||||
columns: [
|
||||
textColumn('Ruta'),
|
||||
textColumn('Beskrivning'),
|
||||
currencyColumn('Belopp'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [r.ruta, r.label, r.amount],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'momsdeklaration',
|
||||
companyRow?.company_name ?? '',
|
||||
declaration.period.end,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera momsdeklaration' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
}))
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue({}),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import { z } from 'zod'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { registerEndpoint } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
@@ -148,6 +149,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }
|
||||
|
||||
let pdfBuffer: Buffer
|
||||
try {
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: typed as Invoice,
|
||||
@@ -155,6 +157,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }
|
||||
items,
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
|
||||
@@ -71,6 +71,7 @@ vi.mock('@/lib/email/invoice-templates', () => ({
|
||||
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue({}),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ import { registerEndpoint } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import {
|
||||
generateInvoiceEmailHtml,
|
||||
@@ -264,6 +265,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
const isFreshAllocation = !typed.invoice_number
|
||||
if (isFreshAllocation) {
|
||||
try {
|
||||
const preflight = prepareInvoicePdfRender(settings)
|
||||
await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: { ...(typed as Invoice), invoice_number: 'F-PREVIEW' },
|
||||
@@ -271,6 +273,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
items,
|
||||
company: settings,
|
||||
originalInvoiceNumber,
|
||||
branding: preflight.branding,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
@@ -352,6 +355,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
|
||||
let pdfBuffer: Buffer
|
||||
try {
|
||||
const { branding } = prepareInvoicePdfRender(settings)
|
||||
pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: renderableInvoice,
|
||||
@@ -359,6 +363,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
items,
|
||||
company: settings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ExternalLink, FileText, ImageIcon, Paperclip } from 'lucide-react'
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet'
|
||||
AlertTriangle,
|
||||
ExternalLink,
|
||||
FileText,
|
||||
ImageIcon,
|
||||
Loader2,
|
||||
Lock,
|
||||
Paperclip,
|
||||
RefreshCw,
|
||||
Trash2,
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
interface DocumentRecord {
|
||||
@@ -47,9 +61,16 @@ export default function AttachmentPreviewSheet({
|
||||
onOpenChange,
|
||||
}: AttachmentPreviewSheetProps) {
|
||||
const t = useTranslations('attachment_preview_sheet')
|
||||
const tj = useTranslations('journal_attachments')
|
||||
const { toast } = useToast()
|
||||
const [documents, setDocuments] = useState<DocumentRecord[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const [blockedDoc, setBlockedDoc] = useState<DocumentRecord | null>(null)
|
||||
const [replacingDocId, setReplacingDocId] = useState<string | null>(null)
|
||||
const replaceFileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const replaceTargetIdRef = useRef<string | null>(null)
|
||||
|
||||
const fetchAttachments = useCallback(async (id: string) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
@@ -87,20 +108,64 @@ export default function AttachmentPreviewSheet({
|
||||
if (open && entryId) {
|
||||
fetchAttachments(entryId)
|
||||
} else if (!open) {
|
||||
// Reset state when closed so the next open starts fresh
|
||||
setDocuments([])
|
||||
setBlockedDoc(null)
|
||||
}
|
||||
}, [open, entryId, fetchAttachments])
|
||||
|
||||
const handleOpenReplacePicker = (docId: string) => {
|
||||
replaceTargetIdRef.current = docId
|
||||
replaceFileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleReplaceFileSelected = async (file: File | null) => {
|
||||
const docId = replaceTargetIdRef.current
|
||||
replaceTargetIdRef.current = null
|
||||
if (replaceFileInputRef.current) {
|
||||
replaceFileInputRef.current.value = ''
|
||||
}
|
||||
if (!file || !docId || !entryId) return
|
||||
|
||||
setReplacingDocId(docId)
|
||||
try {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
const res = await fetch(`/api/documents/${docId}/versions`, {
|
||||
method: 'POST',
|
||||
body: fd,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const { error } = await res.json().catch(() => ({ error: undefined }))
|
||||
toast({
|
||||
title: tj('replace_failed'),
|
||||
description: error || undefined,
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else {
|
||||
await fetchAttachments(entryId)
|
||||
setBlockedDoc(null)
|
||||
}
|
||||
} catch {
|
||||
toast({ title: tj('replace_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setReplacingDocId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-full overflow-y-auto sm:max-w-[560px]"
|
||||
>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] w-[95vw] max-w-4xl overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<input
|
||||
ref={replaceFileInputRef}
|
||||
type="file"
|
||||
accept="application/pdf,image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={(e) => handleReplaceFileSelected(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<div className="space-y-3">
|
||||
@@ -119,6 +184,7 @@ export default function AttachmentPreviewSheet({
|
||||
{documents.map((doc) => {
|
||||
const inlineSrc = `/api/documents/${doc.id}/inline`
|
||||
const previewable = isImageType(doc.mime_type) || isPdfType(doc.mime_type)
|
||||
const isReplacing = replacingDocId === doc.id
|
||||
return (
|
||||
<div key={doc.id} className="space-y-2">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
@@ -137,25 +203,76 @@ export default function AttachmentPreviewSheet({
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{doc.download_url && (
|
||||
<a
|
||||
href={doc.download_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={() => handleOpenReplacePicker(doc.id)}
|
||||
disabled={isReplacing}
|
||||
title={t('replace')}
|
||||
aria-label={t('replace')}
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
{t('open_in_new_tab')}
|
||||
</a>
|
||||
)}
|
||||
{isReplacing ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={() => setBlockedDoc(doc)}
|
||||
title={t('remove')}
|
||||
aria-label={t('remove')}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
{doc.download_url && (
|
||||
<a
|
||||
href={doc.download_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 px-2 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
{t('open_in_new_tab')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isPdfType(doc.mime_type) && (
|
||||
<iframe
|
||||
src={inlineSrc}
|
||||
title={doc.file_name}
|
||||
// <object> + type="application/pdf" invokes Chrome's PDF
|
||||
// plugin directly. <iframe> went through Chrome's frame
|
||||
// pipeline first and intermittently surfaced
|
||||
// "Det här innehållet har blockerats" even with a
|
||||
// permissive CSP. Firefox/Edge handled both fine; Chrome
|
||||
// is the odd one. See crbug.com/271452.
|
||||
<object
|
||||
data={inlineSrc}
|
||||
type="application/pdf"
|
||||
aria-label={doc.file_name}
|
||||
className="h-[70vh] w-full rounded-lg border border-border"
|
||||
/>
|
||||
>
|
||||
<div className="flex h-[70vh] w-full items-center justify-center rounded-lg border border-border bg-muted/30 p-4 text-center text-sm text-muted-foreground">
|
||||
{t('not_previewable')}
|
||||
{doc.download_url && (
|
||||
<>
|
||||
{' — '}
|
||||
<a
|
||||
href={doc.download_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="underline"
|
||||
>
|
||||
{t('open_in_new_tab')}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</object>
|
||||
)}
|
||||
|
||||
{isImageType(doc.mime_type) && (
|
||||
@@ -178,7 +295,56 @@ export default function AttachmentPreviewSheet({
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
<Dialog
|
||||
open={blockedDoc !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setBlockedDoc(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-warning/15 shrink-0">
|
||||
<Lock className="h-5 w-5 text-warning-foreground" />
|
||||
</div>
|
||||
<DialogTitle>{tj('remove_blocked_title')}</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription className="pt-3 text-sm text-muted-foreground">
|
||||
{tj('remove_blocked_body')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="rounded-lg border border-border bg-muted/30 p-3 text-sm">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<p className="text-muted-foreground">{tj('remove_blocked_hint')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setBlockedDoc(null)}>
|
||||
{tj('remove_blocked_cancel_cta')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (blockedDoc) handleOpenReplacePicker(blockedDoc.id)
|
||||
}}
|
||||
disabled={blockedDoc !== null && replacingDocId === blockedDoc.id}
|
||||
>
|
||||
{blockedDoc !== null && replacingDocId === blockedDoc.id ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{tj('replace_uploading')}
|
||||
</>
|
||||
) : (
|
||||
tj('remove_blocked_replace_cta')
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Info } from 'lucide-react'
|
||||
import JournalEntryStatusBadge from '@/components/bookkeeping/JournalEntryStatusBadge'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import type { JournalEntry, JournalEntryLine } from '@/types'
|
||||
|
||||
interface Props {
|
||||
@@ -73,7 +74,7 @@ export default function CorrectionChain({ currentEntryId, chain }: Props) {
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs font-medium text-muted-foreground">{role.label}</span>
|
||||
<span className="font-mono text-sm">
|
||||
{entry.voucher_series}{entry.voucher_number}
|
||||
{formatVoucher(entry)}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground tabular-nums">{formatDate(entry.entry_date)}</span>
|
||||
<JournalEntryStatusBadge entry={entry} showStatus={false} />
|
||||
|
||||
@@ -18,6 +18,7 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { Plus, Trash2 } from 'lucide-react'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import type { JournalEntry, JournalEntryLine, BASAccount } from '@/types'
|
||||
|
||||
interface CorrectionLine {
|
||||
@@ -165,7 +166,7 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
|
||||
{/* Original entry (read-only) */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="font-mono">{entry.voucher_series}{entry.voucher_number}</span>
|
||||
<span className="font-mono">{formatVoucher(entry)}</span>
|
||||
<span className="tabular-nums">{formatDate(entry.entry_date)}</span>
|
||||
<Badge variant="outline" className="text-xs">Original</Badge>
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,28 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { FileText, ImageIcon, Download, ChevronDown, ChevronUp, Plus } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
FileText,
|
||||
ImageIcon,
|
||||
Download,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Plus,
|
||||
Trash2,
|
||||
RefreshCw,
|
||||
Loader2,
|
||||
Lock,
|
||||
AlertTriangle,
|
||||
} from 'lucide-react'
|
||||
import DocumentUploadZone from '@/components/bookkeeping/DocumentUploadZone'
|
||||
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
|
||||
|
||||
@@ -45,12 +66,22 @@ export default function JournalEntryAttachments({
|
||||
onCountChange,
|
||||
}: JournalEntryAttachmentsProps) {
|
||||
const t = useTranslations('journal_attachments')
|
||||
const { toast } = useToast()
|
||||
const [documents, setDocuments] = useState<DocumentRecord[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [expandedDoc, setExpandedDoc] = useState<string | null>(null)
|
||||
const [showUpload, setShowUpload] = useState(false)
|
||||
const [uploadFiles, setUploadFiles] = useState<UploadedFile[]>([])
|
||||
|
||||
// Docs listed here are filtered by journal_entry_id, so every row is bound
|
||||
// to a verifikation — BFL 7 kap 2§ blocks deletion. "Ta bort" therefore
|
||||
// surfaces the educational modal; "Ersätt" goes through createNewVersion()
|
||||
// so the original stays in the version chain.
|
||||
const [blockedDoc, setBlockedDoc] = useState<DocumentRecord | null>(null)
|
||||
const [replacingDocId, setReplacingDocId] = useState<string | null>(null)
|
||||
const replaceFileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const replaceTargetIdRef = useRef<string | null>(null)
|
||||
|
||||
const onCountChangeRef = useRef(onCountChange)
|
||||
onCountChangeRef.current = onCountChange
|
||||
|
||||
@@ -102,7 +133,6 @@ export default function JournalEntryAttachments({
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch signed URL for preview if not already loaded
|
||||
if (!doc.download_url) {
|
||||
try {
|
||||
const res = await fetch(`/api/documents/${doc.id}`)
|
||||
@@ -113,7 +143,6 @@ export default function JournalEntryAttachments({
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — silently ignore
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -121,6 +150,49 @@ export default function JournalEntryAttachments({
|
||||
setExpandedDoc(doc.id)
|
||||
}
|
||||
|
||||
const handleRequestRemove = (doc: DocumentRecord) => {
|
||||
setBlockedDoc(doc)
|
||||
}
|
||||
|
||||
const handleOpenReplacePicker = (docId: string) => {
|
||||
replaceTargetIdRef.current = docId
|
||||
replaceFileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleReplaceFileSelected = async (file: File | null) => {
|
||||
const docId = replaceTargetIdRef.current
|
||||
replaceTargetIdRef.current = null
|
||||
if (replaceFileInputRef.current) {
|
||||
replaceFileInputRef.current.value = ''
|
||||
}
|
||||
if (!file || !docId) return
|
||||
|
||||
setReplacingDocId(docId)
|
||||
try {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
const res = await fetch(`/api/documents/${docId}/versions`, {
|
||||
method: 'POST',
|
||||
body: fd,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const { error } = await res.json().catch(() => ({ error: undefined }))
|
||||
toast({
|
||||
title: t('replace_failed'),
|
||||
description: error || undefined,
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else {
|
||||
await fetchDocuments()
|
||||
setBlockedDoc(null)
|
||||
}
|
||||
} catch {
|
||||
toast({ title: t('replace_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setReplacingDocId(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="py-2 text-sm text-muted-foreground">
|
||||
@@ -131,6 +203,14 @@ export default function JournalEntryAttachments({
|
||||
|
||||
return (
|
||||
<div className="border-t pt-3 mt-3">
|
||||
<input
|
||||
ref={replaceFileInputRef}
|
||||
type="file"
|
||||
accept="application/pdf,image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={(e) => handleReplaceFileSelected(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h4 className="text-sm font-medium">
|
||||
{t('title')} {documents.length > 0 && `(${documents.length})`}
|
||||
@@ -146,7 +226,6 @@ export default function JournalEntryAttachments({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Upload zone */}
|
||||
{showUpload && (
|
||||
<div className="mb-3">
|
||||
<DocumentUploadZone
|
||||
@@ -158,80 +237,157 @@ export default function JournalEntryAttachments({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Document list */}
|
||||
{documents.length === 0 && !showUpload ? (
|
||||
<p className="text-sm text-muted-foreground py-1">
|
||||
{t('empty')}
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{documents.map((doc) => (
|
||||
<div key={doc.id}>
|
||||
<div className="flex items-center gap-2 text-sm py-1.5 px-2 rounded bg-muted/50">
|
||||
{isPreviewable(doc.mime_type) ? (
|
||||
<button
|
||||
onClick={() => handlePreviewToggle(doc)}
|
||||
className="shrink-0 hover:text-primary transition-colors"
|
||||
>
|
||||
{expandedDoc === doc.id ? (
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
|
||||
{isPreviewable(doc.mime_type) && expandedDoc !== doc.id && (
|
||||
isImageType(doc.mime_type) ? (
|
||||
<ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
{documents.map((doc) => {
|
||||
const isReplacing = replacingDocId === doc.id
|
||||
return (
|
||||
<div key={doc.id}>
|
||||
<div className="flex items-center gap-2 text-sm py-1.5 px-2 rounded bg-muted/50">
|
||||
{isPreviewable(doc.mime_type) ? (
|
||||
<button
|
||||
onClick={() => handlePreviewToggle(doc)}
|
||||
className="shrink-0 hover:text-primary transition-colors"
|
||||
>
|
||||
{expandedDoc === doc.id ? (
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
)
|
||||
)}
|
||||
|
||||
{isPreviewable(doc.mime_type) && expandedDoc !== doc.id && (
|
||||
isImageType(doc.mime_type) ? (
|
||||
<ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
) : (
|
||||
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
)
|
||||
)}
|
||||
|
||||
<span className="truncate flex-1">{doc.file_name}</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0">
|
||||
{formatFileSize(doc.file_size_bytes)}
|
||||
</span>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
|
||||
onClick={() => handleOpenReplacePicker(doc.id)}
|
||||
disabled={isReplacing}
|
||||
title={t('replace')}
|
||||
aria-label={t('replace')}
|
||||
>
|
||||
{isReplacing ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
|
||||
onClick={() => handleRequestRemove(doc)}
|
||||
title={t('remove')}
|
||||
aria-label={t('remove')}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
|
||||
onClick={() => handleDownload(doc.id)}
|
||||
title={t('download')}
|
||||
aria-label={t('download')}
|
||||
>
|
||||
<Download className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{expandedDoc === doc.id && doc.download_url && isImageType(doc.mime_type) && (
|
||||
<div className="px-2 py-2">
|
||||
<img
|
||||
src={`/api/documents/${doc.id}/inline`}
|
||||
alt={doc.file_name}
|
||||
className="max-h-48 rounded-lg object-contain"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<span className="truncate flex-1">{doc.file_name}</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0">
|
||||
{formatFileSize(doc.file_size_bytes)}
|
||||
</span>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
|
||||
onClick={() => handleDownload(doc.id)}
|
||||
title={t('download')}
|
||||
>
|
||||
<Download className="h-3 w-3" />
|
||||
</Button>
|
||||
{expandedDoc === doc.id && doc.download_url && isPdfType(doc.mime_type) && (
|
||||
<div className="px-2 py-2">
|
||||
<iframe
|
||||
src={`/api/documents/${doc.id}/inline`}
|
||||
title={doc.file_name}
|
||||
className="w-full h-[60vh] rounded-lg border"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Image preview */}
|
||||
{expandedDoc === doc.id && doc.download_url && isImageType(doc.mime_type) && (
|
||||
<div className="px-2 py-2">
|
||||
<img
|
||||
src={`/api/documents/${doc.id}/inline`}
|
||||
alt={doc.file_name}
|
||||
className="max-h-48 rounded-lg object-contain"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* PDF preview */}
|
||||
{expandedDoc === doc.id && doc.download_url && isPdfType(doc.mime_type) && (
|
||||
<div className="px-2 py-2">
|
||||
<iframe
|
||||
src={`/api/documents/${doc.id}/inline`}
|
||||
title={doc.file_name}
|
||||
className="w-full h-[60vh] rounded-lg border"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={blockedDoc !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setBlockedDoc(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-warning/15 shrink-0">
|
||||
<Lock className="h-5 w-5 text-warning-foreground" />
|
||||
</div>
|
||||
<DialogTitle>{t('remove_blocked_title')}</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription className="pt-3 text-sm text-muted-foreground">
|
||||
{t('remove_blocked_body')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="rounded-lg border border-border bg-muted/30 p-3 text-sm">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<p className="text-muted-foreground">{t('remove_blocked_hint')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setBlockedDoc(null)}>
|
||||
{t('remove_blocked_cancel_cta')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (blockedDoc) handleOpenReplacePicker(blockedDoc.id)
|
||||
}}
|
||||
disabled={blockedDoc !== null && replacingDocId === blockedDoc.id}
|
||||
>
|
||||
{blockedDoc !== null && replacingDocId === blockedDoc.id ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('replace_uploading')}
|
||||
</>
|
||||
) : (
|
||||
t('remove_blocked_replace_cta')
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from '@/lib/hooks/use-submit-with-account-activation'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { formatVoucher, resolveDefaultSeriesForSource } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { useUnsavedChanges } from '@/lib/hooks/use-unsaved-changes'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
|
||||
@@ -144,13 +145,22 @@ export default function JournalEntryForm({
|
||||
useEffect(() => {
|
||||
fetchPeriods()
|
||||
fetchAccounts()
|
||||
// Fetch default voucher series from company settings
|
||||
// Fetch default voucher series from company settings — prefer the
|
||||
// per-source-type mapping when present; fall back to the legacy
|
||||
// default_voucher_series, then to 'A'.
|
||||
if (!embedded) {
|
||||
fetch('/api/settings').then(r => r.json()).then(({ data }) => {
|
||||
if (data?.default_voucher_series) setVoucherSeries(data.default_voucher_series)
|
||||
if (!data) return
|
||||
const effectiveSourceType = sourceType ?? 'manual'
|
||||
const perSource = resolveDefaultSeriesForSource(
|
||||
data as { default_voucher_series_per_source_type?: Record<string, string> | null } | null,
|
||||
effectiveSourceType,
|
||||
)
|
||||
const fallback = data.default_voucher_series || 'A'
|
||||
setVoucherSeries(perSource !== 'A' ? perSource : fallback)
|
||||
}).catch(() => {/* keep 'A' */})
|
||||
}
|
||||
}, [])
|
||||
}, [embedded, sourceType])
|
||||
|
||||
// Auto-select period when entry date changes
|
||||
useEffect(() => {
|
||||
@@ -464,7 +474,7 @@ export default function JournalEntryForm({
|
||||
|
||||
toast({
|
||||
title: t('toast_created_title'),
|
||||
description: t('toast_created_description', { voucher: `${result.data?.voucher_series ?? ''}${result.data?.voucher_number ?? ''}` }),
|
||||
description: t('toast_created_description', { voucher: formatVoucher(result.data ?? {}) }),
|
||||
})
|
||||
setShowReview(false)
|
||||
setDescription('')
|
||||
@@ -996,7 +1006,7 @@ export default function JournalEntryForm({
|
||||
isSubmitting={isSubmitting}
|
||||
title={
|
||||
!embedded && nextVoucherNumber != null
|
||||
? t('review_title_with_voucher', { voucher: `${voucherSeries}${nextVoucherNumber}` })
|
||||
? t('review_title_with_voucher', { voucher: formatVoucher({ voucher_series: voucherSeries, voucher_number: nextVoucherNumber }) })
|
||||
: t('review_title')
|
||||
}
|
||||
warningText={embedded ? '' : t('review_warning')}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { ChevronDown, ChevronRight, Paperclip, AlertTriangle, Loader2, BookOpen, X, Copy, Lock } from 'lucide-react'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
|
||||
@@ -57,6 +58,7 @@ export default function JournalEntryList({ periodId }: Props) {
|
||||
const [dateTo, setDateTo] = useState('')
|
||||
const [dateFromInput, setDateFromInput] = useState('')
|
||||
const [dateToInput, setDateToInput] = useState('')
|
||||
const [seriesFilter, setSeriesFilter] = useState<string>('all')
|
||||
const pageSize = 20
|
||||
|
||||
const normalizeDate = (v: string): string | null => {
|
||||
@@ -123,6 +125,7 @@ export default function JournalEntryList({ periodId }: Props) {
|
||||
if (periodId) params.set('period_id', periodId)
|
||||
if (dateFrom) params.set('date_from', dateFrom)
|
||||
if (dateTo) params.set('date_to', dateTo)
|
||||
if (seriesFilter !== 'all') params.set('series', seriesFilter)
|
||||
|
||||
const res = await fetch(`/api/bookkeeping/journal-entries?${params}`)
|
||||
if (!res.ok) {
|
||||
@@ -142,7 +145,7 @@ export default function JournalEntryList({ periodId }: Props) {
|
||||
|
||||
useEffect(() => {
|
||||
fetchEntries()
|
||||
}, [periodId, page, sortBy, dateFrom, dateTo])
|
||||
}, [periodId, page, sortBy, dateFrom, dateTo, seriesFilter])
|
||||
|
||||
const handleAttachmentCountChange = useCallback((entryId: string, count: number) => {
|
||||
setAttachmentCounts((prev) => ({ ...prev, [entryId]: count }))
|
||||
@@ -161,7 +164,7 @@ export default function JournalEntryList({ periodId }: Props) {
|
||||
const posted = result.data
|
||||
toast({
|
||||
title: t('toast_posted_title'),
|
||||
description: t('toast_posted_description', { voucher: `${posted?.voucher_series ?? ''}${posted?.voucher_number ?? ''}` }),
|
||||
description: t('toast_posted_description', { voucher: formatVoucher(posted ?? {}) }),
|
||||
})
|
||||
await fetchEntries()
|
||||
} else {
|
||||
@@ -242,6 +245,22 @@ export default function JournalEntryList({ periodId }: Props) {
|
||||
<SelectItem value="voucher_desc">{t('sort_voucher_desc')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={seriesFilter} onValueChange={(v) => { setSeriesFilter(v); setPage(0) }}>
|
||||
<SelectTrigger
|
||||
className="h-8 w-auto gap-1.5 text-xs sm:w-[120px] font-mono"
|
||||
aria-label="Verifikationsserie"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all" className="text-xs">Alla serier</SelectItem>
|
||||
{'ABCDEFG'.split('').map((letter) => (
|
||||
<SelectItem key={letter} value={letter} className="font-mono text-xs">
|
||||
Serie {letter}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Input
|
||||
type="text"
|
||||
@@ -326,7 +345,7 @@ export default function JournalEntryList({ periodId }: Props) {
|
||||
className="font-mono text-sm text-primary hover:underline w-16"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{entry.voucher_series}{entry.voucher_number}
|
||||
{formatVoucher(entry)}
|
||||
</Link>
|
||||
<span className="text-sm text-muted-foreground tabular-nums w-24">
|
||||
{formatDate(entry.entry_date)}
|
||||
@@ -396,7 +415,7 @@ export default function JournalEntryList({ periodId }: Props) {
|
||||
className="font-mono text-sm text-primary hover:underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{entry.voucher_series}{entry.voucher_number}
|
||||
{formatVoucher(entry)}
|
||||
</Link>
|
||||
<span className="text-sm text-muted-foreground tabular-nums">
|
||||
{formatDate(entry.entry_date)}
|
||||
|
||||
@@ -35,6 +35,7 @@ const SOURCE_TYPES = [
|
||||
'supplier_invoice_paid',
|
||||
'supplier_invoice_cash_payment',
|
||||
'currency_revaluation',
|
||||
'reminder_fee',
|
||||
] as const
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -18,9 +18,11 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Loader2, Plus, X } from 'lucide-react'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import type { AssetCategory } from '@/types'
|
||||
import { useCompanyOptional } from '@/contexts/CompanyContext'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { AssetCategory, DepreciationMethod, K3Component } from '@/types'
|
||||
|
||||
interface CreateAssetDialogProps {
|
||||
open: boolean
|
||||
@@ -28,6 +30,28 @@ interface CreateAssetDialogProps {
|
||||
onCreated: () => void
|
||||
}
|
||||
|
||||
/** Editor row state — strings so the user can clear inputs without zeroing
|
||||
* out the component immediately. Converted to numbers at submit time. */
|
||||
interface ComponentRow {
|
||||
id: string
|
||||
name: string
|
||||
cost: string
|
||||
useful_life_months: string
|
||||
salvage_value: string
|
||||
}
|
||||
|
||||
let componentRowCounter = 0
|
||||
function newComponentRow(): ComponentRow {
|
||||
componentRowCounter += 1
|
||||
return {
|
||||
id: `cmp-${componentRowCounter}`,
|
||||
name: '',
|
||||
cost: '',
|
||||
useful_life_months: '',
|
||||
salvage_value: '',
|
||||
}
|
||||
}
|
||||
|
||||
// Defaults are K2-redovisning (BFNAR 2016:10) schablon, NOT skattemässig
|
||||
// avskrivning. Building / markanläggning values are conservative — IL 19/20
|
||||
// kap may allow longer (50 yr) or shorter (10 yr) depending on byggnadstyp.
|
||||
@@ -42,8 +66,36 @@ const CATEGORY_OPTIONS: { value: AssetCategory; label: string; defaultYears: num
|
||||
{ value: 'other_tangible', label: 'Övrig materiell tillgång', defaultYears: 5 },
|
||||
]
|
||||
|
||||
const DEPRECIATION_METHOD_OPTIONS: { value: DepreciationMethod; label: string; hint: string }[] = [
|
||||
{
|
||||
value: 'linear',
|
||||
label: 'Linjär',
|
||||
hint: 'Planenlig raklinje över nyttjandeperioden (ÅRL 4 kap 4§).',
|
||||
},
|
||||
{
|
||||
value: 'declining_balance_30',
|
||||
label: 'Räkenskapsenlig 30 %',
|
||||
hint: 'Huvudregeln (IL 18 kap 13§) — 30 % degressivt på avskrivningsunderlaget.',
|
||||
},
|
||||
{
|
||||
value: 'declining_balance_20',
|
||||
label: 'Räkenskapsenlig 20 %',
|
||||
hint: 'Kompletteringsregeln (IL 18 kap 17§) — 20 % degressivt. Vanlig för byggnader.',
|
||||
},
|
||||
{
|
||||
value: 'restvardesavskrivning_25',
|
||||
label: 'Restvärdeavskrivning 25 %',
|
||||
hint: 'IL 18 kap 13§ st.3 — 25 % degressivt ner till angivet restvärde.',
|
||||
},
|
||||
]
|
||||
|
||||
export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAssetDialogProps) {
|
||||
const { toast } = useToast()
|
||||
// useCompanyOptional so the dialog still works in tests / storyboards
|
||||
// that don't wrap it in CompanyProvider. K3 features simply hide.
|
||||
const companyCtx = useCompanyOptional()
|
||||
const isK3 = companyCtx?.company?.accounting_framework === 'k3'
|
||||
|
||||
const [name, setName] = useState('')
|
||||
const [category, setCategory] = useState<AssetCategory>('equipment')
|
||||
const [acquisitionDate, setAcquisitionDate] = useState(
|
||||
@@ -51,6 +103,12 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
|
||||
)
|
||||
const [acquisitionCost, setAcquisitionCost] = useState('')
|
||||
const [usefulLifeYears, setUsefulLifeYears] = useState('5')
|
||||
const [depreciationMethod, setDepreciationMethod] = useState<DepreciationMethod>('linear')
|
||||
const [restvardeTarget, setRestvardeTarget] = useState('')
|
||||
// K3 component depreciation. `useComponents` toggles the advanced section;
|
||||
// null when disabled, an array (possibly empty during editing) when enabled.
|
||||
const [useComponents, setUseComponents] = useState(false)
|
||||
const [componentRows, setComponentRows] = useState<ComponentRow[]>([])
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
@@ -60,6 +118,40 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
|
||||
if (option) setUsefulLifeYears(option.defaultYears.toString())
|
||||
}
|
||||
|
||||
const isRestvarde = depreciationMethod === 'restvardesavskrivning_25'
|
||||
const methodHint =
|
||||
DEPRECIATION_METHOD_OPTIONS.find((o) => o.value === depreciationMethod)?.hint ?? ''
|
||||
|
||||
const totalComponentCost = useMemo(() => {
|
||||
return componentRows.reduce((sum, row) => {
|
||||
const v = parseFloat(row.cost)
|
||||
return Number.isFinite(v) ? sum + v : sum
|
||||
}, 0)
|
||||
}, [componentRows])
|
||||
|
||||
const parsedAcquisitionCost = parseFloat(acquisitionCost)
|
||||
const componentMismatch =
|
||||
useComponents
|
||||
&& componentRows.length > 0
|
||||
&& Number.isFinite(parsedAcquisitionCost)
|
||||
&& Math.abs(totalComponentCost - parsedAcquisitionCost) > 1
|
||||
|
||||
const addComponentRow = () => {
|
||||
setComponentRows((rows) => [...rows, newComponentRow()])
|
||||
}
|
||||
const removeComponentRow = (id: string) => {
|
||||
setComponentRows((rows) => rows.filter((r) => r.id !== id))
|
||||
}
|
||||
const updateComponentRow = (id: string, patch: Partial<ComponentRow>) => {
|
||||
setComponentRows((rows) => rows.map((r) => (r.id === id ? { ...r, ...patch } : r)))
|
||||
}
|
||||
const toggleUseComponents = (next: boolean) => {
|
||||
setUseComponents(next)
|
||||
if (next && componentRows.length === 0) {
|
||||
setComponentRows([newComponentRow()])
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setError(null)
|
||||
const cost = parseFloat(acquisitionCost)
|
||||
@@ -68,6 +160,73 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
|
||||
setError('Fyll i namn, anskaffningsvärde och avskrivningstid.')
|
||||
return
|
||||
}
|
||||
let restvardeTargetNumber: number | null = null
|
||||
if (isRestvarde) {
|
||||
const parsed = parseFloat(restvardeTarget)
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
setError('Ange ett restvärde (0 kr eller högre).')
|
||||
return
|
||||
}
|
||||
if (parsed >= cost) {
|
||||
setError('Restvärdet måste vara lägre än anskaffningsvärdet.')
|
||||
return
|
||||
}
|
||||
restvardeTargetNumber = parsed
|
||||
}
|
||||
// K3 components — only when both the framework permits (gate at API)
|
||||
// and the user opted into the section. Empty array is invalid (the
|
||||
// validator rejects it) so the dialog also flips back to "off" when
|
||||
// every row is removed.
|
||||
let componentsPayload: K3Component[] | null = null
|
||||
if (useComponents && isK3) {
|
||||
if (componentRows.length === 0) {
|
||||
setError('Lägg till minst en komponent eller stäng av komponentuppdelningen.')
|
||||
return
|
||||
}
|
||||
const parsed: K3Component[] = []
|
||||
for (const [index, row] of componentRows.entries()) {
|
||||
const componentCost = parseFloat(row.cost)
|
||||
const months = parseInt(row.useful_life_months, 10)
|
||||
const salvageRaw = row.salvage_value.trim()
|
||||
const salvage = salvageRaw === '' ? undefined : parseFloat(salvageRaw)
|
||||
const trimmedName = row.name.trim()
|
||||
if (!trimmedName) {
|
||||
setError(`Komponent ${index + 1}: ange ett namn.`)
|
||||
return
|
||||
}
|
||||
if (!Number.isFinite(componentCost) || componentCost <= 0) {
|
||||
setError(`${trimmedName}: anskaffningsvärdet måste vara större än 0.`)
|
||||
return
|
||||
}
|
||||
if (!Number.isFinite(months) || months <= 0) {
|
||||
setError(`${trimmedName}: ange ett positivt heltal månader.`)
|
||||
return
|
||||
}
|
||||
if (salvage !== undefined && (!Number.isFinite(salvage) || salvage < 0)) {
|
||||
setError(`${trimmedName}: restvärdet får inte vara negativt.`)
|
||||
return
|
||||
}
|
||||
if (salvage !== undefined && salvage > componentCost) {
|
||||
setError(`${trimmedName}: restvärdet får inte överstiga anskaffningsvärdet.`)
|
||||
return
|
||||
}
|
||||
parsed.push({
|
||||
name: trimmedName,
|
||||
cost: componentCost,
|
||||
useful_life_months: months,
|
||||
...(salvage !== undefined ? { salvage_value: salvage } : {}),
|
||||
})
|
||||
}
|
||||
const sum = parsed.reduce((s, c) => s + c.cost, 0)
|
||||
if (Math.abs(sum - cost) > 1) {
|
||||
setError(
|
||||
`Komponenter summerar till ${formatCurrency(sum)} men anskaffningsvärdet är ${formatCurrency(cost)}.`,
|
||||
)
|
||||
return
|
||||
}
|
||||
componentsPayload = parsed
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const res = await fetch('/api/assets', {
|
||||
@@ -79,7 +238,11 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
|
||||
acquisition_date: acquisitionDate,
|
||||
acquisition_cost: cost,
|
||||
useful_life_months: years * 12,
|
||||
depreciation_method: 'linear',
|
||||
depreciation_method: depreciationMethod,
|
||||
...(restvardeTargetNumber !== null
|
||||
? { restvarde_target: restvardeTargetNumber }
|
||||
: {}),
|
||||
...(componentsPayload !== null ? { k3_components: componentsPayload } : {}),
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
@@ -91,6 +254,10 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
|
||||
// Reset form for next entry
|
||||
setName('')
|
||||
setAcquisitionCost('')
|
||||
setDepreciationMethod('linear')
|
||||
setRestvardeTarget('')
|
||||
setUseComponents(false)
|
||||
setComponentRows([])
|
||||
onCreated()
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Okänt fel')
|
||||
@@ -101,7 +268,7 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogContent className={isK3 ? 'sm:max-w-2xl' : 'sm:max-w-md'}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Ny anläggningstillgång</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -172,6 +339,196 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
|
||||
För skattemässig avskrivning kan annan livslängd gälla (IL 18–20 kap).
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="asset-method">Avskrivningsmetod</Label>
|
||||
<Select
|
||||
value={depreciationMethod}
|
||||
onValueChange={(v) => setDepreciationMethod(v as DepreciationMethod)}
|
||||
>
|
||||
<SelectTrigger id="asset-method">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DEPRECIATION_METHOD_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">{methodHint}</p>
|
||||
</div>
|
||||
{isRestvarde && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="asset-restvarde">Restvärde (kr)</Label>
|
||||
<Input
|
||||
id="asset-restvarde"
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
value={restvardeTarget}
|
||||
onChange={(e) => setRestvardeTarget(e.target.value)}
|
||||
placeholder="t.ex. 5000"
|
||||
className="tabular-nums"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Avskrivningen stannar när bokfört värde når restvärdet. Restvärdet
|
||||
måste vara lägre än anskaffningsvärdet.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{isK3 && (
|
||||
<div className="space-y-3 rounded-md border border-border bg-muted/20 p-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Avancerat — komponentuppdelning
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
K3 (BFNAR 2012:1 17.4) — när väsentliga komponenter har olika nyttjandeperiod
|
||||
skrivs varje komponent av för sig. Typisk för fastigheter (tak, fasad, stomme,
|
||||
installationer).
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant={useComponents ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => toggleUseComponents(!useComponents)}
|
||||
>
|
||||
{useComponents ? 'Aktiverad' : 'Aktivera'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{useComponents && (
|
||||
<div className="space-y-2">
|
||||
{componentRows.map((row, idx) => (
|
||||
<div
|
||||
key={row.id}
|
||||
className="grid grid-cols-12 items-end gap-2 rounded-md border border-border bg-background p-2"
|
||||
>
|
||||
<div className="col-span-12 sm:col-span-4 space-y-1">
|
||||
<Label
|
||||
htmlFor={`cmp-name-${row.id}`}
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
Komponent
|
||||
</Label>
|
||||
<Input
|
||||
id={`cmp-name-${row.id}`}
|
||||
value={row.name}
|
||||
onChange={(e) =>
|
||||
updateComponentRow(row.id, { name: e.target.value })
|
||||
}
|
||||
placeholder={idx === 0 ? 't.ex. Stomme' : 'Namn'}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-6 sm:col-span-3 space-y-1">
|
||||
<Label
|
||||
htmlFor={`cmp-cost-${row.id}`}
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
Kostnad (kr)
|
||||
</Label>
|
||||
<Input
|
||||
id={`cmp-cost-${row.id}`}
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
value={row.cost}
|
||||
onChange={(e) =>
|
||||
updateComponentRow(row.id, { cost: e.target.value })
|
||||
}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-6 sm:col-span-2 space-y-1">
|
||||
<Label
|
||||
htmlFor={`cmp-life-${row.id}`}
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
Liv (mån)
|
||||
</Label>
|
||||
<Input
|
||||
id={`cmp-life-${row.id}`}
|
||||
type="number"
|
||||
min="1"
|
||||
step="1"
|
||||
value={row.useful_life_months}
|
||||
onChange={(e) =>
|
||||
updateComponentRow(row.id, { useful_life_months: e.target.value })
|
||||
}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-9 sm:col-span-2 space-y-1">
|
||||
<Label
|
||||
htmlFor={`cmp-salvage-${row.id}`}
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
Restvärde
|
||||
</Label>
|
||||
<Input
|
||||
id={`cmp-salvage-${row.id}`}
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
value={row.salvage_value}
|
||||
onChange={(e) =>
|
||||
updateComponentRow(row.id, { salvage_value: e.target.value })
|
||||
}
|
||||
placeholder="0"
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-3 sm:col-span-1 flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeComponentRow(row.id)}
|
||||
aria-label="Ta bort komponent"
|
||||
disabled={componentRows.length === 1}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addComponentRow}
|
||||
>
|
||||
<Plus className="mr-1 h-4 w-4" /> Lägg till komponent
|
||||
</Button>
|
||||
<div className="text-xs tabular-nums text-muted-foreground">
|
||||
Summa komponenter:{' '}
|
||||
<span
|
||||
className={
|
||||
componentMismatch
|
||||
? 'text-destructive font-medium'
|
||||
: 'text-foreground'
|
||||
}
|
||||
>
|
||||
{formatCurrency(totalComponentCost)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{componentMismatch && (
|
||||
<p className="text-xs text-destructive">
|
||||
Komponenter summerar inte till anskaffningsvärdet (
|
||||
{formatCurrency(parsedAcquisitionCost)}).
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
|
||||
<strong className="text-foreground">Tips:</strong> Anskaffningen måste redan vara
|
||||
bokförd (debet på 1xxx-kontot mot t.ex. 1930/2440) — registret bokför inte
|
||||
|
||||
@@ -391,6 +391,10 @@ function buildPostItems(proposal: DispositionsProposal, ui: UiState): PostItem[]
|
||||
additionalAmount: sel.overrideAmount ?? p.amount,
|
||||
})
|
||||
break
|
||||
case 'uppskjuten_skatt':
|
||||
// K3 only — server recomputes the amount; client just signals intent.
|
||||
items.push({ kind: 'uppskjuten_skatt' })
|
||||
break
|
||||
}
|
||||
}
|
||||
if (Object.keys(ateforingReturns).length > 0) {
|
||||
|
||||
@@ -1,101 +1,211 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { FileDown, Info } from 'lucide-react'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { AlertTriangle, FileDown, Info } from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { calculateEgenavgifter, type EgenavgiftCategory } from '@/lib/bokslut/enskild-firma/egenavgifter-calculator'
|
||||
import { calculateRantefordelning } from '@/lib/bokslut/enskild-firma/rantefordelning-calculator'
|
||||
import { proposeEfPfondAvsattning } from '@/lib/bokslut/enskild-firma/periodiseringsfond-ef'
|
||||
import { calculateExpansionsfondChange } from '@/lib/bokslut/enskild-firma/expansionsfond-calculator'
|
||||
import type { EgenavgiftCategory } from '@/lib/bokslut/enskild-firma/egenavgifter-calculator'
|
||||
import type { EfDeclarationItem } from '@/lib/bokslut/enskild-firma/types'
|
||||
|
||||
interface EfDeclarationSectionProps {
|
||||
fiscalPeriodId: string
|
||||
/** Bokfört resultat (income statement net_result) — used as the default
|
||||
* surplus base for the calculators. */
|
||||
/** Bokfört resultat (income statement net_result) — shown as the surplus
|
||||
* base in the wizard header. Server recomputes from the trial balance. */
|
||||
bookedSurplus: number
|
||||
/** Closing year of the fiscal period (for periodiseringsfond cohort). */
|
||||
fiscalYear: number
|
||||
}
|
||||
|
||||
interface EfOverrideInputs {
|
||||
category: EgenavgiftCategory
|
||||
kapitalunderlag: string
|
||||
priorSchablon: string
|
||||
priorActual: string
|
||||
pfondDesired: string
|
||||
expansionsfondBalance: string
|
||||
expansionsfondChange: string
|
||||
}
|
||||
|
||||
interface EfPreviewResponse {
|
||||
fiscalPeriod: {
|
||||
id: string
|
||||
name: string
|
||||
period_start: string
|
||||
period_end: string
|
||||
}
|
||||
bookedSurplus: number
|
||||
items: EfDeclarationItem[]
|
||||
postedEntryCount: number
|
||||
inputWarnings: string[]
|
||||
}
|
||||
|
||||
const DEFAULT_OVERRIDES: EfOverrideInputs = {
|
||||
category: 'full',
|
||||
kapitalunderlag: '',
|
||||
priorSchablon: '',
|
||||
priorActual: '',
|
||||
pfondDesired: '',
|
||||
expansionsfondBalance: '',
|
||||
expansionsfondChange: '',
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only EF declaration computation. All values are skattemässiga
|
||||
* justeringar that are filed in NE-bilaga / INK1 — never booked. The card
|
||||
* runs calculators in the browser as the user adjusts inputs and shows the
|
||||
* NE-bilaga ruta where each number lands.
|
||||
* EF declaration step — fetches the four calculator outputs (egenavgifter,
|
||||
* räntefördelning, periodiseringsfond-EF, expansionsfond) from the server
|
||||
* so the same source-of-truth (computeEfDeclarationPreview) is used by
|
||||
* wizard, MCP tool and NE-bilaga.
|
||||
*
|
||||
* EF tax mechanisms are declaration-only — they NEVER produce journal
|
||||
* entries. The banner makes that BFL distinction visible.
|
||||
*
|
||||
* Override inputs persist to localStorage scoped by fiscal period id, so
|
||||
* re-entering the wizard recalls them without round-tripping a write.
|
||||
*/
|
||||
export function EfDeclarationSection({
|
||||
fiscalPeriodId,
|
||||
bookedSurplus,
|
||||
fiscalYear,
|
||||
}: EfDeclarationSectionProps) {
|
||||
const [category, setCategory] = useState<EgenavgiftCategory>('full')
|
||||
const [priorSchablon, setPriorSchablon] = useState('')
|
||||
const [priorActual, setPriorActual] = useState('')
|
||||
const [kapitalunderlag, setKapitalunderlag] = useState('')
|
||||
const [pfondDesired, setPfondDesired] = useState('')
|
||||
const [expansionsfondBalance, setExpansionsfondBalance] = useState('')
|
||||
const [expansionsfondChange, setExpansionsfondChange] = useState('')
|
||||
const storageKey = `ef-declaration-overrides:${fiscalPeriodId}`
|
||||
|
||||
const items: EfDeclarationItem[] = useMemo(() => {
|
||||
const list: EfDeclarationItem[] = []
|
||||
const eg = calculateEgenavgifter({
|
||||
surplusBeforeEgenavgifter: bookedSurplus,
|
||||
category,
|
||||
priorYearSchablonavdrag: parseFloat(priorSchablon) || 0,
|
||||
priorYearActualCharged: parseFloat(priorActual) || 0,
|
||||
})
|
||||
list.push(eg)
|
||||
const [overrides, setOverrides] = useState<EfOverrideInputs>(DEFAULT_OVERRIDES)
|
||||
const [preview, setPreview] = useState<EfPreviewResponse | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const kap = parseFloat(kapitalunderlag) || 0
|
||||
const r = calculateRantefordelning({ kapitalunderlag: kap })
|
||||
if (r) list.push(r)
|
||||
|
||||
const surplusAfterEg = bookedSurplus - eg.amount
|
||||
const pfond = proposeEfPfondAvsattning({
|
||||
surplus: surplusAfterEg,
|
||||
fiscalYear,
|
||||
desiredAmount: pfondDesired === '' ? undefined : parseFloat(pfondDesired),
|
||||
})
|
||||
if (pfond) list.push(pfond)
|
||||
|
||||
const expChange = parseFloat(expansionsfondChange) || 0
|
||||
if (expChange !== 0) {
|
||||
const exp = calculateExpansionsfondChange({
|
||||
kapitalunderlag: kap,
|
||||
existingBalance: parseFloat(expansionsfondBalance) || 0,
|
||||
desiredChange: expChange,
|
||||
})
|
||||
if (exp) list.push(exp)
|
||||
// Restore overrides from localStorage on mount.
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey)
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw) as Partial<EfOverrideInputs>
|
||||
setOverrides({ ...DEFAULT_OVERRIDES, ...parsed })
|
||||
}
|
||||
} catch {
|
||||
// Ignore — start with defaults.
|
||||
}
|
||||
return list
|
||||
}, [
|
||||
bookedSurplus,
|
||||
category,
|
||||
priorSchablon,
|
||||
priorActual,
|
||||
kapitalunderlag,
|
||||
pfondDesired,
|
||||
expansionsfondBalance,
|
||||
expansionsfondChange,
|
||||
fiscalYear,
|
||||
])
|
||||
}, [storageKey])
|
||||
|
||||
// Persist overrides on change.
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return
|
||||
try {
|
||||
window.localStorage.setItem(storageKey, JSON.stringify(overrides))
|
||||
} catch {
|
||||
// Quota exceeded or disabled — non-fatal.
|
||||
}
|
||||
}, [storageKey, overrides])
|
||||
|
||||
const queryString = useMemo(() => {
|
||||
const params = new URLSearchParams()
|
||||
params.set('category', overrides.category)
|
||||
const kap = parseFloat(overrides.kapitalunderlag)
|
||||
if (Number.isFinite(kap)) params.set('kapitalunderlag', String(kap))
|
||||
const ps = parseFloat(overrides.priorSchablon)
|
||||
if (Number.isFinite(ps)) params.set('priorYearSchablonavdrag', String(ps))
|
||||
const pa = parseFloat(overrides.priorActual)
|
||||
if (Number.isFinite(pa)) params.set('priorYearActualCharged', String(pa))
|
||||
const pf = parseFloat(overrides.pfondDesired)
|
||||
if (Number.isFinite(pf)) params.set('pfondDesiredAmount', String(pf))
|
||||
const eb = parseFloat(overrides.expansionsfondBalance)
|
||||
if (Number.isFinite(eb)) params.set('expansionsfondExistingBalance', String(eb))
|
||||
const ec = parseFloat(overrides.expansionsfondChange)
|
||||
if (Number.isFinite(ec) && ec !== 0) params.set('expansionsfondDesiredChange', String(ec))
|
||||
return params.toString()
|
||||
}, [overrides])
|
||||
|
||||
const loadPreview = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/bookkeeping/fiscal-periods/${fiscalPeriodId}/ef-declaration?${queryString}`,
|
||||
)
|
||||
const body = await res.json()
|
||||
if (!res.ok) {
|
||||
setError(body?.error?.message ?? 'Kunde inte ladda EF-deklaration')
|
||||
setPreview(null)
|
||||
return
|
||||
}
|
||||
setPreview(body.data as EfPreviewResponse)
|
||||
} catch {
|
||||
setError('Kunde inte ladda EF-deklaration')
|
||||
setPreview(null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [fiscalPeriodId, queryString])
|
||||
|
||||
// Debounce refetch so each keystroke doesn't slam the API. 350 ms feels
|
||||
// responsive without being noisy.
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
void loadPreview()
|
||||
}, 350)
|
||||
return () => clearTimeout(handle)
|
||||
}, [loadPreview])
|
||||
|
||||
const update = useCallback(
|
||||
<K extends keyof EfOverrideInputs>(field: K, value: EfOverrideInputs[K]) => {
|
||||
setOverrides((prev) => ({ ...prev, [field]: value }))
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const items = preview?.items ?? []
|
||||
const inputWarnings = preview?.inputWarnings ?? []
|
||||
const noPostedEntries = preview ? preview.postedEntryCount === 0 : false
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* BFL distinction banner — EF values are declaration-only, never booked. */}
|
||||
<Card className="border-border bg-secondary/40">
|
||||
<CardContent className="p-4 flex items-start gap-3">
|
||||
<Info className="h-4 w-4 mt-0.5 text-muted-foreground shrink-0" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<span className="font-medium text-foreground">
|
||||
Skattemässiga justeringar — NE-bilaga
|
||||
</span>
|
||||
<br />
|
||||
För enskild firma bokförs varken skatt, egenavgifter, fonder eller räntefördelning.
|
||||
Värdena nedan visar vad du fyller i på NE-bilagan när du deklarerar. Inga verifikat skapas.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* "No journal entries posted" banner — surfaced when the period has
|
||||
zero posted vouchers, so the user knows the surplus is 0 because
|
||||
nothing's booked yet, not because the calculators failed. */}
|
||||
{noPostedEntries && (
|
||||
<Card className="border-border">
|
||||
<CardContent className="p-4 flex items-start gap-3">
|
||||
<AlertTriangle className="h-4 w-4 mt-0.5 text-warning-foreground shrink-0" />
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">Inga verifikat bokförda i perioden.</span>{' '}
|
||||
Värdena nedan baseras enbart på NE-bilagans räkenskapsschema (intäkter och
|
||||
kostnader hittills). Bokför löpande verifikat först för att få ett realistiskt
|
||||
överskott.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Input form */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Skattemässiga justeringar — NE-bilaga</CardTitle>
|
||||
<CardTitle className="text-base">Indata</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
För enskild firma bokförs inte skatt, egenavgifter, fonder eller
|
||||
räntefördelning. Beräkningarna nedan visar vad du fyller i på NE-bilagan
|
||||
när du deklarerar.
|
||||
Bokfört överskott:{' '}
|
||||
<span className="tabular-nums font-medium text-foreground">
|
||||
{formatCurrency(preview?.bookedSurplus ?? bookedSurplus)}
|
||||
</span>
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
@@ -104,8 +214,8 @@ export function EfDeclarationSection({
|
||||
<Label className="text-xs">Egenavgifter — kategori</Label>
|
||||
<select
|
||||
className="border border-border rounded-md h-9 text-sm px-2 w-full bg-background"
|
||||
value={category}
|
||||
onChange={(e) => setCategory(e.target.value as EgenavgiftCategory)}
|
||||
value={overrides.category}
|
||||
onChange={(e) => update('category', e.target.value as EgenavgiftCategory)}
|
||||
>
|
||||
<option value="full">Aktiv, full sats (28,97 %)</option>
|
||||
<option value="pensioner">Pensionär (10,21 %)</option>
|
||||
@@ -117,8 +227,8 @@ export function EfDeclarationSection({
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={kapitalunderlag}
|
||||
onChange={(e) => setKapitalunderlag(e.target.value)}
|
||||
value={overrides.kapitalunderlag}
|
||||
onChange={(e) => update('kapitalunderlag', e.target.value)}
|
||||
placeholder="0"
|
||||
className="tabular-nums h-9"
|
||||
/>
|
||||
@@ -128,8 +238,8 @@ export function EfDeclarationSection({
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={priorSchablon}
|
||||
onChange={(e) => setPriorSchablon(e.target.value)}
|
||||
value={overrides.priorSchablon}
|
||||
onChange={(e) => update('priorSchablon', e.target.value)}
|
||||
placeholder="0"
|
||||
className="tabular-nums h-9"
|
||||
/>
|
||||
@@ -139,8 +249,8 @@ export function EfDeclarationSection({
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={priorActual}
|
||||
onChange={(e) => setPriorActual(e.target.value)}
|
||||
value={overrides.priorActual}
|
||||
onChange={(e) => update('priorActual', e.target.value)}
|
||||
placeholder="0"
|
||||
className="tabular-nums h-9"
|
||||
/>
|
||||
@@ -150,8 +260,8 @@ export function EfDeclarationSection({
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={pfondDesired}
|
||||
onChange={(e) => setPfondDesired(e.target.value)}
|
||||
value={overrides.pfondDesired}
|
||||
onChange={(e) => update('pfondDesired', e.target.value)}
|
||||
placeholder="0"
|
||||
className="tabular-nums h-9"
|
||||
/>
|
||||
@@ -161,8 +271,8 @@ export function EfDeclarationSection({
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={expansionsfondBalance}
|
||||
onChange={(e) => setExpansionsfondBalance(e.target.value)}
|
||||
value={overrides.expansionsfondBalance}
|
||||
onChange={(e) => update('expansionsfondBalance', e.target.value)}
|
||||
placeholder="0"
|
||||
className="tabular-nums h-9"
|
||||
/>
|
||||
@@ -174,8 +284,8 @@ export function EfDeclarationSection({
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
value={expansionsfondChange}
|
||||
onChange={(e) => setExpansionsfondChange(e.target.value)}
|
||||
value={overrides.expansionsfondChange}
|
||||
onChange={(e) => update('expansionsfondChange', e.target.value)}
|
||||
placeholder="0"
|
||||
className="tabular-nums h-9"
|
||||
/>
|
||||
@@ -184,6 +294,32 @@ export function EfDeclarationSection({
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Top-level input warnings (e.g. missing kapitalunderlag) */}
|
||||
{inputWarnings.map((w, i) => (
|
||||
<Card key={i} className="border-border">
|
||||
<CardContent className="p-4 flex items-start gap-3">
|
||||
<AlertTriangle className="h-4 w-4 mt-0.5 text-warning-foreground shrink-0" />
|
||||
<p className="text-sm">{w}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{/* Loading / error / items */}
|
||||
{error && (
|
||||
<Card>
|
||||
<CardContent className="p-4 text-sm text-destructive">{error}</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{loading && !preview && (
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-3">
|
||||
<Skeleton className="h-6 w-1/3" />
|
||||
<Skeleton className="h-20 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{items.map((item) => (
|
||||
<Card key={item.kind}>
|
||||
<CardHeader>
|
||||
@@ -210,6 +346,7 @@ export function EfDeclarationSection({
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{/* NE-bilaga download */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
@@ -217,8 +354,8 @@ export function EfDeclarationSection({
|
||||
NE-bilaga räkenskapsschema (R1–R11)
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Räkenskapsschema-delen genereras automatiskt från bokföringen. Ladda ner
|
||||
SRU-filen och ladda upp den i Skatteverkets e-tjänst för Inkomstdeklaration 1.
|
||||
Räkenskapsschema-delen genereras automatiskt från bokföringen för räkenskapsåret {fiscalYear}.
|
||||
Ladda ner SRU-filen och ladda upp den i Skatteverkets e-tjänst för Inkomstdeklaration 1.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -1,16 +1,39 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { CheckCircle2 } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import { CheckCircle2, AlertTriangle } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import type { YearEndResult } from '@/types'
|
||||
import type { YearEndResult, ContinuityDiscrepancy } from '@/types'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
|
||||
interface ResultStepProps {
|
||||
result: YearEndResult
|
||||
}
|
||||
|
||||
const ORE_TOLERANCE = 0.005
|
||||
|
||||
export function ResultStep({ result }: ResultStepProps) {
|
||||
const [acknowledged, setAcknowledged] = useState(false)
|
||||
|
||||
const continuity = result.continuity
|
||||
const discrepancies = continuity?.discrepancies ?? []
|
||||
|
||||
// If the wizard reached ResultStep, executeYearEndClosing already enforced
|
||||
// that no per-account diff exceeded ORE_TOLERANCE — but surface a panel
|
||||
// grouped by BAS class so the user can confirm visually before leaving.
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
@@ -32,40 +55,82 @@ export function ResultStep({ result }: ResultStepProps) {
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
<ResultRow
|
||||
label="Bokslutsverifikation"
|
||||
value={`${result.closingEntry.voucher_series}${result.closingEntry.voucher_number}`}
|
||||
value={formatVoucher(result.closingEntry)}
|
||||
href={`/bookkeeping/${result.closingEntry.id}`}
|
||||
/>
|
||||
{result.revaluationEntry && (
|
||||
<ResultRow
|
||||
label="Kursrevaluering"
|
||||
value={`${result.revaluationEntry.voucher_series}${result.revaluationEntry.voucher_number}`}
|
||||
value={formatVoucher(result.revaluationEntry)}
|
||||
href={`/bookkeeping/${result.revaluationEntry.id}`}
|
||||
/>
|
||||
)}
|
||||
<ResultRow
|
||||
label="Ingående balanser i ny period"
|
||||
value={`${result.openingBalanceEntry.voucher_series}${result.openingBalanceEntry.voucher_number}`}
|
||||
value={formatVoucher(result.openingBalanceEntry)}
|
||||
href={`/bookkeeping/${result.openingBalanceEntry.id}`}
|
||||
/>
|
||||
<ResultRow label="Ny räkenskapsperiod" value={result.nextPeriod.name} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-3 sm:justify-end">
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/bookkeeping">Till bokföringen</Link>
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/reports">Generera rapporter</Link>
|
||||
</Button>
|
||||
<Button asChild>
|
||||
<Link
|
||||
href={`/bookkeeping/year-end/arsredovisning?period=${result.closingEntry.fiscal_period_id}`}
|
||||
>
|
||||
Skapa årsredovisning
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
{continuity && (
|
||||
<ContinuityPanel
|
||||
discrepancies={discrepancies}
|
||||
checkedAccounts={continuity.checked_accounts}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-4">
|
||||
<label className="flex items-start gap-3 cursor-pointer">
|
||||
<Checkbox
|
||||
checked={acknowledged}
|
||||
onCheckedChange={(v) => setAcknowledged(v === true)}
|
||||
className="mt-0.5"
|
||||
aria-label="Bekräfta bokslut"
|
||||
/>
|
||||
<span className="text-sm leading-relaxed">
|
||||
Jag har granskat bokslutet och IB/UB-kontinuiteten ovan, och
|
||||
bekräftar att alla balanskonton stämmer mot föregående periods
|
||||
utgående balans.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-3 sm:justify-end">
|
||||
<Button variant="outline" asChild disabled={!acknowledged}>
|
||||
<Link
|
||||
href="/bookkeeping"
|
||||
aria-disabled={!acknowledged}
|
||||
tabIndex={acknowledged ? undefined : -1}
|
||||
className={!acknowledged ? 'pointer-events-none opacity-50' : ''}
|
||||
>
|
||||
Till bokföringen
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" asChild disabled={!acknowledged}>
|
||||
<Link
|
||||
href="/reports"
|
||||
aria-disabled={!acknowledged}
|
||||
tabIndex={acknowledged ? undefined : -1}
|
||||
className={!acknowledged ? 'pointer-events-none opacity-50' : ''}
|
||||
>
|
||||
Generera rapporter
|
||||
</Link>
|
||||
</Button>
|
||||
<Button asChild disabled={!acknowledged}>
|
||||
<Link
|
||||
href={`/bookkeeping/year-end/arsredovisning?period=${result.closingEntry.fiscal_period_id}`}
|
||||
aria-disabled={!acknowledged}
|
||||
tabIndex={acknowledged ? undefined : -1}
|
||||
className={!acknowledged ? 'pointer-events-none opacity-50' : ''}
|
||||
>
|
||||
Skapa årsredovisning
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -84,3 +149,114 @@ function ResultRow({ label, value, href }: { label: string; value: string; href?
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface ContinuityPanelProps {
|
||||
discrepancies: ContinuityDiscrepancy[]
|
||||
checkedAccounts: number
|
||||
}
|
||||
|
||||
function ContinuityPanel({ discrepancies, checkedAccounts }: ContinuityPanelProps) {
|
||||
const grouped = useMemo(() => {
|
||||
const byClass = new Map<number, ContinuityDiscrepancy[]>()
|
||||
for (const d of discrepancies) {
|
||||
const klass = parseInt(d.account_number[0]) || 0
|
||||
if (klass !== 1 && klass !== 2) continue
|
||||
const list = byClass.get(klass) ?? []
|
||||
list.push(d)
|
||||
byClass.set(klass, list)
|
||||
}
|
||||
return byClass
|
||||
}, [discrepancies])
|
||||
|
||||
const hasIssues = discrepancies.some(
|
||||
(d) => Math.abs(d.difference) > ORE_TOLERANCE
|
||||
)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<CardTitle className="text-base">IB/UB-avstämning</CardTitle>
|
||||
{hasIssues ? (
|
||||
<Badge variant="destructive" className="gap-1">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
Avvikelser
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
Stämmer
|
||||
</Badge>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{checkedAccounts} balanskonto(n) jämförda mellan utgående balans i
|
||||
stängd period och ingående balans i ny period.
|
||||
</p>
|
||||
|
||||
{discrepancies.length === 0 ? (
|
||||
<p className="text-sm">
|
||||
Inga avvikelser. Alla balanskonton i klass 1 och 2 matchar inom
|
||||
tolerans (±0,005 SEK).
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{[1, 2].map((klass) => {
|
||||
const rows = grouped.get(klass) ?? []
|
||||
if (rows.length === 0) return null
|
||||
return (
|
||||
<div key={klass}>
|
||||
<h3 className="text-sm font-medium uppercase tracking-wider text-muted-foreground mb-2">
|
||||
Klass {klass} – {klass === 1 ? 'Tillgångar' : 'Skulder & eget kapital'}
|
||||
</h3>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Konto</TableHead>
|
||||
<TableHead className="text-right">UB (föregående)</TableHead>
|
||||
<TableHead className="text-right">IB (ny period)</TableHead>
|
||||
<TableHead className="text-right">Diff</TableHead>
|
||||
<TableHead className="text-right">Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.map((d) => {
|
||||
const overTol = Math.abs(d.difference) > ORE_TOLERANCE
|
||||
return (
|
||||
<TableRow key={d.account_number}>
|
||||
<TableCell className="font-medium tabular-nums">
|
||||
{d.account_number}
|
||||
<span className="ml-2 font-normal text-muted-foreground">
|
||||
{d.account_name}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{formatCurrency(d.previous_ub_net)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{formatCurrency(d.current_ib_net)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{formatCurrency(d.difference)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{overTol ? (
|
||||
<Badge variant="destructive">Avviker</Badge>
|
||||
) : (
|
||||
<Badge variant="success">OK</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1098,9 +1098,9 @@ function FiscalYearResult({ result, index }: { result: ImportResult; index: numb
|
||||
{' · '}{d.skippedVouchers.total} hoppade över
|
||||
</span>
|
||||
)}
|
||||
{result.replacedPriorImport && result.replacedPriorImport.cancelledEntries > 0 && (
|
||||
{result.replacedPriorImport && result.replacedPriorImport.deletedEntries > 0 && (
|
||||
<span>
|
||||
{' · '}ersatte {result.replacedPriorImport.cancelledEntries.toLocaleString('sv-SE')} tidigare importerade verifikationer
|
||||
{' · '}ersatte {result.replacedPriorImport.deletedEntries.toLocaleString('sv-SE')} tidigare importerade verifikationer
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
@@ -1868,7 +1868,7 @@ export default function ArcimMigrationWorkspace(_props: WorkspaceComponentProps)
|
||||
// Send every file to the engine. The Fortnox endpoint runs in
|
||||
// replace-mode, so a year that already has a completed import
|
||||
// gets its prior import marked 'replaced' (imported entries
|
||||
// cancelled, user-created entries untouched) before the new
|
||||
// deleted, user-created entries untouched) before the new
|
||||
// SIE is loaded. The per-file result reports replacedPriorImport.
|
||||
const filesToImport = sieData.rawContent.map((content, i) => ({
|
||||
content,
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
throwOnStructuredError,
|
||||
} from '@/lib/hooks/use-submit-with-account-activation'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import type { BASAccount, FiscalPeriod, InvoiceExtractionResult } from '@/types'
|
||||
|
||||
interface InboxItem {
|
||||
@@ -341,7 +342,7 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
|
||||
toast({
|
||||
title: 'Bokfört',
|
||||
description: voucher
|
||||
? `Verifikation ${voucher.voucher_series}${voucher.voucher_number} skapad.`
|
||||
? `Verifikation ${formatVoucher(voucher)} skapad.`
|
||||
: 'Verifikation skapad.',
|
||||
})
|
||||
await onSuccess()
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
import { AlertCircle, ChevronDown, ChevronRight, Link2, Unlink, Play, Eye } from 'lucide-react'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { CashAccountSelector } from '@/components/common/CashAccountSelector'
|
||||
|
||||
function formatAmount(amount: number): string {
|
||||
@@ -411,7 +412,7 @@ export function BankReconciliationView() {
|
||||
<td className="py-2 text-right font-mono">{formatAmount(m.transaction_amount)}</td>
|
||||
<td className="py-2 text-center text-muted-foreground">↔</td>
|
||||
<td className="py-2">
|
||||
<span className="font-mono text-xs">{m.voucher_series}{m.voucher_number}</span>
|
||||
<span className="font-mono text-xs">{formatVoucher(m)}</span>
|
||||
<span className="ml-2 text-muted-foreground truncate">{m.entry_description}</span>
|
||||
</td>
|
||||
<td className="py-2 tabular-nums">{formatDate(m.entry_date)}</td>
|
||||
@@ -478,7 +479,7 @@ export function BankReconciliationView() {
|
||||
const lineAmount = line.debit_amount > 0 ? line.debit_amount : -line.credit_amount
|
||||
return (
|
||||
<option key={line.line_id} value={line.journal_entry_id}>
|
||||
{line.voucher_series}{line.voucher_number} | {formatDate(line.entry_date)} | {formatCurrency(lineAmount)} | {line.entry_description}
|
||||
{formatVoucher(line)} | {formatDate(line.entry_date)} | {formatCurrency(lineAmount)} | {line.entry_description}
|
||||
</option>
|
||||
)
|
||||
})}
|
||||
@@ -528,7 +529,7 @@ export function BankReconciliationView() {
|
||||
return (
|
||||
<tr key={line.line_id} className="border-b last:border-0">
|
||||
<td className="py-2 font-mono text-xs">
|
||||
{line.voucher_series}{line.voucher_number}
|
||||
{formatVoucher(line)}
|
||||
</td>
|
||||
<td className="py-2 tabular-nums">{formatDate(line.entry_date)}</td>
|
||||
<td className="py-2 truncate max-w-[300px]">
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
'use client'
|
||||
|
||||
import React, { useState, useCallback, useMemo } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { ChevronDown, ChevronRight, AlertCircle } from 'lucide-react'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import {
|
||||
createSourceLoader,
|
||||
type ReportSourceLine,
|
||||
type ReportSourceFetcher,
|
||||
} from '@/lib/reports/source-lines'
|
||||
|
||||
interface ReportRowExpansionProps {
|
||||
/** Lazy fetcher invoked the first time the row is expanded. */
|
||||
fetcher: ReportSourceFetcher
|
||||
/** Column span used by the inline expansion `<tr>`. */
|
||||
colSpan: number
|
||||
/** Stable id used as the toggle's aria-controls reference. */
|
||||
rowId: string
|
||||
}
|
||||
|
||||
interface UseSourceLinesResult {
|
||||
lines: ReportSourceLine[] | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
load: () => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook owning the lazy fetch + caching of source lines. Thin wrapper on top
|
||||
* of `createSourceLoader` from `lib/reports/source-lines` so the loading
|
||||
* semantics can be unit-tested in node without DOM.
|
||||
*
|
||||
* The cache lives per-instance — reopening the same row never refetches.
|
||||
*/
|
||||
export function useSourceLines(fetcher: ReportSourceFetcher): UseSourceLinesResult {
|
||||
const [lines, setLines] = useState<ReportSourceLine[] | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// The loader is stable for the lifetime of the fetcher reference; callers
|
||||
// are expected to memoise their fetcher with `useMemo` (every callsite in
|
||||
// `reports/page.tsx` does).
|
||||
const loader = useMemo(
|
||||
() =>
|
||||
createSourceLoader(fetcher, (s) => {
|
||||
setLines(s.lines)
|
||||
setLoading(s.loading)
|
||||
setError(s.error)
|
||||
}),
|
||||
[fetcher]
|
||||
)
|
||||
|
||||
const load = useCallback(() => loader.load(), [loader])
|
||||
|
||||
return { lines, loading, error, load }
|
||||
}
|
||||
|
||||
/**
|
||||
* Drilldown affordance for aggregated report rows.
|
||||
*
|
||||
* Renders two cells (the chevron-toggle is placed in the calling row; the
|
||||
* expansion itself is rendered as a sibling `<tr>` only when expanded).
|
||||
* The caller is responsible for placing `<ReportRowExpansion.Toggle>` inside
|
||||
* the aggregated row and `<ReportRowExpansion.Panel>` immediately below.
|
||||
*
|
||||
* Usage:
|
||||
* const expansion = useReportRowExpansion(fetcher)
|
||||
* <tr><td><expansion.Toggle /></td>...</tr>
|
||||
* {expansion.expanded && <expansion.Panel colSpan={6} />}
|
||||
*
|
||||
* Or use the all-in-one component below where the caller owns the
|
||||
* surrounding `<tr>` and just plugs the expansion in.
|
||||
*/
|
||||
export function ReportRowExpansion({
|
||||
fetcher,
|
||||
colSpan,
|
||||
rowId,
|
||||
}: ReportRowExpansionProps) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const { lines, loading, error, load } = useSourceLines(fetcher)
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
const next = !expanded
|
||||
setExpanded(next)
|
||||
if (next) load()
|
||||
}, [expanded, load])
|
||||
|
||||
return (
|
||||
<>
|
||||
<td className="py-2 w-8">
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
aria-expanded={expanded}
|
||||
aria-controls={`expansion-${rowId}`}
|
||||
aria-label={expanded ? 'Dölj verifikat' : 'Visa verifikat'}
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors"
|
||||
>
|
||||
{expanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
</td>
|
||||
{expanded && (
|
||||
<ExpansionPanel
|
||||
colSpan={colSpan}
|
||||
loading={loading}
|
||||
error={error}
|
||||
lines={lines}
|
||||
rowId={rowId}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant where the toggle and the expansion are placed by the caller. The
|
||||
* caller renders `<Toggle />` inside the aggregated `<tr>`, then below
|
||||
* conditionally renders `<Panel />` as a sibling `<tr>` so its `<td
|
||||
* colSpan={n}>` lines up with the rest of the table.
|
||||
*/
|
||||
export function useReportRowExpansion(fetcher: ReportSourceFetcher, rowId: string) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const { lines, loading, error, load } = useSourceLines(fetcher)
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
const next = !expanded
|
||||
setExpanded(next)
|
||||
if (next) load()
|
||||
}, [expanded, load])
|
||||
|
||||
const Toggle = () => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
aria-expanded={expanded}
|
||||
aria-controls={`expansion-${rowId}`}
|
||||
aria-label={expanded ? 'Dölj verifikat' : 'Visa verifikat'}
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors"
|
||||
>
|
||||
{expanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
|
||||
const Panel = ({ colSpan }: { colSpan: number }) =>
|
||||
expanded ? (
|
||||
<ExpansionPanelRow
|
||||
colSpan={colSpan}
|
||||
loading={loading}
|
||||
error={error}
|
||||
lines={lines}
|
||||
rowId={rowId}
|
||||
/>
|
||||
) : null
|
||||
|
||||
return { expanded, Toggle, Panel }
|
||||
}
|
||||
|
||||
/**
|
||||
* Body of the expansion when the wrapping `<td>` colSpan is provided —
|
||||
* renders inline (used by ReportRowExpansion).
|
||||
*/
|
||||
function ExpansionPanel({
|
||||
colSpan,
|
||||
loading,
|
||||
error,
|
||||
lines,
|
||||
rowId,
|
||||
}: {
|
||||
colSpan: number
|
||||
loading: boolean
|
||||
error: string | null
|
||||
lines: ReportSourceLine[] | null
|
||||
rowId: string
|
||||
}) {
|
||||
return (
|
||||
<td colSpan={colSpan} id={`expansion-${rowId}`} className="bg-muted/20 p-0">
|
||||
<ExpansionContent loading={loading} error={error} lines={lines} />
|
||||
</td>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Body of the expansion when used in a sibling `<tr>` (used by
|
||||
* `useReportRowExpansion`'s Panel).
|
||||
*/
|
||||
function ExpansionPanelRow({
|
||||
colSpan,
|
||||
loading,
|
||||
error,
|
||||
lines,
|
||||
rowId,
|
||||
}: {
|
||||
colSpan: number
|
||||
loading: boolean
|
||||
error: string | null
|
||||
lines: ReportSourceLine[] | null
|
||||
rowId: string
|
||||
}) {
|
||||
return (
|
||||
<tr className="bg-muted/20">
|
||||
<td colSpan={colSpan} id={`expansion-${rowId}`} className="p-0">
|
||||
<ExpansionContent loading={loading} error={error} lines={lines} />
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
function ExpansionContent({
|
||||
loading,
|
||||
error,
|
||||
lines,
|
||||
}: {
|
||||
loading: boolean
|
||||
error: string | null
|
||||
lines: ReportSourceLine[] | null
|
||||
}) {
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="px-4 py-3 space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-5/6" />
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="px-4 py-3 flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!lines || lines.length === 0) {
|
||||
return (
|
||||
<div className="px-4 py-3 text-sm text-muted-foreground">
|
||||
Inga underliggande verifikat.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 py-2">
|
||||
<table className="w-full text-xs">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[10px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="text-left">
|
||||
<th className="py-1 w-24">Verifikat</th>
|
||||
<th className="py-1 w-24">Datum</th>
|
||||
<th className="py-1">Beskrivning</th>
|
||||
<th className="py-1 w-24 text-right">Debet</th>
|
||||
<th className="py-1 w-24 text-right">Kredit</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{lines.map((line) => (
|
||||
<tr key={`${line.voucher_series}-${line.voucher_number}-${line.journal_entry_id}`} className="border-t border-border/40">
|
||||
<td className="py-1.5">
|
||||
{line.journal_entry_id ? (
|
||||
<Link
|
||||
href={`/bookkeeping/${line.journal_entry_id}`}
|
||||
className="font-mono text-foreground hover:underline underline-offset-4"
|
||||
>
|
||||
{formatVoucher(line)}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="font-mono text-muted-foreground">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-1.5 tabular-nums text-muted-foreground">
|
||||
{line.date ? formatDate(line.date) : ''}
|
||||
</td>
|
||||
<td className="py-1.5 truncate max-w-md" title={line.description}>
|
||||
{line.description}
|
||||
</td>
|
||||
<td className="py-1.5 text-right tabular-nums">
|
||||
{line.debit > 0 ? formatAmount(line.debit) : ''}
|
||||
</td>
|
||||
<td className="py-1.5 text-right tabular-nums">
|
||||
{line.credit > 0 ? formatAmount(line.credit) : ''}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function formatAmount(amount: number): string {
|
||||
return amount.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})
|
||||
}
|
||||
@@ -38,6 +38,8 @@ const CATEGORIES: ReportCategory[] = [
|
||||
items: [
|
||||
{ value: 'income-statement', labelKey: 'name_income_statement' },
|
||||
{ value: 'balance-sheet', labelKey: 'name_balance_sheet' },
|
||||
{ value: 'kassaflodesanalys', labelKey: 'name_kassaflodesanalys' },
|
||||
{ value: 'arsredovisning', labelKey: 'name_arsredovisning', entityType: 'aktiebolag' },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import type { AccountingFramework } from '@/types'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface AccountingFrameworkFormProps {
|
||||
/** Current framework on the company row. */
|
||||
current: AccountingFramework
|
||||
/** Bubble up after a successful save so parent state can refresh. */
|
||||
onSaved?: (next: AccountingFramework) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* K2/K3 selector for AB. Lives on the bookkeeping settings page. Renders nothing
|
||||
* for non-AB entities — the parent gates this component by entity_type.
|
||||
*
|
||||
* UX rules (regulatory area — kept in Swedish):
|
||||
* - Default is K2 (matches the column default and BFNAR 2016:10 baseline).
|
||||
* - Switching K2 → K3 fires a confirmation dialog. The recommendation per
|
||||
* BFN is that the choice is permanent for the company once made; we
|
||||
* surface that as a warning, not a block, so the user can still revert.
|
||||
* - The save is its own request (PATCH /api/company/current) — separate
|
||||
* from /api/settings because the column lives on companies, not on
|
||||
* company_settings.
|
||||
*/
|
||||
export function AccountingFrameworkForm({ current, onSaved }: AccountingFrameworkFormProps) {
|
||||
const { toast } = useToast()
|
||||
const [selected, setSelected] = useState<AccountingFramework>(current)
|
||||
const [pending, setPending] = useState<AccountingFramework | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
async function persist(next: AccountingFramework) {
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/company/current', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ accounting_framework: next }),
|
||||
})
|
||||
const body = await res.json()
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: 'Kunde inte spara',
|
||||
description: body?.error ?? 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
setSelected(current)
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: 'Sparat',
|
||||
description:
|
||||
next === 'k3'
|
||||
? 'Bolaget redovisar nu enligt K3 (BFNAR 2012:1).'
|
||||
: 'Bolaget redovisar nu enligt K2 (BFNAR 2016:10).',
|
||||
})
|
||||
onSaved?.(next)
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte spara',
|
||||
description: 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
setSelected(current)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
setPending(null)
|
||||
}
|
||||
}
|
||||
|
||||
function handleChange(next: string) {
|
||||
const value = next as AccountingFramework
|
||||
if (value === selected) return
|
||||
// K2 → K3 is the consequential direction: confirm before persisting.
|
||||
if (selected === 'k2' && value === 'k3') {
|
||||
setPending(value)
|
||||
return
|
||||
}
|
||||
setSelected(value)
|
||||
void persist(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Redovisningsregelverk
|
||||
</h2>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="accounting_framework">Regelverk</Label>
|
||||
<Select
|
||||
value={selected}
|
||||
onValueChange={handleChange}
|
||||
disabled={saving}
|
||||
>
|
||||
<SelectTrigger id="accounting_framework" className="w-full max-w-sm">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="k2">K2 (BFNAR 2016:10) — mindre företag</SelectItem>
|
||||
<SelectItem value="k3">K3 (BFNAR 2012:1) — större företag</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
K2 är standard för mindre bolag och innebär förenklade regler. K3 krävs när
|
||||
bolaget når två av tre tröskelvärden (nettoomsättning > 80 MSEK, tillgångar
|
||||
> 40 MSEK, eller fler än 50 anställda). K3 ställer högre krav: kassaflödesanalys,
|
||||
komponentavskrivning på materiella anläggningstillgångar och redovisning av
|
||||
uppskjuten skatt på obeskattade reserver (79,4 % eget kapital / 20,6 % skuld).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Dialog
|
||||
open={pending !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPending(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Byta till K3?</DialogTitle>
|
||||
<DialogDescription className="space-y-2 pt-2">
|
||||
<span className="block">
|
||||
K3 medför löpande att kassaflödesanalys upprättas, komponentavskrivning
|
||||
används och uppskjuten skatt redovisas separat (konto 2240 / 8940).
|
||||
</span>
|
||||
<span className="block">
|
||||
Bytet är permanent enligt rekommendation. Fortsätt?
|
||||
</span>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setPending(null)}
|
||||
disabled={saving}
|
||||
>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!pending) return
|
||||
setSelected(pending)
|
||||
void persist(pending)
|
||||
}}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Sparar…
|
||||
</>
|
||||
) : (
|
||||
'Byt till K3'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useState, useCallback } from 'react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
@@ -18,6 +19,15 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
|
||||
const { toast } = useToast()
|
||||
const [lateFeeText, setLateFeeText] = useState(settings.invoice_late_fee_text || '')
|
||||
const [creditTermsText, setCreditTermsText] = useState(settings.invoice_credit_terms_text || '')
|
||||
const [reminderFeeAmount, setReminderFeeAmount] = useState(
|
||||
String(settings.reminder_fee_amount ?? 60),
|
||||
)
|
||||
// Display override as a percentage (the DB stores a decimal). Empty = no override.
|
||||
const [interestRatePercent, setInterestRatePercent] = useState(
|
||||
settings.reminder_interest_rate_override != null
|
||||
? String(settings.reminder_interest_rate_override * 100)
|
||||
: '',
|
||||
)
|
||||
|
||||
const saveToggle = useCallback(async (field: string, value: boolean) => {
|
||||
try {
|
||||
@@ -61,6 +71,62 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
|
||||
}
|
||||
}, [onUpdate, toast, t])
|
||||
|
||||
const saveReminderFeeAmount = useCallback(async (raw: string) => {
|
||||
const parsed = parseFloat(raw.replace(',', '.'))
|
||||
if (Number.isNaN(parsed) || parsed < 0) {
|
||||
toast({ title: 'Ogiltigt belopp', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
// Lag 1981:739: maxgräns 60 kr för lagstadgad påminnelseavgift.
|
||||
const clamped = Math.min(parsed, 60)
|
||||
try {
|
||||
const response = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reminder_fee_amount: clamped }),
|
||||
})
|
||||
if (!response.ok) throw new Error()
|
||||
onUpdate({ reminder_fee_amount: clamped })
|
||||
setReminderFeeAmount(String(clamped))
|
||||
} catch {
|
||||
toast({ title: t('toast_save_failed'), variant: 'destructive' })
|
||||
}
|
||||
}, [onUpdate, toast, t])
|
||||
|
||||
const saveInterestOverride = useCallback(async (raw: string) => {
|
||||
if (raw.trim() === '') {
|
||||
try {
|
||||
const response = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reminder_interest_rate_override: null }),
|
||||
})
|
||||
if (!response.ok) throw new Error()
|
||||
onUpdate({ reminder_interest_rate_override: null })
|
||||
} catch {
|
||||
toast({ title: t('toast_save_failed'), variant: 'destructive' })
|
||||
}
|
||||
return
|
||||
}
|
||||
const percent = parseFloat(raw.replace(',', '.'))
|
||||
if (Number.isNaN(percent) || percent < 0 || percent >= 100) {
|
||||
toast({ title: 'Ogiltig räntesats (0–99%)', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
const decimal = Math.round((percent / 100) * 10_000) / 10_000
|
||||
try {
|
||||
const response = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reminder_interest_rate_override: decimal }),
|
||||
})
|
||||
if (!response.ok) throw new Error()
|
||||
onUpdate({ reminder_interest_rate_override: decimal })
|
||||
} catch {
|
||||
toast({ title: t('toast_save_failed'), variant: 'destructive' })
|
||||
}
|
||||
}, [onUpdate, toast, t])
|
||||
|
||||
return (
|
||||
<section className="space-y-6">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
@@ -118,7 +184,7 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
|
||||
<p className="text-xs text-muted-foreground">{t('show_swish_help')}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings.invoice_show_swish ?? true}
|
||||
checked={settings.invoice_show_swish ?? false}
|
||||
onCheckedChange={(v) => saveToggle('invoice_show_swish', v)}
|
||||
/>
|
||||
</div>
|
||||
@@ -221,6 +287,62 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
|
||||
onCheckedChange={(v) => saveToggle('send_invoice_reminders', v)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label>Aktivera påminnelseavgift</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Debitera lagstadgad påminnelseavgift (Lag 1981:739, max 60 kr) på varje påminnelse.
|
||||
Avgiften bokförs automatiskt (1510 / 3990) och adderas till kundens fordran.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings.reminder_fee_enabled ?? true}
|
||||
onCheckedChange={(v) => saveToggle('reminder_fee_enabled', v)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{(settings.reminder_fee_enabled ?? true) && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pl-0">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="reminder_fee_amount">Påminnelseavgift (kr)</Label>
|
||||
<Input
|
||||
id="reminder_fee_amount"
|
||||
type="number"
|
||||
min={0}
|
||||
max={60}
|
||||
step={1}
|
||||
value={reminderFeeAmount}
|
||||
onChange={(e) => setReminderFeeAmount(e.target.value)}
|
||||
onBlur={() => saveReminderFeeAmount(reminderFeeAmount)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Standardvärde 60 kr. Maxgräns enligt Lag 1981:739.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="reminder_interest_rate_override">
|
||||
Räntesats för dröjsmålsränta (% per år)
|
||||
</Label>
|
||||
<Input
|
||||
id="reminder_interest_rate_override"
|
||||
type="number"
|
||||
min={0}
|
||||
max={99}
|
||||
step={0.1}
|
||||
placeholder="Lämna tom för Räntelagen §6 (referensränta + 8 procentenheter)"
|
||||
value={interestRatePercent}
|
||||
onChange={(e) => setInterestRatePercent(e.target.value)}
|
||||
onBlur={() => saveInterestOverride(interestRatePercent)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Om tom används lagstadgad dröjsmålsränta (Räntelagen §6 = Riksbankens
|
||||
referensränta + 8 procentenheter). Räntan visas i påminnelsen men bokförs inte.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useSyncExternalStore } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { ExternalLink } from 'lucide-react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
/**
|
||||
* Per-user toggle for the periodisering wizard's auto-detection step.
|
||||
*
|
||||
* Backed by localStorage (key: `periodisering_autodetect_enabled`) because
|
||||
* the company_settings table does not yet have a dedicated column for this
|
||||
* preference, and the task description explicitly allows the persistence to
|
||||
* be UI-local. A future migration can promote this to a real
|
||||
* `company_settings.periodisering_autodetect_enabled boolean` column and
|
||||
* the wizard's auto-detect step will read either source.
|
||||
*
|
||||
* Default: enabled. The wizard's auto-detect step renders regardless — the
|
||||
* toggle merely controls whether the GET response includes `autoDetected`
|
||||
* on subsequent fetches. (Today the API always returns it; the wizard step
|
||||
* can early-out based on this setting locally.)
|
||||
*/
|
||||
const STORAGE_KEY = 'periodisering_autodetect_enabled'
|
||||
|
||||
function readStored(): boolean {
|
||||
if (typeof window === 'undefined') return true
|
||||
try {
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY)
|
||||
return stored === null ? true : stored !== 'false'
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribe to localStorage changes from OTHER tabs. Same-tab updates are
|
||||
* picked up via the explicit re-render after `setItem` — see
|
||||
* `notifyChange` below. */
|
||||
function subscribe(callback: () => void): () => void {
|
||||
if (typeof window === 'undefined') return () => {}
|
||||
const handler = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEY || e.key === null) callback()
|
||||
}
|
||||
const customHandler = () => callback()
|
||||
window.addEventListener('storage', handler)
|
||||
window.addEventListener('gnubok-periodisering-toggle', customHandler)
|
||||
return () => {
|
||||
window.removeEventListener('storage', handler)
|
||||
window.removeEventListener('gnubok-periodisering-toggle', customHandler)
|
||||
}
|
||||
}
|
||||
|
||||
/** Fire a same-tab notification so useSyncExternalStore re-subscribers
|
||||
* see the change without a manual setState. */
|
||||
function notifyChange() {
|
||||
if (typeof window === 'undefined') return
|
||||
window.dispatchEvent(new Event('gnubok-periodisering-toggle'))
|
||||
}
|
||||
|
||||
export function PeriodiseringAutoDetectToggle() {
|
||||
const enabled = useSyncExternalStore(
|
||||
subscribe,
|
||||
readStored,
|
||||
// Server snapshot: default to enabled. Matches the client default so
|
||||
// hydration is identical.
|
||||
() => true,
|
||||
)
|
||||
|
||||
const handleChange = useCallback((value: boolean) => {
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, String(value))
|
||||
} catch {
|
||||
// No-op; if storage is blocked the toggle simply won't persist.
|
||||
}
|
||||
notifyChange()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Periodisering
|
||||
</h2>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="periodisering-autodetect" className="text-sm">
|
||||
Aktivera automatisk periodiseringsdetektering
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground max-w-md">
|
||||
Skannar fakturor i bokslutet efter datumintervall som sträcker sig
|
||||
in i nästa räkenskapsår och föreslår periodiseringar i bokslut-wizarden.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="periodisering-autodetect"
|
||||
checked={enabled}
|
||||
onCheckedChange={handleChange}
|
||||
/>
|
||||
</div>
|
||||
<Link
|
||||
href="/bookkeeping/year-end/periodisering"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
Öppna periodiserings-wizarden
|
||||
</Link>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -88,6 +88,15 @@ export function SecuritySettings() {
|
||||
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
// Supabase rejects updateUser({password}) with this exact message when
|
||||
// the user has a TOTP factor enrolled but is at AAL1. Send them through
|
||||
// /mfa/verify to step up; on return they land back here and can retry.
|
||||
if (body.error?.includes('AAL2')) {
|
||||
router.push(
|
||||
`/mfa/verify?returnTo=${encodeURIComponent('/settings/account')}`,
|
||||
)
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: t('toast_update_failed_title'),
|
||||
description: body.error || t('toast_update_failed_description'),
|
||||
@@ -122,6 +131,14 @@ export function SecuritySettings() {
|
||||
const { error } = await supabase.auth.mfa.unenroll({ factorId: mfaFactorId })
|
||||
|
||||
if (error) {
|
||||
// mfa.unenroll requires AAL2 — for BankID-linked users at AAL1 (the
|
||||
// shouldEnforceMfa skip path), this is the only way to step up.
|
||||
if (error.message?.includes('AAL2')) {
|
||||
router.push(
|
||||
`/mfa/verify?returnTo=${encodeURIComponent('/settings/account')}`,
|
||||
)
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: t('toast_unenroll_failed_title'),
|
||||
description: error.message,
|
||||
|
||||
@@ -35,6 +35,7 @@ export function SettingsNav({ isSandbox }: { isSandbox?: boolean }) {
|
||||
{ href: '/settings/skatteverket', label: t('skatteverket'), show: hasCompany && !isSandbox && hasSkatteverketExtension },
|
||||
{ href: '/settings/salary', label: t('salary'), show: hasCompany && company?.entity_type === 'aktiebolag' },
|
||||
{ href: '/settings/templates', label: t('templates'), show: hasCompany },
|
||||
{ href: '/settings/approval-rules', label: t('approval_rules'), show: hasCompany },
|
||||
{ href: '/settings/account', label: t('account'), show: true },
|
||||
{ href: '/settings/api', label: t('api'), show: hasCompany && hasMcpExtension },
|
||||
].filter(item => item.show)
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import type { CompanySettings, JournalEntrySourceType } from '@/types'
|
||||
|
||||
const SERIES_OPTIONS = 'ABCDEFG'.split('')
|
||||
|
||||
// Subset of source_types presented to the user. The DB column accepts every
|
||||
// JournalEntrySourceType, but several values (storno, correction, etc.) are
|
||||
// derived from the original entry's series and would surprise the user if
|
||||
// surfaced as configurable. We expose only the user-relevant subset; the
|
||||
// engine still falls back to 'A' for the keys we hide.
|
||||
const VISIBLE_SOURCE_TYPES: Array<{ key: JournalEntrySourceType; labelKey: string }> = [
|
||||
{ key: 'manual', labelKey: 'manual' },
|
||||
{ key: 'invoice_created', labelKey: 'invoice_created' },
|
||||
{ key: 'invoice_paid', labelKey: 'invoice_paid' },
|
||||
{ key: 'supplier_invoice_registered', labelKey: 'supplier_invoice_registered' },
|
||||
{ key: 'supplier_invoice_paid', labelKey: 'supplier_invoice_paid' },
|
||||
{ key: 'salary_payment', labelKey: 'salary_payment' },
|
||||
{ key: 'bank_transaction', labelKey: 'bank_transaction' },
|
||||
{ key: 'reminder_fee', labelKey: 'reminder_fee' },
|
||||
{ key: 'opening_balance', labelKey: 'opening_balance' },
|
||||
{ key: 'year_end', labelKey: 'year_end' },
|
||||
]
|
||||
|
||||
// Swedish labels. Kept inline so this component is self-contained — these
|
||||
// labels are bookkeeping-domain terms that intentionally stay Swedish across
|
||||
// locales (see CLAUDE.md i18n table).
|
||||
const SV_LABELS: Record<string, string> = {
|
||||
manual: 'Manuella verifikat',
|
||||
invoice_created: 'Kundfakturor (skapande)',
|
||||
invoice_paid: 'Kundfakturor (betalning)',
|
||||
supplier_invoice_registered: 'Leverantörsfakturor (registrering)',
|
||||
supplier_invoice_paid: 'Leverantörsfakturor (betalning)',
|
||||
salary_payment: 'Lön',
|
||||
bank_transaction: 'Banktransaktioner',
|
||||
reminder_fee: 'Påminnelseavgifter',
|
||||
opening_balance: 'Ingående balanser',
|
||||
year_end: 'Bokslut',
|
||||
}
|
||||
|
||||
interface Props {
|
||||
settings: CompanySettings
|
||||
onSettingsUpdated: (settings: Partial<CompanySettings>) => void
|
||||
}
|
||||
|
||||
export function VoucherSeriesPerSourceTypeForm({ settings, onSettingsUpdated }: Props) {
|
||||
const { toast } = useToast()
|
||||
const initialMap = settings.default_voucher_series_per_source_type || {}
|
||||
const [draft, setDraft] = useState<Partial<Record<JournalEntrySourceType, string>>>(
|
||||
initialMap as Partial<Record<JournalEntrySourceType, string>>,
|
||||
)
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
|
||||
const handleChange = (sourceType: JournalEntrySourceType, value: string) => {
|
||||
setDraft((prev) => ({ ...prev, [sourceType]: value }))
|
||||
}
|
||||
|
||||
const hasChanges =
|
||||
JSON.stringify(draft) !== JSON.stringify(initialMap)
|
||||
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
default_voucher_series_per_source_type: draft,
|
||||
}),
|
||||
})
|
||||
const json = await res.json()
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: 'Kunde inte spara',
|
||||
description: getErrorMessage(json, { context: 'settings', statusCode: res.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
onSettingsUpdated({
|
||||
default_voucher_series_per_source_type: draft as Record<JournalEntrySourceType, string>,
|
||||
})
|
||||
toast({
|
||||
title: 'Verifikationsserier sparade',
|
||||
description: 'Nya verifikat använder de uppdaterade serierna.',
|
||||
})
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Kunde inte spara',
|
||||
description: getErrorMessage(err, { context: 'settings' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Verifikationsserier per typ
|
||||
</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Tilldela en standardserie per typ av verifikat. Vanlig svensk
|
||||
praxis: leverantörsfakturor på serie B, löner på serie C, övrigt på
|
||||
serie A. Kan alltid ändras per verifikat när du bokför.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{VISIBLE_SOURCE_TYPES.map(({ key, labelKey }) => (
|
||||
<div key={key} className="flex items-center justify-between gap-3">
|
||||
<Label
|
||||
htmlFor={`series-${key}`}
|
||||
className="text-sm text-foreground flex-1 cursor-pointer"
|
||||
>
|
||||
{SV_LABELS[labelKey] ?? key}
|
||||
</Label>
|
||||
<Select
|
||||
value={(draft[key] as string | undefined) || 'A'}
|
||||
onValueChange={(v) => handleChange(key, v)}
|
||||
>
|
||||
<SelectTrigger
|
||||
id={`series-${key}`}
|
||||
className="w-16 font-mono"
|
||||
aria-label={SV_LABELS[labelKey] ?? key}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{SERIES_OPTIONS.map((letter) => (
|
||||
<SelectItem key={letter} value={letter} className="font-mono">
|
||||
{letter}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || isSaving}
|
||||
>
|
||||
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Spara serier
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
} from '@/components/ui/table'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import type { StoredSkattekontoTransaction } from '@/types/skatteverket'
|
||||
|
||||
interface MatchCandidate {
|
||||
@@ -177,9 +178,7 @@ export function SkattekontoMatchDialog({
|
||||
<TableRow key={c.journal_entry_id}>
|
||||
<TableCell className="tabular-nums">{c.entry_date}</TableCell>
|
||||
<TableCell className="tabular-nums">
|
||||
{c.voucher_series && c.voucher_number
|
||||
? `${c.voucher_series}${c.voucher_number}`
|
||||
: '–'}
|
||||
{formatVoucher(c)}
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[260px] truncate">
|
||||
{c.description}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
DataListMetaSeparator,
|
||||
} from '@/components/ui/data-list'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { AlertCircle, ArrowUpRight, ArrowDownRight, Landmark, Link2, Loader2 } from 'lucide-react'
|
||||
import type {
|
||||
SkattekontoMatchSuggestion,
|
||||
@@ -46,7 +47,10 @@ export default function SkattekontoInboxCard({
|
||||
const duplicateLabel =
|
||||
matchSuggestion?.voucher_series && matchSuggestion?.voucher_number
|
||||
? t('duplicate_title_with_voucher', {
|
||||
label: `${matchSuggestion.voucher_series}${matchSuggestion.voucher_number}`,
|
||||
label: formatVoucher({
|
||||
voucher_series: matchSuggestion.voucher_series,
|
||||
voucher_number: matchSuggestion.voucher_number,
|
||||
}),
|
||||
})
|
||||
: t('duplicate_title_draft')
|
||||
|
||||
|
||||
@@ -121,6 +121,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn(),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/email/service', () => ({
|
||||
|
||||
+186
-16
@@ -26,6 +26,28 @@ const timeString = z.string().regex(/^\d{2}:\d{2}(:\d{2})?$/, 'Expected HH:MM or
|
||||
|
||||
export const EntityTypeSchema = z.enum(['enskild_firma', 'aktiebolag'])
|
||||
|
||||
export const AccountingFrameworkSchema = z.enum(['k2', 'k3'])
|
||||
|
||||
/**
|
||||
* Single K3 component (BFNAR 2012:1 ch.17.4 — komponentavskrivning).
|
||||
*
|
||||
* Used inside AssetCreateSchema / AssetUpdateSchema's `k3_components` array.
|
||||
* The cross-component invariant (sum of `cost` equals asset `acquisition_cost`)
|
||||
* lives in `validateComponents` from `lib/bokslut/assets/k3-components.ts`
|
||||
* and is called by the route-layer refinement — it cannot be expressed in
|
||||
* a single-object schema. Component-level checks (cost > 0, salvage ≤ cost,
|
||||
* positive useful life) are reinforced by `validateComponents` too so any
|
||||
* future caller that uses just the validator gets the same guarantees.
|
||||
*
|
||||
* `salvage_value` is optional; the engine treats omission as 0.
|
||||
*/
|
||||
export const K3ComponentSchema = z.object({
|
||||
name: z.string().min(1, 'Komponentens namn krävs.'),
|
||||
cost: z.number().positive('Anskaffningsvärdet måste vara större än 0.'),
|
||||
useful_life_months: z.number().int().positive('Nyttjandeperioden måste vara ett positivt heltal månader.'),
|
||||
salvage_value: z.number().nonnegative().optional(),
|
||||
})
|
||||
|
||||
export const CustomerTypeSchema = z.enum([
|
||||
'individual',
|
||||
'swedish_business',
|
||||
@@ -103,6 +125,7 @@ export const JournalEntrySourceTypeSchema = z.enum([
|
||||
'supplier_invoice_privately_paid',
|
||||
'supplier_credit_note',
|
||||
'currency_revaluation',
|
||||
'reminder_fee',
|
||||
])
|
||||
|
||||
export const AccountTypeSchema = z.enum([
|
||||
@@ -156,6 +179,14 @@ export const CreateInvoiceItemSchema = z.object({
|
||||
unit: z.string().min(1, 'Unit is required'),
|
||||
unit_price: z.number(),
|
||||
vat_rate: z.number().min(0).max(100).optional(),
|
||||
// ROT/RUT-avdrag fields. `deduction_amount` is intentionally omitted from
|
||||
// the client schema — the API computes it from rot-rut-rules.ts so a
|
||||
// tampered client can't expand the 1513 receivable beyond the line total.
|
||||
deduction_type: z.enum(['rot', 'rut']).nullable().optional(),
|
||||
labor_hours: z.number().nonnegative().nullable().optional(),
|
||||
work_type: z.string().max(64).nullable().optional(),
|
||||
housing_designation: z.string().max(128).nullable().optional(),
|
||||
apartment_number: z.string().max(32).nullable().optional(),
|
||||
})
|
||||
|
||||
const optionalIsoDate = isoDate.or(z.literal('')).transform(v => v || undefined).optional()
|
||||
@@ -170,6 +201,13 @@ export const CreateInvoiceSchema = z.object({
|
||||
your_reference: z.string().optional(),
|
||||
our_reference: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
// ROT/RUT claim info. The personnummer is plaintext on the wire and gets
|
||||
// encrypted server-side before it ever hits the DB (see encryptPersonnummer
|
||||
// in lib/salary/personnummer.ts). `deduction_housing_designation` is the
|
||||
// fastighetsbeteckning at invoice level — required when any ROT item is
|
||||
// present (enforced via rot-rut-rules.validateInvoice in the API).
|
||||
deduction_personnummer: z.string().max(20).optional(),
|
||||
deduction_housing_designation: z.string().max(128).optional(),
|
||||
items: z.array(CreateInvoiceItemSchema).min(1, 'At least one item is required'),
|
||||
})
|
||||
|
||||
@@ -515,6 +553,16 @@ export const UpdateSettingsSchema = z.object({
|
||||
auto_lock_period_days: z.number().int().positive().nullable().optional(),
|
||||
// Voucher series
|
||||
default_voucher_series: z.string().regex(/^[A-Z]$/, 'Verifikationsserie måste vara en bokstav A–Z').optional(),
|
||||
// Per-source-type voucher series map. Keys are journal_entries.source_type
|
||||
// values; values are single uppercase letters A–Z. Read by the engine
|
||||
// (`createDraftEntry`) when no explicit voucher_series is passed, with a
|
||||
// fallback to 'A' for unknown keys.
|
||||
default_voucher_series_per_source_type: z
|
||||
.record(
|
||||
JournalEntrySourceTypeSchema,
|
||||
z.string().regex(/^[A-Z]$/, 'Verifikationsserie måste vara en bokstav A–Z'),
|
||||
)
|
||||
.optional(),
|
||||
// Invoice PDF settings
|
||||
ore_rounding: z.boolean().optional(),
|
||||
invoice_show_ocr: z.boolean().optional(),
|
||||
@@ -526,8 +574,36 @@ export const UpdateSettingsSchema = z.object({
|
||||
invoice_company_name_position: z.enum(['header', 'footer']).optional(),
|
||||
invoice_late_fee_text: z.string().nullable().optional(),
|
||||
invoice_credit_terms_text: z.string().nullable().optional(),
|
||||
// Invoice branding — colors enforced as #RRGGBB at the DB level too
|
||||
// (see migration 20260526120200_invoice_branding.sql). The dedicated
|
||||
// /api/settings/invoicing/branding route is the primary path; these
|
||||
// entries let the generic PUT /api/settings also accept the same fields.
|
||||
invoice_primary_color: z
|
||||
.string()
|
||||
.regex(/^#[0-9A-Fa-f]{6}$/, 'Ange en giltig hex-färg (#RRGGBB)')
|
||||
.optional(),
|
||||
invoice_accent_color: z
|
||||
.string()
|
||||
.regex(/^#[0-9A-Fa-f]{6}$/, 'Ange en giltig hex-färg (#RRGGBB)')
|
||||
.optional(),
|
||||
invoice_font_family: z.enum(['Helvetica', 'Times-Roman', 'Courier']).optional(),
|
||||
invoice_header_text: z.string().max(200).nullable().optional(),
|
||||
invoice_footer_text: z.string().max(500).nullable().optional(),
|
||||
// Automation
|
||||
send_invoice_reminders: z.boolean().optional(),
|
||||
// Reminder surcharges (dröjsmålsränta + lagstadgad påminnelseavgift)
|
||||
reminder_fee_enabled: z.boolean().optional(),
|
||||
reminder_fee_amount: z
|
||||
.number()
|
||||
.min(0, 'Påminnelseavgift kan inte vara negativ')
|
||||
.max(60, 'Lagstadgad maxgräns för påminnelseavgift är 60 kr (Lag 1981:739)')
|
||||
.optional(),
|
||||
reminder_interest_rate_override: z
|
||||
.number()
|
||||
.min(0, 'Räntesats kan inte vara negativ')
|
||||
.max(0.9999, 'Ange räntesatsen som en decimal mindre än 1 (t.ex. 0.115 för 11,5%)')
|
||||
.nullable()
|
||||
.optional(),
|
||||
// AI agent flow
|
||||
ai_flow_enabled: z.boolean().optional(),
|
||||
// Salary payment file
|
||||
@@ -830,11 +906,14 @@ export const VacationRuleSchema = z.enum(['procentregeln', 'sammaloneregeln', 'n
|
||||
export const SalaryRunStatusSchema = z.enum(['draft', 'review', 'approved', 'paid', 'booked', 'corrected'])
|
||||
|
||||
export const SalaryLineItemTypeSchema = z.enum([
|
||||
'monthly_salary', 'hourly_salary', 'overtime', 'bonus', 'commission',
|
||||
'monthly_salary', 'hourly_salary',
|
||||
'overtime', 'overtime_50', 'overtime_100',
|
||||
'ob_weekday_evening', 'ob_weekend', 'ob_night', 'ob_holiday',
|
||||
'bonus', 'commission',
|
||||
'gross_deduction_pension', 'gross_deduction_other',
|
||||
'benefit_car', 'benefit_housing', 'benefit_meals', 'benefit_wellness', 'benefit_bike', 'benefit_other',
|
||||
'sick_karens', 'sick_day2_14', 'sick_day15_plus',
|
||||
'vab', 'parental_leave', 'vacation',
|
||||
'vab', 'parental_leave', 'vacation', 'semesterersattning',
|
||||
'traktamente_taxfree', 'traktamente_taxable',
|
||||
'mileage_taxfree', 'mileage_taxable',
|
||||
'net_deduction_advance', 'net_deduction_union', 'net_deduction_benefit_payment',
|
||||
@@ -1117,12 +1196,25 @@ export const AbsenceRangeQuerySchema = z.object({
|
||||
// same calendar UX, half-day mixing with absence enforced by the 24h cap
|
||||
// trigger. The calculator sums these per pay period at calculate time.
|
||||
|
||||
export const UpsertWorkedDaySchema = z.object({
|
||||
work_date: isoDate,
|
||||
hours: z.number().positive().max(24).default(8),
|
||||
notes: z.string().max(2000).optional(),
|
||||
salary_run_employee_id: uuid.optional(),
|
||||
})
|
||||
export const UpsertWorkedDaySchema = z
|
||||
.object({
|
||||
work_date: isoDate,
|
||||
hours: z.number().positive().max(24).default(8),
|
||||
notes: z.string().max(2000).optional(),
|
||||
salary_run_employee_id: uuid.optional(),
|
||||
// Optional shift window. Feeds the shift-premium engine — without explicit
|
||||
// times, the engine assumes a default 08:00–17:00 day shift. Either both
|
||||
// fields are provided or neither.
|
||||
start_time: timeString.optional(),
|
||||
end_time: timeString.optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => (data.start_time == null && data.end_time == null) || (data.start_time != null && data.end_time != null),
|
||||
{
|
||||
message: 'Ange både start- och sluttid eller låt båda vara tomma',
|
||||
path: ['start_time'],
|
||||
},
|
||||
)
|
||||
|
||||
export const WorkedHoursRangeQuerySchema = z.object({
|
||||
from: isoDate,
|
||||
@@ -1132,14 +1224,26 @@ export const WorkedHoursRangeQuerySchema = z.object({
|
||||
path: ['from'],
|
||||
})
|
||||
|
||||
export const BatchUpsertWorkedDaysSchema = z.object({
|
||||
// 100-row sanity cap: typical use is one pay period (~22 weekdays). A larger
|
||||
// value usually indicates the caller is iterating wrong.
|
||||
dates: z.array(isoDate).min(1).max(100),
|
||||
hours: z.number().positive().max(24).default(8),
|
||||
notes: z.string().max(2000).optional(),
|
||||
salary_run_employee_id: uuid.optional(),
|
||||
})
|
||||
export const BatchUpsertWorkedDaysSchema = z
|
||||
.object({
|
||||
// 100-row sanity cap: typical use is one pay period (~22 weekdays). A larger
|
||||
// value usually indicates the caller is iterating wrong.
|
||||
dates: z.array(isoDate).min(1).max(100),
|
||||
hours: z.number().positive().max(24).default(8),
|
||||
notes: z.string().max(2000).optional(),
|
||||
salary_run_employee_id: uuid.optional(),
|
||||
// Optional shift window applied to every date in the batch. Pair both or
|
||||
// neither; same fallback behaviour as the single-row endpoint.
|
||||
start_time: timeString.optional(),
|
||||
end_time: timeString.optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => (data.start_time == null && data.end_time == null) || (data.start_time != null && data.end_time != null),
|
||||
{
|
||||
message: 'Ange både start- och sluttid eller låt båda vara tomma',
|
||||
path: ['start_time'],
|
||||
},
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
// AI agent flow schemas
|
||||
@@ -1228,3 +1332,69 @@ export const ListProposalsQuerySchema = z.object({
|
||||
export const AttachDocumentSchema = z.object({
|
||||
document_id: uuid,
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// Shift-premium rules (OB-tillägg och övertid)
|
||||
// ============================================================
|
||||
|
||||
export const ShiftPremiumItemTypeSchema = z.enum([
|
||||
'overtime_50',
|
||||
'overtime_100',
|
||||
'ob_weekday_evening',
|
||||
'ob_weekend',
|
||||
'ob_night',
|
||||
'ob_holiday',
|
||||
])
|
||||
|
||||
const dayOfWeekArray = z
|
||||
.array(z.number().int().min(1).max(7))
|
||||
.min(1, 'Välj minst en veckodag')
|
||||
.max(7, 'Högst sju veckodagar tillåtna')
|
||||
|
||||
export const CreateShiftPremiumRuleSchema = z
|
||||
.object({
|
||||
name: z.string().min(1).max(120),
|
||||
applies_to_all_employees: z.boolean().default(true),
|
||||
applies_to_employee_ids: z.array(uuid).default([]),
|
||||
day_of_week: dayOfWeekArray,
|
||||
start_time: timeString,
|
||||
end_time: timeString,
|
||||
premium_percent: z.number().min(0).max(500),
|
||||
item_type: ShiftPremiumItemTypeSchema,
|
||||
priority: z.number().int().min(0).max(1000).default(0),
|
||||
is_active: z.boolean().default(true),
|
||||
})
|
||||
.refine(
|
||||
(data) => data.applies_to_all_employees || data.applies_to_employee_ids.length > 0,
|
||||
{
|
||||
message: 'Välj minst en anställd när regeln inte gäller alla',
|
||||
path: ['applies_to_employee_ids'],
|
||||
},
|
||||
)
|
||||
|
||||
export const UpdateShiftPremiumRuleSchema = z
|
||||
.object({
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
applies_to_all_employees: z.boolean().optional(),
|
||||
applies_to_employee_ids: z.array(uuid).optional(),
|
||||
day_of_week: dayOfWeekArray.optional(),
|
||||
start_time: timeString.optional(),
|
||||
end_time: timeString.optional(),
|
||||
premium_percent: z.number().min(0).max(500).optional(),
|
||||
item_type: ShiftPremiumItemTypeSchema.optional(),
|
||||
priority: z.number().int().min(0).max(1000).optional(),
|
||||
is_active: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
if (data.applies_to_all_employees === false && data.applies_to_employee_ids !== undefined) {
|
||||
return data.applies_to_employee_ids.length > 0
|
||||
}
|
||||
return true
|
||||
},
|
||||
{
|
||||
message: 'Välj minst en anställd när regeln inte gäller alla',
|
||||
path: ['applies_to_employee_ids'],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -39,4 +39,9 @@ describe('safeReturnTo', () => {
|
||||
expect(safeReturnTo('settings', '/')).toBe('/')
|
||||
expect(safeReturnTo('javascript:alert(1)', '/')).toBe('/')
|
||||
})
|
||||
|
||||
it('rejects data: URIs', () => {
|
||||
expect(safeReturnTo('data:text/html,<script>alert(1)</script>', '/')).toBe('/')
|
||||
expect(safeReturnTo('data:,', '/')).toBe('/')
|
||||
})
|
||||
})
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user