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:
1 parent
fa9304834a
commit
ddd2273f7e
33 files changed
+4081
-37
No files matched your search
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user