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

@@ -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);
}
}