using Khaemhat.Application.Documents; using Khaemhat.Application.Parties; using Khaemhat.Application.Querying; 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.Web.Documents; using Khaemhat.Web.Tests.Hosting; using Khaemhat.Web.Ui; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace Khaemhat.Web.Tests.Documents; /// /// The sales screens on a real instance (issues #48-#51): what the editor proposes, the totals saved with the document, /// the radar, the deferred invoicing of several delivery notes and customers. /// [TestClass] public sealed class SalesFlowTests { private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); [TestMethod] public async Task Save_WritesTheVatSummaryAndTheInstallments_FromTheTermsOfTheCustomer() { var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); await using (app) { var engine = app.Services.GetRequiredService(); var editor = app.Services.GetRequiredService(); var tables = app.Services.GetRequiredService(); var taxes = await tables.ActiveAsync(Root, company); var terms = await tables.ActiveAsync(Root, company); var vat22 = taxes.Single(t => t.Code == "22").Id; var vat10 = taxes.Single(t => t.Code == "10").Id; var endOfMonth = terms.Single(t => t.Code == "BB30FM").Id; var customer = await CustomerAsync(app, company, "Bianchi Forniture S.p.A.", "07654321012", endOfMonth); var invoice = await engine.NewAsync(Root, company, "FI"); invoice.Header.DocumentDate = new DateOnly(DateTime.Now.Year, 3, 10); await editor.ApplyPartyAsync(Root, company, invoice, customer); Assert.AreEqual(customer, invoice.Header.PartyId); Assert.AreEqual(endOfMonth, invoice.Header.PaymentTermId, "The terms of the customer are proposed."); invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = "Quadro elettrico", Quantity = 2m, Price = 150m, DiscountFormula = "10", TaxCodeId = vat22 }); invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = "Manuale d'uso", Quantity = 1m, Price = 20m, TaxCodeId = vat10 }); invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Description, Description = "Consegna al magazzino centrale" }); // The preview computes what the save will write, without writing. var preview = await editor.PreviewAsync(Root, company, invoice); Assert.AreEqual(290m, invoice.Header.TaxableAmount); Assert.HasCount(2, preview.Summary); var saved = await engine.SaveAsync(Root, company, invoice); Assert.AreEqual(270m, saved.Lines[0].TaxableAmount, "2 x 150 less 10%."); Assert.AreEqual(290m, saved.Header.TaxableAmount); Assert.AreEqual(59.40m + 2m, saved.Header.TaxAmount); Assert.AreEqual(351.40m, saved.Header.TotalAmount); CollectionAssert.AreEquivalent(new[] { 22m, 10m }, saved.Figures.Summary.Select(s => s.Rate).ToArray()); var due = saved.Figures.Installments.Single(); Assert.AreEqual(351.40m, due.Amount); Assert.AreEqual(new DateOnly(DateTime.Now.Year, 4, 30), due.DueDate, "30 days, end of month."); // Read back, the figures are those written. var read = await engine.GetAsync(Root, company, DocumentFamily.SaleDocument, saved.Header.Id); Assert.HasCount(2, read!.Figures.Summary); Assert.HasCount(1, read.Figures.Installments); // The radar finds the draft by the name of the customer. var page = await editor.ListAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.ImmediateInvoice], new ListQuery { Search = "bianchi" }); Assert.AreEqual(saved.Header.Id, page.Items.Single().Id); Assert.AreEqual("Bianchi Forniture S.p.A.", page.Items[0].PartyName); Assert.AreEqual(351.40m, page.Items[0].Total); await app.StopAsync(); } } [TestMethod] public async Task DeferredInvoicing_MergesTheDeliveryNotesOfOneCustomer_AndLeavesTheOthersOpen() { var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); await using (app) { var engine = app.Services.GetRequiredService(); var editor = app.Services.GetRequiredService(); var copies = app.Services.GetRequiredService(); var first = await CustomerAsync(app, company, "Rossi Impianti S.r.l.", "02987654304", null); var second = await CustomerAsync(app, company, "Verdi Costruzioni S.n.c.", "03111222331", null); var month = new DateOnly(DateTime.Now.Year, 2, 1); var notes = new List { await DeliveryNoteAsync(engine, company, first, month.AddDays(2), "Tubo multistrato 16 mm", 50m), await DeliveryNoteAsync(engine, company, second, month.AddDays(5), "Collettore 4 vie", 2m), await DeliveryNoteAsync(engine, company, first, month.AddDays(9), "Raccordo a pressare", 30m), }; var open = await editor.OpenAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], null, month, month.AddMonths(1).AddDays(-1)); Assert.HasCount(3, open); CollectionAssert.AreEqual(new[] { "Rossi Impianti S.r.l.", "Rossi Impianti S.r.l.", "Verdi Costruzioni S.n.c." }, open.Select(o => o.Row.PartyName).ToArray()); var mixed = await Assert.ThrowsExactlyAsync(() => copies.MergeAsync(Root, company, DocumentFamily.SaleDocument, [notes[0].Header.Id, notes[1].Header.Id], "FD")); Assert.AreEqual(":" + DocumentErrors.CopyParties, mixed.Errors.Single()); var invoiceDate = month.AddMonths(1).AddDays(-1); var invoice = await copies.MergeAsync(Root, company, DocumentFamily.SaleDocument, [notes[0].Header.Id, notes[2].Header.Id], "FD", invoiceDate); Assert.AreEqual(DocumentKind.DeferredInvoice, invoice.Header.Kind); Assert.AreEqual(invoiceDate, invoice.Header.DocumentDate); Assert.HasCount(4, invoice.Lines, "A reference line before the lines of each delivery note."); StringAssert.StartsWith(invoice.Lines[0].Description, "Rif. DDT n. " + notes[0].Header.DocumentNumber); Assert.AreEqual(DocumentLineKind.Description, invoice.Lines[2].Kind); Assert.AreEqual(0m, invoice.Header.TaxableAmount, "Without VAT codes nothing is taxable yet."); // An invoice needs the VAT of every line before it is issued. var untaxed = await Assert.ThrowsExactlyAsync(() => engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, invoice.Header.Id)); CollectionAssert.AreEquivalent( new[] { "Lines.1.TaxCodeId:" + DocumentErrors.LineTaxRequired, "Lines.3.TaxCodeId:" + DocumentErrors.LineTaxRequired }, untaxed.Errors.ToArray()); var vat22 = (await app.Services.GetRequiredService().ActiveAsync(Root, company)).Single(t => t.Code == "22").Id; foreach (var line in invoice.Lines.Where(l => l.Kind != DocumentLineKind.Description)) { line.TaxCodeId = vat22; } invoice = await engine.SaveAsync(Root, company, invoice); Assert.AreEqual(80m * 3m, invoice.Header.TaxableAmount, "50 + 30 pieces at 3 euro."); Assert.AreEqual(52.80m, invoice.Header.TaxAmount); await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, invoice.Header.Id); Assert.AreEqual(DocumentStatus.Fulfilled, (await engine.GetAsync(Root, company, DocumentFamily.SaleDocument, notes[0].Header.Id))!.Header.Status); Assert.AreEqual(DocumentStatus.Fulfilled, (await engine.GetAsync(Root, company, DocumentFamily.SaleDocument, notes[2].Header.Id))!.Header.Status); var left = await editor.OpenAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], null, month, invoiceDate); Assert.AreEqual(notes[1].Header.Id, left.Single().Row.Id); // The invoice knows where its lines come from. var links = await editor.LinksAsync(Root, company, (await engine.GetAsync(Root, company, DocumentFamily.SaleDocument, invoice.Header.Id))!); CollectionAssert.AreEquivalent(new[] { notes[0].Header.Id, notes[2].Header.Id }, links.Select(l => l.Id).ToArray()); Assert.IsTrue(links.All(l => l.Direction == LinkDirection.Source)); await app.StopAsync(); } } [TestMethod] public void Screens_MapEveryKindToItsRadar_AndHaveTheirTexts() { var invoices = SalesScreens.Find("FATTURE")!; Assert.AreEqual(DocumentFamily.SaleDocument, invoices.Family); Assert.AreEqual("vendite/fatture/12", SalesScreens.RecordUrl(DocumentKind.Fee, 12)); Assert.AreEqual("vendite/note-credito/3", SalesScreens.RecordUrl(DocumentKind.DebitNote, 3)); Assert.AreEqual("vendite/ddt/nuovo?tipo=DDT", SalesScreens.NewUrl(SalesScreens.Find("ddt")!, "DDT")); Assert.AreEqual("acquisti/fatture/1", SalesScreens.RecordUrl(DocumentKind.PurchaseInvoice, 1)); Assert.AreEqual("magazzino/movimenti/4", SalesScreens.RecordUrl(DocumentKind.InventoryEntry, 4)); Assert.AreEqual(DocumentFamily.PurchaseDocument, SalesScreens.Find("acquisti", "fatture")!.Family); Assert.IsNull(SalesScreens.Find("magazzino", "fatture")); Assert.AreEqual("acquisti", SalesScreens.AreaOf("acquisti/fatture/3?x=1")); Assert.AreEqual("Purchases.Fields.Supplier", SalesScreens.PartyLabel(SalesScreens.Find("acquisti", "autofatture")!.Direction)); // Each sales kind belongs to one radar only. var kinds = SalesScreens.Sections.SelectMany(s => s.Kinds).ToList(); Assert.HasCount(kinds.Distinct().Count(), kinds); var texts = Shell.ShellTests.Texts; var today = new DateOnly(2026, 5, 10); Assert.AreEqual((texts["Sales.Outcomes.Expired"], KhTone.Warning), SalesScreens.State(texts, DocumentKind.Quotation, DocumentStatus.Confirmed, today.AddDays(-1), today)); Assert.AreEqual((texts["Sales.Outcomes.Accepted"], KhTone.Ok), SalesScreens.State(texts, DocumentKind.Quotation, DocumentStatus.Fulfilled, null, today)); Assert.AreEqual((texts["Sales.Outcomes.Refused"], KhTone.Error), SalesScreens.State(texts, DocumentKind.Quotation, DocumentStatus.Closed, null, today)); var keys = Enum.GetValues().Select(k => "Sales.Kinds." + k) .Concat(Enum.GetValues().Select(s => "Sales.States." + s)) .Concat(kinds.Select(k => "Sales.Hints.Kinds." + k)) .Concat(SalesScreens.Sections.SelectMany(s => new[] { "Sales.Sections." + s.Key + ".Title", "Sales.Sections." + s.Key + ".New" })) .Concat(Enum.GetValues().Select(d => "Sales.Links." + d)) .Concat(Enum.GetValues().Select(k => "Sales.LineKinds." + k)); var missing = keys.Where(k => !texts.Contains(k)).ToList(); Assert.IsEmpty(missing, string.Join(", ", missing)); } private static async Task DeliveryNoteAsync(DocumentEngine engine, string company, long customer, DateOnly date, string what, decimal quantity) { var note = await engine.NewAsync(Root, company, "DDT"); note.Header.PartyId = customer; note.Header.DocumentDate = date; note.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = what, Quantity = quantity, Price = 3m }); note = await engine.SaveAsync(Root, company, note); return await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, note.Header.Id); } private static async Task CustomerAsync(WebApplication app, string company, string name, string vatNumber, long? paymentTermId) { var parties = app.Services.GetRequiredService(); var record = await parties.NewAsync(Root, company, PartyKind.Customer); record.Party.Name = name; record.Party.VatNumber = vatNumber; record.Sales.PaymentTermId = paymentTermId; return (await parties.SaveAsync(Root, company, record)).Party.Id; } }