* fix(bookkeeping): harden correction account changes

* feat(tax): enhance tax deadline generation with new settings and filing methods

- Added new company settings: tax_turnover_over_40m, vat_has_eu_trade, vat_filing_method, periodisk_sammanstallning_enabled, and periodisk_sammanstallning_filing_method.
- Updated deadline generation logic to accommodate new settings affecting VAT and employer declaration deadlines.
- Implemented tests for new functionality, ensuring that completed obligations are preserved and not replaced by new pending rows.
- Introduced a cron job to backfill missing tax deadlines for companies with settings but no upcoming deadlines.
- Updated API routes for generating tax deadlines and handling cron jobs.
- Modified database schema to include new columns for tax filing profiles and constraints for filing methods.

* fix(invoices): record credit note reconciliation guard

* fix(tax): correct automatic deadline settings

* fix(tax): key AGI deadline to VAT taxable base and add storforetag payment deadline

The 26th filing day for the skattedeklaration (AGI and VAT together) hinges
on one statutory measure, a VAT taxable base above SEK 40 million (SFL 26
kap.), not a separate employer turnover. Drop employer_turnover_over_40m and
derive the AGI schedule from vat_registered plus vat_taxable_base_over_40m,
so a non-VAT-reporting employer is never shown the 26th when its binding
date is the 12th.

Also:
- add a skatteinbetalning deadline row (12th, 17 January) for storforetag,
  whose deducted tax and employer contributions are due before the 26th
  filing date
- normalize legally incoherent over-40m flag combinations to the earlier
  small-company schedule in a follow-up migration
- replace hardcoded 27 December dates with the banking-day adjustment
- extend the 40m help text to cover the SKV-decided early filing election
  and the payment-still-on-the-12th rule
- document the regeneration race repaired by the daily backfill cron

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(migrations): add AGI and VAT filing logic with employer column removal

