feat: reverse charge VAT (ruta 20-32) + mobile UX improvements (#50)

* fix: include reversed entries in all reports (general ledger, trial balance, VAT, SIE, NE, INK2)

Reversed entries (storno) must appear alongside their original posted entries
in reports for a complete audit trail. Previously, filtering by status='posted'
excluded them, causing discrepancies when corrections had been made.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: semi-manual invoice payment booking with editable journal lines

When marking an invoice as paid, users now see a dialog where they can:
- Choose which bank/cash account the payment goes to (1910, 1920, 1930, etc.)
- Review and edit the proposed journal entry lines before committing
- The happy path remains fast — lines are pre-filled correctly

Implementation:
- Pure proposePaymentLines() function for line computation (accrual + cash)
- PaymentBookingDialog with AccountCombobox, balance validation, date picker
- API accepts optional custom lines, falls back to auto-generation without them
- 18 tests (8 unit + 10 API) all passing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address Greptile review — validation fallback, balance check, error handling

- P1: Return 400 on invalid body instead of silently falling back to
  auto-generated lines (split JSON parse from schema validation)
- P1: Add server-side balance check for custom lines before committing
  (debit must equal credit, totalDebit > 0)
- P2: Wrap PaymentBookingDialog init() in try/catch with toast on
  failure and auto-close instead of silent empty state
- Add 2 new tests: unbalanced lines → 400, invalid schema → 400

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: OAuth callback redirect for local dev and timeout resilience

- Pass redirectUri dynamically from NEXT_PUBLIC_APP_URL so OAuth
  callbacks work on localhost (not just production)
- Encode consentId/provider in OAuth state (base64url JSON) so the
  callback doesn't depend on session storage
- Add skipAuth flag to extension API routes for OAuth callbacks
  (external provider redirects have no user session cookie)
- Wrap AbortError in descriptive timeout messages in arcim-client
- Make preview endpoint resilient to partial failures (company info
  and SIE fetch are individually non-blocking)
- Simplify login page (remove unused magic link auth mode)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: create journal entry before marking invoice as paid

Move journal entry creation before the invoice status update so that
if accounting fails, the invoice is not permanently marked paid without
a corresponding entry. Previously the error was silently swallowed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: update mark-paid tests for journal-first ordering

Reorder mock queue to match new flow (settings before update), update
failure test to expect 500 instead of silent success, add try-catch
with proper error response in route handler.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: add reverse charge VAT (ruta 20-32) and improve mobile UX across dashboard

Add full reverse charge (omvänd skattskyldighet) support to the VAT declaration:
- Map accounts 2614/2624/2634 to ruta 30/31/32 for self-assessed output VAT
- Calculate purchase bases (ruta 20-24) from supplier invoices by supplier type
- Include ruta 30-32 in ruta 49 formula and totalOutputVat summary
- Display reverse charge section in reports UI and composition chart
- Add comprehensive test coverage for all reverse charge scenarios

Improve mobile UX across the app:
- Convert nav drawer to bottom sheet with drag handle and safe area padding
- Add mobile card layout for PaymentBookingDialog journal lines
- Replace settings tab pills with dropdown selector on mobile
- Make wizard step indicators responsive (collapsed on mobile)
- Ensure all dialog footers stack buttons full-width on mobile
- Add 44px minimum touch targets throughout
- Make onboarding buttons full-width on mobile

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address Greptile review — indentation, query efficiency, tab dedup

- Fix misleading try-block indentation in mark-paid route
- Filter reversed entries at DB level (.eq('status', 'posted')) instead
  of fetching then discarding in memory
- Extract shared settingsTabs array so mobile Select and desktop
  TabsList stay in sync automatically

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-03-18 10:42:57 +01:00
committed by GitHub
co-authored by Claude Opus 4.6
parent f33806cd15
commit ceec8c02a8
18 changed files with 824 additions and 183 deletions
+14 -3
View File
@@ -6,6 +6,7 @@ import { Progress } from '@/components/ui/progress'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { ArrowLeftRight, ArrowRightLeft, FileText, ArrowLeft, Landmark, Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { createClient } from '@/lib/supabase/client'
import { BankSelector, type Bank } from '@/extensions/general/enable-banking/components/BankSelector'
import { BankConnectionStatus } from '@/extensions/general/enable-banking/components/BankConnectionStatus'
@@ -223,12 +224,16 @@ function BankFileImportWizard() {
<CardContent className="pt-6">
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="sm:hidden text-primary font-medium">
Steg {currentStepIndex + 1}/{steps.length}: {BANK_STEP_LABELS[bankStep]}
</span>
{steps.map((s, i) => (
<span
key={s}
className={
className={cn(
'hidden sm:inline',
i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground'
}
)}
>
{BANK_STEP_LABELS[s]}
</span>
@@ -517,8 +522,14 @@ function SIEImportWizard() {
<CardContent className="pt-6">
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="sm:hidden text-primary font-medium">
Steg {currentStepIndex + 1}/{sieSteps.length}: {SIE_STEP_LABELS[step]}
</span>
{sieSteps.map((s, i) => (
<span key={s} className={i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground'}>
<span key={s} className={cn(
'hidden sm:inline',
i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground'
)}>
{SIE_STEP_LABELS[s]}
</span>
))}
+31 -6
View File
@@ -949,11 +949,34 @@ function VatDeclarationView() {
<tr className="border-t-2 font-semibold">
<td className="py-2">Summa utgående</td>
<td className="py-2 text-right">
{formatAmount(data.rutor.ruta10 + data.rutor.ruta11 + data.rutor.ruta12)} kr
{formatAmount(
data.rutor.ruta10 + data.rutor.ruta11 + data.rutor.ruta12 +
data.rutor.ruta30 + data.rutor.ruta31 + data.rutor.ruta32
)} kr
</td>
</tr>
</tfoot>
</table></div>
{/* Omvänd skattskyldighet (inköp) */}
{(data.rutor.ruta20 > 0 || data.rutor.ruta21 > 0 || data.rutor.ruta22 > 0 || data.rutor.ruta23 > 0 || data.rutor.ruta24 > 0 ||
data.rutor.ruta30 > 0 || data.rutor.ruta31 > 0 || data.rutor.ruta32 > 0) && (
<>
<h4 className="font-semibold mb-3 mt-6">Omvänd skattskyldighet (inköp)</h4>
<div className="overflow-x-auto -mx-2 px-2"><table className="w-full text-sm min-w-[400px]">
<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} />
</tbody>
</table></div>
</>
)}
</div>
{/* Ingående moms */}
@@ -1056,12 +1079,14 @@ function VatRutaRow({
<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(amount)} kr`}</td>
</tr>
<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-2 text-right">{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>
</tr>
)}
</>
)
}
+39 -29
View File
@@ -10,6 +10,7 @@ import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useToast } from '@/components/ui/use-toast'
import { Separator } from '@/components/ui/separator'
import {
@@ -60,6 +61,16 @@ export default function SettingsPage() {
const [mounted, setMounted] = useState(false)
const initialTab = searchParams.get('tab') || 'company'
const [activeTab, setActiveTab] = useState(initialTab)
const settingsTabs = [
{ value: 'company', label: 'Företag', show: true },
{ value: 'banking', label: 'Bank (PSD2)', show: !settings?.is_sandbox },
{ value: 'calendar', label: 'Kalender', show: hasCalendarExtension },
{ value: 'security', label: 'Säkerhet', show: true },
{ value: 'appearance', label: 'Utseende', show: true },
{ value: 'account', label: 'Konto', show: true },
].filter(t => t.show)
useEffect(() => {
setMounted(true)
@@ -159,9 +170,11 @@ export default function SettingsPage() {
const formData = new FormData(e.currentTarget)
// Disabled inputs are excluded from FormData by the browser,
// so only include company_name/org_number when not locked
const updates: Record<string, unknown> = {
company_name: formData.get('company_name') as string,
org_number: formData.get('org_number') as string,
...(formData.has('company_name') && { company_name: formData.get('company_name') as string }),
...(formData.has('org_number') && { org_number: formData.get('org_number') as string }),
address_line1: formData.get('address_line1') as string,
postal_code: formData.get('postal_code') as string,
city: formData.get('city') as string,
@@ -290,30 +303,26 @@ export default function SettingsPage() {
</p>
</div>
<Tabs defaultValue={initialTab} className="space-y-6">
<TabsList className="flex-wrap h-auto gap-1">
<TabsTrigger value="company">
Företag
</TabsTrigger>
{!settings?.is_sandbox && (
<TabsTrigger value="banking">
Bank (PSD2)
</TabsTrigger>
)}
{hasCalendarExtension && (
<TabsTrigger value="calendar">
Kalender
</TabsTrigger>
)}
<TabsTrigger value="security">
Säkerhet
</TabsTrigger>
<TabsTrigger value="appearance">
Utseende
</TabsTrigger>
<TabsTrigger value="account">
Konto
</TabsTrigger>
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
{/* Mobile: dropdown selector */}
<div className="sm:hidden">
<Select value={activeTab} onValueChange={setActiveTab}>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{settingsTabs.map(t => (
<SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Desktop: tab pills */}
<TabsList className="hidden sm:inline-flex flex-wrap h-auto gap-1">
{settingsTabs.map(t => (
<TabsTrigger key={t.value} value={t.value}>{t.label}</TabsTrigger>
))}
</TabsList>
{/* Company settings */}
@@ -432,7 +441,7 @@ export default function SettingsPage() {
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-3 gap-4">
<div className="grid grid-cols-3 gap-4 items-end">
<div className="space-y-2">
<Label htmlFor="invoice_prefix">Fakturaprefix</Label>
<Input
@@ -719,8 +728,8 @@ export default function SettingsPage() {
</div>
</div>
<div className="flex items-center justify-between">
<Button variant="outline" asChild>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<Button variant="outline" className="w-full sm:w-auto min-h-11" asChild>
<Link href="/reports?type=sie">
<ExternalLink className="mr-2 h-4 w-4" />
Exportera bokföringsdata (SIE)
@@ -728,6 +737,7 @@ export default function SettingsPage() {
</Button>
<Button
variant="destructive"
className="w-full sm:w-auto min-h-11"
onClick={() => setShowDeleteDialog(true)}
>
Radera mitt konto
+48 -48
View File
@@ -95,57 +95,57 @@ export async function POST(
if (isRealInvoice) {
try {
if (customLines) {
// Server-side balance validation — never commit imbalanced entries
const totalDebit = customLines.reduce((s, l) => s + l.debit_amount, 0)
const totalCredit = customLines.reduce((s, l) => s + l.credit_amount, 0)
if (Math.round((totalDebit - totalCredit) * 100) !== 0 || totalDebit <= 0) {
return NextResponse.json(
{ error: 'Verifikationsraderna är inte balanserade (debet ≠ kredit)' },
{ status: 400 }
)
}
if (customLines) {
// Server-side balance validation — never commit imbalanced entries
const totalDebit = customLines.reduce((s, l) => s + l.debit_amount, 0)
const totalCredit = customLines.reduce((s, l) => s + l.credit_amount, 0)
if (Math.round((totalDebit - totalCredit) * 100) !== 0 || totalDebit <= 0) {
return NextResponse.json(
{ error: 'Verifikationsraderna är inte balanserade (debet ≠ kredit)' },
{ status: 400 }
)
}
// User-provided lines from PaymentBookingDialog
const fiscalPeriodId = await findFiscalPeriod(supabase, user.id, paymentDate)
if (!fiscalPeriodId) {
return NextResponse.json(
{ error: 'Ingen öppen räkenskapsperiod för betalningsdatumet' },
{ status: 400 }
// User-provided lines from PaymentBookingDialog
const fiscalPeriodId = await findFiscalPeriod(supabase, user.id, paymentDate)
if (!fiscalPeriodId) {
return NextResponse.json(
{ error: 'Ingen öppen räkenskapsperiod för betalningsdatumet' },
{ status: 400 }
)
}
const sourceType = accountingMethod === 'accrual' ? 'invoice_paid' : 'invoice_cash_payment'
const input: CreateJournalEntryInput = {
fiscal_period_id: fiscalPeriodId,
entry_date: paymentDate,
description: `Betalning faktura ${invoice.invoice_number}`,
source_type: sourceType,
source_id: invoice.id,
lines: customLines,
}
const journalEntry = await createJournalEntry(supabase, user.id, input)
journalEntryId = journalEntry?.id ?? null
} else if (accountingMethod === 'accrual') {
// Faktureringsmetoden: clear receivable (Debit 1930, Credit 1510)
const journalEntry = await createInvoicePaymentJournalEntry(
supabase,
user.id,
invoice as Invoice,
paymentDate,
exchangeRateDifference
)
journalEntryId = journalEntry?.id ?? null
} else {
// Kontantmetoden: combined revenue entry (Debit 1930, Credit 30xx, Credit 26xx)
const journalEntry = await createInvoiceCashEntry(
supabase,
user.id,
invoice as Invoice,
paymentDate,
entityType
)
journalEntryId = journalEntry?.id ?? null
}
const sourceType = accountingMethod === 'accrual' ? 'invoice_paid' : 'invoice_cash_payment'
const input: CreateJournalEntryInput = {
fiscal_period_id: fiscalPeriodId,
entry_date: paymentDate,
description: `Betalning faktura ${invoice.invoice_number}`,
source_type: sourceType,
source_id: invoice.id,
lines: customLines,
}
const journalEntry = await createJournalEntry(supabase, user.id, input)
journalEntryId = journalEntry?.id ?? null
} else if (accountingMethod === 'accrual') {
// Faktureringsmetoden: clear receivable (Debit 1930, Credit 1510)
const journalEntry = await createInvoicePaymentJournalEntry(
supabase,
user.id,
invoice as Invoice,
paymentDate,
exchangeRateDifference
)
journalEntryId = journalEntry?.id ?? null
} else {
// Kontantmetoden: combined revenue entry (Debit 1930, Credit 30xx, Credit 26xx)
const journalEntry = await createInvoiceCashEntry(
supabase,
user.id,
invoice as Invoice,
paymentDate,
entityType
)
journalEntryId = journalEntry?.id ?? null
}
} catch (err) {
console.error('Failed to create payment journal entry:', err)
return NextResponse.json(
+70 -54
View File
@@ -315,7 +315,7 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
</div>
</nav>
{/* Mobile menu drawer */}
{/* Mobile menu — bottom sheet */}
{isMobileMenuOpen && (
<>
{/* Backdrop */}
@@ -327,39 +327,41 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
onClick={closeMobileMenu}
aria-hidden="true"
/>
{/* Drawer */}
{/* Bottom sheet */}
<div
className={cn(
"md:hidden fixed right-0 top-0 bottom-0 w-72 bg-card border-l border-border/40 z-50 overflow-y-auto",
"md:hidden fixed inset-x-0 bottom-0 z-50 bg-card rounded-t-2xl border-t border-border/40 overflow-y-auto overscroll-contain",
isClosing
? "animate-out slide-out-to-right duration-200"
: "animate-in slide-in-from-right duration-300"
? "animate-out slide-out-to-bottom duration-200"
: "animate-in slide-in-from-bottom duration-300"
)}
style={{ maxHeight: '85dvh', paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}
role="dialog"
aria-label="Navigeringsmeny"
>
<div className="p-4 border-b border-border/40 flex items-center justify-between">
<div>
<p className="font-medium truncate">{companyName}</p>
<p className="text-xs text-muted-foreground">Meny</p>
</div>
{/* Drag handle */}
<div className="flex justify-center pt-3 pb-1 sticky top-0 bg-card rounded-t-2xl">
<div className="w-8 h-1 rounded-full bg-muted-foreground/25" />
</div>
{/* Header */}
<div className="px-4 pb-2 flex items-center justify-between">
<p className="font-medium text-sm truncate">{companyName}</p>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 -mr-1"
onClick={closeMobileMenu}
aria-label="Stäng meny"
>
<X className="h-5 w-5" />
<X className="h-4 w-4" />
</Button>
</div>
{/* Grouped navigation */}
<div className="p-2">
{/* Main section */}
<div className="mb-4">
<p className="px-3 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wider">
Huvudmeny
</p>
{/* Navigation */}
<div className="px-2">
{/* Main items */}
<div className="space-y-0.5">
{mainItems.map((item) => {
const Icon = item.icon
const active = isActive(item.href)
@@ -369,51 +371,65 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
href={item.href}
onClick={closeMobileMenu}
className={cn(
'flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors',
'flex items-center gap-3 px-3 min-h-[44px] rounded-lg transition-colors',
active
? 'bg-primary/10 text-primary font-medium'
: 'text-muted-foreground hover:bg-secondary/50 hover:text-foreground'
: 'text-foreground active:bg-muted/60'
)}
>
<Icon className="h-5 w-5" />
{item.label}
<Icon className={cn("h-[18px] w-[18px] flex-shrink-0", active ? "text-primary" : "text-muted-foreground")} />
<span className="text-sm">{item.label}</span>
</Link>
)
})}
</div>
{/* Finance section */}
<div className="mb-4">
<p className="px-3 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wider">
Finans
</p>
{/* Finans divider */}
<div className="flex items-center gap-3 my-1.5 px-3">
<span className="text-[10px] font-semibold text-muted-foreground/60 uppercase tracking-[0.08em]">Finans</span>
<div className="flex-1 h-px bg-border/30" />
</div>
{/* Finance items */}
<div className="space-y-0.5">
{finansItems.map((item) => {
const Icon = item.icon
const active = isActive(item.href)
const badge = item.href === '/transactions' && uncategorizedTransactionCount > 0
? uncategorizedTransactionCount
: null
return (
<Link
key={item.href}
href={item.href}
onClick={closeMobileMenu}
className={cn(
'flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors',
'flex items-center gap-3 px-3 min-h-[44px] rounded-lg transition-colors',
active
? 'bg-primary/10 text-primary font-medium'
: 'text-muted-foreground hover:bg-secondary/50 hover:text-foreground'
: 'text-foreground active:bg-muted/60'
)}
>
<Icon className="h-5 w-5" />
{item.label}
<Icon className={cn("h-[18px] w-[18px] flex-shrink-0", active ? "text-primary" : "text-muted-foreground")} />
<span className="text-sm flex-1">{item.label}</span>
{badge !== null && (
<span className="min-w-[20px] h-[20px] flex items-center justify-center rounded-full bg-primary/15 text-primary text-[10px] font-semibold px-1.5">
{badge > 99 ? '99+' : badge}
</span>
)}
</Link>
)
})}
</div>
{/* Other section */}
<div className="mb-4">
<p className="px-3 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wider">
Övrigt
</p>
{/* Övrigt divider */}
<div className="flex items-center gap-3 my-1.5 px-3">
<span className="text-[10px] font-semibold text-muted-foreground/60 uppercase tracking-[0.08em]">Övrigt</span>
<div className="flex-1 h-px bg-border/30" />
</div>
{/* Other items */}
<div className="space-y-0.5">
{övrigtItems.map((item) => {
const Icon = item.icon
const active = isActive(item.href)
@@ -423,33 +439,33 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
href={item.href}
onClick={closeMobileMenu}
className={cn(
'flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors',
'flex items-center gap-3 px-3 min-h-[44px] rounded-lg transition-colors',
active
? 'bg-primary/10 text-primary font-medium'
: 'text-muted-foreground hover:bg-secondary/50 hover:text-foreground'
: 'text-foreground active:bg-muted/60'
)}
>
<Icon className="h-5 w-5" />
{item.label}
<Icon className={cn("h-[18px] w-[18px] flex-shrink-0", active ? "text-primary" : "text-muted-foreground")} />
<span className="text-sm">{item.label}</span>
</Link>
)
})}
</div>
</div>
{/* Logout */}
<div className="pt-4 border-t border-border/40">
<Button
variant="ghost"
className="w-full justify-start text-muted-foreground hover:text-foreground"
onClick={() => {
closeMobileMenu()
handleLogout()
}}
>
<LogOut className="mr-3 h-5 w-5" />
{isSandbox ? 'Avsluta sandbox' : 'Logga ut'}
</Button>
</div>
{/* Logout */}
<div className="px-2 py-2 mt-1 border-t border-border/30">
<Button
variant="ghost"
className="w-full justify-start text-muted-foreground active:text-foreground text-sm h-11 px-3"
onClick={() => {
closeMobileMenu()
handleLogout()
}}
>
<LogOut className="mr-3 h-[18px] w-[18px]" />
{isSandbox ? 'Avsluta sandbox' : 'Logga ut'}
</Button>
</div>
</div>
</>
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { useToast } from '@/components/ui/use-toast'
import { cn } from '@/lib/utils'
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
import Link from 'next/link'
import {
@@ -1513,10 +1514,16 @@ export default function ArcimMigrationWorkspace(_props: WorkspaceComponentProps)
<CardContent className="pt-6">
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="sm:hidden text-primary font-medium">
Steg {currentUserStepIndex + 1}/{userSteps.length}: {STEP_LABELS[step]}
</span>
{userSteps.map((s) => (
<span
key={s}
className={userSteps.indexOf(s) <= currentUserStepIndex ? 'font-medium text-primary' : 'text-muted-foreground'}
className={cn(
'hidden sm:inline',
userSteps.indexOf(s) <= currentUserStepIndex ? 'font-medium text-primary' : 'text-muted-foreground'
)}
>
{STEP_LABELS[s]}
</span>
+63 -4
View File
@@ -225,12 +225,71 @@ export default function PaymentBookingDialog({
type="date"
value={paymentDate}
onChange={(e) => setPaymentDate(e.target.value)}
className="w-48"
className="w-full sm:w-48"
/>
</div>
{/* Journal entry lines */}
<div className="space-y-2">
{/* Mobile card layout */}
<div className="sm:hidden space-y-3">
{lines.map((line, index) => (
<div key={index} className="rounded-lg border bg-card p-3 space-y-2">
<div className="flex items-start gap-2">
<div className="flex-1">
<AccountCombobox
value={line.account_number}
accounts={accounts}
onChange={(val) => updateLine(index, 'account_number', val)}
/>
</div>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 w-8 p-0 min-h-[44px] min-w-[44px] shrink-0 -mr-1 -mt-1"
onClick={() => removeLine(index)}
disabled={lines.length <= 2}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Debet</Label>
<Input
type="number"
step="0.01"
min="0"
placeholder="0,00"
value={line.debit_amount}
onChange={(e) => updateLine(index, 'debit_amount', e.target.value)}
className="font-mono text-right"
inputMode="decimal"
/>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Kredit</Label>
<Input
type="number"
step="0.01"
min="0"
placeholder="0,00"
value={line.credit_amount}
onChange={(e) => updateLine(index, 'credit_amount', e.target.value)}
className="font-mono text-right"
inputMode="decimal"
/>
</div>
</div>
</div>
))}
<Button type="button" variant="outline" size="sm" onClick={addLine} className="w-full">
<Plus className="mr-1 h-3.5 w-3.5" /> Lägg till rad
</Button>
</div>
{/* Desktop table layout */}
<div className="hidden sm:block space-y-2">
{/* Header */}
<div className="grid grid-cols-[1fr_120px_120px_32px] gap-2 text-xs font-medium text-muted-foreground px-1">
<span>Konto</span>
@@ -316,10 +375,10 @@ export default function PaymentBookingDialog({
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting} className="w-full sm:w-auto min-h-11">
Avbryt
</Button>
<Button onClick={handleSubmit} disabled={!isBalanced || isSubmitting || !isInitialized}>
<Button onClick={handleSubmit} disabled={!isBalanced || isSubmitting || !isInitialized} className="w-full sm:w-auto min-h-11">
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Bekräfta &amp; bokför
</Button>
+2 -1
View File
@@ -104,11 +104,12 @@ export default function Step1EntityType({ initialData, onNext, isSaving }: Step1
})}
</div>
<div className="flex justify-end">
<div className="flex flex-col-reverse sm:flex-row sm:justify-end gap-3">
<Button
onClick={handleNext}
disabled={!selected || isSaving}
size="lg"
className="w-full sm:w-auto"
>
{isSaving ? (
<>
@@ -139,17 +139,18 @@ export default function Step2CompanyDetails({
</div>
</div>
<div className="flex justify-between pt-4">
<div className="flex flex-col-reverse sm:flex-row sm:justify-between gap-3 pt-4">
<Button
type="button"
variant="ghost"
onClick={onBack}
disabled={isSaving}
className="w-full sm:w-auto"
>
<ArrowLeft className="mr-2 h-4 w-4" />
Tillbaka
</Button>
<Button type="submit" disabled={isSaving}>
<Button type="submit" disabled={isSaving} className="w-full sm:w-auto">
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
@@ -754,17 +754,18 @@ export default function Step3TaxRegistration({
</div>
</div>
<div className="flex justify-between pt-4">
<div className="flex flex-col-reverse sm:flex-row sm:justify-between gap-3 pt-4">
<Button
type="button"
variant="ghost"
onClick={onBack}
disabled={isSaving}
className="w-full sm:w-auto"
>
<ArrowLeft className="mr-2 h-4 w-4" />
Tillbaka
</Button>
<Button type="submit" disabled={isSaving}>
<Button type="submit" disabled={isSaving} className="w-full sm:w-auto">
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
@@ -15,6 +15,9 @@ const COLORS = [
'hsl(var(--chart-2))',
'hsl(var(--chart-3))',
'hsl(var(--chart-4))',
'hsl(var(--chart-1) / 0.6)',
'hsl(var(--chart-2) / 0.6)',
'hsl(var(--chart-3) / 0.6)',
]
export function VatCompositionChart({ rutor }: VatCompositionChartProps) {
@@ -23,6 +26,9 @@ export function VatCompositionChart({ rutor }: VatCompositionChartProps) {
{ name: 'Utgående 25%', value: rutor.ruta10 },
{ name: 'Utgående 12%', value: rutor.ruta11 },
{ name: 'Utgående 6%', value: rutor.ruta12 },
{ name: 'Omvänd 25%', value: rutor.ruta30 },
{ name: 'Omvänd 12%', value: rutor.ruta31 },
{ name: 'Omvänd 6%', value: rutor.ruta32 },
{ name: 'Ingående moms', value: rutor.ruta48 },
]
return segments.filter((s) => s.value > 0)
+1 -1
View File
@@ -23,7 +23,7 @@ export default function InboxZeroState({ hasTransactions, onCreateTransaction }:
<p className="text-sm text-muted-foreground text-center max-w-sm mb-6">
Importera kontoutdrag från din bank eller lägg till transaktioner manuellt för att komma igång.
</p>
<div className="flex gap-2">
<div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto px-4 sm:px-0">
<Button asChild>
<Link href="/import">
<Upload className="mr-2 h-4 w-4" />
+2 -1
View File
@@ -67,11 +67,12 @@ export function ConfirmationDialog({
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isSubmitting}
className="min-h-11 w-full sm:w-auto"
>
Tillbaka
</Button>
{extraActions}
<Button onClick={onConfirm} disabled={isSubmitting}>
<Button onClick={onConfirm} disabled={isSubmitting} className="min-h-11 w-full sm:w-auto">
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
+5 -5
View File
@@ -78,6 +78,7 @@ export function DestructiveConfirmDialog({
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
className="min-h-11 w-full sm:w-auto"
>
{cancelLabel}
</Button>
@@ -85,11 +86,10 @@ export function DestructiveConfirmDialog({
variant={variant === 'destructive' ? 'destructive' : 'default'}
onClick={handleConfirm}
disabled={isLoading}
className={
variant === 'warning'
? 'bg-warning hover:bg-warning/90 text-warning-foreground'
: undefined
}
className={cn(
'min-h-11 w-full sm:w-auto',
variant === 'warning' && 'bg-warning hover:bg-warning/90 text-warning-foreground'
)}
>
{isLoading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
+1 -1
View File
@@ -72,7 +72,7 @@ const DialogFooter = ({
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end sm:space-x-2 sm:gap-0",
className
)}
{...props}
+371 -23
View File
@@ -92,20 +92,18 @@ describe('formatPeriodLabel', () => {
})
describe('getVatDeclarationSummary', () => {
const emptyRc = { ruta20: 0, ruta21: 0, ruta22: 0, ruta23: 0, ruta24: 0, ruta30: 0, ruta31: 0, ruta32: 0 }
it('calculates totals and detects payment', () => {
const declaration: VatDeclaration = {
period: { type: 'monthly', year: 2024, period: 1, start: '2024-01-01', end: '2024-01-31' },
rutor: {
ruta05: 10000, // domestic taxable sales
ruta06: 0,
ruta07: 0,
ruta10: 2500, // output VAT 25%
ruta11: 0,
ruta12: 0,
ruta39: 0,
ruta40: 0,
ruta48: 1000,
ruta49: 1500, // 2500 - 1000
ruta05: 10000, ruta06: 0, ruta07: 0,
ruta10: 2500, ruta11: 0, ruta12: 0,
ruta20: 0, ruta21: 0, ruta22: 0, ruta23: 0, ruta24: 0,
ruta30: 0, ruta31: 0, ruta32: 0,
ruta39: 0, ruta40: 0,
ruta48: 1000, ruta49: 1500,
},
invoiceCount: 5,
transactionCount: 10,
@@ -113,6 +111,7 @@ describe('getVatDeclarationSummary', () => {
invoices: { ruta05: 10000, ruta06: 0, ruta07: 0, ruta10: 2500, ruta11: 0, ruta12: 0, ruta39: 0, ruta40: 0, base25: 10000, base12: 0, base6: 0 },
transactions: { ruta48: 1000 },
receipts: { ruta48: 0 },
reverseCharge: emptyRc,
},
}
@@ -127,16 +126,12 @@ describe('getVatDeclarationSummary', () => {
const declaration: VatDeclaration = {
period: { type: 'monthly', year: 2024, period: 1, start: '2024-01-01', end: '2024-01-31' },
rutor: {
ruta05: 2000, // domestic taxable sales
ruta06: 0,
ruta07: 0,
ruta10: 500, // output VAT 25%
ruta11: 0,
ruta12: 0,
ruta39: 0,
ruta40: 0,
ruta48: 3000,
ruta49: -2500, // 500 - 3000
ruta05: 2000, ruta06: 0, ruta07: 0,
ruta10: 500, ruta11: 0, ruta12: 0,
ruta20: 0, ruta21: 0, ruta22: 0, ruta23: 0, ruta24: 0,
ruta30: 0, ruta31: 0, ruta32: 0,
ruta39: 0, ruta40: 0,
ruta48: 3000, ruta49: -2500,
},
invoiceCount: 1,
transactionCount: 20,
@@ -144,6 +139,7 @@ describe('getVatDeclarationSummary', () => {
invoices: { ruta05: 2000, ruta06: 0, ruta07: 0, ruta10: 500, ruta11: 0, ruta12: 0, ruta39: 0, ruta40: 0, base25: 2000, base12: 0, base6: 0 },
transactions: { ruta48: 3000 },
receipts: { ruta48: 0 },
reverseCharge: emptyRc,
},
}
@@ -151,6 +147,32 @@ describe('getVatDeclarationSummary', () => {
expect(summary.isRefund).toBe(true)
expect(summary.vatToPay).toBe(-2500)
})
it('includes ruta30-32 in totalOutputVat', () => {
const declaration: VatDeclaration = {
period: { type: 'monthly', year: 2024, period: 1, start: '2024-01-01', end: '2024-01-31' },
rutor: {
ruta05: 10000, ruta06: 0, ruta07: 0,
ruta10: 2500, ruta11: 0, ruta12: 0,
ruta20: 0, ruta21: 5000, ruta22: 0, ruta23: 0, ruta24: 0,
ruta30: 1250, ruta31: 0, ruta32: 0,
ruta39: 0, ruta40: 0,
ruta48: 2250, ruta49: 1500,
},
invoiceCount: 2,
transactionCount: 0,
breakdown: {
invoices: { ruta05: 10000, ruta06: 0, ruta07: 0, ruta10: 2500, ruta11: 0, ruta12: 0, ruta39: 0, ruta40: 0, base25: 10000, base12: 0, base6: 0 },
transactions: { ruta48: 0 },
receipts: { ruta48: 0 },
reverseCharge: { ruta20: 0, ruta21: 5000, ruta22: 0, ruta23: 0, ruta24: 0, ruta30: 1250, ruta31: 0, ruta32: 0 },
},
}
const summary = getVatDeclarationSummary(declaration)
// totalOutputVat = ruta10 + ruta30 = 2500 + 1250 = 3750
expect(summary.totalOutputVat).toBe(3750)
})
})
// ============================================================
@@ -158,14 +180,17 @@ describe('getVatDeclarationSummary', () => {
//
// Mock queue order per call:
// [0] fetchAllRows: journal_entry_lines (VAT-relevant accounts)
// [1] entry counts: journal_entries source_type
// [1] fetchAllRows: journal_entries for reverse charge bases
// [2] (if rc entries found) fetchAllRows: supplier_invoices
// [N] entry counts: journal_entries source_type
// ============================================================
describe('calculateVatDeclaration', () => {
it('returns all zeros when no ledger lines exist', async () => {
results = [
{ data: [], error: null },
{ data: [], error: null },
{ data: [], error: null }, // journal_entry_lines
{ data: [], error: null }, // rc journal entries
{ data: [], error: null }, // entry counts
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
@@ -174,6 +199,9 @@ describe('calculateVatDeclaration', () => {
expect(result.rutor.ruta10).toBe(0)
expect(result.rutor.ruta11).toBe(0)
expect(result.rutor.ruta12).toBe(0)
expect(result.rutor.ruta30).toBe(0)
expect(result.rutor.ruta31).toBe(0)
expect(result.rutor.ruta32).toBe(0)
expect(result.rutor.ruta48).toBe(0)
expect(result.rutor.ruta49).toBe(0)
expect(result.invoiceCount).toBe(0)
@@ -193,6 +221,7 @@ describe('calculateVatDeclaration', () => {
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [{ source_type: 'invoice_created' }, { source_type: 'invoice_created' }], error: null },
]
@@ -220,6 +249,7 @@ describe('calculateVatDeclaration', () => {
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [{ source_type: 'bank_transaction' }, { source_type: 'bank_transaction' }], error: null },
]
@@ -238,6 +268,7 @@ describe('calculateVatDeclaration', () => {
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [], error: null },
]
@@ -256,6 +287,7 @@ describe('calculateVatDeclaration', () => {
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [], error: null },
]
@@ -278,6 +310,7 @@ describe('calculateVatDeclaration', () => {
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [{ source_type: 'invoice_created' }, { source_type: 'credit_note' }], error: null },
]
@@ -299,6 +332,7 @@ describe('calculateVatDeclaration', () => {
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [], error: null },
]
@@ -319,6 +353,7 @@ describe('calculateVatDeclaration', () => {
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [], error: null },
]
@@ -330,6 +365,7 @@ describe('calculateVatDeclaration', () => {
it('accepts accountingMethod parameter for backward compatibility', async () => {
results = [
{ data: [], error: null },
{ data: [], error: null }, // rc journal entries
{ data: [], error: null },
]
@@ -356,6 +392,7 @@ describe('calculateVatDeclaration', () => {
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [], error: null },
]
@@ -372,3 +409,314 @@ describe('calculateVatDeclaration', () => {
expect(result.rutor.ruta49).toBe(2280)
})
})
// ============================================================
// Reverse charge (ruta 20-24, 30-32) tests
// ============================================================
describe('calculateVatDeclaration — reverse charge', () => {
it('maps 2614/2624/2634 credit balances to ruta30/31/32', async () => {
results = [
{
data: [
// Reverse charge output VAT accounts
{ account_number: '2614', debit_amount: 0, credit_amount: 1250 },
{ account_number: '2624', debit_amount: 0, credit_amount: 120 },
{ account_number: '2634', debit_amount: 0, credit_amount: 60 },
// Corresponding input VAT (2645)
{ account_number: '2645', debit_amount: 1430, credit_amount: 0 },
],
error: null,
},
{ data: [], error: null }, // rc journal entries (no supplier invoices for base query)
{ data: [], error: null }, // entry counts
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
expect(result.rutor.ruta30).toBe(1250)
expect(result.rutor.ruta31).toBe(120)
expect(result.rutor.ruta32).toBe(60)
expect(result.rutor.ruta48).toBe(1430)
// ruta49 = (0+0+0 + 1250+120+60) - 1430 = 0
expect(result.rutor.ruta49).toBe(0)
})
it('includes ruta30-32 in ruta49 formula', async () => {
results = [
{
data: [
// Regular output VAT
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
// Reverse charge output VAT
{ account_number: '2614', debit_amount: 0, credit_amount: 500 },
// Input VAT (regular + calculated)
{ account_number: '2641', debit_amount: 300, credit_amount: 0 },
{ account_number: '2645', debit_amount: 500, credit_amount: 0 },
],
error: null,
},
{ data: [], error: null }, // rc journal entries
{ data: [], error: null }, // entry counts
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
expect(result.rutor.ruta10).toBe(2500)
expect(result.rutor.ruta30).toBe(500)
expect(result.rutor.ruta48).toBe(800)
// ruta49 = (2500 + 0 + 0 + 500 + 0 + 0) - 800 = 2200
expect(result.rutor.ruta49).toBe(2200)
})
it('populates ruta21 for EU services reverse charge base', async () => {
results = [
{
data: [
{ account_number: '2614', debit_amount: 0, credit_amount: 1250 },
{ account_number: '2645', debit_amount: 1250, credit_amount: 0 },
],
error: null,
},
// rc journal entries — found a posted supplier invoice entry
{
data: [
{ id: 'je-1', source_id: 'si-1' },
],
error: null,
},
// supplier_invoices lookup
{
data: [
{
id: 'si-1',
supplier_id: 'sup-1',
reverse_charge: true,
is_credit_note: false,
subtotal_sek: null,
subtotal: 5000,
currency: 'SEK',
exchange_rate: null,
suppliers: { supplier_type: 'eu_business' },
},
],
error: null,
},
{ data: [], error: null }, // entry counts
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
expect(result.rutor.ruta21).toBe(5000)
expect(result.rutor.ruta20).toBe(0)
expect(result.rutor.ruta22).toBe(0)
expect(result.rutor.ruta30).toBe(1250)
expect(result.breakdown.reverseCharge.ruta21).toBe(5000)
expect(result.breakdown.reverseCharge.ruta30).toBe(1250)
})
it('populates ruta22 for non-EU services reverse charge base', async () => {
results = [
{
data: [
{ account_number: '2614', debit_amount: 0, credit_amount: 750 },
{ account_number: '2645', debit_amount: 750, credit_amount: 0 },
],
error: null,
},
{
data: [
{ id: 'je-1', source_id: 'si-1' },
],
error: null,
},
{
data: [
{
id: 'si-1',
supplier_id: 'sup-1',
reverse_charge: true,
is_credit_note: false,
subtotal_sek: 3000,
subtotal: 300,
currency: 'USD',
exchange_rate: 10,
suppliers: { supplier_type: 'non_eu_business' },
},
],
error: null,
},
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
// Uses subtotal_sek when available
expect(result.rutor.ruta22).toBe(3000)
expect(result.rutor.ruta21).toBe(0)
})
it('populates ruta24 for domestic reverse charge base', async () => {
results = [
{
data: [
{ account_number: '2614', debit_amount: 0, credit_amount: 500 },
{ account_number: '2645', debit_amount: 500, credit_amount: 0 },
],
error: null,
},
{
data: [
{ id: 'je-1', source_id: 'si-1' },
],
error: null,
},
{
data: [
{
id: 'si-1',
supplier_id: 'sup-1',
reverse_charge: true,
is_credit_note: false,
subtotal_sek: null,
subtotal: 2000,
currency: 'SEK',
exchange_rate: null,
suppliers: { supplier_type: 'swedish_business' },
},
],
error: null,
},
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
expect(result.rutor.ruta24).toBe(2000)
expect(result.rutor.ruta21).toBe(0)
expect(result.rutor.ruta22).toBe(0)
})
it('returns zero ruta20-24 when no reverse charge entries exist', async () => {
results = [
{
data: [
{ account_number: '2611', debit_amount: 0, credit_amount: 2500 },
{ account_number: '3001', debit_amount: 0, credit_amount: 10000 },
],
error: null,
},
{ data: [], error: null }, // no rc journal entries
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
expect(result.rutor.ruta20).toBe(0)
expect(result.rutor.ruta21).toBe(0)
expect(result.rutor.ruta22).toBe(0)
expect(result.rutor.ruta23).toBe(0)
expect(result.rutor.ruta24).toBe(0)
})
it('credit notes reduce reverse charge bases', async () => {
results = [
{
data: [
// Original invoice RC VAT
{ account_number: '2614', debit_amount: 0, credit_amount: 1250 },
{ account_number: '2645', debit_amount: 1250, credit_amount: 0 },
// Credit note reversal
{ account_number: '2614', debit_amount: 250, credit_amount: 0 },
{ account_number: '2645', debit_amount: 0, credit_amount: 250 },
],
error: null,
},
{
data: [
{ id: 'je-1', source_id: 'si-1' },
{ id: 'je-2', source_id: 'si-2' },
],
error: null,
},
{
data: [
{
id: 'si-1',
supplier_id: 'sup-1',
reverse_charge: true,
is_credit_note: false,
subtotal_sek: null,
subtotal: 5000,
currency: 'SEK',
exchange_rate: null,
suppliers: { supplier_type: 'eu_business' },
},
{
id: 'si-2',
supplier_id: 'sup-1',
reverse_charge: true,
is_credit_note: true,
subtotal_sek: null,
subtotal: 1000,
currency: 'SEK',
exchange_rate: null,
suppliers: { supplier_type: 'eu_business' },
},
],
error: null,
},
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
// 5000 - 1000 = 4000 net base for EU services
expect(result.rutor.ruta21).toBe(4000)
// Net RC output VAT: 1250 - 250 = 1000
expect(result.rutor.ruta30).toBe(1000)
})
it('only includes posted journal entries for reverse charge bases (reversed filtered at DB level)', async () => {
// The query uses .eq('status', 'posted'), so reversed entries never appear
results = [
{
data: [
{ account_number: '2614', debit_amount: 0, credit_amount: 1250 },
{ account_number: '2645', debit_amount: 1250, credit_amount: 0 },
],
error: null,
},
{
data: [
// Only posted entries returned by DB query
{ id: 'je-1', source_id: 'si-1' },
],
error: null,
},
{
data: [
{
id: 'si-1',
supplier_id: 'sup-1',
reverse_charge: true,
is_credit_note: false,
subtotal_sek: null,
subtotal: 5000,
currency: 'SEK',
exchange_rate: null,
suppliers: { supplier_type: 'eu_business' },
},
],
error: null,
},
{ data: [], error: null },
]
const result = await calculateVatDeclaration(supabase, 'user-1', 'monthly', 2024, 1)
// Only the posted entry's invoice (5000) should count
expect(result.rutor.ruta21).toBe(5000)
})
})
+127 -2
View File
@@ -32,6 +32,10 @@ const ACCOUNT_RUTA: Record<string, { box: keyof VatDeclarationRutor; side: 'cred
'2611': { box: 'ruta10', side: 'credit' },
'2621': { box: 'ruta11', side: 'credit' },
'2631': { box: 'ruta12', side: 'credit' },
// Reverse charge output VAT → ruta 30/31/32
'2614': { box: 'ruta30', side: 'credit' },
'2624': { box: 'ruta31', side: 'credit' },
'2634': { box: 'ruta32', side: 'credit' },
// Input VAT → ruta 48
'2641': { box: 'ruta48', side: 'debit' },
'2645': { box: 'ruta48', side: 'debit' },
@@ -162,6 +166,8 @@ export async function calculateVatDeclaration(
const rutor: VatDeclarationRutor = {
ruta05: 0, ruta06: 0, ruta07: 0,
ruta10: 0, ruta11: 0, ruta12: 0,
ruta20: 0, ruta21: 0, ruta22: 0, ruta23: 0, ruta24: 0,
ruta30: 0, ruta31: 0, ruta32: 0,
ruta39: 0, ruta40: 0,
ruta48: 0, ruta49: 0,
}
@@ -175,7 +181,11 @@ export async function calculateVatDeclaration(
rutor[mapping.box] = round(rutor[mapping.box] + balance)
}
rutor.ruta49 = round(rutor.ruta10 + rutor.ruta11 + rutor.ruta12 - rutor.ruta48)
rutor.ruta49 = round(
rutor.ruta10 + rutor.ruta11 + rutor.ruta12 +
rutor.ruta30 + rutor.ruta31 + rutor.ruta32 -
rutor.ruta48
)
// Compute per-rate base amounts from individual revenue accounts
const revenueByRate = {
@@ -188,6 +198,14 @@ export async function calculateVatDeclaration(
if (t) revenueByRate[rate] = round(t.credit - t.debit)
}
// Calculate reverse charge purchase bases (ruta 20-24) from supplier invoices
const rcBases = await calculateReverseChargeBases(supabase, userId, start, end)
rutor.ruta20 = rcBases.ruta20
rutor.ruta21 = rcBases.ruta21
rutor.ruta22 = rcBases.ruta22
rutor.ruta23 = rcBases.ruta23
rutor.ruta24 = rcBases.ruta24
// Count journal entries by source type for metadata
const { data: entryCounts } = await supabase
.from('journal_entries')
@@ -228,10 +246,114 @@ export async function calculateVatDeclaration(
},
transactions: { ruta48: rutor.ruta48 },
receipts: { ruta48: 0 },
reverseCharge: {
ruta20: rutor.ruta20,
ruta21: rutor.ruta21,
ruta22: rutor.ruta22,
ruta23: rutor.ruta23,
ruta24: rutor.ruta24,
ruta30: rutor.ruta30,
ruta31: rutor.ruta31,
ruta32: rutor.ruta32,
},
},
}
}
/**
* Calculate reverse charge purchase bases (ruta 20-24) from supplier invoices.
*
* Queries journal entries with supplier invoice source types, then looks up
* the linked supplier invoices + suppliers to determine supplier_type and
* sum item line_total (the net tax base in SEK).
*
* Classification (all reverse charge is currently services):
* eu_business → ruta21 (services from EU)
* non_eu_business → ruta22 (services from outside EU)
* swedish_business → ruta24 (domestic reverse charge, e.g. construction)
* ruta20/23 (goods) → 0 for now (Tullverket path not implemented)
*/
async function calculateReverseChargeBases(
supabase: SupabaseClient,
userId: string,
start: string,
end: string,
): Promise<{ ruta20: number; ruta21: number; ruta22: number; ruta23: number; ruta24: number }> {
const result = { ruta20: 0, ruta21: 0, ruta22: 0, ruta23: 0, ruta24: 0 }
// Step 1: Find journal entries from supplier invoices in this period
const supplierSourceTypes = [
'supplier_invoice_registered',
'supplier_invoice_cash_payment',
]
const entries = await fetchAllRows<{
id: string
source_id: string
}>(({ from, to }) =>
supabase
.from('journal_entries')
.select('id, source_id')
.eq('user_id', userId)
.in('source_type', supplierSourceTypes)
.eq('status', 'posted')
.gte('entry_date', start)
.lte('entry_date', end)
.range(from, to)
)
if (entries.length === 0) return result
const sourceIds = [...new Set(entries.map(e => e.source_id).filter(Boolean))]
if (sourceIds.length === 0) return result
// Step 2: Fetch supplier invoices that are reverse charge, with supplier type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const invoices = await fetchAllRows<Record<string, any>>(({ from, to }) =>
supabase
.from('supplier_invoices')
.select('id, supplier_id, reverse_charge, is_credit_note, subtotal_sek, subtotal, currency, exchange_rate, suppliers!inner(supplier_type)')
.in('id', sourceIds)
.eq('reverse_charge', true)
.eq('user_id', userId)
.range(from, to)
)
if (invoices.length === 0) return result
// Step 3: Sum tax bases by supplier type
for (const inv of invoices) {
// Use subtotal_sek if available, otherwise convert via exchange_rate
let baseSek: number
if (inv.subtotal_sek != null) {
baseSek = Number(inv.subtotal_sek)
} else if (inv.currency !== 'SEK' && inv.exchange_rate) {
baseSek = Math.round(Number(inv.subtotal) * Number(inv.exchange_rate) * 100) / 100
} else {
baseSek = Number(inv.subtotal)
}
// Credit notes reduce the base
if (inv.is_credit_note) baseSek = -baseSek
// !inner join: Supabase returns the related row as an object (1-to-1 FK)
const supplier = Array.isArray(inv.suppliers) ? inv.suppliers[0] : inv.suppliers
const supplierType = supplier?.supplier_type as string
switch (supplierType) {
case 'eu_business':
result.ruta21 = round(result.ruta21 + baseSek)
break
case 'non_eu_business':
result.ruta22 = round(result.ruta22 + baseSek)
break
case 'swedish_business':
result.ruta24 = round(result.ruta24 + baseSek)
break
}
}
return result
}
/**
* Get a summary of the VAT declaration for display
*/
@@ -244,7 +366,10 @@ export function getVatDeclarationSummary(declaration: VatDeclaration): {
const totalOutputVat = round(
declaration.rutor.ruta10 +
declaration.rutor.ruta11 +
declaration.rutor.ruta12
declaration.rutor.ruta12 +
declaration.rutor.ruta30 +
declaration.rutor.ruta31 +
declaration.rutor.ruta32
)
const totalInputVat = declaration.rutor.ruta48
+30
View File
@@ -1550,6 +1550,18 @@ export interface VatDeclarationRutor {
ruta11: number // Utgående moms 12%
ruta12: number // Utgående moms 6%
// Inköp vid omvänd skattskyldighet (reverse charge purchase bases)
ruta20: number // Inköp av varor från annat EU-land (unused, goods via Tullverket)
ruta21: number // Inköp av tjänster från annat EU-land
ruta22: number // Inköp av tjänster från land utanför EU
ruta23: number // Inköp av varor i Sverige (unused, construction reverse charge goods)
ruta24: number // Övriga inköp av tjänster i Sverige (domestic reverse charge)
// Utgående moms omvänd skattskyldighet (self-assessed output VAT on reverse charge)
ruta30: number // Utgående moms 25% omvänd skattskyldighet
ruta31: number // Utgående moms 12% omvänd skattskyldighet
ruta32: number // Utgående moms 6% omvänd skattskyldighet
// EU och export
ruta39: number // Försäljning av tjänster till annat EU-land (reverse charge)
ruta40: number // Export utanför EU
@@ -1596,6 +1608,16 @@ export interface VatDeclaration {
receipts: {
ruta48: number // Ingående moms from receipts
}
reverseCharge: {
ruta20: number
ruta21: number
ruta22: number
ruta23: number
ruta24: number
ruta30: number
ruta31: number
ruta32: number
}
}
}
@@ -1614,6 +1636,14 @@ export const VAT_RUTA_LABELS: Record<keyof VatDeclarationRutor, string> = {
ruta10: 'Utgående moms 25%',
ruta11: 'Utgående moms 12%',
ruta12: 'Utgående moms 6%',
ruta20: 'Inköp av varor från annat EU-land',
ruta21: 'Inköp av tjänster från annat EU-land',
ruta22: 'Inköp av tjänster från land utanför EU',
ruta23: 'Inköp av varor i Sverige',
ruta24: 'Övriga inköp av tjänster i Sverige',
ruta30: 'Utgående moms 25% (omvänd skattskyldighet)',
ruta31: 'Utgående moms 12% (omvänd skattskyldighet)',
ruta32: 'Utgående moms 6% (omvänd skattskyldighet)',
ruta39: 'Försäljning av tjänster till EU-land',
ruta40: 'Export utanför EU',
ruta48: 'Ingående moms att dra av',