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>
266 lines
18 KiB
C#
266 lines
18 KiB
C#
using Khaemhat.Application.Items;
|
|
using Khaemhat.Application.Parties;
|
|
using Khaemhat.Application.Querying;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Application.Tables;
|
|
using Khaemhat.Core.Items;
|
|
using Khaemhat.Core.Parties;
|
|
using Khaemhat.Core.Security;
|
|
using Khaemhat.Core.Tables;
|
|
using Khaemhat.Web.Tests.Hosting;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Khaemhat.Web.Tests.Items;
|
|
|
|
/// <summary>Items and price lists on a real instance (issue #42): codes, details, checks, costs, search, prices with validity.</summary>
|
|
[TestClass]
|
|
public sealed class ItemServiceTests
|
|
{
|
|
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
|
|
|
[TestMethod]
|
|
public async Task Item_GetsTheCodeOfItsCategory_AndItsDetailsAreSavedWithIt()
|
|
{
|
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
|
await using (app)
|
|
{
|
|
var items = app.Services.GetRequiredService<ItemService>();
|
|
var (category, box, _) = await TablesAsync(app, company);
|
|
var substitute = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("Valvola a farfalla 1/2\"", category));
|
|
|
|
var record = await items.NewAsync(Root, company);
|
|
Assert.AreEqual(ItemKind.Goods, record.Item.Kind);
|
|
Assert.IsTrue(record.Item.Stocked);
|
|
Assert.IsNotNull(record.Item.UnitOfMeasureId, "PZ by default.");
|
|
Assert.IsNotNull(record.Item.SalesTaxCodeId, "VAT 22 by default.");
|
|
record.Item.Description = " Valvola a sfera 1/2\" ";
|
|
record.Item.CategoryId = category;
|
|
record.Item.Barcode = "2000000000015";
|
|
record.Units.Add(new ItemUnit { UnitOfMeasureId = box, Factor = 10m });
|
|
record.Barcodes.Add(new ItemBarcode { Code = " OLD-77 " });
|
|
record.Substitutes.Add(new ItemSubstitute { SubstituteId = substitute.Item.Id });
|
|
var saved = await items.SaveAsync(Root, company, record);
|
|
|
|
Assert.AreEqual("VALV-0002", saved.Item.Code);
|
|
Assert.AreEqual("Valvola a sfera 1/2\"", saved.Item.Description);
|
|
Assert.AreEqual(10m, saved.Units.Single().Factor);
|
|
Assert.AreEqual("OLD-77", saved.Barcodes.Single().Code);
|
|
Assert.AreEqual(substitute.Item.Id, saved.Substitutes.Single().SubstituteId);
|
|
|
|
// A service is never in stock; the search finds the alternative code exactly.
|
|
saved.Item.Kind = ItemKind.Service;
|
|
var service = await items.SaveAsync(Root, company, saved);
|
|
Assert.IsFalse(service.Item.Stocked);
|
|
Assert.AreEqual(saved.Item.Id, (await items.SearchAsync(Root, company, "OLD-77")).Single().Id);
|
|
Assert.IsNotEmpty(await items.HistoryAsync(Root, company, saved.Item.Id));
|
|
|
|
var list = await items.ListAsync(Root, company, new ListQuery { Search = "sfera" });
|
|
Assert.AreEqual("VALV-0002", list.Items.Single().Code);
|
|
|
|
// Used as a substitute, the other item is disabled instead of deleted.
|
|
Assert.AreEqual(ItemDeleteOutcome.Disabled, await items.DeleteAsync(Root, company, substitute.Item.Id));
|
|
Assert.AreEqual(ItemDeleteOutcome.Deleted, await items.DeleteAsync(Root, company, saved.Item.Id));
|
|
await app.StopAsync();
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task Save_RefusesWhatTheRulesDoNotAllow()
|
|
{
|
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
|
await using (app)
|
|
{
|
|
var items = app.Services.GetRequiredService<ItemService>();
|
|
var (category, box, _) = await TablesAsync(app, company);
|
|
var other = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId, r.Item.Barcode) = ("Altro", category, "2000000000022"));
|
|
|
|
async Task<string[]> ErrorsAsync(Action<ItemRecord> fill)
|
|
{
|
|
var record = await items.NewAsync(Root, company);
|
|
record.Item.Description = "Prova";
|
|
record.Item.CategoryId = category;
|
|
fill(record);
|
|
return [.. (await items.ValidateAsync(Root, company, record)).Select(p => p.Field + ":" + p.Code + (p.IsWarning ? "!" : string.Empty))];
|
|
}
|
|
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Description = " "), "Description:" + ItemService.DescriptionRequired);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.CategoryId = null), "CategoryId:" + ItemService.CategoryRequired);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Code = other.Item.Code), "Code:" + ItemService.CodeDuplicate);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Barcode = "2000000000016"), "Barcode:" + ItemService.BarcodeInvalid);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Barcode = "2000000000022"), "Barcode:" + ItemService.BarcodeDuplicate,
|
|
"By default the code rules want the bar code unique.");
|
|
var rules = app.Services.GetRequiredService<CodeRuleService>();
|
|
await rules.SaveAsync(Root, company, [.. (await rules.RulesAsync(Root, company)).Select(r => r with { UniqueBarcode = false })]);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.Barcode = "2000000000022"), "Barcode:" + ItemService.BarcodeDuplicate + "!",
|
|
"Without the rule the same bar code is a warning.");
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.CustomsCode = "8481"), "CustomsCode:" + ItemService.CustomsCodeInvalid);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Item.MinimumStock = -1), "MinimumStock:" + ItemService.NotNegative);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Units.Add(new ItemUnit { UnitOfMeasureId = box, Factor = 0 })), "Units.0.Factor:" + ItemService.FactorInvalid);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Units.Add(new ItemUnit { UnitOfMeasureId = r.Item.UnitOfMeasureId!.Value, Factor = 1 })), "Units.0.UnitOfMeasureId:" + ItemService.UnitDuplicate);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Units.Add(new ItemUnit())), "Units.0.UnitOfMeasureId:" + ItemService.DetailRequired);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Barcodes.AddRange([new ItemBarcode { Code = "X1" }, new ItemBarcode { Code = "X1" }])), "Barcodes.1.Code:" + ItemService.DetailDuplicate);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Prices.Add(new ItemPrice { Price = 1 })), "Prices.0.PriceListId:" + ItemService.PriceTarget);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Prices.Add(new ItemPrice { PartyId = 0, Price = 1 })), "Prices.0.PartyId:" + ItemService.DetailRequired);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Suppliers.Add(new ItemSupplier())), "Suppliers.0.PartyId:" + ItemService.DetailRequired);
|
|
CollectionAssert.Contains(await ErrorsAsync(r => r.Substitutes.Add(new ItemSubstitute())), "Substitutes.0.SubstituteId:" + ItemService.DetailRequired);
|
|
await app.StopAsync();
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task Costs_AreHiddenAndKept_ForWhoCannotSeeThem()
|
|
{
|
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
|
await using (app)
|
|
{
|
|
var items = app.Services.GetRequiredService<ItemService>();
|
|
var users = app.Services.GetRequiredService<UserService>();
|
|
var (category, _, _) = await TablesAsync(app, company);
|
|
var item = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId, r.Item.StandardCost) = ("Caldaia", category, 800m));
|
|
var (user, _) = await users.CreateAsync(Root, company, new NewCompanyUser("magazzino", "Magazzino", null, UserKind.Human, ["WAREHOUSE"], new UserFlags(false, false, false, false)));
|
|
var warehouse = new Actor("magazzino", UserLevel.Standard, null, user.Id, company);
|
|
|
|
Assert.IsFalse(await items.CanSeeCostsAsync(warehouse, company));
|
|
var seen = (await items.GetAsync(warehouse, company, item.Item.Id))!;
|
|
Assert.IsNull(seen.Item.StandardCost);
|
|
seen.Item.Brand = "Termodemo";
|
|
seen.Item.StandardCost = 1m;
|
|
await items.SaveAsync(warehouse, company, seen);
|
|
Assert.AreEqual(800m, (await items.GetAsync(Root, company, item.Item.Id))!.Item.StandardCost, "The cost stays as it was.");
|
|
Assert.IsNull((await items.ListAsync(warehouse, company, new ListQuery())).Items.Single().AverageCost);
|
|
await app.StopAsync();
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task PriceGrid_ReadsAndWritesPricesAtADate_KeepingTheOlderOnes()
|
|
{
|
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
|
await using (app)
|
|
{
|
|
var items = app.Services.GetRequiredService<ItemService>();
|
|
var prices = app.Services.GetRequiredService<PriceListService>();
|
|
var tables = app.Services.GetRequiredService<TableService>();
|
|
var (category, _, baseList) = await TablesAsync(app, company);
|
|
var derived = await tables.SaveAsync(Root, company, new PriceList { Code = "PUBB", Description = "Pubblico", BasePriceListId = baseList, MarkupPercent = 45m, RoundingStep = 0.10m });
|
|
var valve = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("Valvola", category));
|
|
var customer = await CustomerAsync(app, company);
|
|
var jan = new DateOnly(2026, 1, 1);
|
|
var jun = new DateOnly(2026, 6, 1);
|
|
|
|
Assert.AreEqual(2, await prices.SaveAsync(Root, company,
|
|
[new PriceEdit(valve.Item.Id, baseList, null, 32m, jan), new PriceEdit(valve.Item.Id, null, customer, 30.40m, jan)]));
|
|
Assert.AreEqual(1, await prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, baseList, null, 34m, jun)]));
|
|
Assert.AreEqual(0, await prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, baseList, null, 34m, new DateOnly(2026, 7, 1))]),
|
|
"The price in effect is not written again.");
|
|
|
|
var march = await prices.GridAsync(Root, company, new ListQuery(), new DateOnly(2026, 3, 1), customer);
|
|
var row = march.Page.Items.Single();
|
|
Assert.AreEqual(baseList, march.Lists[0].Id, "The base list first.");
|
|
Assert.AreEqual(32m, row.Prices[baseList].Price);
|
|
Assert.AreEqual(new PriceCell(46.40m, true, jan), row.Prices[derived.Id]);
|
|
Assert.AreEqual(30.40m, row.Net!.Price);
|
|
Assert.AreEqual(34m, (await prices.GridAsync(Root, company, new ListQuery(), jun, null)).Page.Items.Single().Prices[baseList].Price);
|
|
|
|
// The quote of a document line: net price for the customer, base list for anybody else.
|
|
Assert.AreEqual((30.40m, PriceSource.PartyNet), Short(await prices.QuoteAsync(Root, company, valve.Item.Id, customer, null, jun)));
|
|
Assert.AreEqual((34m, PriceSource.BasePriceList), Short(await prices.QuoteAsync(Root, company, valve.Item.Id, null, null, jun)));
|
|
Assert.AreEqual((49.30m, PriceSource.PartyPriceList), Short(await prices.QuoteAsync(Root, company, valve.Item.Id, null, derived.Id, jun)));
|
|
|
|
// The same day changes the row; no price removes it.
|
|
await prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, baseList, null, 35m, jun)]);
|
|
Assert.AreEqual(35m, (await prices.GridAsync(Root, company, new ListQuery(), jun, null)).Page.Items.Single().Prices[baseList].Price);
|
|
await prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, baseList, null, null, jun)]);
|
|
Assert.AreEqual(32m, (await prices.GridAsync(Root, company, new ListQuery(), jun, null)).Page.Items.Single().Prices[baseList].Price);
|
|
Assert.IsTrue((await items.HistoryAsync(Root, company, valve.Item.Id)).Count >= 4, "Every price goes in the history of the item.");
|
|
|
|
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => prices.SaveAsync(Root, company, [new PriceEdit(valve.Item.Id, null, null, 1m, jun)]));
|
|
await app.StopAsync();
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task BulkUpdate_ComputesTheChangedPrices_WithoutSavingThem()
|
|
{
|
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
|
await using (app)
|
|
{
|
|
var items = app.Services.GetRequiredService<ItemService>();
|
|
var prices = app.Services.GetRequiredService<PriceListService>();
|
|
var tables = app.Services.GetRequiredService<TableService>();
|
|
var (category, _, baseList) = await TablesAsync(app, company);
|
|
var resellers = await tables.SaveAsync(Root, company, new PriceList { Code = "RIV", Description = "Rivenditori" });
|
|
var a = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("A", category));
|
|
var b = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("B", category));
|
|
var date = new DateOnly(2026, 1, 1);
|
|
await prices.SaveAsync(Root, company, [new PriceEdit(a.Item.Id, baseList, null, 10m, date), new PriceEdit(b.Item.Id, baseList, null, 21.37m, date)]);
|
|
|
|
var up = await prices.PreviewAsync(Root, company, new BulkUpdate { PriceListId = baseList, Percent = 5m, RoundingStep = 0.50m, Direction = RoundingDirection.Up, Date = date });
|
|
CollectionAssert.AreEqual(new[] { 10.50m, 22.50m }, up.Select(e => e.Price).ToArray());
|
|
Assert.AreEqual(10m, (await prices.GridAsync(Root, company, new ListQuery(), date, null)).Page.Items.First(r => r.ItemId == a.Item.Id).Prices[baseList].Price, "Nothing saved.");
|
|
|
|
var fromBase = await prices.PreviewAsync(Root, company,
|
|
new BulkUpdate { PriceListId = resellers.Id, SourcePriceListId = baseList, Percent = -10m, RoundingStep = 0.10m, Date = date, ItemIds = [b.Item.Id] });
|
|
Assert.AreEqual(new PriceEdit(b.Item.Id, resellers.Id, null, 19.20m, date), fromBase.Single());
|
|
Assert.IsEmpty(await prices.PreviewAsync(Root, company, new BulkUpdate { PriceListId = baseList, Date = date }), "No change, nothing to write.");
|
|
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => prices.PreviewAsync(Root, company, new BulkUpdate { PriceListId = 999, Date = date }));
|
|
await app.StopAsync();
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task PartyItemCodes_AreSavedWithTheParty_AndFoundByTheSearchOfItsDocuments()
|
|
{
|
|
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
|
await using (app)
|
|
{
|
|
var items = app.Services.GetRequiredService<ItemService>();
|
|
var parties = app.Services.GetRequiredService<PartyService>();
|
|
var (category, _, _) = await TablesAsync(app, company);
|
|
var valve = await SaveAsync(items, company, r => (r.Item.Description, r.Item.CategoryId) = ("Valvola", category));
|
|
var customer = await CustomerAsync(app, company);
|
|
|
|
var record = (await parties.GetAsync(Root, company, customer))!;
|
|
record.ItemCodes.Add(new PartyItemCode { ItemId = valve.Item.Id, Code = " RI-100 " });
|
|
record.ItemCodes.Add(new PartyItemCode { ItemId = valve.Item.Id, Code = "RI-100" });
|
|
Assert.IsTrue((await parties.ValidateAsync(Root, company, record)).Any(p => p.Field == "ItemCodes.1.Code" && p.Code == ItemService.PartyCodeDuplicate));
|
|
record.ItemCodes.RemoveAt(1);
|
|
var saved = await parties.SaveAsync(Root, company, record);
|
|
Assert.AreEqual("RI-100", saved.ItemCodes.Single().Code);
|
|
|
|
Assert.AreEqual(valve.Item.Id, (await items.SearchAsync(Root, company, "RI-100", customer)).Single().Id);
|
|
Assert.IsEmpty(await items.SearchAsync(Root, company, "RI-100"), "Another party does not use that code.");
|
|
Assert.AreEqual("Valvola", (await items.RowsAsync(Root, company, [valve.Item.Id])).Single().Description);
|
|
Assert.AreEqual(customer, (await parties.RowsAsync(Root, company, [customer])).Single().Id);
|
|
await app.StopAsync();
|
|
}
|
|
}
|
|
|
|
private static (decimal? Price, PriceSource Source) Short((PriceQuote Price, DiscountQuote Discounts) quote) => (quote.Price.Price, quote.Price.Source);
|
|
|
|
private static async Task<ItemRecord> SaveAsync(ItemService items, string company, Action<ItemRecord> fill)
|
|
{
|
|
var record = await items.NewAsync(Root, company);
|
|
fill(record);
|
|
return await items.SaveAsync(Root, company, record);
|
|
}
|
|
|
|
private static async Task<(long Category, long Box, long BaseList)> TablesAsync(Microsoft.AspNetCore.Builder.WebApplication app, string company)
|
|
{
|
|
var tables = app.Services.GetRequiredService<TableService>();
|
|
var category = await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" });
|
|
var units = await tables.ListAsync<UnitOfMeasure>(Root, company, new ListQuery { Limit = 100 });
|
|
var lists = await tables.ListAsync<PriceList>(Root, company, new ListQuery { Limit = 100 });
|
|
return (category.Id, units.Items.Single(u => u.Code == "CT").Id, lists.Items.Single(l => l.IsBase).Id);
|
|
}
|
|
|
|
private static async Task<long> CustomerAsync(Microsoft.AspNetCore.Builder.WebApplication app, string company)
|
|
{
|
|
var parties = app.Services.GetRequiredService<PartyService>();
|
|
var record = await parties.NewAsync(Root, company, PartyKind.Customer);
|
|
record.Party.Name = "Rossi Impianti S.r.l.";
|
|
record.Party.VatNumber = "01234567897";
|
|
return (await parties.SaveAsync(Root, company, record)).Party.Id;
|
|
}
|
|
}
|