* feat(settings): implement VAT registration logic and update related flags; enhance deadline handling

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-17 00:52:57 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 1443235cec
commit a5e37d3510
32 changed files with 1978 additions and 259 deletions
+5 -3
View File
@@ -40,9 +40,10 @@ interface AccountComboboxProps {
// internal one. Lets a parent imperatively focus the field (e.g. auto-advance
// to the next konteringsrad's account on Enter: see JournalEntryForm.focusAccount).
inputRef?: React.RefCallback<HTMLInputElement>
disabled?: boolean
}
export default function AccountCombobox({ value, accounts, onChange, onCommit, onCreateAccount, catalog, notActivatedLabel = 'Aktiveras vid bokföring', className, inputRef }: AccountComboboxProps) {
export default function AccountCombobox({ value, accounts, onChange, onCommit, onCreateAccount, catalog, notActivatedLabel = 'Aktiveras vid bokföring', className, inputRef, disabled = false }: AccountComboboxProps) {
const [search, setSearch] = useState(value)
const [isOpen, setIsOpen] = useState(false)
const [highlightedIndex, setHighlightedIndex] = useState(0)
@@ -247,11 +248,12 @@ export default function AccountCombobox({ value, accounts, onChange, onCommit, o
placeholder="Sök konto…"
className={`font-mono ${className ?? ''}`.trim()}
autoComplete="off"
disabled={disabled}
/>
{/* Dropdown */}
{isOpen && flatList.length > 0 && (
{isOpen && !disabled && flatList.length > 0 && (
<div
ref={listRef}
className="absolute z-50 top-full left-0 mt-1 min-w-[24rem] w-[max(100%,34rem)] max-h-[300px] overflow-y-auto rounded-md border border-input bg-card shadow-md"
@@ -296,7 +298,7 @@ export default function AccountCombobox({ value, accounts, onChange, onCommit, o
)}
{/* Empty state */}
{isOpen && search.trim() && flatList.length === 0 && (
{isOpen && !disabled && search.trim() && flatList.length === 0 && (
<div className="absolute z-50 top-full left-0 mt-1 min-w-[24rem] w-[max(100%,34rem)] rounded-md border border-input bg-card shadow-md p-3">
<p className="text-sm text-muted-foreground">
Hittade inget konto som matchar.
@@ -1,7 +1,8 @@
'use client'
import { useState, useEffect } from 'react'
import { useState, useEffect, useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
@@ -21,9 +22,14 @@ import {
import { nextLineDescriptionForAccountChange } from '@/components/bookkeeping/correction-line-description'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { Plus, Trash2 } from 'lucide-react'
import { Loader2, Plus, Trash2 } from 'lucide-react'
import { formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import {
changeCorrectionLineAccount,
getSelectableCorrectionCatalog,
} from '@/lib/bookkeeping/correction-line-account'
import { loadBasCatalog, type CatalogAccount } from '@/lib/bookkeeping/bas-catalog-client'
import type { JournalEntry, JournalEntryLine, BASAccount } from '@/types'
interface CorrectionLine {
@@ -43,11 +49,27 @@ interface Props {
export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCorrected }: Props) {
const { toast } = useToast()
const router = useRouter()
const t = useTranslations('journal_detail')
const [accounts, setAccounts] = useState<BASAccount[]>([])
const [catalog, setCatalog] = useState<CatalogAccount[]>([])
const [accountsStatus, setAccountsStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const [lines, setLines] = useState<CorrectionLine[]>([])
const [description, setDescription] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const activeAccounts = useMemo(
() => accounts.filter((account) => account.is_active),
[accounts],
)
const selectableCatalog = useMemo(
() => getSelectableCorrectionCatalog(accounts, catalog),
[accounts, catalog],
)
const accountNameSources = useMemo(
() => [...accounts, ...catalog],
[accounts, catalog],
)
const originalLines = ((entry.lines || []) as JournalEntryLine[])
.slice()
.sort((a, b) => a.sort_order - b.sort_order)
@@ -66,17 +88,26 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
// Pre-fill the verifikationstext with the same auto text the server
// would generate; only a user edit is sent along (see handleSubmit).
setDescription(autoCorrectionDescription(entry.description))
fetchAccounts()
void fetchAccounts()
}
}, [open, entry.id]) // eslint-disable-line react-hooks/exhaustive-deps
async function fetchAccounts() {
setAccountsStatus('loading')
try {
const res = await fetch('/api/bookkeeping/accounts')
const [res, basCatalog] = await Promise.all([
fetch('/api/bookkeeping/accounts?active=false'),
loadBasCatalog(),
])
if (!res.ok) throw new Error(`accounts ${res.status}`)
const { data } = await res.json()
setAccounts(data || [])
setCatalog(basCatalog)
setAccountsStatus('ready')
} catch {
// Accounts will be empty: user can still type account numbers manually
setAccounts([])
setCatalog([])
setAccountsStatus('error')
}
}
@@ -102,6 +133,14 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
)
}
const updateLineAccount = (index: number, accountNumber: string) => {
setLines((prev) => prev.map((line, lineIndex) => (
lineIndex === index
? changeCorrectionLineAccount(line, accountNumber, accountNameSources)
: line
)))
}
const addLine = () => {
setLines((prev) => [...prev, { account_number: '', debit_amount: '', credit_amount: '', line_description: '' }])
}
@@ -236,14 +275,30 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
</p>
</div>
{accountsStatus !== 'ready' && (
<div className="flex items-center justify-between gap-3 rounded-lg border bg-muted/50 p-3 text-sm text-muted-foreground">
<span className="flex items-center gap-2">
{accountsStatus === 'loading' && <Loader2 className="h-4 w-4 animate-spin" />}
{accountsStatus === 'loading' ? t('accounts_loading') : t('accounts_load_failed')}
</span>
{accountsStatus === 'error' && (
<Button variant="outline" size="sm" onClick={() => void fetchAccounts()}>
{t('accounts_retry')}
</Button>
)}
</div>
)}
<div className="space-y-2">
{lines.map((line, index) => (
<div key={index} className="space-y-2 sm:space-y-0 sm:grid sm:grid-cols-[1fr_1fr_120px_120px_auto] sm:gap-2 sm:items-start border-b sm:border-0 pb-3 sm:pb-0 last:border-0">
<div className="grid grid-cols-[1fr_auto] sm:contents gap-2">
<AccountCombobox
value={line.account_number}
accounts={accounts}
onChange={(v) => updateLine(index, 'account_number', v)}
accounts={activeAccounts}
catalog={selectableCatalog}
onChange={(v) => updateLineAccount(index, v)}
disabled={accountsStatus !== 'ready'}
/>
<Button
variant="ghost"
+140 -21
View File
@@ -17,6 +17,12 @@ export function TaxSettingsForm({ settings }: TaxSettingsFormProps) {
const [vatRegistered, setVatRegistered] = useState(settings.vat_registered ?? false)
const [fSkatt, setFSkatt] = useState(settings.f_skatt ?? true)
const [paysSalaries, setPaysSalaries] = useState(settings.pays_salaries ?? false)
const [momsPeriod, setMomsPeriod] = useState(settings.moms_period || '')
const [vatTaxableBaseOver40m, setVatTaxableBaseOver40m] = useState(
settings.vat_taxable_base_over_40m ?? false,
)
const [hasEuTrade, setHasEuTrade] = useState(settings.vat_has_eu_trade ?? false)
const [psEnabled, setPsEnabled] = useState(settings.periodisk_sammanstallning_enabled ?? false)
const isEnskildFirma = settings.entity_type === 'enskild_firma'
@@ -69,7 +75,11 @@ export function TaxSettingsForm({ settings }: TaxSettingsFormProps) {
<Checkbox
id="vat_registered"
checked={vatRegistered}
onCheckedChange={(v) => setVatRegistered(v === true)}
onCheckedChange={(value) => {
const checked = value === true
setVatRegistered(checked)
if (checked && vatTaxableBaseOver40m) setMomsPeriod('monthly')
}}
/>
<input type="hidden" name="vat_registered" value={vatRegistered ? 'true' : 'false'} />
<div className="space-y-1">
@@ -99,15 +109,20 @@ export function TaxSettingsForm({ settings }: TaxSettingsFormProps) {
<Label>{t('moms_period_label')}</Label>
<Select
name="moms_period"
defaultValue={settings.moms_period || undefined}
value={momsPeriod || undefined}
onValueChange={setMomsPeriod}
>
<SelectTrigger>
<SelectValue placeholder={t('select_period_placeholder')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="monthly">{t('period_monthly')}</SelectItem>
<SelectItem value="quarterly">{t('period_quarterly')}</SelectItem>
<SelectItem value="yearly">{t('period_yearly')}</SelectItem>
<SelectItem value="quarterly" disabled={vatTaxableBaseOver40m}>
{t('period_quarterly')}
</SelectItem>
<SelectItem value="yearly" disabled={vatTaxableBaseOver40m}>
{t('period_yearly')}
</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
@@ -115,26 +130,130 @@ export function TaxSettingsForm({ settings }: TaxSettingsFormProps) {
</p>
</div>
<div className="max-w-xs space-y-2">
<Label>{t('periodisk_label')}</Label>
<Select
name="periodisk_sammanstallning_period"
defaultValue={settings.periodisk_sammanstallning_period || 'monthly'}
>
<SelectTrigger>
<SelectValue placeholder={t('select_period_placeholder')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="monthly">{t('period_monthly')}</SelectItem>
<SelectItem value="quarterly">{t('period_quarterly')}</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
{t('periodisk_help')}
</p>
<div className="flex items-start space-x-3">
<Checkbox
id="vat_taxable_base_over_40m"
checked={vatTaxableBaseOver40m}
onCheckedChange={(value) => {
const checked = value === true
setVatTaxableBaseOver40m(checked)
if (checked) setMomsPeriod('monthly')
}}
/>
<input
type="hidden"
name="vat_taxable_base_over_40m"
value={vatTaxableBaseOver40m ? 'true' : 'false'}
/>
<div className="space-y-1">
<Label htmlFor="vat_taxable_base_over_40m" className="cursor-pointer">
{t('vat_taxable_base_over_40m_label')}
</Label>
<p className="text-xs text-muted-foreground">
{t('vat_taxable_base_over_40m_help')}
</p>
</div>
</div>
<div className="flex items-start space-x-3">
<Checkbox
id="vat_has_eu_trade"
checked={hasEuTrade}
onCheckedChange={(value) => {
const checked = value === true
setHasEuTrade(checked)
if (!checked) setPsEnabled(false)
}}
/>
<input type="hidden" name="vat_has_eu_trade" value={hasEuTrade ? 'true' : 'false'} />
<div className="space-y-1">
<Label htmlFor="vat_has_eu_trade" className="cursor-pointer">
{t('vat_has_eu_trade_label')}
</Label>
<p className="text-xs text-muted-foreground">
{t('vat_has_eu_trade_help')}
</p>
</div>
</div>
{momsPeriod === 'yearly' && !hasEuTrade && !isEnskildFirma && (
<div className="max-w-xs space-y-2">
<Label>{t('vat_filing_method_label')}</Label>
<Select
name="vat_filing_method"
defaultValue={settings.vat_filing_method || 'electronic'}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="electronic">{t('filing_method_electronic')}</SelectItem>
<SelectItem value="paper">{t('filing_method_paper')}</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">{t('vat_filing_method_help')}</p>
</div>
)}
{hasEuTrade && (
<div className="space-y-4">
<div className="flex items-start space-x-3">
<Checkbox
id="periodisk_sammanstallning_enabled"
checked={psEnabled}
onCheckedChange={(value) => setPsEnabled(value === true)}
/>
<input
type="hidden"
name="periodisk_sammanstallning_enabled"
value={psEnabled ? 'true' : 'false'}
/>
<div className="space-y-1">
<Label htmlFor="periodisk_sammanstallning_enabled" className="cursor-pointer">
{t('periodisk_enabled_label')}
</Label>
<p className="text-xs text-muted-foreground">{t('periodisk_enabled_help')}</p>
</div>
</div>
{psEnabled && (
<div className="grid max-w-2xl grid-cols-1 gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label>{t('periodisk_label')}</Label>
<Select
name="periodisk_sammanstallning_period"
defaultValue={settings.periodisk_sammanstallning_period || 'monthly'}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="monthly">{t('period_monthly')}</SelectItem>
<SelectItem value="quarterly">{t('period_quarterly')}</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">{t('periodisk_help')}</p>
</div>
<div className="space-y-2">
<Label>{t('periodisk_filing_method_label')}</Label>
<Select
name="periodisk_sammanstallning_filing_method"
defaultValue={settings.periodisk_sammanstallning_filing_method || 'electronic'}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="electronic">{t('filing_method_electronic')}</SelectItem>
<SelectItem value="paper">{t('filing_method_paper')}</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
{t('periodisk_filing_method_help')}
</p>
</div>
</div>
)}
</div>
)}
</div>
)}
</div>
</section>
@@ -47,19 +47,39 @@ export function TaxSettingsContent() {
function handleSave(formData: FormData) {
const vatRegistered = formData.get('vat_registered') === 'true'
const paysSalaries = formData.get('pays_salaries') === 'true'
const updates: Record<string, unknown> = {
f_skatt: formData.get('f_skatt') === 'true',
vat_registered: vatRegistered,
vat_number: vatRegistered ? ((formData.get('vat_number') as string) || null) : null,
moms_period: vatRegistered ? ((formData.get('moms_period') as string) || null) : null,
vat_taxable_base_over_40m:
vatRegistered && formData.get('vat_taxable_base_over_40m') === 'true',
vat_has_eu_trade: vatRegistered && formData.get('vat_has_eu_trade') === 'true',
// The filing-method and PS selects are conditionally rendered: when a
// control is unmounted its FormData key is absent, and defaulting would
// silently overwrite the saved preference. Fall back to the stored
// value first, then the default.
vat_filing_method:
(formData.get('vat_filing_method') as string) ||
settings?.vat_filing_method ||
'electronic',
periodisk_sammanstallning_enabled:
vatRegistered && formData.get('periodisk_sammanstallning_enabled') === 'true',
periodisk_sammanstallning_period:
(formData.get('periodisk_sammanstallning_period') as string) || 'monthly',
(formData.get('periodisk_sammanstallning_period') as string) ||
settings?.periodisk_sammanstallning_period ||
'monthly',
periodisk_sammanstallning_filing_method:
(formData.get('periodisk_sammanstallning_filing_method') as string) ||
settings?.periodisk_sammanstallning_filing_method ||
'electronic',
tax_contact_name: (formData.get('tax_contact_name') as string) || null,
tax_contact_phone: (formData.get('tax_contact_phone') as string) || null,
tax_contact_email: (formData.get('tax_contact_email') as string) || null,
fiscal_year_start_month: parseInt(formData.get('fiscal_year_start_month') as string) || 1,
pays_salaries: formData.get('pays_salaries') === 'true',
pays_salaries: paysSalaries,
preliminary_tax_monthly: parseFloat(formData.get('preliminary_tax_monthly') as string) || null,
}
return {