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

@@ -0,0 +1,885 @@
using System.Data.Common;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Instance;
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.Items;
/// <summary>An item with all its details, as the record screen edits it (mockup 017).</summary>
public sealed class ItemRecord
{
/// <summary>The item.</summary>
public Item Item { get; set; } = new();
/// <summary>The alternative units.</summary>
public List<ItemUnit> Units { get; set; } = [];
/// <summary>The alternative codes.</summary>
public List<ItemBarcode> Barcodes { get; set; } = [];
/// <summary>The prices: of the price lists and net of the customers, each with its validity.</summary>
public List<ItemPrice> Prices { get; set; } = [];
/// <summary>The suppliers.</summary>
public List<ItemSupplier> Suppliers { get; set; } = [];
/// <summary>The substitutes.</summary>
public List<ItemSubstitute> Substitutes { get; set; } = [];
}
/// <summary>A row of the items radar.</summary>
/// <param name="Id">The item.</param>
/// <param name="Code">The code.</param>
/// <param name="Description">The description.</param>
/// <param name="Kind">What the item is.</param>
/// <param name="CategoryId">The category.</param>
/// <param name="UnitOfMeasureId">The base unit.</param>
/// <param name="Barcode">The main bar code.</param>
/// <param name="Brand">The brand.</param>
/// <param name="Stocked">Kept in stock.</param>
/// <param name="AverageCost">The average cost, only for who can see costs.</param>
/// <param name="Disabled">Disabled.</param>
public sealed record ItemRow(
long Id, string Code, string Description, ItemKind Kind, long? CategoryId, long? UnitOfMeasureId, string? Barcode, string? Brand, bool Stocked,
decimal? AverageCost, bool Disabled)
{
/// <summary>The price of the base list today.</summary>
public decimal? BasePrice { get; init; }
}
/// <summary>What happened to an item asked to be deleted.</summary>
public enum ItemDeleteOutcome
{
/// <summary>Deleted.</summary>
Deleted = 0,
/// <summary>Used by other data: disabled instead.</summary>
Disabled = 1,
}
/// <summary>
/// Items (SPEC §11.2, mockup 017, ADR 0030): list, search by code, description, bar codes and codes of the parties,
/// record with units, codes, prices, suppliers and substitutes, checks, automatic code per category, history.
/// </summary>
/// <remarks>Permissions <c>items.item.read</c>, <c>write</c>, <c>delete</c>; costs only with <c>items.cost.read</c>.</remarks>
public sealed class ItemService
{
/// <summary>Permission to read items and price lists.</summary>
public const string ReadPermission = "items.item.read";
/// <summary>Permission to write items and price lists.</summary>
public const string WritePermission = "items.item.write";
/// <summary>Permission to delete items.</summary>
public const string DeletePermission = "items.item.delete";
/// <summary>Permission to see costs and margins.</summary>
public const string CostPermission = "items.cost.read";
/// <summary>The entity of the attachments of an item.</summary>
public const string Entity = "items.item";
/// <summary>The code rule of the items (ADR 0027).</summary>
public const string CodeRule = "items";
/// <summary>Error: no description.</summary>
public const string DescriptionRequired = "items.description.required";
/// <summary>Error: the code is used by another item.</summary>
public const string CodeDuplicate = "items.code.duplicate";
/// <summary>Error: the code mask needs the category.</summary>
public const string CategoryRequired = "items.category.required";
/// <summary>Error: the bar code has a wrong check digit.</summary>
public const string BarcodeInvalid = "items.barcode.invalid";
/// <summary>Error or warning (by preference): another item has the bar code.</summary>
public const string BarcodeDuplicate = "items.barcode.duplicate";
/// <summary>Error: the NC8 code is not eight digits.</summary>
public const string CustomsCodeInvalid = "items.customs-code.invalid";
/// <summary>Error: a negative quantity, weight, price or cost.</summary>
public const string NotNegative = "items.value.negative";
/// <summary>Error: the factor of a unit is not above zero.</summary>
public const string FactorInvalid = "items.factor.invalid";
/// <summary>Error: a unit is listed twice, or is the base unit.</summary>
public const string UnitDuplicate = "items.unit.duplicate";
/// <summary>Error: a required detail field is empty.</summary>
public const string DetailRequired = "items.detail.required";
/// <summary>Error: the party of a supplier row is not a supplier.</summary>
public const string SupplierInvalid = "items.supplier.invalid";
/// <summary>Error: a supplier or a substitute is listed twice.</summary>
public const string DetailDuplicate = "items.detail.duplicate";
/// <summary>Error: an item cannot be its own substitute.</summary>
public const string SubstituteSelf = "items.substitute.self";
/// <summary>Error: a price is neither of a price list nor of a customer, or of both.</summary>
public const string PriceTarget = "items.price.target";
/// <summary>Error: a net price is for a customer only.</summary>
public const string PriceParty = "items.price.party";
/// <summary>Error: two prices of the same list or customer start on the same day.</summary>
public const string PriceDuplicate = "items.price.duplicate";
/// <summary>Error: the code of a party is used for another item.</summary>
public const string PartyCodeDuplicate = "items.party-code.duplicate";
/// <summary>Error: the item does not exist.</summary>
public const string NotFound = "items.not-found";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly CodeRuleService _codes;
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="audit">The audit trail.</param>
/// <param name="codes">The automatic codes.</param>
/// <param name="clock">The clock.</param>
public ItemService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, CodeRuleService codes, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(codes);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_audit = audit;
_codes = codes;
_clock = clock;
}
/// <summary>The fields of the items radar.</summary>
public static ListFields<Item> Fields { get; } = new ListFields<Item>()
.Add("code", i => i.Code, searchable: true)
.Add("description", i => i.Description, searchable: true)
.Add("barcode", i => i.Barcode, searchable: true)
.Add("brand", i => i.Brand, searchable: true)
.Add("manufacturer", i => i.Manufacturer, searchable: true)
.Add("kind", i => i.Kind)
.Add("category", i => i.CategoryId)
.Add("unit", i => i.UnitOfMeasureId)
.Add("stocked", i => i.Stocked)
.Add("disabled", i => i.Disabled)
.OrderByDefault(new ListSort("code"));
/// <summary>The items for the radar, with the price of the base list today.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="query">Search, filters, sort, page.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The page.</returns>
public async Task<ListPage<ItemRow>> ListAsync(Actor actor, string companyCode, ListQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var page = await uow.Repository<Item, long>().ListAsync(Fields.Apply(Query.For<Item>(), query), cancellationToken).ConfigureAwait(false);
var book = await BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
var today = Today();
IReadOnlyList<ItemRow> rows =
[
.. page.Items.Select(i => RowOf(i, costs) with
{
BasePrice = book.Base is { } baseList ? book.ListPrice(i.Id, baseList.Id, today).Price : i.Price,
}),
];
return new ListPage<ItemRow>(rows, page.TotalCount, new Dictionary<string, decimal>());
}
/// <summary>
/// The active items matching a text, for the lookups: code, description, bar code and brand, or exactly an
/// alternative code or the code a party uses for the item.
/// </summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="text">The text.</param>
/// <param name="partyId">The party of the document, whose codes count too.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>At most 20 items.</returns>
public async Task<IReadOnlyList<ItemRow>> SearchAsync(Actor actor, string companyCode, string? text, long? partyId = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var items = uow.Repository<Item, long>();
var page = await items.ListAsync(
Fields.Apply(Query.For<Item>(), new ListQuery { Search = text, Filters = [ListFilter.Of("disabled", ListFilterOperator.Equals, "false")], Limit = 20 }),
cancellationToken).ConfigureAwait(false);
var found = page.Items.ToList();
var exact = text?.Trim();
if (!string.IsNullOrEmpty(exact))
{
var ids = (await uow.Repository<ItemBarcode, long>().ListAsync(Query.For<ItemBarcode>().Where(b => b.Code == exact), cancellationToken).ConfigureAwait(false))
.Items.Select(b => b.ItemId).ToList();
if (partyId is { } party)
{
ids.AddRange((await uow.Repository<PartyItemCode, long>().ListAsync(
Query.For<PartyItemCode>().Where(c => c.PartyId == party && c.Code == exact), cancellationToken).ConfigureAwait(false)).Items.Select(c => c.ItemId));
}
foreach (var id in ids.Distinct().Where(id => found.All(i => i.Id != id)))
{
if (await items.GetAsync(id, cancellationToken).ConfigureAwait(false) is { Disabled: false } item)
{
found.Insert(0, item);
}
}
}
return [.. found.Take(20).Select(i => RowOf(i, costs))];
}
/// <summary>An item with its details; costs hidden without <c>items.cost.read</c>.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The record, or none.</returns>
public async Task<ItemRecord?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var record = await LoadAsync(uow, id, cancellationToken).ConfigureAwait(false);
if (record is not null && !costs)
{
HideCosts(record);
}
return record;
}
/// <summary>A new item with the usual values: goods kept in stock, unit PZ, VAT 22, the default warehouse.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The record to fill.</returns>
public async Task<ItemRecord> NewAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var unit = await uow.Repository<UnitOfMeasure, long>().FindAsync(Query.For<UnitOfMeasure>().Where(u => u.Code == "PZ" && !u.Disabled), cancellationToken).ConfigureAwait(false);
var tax = await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Code == "22" && !t.Disabled), cancellationToken).ConfigureAwait(false);
var warehouse = await uow.Repository<Warehouse, long>().FindAsync(Query.For<Warehouse>().Where(w => w.IsDefault && !w.Disabled), cancellationToken).ConfigureAwait(false);
return new ItemRecord
{
Item = new Item
{
Kind = ItemKind.Goods, Stocked = true, UnitOfMeasureId = unit?.Id, SalesTaxCodeId = tax?.Id, PurchaseTaxCodeId = tax?.Id, WarehouseId = warehouse?.Id,
},
};
}
/// <summary>Checks a record without saving it (also cleans it, as the save would).</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Errors and warnings.</returns>
public async Task<IReadOnlyList<TableProblem>> ValidateAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Saves an item and its details in one transaction; a new item gets its code from the rule of the items
/// (<c>{categoria}</c> is the code of its category). Without <c>items.cost.read</c> the costs stay as they were.
/// </summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="record">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The record as saved.</returns>
/// <exception cref="ValidationFailedException">With the errors (<c>field:code</c>).</exception>
public async Task<ItemRecord> SaveAsync(Actor actor, string companyCode, ItemRecord record, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(record);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
var rule = await _codes.RuleAsync(company, CodeRule, cancellationToken).ConfigureAwait(false);
var item = record.Item;
long id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var before = item.Id == 0 ? null : await LoadAsync(uow, item.Id, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException([":" + NotFound]);
// The last and average costs come from the receipts (M6); the standard cost only from who sees costs.
item.LastCost = before?.Item.LastCost;
item.AverageCost = before?.Item.AverageCost;
if (!costs)
{
item.StandardCost = before?.Item.StandardCost;
}
var problems = (await CheckAsync(uow, rule, record, cancellationToken).ConfigureAwait(false)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
if (problems.Count > 0)
{
throw new ValidationFailedException(problems);
}
if (item.Code.Length == 0)
{
var category = item.CategoryId is { } categoryId ? (await uow.Repository<ItemCategory, long>().GetAsync(categoryId, cancellationToken).ConfigureAwait(false))?.Code : null;
item.Code = await CodeRuleService.AssignAsync(uow, rule, Today(), category, (c, ct) => TakenAsync(uow, c, ct), cancellationToken).ConfigureAwait(false);
}
id = await WriteAsync(uow, record, before, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return await GetAsync(actor, company, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
}
/// <summary>Disables or enables items (radar selection).</summary>
/// <param name="actor">Who does it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The items.</param>
/// <param name="disabled">Disable or enable.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many changed.</returns>
public async Task<int> SetDisabledAsync(Actor actor, string companyCode, IEnumerable<long> ids, bool disabled, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<Item, long>();
var changed = 0;
foreach (var id in ids.Distinct())
{
if (await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } item && item.Disabled != disabled)
{
var before = Clone(item);
item.Disabled = disabled;
await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, id, before, item, actor.UserName, cancellationToken).ConfigureAwait(false);
changed++;
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return changed;
}
/// <summary>Deletes an item; one used by other data (a substitute, documents from M5) is disabled instead.</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened.</returns>
public async Task<ItemDeleteOutcome> DeleteAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
try
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var before = await uow.Repository<Item, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFound);
await uow.Repository<Item, long>().DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, id, before, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return ItemDeleteOutcome.Deleted;
}
catch (DbException)
{
await SetDisabledAsync(actor, company, [id], true, cancellationToken).ConfigureAwait(false);
return ItemDeleteOutcome.Disabled;
}
}
/// <summary>The history of an item and of its prices, newest first.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The changes.</returns>
public async Task<IReadOnlyList<AuditEntry>> HistoryAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var key = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
var entries = new List<AuditEntry>();
foreach (var entity in new[] { nameof(Item), nameof(ItemPrice) })
{
entries.AddRange(await AuditTrail.HistoryAsync(uow, entity, key, cancellationToken).ConfigureAwait(false));
}
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
}
/// <summary>The rows of some items, for the lookups that show them by id.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The items.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows found.</returns>
public async Task<IReadOnlyList<ItemRow>> RowsAsync(Actor actor, string companyCode, IEnumerable<long> ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var costs = await CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
long[] wanted = [.. ids.Distinct()];
if (wanted.Length == 0)
{
return [];
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return [.. (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => wanted.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items
.Select(i => RowOf(i, costs))];
}
/// <summary>Checks the codes of a party: code and item required, no code twice.</summary>
/// <param name="codes">The codes.</param>
/// <returns>The errors.</returns>
public static IReadOnlyList<TableProblem> CheckPartyCodes(IReadOnlyList<PartyItemCode> codes)
{
ArgumentNullException.ThrowIfNull(codes);
var problems = new List<TableProblem>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < codes.Count; i++)
{
var code = codes[i];
code.Code = code.Code.Trim();
code.Description = Clean(code.Description);
if (code.Code.Length == 0)
{
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", DetailRequired));
}
else if (!seen.Add(code.Code))
{
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.Code)}", PartyCodeDuplicate));
}
if (code.ItemId == 0)
{
problems.Add(new($"ItemCodes.{i}.{nameof(PartyItemCode.ItemId)}", DetailRequired));
}
}
return problems;
}
/// <summary>Whether an actor sees costs and margins.</summary>
/// <param name="actor">The actor.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Whether costs are visible.</returns>
public async Task<bool> CanSeeCostsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
return (actor.IsInstanceAccount || string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
&& (await _permissions.CheckAsync(actor, CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
}
/// <summary>The prices of some items and all the price lists, in memory.</summary>
/// <param name="uow">The unit of work of the company.</param>
/// <param name="itemIds">The items.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The book.</returns>
public static async Task<PriceBook> BookAsync(IUnitOfWork uow, IReadOnlyList<long> itemIds, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(uow);
ArgumentNullException.ThrowIfNull(itemIds);
var lists = (await uow.Repository<PriceList, long>().ListAsync(Query.For<PriceList>(), cancellationToken).ConfigureAwait(false)).Items;
var prices = new List<ItemPrice>();
foreach (var chunk in itemIds.Distinct().Chunk(500))
{
long[] ids = [.. chunk];
prices.AddRange((await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>().Where(p => ids.Contains(p.ItemId)), cancellationToken).ConfigureAwait(false)).Items);
}
return new PriceBook(lists, prices);
}
private DateOnly Today() => DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
private static ItemRow RowOf(Item i, bool costs) =>
new(i.Id, i.Code, i.Description, i.Kind, i.CategoryId, i.UnitOfMeasureId, i.Barcode, i.Brand, i.Stocked, costs ? i.AverageCost : null, i.Disabled);
private static void HideCosts(ItemRecord record)
{
record.Item.StandardCost = null;
record.Item.LastCost = null;
record.Item.AverageCost = null;
}
private static async Task<bool> TakenAsync(IUnitOfWork uow, string code, CancellationToken cancellationToken) =>
await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Code == code), cancellationToken).ConfigureAwait(false) > 0;
private static async Task<ItemRecord?> LoadAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
{
if (await uow.Repository<Item, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item)
{
return null;
}
return new ItemRecord
{
Item = item,
Units = [.. (await uow.Repository<ItemUnit, long>().ListAsync(Query.For<ItemUnit>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
Barcodes = [.. (await uow.Repository<ItemBarcode, long>().ListAsync(Query.For<ItemBarcode>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
Prices = [.. (await uow.Repository<ItemPrice, long>().ListAsync(Query.For<ItemPrice>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
Suppliers = [.. (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
Substitutes = [.. (await uow.Repository<ItemSubstitute, long>().ListAsync(Query.For<ItemSubstitute>().Where(u => u.ItemId == id).OrderBy(u => u.Id), cancellationToken).ConfigureAwait(false)).Items],
};
}
private async Task<long> WriteAsync(IUnitOfWork uow, ItemRecord record, ItemRecord? before, string userName, CancellationToken cancellationToken)
{
var item = record.Item;
var items = uow.Repository<Item, long>();
if (before is null)
{
item.Id = await items.InsertAsync(item, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<Item>(uow, AuditAction.Insert, item.Id, null, item, userName, cancellationToken).ConfigureAwait(false);
}
else
{
await items.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, item.Id, before.Item, item, userName, cancellationToken).ConfigureAwait(false);
}
var id = item.Id;
await ReplaceAsync(uow, record.Units, before?.Units ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.Barcodes, before?.Barcodes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.Suppliers, before?.Suppliers ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.Substitutes, before?.Substitutes ?? [], u => u.ItemId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.Prices, before?.Prices ?? [], u => u.ItemId = id, cancellationToken, async (old, row, ct) =>
await _audit.RecordAsync(uow, old is null ? AuditAction.Insert : row is null ? AuditAction.Delete : AuditAction.Update, id, old, row, userName, ct).ConfigureAwait(false))
.ConfigureAwait(false);
return id;
}
// The lists: rows removed are deleted, rows kept are updated, new rows inserted; the prices are written in the history.
private static async Task ReplaceAsync<T>(
IUnitOfWork uow, List<T> rows, List<T> before, Action<T> link, CancellationToken cancellationToken, Func<T?, T?, CancellationToken, Task>? audit = null)
where T : Core.Entities.Entity<long>, new()
{
var repository = uow.Repository<T, long>();
var kept = rows.Where(r => r.Id != 0).Select(r => r.Id).ToHashSet();
foreach (var old in before.Where(b => !kept.Contains(b.Id)))
{
await repository.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
if (audit is not null)
{
await audit(old, null, cancellationToken).ConfigureAwait(false);
}
}
var previous = before.ToDictionary(b => b.Id);
foreach (var row in rows)
{
link(row);
if (row.Id != 0 && previous.TryGetValue(row.Id, out var old))
{
row.RowVersion = old.RowVersion;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
if (audit is not null)
{
await audit(old, row, cancellationToken).ConfigureAwait(false);
}
}
else
{
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
if (audit is not null)
{
await audit(null, row, cancellationToken).ConfigureAwait(false);
}
}
}
}
private static async Task<IReadOnlyList<TableProblem>> CheckAsync(IUnitOfWork uow, CodeRule rule, ItemRecord record, CancellationToken cancellationToken)
{
var problems = new List<TableProblem>();
var item = record.Item;
Normalize(item);
if (item.Description.Length == 0)
{
problems.Add(new(nameof(Item.Description), DescriptionRequired));
}
var id = item.Id;
if (item.Code.Length > 0)
{
var code = item.Code;
if (await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Code == code && i.Id != id), cancellationToken).ConfigureAwait(false) > 0)
{
problems.Add(new(nameof(Item.Code), CodeDuplicate));
}
}
else if (item.CategoryId is null && CodeMask.TryParse(rule.Mask, out var mask, out _) && mask!.UsesCategory)
{
problems.Add(new(nameof(Item.CategoryId), CategoryRequired));
}
if (item.Barcode is { } barcode)
{
if (!EanValidator.IsValid(barcode))
{
problems.Add(new(nameof(Item.Barcode), BarcodeInvalid));
}
else if (await BarcodeUsedAsync(uow, barcode, id, cancellationToken).ConfigureAwait(false))
{
problems.Add(new(nameof(Item.Barcode), BarcodeDuplicate, IsWarning: !rule.UniqueBarcode));
}
}
if (item.CustomsCode is { } customs && (customs.Length != 8 || !customs.All(char.IsAsciiDigit)))
{
problems.Add(new(nameof(Item.CustomsCode), CustomsCodeInvalid));
}
foreach (var (value, field) in new (decimal?, string)[]
{
(item.NetWeight, nameof(Item.NetWeight)), (item.GrossWeight, nameof(Item.GrossWeight)), (item.MinimumStock, nameof(Item.MinimumStock)),
(item.ReorderPoint, nameof(Item.ReorderPoint)), (item.ReorderLot, nameof(Item.ReorderLot)), (item.Price, nameof(Item.Price)),
(item.StandardCost, nameof(Item.StandardCost)),
})
{
if (value < 0)
{
problems.Add(new(field, NotNegative));
}
}
CheckUnits(record, problems);
CheckBarcodes(record, problems);
await CheckPricesAsync(uow, record, problems, cancellationToken).ConfigureAwait(false);
await CheckSuppliersAsync(uow, record, problems, cancellationToken).ConfigureAwait(false);
CheckSubstitutes(record, problems);
return problems;
}
private static void Normalize(Item item)
{
item.Code = item.Code.Trim();
item.Description = item.Description.Trim();
item.ExtendedDescription = Clean(item.ExtendedDescription);
item.Barcode = Clean(item.Barcode);
item.CustomsCode = Clean(item.CustomsCode)?.Replace(" ", string.Empty, StringComparison.Ordinal).Replace(".", string.Empty, StringComparison.Ordinal);
item.Manufacturer = Clean(item.Manufacturer);
item.Brand = Clean(item.Brand);
item.RevenueAccountCode = Clean(item.RevenueAccountCode);
item.CostAccountCode = Clean(item.CostAccountCode);
item.Notes = Clean(item.Notes);
// Only goods move in the warehouse.
if (item.Kind != ItemKind.Goods)
{
item.Stocked = false;
}
}
private static async Task<bool> BarcodeUsedAsync(IUnitOfWork uow, string barcode, long id, CancellationToken cancellationToken) =>
await uow.Repository<Item, long>().CountAsync(Query.For<Item>().Where(i => i.Barcode == barcode && i.Id != id), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<ItemBarcode, long>().CountAsync(Query.For<ItemBarcode>().Where(b => b.Code == barcode && b.ItemId != id), cancellationToken).ConfigureAwait(false) > 0;
private static void CheckUnits(ItemRecord record, List<TableProblem> problems)
{
var seen = new HashSet<long>();
if (record.Item.UnitOfMeasureId is { } baseUnit)
{
seen.Add(baseUnit);
}
for (var i = 0; i < record.Units.Count; i++)
{
var unit = record.Units[i];
unit.Barcode = Clean(unit.Barcode);
if (unit.UnitOfMeasureId == 0)
{
problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", DetailRequired));
}
else if (!seen.Add(unit.UnitOfMeasureId))
{
problems.Add(new($"Units.{i}.{nameof(ItemUnit.UnitOfMeasureId)}", UnitDuplicate));
}
if (unit.Factor <= 0)
{
problems.Add(new($"Units.{i}.{nameof(ItemUnit.Factor)}", FactorInvalid));
}
if (unit.Barcode is { } barcode && !EanValidator.IsValid(barcode))
{
problems.Add(new($"Units.{i}.{nameof(ItemUnit.Barcode)}", BarcodeInvalid));
}
}
}
private static void CheckBarcodes(ItemRecord record, List<TableProblem> problems)
{
var seen = new HashSet<string>(StringComparer.Ordinal);
if (record.Item.Barcode is { } main)
{
seen.Add(main);
}
for (var i = 0; i < record.Barcodes.Count; i++)
{
var code = record.Barcodes[i];
code.Code = code.Code.Trim();
code.Description = Clean(code.Description);
if (code.Code.Length == 0)
{
problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailRequired));
}
else if (!seen.Add(code.Code))
{
problems.Add(new($"Barcodes.{i}.{nameof(ItemBarcode.Code)}", DetailDuplicate));
}
}
}
private static async Task CheckPricesAsync(IUnitOfWork uow, ItemRecord record, List<TableProblem> problems, CancellationToken cancellationToken)
{
var seen = new HashSet<(long?, long?, DateOnly?)>();
var parties = uow.Repository<Party, long>();
for (var i = 0; i < record.Prices.Count; i++)
{
var price = record.Prices[i];
var field = $"Prices.{i}.";
if ((price.PriceListId is null) == (price.PartyId is null))
{
problems.Add(new(field + nameof(ItemPrice.PriceListId), PriceTarget));
continue;
}
// A row added on the screen and not filled has id 0.
if (price.PriceListId is 0 || price.PartyId is 0)
{
problems.Add(new(field + (price.PartyId is null ? nameof(ItemPrice.PriceListId) : nameof(ItemPrice.PartyId)), DetailRequired));
continue;
}
if (price.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true })
{
problems.Add(new(field + nameof(ItemPrice.PartyId), PriceParty));
}
if (price.Price < 0)
{
problems.Add(new(field + nameof(ItemPrice.Price), NotNegative));
}
if (!seen.Add((price.PriceListId, price.PartyId, price.ValidFrom)))
{
problems.Add(new(field + nameof(ItemPrice.ValidFrom), PriceDuplicate));
}
}
}
private static async Task CheckSuppliersAsync(IUnitOfWork uow, ItemRecord record, List<TableProblem> problems, CancellationToken cancellationToken)
{
var seen = new HashSet<long>();
var parties = uow.Repository<Party, long>();
for (var i = 0; i < record.Suppliers.Count; i++)
{
var supplier = record.Suppliers[i];
var field = $"Suppliers.{i}.";
supplier.SupplierCode = Clean(supplier.SupplierCode);
if (supplier.PartyId == 0)
{
problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailRequired));
}
else if (!seen.Add(supplier.PartyId))
{
problems.Add(new(field + nameof(ItemSupplier.PartyId), DetailDuplicate));
}
else if (await parties.GetAsync(supplier.PartyId, cancellationToken).ConfigureAwait(false) is not { IsSupplier: true })
{
problems.Add(new(field + nameof(ItemSupplier.PartyId), SupplierInvalid));
}
if (supplier.Price < 0)
{
problems.Add(new(field + nameof(ItemSupplier.Price), NotNegative));
}
if (supplier.MinimumQuantity < 0)
{
problems.Add(new(field + nameof(ItemSupplier.MinimumQuantity), NotNegative));
}
if (supplier.LeadTimeDays < 0)
{
problems.Add(new(field + nameof(ItemSupplier.LeadTimeDays), NotNegative));
}
}
// One usual supplier: the first one marked.
var found = false;
foreach (var supplier in record.Suppliers.Where(s => s.IsDefault))
{
supplier.IsDefault = !found;
found = true;
}
}
private static void CheckSubstitutes(ItemRecord record, List<TableProblem> problems)
{
var seen = new HashSet<long>();
for (var i = 0; i < record.Substitutes.Count; i++)
{
var substitute = record.Substitutes[i];
var field = $"Substitutes.{i}.{nameof(ItemSubstitute.SubstituteId)}";
substitute.Notes = Clean(substitute.Notes);
if (substitute.SubstituteId == 0)
{
problems.Add(new(field, DetailRequired));
}
else if (substitute.SubstituteId == record.Item.Id)
{
problems.Add(new(field, SubstituteSelf));
}
else if (!seen.Add(substitute.SubstituteId))
{
problems.Add(new(field, DetailDuplicate));
}
}
}
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private static Item Clone(Item item)
{
var copy = new Item();
foreach (var property in typeof(Item).GetProperties().Where(p => p.CanRead && p.CanWrite))
{
property.SetValue(copy, property.GetValue(item));
}
return copy;
}
}
+188
View File
@@ -0,0 +1,188 @@
using Khaemhat.Application.Tables;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
namespace Khaemhat.Application.Items;
/// <summary>The price proposed for an item and where it comes from (<c>price_source</c> of the document lines).</summary>
/// <param name="Price">The price, or none.</param>
/// <param name="Source">Where it comes from.</param>
/// <param name="PriceListId">The price list it comes from.</param>
/// <param name="VatIncluded">The price includes VAT (a price list with VAT included).</param>
/// <param name="ValidFrom">The price is valid from this day.</param>
public sealed record PriceQuote(decimal? Price, PriceSource Source, long? PriceListId, bool VatIncluded, DateOnly? ValidFrom)
{
/// <summary>No price.</summary>
public static PriceQuote None { get; } = new(null, PriceSource.None, null, false, null);
}
/// <summary>The discounts proposed on a line.</summary>
/// <param name="Formula">The chain, such as <c>5+2</c>, or none.</param>
/// <param name="Equivalent">The single discount equal to the chain, in percent.</param>
public sealed record DiscountQuote(string? Formula, decimal Equivalent)
{
/// <summary>No discount.</summary>
public static DiscountQuote None { get; } = new(null, 0m);
}
/// <summary>A price of a price list for an item at a date.</summary>
/// <param name="Price">The price, or none.</param>
/// <param name="Derived">The price is computed from the base list of a derived list, not written.</param>
/// <param name="ValidFrom">The price is valid from this day.</param>
public sealed record PriceCell(decimal? Price, bool Derived, DateOnly? ValidFrom)
{
/// <summary>No price.</summary>
public static PriceCell Empty { get; } = new(null, false, null);
}
/// <summary>
/// The prices of some items in memory, and the search of SPEC §11.3 (ADR 0030): net price of the party for the item,
/// then the price list of the party or of the document, then the base price list, then the price of the item. A
/// derived list without its own price takes the price of its base list with the markup and the rounding of the list.
/// </summary>
public sealed class PriceBook
{
// A derived list of a derived list... is followed at most this deep (the table forbids only a list on itself).
private const int MaxDepth = 5;
private readonly Dictionary<long, PriceList> _lists;
private readonly ILookup<(long Item, long List), ItemPrice> _listPrices;
private readonly ILookup<(long Item, long Party), ItemPrice> _netPrices;
/// <summary>Creates the book.</summary>
/// <param name="lists">The price lists of the company.</param>
/// <param name="prices">The prices of the items wanted (all their rows).</param>
public PriceBook(IEnumerable<PriceList> lists, IEnumerable<ItemPrice> prices)
{
ArgumentNullException.ThrowIfNull(lists);
ArgumentNullException.ThrowIfNull(prices);
_lists = lists.ToDictionary(l => l.Id);
var all = prices.ToList();
_listPrices = all.Where(p => p.PriceListId is not null).ToLookup(p => (p.ItemId, p.PriceListId!.Value));
_netPrices = all.Where(p => p.PartyId is not null).ToLookup(p => (p.ItemId, p.PartyId!.Value));
Base = BaseOf(_lists.Values);
}
/// <summary>The base price list: the one marked, or the one with code <c>BASE</c>.</summary>
public PriceList? Base { get; }
/// <summary>The price lists.</summary>
public IReadOnlyCollection<PriceList> Lists => _lists.Values;
/// <summary>The base price list among some.</summary>
/// <param name="lists">The price lists.</param>
/// <returns>The base one, or none.</returns>
public static PriceList? BaseOf(IEnumerable<PriceList> lists)
{
ArgumentNullException.ThrowIfNull(lists);
var active = lists.Where(l => !l.Disabled).OrderBy(l => l.Code, StringComparer.Ordinal).ToList();
return active.FirstOrDefault(l => l.IsBase) ?? active.FirstOrDefault(l => l.Code == "BASE");
}
/// <summary>The row in effect at a date: the latest start not after it (a row without start is always valid).</summary>
/// <param name="rows">The rows of one item and one list or party.</param>
/// <param name="date">The date.</param>
/// <returns>The row, or none.</returns>
public static ItemPrice? At(IEnumerable<ItemPrice> rows, DateOnly date)
{
ArgumentNullException.ThrowIfNull(rows);
return rows.Where(r => r.ValidFrom is null || r.ValidFrom <= date).OrderByDescending(r => r.ValidFrom ?? DateOnly.MinValue).FirstOrDefault();
}
/// <summary>Whether a price list can be used at a date: active and within its validity.</summary>
/// <param name="list">The list.</param>
/// <param name="date">The date.</param>
/// <returns>Whether it is valid.</returns>
public static bool IsValid(PriceList list, DateOnly date)
{
ArgumentNullException.ThrowIfNull(list);
return !list.Disabled && (list.ValidFrom is null || list.ValidFrom <= date) && (list.ValidTo is null || list.ValidTo >= date);
}
/// <summary>The price of an item in a list at a date, derived from the base list when the list has none.</summary>
/// <param name="itemId">The item.</param>
/// <param name="listId">The list.</param>
/// <param name="date">The date.</param>
/// <returns>The price.</returns>
public PriceCell ListPrice(long itemId, long listId, DateOnly date) => ListPrice(itemId, listId, date, 0);
/// <summary>The price written in a list for an item at a date, without derivation.</summary>
/// <param name="itemId">The item.</param>
/// <param name="listId">The list.</param>
/// <param name="date">The date.</param>
/// <returns>The row, or none.</returns>
public ItemPrice? OwnPrice(long itemId, long listId, DateOnly date) => At(_listPrices[(itemId, listId)], date);
/// <summary>The net price of a party for an item at a date.</summary>
/// <param name="itemId">The item.</param>
/// <param name="partyId">The party.</param>
/// <param name="date">The date.</param>
/// <returns>The row, or none.</returns>
public ItemPrice? NetPrice(long itemId, long partyId, DateOnly date) => At(_netPrices[(itemId, partyId)], date);
/// <summary>The price proposed for an item (SPEC §11.3): net of the party, list, base list, item.</summary>
/// <param name="item">The item.</param>
/// <param name="partyId">The party of the document.</param>
/// <param name="priceListId">The price list of the party or of the document.</param>
/// <param name="date">The date of the document.</param>
/// <returns>The price and its source.</returns>
public PriceQuote Quote(Item item, long? partyId, long? priceListId, DateOnly date)
{
ArgumentNullException.ThrowIfNull(item);
if (partyId is { } party && NetPrice(item.Id, party, date) is { } net)
{
return new PriceQuote(net.Price, PriceSource.PartyNet, null, false, net.ValidFrom);
}
if (priceListId is { } listId && _lists.TryGetValue(listId, out var list) && IsValid(list, date)
&& ListPrice(item.Id, listId, date) is { Price: { } listPrice } cell)
{
return new PriceQuote(listPrice, PriceSource.PartyPriceList, listId, list.VatIncluded, cell.ValidFrom);
}
if (Base is { } baseList && baseList.Id != priceListId && IsValid(baseList, date)
&& ListPrice(item.Id, baseList.Id, date) is { Price: { } basePrice } baseCell)
{
return new PriceQuote(basePrice, PriceSource.BasePriceList, baseList.Id, baseList.VatIncluded, baseCell.ValidFrom);
}
return item.Price is { } own ? new PriceQuote(own, PriceSource.Item, null, false, null) : PriceQuote.None;
}
/// <summary>The discounts of the party on a price (SPEC §11.3): none on a net price, else the two of the sales terms.</summary>
/// <param name="price">The price proposed.</param>
/// <param name="terms">The sales terms of the party.</param>
/// <returns>The discounts.</returns>
public static DiscountQuote Discounts(PriceQuote price, PartySalesTerms? terms)
{
ArgumentNullException.ThrowIfNull(price);
if (price.Source == PriceSource.PartyNet || terms is null)
{
return DiscountQuote.None;
}
decimal[] steps = [.. new[] { terms.Discount1, terms.Discount2 }.Where(d => d is > 0).Select(d => d!.Value)];
return steps.Length == 0 ? DiscountQuote.None : new DiscountQuote(DiscountFormula.Format(steps), DiscountFormula.Equivalent(steps));
}
private PriceCell ListPrice(long itemId, long listId, DateOnly date, int depth)
{
if (depth > MaxDepth || !_lists.TryGetValue(listId, out var list))
{
return PriceCell.Empty;
}
if (OwnPrice(itemId, listId, date) is { } own)
{
return new PriceCell(own.Price, false, own.ValidFrom);
}
if (list.BasePriceListId is { } parent && ListPrice(itemId, parent, date, depth + 1) is { Price: { } basePrice } from)
{
return new PriceCell(PriceRounding.Round(PriceRounding.Change(basePrice, list.MarkupPercent), list.RoundingStep), true, from.ValidFrom);
}
return PriceCell.Empty;
}
}
@@ -0,0 +1,360 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Items;
/// <summary>A column of the price grid: a price list.</summary>
/// <param name="Id">The list.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="IsBase">The base list.</param>
/// <param name="Derived">Derived from another list.</param>
/// <param name="VatIncluded">Prices with VAT.</param>
public sealed record PriceListColumn(long Id, string Code, string Description, bool IsBase, bool Derived, bool VatIncluded);
/// <summary>A row of the price grid: an item with its price in every list at the date.</summary>
/// <param name="ItemId">The item.</param>
/// <param name="Code">Its code.</param>
/// <param name="Description">Its description.</param>
/// <param name="UnitOfMeasureId">Its unit.</param>
/// <param name="AverageCost">Its average cost (standard when none), only for who sees costs.</param>
/// <param name="Prices">The prices by list.</param>
/// <param name="Net">The net price of the party chosen, if any.</param>
public sealed record PriceGridRow(
long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal? AverageCost, IReadOnlyDictionary<long, PriceCell> Prices, PriceCell? Net);
/// <summary>The price grid (mockup 018).</summary>
/// <param name="Lists">The columns.</param>
/// <param name="Page">The rows.</param>
public sealed record PriceGrid(IReadOnlyList<PriceListColumn> Lists, ListPage<PriceGridRow> Page);
/// <summary>A price to write: of a list or net of a customer, valid from a day; no price removes the row of that day.</summary>
/// <param name="ItemId">The item.</param>
/// <param name="PriceListId">The list.</param>
/// <param name="PartyId">The customer.</param>
/// <param name="Price">The price, or none to remove it.</param>
/// <param name="ValidFrom">Valid from this day.</param>
public sealed record PriceEdit(long ItemId, long? PriceListId, long? PartyId, decimal? Price, DateOnly? ValidFrom);
/// <summary>A mass update of a price list (mockup 018): from the list itself or another one, a percent and a rounding.</summary>
public sealed record BulkUpdate
{
/// <summary>The list to update.</summary>
public long PriceListId { get; init; }
/// <summary>The list the prices start from; none: the list itself.</summary>
public long? SourcePriceListId { get; init; }
/// <summary>The change in percent, also negative.</summary>
public decimal Percent { get; init; }
/// <summary>The rounding step, such as 0.10, 0.50 or 1.00; zero: cents.</summary>
public decimal RoundingStep { get; init; }
/// <summary>Rounding up, down or to the nearest.</summary>
public RoundingDirection Direction { get; init; }
/// <summary>The prices are read at this day and the new ones are valid from it.</summary>
public DateOnly Date { get; init; }
/// <summary>Only the items of this category.</summary>
public long? CategoryId { get; init; }
/// <summary>Only these items (the selection); none: all the active items with a price.</summary>
public IReadOnlyList<long>? ItemIds { get; init; }
}
/// <summary>
/// Price lists (mockup 018, ADR 0030): the grid of items by lists at a date with the net prices of a customer, mass
/// updates, the writing of prices with their validity, and the price and discounts proposed for a document line.
/// </summary>
/// <remarks>Permissions <c>items.item.read</c> and <c>write</c>; costs and margins with <c>items.cost.read</c>.</remarks>
public sealed class PriceListService
{
/// <summary>Error: a price is negative.</summary>
public const string NotNegative = ItemService.NotNegative;
/// <summary>Error: the list of a mass update does not exist.</summary>
public const string ListUnknown = "items.price-list.unknown";
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly ItemService _items;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="audit">The audit trail.</param>
/// <param name="items">The items (for the cost permission).</param>
public PriceListService(IUnitOfWorkFactory factory, PermissionService permissions, AuditTrail audit, ItemService items)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(items);
_factory = factory;
_permissions = permissions;
_audit = audit;
_items = items;
}
/// <summary>The active price lists: the base one first, then by code.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The lists.</returns>
public async Task<IReadOnlyList<PriceListColumn>> ListsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false);
}
/// <summary>The price grid: a page of items (no text items) with the price of every list at a date.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="query">Search, filters (those of the items radar), sort, page.</param>
/// <param name="date">The day the prices are read at.</param>
/// <param name="partyId">The customer whose net prices are shown.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The grid.</returns>
public async Task<PriceGrid> GridAsync(Actor actor, string companyCode, ListQuery query, DateOnly date, long? partyId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
var costs = await _items.CanSeeCostsAsync(actor, company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var columns = await ColumnsAsync(uow, cancellationToken).ConfigureAwait(false);
var page = await uow.Repository<Item, long>().ListAsync(
ItemService.Fields.Apply(Query.For<Item>().Where(i => i.Kind != ItemKind.Text), query), cancellationToken).ConfigureAwait(false);
var book = await ItemService.BookAsync(uow, [.. page.Items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
IReadOnlyList<PriceGridRow> rows =
[
.. page.Items.Select(i => new PriceGridRow(
i.Id, i.Code, i.Description, i.UnitOfMeasureId, costs ? i.AverageCost ?? i.StandardCost : null,
columns.ToDictionary(c => c.Id, c => book.ListPrice(i.Id, c.Id, date)),
partyId is { } party ? book.NetPrice(i.Id, party, date) is { } net ? new PriceCell(net.Price, false, net.ValidFrom) : PriceCell.Empty : null)),
];
return new PriceGrid(columns, new ListPage<PriceGridRow>(rows, page.TotalCount, new Dictionary<string, decimal>()));
}
/// <summary>
/// Computes a mass update without saving it: for every item with a price in the source list at the date, the new
/// price of the list, changed by the percent and rounded. The screen shows them highlighted until saved.
/// </summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="update">The update.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The prices to write; unchanged ones are left out.</returns>
/// <exception cref="ValidationFailedException">When the lists are unknown or the step negative.</exception>
public async Task<IReadOnlyList<PriceEdit>> PreviewAsync(Actor actor, string companyCode, BulkUpdate update, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(update);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var lists = uow.Repository<PriceList, long>();
var source = update.SourcePriceListId ?? update.PriceListId;
if (await lists.GetAsync(update.PriceListId, cancellationToken).ConfigureAwait(false) is null || await lists.GetAsync(source, cancellationToken).ConfigureAwait(false) is null)
{
throw new ValidationFailedException([nameof(BulkUpdate.PriceListId) + ":" + ListUnknown]);
}
if (update.RoundingStep < 0)
{
throw new ValidationFailedException([nameof(BulkUpdate.RoundingStep) + ":" + TableCatalog.NumberRange]);
}
var select = Query.For<Item>().Where(i => !i.Disabled && i.Kind != ItemKind.Text);
if (update.CategoryId is { } category)
{
select = select.Where(i => i.CategoryId == category);
}
var items = (await uow.Repository<Item, long>().ListAsync(select, cancellationToken).ConfigureAwait(false)).Items;
if (update.ItemIds is { } wanted)
{
var only = wanted.ToHashSet();
items = [.. items.Where(i => only.Contains(i.Id))];
}
var book = await ItemService.BookAsync(uow, [.. items.Select(i => i.Id)], cancellationToken).ConfigureAwait(false);
var edits = new List<PriceEdit>();
foreach (var item in items.OrderBy(i => i.Code, StringComparer.Ordinal))
{
if (book.ListPrice(item.Id, source, update.Date).Price is not { } from)
{
continue;
}
var price = PriceRounding.Round(PriceRounding.Change(from, update.Percent), update.RoundingStep, update.Direction);
if (book.ListPrice(item.Id, update.PriceListId, update.Date).Price != price)
{
edits.Add(new PriceEdit(item.Id, update.PriceListId, null, price, update.Date));
}
}
return edits;
}
/// <summary>
/// Writes prices: a row of the same list or customer and day is changed (or removed when the price is none), else a
/// new row starts that day, so the prices before it stay for older documents. A price equal to the one in effect is
/// not written again. Every change goes in the history of the item.
/// </summary>
/// <param name="actor">Who saves.</param>
/// <param name="companyCode">The company.</param>
/// <param name="edits">The prices.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many rows were written or removed.</returns>
/// <exception cref="ValidationFailedException">With the errors (<c>index:code</c>).</exception>
public async Task<int> SaveAsync(Actor actor, string companyCode, IReadOnlyList<PriceEdit> edits, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(edits);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.WritePermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var problems = new List<string>();
var parties = uow.Repository<Party, long>();
for (var i = 0; i < edits.Count; i++)
{
var edit = edits[i];
if ((edit.PriceListId is null) == (edit.PartyId is null))
{
problems.Add(i + ":" + ItemService.PriceTarget);
}
else if (edit.PartyId is { } partyId && await parties.GetAsync(partyId, cancellationToken).ConfigureAwait(false) is not { IsCustomer: true })
{
problems.Add(i + ":" + ItemService.PriceParty);
}
if (edit.Price < 0)
{
problems.Add(i + ":" + NotNegative);
}
}
if (problems.Count > 0)
{
throw new ValidationFailedException(problems);
}
var prices = uow.Repository<ItemPrice, long>();
var written = 0;
foreach (var group in edits.GroupBy(e => e.ItemId))
{
var itemId = group.Key;
var rows = (await prices.ListAsync(Query.For<ItemPrice>().Where(p => p.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items.ToList();
foreach (var edit in group)
{
var same = rows.Where(r => r.PriceListId == edit.PriceListId && r.PartyId == edit.PartyId).ToList();
var day = same.FirstOrDefault(r => r.ValidFrom == edit.ValidFrom);
if (edit.Price is not { } price)
{
if (day is not null)
{
await prices.DeleteAsync(day.Id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Delete, itemId, day, null, actor.UserName, cancellationToken).ConfigureAwait(false);
rows.Remove(day);
written++;
}
continue;
}
if (day is not null)
{
if (day.Price != price)
{
var before = Copy(day);
day.Price = price;
await prices.UpdateAsync(day, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, itemId, before, day, actor.UserName, cancellationToken).ConfigureAwait(false);
written++;
}
continue;
}
if (edit.ValidFrom is { } from && PriceBook.At(same, from) is { } current && current.Price == price)
{
continue;
}
var row = new ItemPrice { ItemId = itemId, PriceListId = edit.PriceListId, PartyId = edit.PartyId, Price = price, ValidFrom = edit.ValidFrom };
row.Id = await prices.InsertAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<ItemPrice>(uow, AuditAction.Insert, itemId, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
rows.Add(row);
written++;
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return written;
}
/// <summary>
/// The price and the discounts proposed for an item on a document (SPEC §11.3): net price of the party, then the
/// list given or the one of the party, then the base list, then the item; the discounts of the party unless net.
/// </summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="itemId">The item.</param>
/// <param name="partyId">The party of the document.</param>
/// <param name="priceListId">The list of the document; none: the one of the party.</param>
/// <param name="date">The date of the document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The price and the discounts.</returns>
public async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync(
Actor actor, string companyCode, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ItemService.ReadPermission, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await QuoteAsync(uow, itemId, partyId, priceListId, date, cancellationToken).ConfigureAwait(false);
}
/// <summary>The price and the discounts of a line, inside the unit of work of a document.</summary>
/// <param name="uow">The unit of work of the company.</param>
/// <param name="itemId">The item.</param>
/// <param name="partyId">The party of the document.</param>
/// <param name="priceListId">The list of the document; none: the one of the party.</param>
/// <param name="date">The date of the document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The price and the discounts.</returns>
public static async Task<(PriceQuote Price, DiscountQuote Discounts)> QuoteAsync(
IUnitOfWork uow, long itemId, long? partyId, long? priceListId, DateOnly date, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(uow);
var item = await uow.Repository<Item, long>().GetAsync(itemId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(ItemService.NotFound);
var terms = partyId is { } party
? await uow.Repository<PartySalesTerms, long>().FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == party), cancellationToken).ConfigureAwait(false)
: null;
var book = await ItemService.BookAsync(uow, [itemId], cancellationToken).ConfigureAwait(false);
var price = book.Quote(item, partyId, priceListId ?? terms?.PriceListId, date);
return (price, PriceBook.Discounts(price, terms));
}
private static async Task<IReadOnlyList<PriceListColumn>> ColumnsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var lists = (await uow.Repository<PriceList, long>().ListAsync(Query.For<PriceList>().Where(l => !l.Disabled), cancellationToken).ConfigureAwait(false)).Items;
var baseList = PriceBook.BaseOf(lists);
return
[
.. lists.OrderBy(l => l.Id == baseList?.Id ? 0 : 1).ThenBy(l => l.Code, StringComparer.Ordinal)
.Select(l => new PriceListColumn(l.Id, l.Code, l.Description, l.Id == baseList?.Id, l.BasePriceListId is not null, l.VatIncluded)),
];
}
private static ItemPrice Copy(ItemPrice price) => new()
{
Id = price.Id, ItemId = price.ItemId, PriceListId = price.PriceListId, PartyId = price.PartyId, Price = price.Price, ValidFrom = price.ValidFrom,
};
}
@@ -4,6 +4,8 @@ using Khaemhat.Core.Instance;
using Khaemhat.Application.Querying;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Application.Items;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Validation;
@@ -37,6 +39,9 @@ public sealed class PartyRecord
/// <summary>The bank accounts.</summary>
public List<PartyBankAccount> BankAccounts { get; set; } = [];
/// <summary>The codes the party uses for our items (tab <i>Articoli e codici</i>).</summary>
public List<PartyItemCode> ItemCodes { get; set; } = [];
}
/// <summary>Which parties a radar shows (menu <i>Anagrafiche</i>).</summary>
@@ -538,6 +543,26 @@ public sealed class PartyService
return [.. entries.OrderByDescending(e => e.At).ThenByDescending(e => e.Id)];
}
/// <summary>The rows of some parties, for the lookups that show them by id.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The parties.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows found.</returns>
public async Task<IReadOnlyList<PartyRow>> RowsAsync(Actor actor, string companyCode, IEnumerable<long> ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
long[] wanted = [.. ids.Distinct()];
if (wanted.Length == 0)
{
return [];
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return [.. (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => wanted.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items.Select(RowOf)];
}
private static PartyRow RowOf(Party p) =>
new(p.Id, p.Code, p.Name, p.Kind, p.IsAlsoSupplier, p.SubjectType, p.VatNumber, p.TaxCode, p.City, p.Province, p.CountryCode, p.SalespersonId, p.CategoryId, p.Disabled);
@@ -563,6 +588,7 @@ public sealed class PartyService
Addresses = [.. (await uow.Repository<PartyAddress, long>().ListAsync(Query.For<PartyAddress>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
Contacts = [.. (await uow.Repository<PartyContact, long>().ListAsync(Query.For<PartyContact>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
BankAccounts = [.. (await uow.Repository<PartyBankAccount, long>().ListAsync(Query.For<PartyBankAccount>().Where(a => a.PartyId == id).OrderBy(a => a.Id), cancellationToken).ConfigureAwait(false)).Items],
ItemCodes = [.. (await uow.Repository<PartyItemCode, long>().ListAsync(Query.For<PartyItemCode>().Where(a => a.PartyId == id).OrderBy(a => a.Code), cancellationToken).ConfigureAwait(false)).Items],
};
}
@@ -588,6 +614,7 @@ public sealed class PartyService
await ReplaceAsync(uow, record.Addresses, before?.Addresses ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.Contacts, before?.Contacts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.BankAccounts, before?.BankAccounts ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
await ReplaceAsync(uow, record.ItemCodes, before?.ItemCodes ?? [], a => a.PartyId = id, cancellationToken).ConfigureAwait(false);
return id;
}
@@ -922,6 +949,8 @@ public sealed class PartyService
}
}
problems.AddRange(ItemService.CheckPartyCodes(record.ItemCodes));
// One default per list: the first one marked wins.
OneDefault(record.Contacts, c => c.IsDefault, (c, v) => c.IsDefault = v);
OneDefault(record.BankAccounts, c => c.IsDefault, (c, v) => c.IsDefault = v);
@@ -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);
@@ -63,6 +63,9 @@ public sealed partial class TableCatalog
/// <summary>Error: a transfer reason must not change quantities by itself.</summary>
public const string TransferEffect = "tables.inventory-reason.transfer";
/// <summary>Error: another price list is already the base one.</summary>
public const string BaseDuplicate = "tables.price-list.base-duplicate";
/// <summary>The maximum depth of item categories.</summary>
public const int MaxCategoryLevel = 3;
@@ -247,6 +250,12 @@ public sealed partial class TableCatalog
{
c.Error(nameof(PriceList.BasePriceListId), ParentInvalid);
}
var id = x.Id;
if (x.IsBase && await c.CountAsync<PriceList>(p => p.IsBase && p.Id != id, ct).ConfigureAwait(false) > 0)
{
c.Error(nameof(PriceList.IsBase), BaseDuplicate);
}
}));
Add(new TableDefinition<DiscountPolicy>("discount-policies", "discount_policies")
.Field("formula", x => x.Formula)
@@ -54,6 +54,15 @@ public sealed class TableRuleContext
where TOther : class, IEntity<long>, new() =>
_unitOfWork.Repository<TOther, long>().GetAsync(id, cancellationToken);
/// <summary>Counts the rows of another table that match.</summary>
/// <typeparam name="TOther">The other table.</typeparam>
/// <param name="where">The condition.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many rows match.</returns>
public Task<int> CountAsync<TOther>(System.Linq.Expressions.Expression<Func<TOther, bool>> where, CancellationToken cancellationToken)
where TOther : class, IEntity<long>, new() =>
_unitOfWork.Repository<TOther, long>().CountAsync(Query.For<TOther>().Where(where), cancellationToken);
/// <summary>Whether a coded row with a code exists.</summary>
/// <typeparam name="TOther">The entity.</typeparam>
/// <param name="code">The code.</param>