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; /// Printing and sending documents (SPEC §9.4, §12.6, issue #52): the print model, the PDF, MIME, SMTP and the queue. [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 { ["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 ", 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 ", 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:"); CollectionAssert.Contains(commands, "RCPT TO:"); CollectionAssert.Contains(commands, "RCPT TO:"); 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(() => sender.SendAsync(new OutgoingMail(["a@example.com"], "Prova", "Testo"))); await Assert.ThrowsExactlyAsync(() => 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(queue), CancellationToken.None); await using (app) { await app.Services.GetRequiredService().RunAsync(company, SeedKind.Demo); await app.Services.GetRequiredService().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true)); var editor = app.Services.GetRequiredService(); var engine = app.Services.GetRequiredService(); 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().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() .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(), 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(); 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(() => 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(() => 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 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 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(); 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 Mails { get; } = []; public bool Configured { get; set; } = true; public bool IsConfigured => Configured; public bool Enqueue(OutgoingMail mail) { Mails.Add(mail); return true; } } }