Files
Khaemhat/src/Khaemhat.Application/Documents/DocumentDefinition.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

98 lines
4.8 KiB
C#

using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>
/// A document type of the company with the behaviour of its kind (SPEC §11.3, ADR 0032): code, kind, direction,
/// numerator, warehouse reason, effects, sources for fulfilment, SDI type, journal template, VAT register, print
/// template.
/// </summary>
/// <param name="Type">The row of <c>document_types</c>.</param>
/// <param name="Behavior">The behaviour of its kind.</param>
public sealed record DocumentDefinition(DocumentType Type, DocumentBehavior Behavior)
{
/// <summary>The code of the type.</summary>
public string Code => Type.Code;
/// <summary>The kind.</summary>
public DocumentKind Kind => Behavior.Kind;
/// <summary>The family (tables).</summary>
public DocumentFamily Family => Behavior.Family;
/// <summary>The life cycle.</summary>
public DocumentLifecycle Lifecycle => Behavior.Lifecycle;
/// <summary>The action that confirms the documents: issue for invoices, confirm for the others.</summary>
public DocumentAction ConfirmAction => Lifecycle == DocumentLifecycle.Invoice ? DocumentAction.Issue : DocumentAction.Confirm;
}
/// <summary>Reads the definitions of the company's document types.</summary>
public static class DocumentDefinitionService
{
/// <summary>Error: the document type does not exist.</summary>
public const string TypeMissing = "document.type.missing";
/// <summary>Error: the document type has no kind.</summary>
public const string TypeWithoutKind = "document.type.no-kind";
/// <summary>Error: the document type is disabled.</summary>
public const string TypeDisabled = "document.type.disabled";
/// <summary>The definition of a document type.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="typeId">The type.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type is missing or has no kind.</exception>
public static async Task<DocumentDefinition> GetAsync(IUnitOfWork uow, long typeId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var type = await uow.Repository<DocumentType, long>().GetAsync(typeId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]);
return Of(type);
}
/// <summary>The definition of a document type by code.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="code">The code, such as <c>FI</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type is missing or has no kind.</exception>
public static async Task<DocumentDefinition> GetAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var normalized = (code ?? string.Empty).Trim().ToUpperInvariant();
var type = await uow.Repository<DocumentType, long>().FindAsync(Query.For<DocumentType>().Where(t => t.Code == normalized), cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeMissing]);
return Of(type);
}
/// <summary>The definitions of every usable type (enabled, with a kind), by code.</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definitions.</returns>
public static async Task<IReadOnlyList<DocumentDefinition>> ListAsync(IUnitOfWork uow, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var types = await uow.Repository<DocumentType, long>().ListAsync(Query.For<DocumentType>().OrderBy(t => t.Code), cancellationToken).ConfigureAwait(false);
return [.. types.Items.Where(t => !t.Disabled && t.DocumentKind is not null).Select(Of)];
}
/// <summary>The definition of a type row.</summary>
/// <param name="type">The row.</param>
/// <returns>The definition.</returns>
/// <exception cref="ValidationFailedException">The type has no kind.</exception>
public static DocumentDefinition Of(DocumentType type)
{
ArgumentNullException.ThrowIfNull(type);
return type.DocumentKind is { } kind
? new DocumentDefinition(type, DocumentBehaviors.Of(kind))
: throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + TypeWithoutKind]);
}
}