Bug/vat selection warning (#583)

* refactor: update VAT handling logic for non-registered sellers and improve related comments

* chore: gate automated email flows behind 503 responses

Disables user-facing access to invoice payment reminders and salary
payslip email sending. Underlying lib code (reminder-processor,
PDF templates, notification_settings) is preserved for easy re-enable.

- Invoice reminders cron route returns 503; settings UI section removed.
- Payslip send route returns 503; original implementation kept as
  _sendPayslipsImpl for future re-enable.
- Push notifications were already extension-disabled, no change needed.

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

* chore: remove Recapt feedback widget

Strips the third-party Recapt SDK and its floating feedback bubble from
the app. The in-app contact form keeps working via the existing email
channel (/api/support/contact). Drops the Recapt entries from the CSP
and the subprocessor list in the privacy policy.

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

* feat: reject meaningless rättelser in correctEntry

Guard against zero-economic-effect corrections in the storno engine:
- Reject when proposed lines net to zero on every account (e.g. 1930
  debit 100 / 1930 credit 100), which would erase the original posting
  without representing any affärshändelse (BFL 5 kap. 5 §).
- Reject when proposed lines are an exact multiset match of the original
  entry — a rättelse must actually change something.

New MeaninglessCorrectionError wired through bookkeepingErrorResponse
(HTTP 400) and the Swedish error translator.

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

* feat: add date-range picker to resultat- and balansrapport

Adds optional from/to date filtering to the four operational financial
reports (resultatrapport, balansrapport, income-statement, balance-sheet)
so users can view a month, quarter, or custom range inside a fiscal year
without leaving the report. Defaults to YTD; "Hela året" preserves the
prior full-period behaviour (URL-identical, cache-stable).

- trial-balance engine accepts optional fromDate/toDate, rolling prior
  in-period activity into IB and clamping period activity to the window
- 12 API routes accept and validate from_date/to_date query params
- ReportDateRange chip picker persists preset per company, only renders
  on the four relevant tabs
- FiscalYearSelector now emits the period object so the range picker
  has bounds without an extra fetch
- PDF/XLSX filenames reflect the chosen range
- Resultatrapport drops the prior-year column when narrowed (full-year
  vs partial-year would mislead)
- 11 new tests (engine + parser); all existing report tests pass

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

* feat: add support for marking journal entries as "no document required"

- Introduced a new sidecar table `journal_entry_no_doc_required` to track entries that do not require separate documentation (e.g., bank fees, interest).
- Implemented API routes for creating and deleting exemptions, including validation and authorization checks.
- Added a toggle component in the UI to allow users to mark entries as exempt, with an optional reason.
- Updated relevant tests to cover the new functionality, including RLS checks and cascading deletes.
- Enhanced existing schemas and types to accommodate the new `vat_amount` field for supplier invoice items.

* fix: address PR review findings on no-doc-required + VAT changes

- pg-real cascade test wraps DELETE in gnubok.allow_delete='true' txn so the
  immutability trigger bypass fires (mirrors delete_last_voucher RPC).
- Clamp supplier-invoice item vat_amount to <= line_total * vat_rate via Zod
  refinement (with 1-öre rounding tolerance) so the manual override can't
  inflate the 2641 debit beyond the statutory ceiling.
- groupVatByRate falls back to line_total * rate when stored vat_amount is 0
  with a positive rate, so legacy/import paths leaving the column at its
  NOT NULL DEFAULT 0 don't silently understate ruta 48.
- ReportDateRange todayIso() and preset endpoints use local date components
  instead of toISOString() (UTC) — fixes the midnight-to-02:00 off-by-one
  that truncated a day from YTD / this-month / this-quarter for Swedish
  users.
- NoDocRequiredToggle restores the previous reason on failed POST/DELETE so
  the rolled-back toggle state stays consistent with the rendered reason.
- Document the company-scoped (not user-scoped) DELETE authorization policy
  on the no-document-required route.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-05-28 01:56:09 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 627109b5bd
commit a9b43ebeb7
73 changed files with 2552 additions and 714 deletions
-38
View File
@@ -1,38 +0,0 @@
'use client'
import { useEffect } from 'react'
/**
* Hides Recapt's floating feedback bubble while keeping the SDK active so
* `window.recapt('identify', ...)` and programmatic `window.recapt('feedback',
* { message })` calls continue to work. Mounted globally in the root layout.
*/
export function RecaptHideWidget() {
useEffect(() => {
let attempts = 0
const maxAttempts = 50
const hide = (): boolean => {
if (typeof window.recapt !== 'function') return false
try {
window.recapt('feedback', { widget: 'hide' })
} catch {
// best-effort
}
return true
}
if (hide()) return
const interval = setInterval(() => {
attempts++
if (hide() || attempts >= maxAttempts) {
clearInterval(interval)
}
}, 100)
return () => clearInterval(interval)
}, [])
return null
}
-37
View File
@@ -1,37 +0,0 @@
'use client'
import { useEffect } from 'react'
export function RecaptIdentify({
userId,
email,
displayName,
}: {
userId: string
email?: string
displayName?: string
}) {
useEffect(() => {
let attempts = 0
const maxAttempts = 50
const interval = setInterval(() => {
if (typeof window.recapt === 'function') {
window.recapt('identify', {
uid: userId,
email,
nickname: displayName,
})
clearInterval(interval)
return
}
attempts++
if (attempts >= maxAttempts) {
clearInterval(interval)
}
}, 100)
return () => clearInterval(interval)
}, [userId, email, displayName])
return null
}
+24 -2
View File
@@ -1,6 +1,7 @@
'use client'
import { useState, useRef, useEffect, useMemo, useCallback } from 'react'
import { Plus } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { getAccountClassName } from '@/lib/bookkeeping/account-descriptions'
import type { BASAccount } from '@/types'
@@ -9,11 +10,18 @@ interface AccountComboboxProps {
value: string
accounts: BASAccount[]
onChange: (accountNumber: string) => void
// When provided, an inline "Skapa nytt konto" affordance appears in the
// dropdown's empty state. The current search string is passed so the caller
// can prefill the create dialog.
onCreateAccount?: (prefill: string) => void
// Extra classes merged into the trigger Input — callers pass `h-8` for dense
// table rows, omit it to use the default Input height.
className?: string
}
const MAX_RESULTS = 50
export default function AccountCombobox({ value, accounts, onChange }: AccountComboboxProps) {
export default function AccountCombobox({ value, accounts, onChange, onCreateAccount, className }: AccountComboboxProps) {
const [search, setSearch] = useState(value)
const [isOpen, setIsOpen] = useState(false)
const [highlightedIndex, setHighlightedIndex] = useState(0)
@@ -179,7 +187,7 @@ export default function AccountCombobox({ value, accounts, onChange }: AccountCo
onBlur={handleBlur}
onKeyDown={handleKeyDown}
placeholder="Sök konto…"
className="font-mono"
className={`font-mono ${className ?? ''}`.trim()}
autoComplete="off"
/>
@@ -237,6 +245,20 @@ export default function AccountCombobox({ value, accounts, onChange }: AccountCo
Kontot kan behöva aktiveras i din kontoplan.
</p>
)}
{onCreateAccount && (
<button
type="button"
className="mt-2 flex w-full items-center gap-2 rounded-md border border-input bg-card px-2 py-1.5 text-left text-sm hover:bg-muted/50"
onMouseDown={(e) => {
e.preventDefault()
setIsOpen(false)
onCreateAccount(search.trim())
}}
>
<Plus className="h-3.5 w-3.5 shrink-0" />
<span className="truncate">Skapa konto &quot;{search.trim()}&quot;</span>
</button>
)}
</div>
)}
</div>
@@ -17,6 +17,10 @@ export interface ActivateAccountsDialogProps {
accountNumbers: string[]
onConfirm: () => Promise<void> | void
onCancel: () => void
// Optional: invoked when the user wants to create a custom (non-BAS) account
// for a number that isn't in the BAS catalogue. The host should close this
// dialog and open AddAccountDialog prefilled with the number.
onCreateUnknown?: (accountNumber: string) => void
}
interface BasLookupRow {
@@ -30,6 +34,7 @@ export function ActivateAccountsDialog({
accountNumbers,
onConfirm,
onCancel,
onCreateUnknown,
}: ActivateAccountsDialogProps) {
const [rows, setRows] = useState<BasLookupRow[]>([])
const [loading, setLoading] = useState(false)
@@ -104,12 +109,29 @@ export function ActivateAccountsDialog({
)}
{!loading && unknownRows.length > 0 && (
<div className="rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive">
<p className="font-medium">Okända konton:</p>
<div className="rounded-md border border-warning/40 bg-warning/5 px-3 py-2 text-xs text-warning-foreground">
<p className="font-medium">Finns inte i BAS-katalogen:</p>
<p className="mt-1 font-mono">{unknownRows.map((r) => r.account_number).join(', ')}</p>
<p className="mt-1 text-destructive/80">
Dessa nummer finns inte i BAS-katalogen och kan inte aktiveras automatiskt. Kontrollera inmatningen.
<p className="mt-1 text-warning-foreground/80">
Skapa dem som egna konton, eller kontrollera inmatningen.
</p>
{onCreateUnknown && (
<div className="mt-2 flex flex-wrap gap-1.5">
{unknownRows.map((r) => (
<Button
key={r.account_number}
type="button"
variant="outline"
size="sm"
className="h-8 text-xs"
onClick={() => onCreateUnknown(r.account_number)}
>
<Plus className="mr-1 h-3 w-3" />
Skapa {r.account_number}
</Button>
))}
</div>
)}
</div>
)}
</div>
+29 -4
View File
@@ -1,6 +1,6 @@
'use client'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
@@ -16,11 +16,14 @@ import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Loader2, AlertTriangle } from 'lucide-react'
import { isStandardBASAccount } from '@/lib/bookkeeping/bas-reference'
import type { BASAccount } from '@/types'
interface AddAccountDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onCreated: () => void
onCreated: (account: BASAccount) => void
initialAccountNumber?: string
initialAccountName?: string
}
function deriveAccountType(accountNumber: string): { type: string; balance: string } {
@@ -44,7 +47,13 @@ function deriveAccountType(accountNumber: string): { type: string; balance: stri
}
}
export function AddAccountDialog({ open, onOpenChange, onCreated }: AddAccountDialogProps) {
export function AddAccountDialog({
open,
onOpenChange,
onCreated,
initialAccountNumber,
initialAccountName,
}: AddAccountDialogProps) {
const [accountNumber, setAccountNumber] = useState('')
const [accountName, setAccountName] = useState('')
const [description, setDescription] = useState('')
@@ -54,6 +63,20 @@ export function AddAccountDialog({ open, onOpenChange, onCreated }: AddAccountDi
const [isSaving, setIsSaving] = useState(false)
const [error, setError] = useState('')
// Apply prefill values whenever the dialog opens. Resetting on close happens
// implicitly after a successful create; here we only need to seed inputs so
// the user doesn't retype what the combobox already captured.
useEffect(() => {
if (!open) return
const num = (initialAccountNumber ?? '').replace(/\D/g, '').slice(0, 4)
setAccountNumber(num)
setAccountName(initialAccountName ?? '')
setError('')
if (num.length === 4) {
setNormalBalance(deriveAccountType(num).balance as 'debit' | 'credit')
}
}, [open, initialAccountNumber, initialAccountName])
const isBASMatch = accountNumber.length === 4 && isStandardBASAccount(accountNumber)
const derived = accountNumber.length === 4 ? deriveAccountType(accountNumber) : null
@@ -91,13 +114,15 @@ export function AddAccountDialog({ open, onOpenChange, onCreated }: AddAccountDi
throw new Error(data.error || 'Kunde inte skapa kontot')
}
const { data: createdAccount } = await response.json() as { data: BASAccount }
// Reset form
setAccountNumber('')
setAccountName('')
setDescription('')
setDefaultVatCode('')
setSruCode('')
onCreated()
onCreated(createdAccount)
onOpenChange(false)
} catch (err) {
setError(err instanceof Error ? err.message : 'Något gick fel')
@@ -18,6 +18,7 @@ import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import BookingTemplatePicker from '@/components/bookkeeping/BookingTemplatePicker'
import CreatePeriodDialog from '@/components/bookkeeping/CreatePeriodDialog'
import { ActivateAccountsDialog } from '@/components/bookkeeping/ActivateAccountsDialog'
import { AddAccountDialog } from '@/components/bookkeeping/AddAccountDialog'
import { Skeleton } from '@/components/ui/skeleton'
import {
useSubmitWithAccountActivation,
@@ -107,6 +108,10 @@ export default function JournalEntryForm({
// Per-account saldo as of entryDate, keyed by account_number.
// undefined = not fetched, null = fetch in flight.
const [accountBalances, setAccountBalances] = useState<Record<string, number | null>>({})
// Inline account-creation: which line triggered the dialog, and what the
// user typed in the combobox so we can prefill the dialog.
const [creatingAccountForLine, setCreatingAccountForLine] = useState<number | null>(null)
const [createAccountPrefill, setCreateAccountPrefill] = useState<string>('')
const isForeign = entryCurrency !== 'SEK'
@@ -382,6 +387,23 @@ export default function JournalEntryForm({
if (!description) setDescription(templateDescription)
}
const handleOpenCreateAccount = (lineIndex: number, prefill: string) => {
setCreatingAccountForLine(lineIndex)
setCreateAccountPrefill(prefill)
}
// After a new account is created, refresh the chart, auto-select it on the
// line that initiated the create, and close the dialog. All other form
// state is preserved — we never navigate away from the form.
const handleAccountCreated = async (account: BASAccount) => {
await fetchAccounts()
if (creatingAccountForLine != null) {
updateLine(creatingAccountForLine, 'account_number', account.account_number)
}
setCreatingAccountForLine(null)
setCreateAccountPrefill('')
}
const handleReview = () => {
if (!selectedPeriod || !description || !isBalanced || periodMismatch) return
const hasDocuments = uploadedFiles.some((f) => f.status === 'uploaded')
@@ -730,6 +752,7 @@ export default function JournalEntryForm({
value={line.account_number}
accounts={accounts}
onChange={(num) => updateLine(index, 'account_number', num)}
onCreateAccount={(prefill) => handleOpenCreateAccount(index, prefill)}
/>
</div>
<Button
@@ -840,6 +863,8 @@ export default function JournalEntryForm({
value={line.account_number}
accounts={accounts}
onChange={(num) => updateLine(index, 'account_number', num)}
onCreateAccount={(prefill) => handleOpenCreateAccount(index, prefill)}
className="h-8"
/>
</td>
<td className="py-1.5 px-1">
@@ -997,6 +1022,25 @@ export default function JournalEntryForm({
accountNumbers={activationDialog.accountNumbers}
onConfirm={confirmActivation}
onCancel={cancelActivation}
onCreateUnknown={(num) => {
cancelActivation()
const lineIndex = lines.findIndex((l) => l.account_number === num)
setCreatingAccountForLine(lineIndex >= 0 ? lineIndex : null)
setCreateAccountPrefill(num)
}}
/>
<AddAccountDialog
open={creatingAccountForLine != null}
onOpenChange={(next) => {
if (!next) {
setCreatingAccountForLine(null)
setCreateAccountPrefill('')
}
}}
initialAccountNumber={/^\d{1,4}$/.test(createAccountPrefill) ? createAccountPrefill : undefined}
initialAccountName={/^\d{1,4}$/.test(createAccountPrefill) ? undefined : createAccountPrefill}
onCreated={handleAccountCreated}
/>
<ConfirmationDialog
+59 -8
View File
@@ -10,13 +10,14 @@ import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { ChevronDown, ChevronRight, Paperclip, AlertTriangle, Loader2, BookOpen, X, Copy, Lock } from 'lucide-react'
import { ChevronDown, ChevronRight, Paperclip, AlertTriangle, CircleSlash, 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'
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
import NoDocRequiredToggle from '@/components/bookkeeping/NoDocRequiredToggle'
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
import JournalEntryStatusBadge from '@/components/bookkeeping/JournalEntryStatusBadge'
import AttachmentPreviewSheet from '@/components/bookkeeping/AttachmentPreviewSheet'
@@ -50,6 +51,7 @@ export default function JournalEntryList({ periodId }: Props) {
const [count, setCount] = useState(0)
const [page, setPage] = useState(0)
const [attachmentCounts, setAttachmentCounts] = useState<Record<string, number>>({})
const [noDocRequired, setNoDocRequired] = useState<Map<string, string | null>>(new Map())
const [showMissingOnly, setShowMissingOnly] = useState(false)
const [correctionEntry, setCorrectionEntry] = useState<JournalEntry | null>(null)
const [previewEntryId, setPreviewEntryId] = useState<string | null>(null)
@@ -115,6 +117,25 @@ export default function JournalEntryList({ periodId }: Props) {
}
}, [])
const fetchNoDocRequired = useCallback(async () => {
try {
const res = await fetch('/api/bookkeeping/no-doc-required')
if (!res.ok) return
const { data } = await res.json()
const map = new Map<string, string | null>()
for (const row of (data || []) as { journal_entry_id: string; reason: string | null }[]) {
map.set(row.journal_entry_id, row.reason)
}
setNoDocRequired(map)
} catch {
// Non-critical — silently ignore
}
}, [])
useEffect(() => {
fetchNoDocRequired()
}, [fetchNoDocRequired])
async function fetchEntries() {
setLoading(true)
const params = new URLSearchParams({
@@ -209,7 +230,8 @@ export default function JournalEntryList({ periodId }: Props) {
(e) =>
NEEDS_ATTACHMENT.has(e.source_type) &&
!attachmentCounts[e.id] &&
e.status === 'posted'
e.status === 'posted' &&
!noDocRequired.has(e.id)
)
: entries
@@ -396,9 +418,15 @@ export default function JournalEntryList({ periodId }: Props) {
</Button>
) : (
NEEDS_ATTACHMENT.has(entry.source_type) && entry.status === 'posted' && (
<span className="mr-1" title={t('missing_attachment_tooltip')}>
<AlertTriangle className="h-3.5 w-3.5 text-warning-foreground" />
</span>
noDocRequired.has(entry.id) ? (
<span className="mr-1" title={t('no_doc_required_indicator_tooltip')}>
<CircleSlash className="h-3.5 w-3.5 text-muted-foreground" />
</span>
) : (
<span className="mr-1" title={t('missing_attachment_tooltip')}>
<AlertTriangle className="h-3.5 w-3.5 text-warning-foreground" />
</span>
)
)
)}
</div>
@@ -466,9 +494,15 @@ export default function JournalEntryList({ periodId }: Props) {
</Button>
) : (
NEEDS_ATTACHMENT.has(entry.source_type) && entry.status === 'posted' && (
<span title={t('missing_attachment_tooltip')}>
<AlertTriangle className="h-3.5 w-3.5 text-warning-foreground" />
</span>
noDocRequired.has(entry.id) ? (
<span title={t('no_doc_required_indicator_tooltip')}>
<CircleSlash className="h-3.5 w-3.5 text-muted-foreground" />
</span>
) : (
<span title={t('missing_attachment_tooltip')}>
<AlertTriangle className="h-3.5 w-3.5 text-warning-foreground" />
</span>
)
)
)}
</span>
@@ -545,6 +579,23 @@ export default function JournalEntryList({ periodId }: Props) {
onCountChange={(c) => handleAttachmentCountChange(entry.id, c)}
/>
{entry.status === 'posted' && NEEDS_ATTACHMENT.has(entry.source_type) && (
<NoDocRequiredToggle
entryId={entry.id}
initialExempt={noDocRequired.has(entry.id)}
initialReason={noDocRequired.get(entry.id) ?? null}
canWrite={canWrite}
onChange={(exempted, reason) => {
setNoDocRequired((prev) => {
const next = new Map(prev)
if (exempted) next.set(entry.id, reason ?? null)
else next.delete(entry.id)
return next
})
}}
/>
)}
<div className="mt-4 pt-3 border-t flex flex-col sm:flex-row gap-2">
{entry.status === 'draft' && (
<Button
@@ -0,0 +1,164 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Loader2, CircleSlash, Lock } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
interface Props {
entryId: string
initialExempt: boolean
initialReason: string | null
canWrite: boolean
onChange: (exempted: boolean, reason: string | null) => void
}
/**
* Lets the bookkeeper mark a posted verifikation as not needing a separate
* underlag (bankavgift, ränta, intern överföring etc.). Toggling persists via
* /api/bookkeeping/journal-entries/[id]/no-document-required.
*
* The flag lives in journal_entry_no_doc_required (sidecar) so the underlying
* verifikation stays immutable per BFL.
*/
export default function NoDocRequiredToggle({
entryId,
initialExempt,
initialReason,
canWrite,
onChange,
}: Props) {
const t = useTranslations('journal_list')
const { toast } = useToast()
const [exempt, setExempt] = useState(initialExempt)
const [reason, setReason] = useState(initialReason ?? '')
const [saving, setSaving] = useState(false)
const [editingReason, setEditingReason] = useState(false)
const persistExempt = async (
nextExempt: boolean,
nextReason: string | null,
previousReason: string,
) => {
setSaving(true)
try {
const res = nextExempt
? await fetch(`/api/bookkeeping/journal-entries/${entryId}/no-document-required`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason: nextReason ?? null }),
})
: await fetch(`/api/bookkeeping/journal-entries/${entryId}/no-document-required`, {
method: 'DELETE',
})
if (!res.ok) {
const body = await res.json().catch(() => ({}))
toast({
title: t('no_doc_required_save_failed'),
description: body.error,
variant: 'destructive',
})
// Roll back UI state on failure — both the toggle AND the reason so
// the rendered state matches the DB row we failed to mutate.
setExempt(!nextExempt)
setReason(previousReason)
return
}
onChange(nextExempt, nextExempt ? nextReason : null)
} catch {
toast({ title: t('no_doc_required_save_failed'), variant: 'destructive' })
setExempt(!nextExempt)
setReason(previousReason)
} finally {
setSaving(false)
}
}
const handleToggle = (checked: boolean) => {
const previousReason = reason
setExempt(checked)
if (!checked) {
setReason('')
setEditingReason(false)
}
persistExempt(checked, checked ? (reason.trim() || null) : null, previousReason)
}
const handleSaveReason = () => {
setEditingReason(false)
persistExempt(true, reason.trim() || null, reason)
}
return (
<div className="mt-4 pt-3 border-t">
<div className="flex items-center gap-2">
<Switch
id={`no-doc-${entryId}`}
checked={exempt}
onCheckedChange={handleToggle}
disabled={!canWrite || saving}
/>
<Label
htmlFor={`no-doc-${entryId}`}
className="text-sm cursor-pointer flex items-center gap-1.5"
>
{!canWrite && <Lock className="h-3 w-3" />}
{saving && <Loader2 className="h-3 w-3 animate-spin" />}
{!saving && exempt && <CircleSlash className="h-3.5 w-3.5 text-muted-foreground" />}
{t('no_doc_required_toggle')}
</Label>
</div>
{exempt && (
<div className="mt-2 ml-10 space-y-1">
{editingReason ? (
<div className="flex items-center gap-2">
<Input
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder={t('no_doc_required_reason_placeholder')}
list={`no-doc-suggestions-${entryId}`}
maxLength={200}
className="h-8 text-xs flex-1 max-w-sm"
disabled={saving}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
handleSaveReason()
}
}}
/>
<datalist id={`no-doc-suggestions-${entryId}`}>
<option value={t('no_doc_required_suggestion_bank_fee')} />
<option value={t('no_doc_required_suggestion_interest')} />
<option value={t('no_doc_required_suggestion_internal_transfer')} />
<option value={t('no_doc_required_suggestion_tax_payment')} />
<option value={t('no_doc_required_suggestion_salary')} />
</datalist>
<Button size="sm" variant="outline" className="h-8" onClick={handleSaveReason} disabled={saving}>
{t('no_doc_required_save_reason')}
</Button>
</div>
) : (
<button
type="button"
onClick={() => canWrite && setEditingReason(true)}
disabled={!canWrite}
className="text-xs text-muted-foreground hover:text-foreground transition-colors text-left"
>
{reason
? `${t('no_doc_required_reason_label')}: ${reason}`
: t('no_doc_required_reason_add')}
</button>
)}
</div>
)}
</div>
)
}
+12 -6
View File
@@ -23,7 +23,12 @@ interface Props {
* Current selection. `null` means "all years" — no filter applied.
*/
value: string | null
onChange: (periodId: string | null) => void
/**
* Called with the selected period id (or null for "all years"). The second
* arg is the matching FiscalPeriod object so callers can read period_start
* / period_end without an extra fetch.
*/
onChange: (periodId: string | null, period?: FiscalPeriod | null) => void
/**
* If true, include an "Alla räkenskapsår" option that clears the filter.
* Pages that require a specific period (e.g. Reports) should pass false.
@@ -107,12 +112,12 @@ export function FiscalYearSelector({
if (value === null && typeof window !== 'undefined') {
const stored = window.localStorage.getItem(STORAGE_KEY_PREFIX + company.id)
if (stored === ALL_YEARS_VALUE) {
if (includeAllOption) onChange(null)
else if (fetched.length > 0) onChange(fetched[0].id)
if (includeAllOption) onChange(null, null)
else if (fetched.length > 0) onChange(fetched[0].id, fetched[0])
} else if (stored && fetched.some((p) => p.id === stored)) {
onChange(stored)
onChange(stored, fetched.find((p) => p.id === stored) ?? null)
} else if (!includeAllOption && fetched.length > 0) {
onChange(fetched[0].id)
onChange(fetched[0].id, fetched[0])
}
}
@@ -134,7 +139,8 @@ export function FiscalYearSelector({
nextPeriodId ?? ALL_YEARS_VALUE,
)
}
onChange(nextPeriodId)
const nextPeriod = nextPeriodId ? periods.find((p) => p.id === nextPeriodId) ?? null : null
onChange(nextPeriodId, nextPeriod)
}
const selectValue = value ?? (includeAllOption ? ALL_YEARS_VALUE : '')
+237
View File
@@ -0,0 +1,237 @@
'use client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { useCompany } from '@/contexts/CompanyContext'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
export type DateRangeValue = {
/** Inclusive lower bound. ISO YYYY-MM-DD. `undefined` = period start. */
fromDate?: string
/** Inclusive upper bound. ISO YYYY-MM-DD. `undefined` = period end. */
toDate?: string
}
type Preset = 'full_year' | 'ytd' | 'this_month' | 'last_month' | 'this_quarter' | 'custom'
interface Props {
/** Selected fiscal period — bounds the range. */
periodStart: string
periodEnd: string
value: DateRangeValue
onChange: (next: DateRangeValue) => void
className?: string
}
const STORAGE_KEY_PREFIX = 'gnubok:report-range-preset:'
const PRESETS: Preset[] = ['full_year', 'ytd', 'this_month', 'last_month', 'this_quarter', 'custom']
function todayIso(): string {
// Local calendar date — using toISOString() returns UTC, which falls a day
// behind for Swedish users between midnight and 01:00/02:00 local time and
// would silently truncate "today" from YTD / this-month / this-quarter.
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}-${m}-${day}`
}
function clampToPeriod(date: string, periodStart: string, periodEnd: string): string {
if (date < periodStart) return periodStart
if (date > periodEnd) return periodEnd
return date
}
/**
* Resolve a preset to a concrete range inside the fiscal period.
*
* Endpoints are always clamped to the period — e.g. "this month" outside the
* period collapses to a zero-width range at whichever boundary you're nearest.
* `full_year` returns `{}` so the API call omits the params entirely and the
* report falls back to its full-period default (preserves cache parity with
* the pre-feature behaviour).
*/
function resolvePreset(
preset: Preset,
periodStart: string,
periodEnd: string,
reference: string,
): DateRangeValue {
if (preset === 'full_year') return {}
if (preset === 'custom') return {}
if (preset === 'ytd') {
const to = clampToPeriod(reference, periodStart, periodEnd)
return { fromDate: periodStart, toDate: to }
}
const ref = new Date(reference)
// Same UTC pitfall as todayIso(): Date.toISOString() returns UTC, so a
// local Date constructed via `new Date(y, m, d)` round-trips to the wrong
// calendar day in any timezone west of UTC. Use the local components.
const toLocalIso = (d: Date) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
if (preset === 'this_month') {
const y = ref.getFullYear()
const m = ref.getMonth()
const start = `${y}-${String(m + 1).padStart(2, '0')}-01`
const end = toLocalIso(new Date(y, m + 1, 0))
return {
fromDate: clampToPeriod(start, periodStart, periodEnd),
toDate: clampToPeriod(end, periodStart, periodEnd),
}
}
if (preset === 'last_month') {
const y = ref.getFullYear()
const m = ref.getMonth() - 1
const start = toLocalIso(new Date(y, m, 1))
const end = toLocalIso(new Date(y, m + 1, 0))
return {
fromDate: clampToPeriod(start, periodStart, periodEnd),
toDate: clampToPeriod(end, periodStart, periodEnd),
}
}
if (preset === 'this_quarter') {
const y = ref.getFullYear()
const q = Math.floor(ref.getMonth() / 3)
const start = `${y}-${String(q * 3 + 1).padStart(2, '0')}-01`
const end = toLocalIso(new Date(y, q * 3 + 3, 0))
return {
fromDate: clampToPeriod(start, periodStart, periodEnd),
toDate: clampToPeriod(end, periodStart, periodEnd),
}
}
return {}
}
/**
* Date-range picker for the resultat-/balansrapport family.
*
* Default = "Hittills i år" (YTD) which matches Fortnox/Visma. A "Hela året"
* preset clears the range entirely so the API falls back to full-period
* behaviour. Custom range is clamped to the fiscal period — cross-year
* ranges are out of scope.
*/
export function ReportDateRange({
periodStart,
periodEnd,
value,
onChange,
className,
}: Props) {
const t = useTranslations('reports')
const { company } = useCompany()
const [preset, setPreset] = useState<Preset>('ytd')
// Restore last-used preset per company, then resolve it against the
// current fiscal period. The period selector lives upstream — when it
// changes, we re-resolve so the dates always sit inside the visible year.
useEffect(() => {
if (!company?.id || typeof window === 'undefined') return
const stored = window.localStorage.getItem(STORAGE_KEY_PREFIX + company.id) as Preset | null
const initial: Preset = stored && PRESETS.includes(stored) ? stored : 'ytd'
setPreset(initial)
if (initial !== 'custom') {
onChange(resolvePreset(initial, periodStart, periodEnd, todayIso()))
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [company?.id, periodStart, periodEnd])
const handlePreset = useCallback(
(next: Preset) => {
setPreset(next)
if (company?.id && typeof window !== 'undefined') {
window.localStorage.setItem(STORAGE_KEY_PREFIX + company.id, next)
}
if (next === 'custom') {
// Seed the custom inputs with whatever is currently active so the
// user can nudge them rather than start from scratch.
if (!value.fromDate && !value.toDate) {
onChange({ fromDate: periodStart, toDate: clampToPeriod(todayIso(), periodStart, periodEnd) })
}
return
}
onChange(resolvePreset(next, periodStart, periodEnd, todayIso()))
},
[company?.id, onChange, periodEnd, periodStart, value.fromDate, value.toDate],
)
const handleFromChange = (raw: string) => {
const next = raw ? clampToPeriod(raw, periodStart, periodEnd) : undefined
onChange({ fromDate: next, toDate: value.toDate })
}
const handleToChange = (raw: string) => {
const next = raw ? clampToPeriod(raw, periodStart, periodEnd) : undefined
onChange({ fromDate: value.fromDate, toDate: next })
}
const presetLabels: Record<Preset, string> = useMemo(
() => ({
full_year: t('date_range_preset_full_year'),
ytd: t('date_range_preset_ytd'),
this_month: t('date_range_preset_this_month'),
last_month: t('date_range_preset_last_month'),
this_quarter: t('date_range_preset_this_quarter'),
custom: t('date_range_preset_custom'),
}),
[t],
)
return (
<div className={cn('flex flex-col gap-2', className)}>
<Label className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
{t('date_range_label')}
</Label>
<div className="flex flex-wrap items-center gap-1.5">
{PRESETS.map((p) => {
const active = preset === p
return (
<button
key={p}
type="button"
onClick={() => handlePreset(p)}
className={cn(
'px-3 py-1.5 text-xs rounded-md border transition-colors duration-150',
active
? 'bg-secondary border-border text-foreground'
: 'bg-transparent border-border text-muted-foreground hover:bg-secondary/60 hover:text-foreground',
)}
>
{presetLabels[p]}
</button>
)
})}
</div>
{preset === 'custom' && (
<div className="flex flex-wrap items-end gap-3 mt-1">
<div className="flex flex-col gap-1">
<Label className="text-xs text-muted-foreground">{t('date_range_from')}</Label>
<Input
type="date"
min={periodStart}
max={periodEnd}
value={value.fromDate ?? ''}
onChange={(e) => handleFromChange(e.target.value)}
className="w-[160px] tabular-nums"
/>
</div>
<div className="flex flex-col gap-1">
<Label className="text-xs text-muted-foreground">{t('date_range_to')}</Label>
<Input
type="date"
min={periodStart}
max={periodEnd}
value={value.toDate ?? ''}
onChange={(e) => handleToChange(e.target.value)}
className="w-[160px] tabular-nums"
/>
</div>
</div>
)}
</div>
)
}
-2
View File
@@ -35,7 +35,6 @@ import { resolveIcon } from '@/lib/extensions/icon-resolver'
import { SupportLink } from '@/components/ui/support-link'
import CompanySwitcher from '@/components/dashboard/CompanySwitcher'
import { useCompany } from '@/contexts/CompanyContext'
import { clearRecaptIdentity } from '@/lib/recapt'
import type { EntityType } from '@/types'
void _ENABLED_EXTENSION_IDS
@@ -153,7 +152,6 @@ export default function DashboardNav({ companyName: _companyName, entityType, un
}
const handleLogout = async () => {
clearRecaptIdentity()
await supabase.auth.signOut()
router.push(isSandbox ? '/sandbox' : '/login')
}
-140
View File
@@ -2,7 +2,6 @@
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'
@@ -19,15 +18,6 @@ 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 {
@@ -71,62 +61,6 @@ 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">
@@ -270,80 +204,6 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
</div>
</div>
<div className="pt-6 space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Automatisering
</h2>
<div className="flex items-center justify-between">
<div>
<Label>Skicka automatiska påminnelser</Label>
<p className="text-xs text-muted-foreground">
Skicka påminnelser till kunder för försenade fakturor enligt din inställning för påminnelseintervall.
</p>
</div>
<Switch
checked={settings.send_invoice_reminders ?? true}
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>
)
}
@@ -12,6 +12,9 @@ interface ReviewLineItem {
amount: number
account_number: string
vat_rate: number
// When set, the user typed the deductible VAT explicitly (manual override).
// Used for bilförmån 50%, representation tak, FX-rundningar etc.
vat_amount?: number
}
interface SupplierInvoiceReviewContentProps {
@@ -80,20 +83,28 @@ function buildJournalPreview(
})
}
// Per-line effective VAT — manual override wins over computed amount × rate.
// The engine reads stored vat_amount; the preview must reflect the same.
const itemVat = (item: ReviewLineItem) =>
item.vat_amount != null
? Math.round(item.vat_amount * 100) / 100
: Math.round(item.amount * item.vat_rate * 100) / 100
if (reverseCharge) {
// Reverse charge: fiktiv moms per VAT rate (matches engine groupVatByRate logic)
// Reverse charge: fiktiv moms is always statutory base × rate, regardless
// of any manual override on the items themselves (matches engine).
const isDomesticRC = supplierType === 'swedish_business'
const inputAccount = isDomesticRC ? '2647' : '2645'
const vatByRate = new Map<number, number>()
const baseByRate = new Map<number, number>()
for (const item of items) {
if (item.vat_rate > 0) {
const current = vatByRate.get(item.vat_rate) || 0
vatByRate.set(item.vat_rate, current + toSek(item.amount))
const current = baseByRate.get(item.vat_rate) || 0
baseByRate.set(item.vat_rate, current + toSek(item.amount))
}
}
for (const [rate, netAmount] of vatByRate) {
for (const [rate, netAmount] of baseByRate) {
const fiktivVat = Math.round(netAmount * rate * 100) / 100
const outputAccount = getOutputVatAccount(rate)
lines.push({
@@ -119,12 +130,23 @@ function buildJournalPreview(
})
} else {
if (totalVat > 0) {
lines.push({
account_number: '2641',
description: 'Ingående moms',
debit: toSek(totalVat),
credit: 0,
})
// Sum per-rate using effective (manual-or-computed) VAT, so the preview
// matches what groupVatByRate will write to 2641 server-side.
const vatByRate = new Map<number, number>()
for (const item of items) {
const v = itemVat(item)
if (v > 0) {
vatByRate.set(item.vat_rate, (vatByRate.get(item.vat_rate) || 0) + v)
}
}
for (const [, vat] of vatByRate) {
lines.push({
account_number: '2641',
description: 'Ingående moms',
debit: toSek(vat),
credit: 0,
})
}
}
// Credit: 2440 at total incl. VAT
lines.push({
@@ -226,7 +248,9 @@ export function SupplierInvoiceReviewContent({
</thead>
<tbody>
{items.map((item, index) => {
const vatAmount = Math.round(item.amount * item.vat_rate * 100) / 100
const vatAmount = item.vat_amount != null
? Math.round(item.vat_amount * 100) / 100
: Math.round(item.amount * item.vat_rate * 100) / 100
return (
<tr key={index} className="border-b last:border-0">
<td className="py-2">
@@ -244,7 +268,9 @@ export function SupplierInvoiceReviewContent({
</div>
<div className="sm:hidden space-y-2">
{items.map((item, index) => {
const vatAmount = Math.round(item.amount * item.vat_rate * 100) / 100
const vatAmount = item.vat_amount != null
? Math.round(item.vat_amount * 100) / 100
: Math.round(item.amount * item.vat_rate * 100) / 100
return (
<div key={index} className="border rounded-lg p-3 text-sm space-y-1.5">
<div className="flex items-center justify-between">