feat: items and price lists with dated prices, derived lists and demo catalogue (#42)

Items get their own archive and record (mockup 017): codes from the
per-category mask, EAN and NC8 checks, alternative units and bar codes,
suppliers with the usual one, substitutes, notes and history. Only goods
can be stocked; stock itself comes with the warehouse in M6. Costs are
hidden from users without items.cost.read and kept as they were when
those users save. A used item is disabled instead of deleted.

Prices live in one item_prices table, either for a price list or as a
customer's net price, each valid from a date, so documents keep the price
of their day. Derived lists compute a price from their base list with
markup and rounding when they have none of their own. The price grid
(mockup 018) edits every list at one validity date, keeps changes pending
and highlighted until saved, and computes mass updates as a preview.
PriceListService.QuoteAsync gives documents (M5) the price search order
net, list, base, item price with its source.

Parties get the "Articoli e codici" tab: the codes a customer or supplier
uses for our items, found by the item search in that party's documents.

Demo data adds 120 items of a plumbing wholesaler, the PUBB and RIV lists,
last year's prices, suppliers, units, codes and a customer's net prices;
seed --demo [--scale N] loads them from the command line and repeats the
catalogue for performance tests.

ADR 0030 records the decisions; wiki, data model, CHANGELOG and STATUS
are updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 11:06:57 +01:00
1 parent c8241a414e
commit 3dbbaba86e
46 files changed
+5318 -144

No files matched your search

@@ -100,7 +100,7 @@ public sealed class BaseTablesSeeder(FiscalYearService years) : ISeeder
cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("item_categories", [new ItemCategory { Code = "GEN", Description = "Generica" }], cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("party_categories", Coded<PartyCategory>(("GEN", "Generica")), cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base" }], cancellationToken).ConfigureAwait(false);
await context.EnsureAsync("price_lists", [new PriceList { Code = "BASE", Description = "Listino base", IsBase = true }], cancellationToken).ConfigureAwait(false);
var year = context.Today.Year;
var numerators = new Dictionary<string, DocumentNumerator>(StringComparer.Ordinal);
@@ -0,0 +1,382 @@
using System.Globalization;
using Khaemhat.Application.Items;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Validation;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The items of the demo company (SPEC §14, issue #42): 120 items of a plumbing and heating wholesaler in ten categories
/// (goods, services, expenses and description lines), two price lists derived from the base one (public with markup and
/// rounding, resellers with a discount), prices with an older row for the history, the net prices and the item codes of
/// a customer, usual suppliers, alternative units and codes, substitutes, demo costs. Names and brands are fictitious;
/// the bar codes use the prefix 200-299, reserved for internal use, with a valid check digit. Runs only on a company
/// without items; <c>seed --demo --scale N</c> repeats the catalogue N times. The rows are marked as demo.
/// </summary>
/// <param name="codes">The automatic code rules.</param>
public sealed class DemoItemsSeeder(CodeRuleService codes) : ISeeder
{
/// <summary>The items of one scale.</summary>
public const int ItemsPerScale = 120;
private static readonly string[] Sizes = ["1/2\"", "3/4\"", "1\"", "1 1/4\"", "1 1/2\"", "2\""];
/// <inheritdoc />
public string ModuleCode => ModuleCodes.Core;
/// <inheritdoc />
public SeedKind Kind => SeedKind.Demo;
/// <inheritdoc />
public int Order => 20;
/// <summary>The catalogue of one scale, in order.</summary>
/// <returns>The items to create.</returns>
public static IReadOnlyList<DemoItem> Catalogue()
{
var items = new List<DemoItem>();
// Valves: ball valves with lever and butterfly handle, check valves, gate valves.
for (var i = 0; i < Sizes.Length; i++)
{
items.Add(Goods("VALV", "Valvola a sfera " + Sizes[i] + " ottone cromato leva", "PZ", 12.80m + (i * 9.6m), "Idrodemo", "84818081", 0.25m + (i * 0.2m)));
items.Add(Goods("VALV", "Valvola a sfera " + Sizes[i] + " ottone cromato farfalla", "PZ", 11.90m + (i * 9.1m), "Idrodemo", "84818081", 0.24m + (i * 0.2m)));
items.Add(Goods("VALV", "Valvola di ritegno " + Sizes[i] + " a molla", "PZ", 9.40m + (i * 6.2m), "Idrodemo", "84813091", 0.2m + (i * 0.15m)));
}
for (var i = 0; i < 4; i++)
{
items.Add(Goods("VALV", "Saracinesca " + Sizes[i] + " ottone", "PZ", 14.50m + (i * 8.3m), "Idrodemo", "84818081", 0.4m + (i * 0.25m)));
}
items.Add(Goods("VALV", "Valvola miscelatrice termostatica 3/4\"", "PZ", 54m, "Idrodemo", "84818019", 0.7m));
items.Add(Goods("VALV", "Riduttore di pressione 1/2\" con manometro", "PZ", 39.50m, "Idrodemo", "84811019", 0.6m));
items.Add(Goods("VALV", "Filtro autopulente 3/4\"", "PZ", 68m, "Idrodemo", "84212100", 0.9m));
// Fittings: five shapes in four sizes.
foreach (var shape in new[] { "Manicotto", "Gomito 90 gradi", "Raccordo a T", "Nipplo", "Riduzione" })
{
for (var i = 0; i < 4; i++)
{
items.Add(Goods("RACC", shape + " " + Sizes[i] + " ottone M/F", "PZ", 1.60m + (i * 1.35m) + (shape.Length / 10m), "Raccordemo", "74122000", 0.05m + (i * 0.04m)));
}
}
// Pipes: copper bars, multilayer and polyethylene rolls.
foreach (var (diameter, price) in new[] { (12, 2.10m), (14, 2.45m), (15, 2.78m), (16, 3.05m), (18, 3.60m), (22, 4.85m) })
{
items.Add(Goods("TUBI", "Tubo rame " + diameter.ToString(CultureInfo.InvariantCulture) + "x1 barra 5 m", "M", price, "Ramedemo", "74111010", 0.4m));
}
foreach (var (diameter, price) in new[] { (16, 1.15m), (20, 1.65m), (26, 2.70m) })
{
items.Add(Goods("TUBI", "Tubo multistrato " + diameter.ToString(CultureInfo.InvariantCulture) + "x2 rotolo 100 m", "M", price, "Plastidemo", "39172110", 0.15m));
items.Add(Goods("TUBI", "Tubo polietilene PE100 " + (diameter + 9).ToString(CultureInfo.InvariantCulture) + " mm rotolo 50 m", "M", price * 0.8m, "Plastidemo", "39172110", 0.2m));
}
// Heating: boilers, radiators, thermostats, manifolds, expansion vessels.
foreach (var (kw, price) in new[] { (24, 1180m), (28, 1290m), (35, 1520m) })
{
items.Add(Goods("CALD", "Caldaia a condensazione " + kw.ToString(CultureInfo.InvariantCulture) + " kW", "PZ", price, "Termodemo", "84031090", 32m + kw));
}
foreach (var (height, price) in new[] { (500, 9.20m), (600, 10.40m), (700, 11.60m), (800, 12.90m) })
{
items.Add(Goods("CALD", "Elemento radiatore alluminio interasse " + height.ToString(CultureInfo.InvariantCulture), "PZ", price, "Termodemo", "76169990", 1.2m));
}
items.Add(Goods("CALD", "Termostato ambiente digitale", "PZ", 48m, "Termodemo", "90321020", 0.3m));
items.Add(Goods("CALD", "Cronotermostato settimanale wifi", "PZ", 129m, "Termodemo", "90321020", 0.35m));
for (var ways = 2; ways <= 5; ways++)
{
items.Add(Goods("CALD", "Collettore " + ways.ToString(CultureInfo.InvariantCulture) + " vie con valvole", "PZ", 58m + (ways * 23m), "Idrodemo", "84818081", 0.6m * ways));
}
foreach (var (liters, price) in new[] { (8, 32m), (18, 46m), (24, 58m) })
{
items.Add(Goods("CALD", "Vaso di espansione " + liters.ToString(CultureInfo.InvariantCulture) + " l", "PZ", price, "Termodemo", "73110099", liters / 4m));
}
// Taps and sanitary.
foreach (var (name, price) in new[] { ("Miscelatore lavabo monocomando", 64m), ("Miscelatore bidet monocomando", 61m), ("Miscelatore doccia esterno", 72m), ("Miscelatore cucina canna alta", 89m), ("Sifone lavabo 1 1/4\"", 7.80m), ("Sifone lavello doppio", 14.50m) })
{
items.Add(Goods("SAN", name, "PZ", price, "Rubidemo", "84818011", 0.9m));
}
foreach (var length in new[] { 30, 40, 50 })
{
items.Add(Goods("SAN", "Flessibile inox 1/2\" F/F " + length.ToString(CultureInfo.InvariantCulture) + " cm", "PZ", 3.10m + (length / 20m), "Rubidemo", "83071000", 0.12m));
}
// Consumables.
foreach (var (name, unit, price) in new[]
{
("Nastro PTFE 12 mm x 12 m", "PZ", 0.95m), ("Canapa pettinata 100 g", "PZ", 2.40m), ("Pasta sigillante 500 g", "PZ", 6.90m),
("Silicone sanitario trasparente 280 ml", "PZ", 5.20m), ("Kit guarnizioni assortite", "CF", 9.80m), ("Collare fissatubo 1/2\" con tassello", "CF", 12.40m),
("Tassello nylon 8 mm", "CF", 4.60m), ("Fascetta stringitubo 20-32", "CF", 7.30m), ("Saldatura stagno-rame 250 g", "PZ", 18.50m), ("Disossidante 125 ml", "PZ", 4.10m),
})
{
items.Add(Goods("CONS", name, unit, price, null, null, 0.2m));
}
// Pumps.
foreach (var (name, price) in new[] { ("Circolatore elettronico 25-40", 168m), ("Circolatore elettronico 25-60", 196m), ("Circolatore elettronico 25-80", 254m), ("Pompa sommersa 0,75 kW", 312m), ("Pompa sommersa 1,1 kW", 389m), ("Pompa sommersa 1,5 kW", 465m), ("Autoclave 24 l 0,8 kW", 278m), ("Autoclave 60 l 1,1 kW", 412m) })
{
items.Add(Goods("POMP", name, "PZ", price, "Pompdemo", "84137035", 4.5m));
}
// Tools.
foreach (var (name, price) in new[] { ("Chiave stringitubi 14\"", 24.50m), ("Tagliatubi rame 3-35 mm", 19.80m), ("Piegatubi a molla set", 15.40m), ("Svasatubi", 28.90m), ("Cannello a gas", 32m), ("Pinza regolabile 250 mm", 16.70m), ("Seghetto per metalli", 12.30m), ("Livella 60 cm", 14.90m) })
{
items.Add(Goods("UTEN", name, "PZ", price, "Utendemo", "82055980", 0.6m));
}
// Services, expenses and description lines: never in stock.
items.Add(Other(ItemKind.Service, "SERV", "Manodopera idraulico", "ORE", 38m));
items.Add(Other(ItemKind.Service, "SERV", "Manodopera apprendista", "ORE", 26m));
items.Add(Other(ItemKind.Service, "SERV", "Uscita e diritto di chiamata", "SERV", 35m));
items.Add(Other(ItemKind.Service, "SERV", "Sopralluogo tecnico", "SERV", 60m));
items.Add(Other(ItemKind.Service, "SERV", "Manutenzione annuale caldaia", "SERV", 95m));
items.Add(Other(ItemKind.Service, "SERV", "Analisi fumi e libretto impianto", "SERV", 45m));
items.Add(Other(ItemKind.Service, "SERV", "Dichiarazione di conformità impianto", "SERV", 120m));
items.Add(Other(ItemKind.Expense, "SPESE", "Spese di trasporto", "SERV", 15m));
items.Add(Other(ItemKind.Expense, "SPESE", "Spese di imballo", "SERV", 5m));
items.Add(Other(ItemKind.Expense, "SPESE", "Smaltimento materiale rimosso", "SERV", 25m));
items.Add(Other(ItemKind.Text, "SERV", "Riga descrittiva", "NR", null));
items.Add(Other(ItemKind.Text, "SERV", "Materiale fornito dal cliente", "NR", null));
return items;
}
/// <inheritdoc />
public async Task RunAsync(SeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var uow = context.UnitOfWork;
if (await uow.Repository<Item, long>().CountAsync(Query.For<Item>(), cancellationToken).ConfigureAwait(false) > 0)
{
return;
}
var categories = await context.EnsureAsync(
"item_categories",
[
new ItemCategory { Code = "VALV", Description = "Valvolame", IsDemo = true },
new ItemCategory { Code = "RACC", Description = "Raccorderia", IsDemo = true },
new ItemCategory { Code = "TUBI", Description = "Tubi", IsDemo = true },
new ItemCategory { Code = "CALD", Description = "Caldaie e riscaldamento", IsDemo = true },
new ItemCategory { Code = "SAN", Description = "Rubinetteria e sanitari", IsDemo = true },
new ItemCategory { Code = "CONS", Description = "Materiale di consumo", IsDemo = true },
new ItemCategory { Code = "POMP", Description = "Pompe e circolatori", IsDemo = true },
new ItemCategory { Code = "UTEN", Description = "Utensili", IsDemo = true },
new ItemCategory { Code = "SERV", Description = "Servizi e manodopera", IsDemo = true },
new ItemCategory { Code = "SPESE", Description = "Spese accessorie", IsDemo = true },
],
cancellationToken).ConfigureAwait(false);
var lists = uow.Repository<PriceList, long>();
var allLists = (await lists.ListAsync(Query.For<PriceList>(), cancellationToken).ConfigureAwait(false)).Items;
var baseList = PriceBook.BaseOf(allLists);
if (baseList is null)
{
baseList = new PriceList { Code = "BASE", Description = "Listino base", IsBase = true, IsDemo = true };
baseList.Id = await lists.InsertAsync(baseList, cancellationToken).ConfigureAwait(false);
context.Count("price_lists");
}
await context.EnsureAsync(
"price_lists",
[
new PriceList { Code = "PUBB", Description = "Pubblico", BasePriceListId = baseList.Id, MarkupPercent = 45m, RoundingStep = 0.10m, IsDemo = true },
new PriceList { Code = "RIV", Description = "Rivenditori", BasePriceListId = baseList.Id, MarkupPercent = -10m, RoundingStep = 0.01m, IsDemo = true },
],
cancellationToken).ConfigureAwait(false);
var units = (await uow.Repository<UnitOfMeasure, long>().ListAsync(Query.For<UnitOfMeasure>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(u => u.Code, u => u.Id, StringComparer.OrdinalIgnoreCase);
var tax = (await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Code == "22"), cancellationToken).ConfigureAwait(false))?.Id;
var warehouse = (await uow.Repository<Warehouse, long>().FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault), cancellationToken).ConfigureAwait(false))?.Id;
var parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>(), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
long? PartyOf(string name) => parties.TryGetValue(name, out var id) ? id : null;
var suppliers = new Dictionary<string, long?>(StringComparer.Ordinal)
{
["VALV"] = PartyOf("Metalli Nord S.p.A."), ["RACC"] = PartyOf("Metalli Nord S.p.A."), ["TUBI"] = PartyOf("Metalli Nord S.p.A."),
["SAN"] = PartyOf("Metalli Nord S.p.A."), ["CONS"] = PartyOf("Plastica Sud S.r.l."), ["CALD"] = PartyOf("Elektro Werke Süd GmbH"),
["POMP"] = PartyOf("Elektro Werke Süd GmbH"), ["UTEN"] = PartyOf("Plastica Sud S.r.l."),
};
var customer = PartyOf("Rossi Impianti S.r.l.");
var rule = await codes.RuleAsync(context.CompanyCode, ItemService.CodeRule, cancellationToken).ConfigureAwait(false);
var items = uow.Repository<Item, long>();
var thisYear = new DateOnly(context.Today.Year, 1, 1);
var lastYear = thisYear.AddYears(-1);
var catalogue = Catalogue();
var created = new List<(DemoItem Seed, Item Item)>();
var ean = 0;
for (var round = 1; round <= Math.Max(1, context.Scale); round++)
{
foreach (var seed in catalogue)
{
var category = categories[seed.Category];
var cost = seed.Price is { } p && seed.Kind == ItemKind.Goods ? Math.Round(p * 0.58m, 2) : (decimal?)null;
var item = new Item
{
Kind = seed.Kind,
Description = round == 1 ? seed.Description : seed.Description + " (serie " + round.ToString(CultureInfo.InvariantCulture) + ")",
CategoryId = category.Id,
UnitOfMeasureId = units.TryGetValue(seed.Unit, out var unit) ? unit : null,
SalesTaxCodeId = tax,
PurchaseTaxCodeId = tax,
Barcode = seed.Kind == ItemKind.Goods ? Ean(++ean) : null,
CustomsCode = seed.CustomsCode,
Brand = seed.Brand,
Manufacturer = seed.Brand is null ? null : seed.Brand + " Industrie",
NetWeight = seed.Weight,
GrossWeight = seed.Weight is { } w ? Math.Round(w * 1.08m, 3) : null,
Stocked = seed.Kind == ItemKind.Goods,
WarehouseId = seed.Kind == ItemKind.Goods ? warehouse : null,
MinimumStock = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 5m : null,
ReorderPoint = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 10m : null,
ReorderLot = seed.Kind == ItemKind.Goods && seed.Unit == "PZ" ? 20m : null,
Price = seed.Kind is ItemKind.Service or ItemKind.Expense ? seed.Price : null,
StandardCost = cost,
AverageCost = cost,
LastCost = cost is { } c ? Math.Round(c * 1.02m, 2) : null,
IsDemo = true,
};
item.Code = await CodeRuleService.AssignAsync(
uow, rule, context.Today, category.Code,
async (code, ct) => await items.CountAsync(Query.For<Item>().Where(i => i.Code == code), ct).ConfigureAwait(false) > 0,
cancellationToken).ConfigureAwait(false);
item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false);
context.Count("items");
created.Add((seed, item));
if (seed.Kind == ItemKind.Goods && seed.Price is { } price)
{
// The price of this year, and the one of last year for the history.
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = item.Id, PriceListId = baseList.Id, Price = price, ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
await AddAsync(uow, context, "item_prices",
new ItemPrice { ItemId = item.Id, PriceListId = baseList.Id, Price = PriceRounding.Round(price * 0.96m, 0.10m), ValidFrom = lastYear }, cancellationToken).ConfigureAwait(false);
if (suppliers.GetValueOrDefault(seed.Category) is { } supplier)
{
await AddAsync(uow, context, "item_suppliers", new ItemSupplier
{
ItemId = item.Id, PartyId = supplier, SupplierCode = "F-" + item.Code, Price = cost, LeadTimeDays = 7, MinimumQuantity = seed.Unit == "M" ? 50m : 1m, IsDefault = true,
}, cancellationToken).ConfigureAwait(false);
}
}
}
}
await DetailsAsync(uow, context, created, units, customer, baseList, thisYear, cancellationToken).ConfigureAwait(false);
}
private static async Task DetailsAsync(IUnitOfWork uow, SeedContext context, List<(DemoItem Seed, Item Item)> created, Dictionary<string, long> units,
long? customer, PriceList baseList, DateOnly thisYear, CancellationToken cancellationToken)
{
Item? Find(string description) => created.FirstOrDefault(c => c.Item.Description == description).Item;
// Copper bars are sold also by the bar of 5 m; small valves and fittings by the box of 10.
foreach (var (seed, item) in created.Where(c => c.Item.Description.StartsWith("Tubo rame", StringComparison.Ordinal)))
{
if (units.TryGetValue("PZ", out var bar))
{
await AddAsync(uow, context, "item_uoms", new ItemUnit { ItemId = item.Id, UnitOfMeasureId = bar, Factor = 5m }, cancellationToken).ConfigureAwait(false);
}
}
foreach (var (seed, item) in created.Where(c => c.Seed.Category is "VALV" or "RACC" && c.Seed.Unit == "PZ").Take(30))
{
if (units.TryGetValue("CT", out var box))
{
await AddAsync(uow, context, "item_uoms", new ItemUnit { ItemId = item.Id, UnitOfMeasureId = box, Factor = 10m, Barcode = Ean(500_000 + (int)item.Id) }, cancellationToken).ConfigureAwait(false);
}
}
// The codes of the old system, found by the search.
foreach (var (seed, item) in created.Where(c => c.Seed.Category == "VALV").Take(6))
{
await AddAsync(uow, context, "item_barcodes", new ItemBarcode { ItemId = item.Id, Code = "OLD-" + item.Id.ToString("00000", CultureInfo.InvariantCulture), Description = "Codice del gestionale precedente" }, cancellationToken).ConfigureAwait(false);
}
// Substitutes: the butterfly valve for the lever one of the same size, the bigger boiler for the smaller one.
foreach (var size in Sizes)
{
if (Find("Valvola a sfera " + size + " ottone cromato leva") is { } lever && Find("Valvola a sfera " + size + " ottone cromato farfalla") is { } butterfly)
{
await AddAsync(uow, context, "item_substitutes", new ItemSubstitute { ItemId = lever.Id, SubstituteId = butterfly.Id, Notes = "Stessa misura, maniglia a farfalla" }, cancellationToken).ConfigureAwait(false);
}
}
if (Find("Caldaia a condensazione 24 kW") is { } small && Find("Caldaia a condensazione 28 kW") is { } big)
{
await AddAsync(uow, context, "item_substitutes", new ItemSubstitute { ItemId = small.Id, SubstituteId = big.Id, Notes = "Potenza superiore, stessi attacchi" }, cancellationToken).ConfigureAwait(false);
}
if (customer is not { } rossi)
{
return;
}
// The usual customer has net prices on the valves and calls some items with its own codes.
var valves = created.Where(c => c.Seed.Category == "VALV" && c.Seed.Price is not null).Take(8).ToList();
for (var i = 0; i < valves.Count; i++)
{
var (seed, item) = valves[i];
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = item.Id, PartyId = rossi, Price = PriceRounding.Round(seed.Price!.Value * 0.95m, 0.05m), ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
if (i < 5)
{
await AddAsync(uow, context, "party_item_codes",
new PartyItemCode { PartyId = rossi, ItemId = item.Id, Code = "RI-" + (100 + i).ToString(CultureInfo.InvariantCulture), Description = "Valvola " + (i + 1).ToString(CultureInfo.InvariantCulture) }, cancellationToken).ConfigureAwait(false);
}
}
// A price of the public list written by hand, over the derived one.
if (Find("Caldaia a condensazione 24 kW") is { } boiler
&& await uow.Repository<PriceList, long>().FindAsync(Query.For<PriceList>().Where(l => l.Code == "PUBB"), cancellationToken).ConfigureAwait(false) is { } publicList
&& publicList.BasePriceListId == baseList.Id)
{
await AddAsync(uow, context, "item_prices", new ItemPrice { ItemId = boiler.Id, PriceListId = publicList.Id, Price = 1690m, ValidFrom = thisYear }, cancellationToken).ConfigureAwait(false);
}
}
private static async Task AddAsync<T>(IUnitOfWork uow, SeedContext context, string table, T row, CancellationToken cancellationToken)
where T : class, Khaemhat.Core.Entities.IEntity<long>, new()
{
await uow.Repository<T, long>().InsertAsync(row, cancellationToken).ConfigureAwait(false);
context.Count(table);
}
/// <summary>A fictitious EAN-13 with the prefix 200, for internal use, and a valid check digit.</summary>
/// <param name="number">The progressive number.</param>
/// <returns>The code.</returns>
public static string Ean(int number)
{
var digits = "200" + number.ToString("000000000", CultureInfo.InvariantCulture);
return digits + EanValidator.CheckDigit(digits).ToString(CultureInfo.InvariantCulture);
}
private static DemoItem Goods(string category, string description, string unit, decimal price, string? brand, string? customs, decimal? weight) =>
new(category, ItemKind.Goods, description, unit, Math.Round(price, 2), brand, customs, weight);
private static DemoItem Other(ItemKind kind, string category, string description, string unit, decimal? price) =>
new(category, kind, description, unit, price, null, null, null);
}
/// <summary>An item of the demo catalogue.</summary>
/// <param name="Category">The category code.</param>
/// <param name="Kind">What it is.</param>
/// <param name="Description">The description.</param>
/// <param name="Unit">The unit code.</param>
/// <param name="Price">The price of the base list (goods) or of the item (services and expenses).</param>
/// <param name="Brand">The fictitious brand.</param>
/// <param name="CustomsCode">The combined nomenclature.</param>
/// <param name="Weight">The net weight in kg.</param>
public sealed record DemoItem(string Category, ItemKind Kind, string Description, string Unit, decimal? Price, string? Brand, string? CustomsCode, decimal? Weight);
+14 -2
View File
@@ -73,6 +73,9 @@ public sealed class SeedContext
/// <summary>Today.</summary>
public DateOnly Today { get; }
/// <summary>How many times the demo seeders repeat their catalogues (<c>seed --demo --scale N</c>), at least 1.</summary>
public int Scale { get; init; } = 1;
/// <summary>Rows added, by table.</summary>
public IReadOnlyDictionary<string, int> Added => _added;
@@ -242,7 +245,16 @@ public sealed partial class SeedRunner : ICompanySeeder
/// <param name="kind">Base or demo.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was added.</returns>
public async Task<SeedReport> RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default)
public Task<SeedReport> RunAsync(string companyCode, SeedKind kind, CancellationToken cancellationToken = default) =>
RunAsync(companyCode, kind, 1, cancellationToken);
/// <summary>Runs every seeder of a kind on a company, the demo ones repeating their catalogues.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="kind">Base or demo.</param>
/// <param name="scale">How many times the demo catalogues are repeated (<c>--scale</c>), at least 1.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What was added.</returns>
public async Task<SeedReport> RunAsync(string companyCode, SeedKind kind, int scale, CancellationToken cancellationToken = default)
{
var company = CompanyCodes.Normalize(companyCode);
var pack = await _fiscal.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
@@ -251,7 +263,7 @@ public sealed partial class SeedRunner : ICompanySeeder
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
context = new SeedContext(company, uow, pack, today);
context = new SeedContext(company, uow, pack, today) { Scale = Math.Max(1, scale) };
foreach (var seeder in _seeders.Where(s => s.Kind == kind))
{
await seeder.RunAsync(context, cancellationToken).ConfigureAwait(false);