diff --git a/scripts/run-dev.sh b/scripts/run-dev.sh index b714a75..ad55cf2 100755 --- a/scripts/run-dev.sh +++ b/scripts/run-dev.sh @@ -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}" diff --git a/src/Khaemhat.Application/Documents/DocumentCopyService.cs b/src/Khaemhat.Application/Documents/DocumentCopyService.cs index 392e166..00163f7 100644 --- a/src/Khaemhat.Application/Documents/DocumentCopyService.cs +++ b/src/Khaemhat.Application/Documents/DocumentCopyService.cs @@ -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; diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs index 6ec090d..73c1ab0 100644 --- a/src/Khaemhat.Application/Documents/DocumentEngine.cs +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -85,6 +85,9 @@ public static class DocumentErrors /// Error: a discount formula that cannot be read. public const string LineDiscountInvalid = "document.line.discount-invalid"; + + /// Error: a line of an invoice without its VAT code. + public const string LineTaxRequired = "document.line.tax-required"; } /// @@ -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); } + /// Records that the document was printed (its PDF kept among the attachments); the state does not change. + /// Who prints: needs to read the document. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// A task. + public Task MarkPrintedAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) => + MarkAsync(actor, companyCode, family, id, h => h.Printed = true, cancellationToken); + + /// Records that the document was sent by e-mail; the state does not change. + /// Who sends: needs to read the document. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// A task. + public Task MarkSentAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) => + MarkAsync(actor, companyCode, family, id, h => h.Sent = true, cancellationToken); + /// Deletes a draft. /// Who deletes. /// The company. @@ -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 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) { diff --git a/src/Khaemhat.Application/Documents/DocumentMail.cs b/src/Khaemhat.Application/Documents/DocumentMail.cs new file mode 100644 index 0000000..19f04f7 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentMail.cs @@ -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; + +/// +/// Fills a mail template (SPEC §12.6): {{Name}} becomes the value of the field, unknown fields stay as they are +/// so that a typing error shows in the message instead of disappearing. +/// +public static partial class MailTemplateRenderer +{ + /// Fills a template. + /// The template. + /// The values by name (case does not matter). + /// The text. + public static string Render(string template, IReadOnlyDictionary fields) + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(fields); + var lookup = new Dictionary(fields, StringComparer.OrdinalIgnoreCase); + return Field().Replace(template, m => lookup.TryGetValue(m.Groups[1].Value, out var value) ? value ?? string.Empty : m.Value); + } + + [GeneratedRegex(@"\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}", RegexOptions.CultureInvariant, 1000)] + private static partial Regex Field(); +} + +/// A message about a document, as the user is about to send it. +/// The recipients, separated by commas or semicolons. +/// The subject. +/// The text. +public sealed record DocumentMailDraft(string To, string Subject, string Body); + +/// The errors of (text keys). +public static class DocumentMailErrors +{ + /// No SMTP server is configured. + public const string NotConfigured = "document.mail.not-configured"; + + /// No recipient, or one that is not an e-mail address. + public const string RecipientInvalid = "document.mail.recipient-invalid"; + + /// The subject is empty. + public const string SubjectRequired = "document.mail.subject-required"; + + /// The queue is full. + public const string QueueFull = "document.mail.queue-full"; +} + +/// +/// Sends a document by e-mail (SPEC §9.4, §12.6, issue #52): proposes recipient, subject and text from the templates +/// (Print.Mail.*) and the e-mail of the party; on sending keeps the PDF as a new version among the attachments, +/// attaches it, queues the message and marks the document as sent. The outcome is in the log, section E-mail/PEC. +/// +/// The printed form of documents. +/// The document engine. +/// The generated files (the PDF). +/// The attachments. +/// The mail queue. +/// The units of work. +/// The texts. +public sealed partial class DocumentMailService( + DocumentPrintService prints, DocumentEngine engine, FileGenerationService generation, AttachmentService attachments, IMailQueue queue, IUnitOfWorkFactory factory, + ITexts texts) +{ + /// Whether mail can be sent from this instance. + public bool IsConfigured => queue.IsConfigured; + + /// The message proposed for a document. + /// Who sends. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The draft. + public async Task DraftAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) + { + var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false); + var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound); + string? email = null; + if (record.Header.PartyId is { } partyId) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false); + email = (await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false))?.Email; + } + + var fields = new Dictionary + { + ["Documento"] = model.Title, + ["Numero"] = model.Number, + ["Data"] = model.Date, + ["Cliente"] = model.Party.Name, + ["Azienda"] = model.Company.Name, + ["Totale"] = model.Totals.LastOrDefault(t => t.Strong)?.Value, + }; + + return new DocumentMailDraft( + email ?? string.Empty, + MailTemplateRenderer.Render(texts["Print.Mail.Subject"], fields), + MailTemplateRenderer.Render(texts["Print.Mail.Body"], fields)); + } + + /// Sends a document: the PDF becomes a new attachment version and leaves with the message. + /// Who sends. + /// The company. + /// The family. + /// The document. + /// The message. + /// Cancellation. + /// The PDF attached. + /// The message is not complete, or mail is not configured. + public async Task SendAsync( + Actor actor, string companyCode, DocumentFamily family, long id, DocumentMailDraft draft, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(draft); + var recipients = Recipients(draft.To); + var errors = new List(); + if (!queue.IsConfigured) + { + errors.Add(":" + DocumentMailErrors.NotConfigured); + } + + if (recipients.Count == 0 || !recipients.All(r => Address().IsMatch(r))) + { + errors.Add(nameof(DocumentMailDraft.To) + ":" + DocumentMailErrors.RecipientInvalid); + } + + if (string.IsNullOrWhiteSpace(draft.Subject)) + { + errors.Add(nameof(DocumentMailDraft.Subject) + ":" + DocumentMailErrors.SubjectRequired); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false); + var pdf = await generation.GenerateAsync(actor, companyCode, DocumentPrintService.EntityOf(family), id, DocumentPdfGenerator.GeneratorCode, cancellationToken) + .ConfigureAwait(false); + byte[] bytes; + await using (var content = await attachments.OpenAsync(actor, companyCode, pdf.Id, cancellationToken).ConfigureAwait(false)) + { + using var buffer = new MemoryStream(); + await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); + bytes = buffer.ToArray(); + } + + var mail = new OutgoingMail(recipients, draft.Subject.Trim(), draft.Body) + { + Attachments = [new MailAttachment(pdf.FileName, pdf.Mime, bytes)], + Reference = model.Title + " " + model.Number, + }; + + if (!queue.Enqueue(mail)) + { + throw new ValidationFailedException([":" + DocumentMailErrors.QueueFull]); + } + + await engine.MarkSentAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false); + return pdf; + } + + /// The addresses of a recipient field (commas, semicolons or spaces between them). + /// The field. + /// The addresses. + public static IReadOnlyList Recipients(string? text) => + string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';', ' ', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + [GeneratedRegex(@"^[^@\s<>]+@[^@\s<>]+\.[^@\s<>]+$", RegexOptions.CultureInvariant, 1000)] + private static partial Regex Address(); +} diff --git a/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs b/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs new file mode 100644 index 0000000..b9bf3b8 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs @@ -0,0 +1,440 @@ +using Khaemhat.Application.Files; +using Khaemhat.Application.Security; +using Khaemhat.Infrastructure.Files; + +namespace Khaemhat.Application.Documents; + +/// +/// 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 +/// Rigenera writes the current state after a change. +/// +/// The printed form of documents. +/// The attachments (the logo of the company). +public sealed class DocumentPdfGenerator(DocumentPrintService prints, AttachmentService attachments) : IFileGenerator +{ + /// The code of the generator. + 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"); + + /// + public string Code => GeneratorCode; + + /// + public string TitleKey => "files.generators.document_pdf"; + + /// + public string MediaType => PdfWriter.MediaType; + + /// + public string Extension => ".pdf"; + + /// + public bool Supports(string entity) => DocumentPrintService.FamilyOf(entity) is not null; + + /// + public string FileName(FileGenerationContext context) + { + ArgumentNullException.ThrowIfNull(context); + return Stem(context) + Extension; + } + + /// + 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 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 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 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); + } + } +} diff --git a/src/Khaemhat.Application/Documents/DocumentPrint.cs b/src/Khaemhat.Application/Documents/DocumentPrint.cs new file mode 100644 index 0000000..e33deb4 --- /dev/null +++ b/src/Khaemhat.Application/Documents/DocumentPrint.cs @@ -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; + +/// A block of name and lines: the company in the letterhead, the party in the address box. +/// The name. +/// The code of the party, when there is one. +/// Address, tax numbers, contacts. +public sealed record PrintParty(string Name, string? Code, IReadOnlyList Lines); + +/// A label and its value. +/// The label. +/// The value, formatted. +public sealed record PrintField(string Label, string Value); + +/// A row of the totals. +/// The label. +/// The amount, formatted. +/// Whether it is the amount to pay. +public sealed record PrintRow(string Label, string Value, bool Strong); + +/// A line of the document as printed; every value formatted, empty for a descriptive line. +/// The item code. +/// The description. +/// The unit of measure. +/// The quantity. +/// The unit price. +/// The discounts, such as 10+5. +/// The VAT code. +/// The amount. +/// Whether the line is only text. +public sealed record PrintLine( + string? Code, string Description, string? Unit, string? Quantity, string? Price, string? Discount, string? Tax, string? Amount, bool IsDescription); + +/// A small table (VAT summary, installments) with its headings and rows. +/// The title. +/// The headings. +/// Which columns hold numbers (aligned right). +/// The rows, formatted. +public sealed record PrintTable(string Title, IReadOnlyList Headers, IReadOnlyList Numeric, IReadOnlyList> Rows); + +/// +/// 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. +/// +public sealed record DocumentPrintModel +{ + /// The kind, such as Fattura immediata. + public required string Title { get; init; } + + /// The number, or the draft label. + public required string Number { get; init; } + + /// The date. + public required string Date { get; init; } + + /// A mark across the sheet: draft, cancelled, demo; none for a valid document. + public string? Watermark { get; init; } + + /// The company in the letterhead. + public required PrintParty Company { get; init; } + + /// The logo of the company, a JPEG, when it has one. + public byte[]? Logo { get; init; } + + /// The attachment of the logo, for the HTML preview. + public long? LogoAttachmentId { get; init; } + + /// The heading of the address box (Spett.le, Fornitore). + public required string PartyLabel { get; init; } + + /// The customer or supplier. + public required PrintParty Party { get; init; } + + /// Payment, reference, validity, delivery, agent, CIG and CUP. + public required IReadOnlyList Fields { get; init; } + + /// The headings of the lines. + public required IReadOnlyList LineHeaders { get; init; } + + /// The lines. + public required IReadOnlyList Lines { get; init; } + + /// The VAT summary; empty for documents without VAT. + public PrintTable? Summary { get; init; } + + /// The installments; empty when the document has none. + public PrintTable? Installments { get; init; } + + /// The totals, the amount to pay last. + public required IReadOnlyList Totals { get; init; } + + /// The transport data of a delivery note or accompanying invoice; empty otherwise. + public required IReadOnlyList Transport { get; init; } + + /// The signature boxes of a delivery note. + public required IReadOnlyList Signatures { get; init; } + + /// Notes printed under the lines (document notes, legal notes such as split payment). + public required IReadOnlyList Notes { get; init; } + + /// The footer of the company. + public string? Footer { get; init; } + + /// The name of the file without extension, such as fattura-immediata-6-2026. + public required string FileStem { get; init; } +} + +/// +/// 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 (Print.*); the same model feeds the HTML preview and the PDF generator. +/// +/// The document engine (reads the document with its permission). +/// The units of work. +/// The company registry (name of a company without profile). +/// The texts. +public sealed class DocumentPrintService(DocumentEngine engine, IUnitOfWorkFactory factory, ICompanyRegistry companies, ITexts texts) +{ + private static readonly Dictionary Entities = new Dictionary + { + [DocumentFamily.SaleQuotation] = "sales.salequotation", + [DocumentFamily.SaleOrder] = "sales.saleorder", + [DocumentFamily.SaleDocument] = "sales.saledocument", + [DocumentFamily.PurchaseOrder] = "purchases.purchaseorder", + [DocumentFamily.PurchaseDocument] = "purchases.purchasedocument", + [DocumentFamily.InventoryDocument] = "inventory.inventorydocument", + }; + + /// The entity of the attachments of a family, such as sales.saledocument. + /// The family. + /// The entity. + public static string EntityOf(DocumentFamily family) => Entities[family]; + + /// The family of an attachment entity. + /// The entity. + /// The family, or none for another entity. + public static DocumentFamily? FamilyOf(string? entity) => + Entities.Where(e => string.Equals(e.Value, entity, StringComparison.Ordinal)).Select(e => (DocumentFamily?)e.Key).FirstOrDefault(); + + /// The printed form of a document. + /// Who prints: needs to read the document. + /// The company. + /// The family. + /// The document. + /// The logo, read by the caller with its own permission (a JPEG for the PDF). + /// Cancellation. + /// The model. + /// No such document. + public async Task BuildAsync( + Actor actor, string companyCode, DocumentFamily family, long id, Func>? 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().FindAsync(Query.For(), 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().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null; + + var lookups = new Lookups(uow, cancellationToken); + var behavior = definition.Behavior; + var lines = new List(); + 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(itemId).ConfigureAwait(false))?.Code : null; + lines.Add(new PrintLine( + code, + line.Description, + await lookups.CodeAsync(line.UnitOfMeasureId).ConfigureAwait(false), + texts.Number(line.Quantity, 2), + texts.Money(line.Price), + string.IsNullOrWhiteSpace(line.DiscountFormula) ? null : line.DiscountFormula, + await lookups.CodeAsync(line.TaxCodeId).ConfigureAwait(false), + texts.Money(line.TaxableAmount), + false)); + } + + var fields = new List(); + void Field(string key, string? value) + { + if (!string.IsNullOrWhiteSpace(value)) + { + fields.Add(new PrintField(texts["Print.Fields." + key], value)); + } + } + + Field("Payment", await lookups.DescriptionAsync(h.PaymentTermId).ConfigureAwait(false)); + if (h.BankAccountId is { } bankId && await lookups.GetAsync(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(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(); + var signatures = new List(); + 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(h.TransportReasonId).ConfigureAwait(false)); + Transport("By", h.TransportBy is { } by ? texts["Sales.TransportBy." + by] : null); + Transport("Carrier", await lookups.DescriptionAsync(h.CarrierId).ConfigureAwait(false)); + Transport("Port", await lookups.DescriptionAsync(h.ShippingTermId).ConfigureAwait(false)); + Transport("Appearance", await lookups.DescriptionAsync(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>(); + foreach (var row in record.Figures.Summary) + { + var tax = row.TaxCodeId is { } taxId ? await lookups.GetAsync(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>(); + foreach (var due in record.Figures.Installments) + { + rows.Add([ + due.Number.ToString(texts.Culture), + texts.Date(due.DueDate), + await lookups.DescriptionAsync(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(); + 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(); + 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(); + 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 TotalsOf(DocumentRecord record, DocumentDefinition definition) + { + var h = record.Header; + var rows = new List(); + 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 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 GetAsync(long id) + where T : Core.Entities.Entity, new() + { + if (!_cache.TryGetValue((typeof(T), id), out var found)) + { + found = await uow.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + _cache[(typeof(T), id)] = found; + } + + return (T?)found; + } + + public async Task CodeAsync(long? id) + where T : CodedEntity, new() => + id is { } value ? (await GetAsync(value).ConfigureAwait(false))?.Code : null; + + public async Task DescriptionAsync(long? id) + where T : CodedEntity, new() => + id is { } value ? (await GetAsync(value).ConfigureAwait(false))?.Description : null; + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs new file mode 100644 index 0000000..1fa80f7 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs @@ -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; + +/// +/// 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. +/// +/// The document engine. +/// The document editor (party terms, item prices). +/// The transformations between documents. +/// The company profiles. +/// The units of work. +/// The clock. +public sealed class DemoSalesSeeder( + DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, CompanyProfileService profiles, IUnitOfWorkFactory factory, TimeProvider clock) + : ICompanySeeder +{ + /// The fictitious VAT number of the demo company (valid check digit). + 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; + + /// + public int Order => 20; + + /// + 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 ReadAsync(string companyCode, CancellationToken cancellationToken) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0) + { + return null; + } + + var parties = (await uow.Repository().ListAsync(Query.For().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().ListAsync(Query.For().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 Parties, IReadOnlyList Goods, IReadOnlyList 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 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 CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection? lines = null) => + owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken); + + private Task ConfirmAsync(DocumentRecord record) => + owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken); + } +} diff --git a/src/Khaemhat.Core/Logging/LogSection.cs b/src/Khaemhat.Core/Logging/LogSection.cs index 106b465..b410bcf 100644 --- a/src/Khaemhat.Core/Logging/LogSection.cs +++ b/src/Khaemhat.Core/Logging/LogSection.cs @@ -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, diff --git a/src/Khaemhat.Infrastructure/Mail/Mail.cs b/src/Khaemhat.Infrastructure/Mail/Mail.cs new file mode 100644 index 0000000..8c706e8 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Mail/Mail.cs @@ -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; + +/// A file attached to a message. +/// The file name. +/// The media type. +/// The bytes. +public sealed record MailAttachment(string FileName, string MediaType, byte[] Content); + +/// A message to send. +/// The recipients. +/// The subject. +/// The text of the message. +public sealed record OutgoingMail(IReadOnlyList To, string Subject, string Body) +{ + /// The recipients in copy. + public IReadOnlyList Cc { get; init; } = []; + + /// The address replies go to, when not the sender. + public string? ReplyTo { get; init; } + + /// The attachments. + public IReadOnlyList Attachments { get; init; } = []; + + /// What the message is about, for the log, such as Fattura immediata 6/2026. + public string? Reference { get; init; } +} + +/// How the connection to the SMTP server is protected (KHAEMHAT_SMTP_SECURITY). +public enum SmtpTransportSecurity +{ + /// Plain connection upgraded with STARTTLS (port 587). + StartTls = 0, + + /// TLS from the first byte (port 465). + Ssl = 1, + + /// No encryption: only for a relay on the local network. + None = 2, +} + +/// The SMTP server (SPEC §6: KHAEMHAT_SMTP_*). +/// The host; none when mail is not configured. +/// The port. +/// The user, when the server wants authentication. +/// The password. +/// The sender address. +/// The protection of the connection. +public sealed record SmtpSettings(string? Host, int Port, string? User, string? Password, string? From, SmtpTransportSecurity Security) +{ + /// Whether messages can be sent. + public bool IsConfigured => !string.IsNullOrWhiteSpace(Host) && !string.IsNullOrWhiteSpace(From); + + /// + public override string ToString() => $"{Host}:{Port} ({Security})"; +} + +/// Sends a message now. +public interface IMailSender +{ + /// Whether a server is configured. + bool IsConfigured { get; } + + /// Sends a message. + /// The message. + /// Cancellation. + /// A task. + /// The server refused the message or could not be reached. + Task SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default); +} + +/// A message the SMTP server refused, or a server that could not be reached. +public sealed class MailException : Exception +{ + /// Creates the exception. + public MailException() + { + } + + /// Creates the exception. + /// What went wrong. + public MailException(string message) + : base(message) + { + } + + /// Creates the exception. + /// What went wrong. + /// The cause. + public MailException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// +/// 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. +/// +public static class MimeMessageWriter +{ + /// Writes the message. + /// The message. + /// The sender. + /// The date of the message. + /// The MIME boundary; a new one when empty. + /// The message, lines ended by CRLF. + 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(); + } + + /// A header value, as an encoded word when it is not plain ASCII. + /// The value. + /// The header text. + 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"); + } + } +} + +/// +/// 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. +/// +/// The server. +/// The clock (date of the messages). +public sealed class SmtpMailSender(SmtpSettings settings, TimeProvider clock) : IMailSender +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60); + + /// + public bool IsConfigured => settings.IsConfigured; + + /// + 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 " 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 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 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 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)); + } + } + } +} + +/// Messages waiting to be sent. +[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 +{ + /// Whether a server is configured. + bool IsConfigured { get; } + + /// Puts a message in the queue; it leaves in the background, the outcome goes to the log (section E-mail/PEC). + /// The message. + /// Whether the message was accepted. + bool Enqueue(OutgoingMail mail); +} + +/// +/// 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. +/// +/// The sender. +/// The log. +[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 logger) : BackgroundService, IMailQueue +{ + private const int Attempts = 3; + private readonly Channel _channel = Channel.CreateBounded(new BoundedChannelOptions(500) { SingleReader = true }); + + /// + public bool IsConfigured => sender.IsConfigured; + + /// The pause between two attempts, shorter in tests. + public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(30); + + /// + 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; + } + + /// + 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); +} diff --git a/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor b/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor index 96533f7..e032ea4 100644 --- a/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Parties/PartyPage.razor @@ -273,6 +273,12 @@ else Value="@PartyScreens.Text(s.CompanyBankAccountId)" ValueChanged="v => Change(() => s.CompanyBankAccountId = PartyScreens.Id(v))" /> + + + Change(() => address.Kind = Enum.Parse(value!)); + // The months a customer excludes from the due dates (August, December...), named in the language of the screen. + private IReadOnlyList> MonthChoices => + [.. Enumerable.Range(1, 12).Select(m => new KhOption(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(value!)); private Task SetSubjectAsync(string? value) diff --git a/src/Khaemhat.Web/Components/Pages/Sales/DeferredInvoicingPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/DeferredInvoicingPage.razor new file mode 100644 index 0000000..755507d --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/DeferredInvoicingPage.razor @@ -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. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Sales.NoCompany"]

