Fix/invoice numbers (#365)
* feat: make invoice_number nullable and assign on send - Updated the invoices table to allow invoice_number to be nullable. - Modified the logic to assign invoice numbers only when the invoice status transitions to 'sent'. - Refactored related code to handle nullable invoice numbers, including UI components and API routes. - Added tests to ensure correct behavior when handling invoices with null invoice numbers. - Introduced a utility function to display invoice numbers, defaulting to '(Utkast)' for drafts. * fix: update fiscal period handling to return names of open periods in error messages * fix: enhance period creation logic to account for company-wide bookkeeping lock-through * fix: remove unnecessary customer_type field from customer insertion query * fix: scope invoice number count query to specific companies to avoid test interference * feat: Implement atomic invoice number generation and ensure compliance with invoice numbering rules - Introduced `ensureInvoiceNumber` function to assign invoice numbers atomically, handling concurrency and ensuring compliance with document types. - Updated invoice-related components to utilize the new `invoiceNumberDisplay` utility for consistent invoice number formatting. - Added checks to ensure that invoices in non-draft statuses have valid invoice numbers, preventing violations of legal requirements. - Created tests for the new invoice number generation logic, ensuring correct behavior under various scenarios, including concurrent requests. - Added a draft banner to PDF templates for invoices without assigned numbers, clarifying their status to users. - Updated database migrations to support the new atomic invoice number generation logic and enforce constraints on invoice statuses.
This commit is contained in:
@@ -133,7 +133,7 @@ export async function previewCurrencyRevaluation(
|
||||
items.push({
|
||||
type: 'receivable',
|
||||
source_id: inv.id,
|
||||
reference: inv.invoice_number,
|
||||
reference: inv.invoice_number ?? '',
|
||||
currency: inv.currency,
|
||||
amount_in_currency: amountInCurrency,
|
||||
original_rate: inv.exchange_rate,
|
||||
|
||||
@@ -16,16 +16,32 @@ import type {
|
||||
|
||||
const log = createLogger('invoice-entries')
|
||||
|
||||
/**
|
||||
* Build the invoice identifier used in line_description. Prefers the assigned
|
||||
* invoice number; falls back to a draft tag with the first 8 chars of the
|
||||
* invoice UUID so the verifikation still identifies *vad affärshändelsen avser*
|
||||
* per BFL 5 kap 6§ p.3 even if a journal entry is somehow created against an
|
||||
* unnumbered invoice. The send path always assigns a number first, so this
|
||||
* fallback is defensive — but it leaves no ambiguity if a future caller skips
|
||||
* ensureInvoiceNumber.
|
||||
*/
|
||||
function invoiceTag(invoice: Pick<Invoice, 'id' | 'invoice_number'>): string {
|
||||
return invoice.invoice_number ?? `utkast ${invoice.id.slice(0, 8)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a BFL-compliant verifikation description with event type and counterparty.
|
||||
* Falls back to prefix + invoiceNumber if name is not provided (backward compat).
|
||||
*/
|
||||
function buildInvoiceDescription(
|
||||
prefix: string, invoiceNumber: string, counterpartyName?: string
|
||||
prefix: string, invoiceNumber: string | null, counterpartyName?: string,
|
||||
invoiceId?: string,
|
||||
): string {
|
||||
const tag = invoiceNumber ?? (invoiceId ? `utkast ${invoiceId.slice(0, 8)}` : null)
|
||||
const tagPart = tag ? ` ${tag}` : ''
|
||||
return counterpartyName
|
||||
? `${prefix} ${invoiceNumber}, ${counterpartyName}`
|
||||
: `${prefix} ${invoiceNumber}`
|
||||
? `${prefix}${tagPart}, ${counterpartyName}`
|
||||
: `${prefix}${tagPart}`
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,7 +52,7 @@ function generatePerRateLines(
|
||||
items: InvoiceItem[],
|
||||
invoiceVatTreatment: VatTreatment,
|
||||
entityType: EntityType,
|
||||
invoiceNumber: string,
|
||||
invoiceTagText: string,
|
||||
currency?: string | null,
|
||||
exchangeRate?: number | null
|
||||
): CreateJournalEntryLineInput[] {
|
||||
@@ -64,7 +80,7 @@ function generatePerRateLines(
|
||||
account_number: revenueAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: subtotalSek,
|
||||
line_description: `Försäljning faktura ${invoiceNumber}`,
|
||||
line_description: `Försäljning faktura ${invoiceTagText}`,
|
||||
})
|
||||
|
||||
const totalVat = items.reduce((sum, item) => sum + (item.vat_amount || 0), 0)
|
||||
@@ -77,7 +93,7 @@ function generatePerRateLines(
|
||||
account_number: vatAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: vatSek,
|
||||
line_description: `Utgående moms`,
|
||||
line_description: `Utgående moms faktura ${invoiceTagText}`,
|
||||
})
|
||||
} else {
|
||||
const vatLines = generateSalesVatLines({
|
||||
@@ -113,7 +129,7 @@ function generatePerRateLines(
|
||||
account_number: revenueAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: roundedSubtotal,
|
||||
line_description: `Försäljning faktura ${invoiceNumber}`,
|
||||
line_description: `Försäljning faktura ${invoiceTagText}`,
|
||||
})
|
||||
|
||||
const roundedVat = Math.round(toSek(group.vatAmount) * 100) / 100
|
||||
@@ -123,7 +139,7 @@ function generatePerRateLines(
|
||||
account_number: vatAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: roundedVat,
|
||||
line_description: `Utgående moms ${rate}%`,
|
||||
line_description: `Utgående moms ${rate}% faktura ${invoiceTagText}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -166,13 +182,14 @@ export async function createInvoiceJournalEntry(
|
||||
|
||||
const lines: CreateJournalEntryLineInput[] = []
|
||||
const isForeign = invoice.currency !== 'SEK'
|
||||
const tag = invoiceTag(invoice)
|
||||
|
||||
// Credit lines: revenue + VAT per rate group (compute first to guarantee balance)
|
||||
const creditLines: CreateJournalEntryLineInput[] = []
|
||||
|
||||
if (invoice.items && invoice.items.length > 0) {
|
||||
creditLines.push(...generatePerRateLines(
|
||||
invoice.items, invoice.vat_treatment, entityType, invoice.invoice_number,
|
||||
invoice.items, invoice.vat_treatment, entityType, tag,
|
||||
invoice.currency, invoice.exchange_rate
|
||||
))
|
||||
} else {
|
||||
@@ -184,7 +201,7 @@ export async function createInvoiceJournalEntry(
|
||||
account_number: revenueAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: subtotalSek,
|
||||
line_description: `Försäljning faktura ${invoice.invoice_number}`,
|
||||
line_description: `Försäljning faktura ${tag}`,
|
||||
})
|
||||
|
||||
if (invoice.vat_amount > 0) {
|
||||
@@ -195,7 +212,7 @@ export async function createInvoiceJournalEntry(
|
||||
account_number: vatAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: vatSek,
|
||||
line_description: `Utgående moms faktura ${invoice.invoice_number}`,
|
||||
line_description: `Utgående moms faktura ${tag}`,
|
||||
})
|
||||
} else {
|
||||
const vatLines = generateSalesVatLines({
|
||||
@@ -218,7 +235,7 @@ export async function createInvoiceJournalEntry(
|
||||
account_number: '1510',
|
||||
debit_amount: debitAmount,
|
||||
credit_amount: 0,
|
||||
line_description: `Faktura ${invoice.invoice_number}`,
|
||||
line_description: `Faktura ${tag}`,
|
||||
...buildCurrencyMetadata(invoice.currency, isForeign ? invoice.total : undefined, invoice.exchange_rate),
|
||||
})
|
||||
|
||||
@@ -227,7 +244,7 @@ export async function createInvoiceJournalEntry(
|
||||
const input: CreateJournalEntryInput = {
|
||||
fiscal_period_id: fiscalPeriodId,
|
||||
entry_date: invoice.invoice_date,
|
||||
description: buildInvoiceDescription('Kundfaktura', invoice.invoice_number, customerName),
|
||||
description: buildInvoiceDescription('Kundfaktura', invoice.invoice_number, customerName, invoice.id),
|
||||
source_type: 'invoice_created',
|
||||
source_id: invoice.id,
|
||||
lines,
|
||||
@@ -262,7 +279,8 @@ export async function createInvoicePaymentJournalEntry(
|
||||
const desc = buildInvoiceDescription(
|
||||
isPartial ? 'Delbetalning kundfaktura' : 'Inbetalning kundfaktura',
|
||||
invoice.invoice_number,
|
||||
customerName
|
||||
customerName,
|
||||
invoice.id,
|
||||
)
|
||||
|
||||
// When paymentAmount is provided, use it for the 1930/1510 line amounts.
|
||||
@@ -365,6 +383,7 @@ export async function createCreditNoteJournalEntry(
|
||||
}
|
||||
|
||||
const lines: CreateJournalEntryLineInput[] = []
|
||||
const tag = invoiceTag(creditNote)
|
||||
|
||||
// Generate reversed revenue + VAT lines per rate group (debit side for credit notes)
|
||||
const debitLines: CreateJournalEntryLineInput[] = []
|
||||
@@ -372,7 +391,7 @@ export async function createCreditNoteJournalEntry(
|
||||
if (creditNote.items && creditNote.items.length > 0) {
|
||||
// Use absolute items for generatePerRateLines, then swap debit/credit
|
||||
const creditLines = generatePerRateLines(
|
||||
creditNote.items, creditNote.vat_treatment, entityType, creditNote.invoice_number,
|
||||
creditNote.items, creditNote.vat_treatment, entityType, tag,
|
||||
creditNote.currency, creditNote.exchange_rate
|
||||
)
|
||||
for (const line of creditLines) {
|
||||
@@ -380,7 +399,7 @@ export async function createCreditNoteJournalEntry(
|
||||
...line,
|
||||
debit_amount: Math.abs(line.credit_amount),
|
||||
credit_amount: Math.abs(line.debit_amount),
|
||||
line_description: `Kreditfaktura ${creditNote.invoice_number}`,
|
||||
line_description: `Kreditfaktura ${tag}`,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
@@ -393,7 +412,7 @@ export async function createCreditNoteJournalEntry(
|
||||
account_number: revenueAccount,
|
||||
debit_amount: absSubtotal,
|
||||
credit_amount: 0,
|
||||
line_description: `Kreditfaktura ${creditNote.invoice_number}`,
|
||||
line_description: `Kreditfaktura ${tag}`,
|
||||
})
|
||||
|
||||
if (absVat > 0) {
|
||||
@@ -402,7 +421,7 @@ export async function createCreditNoteJournalEntry(
|
||||
account_number: vatAccount,
|
||||
debit_amount: absVat,
|
||||
credit_amount: 0,
|
||||
line_description: `Moms kreditfaktura ${creditNote.invoice_number}`,
|
||||
line_description: `Moms kreditfaktura ${tag}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -415,13 +434,13 @@ export async function createCreditNoteJournalEntry(
|
||||
account_number: '1510',
|
||||
debit_amount: 0,
|
||||
credit_amount: Math.round(totalDebits * 100) / 100,
|
||||
line_description: `Kreditfaktura ${creditNote.invoice_number}`,
|
||||
line_description: `Kreditfaktura ${tag}`,
|
||||
})
|
||||
|
||||
const input: CreateJournalEntryInput = {
|
||||
fiscal_period_id: fiscalPeriodId,
|
||||
entry_date: creditNote.invoice_date,
|
||||
description: buildInvoiceDescription('Kreditfaktura', creditNote.invoice_number, customerName),
|
||||
description: buildInvoiceDescription('Kreditfaktura', creditNote.invoice_number, customerName, creditNote.id),
|
||||
source_type: 'credit_note',
|
||||
source_id: creditNote.id,
|
||||
lines,
|
||||
@@ -455,13 +474,14 @@ export async function createInvoiceCashEntry(
|
||||
|
||||
const lines: CreateJournalEntryLineInput[] = []
|
||||
const isForeign = invoice.currency !== 'SEK'
|
||||
const tag = invoiceTag(invoice)
|
||||
|
||||
// Credit lines: revenue + VAT per rate group (compute first to guarantee balance)
|
||||
const creditLines: CreateJournalEntryLineInput[] = []
|
||||
|
||||
if (invoice.items && invoice.items.length > 0) {
|
||||
creditLines.push(...generatePerRateLines(
|
||||
invoice.items, invoice.vat_treatment, entityType, invoice.invoice_number,
|
||||
invoice.items, invoice.vat_treatment, entityType, tag,
|
||||
invoice.currency, invoice.exchange_rate
|
||||
))
|
||||
} else {
|
||||
@@ -473,7 +493,7 @@ export async function createInvoiceCashEntry(
|
||||
account_number: revenueAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: subtotalSek,
|
||||
line_description: `Försäljning faktura ${invoice.invoice_number}`,
|
||||
line_description: `Försäljning faktura ${tag}`,
|
||||
})
|
||||
|
||||
if (invoice.vat_amount > 0) {
|
||||
@@ -483,7 +503,7 @@ export async function createInvoiceCashEntry(
|
||||
account_number: vatAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: vatSek,
|
||||
line_description: `Utgående moms faktura ${invoice.invoice_number}`,
|
||||
line_description: `Utgående moms faktura ${tag}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -494,7 +514,7 @@ export async function createInvoiceCashEntry(
|
||||
account_number: '1930',
|
||||
debit_amount: isForeign ? Math.round(totalCredits * 100) / 100 : resolveSekAmount(invoice.total, invoice.total_sek, invoice.currency, invoice.exchange_rate),
|
||||
credit_amount: 0,
|
||||
line_description: buildInvoiceDescription('Kontantbetalning kundfaktura', invoice.invoice_number, customerName),
|
||||
line_description: buildInvoiceDescription('Kontantbetalning kundfaktura', invoice.invoice_number, customerName, invoice.id),
|
||||
})
|
||||
|
||||
lines.push(...creditLines)
|
||||
@@ -502,7 +522,7 @@ export async function createInvoiceCashEntry(
|
||||
const input: CreateJournalEntryInput = {
|
||||
fiscal_period_id: fiscalPeriodId,
|
||||
entry_date: paymentDate,
|
||||
description: buildInvoiceDescription('Kontantbetalning kundfaktura', invoice.invoice_number, customerName),
|
||||
description: buildInvoiceDescription('Kontantbetalning kundfaktura', invoice.invoice_number, customerName, invoice.id),
|
||||
source_type: 'invoice_cash_payment',
|
||||
source_id: invoice.id,
|
||||
lines,
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { EntityType, InvoiceItem, VatTreatment } from '@/types'
|
||||
|
||||
export interface ProposePaymentLinesInput {
|
||||
invoice: {
|
||||
invoice_number: string
|
||||
invoice_number: string | null
|
||||
total: number
|
||||
total_sek?: number | null
|
||||
subtotal: number
|
||||
@@ -44,7 +44,7 @@ function toFormAmount(n: number): string {
|
||||
export function proposePaymentLines(input: ProposePaymentLinesInput): FormLine[] {
|
||||
const { invoice, accountingMethod, entityType, exchangeRateDifference } = input
|
||||
const paymentAccount = input.paymentAccount || '1930'
|
||||
const desc = `Betalning faktura ${invoice.invoice_number}`
|
||||
const desc = invoice.invoice_number ? `Betalning faktura ${invoice.invoice_number}` : 'Betalning faktura'
|
||||
|
||||
if (accountingMethod === 'accrual') {
|
||||
return proposeAccrualLines(invoice, paymentAccount, desc, exchangeRateDifference)
|
||||
@@ -148,7 +148,7 @@ function proposeCashLines(
|
||||
account_number: revenueAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(toSek(subtotal)),
|
||||
line_description: `Försäljning faktura ${invoice.invoice_number}`,
|
||||
line_description: (invoice.invoice_number ? `Försäljning faktura ${invoice.invoice_number}` : 'Försäljning faktura'),
|
||||
})
|
||||
|
||||
const totalVat = invoice.items.reduce((sum, item) => sum + (item.vat_amount || 0), 0)
|
||||
@@ -182,7 +182,7 @@ function proposeCashLines(
|
||||
account_number: revenueAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(Math.round(toSek(group.subtotal) * 100) / 100),
|
||||
line_description: `Försäljning faktura ${invoice.invoice_number}`,
|
||||
line_description: (invoice.invoice_number ? `Försäljning faktura ${invoice.invoice_number}` : 'Försäljning faktura'),
|
||||
})
|
||||
|
||||
const roundedVat = Math.round(toSek(group.vatAmount) * 100) / 100
|
||||
@@ -205,7 +205,7 @@ function proposeCashLines(
|
||||
account_number: revenueAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(subtotalSek),
|
||||
line_description: `Försäljning faktura ${invoice.invoice_number}`,
|
||||
line_description: (invoice.invoice_number ? `Försäljning faktura ${invoice.invoice_number}` : 'Försäljning faktura'),
|
||||
})
|
||||
|
||||
if (invoice.vat_amount > 0) {
|
||||
@@ -215,7 +215,7 @@ function proposeCashLines(
|
||||
account_number: vatAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(vatSek),
|
||||
line_description: `Utgående moms faktura ${invoice.invoice_number}`,
|
||||
line_description: (invoice.invoice_number ? `Utgående moms faktura ${invoice.invoice_number}` : 'Utgående moms faktura'),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { EntityType, InvoiceItem, VatTreatment } from '@/types'
|
||||
|
||||
export interface ProposeSendLinesInput {
|
||||
invoice: {
|
||||
invoice_number: string
|
||||
invoice_number: string | null
|
||||
total: number
|
||||
total_sek?: number | null
|
||||
subtotal: number
|
||||
@@ -43,7 +43,7 @@ export function proposeSendLines(input: ProposeSendLinesInput): FormLine[] {
|
||||
const { invoice, entityType } = input
|
||||
const lines: FormLine[] = []
|
||||
const isForeign = invoice.currency !== 'SEK'
|
||||
const desc = `Försäljning faktura ${invoice.invoice_number}`
|
||||
const desc = invoice.invoice_number ? `Försäljning faktura ${invoice.invoice_number}` : 'Försäljning faktura'
|
||||
|
||||
const toSek = (amount: number): number => {
|
||||
if (!isForeign) return amount
|
||||
@@ -134,7 +134,7 @@ export function proposeSendLines(input: ProposeSendLinesInput): FormLine[] {
|
||||
account_number: vatAccount,
|
||||
debit_amount: '',
|
||||
credit_amount: toFormAmount(vatSek),
|
||||
line_description: `Utgående moms faktura ${invoice.invoice_number}`,
|
||||
line_description: (invoice.invoice_number ? `Utgående moms faktura ${invoice.invoice_number}` : 'Utgående moms faktura'),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
|
||||
type MockChain = {
|
||||
from: ReturnType<typeof vi.fn>
|
||||
rpc: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function buildMockSupabase(): MockChain {
|
||||
return {
|
||||
from: vi.fn(),
|
||||
rpc: vi.fn(),
|
||||
}
|
||||
}
|
||||
|
||||
describe('ensureInvoiceNumber', () => {
|
||||
let supabase: MockChain
|
||||
|
||||
beforeEach(() => {
|
||||
supabase = buildMockSupabase()
|
||||
})
|
||||
|
||||
it('returns existing number without RPC when invoice already has one', async () => {
|
||||
const invoice = { id: 'inv-1', invoice_number: 'F-2026001' }
|
||||
|
||||
const result = await ensureInvoiceNumber(supabase as never, 'company-1', invoice)
|
||||
|
||||
expect(result).toBe('F-2026001')
|
||||
expect(supabase.rpc).not.toHaveBeenCalled()
|
||||
expect(invoice.invoice_number).toBe('F-2026001')
|
||||
})
|
||||
|
||||
it('calls RPC with invoice id and document_type=invoice when number is null', async () => {
|
||||
const invoice: { id: string; invoice_number: string | null } = {
|
||||
id: 'inv-1',
|
||||
invoice_number: null,
|
||||
}
|
||||
|
||||
supabase.rpc.mockResolvedValue({ data: 'F2026005', error: null })
|
||||
|
||||
const result = await ensureInvoiceNumber(supabase as never, 'company-1', invoice)
|
||||
|
||||
expect(result).toBe('F2026005')
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('generate_invoice_number', {
|
||||
p_company_id: 'company-1',
|
||||
p_invoice_id: 'inv-1',
|
||||
p_document_type: 'invoice',
|
||||
})
|
||||
expect(invoice.invoice_number).toBe('F2026005')
|
||||
})
|
||||
|
||||
it('passes document_type=proforma so the RPC produces a PF- prefix', async () => {
|
||||
const invoice = {
|
||||
id: 'inv-2',
|
||||
invoice_number: null,
|
||||
document_type: 'proforma' as const,
|
||||
}
|
||||
|
||||
supabase.rpc.mockResolvedValue({ data: 'PF-2026005', error: null })
|
||||
|
||||
const result = await ensureInvoiceNumber(supabase as never, 'company-1', invoice)
|
||||
|
||||
expect(result).toBe('PF-2026005')
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('generate_invoice_number', {
|
||||
p_company_id: 'company-1',
|
||||
p_invoice_id: 'inv-2',
|
||||
p_document_type: 'proforma',
|
||||
})
|
||||
expect(invoice.invoice_number).toBe('PF-2026005')
|
||||
})
|
||||
|
||||
it('throws when RPC fails', async () => {
|
||||
const invoice = { id: 'inv-1', invoice_number: null }
|
||||
supabase.rpc.mockResolvedValue({ data: null, error: { message: 'RPC failed' } })
|
||||
|
||||
await expect(
|
||||
ensureInvoiceNumber(supabase as never, 'company-1', invoice)
|
||||
).rejects.toThrow('Failed to assign invoice number')
|
||||
})
|
||||
|
||||
it('throws when RPC returns no data even without an error', async () => {
|
||||
const invoice = { id: 'inv-1', invoice_number: null }
|
||||
supabase.rpc.mockResolvedValue({ data: null, error: null })
|
||||
|
||||
await expect(
|
||||
ensureInvoiceNumber(supabase as never, 'company-1', invoice)
|
||||
).rejects.toThrow('no value returned')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,191 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool } from '@/tests/pg/setup'
|
||||
import { seedCompany } from '@/tests/pg/fixtures'
|
||||
|
||||
// Insert a customer + draft invoice (invoice_number=null) and return the invoice id.
|
||||
async function insertDraftInvoice(params: {
|
||||
userId: string
|
||||
companyId: string
|
||||
documentType?: 'invoice' | 'proforma'
|
||||
}): Promise<string> {
|
||||
const customerId = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.customers (id, user_id, company_id, name)
|
||||
VALUES ($1, $2, $3, 'Test Customer')`,
|
||||
[customerId, params.userId, params.companyId],
|
||||
)
|
||||
|
||||
const invoiceId = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.invoices
|
||||
(id, user_id, company_id, customer_id, invoice_number, document_type,
|
||||
invoice_date, due_date, currency, subtotal, vat_amount, total,
|
||||
vat_treatment, vat_rate, moms_ruta, status)
|
||||
VALUES ($1, $2, $3, $4, NULL, $5,
|
||||
'2026-04-27', '2026-05-27', 'SEK', 1000, 250, 1250,
|
||||
'standard_25', 25, '10', 'draft')`,
|
||||
[invoiceId, params.userId, params.companyId, customerId, params.documentType ?? 'invoice'],
|
||||
)
|
||||
return invoiceId
|
||||
}
|
||||
|
||||
async function ensureCompanySettings(params: {
|
||||
userId: string
|
||||
companyId: string
|
||||
invoicePrefix?: string
|
||||
nextInvoiceNumber?: number
|
||||
}): Promise<void> {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.company_settings
|
||||
(user_id, company_id, invoice_prefix, next_invoice_number)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (company_id) DO UPDATE
|
||||
SET invoice_prefix = EXCLUDED.invoice_prefix,
|
||||
next_invoice_number = EXCLUDED.next_invoice_number`,
|
||||
[params.userId, params.companyId, params.invoicePrefix ?? 'F', params.nextInvoiceNumber ?? 1],
|
||||
)
|
||||
}
|
||||
|
||||
async function readCounter(companyId: string): Promise<number> {
|
||||
const { rows } = await getPool().query<{ next_invoice_number: number }>(
|
||||
'SELECT next_invoice_number FROM public.company_settings WHERE company_id = $1',
|
||||
[companyId],
|
||||
)
|
||||
return rows[0]!.next_invoice_number
|
||||
}
|
||||
|
||||
describe('generate_invoice_number RPC', () => {
|
||||
it('assigns a number to a draft and persists it on the invoice row', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await ensureCompanySettings({ userId, companyId, invoicePrefix: 'F', nextInvoiceNumber: 1 })
|
||||
const invoiceId = await insertDraftInvoice({ userId, companyId })
|
||||
|
||||
const { rows } = await getPool().query<{ generate_invoice_number: string }>(
|
||||
'SELECT public.generate_invoice_number($1, $2, $3)',
|
||||
[companyId, invoiceId, 'invoice'],
|
||||
)
|
||||
|
||||
const assigned = rows[0]!.generate_invoice_number
|
||||
expect(assigned).toMatch(/^F\d{4}\d{3}$/)
|
||||
|
||||
const persisted = await getPool().query<{ invoice_number: string }>(
|
||||
'SELECT invoice_number FROM public.invoices WHERE id = $1',
|
||||
[invoiceId],
|
||||
)
|
||||
expect(persisted.rows[0]!.invoice_number).toBe(assigned)
|
||||
})
|
||||
|
||||
it('produces a PF- prefix when document_type is proforma', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await ensureCompanySettings({ userId, companyId, invoicePrefix: 'F', nextInvoiceNumber: 42 })
|
||||
const invoiceId = await insertDraftInvoice({ userId, companyId, documentType: 'proforma' })
|
||||
|
||||
const { rows } = await getPool().query<{ generate_invoice_number: string }>(
|
||||
'SELECT public.generate_invoice_number($1, $2, $3)',
|
||||
[companyId, invoiceId, 'proforma'],
|
||||
)
|
||||
|
||||
expect(rows[0]!.generate_invoice_number).toMatch(/^PF-\d{4}042$/)
|
||||
})
|
||||
|
||||
it('is idempotent: a second call on the same invoice returns the same number without bumping the counter', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await ensureCompanySettings({ userId, companyId, invoicePrefix: 'F', nextInvoiceNumber: 10 })
|
||||
const invoiceId = await insertDraftInvoice({ userId, companyId })
|
||||
|
||||
const first = await getPool().query<{ generate_invoice_number: string }>(
|
||||
'SELECT public.generate_invoice_number($1, $2, $3)',
|
||||
[companyId, invoiceId, 'invoice'],
|
||||
)
|
||||
const counterAfterFirst = await readCounter(companyId)
|
||||
|
||||
const second = await getPool().query<{ generate_invoice_number: string }>(
|
||||
'SELECT public.generate_invoice_number($1, $2, $3)',
|
||||
[companyId, invoiceId, 'invoice'],
|
||||
)
|
||||
const counterAfterSecond = await readCounter(companyId)
|
||||
|
||||
expect(second.rows[0]!.generate_invoice_number).toBe(first.rows[0]!.generate_invoice_number)
|
||||
expect(counterAfterSecond).toBe(counterAfterFirst)
|
||||
})
|
||||
|
||||
it('serializes concurrent calls on the same invoice — both see the same number, counter advances by 1', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await ensureCompanySettings({ userId, companyId, invoicePrefix: 'F', nextInvoiceNumber: 100 })
|
||||
const invoiceId = await insertDraftInvoice({ userId, companyId })
|
||||
const counterBefore = await readCounter(companyId)
|
||||
|
||||
// Race two RPC calls on dedicated clients so they really execute in parallel.
|
||||
const a = getPool()
|
||||
.connect()
|
||||
.then(async (c) => {
|
||||
try {
|
||||
const { rows } = await c.query<{ generate_invoice_number: string }>(
|
||||
'SELECT public.generate_invoice_number($1, $2, $3)',
|
||||
[companyId, invoiceId, 'invoice'],
|
||||
)
|
||||
return rows[0]!.generate_invoice_number
|
||||
} finally {
|
||||
c.release()
|
||||
}
|
||||
})
|
||||
const b = getPool()
|
||||
.connect()
|
||||
.then(async (c) => {
|
||||
try {
|
||||
const { rows } = await c.query<{ generate_invoice_number: string }>(
|
||||
'SELECT public.generate_invoice_number($1, $2, $3)',
|
||||
[companyId, invoiceId, 'invoice'],
|
||||
)
|
||||
return rows[0]!.generate_invoice_number
|
||||
} finally {
|
||||
c.release()
|
||||
}
|
||||
})
|
||||
|
||||
const [resultA, resultB] = await Promise.all([a, b])
|
||||
const counterAfter = await readCounter(companyId)
|
||||
|
||||
expect(resultA).toBe(resultB)
|
||||
expect(counterAfter - counterBefore).toBe(1)
|
||||
})
|
||||
|
||||
it('different invoices in the same company get distinct sequential numbers', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await ensureCompanySettings({ userId, companyId, invoicePrefix: 'F', nextInvoiceNumber: 200 })
|
||||
|
||||
const invoiceA = await insertDraftInvoice({ userId, companyId })
|
||||
const invoiceB = await insertDraftInvoice({ userId, companyId })
|
||||
|
||||
const a = await getPool().query<{ generate_invoice_number: string }>(
|
||||
'SELECT public.generate_invoice_number($1, $2, $3)',
|
||||
[companyId, invoiceA, 'invoice'],
|
||||
)
|
||||
const b = await getPool().query<{ generate_invoice_number: string }>(
|
||||
'SELECT public.generate_invoice_number($1, $2, $3)',
|
||||
[companyId, invoiceB, 'invoice'],
|
||||
)
|
||||
|
||||
expect(a.rows[0]!.generate_invoice_number).toMatch(/200$/)
|
||||
expect(b.rows[0]!.generate_invoice_number).toMatch(/201$/)
|
||||
})
|
||||
|
||||
it('raises when the invoice id does not belong to the company', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await ensureCompanySettings({ userId, companyId })
|
||||
const otherCompany = await seedCompany()
|
||||
const invoiceId = await insertDraftInvoice({
|
||||
userId: otherCompany.userId,
|
||||
companyId: otherCompany.companyId,
|
||||
})
|
||||
|
||||
await expect(
|
||||
getPool().query('SELECT public.generate_invoice_number($1, $2, $3)', [
|
||||
companyId,
|
||||
invoiceId,
|
||||
'invoice',
|
||||
]),
|
||||
).rejects.toThrow(/Invoice .* not found/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool } from '@/tests/pg/setup'
|
||||
import { seedCompany } from '@/tests/pg/fixtures'
|
||||
|
||||
describe('invoices.invoice_number nullable + partial unique index', () => {
|
||||
async function insertInvoice(params: {
|
||||
userId: string
|
||||
companyId: string
|
||||
invoiceNumber: string | null
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const customerId = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.customers (id, user_id, company_id, name)
|
||||
VALUES ($1, $2, $3, 'Test Customer')`,
|
||||
[customerId, params.userId, params.companyId],
|
||||
)
|
||||
await getPool().query(
|
||||
`INSERT INTO public.invoices
|
||||
(id, user_id, company_id, customer_id, invoice_number,
|
||||
invoice_date, due_date, currency, subtotal, vat_amount, total,
|
||||
vat_treatment, vat_rate, moms_ruta, status)
|
||||
VALUES ($1, $2, $3, $4, $5,
|
||||
'2026-04-27', '2026-05-27', 'SEK', 1000, 250, 1250,
|
||||
'standard_25', 25, '10', 'draft')`,
|
||||
[id, params.userId, params.companyId, customerId, params.invoiceNumber],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
it('accepts NULL invoice_number for drafts (constraint dropped)', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
|
||||
const id = await insertInvoice({ userId, companyId, invoiceNumber: null })
|
||||
|
||||
const { rows } = await getPool().query<{ invoice_number: string | null }>(
|
||||
'SELECT invoice_number FROM public.invoices WHERE id = $1',
|
||||
[id],
|
||||
)
|
||||
expect(rows[0]!.invoice_number).toBeNull()
|
||||
})
|
||||
|
||||
it('allows multiple drafts with NULL invoice_number in the same company', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
|
||||
const a = await insertInvoice({ userId, companyId, invoiceNumber: null })
|
||||
const b = await insertInvoice({ userId, companyId, invoiceNumber: null })
|
||||
|
||||
expect(a).not.toBe(b)
|
||||
const { rows } = await getPool().query(
|
||||
'SELECT count(*)::int FROM public.invoices WHERE company_id = $1 AND invoice_number IS NULL',
|
||||
[companyId],
|
||||
)
|
||||
expect(rows[0]!.count).toBe(2)
|
||||
})
|
||||
|
||||
it('still rejects duplicate non-NULL numbers within a company', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
|
||||
await insertInvoice({ userId, companyId, invoiceNumber: 'F-2026001' })
|
||||
|
||||
await expect(
|
||||
insertInvoice({ userId, companyId, invoiceNumber: 'F-2026001' }),
|
||||
).rejects.toThrow(/idx_invoices_company_invoice_number|duplicate key/i)
|
||||
})
|
||||
|
||||
it('lets two different companies use the same invoice number', async () => {
|
||||
const a = await seedCompany()
|
||||
const b = await seedCompany()
|
||||
|
||||
await insertInvoice({ userId: a.userId, companyId: a.companyId, invoiceNumber: 'F-2026001' })
|
||||
await insertInvoice({ userId: b.userId, companyId: b.companyId, invoiceNumber: 'F-2026001' })
|
||||
|
||||
// Scope the count to these two companies — earlier tests in the suite leave
|
||||
// 'F-2026001' rows behind in their own companies, and pg-real has no
|
||||
// per-test cleanup.
|
||||
const { rows } = await getPool().query(
|
||||
'SELECT count(*)::int FROM public.invoices WHERE invoice_number = $1 AND company_id = ANY($2::uuid[])',
|
||||
['F-2026001', [a.companyId, b.companyId]],
|
||||
)
|
||||
expect(rows[0]!.count).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
export const INVOICE_NUMBER_DRAFT_LABEL = '(Utkast)'
|
||||
|
||||
export function invoiceNumberDisplay(value: string | null | undefined): string {
|
||||
return value ?? INVOICE_NUMBER_DRAFT_LABEL
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { Invoice, InvoiceDocumentType } from '@/types'
|
||||
|
||||
type InvoiceShape = Pick<Invoice, 'id' | 'invoice_number'> & {
|
||||
invoice_number: string | null
|
||||
document_type?: InvoiceDocumentType | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign an invoice number to a draft invoice. Idempotent: if the row already
|
||||
* has a number, returns it unchanged without consuming a sequence number.
|
||||
*
|
||||
* Concurrency is handled inside the generate_invoice_number RPC via row lock.
|
||||
* Two callers racing on the same draft both return the same final number; the
|
||||
* counter advances by exactly one. Proforma document_type produces a 'PF-'
|
||||
* prefix; everything else uses the company's configured invoice_prefix.
|
||||
*/
|
||||
export async function ensureInvoiceNumber(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
invoice: InvoiceShape,
|
||||
): Promise<string> {
|
||||
if (invoice.invoice_number) {
|
||||
return invoice.invoice_number
|
||||
}
|
||||
|
||||
const { data: assigned, error: rpcError } = await supabase.rpc('generate_invoice_number', {
|
||||
p_company_id: companyId,
|
||||
p_invoice_id: invoice.id,
|
||||
p_document_type: invoice.document_type ?? 'invoice',
|
||||
})
|
||||
|
||||
if (rpcError || !assigned) {
|
||||
throw new Error(`Failed to assign invoice number: ${rpcError?.message ?? 'no value returned'}`)
|
||||
}
|
||||
|
||||
invoice.invoice_number = assigned
|
||||
return assigned
|
||||
}
|
||||
@@ -214,6 +214,26 @@ const styles = StyleSheet.create({
|
||||
creditNoteTitle: {
|
||||
color: '#721c24',
|
||||
},
|
||||
draftBanner: {
|
||||
marginBottom: 16,
|
||||
padding: 10,
|
||||
backgroundColor: '#fff3cd',
|
||||
borderWidth: 2,
|
||||
borderColor: '#856404',
|
||||
borderRadius: 4,
|
||||
},
|
||||
draftBannerTitle: {
|
||||
fontSize: 14,
|
||||
fontWeight: 'bold',
|
||||
color: '#856404',
|
||||
textAlign: 'center',
|
||||
marginBottom: 2,
|
||||
},
|
||||
draftBannerText: {
|
||||
fontSize: 9,
|
||||
color: '#856404',
|
||||
textAlign: 'center',
|
||||
},
|
||||
footer: {
|
||||
position: 'absolute',
|
||||
bottom: 30,
|
||||
@@ -305,13 +325,26 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
return (
|
||||
<Document>
|
||||
<Page size="A4" style={styles.page}>
|
||||
{/* Draft banner — visible warning when this PDF is rendered for an
|
||||
invoice that has not yet been assigned a löpnummer. ML 17 kap 24§
|
||||
requires a unique invoice number; without one the document is not
|
||||
valid as fakturaunderlag and must not be sent to a customer. */}
|
||||
{!invoice.invoice_number && (
|
||||
<View style={styles.draftBanner}>
|
||||
<Text style={styles.draftBannerTitle}>UTKAST – inte en giltig faktura</Text>
|
||||
<Text style={styles.draftBannerText}>
|
||||
Denna faktura saknar löpnummer och kan inte användas som fakturaunderlag enligt ML 17 kap 24§. Skicka fakturan via systemet för att tilldela ett nummer.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Header */}
|
||||
<View style={styles.header}>
|
||||
<View>
|
||||
<Text style={[styles.title, isCreditNote ? styles.creditNoteTitle : {}]}>
|
||||
{getDocumentTitle(invoice)}
|
||||
</Text>
|
||||
<Text style={{ marginTop: 5, color: '#666' }}>{invoice.invoice_number}</Text>
|
||||
<Text style={{ marginTop: 5, color: '#666' }}>{invoice.invoice_number ?? 'FÖRHANDSGRANSKNING'}</Text>
|
||||
</View>
|
||||
<View style={styles.companyInfo}>
|
||||
{company.logo_url && (
|
||||
@@ -567,7 +600,7 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
{(company.invoice_show_ocr ?? true) && (
|
||||
<View style={styles.paymentRow}>
|
||||
<Text style={styles.paymentLabel}>OCR/Referens:</Text>
|
||||
<Text style={[styles.paymentValue, { fontWeight: 'bold' }]}>{generateOcrReference(invoice.invoice_number)}</Text>
|
||||
<Text style={[styles.paymentValue, { fontWeight: 'bold' }]}>{invoice.invoice_number ? generateOcrReference(invoice.invoice_number) : '—'}</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
Reference in New Issue
Block a user