Fix/supp ag fb (#1023)

* fix: prevent credit notes from entering payment flow

* fix: persist and display customer personal numbers

* feat: configure automatic invoice reminder days

* fix: issue credit notes through send flow

* chore: add repository agent guidance

* feat(mcp): route tools across user companies

* fix(articles): delete unused register entries

* feat(invoices): improve issued invoice actions

* feat(supplier-invoices): retain uploaded source documents

* docs: record implementation decisions

* feat: enhance customer personal number handling and validation

- Updated CustomerForm to allow personal numbers in the format of "********-1234" for individual customers.
- Added validation to ensure personal numbers are only accepted for individual customers in CreateCustomerSchema.
- Implemented masking and encryption for personal numbers to enhance data protection.
- Introduced new utility functions for masking and encrypting personal numbers.
- Added database migration to enforce unique constraints on credit note relationships and prevent duplicate entries.
- Enhanced error handling and logging for credit note issuance and invoice processing.
- Updated tests to cover new credit note creation guards and personal number handling.

* test: enhance list companies test with supabase query mocks
This commit is contained in:
Mattsson
2026-07-15 15:53:15 +02:00
committed by GitHub
parent a558c75678
commit 072aedeaf9
116 changed files with 5708 additions and 669 deletions
+21 -15
View File
@@ -1,6 +1,7 @@
'use client'
import { useState, useCallback, useRef } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Upload, FileText, ImageIcon, X, Loader2 } from 'lucide-react'
@@ -45,10 +46,13 @@ function isImageType(type: string): boolean {
* returned by /api/documents. Falls back to message_en or null if the
* shape is unexpected.
*/
function extractErrorMessage(err: unknown): string | null {
function extractErrorMessage(err: unknown, locale: string): string | null {
if (typeof err === 'string') return err
if (err && typeof err === 'object') {
const e = err as { message?: unknown; message_en?: unknown; code?: unknown }
if (locale === 'en' && typeof e.message_en === 'string' && e.message_en.length > 0) {
return e.message_en
}
if (typeof e.message === 'string' && e.message.length > 0) return e.message
if (typeof e.message_en === 'string' && e.message_en.length > 0) return e.message_en
if (typeof e.code === 'string') return e.code
@@ -64,6 +68,8 @@ export default function DocumentUploadZone({
disabled = false,
compact = false,
}: DocumentUploadZoneProps) {
const t = useTranslations('document_upload')
const locale = useLocale()
const [isDragging, setIsDragging] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
@@ -91,13 +97,13 @@ export default function DocumentUploadZone({
fileName: file.fileName,
})
const reason = res.status === 401 || res.status === 403
? 'Din session har gått ut. Ladda om sidan och logga in igen.'
: `Servern svarade ${res.status}.`
? t('session_expired')
: t('server_status', { status: res.status })
return { ...file, status: 'error', error: reason }
}
if (!res.ok || result.error) {
const errMessage = extractErrorMessage(result.error) || `Uppladdning misslyckades (${res.status})`
const errMessage = extractErrorMessage(result.error, locale) || t('failed_status', { status: res.status })
console.warn('[DocumentUploadZone] Upload error', {
status: res.status,
error: result.error,
@@ -112,9 +118,9 @@ export default function DocumentUploadZone({
error: err,
fileName: file.fileName,
})
return { ...file, status: 'error', error: 'Uppladdning misslyckades: nätverksfel' }
return { ...file, status: 'error', error: t('network_error') }
}
}, [journalEntryId])
}, [journalEntryId, locale, t])
const handleFiles = useCallback(async (newFiles: File[]) => {
const remaining = maxFiles - files.length
@@ -127,7 +133,7 @@ export default function DocumentUploadZone({
validFiles.push({
file,
status: 'error',
error: 'Filtypen stöds inte',
error: t('unsupported_type'),
fileName: file.name,
fileSize: file.size,
uploadKey: `upload-${++uploadCounter}`,
@@ -138,7 +144,7 @@ export default function DocumentUploadZone({
validFiles.push({
file,
status: 'error',
error: 'Filen är för stor (max 10 MB)',
error: t('too_large'),
fileName: file.name,
fileSize: file.size,
uploadKey: `upload-${++uploadCounter}`,
@@ -165,7 +171,7 @@ export default function DocumentUploadZone({
)
onFilesChange([...currentFiles])
}
}, [files, maxFiles, onFilesChange, uploadFile])
}, [files, maxFiles, onFilesChange, t, uploadFile])
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault()
@@ -230,11 +236,11 @@ export default function DocumentUploadZone({
<Upload className={compact ? 'h-4 w-4 text-muted-foreground' : 'mx-auto h-8 w-8 text-muted-foreground'} />
<div>
<p className={compact ? 'text-sm text-muted-foreground' : 'text-sm font-medium'}>
{compact ? 'Dra och släpp eller klicka' : 'Dra och släpp filer här'}
{compact ? t('compact_prompt') : t('prompt')}
</p>
{!compact && (
<p className="text-xs text-muted-foreground">
PDF, bilder (max 10 MB)
{t('format_hint')}
</p>
)}
</div>
@@ -264,13 +270,13 @@ export default function DocumentUploadZone({
)}
{file.status === 'uploaded' && (
<Badge variant="success" className="text-xs px-1.5 py-0">
Uppladdad
{t('uploaded')}
</Badge>
)}
{file.status === 'error' && (
<>
<Badge variant="destructive" className="text-xs px-1.5 py-0">
Fel
{t('error')}
</Badge>
{file.error && (
<span className="text-xs text-destructive">{file.error}</span>
@@ -281,7 +287,7 @@ export default function DocumentUploadZone({
<Button
variant="ghost"
size="sm"
aria-label="Ta bort fil"
aria-label={t('remove_file')}
className="h-6 w-6 p-0 shrink-0"
onClick={(e) => {
e.stopPropagation()
@@ -297,7 +303,7 @@ export default function DocumentUploadZone({
)}
{isUploading && (
<p className="text-xs text-muted-foreground">Laddar upp...</p>
<p className="text-xs text-muted-foreground">{t('uploading')}</p>
)}
</div>
)
@@ -3,6 +3,7 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
Dialog,
DialogContent,
@@ -38,6 +39,7 @@ interface DocumentRecord {
storage_path: string
created_at: string
download_url?: string
referenced?: boolean
}
interface JournalEntryAttachmentsProps {
@@ -90,12 +92,45 @@ export default function JournalEntryAttachments({
const fetchDocuments = useCallback(async () => {
try {
const res = await fetch(
`/api/documents?journal_entry_id=${journalEntryId}&current_only=true`
)
const { data } = await res.json()
setDocuments(data || [])
onCountChangeRef.current?.(data?.length || 0)
const [documentsRes, referencesRes] = await Promise.all([
fetch(`/api/documents?journal_entry_id=${journalEntryId}&current_only=true`),
fetch(`/api/bookkeeping/journal-entries/${journalEntryId}/references`),
])
const { data: directDocuments } = await documentsRes.json()
const direct = (directDocuments || []) as DocumentRecord[]
const directIds = new Set(direct.map((document) => document.id))
let referenced: DocumentRecord[] = []
if (referencesRes.ok) {
const { data: referenceData } = await referencesRes.json()
const documentIds = Array.from(new Set<string>(
(referenceData?.references || [])
.map((reference: { document_id?: string }) => reference.document_id)
.filter((documentId: string | undefined): documentId is string => (
Boolean(documentId) && !directIds.has(documentId as string)
)),
))
const referencedDocuments = await Promise.all(
documentIds.map(async (documentId) => {
try {
const response = await fetch(`/api/documents/${documentId}`)
if (!response.ok) return null
const { data } = await response.json()
return data ? { ...data, referenced: true } as DocumentRecord : null
} catch {
return null
}
}),
)
referenced = referencedDocuments.filter(
(document): document is DocumentRecord => document !== null,
)
}
const allDocuments = [...direct, ...referenced]
setDocuments(allDocuments)
onCountChangeRef.current?.(allDocuments.length)
} catch {
// Non-critical: silently ignore
} finally {
@@ -286,36 +321,45 @@ export default function JournalEntryAttachments({
)}
<span className="truncate flex-1">{doc.file_name}</span>
{doc.referenced && (
<Badge variant="secondary" className="shrink-0">
{t('via_supplier_invoice')}
</Badge>
)}
<span className="text-xs text-muted-foreground shrink-0">
{formatFileSize(doc.file_size_bytes)}
</span>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleOpenReplacePicker(doc.id)}
disabled={isReplacing}
title={t('replace')}
aria-label={t('replace')}
>
{isReplacing ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<RefreshCw className="h-3 w-3" />
)}
</Button>
{!doc.referenced && (
<>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleOpenReplacePicker(doc.id)}
disabled={isReplacing}
title={t('replace')}
aria-label={t('replace')}
>
{isReplacing ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<RefreshCw className="h-3 w-3" />
)}
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleRequestRemove(doc)}
title={t('remove')}
aria-label={t('remove')}
>
<Trash2 className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleRequestRemove(doc)}
title={t('remove')}
aria-label={t('remove')}
>
<Trash2 className="h-3 w-3" />
</Button>
</>
)}
<Button
variant="ghost"
+8 -4
View File
@@ -50,7 +50,7 @@ export default function CustomerForm({
vat_number: z.string().optional(),
personal_number: z
.string()
.regex(/^(\d{6}|\d{8})[-+]?\d{4}$/, t('personal_number_invalid'))
.regex(/^(?:(\d{6}|\d{8})[-+]?\d{4}|\*{8}-\d{4})$/, t('personal_number_invalid'))
.optional()
.or(z.literal('')),
language: z.enum(['sv', 'en']).optional(),
@@ -133,11 +133,15 @@ export default function CustomerForm({
}
const onFormSubmit = (data: FormData) => {
onSubmit({
const payload: CreateCustomerInput = {
...data,
email: data.email || undefined,
personal_number: data.personal_number || undefined,
})
personal_number: data.personal_number || null,
}
if (data.personal_number?.startsWith('*') && data.personal_number === initialData?.personal_number) {
delete payload.personal_number
}
onSubmit(payload)
}
return (
+47 -7
View File
@@ -25,7 +25,7 @@ import { formatCurrency } from '@/lib/utils'
import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
import { getAmountToPay } from '@/lib/invoices/rounding'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye, Landmark, Lock, AlertTriangle, MoreVertical, CalendarClock, Tags } from 'lucide-react'
import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye, Landmark, Lock, AlertTriangle, MoreVertical, CalendarClock, Tags, Copy } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -60,6 +60,7 @@ import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import LineDimensionFields from '@/components/dimensions/LineDimensionFields'
import { DEFAULT_DEFERRED_REVENUE_ACCOUNT } from '@/lib/bookkeeping/accruals/account-suggestions'
import { countCalendarMonths } from '@/lib/bookkeeping/accruals/compute'
import type { InvoiceCopyInitial } from '@/lib/invoices/copy-invoice'
import type { Customer, Currency, CreateInvoiceInput, CreateCustomerInput, InvoiceDocumentType, Article, Invoice, InvoiceItem, BASAccount } from '@/types'
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
@@ -77,6 +78,7 @@ export type InvoiceForEdit = Invoice & { items: InvoiceItem[] }
export type InvoiceEditorProps = (
| { mode?: 'create' }
| { mode: 'edit'; initial: InvoiceForEdit }
| { mode: 'copy'; initial: InvoiceCopyInitial }
) & { bare?: boolean }
// Subset of Article fields the line picker needs to pre-fill a row.
@@ -106,7 +108,10 @@ function compactDims(dims: Record<string, string>): string {
export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'create' }) {
// Edit mode pre-fills the form from an existing draft and saves via PATCH.
const isEditMode = props.mode === 'edit'
const isCopyMode = props.mode === 'copy'
const initial = props.mode === 'edit' ? props.initial : null
const copyInitial = props.mode === 'copy' ? props.initial : null
const initialOreRounding = initial?.ore_rounding ?? copyInitial?.ore_rounding
const bare = props.bare === true
const router = useRouter()
const { toast } = useToast()
@@ -271,7 +276,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
// Öresavrundning is display-only. In edit mode the draft's stored flag wins;
// otherwise it defaults to the company-wide setting (loaded below).
const [oreRounding, setOreRounding] = useState<boolean>(
typeof initial?.ore_rounding === 'boolean' ? initial.ore_rounding : true,
typeof initialOreRounding === 'boolean' ? initialOreRounding : true,
)
const [vatRegistered, setVatRegistered] = useState<boolean>(true)
const [numberPreview, setNumberPreview] = useState<string | null>(null)
@@ -291,7 +296,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
// open/close bookkeeping as accountOverrideRows).
const [dimensionsEnabled, setDimensionsEnabled] = useState(false)
const [defaultDims, setDefaultDims] = useState<Record<string, string>>(
initial?.default_dimensions ?? {},
initial?.default_dimensions ?? copyInitial?.default_dimensions ?? {},
)
const [dimensionOverrideRows, setDimensionOverrideRows] = useState<Set<number>>(new Set())
// True only when the user had zero invoices when this page loaded. The
@@ -362,6 +367,26 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
dimensions: hasDimensionValues(item.dimensions) ? item.dimensions ?? null : null,
})),
}
: copyInitial
? {
customer_id: copyInitial.customer_id,
invoice_date: '',
due_date: '',
delivery_date: '',
currency: copyInitial.currency,
document_type: 'invoice' as InvoiceDocumentType,
your_reference: '',
our_reference: copyInitial.our_reference,
notes: copyInitial.notes,
payment_link_url: '',
payment_link_auto: true,
external_invoice_number: '',
self_billing_agreement_ref: '',
received_date: '',
deduction_personnummer: '',
deduction_housing_designation: '',
items: copyInitial.items,
}
: {
customer_id: '',
invoice_date: '',
@@ -542,11 +567,13 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
.single()
if (data?.invoice_default_notes) {
setDefaultNotes(data.invoice_default_notes)
setValue('notes', data.invoice_default_notes)
if (!isEditMode && !isCopyMode) {
setValue('notes', data.invoice_default_notes)
}
}
// Pre-fill "Vår referens" from the company default: only when creating a
// fresh invoice, so an edited draft's own reference is never overwritten.
if (!isEditMode && data?.default_our_reference) {
if (!isEditMode && !isCopyMode && data?.default_our_reference) {
setValue('our_reference', data.default_our_reference)
}
setHasBankDetails(
@@ -557,7 +584,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
}
// An explicit per-invoice flag (edit mode) wins; only fall back to the
// company-wide setting when creating or when the draft never set one.
if (typeof data?.ore_rounding === 'boolean' && (!isEditMode || initial?.ore_rounding == null)) {
if (typeof data?.ore_rounding === 'boolean' && initialOreRounding == null) {
setOreRounding(data.ore_rounding)
}
setLogoUrl(data?.logo_url ?? null)
@@ -1266,6 +1293,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
const titleText = isEditMode
? t('title_edit')
: isCopyMode
? t('title_copy')
: isSelfBilled
? ts('title')
: watchDocumentType === 'proforma'
@@ -1275,6 +1304,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
: t('title_invoice')
const subtitleText = isEditMode
? t('subtitle_edit')
: isCopyMode
? t('subtitle_copy')
: isSelfBilled
? ts('subtitle')
: watchDocumentType === 'proforma'
@@ -1314,7 +1345,16 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
/>
</div>
{!isEditMode && (
{isCopyMode && copyInitial && (
<div className="flex items-start gap-3 rounded-lg border border-border/60 bg-muted/30 px-4 py-3 text-sm">
<Copy className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<p className="text-muted-foreground">
{t('copy_notice', { number: copyInitial.source_invoice_number })}
</p>
</div>
)}
{!isEditMode && !isCopyMode && (
<Tabs value={mode} onValueChange={(v) => setMode(v as 'invoice' | 'self_billed')}>
<TabsList>
<TabsTrigger value="invoice">{t('mode_invoice')}</TabsTrigger>
+100 -4
View File
@@ -1,12 +1,23 @@
'use client'
import dynamic from 'next/dynamic'
import { useEffect, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
import { Button } from '@/components/ui/button'
import { createClient } from '@/lib/supabase/client'
import { useCompany } from '@/contexts/CompanyContext'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
buildInvoiceCopyInitial,
canCopyInvoice,
type InvoiceCopyInitial,
type InvoiceCopySource,
} from '@/lib/invoices/copy-invoice'
// Deferred: the editor (and its framer-motion dependency) is a large chunk
// that would otherwise ship with the invoice LIST bundle — it's only needed
// that would otherwise ship with the invoice LIST bundle: it is only needed
// once this dialog actually opens.
const InvoiceEditor = dynamic(() => import('@/components/invoices/InvoiceEditor'), {
ssr: false,
@@ -22,6 +33,7 @@ const InvoiceEditor = dynamic(() => import('@/components/invoices/InvoiceEditor'
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
copyFromId?: string | null
}
/**
@@ -35,8 +47,70 @@ interface Props {
* shows the invoice-number preview: a static DialogTitle would duplicate or
* contradict it.
*/
export default function NewInvoiceDialog({ open, onOpenChange }: Props) {
export default function NewInvoiceDialog({ open, onOpenChange, copyFromId = null }: Props) {
const t = useTranslations('invoice_editor')
const { company } = useCompany()
const supabase = useMemo(() => createClient(), [])
const [copyLoad, setCopyLoad] = useState<{
sourceId: string | null
initial: InvoiceCopyInitial | null
failed: boolean
}>({ sourceId: null, initial: null, failed: false })
useEffect(() => {
if (!open || !copyFromId) return
if (!company?.id) return
let cancelled = false
const loadCopySource = async () => {
const { data, error } = await supabase
.from('invoices')
.select('*')
.eq('id', copyFromId)
.eq('company_id', company.id)
.single()
let items: Record<string, unknown>[] = []
if (!error && data) {
try {
items = await fetchAllRows<Record<string, unknown>>(({ from, to }) =>
supabase
.from('invoice_items')
.select('*')
.eq('invoice_id', copyFromId)
.eq('company_id', company.id)
.order('id', { ascending: true })
.range(from, to),
)
} catch {
if (!cancelled) setCopyLoad({ sourceId: copyFromId, initial: null, failed: true })
return
}
}
if (cancelled) return
const source = data ? { ...data, items } : null
if (error || !source || !canCopyInvoice(source)) {
setCopyLoad({ sourceId: copyFromId, initial: null, failed: true })
return
}
setCopyLoad({
sourceId: copyFromId,
initial: buildInvoiceCopyInitial(source as InvoiceCopySource),
failed: false,
})
}
void loadCopySource()
return () => {
cancelled = true
}
}, [company?.id, copyFromId, open, supabase])
const copyInitial = copyLoad.sourceId === copyFromId ? copyLoad.initial : null
const copyLoadFailed = copyLoad.sourceId === copyFromId && copyLoad.failed
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -50,8 +124,30 @@ export default function NewInvoiceDialog({ open, onOpenChange }: Props) {
onPointerDownOutside={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
>
<DialogTitle className="sr-only">{t('title_invoice')}</DialogTitle>
<InvoiceEditor mode="create" bare />
<DialogTitle className="sr-only">
{copyFromId ? t('title_copy') : t('title_invoice')}
</DialogTitle>
{copyFromId ? (
copyLoadFailed ? (
<div className="space-y-4 p-6 text-center">
<p className="font-medium">{t('copy_load_failed_title')}</p>
<p className="text-sm text-muted-foreground">{t('copy_load_failed_description')}</p>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('close')}
</Button>
</div>
) : copyInitial ? (
<InvoiceEditor key={copyFromId} mode="copy" initial={copyInitial} bare />
) : (
<div className="space-y-4 p-6">
<Skeleton className="h-8 w-1/3" />
<Skeleton className="h-32 w-full" />
<Skeleton className="h-32 w-full" />
</div>
)
) : (
<InvoiceEditor mode="create" bare />
)}
</DialogContent>
</Dialog>
)
+118 -39
View File
@@ -1,7 +1,7 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { useTranslations } from 'next-intl'
import { useLocale, useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
@@ -16,8 +16,10 @@ import { JournalEntryReviewContent } from '@/components/bookkeeping/JournalEntry
import { proposeSendLines } from '@/lib/bookkeeping/propose-send-lines'
import { formatCurrency } from '@/lib/utils'
import { createClient } from '@/lib/supabase/client'
import { getResponseErrorMessage } from '@/lib/errors/get-error-message'
import { useCompany, useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { creditNoteNeedsJournalEntry } from '@/lib/invoices/issue-credit-note'
import { Loader2, Mail, Send } from 'lucide-react'
import type { Invoice, InvoiceItem, Customer, EntityType } from '@/types'
@@ -47,12 +49,16 @@ export default function SendInvoiceDialog({
const { company, isSandbox } = useCompany()
const canEmail = useCapability(CAPABILITY.email_send)
const t = useTranslations('invoice_send_dialog')
const locale = useLocale() as 'sv' | 'en'
const isCreditNote = !!invoice.credited_invoice_id
const isCreditRepair = isCreditNote && invoice.status === 'sent'
const [isSubmitting, setIsSubmitting] = useState(false)
const [accountingMethod, setAccountingMethod] = useState<'accrual' | 'cash'>('accrual')
const [entityType, setEntityType] = useState<EntityType>('enskild_firma')
const [periodName, setPeriodName] = useState('')
const [isInitialized, setIsInitialized] = useState(false)
const [shouldBookOnIssue, setShouldBookOnIssue] = useState(true)
useEffect(() => {
if (!open) {
@@ -66,30 +72,44 @@ export default function SendInvoiceDialog({
try {
if (!company?.id) throw new Error(t('no_active_company'))
// Fetch company settings
const { data: settings, error } = await supabase
.from('company_settings')
.select('accounting_method, entity_type')
.eq('company_id', company.id)
.maybeSingle()
const [settingsResult, periodResult, originalResult] = await Promise.all([
supabase
.from('company_settings')
.select('accounting_method, entity_type')
.eq('company_id', company.id)
.maybeSingle(),
supabase
.from('fiscal_periods')
.select('name')
.eq('company_id', company.id)
.lte('start_date', invoice.invoice_date)
.gte('end_date', invoice.invoice_date)
.maybeSingle(),
invoice.credited_invoice_id
? supabase
.from('invoices')
.select('id, invoice_number, status, journal_entry_id, paid_at, paid_amount, total')
.eq('id', invoice.credited_invoice_id)
.eq('company_id', company.id)
.maybeSingle()
: Promise.resolve({ data: null, error: null }),
])
if (error) throw new Error(t('company_settings_failed'))
if (cancelled) return
// Fetch fiscal period for the invoice date
const { data: period } = await supabase
.from('fiscal_periods')
.select('name')
.eq('company_id', company.id)
.lte('start_date', invoice.invoice_date)
.gte('end_date', invoice.invoice_date)
.maybeSingle()
if (settingsResult.error) throw new Error(t('company_settings_failed'))
if (periodResult.error) throw new Error(t('fiscal_period_failed'))
if (originalResult.error) throw new Error(t('original_invoice_failed'))
if (cancelled) return
setAccountingMethod((settings?.accounting_method || 'accrual') as 'accrual' | 'cash')
setEntityType((settings?.entity_type as EntityType) || 'enskild_firma')
setPeriodName(period?.name || '')
const method = (settingsResult.data?.accounting_method || 'accrual') as 'accrual' | 'cash'
setAccountingMethod(method)
setEntityType((settingsResult.data?.entity_type as EntityType) || 'enskild_firma')
setPeriodName(periodResult.data?.name || '')
setShouldBookOnIssue(
invoice.credited_invoice_id && originalResult.data
? creditNoteNeedsJournalEntry(method, originalResult.data)
: method === 'accrual',
)
setIsInitialized(true)
} catch (err) {
if (cancelled) return
@@ -107,7 +127,7 @@ export default function SendInvoiceDialog({
}, [open, invoice.id, invoice.invoice_date, company?.id])
const proposedLines = useMemo(() => {
if (!isInitialized || accountingMethod !== 'accrual') return []
if (!isInitialized || !shouldBookOnIssue) return []
return proposeSendLines({
invoice: {
@@ -121,12 +141,13 @@ export default function SendInvoiceDialog({
currency: invoice.currency,
exchange_rate: invoice.exchange_rate,
vat_treatment: invoice.vat_treatment,
credited_invoice_id: invoice.credited_invoice_id,
items: invoice.items,
default_dimensions: invoice.default_dimensions,
},
entityType,
})
}, [isInitialized, accountingMethod, entityType, invoice])
}, [isInitialized, shouldBookOnIssue, entityType, invoice])
const { totalDebit, totalCredit } = useMemo(() => {
let totalDebit = 0
@@ -147,33 +168,62 @@ export default function SendInvoiceDialog({
: `/api/invoices/${invoice.id}/mark-sent`
const response = await fetch(url, { method: 'POST' })
const data = await response.json()
if (!response.ok) {
throw new Error(data.error || t('send_failed_fallback'))
throw new Error(await getResponseErrorMessage(response, 'invoice', locale))
}
const data = await response.json()
onSuccess()
if (mode === 'email') {
onOpenChange(false)
const successMessage = data.message || t('send_success_default', { email: invoice.customer.email ?? '' })
toast({
title: t('send_success_title'),
description: data.message || t('send_success_default', { email: invoice.customer.email ?? '' }),
title: t(
shouldBookOnIssue && !data.partial
? isCreditNote
? 'credit_send_book_success_title'
: 'send_book_success_title'
: isCreditNote
? 'credit_send_success_title'
: 'send_success_title',
),
description: data.partial
? t('partial_success', { message: successMessage })
: isCreditNote
? t('credit_send_success', { email: invoice.customer.email ?? '' })
: successMessage,
})
} else {
// For manual send, just close: no email to confirm
onOpenChange(false)
toast({
title: t('mark_success_title'),
description: accountingMethod === 'accrual'
? t('mark_success_voucher_created')
: undefined,
title: t(
isCreditRepair
? 'credit_repair_success_title'
: shouldBookOnIssue && !data.partial
? isCreditNote
? 'credit_mark_book_success_title'
: 'mark_book_success_title'
: isCreditNote
? 'credit_mark_success_title'
: 'mark_success_title',
),
description: data.partial
? t('mark_partial_success')
: isCreditNote
? shouldBookOnIssue
? t('credit_mark_success_voucher_created')
: t('credit_mark_success_no_voucher')
: accountingMethod === 'accrual'
? t('mark_success_voucher_created')
: undefined,
})
}
} catch (error) {
toast({
title: t('send_failed_title'),
title: t(isCreditNote ? 'credit_send_failed_title' : 'send_failed_title'),
description: error instanceof Error ? error.message : t('try_again'),
variant: 'destructive',
})
@@ -186,14 +236,25 @@ export default function SendInvoiceDialog({
onOpenChange(false)
}
const showJournalPreview = accountingMethod === 'accrual' && proposedLines.length > 0
const showJournalPreview = shouldBookOnIssue && proposedLines.length > 0
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>
{mode === 'email' ? t('title_email') : t('title_manual')}{invoice.invoice_number ? t('title_suffix', { number: invoice.invoice_number }) : ''}
{t(
isCreditRepair
? 'title_credit_repair'
: isCreditNote
? mode === 'email'
? 'title_credit_email'
: 'title_credit_manual'
: mode === 'email'
? 'title_email'
: 'title_manual',
)}
{invoice.invoice_number ? t('title_suffix', { number: invoice.invoice_number }) : ''}
</DialogTitle>
<DialogDescription>
{formatCurrency(invoice.total, invoice.currency)}
@@ -236,7 +297,7 @@ export default function SendInvoiceDialog({
<JournalEntryReviewContent
periodName={periodName}
entryDate={invoice.invoice_date}
description={t('voucher_description', {
description={t(isCreditNote ? 'credit_voucher_description' : 'voucher_description', {
numberSpace: invoice.invoice_number ? ` ${invoice.invoice_number}` : '',
customerSuffix: invoice.customer.name ? `, ${invoice.customer.name}` : '',
})}
@@ -249,8 +310,8 @@ export default function SendInvoiceDialog({
</>
) : (
<p className="text-sm text-muted-foreground">
{accountingMethod === 'cash'
? t('explain_cash')
{!shouldBookOnIssue
? t(isCreditNote ? 'explain_credit_cash' : 'explain_cash')
: mode === 'email'
? t('explain_email', { email: invoice.customer.email ?? '' })
: t('explain_manual')}
@@ -266,7 +327,7 @@ export default function SendInvoiceDialog({
disabled={isSubmitting}
className="w-full sm:w-auto min-h-11"
>
{t('cancel')}
{t(isCreditNote ? 'later' : 'cancel')}
</Button>
<Button
onClick={handleConfirm}
@@ -287,7 +348,25 @@ export default function SendInvoiceDialog({
) : (
<Send className="mr-2 h-4 w-4" />
)}
{mode === 'email' ? t('send_invoice') : t('mark_as_sent')}
{t(
isCreditRepair
? 'complete_credit_bookkeeping'
: isCreditNote
? mode === 'email'
? shouldBookOnIssue
? 'send_credit_note_and_book'
: 'send_credit_note'
: shouldBookOnIssue
? 'mark_credit_note_sent_and_book'
: 'mark_credit_note_sent'
: mode === 'email'
? shouldBookOnIssue
? 'send_invoice_and_book'
: 'send_invoice'
: shouldBookOnIssue
? 'mark_as_sent_and_book'
: 'mark_as_sent',
)}
</Button>
</DialogFooter>
</DialogContent>
+1 -1
View File
@@ -106,7 +106,7 @@ const SCOPE_GROUPS: ScopeGroup[] = [
{
domain: 'companies',
labelKey: 'group_companies',
read: { scope: 'companies:read', labelKey: 'scope_companies_read', tools: 0 },
read: { scope: 'companies:read', labelKey: 'scope_companies_read', tools: 1 },
write: null,
},
{
@@ -92,6 +92,46 @@ export function InvoiceSettingsForm({ settings }: InvoiceSettingsFormProps) {
{t('default_our_reference_help')}
</p>
</div>
<fieldset className="space-y-4 border-t border-border pt-4">
<legend className="text-sm font-medium">{t('reminder_days_heading')}</legend>
<p className="text-xs text-muted-foreground">{t('reminder_days_help')}</p>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="reminder_days_level_1">{t('reminder_days_level_1')}</Label>
<Input
id="reminder_days_level_1"
name="reminder_days_level_1"
type="number"
min="1"
max="365"
defaultValue={settings.reminder_days_level_1 ?? 15}
/>
</div>
<div className="space-y-2">
<Label htmlFor="reminder_days_level_2">{t('reminder_days_level_2')}</Label>
<Input
id="reminder_days_level_2"
name="reminder_days_level_2"
type="number"
min="1"
max="365"
defaultValue={settings.reminder_days_level_2 ?? 30}
/>
</div>
<div className="space-y-2">
<Label htmlFor="reminder_days_level_3">{t('reminder_days_level_3')}</Label>
<Input
id="reminder_days_level_3"
name="reminder_days_level_3"
type="number"
min="1"
max="365"
defaultValue={settings.reminder_days_level_3 ?? 45}
/>
</div>
</div>
</fieldset>
</section>
)
}
@@ -51,6 +51,12 @@ export function InvoicingSettingsContent() {
invoice_default_days: parseInt(formData.get('invoice_default_days') as string) || 30,
invoice_default_notes: (formData.get('invoice_default_notes') as string) || null,
default_our_reference: (formData.get('default_our_reference') as string) || null,
reminder_days_level_1:
Number.parseInt(formData.get('reminder_days_level_1') as string) || 15,
reminder_days_level_2:
Number.parseInt(formData.get('reminder_days_level_2') as string) || 30,
reminder_days_level_3:
Number.parseInt(formData.get('reminder_days_level_3') as string) || 45,
}
return {
updates,
@@ -28,9 +28,10 @@ import { useCanWrite } from '@/lib/hooks/use-can-write'
import BankTransactionPicker from '@/components/transactions/BankTransactionPicker'
import AccrualPeriodControl from '@/components/bookkeeping/AccrualPeriodControl'
import LineDimensionFields from '@/components/dimensions/LineDimensionFields'
import DocumentUploadZone, { type UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
import { suggestBalanceAccount } from '@/lib/bookkeeping/accruals/account-suggestions'
import { countCalendarMonths } from '@/lib/bookkeeping/accruals/compute'
import { ArrowLeft, Plus, Trash2, ChevronDown, Loader2, Lock, AlertCircle, MessageCircle, Link2, CalendarClock, Tags } from 'lucide-react'
import { ArrowLeft, Plus, Trash2, ChevronDown, Loader2, Lock, AlertCircle, MessageCircle, Link2, CalendarClock, Tags, Paperclip } from 'lucide-react'
import type { Supplier, BASAccount, VatTreatment, EntityType, InvoiceExtractionResult, FiscalPeriod } from '@/types'
interface LineItem {
@@ -66,6 +67,7 @@ interface ExistingSupplierInvoice {
// paths still return a flat string, so accept both.
interface CreateResult {
data?: { id: string; arrival_number: number }
warnings?: Array<{ code: string; message: string }>
error?:
| string
| {
@@ -303,6 +305,7 @@ export default function NewSupplierInvoiceForm({
// with onCreated (dialog mode), otherwise navigate like the old standalone
// page did.
const finishCreate = (invoiceId?: string) => {
createFinishedRef.current = true
if (onCreated) onCreated(invoiceId)
else router.push(afterCreate(invoiceId))
}
@@ -331,6 +334,9 @@ export default function NewSupplierInvoiceForm({
const [pendingSupplierSelect, setPendingSupplierSelect] = useState<string | null>(null)
const [advancedOpen, setAdvancedOpen] = useState(false)
const [newSupplier, setNewSupplier] = useState<NewSupplierForm>(EMPTY_NEW_SUPPLIER)
const [documentFiles, setDocumentFiles] = useState<UploadedFile[]>([])
const documentFilesRef = useRef<UploadedFile[]>([])
const createFinishedRef = useRef(false)
// Inbox/AI state
const [extractedData, setExtractedData] = useState<InvoiceExtractionResult | null>(null)
@@ -379,6 +385,19 @@ export default function NewSupplierInvoiceForm({
useUnsavedChanges(isDirty)
useEffect(() => {
documentFilesRef.current = documentFiles
}, [documentFiles])
useEffect(() => () => {
if (inboxItemId || createFinishedRef.current) return
for (const file of documentFilesRef.current) {
if (file.status === 'uploaded' && file.id) {
void fetch(`/api/documents/${file.id}`, { method: 'DELETE', keepalive: true })
}
}
}, [inboxItemId])
const { fields, append, remove, replace } = useFieldArray({ control, name: 'items' })
const watchedItems = watch('items')
const watchedSupplierId = watch('supplier_id')
@@ -392,6 +411,9 @@ export default function NewSupplierInvoiceForm({
const watchedInvoiceDate = watch('invoice_date')
const watchedDueDate = watch('due_date')
const watchedPaymentReference = watch('payment_reference')
const documentUploadInProgress = documentFiles.some((file) => file.status === 'uploading')
const documentUploadFailed = documentFiles.some((file) => file.status === 'error')
const uploadedDocumentId = documentFiles.find((file) => file.status === 'uploaded')?.id
// Returns true when the field currently matches whatever the AI wrote
// when the form first loaded. Edits diverge it, hiding the dot.
function stillFromAi(value: string | null | undefined, original: string | null | undefined): boolean {
@@ -943,6 +965,7 @@ export default function NewSupplierInvoiceForm({
: data.due_date
return {
supplier_id: data.supplier_id,
...(!inboxItemId && uploadedDocumentId ? { document_id: uploadedDocumentId } : {}),
supplier_invoice_number: data.supplier_invoice_number,
invoice_date: data.invoice_date,
due_date: dueDate,
@@ -1044,10 +1067,36 @@ export default function NewSupplierInvoiceForm({
body: JSON.stringify(buildPayload(data)),
})
const result = await res.json()
if (
res.ok &&
(result as CreateResult).warnings?.some((warning) => warning.code === 'DOCUMENT_LINK_FAILED')
) {
toast({
title: t('document_link_warning_title'),
description: t('document_link_warning_description'),
variant: 'destructive',
})
}
return { ok: res.ok, status: res.status, result }
}
function onSubmit(data: FormData) {
if (documentUploadInProgress) {
toast({
title: t('document_upload_in_progress_title'),
description: t('document_upload_in_progress_description'),
variant: 'destructive',
})
return
}
if (documentUploadFailed) {
toast({
title: t('document_upload_failed_title'),
description: t('document_upload_failed_description'),
variant: 'destructive',
})
return
}
// Hard block: under faktureringsmetoden (and for privately-paid kvitton) a
// verifikation is posted at registration, and BFL 5 kap kräver att
// verifikationsnumret ligger i en obruten serie inom ett räkenskapsår. No
@@ -1328,6 +1377,34 @@ export default function NewSupplierInvoiceForm({
setTimeout(() => invoiceNumberInputRef.current?.focus(), 0)
}
function handleDocumentFilesChange(nextFiles: UploadedFile[]) {
const retainedKeys = new Set(nextFiles.map((file) => file.uploadKey))
const removedDocuments = documentFiles.filter(
(file) => file.id && !retainedKeys.has(file.uploadKey),
)
setDocumentFiles(nextFiles)
for (const document of removedDocuments) {
void fetch(`/api/documents/${document.id}`, { method: 'DELETE' })
}
}
async function discardUploadedDocument() {
const ids = documentFiles
.filter((file) => file.status === 'uploaded' && file.id)
.map((file) => file.id as string)
await Promise.allSettled(
ids.map((documentId) => fetch(`/api/documents/${documentId}`, { method: 'DELETE' })),
)
}
function handleCancel() {
void discardUploadedDocument().finally(() => {
if (onCancel) onCancel()
else router.push(inboxItemId ? '/e/general/invoice-inbox' : '/supplier-invoices')
})
}
// Match-on-create: register the invoice, then match the picked transaction.
// EF goes straight through (auto-approve included). AB stores the picked
// transaction and routes through the same review dialog as the plain
@@ -1559,6 +1636,25 @@ export default function NewSupplierInvoiceForm({
)}
</div>
{!inboxItemId && (
<div className="space-y-3 rounded-lg border border-border p-4">
<div className="flex items-start gap-3">
<Paperclip className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div>
<Label>{t('document_label')}</Label>
<p className="text-xs text-muted-foreground">{t('document_help')}</p>
</div>
</div>
<DocumentUploadZone
files={documentFiles}
onFilesChange={handleDocumentFilesChange}
maxFiles={1}
disabled={isSubmitting}
compact
/>
</div>
)}
{/* Invoice-level default dims (kostnadsställe/projekt): applied to
every generated journal line; per-row bags in Kontering merge on
top. Renders only when dimensions are enabled for the company. */}
@@ -2052,10 +2148,8 @@ export default function NewSupplierInvoiceForm({
type="button"
variant="outline"
className="w-full sm:w-auto"
onClick={() => {
if (onCancel) onCancel()
else router.push(inboxItemId ? '/e/general/invoice-inbox' : '/supplier-invoices')
}}
onClick={handleCancel}
disabled={isSubmitting || documentUploadInProgress}
>
{t('cancel')}
</Button>
@@ -2064,7 +2158,7 @@ export default function NewSupplierInvoiceForm({
type="submit"
variant="outline"
className="w-full sm:w-auto"
disabled={isSubmitting || !canWrite || showNoPeriodWarning}
disabled={isSubmitting || documentUploadInProgress || !canWrite || showNoPeriodWarning}
onClick={() => { submitModeRef.current = 'register_and_match' }}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
@@ -2074,7 +2168,7 @@ export default function NewSupplierInvoiceForm({
)}
<Button
type="submit"
disabled={isSubmitting || !canWrite || showNoPeriodWarning}
disabled={isSubmitting || documentUploadInProgress || !canWrite || showNoPeriodWarning}
className="w-full sm:w-auto"
onClick={() => { submitModeRef.current = 'register' }}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
@@ -48,6 +48,7 @@ export default function InvoicePicker({ transaction, onSelect, isProcessing }: I
.select('*, customer:customers(*)')
.eq('company_id', companyId)
.eq('document_type', 'invoice')
.is('credited_invoice_id', null)
.in('status', ['sent', 'overdue', 'partially_paid'])
.gt('remaining_amount', 0)
.order('invoice_date', { ascending: false })
@@ -112,6 +112,7 @@ export default function MatchAllocationDialog({
.select('*, customer:customers(id, name)')
.eq('company_id', companyId)
.eq('document_type', 'invoice')
.is('credited_invoice_id', null)
.in('status', ['sent', 'overdue', 'partially_paid'])
.gt('remaining_amount', 0)
.order('due_date', { ascending: true })