+} +else if (!Session.Permissions.Allows("sales.invoice.write") || !Session.Permissions.Allows("sales.delivery.read")) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ +
+
+ + +
+ + + + + + +
+ +
+
+
+
+
+ @if (_results.Count > 0) + { + +
+ + + + + + + + + + + @foreach (var result in _results) + { + + + @if (result.Record is { } record) + { + var state = SalesScreens.State(T, record.Header.Kind, record.Header.Status, null, Today); + + + + } + else + { + + } + + } + +
@T["Sales.Fields.PartyId"]@T["Sales.Deferred.Invoice"]@T["Sales.Radar.State"]@T["Sales.Totals.Total"]
@result.PartyName@(record.Header.DocumentNumber ?? T["Sales.DraftNumber"])@state.Text@T.Money(record.Header.TotalAmount) @result.Error
+
+
+ @T["Sales.Sections.Invoices.Title"] + +
+
+ } + else + { + + + @T.Format("Sales.Deferred.Selected", _selected.Count, T.Money(SelectedTotal)) + + + + @if (_notes is null) + { +

@T["Sales.Deferred.Start"]

+ } + else if (_notes.Count == 0) + { +

@T["Sales.Deferred.None"]

+ } + else + { +
+ + + + + + + + + + + + + + @foreach (var note in _notes) + { + var id = note.Row.Id; + + + + + + + + + + } + +
@T["Sales.Kinds.DeliveryNote"]@T["Sales.Fields.DocumentDate"]@T["Sales.Fields.PartyId"]@T["Sales.Deferred.Lines"]@T["Sales.Totals.Taxable"]@T["Sales.Deferred.Invoice"]
@note.Row.DocumentNumber@T.Date(note.Row.Date)@note.Row.PartyName@note.Lines.Count@T.Money(note.Row.Taxable)@InvoiceLabel(note)
+
+ } +
+
+ } +
+
+} + +@code { + private readonly HashSet _selected = []; + private readonly List _results = []; + private IReadOnlyList? _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 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> 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; + + /// + 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> 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> Groups() => _notes is null ? [] : _perNote + ? [.. _notes.Where(n => _selected.Contains(n.Row.Id)).Select(n => new List { 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); +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor new file mode 100644 index 0000000..cf5330b --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor @@ -0,0 +1,409 @@ +@page "/vendite/{Segment}/nuovo" +@page "/vendite/{Segment}/{Id:long}" +@attribute [Authorize] +@inherits DocumentPage +@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. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Sales.NoCompany"]

+} +else if (_denied) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else if (Record is null || _section is null || _definition is null) +{ +
+ +

@T["Sales.NotFound"]

+ @T["Sales.BackToList"] +
+} +else +{ + var h = Record.Header; + + + + + @T["Sales.Fields.DocumentDate"] @T.Date(h.DocumentDate) + @if (h.Kind == DocumentKind.Quotation && h.ValidUntil is { } until) + { + @T["Sales.Fields.ValidUntil"] @T.Date(until) + } + @if (h.DeliveryDate is { } delivery) + { + @T["Sales.Fields.DeliveryDate"] @T.Date(delivery) + } + @if (h.Revision > 0) + { + @T["Sales.Fields.Revision"] @h.Revision + } + @if (h.RelatedNumber is { } related) + { + @T["Sales.Fields.Related"] @related@(h.RelatedDate is { } rd ? " · " + T.Date(rd) : null) + } + + + @{ var state = SalesScreens.State(T, h.Kind, h.Status, h.ValidUntil, Today); } + @state.Text + @if (h.IsDemo) + { + @T["Sales.Demo"] + } + @if (IsModified) + { + @T["CompanyTables.Modified"] + } + + + @if (PartyScreens.Describe(_lookups.PaymentTerms, h.PaymentTermId) is { } payment) + { + + } + @if (PartyScreens.Describe(_lookups.PriceLists, h.PriceListId) is { } list) + { + + } + @if (PartyScreens.Describe(_lookups.Salespeople, h.SalespersonId) is { } agent) + { + + } + @if (h.SplitPayment) + { + + } + + + + + @switch (ActiveTab) + { + case TabIds.Lines: + @if (h.PartyId is null && !IsReadOnly) + { +
@T["Sales.Hints.PartyFirst"] +
+ } + + @if (Validation.Messages.Any(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true)) + { +
    + @foreach (var message in Validation.Messages.Where(m => m.Field?.StartsWith("Lines.", StringComparison.Ordinal) == true)) + { +
  • @LineErrorText(message.Field!, message.Message)
  • + } +
+ } +
+ @TaxSummary + @Installments + @Totals +
+ break; + + case TabIds.Header: + + + + + + @if (h.Kind == DocumentKind.Quotation) + { + + } + @if (h.Kind is DocumentKind.Quotation or DocumentKind.SalesOrder or DocumentKind.DeliveryNote or DocumentKind.ProForma) + { + + } + + + @if (IsNote) + { + + + } + + + + + + @if (h.PartyId is not null) + { +

@T["Sales.Hints.PartyDefaults"]

+ } +
+ + + + + + + + + @if (IsInvoice) + { + + + + + + + + + + + + + + + + + +

@T["Sales.Hints.Withholding"]

+
+ } +
+ break; + + case SalesScreens.TransportTab: + + + + + + + + + + + + + + + +

@T["Sales.Hints.Transport"]

+
+
+ break; + + case TabIds.Totals: +
+ @TaxSummary + @Totals +
+ break; + + case TabIds.DueDates: +
+ @Installments +
+

@T[Behavior.Has(DocumentEffects.Installments) ? "Sales.Hints.Installments" : "Sales.Hints.InstallmentsForecast"]

+ break; + + case TabIds.Notes: + + + + + @if (h.CancelReason is { } reason) + { + + + + } + + break; + + case TabIds.Attachments: +
+ break; + + case TabIds.Links: +
+ @if (_links.Count == 0) + { +

@T["Sales.Links.Empty"]

+ } + else + { +
+ + + + + + + + + + + + + + @foreach (var link in _links) + { + var linkState = SalesScreens.State(T, link.Kind, link.Status, null, Today); + + + + + + + + + + } + +
@T["Sales.Links.Relation"]@T["Sales.Radar.Kind"]@T["Sales.Fields.DocumentNumber"]@T["Sales.Fields.DocumentDate"]@T["Sales.Radar.State"]@T["Sales.Links.Quantity"]@T["Sales.Totals.Total"]
@T["Sales.Links." + link.Direction]@SalesScreens.KindName(T, link.Kind) + @if (SalesScreens.RecordUrl(link.Kind, link.Id) is { } url) + { + @(link.DocumentNumber ?? T["Sales.DraftNumber"]) + } + else + { + @(link.DocumentNumber ?? T["Sales.DraftNumber"]) + } + @T.Date(link.Date)@linkState.Text@(link.Quantity > 0 ? T.Number(link.Quantity, 2) : null)@T.Money(link.Total)
+
+ } +
+ break; + + case TabIds.History: +
+ break; + } +
+
+ + + + + + @if (_transform is { } t) + { +

@t.Lead

+
+ + + + + + + @if (t.Fulfils) + { + + } + + + + + @foreach (var line in t.Lines) + { + var id = line.Id; + + + + + @if (t.Fulfils) + { + + } + + + } + +
@T["Sales.Lines.Description"]@T["Sales.Lines.Quantity"]@T["Sales.Lines.Residual"]@T["Sales.Lines.Amount"]
@line.Description@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Quantity, 2) : null)@(DocumentLine.CarriesQuantity(line.Kind) ? T.Number(line.Residual, 2) : null)@(line.Kind == DocumentLineKind.Description ? null : T.Money(line.TaxableAmount))
+
+ } +
+
+ + +
+
+ + + +

