Files
Khaemhat/src/Khaemhat.Core/Documents/DocumentBehaviors.cs
T
Alby96andClaude Opus 5.5 ddd2273f7e 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>
2026-11-12 15:30:24 +01:00

114 lines
8.6 KiB
C#

namespace Khaemhat.Core.Documents;
/// <summary>How the documents of a kind behave (ADR 0032).</summary>
/// <param name="Kind">The kind.</param>
/// <param name="Family">The tables that hold them.</param>
/// <param name="Direction">Customer, supplier or internal.</param>
/// <param name="Lifecycle">The states they go through.</param>
/// <param name="Effects">What confirming them does.</param>
/// <param name="Lines">The line kinds they accept.</param>
/// <param name="Sources">The kinds whose lines they fulfil (order to delivery note, delivery note to invoice...).</param>
/// <param name="ReadPermission">The permission to see them.</param>
/// <param name="WritePermission">The permission to create and change drafts.</param>
/// <param name="ConfirmPermission">The permission to confirm or issue, cancel, close and reopen.</param>
/// <param name="DeletePermission">The permission to delete drafts.</param>
public sealed record DocumentBehavior(
DocumentKind Kind,
DocumentFamily Family,
DocumentDirection Direction,
DocumentLifecycle Lifecycle,
DocumentEffects Effects,
IReadOnlyList<DocumentLineKind> Lines,
IReadOnlyList<DocumentKind> Sources,
string ReadPermission,
string WritePermission,
string ConfirmPermission,
string DeletePermission)
{
/// <summary>Whether the documents need a customer or supplier.</summary>
public bool NeedsParty => Direction != DocumentDirection.Internal;
/// <summary>Whether the documents have the given effect.</summary>
/// <param name="effect">The effect.</param>
/// <returns>Whether they have it.</returns>
public bool Has(DocumentEffects effect) => (Effects & effect) == effect;
/// <summary>Whether the documents fulfil the lines of documents of another kind.</summary>
/// <param name="source">The kind of the source.</param>
/// <returns>Whether a copy from it creates fulfilment links.</returns>
public bool Fulfils(DocumentKind source) => Sources.Contains(source);
}
/// <summary>The behaviour of every <see cref="DocumentKind"/>.</summary>
public static class DocumentBehaviors
{
private static readonly DocumentLineKind[] Commercial =
[DocumentLineKind.Item, DocumentLineKind.Free, DocumentLineKind.Description, DocumentLineKind.Expense, DocumentLineKind.Discount];
private static readonly DocumentLineKind[] Goods = [DocumentLineKind.Item, DocumentLineKind.Free, DocumentLineKind.Description];
private static readonly DocumentLineKind[] Stock = [DocumentLineKind.Item, DocumentLineKind.Description];
private static readonly DocumentKind[] SaleInvoices =
[
DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice,
DocumentKind.Fee,
];
private static readonly Dictionary<DocumentKind, DocumentBehavior> ByKind = Build().ToDictionary(b => b.Kind);
/// <summary>Every behaviour, in the order of <see cref="DocumentKind"/>.</summary>
public static IReadOnlyList<DocumentBehavior> All { get; } = [.. ByKind.Values.OrderBy(b => b.Kind)];
/// <summary>The behaviour of a kind.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The behaviour.</returns>
public static DocumentBehavior Of(DocumentKind kind) =>
ByKind.TryGetValue(kind, out var behavior) ? behavior : throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown document kind.");
/// <summary>The kinds kept in a family.</summary>
/// <param name="family">The family.</param>
/// <returns>The kinds.</returns>
public static IReadOnlyList<DocumentKind> KindsOf(DocumentFamily family) => [.. All.Where(b => b.Family == family).Select(b => b.Kind)];
private static IEnumerable<DocumentBehavior> Build()
{
const DocumentEffects Invoice = DocumentEffects.Ledger | DocumentEffects.Installments | DocumentEffects.EInvoice;
var quote = Permissions("sales.quote");
var order = Permissions("sales.order");
var delivery = Permissions("sales.delivery");
var invoice = new Perms("sales.invoice.read", "sales.invoice.write", "sales.invoice.issue", "sales.invoice.delete");
var proForma = new Perms("sales.invoice.read", "sales.invoice.write", "sales.invoice.write", "sales.invoice.delete");
var purchaseOrder = Permissions("purchases.order");
var purchaseInvoice = Permissions("purchases.invoice");
var entry = new Perms("inventory.entry.read", "inventory.entry.write", "inventory.entry.post", "inventory.entry.write");
yield return Make(DocumentKind.Quotation, DocumentFamily.SaleQuotation, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.None, Commercial, [], quote);
yield return Make(DocumentKind.SalesOrder, DocumentFamily.SaleOrder, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.Commitment, Commercial, [DocumentKind.Quotation], order);
yield return Make(DocumentKind.DeliveryNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.Inventory, Goods, [DocumentKind.SalesOrder], delivery);
yield return Make(DocumentKind.ImmediateInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.AccompanyingInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice | DocumentEffects.Inventory, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.DeferredInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.DeliveryNote], invoice);
yield return Make(DocumentKind.DownPaymentInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder], invoice);
yield return Make(DocumentKind.CreditNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, SaleInvoices, invoice);
yield return Make(DocumentKind.DebitNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, SaleInvoices, invoice);
yield return Make(DocumentKind.Fee, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.ProForma, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.None, Commercial, [DocumentKind.SalesOrder], proForma);
yield return Make(DocumentKind.SelfInvoice, DocumentFamily.SaleDocument, DocumentDirection.Purchase, DocumentLifecycle.Invoice, DocumentEffects.Ledger | DocumentEffects.EInvoice, Commercial, [DocumentKind.PurchaseInvoice], purchaseInvoice);
yield return Make(DocumentKind.PurchaseOrder, DocumentFamily.PurchaseOrder, DocumentDirection.Purchase, DocumentLifecycle.Order, DocumentEffects.Ordered, Commercial, [], purchaseOrder);
yield return Make(DocumentKind.PurchaseDeliveryNote, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Order, DocumentEffects.Inventory, Goods, [DocumentKind.PurchaseOrder], entry);
yield return Make(DocumentKind.PurchaseInvoice, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Simple, DocumentEffects.Ledger | DocumentEffects.Installments, Commercial, [DocumentKind.PurchaseOrder, DocumentKind.PurchaseDeliveryNote], purchaseInvoice);
yield return Make(DocumentKind.PurchaseCreditNote, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Simple, DocumentEffects.Ledger | DocumentEffects.Installments, Commercial, [DocumentKind.PurchaseInvoice], purchaseInvoice);
yield return Make(DocumentKind.InventoryEntry, DocumentFamily.InventoryDocument, DocumentDirection.Internal, DocumentLifecycle.Simple, DocumentEffects.Inventory, Stock, [], entry);
}
private static Perms Permissions(string area) => new(area + ".read", area + ".write", area + ".write", area + ".write");
private static DocumentBehavior Make(
DocumentKind kind, DocumentFamily family, DocumentDirection direction, DocumentLifecycle lifecycle, DocumentEffects effects,
DocumentLineKind[] lines, DocumentKind[] sources, Perms perms) =>
new(kind, family, direction, lifecycle, effects, lines, sources, perms.Read, perms.Write, perms.Confirm, perms.Delete);
private sealed record Perms(string Read, string Write, string Confirm, string Delete);
}