feat: document engine with kinds, states, atomic numbering and fulfilment (#47)

One engine for sales, purchases and warehouse documents (ADR 0032). Each document
type now carries a kind that decides its family of tables, life cycle, effects,
accepted lines, the kinds it fulfils and its permissions, so company-defined types
work without code.

- Six families of header and line tables plus document_links; document_types gets
  document_kind (seeded types filled by the migration and the Italian template),
  document_numerators gets last_date.
- DocumentStateMachine with the order, invoice and simple life cycles and the
  actions each state admits; issued invoices are immutable and are cancelled with
  a reason only before the file reaches the exchange system.
- DocumentNumberingService numbers at confirmation inside the transaction under
  the numerator lock (advisory lock on PostgreSQL, write lock on SQLite): no
  duplicates, a rollback gives the number back, out-of-sequence dates refused on
  gap-free numerators, the new year's numerator created on first use, gap report.
- DocumentEngine, the generic DocumentService<THeader, TLine> and
  DocumentCopyService: save, confirm or issue, cancel, close, reopen, delete,
  duplicate and transform; links are recorded at confirmation and removed at
  cancellation, and FulfillmentCalculator recomputes quantities and states.
- Tests: rules in Core, concurrent numbering on SQLite and PostgreSQL (data tests,
  run on PostgreSQL 18 locally), order to delivery notes to deferred invoice on a
  real instance. Wiki (Vendite, Tabelle azienda), CHANGELOG, STATUS, DATA-MODEL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 15:30:24 +01:00
1 parent fa9304834a
commit ddd2273f7e
33 files changed
+4081 -37

No files matched your search

@@ -0,0 +1,179 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>
/// The document engine (SPEC §11.3, ADR 0032, issue #47): six families of headers with their lines, the fulfilment
/// links, the kind of each document type and the date of the last number of each numerator.
/// </summary>
[Migration(20261112_003, "create_documents")]
public sealed class M20261112_003_CreateDocuments : IMigration
{
// The kinds of the document types seeded by M20261111_014 (ItalianBaseTables): the code decides the behaviour.
private static readonly (string Code, string Kind)[] SeededKinds =
[
("PRE", "Quotation"), ("OC", "SalesOrder"), ("DDT", "DeliveryNote"), ("FI", "ImmediateInvoice"), ("FA", "AccompanyingInvoice"),
("FD", "DeferredInvoice"), ("FACC", "DownPaymentInvoice"), ("NC", "CreditNote"), ("ND", "DebitNote"), ("PAR", "Fee"), ("PF", "ProForma"),
("AF16", "SelfInvoice"), ("AF17", "SelfInvoice"), ("AF18", "SelfInvoice"), ("AF19", "SelfInvoice"), ("OF", "PurchaseOrder"),
("DDTF", "PurchaseDeliveryNote"), ("FF", "PurchaseInvoice"), ("NCF", "PurchaseCreditNote"), ("MM", "InventoryEntry"),
];
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.AlterTable("document_types", t => t.String("document_kind", 40));
foreach (var (code, kind) in SeededKinds)
{
schema.Sql(_ => "UPDATE document_types SET document_kind = '" + kind + "' WHERE code = '" + code + "'");
}
schema.AlterTable("document_numerators", t => t.Date("last_date"));
Family(schema, "sale_quotations", "sale_quotation_lines");
Family(schema, "sale_orders", "sale_order_lines");
Family(schema, "sale_documents", "sale_document_lines");
Family(schema, "purchase_orders", "purchase_order_lines");
Family(schema, "purchase_documents", "purchase_document_lines");
Family(schema, "inventory_documents", "inventory_document_lines");
schema.CreateTable("document_links", t =>
{
t.Id();
t.String("target_family", 40).NotNull();
t.Int64("target_document_id").NotNull();
t.Int64("target_line_id").NotNull();
t.String("source_family", 40).NotNull();
t.Int64("source_document_id").NotNull();
t.Int64("source_line_id").NotNull();
t.Decimal("quantity").NotNull();
t.AuditColumns();
t.Index("ix_document_links_source", "source_family", "source_line_id");
t.Index("ix_document_links_source_document", "source_family", "source_document_id");
t.Index("ix_document_links_target", "target_family", "target_document_id");
});
}
private static void Family(ISchemaBuilder schema, string headers, string lines)
{
schema.CreateTable(headers, t =>
{
t.Id();
t.Int64("document_type_id").NotNull();
t.String("kind", 40).NotNull();
t.String("status", 40).NotNull();
t.Int64("numerator_id");
t.String("section", 10);
t.Int64("number");
t.String("document_number", 30);
t.Date("document_date").NotNull();
t.Int32("year").NotNull();
t.Int64("party_id");
t.Int64("destination_id");
t.String("external_reference", 40);
t.Date("external_date");
t.String("currency_code", 3).NotNull();
t.Decimal("exchange_rate").NotNull().Default(1m);
t.Int64("price_list_id");
t.Int64("payment_term_id");
t.Int64("payment_method_id");
t.Int64("bank_account_id");
t.Int64("salesperson_id");
t.Int64("warehouse_id");
t.Int64("inventory_reason_id");
t.Int64("transport_reason_id");
t.Int64("shipping_term_id");
t.Int64("carrier_id");
t.Int64("goods_appearance_id");
t.Int32("packages");
t.Decimal("gross_weight");
t.Decimal("net_weight");
t.DateTimeUtc("transport_start");
t.Date("valid_until");
t.Date("delivery_date");
t.Int32("revision").NotNull().Default(0);
t.Bool("printed").NotNull().Default(false);
t.Bool("sent").NotNull().Default(false);
t.Bool("posted").NotNull().Default(false);
t.Bool("installments_generated").NotNull().Default(false);
t.Bool("xml_generated").NotNull().Default(false);
t.Decimal("taxable_amount").NotNull().Default(0m);
t.Decimal("tax_amount").NotNull().Default(0m);
t.Decimal("total_amount").NotNull().Default(0m);
t.String("footer_discount", 30);
t.Decimal("expenses_amount").NotNull().Default(0m);
t.Decimal("stamp_duty").NotNull().Default(0m);
t.Decimal("withholding_amount").NotNull().Default(0m);
t.Decimal("social_security_amount").NotNull().Default(0m);
t.Decimal("net_amount").NotNull().Default(0m);
t.Text("notes");
t.Int64("gl_entry_id");
t.Int64("vat_protocol");
t.DateTimeUtc("confirmed_at");
t.String("confirmed_by", 100);
t.DateTimeUtc("cancelled_at");
t.String("cancel_reason", 200);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_" + headers + "_number", "numerator_id", "number");
t.Index("ix_" + headers + "_date", "document_date");
t.Index("ix_" + headers + "_party", "party_id");
t.Index("ix_" + headers + "_status", "status");
t.ForeignKey("fk_" + headers + "_type", "document_type_id", "document_types", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_numerator", "numerator_id", "document_numerators", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_party", "party_id", "parties", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_destination", "destination_id", "party_addresses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_bank_account", "bank_account_id", "bank_accounts", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_salesperson", "salesperson_id", "salespeople", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_inventory_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_transport_reason", "transport_reason_id", "transport_reasons", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_carrier", "carrier_id", "carriers", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_goods_appearance", "goods_appearance_id", "goods_appearances", ReferentialAction.Restrict);
});
schema.CreateTable(lines, t =>
{
t.Id();
t.Int64("document_id").NotNull();
t.Int32("line_number").NotNull();
t.String("kind", 40).NotNull();
t.Int64("item_id");
t.String("description", 1000).NotNull();
t.Int64("unit_of_measure_id");
t.Decimal("quantity").NotNull().Default(0m);
t.Decimal("price").NotNull().Default(0m);
t.String("price_source", 40).NotNull();
t.String("discount_formula", 30);
t.Int64("tax_code_id");
t.Decimal("taxable_amount").NotNull().Default(0m);
t.Int64("warehouse_id");
t.Date("delivery_date");
t.Decimal("fulfilled_quantity").NotNull().Default(0m);
t.Bool("fulfillment_closed").NotNull().Default(false);
t.String("source_family", 40);
t.Int64("source_line_id");
t.String("account_code", 20);
t.Int64("cost_center_id");
t.Int64("job_id");
t.Text("notes");
t.Int32("sort_order").NotNull().Default(0);
t.AuditColumns();
t.Index("ix_" + lines + "_document", "document_id");
t.Index("ix_" + lines + "_item", "item_id");
t.Index("ix_" + lines + "_source", "source_family", "source_line_id");
t.ForeignKey("fk_" + lines + "_document", "document_id", headers, ReferentialAction.Cascade);
t.ForeignKey("fk_" + lines + "_item", "item_id", "items", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_cost_center", "cost_center_id", "cost_centers", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_job", "job_id", "jobs", ReferentialAction.Restrict);
});
}
}