@T[Behavior.Lifecycle == DocumentLifecycle.Invoice ? "Sales.Cancel.LeadInvoice" : "Sales.Cancel.Lead"]

+ + + +
+
+ + +
+
+ + + + @if (!Mails.IsConfigured) + { +
@T[DocumentMailErrors.NotConfigured]
+ } +

@T["Sales.Mail.Lead"]

+
+ + + + + +
+
+
+ + +
+
+} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs new file mode 100644 index 0000000..e52d490 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentPage.razor.cs @@ -0,0 +1,1372 @@ +using System.Globalization; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Documents; +using Khaemhat.Application.Files; +using Khaemhat.Application.Items; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Parties; +using Khaemhat.Application.Querying; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Common; +using Khaemhat.Core.Documents; +using Khaemhat.Core.Tax; +using Khaemhat.Web.Components.Ui; +using Khaemhat.Web.Documents; +using Khaemhat.Web.Parties; +using Khaemhat.Web.Shell; +using Khaemhat.Web.Tables; +using Khaemhat.Web.Ui; +using Microsoft.AspNetCore.Components; + +namespace Khaemhat.Web.Components.Pages.Sales; + +/// The record of a sales document: loading, lines, live totals, state actions and transformations. +public sealed partial class SalesDocumentPage +{ + private readonly Dictionary _items = []; + private readonly Dictionary _typedCodes = new(ReferenceEqualityComparer.Instance); + private readonly KhValidation _cancelValidation = new(); + private SalesSection? _section; + private DocumentDefinition? _definition; + private IReadOnlyList _definitions = []; + private DocumentLookups _lookups = DocumentLookups.Empty; + private PartyRow? _party; + private IReadOnlyList _actions = []; + private IReadOnlyList _links = []; + private IReadOnlyList _history = []; + private int _attachments; + private bool _loaded; + private bool _denied; + private bool _busy; + private (string? Segment, long? Id, string? Type)? _shown; + private KhLinesGrid? _grid; + private DocumentLine? _lookupLine; + private string? _lookupText; + private TaskCompletionSource? _lookupDone; + private CancellationTokenSource? _preview; + private TransformRequest? _transform; + private bool _cancelling; + private string? _cancelReason; + private readonly KhValidation _mailValidation = new(); + private bool _mailing; + private string? _mailTo; + private string? _mailSubject; + private string? _mailBody; + private IReadOnlyList>? _lineColumns; + + /// The radar segment, such as fatture. + [Parameter] + public string? Segment { get; set; } + + /// The document; none for a new one. + [Parameter] + public long? Id { get; set; } + + /// The type of a new document, such as FI. + [SupplyParameterFromQuery(Name = "tipo")] + public string? TypeCode { get; set; } + + [Inject] + private ShellSession Session { get; set; } = default!; + + [Inject] + private DocumentEngine Engine { get; set; } = default!; + + [Inject] + private DocumentEditor Editor { get; set; } = default!; + + [Inject] + private DocumentCopyService Copies { get; set; } = default!; + + [Inject] + private PartyService Parties { get; set; } = default!; + + [Inject] + private ItemService Items { get; set; } = default!; + + [Inject] + private TableService Tables { get; set; } = default!; + + [Inject] + private AttachmentService Attachments { get; set; } = default!; + + [Inject] + private AuditTrailService Audit { get; set; } = default!; + + [Inject] + private DocumentMailService Mails { get; set; } = default!; + + [Inject] + private TimeProvider Clock { get; set; } = default!; + + private DocumentHeader H => Record!.Header; + + private DocumentBehavior Behavior => DocumentBehaviors.Of(Record!.Header.Kind); + + private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime); + + private string PageTitle => Record is null || _definition is null + ? T["Shell.Menu.Sales"] + : _definition.Type.Description + " " + (Record.Header.DocumentNumber ?? T["Sales.DraftNumber"]); + + private bool IsInvoice => Record is not null && (Behavior.Lifecycle == DocumentLifecycle.Invoice || H.Kind == DocumentKind.ProForma); + + private bool IsNote => Record is not null && H.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote; + + private bool ShowsNet => Record is not null && H.NetAmount != H.TotalAmount && H.NetAmount != 0m; + + private bool CanWrite => Record is not null && Session.Permissions.Allows(Behavior.WritePermission); + + // The entity of the attachments, such as sales.saledocument. + private string AttachmentEntity => "sales." + Record!.Header.GetType().Name.ToLowerInvariant(); + + /// + public override bool IsReadOnly => Record is null || !CanWrite || !(IsNew || _actions.Contains(DocumentAction.Edit)); + + /// + protected override bool IsNew => Record is { Header.Id: 0 }; + + /// + protected override bool CanDelete => !IsNew && _actions.Contains(DocumentAction.Delete); + + /// + protected override IList Lines => Record?.Lines ?? []; + + /// + protected override string? NewUrl => _section is not null && _definition is not null && CanWrite ? SalesScreens.NewUrl(_section, _definition.Code) : null; + + /// + protected override int? AttachmentCount => IsNew || Record is null ? null : _attachments; + + /// + public override IReadOnlyList Tabs + { + get + { + if (Record is null) + { + return []; + } + + var tabs = new List + { + TabOf(TabIds.Lines, "list", "Ui.Record.Tabs.Lines", Record.Lines.Count), + TabOf(TabIds.Header, "file", "Ui.Record.Tabs.Header"), + }; + if (Behavior.Has(DocumentEffects.Inventory)) + { + tabs.Add(TabOf(SalesScreens.TransportTab, "truck", "Sales.Tabs.Transport")); + } + + tabs.Add(TabOf(TabIds.Totals, "euro", "Ui.Record.Tabs.Totals")); + tabs.Add(TabOf(TabIds.DueDates, "calendar", "Ui.Record.Tabs.DueDates", Record.Figures.Installments.Count)); + tabs.Add(TabOf(TabIds.Notes, "edit", "Ui.Record.Tabs.Notes")); + if (!IsNew) + { + tabs.Add(TabOf(TabIds.Attachments, "paperclip", "Ui.Record.Tabs.Attachments", _attachments)); + tabs.Add(TabOf(TabIds.Links, "link", "Ui.Record.Tabs.Links", _links.Count)); + tabs.Add(TabOf(TabIds.History, "history", "Ui.Record.Tabs.History")); + } + + return tabs; + } + } + + private KhTabItem TabOf(string id, string icon, string key, int? count = null) + { + // A tab with errors shows how many; otherwise how many details it holds. + var errors = Validation.Messages.Count(m => TabOfField(m.Field) == id); + return new(id, icon, T[key], errors > 0 ? errors : count is > 0 ? count : null); + } + + private static readonly HashSet TransportFields = + [ + nameof(DocumentHeader.TransportReasonId), nameof(DocumentHeader.TransportBy), nameof(DocumentHeader.CarrierId), nameof(DocumentHeader.ShippingTermId), + nameof(DocumentHeader.TransportStart), nameof(DocumentHeader.WarehouseId), nameof(DocumentHeader.GoodsAppearanceId), nameof(DocumentHeader.Packages), + nameof(DocumentHeader.GrossWeight), nameof(DocumentHeader.NetWeight), + ]; + + private static string TabOfField(string? field) => field switch + { + null or "" => TabIds.Lines, + _ when field.StartsWith("Lines", StringComparison.Ordinal) => TabIds.Lines, + nameof(DocumentHeader.Notes) => TabIds.Notes, + _ when TransportFields.Contains(field) => SalesScreens.TransportTab, + _ => TabIds.Header, + }; + + // ---- Loading ---------------------------------------------------------------------------------------------------- + + /// + protected override async Task OnParametersSetAsync() + { + await Session.EnsureLoadedAsync(); + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + _loaded = true; + return; + } + + var wanted = (Segment, Id, TypeCode); + if (_shown == wanted && Record is not null) + { + return; + } + + _section = SalesScreens.Find(Segment); + if (!_loaded) + { + _lookups = await DocumentLookups.ReadAsync(Tables, actor, company); + _definitions = await Engine.DefinitionsAsync(actor, company); + } + + _shown = wanted; + await ReloadAsync(); + MarkSaved(); + if (IsNew && Record is not null) + { + // A new document starts from the customer. + await ShowTabAsync(TabIds.Header); + } + + _loaded = true; + } + + /// + protected override async Task ReloadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _section is null) + { + return; + } + + Validation.Clear(); + _typedCodes.Clear(); + _denied = false; + try + { + if (Id is { } id) + { + Record = await Engine.GetAsync(actor, company, _section.Family, id); + if (Record is not null && !_section.Kinds.Contains(Record.Header.Kind)) + { + // The address of another radar: show the document where it belongs. + if (SalesScreens.RecordUrl(Record.Header.Kind, id) is { } url) + { + Navigation.NavigateTo(url, new NavigationOptions { ReplaceHistoryEntry = true }); + } + + Record = null; + } + } + else + { + var type = _section.NewTypes.FirstOrDefault(t => string.Equals(t, TypeCode, StringComparison.OrdinalIgnoreCase)) ?? _section.NewTypes[0]; + Record = await Engine.NewAsync(actor, company, type); + await PreviewNowAsync(); + } + } + catch (AccessDeniedException) + { + _denied = true; + Record = null; + } + + _definition = Record is null ? null : _definitions.FirstOrDefault(d => d.Type.Id == Record.Header.DocumentTypeId); + await LoadSideAsync(actor, company); + } + + private async Task LoadSideAsync(Actor actor, string company) + { + if (Record is null) + { + return; + } + + _actions = await Engine.ActionsAsync(actor, Record); + _party = Record.Header.PartyId is { } partyId && Session.Permissions.Allows(PartyService.ReadPermission) + ? (await Parties.RowsAsync(actor, company, [partyId])) is [var partyRow, ..] ? partyRow : null + : null; + long[] items = [.. Record.Lines.Where(l => l.ItemId is not null).Select(l => l.ItemId!.Value).Distinct().Where(i => !_items.ContainsKey(i))]; + if (items.Length > 0) + { + foreach (var row in await Items.RowsAsync(actor, company, items)) + { + _items[row.Id] = row; + } + } + + if (IsNew) + { + _links = []; + _history = []; + _attachments = 0; + return; + } + + _links = await Editor.LinksAsync(actor, company, Record); + _history = await Audit.HistoryAsync(actor, company, Record.Header.GetType().Name, Record.Header.Id.ToString(CultureInfo.InvariantCulture), Behavior.ReadPermission); + _attachments = Session.Permissions.Allows(AttachmentService.ReadPermission) + ? await Attachments.CountAsync(actor, company, AttachmentEntity, Record.Header.Id) + : 0; + } + + // ---- Head ------------------------------------------------------------------------------------------------------- + + private IReadOnlyList PartyLines + { + get + { + if (_party is null) + { + return []; + } + + var lines = new List(); + if (_party.City is { } city) + { + lines.Add(_party.Province is { } province ? city + " (" + province + ")" : city); + } + + if (_party.VatNumber is { } vat) + { + lines.Add(T["Sales.Head.Vat"] + " " + vat); + } + else if (_party.TaxCode is { } taxCode) + { + lines.Add(T["Sales.Head.TaxCode"] + " " + taxCode); + } + + return lines; + } + } + + private IReadOnlyList HeadStats => + [ + new(T["Sales.Totals.Taxable"], T.Money(H.TaxableAmount)), + new(T["Sales.Totals.Tax"], T.Money(H.TaxAmount)), + .. ShowsNet ? [new KhStat(T["Sales.Totals.Total"], T.Money(H.TotalAmount))] : Array.Empty(), + ]; + + // ---- Lines ------------------------------------------------------------------------------------------------------ + + private IReadOnlyList> LineColumns => _lineColumns ??= BuildColumns(); + + private List> BuildColumns() + { + var columns = new List> + { + new("item", T["Sales.Lines.Item"], ItemCode) { Kind = KhColumnKind.Code, Width = "120px", SetText = SetItemCode, Lookup = LookupItemAsync }, + new("description", T["Sales.Lines.Description"], l => l.Description) { SetText = (l, v) => l.Description = v ?? string.Empty }, + new("unit", T["Sales.Lines.Unit"], l => DocumentLookups.CodeOf(_lookups.Units, l.UnitOfMeasureId)) + { + Width = "56px", SetText = (l, v) => l.UnitOfMeasureId = DocumentLookups.IdOf(_lookups.Units, v), + }, + new("quantity", T["Sales.Lines.Quantity"], l => DocumentLine.CarriesQuantity(l.Kind) ? l.Quantity : null) + { + Kind = KhColumnKind.Number, Width = "86px", SetNumber = (l, v) => l.Quantity = v ?? 0m, + }, + new("price", T["Sales.Lines.Price"], l => l.Kind == DocumentLineKind.Description ? null : l.Price) + { + Kind = KhColumnKind.Money, Width = "104px", SetNumber = SetPrice, + }, + new("discount", T["Sales.Lines.Discount"], l => l.DiscountFormula) { Width = "76px", SetText = (l, v) => l.DiscountFormula = v }, + new("tax", T["Sales.Lines.Tax"], l => DocumentLookups.CodeOf(_lookups.TaxCodes, l.TaxCodeId)) + { + Width = "64px", SetText = (l, v) => l.TaxCodeId = DocumentLookups.IdOf(_lookups.TaxCodes, v), + }, + }; + if (Record is not null && H.Kind is DocumentKind.SalesOrder or DocumentKind.Quotation) + { + columns.Add(new("delivery", T["Sales.Lines.Delivery"], l => l.DeliveryDate is { } d ? d.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) : null) + { + Kind = KhColumnKind.Date, Width = "96px", SetText = (l, v) => l.DeliveryDate = ParseDate(v), + }); + } + + if (Record is not null && Behavior.Lifecycle == DocumentLifecycle.Order) + { + columns.Add(new("fulfilled", T["Sales.Lines.Fulfilled"], l => l.FulfilledQuantity > 0m ? l.FulfilledQuantity : null) { Kind = KhColumnKind.Number, Width = "76px" }); + } + + columns.Add(new("amount", T["Sales.Lines.Amount"], l => l.Kind == DocumentLineKind.Description ? null : l.TaxableAmount) { Kind = KhColumnKind.Money, Width = "112px" }); + return columns; + } + + private static DateOnly? ParseDate(string? text) => + DateOnly.TryParse(text, CultureInfo.GetCultureInfo("it-IT"), DateTimeStyles.None, out var date) ? date : null; + + private static void SetPrice(DocumentLine line, decimal? value) => line.Price = value ?? 0m; + + private string? ItemCode(DocumentLine line) => + _typedCodes.TryGetValue(line, out var typed) ? typed + : line.ItemId is { } id && _items.TryGetValue(id, out var row) ? row.Code + : line.Kind switch + { + DocumentLineKind.Expense => T["Sales.LineKinds.Expense"], + DocumentLineKind.Discount => T["Sales.LineKinds.Discount"], + _ => null, + }; + + private void SetItemCode(DocumentLine line, string? code) + { + if (string.IsNullOrWhiteSpace(code)) + { + _typedCodes.Remove(line); + if (line.Kind == DocumentLineKind.Item) + { + line.Kind = DocumentLineKind.Free; + line.ItemId = null; + } + + return; + } + + _typedCodes[line] = code.Trim().ToUpperInvariant(); + } + + private DocumentLine NewLine() + { + var line = CreateLine(Record!.Family); + line.Kind = DocumentLineKind.Free; + line.TaxCodeId = DefaultTaxCode(); + return line; + } + + private DocumentLine NewDescriptionLine() + { + var line = CreateLine(Record!.Family); + line.Kind = DocumentLineKind.Description; + return line; + } + + private DocumentLine NewKindLine(DocumentLineKind kind) + { + var line = NewLine(); + line.Kind = kind; + line.Description = T["Sales.LineKinds." + kind]; + line.Quantity = 0m; + line.WithholdingExcluded = kind == DocumentLineKind.Expense; + return line; + } + + private async Task AddKindLineAsync(DocumentLineKind kind) + { + Record!.Lines.Add(NewKindLine(kind)); + await ShowTabAsync(TabIds.Lines); + MarkModified(); + SchedulePreview(); + } + + // The VAT code a new line proposes: the one of the last line that has one. + private long? DefaultTaxCode() => Record?.Lines.LastOrDefault(l => l.TaxCodeId is not null)?.TaxCodeId; + + private static DocumentLine CreateLine(DocumentFamily family) => family switch + { + DocumentFamily.SaleQuotation => new SaleQuotationLine(), + DocumentFamily.SaleOrder => new SaleOrderLine(), + _ => new SaleDocumentLine(), + }; + + private bool IsEmptyLine(DocumentLine line) => + line.ItemId is null && line.Description.Length == 0 && line.Quantity == 0m && line.Price == 0m && !_typedCodes.ContainsKey(line); + + private async Task LinesChangedAsync() + { + MarkModified(); + foreach (var line in Record!.Lines) + { + // A line with a quantity but no kind of its own is a free line; a line with an item is an item line. + if (line.Kind == DocumentLineKind.Free && line.ItemId is not null) + { + line.Kind = DocumentLineKind.Item; + } + } + + if (_typedCodes.Count > 0) + { + await ResolveCodesAsync(); + } + + SchedulePreview(); + } + + // The codes typed in the item column: an exact code fills the line, otherwise the item radar opens on the text. + private async Task ResolveCodesAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + foreach (var (line, code) in _typedCodes.ToList()) + { + if (!Record!.Lines.Contains(line)) + { + continue; + } + + var found = await Items.SearchAsync(actor, company, code, H.PartyId); + var match = found.FirstOrDefault(i => string.Equals(i.Code, code, StringComparison.OrdinalIgnoreCase)) + ?? (found.Count == 1 ? found[0] : null); + _typedCodes.Remove(line); + if (match is not null) + { + await FillAsync(line, match); + } + else + { + await LookupItemAsync(line, code); + } + } + } + + private async Task FillAsync(DocumentLine line, ItemRow item) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _items[item.Id] = item; + try + { + await Editor.FillLineAsync(actor, company, Record!, line, item.Id); + } + catch (KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T["Sales.Lines.ItemMissing"]); + } + + MarkModified(); + } + + private Task LookupItemAsync(DocumentLine line) => LookupItemAsync(line, null); + + private Task LookupItemAsync(DocumentLine line, string? text) + { + _lookupLine = line; + _lookupText = text ?? ItemCode(line); + _lookupDone = new TaskCompletionSource(); + StateHasChanged(); + return _lookupDone.Task; + } + + private async Task PickItemAsync(ItemRow item) + { + if (_lookupLine is { } line) + { + if (!Record!.Lines.Contains(line)) + { + Record.Lines.Add(line); + } + + await FillAsync(line, item); + CloseLookup(); + SchedulePreview(); + await Task.Yield(); + if (_grid is not null) + { + await _grid.FocusCellAsync(line, "quantity"); + } + } + } + + private void CloseLookup() + { + _lookupLine = null; + _lookupText = null; + _lookupDone?.TrySetResult(); + } + + private IReadOnlyList> ItemColumns => + [ + new("code", T["Items.Fields.Code"], i => i.Code) { Kind = KhColumnKind.Code, Width = "130px" }, + new("description", T["Items.Fields.Description"], i => i.Description), + new("unit", T["Items.Radar.Unit"], i => PartyScreens.Describe(_lookups.Units, i.UnitOfMeasureId)) { Width = "60px", Sortable = false }, + new("brand", T["Items.Fields.Brand"], i => i.Brand) { Width = "120px" }, + new("basePrice", T["Items.Radar.BasePrice"], i => i.BasePrice) { Kind = KhColumnKind.Money, Width = "110px", Sortable = false }, + ]; + + private Task> ListItemsAsync(ListQuery query, CancellationToken cancellationToken) => + Session.Actor is { } actor && Session.Company?.Code is { } company + ? Items.ListAsync(actor, company, query with { Filters = [.. query.Filters, ListFilter.Of("disabled", ListFilterOperator.Equals, "false")] }, cancellationToken) + : Task.FromResult(new ListPage([], 0, new Dictionary())); + + private string LineErrorText(string field, string text) + { + var parts = field.Split('.'); + return parts.Length > 1 && int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var index) + ? T.Format("Sales.Lines.ErrorAt", index + 1, text) + : text; + } + + // ---- Totals ----------------------------------------------------------------------------------------------------- + + private void SchedulePreview() + { + _preview?.Cancel(); + _preview?.Dispose(); + _preview = new CancellationTokenSource(); + var token = _preview.Token; + _ = InvokeAsync(async () => + { + try + { + await Task.Delay(250, token); + await PreviewNowAsync(token); + StateHasChanged(); + } + catch (OperationCanceledException) + { + // A newer change computes again. + } + }); + } + + private async Task PreviewNowAsync(CancellationToken cancellationToken = default) + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + try + { + var figures = await Editor.PreviewAsync(actor, company, Record, cancellationToken); + Record = new DocumentRecord { Family = Record.Family, Header = Record.Header, Lines = Record.Lines, Figures = figures }; + } + catch (Exception ex) when (ex is ValidationFailedException or KeyNotFoundException or FormatException or ArgumentException) + { + // Half-typed lines (a discount being written, a VAT code missing): the totals wait for the next change. + } + } + + private RenderFragment TaxSummary => __builder => + { + var summary = Record!.Figures.Summary; + if (summary.Count == 0) + { + __builder.OpenElement(0, "p"); + __builder.AddAttribute(1, "class", "muted sm kh-pad"); + __builder.AddContent(2, T["Sales.Totals.SummaryEmpty"]); + __builder.CloseElement(); + return; + } + + __builder.OpenElement(10, "table"); + __builder.AddAttribute(11, "class", "grid compact"); + __builder.AddAttribute(12, "aria-label", T["Sales.Totals.Summary"]); + __builder.OpenElement(13, "thead"); + __builder.OpenElement(14, "tr"); + foreach (var (title, numeric) in new[] { (T["Sales.Totals.TaxCode"], false), (T["Sales.Totals.Rate"], true), (T["Sales.Totals.Taxable"], true), (T["Sales.Totals.Tax"], true) }) + { + __builder.OpenElement(15, "th"); + __builder.AddAttribute(16, "scope", "col"); + __builder.AddAttribute(17, "class", numeric ? "num" : null); + __builder.AddContent(18, title); + __builder.CloseElement(); + } + + __builder.CloseElement(); + __builder.CloseElement(); + __builder.OpenElement(20, "tbody"); + foreach (var row in summary) + { + __builder.OpenElement(21, "tr"); + Cell(__builder, PartyScreens.Describe(_lookups.TaxCodes, row.TaxCodeId, full: true) ?? row.Nature ?? string.Empty, false); + Cell(__builder, T.Number(row.Rate, 2) + "%", true); + Cell(__builder, T.Money(row.Taxable), true); + Cell(__builder, T.Money(row.Tax), true); + __builder.CloseElement(); + } + + __builder.OpenElement(30, "tr"); + __builder.AddAttribute(31, "class", "kh-total-row"); + Cell(__builder, T["Sales.Totals.Total"], false); + Cell(__builder, string.Empty, true); + Cell(__builder, T.Money(summary.Sum(r => r.Taxable)), true); + Cell(__builder, T.Money(summary.Sum(r => r.Tax)), true); + __builder.CloseElement(); + __builder.CloseElement(); + __builder.CloseElement(); + }; + + private RenderFragment Installments => __builder => + { + var rows = Record!.Figures.Installments; + if (rows.Count == 0) + { + __builder.OpenElement(0, "p"); + __builder.AddAttribute(1, "class", "muted sm kh-pad"); + __builder.AddContent(2, T[H.PaymentTermId is null ? "Sales.Totals.InstallmentsNoTerm" : "Sales.Totals.InstallmentsEmpty"]); + __builder.CloseElement(); + return; + } + + __builder.OpenElement(10, "table"); + __builder.AddAttribute(11, "class", "grid compact"); + __builder.AddAttribute(12, "aria-label", T["Sales.Totals.Installments"]); + __builder.OpenElement(13, "thead"); + __builder.OpenElement(14, "tr"); + foreach (var (title, numeric) in new[] { ("#", false), (T["Sales.Totals.DueDate"], false), (T["Sales.Totals.Method"], false), (T["Sales.Totals.Amount"], true) }) + { + __builder.OpenElement(15, "th"); + __builder.AddAttribute(16, "scope", "col"); + __builder.AddAttribute(17, "class", numeric ? "num" : null); + __builder.AddContent(18, title); + __builder.CloseElement(); + } + + __builder.CloseElement(); + __builder.CloseElement(); + __builder.OpenElement(20, "tbody"); + foreach (var row in rows) + { + __builder.OpenElement(21, "tr"); + Cell(__builder, row.Number.ToString(T.Culture), false); + Cell(__builder, T.Date(row.DueDate), false); + Cell(__builder, PartyScreens.Describe(_lookups.PaymentMethods, row.PaymentMethodId) ?? string.Empty, false); + Cell(__builder, T.Money(row.Amount), true); + __builder.CloseElement(); + } + + __builder.CloseElement(); + __builder.CloseElement(); + }; + + private RenderFragment Totals => __builder => + { + var h = H; + var rows = new List<(string Label, decimal Value, bool Big)> + { + (T["Sales.Totals.Goods"], Record!.Lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free or DocumentLineKind.Discount).Sum(l => l.TaxableAmount), false), + }; + if (h.FooterDiscountAmount != 0m) + { + rows.Add((T["Sales.Totals.FooterDiscount"] + (h.FooterDiscount is { } f ? " " + f + "%" : null), -h.FooterDiscountAmount, false)); + } + + if (h.ExpensesAmount != 0m) + { + rows.Add((T["Sales.Totals.Expenses"], h.ExpensesAmount, false)); + } + + if (h.SocialSecurityAmount != 0m) + { + rows.Add((T["Sales.Totals.SocialSecurity"], h.SocialSecurityAmount, false)); + } + + rows.Add((T["Sales.Totals.Taxable"], h.TaxableAmount, false)); + rows.Add((T["Sales.Totals.Tax"], h.TaxAmount, false)); + if (h.StampDuty != 0m) + { + rows.Add((T[h.StampDutyCharged ? "Sales.Totals.StampDutyCharged" : "Sales.Totals.StampDuty"], h.StampDuty, false)); + } + + rows.Add((T["Sales.Totals.Total"], h.TotalAmount, !ShowsNet)); + if (h.WithholdingAmount != 0m) + { + rows.Add((T["Sales.Totals.Withholding"], -h.WithholdingAmount, false)); + } + + if (h.EnasarcoAmount != 0m) + { + rows.Add((T["Sales.Totals.Enasarco"], -h.EnasarcoAmount, false)); + } + + if (h.SplitPayment && h.TaxAmount != 0m) + { + rows.Add((T["Sales.Totals.SplitPayment"], -h.TaxAmount, false)); + } + + if (ShowsNet) + { + rows.Add((T["Sales.Totals.Net"], h.NetAmount, true)); + } + + __builder.OpenElement(0, "div"); + __builder.AddAttribute(1, "class", "totals kh-pad"); + foreach (var (label, value, big) in rows) + { + __builder.OpenElement(2, "span"); + __builder.AddAttribute(3, "class", big ? "big" : null); + __builder.AddContent(4, label); + __builder.CloseElement(); + __builder.OpenElement(5, "span"); + __builder.AddContent(6, T.Money(value)); + __builder.CloseElement(); + } + + __builder.CloseElement(); + }; + + private static void Cell(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder, string text, bool numeric) + { + builder.OpenElement(40, "td"); + builder.AddAttribute(41, "class", numeric ? "num" : null); + builder.AddContent(42, text); + builder.CloseElement(); + } + + // ---- Header ----------------------------------------------------------------------------------------------------- + + private IReadOnlyList> ExigibilityChoices => SalesScreens.Choices(T, "Exigibilities"); + + private IReadOnlyList> TransportChoices => SalesScreens.Choices(T, "TransportBy"); + + private DateOnly? TransportDate => H.TransportStart is { } start ? DateOnly.FromDateTime(start) : null; + + private string? TransportTime => H.TransportStart?.ToString("HH:mm", CultureInfo.InvariantCulture); + + private void SetTransportDate(DateOnly? date) => Change(() => + H.TransportStart = date is { } d ? d.ToDateTime(H.TransportStart is { } s ? TimeOnly.FromDateTime(s) : new TimeOnly(8, 0)) : null); + + private void SetTransportTime(string? text) => Change(() => + { + if (TimeOnly.TryParse(text, CultureInfo.InvariantCulture, out var time)) + { + H.TransportStart = (TransportDate ?? Today).ToDateTime(time); + } + }); + + private async Task SetPartyAsync(PartyRow? row) + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _party = row; + await Editor.ApplyPartyAsync(actor, company, Record, row?.Id); + MarkModified(); + await PreviewNowAsync(); + StateHasChanged(); + } + + private async Task> SearchPartiesAsync(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 void OpenParty(PartyRow row) => Navigation.NavigateTo(PartyScreens.RecordUrl(PartyArchive.Customers, row.Id)); + + private void Change(Action change) + { + change(); + MarkModified(); + } + + private async Task ChangeAsync(Action change) + { + change(); + MarkModified(); + await PreviewNowAsync(); + } + + private Task SetExigibilityAsync(string? value) => + ChangeAsync(() => H.Exigibility = Enum.TryParse(value, out var exigibility) ? exigibility : null); + + private void SetTransportBy(string? value) => + Change(() => H.TransportBy = Enum.TryParse(value, out var by) ? by : null); + + private void SetCurrency(string? code) => Change(() => H.CurrencyCode = code ?? "EUR"); + + private void SetAttachments(int count) => _attachments = count; + + private string? FieldLabel(string field) + { + var key = "Sales.Fields." + field.Split('.')[^1]; + return T.Contains(key) ? T[key] : null; + } + + // ---- Save and delete -------------------------------------------------------------------------------------------- + + /// + protected override async Task SaveCoreAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _busy) + { + return false; + } + + _busy = true; + Validation.Clear(); + try + { + if (_typedCodes.Count > 0) + { + await ResolveCodesAsync(); + } + + var wasNew = IsNew; + Record = await Engine.SaveAsync(actor, company, Record); + await LoadSideAsync(actor, company); + if (wasNew && SalesScreens.RecordUrl(Record.Header.Kind, Record.Header.Id) is { } url) + { + MarkSaved(); + _shown = (Segment, Record.Header.Id, TypeCode); + Navigation.NavigateTo(url, new NavigationOptions { ReplaceHistoryEntry = true }); + } + + return true; + } + catch (ValidationFailedException ex) + { + Refuse(ex.Errors); + return false; + } + catch (InvalidDocumentActionException) + { + Toasts.Show(ToastKind.Error, T[InvalidDocumentActionException.Code]); + return false; + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + return false; + } + finally + { + _busy = false; + } + } + + private void Refuse(IEnumerable errors) + { + foreach (var (field, code) in errors.Select(TableValues.SplitError)) + { + Validation.Add(field, Message(code)); + } + + // Show the tab of the first error when the open one has none. + if (!Validation.Messages.Any(m => TabOfField(m.Field) == ActiveTab) && Validation.Messages is [var first, ..]) + { + _ = ShowTabAsync(TabOfField(first.Field)); + } + + // Errors without a field have nowhere to show: a message says them. + foreach (var message in Validation.Messages.Where(m => string.IsNullOrEmpty(m.Field))) + { + Toasts.Show(ToastKind.Error, message.Message); + } + } + + private string Message(string code) => T.Contains(code) ? T[code] : T["CompanyTables.UnknownError"]; + + /// + protected override async Task DeleteCoreAsync() + { + if (Record is not { Header.Id: > 0 } record || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _section is null) + { + return; + } + + await RunAsync(async () => + { + await Engine.DeleteAsync(actor, company, record.Family, record.Header.Id); + Navigation.NavigateTo(SalesScreens.RadarUrl(_section)); + }); + } + + /// + protected override Task RadarAsync() + { + if (_section is not null) + { + Navigation.NavigateTo(SalesScreens.RadarUrl(_section)); + } + + return Task.CompletedTask; + } + + /// + protected override Task AttachmentsAsync() => ShowTabAsync(TabIds.Attachments); + + /// + protected override async Task PrintAsync() + { + // The preview prints what is saved: a new or changed document is saved first. + if (_section is null || Record is null || ((IsNew || IsModified) && !await SaveAsync()) || Record.Header.Id == 0) + { + return; + } + + Navigation.NavigateTo(SalesScreens.PrintUrl(_section, Record.Header.Id)); + } + + // ---- Actions ---------------------------------------------------------------------------------------------------- + + /// + protected override IEnumerable ContextActions() + { + if (Record is null || _definition is null) + { + yield break; + } + + var confirm = _definition.ConfirmAction; + if (_actions.Contains(confirm)) + { + yield return new ToolbarItem("confirm", "send", T[confirm == DocumentAction.Issue ? "Sales.Actions.Issue" : "Sales.Actions.Confirm"]) + { + Kind = ToolbarKind.Action, Primary = !IsModified, Disabled = _busy, OnClick = ConfirmAsync, + }; + } + + var targets = Targets().ToList(); + for (var i = 0; i < targets.Count; i++) + { + var target = targets[i]; + yield return new ToolbarItem("to-" + target.Code, "copy", T.Format("Sales.Actions.Create", target.Type.Description)) + { + Kind = i == 0 ? ToolbarKind.Action : ToolbarKind.Menu, Disabled = _busy || IsModified || IsNew, OnClick = () => OpenTransformAsync(target), + }; + } + } + + /// + protected override IEnumerable MenuCommands() + { + if (Record is null || _definition is null) + { + yield break; + } + + if (!IsReadOnly && Behavior.Lines.Contains(DocumentLineKind.Expense)) + { + yield return new ToolbarItem("add-expense", "plus", T["Sales.Actions.AddExpense"]) + { + Kind = ToolbarKind.Menu, OnClick = () => AddKindLineAsync(DocumentLineKind.Expense), + }; + yield return new ToolbarItem("add-discount", "minus", T["Sales.Actions.AddDiscount"]) + { + Kind = ToolbarKind.Menu, OnClick = () => AddKindLineAsync(DocumentLineKind.Discount), + }; + } + + if (IsNew) + { + yield break; + } + + if (_actions.Contains(DocumentAction.Copy)) + { + yield return new ToolbarItem("duplicate", "copy", T["Sales.Actions.Duplicate"]) + { + Kind = ToolbarKind.Menu, Disabled = _busy || IsModified, OnClick = () => OpenTransformAsync(_definition), + }; + } + + yield return new ToolbarItem("send-mail", "mail", T["Sales.Mail.Title"]) + { + Kind = ToolbarKind.Menu, Disabled = _busy || IsModified, OnClick = OpenMailAsync, + }; + + if (_actions.Contains(DocumentAction.Close)) + { + yield return new ToolbarItem("close", "check-circle", T[H.Kind == DocumentKind.Quotation ? "Sales.Actions.Refuse" : "Sales.Actions.Close"]) + { + Kind = ToolbarKind.Menu, Disabled = _busy || IsModified, OnClick = () => ChangeStateAsync(DocumentAction.Close), + }; + } + + if (_actions.Contains(DocumentAction.Reopen)) + { + yield return new ToolbarItem("reopen", "refresh", T["Sales.Actions.Reopen"]) + { + Kind = ToolbarKind.Menu, Disabled = _busy || IsModified, OnClick = () => ChangeStateAsync(DocumentAction.Reopen), + }; + } + + if (_actions.Contains(DocumentAction.Cancel)) + { + yield return new ToolbarItem("cancel-document", "x-circle", T["Sales.Actions.Cancel"]) + { + Kind = ToolbarKind.Menu, Danger = true, Disabled = _busy || IsModified, OnClick = OpenCancel, + }; + } + } + + // The sales types that can come from this document (order from a quotation, invoice from a delivery note...). + private IEnumerable Targets() + { + if (Record is null || IsNew || !_actions.Contains(DocumentAction.Copy)) + { + return []; + } + + // An order-like document gives what is left to fulfil; an issued invoice gives its notes. + var open = H.Status is DocumentStatus.Confirmed or DocumentStatus.PartiallyFulfilled; + var issued = Behavior.Lifecycle == DocumentLifecycle.Invoice && DocumentStateMachine.IsInForce(H.Status); + var preferred = SalesScreens.Sections.SelectMany(s => s.NewTypes).ToList(); + return _definitions + .Where(d => d.Behavior.Direction == DocumentDirection.Sale && d.Behavior.Fulfils(H.Kind) && preferred.Contains(d.Code) + && Session.Permissions.Allows(d.Behavior.WritePermission) + && (d.Kind is DocumentKind.CreditNote or DocumentKind.DebitNote ? issued : open)) + .OrderBy(d => Preference(H.Kind, d.Kind)) + .ThenBy(d => preferred.IndexOf(d.Code)); + } + + // The usual next step first: order after quotation, delivery note after order, deferred invoice after delivery note. + private static int Preference(DocumentKind source, DocumentKind target) => (source, target) switch + { + (DocumentKind.Quotation, DocumentKind.SalesOrder) => 0, + (DocumentKind.SalesOrder, DocumentKind.DeliveryNote) => 0, + (DocumentKind.DeliveryNote, DocumentKind.DeferredInvoice) => 0, + (DocumentKind.ProForma, DocumentKind.ImmediateInvoice) => 0, + (_, DocumentKind.CreditNote) => 0, + _ => 1, + }; + + private Task OpenTransformAsync(DocumentDefinition target) + { + if (Record is null) + { + return Task.CompletedTask; + } + + var fulfils = target.Behavior.Fulfils(H.Kind); + var lines = Record.Lines.Where(l => target.Behavior.Lines.Contains(l.Kind)).ToList(); + var selected = lines.Where(l => !fulfils || !DocumentLine.CarriesQuantity(l.Kind) || l.Residual > 0m).Select(l => l.Id).ToHashSet(); + _transform = new TransformRequest(target, T.Format("Sales.Actions.Create", target.Type.Description), + T[fulfils ? "Sales.Transform.LeadFulfil" : "Sales.Transform.LeadCopy"], lines, selected, fulfils); + StateHasChanged(); + return Task.CompletedTask; + } + + private void ToggleLine(long id, bool on) + { + if (_transform is null) + { + return; + } + + if (on) + { + _transform.Selected.Add(id); + } + else + { + _transform.Selected.Remove(id); + } + } + + private void ToggleAllLines(ChangeEventArgs e) + { + if (_transform is null) + { + return; + } + + _transform.Selected.Clear(); + if (e.Value is true) + { + _transform.Selected.UnionWith(_transform.Lines.Select(l => l.Id)); + } + } + + private async Task TransformAsync() + { + if (_transform is not { } request || Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + await RunAsync(async () => + { + var all = request.Selected.Count == request.Lines.Count; + var copy = await Copies.CopyAsync(actor, company, Record.Family, H.Id, request.Target.Code, all ? null : request.Selected); + _transform = null; + Toasts.Show(ToastKind.Success, T.Format("Sales.Transform.Created", request.Target.Type.Description)); + if (SalesScreens.RecordUrl(copy.Header.Kind, copy.Header.Id) is { } url) + { + Navigation.NavigateTo(url); + } + }); + } + + private async Task ConfirmAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company || _definition is null) + { + return; + } + + if (IsModified && !await SaveAsync()) + { + return; + } + + var issue = _definition.ConfirmAction == DocumentAction.Issue; + if (issue && !await Dialogs.ConfirmAsync(new(T["Sales.Actions.Issue"], T["Sales.Confirm.IssueText"], T["Sales.Actions.Issue"], T["Common.Cancel"]))) + { + return; + } + + await RunAsync(async () => + { + Record = await Engine.ConfirmAsync(actor, company, Record.Family, H.Id); + await LoadSideAsync(actor, company); + Toasts.Show(ToastKind.Success, T.Format(issue ? "Sales.Confirm.Issued" : "Sales.Confirm.Confirmed", H.DocumentNumber ?? string.Empty)); + }); + } + + private async Task ChangeStateAsync(DocumentAction action) + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + await RunAsync(async () => + { + Record = action == DocumentAction.Close + ? await Engine.CloseAsync(actor, company, Record.Family, H.Id) + : await Engine.ReopenAsync(actor, company, Record.Family, H.Id); + await LoadSideAsync(actor, company); + Toasts.Show(ToastKind.Success, T["Sales.States." + H.Status]); + }); + } + + // The message proposed from the template and the e-mail of the customer. + private async Task OpenMailAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + await RunAsync(async () => + { + var draft = await Mails.DraftAsync(actor, company, Record.Family, H.Id); + (_mailTo, _mailSubject, _mailBody) = (draft.To, draft.Subject, draft.Body); + _mailValidation.Clear(); + _mailing = true; + }); + } + + private async Task SendMailAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _mailValidation.Clear(); + _busy = true; + try + { + await Mails.SendAsync(actor, company, Record.Family, H.Id, new DocumentMailDraft(_mailTo ?? string.Empty, _mailSubject ?? string.Empty, _mailBody ?? string.Empty)); + _mailing = false; + Toasts.Show(ToastKind.Success, T["Sales.Mail.Queued"], T.Format("Sales.Mail.QueuedDetail", _mailTo ?? string.Empty)); + Record = await Engine.GetAsync(actor, company, Record.Family, H.Id) ?? Record; + await LoadSideAsync(actor, company); + } + catch (ValidationFailedException ex) + { + foreach (var error in ex.Errors) + { + var split = error.IndexOf(':', StringComparison.Ordinal); + var field = split > 0 ? error[..split] : null; + var code = error[(split + 1)..]; + if (field is null) + { + Toasts.Show(ToastKind.Error, T["Sales.Mail.Title"], T[code]); + } + else + { + _mailValidation.Add(field, T[code]); + } + } + } + catch (Exception ex) when (ex is AccessDeniedException or KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T["Sales.Mail.Title"], T[DocumentErrors.NotFound]); + } + finally + { + _busy = false; + } + } + + private Task OpenCancel() + { + _cancelReason = null; + _cancelValidation.Clear(); + _cancelling = true; + StateHasChanged(); + return Task.CompletedTask; + } + + private async Task CancelDocumentAsync() + { + if (Record is null || Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _cancelValidation.Clear(); + if (Behavior.Lifecycle == DocumentLifecycle.Invoice && string.IsNullOrWhiteSpace(_cancelReason)) + { + _cancelValidation.Add("CancelReason", T[DocumentErrors.CancelReasonRequired]); + return; + } + + await RunAsync(async () => + { + Record = await Engine.CancelAsync(actor, company, Record.Family, H.Id, _cancelReason); + _cancelling = false; + await LoadSideAsync(actor, company); + Toasts.Show(ToastKind.Success, T["Sales.States." + H.Status]); + }); + } + + // Runs an action of the engine and reports its refusal. + private async Task RunAsync(Func action) + { + _busy = true; + try + { + await action(); + } + catch (ValidationFailedException ex) + { + Validation.Clear(); + Refuse(ex.Errors); + } + catch (InvalidDocumentActionException) + { + Toasts.Show(ToastKind.Error, T[InvalidDocumentActionException.Code]); + } + catch (ConcurrencyException) + { + Toasts.Show(ToastKind.Error, T["CompanyTables.NotSaved"], T["CompanyTables.Concurrency"]); + } + catch (KeyNotFoundException) + { + Toasts.Show(ToastKind.Error, T[DocumentErrors.NotFound]); + } + finally + { + _busy = false; + StateHasChanged(); + } + } + + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + _preview?.Cancel(); + _preview?.Dispose(); + } + + base.Dispose(disposing); + } + + /// The lines offered when a document becomes another one. + private sealed record TransformRequest(DocumentDefinition Target, string Title, string Lead, IReadOnlyList Lines, HashSet Selected, bool Fulfils); +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor new file mode 100644 index 0000000..1d436bc --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesDocumentsPage.razor @@ -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. *@ + + +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +

