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
+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>