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;
/// The document engine on a real instance (issue #47): definitions, numbering, states, copies and fulfilment.
[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>();
var sales = app.Services.GetRequiredService>();
var copies = app.Services.GetRequiredService();
var customer = await CustomerAsync(app, company);
var vat = await VatAsync(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, TaxCodeId = vat });
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Free, Description = "Raccordo a T", Quantity = 4m, Price = 2m, TaxCodeId = vat });
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(() => orders.SaveAsync(Root, company, order));
Assert.AreEqual("Lines.0.Quantity:" + DocumentErrors.LineBelowFulfilled, below.Errors.Single());
await Assert.ThrowsExactlyAsync(() => 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(() => 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(() => 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(() => sales.SaveAsync(Root, company, invoice));
await Assert.ThrowsExactlyAsync(() => sales.DeleteAsync(Root, company, invoice.Header.Id));
await Assert.ThrowsExactlyAsync(() => sales.CancelAsync(Root, company, first.Header.Id, null), "Fulfilled by the invoice.");
var reason = await Assert.ThrowsExactlyAsync(() => 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();
var sales = app.Services.GetRequiredService>();
var customer = await CustomerAsync(app, company);
var vat = await VatAsync(app, company);
var year = DateTime.Now.Year;
var definitions = await engine.DefinitionsAsync(Root, company);
Assert.HasCount(26, 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(() => 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(() => 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(() => sales.SaveAsync(Root, company, delivery));
Assert.AreEqual("Lines.0.Kind:" + DocumentErrors.LineKindNotAllowed, expense.Errors.Single());
var later = await InvoiceAsync(sales, company, customer, vat, new DateOnly(year, 3, 10));
var earlier = await InvoiceAsync(sales, company, customer, vat, new DateOnly(year, 3, 9));
var empty = await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, vat, new DateOnly(year, 3, 11), lines: false));
var noLines = await Assert.ThrowsExactlyAsync(() => 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(() => 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();
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();
var noKind = await Assert.ThrowsExactlyAsync(() =>
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().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> NewInvoiceAsync(
DocumentService sales, string company, long customer, long vat, 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, TaxCodeId = vat });
}
return invoice;
}
private static async Task> InvoiceAsync(
DocumentService sales, string company, long customer, long vat, DateOnly date) =>
await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, vat, date));
private static DocumentRecord Typed(DocumentRecord record) =>
new() { Header = (SaleDocument)record.Header, Lines = [.. record.Lines.Cast()] };
private static async Task VatAsync(WebApplication app, string company) =>
(await app.Services.GetRequiredService().ActiveAsync(Root, company)).Single(t => t.Code == "22").Id;
private static async Task CustomerAsync(WebApplication app, string company)
{
var parties = app.Services.GetRequiredService();
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;
}
}