feat: sales screens, deferred invoicing, printing and mail of documents (#49 #50 #51 #52)

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:
Alby96andClaude Opus 5.5 committed 2026-11-12 17:20:25 +01:00
1 parent f12848865d
commit 826042f828
31 files changed
+5682 -16

No files matched your search

+445
View File
@@ -0,0 +1,445 @@
using System.Globalization;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading.Channels;
using Khaemhat.Core.Logging;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Infrastructure.Mail;
/// <summary>A file attached to a message.</summary>
/// <param name="FileName">The file name.</param>
/// <param name="MediaType">The media type.</param>
/// <param name="Content">The bytes.</param>
public sealed record MailAttachment(string FileName, string MediaType, byte[] Content);
/// <summary>A message to send.</summary>
/// <param name="To">The recipients.</param>
/// <param name="Subject">The subject.</param>
/// <param name="Body">The text of the message.</param>
public sealed record OutgoingMail(IReadOnlyList<string> To, string Subject, string Body)
{
/// <summary>The recipients in copy.</summary>
public IReadOnlyList<string> Cc { get; init; } = [];
/// <summary>The address replies go to, when not the sender.</summary>
public string? ReplyTo { get; init; }
/// <summary>The attachments.</summary>
public IReadOnlyList<MailAttachment> Attachments { get; init; } = [];
/// <summary>What the message is about, for the log, such as <c>Fattura immediata 6/2026</c>.</summary>
public string? Reference { get; init; }
}
/// <summary>How the connection to the SMTP server is protected (<c>KHAEMHAT_SMTP_SECURITY</c>).</summary>
public enum SmtpTransportSecurity
{
/// <summary>Plain connection upgraded with STARTTLS (port 587).</summary>
StartTls = 0,
/// <summary>TLS from the first byte (port 465).</summary>
Ssl = 1,
/// <summary>No encryption: only for a relay on the local network.</summary>
None = 2,
}
/// <summary>The SMTP server (SPEC §6: <c>KHAEMHAT_SMTP_*</c>).</summary>
/// <param name="Host">The host; none when mail is not configured.</param>
/// <param name="Port">The port.</param>
/// <param name="User">The user, when the server wants authentication.</param>
/// <param name="Password">The password.</param>
/// <param name="From">The sender address.</param>
/// <param name="Security">The protection of the connection.</param>
public sealed record SmtpSettings(string? Host, int Port, string? User, string? Password, string? From, SmtpTransportSecurity Security)
{
/// <summary>Whether messages can be sent.</summary>
public bool IsConfigured => !string.IsNullOrWhiteSpace(Host) && !string.IsNullOrWhiteSpace(From);
/// <inheritdoc />
public override string ToString() => $"{Host}:{Port} ({Security})";
}
/// <summary>Sends a message now.</summary>
public interface IMailSender
{
/// <summary>Whether a server is configured.</summary>
bool IsConfigured { get; }
/// <summary>Sends a message.</summary>
/// <param name="mail">The message.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="MailException">The server refused the message or could not be reached.</exception>
Task SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default);
}
/// <summary>A message the SMTP server refused, or a server that could not be reached.</summary>
public sealed class MailException : Exception
{
/// <summary>Creates the exception.</summary>
public MailException()
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public MailException(string message)
: base(message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public MailException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Writes a message as MIME (RFC 5322, 2045-2047): UTF-8 text in base64, attachments in base64 at 76 columns, headers
/// with non-ASCII text as encoded words.
/// </summary>
public static class MimeMessageWriter
{
/// <summary>Writes the message.</summary>
/// <param name="mail">The message.</param>
/// <param name="from">The sender.</param>
/// <param name="date">The date of the message.</param>
/// <param name="boundary">The MIME boundary; a new one when empty.</param>
/// <returns>The message, lines ended by CRLF.</returns>
public static string Write(OutgoingMail mail, string from, DateTimeOffset date, string? boundary = null)
{
ArgumentNullException.ThrowIfNull(mail);
ArgumentNullException.ThrowIfNull(from);
boundary ??= "=_kh_" + Guid.NewGuid().ToString("N");
var domain = from.Contains('@', StringComparison.Ordinal) ? from[(from.IndexOf('@', StringComparison.Ordinal) + 1)..] : "localhost";
var text = new StringBuilder();
void Line(string value) => text.Append(value).Append("\r\n");
Line("From: " + from);
Line("To: " + string.Join(", ", mail.To));
if (mail.Cc.Count > 0)
{
Line("Cc: " + string.Join(", ", mail.Cc));
}
if (mail.ReplyTo is { Length: > 0 } replyTo)
{
Line("Reply-To: " + replyTo);
}
Line("Subject: " + EncodeHeader(mail.Subject));
Line("Date: " + date.ToString("ddd, dd MMM yyyy HH:mm:ss ", CultureInfo.InvariantCulture) + date.ToString("zzz", CultureInfo.InvariantCulture).Replace(":", string.Empty, StringComparison.Ordinal));
Line("Message-ID: <" + Guid.NewGuid().ToString("N") + "@" + domain + ">");
Line("MIME-Version: 1.0");
Line("Content-Type: multipart/mixed; boundary=\"" + boundary + "\"");
Line(string.Empty);
Line("--" + boundary);
Line("Content-Type: text/plain; charset=utf-8");
Line("Content-Transfer-Encoding: base64");
Line(string.Empty);
Base64(text, Encoding.UTF8.GetBytes(mail.Body.Replace("\r\n", "\n", StringComparison.Ordinal).Replace("\n", "\r\n", StringComparison.Ordinal)));
foreach (var attachment in mail.Attachments)
{
Line("--" + boundary);
var name = EncodeHeader(attachment.FileName);
Line("Content-Type: " + attachment.MediaType + "; name=\"" + name + "\"");
Line("Content-Transfer-Encoding: base64");
Line("Content-Disposition: attachment; filename=\"" + name + "\"");
Line(string.Empty);
Base64(text, attachment.Content);
}
Line("--" + boundary + "--");
return text.ToString();
}
/// <summary>A header value, as an encoded word when it is not plain ASCII.</summary>
/// <param name="value">The value.</param>
/// <returns>The header text.</returns>
public static string EncodeHeader(string value)
{
ArgumentNullException.ThrowIfNull(value);
return value.All(c => c is >= ' ' and <= '~' && c != '"')
? value
: "=?utf-8?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes(value)) + "?=";
}
private static void Base64(StringBuilder text, byte[] bytes)
{
var encoded = Convert.ToBase64String(bytes);
for (var i = 0; i < encoded.Length; i += 76)
{
text.Append(encoded, i, Math.Min(76, encoded.Length - i)).Append("\r\n");
}
}
}
/// <summary>
/// An SMTP client written in house (SPEC §1.4, §6): STARTTLS or TLS from the start, AUTH PLAIN or LOGIN, one message
/// per connection. Enough for a business sending its documents; no pipelining, no DSN.
/// </summary>
/// <param name="settings">The server.</param>
/// <param name="clock">The clock (date of the messages).</param>
public sealed class SmtpMailSender(SmtpSettings settings, TimeProvider clock) : IMailSender
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60);
/// <inheritdoc />
public bool IsConfigured => settings.IsConfigured;
/// <inheritdoc />
public async Task SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(mail);
if (!settings.IsConfigured)
{
throw new MailException("No SMTP server is configured (KHAEMHAT_SMTP_HOST, KHAEMHAT_SMTP_FROM).");
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
var token = timeout.Token;
try
{
using var client = new TcpClient();
await client.ConnectAsync(settings.Host!, settings.Port, token).ConfigureAwait(false);
Stream stream = client.GetStream();
if (settings.Security == SmtpTransportSecurity.Ssl)
{
stream = await TlsAsync(stream, token).ConfigureAwait(false);
}
var session = new Session(stream);
await session.ExpectAsync(220, token).ConfigureAwait(false);
var features = await session.CommandAsync("EHLO " + Environment.MachineName.ToLowerInvariant(), 250, token).ConfigureAwait(false);
if (settings.Security == SmtpTransportSecurity.StartTls)
{
await session.CommandAsync("STARTTLS", 220, token).ConfigureAwait(false);
session = new Session(await TlsAsync(stream, token).ConfigureAwait(false));
features = await session.CommandAsync("EHLO " + Environment.MachineName.ToLowerInvariant(), 250, token).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(settings.User))
{
if (features.Contains("PLAIN", StringComparison.OrdinalIgnoreCase) || !features.Contains("LOGIN", StringComparison.OrdinalIgnoreCase))
{
var plain = Convert.ToBase64String(Encoding.UTF8.GetBytes("\0" + settings.User + "\0" + settings.Password));
await session.CommandAsync("AUTH PLAIN " + plain, 235, token, secret: true).ConfigureAwait(false);
}
else
{
await session.CommandAsync("AUTH LOGIN", 334, token).ConfigureAwait(false);
await session.CommandAsync(Convert.ToBase64String(Encoding.UTF8.GetBytes(settings.User)), 334, token, secret: true).ConfigureAwait(false);
await session.CommandAsync(Convert.ToBase64String(Encoding.UTF8.GetBytes(settings.Password ?? string.Empty)), 235, token, secret: true).ConfigureAwait(false);
}
}
await session.CommandAsync("MAIL FROM:<" + Address(settings.From!) + ">", 250, token).ConfigureAwait(false);
foreach (var recipient in mail.To.Concat(mail.Cc))
{
await session.CommandAsync("RCPT TO:<" + Address(recipient) + ">", 250, token, alsoAccepted: 251).ConfigureAwait(false);
}
await session.CommandAsync("DATA", 354, token).ConfigureAwait(false);
var message = MimeMessageWriter.Write(mail, settings.From!, clock.GetLocalNow());
var stuffed = string.Join("\r\n", message.Split("\r\n").Select(l => l.StartsWith('.') ? "." + l : l));
await session.CommandAsync(stuffed.TrimEnd('\r', '\n') + "\r\n.", 250, token).ConfigureAwait(false);
await session.CommandAsync("QUIT", 221, token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is SocketException or IOException or System.Security.Authentication.AuthenticationException
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
throw new MailException("The SMTP server " + settings + " could not be reached: " + ex.Message, ex);
}
}
// The address inside angle brackets: "Name <a@b>" gives a@b.
private static string Address(string text)
{
var start = text.IndexOf('<', StringComparison.Ordinal);
var end = text.IndexOf('>', StringComparison.Ordinal);
return start >= 0 && end > start ? text[(start + 1)..end].Trim() : text.Trim();
}
private async Task<Stream> TlsAsync(Stream inner, CancellationToken cancellationToken)
{
var tls = new SslStream(inner, leaveInnerStreamOpen: false);
await tls.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = settings.Host }, cancellationToken).ConfigureAwait(false);
return tls;
}
// The dialogue on one stream: commands out, replies (possibly on several lines) in.
private sealed class Session(Stream stream)
{
private readonly byte[] _buffer = new byte[4096];
private readonly StringBuilder _pending = new();
public async Task<string> CommandAsync(string command, int expected, CancellationToken cancellationToken, bool secret = false, int? alsoAccepted = null)
{
await stream.WriteAsync(Encoding.UTF8.GetBytes(command + "\r\n"), cancellationToken).ConfigureAwait(false);
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
var (code, text) = await ReplyAsync(cancellationToken).ConfigureAwait(false);
if (code != expected && code != alsoAccepted)
{
var shown = secret ? command.Split(' ')[0] + " ***" : command.Length > 60 ? command[..60] + "…" : command;
throw new MailException($"The SMTP server answered {code} {text.Trim()} to {shown}.");
}
return text;
}
public async Task ExpectAsync(int expected, CancellationToken cancellationToken)
{
var (code, text) = await ReplyAsync(cancellationToken).ConfigureAwait(false);
if (code != expected)
{
throw new MailException($"The SMTP server greeted with {code} {text.Trim()}.");
}
}
private async Task<(int Code, string Text)> ReplyAsync(CancellationToken cancellationToken)
{
var text = new StringBuilder();
while (true)
{
var line = await LineAsync(cancellationToken).ConfigureAwait(false);
text.Append(line.Length > 4 ? line[4..] : string.Empty).Append('\n');
if (line.Length < 3 || !int.TryParse(line.AsSpan(0, 3), NumberStyles.None, CultureInfo.InvariantCulture, out var code))
{
throw new MailException("The SMTP server sent a reply that is not SMTP: " + line);
}
if (line.Length == 3 || line[3] != '-')
{
return (code, text.ToString());
}
}
}
private async Task<string> LineAsync(CancellationToken cancellationToken)
{
while (true)
{
var text = _pending.ToString();
var end = text.IndexOf("\r\n", StringComparison.Ordinal);
if (end >= 0)
{
_pending.Remove(0, end + 2);
return text[..end];
}
var read = await stream.ReadAsync(_buffer, cancellationToken).ConfigureAwait(false);
if (read == 0)
{
throw new MailException("The SMTP server closed the connection.");
}
_pending.Append(Encoding.UTF8.GetString(_buffer, 0, read));
}
}
}
}
/// <summary>Messages waiting to be sent.</summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "The name of SPEC §21: a queue of messages.")]
public interface IMailQueue
{
/// <summary>Whether a server is configured.</summary>
bool IsConfigured { get; }
/// <summary>Puts a message in the queue; it leaves in the background, the outcome goes to the log (section E-mail/PEC).</summary>
/// <param name="mail">The message.</param>
/// <returns>Whether the message was accepted.</returns>
bool Enqueue(OutgoingMail mail);
}
/// <summary>
/// The queue of outgoing mail (SPEC §12.6): a background service sends one message at a time, tries three times with
/// growing pauses, and writes each outcome in the log, section E-mail/PEC. The queue lives in memory: a message waiting
/// when the service stops is lost and its log says so.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="logger">The log.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "The name of SPEC §21: a queue of messages.")]
public sealed partial class MailQueue(IMailSender sender, ILogger<MailQueue> logger) : BackgroundService, IMailQueue
{
private const int Attempts = 3;
private readonly Channel<OutgoingMail> _channel = Channel.CreateBounded<OutgoingMail>(new BoundedChannelOptions(500) { SingleReader = true });
/// <inheritdoc />
public bool IsConfigured => sender.IsConfigured;
/// <summary>The pause between two attempts, shorter in tests.</summary>
public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(30);
/// <inheritdoc />
public bool Enqueue(OutgoingMail mail)
{
ArgumentNullException.ThrowIfNull(mail);
var accepted = _channel.Writer.TryWrite(mail);
using (logger.BeginScope(LogSections.Scope(LogSection.Email)))
{
if (accepted)
{
LogQueued(logger, mail.Reference ?? mail.Subject, string.Join(", ", mail.To));
}
else
{
LogFull(logger, mail.Reference ?? mail.Subject);
}
}
return accepted;
}
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var mail in _channel.Reader.ReadAllAsync(stoppingToken).ConfigureAwait(false))
{
using var scope = logger.BeginScope(LogSections.Scope(LogSection.Email));
var reference = mail.Reference ?? mail.Subject;
var to = string.Join(", ", mail.To);
for (var attempt = 1; attempt <= Attempts; attempt++)
{
try
{
await sender.SendAsync(mail, stoppingToken).ConfigureAwait(false);
LogSent(logger, reference, to, attempt);
break;
}
catch (MailException ex) when (attempt < Attempts)
{
LogRetry(logger, reference, to, attempt, ex.Message);
await Task.Delay(RetryDelay * attempt, stoppingToken).ConfigureAwait(false);
}
catch (MailException ex)
{
LogFailed(logger, ex, reference, to, attempt);
}
}
}
}
[LoggerMessage(EventId = 1301, Level = LogLevel.Information, Message = "Mail {Reference} queued for {To}.")]
private static partial void LogQueued(ILogger logger, string reference, string to);
[LoggerMessage(EventId = 1302, Level = LogLevel.Warning, Message = "Mail {Reference} refused: the queue is full.")]
private static partial void LogFull(ILogger logger, string reference);
[LoggerMessage(EventId = 1303, Level = LogLevel.Information, Message = "Mail {Reference} sent to {To} (attempt {Attempt}).")]
private static partial void LogSent(ILogger logger, string reference, string to, int attempt);
[LoggerMessage(EventId = 1304, Level = LogLevel.Warning, Message = "Mail {Reference} to {To} not sent at attempt {Attempt}: {Reason}. It will be tried again.")]
private static partial void LogRetry(ILogger logger, string reference, string to, int attempt, string reason);
[LoggerMessage(EventId = 1305, Level = LogLevel.Error, Message = "Mail {Reference} to {To} not sent after {Attempt} attempts.")]
private static partial void LogFailed(ILogger logger, Exception exception, string reference, string to, int attempt);
}