feat: warehouse and purchase screens, e-invoice import, demo purchases (#55 #56 #57 #58 #60)

Stock, stock take and reorder screens under /magazzino, with valuation, rebuild and the
movements of an item; the understock dashboard widget. Supplier e-invoices (XML, p7m, ZIP)
become draft purchase invoices with supplier, items and tax codes matched, the file attached
and duplicates refused; the TD code mapping stays in the Italian fiscal pack. Purchase
invoices show price differences against the order and the self-invoice still to issue,
with a pending list on the self-invoice screen. The opening stock import now writes an
opening movement. The demo company gets purchases, an opening stock, a pending
self-invoice and a stock take being counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 22:01:32 +01:00
1 parent eb301fa570
commit ced689b297
31 files changed
+3478 -110

No files matched your search

@@ -105,7 +105,7 @@ public static class WidgetCatalog
new(WidgetIds.CrmActivities, "Dashboard.Widgets.CrmActivities.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.Notes, "Dashboard.Widgets.Notes.Title", "edit", 4, ModuleCodes.Core),
new(WidgetIds.Shortcuts, "Dashboard.Widgets.Shortcuts.Title", "zap", 4, ModuleCodes.Core),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read", Milestone: "M6"),
new(WidgetIds.Understock, "Dashboard.Widgets.Understock.Title", "box", 6, ModuleCodes.Core, "inventory.stock.read"),
new(WidgetIds.Pipeline, "Dashboard.Widgets.Pipeline.Title", "target", 6, ModuleCodes.Crm, "crm.lead.read", Milestone: "M11"),
new(WidgetIds.RecentDocuments, "Dashboard.Widgets.RecentDocuments.Title", "file", 6, ModuleCodes.Core, "sales.invoice.read", Milestone: "M5"),
new(WidgetIds.SystemStatus, "Dashboard.Widgets.System.Title", "shield", 4, ModuleCodes.Core, InstanceOnly: true),
@@ -2,10 +2,6 @@ using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
@@ -232,101 +228,3 @@ public sealed class ChartOfAccountsImportTarget(PermissionService permissions) :
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
}
/// <summary>
/// The opening stock (<c>giacenze-iniziali</c>): item, warehouse, quantity and unit cost. Until the stock entries exist
/// (M6) the file is only checked; M6 writes the opening entry from the rows this check accepts.
/// </summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions) : IImportTarget
{
private static readonly ImportField[] StockFields =
[
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
];
/// <inheritdoc />
public string Key => "giacenze-iniziali";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => "inventory.entry.write";
/// <inheritdoc />
public string ExportPermission => "inventory.stock.read";
/// <inheritdoc />
public bool CanApply => false;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => StockFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
var byId = items.ToDictionary(i => i.Id);
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
var seen = new HashSet<(long, long)>();
var results = new List<ImportRowResult>(rows.Count);
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId);
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
{
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
}
if (item is not null && warehouse is null && !cells.Has("deposito"))
{
messages.Add(new("deposito", ImportErrors.Required));
}
if (cells.Number("quantita") is <= 0)
{
messages.Add(new("quantita", ImportErrors.Positive));
}
if (cells.Number("costo_unitario") is < 0)
{
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
}
var label = row["articolo"] ?? string.Empty;
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
}
results.Add(new(row.Line, label, messages.Any(m => !m.IsWarning) ? ImportAction.Skip : ImportAction.Create, messages));
}
return results;
}
/// <inheritdoc />
public Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
throw new InvalidOperationException(ImportErrors.CheckOnly);
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
}
@@ -0,0 +1,191 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.ImportExport;
/// <summary>
/// The opening stock (<c>giacenze-iniziali</c>, SPEC §12.12): item, warehouse, quantity and unit cost. The rows accepted
/// become one warehouse movement per warehouse with the reason <c>APE</c> (opening stock), confirmed at the day of the
/// import: the stock and the average cost start from there.
/// </summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="permissions">Checks the permission.</param>
/// <param name="engine">Writes the movements.</param>
/// <param name="clock">The day of the movements.</param>
public sealed class OpeningStockImportTarget(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock) : IImportTarget
{
/// <summary>The reason of the opening stock.</summary>
public const string OpeningReason = "APE";
/// <summary>Error: the reason APE is missing.</summary>
public const string ReasonMissing = "import.stock.reason-missing";
private static readonly ImportField[] StockFields =
[
new("articolo", ImportFieldKind.Code, Required: true, Aliases: ["codice_articolo", "codice", "cod_articolo", "sku"]),
new("deposito", ImportFieldKind.Code, Aliases: ["magazzino", "codice_magazzino"]),
new("quantita", ImportFieldKind.Number, Required: true, Aliases: ["qta", "qty", "giacenza", "esistenza"]),
new("costo_unitario", ImportFieldKind.Number, Aliases: ["costo", "valore_unitario", "prezzo_acquisto"]),
];
/// <inheritdoc />
public string Key => "giacenze-iniziali";
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public string Permission => "inventory.entry.write";
/// <inheritdoc />
public string ExportPermission => "inventory.stock.read";
/// <inheritdoc />
public bool CanApply => true;
/// <inheritdoc />
public bool CanExport => false;
/// <inheritdoc />
public IReadOnlyList<ImportField> Fields => StockFields;
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> CheckAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken) =>
[.. (await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false)).Select(r => r.Result)];
/// <inheritdoc />
public async Task<IReadOnlyList<ImportRowResult>> ApplyAsync(ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var read = await ReadAsync(context, rows, cancellationToken).ConfigureAwait(false);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
long? reason;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
reason = (await uow.Repository<InventoryReason, long>().FindAsync(Query.For<InventoryReason>().Where(r => r.Code == OpeningReason), cancellationToken)
.ConfigureAwait(false))?.Id;
}
var results = read.Select(r => r.Result).ToArray();
var good = read.Select((r, i) => (Row: r, Index: i)).Where(x => x.Row.Result.Action == ImportAction.Create && x.Row.Stock is not null).ToList();
if (reason is null)
{
foreach (var (_, index) in good)
{
results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, new ImportMessage("articolo", ReasonMissing)] };
}
return results;
}
var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
foreach (var group in good.GroupBy(x => x.Row.Stock!.Value.WarehouseId))
{
var movement = await engine.NewAsync(context.Actor, company, "MM", cancellationToken).ConfigureAwait(false);
movement.Header.DocumentDate = today;
movement.Header.WarehouseId = group.Key;
movement.Header.InventoryReasonId = reason;
foreach (var (row, _) in group)
{
var stock = row.Stock!.Value;
movement.Lines.Add(new InventoryDocumentLine
{
Kind = DocumentLineKind.Item,
ItemId = stock.Item.Id,
Description = stock.Item.Description,
UnitOfMeasureId = stock.Item.UnitOfMeasureId,
Quantity = stock.Quantity,
Price = stock.Cost,
WarehouseId = group.Key,
});
}
try
{
var saved = await engine.SaveAsync(context.Actor, company, movement, cancellationToken).ConfigureAwait(false);
await engine.ConfirmAsync(context.Actor, company, saved.Family, saved.Header.Id, cancellationToken).ConfigureAwait(false);
}
catch (ValidationFailedException ex)
{
var message = new ImportMessage("articolo", ex.Errors.Count > 0 ? ex.Errors[0].Split(':', 2)[^1] : ImportErrors.Required);
foreach (var (_, index) in group)
{
results[index] = results[index] with { Action = ImportAction.Skip, Messages = [.. results[index].Messages, message] };
}
}
}
return results;
}
/// <inheritdoc />
public Task<IReadOnlyList<IReadOnlyList<object?>>> ExportAsync(ImportContext context, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<IReadOnlyList<object?>>>([]);
private async Task<List<(ImportRowResult Result, (Item Item, long WarehouseId, decimal Quantity, decimal Cost)? Stock)>> ReadAsync(
ImportContext context, IReadOnlyList<ImportRow> rows, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(rows);
var company = await CompanyGuard.DemandAsync(permissions, context.Actor, context.CompanyCode, Permission, cancellationToken).ConfigureAwait(false);
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false)).Items;
var codes = new CodeIndex(items.Select(i => (i.Code, i.Id)));
var byId = items.ToDictionary(i => i.Id);
var warehouses = await CodeIndex.LoadAsync<Warehouse>(uow, cancellationToken).ConfigureAwait(false);
var fallback = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items
.OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id;
var seen = new HashSet<(long, long)>();
var results = new List<(ImportRowResult, (Item, long, decimal, decimal)?)>(rows.Count);
foreach (var row in rows)
{
var messages = new List<ImportMessage>();
var cells = new CellReader(row, messages);
messages.AddRange(StockFields.Where(f => f.Required && !cells.Has(f.Key)).Select(f => new ImportMessage(f.Key, ImportErrors.Required)));
var item = cells.Code("articolo", codes) is { } id ? byId[id] : null;
var warehouse = cells.Code("deposito", warehouses) ?? (cells.Has("deposito") ? null : item?.WarehouseId ?? fallback);
if (item is not null && (item.Kind != ItemKind.Goods || !item.Stocked))
{
messages.Add(new("articolo", ImportErrors.NotStocked, Value: item.Code));
}
if (item is not null && warehouse is null && !cells.Has("deposito"))
{
messages.Add(new("deposito", ImportErrors.Required));
}
var quantity = cells.Number("quantita");
if (quantity is <= 0)
{
messages.Add(new("quantita", ImportErrors.Positive));
}
var cost = cells.Number("costo_unitario");
if (cost is < 0)
{
messages.Add(new("costo_unitario", Items.ItemService.NotNegative));
}
var label = row["articolo"] ?? string.Empty;
if (item is not null && warehouse is { } w && !seen.Add((item.Id, w)))
{
messages.Add(new("articolo", ImportErrors.CodeRepeated, Value: label));
}
var failed = messages.Any(m => !m.IsWarning);
(Item, long, decimal, decimal)? stock = !failed && item is not null && warehouse is { } where && quantity is { } q
? (item, where, q, cost ?? item.AverageCost ?? item.StandardCost ?? item.LastCost ?? 0m)
: null;
results.Add((new ImportRowResult(row.Line, label, failed ? ImportAction.Skip : ImportAction.Create, messages), stock));
}
return results;
}
}
@@ -0,0 +1,522 @@
using System.IO.Compression;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Files;
using Khaemhat.Application.Parties;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Files;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Purchases;
/// <summary>An invoice found in a received file, as the import screen shows it before registering (mockup 034).</summary>
/// <param name="FileName">The file (inside a ZIP, its entry).</param>
/// <param name="File">The file as read.</param>
/// <param name="Invoice">The invoice (a file may hold several).</param>
/// <param name="DocumentTypeCode">The purchase document type that registers it, or none.</param>
/// <param name="SupplierId">The supplier already in the archive, by VAT number or tax code.</param>
/// <param name="Duplicate">Whether the supplier already has a document with this number in this year.</param>
/// <param name="ComputedTotal">Taxable plus tax of the summary, plus rounding: what the total should be.</param>
/// <param name="Problems">What stops or warns (resource codes).</param>
public sealed record IncomingCandidate(
string FileName, IncomingInvoiceFile File, IncomingInvoice Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal,
IReadOnlyList<string> Problems)
{
/// <summary>Whether it can be registered.</summary>
public bool CanImport => DocumentTypeCode is not null && !Duplicate;
/// <summary>The total in the file, or the computed one.</summary>
public decimal Total => Invoice.Total ?? ComputedTotal;
}
/// <summary>A file that could not be read.</summary>
/// <param name="FileName">The file.</param>
/// <param name="Error">Why (resource code).</param>
public sealed record IncomingRejected(string FileName, string Error);
/// <summary>What the files hold.</summary>
/// <param name="Invoices">The invoices found.</param>
/// <param name="Rejected">The files not read.</param>
public sealed record IncomingReading(IReadOnlyList<IncomingCandidate> Invoices, IReadOnlyList<IncomingRejected> Rejected);
/// <summary>An invoice registered, or why not.</summary>
/// <param name="Candidate">The invoice.</param>
/// <param name="Record">The draft document.</param>
/// <param name="SupplierCreated">Whether the supplier was added to the archive.</param>
/// <param name="Error">Why it was not registered (resource code).</param>
/// <param name="Warnings">What to check on the draft (resource codes).</param>
public sealed record IncomingImported(IncomingCandidate Candidate, DocumentRecord? Record, bool SupplierCreated, string? Error, IReadOnlyList<string> Warnings);
/// <summary>
/// The import of supplier e-invoices (SPEC §11.5, mockup 034): XML, signed P7M and ZIP files are read by the fiscal pack;
/// each invoice finds its supplier by VAT number or tax code (or adds it), its items by the supplier code, bar code or
/// code, its tax codes by rate and nature; it becomes a draft supplier invoice or credit note with the file attached, to
/// check and confirm. Duplicates (same supplier, number and year) are refused; a total that does not match the lines is
/// reported.
/// </summary>
public sealed class PurchaseInvoiceImportService
{
/// <summary>The largest file accepted, ZIP included.</summary>
public const int MaxFileSize = 50 * 1024 * 1024;
/// <summary>Problem: the type of the invoice is not a purchase (a self-invoice).</summary>
public const string UnsupportedType = "purchase.import.unsupported-type";
/// <summary>Problem: already registered.</summary>
public const string DuplicateProblem = "purchase.import.duplicate";
/// <summary>Warning: the total in the file differs from the lines.</summary>
public const string TotalMismatch = "purchase.import.total-mismatch";
/// <summary>Warning: the signature of the file could not be verified.</summary>
public const string SignatureNotVerified = "purchase.import.signature";
/// <summary>Warning: the discounts of the whole document are not carried to the lines.</summary>
public const string DocumentDiscount = "purchase.import.document-discount";
/// <summary>Error: no tax code of the company has the rate and nature of a line.</summary>
public const string TaxCodeMissing = "purchase.import.tax-code";
/// <summary>Error: the archive is empty of invoices.</summary>
public const string EmptyArchive = "purchase.import.empty";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly DocumentEngine _engine;
private readonly DocumentEditor _editor;
private readonly PartyService _parties;
private readonly AttachmentService _attachments;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The editor (terms of the supplier).</param>
/// <param name="parties">The parties (new suppliers).</param>
/// <param name="attachments">The attachments (the file).</param>
/// <param name="clock">The clock.</param>
public PurchaseInvoiceImportService(
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, DocumentEditor editor, PartyService parties,
AttachmentService attachments, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(editor);
ArgumentNullException.ThrowIfNull(parties);
ArgumentNullException.ThrowIfNull(attachments);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_engine = engine;
_editor = editor;
_parties = parties;
_attachments = attachments;
_clock = clock;
}
/// <summary>Reads files: each XML or P7M, and those inside a ZIP.</summary>
/// <param name="actor">Who imports: needs <c>purchases.invoice.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="files">The files, by name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The invoices found and the files not read.</returns>
public async Task<IncomingReading> ReadAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var reader = pack.GetFeature<IIncomingInvoiceReader>();
var rules = pack.GetFeature<IIncomingInvoiceRules>();
var found = new List<(string Name, IncomingInvoiceFile File)>();
var rejected = new List<IncomingRejected>();
foreach (var (name, content) in Expand(files, rejected))
{
if (reader is null || !reader.CanRead(name, content))
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
continue;
}
try
{
found.Add((name, reader.Read(name, content)));
}
catch (IncomingInvoiceException ex)
{
rejected.Add(new(name, ex.Code));
}
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var result = new List<IncomingCandidate>();
foreach (var (name, file) in found)
{
var supplierId = await FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false);
foreach (var invoice in file.Invoices)
{
var problems = new List<string>();
var typeCode = rules?.DocumentTypeCode(invoice.DocumentType);
if (typeCode is null)
{
problems.Add(UnsupportedType);
}
var duplicate = supplierId is { } supplier && await IsDuplicateAsync(uow, supplier, invoice, cancellationToken).ConfigureAwait(false);
if (duplicate)
{
problems.Add(DuplicateProblem);
}
var computed = invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) + (invoice.Rounding ?? 0m);
if (invoice.Total is { } total && Math.Abs(total - computed) > 0.01m && invoice.Discounts.Count == 0)
{
problems.Add(TotalMismatch);
}
if (invoice.Discounts.Count > 0)
{
problems.Add(DocumentDiscount);
}
if (file.Signature is { Verified: false })
{
problems.Add(SignatureNotVerified);
}
result.Add(new IncomingCandidate(name, file, invoice, typeCode, supplierId, duplicate, computed, problems));
}
}
if (result.Count == 0 && rejected.Count == 0)
{
rejected.Add(new(files.Count == 1 ? files[0].FileName : string.Empty, EmptyArchive));
}
return new IncomingReading([.. result.OrderBy(c => c.Invoice.Date).ThenBy(c => c.File.Supplier.DisplayName, StringComparer.CurrentCulture)], rejected);
}
/// <summary>
/// Registers the invoices as drafts: the supplier is found or added, each line takes its item and tax code, the
/// file is attached. One invoice that fails does not stop the others.
/// </summary>
/// <param name="actor">Who imports.</param>
/// <param name="companyCode">The company.</param>
/// <param name="candidates">The invoices to register.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<IncomingImported>> ImportAsync(
Actor actor, string companyCode, IReadOnlyList<IncomingCandidate> candidates, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(candidates);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PurchaseService.WritePermission, cancellationToken).ConfigureAwait(false);
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
var created = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
var result = new List<IncomingImported>();
foreach (var candidate in candidates)
{
if (candidate.DocumentTypeCode is not { } typeCode)
{
result.Add(new(candidate, null, false, UnsupportedType, []));
continue;
}
var supplierCreated = false;
try
{
long supplierId;
var key = KeyOf(candidate.File.Supplier);
if (candidate.SupplierId is { } known)
{
supplierId = known;
}
else if (key.Length > 0 && created.TryGetValue(key, out var made))
{
supplierId = made;
}
else
{
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
supplierId = await FindSupplierAsync(uow, candidate.File.Supplier, cancellationToken).ConfigureAwait(false) ?? 0;
}
if (supplierId == 0)
{
supplierId = await CreateSupplierAsync(actor, company, candidate.File.Supplier, cancellationToken).ConfigureAwait(false);
supplierCreated = true;
}
if (key.Length > 0)
{
created[key] = supplierId;
}
}
var (record, warnings) = await DraftAsync(actor, company, candidate, typeCode, supplierId, today, cancellationToken).ConfigureAwait(false);
result.Add(new(candidate, record, supplierCreated, null, warnings));
}
catch (ValidationFailedException ex)
{
result.Add(new(candidate, null, supplierCreated, (ex.Errors.Count > 0 ? ex.Errors[0] : null)?.Split(':', 2)[^1] ?? IncomingInvoiceErrors.Invalid, []));
}
}
return result;
}
// ZIP archives are opened (one level, entries .xml and .p7m); other files pass as they are.
private static List<(string Name, byte[] Content)> Expand(IReadOnlyList<(string FileName, byte[] Content)> files, List<IncomingRejected> rejected)
{
var result = new List<(string, byte[])>();
foreach (var (name, content) in files)
{
if (content.Length > MaxFileSize)
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
continue;
}
if (content.Length < 4 || content[0] != (byte)'P' || content[1] != (byte)'K')
{
result.Add((name, content));
continue;
}
try
{
using var archive = new ZipArchive(new MemoryStream(content, writable: false), ZipArchiveMode.Read);
long total = 0;
foreach (var entry in archive.Entries.Where(e => e.Length > 0 && !e.FullName.EndsWith('/')))
{
var entryName = Path.GetFileName(entry.FullName);
if (!entryName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && !entryName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase))
{
continue;
}
total += entry.Length;
if (entry.Length > MaxFileSize || total > 4L * MaxFileSize)
{
rejected.Add(new(entryName, IncomingInvoiceErrors.NotReadable));
continue;
}
using var stream = entry.Open();
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
result.Add((entryName, buffer.ToArray()));
}
}
catch (InvalidDataException)
{
rejected.Add(new(name, IncomingInvoiceErrors.NotReadable));
}
}
return result;
}
private static string KeyOf(IncomingParty party) =>
(party.VatNumber is { Length: > 0 } vat ? (party.CountryCode ?? "IT") + vat : party.TaxCode ?? string.Empty).ToUpperInvariant();
// The VAT number as the archive keeps it: digits only for Italy, with the country prefix abroad.
private static string? VatOf(IncomingParty party) =>
party.VatNumber is not { Length: > 0 } vat ? null
: party.CountryCode is null or "IT" ? vat
: vat.StartsWith(party.CountryCode, StringComparison.OrdinalIgnoreCase) ? vat : party.CountryCode + vat;
private static async Task<long?> FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken)
{
var parties = uow.Repository<Party, long>();
if (VatOf(party) is { } vat)
{
var bare = party.VatNumber!;
var byVat = (await parties.ListAsync(Query.For<Party>().Where(p => p.VatNumber == vat || p.VatNumber == bare), cancellationToken).ConfigureAwait(false)).Items;
if (Pick(byVat) is { } found)
{
return found;
}
}
if (party.TaxCode is { Length: > 0 } taxCode)
{
var byTaxCode = (await parties.ListAsync(Query.For<Party>().Where(p => p.TaxCode == taxCode), cancellationToken).ConfigureAwait(false)).Items;
return Pick(byTaxCode);
}
return null;
// A supplier first, then a customer that is also a supplier, then any party; the enabled ones first.
static long? Pick(IReadOnlyList<Party> parties) => parties
.OrderBy(p => p.Disabled).ThenBy(p => p.Kind == PartyKind.Supplier ? 0 : p.IsSupplier ? 1 : 2).ThenBy(p => p.Id).FirstOrDefault()?.Id;
}
private static async Task<bool> IsDuplicateAsync(IUnitOfWork uow, long supplierId, IncomingInvoice invoice, CancellationToken cancellationToken)
{
var number = invoice.Number.Trim();
var from = new DateOnly(invoice.Date.Year, 1, 1);
var to = new DateOnly(invoice.Date.Year, 12, 31);
return await uow.Repository<PurchaseDocument, long>().CountAsync(
Query.For<PurchaseDocument>().Where(d => d.PartyId == supplierId && d.ExternalReference == number && d.ExternalDate >= from && d.ExternalDate <= to
&& d.Status != DocumentStatus.Cancelled
&& (d.Kind == DocumentKind.PurchaseInvoice || d.Kind == DocumentKind.PurchaseCreditNote)),
cancellationToken).ConfigureAwait(false) > 0;
}
private async Task<long> CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken)
{
var record = await _parties.NewAsync(actor, company, PartyKind.Supplier, cancellationToken).ConfigureAwait(false);
var p = record.Party;
var country = string.IsNullOrWhiteSpace(party.CountryCode) ? "IT" : party.CountryCode.Trim().ToUpperInvariant();
bool inEu;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
inEu = (await uow.Repository<Country, long>().FindAsync(Query.For<Country>().Where(c => c.Code == country), cancellationToken).ConfigureAwait(false))?.EuMember ?? false;
}
p.CountryCode = country;
p.SubjectType = country == "IT"
? (party.Name is null && party.VatNumber is null ? SubjectType.Person : SubjectType.Company)
: inEu ? SubjectType.EuCompany : SubjectType.NonEuCompany;
p.Name = Limit(party.DisplayName, 200) ?? string.Empty;
p.FirstName = p.SubjectType == SubjectType.Person ? Limit(party.FirstName, 100) : null;
p.LastName = p.SubjectType == SubjectType.Person ? Limit(party.LastName, 100) : null;
p.VatNumber = VatOf(party);
p.TaxCode = Limit(party.TaxCode, 16);
p.Address = Limit(party.Address, 200);
p.StreetNumber = Limit(party.StreetNumber, 20);
p.PostalCode = Limit(party.PostalCode, 10);
p.City = Limit(party.City, 100);
p.Province = country == "IT" ? Limit(party.Province, 2) : null;
p.Email = Limit(party.Email, 200);
p.Phone = Limit(party.Phone, 40);
p.Rea = party.ReaOffice is null || party.ReaNumber is null ? null : Limit(party.ReaOffice + "-" + party.ReaNumber, 30);
return (await _parties.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false)).Party.Id;
}
private static string? Limit(string? text, int length) =>
string.IsNullOrWhiteSpace(text) ? null : text.Trim() is var trimmed && trimmed.Length > length ? trimmed[..length] : text.Trim();
private async Task<(DocumentRecord Record, IReadOnlyList<string> Warnings)> DraftAsync(
Actor actor, string company, IncomingCandidate candidate, string typeCode, long supplierId, DateOnly today, CancellationToken cancellationToken)
{
var invoice = candidate.Invoice;
var record = await _engine.NewAsync(actor, company, typeCode, cancellationToken).ConfigureAwait(false);
await _editor.ApplyPartyAsync(actor, company, record, supplierId, cancellationToken).ConfigureAwait(false);
var header = record.Header;
header.DocumentDate = invoice.Date > today ? invoice.Date : today;
header.ExternalReference = Limit(invoice.Number, 50);
header.ExternalDate = invoice.Date;
if (invoice.Causals.Count > 0)
{
header.Notes = Limit(string.Join(Environment.NewLine, invoice.Causals), 2000);
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
var taxes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items;
var codes = invoice.Lines.SelectMany(l => l.Codes).Select(c => c.Value.Trim()).Where(v => v.Length > 0).Distinct(StringComparer.Ordinal).ToList();
var bySupplierCode = codes.Count == 0 ? [] : (await uow.Repository<ItemSupplier, long>().ListAsync(
Query.For<ItemSupplier>().Where(s => s.PartyId == supplierId && codes.Contains(s.SupplierCode!)), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(s => s.SupplierCode!, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal);
var byBarcode = codes.Count == 0 ? [] : (await uow.Repository<ItemBarcode, long>().ListAsync(
Query.For<ItemBarcode>().Where(b => codes.Contains(b.Code)), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(b => b.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ItemId, StringComparer.Ordinal);
var byCode = codes.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(
Query.For<Item>().Where(i => codes.Contains(i.Code)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Code, StringComparer.Ordinal);
var itemIds = bySupplierCode.Values.Concat(byBarcode.Values).Distinct().ToList();
var items = itemIds.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
foreach (var item in byCode.Values)
{
items.TryAdd(item.Id, item);
}
var credit = record.Header.Kind == DocumentKind.PurchaseCreditNote;
foreach (var source in invoice.Lines.OrderBy(l => l.Number))
{
var line = new PurchaseDocumentLine();
line.Kind = DocumentLineKind.Free;
line.Description = Limit(source.Description, 1000) ?? "-";
line.TaxCodeId = TaxCodeOf(taxes, source.TaxRate, source.Nature)
?? throw new ValidationFailedException([":" + TaxCodeMissing]);
var quantity = source.Quantity is { } q && q != 0m ? q : 1m;
var price = source.UnitPrice;
var discounts = source.Discounts;
if (discounts.Count > 0 && discounts.All(d => d.Percent is > 0m and <= 100m && !d.IsSurcharge))
{
line.DiscountFormula = string.Join('+', discounts.Select(d => d.Percent!.Value.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)));
}
else if (discounts.Count > 0 || (source.Quantity is null && source.TotalPrice != source.UnitPrice))
{
// Amounts or surcharges: the net price keeps the total of the line.
price = Math.Round(source.TotalPrice / quantity, 6);
}
line.Quantity = credit ? Math.Abs(quantity) : quantity;
line.Price = credit && quantity < 0m ? -price : price;
if (ItemOf(source, bySupplierCode, byBarcode, byCode) is { } itemId && items.TryGetValue(itemId, out var item) && !item.Disabled)
{
line.Kind = DocumentLineKind.Item;
line.ItemId = item.Id;
line.UnitOfMeasureId = item.UnitOfMeasureId;
}
record.Lines.Add(line);
}
}
var saved = await _engine.SaveAsync(actor, company, record, cancellationToken).ConfigureAwait(false);
await _attachments.AddAsync(
actor, company, DocumentPrintService.EntityOf(saved.Family), saved.Header.Id, new AttachmentFile(AttachmentKind.EInvoice, candidate.File.FileName, null),
(stream, ct) => stream.WriteAsync(candidate.File.Xml, ct).AsTask(), cancellationToken).ConfigureAwait(false);
var warnings = candidate.Problems.Where(p => p is TotalMismatch or SignatureNotVerified or DocumentDiscount).ToList();
if (invoice.Total is { } total && Math.Abs(total - saved.Header.TotalAmount) > 0.01m && !warnings.Contains(TotalMismatch))
{
warnings.Add(TotalMismatch);
}
return (saved, warnings);
}
private static long? ItemOf(IncomingLine line, Dictionary<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
{
foreach (var code in line.Codes.Select(c => c.Value.Trim()))
{
if (bySupplierCode.TryGetValue(code, out var id) || byBarcode.TryGetValue(code, out id))
{
return id;
}
}
return line.Codes.Select(c => c.Value.Trim()).FirstOrDefault(byCode.ContainsKey) is { } own ? byCode[own].Id : null;
}
// The tax code with the rate and nature of the line: the exact nature first, then the family of the nature (N3 for
// N3.2), then for an ordinary rate the ordinary codes before the others.
private static long? TaxCodeOf(IReadOnlyList<TaxCode> taxes, decimal rate, string? nature)
{
var withRate = taxes.Where(t => t.Rate == rate).OrderBy(t => t.ValidTo is not null).ThenBy(t => t.Code, StringComparer.Ordinal).ToList();
if (nature is null)
{
return (withRate.FirstOrDefault(t => t.Nature is null && t.Kind == TaxCodeKind.Taxable) ?? withRate.FirstOrDefault(t => t.Nature is null))?.Id;
}
return (withRate.FirstOrDefault(t => string.Equals(t.Nature, nature, StringComparison.OrdinalIgnoreCase))
?? withRate.FirstOrDefault(t => t.Nature is not null && t.Nature.StartsWith(nature.Split('.')[0], StringComparison.OrdinalIgnoreCase)))?.Id;
}
}
@@ -0,0 +1,260 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Inventory;
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.Querying;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The purchases and the warehouse of the demo company (SPEC §14, issue #61), made through the document engine like a
/// user makes them: the opening stock on the first of January, supplier orders received in full and in part, the
/// supplier invoice of a receipt with a price that differs from the order, a professional's invoice, an invoice from a
/// German supplier still waiting for its self-invoice, and a stock take being counted. Some items start low, so that the
/// sales bring them under their minimum and the reorder proposal has something to propose. Runs only when the demo data
/// are asked and the company has no purchase documents yet; every document is marked as demo.
/// </summary>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The document editor (supplier terms, item costs).</param>
/// <param name="copies">The transformations between documents.</param>
/// <param name="stockTakes">The stock takes.</param>
/// <param name="factory">The units of work.</param>
/// <param name="clock">The clock.</param>
public sealed class DemoPurchasesSeeder(
DocumentEngine engine, DocumentEditor editor, DocumentCopyService copies, StockTakeService stockTakes, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
private static readonly Actor Seed = Actor.System;
private DocumentEngine Engine { get; } = engine;
private DocumentEditor Editor { get; } = editor;
private DocumentCopyService Copies { get; } = copies;
private StockTakeService StockTakes { get; } = stockTakes;
/// <inheritdoc />
public int Order => 30;
/// <inheritdoc />
public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Demo)
{
return;
}
var data = await ReadAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (data is null)
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
var run = new Run(this, companyCode, data, today, cancellationToken);
await run.ExecuteAsync().ConfigureAwait(false);
}
// The suppliers, goods and reasons the documents use; null when the company already has purchases or lacks them.
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<PurchaseOrder, long>().CountAsync(Query.For<PurchaseOrder>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<PurchaseDocument, long>().CountAsync(Query.For<PurchaseDocument>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<InventoryDocument, long>().CountAsync(Query.For<InventoryDocument>(), 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 goods = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.IsDemo && i.Kind == ItemKind.Goods && i.Stocked), cancellationToken)
.ConfigureAwait(false)).Items.OrderBy(i => i.Id).ToList();
var goodIds = goods.Select(g => g.Id).ToList();
var suppliers = (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(s => goodIds.Contains(s.ItemId)), cancellationToken)
.ConfigureAwait(false)).Items.GroupBy(s => s.PartyId).ToDictionary(g => g.Key, g => (IReadOnlyList<long>)[.. g.Select(s => s.ItemId).Distinct()]);
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(r => r.Code, r => r.Id, StringComparer.Ordinal);
var taxes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => !t.Disabled), cancellationToken).ConfigureAwait(false)).Items;
var warehouse = (await uow.Repository<Warehouse, long>().ListAsync(Query.For<Warehouse>().Where(w => !w.Disabled), cancellationToken).ConfigureAwait(false)).Items
.OrderByDescending(w => w.IsDefault).ThenBy(w => w.Code, StringComparer.Ordinal).FirstOrDefault()?.Id;
string[] names = ["Metalli Nord S.p.A.", "Plastica Sud S.r.l.", "Studio Rag. Neri Paola", "Elektro Werke Süd GmbH"];
var ordinary = taxes.FirstOrDefault(t => t.Code == "22")?.Id;
var intraEu = taxes.Where(t => t.Nature is not null && t.Nature.StartsWith("N3.2", StringComparison.Ordinal)).Select(t => (long?)t.Id).FirstOrDefault()
?? taxes.Where(t => t.Nature is not null && t.Nature.StartsWith("N2", StringComparison.Ordinal)).Select(t => (long?)t.Id).FirstOrDefault();
if (goods.Count < 12 || !names.All(parties.ContainsKey) || !reasons.TryGetValue("APE", out var opening) || warehouse is null || ordinary is null || intraEu is null)
{
return null;
}
return new DemoData(parties, goods, suppliers, opening, warehouse.Value, ordinary.Value, intraEu.Value);
}
private sealed record DemoData(
IReadOnlyDictionary<string, long> Parties, IReadOnlyList<Item> Goods, IReadOnlyDictionary<long, IReadOnlyList<long>> ItemsBySupplier, long OpeningReason,
long Warehouse, long Ordinary, long IntraEu);
// One seeding, with its company and dates.
private sealed class Run(DemoPurchasesSeeder 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 (as the sales do).
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;
}
// The goods a supplier sells, else the first goods.
private List<Item> GoodsOf(string supplier, int count)
{
var ids = data.ItemsBySupplier.GetValueOrDefault(Party(supplier)) ?? [];
var own = data.Goods.Where(g => ids.Contains(g.Id)).Take(count).ToList();
return own.Count >= count ? own : [.. own, .. data.Goods.Where(g => !own.Contains(g)).Take(count - own.Count)];
}
public async Task ExecuteAsync()
{
await OpeningAsync().ConfigureAwait(false);
// Metalli Nord: an order received in full, invoiced at a higher price on one line.
var metals = GoodsOf("Metalli Nord S.p.A.", 3);
var o1 = await OrderAsync("Metalli Nord S.p.A.", D(4, 5), [(metals[0], 30m), (metals[1], 20m), (metals[2], 50m)], "Riordino trimestrale").ConfigureAwait(false);
var r1 = await ReceiveAsync(o1, D(4, 15), "DDT 1184", null).ConfigureAwait(false);
var f1 = await CopyAsync(r1, "FF", D(4, 30)).ConfigureAwait(false);
var dearer = f1.Lines.First(l => l.Kind == DocumentLineKind.Item);
dearer.Price = Math.Round(dearer.Price * 1.04m, 2);
f1.Header.ExternalReference = "MN/2026/0311";
f1.Header.ExternalDate = D(4, 28);
await ConfirmAsync(await SaveAsync(f1).ConfigureAwait(false)).ConfigureAwait(false);
// Plastica Sud: an order received in part; the rest is still on its way.
var plastics = GoodsOf("Plastica Sud S.r.l.", 3);
var o2 = await OrderAsync("Plastica Sud S.r.l.", D(2, 3), [(plastics[0], 40m), (plastics[1], 60m), (plastics[2], 25m)], null).ConfigureAwait(false);
await ReceiveAsync(o2, D(1, 10), "Bolla 552", [o2.Lines[0].Id, o2.Lines[1].Id]).ConfigureAwait(false);
// The accountant's fees, with withholding tax.
await InvoiceAsync("Studio Rag. Neri Paola", D(1, 28), "12/2026", D(1, 27), "Tenuta contabilità e dichiarativi", 450m, data.Ordinary).ConfigureAwait(false);
// Goods from Germany: no Italian VAT on the invoice, the self-invoice is still to issue.
var german = data.Goods[^1];
await InvoiceAsync("Elektro Werke Süd GmbH", D(0, 3), "RE-2026-08841", D(0, 1), german.Description, 1280m, data.IntraEu, german).ConfigureAwait(false);
// A stock take being counted: half of the list, two items differ from the books.
var take = await owner.StockTakes.CreateAsync(Seed, company, data.Warehouse, today, null, null, cancellationToken).ConfigureAwait(false);
var counts = new Dictionary<long, decimal?>();
foreach (var (line, index) in take.Lines.Take(Math.Min(12, take.Lines.Count)).Select((l, i) => (l, i)))
{
counts[line.Line.Id] = Math.Max(0m, line.Line.BookQuantity + index switch { 2 => -2m, 7 => 1m, _ => 0m });
}
await owner.StockTakes.SaveCountsAsync(Seed, company, take.Take.Id, counts, cancellationToken).ConfigureAwait(false);
}
// The opening stock: plenty of most goods, little of one in five, so that the year's sales bring them under.
private async Task OpeningAsync()
{
var movement = await owner.Engine.NewAsync(Seed, company, "MM", cancellationToken).ConfigureAwait(false);
movement.Header.IsDemo = true;
movement.Header.DocumentDate = new DateOnly(today.Year, 1, 1);
movement.Header.WarehouseId = data.Warehouse;
movement.Header.InventoryReasonId = data.OpeningReason;
movement.Header.Notes = "Esistenze iniziali dall'inventario di fine anno.";
foreach (var (item, index) in data.Goods.Select((g, i) => (g, i)))
{
var bulk = item.ReorderPoint is null;
movement.Lines.Add(new InventoryDocumentLine
{
Kind = DocumentLineKind.Item,
ItemId = item.Id,
Description = item.Description,
UnitOfMeasureId = item.UnitOfMeasureId,
Quantity = index % 5 == 0 ? (bulk ? 30m : 6m) : bulk ? 400m : 60m,
Price = item.StandardCost ?? 0m,
WarehouseId = data.Warehouse,
});
}
await ConfirmAsync(await SaveAsync(movement).ConfigureAwait(false)).ConfigureAwait(false);
}
private async Task<DocumentRecord> OrderAsync(string supplier, DateOnly date, IReadOnlyList<(Item Item, decimal Quantity)> lines, string? notes)
{
var order = await owner.Engine.NewAsync(Seed, company, "OF", cancellationToken).ConfigureAwait(false);
order.Header.IsDemo = true;
order.Header.DocumentDate = date;
order.Header.Notes = notes;
await owner.Editor.ApplyPartyAsync(Seed, company, order, Party(supplier), cancellationToken).ConfigureAwait(false);
foreach (var (item, quantity) in lines)
{
var line = new PurchaseOrderLine { Quantity = quantity };
await owner.Editor.FillLineAsync(Seed, company, order, line, item.Id, cancellationToken).ConfigureAwait(false);
line.Quantity = quantity;
order.Lines.Add(line);
}
return await ConfirmAsync(await SaveAsync(order).ConfigureAwait(false)).ConfigureAwait(false);
}
private async Task<DocumentRecord> ReceiveAsync(DocumentRecord order, DateOnly date, string reference, IReadOnlyCollection<long>? lines)
{
var receipt = await CopyAsync(order, "DDTF", date, lines).ConfigureAwait(false);
receipt.Header.ExternalReference = reference;
receipt.Header.ExternalDate = date;
return await ConfirmAsync(await SaveAsync(receipt).ConfigureAwait(false)).ConfigureAwait(false);
}
private async Task InvoiceAsync(string supplier, DateOnly date, string number, DateOnly numberDate, string description, decimal amount, long taxCode, Item? item = null)
{
var invoice = await owner.Engine.NewAsync(Seed, company, "FF", cancellationToken).ConfigureAwait(false);
invoice.Header.IsDemo = true;
invoice.Header.DocumentDate = date;
invoice.Header.ExternalReference = number;
invoice.Header.ExternalDate = numberDate;
await owner.Editor.ApplyPartyAsync(Seed, company, invoice, Party(supplier), cancellationToken).ConfigureAwait(false);
var line = new PurchaseDocumentLine { Quantity = 1m };
if (item is not null)
{
await owner.Editor.FillLineAsync(Seed, company, invoice, line, item.Id, cancellationToken).ConfigureAwait(false);
line.Quantity = 10m;
line.Price = Math.Round(amount / 10m, 2);
}
else
{
line.Kind = DocumentLineKind.Free;
line.Description = description;
line.Price = amount;
}
line.TaxCodeId = taxCode;
invoice.Lines.Add(line);
await ConfirmAsync(await SaveAsync(invoice).ConfigureAwait(false)).ConfigureAwait(false);
}
private async Task<DocumentRecord> CopyAsync(DocumentRecord source, string type, DateOnly date, IReadOnlyCollection<long>? lines = null)
{
var copy = await owner.Copies.MergeAsync(Seed, company, source.Family, [source.Header.Id], type, date, lines, cancellationToken).ConfigureAwait(false);
copy.Header.IsDemo = true;
return copy;
}
private Task<DocumentRecord> SaveAsync(DocumentRecord record)
{
record.Header.IsDemo = true;
return owner.Engine.SaveAsync(Seed, company, record, cancellationToken);
}
private Task<DocumentRecord> ConfirmAsync(DocumentRecord record) =>
owner.Engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken);
}
}