@T["Sales.NoCompany"]

+} +else if (_section is null) +{ +

@T["Pages.NotFound.Title"]

+} +else if (!CanRead) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+
+} +else +{ + + + @if (NewTypes.Count > 0) + { + + } + @if (_section.Segment == "fatture" && Session.Permissions.Allows("sales.invoice.write")) + { + @T["Sales.Deferred.Title"] + } + + + + + +
+ @foreach (var type in NewTypes) + { + + } +
+
+
+} + +@code { + private SalesSection? _section; + private IReadOnlyList _definitions = []; + private bool _loaded; + private bool _choosing; + + /// The radar segment, such as fatture. + [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 NewTypes => _section is null ? [] : + [.. _section.NewTypes.Select(code => _definitions.FirstOrDefault(d => d.Code == code)).OfType() + .Where(d => Session.Permissions.Allows(d.Behavior.WritePermission))]; + + private IReadOnlyList> 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 => @@StateOf(r).Text, + }, + ]; + + private IReadOnlyList QuickFilters + { + get + { + var filters = new List + { + new("status", T["Sales.Radar.State"], [new(string.Empty, T["Sales.Radar.All"]), .. States.Select(s => new KhOption(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(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((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 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]; + + /// + 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> 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([], 0, new Dictionary())); + + 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)); + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor b/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor new file mode 100644 index 0000000..d6c7b9d --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Sales/SalesPrintPage.razor @@ -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. *@ + + +@if (_model is null) +{ +
+ +

@(_missing ? T["Sales.NotFound"] : T["Common.Loading"])

+
+} +else +{ +
+
+
@_model.Title @_model.Number › @T["Sales.Print.Title"]
+

@Heading

+
+
+ + +
+
+ @if (_model.LogoAttachmentId is { } logo) + { + + } +
+
@_model.Company.Name
+ @foreach (var line in _model.Company.Lines) + { +
@line
+ } +
+
+
+
@_model.Title
+
@_model.Number
+
@_model.Date
+ @if (_model.Watermark is { } mark) + { +
@mark
+ } +
+
+ +
+
+ @foreach (var field in _model.Fields) + { +
@field.Label
+
@field.Value
+ } +
+
+
@_model.PartyLabel @_model.Party.Code
+ @_model.Party.Name + @foreach (var line in _model.Party.Lines) + { +
@line
+ } +
+
+ + + + + @for (var i = 0; i < _model.LineHeaders.Count; i++) + { + + } + + + + @foreach (var line in _model.Lines) + { + if (line.IsDescription) + { + + } + else + { + + + + + + + + + + + } + } + +
@_model.LineHeaders[i]
@line.Description
@line.Code@line.Description@line.Unit@line.Quantity@line.Price@line.Discount@line.Tax@line.Amount
+ + @foreach (var note in _model.Notes) + { +

@note

+ } + +
+
+ @if (_model.Summary is { } summary) + { + @Table(summary) + } + @if (_model.Installments is { } installments) + { + @Table(installments) + } +
+
+ @foreach (var row in _model.Totals) + { + @row.Label + @row.Value + } +
+
+ + @if (_model.Transport.Count > 0) + { +
+ @foreach (var field in _model.Transport) + { +
@field.Label
@field.Value
+ } +
+
+ @foreach (var signature in _model.Signatures) + { +
@signature
+ } +
+ } + + @if (_model.Footer is { } footer) + { +

@footer

+ } +
+} + +@code { + private SalesSection? _section; + private DocumentPrintModel? _model; + private bool _missing; + private bool _saving; + + /// The radar segment, such as fatture. + [Parameter] + public string? Segment { get; set; } + + /// The document. + [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); + + /// + 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 => + { +
+
@table.Title
+ + + + @for (var i = 0; i < table.Headers.Count; i++) + { + + } + + + + @foreach (var row in table.Rows) + { + + @for (var i = 0; i < row.Count; i++) + { + + } + + } + +
@table.Headers[i]
@row[i]
+
+ }; +} diff --git a/src/Khaemhat.Web/Documents/DocumentLookups.cs b/src/Khaemhat.Web/Documents/DocumentLookups.cs new file mode 100644 index 0000000..33244b9 --- /dev/null +++ b/src/Khaemhat.Web/Documents/DocumentLookups.cs @@ -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; + +/// +/// 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 code · description. +/// +public sealed class DocumentLookups +{ + /// No choices, before loading. + public static DocumentLookups Empty { get; } = new(); + + /// Payment terms. + public IReadOnlyList> PaymentTerms { get; private init; } = []; + + /// Payment methods. + public IReadOnlyList> PaymentMethods { get; private init; } = []; + + /// Price lists. + public IReadOnlyList> PriceLists { get; private init; } = []; + + /// Salespeople. + public IReadOnlyList> Salespeople { get; private init; } = []; + + /// The company bank accounts. + public IReadOnlyList> BankAccounts { get; private init; } = []; + + /// Warehouses. + public IReadOnlyList> Warehouses { get; private init; } = []; + + /// Carriers. + public IReadOnlyList> Carriers { get; private init; } = []; + + /// Shipping terms (porto). + public IReadOnlyList> ShippingTerms { get; private init; } = []; + + /// Reasons of transport. + public IReadOnlyList> TransportReasons { get; private init; } = []; + + /// Appearances of the goods. + public IReadOnlyList> GoodsAppearances { get; private init; } = []; + + /// VAT codes. + public IReadOnlyList> TaxCodes { get; private init; } = []; + + /// Units of measure. + public IReadOnlyList> Units { get; private init; } = []; + + /// Currencies, by code. + public IReadOnlyList> Currencies { get; private init; } = []; + + /// Reads the choices. + /// The tables. + /// Who reads. + /// The company. + /// Cancellation. + /// The choices. + public static async Task ReadAsync(TableService tables, Actor actor, string company, CancellationToken cancellationToken = default) => new() + { + PaymentTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + PaymentMethods = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + PriceLists = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Salespeople = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + BankAccounts = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Warehouses = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Carriers = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + ShippingTerms = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + TransportReasons = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + GoodsAppearances = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + TaxCodes = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Units = await ReadAsync(tables, actor, company, false, cancellationToken).ConfigureAwait(false), + Currencies = await ReadAsync(tables, actor, company, true, cancellationToken).ConfigureAwait(false), + }; + + /// The code of a choice (the part before · ). + /// The choices. + /// The id. + /// The code, or . + public static string? CodeOf(IReadOnlyList> 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]; + } + + /// The id of the choice with a code, ignoring case. + /// The choices. + /// The code typed. + /// The id, or . + public static long? IdOf(IReadOnlyList> 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>> ReadAsync(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(c.Value, c.Text))]; + } +} diff --git a/src/Khaemhat.Web/Documents/SalesScreens.cs b/src/Khaemhat.Web/Documents/SalesScreens.cs new file mode 100644 index 0000000..6f05be7 --- /dev/null +++ b/src/Khaemhat.Web/Documents/SalesScreens.cs @@ -0,0 +1,144 @@ +using System.Globalization; +using Khaemhat.Application.Localization; +using Khaemhat.Core.Documents; +using Khaemhat.Web.Ui; + +namespace Khaemhat.Web.Documents; + +/// A radar of the sales menu and the document types it holds. +/// The path segment, such as fatture. +/// The family of the documents. +/// The kinds shown. +/// The document types a user can create from the radar, the first being the usual one. +/// The icon. +/// The key of the texts under Sales.Sections. +public sealed record SalesSection(string Segment, DocumentFamily Family, IReadOnlyList Kinds, IReadOnlyList NewTypes, string Icon, string Key); + +/// +/// Addresses and labels of the sales screens (SPEC §11.3, mockups 020-030): one radar per menu entry under +/// /vendite, the record of a document under it, and the deferred invoicing. +/// +public static class SalesScreens +{ + /// The menu area. + public const string BasePath = "vendite"; + + /// The deferred invoicing of the delivery notes. + public const string DeferredInvoicingUrl = BasePath + "/fatturazione-differita"; + + /// The tab of the transport data, after Testata, for delivery notes and accompanying invoices. + public const string TransportTab = "trasporto"; + + /// The radars, in the order of the menu. + public static IReadOnlyList 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"), + ]; + + /// The radar of a path segment. + /// The segment. + /// The radar, or . + public static SalesSection? Find(string? segment) => Sections.FirstOrDefault(s => string.Equals(s.Segment, segment, StringComparison.OrdinalIgnoreCase)); + + /// The radar that holds a kind of document. + /// The kind. + /// The radar, or for a kind outside sales. + public static SalesSection? Of(DocumentKind kind) => Sections.FirstOrDefault(s => s.Kinds.Contains(kind)); + + /// The address of a radar. + /// The radar. + /// The address. + public static string RadarUrl(SalesSection section) + { + ArgumentNullException.ThrowIfNull(section); + return BasePath + "/" + section.Segment; + } + + /// The address of a document. + /// The kind. + /// The document. + /// The address, or for a kind outside sales. + public static string? RecordUrl(DocumentKind kind, long id) => + Of(kind) is { } section ? RadarUrl(section) + "/" + id.ToString(CultureInfo.InvariantCulture) : null; + + /// The address of a new document of a type. + /// The radar. + /// The document type. + /// The address. + public static string NewUrl(SalesSection section, string typeCode) => RadarUrl(section) + "/nuovo?tipo=" + Uri.EscapeDataString(typeCode); + + /// The print preview of a document. + /// The radar. + /// The document. + /// The relative URL. + public static string PrintUrl(SalesSection section, long id) + { + ArgumentNullException.ThrowIfNull(section); + return RadarUrl(section) + "/" + id.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/stampa"; + } + + /// The name of a kind, such as Fattura immediata. + /// The texts. + /// The kind. + /// The name. + public static string KindName(ITexts texts, DocumentKind kind) + { + ArgumentNullException.ThrowIfNull(texts); + return texts["Sales.Kinds." + kind]; + } + + /// The label and tone of a state; a quotation shows its outcome (accepted, refused, expired). + /// The texts. + /// The kind. + /// The state. + /// Until when a quotation is valid. + /// Today. + /// The label and the tone. + 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); + } + + /// The choices of an enumeration, labelled from Sales.{group}.{value}. + /// The enumeration. + /// The texts. + /// The group of texts. + /// The choices. + public static IReadOnlyList> Choices(ITexts texts, string group) + where TEnum : struct, Enum + { + ArgumentNullException.ThrowIfNull(texts); + return [.. Enum.GetValues().Select(v => new KhOption(v.ToString(), texts["Sales." + group + "." + v]))]; + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 448f38a..142c091 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -176,6 +176,8 @@ internal static class KhaemhatServices // Companies and start. services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); @@ -226,6 +228,23 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + // 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(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddHostedService(sp => sp.GetRequiredService()); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs index 80edc9a..0972cd0 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -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().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Documents.json b/src/Khaemhat.Web/Resources/it-IT/Documents.json index 5506e0f..6ac2981 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Documents.json +++ b/src/Khaemhat.Web/Resources/it-IT/Documents.json @@ -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.", diff --git a/src/Khaemhat.Web/Resources/it-IT/Files.json b/src/Khaemhat.Web/Resources/it-IT/Files.json index 90ea636..80ad3fc 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Files.json +++ b/src/Khaemhat.Web/Resources/it-IT/Files.json @@ -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)" diff --git a/src/Khaemhat.Web/Resources/it-IT/Parties.json b/src/Khaemhat.Web/Resources/it-IT/Parties.json index 8fbdeb5..c0508da 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Parties.json +++ b/src/Khaemhat.Web/Resources/it-IT/Parties.json @@ -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", diff --git a/src/Khaemhat.Web/Resources/it-IT/Print.json b/src/Khaemhat.Web/Resources/it-IT/Print.json new file mode 100644 index 0000000..02377e6 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Print.json @@ -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." + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Sales.json b/src/Khaemhat.Web/Resources/it-IT/Sales.json new file mode 100644 index 0000000..1c01d68 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Sales.json @@ -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" + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index c4de263..c52ec32 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -67,7 +67,8 @@ "Orders": "Ordini clienti", "DeliveryNotes": "DDT", "Invoices": "Fatture", - "CreditNotes": "Note di credito" + "CreditNotes": "Note di credito", + "DeferredInvoicing": "Fatturazione differita" }, "Purchases": { "_": "Acquisti", diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 2c9d753..4c5b190 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -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", diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index c5b6f1d..fd3c6d3 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -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; } diff --git a/tests/Khaemhat.Web.Tests/Documents/DemoSalesTests.cs b/tests/Khaemhat.Web.Tests/Documents/DemoSalesTests.cs new file mode 100644 index 0000000..2d7096f --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Documents/DemoSalesTests.cs @@ -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; + +/// The demo sales (SPEC §14, issue #53): every kind of sales document, in every state, made through the engine. +[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().RunAsync(company, SeedKind.Demo); + var seeder = app.Services.GetRequiredService(); + var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true); + await seeder.SeedAsync(company, context); + + var editor = app.Services.GetRequiredService(); + 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().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> AllAsync(DocumentEditor editor, string company) + { + var all = new List(); + foreach (var family in new[] { DocumentFamily.SaleQuotation, DocumentFamily.SaleOrder, DocumentFamily.SaleDocument }) + { + all.AddRange((await editor.ListAsync(Root, company, family, [.. Enum.GetValues()], new ListQuery { Limit = 200 })).Items); + } + + return all; + } +} diff --git a/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs index ffc102a..6171280 100644 --- a/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs +++ b/tests/Khaemhat.Web.Tests/Documents/DocumentEngineTests.cs @@ -29,13 +29,14 @@ public sealed class DocumentEngineTests var sales = app.Services.GetRequiredService>(); var copies = app.Services.GetRequiredService(); 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(); var sales = app.Services.GetRequiredService>(); 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(() => 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(() => 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> NewInvoiceAsync( - DocumentService sales, string company, long customer, DateOnly date, bool lines = true) + DocumentService 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> InvoiceAsync( - DocumentService sales, string company, long customer, DateOnly date) => - await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, date)); + DocumentService sales, string company, long customer, long vat, DateOnly date) => + await sales.SaveAsync(Root, company, await NewInvoiceAsync(sales, company, customer, vat, date)); private static DocumentRecord Typed(DocumentRecord record) => new() { Header = (SaleDocument)record.Header, Lines = [.. record.Lines.Cast()] }; + private static async Task VatAsync(WebApplication app, string company) => + (await app.Services.GetRequiredService().ActiveAsync(Root, company)).Single(t => t.Code == "22").Id; + private static async Task CustomerAsync(WebApplication app, string company) { var parties = app.Services.GetRequiredService(); diff --git a/tests/Khaemhat.Web.Tests/Documents/DocumentPrintMailTests.cs b/tests/Khaemhat.Web.Tests/Documents/DocumentPrintMailTests.cs new file mode 100644 index 0000000..59b3389 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Documents/DocumentPrintMailTests.cs @@ -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; + +/// Printing and sending documents (SPEC §9.4, §12.6, issue #52): the print model, the PDF, MIME, SMTP and the queue. +[TestClass] +public sealed class DocumentPrintMailTests +{ + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public void Template_FillsKnownFields_AndKeepsUnknownOnes() + { + var text = MailTemplateRenderer.Render("{{Documento}} n. {{ numero }} per {{Cliente}} {{Sconosciuto}}", new Dictionary + { + ["Documento"] = "Fattura", + ["Numero"] = "7/2026", + ["Cliente"] = null, + }); + + Assert.AreEqual("Fattura n. 7/2026 per {{Sconosciuto}}", text); + } + + [TestMethod] + public void Mime_WritesTextAndAttachmentInBase64() + { + var mail = new OutgoingMail(["a@example.com", "b@example.com"], "Fattura n. 7 · Granai", "Buongiorno,\nin allegato.") + { + Attachments = [new MailAttachment("fattura-7.pdf", "application/pdf", Encoding.ASCII.GetBytes("%PDF-1.7 test"))], + }; + + var text = MimeMessageWriter.Write(mail, "Granai ", new DateTimeOffset(2026, 3, 2, 9, 30, 0, TimeSpan.FromHours(1)), "BOUNDARY"); + + StringAssert.Contains(text, "To: a@example.com, b@example.com\r\n"); + StringAssert.Contains(text, "Subject: =?utf-8?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes("Fattura n. 7 · Granai")) + "?=\r\n"); + StringAssert.Contains(text, "Date: Mon, 02 Mar 2026 09:30:00 +0100\r\n"); + StringAssert.Contains(text, "Content-Type: multipart/mixed; boundary=\"BOUNDARY\""); + StringAssert.Contains(text, Convert.ToBase64String(Encoding.UTF8.GetBytes("Buongiorno,\r\nin allegato."))); + StringAssert.Contains(text, "Content-Disposition: attachment; filename=\"fattura-7.pdf\""); + StringAssert.Contains(text, Convert.ToBase64String(Encoding.ASCII.GetBytes("%PDF-1.7 test"))); + Assert.IsTrue(text.EndsWith("--BOUNDARY--\r\n", StringComparison.Ordinal)); + Assert.AreEqual("plain", MimeMessageWriter.EncodeHeader("plain")); + } + + [TestMethod] + public async Task Smtp_SendsTheMessage_ThroughTheDialogue() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var server = Task.Run(() => FakeServerAsync(listener)); + + var settings = new SmtpSettings("127.0.0.1", port, "demo", "test-only", "Granai ", SmtpTransportSecurity.None); + var sender = new SmtpMailSender(settings, TimeProvider.System); + await sender.SendAsync(new OutgoingMail(["cliente@example.com"], "Prova", "Testo") { Cc = ["copia@example.com"] }); + + var (commands, data) = await server; + Assert.IsTrue(commands[0].StartsWith("EHLO ", StringComparison.Ordinal)); + Assert.AreEqual("AUTH PLAIN " + Convert.ToBase64String(Encoding.UTF8.GetBytes("\0demo\0test-only")), commands[1]); + CollectionAssert.Contains(commands, "MAIL FROM:"); + CollectionAssert.Contains(commands, "RCPT TO:"); + CollectionAssert.Contains(commands, "RCPT TO:"); + Assert.AreEqual("QUIT", commands[^1]); + StringAssert.Contains(data, "Subject: Prova"); + StringAssert.Contains(data, "Cc: copia@example.com"); + } + + [TestMethod] + public async Task Smtp_UnreachableServer_IsAMailException() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + + var sender = new SmtpMailSender(new SmtpSettings("127.0.0.1", port, null, null, "ufficio@example.com", SmtpTransportSecurity.None), TimeProvider.System); + await Assert.ThrowsExactlyAsync(() => sender.SendAsync(new OutgoingMail(["a@example.com"], "Prova", "Testo"))); + await Assert.ThrowsExactlyAsync(() => new SmtpMailSender(new SmtpSettings(null, 25, null, null, null, SmtpTransportSecurity.None), TimeProvider.System) + .SendAsync(new OutgoingMail(["a@example.com"], "Prova", "Testo"))); + } + + [TestMethod] + public async Task Invoice_PrintsToPdf_AndLeavesByMail() + { + var queue = new FakeQueue(); + var (app, _, company) = await TestInstance.StartAsync(services => services.AddSingleton(queue), CancellationToken.None); + await using (app) + { + await app.Services.GetRequiredService().RunAsync(company, SeedKind.Demo); + await app.Services.GetRequiredService().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true)); + var editor = app.Services.GetRequiredService(); + var engine = app.Services.GetRequiredService(); + var invoices = await editor.ListAsync(Root, company, DocumentFamily.SaleDocument, [DocumentKind.ImmediateInvoice], new ListQuery { Limit = 50 }); + var invoice = invoices.Items.First(r => r.Status == DocumentStatus.Issued); + var family = DocumentFamily.SaleDocument; + + // The model: every label comes from the resources, the lines and the totals are there. + var model = await app.Services.GetRequiredService().BuildAsync(Root, company, family, invoice.Id); + Assert.AreEqual(invoice.DocumentNumber, model.Number); + Assert.IsNotNull(model.Watermark, "A document of the demo says so on the sheet."); + Assert.IsNotEmpty(model.Lines); + Assert.IsNotNull(model.Summary, "The VAT summary."); + var texts = new[] { model.Title, model.PartyLabel }.Concat(model.LineHeaders).Concat(model.Fields.Select(f => f.Label)).Concat(model.Totals.Select(t => t.Label)); + Assert.IsFalse(texts.Any(t => t.StartsWith('[')), "Missing keys: " + string.Join(", ", texts.Where(t => t.StartsWith('[')))); + Assert.AreEqual("sales.saledocument", DocumentPrintService.EntityOf(family)); + Assert.AreEqual(family, DocumentPrintService.FamilyOf("sales.saledocument")); + + // The PDF, kept among the attachments. + var generated = await app.Services.GetRequiredService() + .GenerateAsync(Root, company, DocumentPrintService.EntityOf(family), invoice.Id, DocumentPdfGenerator.GeneratorCode); + Assert.AreEqual("application/pdf", generated.Mime); + Assert.IsTrue(generated.FileName.EndsWith(".pdf", StringComparison.Ordinal)); + var pdf = await ReadAsync(app.Services.GetRequiredService(), company, generated.Id); + Assert.AreEqual("%PDF", Encoding.ASCII.GetString(pdf, 0, 4)); + + await engine.MarkPrintedAsync(Root, company, family, invoice.Id); + Assert.IsTrue((await engine.GetAsync(Root, company, family, invoice.Id))!.Header.Printed); + + // The mail: proposed from the template, refused when incomplete, queued with the PDF when complete. + var mails = app.Services.GetRequiredService(); + var draft = await mails.DraftAsync(Root, company, family, invoice.Id); + StringAssert.Contains(draft.Subject, invoice.DocumentNumber!); + Assert.IsFalse(draft.Body.Contains("{{", StringComparison.Ordinal), draft.Body); + + var refused = await Assert.ThrowsExactlyAsync(() => mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "non-un-indirizzo", Subject = " " })); + CollectionAssert.AreEquivalent(new[] { "To:" + DocumentMailErrors.RecipientInvalid, "Subject:" + DocumentMailErrors.SubjectRequired }, refused.Errors.ToList()); + Assert.IsEmpty(queue.Mails); + + await mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "amministrazione@example.com; copia@example.com" }); + var mail = queue.Mails.Single(); + CollectionAssert.AreEqual(new[] { "amministrazione@example.com", "copia@example.com" }, mail.To.ToList()); + Assert.AreEqual("%PDF", Encoding.ASCII.GetString(mail.Attachments.Single().Content, 0, 4)); + Assert.IsTrue((await engine.GetAsync(Root, company, family, invoice.Id))!.Header.Sent); + + queue.Configured = false; + var off = await Assert.ThrowsExactlyAsync(() => mails.SendAsync(Root, company, family, invoice.Id, draft with { To = "a@example.com" })); + CollectionAssert.Contains(off.Errors.ToList(), ":" + DocumentMailErrors.NotConfigured); + await app.StopAsync(); + } + } + + private static async Task ReadAsync(AttachmentService attachments, string company, long id) + { + await using var content = await attachments.OpenAsync(Root, company, id); + using var buffer = new MemoryStream(); + await content.Content.CopyToAsync(buffer); + return buffer.ToArray(); + } + + // A server that says yes to everything and keeps what it receives. + private static async Task<(List Commands, string Data)> FakeServerAsync(TcpListener listener) + { + using var client = await listener.AcceptTcpClientAsync(); + var stream = client.GetStream(); + using var reader = new StreamReader(stream, Encoding.UTF8); + using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\r\n", AutoFlush = true }; + var commands = new List(); + var data = new StringBuilder(); + await writer.WriteLineAsync("220 fake ESMTP"); + while (await reader.ReadLineAsync() is { } line) + { + commands.Add(line); + if (line.StartsWith("EHLO", StringComparison.Ordinal)) + { + await writer.WriteLineAsync("250-fake"); + await writer.WriteLineAsync("250 AUTH PLAIN"); + } + else if (line.StartsWith("AUTH", StringComparison.Ordinal)) + { + await writer.WriteLineAsync("235 ok"); + } + else if (line == "DATA") + { + await writer.WriteLineAsync("354 go on"); + while (await reader.ReadLineAsync() is { } body && body != ".") + { + data.Append(body).Append('\n'); + } + + await writer.WriteLineAsync("250 queued"); + } + else if (line == "QUIT") + { + await writer.WriteLineAsync("221 bye"); + break; + } + else + { + await writer.WriteLineAsync("250 ok"); + } + } + + return (commands, data.ToString()); + } + + private sealed class FakeQueue : IMailQueue + { + public List Mails { get; } = []; + + public bool Configured { get; set; } = true; + + public bool IsConfigured => Configured; + + public bool Enqueue(OutgoingMail mail) + { + Mails.Add(mail); + return true; + } + } +} diff --git a/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs b/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs new file mode 100644 index 0000000..9d97bdb --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Documents/SalesFlowTests.cs @@ -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; + +/// +/// 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. +/// +[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(); + var editor = app.Services.GetRequiredService(); + var tables = app.Services.GetRequiredService(); + var taxes = await tables.ActiveAsync(Root, company); + var terms = await tables.ActiveAsync(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(); + var editor = app.Services.GetRequiredService(); + var copies = app.Services.GetRequiredService(); + 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 + { + 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(() => + 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(() => 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().ActiveAsync(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().Select(k => "Sales.Kinds." + k) + .Concat(Enum.GetValues().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().Select(d => "Sales.Links." + d)) + .Concat(Enum.GetValues().Select(k => "Sales.LineKinds." + k)); + var missing = keys.Where(k => !texts.Contains(k)).ToList(); + Assert.IsEmpty(missing, string.Join(", ", missing)); + } + + private static async Task 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 CustomerAsync(WebApplication app, string company, string name, string vatNumber, long? paymentTermId) + { + var parties = app.Services.GetRequiredService(); + 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; + } +}