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,159 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Makes a new draft from an existing document (SPEC §11.3, ADR 0032): a duplicate of the same type, or a
/// transformation to another type of the same direction. When the new kind fulfils the old one (order to delivery note,
/// delivery note to deferred invoice) the lines take what is left to fulfil and remember where they come from; the
/// link is recorded when the new document is confirmed.
/// </summary>
public sealed class DocumentCopyService
{
private readonly DocumentEngine _engine;
private readonly PermissionService _permissions;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="engine">The engine.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="clock">The clock.</param>
public DocumentCopyService(DocumentEngine engine, PermissionService permissions, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(clock);
_engine = engine;
_permissions = permissions;
_clock = clock;
}
/// <summary>Copies a document into a new draft and saves it.</summary>
/// <param name="actor">Who copies.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family of the source.</param>
/// <param name="id">The source.</param>
/// <param name="targetTypeCode">The type of the new document, such as <c>DDT</c>.</param>
/// <param name="lineIds">The lines to copy; all when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new draft.</returns>
/// <exception cref="ValidationFailedException">The copy is not possible.</exception>
public async Task<DocumentRecord> CopyAsync(
Actor actor, string companyCode, DocumentFamily family, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var source = await _engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var company = CompanyCodes.Normalize(companyCode);
DocumentDefinition target;
await using (var uow = await _engine.Factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
target = await DocumentDefinitionService.GetAsync(uow, targetTypeCode, cancellationToken).ConfigureAwait(false);
}
await _permissions.DemandAsync(actor, target.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
var sourceBehavior = DocumentBehaviors.Of(source.Header.Kind);
DocumentStateMachine.Apply(sourceBehavior.Lifecycle, source.Header.Status, DocumentAction.Copy);
if (sourceBehavior.Direction != target.Behavior.Direction)
{
throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.CopyDirection]);
}
var fulfils = target.Behavior.Fulfils(source.Header.Kind);
if (fulfils && (source.Header.Status is DocumentStatus.Draft or DocumentStatus.Closed or DocumentStatus.Cancelled))
{
throw new ValidationFailedException([":" + DocumentErrors.CopySourceNotOpen]);
}
var copy = new DocumentRecord { Family = target.Family, Header = Header(source.Header, target, DateOnly.FromDateTime(_clock.GetLocalNow().DateTime)) };
var wanted = lineIds is { Count: > 0 } ? lineIds.ToHashSet() : null;
foreach (var line in source.Lines.Where(l => wanted is null || wanted.Contains(l.Id)))
{
if (!target.Behavior.Lines.Contains(line.Kind))
{
continue;
}
var quantity = line.Quantity;
if (fulfils && DocumentLine.CarriesQuantity(line.Kind))
{
quantity = line.Residual;
if (quantity <= 0)
{
continue;
}
}
copy.Lines.Add(Line(line, target.Family, quantity, fulfils ? source.Family : null));
}
if (fulfils && !copy.Lines.Any(l => l.SourceLineId is not null))
{
throw new ValidationFailedException([":" + DocumentErrors.CopyNothingLeft]);
}
return await _engine.SaveAsync(actor, company, copy, cancellationToken).ConfigureAwait(false);
}
private static DocumentHeader Header(DocumentHeader source, DocumentDefinition target, DateOnly today)
{
var header = DocumentStores.Of(target.Family).NewHeader();
header.DocumentTypeId = target.Type.Id;
header.Kind = target.Kind;
header.Status = DocumentStatus.Draft;
header.DocumentDate = today;
header.Year = today.Year;
header.PartyId = source.PartyId;
header.DestinationId = source.DestinationId;
header.CurrencyCode = source.CurrencyCode;
header.ExchangeRate = source.ExchangeRate;
header.PriceListId = source.PriceListId;
header.PaymentTermId = source.PaymentTermId;
header.PaymentMethodId = source.PaymentMethodId;
header.BankAccountId = source.BankAccountId;
header.SalespersonId = source.SalespersonId;
header.WarehouseId = source.WarehouseId;
header.InventoryReasonId = target.Type.InventoryReasonId ?? source.InventoryReasonId;
header.TransportReasonId = source.TransportReasonId;
header.ShippingTermId = source.ShippingTermId;
header.CarrierId = source.CarrierId;
header.GoodsAppearanceId = source.GoodsAppearanceId;
header.DeliveryDate = source.DeliveryDate;
header.FooterDiscount = source.FooterDiscount;
header.Notes = source.Notes;
return header;
}
private static DocumentLine Line(DocumentLine source, DocumentFamily family, decimal quantity, DocumentFamily? sourceFamily)
{
var line = DocumentStores.Of(family).NewLine();
line.Kind = source.Kind;
line.ItemId = source.ItemId;
line.Description = source.Description;
line.UnitOfMeasureId = source.UnitOfMeasureId;
line.Quantity = quantity;
line.Price = source.Price;
line.PriceSource = source.PriceSource;
line.DiscountFormula = source.DiscountFormula;
line.TaxCodeId = source.TaxCodeId;
line.TaxableAmount = source.Quantity == 0 || quantity == source.Quantity
? source.TaxableAmount
: Math.Round(source.TaxableAmount * quantity / source.Quantity, 2, MidpointRounding.AwayFromZero);
line.WarehouseId = source.WarehouseId;
line.DeliveryDate = source.DeliveryDate;
line.AccountCode = source.AccountCode;
line.CostCenterId = source.CostCenterId;
line.JobId = source.JobId;
line.Notes = source.Notes;
if (sourceFamily is not null && DocumentLine.CarriesQuantity(source.Kind))
{
line.SourceFamily = sourceFamily;
line.SourceLineId = source.Id;
}
return line;
}
}
@@ -0,0 +1,97 @@
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]);
}
}
@@ -0,0 +1,746 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A document with its lines, whatever the family.</summary>
public sealed class DocumentRecord
{
/// <summary>The family.</summary>
public DocumentFamily Family { get; init; }
/// <summary>The header.</summary>
public required DocumentHeader Header { get; init; }
/// <summary>The lines, in order.</summary>
public List<DocumentLine> Lines { get; init; } = [];
}
/// <summary>The error codes of the document engine; the interface translates them (<c>Documents.json</c>).</summary>
public static class DocumentErrors
{
/// <summary>The document does not exist.</summary>
public const string NotFound = "document.not-found";
/// <summary>A customer or supplier is needed.</summary>
public const string PartyRequired = "document.party.required";
/// <summary>The date is missing.</summary>
public const string DateRequired = "document.date.required";
/// <summary>The date of a numbered document cannot change.</summary>
public const string DateNumbered = "document.date.numbered";
/// <summary>The type belongs to another family of documents.</summary>
public const string TypeFamily = "document.type.family";
/// <summary>The type of a confirmed document cannot change.</summary>
public const string TypeLocked = "document.type.locked";
/// <summary>The document has no lines.</summary>
public const string LinesRequired = "document.lines.required";
/// <summary>The kind of line is not accepted by the document.</summary>
public const string LineKindNotAllowed = "document.line.kind-not-allowed";
/// <summary>A line without description.</summary>
public const string LineDescriptionRequired = "document.line.description-required";
/// <summary>An item line without item.</summary>
public const string LineItemRequired = "document.line.item-required";
/// <summary>A quantity below what later documents already fulfilled.</summary>
public const string LineBelowFulfilled = "document.line.below-fulfilled";
/// <summary>A line fulfilled by later documents cannot be removed.</summary>
public const string LineFulfilledRemoved = "document.line.fulfilled-removed";
/// <summary>The line to fulfil does not exist or belongs to a kind the document does not fulfil.</summary>
public const string LineSourceInvalid = "document.line.source-invalid";
/// <summary>A cancelled invoice needs a reason.</summary>
public const string CancelReasonRequired = "document.cancel.reason-required";
/// <summary>Later documents fulfil this one: cancel them first.</summary>
public const string CancelHasFollowers = "document.cancel.has-followers";
/// <summary>A copy changes direction (sale to purchase).</summary>
public const string CopyDirection = "document.copy.direction";
/// <summary>Nothing is left to fulfil.</summary>
public const string CopyNothingLeft = "document.copy.nothing-left";
/// <summary>A closed or cancelled document cannot be fulfilled.</summary>
public const string CopySourceNotOpen = "document.copy.source-not-open";
}
/// <summary>
/// The document engine (SPEC §11.3, ADR 0032): one implementation of create, save, confirm or issue, cancel, close,
/// reopen and delete for every family, with the numbering and the fulfilment links. The typed entry points are
/// <see cref="DocumentService{THeader, TLine}"/> and <see cref="DocumentCopyService"/>.
/// </summary>
public sealed class DocumentEngine
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly FiscalYearService _fiscal;
private readonly TimeProvider _clock;
/// <summary>Creates the engine.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="audit">The history.</param>
/// <param name="fiscal">The fiscal calendar (open periods).</param>
/// <param name="clock">The clock.</param>
public DocumentEngine(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, FiscalYearService fiscal, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(fiscal);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_audit = audit;
_fiscal = fiscal;
_clock = clock;
}
internal IUnitOfWorkFactory Factory => _factory;
internal AuditTrail Audit => _audit;
/// <summary>The definitions of the usable document types.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The definitions the actor can see.</returns>
public async Task<IReadOnlyList<DocumentDefinition>> DefinitionsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var result = new List<DocumentDefinition>();
foreach (var definition in await DocumentDefinitionService.ListAsync(uow, cancellationToken).ConfigureAwait(false))
{
if ((await _permissions.CheckAsync(actor, definition.Behavior.ReadPermission, cancellationToken).ConfigureAwait(false)).Allowed)
{
result.Add(definition);
}
}
return result;
}
/// <summary>A new draft of a type, not saved: today's date and the defaults of the type.</summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="typeCode">The document type, such as <c>FI</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentRecord> NewAsync(Actor actor, string companyCode, string typeCode, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var definition = await DocumentDefinitionService.GetAsync(uow, typeCode, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
var header = DocumentStores.Of(definition.Family).NewHeader();
header.DocumentTypeId = definition.Type.Id;
header.Kind = definition.Kind;
header.Status = DocumentStatus.Draft;
header.DocumentDate = Today();
header.Year = header.DocumentDate.Year;
header.InventoryReasonId = definition.Type.InventoryReasonId;
return new DocumentRecord { Family = definition.Family, Header = header };
}
/// <summary>Reads a document.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document, if any.</returns>
public async Task<DocumentRecord?> GetAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
if (record is not null)
{
await _permissions.DemandAsync(actor, DocumentBehaviors.Of(record.Header.Kind).ReadPermission, cancellationToken).ConfigureAwait(false);
}
return record;
}
/// <summary>
/// Saves a draft (or the lines of a confirmed order still open): the engine keeps the number, state and other fields
/// it owns, numbers the lines and recomputes the fulfilment of a confirmed order.
/// </summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as saved.</returns>
/// <exception cref="ValidationFailedException">The document breaks a rule.</exception>
/// <exception cref="InvalidDocumentActionException">The state does not admit changes.</exception>
public async Task<DocumentRecord> SaveAsync(Actor actor, string companyCode, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = Company(actor, companyCode);
var store = DocumentStores.Of(record.Family);
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var header = record.Header;
var before = header.Id == 0 ? null : await LoadAsync(uow, record.Family, header.Id, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([":" + DocumentErrors.NotFound]);
var definition = await DocumentDefinitionService.GetAsync(uow, before?.Header.DocumentTypeId ?? header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.WritePermission, cancellationToken).ConfigureAwait(false);
if (before is null)
{
header.Kind = definition.Kind;
header.Status = DocumentStatus.Draft;
Release(header);
}
else
{
DocumentStateMachine.Apply(definition.Lifecycle, before.Header.Status, DocumentAction.Edit);
Keep(header, before.Header);
}
var errors = Check(definition, record, before);
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
id = await WriteAsync(uow, store, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
if (before is not null && DocumentStateMachine.IsInForce(header.Status))
{
await RefreshFulfillmentAsync(uow, record.Family, id, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, record.Family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
/// <summary>
/// Confirms a document, or issues an invoice: checks it, numbers it, records the fulfilment of the documents its
/// lines come from.
/// </summary>
/// <param name="actor">Who confirms.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as confirmed.</returns>
public async Task<DocumentRecord> ConfirmAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
// The open period is read outside the transaction (the calendar has its own cache and connection).
var draft = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = await DocumentDefinitionService.GetAsync(uow, draft.Header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.ConfirmPermission, cancellationToken).ConfigureAwait(false);
DocumentStateMachine.Apply(definition.Lifecycle, draft.Header.Status, definition.ConfirmAction);
if (definition.Behavior.Has(DocumentEffects.Ledger))
{
await _fiscal.DemandOpenAsync(company, draft.Header.DocumentDate, PeriodUse.Vat, cancellationToken).ConfigureAwait(false);
}
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, definition.ConfirmAction);
var errors = Check(definition, record, record);
if (record.Lines.Count == 0)
{
errors.Add("Lines:" + DocumentErrors.LinesRequired);
}
if (errors.Count > 0 || record.Header.DocumentDate != draft.Header.DocumentDate)
{
throw errors.Count > 0 ? new ValidationFailedException(errors) : new Core.Common.ConcurrencyException();
}
var header = record.Header;
var before = header.Clone();
if (definition.Type.NumeratorId is { } numeratorId)
{
var number = await DocumentNumberingService.NextAsync(uow, numeratorId, header.DocumentDate, cancellationToken).ConfigureAwait(false);
header.NumeratorId = number.Numerator.Id;
header.Section = number.Numerator.Section;
header.Number = number.Number;
header.DocumentNumber = number.Text;
}
header.Year = header.DocumentDate.Year;
header.Status = next;
header.ConfirmedAt = _clock.GetUtcNow().UtcDateTime;
header.ConfirmedBy = actor.UserName;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, actor.UserName, cancellationToken).ConfigureAwait(false);
await LinkAsync(uow, definition, record, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
/// <summary>
/// Cancels a document: the number stays, the fulfilment it recorded is given back. An invoice needs a reason and is
/// cancelled only before its file reaches the exchange system (or after a rejection).
/// </summary>
/// <param name="actor">Who cancels.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as cancelled.</returns>
public Task<DocumentRecord> CancelAsync(Actor actor, string companyCode, DocumentFamily family, long id, string? reason, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Cancel, async (uow, definition, record, ct) =>
{
var text = reason?.Trim();
if (definition.Lifecycle == DocumentLifecycle.Invoice && string.IsNullOrEmpty(text))
{
throw new ValidationFailedException([nameof(DocumentHeader.CancelReason) + ":" + DocumentErrors.CancelReasonRequired]);
}
if ((await LinksFromAsync(uow, family, id, ct).ConfigureAwait(false)).Count > 0)
{
throw new ValidationFailedException([":" + DocumentErrors.CancelHasFollowers]);
}
record.Header.CancelReason = string.IsNullOrEmpty(text) ? null : text[..Math.Min(text.Length, 200)];
record.Header.CancelledAt = _clock.GetUtcNow().UtcDateTime;
},
(uow, record, user, ct) => UnlinkAsync(uow, family, id, user, ct),
cancellationToken);
/// <summary>Closes what is left to fulfil of an order, quotation, delivery note or pro forma.</summary>
/// <param name="actor">Who closes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as closed.</returns>
public Task<DocumentRecord> CloseAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Close, null, null, cancellationToken);
/// <summary>Reopens a closed document: its state comes back from the fulfilment of its lines.</summary>
/// <param name="actor">Who reopens.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as reopened.</returns>
public Task<DocumentRecord> ReopenAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
ChangeStateAsync(actor, companyCode, family, id, DocumentAction.Reopen, null,
(uow, record, user, ct) => RefreshFulfillmentAsync(uow, family, id, user, ct), cancellationToken);
/// <summary>
/// Records a step of the electronic invoice (file generated, sent, delivered, rejected, not delivered); the module
/// of the electronic invoice (M8) calls it.
/// </summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="action">The step.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public Task<DocumentRecord> RecordExchangeAsync(Actor actor, string companyCode, DocumentFamily family, long id, DocumentAction action, CancellationToken cancellationToken = default)
{
if (action is not (DocumentAction.GenerateXml or DocumentAction.Send or DocumentAction.MarkDelivered or DocumentAction.MarkRejected or DocumentAction.MarkNotDelivered))
{
throw new ArgumentOutOfRangeException(nameof(action), action, "Not a step of the electronic invoice.");
}
return ChangeStateAsync(actor, companyCode, family, id, action, (uow, definition, record, ct) =>
{
if (action == DocumentAction.GenerateXml)
{
record.Header.XmlGenerated = true;
}
return Task.CompletedTask;
}, null, cancellationToken);
}
/// <summary>Deletes a draft.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = DocumentBehaviors.Of(record.Header.Kind);
await _permissions.DemandAsync(actor, definition.DeletePermission, cancellationToken).ConfigureAwait(false);
DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, DocumentAction.Delete);
await store.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Delete, id, record.Header, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The actions the state of a document admits for an actor.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The actions.</returns>
public async Task<IReadOnlyList<DocumentAction>> ActionsAsync(Actor actor, DocumentRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var behavior = DocumentBehaviors.Of(record.Header.Kind);
var result = new List<DocumentAction>();
foreach (var action in DocumentStateMachine.Actions(behavior.Lifecycle, record.Header.Status))
{
var permission = action switch
{
DocumentAction.Edit or DocumentAction.Copy => behavior.WritePermission,
DocumentAction.Delete => behavior.DeletePermission,
_ => behavior.ConfirmPermission,
};
if ((await _permissions.CheckAsync(actor, permission, cancellationToken).ConfigureAwait(false)).Allowed)
{
result.Add(action);
}
}
return result;
}
internal static async Task<DocumentRecord?> LoadAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
if (await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false) is not { } header)
{
return null;
}
return new DocumentRecord { Family = family, Header = header, Lines = await store.LinesAsync(uow, id, cancellationToken).ConfigureAwait(false) };
}
/// <summary>Checks a document against its definition; <paramref name="before"/> is the stored one.</summary>
internal static List<string> Check(DocumentDefinition definition, DocumentRecord record, DocumentRecord? before)
{
var errors = new List<string>();
var header = record.Header;
if (definition.Family != record.Family)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeFamily);
}
if (before is not null && header.DocumentTypeId != before.Header.DocumentTypeId)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeLocked);
}
if (definition.Type.Disabled && before is null)
{
errors.Add(nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentDefinitionService.TypeDisabled);
}
if (definition.Behavior.NeedsParty && header.PartyId is null)
{
errors.Add(nameof(DocumentHeader.PartyId) + ":" + DocumentErrors.PartyRequired);
}
if (header.DocumentDate == default)
{
errors.Add(nameof(DocumentHeader.DocumentDate) + ":" + DocumentErrors.DateRequired);
}
else if (before?.Header.Number is not null && header.DocumentDate != before.Header.DocumentDate)
{
errors.Add(nameof(DocumentHeader.DocumentDate) + ":" + DocumentErrors.DateNumbered);
}
var stored = before?.Lines.ToDictionary(l => l.Id) ?? [];
for (var i = 0; i < record.Lines.Count; i++)
{
var line = record.Lines[i];
var field = "Lines." + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + ".";
if (!definition.Behavior.Lines.Contains(line.Kind))
{
errors.Add(field + nameof(DocumentLine.Kind) + ":" + DocumentErrors.LineKindNotAllowed);
}
if (string.IsNullOrWhiteSpace(line.Description))
{
errors.Add(field + nameof(DocumentLine.Description) + ":" + DocumentErrors.LineDescriptionRequired);
}
if (line.Kind == DocumentLineKind.Item && line.ItemId is null)
{
errors.Add(field + nameof(DocumentLine.ItemId) + ":" + DocumentErrors.LineItemRequired);
}
if (line.Id != 0 && stored.TryGetValue(line.Id, out var old) && old.FulfilledQuantity > 0 && line.Quantity < old.FulfilledQuantity)
{
errors.Add(field + nameof(DocumentLine.Quantity) + ":" + DocumentErrors.LineBelowFulfilled);
}
}
var kept = record.Lines.Where(l => l.Id != 0).Select(l => l.Id).ToHashSet();
if (before is not null && before.Lines.Any(l => !kept.Contains(l.Id) && l.FulfilledQuantity > 0))
{
errors.Add("Lines:" + DocumentErrors.LineFulfilledRemoved);
}
return errors;
}
/// <summary>Writes the header and replaces the lines of a draft or open document.</summary>
internal async Task<long> WriteAsync(IUnitOfWork uow, IDocumentStore store, DocumentRecord record, DocumentRecord? before, string userName, CancellationToken cancellationToken)
{
var header = record.Header;
if (before is null)
{
header.Year = header.DocumentDate.Year;
await store.InsertAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Insert, header.Id, null, header, userName, cancellationToken).ConfigureAwait(false);
}
else
{
if (header.Number is null)
{
header.Year = header.DocumentDate.Year;
}
header.RowVersion = before.Header.RowVersion;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, header.Id, before.Header, header, userName, cancellationToken).ConfigureAwait(false);
}
var id = header.Id;
var previous = before?.Lines.ToDictionary(l => l.Id) ?? [];
var kept = record.Lines.Where(l => l.Id != 0 && previous.ContainsKey(l.Id)).Select(l => l.Id).ToHashSet();
foreach (var old in previous.Values.Where(l => !kept.Contains(l.Id)))
{
await store.DeleteLineAsync(uow, old.Id, cancellationToken).ConfigureAwait(false);
}
for (var i = 0; i < record.Lines.Count; i++)
{
var line = record.Lines[i];
line.DocumentId = id;
line.LineNumber = i + 1;
line.SortOrder = i + 1;
if (line.Id != 0 && previous.TryGetValue(line.Id, out var old))
{
// The fulfilment is the engine's: what the links say, not what the screen sends.
line.FulfilledQuantity = old.FulfilledQuantity;
line.SourceFamily = old.SourceFamily;
line.SourceLineId = old.SourceLineId;
line.RowVersion = old.RowVersion;
await store.UpdateLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
else
{
line.Id = 0;
line.FulfilledQuantity = 0;
if (line.SourceLineId is null || line.SourceFamily is null)
{
line.SourceLineId = null;
line.SourceFamily = null;
}
await store.InsertLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
}
return id;
}
private async Task<DocumentRecord> ChangeStateAsync(
Actor actor,
string companyCode,
DocumentFamily family,
long id,
DocumentAction action,
Func<IUnitOfWork, DocumentDefinition, DocumentRecord, CancellationToken, Task>? before,
Func<IUnitOfWork, DocumentRecord, string, CancellationToken, Task>? after,
CancellationToken cancellationToken)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var definition = await DocumentDefinitionService.GetAsync(uow, record.Header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
await _permissions.DemandAsync(actor, definition.Behavior.ConfirmPermission, cancellationToken).ConfigureAwait(false);
var next = DocumentStateMachine.Apply(definition.Lifecycle, record.Header.Status, action);
var old = record.Header.Clone();
if (before is not null)
{
await before(uow, definition, record, cancellationToken).ConfigureAwait(false);
}
record.Header.Status = next;
await store.UpdateAsync(uow, record.Header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, record.Header, actor.UserName, cancellationToken).ConfigureAwait(false);
if (after is not null)
{
await after(uow, record, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
// Records the links of a confirmed document towards the lines it fulfils, then the fulfilment of those documents.
private async Task LinkAsync(IUnitOfWork uow, DocumentDefinition definition, DocumentRecord record, string userName, CancellationToken cancellationToken)
{
var links = uow.Repository<DocumentLink, long>();
var touched = new HashSet<(DocumentFamily, long)>();
foreach (var line in record.Lines.Where(l => l.SourceLineId is not null && l.SourceFamily is not null))
{
var sourceFamily = line.SourceFamily!.Value;
var source = await DocumentStores.Of(sourceFamily).GetLineAsync(uow, line.SourceLineId!.Value, cancellationToken).ConfigureAwait(false);
var sourceHeader = source is null ? null : await DocumentStores.Of(sourceFamily).GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false);
if (source is null || sourceHeader is null || !definition.Behavior.Fulfils(sourceHeader.Kind) || !DocumentStateMachine.IsInForce(sourceHeader.Status))
{
throw new ValidationFailedException(["Lines." + (line.LineNumber - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) + ".SourceLineId:" + DocumentErrors.LineSourceInvalid]);
}
await links.InsertAsync(
new DocumentLink
{
TargetFamily = record.Family,
TargetDocumentId = record.Header.Id,
TargetLineId = line.Id,
SourceFamily = sourceFamily,
SourceDocumentId = source.DocumentId,
SourceLineId = source.Id,
Quantity = line.Quantity,
},
cancellationToken).ConfigureAwait(false);
touched.Add((sourceFamily, source.DocumentId));
}
foreach (var (family, documentId) in touched)
{
await RefreshFulfillmentAsync(uow, family, documentId, userName, cancellationToken).ConfigureAwait(false);
}
}
// Removes the links of a cancelled document and gives the quantities back to the documents it fulfilled.
private async Task UnlinkAsync(IUnitOfWork uow, DocumentFamily family, long id, string userName, CancellationToken cancellationToken)
{
var links = uow.Repository<DocumentLink, long>();
var mine = (await links.ListAsync(Query.For<DocumentLink>().Where(l => l.TargetFamily == family && l.TargetDocumentId == id), cancellationToken).ConfigureAwait(false)).Items;
foreach (var link in mine)
{
await links.DeleteAsync(link.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var source in mine.Select(l => (l.SourceFamily, l.SourceDocumentId)).Distinct())
{
await RefreshFulfillmentAsync(uow, source.SourceFamily, source.SourceDocumentId, userName, cancellationToken).ConfigureAwait(false);
}
}
private static async Task<IReadOnlyList<DocumentLink>> LinksFromAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
(await uow.Repository<DocumentLink, long>().ListAsync(Query.For<DocumentLink>().Where(l => l.SourceFamily == family && l.SourceDocumentId == id), cancellationToken)
.ConfigureAwait(false)).Items;
// The quantities fulfilled of each line from the links, then the state of the document from its lines.
private async Task RefreshFulfillmentAsync(IUnitOfWork uow, DocumentFamily family, long id, string userName, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
var record = await LoadAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
if (record is null)
{
return;
}
var links = await LinksFromAsync(uow, family, id, cancellationToken).ConfigureAwait(false);
foreach (var line in FulfillmentCalculator.Apply(record.Lines, links))
{
await store.UpdateLineAsync(uow, line, cancellationToken).ConfigureAwait(false);
}
var header = record.Header;
var lifecycle = DocumentBehaviors.Of(header.Kind).Lifecycle;
var status = DocumentStateMachine.AfterFulfillment(lifecycle, header.Status, FulfillmentCalculator.StateOf(record.Lines));
if (status != header.Status)
{
var before = header.Clone();
header.Status = status;
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, before, header, userName, cancellationToken).ConfigureAwait(false);
}
}
// The fields the engine owns keep their stored value whatever the screen sends.
private static void Keep(DocumentHeader header, DocumentHeader stored)
{
header.Kind = stored.Kind;
header.Status = stored.Status;
header.NumeratorId = stored.NumeratorId;
header.Section = stored.Section;
header.Number = stored.Number;
header.DocumentNumber = stored.DocumentNumber;
header.Year = stored.Year;
header.ConfirmedAt = stored.ConfirmedAt;
header.ConfirmedBy = stored.ConfirmedBy;
header.CancelledAt = stored.CancelledAt;
header.CancelReason = stored.CancelReason;
header.XmlGenerated = stored.XmlGenerated;
header.Posted = stored.Posted;
header.GlEntryId = stored.GlEntryId;
header.InstallmentsGenerated = stored.InstallmentsGenerated;
header.IsDemo = stored.IsDemo;
}
// A new draft has no number and no history of states.
private static void Release(DocumentHeader header)
{
header.Id = 0;
header.NumeratorId = null;
header.Number = null;
header.DocumentNumber = null;
header.ConfirmedAt = null;
header.ConfirmedBy = null;
header.CancelledAt = null;
header.CancelReason = null;
header.XmlGenerated = false;
header.Posted = false;
header.GlEntryId = null;
header.InstallmentsGenerated = false;
}
private static string Company(Actor actor, string companyCode)
{
ArgumentNullException.ThrowIfNull(actor);
var company = CompanyCodes.Normalize(companyCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
return company;
}
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
}
@@ -0,0 +1,172 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A number given to a document.</summary>
/// <param name="Numerator">The numerator row (code and year) that gave it, already updated.</param>
/// <param name="Number">The progressive number.</param>
/// <param name="Text">The number as printed.</param>
public sealed record AssignedNumber(DocumentNumerator Numerator, long Number, string Text);
/// <summary>
/// Numbers documents (SPEC §11.3, ADR 0032): inside the transaction that confirms the document, under the lock of the
/// numerator and year, so that two confirmations never get the same number and a rollback gives the number back.
/// </summary>
public static class DocumentNumberingService
{
/// <summary>Error: on a numerator without gaps the date precedes the last document numbered.</summary>
public const string DateBeforeLast = "document.number.date-before-last";
/// <summary>Error: the numerator of the document type does not exist.</summary>
public const string NumeratorMissing = "document.number.numerator-missing";
/// <summary>Error: the numerator is disabled.</summary>
public const string NumeratorDisabled = "document.number.numerator-disabled";
/// <summary>Error: the formatted number is longer than the column.</summary>
public const string NumberTooLong = "document.number.too-long";
/// <summary>The longest number as printed.</summary>
public const int MaxLength = 30;
/// <summary>The lock that serializes the numbering of a numerator in a year.</summary>
/// <param name="code">The numerator code.</param>
/// <param name="year">The year.</param>
/// <returns>The lock key.</returns>
public static string LockKey(string code, int year) => "numerator:" + code + ":" + year.ToString(CultureInfo.InvariantCulture);
/// <summary>
/// Gives the next number of a numerator for a date. The numerator row of the document type names the code; the
/// number comes from the row of the same code for the year of the date, created from the latest one when missing.
/// </summary>
/// <param name="uow">A company unit of work inside a transaction.</param>
/// <param name="numeratorId">The numerator of the document type.</param>
/// <param name="date">The date of the document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number.</returns>
/// <exception cref="ValidationFailedException">The numerator is missing or disabled, or the date is out of sequence.</exception>
public static async Task<AssignedNumber> NextAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerators = uow.Repository<DocumentNumerator, long>();
var template = await numerators.GetAsync(numeratorId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([NumeratorMissing]);
await uow.AcquireLockAsync(LockKey(template.Code, date.Year), cancellationToken).ConfigureAwait(false);
// Read again under the lock: another transaction may have numbered (or created the year) meanwhile.
var numerator = await ForYearAsync(uow, template, date.Year, cancellationToken).ConfigureAwait(false);
if (numerator.Disabled)
{
throw new ValidationFailedException([NumeratorDisabled]);
}
if (!numerator.GapsAllowed && numerator.LastDate is { } last && date < last)
{
throw new ValidationFailedException([DateBeforeLast]);
}
var number = numerator.LastNumber + 1;
var text = DocumentNumberFormat.Apply(numerator.Format, number, numerator.Year, numerator.Prefix, numerator.Section);
if (text.Length > MaxLength)
{
throw new ValidationFailedException([NumberTooLong]);
}
numerator.LastNumber = number;
if (numerator.LastDate is null || date > numerator.LastDate)
{
numerator.LastDate = date;
}
await numerators.UpdateAsync(numerator, cancellationToken).ConfigureAwait(false);
return new AssignedNumber(numerator, number, text);
}
/// <summary>What the next number would be, without giving it (the preview of a draft).</summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="numeratorId">The numerator of the document type.</param>
/// <param name="date">The date.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number as printed, or <see langword="null"/> when the numerator is missing.</returns>
public static async Task<string?> PreviewAsync(IUnitOfWork uow, long numeratorId, DateOnly date, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerators = uow.Repository<DocumentNumerator, long>();
if (await numerators.GetAsync(numeratorId, cancellationToken).ConfigureAwait(false) is not { } template)
{
return null;
}
var row = template.Year == date.Year
? template
: await numerators.FindAsync(Query.For<DocumentNumerator>().Where(n => n.Code == template.Code && n.Year == date.Year), cancellationToken).ConfigureAwait(false);
var source = row ?? template;
return DocumentNumberFormat.Apply(source.Format, (row?.LastNumber ?? 0) + 1, date.Year, source.Prefix, source.Section);
}
/// <summary>
/// The numbers missing between 1 and the last number given, over every family of documents: on a numerator without
/// gaps the list must be empty.
/// </summary>
/// <param name="uow">A company unit of work.</param>
/// <param name="numeratorId">The numerator row (code and year).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The missing numbers, in order.</returns>
public static async Task<IReadOnlyList<long>> FindGapsAsync(IUnitOfWork uow, long numeratorId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(uow);
var numerator = await uow.Repository<DocumentNumerator, long>().GetAsync(numeratorId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([NumeratorMissing]);
var used = new HashSet<long>();
foreach (var store in DocumentStores.All)
{
var sql = SqlFragment.Literal("SELECT number FROM " + store.HeaderTable + " WHERE ") + SqlFragment.Of($"numerator_id = {numeratorId} AND number IS NOT NULL");
used.UnionWith(await uow.QueryAsync<long>(sql, cancellationToken).ConfigureAwait(false));
}
var missing = new List<long>();
for (var n = 1L; n <= numerator.LastNumber; n++)
{
if (!used.Contains(n))
{
missing.Add(n);
}
}
return missing;
}
private static async Task<DocumentNumerator> ForYearAsync(IUnitOfWork uow, DocumentNumerator template, int year, CancellationToken cancellationToken)
{
var numerators = uow.Repository<DocumentNumerator, long>();
var code = template.Code;
if (await numerators.FindAsync(Query.For<DocumentNumerator>().Where(n => n.Code == code && n.Year == year), cancellationToken).ConfigureAwait(false) is { } row)
{
return row;
}
// A new year: the same rules as the latest year of the code, starting from one.
var found = (await numerators.ListAsync(Query.For<DocumentNumerator>().Where(n => n.Code == code).OrderByDescending(n => n.Year).Take(1), cancellationToken)
.ConfigureAwait(false)).Items;
var latest = found.Count > 0 ? found[0] : template;
var created = new DocumentNumerator
{
Code = latest.Code,
Description = latest.Description,
Kind = latest.Kind,
Section = latest.Section,
Year = year,
Prefix = latest.Prefix,
Format = latest.Format,
GapsAllowed = latest.GapsAllowed,
Disabled = latest.Disabled,
};
await numerators.InsertAsync(created, cancellationToken).ConfigureAwait(false);
return created;
}
}
@@ -0,0 +1,149 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
namespace Khaemhat.Application.Documents;
/// <summary>A document of one family, with its lines.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
public sealed class DocumentRecord<THeader, TLine>
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
/// <summary>The header.</summary>
public THeader Header { get; set; } = new();
/// <summary>The lines, in order.</summary>
public List<TLine> Lines { get; set; } = [];
}
/// <summary>
/// The document engine for one family (SPEC §11.3): create, read, save, confirm or issue, cancel, close, reopen,
/// delete and copy, with the types of that family. The screens of quotations, orders, invoices use one each.
/// </summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
public sealed class DocumentService<THeader, TLine>
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
private readonly DocumentEngine _engine;
private readonly DocumentCopyService _copies;
/// <summary>Creates the service.</summary>
/// <param name="engine">The engine.</param>
/// <param name="copies">The copies.</param>
public DocumentService(DocumentEngine engine, DocumentCopyService copies)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(copies);
_engine = engine;
_copies = copies;
}
/// <summary>The family.</summary>
public DocumentFamily Family => FamilyOfHeader;
private static readonly DocumentFamily FamilyOfHeader = DocumentStores.FamilyOf<THeader>();
/// <summary>A new draft of a type of this family, not saved.</summary>
/// <param name="actor">Who creates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="typeCode">The document type.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentRecord<THeader, TLine>> NewAsync(Actor actor, string companyCode, string typeCode, CancellationToken cancellationToken = default)
{
var record = await _engine.NewAsync(actor, companyCode, typeCode, cancellationToken).ConfigureAwait(false);
if (record.Family != Family)
{
throw new ValidationFailedException([nameof(DocumentHeader.DocumentTypeId) + ":" + DocumentErrors.TypeFamily]);
}
return Typed(record);
}
/// <summary>Reads a document.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document, if any.</returns>
public async Task<DocumentRecord<THeader, TLine>?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
await _engine.GetAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false) is { } record ? Typed(record) : null;
/// <summary>Saves a draft, or an order still open.</summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document as saved.</returns>
public async Task<DocumentRecord<THeader, TLine>> SaveAsync(Actor actor, string companyCode, DocumentRecord<THeader, TLine> record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var saved = await _engine.SaveAsync(actor, companyCode, new DocumentRecord { Family = Family, Header = record.Header, Lines = [.. record.Lines] }, cancellationToken)
.ConfigureAwait(false);
return Typed(saved);
}
/// <summary>Confirms a document, or issues an invoice.</summary>
/// <param name="actor">Who confirms.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> ConfirmAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.ConfirmAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Cancels a document.</summary>
/// <param name="actor">Who cancels.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="reason">Why (required for invoices).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> CancelAsync(Actor actor, string companyCode, long id, string? reason, CancellationToken cancellationToken = default) =>
Typed(await _engine.CancelAsync(actor, companyCode, Family, id, reason, cancellationToken).ConfigureAwait(false));
/// <summary>Closes what is left to fulfil.</summary>
/// <param name="actor">Who closes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> CloseAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.CloseAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Reopens a closed document.</summary>
/// <param name="actor">Who reopens.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The document.</returns>
public async Task<DocumentRecord<THeader, TLine>> ReopenAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
Typed(await _engine.ReopenAsync(actor, companyCode, Family, id, cancellationToken).ConfigureAwait(false));
/// <summary>Deletes a draft.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) =>
_engine.DeleteAsync(actor, companyCode, Family, id, cancellationToken);
/// <summary>Copies a document of this family into a new draft of any type of the same direction.</summary>
/// <param name="actor">Who copies.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The source.</param>
/// <param name="targetTypeCode">The type of the new document.</param>
/// <param name="lineIds">The lines to copy; all when empty.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new draft, in its own family.</returns>
public Task<DocumentRecord> CopyAsync(
Actor actor, string companyCode, long id, string targetTypeCode, IReadOnlyCollection<long>? lineIds = null, CancellationToken cancellationToken = default) =>
_copies.CopyAsync(actor, companyCode, Family, id, targetTypeCode, lineIds, cancellationToken);
private static DocumentRecord<THeader, TLine> Typed(DocumentRecord record) =>
new() { Header = (THeader)record.Header, Lines = [.. record.Lines.Cast<TLine>()] };
}
@@ -0,0 +1,203 @@
using Khaemhat.Application.Audit;
using Khaemhat.Core.Documents;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Reads and writes the headers and lines of one family through the base classes, so that the engine can follow
/// fulfilment links and copies from one family to another (ADR 0032).
/// </summary>
internal interface IDocumentStore
{
/// <summary>The family.</summary>
DocumentFamily Family { get; }
/// <summary>The header table.</summary>
string HeaderTable { get; }
/// <summary>A new header of the family.</summary>
/// <returns>The header.</returns>
DocumentHeader NewHeader();
/// <summary>A new line of the family.</summary>
/// <returns>The line.</returns>
DocumentLine NewLine();
/// <summary>Reads a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The header, if any.</returns>
Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Reads the lines of a document in their order.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lines.</returns>
Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken);
/// <summary>Reads a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line, if any.</returns>
Task<DocumentLine?> GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Inserts a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="header">The header.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken);
/// <summary>Updates a header.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="header">The header.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken);
/// <summary>Deletes a header and, by cascade, its lines.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Inserts a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="line">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken);
/// <summary>Updates a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="line">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken);
/// <summary>Deletes a line.</summary>
/// <param name="uow">The unit of work.</param>
/// <param name="id">The line.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken);
/// <summary>Writes a change of a header in the history, under the name of its class.</summary>
/// <param name="audit">The history.</param>
/// <param name="uow">The unit of work.</param>
/// <param name="action">What happened.</param>
/// <param name="id">The document.</param>
/// <param name="before">The header before.</param>
/// <param name="after">The header after.</param>
/// <param name="userName">Who did it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task RecordAsync(
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
CancellationToken cancellationToken);
}
/// <summary>The store of one family.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <typeparam name="TLine">The line.</typeparam>
internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, string headerTable) : IDocumentStore
where THeader : DocumentHeader, new()
where TLine : DocumentLine, new()
{
/// <inheritdoc />
public DocumentFamily Family => family;
/// <inheritdoc />
public string HeaderTable => headerTable;
/// <inheritdoc />
public DocumentHeader NewHeader() => new THeader();
/// <inheritdoc />
public DocumentLine NewLine() => new TLine();
/// <inheritdoc />
public async Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
await uow.Repository<THeader, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public async Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken)
{
// A SQL condition: the expression of a generic parameter may reach the base property through a conversion.
var rows = await uow.Repository<TLine, long>().ListAsync(Query.For<TLine>().Where(SqlFragment.Of($"document_id = {documentId}")), cancellationToken)
.ConfigureAwait(false);
return [.. rows.Items.OrderBy(l => l.SortOrder).ThenBy(l => l.LineNumber).ThenBy(l => l.Id).Cast<DocumentLine>()];
}
/// <inheritdoc />
public async Task<DocumentLine?> GetLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
await uow.Repository<TLine, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public async Task InsertAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) =>
header.Id = await uow.Repository<THeader, long>().InsertAsync((THeader)header, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public Task UpdateAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken) =>
uow.Repository<THeader, long>().UpdateAsync((THeader)header, cancellationToken);
/// <inheritdoc />
public Task DeleteAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
uow.Repository<THeader, long>().DeleteAsync(id, cancellationToken);
/// <inheritdoc />
public async Task InsertLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) =>
line.Id = await uow.Repository<TLine, long>().InsertAsync((TLine)line, cancellationToken).ConfigureAwait(false);
/// <inheritdoc />
public Task UpdateLineAsync(IUnitOfWork uow, DocumentLine line, CancellationToken cancellationToken) =>
uow.Repository<TLine, long>().UpdateAsync((TLine)line, cancellationToken);
/// <inheritdoc />
public Task DeleteLineAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
uow.Repository<TLine, long>().DeleteAsync(id, cancellationToken);
/// <inheritdoc />
public Task RecordAsync(
AuditTrail audit, IUnitOfWork uow, AuditAction action, long id, DocumentHeader? before, DocumentHeader? after, string? userName,
CancellationToken cancellationToken) =>
audit.RecordAsync(uow, action, id, (THeader?)before, (THeader?)after, userName, cancellationToken);
}
/// <summary>The stores of the six families.</summary>
internal static class DocumentStores
{
private static readonly Dictionary<DocumentFamily, IDocumentStore> ByFamily = new IDocumentStore[]
{
new DocumentStore<SaleQuotation, SaleQuotationLine>(DocumentFamily.SaleQuotation, "sale_quotations"),
new DocumentStore<SaleOrder, SaleOrderLine>(DocumentFamily.SaleOrder, "sale_orders"),
new DocumentStore<SaleDocument, SaleDocumentLine>(DocumentFamily.SaleDocument, "sale_documents"),
new DocumentStore<PurchaseOrder, PurchaseOrderLine>(DocumentFamily.PurchaseOrder, "purchase_orders"),
new DocumentStore<PurchaseDocument, PurchaseDocumentLine>(DocumentFamily.PurchaseDocument, "purchase_documents"),
new DocumentStore<InventoryDocument, InventoryDocumentLine>(DocumentFamily.InventoryDocument, "inventory_documents"),
}.ToDictionary(s => s.Family);
/// <summary>Every store.</summary>
public static IEnumerable<IDocumentStore> All => ByFamily.Values;
/// <summary>The store of a family.</summary>
/// <param name="family">The family.</param>
/// <returns>The store.</returns>
public static IDocumentStore Of(DocumentFamily family) => ByFamily[family];
/// <summary>The family of a header class.</summary>
/// <typeparam name="THeader">The header.</typeparam>
/// <returns>The family.</returns>
public static DocumentFamily FamilyOf<THeader>()
where THeader : DocumentHeader, new()
{
var type = typeof(THeader);
return All.Single(s => s.NewHeader().GetType() == type).Family;
}
}
@@ -123,6 +123,7 @@ public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
Code = d.Code,
Description = d.Description,
Kind = d.Kind,
DocumentKind = d.DocumentKind,
NumeratorId = d.NumeratorCode is { } n && numerators.TryGetValue(n, out var numerator) ? numerator.Id : null,
InventoryReasonId = d.InventoryReasonCode is { } r && reasons.TryGetValue(r, out var reason) ? reason.Id : null,
EInvoiceType = d.EInvoiceType,
@@ -66,6 +66,9 @@ public sealed partial class TableCatalog
/// <summary>Error: another price list is already the base one.</summary>
public const string BaseDuplicate = "tables.price-list.base-duplicate";
/// <summary>A document type without a kind.</summary>
public const string DocumentKindRequired = "tables.document-type.kind-required";
/// <summary>The maximum depth of item categories.</summary>
public const int MaxCategoryLevel = 3;
@@ -303,6 +306,11 @@ public sealed partial class TableCatalog
.Field("einvoice", x => x.EInvoiceType)
.Rule(async (x, c, ct) =>
{
if (x.DocumentKind is null)
{
c.Error(nameof(DocumentType.DocumentKind), DocumentKindRequired);
}
if (!string.IsNullOrWhiteSpace(x.EInvoiceType))
{
x.EInvoiceType = x.EInvoiceType.Trim().ToUpperInvariant();