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:
1 parent
c8241a414e
commit
3dbbaba86e
46 files changed
+5318
-144
No files matched your search
@@ -0,0 +1,85 @@
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Tables;
|
||||
|
||||
namespace Khaemhat.Application.Tests;
|
||||
|
||||
/// <summary>The search of the price of a line (SPEC §11.3, ADR 0030): net price, list, base list, item; validity and derived lists.</summary>
|
||||
[TestClass]
|
||||
public sealed class PriceBookTests
|
||||
{
|
||||
private static readonly DateOnly Jan = new(2026, 1, 1);
|
||||
private static readonly DateOnly Jun = new(2026, 6, 1);
|
||||
private static readonly PriceList Base = new() { Id = 1, Code = "BASE", Description = "Base", IsBase = true };
|
||||
private static readonly PriceList Public = new() { Id = 2, Code = "PUBB", Description = "Pubblico", BasePriceListId = 1, MarkupPercent = 45m, RoundingStep = 0.10m };
|
||||
private static readonly PriceList Resellers = new() { Id = 3, Code = "RIV", Description = "Rivenditori", BasePriceListId = 1, MarkupPercent = -10m };
|
||||
private static readonly PriceList Expired = new() { Id = 4, Code = "OLD", Description = "Scaduto", ValidTo = new DateOnly(2025, 12, 31) };
|
||||
private static readonly Item Valve = new() { Id = 10, Code = "VALV-0001", Description = "Valvola", Price = 30m };
|
||||
private static readonly Item Service = new() { Id = 11, Code = "SERV-0001", Description = "Manodopera", Price = 38m };
|
||||
|
||||
private static PriceBook Book() => new(
|
||||
[Base, Public, Resellers, Expired],
|
||||
[
|
||||
new ItemPrice { ItemId = 10, PriceListId = 1, Price = 30.70m, ValidFrom = new DateOnly(2025, 1, 1) },
|
||||
new ItemPrice { ItemId = 10, PriceListId = 1, Price = 32m, ValidFrom = Jan },
|
||||
new ItemPrice { ItemId = 10, PriceListId = 1, Price = 34m, ValidFrom = Jun },
|
||||
new ItemPrice { ItemId = 10, PriceListId = 3, Price = 27.50m, ValidFrom = Jan },
|
||||
new ItemPrice { ItemId = 10, PriceListId = 4, Price = 1m },
|
||||
new ItemPrice { ItemId = 10, PartyId = 99, Price = 30.40m, ValidFrom = Jan },
|
||||
]);
|
||||
|
||||
[TestMethod]
|
||||
public void ListPrice_IsTheLatestStartNotAfterTheDate()
|
||||
{
|
||||
var book = Book();
|
||||
Assert.AreEqual(30.70m, book.ListPrice(10, 1, new DateOnly(2025, 6, 1)).Price);
|
||||
Assert.AreEqual(32m, book.ListPrice(10, 1, new DateOnly(2026, 5, 31)).Price);
|
||||
Assert.AreEqual(new PriceCell(34m, false, Jun), book.ListPrice(10, 1, new DateOnly(2026, 7, 1)));
|
||||
Assert.IsNull(book.ListPrice(10, 1, new DateOnly(2024, 12, 31)).Price, "Nothing before the first price.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DerivedList_TakesTheBaseWithMarkupAndRounding_UnlessItHasItsOwn()
|
||||
{
|
||||
var book = Book();
|
||||
Assert.AreEqual(new PriceCell(46.40m, true, Jan), book.ListPrice(10, 2, new DateOnly(2026, 3, 1)), "32 + 45% = 46.40.");
|
||||
Assert.AreEqual(49.30m, book.ListPrice(10, 2, Jun).Price, "34 + 45% = 49.30.");
|
||||
Assert.AreEqual(new PriceCell(27.50m, false, Jan), book.ListPrice(10, 3, Jun), "Its own price wins over the derived one.");
|
||||
Assert.AreEqual(PriceCell.Empty, book.ListPrice(11, 2, Jun), "No base price, nothing to derive.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Quote_SearchesNet_ThenList_ThenBase_ThenItem()
|
||||
{
|
||||
var book = Book();
|
||||
Assert.AreEqual(new PriceQuote(30.40m, PriceSource.PartyNet, null, false, Jan), book.Quote(Valve, 99, 2, Jun));
|
||||
Assert.AreEqual(PriceSource.PartyPriceList, book.Quote(Valve, 5, 3, Jun).Source);
|
||||
Assert.AreEqual(27.50m, book.Quote(Valve, 5, 3, Jun).Price);
|
||||
Assert.AreEqual(new PriceQuote(34m, PriceSource.BasePriceList, 1, false, Jun), book.Quote(Valve, 5, 4, Jun), "An expired list is skipped.");
|
||||
Assert.AreEqual(new PriceQuote(38m, PriceSource.Item, null, false, null), book.Quote(Service, null, null, Jun));
|
||||
Assert.AreEqual(PriceQuote.None, book.Quote(new Item { Id = 12 }, null, null, Jun));
|
||||
Assert.AreEqual(Base, book.Base);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BaseOf_IsTheMarkedList_ElseTheCodeBase()
|
||||
{
|
||||
Assert.AreEqual(2, PriceBook.BaseOf([new PriceList { Id = 1, Code = "BASE" }, new PriceList { Id = 2, Code = "A", IsBase = true }])!.Id);
|
||||
Assert.AreEqual(1, PriceBook.BaseOf([new PriceList { Id = 1, Code = "BASE" }, new PriceList { Id = 2, Code = "A" }])!.Id);
|
||||
Assert.IsNull(PriceBook.BaseOf([new PriceList { Id = 1, Code = "BASE", Disabled = true }]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Discounts_ComeFromTheTerms_ButNotOnANetPrice()
|
||||
{
|
||||
var terms = new PartySalesTerms { Discount1 = 10m, Discount2 = 5m };
|
||||
var fromList = new PriceQuote(100m, PriceSource.BasePriceList, 1, false, Jan);
|
||||
var discounts = PriceBook.Discounts(fromList, terms);
|
||||
Assert.AreEqual("10+5", discounts.Formula);
|
||||
Assert.AreEqual(14.5m, discounts.Equivalent);
|
||||
Assert.AreEqual(DiscountQuote.None, PriceBook.Discounts(fromList with { Source = PriceSource.PartyNet }, terms));
|
||||
Assert.AreEqual(DiscountQuote.None, PriceBook.Discounts(fromList, new PartySalesTerms()));
|
||||
Assert.AreEqual(DiscountQuote.None, PriceBook.Discounts(fromList, null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Khaemhat.Core.Items;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Common;
|
||||
|
||||
/// <summary>The rounding of the prices of a list (issue #42, mockup 018): steps of 0.10, 0.50, 1.00, up or down.</summary>
|
||||
[TestClass]
|
||||
public sealed class PriceRoundingTests
|
||||
{
|
||||
[TestMethod]
|
||||
[DataRow("46.43", "0.10", RoundingDirection.Nearest, "46.40")]
|
||||
[DataRow("46.45", "0.10", RoundingDirection.Nearest, "46.50")]
|
||||
[DataRow("46.41", "0.10", RoundingDirection.Up, "46.50")]
|
||||
[DataRow("46.49", "0.10", RoundingDirection.Down, "46.40")]
|
||||
[DataRow("12.345", "0.50", RoundingDirection.Nearest, "12.50")]
|
||||
[DataRow("12.345", "0.50", RoundingDirection.Down, "12.00")]
|
||||
[DataRow("12.01", "1.00", RoundingDirection.Up, "13.00")]
|
||||
[DataRow("12.00", "1.00", RoundingDirection.Up, "12.00")]
|
||||
[DataRow("1.23456", "0", RoundingDirection.Nearest, "1.23")]
|
||||
[DataRow("0.123456", "0.0001", RoundingDirection.Nearest, "0.1235")]
|
||||
public void Round_GoesToTheStep(string value, string step, RoundingDirection direction, string expected) =>
|
||||
Assert.AreEqual(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture),
|
||||
PriceRounding.Round(decimal.Parse(value, System.Globalization.CultureInfo.InvariantCulture), decimal.Parse(step, System.Globalization.CultureInfo.InvariantCulture), direction));
|
||||
|
||||
[TestMethod]
|
||||
public void Round_KeepsTwoDecimals_WhenTheRestAreZeros() =>
|
||||
Assert.AreEqual("46.40", PriceRounding.Round(46.4000m, 0.10m).ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
|
||||
[TestMethod]
|
||||
public void Change_AddsOrTakesOffAPercent()
|
||||
{
|
||||
Assert.AreEqual(46.4m, PriceRounding.Change(32m, 45m));
|
||||
Assert.AreEqual(28.8m, PriceRounding.Change(32m, -10m));
|
||||
Assert.AreEqual(32m, PriceRounding.Change(32m, 0m));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Margin_IsOnThePrice()
|
||||
{
|
||||
Assert.AreEqual(45m, PriceRounding.Margin(32m, 17.60m));
|
||||
Assert.AreEqual(-10m, PriceRounding.Margin(10m, 11m));
|
||||
Assert.IsNull(PriceRounding.Margin(0m, 5m));
|
||||
Assert.IsNull(PriceRounding.Margin(10m, null));
|
||||
Assert.IsNull(PriceRounding.Margin(null, 5m));
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,7 @@ public sealed class MappingTests
|
||||
"goods_appearances", "delivery_terms", "transport_reasons", "inventory_reasons", "warehouses", "item_categories", "party_categories", "price_lists",
|
||||
"discount_policies", "document_numerators", "document_types", "cost_centers", "jobs", "code_sequences",
|
||||
"parties", "party_addresses", "party_contacts", "party_bank_accounts", "party_sales_terms", "party_purchase_terms", "party_fiscal",
|
||||
"items", "item_uoms", "item_barcodes", "item_prices", "item_suppliers", "item_substitutes", "party_item_codes",
|
||||
];
|
||||
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Querying;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Seeding;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Web.Tests.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Items;
|
||||
|
||||
/// <summary>The demo items (SPEC §14, issue #42): 120 per scale, valid bar codes, derived lists, and every item passes the checks.</summary>
|
||||
[TestClass]
|
||||
public sealed class DemoItemsTests
|
||||
{
|
||||
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
|
||||
[TestMethod]
|
||||
public void Catalogue_HasTheItemsOfTheSpecification_WithValidBarCodes()
|
||||
{
|
||||
var catalogue = DemoItemsSeeder.Catalogue();
|
||||
Assert.HasCount(DemoItemsSeeder.ItemsPerScale, catalogue);
|
||||
Assert.HasCount(catalogue.Count, catalogue.Select(i => i.Description).Distinct().ToList(), "No description twice.");
|
||||
Assert.IsTrue(catalogue.All(i => i.Kind != ItemKind.Goods || i.Price > 0));
|
||||
Assert.IsTrue(catalogue.Any(i => i.Kind == ItemKind.Service) && catalogue.Any(i => i.Kind == ItemKind.Expense) && catalogue.Any(i => i.Kind == ItemKind.Text));
|
||||
foreach (var n in new[] { 1, 99, 500_123 })
|
||||
{
|
||||
Assert.IsTrue(EanValidator.IsValid(DemoItemsSeeder.Ean(n)), DemoItemsSeeder.Ean(n));
|
||||
Assert.StartsWith("200", DemoItemsSeeder.Ean(n));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DemoSeed_FillsAnEmptyCompanyOnce_WithItemsThatPassTheChecks()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var runner = app.Services.GetRequiredService<SeedRunner>();
|
||||
var items = app.Services.GetRequiredService<ItemService>();
|
||||
var prices = app.Services.GetRequiredService<PriceListService>();
|
||||
var first = await runner.RunAsync(company, SeedKind.Demo);
|
||||
Assert.AreEqual(DemoItemsSeeder.ItemsPerScale, first.Added["items"]);
|
||||
Assert.AreEqual(2, first.Added["price_lists"]);
|
||||
Assert.IsGreaterThan(0, first.Added["item_suppliers"]);
|
||||
Assert.IsGreaterThan(0, first.Added["party_item_codes"]);
|
||||
Assert.IsEmpty((await runner.RunAsync(company, SeedKind.Demo)).Added, "Only an empty company gets the demo data.");
|
||||
|
||||
var lists = await prices.ListsAsync(Root, company);
|
||||
CollectionAssert.AreEqual(new[] { "BASE", "PUBB", "RIV" }, lists.Select(l => l.Code).ToArray());
|
||||
var grid = await prices.GridAsync(Root, company, new ListQuery { Search = "sfera 1/2", Limit = 10 }, DateOnly.FromDateTime(DateTime.Today), null);
|
||||
var lever = grid.Page.Items[0];
|
||||
Assert.IsTrue(lever.Prices[lists[1].Id].Derived, "The public list is derived from the base one.");
|
||||
Assert.IsNotNull(lever.AverageCost);
|
||||
|
||||
var all = (await items.ListAsync(Root, company, new ListQuery { Limit = 200 })).Items;
|
||||
Assert.HasCount(DemoItemsSeeder.ItemsPerScale, all);
|
||||
foreach (var row in all)
|
||||
{
|
||||
var record = (await items.GetAsync(Root, company, row.Id))!;
|
||||
Assert.IsTrue(record.Item.IsDemo);
|
||||
var errors = (await items.ValidateAsync(Root, company, record)).Where(p => !p.IsWarning).Select(p => p.Field + ":" + p.Code).ToList();
|
||||
Assert.IsEmpty(errors, row.Code + " " + row.Description + ": " + string.Join(", ", errors));
|
||||
}
|
||||
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Scale_RepeatsTheCatalogue()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var report = await app.Services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo, 2);
|
||||
Assert.AreEqual(2 * DemoItemsSeeder.ItemsPerScale, report.Added["items"]);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Web.Items;
|
||||
using Khaemhat.Web.Tests.Shell;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Items;
|
||||
|
||||
/// <summary>Addresses, tabs and cell values of the item screens (issue #42).</summary>
|
||||
[TestClass]
|
||||
public sealed class ItemScreensTests
|
||||
{
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||
|
||||
[TestMethod]
|
||||
public void TabOf_FindsTheTabOfAField()
|
||||
{
|
||||
Assert.AreEqual(ItemScreens.Tabs.Main, ItemScreens.TabOf("Barcode"));
|
||||
Assert.AreEqual(ItemScreens.Tabs.Units, ItemScreens.TabOf("Units.0.Factor"));
|
||||
Assert.AreEqual(ItemScreens.Tabs.Barcodes, ItemScreens.TabOf("Barcodes.2.Code"));
|
||||
Assert.AreEqual(ItemScreens.Tabs.Prices, ItemScreens.TabOf("Prices.1.PartyId"));
|
||||
Assert.AreEqual(ItemScreens.Tabs.Suppliers, ItemScreens.TabOf("Suppliers.0.PartyId"));
|
||||
Assert.AreEqual(ItemScreens.Tabs.Substitutes, ItemScreens.TabOf("Substitutes.0.SubstituteId"));
|
||||
Assert.AreEqual(ItemScreens.Tabs.Notes, ItemScreens.TabOf("Notes"));
|
||||
Assert.AreEqual(ItemScreens.Tabs.Main, ItemScreens.TabOf(null));
|
||||
Assert.AreEqual("anagrafiche/articoli/12", ItemScreens.RecordUrl(12));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("€ 1.180,00", "1180")]
|
||||
[DataRow("32,5", "32.5")]
|
||||
[DataRow(" 0,12345 ", "0.1235")]
|
||||
public void TryParsePrice_ReadsWhatTheCellShows(string text, string expected)
|
||||
{
|
||||
Assert.IsTrue(ItemScreens.TryParsePrice(text, Italian, out var price));
|
||||
Assert.AreEqual(decimal.Parse(expected, CultureInfo.InvariantCulture), price);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TryParsePrice_EmptyIsNoPrice_AndRefusesTheRest()
|
||||
{
|
||||
Assert.IsTrue(ItemScreens.TryParsePrice(" ", Italian, out var none));
|
||||
Assert.IsNull(none);
|
||||
Assert.IsFalse(ItemScreens.TryParsePrice("-3", Italian, out _));
|
||||
Assert.IsFalse(ItemScreens.TryParsePrice("abc", Italian, out _));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MarginText_IsAPercentOfThePrice()
|
||||
{
|
||||
Assert.AreEqual("45%", ItemScreens.MarginText(32m, 17.60m, Italian));
|
||||
Assert.AreEqual("33,3%", ItemScreens.MarginText(30m, 20m, Italian));
|
||||
Assert.IsNull(ItemScreens.MarginText(null, 20m, Italian));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryChoice_HasAText()
|
||||
{
|
||||
Assert.IsTrue(ItemScreens.Choices<ItemKind>(ShellTests.Texts, "Kinds").All(o => !o.Text.StartsWith("Items.", StringComparison.Ordinal)));
|
||||
Assert.IsTrue(ItemScreens.Choices<RoundingDirection>(ShellTests.Texts, "Directions").All(o => !o.Text.StartsWith("Items.", StringComparison.Ordinal)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -271,6 +271,6 @@ public sealed partial class LocalizationRulesTests
|
||||
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
|
||||
private static partial Regex EntityPattern();
|
||||
|
||||
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties)\\.[A-Za-z0-9_.]+)\"")]
|
||||
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items)\\.[A-Za-z0-9_.]+)\"")]
|
||||
private static partial Regex KeyPattern();
|
||||
}
|
||||
@@ -108,11 +108,12 @@ public sealed partial class TableScreensTests
|
||||
[TestMethod]
|
||||
public void EveryErrorCode_HasAText()
|
||||
{
|
||||
var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService), typeof(CodeRuleService), typeof(CodeMask), typeof(Khaemhat.Application.Parties.PartyService) }
|
||||
var codes = new[] { typeof(TableService), typeof(TableCatalog), typeof(CompanyProfileService), typeof(FiscalYearService), typeof(PaymentTermService), typeof(ExchangeRateService), typeof(CodeRuleService), typeof(CodeMask), typeof(Khaemhat.Application.Parties.PartyService), typeof(Khaemhat.Application.Items.ItemService), typeof(Khaemhat.Application.Items.PriceListService) }
|
||||
.SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string)))
|
||||
.Select(f => (string)f.GetRawConstantValue()!)
|
||||
.Where(c => c.StartsWith("tables.", StringComparison.Ordinal) || c.StartsWith("profile.", StringComparison.Ordinal) || c.StartsWith("fiscal.", StringComparison.Ordinal)
|
||||
|| c.StartsWith("codes.", StringComparison.Ordinal) || (c.StartsWith("parties.", StringComparison.Ordinal) && !c.StartsWith("parties.party", StringComparison.Ordinal)))
|
||||
|| c.StartsWith("codes.", StringComparison.Ordinal) || (c.StartsWith("parties.", StringComparison.Ordinal) && !c.StartsWith("parties.party", StringComparison.Ordinal))
|
||||
|| (c.StartsWith("items.", StringComparison.Ordinal) && !c.StartsWith("items.item", StringComparison.Ordinal) && !c.StartsWith("items.cost", StringComparison.Ordinal)))
|
||||
.Where(c => !c.EndsWith('.'))
|
||||
.Concat(Enum.GetValues<PeriodState>().Select(FiscalYearService.ErrorOf))
|
||||
.ToList();
|
||||
@@ -191,13 +192,17 @@ public sealed partial class TableScreensTests
|
||||
Assert.IsFalse(SeedCommand.Matches(["--urls", "http://localhost:5080"]));
|
||||
|
||||
Assert.IsTrue(SeedCommand.TryParse(["seed", "--base"], out var all, out _));
|
||||
Assert.IsNull(all, "Every active company.");
|
||||
Assert.AreEqual(new SeedOptions(false, 1, null), all, "Base data of every active company.");
|
||||
Assert.IsTrue(SeedCommand.TryParse(["seed", "--company", "demo", "--base"], out var one, out _));
|
||||
Assert.AreEqual("DEMO", one);
|
||||
Assert.AreEqual("DEMO", one!.Company);
|
||||
Assert.IsTrue(SeedCommand.TryParse(["seed", "--demo", "--scale", "3", "--company", "demo"], out var demo, out _));
|
||||
Assert.AreEqual(new SeedOptions(true, 3, "DEMO"), demo);
|
||||
|
||||
Assert.IsFalse(SeedCommand.TryParse(["seed"], out _, out var usage));
|
||||
Assert.IsNotNull(usage);
|
||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo"], out _, out _), "Demo data arrive with parties and items.");
|
||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--scale", "2"], out _, out _), "The scale is for the demo data.");
|
||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo", "--scale", "0"], out _, out _));
|
||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--demo", "--scale", "101"], out _, out _));
|
||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--company"], out _, out _));
|
||||
Assert.IsFalse(SeedCommand.TryParse(["seed", "--base", "--other"], out _, out _));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user