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:
@@ -0,0 +1,11 @@
|
||||
-- Make invoices.invoice_number nullable.
|
||||
-- Drafts no longer reserve a number at creation; numbers are assigned at the
|
||||
-- moment status transitions to 'sent'. The partial unique index
|
||||
-- idx_invoices_company_invoice_number (WHERE invoice_number IS NOT NULL) from
|
||||
-- 20260330130000_multi_tenant_company_refactor.sql already permits multiple
|
||||
-- NULLs, so no index changes are required.
|
||||
|
||||
ALTER TABLE public.invoices
|
||||
ALTER COLUMN invoice_number DROP NOT NULL;
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Belt-and-suspenders for the nullable invoice_number column.
|
||||
-- Invoices in any status that implies they have left the draft stage must carry
|
||||
-- a number. ensureInvoiceNumber covers known send paths in application code,
|
||||
-- but a future caller could transition status without going through that helper
|
||||
-- and silently produce a sent invoice with no löpnummer (ML 17 kap 24§ violation).
|
||||
--
|
||||
-- 'draft' and 'cancelled' are the only statuses where invoice_number may legally
|
||||
-- be NULL — drafts have not been numbered yet, and cancelled-from-draft never
|
||||
-- needed one. Cancelled-after-send retains its existing number, so the rule
|
||||
-- still holds. Status enum from invoices_status_check:
|
||||
-- draft, sent, paid, partially_paid, overdue, cancelled, credited
|
||||
|
||||
ALTER TABLE public.invoices
|
||||
ADD CONSTRAINT invoices_sent_requires_number
|
||||
CHECK (status IN ('draft', 'cancelled') OR invoice_number IS NOT NULL);
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,91 @@
|
||||
-- Atomic, document_type-aware invoice number generation.
|
||||
--
|
||||
-- Replaces the single-arg signature with one that:
|
||||
-- 1. Locks the target invoice row (SELECT ... FOR UPDATE) so concurrent
|
||||
-- callers serialize on the same draft.
|
||||
-- 2. Returns the existing number if the row already has one — idempotent;
|
||||
-- the loser of a race never consumes a sequence number.
|
||||
-- 3. Allocates from company_settings.next_invoice_number only when needed.
|
||||
-- 4. Persists the assigned number on the invoice row in the same transaction.
|
||||
-- 5. Applies a 'PF-' prefix when document_type = 'proforma' so proformas
|
||||
-- remain visually distinct from real invoices in the F-series.
|
||||
--
|
||||
-- Why this changes:
|
||||
-- - The old single-arg version always advanced the per-company counter,
|
||||
-- then a separate UPDATE in TS persisted it on the invoices row. Two
|
||||
-- concurrent send calls on the same draft both incremented the counter,
|
||||
-- and the loser's number was discarded — a permanent gap in the F-series.
|
||||
-- Gaps are tolerated under Swedish practice but creating them through a
|
||||
-- race is gratuitous and harms Skatteverket reconciliation traceability.
|
||||
-- - The proforma 'PF-' prefix logic previously lived in the API route
|
||||
-- (app/api/invoices/route.ts) and was lost when invoice_number became
|
||||
-- nullable and assignment moved to ensureInvoiceNumber. Pushing the
|
||||
-- prefix into the RPC keeps prefix logic next to the allocator.
|
||||
|
||||
DROP FUNCTION IF EXISTS public.generate_invoice_number(uuid);
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.generate_invoice_number(
|
||||
p_company_id uuid,
|
||||
p_invoice_id uuid,
|
||||
p_document_type text DEFAULT 'invoice'
|
||||
)
|
||||
RETURNS text
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path TO 'public'
|
||||
AS $function$
|
||||
DECLARE
|
||||
v_existing text;
|
||||
v_prefix text;
|
||||
v_number integer;
|
||||
v_year text;
|
||||
v_final text;
|
||||
BEGIN
|
||||
-- 1. Lock the invoice row. Concurrent callers block here until the first
|
||||
-- transaction commits, then see the persisted number on retry.
|
||||
SELECT invoice_number INTO v_existing
|
||||
FROM public.invoices
|
||||
WHERE id = p_invoice_id AND company_id = p_company_id
|
||||
FOR UPDATE;
|
||||
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION 'Invoice % not found in company %', p_invoice_id, p_company_id;
|
||||
END IF;
|
||||
|
||||
-- 2. Idempotent: if the number is already set, return it without consuming
|
||||
-- the sequence. This is also the path concurrent callers take after
|
||||
-- unblocking from the row lock.
|
||||
IF v_existing IS NOT NULL THEN
|
||||
RETURN v_existing;
|
||||
END IF;
|
||||
|
||||
-- 3. Allocate from per-company counter atomically. UPDATE ... RETURNING is
|
||||
-- serialized by Postgres on the company_settings row.
|
||||
UPDATE public.company_settings
|
||||
SET next_invoice_number = next_invoice_number + 1,
|
||||
updated_at = now()
|
||||
WHERE company_id = p_company_id
|
||||
RETURNING invoice_prefix, next_invoice_number - 1
|
||||
INTO v_prefix, v_number;
|
||||
|
||||
IF v_number IS NULL THEN
|
||||
RAISE EXCEPTION 'Company settings not found for company %', p_company_id;
|
||||
END IF;
|
||||
|
||||
-- 4. Compose: proforma -> 'PF-', otherwise use the company's invoice_prefix.
|
||||
v_year := EXTRACT(YEAR FROM CURRENT_DATE)::text;
|
||||
v_final := CASE
|
||||
WHEN p_document_type = 'proforma' THEN 'PF-'
|
||||
ELSE COALESCE(v_prefix, '')
|
||||
END || v_year || LPAD(v_number::text, 3, '0');
|
||||
|
||||
-- 5. Persist on the invoice row in the same transaction.
|
||||
UPDATE public.invoices
|
||||
SET invoice_number = v_final
|
||||
WHERE id = p_invoice_id AND company_id = p_company_id;
|
||||
|
||||
RETURN v_final;
|
||||
END;
|
||||
$function$;
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
Reference in New Issue
Block a user