feat: document engine with kinds, states, atomic numbering and fulfilment (#47)
One engine for sales, purchases and warehouse documents (ADR 0032). Each document type now carries a kind that decides its family of tables, life cycle, effects, accepted lines, the kinds it fulfils and its permissions, so company-defined types work without code. - Six families of header and line tables plus document_links; document_types gets document_kind (seeded types filled by the migration and the Italian template), document_numerators gets last_date. - DocumentStateMachine with the order, invoice and simple life cycles and the actions each state admits; issued invoices are immutable and are cancelled with a reason only before the file reaches the exchange system. - DocumentNumberingService numbers at confirmation inside the transaction under the numerator lock (advisory lock on PostgreSQL, write lock on SQLite): no duplicates, a rollback gives the number back, out-of-sequence dates refused on gap-free numerators, the new year's numerator created on first use, gap report. - DocumentEngine, the generic DocumentService<THeader, TLine> and DocumentCopyService: save, confirm or issue, cancel, close, reopen, delete, duplicate and transform; links are recorded at confirmation and removed at cancellation, and FulfillmentCalculator recomputes quantities and states. - Tests: rules in Core, concurrent numbering on SQLite and PostgreSQL (data tests, run on PostgreSQL 18 locally), order to delivery notes to deferred invoice on a real instance. Wiki (Vendite, Tabelle azienda), CHANGELOG, STATUS, DATA-MODEL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fa9304834a
commit
ddd2273f7e
33 files changed
+4081
-37
No files matched your search
@@ -0,0 +1,121 @@
|
||||
using Khaemhat.Core.Documents;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Documents;
|
||||
|
||||
/// <summary>The declarative rules of the document engine (issue #47): behaviours, states, fulfilment.</summary>
|
||||
[TestClass]
|
||||
public sealed class DocumentRulesTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void EveryKind_HasABehaviour_AndFulfilsOnlyKindsOfTheSameDirection()
|
||||
{
|
||||
Assert.HasCount(Enum.GetValues<DocumentKind>().Length, DocumentBehaviors.All);
|
||||
foreach (var behavior in DocumentBehaviors.All)
|
||||
{
|
||||
Assert.IsNotEmpty(behavior.Lines, behavior.Kind.ToString());
|
||||
foreach (var source in behavior.Sources)
|
||||
{
|
||||
Assert.AreEqual(behavior.Direction, DocumentBehaviors.Of(source).Direction, $"{behavior.Kind} fulfils {source}");
|
||||
}
|
||||
|
||||
// Invoices are the only documents that reach the exchange system.
|
||||
Assert.AreEqual(behavior.Lifecycle == DocumentLifecycle.Invoice, behavior.Has(DocumentEffects.EInvoice), behavior.Kind.ToString());
|
||||
}
|
||||
|
||||
Assert.AreEqual(DocumentFamily.SaleDocument, DocumentBehaviors.Of(DocumentKind.DeliveryNote).Family);
|
||||
Assert.IsTrue(DocumentBehaviors.Of(DocumentKind.DeferredInvoice).Fulfils(DocumentKind.DeliveryNote));
|
||||
Assert.IsFalse(DocumentBehaviors.Of(DocumentKind.DeferredInvoice).Fulfils(DocumentKind.SalesOrder));
|
||||
Assert.IsTrue(DocumentBehaviors.Of(DocumentKind.Quotation).NeedsParty);
|
||||
Assert.IsFalse(DocumentBehaviors.Of(DocumentKind.InventoryEntry).NeedsParty);
|
||||
CollectionAssert.AreEquivalent(
|
||||
new[] { DocumentKind.DeliveryNote, DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice,
|
||||
DocumentKind.CreditNote, DocumentKind.DebitNote, DocumentKind.Fee, DocumentKind.ProForma, DocumentKind.SelfInvoice },
|
||||
DocumentBehaviors.KindsOf(DocumentFamily.SaleDocument).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OrderLifecycle_MovesThroughItsStates_AndRefusesTheRest()
|
||||
{
|
||||
const DocumentLifecycle Order = DocumentLifecycle.Order;
|
||||
Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.Apply(Order, DocumentStatus.Draft, DocumentAction.Confirm));
|
||||
Assert.AreEqual(DocumentStatus.Closed, DocumentStateMachine.Apply(Order, DocumentStatus.PartiallyFulfilled, DocumentAction.Close));
|
||||
Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.Apply(Order, DocumentStatus.Closed, DocumentAction.Reopen));
|
||||
Assert.AreEqual(DocumentStatus.Cancelled, DocumentStateMachine.Apply(Order, DocumentStatus.Confirmed, DocumentAction.Cancel));
|
||||
Assert.IsTrue(DocumentStateMachine.IsEditable(Order, DocumentStatus.PartiallyFulfilled));
|
||||
Assert.IsFalse(DocumentStateMachine.IsEditable(Order, DocumentStatus.Fulfilled));
|
||||
|
||||
var refused = Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.PartiallyFulfilled, DocumentAction.Cancel));
|
||||
Assert.AreEqual(DocumentAction.Cancel, refused.Action);
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Confirmed, DocumentAction.Delete));
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Draft, DocumentAction.Issue));
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Cancelled, DocumentAction.Reopen));
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(Order, DocumentStatus.Issued, DocumentAction.Copy), "Not a state of the cycle.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvoiceLifecycle_IsUnchangeableOnceIssued_AndCancelledOnlyBeforeTheExchangeSystemHasIt()
|
||||
{
|
||||
const DocumentLifecycle Invoice = DocumentLifecycle.Invoice;
|
||||
var status = DocumentStatus.Draft;
|
||||
foreach (var action in new[] { DocumentAction.Issue, DocumentAction.GenerateXml, DocumentAction.Send, DocumentAction.MarkDelivered })
|
||||
{
|
||||
status = DocumentStateMachine.Apply(Invoice, status, action);
|
||||
}
|
||||
|
||||
Assert.AreEqual(DocumentStatus.SdiDelivered, status);
|
||||
CollectionAssert.AreEqual(new[] { DocumentAction.Copy }, DocumentStateMachine.Actions(Invoice, DocumentStatus.SdiDelivered).ToArray());
|
||||
foreach (var issued in DocumentStateMachine.States(Invoice).Where(s => s != DocumentStatus.Draft))
|
||||
{
|
||||
Assert.IsFalse(DocumentStateMachine.IsEditable(Invoice, issued), issued.ToString());
|
||||
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, issued, DocumentAction.Delete), issued.ToString());
|
||||
}
|
||||
|
||||
Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiGenerated, DocumentAction.Cancel));
|
||||
Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiRejected, DocumentAction.Cancel));
|
||||
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiSent, DocumentAction.Cancel));
|
||||
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.Draft, DocumentAction.Confirm), "Invoices are issued, not confirmed.");
|
||||
Assert.AreEqual(DocumentStatus.SdiGenerated, DocumentStateMachine.Apply(Invoice, DocumentStatus.SdiRejected, DocumentAction.GenerateXml));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SimpleLifecycle_HasDraftConfirmedCancelled()
|
||||
{
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { DocumentStatus.Draft, DocumentStatus.Confirmed, DocumentStatus.Cancelled }, DocumentStateMachine.States(DocumentLifecycle.Simple).ToArray());
|
||||
Assert.ThrowsExactly<InvalidDocumentActionException>(() => DocumentStateMachine.Apply(DocumentLifecycle.Simple, DocumentStatus.Confirmed, DocumentAction.Close));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Fulfilment_SumsTheLinks_AndClosedLinesCountAsFulfilled()
|
||||
{
|
||||
var lines = new List<DocumentLine>
|
||||
{
|
||||
new SaleOrderLine { Id = 1, Kind = DocumentLineKind.Item, Quantity = 10m },
|
||||
new SaleOrderLine { Id = 2, Kind = DocumentLineKind.Free, Quantity = 4m },
|
||||
new SaleOrderLine { Id = 3, Kind = DocumentLineKind.Description },
|
||||
new SaleOrderLine { Id = 4, Kind = DocumentLineKind.Expense, Quantity = 1m },
|
||||
};
|
||||
Assert.AreEqual(FulfillmentState.None, FulfillmentCalculator.StateOf(lines));
|
||||
|
||||
var changed = FulfillmentCalculator.Apply(lines, [Link(1, 6m), Link(1, 1m)]);
|
||||
Assert.HasCount(1, changed);
|
||||
Assert.AreEqual(7m, lines[0].FulfilledQuantity);
|
||||
Assert.AreEqual(3m, lines[0].Residual);
|
||||
Assert.AreEqual(0m, lines[3].Residual, "Expenses are not fulfilled.");
|
||||
Assert.AreEqual(FulfillmentState.Partial, FulfillmentCalculator.StateOf(lines));
|
||||
|
||||
FulfillmentCalculator.Apply(lines, [Link(1, 12m), Link(2, 1m)]);
|
||||
Assert.AreEqual(0m, lines[0].Residual, "More than ordered leaves nothing to fulfil.");
|
||||
Assert.AreEqual(FulfillmentState.Partial, FulfillmentCalculator.StateOf(lines));
|
||||
lines[1].FulfillmentClosed = true;
|
||||
Assert.AreEqual(FulfillmentState.Fulfilled, FulfillmentCalculator.StateOf(lines));
|
||||
|
||||
Assert.AreEqual(DocumentStatus.Fulfilled, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.Confirmed, FulfillmentState.Fulfilled));
|
||||
Assert.AreEqual(DocumentStatus.Confirmed, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.PartiallyFulfilled, FulfillmentState.None));
|
||||
Assert.AreEqual(DocumentStatus.Closed, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Order, DocumentStatus.Closed, FulfillmentState.Fulfilled));
|
||||
Assert.AreEqual(DocumentStatus.Issued, DocumentStateMachine.AfterFulfillment(DocumentLifecycle.Invoice, DocumentStatus.Issued, FulfillmentState.Fulfilled));
|
||||
}
|
||||
|
||||
private static DocumentLink Link(long sourceLine, decimal quantity) =>
|
||||
new() { SourceFamily = DocumentFamily.SaleOrder, SourceLineId = sourceLine, Quantity = quantity };
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Data.Tests.Support;
|
||||
|
||||
namespace Khaemhat.Data.Tests;
|
||||
|
||||
/// <summary>Document numbering on both engines (issue #47): concurrent confirmations never share a number.</summary>
|
||||
[TestClass]
|
||||
public sealed class DocumentNumberingTests
|
||||
{
|
||||
private static readonly DateOnly Day = new(2026, 11, 12);
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(TestDatabase.Sqlite)]
|
||||
[DataRow(TestDatabase.Postgres)]
|
||||
public async Task ConcurrentConfirmations_GetEveryNumberOnce_AndRollbacksGiveTheNumberBack(string engine)
|
||||
{
|
||||
await using var db = await TestDatabase.CreateAsync(engine);
|
||||
var id = await NumeratorAsync(db);
|
||||
const int Workers = 24;
|
||||
|
||||
var results = await Task.WhenAll(Enumerable.Range(0, Workers).Select(i => Task.Run(async () =>
|
||||
{
|
||||
await using var uow = await db.OpenAsync();
|
||||
await uow.BeginAsync();
|
||||
var number = await DocumentNumberingService.NextAsync(uow, id, Day);
|
||||
await Task.Yield();
|
||||
if (i % 4 == 0)
|
||||
{
|
||||
await uow.RollbackAsync();
|
||||
return (long?)null;
|
||||
}
|
||||
|
||||
await uow.CommitAsync();
|
||||
return number.Number;
|
||||
})));
|
||||
|
||||
var given = results.OfType<long>().Order().ToArray();
|
||||
CollectionAssert.AreEqual(Enumerable.Range(1, given.Length).Select(n => (long)n).ToArray(), given, "Each number once, none skipped.");
|
||||
await using var check = await db.OpenAsync();
|
||||
var numerator = await check.Repository<DocumentNumerator, long>().GetAsync(id);
|
||||
Assert.AreEqual((long)given.Length, numerator!.LastNumber);
|
||||
Assert.AreEqual(Day, numerator.LastDate);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(TestDatabase.Sqlite)]
|
||||
[DataRow(TestDatabase.Postgres)]
|
||||
public async Task Numbering_RefusesDatesBeforeTheLast_AndStartsANewYearFromOne(string engine)
|
||||
{
|
||||
await using var db = await TestDatabase.CreateAsync(engine);
|
||||
var id = await NumeratorAsync(db);
|
||||
await using var uow = await db.OpenAsync();
|
||||
|
||||
await uow.BeginAsync();
|
||||
var first = await DocumentNumberingService.NextAsync(uow, id, Day);
|
||||
Assert.AreEqual("FV-2026/0001", first.Text);
|
||||
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => DocumentNumberingService.NextAsync(uow, id, Day.AddDays(-1)));
|
||||
Assert.AreEqual(DocumentNumberingService.DateBeforeLast, refused.Errors.Single());
|
||||
Assert.AreEqual("FV-2027/0001", await DocumentNumberingService.PreviewAsync(uow, id, new DateOnly(2027, 1, 2)));
|
||||
|
||||
// The first document of a new year creates the numerator of that year with the same rules.
|
||||
var next = await DocumentNumberingService.NextAsync(uow, id, new DateOnly(2027, 1, 2));
|
||||
Assert.AreEqual(1L, next.Number);
|
||||
Assert.AreEqual("FV-2027/0001", next.Text);
|
||||
Assert.AreNotEqual(id, next.Numerator.Id);
|
||||
Assert.AreEqual(2, (await uow.Repository<DocumentNumerator, long>().ListAsync(Query.For<DocumentNumerator>().Where(n => n.Code == "FAT"))).Items.Count);
|
||||
Assert.AreEqual(2L, (await DocumentNumberingService.NextAsync(uow, id, Day.AddDays(1))).Number, "2026 goes on by itself.");
|
||||
await uow.CommitAsync();
|
||||
|
||||
// No document carries the number given in 2027: the check lists it as missing.
|
||||
CollectionAssert.AreEqual(new long[] { 1 }, (await DocumentNumberingService.FindGapsAsync(uow, next.Numerator.Id)).ToArray());
|
||||
}
|
||||
|
||||
private static async Task<long> NumeratorAsync(TestDatabase db)
|
||||
{
|
||||
await new MigrationRunner(db.Context).RunAsync(db.Target, MigrationCatalog.ForCompany());
|
||||
await using var setup = await db.OpenAsync();
|
||||
return await setup.Repository<DocumentNumerator, long>().InsertAsync(new DocumentNumerator
|
||||
{
|
||||
Code = "FAT",
|
||||
Description = "Fatture",
|
||||
Kind = NumeratorKind.SalesInvoice,
|
||||
Year = 2026,
|
||||
Prefix = "FV",
|
||||
Format = "{prefix}-{year}/{number:D4}",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@
|
||||
<ProjectReference Include="../../src/Khaemhat.Data.Sqlite/Khaemhat.Data.Sqlite.csproj" />
|
||||
<ProjectReference Include="../../src/Khaemhat.Data.PostgreSql/Khaemhat.Data.PostgreSql.csproj" />
|
||||
<ProjectReference Include="../../src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj" />
|
||||
<!-- The document numbering (issue #47) runs against both engines here, the only tests the tag CI runs on PostgreSQL. -->
|
||||
<ProjectReference Include="../../src/Khaemhat.Application/Khaemhat.Application.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -78,6 +78,9 @@ public sealed class MappingTests
|
||||
"discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", "code_sequences",
|
||||
"parties", "party_addresses", "party_contacts", "party_bank_accounts", "party_sales_terms", "party_purchase_terms", "party_fiscal",
|
||||
"items", "item_uoms", "item_barcodes", "item_prices", "item_suppliers", "item_substitutes", "party_item_codes",
|
||||
"sale_quotations", "sale_quotation_lines", "sale_orders", "sale_order_lines", "sale_documents", "sale_document_lines",
|
||||
"purchase_orders", "purchase_order_lines", "purchase_documents", "purchase_document_lines", "inventory_documents", "inventory_document_lines",
|
||||
"document_links",
|
||||
];
|
||||
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Parties;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Web.Tests.Hosting;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Documents;
|
||||
|
||||
/// <summary>The document engine on a real instance (issue #47): definitions, numbering, states, copies and fulfilment.</summary>
|
||||
[TestClass]
|
||||
public sealed class DocumentEngineTests
|
||||
{
|
||||
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
|
||||
[TestMethod]
|
||||
public async Task OrderToDeliveryNotesToDeferredInvoice_FollowsTheFulfilmentLineByLine()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var orders = app.Services.GetRequiredService<DocumentService<SaleOrder, SaleOrderLine>>();
|
||||
var sales = app.Services.GetRequiredService<DocumentService<SaleDocument, SaleDocumentLine>>();
|
||||
var copies = app.Services.GetRequiredService<DocumentCopyService>();
|
||||
var customer = await CustomerAsync(app, company);
|
||||
var year = DateTime.Now.Year;
|
||||
|
||||
var order = await orders.NewAsync(Root, company, "OC");
|
||||
Assert.AreEqual(DocumentKind.SalesOrder, order.Header.Kind);
|
||||
order.Header.PartyId = customer;
|
||||
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Free, Description = "Valvola a sfera 1/2\"", Quantity = 10m, Price = 5m });
|
||||
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Free, Description = "Raccordo a T", Quantity = 4m, Price = 2m });
|
||||
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Description, Description = "Consegna in cantiere" });
|
||||
order = await orders.SaveAsync(Root, company, order);
|
||||
Assert.AreEqual(DocumentStatus.Draft, order.Header.Status);
|
||||
Assert.IsNull(order.Header.Number, "Numbered at confirmation.");
|
||||
CollectionAssert.AreEqual(new[] { 1, 2, 3 }, order.Lines.Select(l => l.LineNumber).ToArray());
|
||||
|
||||
order = await orders.ConfirmAsync(Root, company, order.Header.Id);
|
||||
Assert.AreEqual(DocumentStatus.Confirmed, order.Header.Status);
|
||||
Assert.AreEqual($"OC-{year}-0001", order.Header.DocumentNumber);
|
||||
Assert.AreEqual(Root.UserName, order.Header.ConfirmedBy);
|
||||
|
||||
// First delivery: part of the first line only.
|
||||
var first = Typed(await copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT"));
|
||||
Assert.AreEqual(DocumentKind.DeliveryNote, first.Header.Kind);
|
||||
Assert.HasCount(3, first.Lines);
|
||||
Assert.AreEqual(order.Lines[0].Id, first.Lines[0].SourceLineId);
|
||||
Assert.IsNull(first.Lines[2].SourceLineId, "Descriptions are copied without a link.");
|
||||
first.Lines[0].Quantity = 6m;
|
||||
first.Lines.RemoveAt(1);
|
||||
first = await sales.SaveAsync(Root, company, first);
|
||||
Assert.AreEqual(DocumentStatus.Confirmed, (await orders.GetAsync(Root, company, order.Header.Id))!.Header.Status, "A draft fulfils nothing.");
|
||||
|
||||
first = await sales.ConfirmAsync(Root, company, first.Header.Id);
|
||||
Assert.AreEqual($"1/{year}", first.Header.DocumentNumber);
|
||||
order = (await orders.GetAsync(Root, company, order.Header.Id))!;
|
||||
Assert.AreEqual(DocumentStatus.PartiallyFulfilled, order.Header.Status);
|
||||
Assert.AreEqual(6m, order.Lines[0].FulfilledQuantity);
|
||||
Assert.AreEqual(4m, order.Lines[0].Residual);
|
||||
|
||||
// The order can still change, but not below what was delivered.
|
||||
order.Lines[0].Quantity = 5m;
|
||||
var below = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => orders.SaveAsync(Root, company, order));
|
||||
Assert.AreEqual("Lines.0.Quantity:" + DocumentErrors.LineBelowFulfilled, below.Errors.Single());
|
||||
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => orders.CancelAsync(Root, company, order.Header.Id, null));
|
||||
|
||||
// Second delivery: the rest.
|
||||
var second = await copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT");
|
||||
CollectionAssert.AreEqual(new[] { 4m, 4m, 0m }, second.Lines.Select(l => l.Quantity).ToArray());
|
||||
await sales.ConfirmAsync(Root, company, second.Header.Id);
|
||||
Assert.AreEqual(DocumentStatus.Fulfilled, (await orders.GetAsync(Root, company, order.Header.Id))!.Header.Status);
|
||||
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT"));
|
||||
|
||||
// Cancelling a delivery gives its quantities back.
|
||||
var cancelled = await sales.CancelAsync(Root, company, second.Header.Id, null);
|
||||
Assert.AreEqual(DocumentStatus.Cancelled, cancelled.Header.Status);
|
||||
Assert.AreEqual($"2/{year}", cancelled.Header.DocumentNumber, "The number stays.");
|
||||
order = (await orders.GetAsync(Root, company, order.Header.Id))!;
|
||||
Assert.AreEqual(DocumentStatus.PartiallyFulfilled, order.Header.Status);
|
||||
Assert.AreEqual(0m, order.Lines[1].FulfilledQuantity);
|
||||
|
||||
// Closing the rest, then reopening, comes back to what the lines say.
|
||||
Assert.AreEqual(DocumentStatus.Closed, (await orders.CloseAsync(Root, company, order.Header.Id)).Header.Status);
|
||||
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => copies.CopyAsync(Root, company, DocumentFamily.SaleOrder, order.Header.Id, "DDT"));
|
||||
Assert.AreEqual(DocumentStatus.PartiallyFulfilled, (await orders.ReopenAsync(Root, company, order.Header.Id)).Header.Status);
|
||||
|
||||
// The deferred invoice fulfils the delivery note; once issued it is unchangeable.
|
||||
var invoice = Typed(await copies.CopyAsync(Root, company, DocumentFamily.SaleDocument, first.Header.Id, "FD"));
|
||||
invoice = await sales.ConfirmAsync(Root, company, invoice.Header.Id);
|
||||
Assert.AreEqual(DocumentStatus.Issued, invoice.Header.Status);
|
||||
Assert.AreEqual($"1/{year}", invoice.Header.DocumentNumber, "Invoices have their own numerator.");
|
||||
Assert.AreEqual(DocumentStatus.Fulfilled, (await sales.GetAsync(Root, company, first.Header.Id))!.Header.Status);
|
||||
invoice.Header.Notes = "Changed";
|
||||
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => sales.SaveAsync(Root, company, invoice));
|
||||
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => sales.DeleteAsync(Root, company, invoice.Header.Id));
|
||||
await Assert.ThrowsExactlyAsync<InvalidDocumentActionException>(() => sales.CancelAsync(Root, company, first.Header.Id, null), "Fulfilled by the invoice.");
|
||||
|
||||
var reason = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.CancelAsync(Root, company, invoice.Header.Id, " "));
|
||||
Assert.AreEqual("CancelReason:" + DocumentErrors.CancelReasonRequired, reason.Errors.Single());
|
||||
invoice = await sales.CancelAsync(Root, company, invoice.Header.Id, "Emessa per errore");
|
||||
Assert.AreEqual("Emessa per errore", invoice.Header.CancelReason);
|
||||
Assert.AreEqual(DocumentStatus.Confirmed, (await sales.GetAsync(Root, company, first.Header.Id))!.Header.Status);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Invoices_AreCheckedAndNumberedWithoutGapsInDateOrder_AndDraftsAreDeleted()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
||||
var sales = app.Services.GetRequiredService<DocumentService<SaleDocument, SaleDocumentLine>>();
|
||||
var customer = await CustomerAsync(app, company);
|
||||
var year = DateTime.Now.Year;
|
||||
|
||||
var definitions = await engine.DefinitionsAsync(Root, company);
|
||||
Assert.HasCount(20, definitions, "Every seeded type has its kind.");
|
||||
Assert.AreEqual(DocumentKind.DeferredInvoice, definitions.Single(d => d.Code == "FD").Kind);
|
||||
Assert.AreEqual(DocumentAction.Issue, definitions.Single(d => d.Code == "FI").ConfirmAction);
|
||||
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.NewAsync(Root, company, "OC"), "An order is not a sale document.");
|
||||
|
||||
var draft = await sales.NewAsync(Root, company, "FI");
|
||||
draft.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Item, Description = "Senza articolo", Quantity = 1m });
|
||||
draft.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = " ", Quantity = 1m });
|
||||
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.SaveAsync(Root, company, draft));
|
||||
CollectionAssert.AreEquivalent(
|
||||
new[] { "PartyId:" + DocumentErrors.PartyRequired, "Lines.0.ItemId:" + DocumentErrors.LineItemRequired, "Lines.1.Description:" + DocumentErrors.LineDescriptionRequired },
|
||||
refused.Errors.ToArray());
|
||||
|
||||
var delivery = await sales.NewAsync(Root, company, "DDT");
|
||||
delivery.Header.PartyId = customer;
|
||||
delivery.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Expense, Description = "Trasporto", Quantity = 1m });
|
||||
var expense = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.SaveAsync(Root, company, delivery));
|
||||
Assert.AreEqual("Lines.0.Kind:" + DocumentErrors.LineKindNotAllowed, expense.Errors.Single());
|
||||
|
||||
var later = await InvoiceAsync(sales, company, customer, new DateOnly(year, 3, 10));
|
||||
var earlier = await InvoiceAsync(sales, company, customer, new DateOnly(year, 3, 9));
|
||||
var empty = await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, new DateOnly(year, 3, 11), lines: false));
|
||||
var noLines = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.ConfirmAsync(Root, company, empty.Header.Id));
|
||||
Assert.AreEqual("Lines:" + DocumentErrors.LinesRequired, noLines.Errors.Single());
|
||||
|
||||
Assert.AreEqual($"1/{year}", (await sales.ConfirmAsync(Root, company, later.Header.Id)).Header.DocumentNumber);
|
||||
var outOfOrder = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => sales.ConfirmAsync(Root, company, earlier.Header.Id));
|
||||
Assert.AreEqual(DocumentNumberingService.DateBeforeLast, outOfOrder.Errors.Single());
|
||||
Assert.AreEqual(DocumentStatus.Draft, (await sales.GetAsync(Root, company, earlier.Header.Id))!.Header.Status, "Nothing changed.");
|
||||
|
||||
earlier.Header.DocumentDate = new DateOnly(year, 3, 12);
|
||||
earlier = await sales.SaveAsync(Root, company, earlier);
|
||||
var issued = await sales.ConfirmAsync(Root, company, earlier.Header.Id);
|
||||
Assert.AreEqual(2L, issued.Header.Number);
|
||||
|
||||
var factory = app.Services.GetRequiredService<IUnitOfWorkFactory>();
|
||||
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company)))
|
||||
{
|
||||
Assert.IsEmpty(await DocumentNumberingService.FindGapsAsync(uow, issued.Header.NumeratorId!.Value));
|
||||
}
|
||||
|
||||
var actions = await engine.ActionsAsync(Root, new DocumentRecord { Family = DocumentFamily.SaleDocument, Header = issued.Header });
|
||||
CollectionAssert.AreEquivalent(new[] { DocumentAction.Copy, DocumentAction.GenerateXml, DocumentAction.Cancel }, actions.ToArray());
|
||||
|
||||
await sales.DeleteAsync(Root, company, empty.Header.Id);
|
||||
Assert.IsNull(await sales.GetAsync(Root, company, empty.Header.Id));
|
||||
|
||||
// A type of the company needs a kind to be used.
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
var noKind = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() =>
|
||||
tables.SaveAsync(Root, company, new DocumentType { Code = "FX", Description = "Fattura speciale", Kind = NumeratorKind.SalesInvoice }));
|
||||
Assert.IsTrue(noKind.Errors.Any(e => e.EndsWith(TableCatalog.DocumentKindRequired, StringComparison.Ordinal)), string.Join(", ", noKind.Errors));
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryErrorCodeAndKind_HasAnItalianText()
|
||||
{
|
||||
var keys = new[] { typeof(DocumentErrors), typeof(DocumentNumberingService), typeof(DocumentDefinitionService) }
|
||||
.SelectMany(t => t.GetFields())
|
||||
.Where(f => f.IsLiteral && f.FieldType == typeof(string))
|
||||
.Select(f => (string)f.GetRawConstantValue()!)
|
||||
.Append(InvalidDocumentActionException.Code)
|
||||
.Append(TableCatalog.DocumentKindRequired)
|
||||
.Concat(Enum.GetValues<DocumentKind>().Select(k => Khaemhat.Web.Tables.TableScreens.EnumKey(k)))
|
||||
.ToList();
|
||||
var missing = keys.Where(k => !Shell.ShellTests.Texts.Contains(k)).ToList();
|
||||
Assert.IsEmpty(missing, string.Join(", ", missing));
|
||||
}
|
||||
|
||||
private static async Task<DocumentRecord<SaleDocument, SaleDocumentLine>> NewInvoiceAsync(
|
||||
DocumentService<SaleDocument, SaleDocumentLine> sales, string company, long customer, DateOnly date, bool lines = true)
|
||||
{
|
||||
var invoice = await sales.NewAsync(Root, company, "FI");
|
||||
invoice.Header.PartyId = customer;
|
||||
invoice.Header.DocumentDate = date;
|
||||
if (lines)
|
||||
{
|
||||
invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = "Assistenza tecnica", Quantity = 2m, Price = 40m });
|
||||
}
|
||||
|
||||
return invoice;
|
||||
}
|
||||
|
||||
private static async Task<DocumentRecord<SaleDocument, SaleDocumentLine>> InvoiceAsync(
|
||||
DocumentService<SaleDocument, SaleDocumentLine> sales, string company, long customer, DateOnly date) =>
|
||||
await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, date));
|
||||
|
||||
private static DocumentRecord<SaleDocument, SaleDocumentLine> Typed(DocumentRecord record) =>
|
||||
new() { Header = (SaleDocument)record.Header, Lines = [.. record.Lines.Cast<SaleDocumentLine>()] };
|
||||
|
||||
private static async Task<long> CustomerAsync(WebApplication app, string company)
|
||||
{
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
var record = await parties.NewAsync(Root, company, PartyKind.Customer);
|
||||
record.Party.Name = "Rossi Impianti S.r.l.";
|
||||
record.Party.VatNumber = "01234567897";
|
||||
return (await parties.SaveAsync(Root, company, record)).Party.Id;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user