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; /// Items and price lists on a real instance (issue #42): codes, details, checks, costs, search, prices with validity. [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(); 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(); 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 ErrorsAsync(Action 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(); 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(); var users = app.Services.GetRequiredService(); 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(); var prices = app.Services.GetRequiredService(); var tables = app.Services.GetRequiredService(); 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(() => 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(); var prices = app.Services.GetRequiredService(); var tables = app.Services.GetRequiredService(); 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(() => 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(); var parties = app.Services.GetRequiredService(); 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 SaveAsync(ItemService items, string company, Action 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(); var category = await tables.SaveAsync(Root, company, new ItemCategory { Code = "VALV", Description = "Valvolame" }); var units = await tables.ListAsync(Root, company, new ListQuery { Limit = 100 }); var lists = await tables.ListAsync(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 CustomerAsync(Microsoft.AspNetCore.Builder.WebApplication app, string company) { var parties = app.Services.GetRequiredService(); 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; } }