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;
///
/// Fills a mail template (SPEC §12.6): {{Name}} becomes the value of the field, unknown fields stay as they are
/// so that a typing error shows in the message instead of disappearing.
///
public static partial class MailTemplateRenderer
{
/// Fills a template.
/// The template.
/// The values by name (case does not matter).
/// The text.
public static string Render(string template, IReadOnlyDictionary fields)
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(fields);
var lookup = new Dictionary(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();
}
/// A message about a document, as the user is about to send it.
/// The recipients, separated by commas or semicolons.
/// The subject.
/// The text.
public sealed record DocumentMailDraft(string To, string Subject, string Body);
/// The errors of (text keys).
public static class DocumentMailErrors
{
/// No SMTP server is configured.
public const string NotConfigured = "document.mail.not-configured";
/// No recipient, or one that is not an e-mail address.
public const string RecipientInvalid = "document.mail.recipient-invalid";
/// The subject is empty.
public const string SubjectRequired = "document.mail.subject-required";
/// The queue is full.
public const string QueueFull = "document.mail.queue-full";
}
///
/// Sends a document by e-mail (SPEC §9.4, §12.6, issue #52): proposes recipient, subject and text from the templates
/// (Print.Mail.*) 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.
///
/// The printed form of documents.
/// The document engine.
/// The generated files (the PDF).
/// The attachments.
/// The mail queue.
/// The units of work.
/// The texts.
public sealed partial class DocumentMailService(
DocumentPrintService prints, DocumentEngine engine, FileGenerationService generation, AttachmentService attachments, IMailQueue queue, IUnitOfWorkFactory factory,
ITexts texts)
{
/// Whether mail can be sent from this instance.
public bool IsConfigured => queue.IsConfigured;
/// The message proposed for a document.
/// Who sends.
/// The company.
/// The family.
/// The document.
/// Cancellation.
/// The draft.
public async Task 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().GetAsync(partyId, cancellationToken).ConfigureAwait(false))?.Email;
}
var fields = new Dictionary
{
["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));
}
/// Sends a document: the PDF becomes a new attachment version and leaves with the message.
/// Who sends.
/// The company.
/// The family.
/// The document.
/// The message.
/// Cancellation.
/// The PDF attached.
/// The message is not complete, or mail is not configured.
public async Task 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();
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;
}
/// The addresses of a recipient field (commas, semicolons or spaces between them).
/// The field.
/// The addresses.
public static IReadOnlyList 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();
}