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

+6 -2
View File
@@ -3,7 +3,8 @@
# Any KHAEMHAT_* variable already set in the shell wins over the defaults below.
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# Under Git Bash on Windows, pwd -W gives B:/... instead of /b/..., which .NET would read as a folder b on the drive.
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && (pwd -W 2>/dev/null || pwd))"
cd "$root"
data_dir="$root/.data/dev"
@@ -11,7 +12,10 @@ mkdir -p "$data_dir"
export ASPNETCORE_ENVIRONMENT="${ASPNETCORE_ENVIRONMENT:-Development}"
export KHAEMHAT_DATA_DIR="${KHAEMHAT_DATA_DIR:-$data_dir}"
export KHAEMHAT_SYSTEM_DB="${KHAEMHAT_SYSTEM_DB:-sqlite://$data_dir/system.db}"
# sqlite:///home/... on Linux and macOS, sqlite:///B:/... on Windows.
db_path="$data_dir"
[[ "$db_path" == /* ]] || db_path="/$db_path"
export KHAEMHAT_SYSTEM_DB="${KHAEMHAT_SYSTEM_DB:-sqlite://$db_path/system.db}"
# Development-only key: never use it outside this script.
export KHAEMHAT_SECRET_KEY="${KHAEMHAT_SECRET_KEY:-a2hhZW1oYXQtZGV2ZWxvcG1lbnQtb25seS1ub3QtYS1zZWNyZXQ=}"
export KHAEMHAT_SUPERUSER="${KHAEMHAT_SUPERUSER:-root}"
@@ -173,6 +173,7 @@ public sealed class DocumentCopyService
header.DocumentTypeId = target.Type.Id;
header.Kind = target.Kind;
header.Status = DocumentStatus.Draft;
header.IsDemo = source.IsDemo;
header.DocumentDate = today;
header.Year = today.Year;
header.PartyId = source.PartyId;
@@ -85,6 +85,9 @@ public static class DocumentErrors
/// <summary>Error: a discount formula that cannot be read.</summary>
public const string LineDiscountInvalid = "document.line.discount-invalid";
/// <summary>Error: a line of an invoice without its VAT code.</summary>
public const string LineTaxRequired = "document.line.tax-required";
}
/// <summary>
@@ -290,6 +293,18 @@ public sealed class DocumentEngine
errors.Add("Lines:" + DocumentErrors.LinesRequired);
}
if (definition.Behavior.Has(DocumentEffects.Ledger))
{
// A document that goes to the VAT registers needs the VAT of every line with an amount.
for (var i = 0; i < record.Lines.Count; i++)
{
if (record.Lines[i] is { Kind: not DocumentLineKind.Description, TaxCodeId: null })
{
errors.Add("Lines." + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + nameof(DocumentLine.TaxCodeId) + ":" + DocumentErrors.LineTaxRequired);
}
}
}
if (errors.Count > 0 || record.Header.DocumentDate != draft.Header.DocumentDate)
{
throw errors.Count > 0 ? new ValidationFailedException(errors) : new Core.Common.ConcurrencyException();
@@ -400,6 +415,26 @@ public sealed class DocumentEngine
}, null, cancellationToken);
}
/// <summary>Records that the document was printed (its PDF kept among the attachments); the state does not change.</summary>
/// <param name="actor">Who prints: needs to read the document.</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>A task.</returns>
public Task MarkPrintedAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
MarkAsync(actor, companyCode, family, id, h => h.Printed = true, cancellationToken);
/// <summary>Records that the document was sent by e-mail; the state does not change.</summary>
/// <param name="actor">Who sends: needs to read the document.</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>A task.</returns>
public Task MarkSentAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
MarkAsync(actor, companyCode, family, id, h => h.Sent = true, cancellationToken);
/// <summary>Deletes a draft.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
@@ -641,6 +676,26 @@ public sealed class DocumentEngine
return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
}
// Sets an output flag (printed, sent) with its trace in the history, whatever the state.
private async Task MarkAsync(Actor actor, string companyCode, DocumentFamily family, long id, Action<DocumentHeader> change, CancellationToken cancellationToken)
{
var company = Company(actor, companyCode);
var store = DocumentStores.Of(family);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var header = await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
await _permissions.DemandAsync(actor, DocumentBehaviors.Of(header.Kind).ReadPermission, cancellationToken).ConfigureAwait(false);
var old = header.Clone();
change(header);
if (old.Printed != header.Printed || old.Sent != header.Sent)
{
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, header, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
// Records the links of a confirmed document towards the lines it fulfils, then the fulfilment of those documents.
private async Task LinkAsync(IUnitOfWork uow, DocumentDefinition definition, DocumentRecord record, string userName, CancellationToken cancellationToken)
{
@@ -0,0 +1,178 @@
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();
}
@@ -0,0 +1,440 @@
using Khaemhat.Application.Files;
using Khaemhat.Application.Security;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Documents;
/// <summary>
/// The PDF of a document (SPEC §9.4, issue #52): A4, letterhead with logo and company data, address box, conditions,
/// lines over as many pages as needed (the headings repeat), VAT summary, totals, installments, transport and signature
/// boxes, notes and footer. Saved as a generated attachment of the document, so every print is a new version and
/// <i>Rigenera</i> writes the current state after a change.
/// </summary>
/// <param name="prints">The printed form of documents.</param>
/// <param name="attachments">The attachments (the logo of the company).</param>
public sealed class DocumentPdfGenerator(DocumentPrintService prints, AttachmentService attachments) : IFileGenerator
{
/// <summary>The code of the generator.</summary>
public const string GeneratorCode = "documents.pdf";
private const double Margin = 42;
private const double Bottom = 60;
private static readonly PdfColor Accent = PdfColor.FromHex("#1F5F8B");
private static readonly PdfColor Muted = PdfColor.Gray(105);
private static readonly PdfColor Rule = PdfColor.Gray(205);
private static readonly PdfColor Band = PdfColor.Gray(238);
private static readonly PdfColor Warning = PdfColor.FromHex("#B54708");
/// <inheritdoc />
public string Code => GeneratorCode;
/// <inheritdoc />
public string TitleKey => "files.generators.document_pdf";
/// <inheritdoc />
public string MediaType => PdfWriter.MediaType;
/// <inheritdoc />
public string Extension => ".pdf";
/// <inheritdoc />
public bool Supports(string entity) => DocumentPrintService.FamilyOf(entity) is not null;
/// <inheritdoc />
public string FileName(FileGenerationContext context)
{
ArgumentNullException.ThrowIfNull(context);
return Stem(context) + Extension;
}
/// <inheritdoc />
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, cancellationToken).ConfigureAwait(false);
}
// The file name follows the document (number and kind); without the logo, which the name does not need.
private string Stem(FileGenerationContext context)
{
try
{
return prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId).GetAwaiter().GetResult().FileStem;
}
catch (KeyNotFoundException)
{
return "documento-" + context.EntityId.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
}
private static Core.Documents.DocumentFamily FamilyOf(FileGenerationContext context) =>
DocumentPrintService.FamilyOf(context.Entity) ?? throw new ValidationFailedException([FileGenerationService.UnknownGeneratorError]);
private Task<DocumentPrintModel> ModelAsync(FileGenerationContext context, CancellationToken cancellationToken) =>
prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId, (id, ct) => LogoAsync(context, id, ct), cancellationToken);
// The logo, when it is a JPEG the actor may read; the PDF writer embeds JPEG only.
private async Task<byte[]?> LogoAsync(FileGenerationContext context, long id, CancellationToken cancellationToken)
{
try
{
await using var content = await attachments.OpenAsync(context.Actor, context.CompanyCode, id, cancellationToken).ConfigureAwait(false);
if (content.Attachment.Mime != "image/jpeg")
{
return null;
}
using var buffer = new MemoryStream();
await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
return buffer.ToArray();
}
catch (Exception ex) when (ex is KeyNotFoundException or AccessDeniedException)
{
return null;
}
}
private static async Task WriteAsync(DocumentPrintModel model, FileGenerationContext context, Stream output, CancellationToken cancellationToken)
{
var info = new PdfDocumentInfo
{
Title = model.Title + " " + model.Number,
Author = model.Company.Name,
Subject = model.Title + " " + model.Number + " · " + model.Party.Name,
CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)),
};
await using var pdf = new PdfWriter(output, info, leaveOpen: true);
var sheet = new Sheet(pdf, model, cancellationToken);
await sheet.FirstPageAsync().ConfigureAwait(false);
await sheet.LinesAsync().ConfigureAwait(false);
await sheet.FooterBlocksAsync().ConfigureAwait(false);
sheet.Finish();
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
// The pen on the pages: where it is, and how to go on to the next page.
private sealed class Sheet(PdfWriter pdf, DocumentPrintModel model, CancellationToken cancellationToken)
{
// Code, description, unit, quantity, price, discounts, VAT, amount: the left edge of each column and the right end.
private double[] _edges = [];
private PdfPage _page = null!;
private int _pages;
private double _y;
private double Right => _page.Width - Margin;
public async Task FirstPageAsync()
{
await NewPageAsync(first: true).ConfigureAwait(false);
}
public async Task LinesAsync()
{
Headings();
foreach (var line in model.Lines)
{
var width = _edges[2] - _edges[1] - 8;
var wrapped = PdfTextLayout.Wrap(line.Description, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Right - _edges[1] - 8 : width);
var height = Math.Max(1, wrapped.Count) * 11 + 5;
if (_y - height < Bottom + 20)
{
await NewPageAsync(first: false).ConfigureAwait(false);
Headings();
}
var y = _y;
if (!line.IsDescription)
{
_page.DrawText(line.Code, _edges[0] + 3, y, PdfFont.Courier, 8);
_page.DrawText(line.Unit, _edges[2] + 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Quantity, _edges[4] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Price, _edges[5] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Discount, _edges[6] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Tax, _edges[7] - 3, y, PdfFont.Helvetica, 8.5);
_page.DrawTextRight(line.Amount, _edges[8] - 3, y, PdfFont.Helvetica, 8.5);
}
foreach (var text in wrapped)
{
_page.DrawText(text, _edges[1] + 3, y, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Muted : null);
y -= 11;
}
_y -= height;
_page.DrawLine(Margin, _y + 8, Right, _y + 8, 0.25, Rule);
}
_y -= 6;
}
public async Task FooterBlocksAsync()
{
foreach (var note in model.Notes)
{
var wrapped = PdfTextLayout.Wrap(note, PdfFont.Helvetica, 8.5, Right - Margin);
await RoomAsync(wrapped.Count * 11 + 4).ConfigureAwait(false);
foreach (var text in wrapped)
{
_page.DrawText(text, Margin, _y, PdfFont.Helvetica, 8.5);
_y -= 11;
}
_y -= 4;
}
// VAT summary on the left, totals on the right, side by side.
var middle = Margin + (Right - Margin) * 0.58;
var summaryHeight = model.Summary is { } s ? 20 + s.Rows.Count * 13 : 0;
var totalsHeight = model.Totals.Count * 14 + 8;
await RoomAsync(Math.Max(summaryHeight, totalsHeight) + 10).ConfigureAwait(false);
var top = _y - 4;
var afterSummary = model.Summary is { } summary ? Table(summary, Margin, middle - 14, top) : top;
var y = top;
_page.DrawRectangle(middle, y - totalsHeight + 10, Right - middle, totalsHeight, fill: Band, stroke: Band);
foreach (var row in model.Totals)
{
var font = row.Strong ? PdfFont.HelveticaBold : PdfFont.Helvetica;
var size = row.Strong ? 11 : 8.5;
if (row.Strong)
{
y -= 3;
}
_page.DrawText(row.Label, middle + 8, y, font, size, row.Strong ? Accent : null);
_page.DrawTextRight(row.Value, Right - 8, y, font, size, row.Strong ? Accent : null);
y -= 14;
}
_y = Math.Min(afterSummary, y) - 12;
if (model.Installments is { } installments)
{
await RoomAsync(22 + installments.Rows.Count * 13).ConfigureAwait(false);
_y = Table(installments, Margin, middle - 14, _y) - 12;
}
if (model.Transport.Count > 0)
{
await RoomAsync(110).ConfigureAwait(false);
_y = Fields(model.Transport, 4) - 10;
var width = (Right - Margin - 24) / Math.Max(1, model.Signatures.Count);
for (var i = 0; i < model.Signatures.Count; i++)
{
var x = Margin + i * (width + 12);
_page.DrawText(model.Signatures[i], x, _y, PdfFont.Helvetica, 7.5, Muted);
_page.DrawLine(x, _y - 28, x + width, _y - 28, 0.5, Rule);
}
_y -= 40;
}
}
public void Finish() => Foot();
private async Task RoomAsync(double height)
{
if (_y - height < Bottom)
{
await NewPageAsync(first: false).ConfigureAwait(false);
}
}
private async Task NewPageAsync(bool first)
{
if (_page is not null)
{
Foot();
}
_page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
_pages++;
var right = _page.Width - Margin;
double[] widths = [62, 0, 30, 50, 62, 44, 30, 66];
var description = right - Margin - widths.Sum();
_edges = new double[9];
_edges[0] = Margin;
for (var i = 0; i < widths.Length; i++)
{
_edges[i + 1] = _edges[i] + (i == 1 ? description : widths[i]);
}
_y = _page.Height - Margin;
if (!first)
{
_page.DrawText(model.Company.Name, Margin, _y - 8, PdfFont.HelveticaBold, 9);
_page.DrawTextRight(model.Title + " " + model.Number + " · " + model.Date, right, _y - 8, PdfFont.Helvetica, 9, Muted);
_y -= 18;
_page.DrawLine(Margin, _y, right, _y, 0.75, Accent);
_y -= 16;
return;
}
Letterhead(right);
}
private void Letterhead(double right)
{
var top = _y;
var x = Margin;
if (model.Logo is { } logo)
{
try
{
var info = JpegInfo.Read(logo);
var image = pdf.AddJpeg(logo);
const double height = 44;
var width = Math.Min(130, height * info.Width / Math.Max(1, info.Height));
_page.DrawImage(image, Margin, top - height, width, height);
x = Margin + width + 12;
}
catch (InvalidDataException)
{
// Not a JPEG the writer can embed: the name alone.
}
}
var y = top - 12;
_page.DrawText(model.Company.Name, x, y, PdfFont.HelveticaBold, 13, Accent);
y -= 13;
foreach (var line in model.Company.Lines)
{
_page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 7.5, right - x - 190), x, y, PdfFont.Helvetica, 7.5, Muted);
y -= 9.5;
}
// Kind, number and date on the right; a mark for drafts, cancelled and demo documents.
_page.DrawTextRight(model.Title.ToUpperInvariant(), right, top - 10, PdfFont.HelveticaBold, 9, Accent);
_page.DrawTextRight(model.Number, right, top - 28, PdfFont.HelveticaBold, 16);
_page.DrawTextRight(model.Date, right, top - 42, PdfFont.Helvetica, 9, Muted);
if (model.Watermark is { } mark)
{
_page.DrawTextRight(mark.ToUpperInvariant(), right, top - 56, PdfFont.HelveticaBold, 9, Warning);
}
_y = Math.Min(y, top - 62) - 8;
_page.DrawLine(Margin, _y, right, _y, 1, Accent);
_y -= 14;
// The address box on the right half, the conditions on the left.
var boxLeft = Margin + (right - Margin) * 0.52;
var boxTop = _y + 6;
var lines = 2 + model.Party.Lines.Count;
var boxHeight = lines * 11 + 14;
_page.DrawRectangle(boxLeft, boxTop - boxHeight, right - boxLeft, boxHeight, stroke: Rule);
var by = boxTop - 13;
_page.DrawText(model.PartyLabel, boxLeft + 8, by, PdfFont.Helvetica, 7.5, Muted);
if (model.Party.Code is { } code)
{
_page.DrawTextRight(code, right - 8, by, PdfFont.Courier, 7.5, Muted);
}
by -= 13;
_page.DrawText(PdfTextLayout.Fit(model.Party.Name, PdfFont.HelveticaBold, 10, right - boxLeft - 16), boxLeft + 8, by, PdfFont.HelveticaBold, 10);
foreach (var line in model.Party.Lines)
{
by -= 11;
_page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 8.5, right - boxLeft - 16), boxLeft + 8, by, PdfFont.Helvetica, 8.5);
}
var fy = _y - 6;
foreach (var field in model.Fields)
{
_page.DrawText(field.Label, Margin, fy, PdfFont.Helvetica, 7.5, Muted);
_page.DrawText(PdfTextLayout.Fit(field.Value, PdfFont.Helvetica, 8.5, boxLeft - Margin - 100), Margin + 92, fy, PdfFont.Helvetica, 8.5);
fy -= 12;
}
_y = Math.Min(boxTop - boxHeight, fy) - 14;
}
private void Headings()
{
_page.DrawRectangle(Margin, _y - 5, Right - Margin, 16, fill: Band, stroke: Band);
for (var i = 0; i < model.LineHeaders.Count; i++)
{
if (i is 0 or 1 or 2)
{
_page.DrawText(model.LineHeaders[i], _edges[i] + 3, _y, PdfFont.HelveticaBold, 7.5);
}
else
{
_page.DrawTextRight(model.LineHeaders[i], _edges[i + 1] - 3, _y, PdfFont.HelveticaBold, 7.5);
}
}
_y -= 17;
}
// A small table; returns the y under it.
private double Table(PrintTable table, double left, double right, double y)
{
_page.DrawText(table.Title, left, y, PdfFont.HelveticaBold, 8.5, Accent);
y -= 13;
var width = (right - left) / table.Headers.Count;
for (var i = 0; i < table.Headers.Count; i++)
{
Cell(table.Headers[i], left + i * width, width, y, table.Numeric[i], PdfFont.HelveticaBold, 7.5);
}
_page.DrawLine(left, y - 4, right, y - 4, 0.5, Rule);
y -= 13;
foreach (var row in table.Rows)
{
for (var i = 0; i < row.Count; i++)
{
Cell(row[i], left + i * width, width, y, table.Numeric[i], PdfFont.Helvetica, 8);
}
y -= 13;
}
return y;
}
private void Cell(string text, double x, double width, double y, bool numeric, PdfFont font, double size)
{
var fitted = PdfTextLayout.Fit(text, font, size, width - 6);
if (numeric)
{
_page.DrawTextRight(fitted, x + width - 3, y, font, size);
}
else
{
_page.DrawText(fitted, x + 3, y, font, size);
}
}
// Label and value pairs in columns; returns the y under them.
private double Fields(IReadOnlyList<PrintField> fields, int columns)
{
var width = (Right - Margin) / columns;
var y = _y;
for (var i = 0; i < fields.Count; i++)
{
var x = Margin + (i % columns) * width;
_page.DrawText(fields[i].Label, x, y, PdfFont.Helvetica, 7.5, Muted);
_page.DrawText(PdfTextLayout.Fit(fields[i].Value, PdfFont.Helvetica, 8.5, width - 8), x, y - 11, PdfFont.Helvetica, 8.5);
if (i % columns == columns - 1 || i == fields.Count - 1)
{
y -= 26;
}
}
return y;
}
private void Foot()
{
var right = _page.Width - Margin;
_page.DrawLine(Margin, 46, right, 46, 0.5, Rule);
if (model.Footer is { } footer)
{
_page.DrawText(PdfTextLayout.Fit(footer, PdfFont.Helvetica, 7, right - Margin - 80), Margin, 34, PdfFont.Helvetica, 7, Muted);
}
_page.DrawTextRight(_pages.ToString(System.Globalization.CultureInfo.InvariantCulture), right, 34, PdfFont.Helvetica, 7, Muted);
}
}
}
@@ -0,0 +1,514 @@
using System.Globalization;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Documents;
/// <summary>A block of name and lines: the company in the letterhead, the party in the address box.</summary>
/// <param name="Name">The name.</param>
/// <param name="Code">The code of the party, when there is one.</param>
/// <param name="Lines">Address, tax numbers, contacts.</param>
public sealed record PrintParty(string Name, string? Code, IReadOnlyList<string> Lines);
/// <summary>A label and its value.</summary>
/// <param name="Label">The label.</param>
/// <param name="Value">The value, formatted.</param>
public sealed record PrintField(string Label, string Value);
/// <summary>A row of the totals.</summary>
/// <param name="Label">The label.</param>
/// <param name="Value">The amount, formatted.</param>
/// <param name="Strong">Whether it is the amount to pay.</param>
public sealed record PrintRow(string Label, string Value, bool Strong);
/// <summary>A line of the document as printed; every value formatted, empty for a descriptive line.</summary>
/// <param name="Code">The item code.</param>
/// <param name="Description">The description.</param>
/// <param name="Unit">The unit of measure.</param>
/// <param name="Quantity">The quantity.</param>
/// <param name="Price">The unit price.</param>
/// <param name="Discount">The discounts, such as 10+5.</param>
/// <param name="Tax">The VAT code.</param>
/// <param name="Amount">The amount.</param>
/// <param name="IsDescription">Whether the line is only text.</param>
public sealed record PrintLine(
string? Code, string Description, string? Unit, string? Quantity, string? Price, string? Discount, string? Tax, string? Amount, bool IsDescription);
/// <summary>A small table (VAT summary, installments) with its headings and rows.</summary>
/// <param name="Title">The title.</param>
/// <param name="Headers">The headings.</param>
/// <param name="Numeric">Which columns hold numbers (aligned right).</param>
/// <param name="Rows">The rows, formatted.</param>
public sealed record PrintTable(string Title, IReadOnlyList<string> Headers, IReadOnlyList<bool> Numeric, IReadOnlyList<IReadOnlyList<string>> Rows);
/// <summary>
/// A document ready to print (SPEC §9.4, issue #52): every text already formatted and translated, so that the HTML
/// preview and the PDF show exactly the same thing.
/// </summary>
public sealed record DocumentPrintModel
{
/// <summary>The kind, such as Fattura immediata.</summary>
public required string Title { get; init; }
/// <summary>The number, or the draft label.</summary>
public required string Number { get; init; }
/// <summary>The date.</summary>
public required string Date { get; init; }
/// <summary>A mark across the sheet: draft, cancelled, demo; none for a valid document.</summary>
public string? Watermark { get; init; }
/// <summary>The company in the letterhead.</summary>
public required PrintParty Company { get; init; }
/// <summary>The logo of the company, a JPEG, when it has one.</summary>
public byte[]? Logo { get; init; }
/// <summary>The attachment of the logo, for the HTML preview.</summary>
public long? LogoAttachmentId { get; init; }
/// <summary>The heading of the address box (Spett.le, Fornitore).</summary>
public required string PartyLabel { get; init; }
/// <summary>The customer or supplier.</summary>
public required PrintParty Party { get; init; }
/// <summary>Payment, reference, validity, delivery, agent, CIG and CUP.</summary>
public required IReadOnlyList<PrintField> Fields { get; init; }
/// <summary>The headings of the lines.</summary>
public required IReadOnlyList<string> LineHeaders { get; init; }
/// <summary>The lines.</summary>
public required IReadOnlyList<PrintLine> Lines { get; init; }
/// <summary>The VAT summary; empty for documents without VAT.</summary>
public PrintTable? Summary { get; init; }
/// <summary>The installments; empty when the document has none.</summary>
public PrintTable? Installments { get; init; }
/// <summary>The totals, the amount to pay last.</summary>
public required IReadOnlyList<PrintRow> Totals { get; init; }
/// <summary>The transport data of a delivery note or accompanying invoice; empty otherwise.</summary>
public required IReadOnlyList<PrintField> Transport { get; init; }
/// <summary>The signature boxes of a delivery note.</summary>
public required IReadOnlyList<string> Signatures { get; init; }
/// <summary>Notes printed under the lines (document notes, legal notes such as split payment).</summary>
public required IReadOnlyList<string> Notes { get; init; }
/// <summary>The footer of the company.</summary>
public string? Footer { get; init; }
/// <summary>The name of the file without extension, such as fattura-immediata-6-2026.</summary>
public required string FileStem { get; init; }
}
/// <summary>
/// Builds the printed form of a document (SPEC §9.4, §11.3, issue #52; mockup 025): letterhead with logo and data of
/// the company, address box, conditions, lines, VAT summary, installments, totals, transport and notes. The texts come
/// from the resources (<c>Print.*</c>); the same model feeds the HTML preview and the PDF generator.
/// </summary>
/// <param name="engine">The document engine (reads the document with its permission).</param>
/// <param name="factory">The units of work.</param>
/// <param name="companies">The company registry (name of a company without profile).</param>
/// <param name="texts">The texts.</param>
public sealed class DocumentPrintService(DocumentEngine engine, IUnitOfWorkFactory factory, ICompanyRegistry companies, ITexts texts)
{
private static readonly Dictionary<DocumentFamily, string> Entities = new Dictionary<DocumentFamily, string>
{
[DocumentFamily.SaleQuotation] = "sales.salequotation",
[DocumentFamily.SaleOrder] = "sales.saleorder",
[DocumentFamily.SaleDocument] = "sales.saledocument",
[DocumentFamily.PurchaseOrder] = "purchases.purchaseorder",
[DocumentFamily.PurchaseDocument] = "purchases.purchasedocument",
[DocumentFamily.InventoryDocument] = "inventory.inventorydocument",
};
/// <summary>The entity of the attachments of a family, such as <c>sales.saledocument</c>.</summary>
/// <param name="family">The family.</param>
/// <returns>The entity.</returns>
public static string EntityOf(DocumentFamily family) => Entities[family];
/// <summary>The family of an attachment entity.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The family, or none for another entity.</returns>
public static DocumentFamily? FamilyOf(string? entity) =>
Entities.Where(e => string.Equals(e.Value, entity, StringComparison.Ordinal)).Select(e => (DocumentFamily?)e.Key).FirstOrDefault();
/// <summary>The printed form of a document.</summary>
/// <param name="actor">Who prints: needs to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="logo">The logo, read by the caller with its own permission (a JPEG for the PDF).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The model.</returns>
/// <exception cref="KeyNotFoundException">No such document.</exception>
public async Task<DocumentPrintModel> BuildAsync(
Actor actor, string companyCode, DocumentFamily family, long id, Func<long, CancellationToken, Task<byte[]?>>? logo = null, CancellationToken cancellationToken = default)
{
var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(DocumentErrors.NotFound);
var company = CompanyCodes.Normalize(companyCode);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var h = record.Header;
var definition = await DocumentDefinitionService.GetAsync(uow, h.DocumentTypeId, cancellationToken).ConfigureAwait(false);
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
var registered = profile is null ? await companies.FindAsync(company, cancellationToken).ConfigureAwait(false) : null;
var party = h.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var lookups = new Lookups(uow, cancellationToken);
var behavior = definition.Behavior;
var lines = new List<PrintLine>();
foreach (var line in record.Lines)
{
if (line.Kind == DocumentLineKind.Description)
{
lines.Add(new PrintLine(null, line.Description, null, null, null, null, null, null, true));
continue;
}
var code = line.ItemId is { } itemId ? (await lookups.GetAsync<Item>(itemId).ConfigureAwait(false))?.Code : null;
lines.Add(new PrintLine(
code,
line.Description,
await lookups.CodeAsync<UnitOfMeasure>(line.UnitOfMeasureId).ConfigureAwait(false),
texts.Number(line.Quantity, 2),
texts.Money(line.Price),
string.IsNullOrWhiteSpace(line.DiscountFormula) ? null : line.DiscountFormula,
await lookups.CodeAsync<TaxCode>(line.TaxCodeId).ConfigureAwait(false),
texts.Money(line.TaxableAmount),
false));
}
var fields = new List<PrintField>();
void Field(string key, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
fields.Add(new PrintField(texts["Print.Fields." + key], value));
}
}
Field("Payment", await lookups.DescriptionAsync<PaymentTerm>(h.PaymentTermId).ConfigureAwait(false));
if (h.BankAccountId is { } bankId && await lookups.GetAsync<BankAccount>(bankId).ConfigureAwait(false) is { } bank)
{
Field("Bank", string.Join(" · ", new[] { bank.BankName ?? bank.Description, bank.Iban }.Where(s => !string.IsNullOrWhiteSpace(s))));
}
Field("Reference", h.ExternalReference is { } reference
? reference + (h.ExternalDate is { } externalDate ? " " + texts.Format("Print.Of", texts.Date(externalDate)) : null)
: null);
Field("ValidUntil", h.ValidUntil is { } validUntil ? texts.Date(validUntil) : null);
Field("Delivery", h.DeliveryDate is { } delivery ? texts.Date(delivery) : null);
Field("Salesperson", await lookups.DescriptionAsync<Salesperson>(h.SalespersonId).ConfigureAwait(false));
Field("Revision", h.Revision > 0 ? h.Revision.ToString(texts.Culture) : null);
Field("Cig", h.Cig);
Field("Cup", h.Cup);
Field("Related", h.RelatedNumber is { } related
? related + (h.RelatedDate is { } relatedDate ? " " + texts.Format("Print.Of", texts.Date(relatedDate)) : null)
: null);
var transport = new List<PrintField>();
var signatures = new List<string>();
if (behavior.Has(DocumentEffects.Inventory) && definition.Kind is DocumentKind.DeliveryNote or DocumentKind.AccompanyingInvoice or DocumentKind.PurchaseDeliveryNote)
{
void Transport(string key, string? value)
{
if (!string.IsNullOrWhiteSpace(value))
{
transport.Add(new PrintField(texts["Print.Transport." + key], value));
}
}
Transport("Reason", await lookups.DescriptionAsync<TransportReason>(h.TransportReasonId).ConfigureAwait(false));
Transport("By", h.TransportBy is { } by ? texts["Sales.TransportBy." + by] : null);
Transport("Carrier", await lookups.DescriptionAsync<Carrier>(h.CarrierId).ConfigureAwait(false));
Transport("Port", await lookups.DescriptionAsync<ShippingTerm>(h.ShippingTermId).ConfigureAwait(false));
Transport("Appearance", await lookups.DescriptionAsync<GoodsAppearance>(h.GoodsAppearanceId).ConfigureAwait(false));
Transport("Packages", h.Packages?.ToString(texts.Culture));
Transport("GrossWeight", h.GrossWeight is { } gross ? texts.Number(gross, 3) : null);
Transport("NetWeight", h.NetWeight is { } net ? texts.Number(net, 3) : null);
Transport("Start", h.TransportStart is { } start ? start.ToString("g", texts.Culture) : null);
signatures.AddRange([texts["Print.Transport.SignatureDriver"], texts["Print.Transport.SignatureCarrier"], texts["Print.Transport.SignatureRecipient"]]);
}
PrintTable? summary = null;
if (record.Figures.Summary.Count > 0)
{
var rows = new List<IReadOnlyList<string>>();
foreach (var row in record.Figures.Summary)
{
var tax = row.TaxCodeId is { } taxId ? await lookups.GetAsync<TaxCode>(taxId).ConfigureAwait(false) : null;
rows.Add([
tax is null ? row.Nature ?? string.Empty : tax.Code + " · " + tax.Description,
row.Rate.ToString("0.##", texts.Culture) + "%",
texts.Money(row.Taxable),
texts.Money(row.Tax),
]);
}
summary = new PrintTable(
texts["Print.Summary.Title"],
[texts["Print.Summary.Code"], texts["Print.Summary.Rate"], texts["Print.Summary.Taxable"], texts["Print.Summary.Tax"]],
[false, true, true, true],
rows);
}
PrintTable? installments = null;
if (record.Figures.Installments.Count > 0)
{
var rows = new List<IReadOnlyList<string>>();
foreach (var due in record.Figures.Installments)
{
rows.Add([
due.Number.ToString(texts.Culture),
texts.Date(due.DueDate),
await lookups.DescriptionAsync<PaymentMethod>(due.PaymentMethodId).ConfigureAwait(false) ?? string.Empty,
texts.Money(due.Amount),
]);
}
installments = new PrintTable(
texts["Print.Installments.Title"],
[texts["Print.Installments.Number"], texts["Print.Installments.Due"], texts["Print.Installments.Method"], texts["Print.Installments.Amount"]],
[true, false, false, true],
rows);
}
var notes = new List<string>();
if (!string.IsNullOrWhiteSpace(h.Notes))
{
notes.Add(h.Notes.Trim());
}
if (h.SplitPayment)
{
notes.Add(texts["Print.Notes.SplitPayment"]);
}
if (definition.Kind == DocumentKind.ProForma)
{
notes.Add(texts["Print.Notes.ProForma"]);
}
if (definition.Kind is DocumentKind.DeferredInvoice)
{
notes.Add(texts["Print.Notes.Deferred"]);
}
var title = definition.Type.Description;
var number = h.DocumentNumber ?? texts["Print.Draft"];
var stem = Slug(title + (h.DocumentNumber is { } n ? " " + n : " " + texts["Print.Draft"]));
return new DocumentPrintModel
{
Title = title,
Number = number,
Date = texts.Date(h.DocumentDate),
Watermark = h.Status switch
{
DocumentStatus.Draft => texts["Print.Watermarks.Draft"],
DocumentStatus.Cancelled => texts["Print.Watermarks.Cancelled"],
_ => h.IsDemo ? texts["Print.Watermarks.Demo"] : null,
},
Company = CompanyBlock(profile, registered?.Name ?? company),
Logo = profile?.LogoAttachmentId is { } logoId && logo is not null ? await logo(logoId, cancellationToken).ConfigureAwait(false) : null,
LogoAttachmentId = profile?.LogoAttachmentId,
PartyLabel = texts[behavior.Direction == DocumentDirection.Purchase ? "Print.Supplier" : "Print.Customer"],
Party = PartyBlock(party),
Fields = fields,
LineHeaders =
[
texts["Print.Lines.Code"], texts["Print.Lines.Description"], texts["Print.Lines.Unit"], texts["Print.Lines.Quantity"],
texts["Print.Lines.Price"], texts["Print.Lines.Discount"], texts["Print.Lines.Tax"], texts["Print.Lines.Amount"],
],
Lines = lines,
Summary = summary,
Installments = installments,
Totals = TotalsOf(record, definition),
Transport = transport,
Signatures = signatures,
Notes = notes,
Footer = profile?.FooterNotes,
FileStem = stem,
};
}
// A name for files: lower case letters and digits joined by dashes, such as fattura-immediata-6-2026.
private static string Slug(string text)
{
var builder = new System.Text.StringBuilder();
foreach (var c in text.Normalize(System.Text.NormalizationForm.FormD))
{
if (char.IsLetterOrDigit(c) && c < 128)
{
builder.Append(char.ToLowerInvariant(c));
}
else if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark && builder.Length > 0 && builder[^1] != '-')
{
builder.Append('-');
}
}
return builder.ToString().Trim('-');
}
private PrintParty CompanyBlock(CompanyProfile? profile, string fallbackName)
{
if (profile is null)
{
return new PrintParty(fallbackName, null, []);
}
var lines = new List<string>();
Add(lines, Address(profile.Address, profile.StreetNumber, profile.PostalCode, profile.City, profile.ProvinceCode, profile.AddressCountry));
Add(lines, Join(
profile.VatNumber is { Length: > 0 } vat ? texts.Format("Print.VatNumber", vat) : null,
profile.TaxCode is { Length: > 0 } taxCode && taxCode != profile.VatNumber ? texts.Format("Print.TaxCode", taxCode) : null));
Add(lines, Join(
profile.ReaNumber is { Length: > 0 } rea ? texts.Format("Print.Rea", profile.ReaOffice ?? string.Empty, rea) : null,
profile.ShareCapital is { } capital ? texts.Format("Print.ShareCapital", texts.Money(capital)) : null));
Add(lines, Join(
profile.Phone is { Length: > 0 } phone ? texts.Format("Print.Phone", phone) : null,
profile.Email,
profile.Pec is { Length: > 0 } pec ? texts.Format("Print.Pec", pec) : null,
profile.Website));
return new PrintParty(profile.LegalName, null, lines);
}
private PrintParty PartyBlock(Party? party)
{
if (party is null)
{
return new PrintParty(texts["Print.NoParty"], null, []);
}
var lines = new List<string>();
Add(lines, Join(party.Address, party.StreetNumber));
Add(lines, Join(party.PostalCode, party.City, party.Province is { Length: > 0 } province ? "(" + province + ")" : null)
+ (party.CountryCode is { Length: > 0 } country && country != "IT" ? " · " + country : null));
Add(lines, Join(
party.VatNumber is { Length: > 0 } vat ? texts.Format("Print.VatNumber", vat) : null,
party.TaxCode is { Length: > 0 } taxCode && taxCode != party.VatNumber ? texts.Format("Print.TaxCode", taxCode) : null));
Add(lines, party.Pec is { Length: > 0 } pec ? texts.Format("Print.Pec", pec) : null);
return new PrintParty(party.Name, party.Code, lines);
}
private List<PrintRow> TotalsOf(DocumentRecord record, DocumentDefinition definition)
{
var h = record.Header;
var rows = new List<PrintRow>();
void Row(string key, decimal value, bool strong = false, string? suffix = null) =>
rows.Add(new PrintRow(texts["Print.Totals." + key] + suffix, texts.Money(value), strong));
var goods = record.Lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free or DocumentLineKind.Discount).Sum(l => l.TaxableAmount);
Row("Goods", goods);
if (h.FooterDiscountAmount != 0m)
{
Row("FooterDiscount", -h.FooterDiscountAmount, suffix: h.FooterDiscount is { } f ? " " + f + "%" : null);
}
if (h.ExpensesAmount != 0m)
{
Row("Expenses", h.ExpensesAmount);
}
if (h.SocialSecurityAmount != 0m)
{
Row("SocialSecurity", h.SocialSecurityAmount);
}
var ledger = definition.Behavior.Has(DocumentEffects.Ledger) || h.TaxAmount != 0m;
if (ledger)
{
Row("Taxable", h.TaxableAmount);
Row("Tax", h.TaxAmount);
}
if (h.StampDuty != 0m)
{
Row("StampDuty", h.StampDuty);
}
var showsNet = h.NetAmount != h.TotalAmount && h.NetAmount != 0m;
Row("Total", h.TotalAmount, strong: !showsNet);
if (h.WithholdingAmount != 0m)
{
Row("Withholding", -h.WithholdingAmount);
}
if (h.EnasarcoAmount != 0m)
{
Row("Enasarco", -h.EnasarcoAmount);
}
if (h.SplitPayment && h.TaxAmount != 0m)
{
Row("SplitPayment", -h.TaxAmount);
}
if (showsNet)
{
Row("Net", h.NetAmount, strong: true);
}
return rows;
}
private static string? Address(string? street, string? number, string? postalCode, string? city, string? province, string? country) =>
Join(Join(street, number), Join(postalCode, city, province is { Length: > 0 } p ? "(" + p + ")" : null), country is { Length: > 0 } c && c != "IT" ? c : null) is { } text
? text.Replace(" · ", " - ", StringComparison.Ordinal)
: null;
private static string? Join(params string?[] parts)
{
var present = parts.Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
return present.Count == 0 ? null : string.Join(" · ", present);
}
private static void Add(List<string> lines, string? line)
{
if (!string.IsNullOrWhiteSpace(line))
{
lines.Add(line);
}
}
// The coded rows the printout names, read once each.
private sealed class Lookups(IUnitOfWork uow, CancellationToken cancellationToken)
{
private readonly Dictionary<(Type, long), object?> _cache = [];
public async Task<T?> GetAsync<T>(long id)
where T : Core.Entities.Entity<long>, new()
{
if (!_cache.TryGetValue((typeof(T), id), out var found))
{
found = await uow.Repository<T, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
_cache[(typeof(T), id)] = found;
}
return (T?)found;
}
public async Task<string?> CodeAsync<T>(long? id)
where T : CodedEntity, new() =>
id is { } value ? (await GetAsync<T>(value).ConfigureAwait(false))?.Code : null;
public async Task<string?> DescriptionAsync<T>(long? id)
where T : CodedEntity, new() =>
id is { } value ? (await GetAsync<T>(value).ConfigureAwait(false))?.Description : null;
}
}
@@ -0,0 +1,215 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The sales of the demo company (SPEC §14, issue #53): the profile of the company, then a year of documents made the
/// way a user makes them, through the document engine: quotations sent, accepted, refused and expired; orders from
/// quotations and direct, delivered in full or in part; delivery notes still to invoice (for the deferred invoicing);
/// immediate and deferred invoices, a credit note, a pro forma and a few drafts. Dates fall between the first of
/// January and today, in order for each numerator. Runs only when the demo data are asked and the company has no sales
/// documents yet; every document is marked as demo.
/// </summary>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The document editor (party terms, item prices).</param>
/// <param name="copies">The transformations between documents.</param>
/// <param name="profiles">The company profiles.</param>
/// <param name="factory">The units of work.</param>
/// <param name="clock">The clock.</param>
public sealed class DemoSalesSeeder(
DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, CompanyProfileService profiles, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The fictitious VAT number of the demo company (valid check digit).</summary>
public const string CompanyVatNumber = "03579135793";
private static readonly Actor Seed = Actor.System;
private DocumentEngine Engine { get; } = engine;
private DocumentEditor Editor { get; } = editor;
private DocumentCopyService Copies { get; } = copies;
/// <inheritdoc />
public int Order => 20;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
{
return;
}
await ProfileAsync(companyCode, cancellationToken).ConfigureAwait(false);
var data = await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (data is null)
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
await new Run(this, companyCode, data, today, cancellationToken).ExecuteAsync().ConfigureAwait(false);
}
// The letterhead of the demo company, when nobody wrote it yet.
private async Task ProfileAsync(string companyCode, CancellationToken cancellationToken)
{
var profile = await profiles.GetAsync(Seed, companyCode, cancellationToken).ConfigureAwait(false);
if (profile.Id != 0 || !string.IsNullOrEmpty(profile.VatNumber))
{
return;
}
profile.FiscalName = profile.LegalName;
profile.VatNumber = CompanyVatNumber;
profile.TaxCode = CompanyVatNumber;
profile.ReaOffice = "CN";
profile.ReaNumber = "123456";
profile.ShareCapital = 50000m;
profile.Shareholders = "SM";
profile.LiquidationStatus = "LN";
profile.Address = "Via dei Granai";
profile.StreetNumber = "57";
profile.PostalCode = "12100";
profile.City = "Cuneo";
profile.ProvinceCode = "CN";
profile.AddressCountry = "IT";
profile.Phone = "+39 0171 000000";
profile.Email = "info@demo.example";
profile.Pec = "demo@pec.demo.example";
profile.Website = "https://demo.example";
profile.FooterNotes = "Dati dimostrativi: nomi, numeri e conti sono fittizi.";
await profiles.SaveAsync(Seed, companyCode, profile, cancellationToken).ConfigureAwait(false);
}
// The parties and items the documents use; null when the company already has sales or lacks the demo masters.
private async Task<DemoData?> ReadAsync(string companyCode, CancellationToken cancellationToken)
{
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
if (await uow.Repository<SaleQuotation, long>().CountAsync(Query.For<SaleQuotation>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<SaleDocument, long>().CountAsync(Query.For<SaleDocument>(), cancellationToken).ConfigureAwait(false) > 0)
{
return null;
}
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.IsDemo), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(i => i.Id).ToList();
var goods = items.Where(i => i.Kind == ItemKind.Goods).Select(i => i.Id).ToList();
var services = items.Where(i => i.Kind == ItemKind.Service).Select(i => i.Id).ToList();
string[] names = ["Rossi Impianti S.r.l.", "Bianchi & Figli S.n.c.", "Idrotermica Piemonte S.r.l.", "Edilizia Moderna S.p.A.", "Hotel Belvedere S.r.l.", "Esposito Mario"];
return goods.Count >= 12 && services.Count > 0 && names.All(parties.ContainsKey) ? new DemoData(parties, goods, services) : null;
}
private sealed record DemoData(IReadOnlyDictionary<string, long> Parties, IReadOnlyList<long> Goods, IReadOnlyList<long> Services);
// One seeding, with its company and dates.
private sealed class Run(DemoSalesSeeder owner, string company, DemoData data, DateOnly today, CancellationToken cancellationToken)
{
private long Party(string name) => data.Parties[name];
// A date some months before today, kept between the first of January and today so that every document falls
// in the current year and the numbering stays in date order.
private DateOnly D(int monthsBack, int day)
{
var month = today.AddMonths(-monthsBack);
var date = new DateOnly(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month)));
var first = new DateOnly(today.Year, 1, 1);
return date < first ? first : date > today ? today : date;
}
public async Task ExecuteAsync()
{
// Quotations (numerator PRE), in date order.
var q1 = await NewAsync("PRE", "Rossi Impianti S.r.l.", D(5, 10), [(0, 4m), (1, 10m), (2, 24m)], validDays: 30).ConfigureAwait(false);
var q2 = await NewAsync("PRE", "Hotel Belvedere S.r.l.", D(4, 3), [(3, 6m), (4, 6m)], validDays: 30).ConfigureAwait(false);
await NewAsync("PRE", "Edilizia Moderna S.p.A.", D(3, 1), [(5, 20m), (6, 40m)], validDays: 30).ConfigureAwait(false);
var q4 = await NewAsync("PRE", "Bianchi & Figli S.n.c.", D(2, 5), [(7, 12m), (8, 3m)], validDays: 60, service: 8m).ConfigureAwait(false);
await NewAsync("PRE", "Idrotermica Piemonte S.r.l.", D(0, 2), [(9, 2m), (10, 5m)], validDays: 30).ConfigureAwait(false);
await owner.Engine.CloseAsync(Seed, company, q2.Family, q2.Header.Id, cancellationToken).ConfigureAwait(false);
await NewAsync("PRE", "Esposito Mario", today, [(11, 1m)], validDays: 15, confirm: false).ConfigureAwait(false);
// Orders (numerator ORD): from the accepted quotations and direct.
var o1 = await ConfirmAsync(await CopyAsync(q1, "OC", D(5, 20)).ConfigureAwait(false)).ConfigureAwait(false);
var o3 = await NewAsync("OC", "Edilizia Moderna S.p.A.", D(3, 10), [(0, 10m), (2, 30m), (5, 50m)], reference: "ORD-EM-0412").ConfigureAwait(false);
var o2 = await ConfirmAsync(await CopyAsync(q4, "OC", D(2, 12)).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("OC", "Hotel Belvedere S.r.l.", D(1, 8), [(3, 4m), (4, 4m), (11, 2m)], reference: "Ristrutturazione bagni").ConfigureAwait(false);
// Delivery notes (numerator DDT): one per order, the second order in two goes; the last three stay to invoice.
var d1 = await ConfirmAsync(await CopyAsync(o1, "DDT", D(4, 2)).ConfigureAwait(false)).ConfigureAwait(false);
var d2 = await ConfirmAsync(await CopyAsync(o3, "DDT", D(3, 15), [o3.Lines[0].Id, o3.Lines[1].Id]).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(o2, "DDT", D(1, 5)).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(o3, "DDT", D(1, 12)).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("DDT", "Rossi Impianti S.r.l.", D(1, 20), [(6, 15m), (1, 6m)]).ConfigureAwait(false);
// Invoices and notes (numerator FAT, shared), in date order.
await NewAsync("FI", "Bianchi & Figli S.n.c.", D(5, 28), [(2, 12m), (9, 1m)], service: 4m).ConfigureAwait(false);
var f2 = await NewAsync("FI", "Hotel Belvedere S.r.l.", D(4, 10), [(3, 2m), (4, 2m), (10, 3m)]).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(d1, "FD", D(4, 30)).ConfigureAwait(false)).ConfigureAwait(false);
await ConfirmAsync(await CopyAsync(d2, "FD", D(3, 31)).ConfigureAwait(false)).ConfigureAwait(false);
var note = await CopyAsync(f2, "NC", D(2, 15), [f2.Lines[0].Id]).ConfigureAwait(false);
note.Lines[^1].Quantity = 1m;
note.Header.Notes = "Reso di un articolo difettoso.";
await ConfirmAsync(await owner.Engine.SaveAsync(Seed, company, note, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
await NewAsync("FI", "Edilizia Moderna S.p.A.", D(1, 25), [(7, 30m), (8, 10m)], service: 16m).ConfigureAwait(false);
await NewAsync("FI", "Rossi Impianti S.r.l.", D(0, 5), [(0, 2m), (11, 1m)]).ConfigureAwait(false);
await NewAsync("FI", "Idrotermica Piemonte S.r.l.", today, [(5, 8m)], confirm: false).ConfigureAwait(false);
await NewAsync("PF", "Esposito Mario", today, [(9, 1m)], service: 3m).ConfigureAwait(false);
}
// A new document of the customer with goods (index in the demo goods, quantity) and optional hours of work.
private async Task<DocumentRecord> NewAsync(
string type, string customer, DateOnly date, IReadOnlyList<(int Good, decimal Quantity)> lines, int? validDays = null, decimal? service = null,
string? reference = null, bool confirm = true)
{
var record = await owner.Engine.NewAsync(Seed, company, type, cancellationToken).ConfigureAwait(false);
record.Header.IsDemo = true;
record.Header.DocumentDate = date;
record.Header.ExternalReference = reference;
await owner.Editor.ApplyPartyAsync(Seed, company, record, Party(customer), cancellationToken).ConfigureAwait(false);
if (validDays is { } days)
{
record.Header.ValidUntil = date.AddDays(days);
}
foreach (var (good, quantity) in lines)
{
await AddAsync(record, data.Goods[good % data.Goods.Count], quantity).ConfigureAwait(false);
}
if (service is { } hours)
{
await AddAsync(record, data.Services[0], hours).ConfigureAwait(false);
}
record = await owner.Engine.SaveAsync(Seed, company, record, cancellationToken).ConfigureAwait(false);
return confirm ? await ConfirmAsync(record).ConfigureAwait(false) : record;
}
private async Task AddAsync(DocumentRecord record, long itemId, decimal quantity)
{
var line = DocumentStores.Of(record.Family).NewLine();
line.Quantity = quantity;
await owner.Editor.FillLineAsync(Seed, company, record, line, itemId, cancellationToken).ConfigureAwait(false);
record.Lines.Add(line);
}
private Task<DocumentRecord> CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection<long>? lines = null) =>
owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken);
private Task<DocumentRecord> ConfirmAsync(DocumentRecord record) =>
owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken);
}
}
+2
View File
@@ -124,6 +124,8 @@ public static class LogSections
_ when category.Contains("Migration", StringComparison.Ordinal) => LogSection.Migrations,
_ when category.StartsWith("Khaemhat.Data", StringComparison.Ordinal) => LogSection.Database,
_ when category.Contains(".Jobs", StringComparison.Ordinal) => LogSection.ScheduledJobs,
_ when category.Contains(".Mail", StringComparison.Ordinal) => LogSection.Email,
_ when category.Contains(".Documents", StringComparison.Ordinal) => LogSection.Documents,
_ when category.StartsWith("Microsoft.AspNetCore.Components", StringComparison.Ordinal) => LogSection.Ui,
_ when category.Contains("SlowQuer", StringComparison.Ordinal) || category.Contains("Performance", StringComparison.Ordinal) => LogSection.Performance,
_ => LogSection.System,
+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);
}
@@ -273,6 +273,12 @@ else
Value="@PartyScreens.Text(s.CompanyBankAccountId)" ValueChanged="v => Change(() => s.CompanyBankAccountId = PartyScreens.Id(v))" />
<KhNumberBox Label="@T["Parties.Fields.CreditLimit"]" Name="Sales.CreditLimit" Value="s.CreditLimit" ValueChanged="v => Change(() => s.CreditLimit = v)" Min="0" Span="3" />
<KhCheck Label="@T["Parties.Fields.Blocked"]" Name="Sales.Blocked" Value="s.Blocked" ValueChanged="v => Change(() => s.Blocked = v)" Span="3" />
<KhSelect TValue="string" Label="@T["Parties.Fields.ExcludedMonth1"]" Name="Sales.ExcludedMonth1" Options="MonthChoices" Empty="" Span="4"
Value="@s.ExcludedMonth1?.ToString(System.Globalization.CultureInfo.InvariantCulture)" ValueChanged="v => Change(() => s.ExcludedMonth1 = Month(v))" />
<KhSelect TValue="string" Label="@T["Parties.Fields.ExcludedMonth2"]" Name="Sales.ExcludedMonth2" Options="MonthChoices" Empty="" Span="4"
Value="@s.ExcludedMonth2?.ToString(System.Globalization.CultureInfo.InvariantCulture)" ValueChanged="v => Change(() => s.ExcludedMonth2 = Month(v))" />
<KhNumberBox Label="@T["Parties.Fields.ExcludedMonthsDay"]" Name="Sales.ExcludedMonthsDay" Value="s.ExcludedMonthsDay" ValueChanged="v => Change(() => s.ExcludedMonthsDay = (int?)v)"
Min="1" Max="31" Decimals="0" Span="4" Hint="@T["Parties.Hints.ExcludedMonths"]" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Parties.Groups.Delivery"]" Icon="truck">
<KhSelect TValue="string" Label="@T["Parties.Fields.CarrierId"]" Name="Sales.CarrierId" Options="_lookups.Carriers" Empty=""
@@ -874,6 +880,13 @@ else
private void SetAddressKind(PartyAddress address, string? value) => Change(() => address.Kind = Enum.Parse<PartyAddressKind>(value!));
// The months a customer excludes from the due dates (August, December...), named in the language of the screen.
private IReadOnlyList<KhOption<string>> MonthChoices =>
[.. Enumerable.Range(1, 12).Select(m => new KhOption<string>(m.ToString(System.Globalization.CultureInfo.InvariantCulture),
T.Culture.TextInfo.ToTitleCase(T.Culture.DateTimeFormat.GetMonthName(m))))];
private static int? Month(string? value) => int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var m) ? m : null;
private void SetDelivery(PartySalesTerms terms, string? value) => Change(() => terms.SendDocuments = Enum.Parse<DocumentDelivery>(value!));
private Task SetSubjectAsync(string? value)
@@ -0,0 +1,334 @@
@page "/vendite/fatturazione-differita"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Parties
@using Khaemhat.Application.Security
@using Khaemhat.Core.Documents
@using Khaemhat.Core.Parties
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Tables
@inject ShellSession Session
@inject DocumentEditor Editor
@inject DocumentEngine Engine
@inject DocumentCopyService Copies
@inject PartyService Parties
@inject ToastService Toasts
@inject TimeProvider Clock
@* The deferred invoicing (SPEC §11.3, mockup 030): the confirmed delivery notes not yet invoiced in a period, for one
customer or all; one deferred invoice (TD24) per customer, or per delivery note, with a reference line for each
delivery note; the invoices can be issued at once. *@
<KhPageTitle Text="@T["Sales.Deferred.Title"]" Icon="layers" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (!Session.Permissions.Allows("sales.invoice.write") || !Session.Permissions.Allows("sales.delivery.read"))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else
{
<div class="kh-import">
<div class="kh-import-side">
<KhPanel Title="@T["Sales.Deferred.Procedure"]" Icon="layers">
<KhVSteps Items="Steps" Current="_step" Label="@T["Sales.Deferred.Procedure"]" />
<div class="kh-import-options">
<KhDateBox Label="@T["Sales.Deferred.From"]" Name="From" Value="_from" ValueChanged="v => Reset(() => _from = v)" Span="6" Disabled="_busy" />
<KhDateBox Label="@T["Sales.Deferred.To"]" Name="To" Value="_to" ValueChanged="v => Reset(() => _to = v)" Span="6" Required="true" Disabled="_busy" />
<KhHotlink TItem="PartyRow" Label="@T["Sales.Deferred.Customer"]" Name="PartyId" Value="_party" ValueChanged="v => Reset(() => _party = v)" Span="12"
Search="SearchAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" Hint="@T["Sales.Deferred.AllCustomers"]" Disabled="_busy" />
<KhDateBox Label="@T["Sales.Deferred.InvoiceDate"]" Name="InvoiceDate" Value="_invoiceDate" ValueChanged="v => _invoiceDate = v" Span="12" Required="true" Disabled="_busy" />
<KhSelect TValue="string" Label="@T["Sales.Deferred.Grouping"]" Name="Grouping" Options="GroupingChoices" Value="@(_perNote ? "note" : "party")"
ValueChanged="SetGrouping" Span="12" Disabled="_busy" />
<KhCheck Label="@T["Sales.Deferred.Issue"]" Name="Issue" Value="_issue" ValueChanged="v => _issue = v" Span="12" Disabled="_busy" />
<div class="c12 kh-endrow">
<button type="button" class="btn" disabled="@_busy" @onclick="SearchNotesAsync"><KhIcon Name="search" /> @T["Sales.Deferred.Search"]</button>
</div>
</div>
</KhPanel>
</div>
<div class="kh-import-main">
@if (_results.Count > 0)
{
<KhPanel Title="@T["Sales.Deferred.Results"]" Icon="check-circle">
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Deferred.Results"]">
<thead>
<tr>
<th scope="col">@T["Sales.Fields.PartyId"]</th>
<th scope="col">@T["Sales.Deferred.Invoice"]</th>
<th scope="col">@T["Sales.Radar.State"]</th>
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
</tr>
</thead>
<tbody>
@foreach (var result in _results)
{
<tr>
<td>@result.PartyName</td>
@if (result.Record is { } record)
{
var state = SalesScreens.State(T, record.Header.Kind, record.Header.Status, null, Today);
<td class="code"><a href="@SalesScreens.RecordUrl(record.Header.Kind, record.Header.Id)">@(record.Header.DocumentNumber ?? T["Sales.DraftNumber"])</a></td>
<td><KhBadge Tone="state.Tone">@state.Text</KhBadge></td>
<td class="num">@T.Money(record.Header.TotalAmount)</td>
}
else
{
<td colspan="3" class="err"><KhIcon Name="alert-circle" /> @result.Error</td>
}
</tr>
}
</tbody>
</table>
</div>
<div class="kh-endrow kh-pad">
<a class="btn" href="vendite/fatture"><KhIcon Name="euro" /> @T["Sales.Sections.Invoices.Title"]</a>
<button type="button" class="btn" @onclick="Restart"><KhIcon Name="refresh" /> @T["Sales.Deferred.Again"]</button>
</div>
</KhPanel>
}
else
{
<KhPanel Title="@T["Sales.Deferred.Notes"]" Icon="truck">
<Actions>
<span class="muted sm">@T.Format("Sales.Deferred.Selected", _selected.Count, T.Money(SelectedTotal))</span>
<button type="button" class="btn primary" disabled="@(_selected.Count == 0 || _busy || _invoiceDate is null)" @onclick="GenerateAsync">
<KhIcon Name="send" /> @T["Sales.Deferred.Generate"]
</button>
</Actions>
<ChildContent>
@if (_notes is null)
{
<p class="muted kh-pad">@T["Sales.Deferred.Start"]</p>
}
else if (_notes.Count == 0)
{
<p class="muted kh-pad">@T["Sales.Deferred.None"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Deferred.Notes"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@(_selected.Count == _notes.Count)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAll" /></th>
<th scope="col">@T["Sales.Kinds.DeliveryNote"]</th>
<th scope="col">@T["Sales.Fields.DocumentDate"]</th>
<th scope="col">@T["Sales.Fields.PartyId"]</th>
<th scope="col" class="num">@T["Sales.Deferred.Lines"]</th>
<th scope="col" class="num">@T["Sales.Totals.Taxable"]</th>
<th scope="col">@T["Sales.Deferred.Invoice"]</th>
</tr>
</thead>
<tbody>
@foreach (var note in _notes)
{
var id = note.Row.Id;
<tr>
<td class="kh-check"><input type="checkbox" checked="@_selected.Contains(id)" aria-label="@note.Row.DocumentNumber" @onchange="e => Toggle(id, e.Value is true)" /></td>
<td class="code"><a href="@SalesScreens.RecordUrl(note.Row.Kind, id)">@note.Row.DocumentNumber</a></td>
<td>@T.Date(note.Row.Date)</td>
<td>@note.Row.PartyName</td>
<td class="num">@note.Lines.Count</td>
<td class="num">@T.Money(note.Row.Taxable)</td>
<td class="muted">@InvoiceLabel(note)</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
</KhPanel>
}
</div>
</div>
}
@code {
private readonly HashSet<long> _selected = [];
private readonly List<DeferredResult> _results = [];
private IReadOnlyList<OpenDocument>? _notes;
private PartyRow? _party;
private DateOnly? _from;
private DateOnly? _to;
private DateOnly? _invoiceDate;
private bool _perNote;
private bool _issue;
private bool _busy;
private bool _loaded;
private int _step;
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
private IReadOnlyList<KhStep> Steps =>
[
new(T["Sales.Deferred.Steps.Period"], T["Sales.Deferred.Steps.PeriodDetail"]),
new(T["Sales.Deferred.Steps.Choose"], T["Sales.Deferred.Steps.ChooseDetail"]),
new(T["Sales.Deferred.Steps.Generate"], T["Sales.Deferred.Steps.GenerateDetail"]),
];
private IReadOnlyList<KhOption<string>> GroupingChoices =>
[new("party", T["Sales.Deferred.PerParty"]), new("note", T["Sales.Deferred.PerNote"])];
private decimal SelectedTotal => _notes?.Where(n => _selected.Contains(n.Row.Id)).Sum(n => n.Row.Taxable) ?? 0m;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
// The usual run: the delivery notes of last month, invoiced on its last day.
var firstOfMonth = new DateOnly(Today.Year, Today.Month, 1);
_from = firstOfMonth.AddMonths(-1);
_to = firstOfMonth.AddDays(-1);
_invoiceDate = _to;
_loaded = true;
}
private void Reset(Action change)
{
change();
_notes = null;
_selected.Clear();
_step = 0;
}
private async Task<IReadOnlyList<PartyRow>> SearchAsync(string text, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && Session.Permissions.Allows(PartyService.ReadPermission)
? await Parties.SearchAsync(actor, company, PartyArchive.Customers, text, cancellationToken)
: [];
private async Task SearchNotesAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
if (_to is null)
{
Toasts.Show(ToastKind.Error, T["Sales.Deferred.ToRequired"]);
return;
}
_busy = true;
try
{
_notes = await Editor.OpenAsync(actor, company, DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], _party?.Id, _from, _to);
_selected.Clear();
_selected.UnionWith(_notes.Select(n => n.Row.Id));
_step = 1;
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, T["Pages.AccessDenied.Title"]);
}
finally
{
_busy = false;
}
}
private void Toggle(long id, bool on)
{
if (on)
{
_selected.Add(id);
}
else
{
_selected.Remove(id);
}
}
private void ToggleAll(ChangeEventArgs e)
{
_selected.Clear();
if (e.Value is true && _notes is not null)
{
_selected.UnionWith(_notes.Select(n => n.Row.Id));
}
}
// The invoices the run will make: one per customer (or per delivery note), in the order of the list.
private List<List<OpenDocument>> Groups() => _notes is null ? [] : _perNote
? [.. _notes.Where(n => _selected.Contains(n.Row.Id)).Select(n => new List<OpenDocument> { n })]
: [.. _notes.Where(n => _selected.Contains(n.Row.Id)).GroupBy(n => n.Row.PartyId).Select(g => g.ToList())];
private string? InvoiceLabel(OpenDocument note)
{
if (!_selected.Contains(note.Row.Id))
{
return null;
}
var groups = Groups();
var index = groups.FindIndex(g => g.Any(n => n.Row.Id == note.Row.Id));
return index < 0 ? null : T.Format("Sales.Deferred.InvoiceNumber", index + 1, groups[index].Count);
}
private async Task GenerateAsync()
{
if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _invoiceDate is not { } date)
{
return;
}
_busy = true;
_results.Clear();
try
{
foreach (var group in Groups())
{
var name = group[0].Row.PartyName ?? string.Empty;
try
{
var invoice = await Copies.MergeAsync(actor, company, DocumentFamily.SaleDocument, [.. group.Select(n => n.Row.Id)], "FD", date);
if (_issue)
{
invoice = await Engine.ConfirmAsync(actor, company, invoice.Family, invoice.Header.Id);
}
_results.Add(new(name, invoice, null));
}
catch (ValidationFailedException ex)
{
_results.Add(new(name, null, string.Join(" ", ex.Errors.Select(e => TableValues.SplitError(e).Code).Select(c => T.Contains(c) ? T[c] : c))));
}
catch (InvalidDocumentActionException)
{
_results.Add(new(name, null, T[InvalidDocumentActionException.Code]));
}
}
_step = 2;
var made = _results.Count(r => r.Record is not null);
Toasts.Show(made == _results.Count ? ToastKind.Success : ToastKind.Warning, T.Format("Sales.Deferred.Done", made, _results.Count));
}
finally
{
_busy = false;
}
}
private void SetGrouping(string? value) => _perNote = value == "note";
private void Restart()
{
_results.Clear();
Reset(() => { });
}
private sealed record DeferredResult(string PartyName, DocumentRecord? Record, string? Error);
}
@@ -0,0 +1,409 @@
@page "/vendite/{Segment}/nuovo"
@page "/vendite/{Segment}/{Id:long}"
@attribute [Authorize]
@inherits DocumentPage<DocumentRecord, DocumentLine>
@using Khaemhat.Application.Audit
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Items
@using Khaemhat.Application.Parties
@using Khaemhat.Core.Documents
@using Khaemhat.Core.Tax
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Parties
@* The record of a sales document (SPEC §11.3, mockups 020-022 and 026-029): quotation, order, delivery note, invoice of
every kind, pro forma, credit and debit note. Righe first with the VAT summary, due dates and totals underneath, then
Testata, Trasporto for the documents that move goods, Totali, Scadenze, Note, Allegati, Collegamenti, Storico. The
totals are computed while typing with the code of the save; the actions follow the state machine of the engine. *@
<KhPageTitle Text="@PageTitle" Icon="@(_section?.Icon ?? "file")" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (_denied)
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else if (Record is null || _section is null || _definition is null)
{
<div class="kh-message">
<KhIcon Name="alert" Class="lg" />
<h1>@T["Sales.NotFound"]</h1>
<a class="btn" href="@(_section is null ? SalesScreens.BasePath : SalesScreens.RadarUrl(_section))">@T["Sales.BackToList"]</a>
</div>
}
else
{
var h = Record.Header;
<KhRecordLayout Page="this">
<Heading>
<KhDocHead KindIcon="@_section.Icon" KindLabel="@_definition.Type.Description" Number="@(h.DocumentNumber ?? T["Sales.DraftNumber"])"
PartyName="@(_party?.Name ?? T["Sales.NoParty"])" PartyCode="@_party?.Code" PartyLines="PartyLines"
TotalLabel="@T[ShowsNet ? "Sales.Totals.Net" : "Sales.Totals.Total"]" TotalValue="@T.Money(ShowsNet ? h.NetAmount : h.TotalAmount)" SubValues="HeadStats">
<Facts>
<span>@T["Sales.Fields.DocumentDate"] <b>@T.Date(h.DocumentDate)</b></span>
@if (h.Kind == DocumentKind.Quotation && h.ValidUntil is { } until)
{
<span>@T["Sales.Fields.ValidUntil"] <b>@T.Date(until)</b></span>
}
@if (h.DeliveryDate is { } delivery)
{
<span>@T["Sales.Fields.DeliveryDate"] <b>@T.Date(delivery)</b></span>
}
@if (h.Revision > 0)
{
<span>@T["Sales.Fields.Revision"] <b>@h.Revision</b></span>
}
@if (h.RelatedNumber is { } related)
{
<span>@T["Sales.Fields.Related"] <b>@related</b>@(h.RelatedDate is { } rd ? " · " + T.Date(rd) : null)</span>
}
</Facts>
<State>
@{ var state = SalesScreens.State(T, h.Kind, h.Status, h.ValidUntil, Today); }
<KhBadge Tone="state.Tone">@state.Text</KhBadge>
@if (h.IsDemo)
{
<KhBadge Tone="KhTone.Info">@T["Sales.Demo"]</KhBadge>
}
@if (IsModified)
{
<KhBadge Tone="KhTone.Warning">@T["CompanyTables.Modified"]</KhBadge>
}
</State>
<Chips>
@if (PartyScreens.Describe(_lookups.PaymentTerms, h.PaymentTermId) is { } payment)
{
<KhChip Icon="coins" Text="@T["Sales.Fields.PaymentTermId"]" Value="@payment" />
}
@if (PartyScreens.Describe(_lookups.PriceLists, h.PriceListId) is { } list)
{
<KhChip Icon="tag" Text="@T["Sales.Fields.PriceListId"]" Value="@list" />
}
@if (PartyScreens.Describe(_lookups.Salespeople, h.SalespersonId) is { } agent)
{
<KhChip Icon="user" Text="@T["Sales.Fields.SalespersonId"]" Value="@agent" />
}
@if (h.SplitPayment)
{
<KhChip Icon="shield" Text="@T["Sales.Fields.SplitPayment"]" Value="@T["Common.Yes"]" />
}
</Chips>
</KhDocHead>
</Heading>
<ChildContent>
@switch (ActiveTab)
{
case TabIds.Lines:
@if (h.PartyId is null && !IsReadOnly)
{
<div class="callout info kh-doc-callout"><KhIcon Name="info" /> <span>@T["Sales.Hints.PartyFirst"]</span>
<button type="button" class="btn" @onclick="() => ShowTabAsync(TabIds.Header)">@T["Sales.Actions.ChooseParty"]</button></div>
}
<KhLinesGrid TLine="DocumentLine" @ref="_grid" Lines="Record.Lines" Columns="LineColumns" NewLine="NewLine" IsEmpty="IsEmptyLine"
IsDescriptive="l => l.Kind == DocumentLineKind.Description" NewDescriptive="NewDescriptionLine" DescriptionColumn="LineColumns[1]"
ReadOnly="IsReadOnly" OnChanged="LinesChangedAsync" Label="@T["Sales.Lines.Title"]" />
@if (Validation.Messages.Any(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true))
{
<ul class="kh-doc-errors">
@foreach (var message in Validation.Messages.Where(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true))
{
<li><KhIcon Name="alert-circle" /> @LineErrorText(message.Field!, message.Message)</li>
}
</ul>
}
<div class="kh-doc-panels">
<KhPanel Title="@T["Sales.Totals.Summary"]" Icon="euro" Tight="true">@TaxSummary</KhPanel>
<KhPanel Title="@T["Sales.Totals.Installments"]" Icon="calendar" Tight="true">@Installments</KhPanel>
<KhPanel Title="@T["Sales.Totals.Title"]" Icon="coins" Tight="true">@Totals</KhPanel>
</div>
break;
case TabIds.Header:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Document"]" Icon="file">
<KhTextBox Label="@T["Sales.Fields.DocumentTypeId"]" Name="DocumentTypeId" Value="@(_definition.Code + " · " + _definition.Type.Description)" ReadOnly="true" Span="6" />
<KhTextBox Label="@T["Sales.Fields.DocumentNumber"]" Name="DocumentNumber" Value="@(h.DocumentNumber ?? T["Sales.NumberOnConfirm"])" ReadOnly="true" Mono="true" Span="6" />
<KhDateBox Label="@T["Sales.Fields.DocumentDate"]" Name="DocumentDate" Value="h.DocumentDate" Required="true" Span="4" ReadOnly="@(h.Number is not null)"
ValueChanged="v => ChangeAsync(() => { if (v is { } d) { h.DocumentDate = d; h.Year = d.Year; } })" />
@if (h.Kind == DocumentKind.Quotation)
{
<KhDateBox Label="@T["Sales.Fields.ValidUntil"]" Name="ValidUntil" Value="h.ValidUntil" ValueChanged="v => Change(() => h.ValidUntil = v)" Span="4" />
}
@if (h.Kind is DocumentKind.Quotation or DocumentKind.SalesOrder or DocumentKind.DeliveryNote or DocumentKind.ProForma)
{
<KhDateBox Label="@T["Sales.Fields.DeliveryDate"]" Name="DeliveryDate" Value="h.DeliveryDate" ValueChanged="v => Change(() => h.DeliveryDate = v)" Span="4" />
}
<KhTextBox Label="@T["Sales.Fields.ExternalReference"]" Name="ExternalReference" Value="@h.ExternalReference" ValueChanged="v => Change(() => h.ExternalReference = v)"
Span="8" MaxLength="60" Hint="@T["Sales.Hints.ExternalReference"]" />
<KhDateBox Label="@T["Sales.Fields.ExternalDate"]" Name="ExternalDate" Value="h.ExternalDate" ValueChanged="v => Change(() => h.ExternalDate = v)" Span="4" />
@if (IsNote)
{
<KhTextBox Label="@T["Sales.Fields.RelatedNumber"]" Name="RelatedNumber" Value="@h.RelatedNumber" ValueChanged="v => Change(() => h.RelatedNumber = v)"
Span="8" MaxLength="30" Mono="true" Hint="@T["Sales.Hints.Related"]" />
<KhDateBox Label="@T["Sales.Fields.RelatedDate"]" Name="RelatedDate" Value="h.RelatedDate" ValueChanged="v => Change(() => h.RelatedDate = v)" Span="4" />
}
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Party"]" Icon="users">
<KhHotlink TItem="PartyRow" Label="@T["Sales.Fields.PartyId"]" Name="PartyId" Span="12" Required="true" Value="_party" ValueChanged="SetPartyAsync"
Search="SearchPartiesAsync" CodeOf="r => r.Code" DescriptionOf="r => r.Name" OnOpen="OpenParty" ReadOnly="@(Record.Lines.Any(l => l.SourceLineId is not null))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.SalespersonId"]" Name="SalespersonId" Options="_lookups.Salespeople" Empty="" Span="6"
Value="@PartyScreens.Text(h.SalespersonId)" ValueChanged="v => Change(() => h.SalespersonId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.CurrencyCode"]" Name="CurrencyCode" Options="_lookups.Currencies" Span="6"
Value="@h.CurrencyCode" ValueChanged="SetCurrency" />
@if (h.PartyId is not null)
{
<p class="muted sm c12"><KhIcon Name="info" /> @T["Sales.Hints.PartyDefaults"]</p>
}
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Conditions"]" Icon="coins">
<KhSelect TValue="string" Label="@T["Sales.Fields.PriceListId"]" Name="PriceListId" Options="_lookups.PriceLists" Empty="" Span="6"
Value="@PartyScreens.Text(h.PriceListId)" ValueChanged="v => Change(() => h.PriceListId = PartyScreens.Id(v))" />
<KhTextBox Label="@T["Sales.Fields.FooterDiscount"]" Name="FooterDiscount" Value="@h.FooterDiscount" ValueChanged="v => ChangeAsync(() => h.FooterDiscount = v)"
Span="3" Mono="true" MaxLength="30" Placeholder="10+5" />
<KhCheck Label="@T["Sales.Fields.PricesIncludeTax"]" Name="PricesIncludeTax" Value="h.PricesIncludeTax" ValueChanged="v => ChangeAsync(() => h.PricesIncludeTax = v)" Span="3" />
<KhSelect TValue="string" Label="@T["Sales.Fields.PaymentTermId"]" Name="PaymentTermId" Options="_lookups.PaymentTerms" Empty="" Span="6"
Value="@PartyScreens.Text(h.PaymentTermId)" ValueChanged="v => ChangeAsync(() => h.PaymentTermId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.PaymentMethodId"]" Name="PaymentMethodId" Options="_lookups.PaymentMethods" Empty="" Span="6"
Value="@PartyScreens.Text(h.PaymentMethodId)" ValueChanged="v => Change(() => h.PaymentMethodId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.BankAccountId"]" Name="BankAccountId" Options="_lookups.BankAccounts" Empty="" Span="12"
Value="@PartyScreens.Text(h.BankAccountId)" ValueChanged="v => Change(() => h.BankAccountId = PartyScreens.Id(v))" />
</KhFieldGroup>
@if (IsInvoice)
{
<KhFieldGroup Title="@T["Sales.Groups.Tax"]" Icon="shield">
<KhSelect TValue="string" Label="@T["Sales.Fields.Exigibility"]" Name="Exigibility" Options="ExigibilityChoices" Empty="" Span="6"
Value="@h.Exigibility?.ToString()" ValueChanged="SetExigibilityAsync" />
<KhCheck Label="@T["Sales.Fields.SplitPayment"]" Name="SplitPayment" Value="h.SplitPayment" ValueChanged="v => ChangeAsync(() => h.SplitPayment = v)" Span="3" />
<KhCheck Label="@T["Sales.Fields.StampDutyCharged"]" Name="StampDutyCharged" Value="h.StampDutyCharged" ValueChanged="v => ChangeAsync(() => h.StampDutyCharged = v)" Span="3" />
<KhTextBox Label="@T["Sales.Fields.Cig"]" Name="Cig" Value="@h.Cig" ValueChanged="v => Change(() => h.Cig = v)" Span="6" Mono="true" MaxLength="15" />
<KhTextBox Label="@T["Sales.Fields.Cup"]" Name="Cup" Value="@h.Cup" ValueChanged="v => Change(() => h.Cup = v)" Span="6" Mono="true" MaxLength="15" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Withholding"]" Icon="coins">
<KhNumberBox Label="@T["Sales.Fields.WithholdingRate"]" Name="WithholdingRate" Value="h.WithholdingRate" ValueChanged="v => ChangeAsync(() => h.WithholdingRate = v)" Min="0" Max="100" Span="3" />
<KhNumberBox Label="@T["Sales.Fields.WithholdingBasePercent"]" Name="WithholdingBasePercent" Value="h.WithholdingBasePercent"
ValueChanged="v => ChangeAsync(() => h.WithholdingBasePercent = v ?? 100m)" Min="0" Max="100" Span="3" />
<KhTextBox Label="@T["Sales.Fields.WithholdingType"]" Name="WithholdingType" Value="@h.WithholdingType" ValueChanged="v => Change(() => h.WithholdingType = v)" Span="3" Mono="true" MaxLength="4" Placeholder="RT01" />
<KhTextBox Label="@T["Sales.Fields.WithholdingReason"]" Name="WithholdingReason" Value="@h.WithholdingReason" ValueChanged="v => Change(() => h.WithholdingReason = v)" Span="3" Mono="true" MaxLength="2" Placeholder="A" />
<KhTextBox Label="@T["Sales.Fields.SocialSecurityFund"]" Name="SocialSecurityFund" Value="@h.SocialSecurityFund" ValueChanged="v => Change(() => h.SocialSecurityFund = v)" Span="3" Mono="true" MaxLength="4" Placeholder="TC22" />
<KhNumberBox Label="@T["Sales.Fields.SocialSecurityRate"]" Name="SocialSecurityRate" Value="h.SocialSecurityRate" ValueChanged="v => ChangeAsync(() => h.SocialSecurityRate = v)" Min="0" Max="100" Span="3" />
<KhSelect TValue="string" Label="@T["Sales.Fields.SocialSecurityTaxCodeId"]" Name="SocialSecurityTaxCodeId" Options="_lookups.TaxCodes" Empty="" Span="3"
Value="@PartyScreens.Text(h.SocialSecurityTaxCodeId)" ValueChanged="v => ChangeAsync(() => h.SocialSecurityTaxCodeId = PartyScreens.Id(v))" />
<KhCheck Label="@T["Sales.Fields.SocialSecurityWithheld"]" Name="SocialSecurityWithheld" Value="h.SocialSecurityWithheld" ValueChanged="v => ChangeAsync(() => h.SocialSecurityWithheld = v)" Span="3" />
<KhNumberBox Label="@T["Sales.Fields.EnasarcoRate"]" Name="EnasarcoRate" Value="h.EnasarcoRate" ValueChanged="v => ChangeAsync(() => h.EnasarcoRate = v)" Min="0" Max="100" Span="3" />
<p class="muted sm c9">@T["Sales.Hints.Withholding"]</p>
</KhFieldGroup>
}
</KhForm>
break;
case SalesScreens.TransportTab:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Transport"]" Icon="truck">
<KhSelect TValue="string" Label="@T["Sales.Fields.TransportReasonId"]" Name="TransportReasonId" Options="_lookups.TransportReasons" Empty="" Span="6"
Value="@PartyScreens.Text(h.TransportReasonId)" ValueChanged="v => Change(() => h.TransportReasonId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.TransportBy"]" Name="TransportBy" Options="TransportChoices" Empty="" Span="6"
Value="@h.TransportBy?.ToString()" ValueChanged="SetTransportBy" />
<KhSelect TValue="string" Label="@T["Sales.Fields.CarrierId"]" Name="CarrierId" Options="_lookups.Carriers" Empty="" Span="6"
Value="@PartyScreens.Text(h.CarrierId)" ValueChanged="v => Change(() => h.CarrierId = PartyScreens.Id(v))" />
<KhSelect TValue="string" Label="@T["Sales.Fields.ShippingTermId"]" Name="ShippingTermId" Options="_lookups.ShippingTerms" Empty="" Span="6"
Value="@PartyScreens.Text(h.ShippingTermId)" ValueChanged="v => Change(() => h.ShippingTermId = PartyScreens.Id(v))" />
<KhDateBox Label="@T["Sales.Fields.TransportStartDate"]" Name="TransportStart" Value="TransportDate" ValueChanged="SetTransportDate" Span="4" />
<KhTextBox Label="@T["Sales.Fields.TransportStartTime"]" Name="TransportStartTime" Type="time" Value="@TransportTime" ValueChanged="SetTransportTime" Span="2" />
<KhSelect TValue="string" Label="@T["Sales.Fields.WarehouseId"]" Name="WarehouseId" Options="_lookups.Warehouses" Empty="" Span="6"
Value="@PartyScreens.Text(h.WarehouseId)" ValueChanged="v => Change(() => h.WarehouseId = PartyScreens.Id(v))" />
</KhFieldGroup>
<KhFieldGroup Title="@T["Sales.Groups.Goods"]" Icon="box">
<KhSelect TValue="string" Label="@T["Sales.Fields.GoodsAppearanceId"]" Name="GoodsAppearanceId" Options="_lookups.GoodsAppearances" Empty="" Span="12"
Value="@PartyScreens.Text(h.GoodsAppearanceId)" ValueChanged="v => Change(() => h.GoodsAppearanceId = PartyScreens.Id(v))" />
<KhNumberBox Label="@T["Sales.Fields.Packages"]" Name="Packages" Value="h.Packages" ValueChanged="v => Change(() => h.Packages = (int?)v)" Min="0" Decimals="0" Span="4" />
<KhNumberBox Label="@T["Sales.Fields.GrossWeight"]" Name="GrossWeight" Value="h.GrossWeight" ValueChanged="v => Change(() => h.GrossWeight = v)" Min="0" Decimals="3" Span="4" />
<KhNumberBox Label="@T["Sales.Fields.NetWeight"]" Name="NetWeight" Value="h.NetWeight" ValueChanged="v => Change(() => h.NetWeight = v)" Min="0" Decimals="3" Span="4" />
<p class="muted sm c12">@T["Sales.Hints.Transport"]</p>
</KhFieldGroup>
</KhForm>
break;
case TabIds.Totals:
<div class="kh-doc-panels wide">
<KhPanel Title="@T["Sales.Totals.Summary"]" Icon="euro" Tight="true">@TaxSummary</KhPanel>
<KhPanel Title="@T["Sales.Totals.Title"]" Icon="coins" Tight="true">@Totals</KhPanel>
</div>
break;
case TabIds.DueDates:
<div class="kh-doc-panels single">
<KhPanel Title="@T["Sales.Totals.Installments"]" Icon="calendar" Tight="true">@Installments</KhPanel>
</div>
<p class="muted sm kh-pad"><KhIcon Name="info" /> @T[Behavior.Has(DocumentEffects.Installments) ? "Sales.Hints.Installments" : "Sales.Hints.InstallmentsForecast"]</p>
break;
case TabIds.Notes:
<KhForm Validation="Validation" ReadOnly="IsReadOnly" Layout="KhFormLayout.Groups" @ref="Form">
<KhFieldGroup Title="@T["Sales.Groups.Notes"]" Icon="edit" Wide="true">
<KhTextArea Label="@T["Sales.Fields.Notes"]" Name="Notes" Value="@h.Notes" ValueChanged="v => Change(() => h.Notes = v)" Span="12" Rows="6"
Hint="@T["Sales.Hints.Notes"]" />
</KhFieldGroup>
@if (h.CancelReason is { } reason)
{
<KhFieldGroup Title="@T["Sales.Groups.Cancelled"]" Icon="x-circle" Wide="true">
<KhTextArea Label="@T["Sales.Fields.CancelReason"]" Name="CancelReason" Value="@reason" ReadOnly="true" Span="12" Rows="2" />
</KhFieldGroup>
}
</KhForm>
break;
case TabIds.Attachments:
<div class="kh-tab-body"><KhAttachmentList Entity="@AttachmentEntity" EntityId="h.Id" OnCountChanged="SetAttachments" /></div>
break;
case TabIds.Links:
<div class="kh-tab-body">
@if (_links.Count == 0)
{
<p class="muted">@T["Sales.Links.Empty"]</p>
}
else
{
<div class="gridwrap">
<table class="grid" aria-label="@T["Ui.Record.Tabs.Links"]">
<thead>
<tr>
<th scope="col">@T["Sales.Links.Relation"]</th>
<th scope="col">@T["Sales.Radar.Kind"]</th>
<th scope="col">@T["Sales.Fields.DocumentNumber"]</th>
<th scope="col">@T["Sales.Fields.DocumentDate"]</th>
<th scope="col">@T["Sales.Radar.State"]</th>
<th scope="col" class="num">@T["Sales.Links.Quantity"]</th>
<th scope="col" class="num">@T["Sales.Totals.Total"]</th>
</tr>
</thead>
<tbody>
@foreach (var link in _links)
{
var linkState = SalesScreens.State(T, link.Kind, link.Status, null, Today);
<tr>
<td>@T["Sales.Links." + link.Direction]</td>
<td>@SalesScreens.KindName(T, link.Kind)</td>
<td class="code">
@if (SalesScreens.RecordUrl(link.Kind, link.Id) is { } url)
{
<a href="@url">@(link.DocumentNumber ?? T["Sales.DraftNumber"])</a>
}
else
{
@(link.DocumentNumber ?? T["Sales.DraftNumber"])
}
</td>
<td>@T.Date(link.Date)</td>
<td><KhBadge Tone="linkState.Tone">@linkState.Text</KhBadge></td>
<td class="num">@(link.Quantity > 0 ? T.Number(link.Quantity, 2) : null)</td>
<td class="num">@T.Money(link.Total)</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
break;
case TabIds.History:
<div class="kh-tab-body"><KhAuditList Items="_history" FieldName="FieldLabel" /></div>
break;
}
</ChildContent>
</KhRecordLayout>
<KhRadarDialog TItem="ItemRow" Id="sales.items" Open="_lookupLine is not null" Title="@T["Sales.Lines.ItemRadar"]" Columns="ItemColumns" Source="ListItemsAsync"
KeyOf="i => i.Id" InitialSearch="@_lookupText" OnPick="PickItemAsync" OnClose="CloseLookup" />
<KhDialog Open="_transform is not null" Title="@_transform?.Title" Icon="copy" Size="lg" OnClose="() => _transform = null">
<ChildContent>
@if (_transform is { } t)
{
<p class="muted">@t.Lead</p>
<div class="gridwrap">
<table class="grid" aria-label="@T["Sales.Lines.Title"]">
<thead>
<tr>
<th scope="col" class="kh-check"><input type="checkbox" checked="@(t.Selected.Count == t.Lines.Count)" aria-label="@T["Sales.Transform.All"]" @onchange="ToggleAllLines" /></th>
<th scope="col">@T["Sales.Lines.Description"]</th>
<th scope="col" class="num">@T["Sales.Lines.Quantity"]</th>
@if (t.Fulfils)
{
<th scope="col" class="num">@T["Sales.Lines.Residual"]</th>
}
<th scope="col" class="num">@T["Sales.Lines.Amount"]</th>
</tr>
</thead>
<tbody>
@foreach (var line in t.Lines)
{
var id = line.Id;
<tr class="@(line.Kind == DocumentLineKind.Description ? "kh-desc" : null)">
<td class="kh-check"><input type="checkbox" checked="@t.Selected.Contains(id)" aria-label="@line.Description" @onchange="e => ToggleLine(id, e.Value is true)" /></td>
<td>@line.Description</td>
<td class="num">@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Quantity, 2) : null)</td>
@if (t.Fulfils)
{
<td class="num">@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Residual, 2) : null)</td>
}
<td class="num">@(line.Kind == DocumentLineKind.Description ? null : T.Money(line.TaxableAmount))</td>
</tr>
}
</tbody>
</table>
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _transform = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_transform?.Selected.Count == 0 || _busy)" @onclick="TransformAsync"><KhIcon Name="copy" /> @T["Sales.Transform.Create"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_cancelling" Title="@T["Sales.Actions.Cancel"]" Icon="x-circle" OnClose="() => _cancelling = false">
<ChildContent>
<p>@T[Behavior.Lifecycle == DocumentLifecycle.Invoice ? "Sales.Cancel.LeadInvoice" : "Sales.Cancel.Lead"]</p>
<KhForm Validation="_cancelValidation" Layout="KhFormLayout.Groups">
<KhTextArea Label="@T["Sales.Fields.CancelReason"]" Name="CancelReason" Value="@_cancelReason" ValueChanged="v => _cancelReason = v" Span="12" Rows="3"
Required="@(Behavior.Lifecycle == DocumentLifecycle.Invoice)" />
</KhForm>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _cancelling = false">@T["Common.Cancel"]</button>
<button type="button" class="btn danger" disabled="@_busy" @onclick="CancelDocumentAsync"><KhIcon Name="x-circle" /> @T["Sales.Actions.Cancel"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_mailing" Title="@T["Sales.Mail.Title"]" Icon="mail" Size="lg" OnClose="() => _mailing = false">
<ChildContent>
@if (!Mails.IsConfigured)
{
<div class="callout warn kh-doc-callout"><KhIcon Name="alert" /> <span>@T[DocumentMailErrors.NotConfigured]</span></div>
}
<p class="muted">@T["Sales.Mail.Lead"]</p>
<div class="kh-mail-form">
<KhForm Validation="_mailValidation" Layout="KhFormLayout.Groups">
<KhTextBox Label="@T["Sales.Mail.To"]" Name="To" Value="@_mailTo" ValueChanged="v => _mailTo = v" Span="12" Required="true" Hint="@T["Sales.Mail.ToHint"]" />
<KhTextBox Label="@T["Sales.Mail.Subject"]" Name="Subject" Value="@_mailSubject" ValueChanged="v => _mailSubject = v" Span="12" Required="true" />
<KhTextArea Label="@T["Sales.Mail.Body"]" Name="Body" Value="@_mailBody" ValueChanged="v => _mailBody = v" Span="12" Rows="9" />
</KhForm>
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _mailing = false">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@(_busy || !Mails.IsConfigured)" @onclick="SendMailAsync"><KhIcon Name="send" /> @T["Sales.Mail.Send"]</button>
</Footer>
</KhDialog>
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,185 @@
@page "/vendite/{Segment}"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Core.Documents
@using Khaemhat.Web.Documents
@inject ShellSession Session
@inject DocumentEngine Engine
@inject DocumentEditor Editor
@inject NavigationManager Navigation
@inject TimeProvider Clock
@* The radar of a kind of sales documents (SPEC §11.3): quotations, orders, delivery notes, invoices (with pro forma
and fees), credit and debit notes. Search on number, reference and customer; filters for state, type and year;
totals of the page. Enter or double click opens the document. *@
<KhPageTitle Text="@Title" Icon="@(_section?.Icon ?? "cart")" />
@if (!_loaded)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message"><KhIcon Name="building" Class="lg" /><h1>@T["Sales.NoCompany"]</h1></div>
}
else if (_section is null)
{
<div class="kh-message"><KhIcon Name="alert" Class="lg" /><h1>@T["Pages.NotFound.Title"]</h1></div>
}
else if (!CanRead)
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
</div>
}
else
{
<KhRadar TItem="DocumentRow" @key="_section.Segment" Id="@("sales." + _section.Segment)" Columns="Columns" Source="ListAsync" KeyOf="r => r.Id" Selectable="false"
OnOpen="Open" QuickFilters="QuickFilters" RowClass="RowClassOf" SearchPlaceholder="@T["Sales.Radar.Search"]" ExportName="@_section.Segment"
Label="@Title">
<Toolbar>
@if (NewTypes.Count > 0)
{
<button type="button" class="btn primary" @onclick="New"><KhIcon Name="plus" /> @T["Sales.Sections." + _section.Key + ".New"]</button>
}
@if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write"))
{
<a class="btn" href="@SalesScreens.DeferredInvoicingUrl"><KhIcon Name="layers" /> @T["Sales.Deferred.Title"]</a>
}
</Toolbar>
</KhRadar>
<KhDialog Open="_choosing" Title="@T["Sales.NewDocument"]" Icon="plus" OnClose="() => _choosing = false">
<ChildContent>
<div class="kh-choice-list">
@foreach (var type in NewTypes)
{
<button type="button" class="btn kh-choice" @onclick="() => Create(type.Code)">
<span class="code">@type.Code</span>
<b>@type.Type.Description</b>
<span class="muted sm">@T["Sales.Hints.Kinds." + type.Kind]</span>
</button>
}
</div>
</ChildContent>
</KhDialog>
}
@code {
private SalesSection? _section;
private IReadOnlyList<DocumentDefinition> _definitions = [];
private bool _loaded;
private bool _choosing;
/// <summary>The radar segment, such as <c>fatture</c>.</summary>
[Parameter]
public string? Segment { get; set; }
private string Title => _section is null ? T["Shell.Menu.Sales"] : T["Sales.Sections." + _section.Key + ".Title"];
private bool CanRead => _section is not null && Session.Permissions.Allows(DocumentBehaviors.Of(_section.Kinds[0]).ReadPermission);
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
// The types of the radar the user may create, in the order of the section.
private List<DocumentDefinition> NewTypes => _section is null ? [] :
[.. _section.NewTypes.Select(code => _definitions.FirstOrDefault(d => d.Code == code)).OfType<DocumentDefinition>()
.Where(d => Session.Permissions.Allows(d.Behavior.WritePermission))];
private IReadOnlyList<KhColumn<DocumentRow>> Columns =>
[
new("number", T["Sales.Fields.DocumentNumber"], r => r.DocumentNumber ?? T["Sales.DraftNumber"]) { Kind = KhColumnKind.Code, Width = "130px" },
new("date", T["Sales.Fields.DocumentDate"], r => r.Date) { Kind = KhColumnKind.Date, Width = "100px" },
new("type", T["Sales.Radar.Kind"], r => SalesScreens.KindName(T, r.Kind)) { Width = "150px", Sortable = false, Visible = _section?.Kinds.Count > 1 },
new("party", T["Sales.Fields.PartyId"], r => r.PartyName) { Sortable = false },
new("reference", T["Sales.Fields.ExternalReference"], r => r.Reference) { Width = "140px" },
new("validUntil", T["Sales.Fields.ValidUntil"], r => r.ValidUntil) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment == "preventivi" },
new("delivery", T["Sales.Fields.DeliveryDate"], r => r.DeliveryDate) { Kind = KhColumnKind.Date, Width = "100px", Visible = _section?.Segment is "ordini" or "ddt" },
new("taxable", T["Sales.Totals.Taxable"], r => r.Taxable) { Kind = KhColumnKind.Money, Width = "120px" },
new("total", T["Sales.Totals.Total"], r => r.Total) { Kind = KhColumnKind.Money, Width = "120px" },
new("status", T["Sales.Radar.State"], r => StateOf(r).Text)
{
Width = "130px",
Template = r => @<KhBadge Tone="StateOf(r).Tone">@StateOf(r).Text</KhBadge>,
},
];
private IReadOnlyList<KhQuickFilter> QuickFilters
{
get
{
var filters = new List<KhQuickFilter>
{
new("status", T["Sales.Radar.State"], [new(string.Empty, T["Sales.Radar.All"]), .. States.Select(s => new KhOption<string>(s.ToString(), T["Sales.States." + s]))]),
};
if (_section is { Kinds.Count: > 1 })
{
filters.Add(new("kind", T["Sales.Radar.Kind"], [new(string.Empty, T["Sales.Radar.All"]), .. _section.Kinds.Select(k => new KhOption<string>(k.ToString(), SalesScreens.KindName(T, k)))]));
}
var year = Today.Year;
filters.Add(new("year", T["Sales.Radar.Year"],
[new(string.Empty, T["Sales.Radar.All"]), .. Enumerable.Range(0, 3).Select(i => new KhOption<string>((year - i).ToString(T.Culture), (year - i).ToString(T.Culture)))]));
return filters;
}
}
// The states that make sense for the life cycle of the radar.
private IEnumerable<DocumentStatus> States => _section is null ? [] :
DocumentBehaviors.Of(_section.Kinds[0]).Lifecycle == DocumentLifecycle.Invoice && _section.Kinds.All(k => DocumentBehaviors.Of(k).Lifecycle == DocumentLifecycle.Invoice)
? [DocumentStatus.Draft, DocumentStatus.Issued, DocumentStatus.Cancelled]
: [DocumentStatus.Draft, DocumentStatus.Confirmed, DocumentStatus.PartiallyFulfilled, DocumentStatus.Fulfilled, DocumentStatus.Closed, DocumentStatus.Cancelled, DocumentStatus.Issued];
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
_section = SalesScreens.Find(Segment);
if (!_loaded && Session.Actor is { } actor && Session.Company?.Code is { } company)
{
_definitions = await Engine.DefinitionsAsync(actor, company);
}
_loaded = true;
}
private (string Text, KhTone Tone) StateOf(DocumentRow row) => SalesScreens.State(T, row.Kind, row.Status, row.ValidUntil, Today);
private static string? RowClassOf(DocumentRow row) => row.Status == DocumentStatus.Cancelled ? "muted" : null;
private Task<ListPage<DocumentRow>> ListAsync(ListQuery query, CancellationToken cancellationToken) =>
Session.Actor is { } actor && Session.Company?.Code is { } company && _section is not null
? Editor.ListAsync(actor, company, _section.Family, _section.Kinds, query, cancellationToken)
: Task.FromResult(new ListPage<DocumentRow>([], 0, new Dictionary<string, decimal>()));
private void Open(DocumentRow row)
{
if (SalesScreens.RecordUrl(row.Kind, row.Id) is { } url)
{
Navigation.NavigateTo(url);
}
}
private void New()
{
if (NewTypes.Count == 1)
{
Create(NewTypes[0].Code);
}
else
{
_choosing = true;
}
}
private void Create(string code)
{
_choosing = false;
if (_section is not null)
{
Navigation.NavigateTo(SalesScreens.NewUrl(_section, code));
}
}
}
@@ -0,0 +1,252 @@
@page "/vendite/{Segment}/{Id:long}/stampa"
@attribute [Authorize]
@using Khaemhat.Application.Documents
@using Khaemhat.Application.Security
@using Khaemhat.Web.Documents
@using Khaemhat.Web.Hosting
@inject ShellSession Session
@inject DocumentPrintService Prints
@inject DocumentEngine Engine
@inject FileGenerationService Generation
@inject ToastService Toasts
@* The print preview of a sales document (SPEC §9.4, issue #52, mockup 025): the A4 sheet in HTML from the same model
as the PDF, with Stampa (the print of the browser), the PDF made by Khaemhat and "Salva come allegato", which keeps
the PDF among the attachments of the document as a new version. *@
<KhPageTitle Text="@Heading" Icon="printer" />
@if (_model is null)
{
<div class="kh-message">
<KhIcon Name="@(_missing ? "alert" : "printer")" Class="lg" />
<h1>@(_missing ? T["Sales.NotFound"] : T["Common.Loading"])</h1>
</div>
}
else
{
<div class="phead">
<div>
<div class="crumbs"><a href="@BackUrl">@_model.Title @_model.Number</a> › <b>@T["Sales.Print.Title"]</b></div>
<h1>@Heading</h1>
</div>
</div>
<KhPrintPreview PdfUrl="@PdfUrl(false)" PdfDownloadUrl="@PdfUrl(true)" OnSaveAttachment="SaveAsync" Saving="_saving">
<div class="kh-sheet-head">
<div class="kh-print-company">
@if (_model.LogoAttachmentId is { } logo)
{
<img class="kh-print-logo" src="@FileEndpoints.View(logo)" alt="" />
}
<div>
<div class="kh-sheet-company">@_model.Company.Name</div>
@foreach (var line in _model.Company.Lines)
{
<div class="kh-sheet-muted">@line</div>
}
</div>
</div>
<div class="kh-sheet-title">
<div class="k">@_model.Title</div>
<div class="kh-print-number">@_model.Number</div>
<div class="n">@_model.Date</div>
@if (_model.Watermark is { } mark)
{
<div class="kh-print-mark">@mark</div>
}
</div>
</div>
<div class="kh-print-top">
<dl class="kh-print-fields">
@foreach (var field in _model.Fields)
{
<dt>@field.Label</dt>
<dd>@field.Value</dd>
}
</dl>
<div class="kh-print-party">
<div class="kh-sheet-muted">@_model.PartyLabel <span class="mono">@_model.Party.Code</span></div>
<b>@_model.Party.Name</b>
@foreach (var line in _model.Party.Lines)
{
<div>@line</div>
}
</div>
</div>
<table class="kh-sheet-table">
<thead>
<tr>
@for (var i = 0; i < _model.LineHeaders.Count; i++)
{
<th class="@(i >= 3 ? "num" : null)">@_model.LineHeaders[i]</th>
}
</tr>
</thead>
<tbody>
@foreach (var line in _model.Lines)
{
if (line.IsDescription)
{
<tr class="kh-print-text"><td></td><td colspan="7">@line.Description</td></tr>
}
else
{
<tr>
<td class="mono">@line.Code</td>
<td>@line.Description</td>
<td>@line.Unit</td>
<td class="num">@line.Quantity</td>
<td class="num">@line.Price</td>
<td class="num">@line.Discount</td>
<td class="num">@line.Tax</td>
<td class="num">@line.Amount</td>
</tr>
}
}
</tbody>
</table>
@foreach (var note in _model.Notes)
{
<p class="kh-print-note">@note</p>
}
<div class="kh-print-sums">
<div>
@if (_model.Summary is { } summary)
{
@Table(summary)
}
@if (_model.Installments is { } installments)
{
@Table(installments)
}
</div>
<div class="kh-print-totals">
@foreach (var row in _model.Totals)
{
<span class="@(row.Strong ? "big" : null)">@row.Label</span>
<span class="@(row.Strong ? "big num" : "num")">@row.Value</span>
}
</div>
</div>
@if (_model.Transport.Count > 0)
{
<dl class="kh-print-transport">
@foreach (var field in _model.Transport)
{
<div><dt>@field.Label</dt><dd>@field.Value</dd></div>
}
</dl>
<div class="kh-print-signatures">
@foreach (var signature in _model.Signatures)
{
<div>@signature</div>
}
</div>
}
@if (_model.Footer is { } footer)
{
<p class="kh-sheet-foot">@footer</p>
}
</KhPrintPreview>
}
@code {
private SalesSection? _section;
private DocumentPrintModel? _model;
private bool _missing;
private bool _saving;
/// <summary>The radar segment, such as <c>fatture</c>.</summary>
[Parameter]
public string? Segment { get; set; }
/// <summary>The document.</summary>
[Parameter]
public long Id { get; set; }
private string Heading => _model is null ? T["Sales.Print.Title"] : T.Format("Sales.Print.Heading", _model.Title, _model.Number);
private string BackUrl => _section is null ? SalesScreens.BasePath : SalesScreens.BasePath + "/" + _section.Segment + "/" + Id.ToString(T.Culture);
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await Session.EnsureLoadedAsync();
_section = SalesScreens.Find(Segment);
if (_section is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
_missing = true;
return;
}
try
{
_model = await Prints.BuildAsync(actor, company, _section.Family, Id);
}
catch (Exception ex) when (ex is KeyNotFoundException or AccessDeniedException)
{
_missing = true;
}
}
private string? PdfUrl(bool download) =>
_section is null ? null : FileEndpoints.Generated(DocumentPrintService.EntityOf(_section.Family), Id, DocumentPdfGenerator.GeneratorCode, download);
private async Task SaveAsync()
{
if (_section is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company)
{
return;
}
_saving = true;
try
{
var saved = await Generation.GenerateAsync(actor, company, DocumentPrintService.EntityOf(_section.Family), Id, DocumentPdfGenerator.GeneratorCode);
await Engine.MarkPrintedAsync(actor, company, _section.Family, Id);
Toasts.Show(ToastKind.Success, T["Ui.Attachments.GeneratedToast"], saved.FileName);
}
catch (Exception ex) when (ex is AccessDeniedException or ValidationFailedException or KeyNotFoundException)
{
Toasts.Show(ToastKind.Error, T["Ui.Print.SaveAttachment"], T["Ui.Attachments.Denied"]);
}
finally
{
_saving = false;
}
}
private static RenderFragment Table(PrintTable table) => __builder =>
{
<div class="kh-print-block">
<div class="kh-print-block-title">@table.Title</div>
<table class="kh-sheet-table">
<thead>
<tr>
@for (var i = 0; i < table.Headers.Count; i++)
{
<th class="@(table.Numeric[i] ? "num" : null)">@table.Headers[i]</th>
}
</tr>
</thead>
<tbody>
@foreach (var row in table.Rows)
{
<tr>
@for (var i = 0; i < row.Count; i++)
{
<td class="@(table.Numeric[i] ? "num" : null)">@row[i]</td>
}
</tr>
}
</tbody>
</table>
</div>
};
}
@@ -0,0 +1,120 @@
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Tables;
using Khaemhat.Web.Tables;
using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Documents;
/// <summary>
/// The choices of the document screens, read once per page from the company tables: conditions, transport, the VAT
/// codes and units of the lines. Values are ids, except the currencies (by code); texts are <c>code · description</c>.
/// </summary>
public sealed class DocumentLookups
{
/// <summary>No choices, before loading.</summary>
public static DocumentLookups Empty { get; } = new();
/// <summary>Payment terms.</summary>
public IReadOnlyList<KhOption<string>> PaymentTerms { get; private init; } = [];
/// <summary>Payment methods.</summary>
public IReadOnlyList<KhOption<string>> PaymentMethods { get; private init; } = [];
/// <summary>Price lists.</summary>
public IReadOnlyList<KhOption<string>> PriceLists { get; private init; } = [];
/// <summary>Salespeople.</summary>
public IReadOnlyList<KhOption<string>> Salespeople { get; private init; } = [];
/// <summary>The company bank accounts.</summary>
public IReadOnlyList<KhOption<string>> BankAccounts { get; private init; } = [];
/// <summary>Warehouses.</summary>
public IReadOnlyList<KhOption<string>> Warehouses { get; private init; } = [];
/// <summary>Carriers.</summary>
public IReadOnlyList<KhOption<string>> Carriers { get; private init; } = [];
/// <summary>Shipping terms (porto).</summary>
public IReadOnlyList<KhOption<string>> ShippingTerms { get; private init; } = [];
/// <summary>Reasons of transport.</summary>
public IReadOnlyList<KhOption<string>> TransportReasons { get; private init; } = [];
/// <summary>Appearances of the goods.</summary>
public IReadOnlyList<KhOption<string>> GoodsAppearances { get; private init; } = [];
/// <summary>VAT codes.</summary>
public IReadOnlyList<KhOption<string>> TaxCodes { get; private init; } = [];
/// <summary>Units of measure.</summary>
public IReadOnlyList<KhOption<string>> Units { get; private init; } = [];
/// <summary>Currencies, by code.</summary>
public IReadOnlyList<KhOption<string>> Currencies { get; private init; } = [];
/// <summary>Reads the choices.</summary>
/// <param name="tables">The tables.</param>
/// <param name="actor">Who reads.</param>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The choices.</returns>
public static async Task<DocumentLookups> ReadAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new()
{
PaymentTerms = await ReadAsync<PaymentTerm>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
PaymentMethods = await ReadAsync<PaymentMethod>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
PriceLists = await ReadAsync<PriceList>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Salespeople = await ReadAsync<Salesperson>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
BankAccounts = await ReadAsync<BankAccount>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Warehouses = await ReadAsync<Warehouse>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Carriers = await ReadAsync<Carrier>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
ShippingTerms = await ReadAsync<ShippingTerm>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
TransportReasons = await ReadAsync<TransportReason>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
GoodsAppearances = await ReadAsync<GoodsAppearance>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
TaxCodes = await ReadAsync<TaxCode>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Units = await ReadAsync<UnitOfMeasure>(tables, actor, company, false, cancellationToken).ConfigureAwait(false),
Currencies = await ReadAsync<Currency>(tables, actor, company, true, cancellationToken).ConfigureAwait(false),
};
/// <summary>The code of a choice (the part before <c> · </c>).</summary>
/// <param name="options">The choices.</param>
/// <param name="id">The id.</param>
/// <returns>The code, or <see langword="null"/>.</returns>
public static string? CodeOf(IReadOnlyList<KhOption<string>> options, long? id)
{
ArgumentNullException.ThrowIfNull(options);
if (id is null)
{
return null;
}
var value = id.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
var text = options.FirstOrDefault(o => o.Value == value)?.Text;
return text is null ? null : text.Split(" · ", 2)[0];
}
/// <summary>The id of the choice with a code, ignoring case.</summary>
/// <param name="options">The choices.</param>
/// <param name="code">The code typed.</param>
/// <returns>The id, or <see langword="null"/>.</returns>
public static long? IdOf(IReadOnlyList<KhOption<string>> options, string? code)
{
ArgumentNullException.ThrowIfNull(options);
if (string.IsNullOrWhiteSpace(code))
{
return null;
}
var wanted = code.Trim();
var match = options.FirstOrDefault(o => string.Equals(o.Text.Split(" · ", 2)[0], wanted, StringComparison.OrdinalIgnoreCase));
return match is null ? null : long.Parse(match.Value, System.Globalization.CultureInfo.InvariantCulture);
}
private static async Task<IReadOnlyList<KhOption<string>>> ReadAsync<T>(TableService tables, Actor actor, string company, bool byCode,
CancellationToken cancellationToken)
{
var choices = await TableValues.LookupAsync(tables, typeof(T), byCode, actor, company, cancellationToken).ConfigureAwait(false);
return [.. choices.Select(c => new KhOption<string>(c.Value, c.Text))];
}
}
+144
View File
@@ -0,0 +1,144 @@
using System.Globalization;
using Khaemhat.Application.Localization;
using Khaemhat.Core.Documents;
using Khaemhat.Web.Ui;
namespace Khaemhat.Web.Documents;
/// <summary>A radar of the sales menu and the document types it holds.</summary>
/// <param name="Segment">The path segment, such as <c>fatture</c>.</param>
/// <param name="Family">The family of the documents.</param>
/// <param name="Kinds">The kinds shown.</param>
/// <param name="NewTypes">The document types a user can create from the radar, the first being the usual one.</param>
/// <param name="Icon">The icon.</param>
/// <param name="Key">The key of the texts under <c>Sales.Sections</c>.</param>
public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList<DocumentKind> Kinds, IReadOnlyList<string> NewTypes, string Icon, string Key);
/// <summary>
/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under
/// <c>/vendite</c>, the record of a document under it, and the deferred invoicing.
/// </summary>
public static class SalesScreens
{
/// <summary>The menu area.</summary>
public const string BasePath = "vendite";
/// <summary>The deferred invoicing of the delivery notes.</summary>
public const string DeferredInvoicingUrl = BasePath + "/fatturazione-differita";
/// <summary>The tab of the transport data, after Testata, for delivery notes and accompanying invoices.</summary>
public const string TransportTab = "trasporto";
/// <summary>The radars, in the order of the menu.</summary>
public static IReadOnlyList<SalesSection> Sections { get; } =
[
new("preventivi", DocumentFamily.SaleQuotation, [DocumentKind.Quotation], ["PRE"], "file", "Quotes"),
new("ordini", DocumentFamily.SaleOrder, [DocumentKind.SalesOrder], ["OC"], "file-check", "Orders"),
new("ddt", DocumentFamily.SaleDocument, [DocumentKind.DeliveryNote], ["DDT"], "truck", "DeliveryNotes"),
new("fatture", DocumentFamily.SaleDocument,
[DocumentKind.ImmediateInvoice, DocumentKind.AccompanyingInvoice, DocumentKind.DeferredInvoice, DocumentKind.DownPaymentInvoice, DocumentKind.Fee, DocumentKind.ProForma],
["FI", "FA", "FD", "FACC", "PAR", "PF"], "euro", "Invoices"),
new("note-credito", DocumentFamily.SaleDocument, [DocumentKind.CreditNote, DocumentKind.DebitNote], ["NC", "ND"], "undo", "CreditNotes"),
];
/// <summary>The radar of a path segment.</summary>
/// <param name="segment">The segment.</param>
/// <returns>The radar, or <see langword="null"/>.</returns>
public static SalesSection? Find(string? segment) => Sections.FirstOrDefault(s => string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase));
/// <summary>The radar that holds a kind of document.</summary>
/// <param name="kind">The kind.</param>
/// <returns>The radar, or <see langword="null"/> for a kind outside sales.</returns>
public static SalesSection? Of(DocumentKind kind) => Sections.FirstOrDefault(s => s.Kinds.Contains(kind));
/// <summary>The address of a radar.</summary>
/// <param name="section">The radar.</param>
/// <returns>The address.</returns>
public static string RadarUrl(SalesSection section)
{
ArgumentNullException.ThrowIfNull(section);
return BasePath + "/" + section.Segment;
}
/// <summary>The address of a document.</summary>
/// <param name="kind">The kind.</param>
/// <param name="id">The document.</param>
/// <returns>The address, or <see langword="null"/> for a kind outside sales.</returns>
public static string? RecordUrl(DocumentKind kind, long id) =>
Of(kind) is { } section ? RadarUrl(section) + "/" + id.ToString(CultureInfo.InvariantCulture) : null;
/// <summary>The address of a new document of a type.</summary>
/// <param name="section">The radar.</param>
/// <param name="typeCode">The document type.</param>
/// <returns>The address.</returns>
public static string NewUrl(SalesSection section, string typeCode) => RadarUrl(section) + "/nuovo?tipo=" + Uri.EscapeDataString(typeCode);
/// <summary>The print preview of a document.</summary>
/// <param name="section">The radar.</param>
/// <param name="id">The document.</param>
/// <returns>The relative URL.</returns>
public static string PrintUrl(SalesSection section, long id)
{
ArgumentNullException.ThrowIfNull(section);
return RadarUrl(section) + "/" + id.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/stampa";
}
/// <summary>The name of a kind, such as <c>Fattura immediata</c>.</summary>
/// <param name="texts">The texts.</param>
/// <param name="kind">The kind.</param>
/// <returns>The name.</returns>
public static string KindName(ITexts texts, DocumentKind kind)
{
ArgumentNullException.ThrowIfNull(texts);
return texts["Sales.Kinds." + kind];
}
/// <summary>The label and tone of a state; a quotation shows its outcome (accepted, refused, expired).</summary>
/// <param name="texts">The texts.</param>
/// <param name="kind">The kind.</param>
/// <param name="status">The state.</param>
/// <param name="validUntil">Until when a quotation is valid.</param>
/// <param name="today">Today.</param>
/// <returns>The label and the tone.</returns>
public static (string Text, KhTone Tone) State(ITexts texts, DocumentKind kind, DocumentStatus status, DateOnly? validUntil, DateOnly today)
{
ArgumentNullException.ThrowIfNull(texts);
if (kind == DocumentKind.Quotation)
{
switch (status)
{
case DocumentStatus.Fulfilled or DocumentStatus.PartiallyFulfilled:
return (texts["Sales.Outcomes.Accepted"], KhTone.Ok);
case DocumentStatus.Closed:
return (texts["Sales.Outcomes.Refused"], KhTone.Error);
case DocumentStatus.Confirmed when validUntil is { } until && until < today:
return (texts["Sales.Outcomes.Expired"], KhTone.Warning);
case DocumentStatus.Confirmed:
return (texts["Sales.Outcomes.Sent"], KhTone.Info);
}
}
var tone = status switch
{
DocumentStatus.Draft => KhTone.Neutral,
DocumentStatus.Confirmed or DocumentStatus.Issued => KhTone.Info,
DocumentStatus.PartiallyFulfilled => KhTone.Warning,
DocumentStatus.Fulfilled or DocumentStatus.SdiDelivered => KhTone.Ok,
DocumentStatus.Cancelled or DocumentStatus.SdiRejected or DocumentStatus.SdiNotDelivered => KhTone.Error,
_ => KhTone.Accent,
};
return (texts["Sales.States." + status], tone);
}
/// <summary>The choices of an enumeration, labelled from <c>Sales.{group}.{value}</c>.</summary>
/// <typeparam name="TEnum">The enumeration.</typeparam>
/// <param name="texts">The texts.</param>
/// <param name="group">The group of texts.</param>
/// <returns>The choices.</returns>
public static IReadOnlyList<KhOption<string>> Choices<TEnum>(ITexts texts, string group)
where TEnum : struct, Enum
{
ArgumentNullException.ThrowIfNull(texts);
return [.. Enum.GetValues<TEnum>().Select(v => new KhOption<string>(v.ToString(), texts["Sales." + group + "." + v]))];
}
}
@@ -176,6 +176,8 @@ internal static class KhaemhatServices
// Companies and start.
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<SeedRunner>());
services.AddSingleton<DemoSalesSeeder>();
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoSalesSeeder>());
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
@@ -226,6 +228,23 @@ internal static class KhaemhatServices
services.AddSingleton<IFileScanner, NoOpFileScanner>();
services.AddSingleton<IFileStore, VolumeFileStore>();
services.AddSingleton<AttachmentService>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentPrintService>();
services.AddSingleton<IFileGenerator, Khaemhat.Application.Documents.DocumentPdfGenerator>();
// Mail (#52): the SMTP client written in house, the queue that sends in the background, documents by e-mail.
services.AddSingleton(new Khaemhat.Infrastructure.Mail.SmtpSettings(
options.SmtpHost, options.SmtpPortNumber, options.SmtpUser, options.SmtpPassword, options.SmtpFrom,
options.SmtpSecurityMode switch
{
SmtpSecurity.Ssl => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.Ssl,
SmtpSecurity.None => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.None,
_ => Khaemhat.Infrastructure.Mail.SmtpTransportSecurity.StartTls,
}));
services.AddSingleton<Khaemhat.Infrastructure.Mail.IMailSender, Khaemhat.Infrastructure.Mail.SmtpMailSender>();
services.AddSingleton<Khaemhat.Infrastructure.Mail.MailQueue>();
services.AddSingleton<Khaemhat.Infrastructure.Mail.IMailQueue>(sp => sp.GetRequiredService<Khaemhat.Infrastructure.Mail.MailQueue>());
services.AddHostedService(sp => sp.GetRequiredService<Khaemhat.Infrastructure.Mail.MailQueue>());
services.AddSingleton<Khaemhat.Application.Documents.DocumentMailService>();
services.AddSingleton<IFileGenerator, DemoPdfGenerator>();
services.AddSingleton<IFileGenerator, DemoCsvGenerator>();
services.AddSingleton<IFileGenerator, DemoXlsxGenerator>();
+3
View File
@@ -129,6 +129,9 @@ public static class SeedCommand
{
Print(code, "dati dimostrativi, scala " + options.Scale.ToString(CultureInfo.InvariantCulture),
await runner.RunAsync(code, SeedKind.Demo, options.Scale).ConfigureAwait(false));
// The demo documents go through the document engine, after the masters they use.
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
}
}
@@ -14,6 +14,12 @@
"party": {
"required": "Indica il cliente o il fornitore."
},
"mail": {
"not-configured": "L'invio delle e-mail non è configurato: chiedi all'amministratore di impostare il server SMTP (KHAEMHAT_SMTP_HOST e KHAEMHAT_SMTP_FROM).",
"recipient-invalid": "Indica uno o più indirizzi e-mail validi, separati da virgola.",
"subject-required": "Scrivi l'oggetto del messaggio.",
"queue-full": "Troppi messaggi in attesa di invio: riprova tra qualche minuto."
},
"date": {
"required": "Indica la data del documento.",
"numbered": "La data di un documento numerato non si può cambiare."
@@ -28,7 +34,8 @@
"below-fulfilled": "La quantità non può scendere sotto quella già evasa.",
"fulfilled-removed": "Una riga già evasa da altri documenti non si può togliere.",
"source-invalid": "La riga d'origine non esiste o non può essere evasa da questo documento.",
"discount-invalid": "Lo sconto si scrive come percentuali separate da +, ad esempio 10+5."
"discount-invalid": "Lo sconto si scrive come percentuali separate da +, ad esempio 10+5.",
"tax-required": "Indica il codice IVA della riga: serve per i registri IVA e la fattura elettronica."
},
"cancel": {
"reason-required": "Per annullare una fattura indica il motivo.",
@@ -11,6 +11,7 @@
},
"files": {
"generators": {
"document_pdf": "Stampa del documento in PDF",
"demo_pdf": "Documento di prova in PDF",
"demo_csv": "Righe in CSV (per Excel)",
"demo_xlsx": "Righe in Excel (XLSX)"
@@ -101,6 +101,9 @@
"Attachments": "Allegati",
"Birth": "Dati di nascita"
},
"Hints": {
"ExcludedMonths": "Le scadenze che cadono in un mese escluso passano a questo giorno del mese successivo (10 se vuoto)."
},
"Fields": {
"Code": "Codice",
"PreviousCode": "Codice precedente",
@@ -148,6 +151,9 @@
"WarehouseId": "Deposito",
"CreditLimit": "Fido",
"Blocked": "Ordini bloccati",
"ExcludedMonth1": "Primo mese escluso",
"ExcludedMonth2": "Secondo mese escluso",
"ExcludedMonthsDay": "Scadenza spostata al giorno",
"GroupDeliveryNotes": "Raggruppa i DDT in fattura",
"InvoiceDay": "Giorno di fatturazione",
"SendDocuments": "Invio dei documenti",
@@ -0,0 +1,93 @@
{
"Print": {
"Draft": "Bozza",
"Of": "del {0}",
"Customer": "Spett.le",
"Supplier": "Fornitore",
"NoParty": "Intestatario da indicare",
"VatNumber": "P. IVA {0}",
"TaxCode": "C.F. {0}",
"Rea": "REA {0} {1}",
"ShareCapital": "Cap. soc. {0} i.v.",
"Phone": "Tel. {0}",
"Pec": "PEC {0}",
"Watermarks": {
"Draft": "Bozza, non valida",
"Cancelled": "Annullato",
"Demo": "Dato dimostrativo"
},
"Fields": {
"Payment": "Pagamento",
"Bank": "Banca d'appoggio",
"Reference": "Vs. riferimento",
"ValidUntil": "Valido fino al",
"Delivery": "Consegna prevista",
"Salesperson": "Agente",
"Revision": "Revisione",
"Cig": "CIG",
"Cup": "CUP",
"Related": "Documento collegato"
},
"Lines": {
"Code": "Codice",
"Description": "Descrizione",
"Unit": "UM",
"Quantity": "Quantità",
"Price": "Prezzo",
"Discount": "Sconti",
"Tax": "IVA",
"Amount": "Importo"
},
"Summary": {
"Title": "Riepilogo IVA",
"Code": "Codice IVA",
"Rate": "Aliquota",
"Taxable": "Imponibile",
"Tax": "Imposta"
},
"Installments": {
"Title": "Scadenze",
"Number": "N.",
"Due": "Scadenza",
"Method": "Modalità",
"Amount": "Importo"
},
"Totals": {
"Goods": "Totale merce",
"FooterDiscount": "Sconto di piede",
"Expenses": "Spese",
"SocialSecurity": "Cassa previdenza",
"Taxable": "Imponibile",
"Tax": "IVA",
"StampDuty": "Bollo",
"Total": "Totale documento",
"Withholding": "Ritenuta d'acconto",
"Enasarco": "Enasarco",
"SplitPayment": "IVA in scissione dei pagamenti",
"Net": "Netto a pagare"
},
"Transport": {
"Reason": "Causale del trasporto",
"By": "Trasporto a cura del",
"Carrier": "Vettore",
"Port": "Porto",
"Appearance": "Aspetto dei beni",
"Packages": "Colli",
"GrossWeight": "Peso lordo (kg)",
"NetWeight": "Peso netto (kg)",
"Start": "Inizio trasporto",
"SignatureDriver": "Firma del conducente",
"SignatureCarrier": "Firma del vettore",
"SignatureRecipient": "Firma del destinatario"
},
"Mail": {
"Subject": "{{Documento}} n. {{Numero}} del {{Data}} · {{Azienda}}",
"Body": "Gentile {{Cliente}},\n\nin allegato trovate il documento {{Documento}} n. {{Numero}} del {{Data}}, per un totale di {{Totale}}.\n\nRestiamo a disposizione per qualsiasi chiarimento.\n\nCordiali saluti,\n{{Azienda}}"
},
"Notes": {
"SplitPayment": "Operazione con scissione dei pagamenti (art. 17-ter del DPR 633/1972): l'IVA è versata dal cliente all'Erario.",
"ProForma": "Documento pro forma, privo di valore fiscale: la fattura sarà emessa al pagamento.",
"Deferred": "Fattura differita (art. 21, comma 4, del DPR 633/1972) relativa ai documenti di trasporto indicati."
}
}
}
+309
View File
@@ -0,0 +1,309 @@
{
"Sales": {
"NoCompany": "Scegli un'azienda per vedere i documenti di vendita.",
"NotFound": "Documento non trovato",
"BackToList": "Torna all'elenco",
"DraftNumber": "Bozza",
"NumberOnConfirm": "Assegnato alla conferma",
"NoParty": "Cliente da scegliere",
"Demo": "Dato dimostrativo",
"NewDocument": "Nuovo documento",
"Sections": {
"Quotes": { "Title": "Preventivi", "New": "Nuovo preventivo" },
"Orders": { "Title": "Ordini clienti", "New": "Nuovo ordine" },
"DeliveryNotes": { "Title": "Documenti di trasporto", "New": "Nuovo DDT" },
"Invoices": { "Title": "Fatture di vendita", "New": "Nuova fattura" },
"CreditNotes": { "Title": "Note di credito e di debito", "New": "Nuova nota" }
},
"Kinds": {
"Quotation": "Preventivo",
"SalesOrder": "Ordine cliente",
"DeliveryNote": "DDT",
"ImmediateInvoice": "Fattura immediata",
"AccompanyingInvoice": "Fattura accompagnatoria",
"DeferredInvoice": "Fattura differita",
"DownPaymentInvoice": "Fattura di acconto",
"CreditNote": "Nota di credito",
"DebitNote": "Nota di debito",
"Fee": "Parcella",
"ProForma": "Pro forma",
"SelfInvoice": "Autofattura",
"PurchaseOrder": "Ordine fornitore",
"PurchaseDeliveryNote": "DDT fornitore",
"PurchaseInvoice": "Fattura fornitore",
"PurchaseCreditNote": "Nota di credito fornitore",
"InventoryEntry": "Movimento di magazzino"
},
"States": {
"Draft": "Bozza",
"Confirmed": "Confermato",
"PartiallyFulfilled": "Evaso in parte",
"Fulfilled": "Evaso",
"Closed": "Chiuso",
"Cancelled": "Annullato",
"Issued": "Emessa",
"SdiGenerated": "XML generato",
"SdiSent": "Inviata allo SdI",
"SdiDelivered": "Consegnata",
"SdiRejected": "Scartata",
"SdiNotDelivered": "Non consegnata"
},
"Outcomes": {
"Sent": "In attesa di risposta",
"Accepted": "Accettato",
"Refused": "Rifiutato",
"Expired": "Scaduto"
},
"LineKinds": {
"Item": "Articolo",
"Free": "Riga libera",
"Description": "Descrizione",
"Expense": "Spese",
"Discount": "Sconto"
},
"Exigibilities": {
"Immediate": "Immediata (I)",
"Deferred": "Differita, IVA per cassa (D)",
"SplitPayment": "Scissione dei pagamenti (S)"
},
"TransportBy": {
"Sender": "Mittente",
"Recipient": "Destinatario",
"Carrier": "Vettore"
},
"Tabs": {
"Transport": "Trasporto"
},
"Head": {
"Vat": "P. IVA",
"TaxCode": "C.F."
},
"Radar": {
"Search": "Cerca per numero, riferimento o cliente",
"All": "Tutti",
"Kind": "Tipo",
"State": "Stato",
"Year": "Anno"
},
"Groups": {
"Document": "Documento",
"Party": "Cliente",
"Conditions": "Condizioni",
"Tax": "Dati fiscali",
"Withholding": "Ritenuta, cassa previdenza, ENASARCO",
"Transport": "Trasporto",
"Goods": "Merce",
"Notes": "Note",
"Cancelled": "Annullamento"
},
"Fields": {
"DocumentTypeId": "Tipo documento",
"DocumentNumber": "Numero",
"DocumentDate": "Data",
"ValidUntil": "Valido fino al",
"DeliveryDate": "Consegna",
"Revision": "Revisione",
"Related": "Rettifica",
"ExternalReference": "Riferimento cliente",
"ExternalDate": "Data riferimento",
"RelatedNumber": "Fattura rettificata",
"RelatedDate": "Data fattura rettificata",
"PartyId": "Cliente",
"SalespersonId": "Agente",
"CurrencyCode": "Valuta",
"PriceListId": "Listino",
"FooterDiscount": "Sconto di piede",
"PricesIncludeTax": "Prezzi IVA compresa",
"PaymentTermId": "Pagamento",
"PaymentMethodId": "Modalità di pagamento",
"BankAccountId": "Banca d'appoggio",
"Exigibility": "Esigibilità IVA",
"SplitPayment": "Split payment",
"StampDutyCharged": "Bollo addebitato al cliente",
"Cig": "CIG",
"Cup": "CUP",
"WithholdingRate": "Ritenuta %",
"WithholdingBasePercent": "Base ritenuta %",
"WithholdingType": "Tipo ritenuta",
"WithholdingReason": "Causale pagamento",
"SocialSecurityFund": "Cassa previdenza",
"SocialSecurityRate": "Cassa %",
"SocialSecurityTaxCodeId": "IVA sulla cassa",
"SocialSecurityWithheld": "Cassa soggetta a ritenuta",
"EnasarcoRate": "ENASARCO %",
"TransportReasonId": "Causale del trasporto",
"TransportBy": "Trasporto a cura del",
"CarrierId": "Vettore",
"ShippingTermId": "Porto",
"TransportStartDate": "Inizio trasporto",
"TransportStartTime": "Ora",
"WarehouseId": "Magazzino",
"GoodsAppearanceId": "Aspetto dei beni",
"Packages": "Colli",
"GrossWeight": "Peso lordo (kg)",
"NetWeight": "Peso netto (kg)",
"Notes": "Note",
"CancelReason": "Motivo dell'annullamento",
"TaxableAmount": "Imponibile",
"TaxAmount": "IVA",
"TotalAmount": "Totale",
"Status": "Stato",
"Number": "Progressivo",
"Printed": "Stampato",
"Sent": "Inviato"
},
"Hints": {
"PartyFirst": "Scegli prima il cliente: il documento ne riprende listino, pagamento, agente, banca e dati fiscali.",
"PartyDefaults": "Cambiando cliente il documento riprende le sue condizioni; puoi poi modificarle qui.",
"ExternalReference": "Ad esempio il numero d'ordine del cliente.",
"Related": "La fattura che questa nota corregge, riportata nel file per lo SdI.",
"Withholding": "Ritenuta, cassa ed ENASARCO si calcolano sulle righe non escluse; si tolgono dal netto a pagare, non dal totale.",
"Transport": "Colli e pesi vanno nella stampa del DDT; il magazzino si muove con la conferma (M6).",
"Installments": "Le scadenze nascono dalla condizione di pagamento, sul netto a pagare. Lo scadenzario arriva con M8.",
"InstallmentsForecast": "Per preventivi, ordini e pro forma le scadenze sono una previsione: quelle vere nascono con la fattura.",
"Notes": "Le note compaiono nella stampa, sotto le righe.",
"Kinds": {
"Quotation": "Offerta al cliente, con validità e revisioni.",
"SalesOrder": "Impegno del cliente, evaso da DDT e fatture.",
"DeliveryNote": "Accompagna la merce; si fattura con la differita.",
"ImmediateInvoice": "TD01, emessa insieme alla cessione o prestazione.",
"AccompanyingInvoice": "TD01 che accompagna anche la merce, con i dati del trasporto.",
"DeferredInvoice": "TD24, raccoglie i DDT del mese.",
"DownPaymentInvoice": "TD02, per un acconto su un ordine.",
"CreditNote": "TD04, storna in tutto o in parte una fattura.",
"DebitNote": "TD05, aggiunge importi a una fattura.",
"Fee": "TD06, per i professionisti, con ritenuta e cassa.",
"ProForma": "Non fiscale: anticipa la fattura al cliente."
}
},
"Lines": {
"Title": "Righe documento",
"Item": "Articolo",
"Description": "Descrizione",
"Unit": "UM",
"Quantity": "Quantità",
"Price": "Prezzo",
"Discount": "Sconti",
"Tax": "IVA",
"Delivery": "Consegna",
"Fulfilled": "Evasa",
"Residual": "Da evadere",
"Amount": "Importo",
"ItemRadar": "Cerca articolo",
"ItemMissing": "L'articolo non esiste più.",
"ErrorAt": "Riga {0}: {1}"
},
"Totals": {
"Title": "Totali",
"Summary": "Castelletto IVA",
"SummaryEmpty": "Il castelletto si compone mentre scrivi le righe.",
"Installments": "Scadenze",
"InstallmentsEmpty": "Nessuna scadenza: il documento non ha importo da pagare.",
"InstallmentsNoTerm": "Scegli la condizione di pagamento per vedere le scadenze.",
"TaxCode": "Codice IVA",
"Rate": "Aliquota",
"Taxable": "Imponibile",
"Tax": "IVA",
"Total": "Totale documento",
"Net": "Netto a pagare",
"Goods": "Totale merce",
"FooterDiscount": "Sconto di piede",
"Expenses": "Spese",
"SocialSecurity": "Cassa previdenza",
"StampDuty": "Bollo (a carico dell'azienda)",
"StampDutyCharged": "Bollo",
"Withholding": "Ritenuta d'acconto",
"Enasarco": "ENASARCO",
"SplitPayment": "IVA in split payment",
"DueDate": "Scadenza",
"Method": "Modalità",
"Amount": "Importo"
},
"Links": {
"Empty": "Nessun documento collegato.",
"Relation": "Relazione",
"Quantity": "Quantità evasa",
"Source": "Origine",
"Target": "Evaso da",
"Related": "Rettifica"
},
"Actions": {
"Confirm": "Conferma",
"Issue": "Emetti",
"Create": "Crea {0}",
"Duplicate": "Duplica",
"Close": "Chiudi",
"Refuse": "Segna come rifiutato",
"Reopen": "Riapri",
"Cancel": "Annulla documento",
"ChooseParty": "Scegli il cliente",
"AddExpense": "Aggiungi riga spese",
"AddDiscount": "Aggiungi riga sconto"
},
"Confirm": {
"IssueText": "La fattura riceve il numero definitivo e non si potrà più modificare: per correggerla servirà una nota di credito. Procedere?",
"Issued": "Fattura {0} emessa.",
"Confirmed": "Documento {0} confermato."
},
"Cancel": {
"Lead": "Il documento resta in archivio come annullato e non conta più nelle evasioni.",
"LeadInvoice": "Annullare una fattura emessa è un'eccezione (ad esempio mai inviata allo SdI): indica il motivo, che resta nello storico."
},
"Transform": {
"LeadFulfil": "Scegli le righe da evadere: il nuovo documento riprende la quantità ancora da evadere, che puoi ridurre prima di confermarlo.",
"LeadCopy": "Scegli le righe da copiare nel nuovo documento.",
"All": "Tutte le righe",
"Create": "Crea il documento",
"Created": "{0} creato in bozza."
},
"Mail": {
"Title": "Invia per e-mail",
"Lead": "Il PDF del documento viene salvato tra gli allegati come nuova versione e parte in allegato al messaggio.",
"To": "Destinatari",
"ToHint": "Più indirizzi separati da virgola.",
"Subject": "Oggetto",
"Body": "Messaggio",
"Send": "Invia",
"Queued": "Messaggio in coda di invio",
"QueuedDetail": "A {0}: l'esito è nel log, sezione E-mail/PEC."
},
"Print": {
"Title": "Anteprima di stampa",
"Heading": "Anteprima di stampa · {0} {1}"
},
"Deferred": {
"Title": "Fatturazione differita",
"Procedure": "Procedura",
"Steps": {
"Period": "Periodo e cliente",
"PeriodDetail": "I DDT confermati e non ancora fatturati.",
"Choose": "Scelta dei DDT",
"ChooseDetail": "Togli quelli da fatturare più avanti.",
"Generate": "Fatture",
"GenerateDetail": "Una fattura differita (TD24) per cliente o per DDT."
},
"From": "DDT dal",
"To": "DDT al",
"ToRequired": "Indica fino a quale data cercare i DDT.",
"Customer": "Cliente",
"AllCustomers": "Vuoto per i DDT di tutti i clienti.",
"InvoiceDate": "Data delle fatture",
"Grouping": "Raggruppamento",
"PerParty": "Una fattura per cliente",
"PerNote": "Una fattura per DDT",
"Issue": "Emetti subito le fatture (altrimenti restano in bozza)",
"Search": "Cerca i DDT",
"Notes": "DDT da fatturare nel periodo",
"Start": "Indica il periodo e premi Cerca i DDT.",
"None": "Nessun DDT da fatturare nel periodo.",
"Lines": "Righe",
"Invoice": "Fattura",
"InvoiceNumber": "Fattura {0} ({1} DDT)",
"Selected": "{0} DDT · {1}",
"Generate": "Genera fatture",
"Results": "Fatture generate",
"Done": "{0} fatture generate su {1}.",
"Again": "Nuova fatturazione"
}
}
}
+2 -1
View File
@@ -67,7 +67,8 @@
"Orders": "Ordini clienti",
"DeliveryNotes": "DDT",
"Invoices": "Fatture",
"CreditNotes": "Note di credito"
"CreditNotes": "Note di credito",
"DeferredInvoicing": "Fatturazione differita"
},
"Purchases": {
"_": "Acquisti",
+3 -3
View File
@@ -54,15 +54,15 @@ public static class MenuCatalog
]),
new("Shell.Menu.Section.Operations",
[
Area("Shell.Menu.Parties", "users", "/anagrafiche", ModuleCodes.Core, "parties.party.read", "M4",
Area("Shell.Menu.Parties", "users", "/anagrafiche", ModuleCodes.Core, "parties.party.read", null,
("Shell.Menu.Parties.Customers", "clienti"), ("Shell.Menu.Parties.Suppliers", "fornitori"), ("Shell.Menu.Parties.Contacts", "contatti"),
("Shell.Menu.Parties.Items", "articoli"), ("Shell.Menu.Parties.PriceLists", "listini"), ("Shell.Menu.Parties.Categories", "categorie")),
Area("Shell.Menu.Crm", "target", "/crm", ModuleCodes.Crm, "crm.lead.read", "M11",
("Shell.Menu.Crm.Dashboard", "cruscotto"), ("Shell.Menu.Crm.Leads", "lead"), ("Shell.Menu.Crm.Pipeline", "pipeline"),
("Shell.Menu.Crm.Agenda", "agenda"), ("Shell.Menu.Crm.Tickets", "ticket"), ("Shell.Menu.Crm.Campaigns", "campagne")),
Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", "M5",
Area("Shell.Menu.Sales", "cart", "/vendite", ModuleCodes.Core, "sales.invoice.read", null,
("Shell.Menu.Sales.Quotes", "preventivi"), ("Shell.Menu.Sales.Orders", "ordini"), ("Shell.Menu.Sales.DeliveryNotes", "ddt"),
("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito")),
("Shell.Menu.Sales.Invoices", "fatture"), ("Shell.Menu.Sales.CreditNotes", "note-credito"), ("Shell.Menu.Sales.DeferredInvoicing", "fatturazione-differita")),
Area("Shell.Menu.Purchases", "truck", "/acquisti", ModuleCodes.Core, "purchases.order.read", "M6",
("Shell.Menu.Purchases.Orders", "ordini"), ("Shell.Menu.Purchases.Receipts", "ricevimenti"), ("Shell.Menu.Purchases.Invoices", "fatture")),
Area("Shell.Menu.Inventory", "box", "/magazzino", ModuleCodes.Core, "inventory.stock.read", "M6",
+44
View File
@@ -356,3 +356,47 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
.grid tbody tr td.kh-import-cell-err { background: var(--kh-err-soft); }
.grid tbody tr td.kh-import-cell-warn { background: var(--kh-warn-soft); }
@media (max-width: 1100px) { .kh-import { grid-template-columns: 1fr; } }
/* Sales documents (SPEC §11.3, mockups 020-030): the panels under the lines, errors of the lines, the choice of a type. */
.kh-doc-panels { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1.2fr) minmax(0, 1fr); gap: var(--kh-gap); padding: 14px 16px; align-items: start; }
.kh-doc-panels.wide { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); }
.kh-doc-panels.single { grid-template-columns: minmax(0, 720px); }
.kh-doc-panels .grid.compact td, .kh-doc-panels .grid.compact th { padding: 5px 10px; }
.kh-doc-panels .totals span { white-space: nowrap; }
.kh-doc-panels .kh-total-row td { font-weight: 600; border-top: 1px solid var(--kh-border); }
.kh-doc-callout { margin: 12px 16px 0; align-items: center; }
.kh-doc-callout span { flex: 1; }
.kh-doc-errors { list-style: none; margin: 8px 16px 0; padding: 8px 12px; border-radius: var(--kh-radius-lg); background: var(--kh-err-soft); font-size: 12.5px; display: grid; gap: 4px; }
.kh-choice-list { display: grid; gap: 8px; }
.kh-choice { display: grid; grid-template-columns: 56px minmax(0, 1fr); grid-template-rows: auto auto; gap: 2px 10px; height: auto; padding: 10px 12px; text-align: left; justify-content: stretch; }
.kh-choice .code { grid-row: span 2; align-self: center; font: 600 12px var(--kh-mono); color: var(--kh-accent); }
.kh-choice .muted { font-weight: 400; }
@media (max-width: 1099px) { .kh-doc-panels, .kh-doc-panels.wide { grid-template-columns: 1fr; } }
/* Print preview of a document (issue #52, mockup 025): the same model as the PDF. */
.kh-print-company { display: flex; gap: 12px; align-items: flex-start; }
.kh-print-logo { max-height: 15mm; max-width: 45mm; object-fit: contain; }
.kh-print-number { font-size: 18pt; font-weight: 700; }
.kh-print-mark { margin-top: 4px; color: #b54708; font-weight: 700; text-transform: uppercase; font-size: 9pt; }
.kh-print-top { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 14px; font-size: 9.5pt; }
.kh-print-fields { display: grid; grid-template-columns: auto 1fr; gap: 3px 12px; margin: 0; align-content: start; }
.kh-print-fields dt { color: #6b7280; }
.kh-print-fields dd { margin: 0; }
.kh-print-party { border: 1px solid #d9dde3; border-radius: 4px; padding: 8px 10px; display: grid; gap: 2px; }
.kh-print-party b { font-size: 11pt; }
.kh-print-text td { color: #6b7280; font-style: italic; }
.kh-print-note { font-size: 9pt; margin: 10px 0 0; }
.kh-print-sums { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); gap: 16px; margin-top: 14px; align-items: start; }
.kh-print-block + .kh-print-block { margin-top: 12px; }
.kh-print-block-title { font-weight: 700; color: #1F5F8B; font-size: 9.5pt; margin-bottom: 4px; }
.kh-print-totals { display: grid; grid-template-columns: 1fr auto; gap: 4px 12px; background: #eceff3; padding: 10px 12px; border-radius: 4px; font-size: 9.5pt; }
.kh-print-totals .num { text-align: right; white-space: nowrap; }
.kh-print-totals .big { font-size: 12pt; font-weight: 700; color: #1F5F8B; padding-top: 4px; }
.kh-print-transport { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px 12px; margin: 16px 0 0; font-size: 9pt; }
.kh-print-transport dt { color: #6b7280; font-size: 8pt; }
.kh-print-transport dd { margin: 0; }
.kh-print-signatures { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-top: 16px; font-size: 8pt; color: #6b7280; }
.kh-print-signatures div { border-bottom: 1px solid #9aa1ab; padding-bottom: 28px; }
/* The message of "Invia per e-mail" (issue #52): room for the whole text proposed by the template. */
.kh-mail-form textarea.in { min-height: 190px; }
@@ -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;
}
}