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();
@@ -0,0 +1,113 @@
namespace Khaemhat.Core.Documents;
/// <summary>How the documents of a kind behave (ADR 0032).</summary>
/// <param name="Kind">The kind.</param>
/// <param name="Family">The tables that hold them.</param>
/// <param name="Direction">Customer, supplier or internal.</param>
/// <param name="Lifecycle">The states they go through.</param>
/// <param name="Effects">What confirming them does.</param>
/// <param name="Lines">The line kinds they accept.</param>
/// <param name="Sources">The kinds whose lines they fulfil (order to delivery note, delivery note to invoice...).</param>
/// <param name="ReadPermission">The permission to see them.</param>
/// <param name="WritePermission">The permission to create and change drafts.</param>
/// <param name="ConfirmPermission">The permission to confirm or issue, cancel, close and reopen.</param>
/// <param name="DeletePermission">The permission to delete drafts.</param>
public sealed record DocumentBehavior(
DocumentKind Kind,
DocumentFamily Family,
DocumentDirection Direction,
DocumentLifecycle Lifecycle,
DocumentEffects Effects,
IReadOnlyList<DocumentLineKind> Lines,
IReadOnlyList<DocumentKind> Sources,
string ReadPermission,
string WritePermission,
string ConfirmPermission,
string DeletePermission)
{
/// <summary>Whether the documents need a customer or supplier.</summary>
public bool NeedsParty => Direction != DocumentDirection.Internal;
/// <summary>Whether the documents have the given effect.</summary>
/// <param name="effect">The effect.</param>
/// <returns>Whether they have it.</returns>
public bool Has(DocumentEffects effect) => (Effects & effect) == effect;
/// <summary>Whether the documents fulfil the lines of documents of another kind.</summary>
/// <param name="source">The kind of the source.</param>
/// <returns>Whether a copy from it creates fulfilment links.</returns>
public bool Fulfils(DocumentKind source) => Sources.Contains(source);
}
/// <summary>The behaviour of every <see cref="DocumentKind"/>.</summary>
public static class DocumentBehaviors
{
private static readonly DocumentLineKind[] Commercial =
[DocumentLineKind.Item, DocumentLineKind.Free, DocumentLineKind.Description, DocumentLineKind.Expense, DocumentLineKind.Discount];
private static readonly DocumentLineKind[] Goods = [DocumentLineKind.Item, DocumentLineKind.Free, DocumentLineKind.Description];
private static readonly DocumentLineKind[] Stock = [DocumentLineKind.Item, DocumentLineKind.Description];
private static readonly DocumentKind[] SaleInvoices =
[
DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice,
DocumentKind.Fee,
];
private static readonly Dictionary<DocumentKind, DocumentBehavior> ByKind = Build().ToDictionary(b => b.Kind);
/// <summary>Every behaviour, in the order of <see cref="DocumentKind"/>.</summary>
public static IReadOnlyList<DocumentBehavior> All { get; } = [.. ByKind.Values.OrderBy(b => b.Kind)];
/// <summary>The behaviour of a kind.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The behaviour.</returns>
public static DocumentBehavior Of(DocumentKind kind) =>
ByKind.TryGetValue(kind, out var behavior) ? behavior : throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown document kind.");
/// <summary>The kinds kept in a family.</summary>
/// <param name="family">The family.</param>
/// <returns>The kinds.</returns>
public static IReadOnlyList<DocumentKind> KindsOf(DocumentFamily family) => [.. All.Where(b => b.Family == family).Select(b => b.Kind)];
private static IEnumerable<DocumentBehavior> Build()
{
const DocumentEffects Invoice = DocumentEffects.Ledger | DocumentEffects.Installments | DocumentEffects.EInvoice;
var quote = Permissions("sales.quote");
var order = Permissions("sales.order");
var delivery = Permissions("sales.delivery");
var invoice = new Perms("sales.invoice.read", "sales.invoice.write", "sales.invoice.issue", "sales.invoice.delete");
var proForma = new Perms("sales.invoice.read", "sales.invoice.write", "sales.invoice.write", "sales.invoice.delete");
var purchaseOrder = Permissions("purchases.order");
var purchaseInvoice = Permissions("purchases.invoice");
var entry = new Perms("inventory.entry.read", "inventory.entry.write", "inventory.entry.post", "inventory.entry.write");
yield return Make(DocumentKind.Quotation, DocumentFamily.SaleQuotation, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.None, Commercial, [], quote);
yield return Make(DocumentKind.SalesOrder, DocumentFamily.SaleOrder, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.Commitment, Commercial, [DocumentKind.Quotation], order);
yield return Make(DocumentKind.DeliveryNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.Inventory, Goods, [DocumentKind.SalesOrder], delivery);
yield return Make(DocumentKind.ImmediateInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.AccompanyingInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice | DocumentEffects.Inventory, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.DeferredInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.DeliveryNote], invoice);
yield return Make(DocumentKind.DownPaymentInvoice, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder], invoice);
yield return Make(DocumentKind.CreditNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, SaleInvoices, invoice);
yield return Make(DocumentKind.DebitNote, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, SaleInvoices, invoice);
yield return Make(DocumentKind.Fee, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Invoice, Invoice, Commercial, [DocumentKind.SalesOrder, DocumentKind.ProForma], invoice);
yield return Make(DocumentKind.ProForma, DocumentFamily.SaleDocument, DocumentDirection.Sale, DocumentLifecycle.Order, DocumentEffects.None, Commercial, [DocumentKind.SalesOrder], proForma);
yield return Make(DocumentKind.SelfInvoice, DocumentFamily.SaleDocument, DocumentDirection.Purchase, DocumentLifecycle.Invoice, DocumentEffects.Ledger | DocumentEffects.EInvoice, Commercial, [DocumentKind.PurchaseInvoice], purchaseInvoice);
yield return Make(DocumentKind.PurchaseOrder, DocumentFamily.PurchaseOrder, DocumentDirection.Purchase, DocumentLifecycle.Order, DocumentEffects.Ordered, Commercial, [], purchaseOrder);
yield return Make(DocumentKind.PurchaseDeliveryNote, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Order, DocumentEffects.Inventory, Goods, [DocumentKind.PurchaseOrder], entry);
yield return Make(DocumentKind.PurchaseInvoice, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Simple, DocumentEffects.Ledger | DocumentEffects.Installments, Commercial, [DocumentKind.PurchaseOrder, DocumentKind.PurchaseDeliveryNote], purchaseInvoice);
yield return Make(DocumentKind.PurchaseCreditNote, DocumentFamily.PurchaseDocument, DocumentDirection.Purchase, DocumentLifecycle.Simple, DocumentEffects.Ledger | DocumentEffects.Installments, Commercial, [DocumentKind.PurchaseInvoice], purchaseInvoice);
yield return Make(DocumentKind.InventoryEntry, DocumentFamily.InventoryDocument, DocumentDirection.Internal, DocumentLifecycle.Simple, DocumentEffects.Inventory, Stock, [], entry);
}
private static Perms Permissions(string area) => new(area + ".read", area + ".write", area + ".write", area + ".write");
private static DocumentBehavior Make(
DocumentKind kind, DocumentFamily family, DocumentDirection direction, DocumentLifecycle lifecycle, DocumentEffects effects,
DocumentLineKind[] lines, DocumentKind[] sources, Perms perms) =>
new(kind, family, direction, lifecycle, effects, lines, sources, perms.Read, perms.Write, perms.Confirm, perms.Delete);
private sealed record Perms(string Read, string Write, string Confirm, string Delete);
}
@@ -0,0 +1,235 @@
namespace Khaemhat.Core.Documents;
/// <summary>The family of a document: the pair of tables that holds it (SPEC §11.3).</summary>
public enum DocumentFamily
{
/// <summary>Quotations (<c>sale_quotations</c>).</summary>
SaleQuotation = 0,
/// <summary>Customer orders (<c>sale_orders</c>).</summary>
SaleOrder = 1,
/// <summary>Delivery notes, invoices, credit and debit notes, pro forma, fees, self-invoices (<c>sale_documents</c>).</summary>
SaleDocument = 2,
/// <summary>Supplier orders (<c>purchase_orders</c>).</summary>
PurchaseOrder = 3,
/// <summary>Supplier delivery notes, invoices and credit notes (<c>purchase_documents</c>).</summary>
PurchaseDocument = 4,
/// <summary>Warehouse entries (<c>inventory_documents</c>).</summary>
InventoryDocument = 5,
}
/// <summary>Who the document is with.</summary>
public enum DocumentDirection
{
/// <summary>A customer: the company sells.</summary>
Sale = 0,
/// <summary>A supplier: the company buys.</summary>
Purchase = 1,
/// <summary>Nobody: an internal document.</summary>
Internal = 2,
}
/// <summary>
/// What a document is, which decides how it behaves (ADR 0032). A document type of the company chooses a kind and adds
/// its numerator, reasons and templates.
/// </summary>
public enum DocumentKind
{
/// <summary>A quotation to a customer.</summary>
Quotation = 0,
/// <summary>A customer order.</summary>
SalesOrder = 1,
/// <summary>A delivery note (DDT) to a customer.</summary>
DeliveryNote = 2,
/// <summary>An immediate invoice.</summary>
ImmediateInvoice = 3,
/// <summary>An accompanying invoice: an invoice that is also the delivery note.</summary>
AccompanyingInvoice = 4,
/// <summary>A deferred invoice of one or more delivery notes.</summary>
DeferredInvoice = 5,
/// <summary>A down payment invoice.</summary>
DownPaymentInvoice = 6,
/// <summary>A credit note to a customer.</summary>
CreditNote = 7,
/// <summary>A debit note to a customer.</summary>
DebitNote = 8,
/// <summary>A professional fee invoice (parcella).</summary>
Fee = 9,
/// <summary>A pro forma invoice, without fiscal effects.</summary>
ProForma = 10,
/// <summary>A self-invoice or integration of a purchase (reverse charge, purchases from abroad).</summary>
SelfInvoice = 11,
/// <summary>An order to a supplier.</summary>
PurchaseOrder = 12,
/// <summary>A delivery note of a supplier (goods received).</summary>
PurchaseDeliveryNote = 13,
/// <summary>An invoice of a supplier.</summary>
PurchaseInvoice = 14,
/// <summary>A credit note of a supplier.</summary>
PurchaseCreditNote = 15,
/// <summary>A warehouse entry: loads, unloads, transfers.</summary>
InventoryEntry = 16,
}
/// <summary>The life cycle a document follows (ADR 0032).</summary>
public enum DocumentLifecycle
{
/// <summary>Draft, confirmed, partially fulfilled, fulfilled, closed, cancelled: quotations, orders, delivery notes, pro forma.</summary>
Order = 0,
/// <summary>Draft, issued, then the states of the exchange system: sale invoices and self-invoices.</summary>
Invoice = 1,
/// <summary>Draft, confirmed, cancelled: supplier invoices, warehouse entries.</summary>
Simple = 2,
}
/// <summary>The state of a document (SPEC §11.3).</summary>
public enum DocumentStatus
{
/// <summary>Being written: no number, no effects.</summary>
Draft = 0,
/// <summary>Confirmed: numbered, effects applied.</summary>
Confirmed = 1,
/// <summary>Some lines fulfilled by later documents.</summary>
PartiallyFulfilled = 2,
/// <summary>Every line fulfilled.</summary>
Fulfilled = 3,
/// <summary>Closed by hand: what is left will not be fulfilled.</summary>
Closed = 4,
/// <summary>Cancelled: the number stays, the effects are removed.</summary>
Cancelled = 5,
/// <summary>An invoice issued: numbered and no longer changeable.</summary>
Issued = 6,
/// <summary>The electronic invoice file has been generated.</summary>
SdiGenerated = 7,
/// <summary>The electronic invoice has been sent to the exchange system.</summary>
SdiSent = 8,
/// <summary>The exchange system delivered the invoice.</summary>
SdiDelivered = 9,
/// <summary>The exchange system rejected the invoice.</summary>
SdiRejected = 10,
/// <summary>The exchange system could not deliver the invoice (made available to the customer).</summary>
SdiNotDelivered = 11,
}
/// <summary>What a user or a procedure can do with a document; the state machine says when.</summary>
public enum DocumentAction
{
/// <summary>Change the header or the lines.</summary>
Edit = 0,
/// <summary>Delete a draft that was never numbered.</summary>
Delete = 1,
/// <summary>Confirm: number and apply the effects (orders, delivery notes, simple documents).</summary>
Confirm = 2,
/// <summary>Issue an invoice: number it and make it unchangeable.</summary>
Issue = 3,
/// <summary>Cancel: keep the number, remove the effects.</summary>
Cancel = 4,
/// <summary>Close what is left to fulfil.</summary>
Close = 5,
/// <summary>Reopen a closed document.</summary>
Reopen = 6,
/// <summary>Make a new draft from the document (duplicate or transform).</summary>
Copy = 7,
/// <summary>Record that the electronic invoice file was generated.</summary>
GenerateXml = 8,
/// <summary>Record that the electronic invoice was sent.</summary>
Send = 9,
/// <summary>Record the delivery receipt.</summary>
MarkDelivered = 10,
/// <summary>Record the rejection.</summary>
MarkRejected = 11,
/// <summary>Record that the invoice could not be delivered.</summary>
MarkNotDelivered = 12,
}
/// <summary>What confirming a document does to the rest of the company's data (applied by the modules: M6, M7, M8).</summary>
[Flags]
public enum DocumentEffects
{
/// <summary>No effect.</summary>
None = 0,
/// <summary>Moves stock (load or unload by the warehouse reason).</summary>
Inventory = 1,
/// <summary>Commits stock to customers (orders).</summary>
Commitment = 2,
/// <summary>Records quantities ordered from suppliers.</summary>
Ordered = 4,
/// <summary>Posts to the general ledger and the VAT registers.</summary>
Ledger = 8,
/// <summary>Generates the installments of the payment schedule.</summary>
Installments = 16,
/// <summary>Produces an electronic invoice.</summary>
EInvoice = 32,
}
/// <summary>The kind of a document line.</summary>
public enum DocumentLineKind
{
/// <summary>An item of the catalogue, with quantity and price.</summary>
Item = 0,
/// <summary>A line with quantity and price but no item.</summary>
Free = 1,
/// <summary>Text only.</summary>
Description = 2,
/// <summary>An ancillary expense (transport, collection).</summary>
Expense = 3,
/// <summary>A discount, premium or allowance.</summary>
Discount = 4,
}
@@ -0,0 +1,157 @@
namespace Khaemhat.Core.Documents;
/// <summary>
/// The states of the three life cycles and the actions each state admits (SPEC §11.3, ADR 0032). The fulfilment states
/// are not reached by actions: <see cref="FulfillmentCalculator"/> computes them.
/// </summary>
public static class DocumentStateMachine
{
private static readonly Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary<DocumentAction, DocumentStatus>> Rules = Build();
/// <summary>The states a life cycle uses, in order.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <returns>The states.</returns>
public static IReadOnlyList<DocumentStatus> States(DocumentLifecycle lifecycle) =>
[.. Rules.Keys.Where(k => k.Item1 == lifecycle).Select(k => k.Item2).OrderBy(s => s)];
/// <summary>The actions a state admits.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <returns>The actions, in the order of <see cref="DocumentAction"/>.</returns>
public static IReadOnlyList<DocumentAction> Actions(DocumentLifecycle lifecycle, DocumentStatus status) =>
Rules.TryGetValue((lifecycle, status), out var actions) ? [.. actions.Keys.OrderBy(a => a)] : [];
/// <summary>Whether a state admits an action.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <param name="action">The action.</param>
/// <returns>Whether it is admitted.</returns>
public static bool Allows(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) =>
Rules.TryGetValue((lifecycle, status), out var actions) && actions.ContainsKey(action);
/// <summary>The state after an action.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <param name="action">The action.</param>
/// <returns>The new state (the same one for actions that do not move it, such as edit and copy).</returns>
/// <exception cref="InvalidDocumentActionException">The state does not admit the action.</exception>
public static DocumentStatus Apply(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action) =>
Rules.TryGetValue((lifecycle, status), out var actions) && actions.TryGetValue(action, out var next)
? next
: throw new InvalidDocumentActionException(lifecycle, status, action);
/// <summary>Whether the header and lines can change in a state.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <returns>Whether they can.</returns>
public static bool IsEditable(DocumentLifecycle lifecycle, DocumentStatus status) => Allows(lifecycle, status, DocumentAction.Edit);
/// <summary>Whether a document in this state counts: confirmed or issued, and not cancelled.</summary>
/// <param name="status">The state.</param>
/// <returns>Whether its effects and links are in force.</returns>
public static bool IsInForce(DocumentStatus status) => status is not (DocumentStatus.Draft or DocumentStatus.Cancelled);
/// <summary>
/// The state of a document after its lines were fulfilled: only confirmed, partially fulfilled and fulfilled
/// documents of the order life cycle move; the others keep their state.
/// </summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <param name="fulfillment">What the lines say.</param>
/// <returns>The new state.</returns>
public static DocumentStatus AfterFulfillment(DocumentLifecycle lifecycle, DocumentStatus status, FulfillmentState fulfillment) =>
lifecycle == DocumentLifecycle.Order && status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled or DocumentStatus.Fulfilled
? fulfillment switch
{
FulfillmentState.Fulfilled => DocumentStatus.Fulfilled,
FulfillmentState.Partial => DocumentStatus.PartiallyFulfilled,
_ => DocumentStatus.Confirmed,
}
: status;
private static Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary<DocumentAction, DocumentStatus>> Build()
{
var rules = new Dictionary<(DocumentLifecycle, DocumentStatus), Dictionary<DocumentAction, DocumentStatus>>();
void Add(DocumentLifecycle lifecycle, DocumentStatus status, params (DocumentAction Action, DocumentStatus? Next)[] actions) =>
rules[(lifecycle, status)] = actions.ToDictionary(a => a.Action, a => a.Next ?? status);
const DocumentAction Copy = DocumentAction.Copy;
const DocumentAction Edit = DocumentAction.Edit;
// Orders, quotations, delivery notes, pro forma: changeable until something is fulfilled.
Add(DocumentLifecycle.Order, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Confirm, DocumentStatus.Confirmed), (Copy, null));
Add(DocumentLifecycle.Order, DocumentStatus.Confirmed, (Edit, null), (Copy, null), (DocumentAction.Cancel, DocumentStatus.Cancelled), (DocumentAction.Close, DocumentStatus.Closed));
Add(DocumentLifecycle.Order, DocumentStatus.PartiallyFulfilled, (Edit, null), (Copy, null), (DocumentAction.Close, DocumentStatus.Closed));
Add(DocumentLifecycle.Order, DocumentStatus.Fulfilled, (Copy, null), (DocumentAction.Close, DocumentStatus.Closed));
Add(DocumentLifecycle.Order, DocumentStatus.Closed, (Copy, null), (DocumentAction.Reopen, DocumentStatus.Confirmed));
Add(DocumentLifecycle.Order, DocumentStatus.Cancelled, (Copy, null));
// Invoices: unchangeable once issued; cancelled (with a reason) only while the file has not reached the
// exchange system or after a rejection, otherwise a credit note.
Add(DocumentLifecycle.Invoice, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Issue, DocumentStatus.Issued), (Copy, null));
Add(DocumentLifecycle.Invoice, DocumentStatus.Issued, (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiGenerated, (Copy, null), (DocumentAction.GenerateXml, null), (DocumentAction.Send, DocumentStatus.SdiSent), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiSent, (Copy, null), (DocumentAction.MarkDelivered, DocumentStatus.SdiDelivered),
(DocumentAction.MarkRejected, DocumentStatus.SdiRejected), (DocumentAction.MarkNotDelivered, DocumentStatus.SdiNotDelivered));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiRejected, (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiDelivered, (Copy, null));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiNotDelivered, (Copy, null));
Add(DocumentLifecycle.Invoice, DocumentStatus.Cancelled, (Copy, null));
// Supplier invoices and warehouse entries.
Add(DocumentLifecycle.Simple, DocumentStatus.Draft, (Edit, null), (DocumentAction.Delete, null), (DocumentAction.Confirm, DocumentStatus.Confirmed), (Copy, null));
Add(DocumentLifecycle.Simple, DocumentStatus.Confirmed, (Copy, null), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Simple, DocumentStatus.Cancelled, (Copy, null));
return rules;
}
}
/// <summary>An action the state of the document does not admit.</summary>
public sealed class InvalidDocumentActionException : InvalidOperationException
{
/// <summary>The error code for the interface.</summary>
public const string Code = "document.action.not-allowed";
/// <summary>Creates the exception.</summary>
public InvalidDocumentActionException()
: base(Code)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public InvalidDocumentActionException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public InvalidDocumentActionException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="lifecycle">The life cycle.</param>
/// <param name="status">The state.</param>
/// <param name="action">The refused action.</param>
public InvalidDocumentActionException(DocumentLifecycle lifecycle, DocumentStatus status, DocumentAction action)
: base($"A {lifecycle} document in state {status} does not admit {action}.")
{
Lifecycle = lifecycle;
Status = status;
Action = action;
}
/// <summary>The life cycle.</summary>
public DocumentLifecycle Lifecycle { get; }
/// <summary>The state.</summary>
public DocumentStatus Status { get; }
/// <summary>The refused action.</summary>
public DocumentAction Action { get; }
}
+329
View File
@@ -0,0 +1,329 @@
using Khaemhat.Core.Entities;
using Khaemhat.Core.Items;
namespace Khaemhat.Core.Documents;
/// <summary>
/// The header of a document (SPEC §11.3): the same columns in the six families of tables. The totals are written by the
/// totals calculator (#48); the flags by printing, sending, posting and the electronic invoice.
/// </summary>
public abstract class DocumentHeader : Entity<long>, IDemoMarkable
{
/// <summary>The document type of the company.</summary>
public long DocumentTypeId { get; set; }
/// <summary>The kind, copied from the type when the document is created.</summary>
public DocumentKind Kind { get; set; }
/// <summary>The state.</summary>
public DocumentStatus Status { get; set; }
/// <summary>The numerator row (code and year) that gave the number.</summary>
public long? NumeratorId { get; set; }
/// <summary>The section (sezionale) of the numerator.</summary>
public string? Section { get; set; }
/// <summary>The progressive number; empty until confirmation.</summary>
public long? Number { get; set; }
/// <summary>The number as printed, such as <c>12/2026</c>.</summary>
public string? DocumentNumber { get; set; }
/// <summary>The date of the document.</summary>
public DateOnly DocumentDate { get; set; }
/// <summary>The year of the numbering.</summary>
public int Year { get; set; }
/// <summary>The customer or supplier.</summary>
public long? PartyId { get; set; }
/// <summary>The destination (an address of the party).</summary>
public long? DestinationId { get; set; }
/// <summary>The reference of the other side: customer order number, supplier invoice or delivery note number.</summary>
public string? ExternalReference { get; set; }
/// <summary>The date of the reference.</summary>
public DateOnly? ExternalDate { get; set; }
/// <summary>The currency.</summary>
public string CurrencyCode { get; set; } = "EUR";
/// <summary>The exchange rate to euro.</summary>
public decimal ExchangeRate { get; set; } = 1m;
/// <summary>The price list.</summary>
public long? PriceListId { get; set; }
/// <summary>The payment terms.</summary>
public long? PaymentTermId { get; set; }
/// <summary>The payment method.</summary>
public long? PaymentMethodId { get; set; }
/// <summary>The bank account of the company that collects or pays.</summary>
public long? BankAccountId { get; set; }
/// <summary>The agent.</summary>
public long? SalespersonId { get; set; }
/// <summary>The warehouse.</summary>
public long? WarehouseId { get; set; }
/// <summary>The warehouse reason.</summary>
public long? InventoryReasonId { get; set; }
/// <summary>The reason of the transport.</summary>
public long? TransportReasonId { get; set; }
/// <summary>The shipping terms (porto).</summary>
public long? ShippingTermId { get; set; }
/// <summary>The carrier.</summary>
public long? CarrierId { get; set; }
/// <summary>The appearance of the goods.</summary>
public long? GoodsAppearanceId { get; set; }
/// <summary>The number of packages.</summary>
public int? Packages { get; set; }
/// <summary>The gross weight in kg.</summary>
public decimal? GrossWeight { get; set; }
/// <summary>The net weight in kg.</summary>
public decimal? NetWeight { get; set; }
/// <summary>When the transport starts.</summary>
public DateTime? TransportStart { get; set; }
/// <summary>Until when a quotation is valid.</summary>
public DateOnly? ValidUntil { get; set; }
/// <summary>The delivery date requested or promised.</summary>
public DateOnly? DeliveryDate { get; set; }
/// <summary>The revision of a quotation.</summary>
public int Revision { get; set; }
/// <summary>Printed at least once.</summary>
public bool Printed { get; set; }
/// <summary>Sent by e-mail at least once.</summary>
public bool Sent { get; set; }
/// <summary>Posted to the ledger.</summary>
public bool Posted { get; set; }
/// <summary>Installments generated in the payment schedule.</summary>
public bool InstallmentsGenerated { get; set; }
/// <summary>Electronic invoice file generated.</summary>
public bool XmlGenerated { get; set; }
/// <summary>The taxable amount.</summary>
public decimal TaxableAmount { get; set; }
/// <summary>The tax.</summary>
public decimal TaxAmount { get; set; }
/// <summary>The total of the document.</summary>
public decimal TotalAmount { get; set; }
/// <summary>The discount on the total (percent formula, such as <c>5</c> or <c>10+5</c>).</summary>
public string? FooterDiscount { get; set; }
/// <summary>The ancillary expenses.</summary>
public decimal ExpensesAmount { get; set; }
/// <summary>The stamp duty.</summary>
public decimal StampDuty { get; set; }
/// <summary>The withholding tax.</summary>
public decimal WithholdingAmount { get; set; }
/// <summary>The social security contribution (cassa previdenza).</summary>
public decimal SocialSecurityAmount { get; set; }
/// <summary>The amount to pay.</summary>
public decimal NetAmount { get; set; }
/// <summary>The notes printed on the document.</summary>
public string? Notes { get; set; }
/// <summary>The ledger entry, once posted (M7).</summary>
public long? GlEntryId { get; set; }
/// <summary>The VAT protocol of a supplier invoice.</summary>
public long? VatProtocol { get; set; }
/// <summary>When the document was confirmed or issued.</summary>
public DateTime? ConfirmedAt { get; set; }
/// <summary>Who confirmed or issued it.</summary>
public string? ConfirmedBy { get; set; }
/// <summary>When it was cancelled.</summary>
public DateTime? CancelledAt { get; set; }
/// <summary>Why it was cancelled.</summary>
public string? CancelReason { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
/// <summary>A shallow copy of the same class (the state before a change, for the history).</summary>
/// <returns>The copy.</returns>
public DocumentHeader Clone() => (DocumentHeader)MemberwiseClone();
}
/// <summary>A line of a document (SPEC §11.3).</summary>
public abstract class DocumentLine : Entity<long>
{
/// <summary>The document.</summary>
public long DocumentId { get; set; }
/// <summary>The progressive number of the line (1, 2...), the one printed and sent.</summary>
public int LineNumber { get; set; }
/// <summary>The kind of line.</summary>
public DocumentLineKind Kind { get; set; }
/// <summary>The item.</summary>
public long? ItemId { get; set; }
/// <summary>The description.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>The unit of measure.</summary>
public long? UnitOfMeasureId { get; set; }
/// <summary>The quantity.</summary>
public decimal Quantity { get; set; }
/// <summary>The unit price.</summary>
public decimal Price { get; set; }
/// <summary>Where the price comes from.</summary>
public PriceSource PriceSource { get; set; }
/// <summary>The discounts, such as <c>10+5</c>.</summary>
public string? DiscountFormula { get; set; }
/// <summary>The VAT code.</summary>
public long? TaxCodeId { get; set; }
/// <summary>The taxable amount of the line.</summary>
public decimal TaxableAmount { get; set; }
/// <summary>The warehouse of the line, when different from the header.</summary>
public long? WarehouseId { get; set; }
/// <summary>The delivery date of the line.</summary>
public DateOnly? DeliveryDate { get; set; }
/// <summary>How much later documents fulfilled.</summary>
public decimal FulfilledQuantity { get; set; }
/// <summary>The rest will not be fulfilled (line closed by hand).</summary>
public bool FulfillmentClosed { get; set; }
/// <summary>The family of the line this one was copied from to fulfil it.</summary>
public DocumentFamily? SourceFamily { get; set; }
/// <summary>The line this one fulfils.</summary>
public long? SourceLineId { get; set; }
/// <summary>The ledger account (M7).</summary>
public string? AccountCode { get; set; }
/// <summary>The cost centre.</summary>
public long? CostCenterId { get; set; }
/// <summary>The job (commessa).</summary>
public long? JobId { get; set; }
/// <summary>Notes of the line.</summary>
public string? Notes { get; set; }
/// <summary>The order on screen and in print.</summary>
public int SortOrder { get; set; }
/// <summary>What is left to fulfil: zero for closed lines and lines without quantity.</summary>
public decimal Residual => FulfillmentClosed || !CarriesQuantity(Kind) ? 0m : Math.Max(0m, Quantity - FulfilledQuantity);
/// <summary>A shallow copy of the same class.</summary>
/// <returns>The copy.</returns>
public DocumentLine Clone() => (DocumentLine)MemberwiseClone();
/// <summary>Whether lines of a kind carry a quantity that later documents can fulfil.</summary>
/// <param name="kind">The kind.</param>
/// <returns>Whether they do.</returns>
public static bool CarriesQuantity(DocumentLineKind kind) => kind is DocumentLineKind.Item or DocumentLineKind.Free;
}
/// <summary>A quotation (<c>sale_quotations</c>).</summary>
public sealed class SaleQuotation : DocumentHeader;
/// <summary>A line of a quotation.</summary>
public sealed class SaleQuotationLine : DocumentLine;
/// <summary>A customer order (<c>sale_orders</c>).</summary>
public sealed class SaleOrder : DocumentHeader;
/// <summary>A line of a customer order.</summary>
public sealed class SaleOrderLine : DocumentLine;
/// <summary>A delivery note, invoice, credit or debit note, pro forma, fee or self-invoice (<c>sale_documents</c>).</summary>
public sealed class SaleDocument : DocumentHeader;
/// <summary>A line of a sale document.</summary>
public sealed class SaleDocumentLine : DocumentLine;
/// <summary>A supplier order (<c>purchase_orders</c>).</summary>
public sealed class PurchaseOrder : DocumentHeader;
/// <summary>A line of a supplier order.</summary>
public sealed class PurchaseOrderLine : DocumentLine;
/// <summary>A supplier delivery note, invoice or credit note (<c>purchase_documents</c>).</summary>
public sealed class PurchaseDocument : DocumentHeader;
/// <summary>A line of a purchase document.</summary>
public sealed class PurchaseDocumentLine : DocumentLine;
/// <summary>A warehouse entry (<c>inventory_documents</c>).</summary>
public sealed class InventoryDocument : DocumentHeader;
/// <summary>A line of a warehouse entry.</summary>
public sealed class InventoryDocumentLine : DocumentLine;
/// <summary>
/// A fulfilment link (<c>document_links</c>): a line of a confirmed document fulfils a quantity of a line of an earlier
/// one (order to delivery note, delivery note to deferred invoice, supplier delivery note to supplier invoice).
/// </summary>
public sealed class DocumentLink : Entity<long>
{
/// <summary>The family of the fulfilling document.</summary>
public DocumentFamily TargetFamily { get; set; }
/// <summary>The fulfilling document.</summary>
public long TargetDocumentId { get; set; }
/// <summary>The fulfilling line.</summary>
public long TargetLineId { get; set; }
/// <summary>The family of the fulfilled document.</summary>
public DocumentFamily SourceFamily { get; set; }
/// <summary>The fulfilled document.</summary>
public long SourceDocumentId { get; set; }
/// <summary>The fulfilled line.</summary>
public long SourceLineId { get; set; }
/// <summary>The quantity fulfilled.</summary>
public decimal Quantity { get; set; }
}
@@ -0,0 +1,61 @@
namespace Khaemhat.Core.Documents;
/// <summary>What the lines of a document say about its fulfilment.</summary>
public enum FulfillmentState
{
/// <summary>Nothing fulfilled.</summary>
None = 0,
/// <summary>Something fulfilled, something left.</summary>
Partial = 1,
/// <summary>Every line fulfilled or closed.</summary>
Fulfilled = 2,
}
/// <summary>Line-by-line fulfilment (SPEC §11.3, ADR 0032): quantities from the links, state of the document from the lines.</summary>
public static class FulfillmentCalculator
{
/// <summary>Writes on each line the quantity fulfilled by the links that point to it.</summary>
/// <param name="lines">The lines of the fulfilled document.</param>
/// <param name="links">The links in force (of confirmed documents) towards those lines.</param>
/// <returns>The lines whose quantity changed.</returns>
public static IReadOnlyList<DocumentLine> Apply(IEnumerable<DocumentLine> lines, IEnumerable<DocumentLink> links)
{
ArgumentNullException.ThrowIfNull(lines);
ArgumentNullException.ThrowIfNull(links);
var byLine = links.GroupBy(l => l.SourceLineId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity));
var changed = new List<DocumentLine>();
foreach (var line in lines)
{
var fulfilled = byLine.GetValueOrDefault(line.Id);
if (line.FulfilledQuantity != fulfilled)
{
line.FulfilledQuantity = fulfilled;
changed.Add(line);
}
}
return changed;
}
/// <summary>The fulfilment of a document from its lines; lines without quantity do not count.</summary>
/// <param name="lines">The lines.</param>
/// <returns>The state.</returns>
public static FulfillmentState StateOf(IEnumerable<DocumentLine> lines)
{
ArgumentNullException.ThrowIfNull(lines);
var counted = lines.Where(l => DocumentLine.CarriesQuantity(l.Kind) && l.Quantity > 0).ToList();
if (counted.Count == 0)
{
return FulfillmentState.None;
}
if (counted.All(l => l.Residual == 0))
{
return FulfillmentState.Fulfilled;
}
return counted.Any(l => l.FulfilledQuantity > 0 || l.FulfillmentClosed) ? FulfillmentState.Partial : FulfillmentState.None;
}
}
+6
View File
@@ -408,6 +408,9 @@ public sealed class DocumentNumerator : CodedEntity
/// <summary>Whether gaps are allowed (never for invoices, credit notes and final entries).</summary>
public bool GapsAllowed { get; set; }
/// <summary>The date of the last document numbered: without gaps, no later document may have an earlier date.</summary>
public DateOnly? LastDate { get; set; }
}
/// <summary>A type of document: the links between a document and its numerator, warehouse reason and SDI type.</summary>
@@ -416,6 +419,9 @@ public sealed class DocumentType : CodedEntity
/// <summary>The family of document.</summary>
public NumeratorKind Kind { get; set; }
/// <summary>What the documents of this type are, which decides how they behave (ADR 0032); empty for types not yet usable.</summary>
public Documents.DocumentKind? DocumentKind { get; set; }
/// <summary>The numerator.</summary>
public long? NumeratorId { get; set; }
@@ -0,0 +1,83 @@
using Khaemhat.Core.Documents;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.CompanyDatabase;
/// <summary>The columns shared by the six document headers (ADR 0032).</summary>
/// <typeparam name="T">The header.</typeparam>
public abstract class DocumentHeaderMap<T> : EntityMap<T>
where T : DocumentHeader, new()
{
/// <summary>Creates the map.</summary>
/// <param name="table">The table of the family.</param>
protected DocumentHeaderMap(string table)
{
ToTable(table);
Map(x => x.Section).MaxLength(10);
Map(x => x.DocumentNumber).MaxLength(30);
Map(x => x.ExternalReference).MaxLength(40);
Map(x => x.CurrencyCode).MaxLength(3);
Map(x => x.FooterDiscount).MaxLength(30);
Map(x => x.ConfirmedBy).MaxLength(100);
Map(x => x.CancelReason).MaxLength(200);
}
}
/// <summary>The columns shared by the six tables of lines.</summary>
/// <typeparam name="T">The line.</typeparam>
public abstract class DocumentLineMap<T> : EntityMap<T>
where T : DocumentLine, new()
{
/// <summary>Creates the map.</summary>
/// <param name="table">The table of the lines.</param>
protected DocumentLineMap(string table)
{
ToTable(table);
Map(x => x.Description).MaxLength(1000);
Map(x => x.DiscountFormula).MaxLength(30);
Map(x => x.AccountCode).MaxLength(20);
}
}
/// <summary>Map of <see cref="SaleQuotation"/> to <c>sale_quotations</c>.</summary>
public sealed class SaleQuotationMap() : DocumentHeaderMap<SaleQuotation>("sale_quotations");
/// <summary>Map of <see cref="SaleQuotationLine"/> to <c>sale_quotation_lines</c>.</summary>
public sealed class SaleQuotationLineMap() : DocumentLineMap<SaleQuotationLine>("sale_quotation_lines");
/// <summary>Map of <see cref="SaleOrder"/> to <c>sale_orders</c>.</summary>
public sealed class SaleOrderMap() : DocumentHeaderMap<SaleOrder>("sale_orders");
/// <summary>Map of <see cref="SaleOrderLine"/> to <c>sale_order_lines</c>.</summary>
public sealed class SaleOrderLineMap() : DocumentLineMap<SaleOrderLine>("sale_order_lines");
/// <summary>Map of <see cref="SaleDocument"/> to <c>sale_documents</c>.</summary>
public sealed class SaleDocumentMap() : DocumentHeaderMap<SaleDocument>("sale_documents");
/// <summary>Map of <see cref="SaleDocumentLine"/> to <c>sale_document_lines</c>.</summary>
public sealed class SaleDocumentLineMap() : DocumentLineMap<SaleDocumentLine>("sale_document_lines");
/// <summary>Map of <see cref="PurchaseOrder"/> to <c>purchase_orders</c>.</summary>
public sealed class PurchaseOrderMap() : DocumentHeaderMap<PurchaseOrder>("purchase_orders");
/// <summary>Map of <see cref="PurchaseOrderLine"/> to <c>purchase_order_lines</c>.</summary>
public sealed class PurchaseOrderLineMap() : DocumentLineMap<PurchaseOrderLine>("purchase_order_lines");
/// <summary>Map of <see cref="PurchaseDocument"/> to <c>purchase_documents</c>.</summary>
public sealed class PurchaseDocumentMap() : DocumentHeaderMap<PurchaseDocument>("purchase_documents");
/// <summary>Map of <see cref="PurchaseDocumentLine"/> to <c>purchase_document_lines</c>.</summary>
public sealed class PurchaseDocumentLineMap() : DocumentLineMap<PurchaseDocumentLine>("purchase_document_lines");
/// <summary>Map of <see cref="InventoryDocument"/> to <c>inventory_documents</c>.</summary>
public sealed class InventoryDocumentMap() : DocumentHeaderMap<InventoryDocument>("inventory_documents");
/// <summary>Map of <see cref="InventoryDocumentLine"/> to <c>inventory_document_lines</c>.</summary>
public sealed class InventoryDocumentLineMap() : DocumentLineMap<InventoryDocumentLine>("inventory_document_lines");
/// <summary>Map of <see cref="DocumentLink"/> to <c>document_links</c>.</summary>
public sealed class DocumentLinkMap : EntityMap<DocumentLink>
{
/// <summary>Creates the map.</summary>
public DocumentLinkMap() => ToTable("document_links");
}
@@ -0,0 +1,179 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>
/// The document engine (SPEC §11.3, ADR 0032, issue #47): six families of headers with their lines, the fulfilment
/// links, the kind of each document type and the date of the last number of each numerator.
/// </summary>
[Migration(20261112_003, "create_documents")]
public sealed class M20261112_003_CreateDocuments : IMigration
{
// The kinds of the document types seeded by M20261111_014 (ItalianBaseTables): the code decides the behaviour.
private static readonly (string Code, string Kind)[] SeededKinds =
[
("PRE", "Quotation"), ("OC", "SalesOrder"), ("DDT", "DeliveryNote"), ("FI", "ImmediateInvoice"), ("FA", "AccompanyingInvoice"),
("FD", "DeferredInvoice"), ("FACC", "DownPaymentInvoice"), ("NC", "CreditNote"), ("ND", "DebitNote"), ("PAR", "Fee"), ("PF", "ProForma"),
("AF16", "SelfInvoice"), ("AF17", "SelfInvoice"), ("AF18", "SelfInvoice"), ("AF19", "SelfInvoice"), ("OF", "PurchaseOrder"),
("DDTF", "PurchaseDeliveryNote"), ("FF", "PurchaseInvoice"), ("NCF", "PurchaseCreditNote"), ("MM", "InventoryEntry"),
];
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.AlterTable("document_types", t => t.String("document_kind", 40));
foreach (var (code, kind) in SeededKinds)
{
schema.Sql(_ => "UPDATE document_types SET document_kind = '" + kind + "' WHERE code = '" + code + "'");
}
schema.AlterTable("document_numerators", t => t.Date("last_date"));
Family(schema, "sale_quotations", "sale_quotation_lines");
Family(schema, "sale_orders", "sale_order_lines");
Family(schema, "sale_documents", "sale_document_lines");
Family(schema, "purchase_orders", "purchase_order_lines");
Family(schema, "purchase_documents", "purchase_document_lines");
Family(schema, "inventory_documents", "inventory_document_lines");
schema.CreateTable("document_links", t =>
{
t.Id();
t.String("target_family", 40).NotNull();
t.Int64("target_document_id").NotNull();
t.Int64("target_line_id").NotNull();
t.String("source_family", 40).NotNull();
t.Int64("source_document_id").NotNull();
t.Int64("source_line_id").NotNull();
t.Decimal("quantity").NotNull();
t.AuditColumns();
t.Index("ix_document_links_source", "source_family", "source_line_id");
t.Index("ix_document_links_source_document", "source_family", "source_document_id");
t.Index("ix_document_links_target", "target_family", "target_document_id");
});
}
private static void Family(ISchemaBuilder schema, string headers, string lines)
{
schema.CreateTable(headers, t =>
{
t.Id();
t.Int64("document_type_id").NotNull();
t.String("kind", 40).NotNull();
t.String("status", 40).NotNull();
t.Int64("numerator_id");
t.String("section", 10);
t.Int64("number");
t.String("document_number", 30);
t.Date("document_date").NotNull();
t.Int32("year").NotNull();
t.Int64("party_id");
t.Int64("destination_id");
t.String("external_reference", 40);
t.Date("external_date");
t.String("currency_code", 3).NotNull();
t.Decimal("exchange_rate").NotNull().Default(1m);
t.Int64("price_list_id");
t.Int64("payment_term_id");
t.Int64("payment_method_id");
t.Int64("bank_account_id");
t.Int64("salesperson_id");
t.Int64("warehouse_id");
t.Int64("inventory_reason_id");
t.Int64("transport_reason_id");
t.Int64("shipping_term_id");
t.Int64("carrier_id");
t.Int64("goods_appearance_id");
t.Int32("packages");
t.Decimal("gross_weight");
t.Decimal("net_weight");
t.DateTimeUtc("transport_start");
t.Date("valid_until");
t.Date("delivery_date");
t.Int32("revision").NotNull().Default(0);
t.Bool("printed").NotNull().Default(false);
t.Bool("sent").NotNull().Default(false);
t.Bool("posted").NotNull().Default(false);
t.Bool("installments_generated").NotNull().Default(false);
t.Bool("xml_generated").NotNull().Default(false);
t.Decimal("taxable_amount").NotNull().Default(0m);
t.Decimal("tax_amount").NotNull().Default(0m);
t.Decimal("total_amount").NotNull().Default(0m);
t.String("footer_discount", 30);
t.Decimal("expenses_amount").NotNull().Default(0m);
t.Decimal("stamp_duty").NotNull().Default(0m);
t.Decimal("withholding_amount").NotNull().Default(0m);
t.Decimal("social_security_amount").NotNull().Default(0m);
t.Decimal("net_amount").NotNull().Default(0m);
t.Text("notes");
t.Int64("gl_entry_id");
t.Int64("vat_protocol");
t.DateTimeUtc("confirmed_at");
t.String("confirmed_by", 100);
t.DateTimeUtc("cancelled_at");
t.String("cancel_reason", 200);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_" + headers + "_number", "numerator_id", "number");
t.Index("ix_" + headers + "_date", "document_date");
t.Index("ix_" + headers + "_party", "party_id");
t.Index("ix_" + headers + "_status", "status");
t.ForeignKey("fk_" + headers + "_type", "document_type_id", "document_types", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_numerator", "numerator_id", "document_numerators", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_party", "party_id", "parties", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_destination", "destination_id", "party_addresses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_price_list", "price_list_id", "price_lists", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_payment_term", "payment_term_id", "payment_terms", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_payment_method", "payment_method_id", "payment_methods", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_bank_account", "bank_account_id", "bank_accounts", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_salesperson", "salesperson_id", "salespeople", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_inventory_reason", "inventory_reason_id", "inventory_reasons", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_transport_reason", "transport_reason_id", "transport_reasons", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_shipping_term", "shipping_term_id", "shipping_terms", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_carrier", "carrier_id", "carriers", ReferentialAction.Restrict);
t.ForeignKey("fk_" + headers + "_goods_appearance", "goods_appearance_id", "goods_appearances", ReferentialAction.Restrict);
});
schema.CreateTable(lines, t =>
{
t.Id();
t.Int64("document_id").NotNull();
t.Int32("line_number").NotNull();
t.String("kind", 40).NotNull();
t.Int64("item_id");
t.String("description", 1000).NotNull();
t.Int64("unit_of_measure_id");
t.Decimal("quantity").NotNull().Default(0m);
t.Decimal("price").NotNull().Default(0m);
t.String("price_source", 40).NotNull();
t.String("discount_formula", 30);
t.Int64("tax_code_id");
t.Decimal("taxable_amount").NotNull().Default(0m);
t.Int64("warehouse_id");
t.Date("delivery_date");
t.Decimal("fulfilled_quantity").NotNull().Default(0m);
t.Bool("fulfillment_closed").NotNull().Default(false);
t.String("source_family", 40);
t.Int64("source_line_id");
t.String("account_code", 20);
t.Int64("cost_center_id");
t.Int64("job_id");
t.Text("notes");
t.Int32("sort_order").NotNull().Default(0);
t.AuditColumns();
t.Index("ix_" + lines + "_document", "document_id");
t.Index("ix_" + lines + "_item", "item_id");
t.Index("ix_" + lines + "_source", "source_family", "source_line_id");
t.ForeignKey("fk_" + lines + "_document", "document_id", headers, ReferentialAction.Cascade);
t.ForeignKey("fk_" + lines + "_item", "item_id", "items", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_unit", "unit_of_measure_id", "units_of_measure", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_tax_code", "tax_code_id", "tax_codes", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_warehouse", "warehouse_id", "warehouses", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_cost_center", "cost_center_id", "cost_centers", ReferentialAction.Restrict);
t.ForeignKey("fk_" + lines + "_job", "job_id", "jobs", ReferentialAction.Restrict);
});
}
}
+3 -1
View File
@@ -221,8 +221,10 @@ public sealed record PaymentTermTemplate(string Code, string Description, string
/// <param name="NumeratorCode">The numerator of the base data (<c>FAT</c>, <c>DDT</c>...), if the document is numbered by the company.</param>
/// <param name="InventoryReasonCode">The warehouse reason of the base data (<c>SCA</c>, <c>CAR</c>...), if the document moves goods.</param>
/// <param name="EInvoiceType">The type of the e-invoice format, if the document is sent electronically.</param>
/// <param name="DocumentKind">What the documents are, which decides how they behave (ADR 0032).</param>
public sealed record DocumentTypeTemplate(
string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType);
string Code, string Description, Khaemhat.Core.Tables.NumeratorKind Kind, string? NumeratorCode, string? InventoryReasonCode, string? EInvoiceType,
Khaemhat.Core.Documents.DocumentKind DocumentKind);
/// <summary>
/// The rows of the base tables that depend on the country's rules (SPEC §14): payment methods and terms with the codes
+21 -20
View File
@@ -1,3 +1,4 @@
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tables;
using Khaemhat.Fiscal.Abstractions;
@@ -46,25 +47,25 @@ public sealed class ItalianBaseTables : IBaseTablesTemplate
/// <inheritdoc />
public IReadOnlyList<DocumentTypeTemplate> DocumentTypes { get; } =
[
new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null),
new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null),
new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null),
new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01"),
new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01"),
new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24"),
new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02"),
new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04"),
new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05"),
new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06"),
new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null),
new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16"),
new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17"),
new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18"),
new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19"),
new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null),
new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null),
new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null),
new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null),
new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null),
new("PRE", "Preventivo", NumeratorKind.Quotation, "PRE", null, null, DocumentKind.Quotation),
new("OC", "Ordine cliente", NumeratorKind.SalesOrder, "ORD", null, null, DocumentKind.SalesOrder),
new("DDT", "Documento di trasporto", NumeratorKind.DeliveryNote, "DDT", "SCA", null, DocumentKind.DeliveryNote),
new("FI", "Fattura immediata", NumeratorKind.SalesInvoice, "FAT", null, "TD01", DocumentKind.ImmediateInvoice),
new("FA", "Fattura accompagnatoria", NumeratorKind.SalesInvoice, "FAT", "SCA", "TD01", DocumentKind.AccompanyingInvoice),
new("FD", "Fattura differita", NumeratorKind.SalesInvoice, "FAT", null, "TD24", DocumentKind.DeferredInvoice),
new("FACC", "Fattura di acconto", NumeratorKind.SalesInvoice, "FAT", null, "TD02", DocumentKind.DownPaymentInvoice),
new("NC", "Nota di credito", NumeratorKind.SalesInvoice, "FAT", null, "TD04", DocumentKind.CreditNote),
new("ND", "Nota di debito", NumeratorKind.SalesInvoice, "FAT", null, "TD05", DocumentKind.DebitNote),
new("PAR", "Parcella", NumeratorKind.SalesInvoice, "FAT", null, "TD06", DocumentKind.Fee),
new("PF", "Fattura pro forma", NumeratorKind.Other, "PRF", null, null, DocumentKind.ProForma),
new("AF16", "Integrazione reverse charge interno", NumeratorKind.SalesInvoice, "AUT", null, "TD16", DocumentKind.SelfInvoice),
new("AF17", "Integrazione acquisto servizi dall'estero", NumeratorKind.SalesInvoice, "AUT", null, "TD17", DocumentKind.SelfInvoice),
new("AF18", "Integrazione acquisto beni intracomunitari", NumeratorKind.SalesInvoice, "AUT", null, "TD18", DocumentKind.SelfInvoice),
new("AF19", "Integrazione acquisto beni art. 17 c.2", NumeratorKind.SalesInvoice, "AUT", null, "TD19", DocumentKind.SelfInvoice),
new("OF", "Ordine fornitore", NumeratorKind.PurchaseOrder, "ORF", null, null, DocumentKind.PurchaseOrder),
new("DDTF", "DDT fornitore (carico)", NumeratorKind.Inventory, null, "CAR", null, DocumentKind.PurchaseDeliveryNote),
new("FF", "Fattura fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseInvoice),
new("NCF", "Nota di credito fornitore", NumeratorKind.PurchaseInvoice, "PRA", null, null, DocumentKind.PurchaseCreditNote),
new("MM", "Movimento di magazzino", NumeratorKind.Inventory, "MAG", null, null, DocumentKind.InventoryEntry),
];
}
@@ -148,6 +148,11 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
services.AddSingleton<Khaemhat.Application.Documents.DocumentEngine>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentCopyService>();
services.AddSingleton(typeof(Khaemhat.Application.Documents.DocumentService<,>));
// Guided import and export (ADR 0031): the entities in the order of the screen.
services.AddSingleton<Khaemhat.Application.ImportExport.IImportTarget>(sp => ActivatorUtilities.CreateInstance<Khaemhat.Application.ImportExport.PartiesImportTarget>(
sp, Khaemhat.Core.Parties.PartyKind.Customer));
@@ -0,0 +1,48 @@
{
"document": {
"not-found": "Il documento non esiste più.",
"action": {
"not-allowed": "Nello stato attuale del documento questa operazione non è ammessa."
},
"type": {
"missing": "Il tipo documento non esiste.",
"no-kind": "Il tipo documento non ha un genere: sceglilo in Tabelle azienda, Tipi documento.",
"disabled": "Il tipo documento è disattivato.",
"family": "Questo tipo documento appartiene a un'altra famiglia di documenti.",
"locked": "Il tipo di un documento già salvato non si può cambiare."
},
"party": {
"required": "Indica il cliente o il fornitore."
},
"date": {
"required": "Indica la data del documento.",
"numbered": "La data di un documento numerato non si può cambiare."
},
"lines": {
"required": "Il documento non ha righe."
},
"line": {
"kind-not-allowed": "Questo tipo di riga non è ammesso in questo documento.",
"description-required": "Ogni riga ha bisogno di una descrizione.",
"item-required": "Una riga articolo ha bisogno dell'articolo.",
"below-fulfilled": "La quantità non può scendere sotto quella già evasa.",
"fulfilled-removed": "Una riga già evasa da altri documenti non si può togliere.",
"source-invalid": "La riga d'origine non esiste o non può essere evasa da questo documento."
},
"cancel": {
"reason-required": "Per annullare una fattura indica il motivo.",
"has-followers": "Altri documenti evadono questo: annulla prima quelli."
},
"copy": {
"direction": "Si trasforma solo in un documento della stessa direzione (vendita o acquisto).",
"nothing-left": "Non c'è più nulla da evadere.",
"source-not-open": "Il documento non è confermato o è chiuso o annullato: non si può evadere."
},
"number": {
"date-before-last": "La data è anteriore a quella dell'ultimo documento numerato: con questo numeratore non sono ammessi documenti fuori sequenza.",
"numerator-missing": "Il numeratore del tipo documento non esiste.",
"numerator-disabled": "Il numeratore del tipo documento è disattivato.",
"too-long": "Il numero formattato supera i 30 caratteri: accorcia il formato del numeratore."
}
}
}
@@ -255,6 +255,7 @@
"IsDefault": "Predefinito",
"Symbol": "Simbolo",
"Decimals": "Decimali",
"DocumentKind": "Genere",
"NumeratorId": "Numeratore",
"InventoryReasonId": "Causale di magazzino",
"EInvoiceType": "Tipo TD",
@@ -266,6 +267,7 @@
"Prefix": "Prefisso",
"Format": "Formato",
"LastNumber": "Ultimo numero",
"LastDate": "Data dell'ultimo numero",
"GapsAllowed": "Ammessi buchi di numerazione",
"CurrencyCode": "Valuta",
"VatIncluded": "IVA inclusa",
@@ -353,6 +355,25 @@
"Journal": "Prima nota",
"Other": "Altro"
},
"DocumentKind": {
"Quotation": "Preventivo",
"SalesOrder": "Ordine cliente",
"DeliveryNote": "DDT di vendita",
"ImmediateInvoice": "Fattura immediata",
"AccompanyingInvoice": "Fattura accompagnatoria",
"DeferredInvoice": "Fattura differita",
"DownPaymentInvoice": "Fattura di acconto",
"CreditNote": "Nota di credito",
"DebitNote": "Nota di debito",
"Fee": "Parcella",
"ProForma": "Pro forma",
"SelfInvoice": "Autofattura o integrazione",
"PurchaseOrder": "Ordine fornitore",
"PurchaseDeliveryNote": "DDT fornitore",
"PurchaseInvoice": "Fattura fornitore",
"PurchaseCreditNote": "Nota di credito fornitore",
"InventoryEntry": "Movimento di magazzino"
},
"StockEffect": {
"None": "Nessuno",
"Load": "Carico",
@@ -446,6 +467,9 @@
"numerator": {
"format": "Il formato deve contenere il segnaposto del numero e solo segnaposto noti (anno, prefisso, sezionale)."
},
"document-type": {
"kind-required": "Scegli il genere: dice come si comportano i documenti di questo tipo."
},
"year": {
"range": "Anno fuori intervallo."
},
+3 -1
View File
@@ -194,6 +194,7 @@ public static class TableScreens
Fields =
[
new(nameof(DocumentType.Kind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "170px" },
new(nameof(DocumentType.DocumentKind), TableFieldKind.Choice) { Required = true, InGrid = true, Width = "190px" },
new(nameof(DocumentType.NumeratorId), TableFieldKind.Lookup) { Lookup = typeof(DocumentNumerator), InGrid = true, Width = "120px" },
new(nameof(DocumentType.InventoryReasonId), TableFieldKind.Lookup) { Lookup = typeof(InventoryReason) },
new(nameof(DocumentType.EInvoiceType), TableFieldKind.CodeList) { CodeList = EInvoice(f => f.DocumentTypes), InGrid = true, Width = "90px" },
@@ -212,7 +213,8 @@ public static class TableScreens
new(nameof(DocumentNumerator.Prefix), TableFieldKind.Code) { MaxLength = 10, Span = 4 },
new(nameof(DocumentNumerator.Format)) { Required = true, Span = 8, InGrid = true, Width = "180px" },
new(nameof(DocumentNumerator.LastNumber), TableFieldKind.Number) { Min = 0, InGrid = true, Width = "100px", Span = 4 },
new(nameof(DocumentNumerator.GapsAllowed), TableFieldKind.Bool) { Span = 8 },
new(nameof(DocumentNumerator.LastDate), TableFieldKind.Date) { Span = 4 },
new(nameof(DocumentNumerator.GapsAllowed), TableFieldKind.Bool) { Span = 4 },
],
},
new("listini", "price-lists", typeof(PriceList), "tag", TableGroup.Sales)