Quotations, orders, delivery notes, invoices and credit notes get their radars and one document screen (lines, header, transport, links, attachments) with the transformations of the engine, so a quotation reaches the invoice without retyping. The deferred invoicing groups the open delivery notes of a period by customer, payment and destination into one invoice each. Every document prints from one model: an HTML preview on screen and a PDF drawn by the in-house writer, kept among the attachments as a new version. "Invia per e-mail" proposes recipient, subject and text from the templates, attaches the PDF and hands it to a background queue that talks SMTP itself (no external library); the outcome goes to the log, section E-mail/PEC. The demo company now has a year of sales in every state, made through the engine, and run-dev.sh no longer writes to a stray B:\b folder under Git Bash. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f12848865d
commit
826042f828
31 files changed
+5682
-16
No files matched your search
@@ -173,6 +173,7 @@ public sealed class DocumentCopyService
|
||||
header.DocumentTypeId = target.Type.Id;
|
||||
header.Kind = target.Kind;
|
||||
header.Status = DocumentStatus.Draft;
|
||||
header.IsDemo = source.IsDemo;
|
||||
header.DocumentDate = today;
|
||||
header.Year = today.Year;
|
||||
header.PartyId = source.PartyId;
|
||||
|
||||
@@ -85,6 +85,9 @@ public static class DocumentErrors
|
||||
|
||||
/// <summary>Error: a discount formula that cannot be read.</summary>
|
||||
public const string LineDiscountInvalid = "document.line.discount-invalid";
|
||||
|
||||
/// <summary>Error: a line of an invoice without its VAT code.</summary>
|
||||
public const string LineTaxRequired = "document.line.tax-required";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -290,6 +293,18 @@ public sealed class DocumentEngine
|
||||
errors.Add("Lines:" + DocumentErrors.LinesRequired);
|
||||
}
|
||||
|
||||
if (definition.Behavior.Has(DocumentEffects.Ledger))
|
||||
{
|
||||
// A document that goes to the VAT registers needs the VAT of every line with an amount.
|
||||
for (var i = 0; i < record.Lines.Count; i++)
|
||||
{
|
||||
if (record.Lines[i] is { Kind: not DocumentLineKind.Description, TaxCodeId: null })
|
||||
{
|
||||
errors.Add("Lines." + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "." + nameof(DocumentLine.TaxCodeId) + ":" + DocumentErrors.LineTaxRequired);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.Count > 0 || record.Header.DocumentDate != draft.Header.DocumentDate)
|
||||
{
|
||||
throw errors.Count > 0 ? new ValidationFailedException(errors) : new Core.Common.ConcurrencyException();
|
||||
@@ -400,6 +415,26 @@ public sealed class DocumentEngine
|
||||
}, null, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Records that the document was printed (its PDF kept among the attachments); the state does not change.</summary>
|
||||
/// <param name="actor">Who prints: needs to read the document.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task MarkPrintedAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
|
||||
MarkAsync(actor, companyCode, family, id, h => h.Printed = true, cancellationToken);
|
||||
|
||||
/// <summary>Records that the document was sent by e-mail; the state does not change.</summary>
|
||||
/// <param name="actor">Who sends: needs to read the document.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public Task MarkSentAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default) =>
|
||||
MarkAsync(actor, companyCode, family, id, h => h.Sent = true, cancellationToken);
|
||||
|
||||
/// <summary>Deletes a draft.</summary>
|
||||
/// <param name="actor">Who deletes.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
@@ -641,6 +676,26 @@ public sealed class DocumentEngine
|
||||
return await GetAsync(actor, company, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
|
||||
}
|
||||
|
||||
// Sets an output flag (printed, sent) with its trace in the history, whatever the state.
|
||||
private async Task MarkAsync(Actor actor, string companyCode, DocumentFamily family, long id, Action<DocumentHeader> change, CancellationToken cancellationToken)
|
||||
{
|
||||
var company = Company(actor, companyCode);
|
||||
var store = DocumentStores.Of(family);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var header = await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
|
||||
await _permissions.DemandAsync(actor, DocumentBehaviors.Of(header.Kind).ReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
var old = header.Clone();
|
||||
change(header);
|
||||
if (old.Printed != header.Printed || old.Sent != header.Sent)
|
||||
{
|
||||
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
|
||||
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, header, actor.UserName, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Records the links of a confirmed document towards the lines it fulfils, then the fulfilment of those documents.
|
||||
private async Task LinkAsync(IUnitOfWork uow, DocumentDefinition definition, DocumentRecord record, string userName, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Khaemhat.Application.Files;
|
||||
using Khaemhat.Application.Localization;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Infrastructure.Mail;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>
|
||||
/// Fills a mail template (SPEC §12.6): <c>{{Name}}</c> becomes the value of the field, unknown fields stay as they are
|
||||
/// so that a typing error shows in the message instead of disappearing.
|
||||
/// </summary>
|
||||
public static partial class MailTemplateRenderer
|
||||
{
|
||||
/// <summary>Fills a template.</summary>
|
||||
/// <param name="template">The template.</param>
|
||||
/// <param name="fields">The values by name (case does not matter).</param>
|
||||
/// <returns>The text.</returns>
|
||||
public static string Render(string template, IReadOnlyDictionary<string, string?> fields)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(fields);
|
||||
var lookup = new Dictionary<string, string?>(fields, StringComparer.OrdinalIgnoreCase);
|
||||
return Field().Replace(template, m => lookup.TryGetValue(m.Groups[1].Value, out var value) ? value ?? string.Empty : m.Value);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}", RegexOptions.CultureInvariant, 1000)]
|
||||
private static partial Regex Field();
|
||||
}
|
||||
|
||||
/// <summary>A message about a document, as the user is about to send it.</summary>
|
||||
/// <param name="To">The recipients, separated by commas or semicolons.</param>
|
||||
/// <param name="Subject">The subject.</param>
|
||||
/// <param name="Body">The text.</param>
|
||||
public sealed record DocumentMailDraft(string To, string Subject, string Body);
|
||||
|
||||
/// <summary>The errors of <see cref="DocumentMailService"/> (text keys).</summary>
|
||||
public static class DocumentMailErrors
|
||||
{
|
||||
/// <summary>No SMTP server is configured.</summary>
|
||||
public const string NotConfigured = "document.mail.not-configured";
|
||||
|
||||
/// <summary>No recipient, or one that is not an e-mail address.</summary>
|
||||
public const string RecipientInvalid = "document.mail.recipient-invalid";
|
||||
|
||||
/// <summary>The subject is empty.</summary>
|
||||
public const string SubjectRequired = "document.mail.subject-required";
|
||||
|
||||
/// <summary>The queue is full.</summary>
|
||||
public const string QueueFull = "document.mail.queue-full";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a document by e-mail (SPEC §9.4, §12.6, issue #52): proposes recipient, subject and text from the templates
|
||||
/// (<c>Print.Mail.*</c>) and the e-mail of the party; on sending keeps the PDF as a new version among the attachments,
|
||||
/// attaches it, queues the message and marks the document as sent. The outcome is in the log, section E-mail/PEC.
|
||||
/// </summary>
|
||||
/// <param name="prints">The printed form of documents.</param>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="generation">The generated files (the PDF).</param>
|
||||
/// <param name="attachments">The attachments.</param>
|
||||
/// <param name="queue">The mail queue.</param>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="texts">The texts.</param>
|
||||
public sealed partial class DocumentMailService(
|
||||
DocumentPrintService prints, DocumentEngine engine, FileGenerationService generation, AttachmentService attachments, IMailQueue queue, IUnitOfWorkFactory factory,
|
||||
ITexts texts)
|
||||
{
|
||||
/// <summary>Whether mail can be sent from this instance.</summary>
|
||||
public bool IsConfigured => queue.IsConfigured;
|
||||
|
||||
/// <summary>The message proposed for a document.</summary>
|
||||
/// <param name="actor">Who sends.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The draft.</returns>
|
||||
public async Task<DocumentMailDraft> DraftAsync(Actor actor, string companyCode, DocumentFamily family, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false);
|
||||
var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(DocumentErrors.NotFound);
|
||||
string? email = null;
|
||||
if (record.Header.PartyId is { } partyId)
|
||||
{
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(CompanyCodes.Normalize(companyCode)), cancellationToken).ConfigureAwait(false);
|
||||
email = (await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false))?.Email;
|
||||
}
|
||||
|
||||
var fields = new Dictionary<string, string?>
|
||||
{
|
||||
["Documento"] = model.Title,
|
||||
["Numero"] = model.Number,
|
||||
["Data"] = model.Date,
|
||||
["Cliente"] = model.Party.Name,
|
||||
["Azienda"] = model.Company.Name,
|
||||
["Totale"] = model.Totals.LastOrDefault(t => t.Strong)?.Value,
|
||||
};
|
||||
|
||||
return new DocumentMailDraft(
|
||||
email ?? string.Empty,
|
||||
MailTemplateRenderer.Render(texts["Print.Mail.Subject"], fields),
|
||||
MailTemplateRenderer.Render(texts["Print.Mail.Body"], fields));
|
||||
}
|
||||
|
||||
/// <summary>Sends a document: the PDF becomes a new attachment version and leaves with the message.</summary>
|
||||
/// <param name="actor">Who sends.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="draft">The message.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The PDF attached.</returns>
|
||||
/// <exception cref="ValidationFailedException">The message is not complete, or mail is not configured.</exception>
|
||||
public async Task<AttachmentView> SendAsync(
|
||||
Actor actor, string companyCode, DocumentFamily family, long id, DocumentMailDraft draft, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(draft);
|
||||
var recipients = Recipients(draft.To);
|
||||
var errors = new List<string>();
|
||||
if (!queue.IsConfigured)
|
||||
{
|
||||
errors.Add(":" + DocumentMailErrors.NotConfigured);
|
||||
}
|
||||
|
||||
if (recipients.Count == 0 || !recipients.All(r => Address().IsMatch(r)))
|
||||
{
|
||||
errors.Add(nameof(DocumentMailDraft.To) + ":" + DocumentMailErrors.RecipientInvalid);
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(draft.Subject))
|
||||
{
|
||||
errors.Add(nameof(DocumentMailDraft.Subject) + ":" + DocumentMailErrors.SubjectRequired);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ValidationFailedException(errors);
|
||||
}
|
||||
|
||||
var model = await prints.BuildAsync(actor, companyCode, family, id, null, cancellationToken).ConfigureAwait(false);
|
||||
var pdf = await generation.GenerateAsync(actor, companyCode, DocumentPrintService.EntityOf(family), id, DocumentPdfGenerator.GeneratorCode, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
byte[] bytes;
|
||||
await using (var content = await attachments.OpenAsync(actor, companyCode, pdf.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
bytes = buffer.ToArray();
|
||||
}
|
||||
|
||||
var mail = new OutgoingMail(recipients, draft.Subject.Trim(), draft.Body)
|
||||
{
|
||||
Attachments = [new MailAttachment(pdf.FileName, pdf.Mime, bytes)],
|
||||
Reference = model.Title + " " + model.Number,
|
||||
};
|
||||
|
||||
if (!queue.Enqueue(mail))
|
||||
{
|
||||
throw new ValidationFailedException([":" + DocumentMailErrors.QueueFull]);
|
||||
}
|
||||
|
||||
await engine.MarkSentAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false);
|
||||
return pdf;
|
||||
}
|
||||
|
||||
/// <summary>The addresses of a recipient field (commas, semicolons or spaces between them).</summary>
|
||||
/// <param name="text">The field.</param>
|
||||
/// <returns>The addresses.</returns>
|
||||
public static IReadOnlyList<string> Recipients(string? text) =>
|
||||
string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';', ' ', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
[GeneratedRegex(@"^[^@\s<>]+@[^@\s<>]+\.[^@\s<>]+$", RegexOptions.CultureInvariant, 1000)]
|
||||
private static partial Regex Address();
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
using Khaemhat.Application.Files;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>
|
||||
/// The PDF of a document (SPEC §9.4, issue #52): A4, letterhead with logo and company data, address box, conditions,
|
||||
/// lines over as many pages as needed (the headings repeat), VAT summary, totals, installments, transport and signature
|
||||
/// boxes, notes and footer. Saved as a generated attachment of the document, so every print is a new version and
|
||||
/// <i>Rigenera</i> writes the current state after a change.
|
||||
/// </summary>
|
||||
/// <param name="prints">The printed form of documents.</param>
|
||||
/// <param name="attachments">The attachments (the logo of the company).</param>
|
||||
public sealed class DocumentPdfGenerator(DocumentPrintService prints, AttachmentService attachments) : IFileGenerator
|
||||
{
|
||||
/// <summary>The code of the generator.</summary>
|
||||
public const string GeneratorCode = "documents.pdf";
|
||||
|
||||
private const double Margin = 42;
|
||||
private const double Bottom = 60;
|
||||
private static readonly PdfColor Accent = PdfColor.FromHex("#1F5F8B");
|
||||
private static readonly PdfColor Muted = PdfColor.Gray(105);
|
||||
private static readonly PdfColor Rule = PdfColor.Gray(205);
|
||||
private static readonly PdfColor Band = PdfColor.Gray(238);
|
||||
private static readonly PdfColor Warning = PdfColor.FromHex("#B54708");
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Code => GeneratorCode;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string TitleKey => "files.generators.document_pdf";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string MediaType => PdfWriter.MediaType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Extension => ".pdf";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Supports(string entity) => DocumentPrintService.FamilyOf(entity) is not null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string FileName(FileGenerationContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return Stem(context) + Extension;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false);
|
||||
await WriteAsync(model, context, output, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The file name follows the document (number and kind); without the logo, which the name does not need.
|
||||
private string Stem(FileGenerationContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
return prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId).GetAwaiter().GetResult().FileStem;
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
return "documento-" + context.EntityId.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
|
||||
private static Core.Documents.DocumentFamily FamilyOf(FileGenerationContext context) =>
|
||||
DocumentPrintService.FamilyOf(context.Entity) ?? throw new ValidationFailedException([FileGenerationService.UnknownGeneratorError]);
|
||||
|
||||
private Task<DocumentPrintModel> ModelAsync(FileGenerationContext context, CancellationToken cancellationToken) =>
|
||||
prints.BuildAsync(context.Actor, context.CompanyCode, FamilyOf(context), context.EntityId, (id, ct) => LogoAsync(context, id, ct), cancellationToken);
|
||||
|
||||
// The logo, when it is a JPEG the actor may read; the PDF writer embeds JPEG only.
|
||||
private async Task<byte[]?> LogoAsync(FileGenerationContext context, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var content = await attachments.OpenAsync(context.Actor, context.CompanyCode, id, cancellationToken).ConfigureAwait(false);
|
||||
if (content.Attachment.Mime != "image/jpeg")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var buffer = new MemoryStream();
|
||||
await content.Content.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
return buffer.ToArray();
|
||||
}
|
||||
catch (Exception ex) when (ex is KeyNotFoundException or AccessDeniedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WriteAsync(DocumentPrintModel model, FileGenerationContext context, Stream output, CancellationToken cancellationToken)
|
||||
{
|
||||
var info = new PdfDocumentInfo
|
||||
{
|
||||
Title = model.Title + " " + model.Number,
|
||||
Author = model.Company.Name,
|
||||
Subject = model.Title + " " + model.Number + " · " + model.Party.Name,
|
||||
CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)),
|
||||
};
|
||||
|
||||
await using var pdf = new PdfWriter(output, info, leaveOpen: true);
|
||||
var sheet = new Sheet(pdf, model, cancellationToken);
|
||||
await sheet.FirstPageAsync().ConfigureAwait(false);
|
||||
await sheet.LinesAsync().ConfigureAwait(false);
|
||||
await sheet.FooterBlocksAsync().ConfigureAwait(false);
|
||||
sheet.Finish();
|
||||
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The pen on the pages: where it is, and how to go on to the next page.
|
||||
private sealed class Sheet(PdfWriter pdf, DocumentPrintModel model, CancellationToken cancellationToken)
|
||||
{
|
||||
// Code, description, unit, quantity, price, discounts, VAT, amount: the left edge of each column and the right end.
|
||||
private double[] _edges = [];
|
||||
private PdfPage _page = null!;
|
||||
private int _pages;
|
||||
private double _y;
|
||||
|
||||
private double Right => _page.Width - Margin;
|
||||
|
||||
public async Task FirstPageAsync()
|
||||
{
|
||||
await NewPageAsync(first: true).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task LinesAsync()
|
||||
{
|
||||
Headings();
|
||||
foreach (var line in model.Lines)
|
||||
{
|
||||
var width = _edges[2] - _edges[1] - 8;
|
||||
var wrapped = PdfTextLayout.Wrap(line.Description, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Right - _edges[1] - 8 : width);
|
||||
var height = Math.Max(1, wrapped.Count) * 11 + 5;
|
||||
if (_y - height < Bottom + 20)
|
||||
{
|
||||
await NewPageAsync(first: false).ConfigureAwait(false);
|
||||
Headings();
|
||||
}
|
||||
|
||||
var y = _y;
|
||||
if (!line.IsDescription)
|
||||
{
|
||||
_page.DrawText(line.Code, _edges[0] + 3, y, PdfFont.Courier, 8);
|
||||
_page.DrawText(line.Unit, _edges[2] + 3, y, PdfFont.Helvetica, 8.5);
|
||||
_page.DrawTextRight(line.Quantity, _edges[4] - 3, y, PdfFont.Helvetica, 8.5);
|
||||
_page.DrawTextRight(line.Price, _edges[5] - 3, y, PdfFont.Helvetica, 8.5);
|
||||
_page.DrawTextRight(line.Discount, _edges[6] - 3, y, PdfFont.Helvetica, 8.5);
|
||||
_page.DrawTextRight(line.Tax, _edges[7] - 3, y, PdfFont.Helvetica, 8.5);
|
||||
_page.DrawTextRight(line.Amount, _edges[8] - 3, y, PdfFont.Helvetica, 8.5);
|
||||
}
|
||||
|
||||
foreach (var text in wrapped)
|
||||
{
|
||||
_page.DrawText(text, _edges[1] + 3, y, line.IsDescription ? PdfFont.HelveticaOblique : PdfFont.Helvetica, 8.5, line.IsDescription ? Muted : null);
|
||||
y -= 11;
|
||||
}
|
||||
|
||||
_y -= height;
|
||||
_page.DrawLine(Margin, _y + 8, Right, _y + 8, 0.25, Rule);
|
||||
}
|
||||
|
||||
_y -= 6;
|
||||
}
|
||||
|
||||
public async Task FooterBlocksAsync()
|
||||
{
|
||||
foreach (var note in model.Notes)
|
||||
{
|
||||
var wrapped = PdfTextLayout.Wrap(note, PdfFont.Helvetica, 8.5, Right - Margin);
|
||||
await RoomAsync(wrapped.Count * 11 + 4).ConfigureAwait(false);
|
||||
foreach (var text in wrapped)
|
||||
{
|
||||
_page.DrawText(text, Margin, _y, PdfFont.Helvetica, 8.5);
|
||||
_y -= 11;
|
||||
}
|
||||
|
||||
_y -= 4;
|
||||
}
|
||||
|
||||
// VAT summary on the left, totals on the right, side by side.
|
||||
var middle = Margin + (Right - Margin) * 0.58;
|
||||
var summaryHeight = model.Summary is { } s ? 20 + s.Rows.Count * 13 : 0;
|
||||
var totalsHeight = model.Totals.Count * 14 + 8;
|
||||
await RoomAsync(Math.Max(summaryHeight, totalsHeight) + 10).ConfigureAwait(false);
|
||||
var top = _y - 4;
|
||||
var afterSummary = model.Summary is { } summary ? Table(summary, Margin, middle - 14, top) : top;
|
||||
var y = top;
|
||||
_page.DrawRectangle(middle, y - totalsHeight + 10, Right - middle, totalsHeight, fill: Band, stroke: Band);
|
||||
foreach (var row in model.Totals)
|
||||
{
|
||||
var font = row.Strong ? PdfFont.HelveticaBold : PdfFont.Helvetica;
|
||||
var size = row.Strong ? 11 : 8.5;
|
||||
if (row.Strong)
|
||||
{
|
||||
y -= 3;
|
||||
}
|
||||
|
||||
_page.DrawText(row.Label, middle + 8, y, font, size, row.Strong ? Accent : null);
|
||||
_page.DrawTextRight(row.Value, Right - 8, y, font, size, row.Strong ? Accent : null);
|
||||
y -= 14;
|
||||
}
|
||||
|
||||
_y = Math.Min(afterSummary, y) - 12;
|
||||
|
||||
if (model.Installments is { } installments)
|
||||
{
|
||||
await RoomAsync(22 + installments.Rows.Count * 13).ConfigureAwait(false);
|
||||
_y = Table(installments, Margin, middle - 14, _y) - 12;
|
||||
}
|
||||
|
||||
if (model.Transport.Count > 0)
|
||||
{
|
||||
await RoomAsync(110).ConfigureAwait(false);
|
||||
_y = Fields(model.Transport, 4) - 10;
|
||||
var width = (Right - Margin - 24) / Math.Max(1, model.Signatures.Count);
|
||||
for (var i = 0; i < model.Signatures.Count; i++)
|
||||
{
|
||||
var x = Margin + i * (width + 12);
|
||||
_page.DrawText(model.Signatures[i], x, _y, PdfFont.Helvetica, 7.5, Muted);
|
||||
_page.DrawLine(x, _y - 28, x + width, _y - 28, 0.5, Rule);
|
||||
}
|
||||
|
||||
_y -= 40;
|
||||
}
|
||||
}
|
||||
|
||||
public void Finish() => Foot();
|
||||
|
||||
private async Task RoomAsync(double height)
|
||||
{
|
||||
if (_y - height < Bottom)
|
||||
{
|
||||
await NewPageAsync(first: false).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task NewPageAsync(bool first)
|
||||
{
|
||||
if (_page is not null)
|
||||
{
|
||||
Foot();
|
||||
}
|
||||
|
||||
_page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
_pages++;
|
||||
var right = _page.Width - Margin;
|
||||
double[] widths = [62, 0, 30, 50, 62, 44, 30, 66];
|
||||
var description = right - Margin - widths.Sum();
|
||||
_edges = new double[9];
|
||||
_edges[0] = Margin;
|
||||
for (var i = 0; i < widths.Length; i++)
|
||||
{
|
||||
_edges[i + 1] = _edges[i] + (i == 1 ? description : widths[i]);
|
||||
}
|
||||
|
||||
_y = _page.Height - Margin;
|
||||
if (!first)
|
||||
{
|
||||
_page.DrawText(model.Company.Name, Margin, _y - 8, PdfFont.HelveticaBold, 9);
|
||||
_page.DrawTextRight(model.Title + " " + model.Number + " · " + model.Date, right, _y - 8, PdfFont.Helvetica, 9, Muted);
|
||||
_y -= 18;
|
||||
_page.DrawLine(Margin, _y, right, _y, 0.75, Accent);
|
||||
_y -= 16;
|
||||
return;
|
||||
}
|
||||
|
||||
Letterhead(right);
|
||||
}
|
||||
|
||||
private void Letterhead(double right)
|
||||
{
|
||||
var top = _y;
|
||||
var x = Margin;
|
||||
if (model.Logo is { } logo)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = JpegInfo.Read(logo);
|
||||
var image = pdf.AddJpeg(logo);
|
||||
const double height = 44;
|
||||
var width = Math.Min(130, height * info.Width / Math.Max(1, info.Height));
|
||||
_page.DrawImage(image, Margin, top - height, width, height);
|
||||
x = Margin + width + 12;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// Not a JPEG the writer can embed: the name alone.
|
||||
}
|
||||
}
|
||||
|
||||
var y = top - 12;
|
||||
_page.DrawText(model.Company.Name, x, y, PdfFont.HelveticaBold, 13, Accent);
|
||||
y -= 13;
|
||||
foreach (var line in model.Company.Lines)
|
||||
{
|
||||
_page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 7.5, right - x - 190), x, y, PdfFont.Helvetica, 7.5, Muted);
|
||||
y -= 9.5;
|
||||
}
|
||||
|
||||
// Kind, number and date on the right; a mark for drafts, cancelled and demo documents.
|
||||
_page.DrawTextRight(model.Title.ToUpperInvariant(), right, top - 10, PdfFont.HelveticaBold, 9, Accent);
|
||||
_page.DrawTextRight(model.Number, right, top - 28, PdfFont.HelveticaBold, 16);
|
||||
_page.DrawTextRight(model.Date, right, top - 42, PdfFont.Helvetica, 9, Muted);
|
||||
if (model.Watermark is { } mark)
|
||||
{
|
||||
_page.DrawTextRight(mark.ToUpperInvariant(), right, top - 56, PdfFont.HelveticaBold, 9, Warning);
|
||||
}
|
||||
|
||||
_y = Math.Min(y, top - 62) - 8;
|
||||
_page.DrawLine(Margin, _y, right, _y, 1, Accent);
|
||||
_y -= 14;
|
||||
|
||||
// The address box on the right half, the conditions on the left.
|
||||
var boxLeft = Margin + (right - Margin) * 0.52;
|
||||
var boxTop = _y + 6;
|
||||
var lines = 2 + model.Party.Lines.Count;
|
||||
var boxHeight = lines * 11 + 14;
|
||||
_page.DrawRectangle(boxLeft, boxTop - boxHeight, right - boxLeft, boxHeight, stroke: Rule);
|
||||
var by = boxTop - 13;
|
||||
_page.DrawText(model.PartyLabel, boxLeft + 8, by, PdfFont.Helvetica, 7.5, Muted);
|
||||
if (model.Party.Code is { } code)
|
||||
{
|
||||
_page.DrawTextRight(code, right - 8, by, PdfFont.Courier, 7.5, Muted);
|
||||
}
|
||||
|
||||
by -= 13;
|
||||
_page.DrawText(PdfTextLayout.Fit(model.Party.Name, PdfFont.HelveticaBold, 10, right - boxLeft - 16), boxLeft + 8, by, PdfFont.HelveticaBold, 10);
|
||||
foreach (var line in model.Party.Lines)
|
||||
{
|
||||
by -= 11;
|
||||
_page.DrawText(PdfTextLayout.Fit(line, PdfFont.Helvetica, 8.5, right - boxLeft - 16), boxLeft + 8, by, PdfFont.Helvetica, 8.5);
|
||||
}
|
||||
|
||||
var fy = _y - 6;
|
||||
foreach (var field in model.Fields)
|
||||
{
|
||||
_page.DrawText(field.Label, Margin, fy, PdfFont.Helvetica, 7.5, Muted);
|
||||
_page.DrawText(PdfTextLayout.Fit(field.Value, PdfFont.Helvetica, 8.5, boxLeft - Margin - 100), Margin + 92, fy, PdfFont.Helvetica, 8.5);
|
||||
fy -= 12;
|
||||
}
|
||||
|
||||
_y = Math.Min(boxTop - boxHeight, fy) - 14;
|
||||
}
|
||||
|
||||
private void Headings()
|
||||
{
|
||||
_page.DrawRectangle(Margin, _y - 5, Right - Margin, 16, fill: Band, stroke: Band);
|
||||
for (var i = 0; i < model.LineHeaders.Count; i++)
|
||||
{
|
||||
if (i is 0 or 1 or 2)
|
||||
{
|
||||
_page.DrawText(model.LineHeaders[i], _edges[i] + 3, _y, PdfFont.HelveticaBold, 7.5);
|
||||
}
|
||||
else
|
||||
{
|
||||
_page.DrawTextRight(model.LineHeaders[i], _edges[i + 1] - 3, _y, PdfFont.HelveticaBold, 7.5);
|
||||
}
|
||||
}
|
||||
|
||||
_y -= 17;
|
||||
}
|
||||
|
||||
// A small table; returns the y under it.
|
||||
private double Table(PrintTable table, double left, double right, double y)
|
||||
{
|
||||
_page.DrawText(table.Title, left, y, PdfFont.HelveticaBold, 8.5, Accent);
|
||||
y -= 13;
|
||||
var width = (right - left) / table.Headers.Count;
|
||||
for (var i = 0; i < table.Headers.Count; i++)
|
||||
{
|
||||
Cell(table.Headers[i], left + i * width, width, y, table.Numeric[i], PdfFont.HelveticaBold, 7.5);
|
||||
}
|
||||
|
||||
_page.DrawLine(left, y - 4, right, y - 4, 0.5, Rule);
|
||||
y -= 13;
|
||||
foreach (var row in table.Rows)
|
||||
{
|
||||
for (var i = 0; i < row.Count; i++)
|
||||
{
|
||||
Cell(row[i], left + i * width, width, y, table.Numeric[i], PdfFont.Helvetica, 8);
|
||||
}
|
||||
|
||||
y -= 13;
|
||||
}
|
||||
|
||||
return y;
|
||||
}
|
||||
|
||||
private void Cell(string text, double x, double width, double y, bool numeric, PdfFont font, double size)
|
||||
{
|
||||
var fitted = PdfTextLayout.Fit(text, font, size, width - 6);
|
||||
if (numeric)
|
||||
{
|
||||
_page.DrawTextRight(fitted, x + width - 3, y, font, size);
|
||||
}
|
||||
else
|
||||
{
|
||||
_page.DrawText(fitted, x + 3, y, font, size);
|
||||
}
|
||||
}
|
||||
|
||||
// Label and value pairs in columns; returns the y under them.
|
||||
private double Fields(IReadOnlyList<PrintField> fields, int columns)
|
||||
{
|
||||
var width = (Right - Margin) / columns;
|
||||
var y = _y;
|
||||
for (var i = 0; i < fields.Count; i++)
|
||||
{
|
||||
var x = Margin + (i % columns) * width;
|
||||
_page.DrawText(fields[i].Label, x, y, PdfFont.Helvetica, 7.5, Muted);
|
||||
_page.DrawText(PdfTextLayout.Fit(fields[i].Value, PdfFont.Helvetica, 8.5, width - 8), x, y - 11, PdfFont.Helvetica, 8.5);
|
||||
if (i % columns == columns - 1 || i == fields.Count - 1)
|
||||
{
|
||||
y -= 26;
|
||||
}
|
||||
}
|
||||
|
||||
return y;
|
||||
}
|
||||
|
||||
private void Foot()
|
||||
{
|
||||
var right = _page.Width - Margin;
|
||||
_page.DrawLine(Margin, 46, right, 46, 0.5, Rule);
|
||||
if (model.Footer is { } footer)
|
||||
{
|
||||
_page.DrawText(PdfTextLayout.Fit(footer, PdfFont.Helvetica, 7, right - Margin - 80), Margin, 34, PdfFont.Helvetica, 7, Muted);
|
||||
}
|
||||
|
||||
_page.DrawTextRight(_pages.ToString(System.Globalization.CultureInfo.InvariantCulture), right, 34, PdfFont.Helvetica, 7, Muted);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Localization;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Documents;
|
||||
|
||||
/// <summary>A block of name and lines: the company in the letterhead, the party in the address box.</summary>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="Code">The code of the party, when there is one.</param>
|
||||
/// <param name="Lines">Address, tax numbers, contacts.</param>
|
||||
public sealed record PrintParty(string Name, string? Code, IReadOnlyList<string> Lines);
|
||||
|
||||
/// <summary>A label and its value.</summary>
|
||||
/// <param name="Label">The label.</param>
|
||||
/// <param name="Value">The value, formatted.</param>
|
||||
public sealed record PrintField(string Label, string Value);
|
||||
|
||||
/// <summary>A row of the totals.</summary>
|
||||
/// <param name="Label">The label.</param>
|
||||
/// <param name="Value">The amount, formatted.</param>
|
||||
/// <param name="Strong">Whether it is the amount to pay.</param>
|
||||
public sealed record PrintRow(string Label, string Value, bool Strong);
|
||||
|
||||
/// <summary>A line of the document as printed; every value formatted, empty for a descriptive line.</summary>
|
||||
/// <param name="Code">The item code.</param>
|
||||
/// <param name="Description">The description.</param>
|
||||
/// <param name="Unit">The unit of measure.</param>
|
||||
/// <param name="Quantity">The quantity.</param>
|
||||
/// <param name="Price">The unit price.</param>
|
||||
/// <param name="Discount">The discounts, such as 10+5.</param>
|
||||
/// <param name="Tax">The VAT code.</param>
|
||||
/// <param name="Amount">The amount.</param>
|
||||
/// <param name="IsDescription">Whether the line is only text.</param>
|
||||
public sealed record PrintLine(
|
||||
string? Code, string Description, string? Unit, string? Quantity, string? Price, string? Discount, string? Tax, string? Amount, bool IsDescription);
|
||||
|
||||
/// <summary>A small table (VAT summary, installments) with its headings and rows.</summary>
|
||||
/// <param name="Title">The title.</param>
|
||||
/// <param name="Headers">The headings.</param>
|
||||
/// <param name="Numeric">Which columns hold numbers (aligned right).</param>
|
||||
/// <param name="Rows">The rows, formatted.</param>
|
||||
public sealed record PrintTable(string Title, IReadOnlyList<string> Headers, IReadOnlyList<bool> Numeric, IReadOnlyList<IReadOnlyList<string>> Rows);
|
||||
|
||||
/// <summary>
|
||||
/// A document ready to print (SPEC §9.4, issue #52): every text already formatted and translated, so that the HTML
|
||||
/// preview and the PDF show exactly the same thing.
|
||||
/// </summary>
|
||||
public sealed record DocumentPrintModel
|
||||
{
|
||||
/// <summary>The kind, such as Fattura immediata.</summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>The number, or the draft label.</summary>
|
||||
public required string Number { get; init; }
|
||||
|
||||
/// <summary>The date.</summary>
|
||||
public required string Date { get; init; }
|
||||
|
||||
/// <summary>A mark across the sheet: draft, cancelled, demo; none for a valid document.</summary>
|
||||
public string? Watermark { get; init; }
|
||||
|
||||
/// <summary>The company in the letterhead.</summary>
|
||||
public required PrintParty Company { get; init; }
|
||||
|
||||
/// <summary>The logo of the company, a JPEG, when it has one.</summary>
|
||||
public byte[]? Logo { get; init; }
|
||||
|
||||
/// <summary>The attachment of the logo, for the HTML preview.</summary>
|
||||
public long? LogoAttachmentId { get; init; }
|
||||
|
||||
/// <summary>The heading of the address box (Spett.le, Fornitore).</summary>
|
||||
public required string PartyLabel { get; init; }
|
||||
|
||||
/// <summary>The customer or supplier.</summary>
|
||||
public required PrintParty Party { get; init; }
|
||||
|
||||
/// <summary>Payment, reference, validity, delivery, agent, CIG and CUP.</summary>
|
||||
public required IReadOnlyList<PrintField> Fields { get; init; }
|
||||
|
||||
/// <summary>The headings of the lines.</summary>
|
||||
public required IReadOnlyList<string> LineHeaders { get; init; }
|
||||
|
||||
/// <summary>The lines.</summary>
|
||||
public required IReadOnlyList<PrintLine> Lines { get; init; }
|
||||
|
||||
/// <summary>The VAT summary; empty for documents without VAT.</summary>
|
||||
public PrintTable? Summary { get; init; }
|
||||
|
||||
/// <summary>The installments; empty when the document has none.</summary>
|
||||
public PrintTable? Installments { get; init; }
|
||||
|
||||
/// <summary>The totals, the amount to pay last.</summary>
|
||||
public required IReadOnlyList<PrintRow> Totals { get; init; }
|
||||
|
||||
/// <summary>The transport data of a delivery note or accompanying invoice; empty otherwise.</summary>
|
||||
public required IReadOnlyList<PrintField> Transport { get; init; }
|
||||
|
||||
/// <summary>The signature boxes of a delivery note.</summary>
|
||||
public required IReadOnlyList<string> Signatures { get; init; }
|
||||
|
||||
/// <summary>Notes printed under the lines (document notes, legal notes such as split payment).</summary>
|
||||
public required IReadOnlyList<string> Notes { get; init; }
|
||||
|
||||
/// <summary>The footer of the company.</summary>
|
||||
public string? Footer { get; init; }
|
||||
|
||||
/// <summary>The name of the file without extension, such as fattura-immediata-6-2026.</summary>
|
||||
public required string FileStem { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the printed form of a document (SPEC §9.4, §11.3, issue #52; mockup 025): letterhead with logo and data of
|
||||
/// the company, address box, conditions, lines, VAT summary, installments, totals, transport and notes. The texts come
|
||||
/// from the resources (<c>Print.*</c>); the same model feeds the HTML preview and the PDF generator.
|
||||
/// </summary>
|
||||
/// <param name="engine">The document engine (reads the document with its permission).</param>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="companies">The company registry (name of a company without profile).</param>
|
||||
/// <param name="texts">The texts.</param>
|
||||
public sealed class DocumentPrintService(DocumentEngine engine, IUnitOfWorkFactory factory, ICompanyRegistry companies, ITexts texts)
|
||||
{
|
||||
private static readonly Dictionary<DocumentFamily, string> Entities = new Dictionary<DocumentFamily, string>
|
||||
{
|
||||
[DocumentFamily.SaleQuotation] = "sales.salequotation",
|
||||
[DocumentFamily.SaleOrder] = "sales.saleorder",
|
||||
[DocumentFamily.SaleDocument] = "sales.saledocument",
|
||||
[DocumentFamily.PurchaseOrder] = "purchases.purchaseorder",
|
||||
[DocumentFamily.PurchaseDocument] = "purchases.purchasedocument",
|
||||
[DocumentFamily.InventoryDocument] = "inventory.inventorydocument",
|
||||
};
|
||||
|
||||
/// <summary>The entity of the attachments of a family, such as <c>sales.saledocument</c>.</summary>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <returns>The entity.</returns>
|
||||
public static string EntityOf(DocumentFamily family) => Entities[family];
|
||||
|
||||
/// <summary>The family of an attachment entity.</summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <returns>The family, or none for another entity.</returns>
|
||||
public static DocumentFamily? FamilyOf(string? entity) =>
|
||||
Entities.Where(e => string.Equals(e.Value, entity, StringComparison.Ordinal)).Select(e => (DocumentFamily?)e.Key).FirstOrDefault();
|
||||
|
||||
/// <summary>The printed form of a document.</summary>
|
||||
/// <param name="actor">Who prints: needs to read the document.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="family">The family.</param>
|
||||
/// <param name="id">The document.</param>
|
||||
/// <param name="logo">The logo, read by the caller with its own permission (a JPEG for the PDF).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The model.</returns>
|
||||
/// <exception cref="KeyNotFoundException">No such document.</exception>
|
||||
public async Task<DocumentPrintModel> BuildAsync(
|
||||
Actor actor, string companyCode, DocumentFamily family, long id, Func<long, CancellationToken, Task<byte[]?>>? logo = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var record = await engine.GetAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException(DocumentErrors.NotFound);
|
||||
var company = CompanyCodes.Normalize(companyCode);
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var h = record.Header;
|
||||
var definition = await DocumentDefinitionService.GetAsync(uow, h.DocumentTypeId, cancellationToken).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
|
||||
var registered = profile is null ? await companies.FindAsync(company, cancellationToken).ConfigureAwait(false) : null;
|
||||
var party = h.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
|
||||
|
||||
var lookups = new Lookups(uow, cancellationToken);
|
||||
var behavior = definition.Behavior;
|
||||
var lines = new List<PrintLine>();
|
||||
foreach (var line in record.Lines)
|
||||
{
|
||||
if (line.Kind == DocumentLineKind.Description)
|
||||
{
|
||||
lines.Add(new PrintLine(null, line.Description, null, null, null, null, null, null, true));
|
||||
continue;
|
||||
}
|
||||
|
||||
var code = line.ItemId is { } itemId ? (await lookups.GetAsync<Item>(itemId).ConfigureAwait(false))?.Code : null;
|
||||
lines.Add(new PrintLine(
|
||||
code,
|
||||
line.Description,
|
||||
await lookups.CodeAsync<UnitOfMeasure>(line.UnitOfMeasureId).ConfigureAwait(false),
|
||||
texts.Number(line.Quantity, 2),
|
||||
texts.Money(line.Price),
|
||||
string.IsNullOrWhiteSpace(line.DiscountFormula) ? null : line.DiscountFormula,
|
||||
await lookups.CodeAsync<TaxCode>(line.TaxCodeId).ConfigureAwait(false),
|
||||
texts.Money(line.TaxableAmount),
|
||||
false));
|
||||
}
|
||||
|
||||
var fields = new List<PrintField>();
|
||||
void Field(string key, string? value)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
fields.Add(new PrintField(texts["Print.Fields." + key], value));
|
||||
}
|
||||
}
|
||||
|
||||
Field("Payment", await lookups.DescriptionAsync<PaymentTerm>(h.PaymentTermId).ConfigureAwait(false));
|
||||
if (h.BankAccountId is { } bankId && await lookups.GetAsync<BankAccount>(bankId).ConfigureAwait(false) is { } bank)
|
||||
{
|
||||
Field("Bank", string.Join(" · ", new[] { bank.BankName ?? bank.Description, bank.Iban }.Where(s => !string.IsNullOrWhiteSpace(s))));
|
||||
}
|
||||
|
||||
Field("Reference", h.ExternalReference is { } reference
|
||||
? reference + (h.ExternalDate is { } externalDate ? " " + texts.Format("Print.Of", texts.Date(externalDate)) : null)
|
||||
: null);
|
||||
Field("ValidUntil", h.ValidUntil is { } validUntil ? texts.Date(validUntil) : null);
|
||||
Field("Delivery", h.DeliveryDate is { } delivery ? texts.Date(delivery) : null);
|
||||
Field("Salesperson", await lookups.DescriptionAsync<Salesperson>(h.SalespersonId).ConfigureAwait(false));
|
||||
Field("Revision", h.Revision > 0 ? h.Revision.ToString(texts.Culture) : null);
|
||||
Field("Cig", h.Cig);
|
||||
Field("Cup", h.Cup);
|
||||
Field("Related", h.RelatedNumber is { } related
|
||||
? related + (h.RelatedDate is { } relatedDate ? " " + texts.Format("Print.Of", texts.Date(relatedDate)) : null)
|
||||
: null);
|
||||
|
||||
var transport = new List<PrintField>();
|
||||
var signatures = new List<string>();
|
||||
if (behavior.Has(DocumentEffects.Inventory) && definition.Kind is DocumentKind.DeliveryNote or DocumentKind.AccompanyingInvoice or DocumentKind.PurchaseDeliveryNote)
|
||||
{
|
||||
void Transport(string key, string? value)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
transport.Add(new PrintField(texts["Print.Transport." + key], value));
|
||||
}
|
||||
}
|
||||
|
||||
Transport("Reason", await lookups.DescriptionAsync<TransportReason>(h.TransportReasonId).ConfigureAwait(false));
|
||||
Transport("By", h.TransportBy is { } by ? texts["Sales.TransportBy." + by] : null);
|
||||
Transport("Carrier", await lookups.DescriptionAsync<Carrier>(h.CarrierId).ConfigureAwait(false));
|
||||
Transport("Port", await lookups.DescriptionAsync<ShippingTerm>(h.ShippingTermId).ConfigureAwait(false));
|
||||
Transport("Appearance", await lookups.DescriptionAsync<GoodsAppearance>(h.GoodsAppearanceId).ConfigureAwait(false));
|
||||
Transport("Packages", h.Packages?.ToString(texts.Culture));
|
||||
Transport("GrossWeight", h.GrossWeight is { } gross ? texts.Number(gross, 3) : null);
|
||||
Transport("NetWeight", h.NetWeight is { } net ? texts.Number(net, 3) : null);
|
||||
Transport("Start", h.TransportStart is { } start ? start.ToString("g", texts.Culture) : null);
|
||||
signatures.AddRange([texts["Print.Transport.SignatureDriver"], texts["Print.Transport.SignatureCarrier"], texts["Print.Transport.SignatureRecipient"]]);
|
||||
}
|
||||
|
||||
PrintTable? summary = null;
|
||||
if (record.Figures.Summary.Count > 0)
|
||||
{
|
||||
var rows = new List<IReadOnlyList<string>>();
|
||||
foreach (var row in record.Figures.Summary)
|
||||
{
|
||||
var tax = row.TaxCodeId is { } taxId ? await lookups.GetAsync<TaxCode>(taxId).ConfigureAwait(false) : null;
|
||||
rows.Add([
|
||||
tax is null ? row.Nature ?? string.Empty : tax.Code + " · " + tax.Description,
|
||||
row.Rate.ToString("0.##", texts.Culture) + "%",
|
||||
texts.Money(row.Taxable),
|
||||
texts.Money(row.Tax),
|
||||
]);
|
||||
}
|
||||
|
||||
summary = new PrintTable(
|
||||
texts["Print.Summary.Title"],
|
||||
[texts["Print.Summary.Code"], texts["Print.Summary.Rate"], texts["Print.Summary.Taxable"], texts["Print.Summary.Tax"]],
|
||||
[false, true, true, true],
|
||||
rows);
|
||||
}
|
||||
|
||||
PrintTable? installments = null;
|
||||
if (record.Figures.Installments.Count > 0)
|
||||
{
|
||||
var rows = new List<IReadOnlyList<string>>();
|
||||
foreach (var due in record.Figures.Installments)
|
||||
{
|
||||
rows.Add([
|
||||
due.Number.ToString(texts.Culture),
|
||||
texts.Date(due.DueDate),
|
||||
await lookups.DescriptionAsync<PaymentMethod>(due.PaymentMethodId).ConfigureAwait(false) ?? string.Empty,
|
||||
texts.Money(due.Amount),
|
||||
]);
|
||||
}
|
||||
|
||||
installments = new PrintTable(
|
||||
texts["Print.Installments.Title"],
|
||||
[texts["Print.Installments.Number"], texts["Print.Installments.Due"], texts["Print.Installments.Method"], texts["Print.Installments.Amount"]],
|
||||
[true, false, false, true],
|
||||
rows);
|
||||
}
|
||||
|
||||
var notes = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(h.Notes))
|
||||
{
|
||||
notes.Add(h.Notes.Trim());
|
||||
}
|
||||
|
||||
if (h.SplitPayment)
|
||||
{
|
||||
notes.Add(texts["Print.Notes.SplitPayment"]);
|
||||
}
|
||||
|
||||
if (definition.Kind == DocumentKind.ProForma)
|
||||
{
|
||||
notes.Add(texts["Print.Notes.ProForma"]);
|
||||
}
|
||||
|
||||
if (definition.Kind is DocumentKind.DeferredInvoice)
|
||||
{
|
||||
notes.Add(texts["Print.Notes.Deferred"]);
|
||||
}
|
||||
|
||||
var title = definition.Type.Description;
|
||||
var number = h.DocumentNumber ?? texts["Print.Draft"];
|
||||
var stem = Slug(title + (h.DocumentNumber is { } n ? " " + n : " " + texts["Print.Draft"]));
|
||||
return new DocumentPrintModel
|
||||
{
|
||||
Title = title,
|
||||
Number = number,
|
||||
Date = texts.Date(h.DocumentDate),
|
||||
Watermark = h.Status switch
|
||||
{
|
||||
DocumentStatus.Draft => texts["Print.Watermarks.Draft"],
|
||||
DocumentStatus.Cancelled => texts["Print.Watermarks.Cancelled"],
|
||||
_ => h.IsDemo ? texts["Print.Watermarks.Demo"] : null,
|
||||
},
|
||||
Company = CompanyBlock(profile, registered?.Name ?? company),
|
||||
Logo = profile?.LogoAttachmentId is { } logoId && logo is not null ? await logo(logoId, cancellationToken).ConfigureAwait(false) : null,
|
||||
LogoAttachmentId = profile?.LogoAttachmentId,
|
||||
PartyLabel = texts[behavior.Direction == DocumentDirection.Purchase ? "Print.Supplier" : "Print.Customer"],
|
||||
Party = PartyBlock(party),
|
||||
Fields = fields,
|
||||
LineHeaders =
|
||||
[
|
||||
texts["Print.Lines.Code"], texts["Print.Lines.Description"], texts["Print.Lines.Unit"], texts["Print.Lines.Quantity"],
|
||||
texts["Print.Lines.Price"], texts["Print.Lines.Discount"], texts["Print.Lines.Tax"], texts["Print.Lines.Amount"],
|
||||
],
|
||||
Lines = lines,
|
||||
Summary = summary,
|
||||
Installments = installments,
|
||||
Totals = TotalsOf(record, definition),
|
||||
Transport = transport,
|
||||
Signatures = signatures,
|
||||
Notes = notes,
|
||||
Footer = profile?.FooterNotes,
|
||||
FileStem = stem,
|
||||
};
|
||||
}
|
||||
|
||||
// A name for files: lower case letters and digits joined by dashes, such as fattura-immediata-6-2026.
|
||||
private static string Slug(string text)
|
||||
{
|
||||
var builder = new System.Text.StringBuilder();
|
||||
foreach (var c in text.Normalize(System.Text.NormalizationForm.FormD))
|
||||
{
|
||||
if (char.IsLetterOrDigit(c) && c < 128)
|
||||
{
|
||||
builder.Append(char.ToLowerInvariant(c));
|
||||
}
|
||||
else if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark && builder.Length > 0 && builder[^1] != '-')
|
||||
{
|
||||
builder.Append('-');
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString().Trim('-');
|
||||
}
|
||||
|
||||
private PrintParty CompanyBlock(CompanyProfile? profile, string fallbackName)
|
||||
{
|
||||
if (profile is null)
|
||||
{
|
||||
return new PrintParty(fallbackName, null, []);
|
||||
}
|
||||
|
||||
var lines = new List<string>();
|
||||
Add(lines, Address(profile.Address, profile.StreetNumber, profile.PostalCode, profile.City, profile.ProvinceCode, profile.AddressCountry));
|
||||
Add(lines, Join(
|
||||
profile.VatNumber is { Length: > 0 } vat ? texts.Format("Print.VatNumber", vat) : null,
|
||||
profile.TaxCode is { Length: > 0 } taxCode && taxCode != profile.VatNumber ? texts.Format("Print.TaxCode", taxCode) : null));
|
||||
Add(lines, Join(
|
||||
profile.ReaNumber is { Length: > 0 } rea ? texts.Format("Print.Rea", profile.ReaOffice ?? string.Empty, rea) : null,
|
||||
profile.ShareCapital is { } capital ? texts.Format("Print.ShareCapital", texts.Money(capital)) : null));
|
||||
Add(lines, Join(
|
||||
profile.Phone is { Length: > 0 } phone ? texts.Format("Print.Phone", phone) : null,
|
||||
profile.Email,
|
||||
profile.Pec is { Length: > 0 } pec ? texts.Format("Print.Pec", pec) : null,
|
||||
profile.Website));
|
||||
return new PrintParty(profile.LegalName, null, lines);
|
||||
}
|
||||
|
||||
private PrintParty PartyBlock(Party? party)
|
||||
{
|
||||
if (party is null)
|
||||
{
|
||||
return new PrintParty(texts["Print.NoParty"], null, []);
|
||||
}
|
||||
|
||||
var lines = new List<string>();
|
||||
Add(lines, Join(party.Address, party.StreetNumber));
|
||||
Add(lines, Join(party.PostalCode, party.City, party.Province is { Length: > 0 } province ? "(" + province + ")" : null)
|
||||
+ (party.CountryCode is { Length: > 0 } country && country != "IT" ? " · " + country : null));
|
||||
Add(lines, Join(
|
||||
party.VatNumber is { Length: > 0 } vat ? texts.Format("Print.VatNumber", vat) : null,
|
||||
party.TaxCode is { Length: > 0 } taxCode && taxCode != party.VatNumber ? texts.Format("Print.TaxCode", taxCode) : null));
|
||||
Add(lines, party.Pec is { Length: > 0 } pec ? texts.Format("Print.Pec", pec) : null);
|
||||
return new PrintParty(party.Name, party.Code, lines);
|
||||
}
|
||||
|
||||
private List<PrintRow> TotalsOf(DocumentRecord record, DocumentDefinition definition)
|
||||
{
|
||||
var h = record.Header;
|
||||
var rows = new List<PrintRow>();
|
||||
void Row(string key, decimal value, bool strong = false, string? suffix = null) =>
|
||||
rows.Add(new PrintRow(texts["Print.Totals." + key] + suffix, texts.Money(value), strong));
|
||||
|
||||
var goods = record.Lines.Where(l => l.Kind is DocumentLineKind.Item or DocumentLineKind.Free or DocumentLineKind.Discount).Sum(l => l.TaxableAmount);
|
||||
Row("Goods", goods);
|
||||
if (h.FooterDiscountAmount != 0m)
|
||||
{
|
||||
Row("FooterDiscount", -h.FooterDiscountAmount, suffix: h.FooterDiscount is { } f ? " " + f + "%" : null);
|
||||
}
|
||||
|
||||
if (h.ExpensesAmount != 0m)
|
||||
{
|
||||
Row("Expenses", h.ExpensesAmount);
|
||||
}
|
||||
|
||||
if (h.SocialSecurityAmount != 0m)
|
||||
{
|
||||
Row("SocialSecurity", h.SocialSecurityAmount);
|
||||
}
|
||||
|
||||
var ledger = definition.Behavior.Has(DocumentEffects.Ledger) || h.TaxAmount != 0m;
|
||||
if (ledger)
|
||||
{
|
||||
Row("Taxable", h.TaxableAmount);
|
||||
Row("Tax", h.TaxAmount);
|
||||
}
|
||||
|
||||
if (h.StampDuty != 0m)
|
||||
{
|
||||
Row("StampDuty", h.StampDuty);
|
||||
}
|
||||
|
||||
var showsNet = h.NetAmount != h.TotalAmount && h.NetAmount != 0m;
|
||||
Row("Total", h.TotalAmount, strong: !showsNet);
|
||||
if (h.WithholdingAmount != 0m)
|
||||
{
|
||||
Row("Withholding", -h.WithholdingAmount);
|
||||
}
|
||||
|
||||
if (h.EnasarcoAmount != 0m)
|
||||
{
|
||||
Row("Enasarco", -h.EnasarcoAmount);
|
||||
}
|
||||
|
||||
if (h.SplitPayment && h.TaxAmount != 0m)
|
||||
{
|
||||
Row("SplitPayment", -h.TaxAmount);
|
||||
}
|
||||
|
||||
if (showsNet)
|
||||
{
|
||||
Row("Net", h.NetAmount, strong: true);
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
private static string? Address(string? street, string? number, string? postalCode, string? city, string? province, string? country) =>
|
||||
Join(Join(street, number), Join(postalCode, city, province is { Length: > 0 } p ? "(" + p + ")" : null), country is { Length: > 0 } c && c != "IT" ? c : null) is { } text
|
||||
? text.Replace(" · ", " - ", StringComparison.Ordinal)
|
||||
: null;
|
||||
|
||||
private static string? Join(params string?[] parts)
|
||||
{
|
||||
var present = parts.Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
|
||||
return present.Count == 0 ? null : string.Join(" · ", present);
|
||||
}
|
||||
|
||||
private static void Add(List<string> lines, string? line)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
lines.Add(line);
|
||||
}
|
||||
}
|
||||
|
||||
// The coded rows the printout names, read once each.
|
||||
private sealed class Lookups(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
{
|
||||
private readonly Dictionary<(Type, long), object?> _cache = [];
|
||||
|
||||
public async Task<T?> GetAsync<T>(long id)
|
||||
where T : Core.Entities.Entity<long>, new()
|
||||
{
|
||||
if (!_cache.TryGetValue((typeof(T), id), out var found))
|
||||
{
|
||||
found = await uow.Repository<T, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
_cache[(typeof(T), id)] = found;
|
||||
}
|
||||
|
||||
return (T?)found;
|
||||
}
|
||||
|
||||
public async Task<string?> CodeAsync<T>(long? id)
|
||||
where T : CodedEntity, new() =>
|
||||
id is { } value ? (await GetAsync<T>(value).ConfigureAwait(false))?.Code : null;
|
||||
|
||||
public async Task<string?> DescriptionAsync<T>(long? id)
|
||||
where T : CodedEntity, new() =>
|
||||
id is { } value ? (await GetAsync<T>(value).ConfigureAwait(false))?.Description : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>
|
||||
/// The sales of the demo company (SPEC §14, issue #53): the profile of the company, then a year of documents made the
|
||||
/// way a user makes them, through the document engine: quotations sent, accepted, refused and expired; orders from
|
||||
/// quotations and direct, delivered in full or in part; delivery notes still to invoice (for the deferred invoicing);
|
||||
/// immediate and deferred invoices, a credit note, a pro forma and a few drafts. Dates fall between the first of
|
||||
/// January and today, in order for each numerator. Runs only when the demo data are asked and the company has no sales
|
||||
/// documents yet; every document is marked as demo.
|
||||
/// </summary>
|
||||
/// <param name="engine">The document engine.</param>
|
||||
/// <param name="editor">The document editor (party terms, item prices).</param>
|
||||
/// <param name="copies">The transformations between documents.</param>
|
||||
/// <param name="profiles">The company profiles.</param>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class DemoSalesSeeder(
|
||||
DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, CompanyProfileService profiles, IUnitOfWorkFactory factory, TimeProvider clock)
|
||||
: ICompanySeeder
|
||||
{
|
||||
/// <summary>The fictitious VAT number of the demo company (valid check digit).</summary>
|
||||
public const string CompanyVatNumber = "03579135793";
|
||||
|
||||
private static readonly Actor Seed = Actor.System;
|
||||
|
||||
private DocumentEngine Engine { get; } = engine;
|
||||
|
||||
private DocumentEditor Editor { get; } = editor;
|
||||
|
||||
private DocumentCopyService Copies { get; } = copies;
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 20;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (!context.Demo)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await ProfileAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
var data = await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
if (data is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
|
||||
await new Run(this, companyCode, data, today, cancellationToken).ExecuteAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The letterhead of the demo company, when nobody wrote it yet.
|
||||
private async Task ProfileAsync(string companyCode, CancellationToken cancellationToken)
|
||||
{
|
||||
var profile = await profiles.GetAsync(Seed, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
if (profile.Id != 0 || !string.IsNullOrEmpty(profile.VatNumber))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
profile.FiscalName = profile.LegalName;
|
||||
profile.VatNumber = CompanyVatNumber;
|
||||
profile.TaxCode = CompanyVatNumber;
|
||||
profile.ReaOffice = "CN";
|
||||
profile.ReaNumber = "123456";
|
||||
profile.ShareCapital = 50000m;
|
||||
profile.Shareholders = "SM";
|
||||
profile.LiquidationStatus = "LN";
|
||||
profile.Address = "Via dei Granai";
|
||||
profile.StreetNumber = "57";
|
||||
profile.PostalCode = "12100";
|
||||
profile.City = "Cuneo";
|
||||
profile.ProvinceCode = "CN";
|
||||
profile.AddressCountry = "IT";
|
||||
profile.Phone = "+39 0171 000000";
|
||||
profile.Email = "info@demo.example";
|
||||
profile.Pec = "demo@pec.demo.example";
|
||||
profile.Website = "https://demo.example";
|
||||
profile.FooterNotes = "Dati dimostrativi: nomi, numeri e conti sono fittizi.";
|
||||
await profiles.SaveAsync(Seed, companyCode, profile, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The parties and items the documents use; null when the company already has sales or lacks the demo masters.
|
||||
private async Task<DemoData?> ReadAsync(string companyCode, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
if (await uow.Repository<SaleQuotation, long>().CountAsync(Query.For<SaleQuotation>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<SaleDocument, long>().CountAsync(Query.For<SaleDocument>(), cancellationToken).ConfigureAwait(false) > 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.IsDemo), cancellationToken).ConfigureAwait(false)).Items
|
||||
.OrderBy(i => i.Id).ToList();
|
||||
var goods = items.Where(i => i.Kind == ItemKind.Goods).Select(i => i.Id).ToList();
|
||||
var services = items.Where(i => i.Kind == ItemKind.Service).Select(i => i.Id).ToList();
|
||||
string[] names = ["Rossi Impianti S.r.l.", "Bianchi & Figli S.n.c.", "Idrotermica Piemonte S.r.l.", "Edilizia Moderna S.p.A.", "Hotel Belvedere S.r.l.", "Esposito Mario"];
|
||||
return goods.Count >= 12 && services.Count > 0 && names.All(parties.ContainsKey) ? new DemoData(parties, goods, services) : null;
|
||||
}
|
||||
|
||||
private sealed record DemoData(IReadOnlyDictionary<string, long> Parties, IReadOnlyList<long> Goods, IReadOnlyList<long> Services);
|
||||
|
||||
// One seeding, with its company and dates.
|
||||
private sealed class Run(DemoSalesSeeder owner, string company, DemoData data, DateOnly today, CancellationToken cancellationToken)
|
||||
{
|
||||
private long Party(string name) => data.Parties[name];
|
||||
|
||||
// A date some months before today, kept between the first of January and today so that every document falls
|
||||
// in the current year and the numbering stays in date order.
|
||||
private DateOnly D(int monthsBack, int day)
|
||||
{
|
||||
var month = today.AddMonths(-monthsBack);
|
||||
var date = new DateOnly(month.Year, month.Month, Math.Min(day, DateTime.DaysInMonth(month.Year, month.Month)));
|
||||
var first = new DateOnly(today.Year, 1, 1);
|
||||
return date < first ? first : date > today ? today : date;
|
||||
}
|
||||
|
||||
public async Task ExecuteAsync()
|
||||
{
|
||||
// Quotations (numerator PRE), in date order.
|
||||
var q1 = await NewAsync("PRE", "Rossi Impianti S.r.l.", D(5, 10), [(0, 4m), (1, 10m), (2, 24m)], validDays: 30).ConfigureAwait(false);
|
||||
var q2 = await NewAsync("PRE", "Hotel Belvedere S.r.l.", D(4, 3), [(3, 6m), (4, 6m)], validDays: 30).ConfigureAwait(false);
|
||||
await NewAsync("PRE", "Edilizia Moderna S.p.A.", D(3, 1), [(5, 20m), (6, 40m)], validDays: 30).ConfigureAwait(false);
|
||||
var q4 = await NewAsync("PRE", "Bianchi & Figli S.n.c.", D(2, 5), [(7, 12m), (8, 3m)], validDays: 60, service: 8m).ConfigureAwait(false);
|
||||
await NewAsync("PRE", "Idrotermica Piemonte S.r.l.", D(0, 2), [(9, 2m), (10, 5m)], validDays: 30).ConfigureAwait(false);
|
||||
await owner.Engine.CloseAsync(Seed, company, q2.Family, q2.Header.Id, cancellationToken).ConfigureAwait(false);
|
||||
await NewAsync("PRE", "Esposito Mario", today, [(11, 1m)], validDays: 15, confirm: false).ConfigureAwait(false);
|
||||
|
||||
// Orders (numerator ORD): from the accepted quotations and direct.
|
||||
var o1 = await ConfirmAsync(await CopyAsync(q1, "OC", D(5, 20)).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
var o3 = await NewAsync("OC", "Edilizia Moderna S.p.A.", D(3, 10), [(0, 10m), (2, 30m), (5, 50m)], reference: "ORD-EM-0412").ConfigureAwait(false);
|
||||
var o2 = await ConfirmAsync(await CopyAsync(q4, "OC", D(2, 12)).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
await NewAsync("OC", "Hotel Belvedere S.r.l.", D(1, 8), [(3, 4m), (4, 4m), (11, 2m)], reference: "Ristrutturazione bagni").ConfigureAwait(false);
|
||||
|
||||
// Delivery notes (numerator DDT): one per order, the second order in two goes; the last three stay to invoice.
|
||||
var d1 = await ConfirmAsync(await CopyAsync(o1, "DDT", D(4, 2)).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
var d2 = await ConfirmAsync(await CopyAsync(o3, "DDT", D(3, 15), [o3.Lines[0].Id, o3.Lines[1].Id]).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
await ConfirmAsync(await CopyAsync(o2, "DDT", D(1, 5)).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
await ConfirmAsync(await CopyAsync(o3, "DDT", D(1, 12)).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
await NewAsync("DDT", "Rossi Impianti S.r.l.", D(1, 20), [(6, 15m), (1, 6m)]).ConfigureAwait(false);
|
||||
|
||||
// Invoices and notes (numerator FAT, shared), in date order.
|
||||
await NewAsync("FI", "Bianchi & Figli S.n.c.", D(5, 28), [(2, 12m), (9, 1m)], service: 4m).ConfigureAwait(false);
|
||||
var f2 = await NewAsync("FI", "Hotel Belvedere S.r.l.", D(4, 10), [(3, 2m), (4, 2m), (10, 3m)]).ConfigureAwait(false);
|
||||
await ConfirmAsync(await CopyAsync(d1, "FD", D(4, 30)).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
await ConfirmAsync(await CopyAsync(d2, "FD", D(3, 31)).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
var note = await CopyAsync(f2, "NC", D(2, 15), [f2.Lines[0].Id]).ConfigureAwait(false);
|
||||
note.Lines[^1].Quantity = 1m;
|
||||
note.Header.Notes = "Reso di un articolo difettoso.";
|
||||
await ConfirmAsync(await owner.Engine.SaveAsync(Seed, company, note, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
|
||||
await NewAsync("FI", "Edilizia Moderna S.p.A.", D(1, 25), [(7, 30m), (8, 10m)], service: 16m).ConfigureAwait(false);
|
||||
await NewAsync("FI", "Rossi Impianti S.r.l.", D(0, 5), [(0, 2m), (11, 1m)]).ConfigureAwait(false);
|
||||
await NewAsync("FI", "Idrotermica Piemonte S.r.l.", today, [(5, 8m)], confirm: false).ConfigureAwait(false);
|
||||
await NewAsync("PF", "Esposito Mario", today, [(9, 1m)], service: 3m).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// A new document of the customer with goods (index in the demo goods, quantity) and optional hours of work.
|
||||
private async Task<DocumentRecord> NewAsync(
|
||||
string type, string customer, DateOnly date, IReadOnlyList<(int Good, decimal Quantity)> lines, int? validDays = null, decimal? service = null,
|
||||
string? reference = null, bool confirm = true)
|
||||
{
|
||||
var record = await owner.Engine.NewAsync(Seed, company, type, cancellationToken).ConfigureAwait(false);
|
||||
record.Header.IsDemo = true;
|
||||
record.Header.DocumentDate = date;
|
||||
record.Header.ExternalReference = reference;
|
||||
await owner.Editor.ApplyPartyAsync(Seed, company, record, Party(customer), cancellationToken).ConfigureAwait(false);
|
||||
if (validDays is { } days)
|
||||
{
|
||||
record.Header.ValidUntil = date.AddDays(days);
|
||||
}
|
||||
|
||||
foreach (var (good, quantity) in lines)
|
||||
{
|
||||
await AddAsync(record, data.Goods[good % data.Goods.Count], quantity).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (service is { } hours)
|
||||
{
|
||||
await AddAsync(record, data.Services[0], hours).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
record = await owner.Engine.SaveAsync(Seed, company, record, cancellationToken).ConfigureAwait(false);
|
||||
return confirm ? await ConfirmAsync(record).ConfigureAwait(false) : record;
|
||||
}
|
||||
|
||||
private async Task AddAsync(DocumentRecord record, long itemId, decimal quantity)
|
||||
{
|
||||
var line = DocumentStores.Of(record.Family).NewLine();
|
||||
line.Quantity = quantity;
|
||||
await owner.Editor.FillLineAsync(Seed, company, record, line, itemId, cancellationToken).ConfigureAwait(false);
|
||||
record.Lines.Add(line);
|
||||
}
|
||||
|
||||
private Task<DocumentRecord> CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection<long>? lines = null) =>
|
||||
owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken);
|
||||
|
||||
private Task<DocumentRecord> ConfirmAsync(DocumentRecord record) =>
|
||||
owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user