Quotations, orders, delivery notes, invoices and credit notes get their radars and one document screen (lines, header, transport, links, attachments) with the transformations of the engine, so a quotation reaches the invoice without retyping. The deferred invoicing groups the open delivery notes of a period by customer, payment and destination into one invoice each. Every document prints from one model: an HTML preview on screen and a PDF drawn by the in-house writer, kept among the attachments as a new version. "Invia per e-mail" proposes recipient, subject and text from the templates, attaches the PDF and hands it to a background queue that talks SMTP itself (no external library); the outcome goes to the log, section E-mail/PEC. The demo company now has a year of sales in every state, made through the engine, and run-dev.sh no longer writes to a stray B:\b folder under Git Bash. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f12848865d
commit
826042f828
31 files changed
+5682
-16
No files matched your search
@@ -0,0 +1,76 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Seeding;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Web.Tests.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Documents;
|
||||
|
||||
/// <summary>The demo sales (SPEC §14, issue #53): every kind of sales document, in every state, made through the engine.</summary>
|
||||
[TestClass]
|
||||
public sealed class DemoSalesTests
|
||||
{
|
||||
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
|
||||
[TestMethod]
|
||||
public async Task DemoSeed_MakesTheSalesOfTheYear_Once()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
await app.Services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo);
|
||||
var seeder = app.Services.GetRequiredService<DemoSalesSeeder>();
|
||||
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
|
||||
await seeder.SeedAsync(company, context);
|
||||
|
||||
var editor = app.Services.GetRequiredService<DocumentEditor>();
|
||||
var all = await AllAsync(editor, company);
|
||||
Assert.IsTrue(all.All(r => r.Date.Year == DateTime.Now.Year && r.Date <= DateOnly.FromDateTime(DateTime.Now)), "Dates of this year, never in the future.");
|
||||
|
||||
int Count(DocumentKind kind, DocumentStatus status) => all.Count(r => r.Kind == kind && r.Status == status);
|
||||
Assert.AreEqual(2, Count(DocumentKind.Quotation, DocumentStatus.Fulfilled), "Two quotations became orders.");
|
||||
Assert.AreEqual(1, Count(DocumentKind.Quotation, DocumentStatus.Closed), "One was refused.");
|
||||
Assert.AreEqual(1, Count(DocumentKind.Quotation, DocumentStatus.Draft));
|
||||
Assert.AreEqual(1, Count(DocumentKind.SalesOrder, DocumentStatus.Confirmed), "An order still to deliver.");
|
||||
Assert.AreEqual(3, Count(DocumentKind.SalesOrder, DocumentStatus.Fulfilled));
|
||||
Assert.AreEqual(2, Count(DocumentKind.DeliveryNote, DocumentStatus.Fulfilled), "Two delivery notes already invoiced.");
|
||||
Assert.AreEqual(3, Count(DocumentKind.DeliveryNote, DocumentStatus.Confirmed), "Three for the deferred invoicing.");
|
||||
Assert.AreEqual(4, Count(DocumentKind.ImmediateInvoice, DocumentStatus.Issued));
|
||||
Assert.AreEqual(1, Count(DocumentKind.ImmediateInvoice, DocumentStatus.Draft));
|
||||
Assert.AreEqual(2, Count(DocumentKind.DeferredInvoice, DocumentStatus.Issued));
|
||||
Assert.AreEqual(1, Count(DocumentKind.CreditNote, DocumentStatus.Issued));
|
||||
Assert.AreEqual(1, all.Count(r => r.Kind == DocumentKind.ProForma));
|
||||
Assert.IsTrue(all.Where(r => r.Status != DocumentStatus.Draft).All(r => r.DocumentNumber is not null && r.Total > 0m));
|
||||
|
||||
// The issued invoices and the note share one numerator, numbered in date order.
|
||||
var numbered = all.Where(r => r.Kind is DocumentKind.ImmediateInvoice or DocumentKind.DeferredInvoice or DocumentKind.CreditNote && r.Status == DocumentStatus.Issued)
|
||||
.OrderBy(r => r.Date).ThenBy(r => r.Id).Select(r => r.DocumentNumber).ToList();
|
||||
Assert.HasCount(7, numbered);
|
||||
CollectionAssert.AllItemsAreUnique(numbered);
|
||||
|
||||
var profile = await app.Services.GetRequiredService<CompanyProfileService>().GetAsync(Root, company);
|
||||
Assert.AreEqual(DemoSalesSeeder.CompanyVatNumber, profile.VatNumber);
|
||||
|
||||
// Run again, nothing changes.
|
||||
await seeder.SeedAsync(company, context);
|
||||
Assert.HasCount(all.Count, await AllAsync(editor, company));
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<List<DocumentRow>> AllAsync(DocumentEditor editor, string company)
|
||||
{
|
||||
var all = new List<DocumentRow>();
|
||||
foreach (var family in new[] { DocumentFamily.SaleQuotation, DocumentFamily.SaleOrder, DocumentFamily.SaleDocument })
|
||||
{
|
||||
all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues<DocumentKind>()], new ListQuery { Limit = 200 })).Items);
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
}
|
||||
@@ -29,13 +29,14 @@ public sealed class DocumentEngineTests
|
||||
var sales = app.Services.GetRequiredService<DocumentService<SaleDocument, SaleDocumentLine>>();
|
||||
var copies = app.Services.GetRequiredService<DocumentCopyService>();
|
||||
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 });
|
||||
order.Lines.Add(new SaleOrderLine { Kind = DocumentLineKind.Free, Description = "Raccordo a T", Quantity = 4m, Price = 2m });
|
||||
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);
|
||||
@@ -120,6 +121,7 @@ public sealed class DocumentEngineTests
|
||||
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
||||
var sales = app.Services.GetRequiredService<DocumentService<SaleDocument, SaleDocumentLine>>();
|
||||
var customer = await CustomerAsync(app, company);
|
||||
var vat = await VatAsync(app, company);
|
||||
var year = DateTime.Now.Year;
|
||||
|
||||
var definitions = await engine.DefinitionsAsync(Root, company);
|
||||
@@ -142,9 +144,9 @@ public sealed class DocumentEngineTests
|
||||
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 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<ValidationFailedException>(() => sales.ConfirmAsync(Root, company, empty.Header.Id));
|
||||
Assert.AreEqual("Lines:" + DocumentErrors.LinesRequired, noLines.Errors.Single());
|
||||
|
||||
@@ -195,26 +197,29 @@ public sealed class DocumentEngineTests
|
||||
}
|
||||
|
||||
private static async Task<DocumentRecord<SaleDocument, SaleDocumentLine>> NewInvoiceAsync(
|
||||
DocumentService<SaleDocument, SaleDocumentLine> sales, string company, long customer, DateOnly date, bool lines = true)
|
||||
DocumentService<SaleDocument, SaleDocumentLine> 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 });
|
||||
invoice.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Free, Description = "Assistenza tecnica", Quantity = 2m, Price = 40m, TaxCodeId = vat });
|
||||
}
|
||||
|
||||
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));
|
||||
DocumentService<SaleDocument, SaleDocumentLine> sales, string company, long customer, long vat, DateOnly date) =>
|
||||
await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, vat, date));
|
||||
|
||||
private static DocumentRecord<SaleDocument, SaleDocumentLine> Typed(DocumentRecord record) =>
|
||||
new() { Header = (SaleDocument)record.Header, Lines = [.. record.Lines.Cast<SaleDocumentLine>()] };
|
||||
|
||||
private static async Task<long> VatAsync(WebApplication app, string company) =>
|
||||
(await app.Services.GetRequiredService<TableService>().ActiveAsync<TaxCode>(Root, company)).Single(t => t.Code == "22").Id;
|
||||
|
||||
private static async Task<long> CustomerAsync(WebApplication app, string company)
|
||||
{
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Files;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Seeding;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Infrastructure.Mail;
|
||||
using Khaemhat.Web.Tests.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Documents;
|
||||
|
||||
/// <summary>Printing and sending documents (SPEC §9.4, §12.6, issue #52): the print model, the PDF, MIME, SMTP and the queue.</summary>
|
||||
[TestClass]
|
||||
public sealed class DocumentPrintMailTests
|
||||
{
|
||||
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
|
||||
[TestMethod]
|
||||
public void Template_FillsKnownFields_AndKeepsUnknownOnes()
|
||||
{
|
||||
var text = MailTemplateRenderer.Render("{{Documento}} n. {{ numero }} per {{Cliente}} {{Sconosciuto}}", new Dictionary<string, string?>
|
||||
{
|
||||
["Documento"] = "Fattura",
|
||||
["Numero"] = "7/2026",
|
||||
["Cliente"] = null,
|
||||
});
|
||||
|
||||
Assert.AreEqual("Fattura n. 7/2026 per {{Sconosciuto}}", text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Mime_WritesTextAndAttachmentInBase64()
|
||||
{
|
||||
var mail = new OutgoingMail(["a@example.com", "b@example.com"], "Fattura n. 7 · Granai", "Buongiorno,\nin allegato.")
|
||||
{
|
||||
Attachments = [new MailAttachment("fattura-7.pdf", "application/pdf", Encoding.ASCII.GetBytes("%PDF-1.7 test"))],
|
||||
};
|
||||
|
||||
var text = MimeMessageWriter.Write(mail, "Granai <ufficio@example.com>", new DateTimeOffset(2026, 3, 2, 9, 30, 0, TimeSpan.FromHours(1)), "BOUNDARY");
|
||||
|
||||
StringAssert.Contains(text, "To: a@example.com, b@example.com\r\n");
|
||||
StringAssert.Contains(text, "Subject: =?utf-8?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes("Fattura n. 7 · Granai")) + "?=\r\n");
|
||||
StringAssert.Contains(text, "Date: Mon, 02 Mar 2026 09:30:00 +0100\r\n");
|
||||
StringAssert.Contains(text, "Content-Type: multipart/mixed; boundary=\"BOUNDARY\"");
|
||||
StringAssert.Contains(text, Convert.ToBase64String(Encoding.UTF8.GetBytes("Buongiorno,\r\nin allegato.")));
|
||||
StringAssert.Contains(text, "Content-Disposition: attachment; filename=\"fattura-7.pdf\"");
|
||||
StringAssert.Contains(text, Convert.ToBase64String(Encoding.ASCII.GetBytes("%PDF-1.7 test")));
|
||||
Assert.IsTrue(text.EndsWith("--BOUNDARY--\r\n", StringComparison.Ordinal));
|
||||
Assert.AreEqual("plain", MimeMessageWriter.EncodeHeader("plain"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Smtp_SendsTheMessage_ThroughTheDialogue()
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
var server = Task.Run(() => FakeServerAsync(listener));
|
||||
|
||||
var settings = new SmtpSettings("127.0.0.1", port, "demo", "test-only", "Granai <ufficio@example.com>", SmtpTransportSecurity.None);
|
||||
var sender = new SmtpMailSender(settings, TimeProvider.System);
|
||||
await sender.SendAsync(new OutgoingMail(["cliente@example.com"], "Prova", "Testo") { Cc = ["copia@example.com"] });
|
||||
|
||||
var (commands, data) = await server;
|
||||
Assert.IsTrue(commands[0].StartsWith("EHLO ", StringComparison.Ordinal));
|
||||
Assert.AreEqual("AUTH PLAIN " + Convert.ToBase64String(Encoding.UTF8.GetBytes("\0demo\0test-only")), commands[1]);
|
||||
CollectionAssert.Contains(commands, "MAIL FROM:<ufficio@example.com>");
|
||||
CollectionAssert.Contains(commands, "RCPT TO:<cliente@example.com>");
|
||||
CollectionAssert.Contains(commands, "RCPT TO:<copia@example.com>");
|
||||
Assert.AreEqual("QUIT", commands[^1]);
|
||||
StringAssert.Contains(data, "Subject: Prova");
|
||||
StringAssert.Contains(data, "Cc: copia@example.com");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Smtp_UnreachableServer_IsAMailException()
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
|
||||
var sender = new SmtpMailSender(new SmtpSettings("127.0.0.1", port, null, null, "ufficio@example.com", SmtpTransportSecurity.None), TimeProvider.System);
|
||||
await Assert.ThrowsExactlyAsync<MailException>(() => sender.SendAsync(new OutgoingMail(["a@example.com"], "Prova", "Testo")));
|
||||
await Assert.ThrowsExactlyAsync<MailException>(() => new SmtpMailSender(new SmtpSettings(null, 25, null, null, null, SmtpTransportSecurity.None), TimeProvider.System)
|
||||
.SendAsync(new OutgoingMail(["a@example.com"], "Prova", "Testo")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Invoice_PrintsToPdf_AndLeavesByMail()
|
||||
{
|
||||
var queue = new FakeQueue();
|
||||
var (app, _, company) = await TestInstance.StartAsync(services => services.AddSingleton<IMailQueue>(queue), CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
await app.Services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo);
|
||||
await app.Services.GetRequiredService<DemoSalesSeeder>().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true));
|
||||
var editor = app.Services.GetRequiredService<DocumentEditor>();
|
||||
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
||||
var invoices = await editor.ListAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.ImmediateInvoice], new ListQuery { Limit = 50 });
|
||||
var invoice = invoices.Items.First(r => r.Status == DocumentStatus.Issued);
|
||||
var family = DocumentFamily.SaleDocument;
|
||||
|
||||
// The model: every label comes from the resources, the lines and the totals are there.
|
||||
var model = await app.Services.GetRequiredService<DocumentPrintService>().BuildAsync(Root, company, family, invoice.Id);
|
||||
Assert.AreEqual(invoice.DocumentNumber, model.Number);
|
||||
Assert.IsNotNull(model.Watermark, "A document of the demo says so on the sheet.");
|
||||
Assert.IsNotEmpty(model.Lines);
|
||||
Assert.IsNotNull(model.Summary, "The VAT summary.");
|
||||
var texts = new[] { model.Title, model.PartyLabel }.Concat(model.LineHeaders).Concat(model.Fields.Select(f => f.Label)).Concat(model.Totals.Select(t => t.Label));
|
||||
Assert.IsFalse(texts.Any(t => t.StartsWith('[')), "Missing keys: " + string.Join(", ", texts.Where(t => t.StartsWith('['))));
|
||||
Assert.AreEqual("sales.saledocument", DocumentPrintService.EntityOf(family));
|
||||
Assert.AreEqual(family, DocumentPrintService.FamilyOf("sales.saledocument"));
|
||||
|
||||
// The PDF, kept among the attachments.
|
||||
var generated = await app.Services.GetRequiredService<FileGenerationService>()
|
||||
.GenerateAsync(Root, company, DocumentPrintService.EntityOf(family), invoice.Id, DocumentPdfGenerator.GeneratorCode);
|
||||
Assert.AreEqual("application/pdf", generated.Mime);
|
||||
Assert.IsTrue(generated.FileName.EndsWith(".pdf", StringComparison.Ordinal));
|
||||
var pdf = await ReadAsync(app.Services.GetRequiredService<AttachmentService>(), company, generated.Id);
|
||||
Assert.AreEqual("%PDF", Encoding.ASCII.GetString(pdf, 0, 4));
|
||||
|
||||
await engine.MarkPrintedAsync(Root, company, family, invoice.Id);
|
||||
Assert.IsTrue((await engine.GetAsync(Root, company, family, invoice.Id))!.Header.Printed);
|
||||
|
||||
// The mail: proposed from the template, refused when incomplete, queued with the PDF when complete.
|
||||
var mails = app.Services.GetRequiredService<DocumentMailService>();
|
||||
var draft = await mails.DraftAsync(Root, company, family, invoice.Id);
|
||||
StringAssert.Contains(draft.Subject, invoice.DocumentNumber!);
|
||||
Assert.IsFalse(draft.Body.Contains("{{", StringComparison.Ordinal), draft.Body);
|
||||
|
||||
var refused = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "non-un-indirizzo", Subject = " " }));
|
||||
CollectionAssert.AreEquivalent(new[] { "To:" + DocumentMailErrors.RecipientInvalid, "Subject:" + DocumentMailErrors.SubjectRequired }, refused.Errors.ToList());
|
||||
Assert.IsEmpty(queue.Mails);
|
||||
|
||||
await mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "amministrazione@example.com; copia@example.com" });
|
||||
var mail = queue.Mails.Single();
|
||||
CollectionAssert.AreEqual(new[] { "amministrazione@example.com", "copia@example.com" }, mail.To.ToList());
|
||||
Assert.AreEqual("%PDF", Encoding.ASCII.GetString(mail.Attachments.Single().Content, 0, 4));
|
||||
Assert.IsTrue((await engine.GetAsync(Root, company, family, invoice.Id))!.Header.Sent);
|
||||
|
||||
queue.Configured = false;
|
||||
var off = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "a@example.com" }));
|
||||
CollectionAssert.Contains(off.Errors.ToList(), ":" + DocumentMailErrors.NotConfigured);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<byte[]> ReadAsync(AttachmentService attachments, string company, long id)
|
||||
{
|
||||
await using var content = await attachments.OpenAsync(Root, company, id);
|
||||
using var buffer = new MemoryStream();
|
||||
await content.Content.CopyToAsync(buffer);
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
// A server that says yes to everything and keeps what it receives.
|
||||
private static async Task<(List<string> Commands, string Data)> FakeServerAsync(TcpListener listener)
|
||||
{
|
||||
using var client = await listener.AcceptTcpClientAsync();
|
||||
var stream = client.GetStream();
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\r\n", AutoFlush = true };
|
||||
var commands = new List<string>();
|
||||
var data = new StringBuilder();
|
||||
await writer.WriteLineAsync("220 fake ESMTP");
|
||||
while (await reader.ReadLineAsync() is { } line)
|
||||
{
|
||||
commands.Add(line);
|
||||
if (line.StartsWith("EHLO", StringComparison.Ordinal))
|
||||
{
|
||||
await writer.WriteLineAsync("250-fake");
|
||||
await writer.WriteLineAsync("250 AUTH PLAIN");
|
||||
}
|
||||
else if (line.StartsWith("AUTH", StringComparison.Ordinal))
|
||||
{
|
||||
await writer.WriteLineAsync("235 ok");
|
||||
}
|
||||
else if (line == "DATA")
|
||||
{
|
||||
await writer.WriteLineAsync("354 go on");
|
||||
while (await reader.ReadLineAsync() is { } body && body != ".")
|
||||
{
|
||||
data.Append(body).Append('\n');
|
||||
}
|
||||
|
||||
await writer.WriteLineAsync("250 queued");
|
||||
}
|
||||
else if (line == "QUIT")
|
||||
{
|
||||
await writer.WriteLineAsync("221 bye");
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
await writer.WriteLineAsync("250 ok");
|
||||
}
|
||||
}
|
||||
|
||||
return (commands, data.ToString());
|
||||
}
|
||||
|
||||
private sealed class FakeQueue : IMailQueue
|
||||
{
|
||||
public List<OutgoingMail> Mails { get; } = [];
|
||||
|
||||
public bool Configured { get; set; } = true;
|
||||
|
||||
public bool IsConfigured => Configured;
|
||||
|
||||
public bool Enqueue(OutgoingMail mail)
|
||||
{
|
||||
Mails.Add(mail);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<DocumentEngine>();
|
||||
var editor = app.Services.GetRequiredService<DocumentEditor>();
|
||||
var tables = app.Services.GetRequiredService<TableService>();
|
||||
var taxes = await tables.ActiveAsync<TaxCode>(Root, company);
|
||||
var terms = await tables.ActiveAsync<PaymentTerm>(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<DocumentEngine>();
|
||||
var editor = app.Services.GetRequiredService<DocumentEditor>();
|
||||
var copies = app.Services.GetRequiredService<DocumentCopyService>();
|
||||
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<DocumentRecord>
|
||||
{
|
||||
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<ValidationFailedException>(() =>
|
||||
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<ValidationFailedException>(() => 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<TableService>().ActiveAsync<TaxCode>(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.IsNull(SalesScreens.RecordUrl(DocumentKind.PurchaseInvoice, 1));
|
||||
|
||||
// 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<DocumentKind>().Select(k => "Sales.Kinds." + k)
|
||||
.Concat(Enum.GetValues<DocumentStatus>().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<LinkDirection>().Select(d => "Sales.Links." + d))
|
||||
.Concat(Enum.GetValues<DocumentLineKind>().Select(k => "Sales.LineKinds." + k));
|
||||
var missing = keys.Where(k => !texts.Contains(k)).ToList();
|
||||
Assert.IsEmpty(missing, string.Join(", ", missing));
|
||||
}
|
||||
|
||||
private static async Task<DocumentRecord> 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<long> CustomerAsync(WebApplication app, string company, string name, string vatNumber, long? paymentTermId)
|
||||
{
|
||||
var parties = app.Services.GetRequiredService<PartyService>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user