Files
Khaemhat/src/Khaemhat.Application/Documents/DocumentMail.cs
T
Alby96andClaude Opus 5.5 826042f828 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>
2026-11-12 17:20:25 +01:00

179 lines
8.4 KiB
C#

using System.Text.RegularExpressions;
using Khaemhat.Application.Files;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Parties;
using Khaemhat.Data;
using Khaemhat.Infrastructure.Mail;
namespace Khaemhat.Application.Documents;
/// <summary>
/// Fills a mail template (SPEC §12.6): <c>{{Name}}</c> becomes the value of the field, unknown fields stay as they are
/// so that a typing error shows in the message instead of disappearing.
/// </summary>
public static partial class MailTemplateRenderer
{
/// <summary>Fills a template.</summary>
/// <param name="template">The template.</param>
/// <param name="fields">The values by name (case does not matter).</param>
/// <returns>The text.</returns>
public static string Render(string template, IReadOnlyDictionary<string, string?> fields)
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(fields);
var lookup = new Dictionary<string, string?>(fields, StringComparer.OrdinalIgnoreCase);
return Field().Replace(template, m => lookup.TryGetValue(m.Groups[1].Value, out var value) ? value ?? string.Empty : m.Value);
}
[GeneratedRegex(@"\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}", RegexOptions.CultureInvariant, 1000)]
private static partial Regex Field();
}
/// <summary>A message about a document, as the user is about to send it.</summary>
/// <param name="To">The recipients, separated by commas or semicolons.</param>
/// <param name="Subject">The subject.</param>
/// <param name="Body">The text.</param>
public sealed record DocumentMailDraft(string To, string Subject, string Body);
/// <summary>The errors of <see cref="DocumentMailService"/> (text keys).</summary>
public static class DocumentMailErrors
{
/// <summary>No SMTP server is configured.</summary>
public const string NotConfigured = "document.mail.not-configured";
/// <summary>No recipient, or one that is not an e-mail address.</summary>
public const string RecipientInvalid = "document.mail.recipient-invalid";
/// <summary>The subject is empty.</summary>
public const string SubjectRequired = "document.mail.subject-required";
/// <summary>The queue is full.</summary>
public const string QueueFull = "document.mail.queue-full";
}
/// <summary>
/// Sends a document by e-mail (SPEC §9.4, §12.6, issue #52): proposes recipient, subject and text from the templates
/// (<c>Print.Mail.*</c>) and the e-mail of the party; on sending keeps the PDF as a new version among the attachments,
/// attaches it, queues the message and marks the document as sent. The outcome is in the log, section E-mail/PEC.
/// </summary>
/// <param name="prints">The printed form of documents.</param>
/// <param name="engine">The document engine.</param>
/// <param name="generation">The generated files (the PDF).</param>
/// <param name="attachments">The attachments.</param>
/// <param name="queue">The mail queue.</param>
/// <param name="factory">The units of work.</param>
/// <param name="texts">The texts.</param>
public sealed partial class DocumentMailService(
DocumentPrintService prints, DocumentEngine engine, FileGenerationService generation, AttachmentService attachments, IMailQueue queue, IUnitOfWorkFactory factory,
ITexts texts)
{
/// <summary>Whether mail can be sent from this instance.</summary>
public bool IsConfigured => queue.IsConfigured;
/// <summary>The message proposed for a document.</summary>
/// <param name="actor">Who sends.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The draft.</returns>
public async Task<DocumentMailDraft> DraftAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
{
var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false);
var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
string? email = null;
if (record.Header.PartyId is { } partyId)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
email = (await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false))?.Email;
}
var fields = new Dictionary<string, string?>
{
["Documento"] = model.Title,
["Numero"] = model.Number,
["Data"] = model.Date,
["Cliente"] = model.Party.Name,
["Azienda"] = model.Company.Name,
["Totale"] = model.Totals.LastOrDefault(t => t.Strong)?.Value,
};
return new DocumentMailDraft(
email ?? string.Empty,
MailTemplateRenderer.Render(texts["Print.Mail.Subject"], fields),
MailTemplateRenderer.Render(texts["Print.Mail.Body"], fields));
}
/// <summary>Sends a document: the PDF becomes a new attachment version and leaves with the message.</summary>
/// <param name="actor">Who sends.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="draft">The message.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The PDF attached.</returns>
/// <exception cref="ValidationFailedException">The message is not complete, or mail is not configured.</exception>
public async Task<AttachmentView> SendAsync(
Actor actor, string companyCode, DocumentFamily family, long id, DocumentMailDraft draft, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(draft);
var recipients = Recipients(draft.To);
var errors = new List<string>();
if (!queue.IsConfigured)
{
errors.Add(":" + DocumentMailErrors.NotConfigured);
}
if (recipients.Count == 0 || !recipients.All(r => Address().IsMatch(r)))
{
errors.Add(nameof(DocumentMailDraft.To) + ":" + DocumentMailErrors.RecipientInvalid);
}
if (string.IsNullOrWhiteSpace(draft.Subject))
{
errors.Add(nameof(DocumentMailDraft.Subject) + ":" + DocumentMailErrors.SubjectRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false);
var pdf = await generation.GenerateAsync(actor, companyCode, DocumentPrintService.EntityOf(family), id, DocumentPdfGenerator.GeneratorCode, cancellationToken)
.ConfigureAwait(false);
byte[] bytes;
await using (var content = await attachments.OpenAsync(actor, companyCode, pdf.Id, cancellationToken).ConfigureAwait(false))
{
using var buffer = new MemoryStream();
await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
bytes = buffer.ToArray();
}
var mail = new OutgoingMail(recipients, draft.Subject.Trim(), draft.Body)
{
Attachments = [new MailAttachment(pdf.FileName, pdf.Mime, bytes)],
Reference = model.Title + " " + model.Number,
};
if (!queue.Enqueue(mail))
{
throw new ValidationFailedException([":" + DocumentMailErrors.QueueFull]);
}
await engine.MarkSentAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false);
return pdf;
}
/// <summary>The addresses of a recipient field (commas, semicolons or spaces between them).</summary>
/// <param name="text">The field.</param>
/// <returns>The addresses.</returns>
public static IReadOnlyList<string> Recipients(string? text) =>
string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';', ' ', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
[GeneratedRegex(@"^[^@\s<>]+@[^@\s<>]+\.[^@\s<>]+$", RegexOptions.CultureInvariant, 1000)]
private static partial Regex Address();
}