M6 · Acquisti e Magazzino (v0.6.0) #125
No files matched your search
@@ -40,6 +40,12 @@ internal interface IDocumentStore
|
||||
/// <returns>The lines.</returns>
|
||||
Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Reads the headers of the documents in force (neither drafts nor cancelled).</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The headers.</returns>
|
||||
Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Reads a line.</summary>
|
||||
/// <param name="uow">The unit of work.</param>
|
||||
/// <param name="id">The line.</param>
|
||||
@@ -136,6 +142,11 @@ internal sealed class DocumentStore<THeader, TLine>(DocumentFamily family, strin
|
||||
public async Task<DocumentHeader?> GetAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken) =>
|
||||
await uow.Repository<THeader, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<DocumentHeader>> InForceAsync(IUnitOfWork uow, CancellationToken cancellationToken) =>
|
||||
[.. (await uow.Repository<THeader, long>().ListAsync(
|
||||
Query.For<THeader>().Where(h => h.Status != DocumentStatus.Draft && h.Status != DocumentStatus.Cancelled), cancellationToken).ConfigureAwait(false)).Items];
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<DocumentLine>> LinesAsync(IUnitOfWork uow, long documentId, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -52,6 +52,61 @@ public static class InventoryPoster
|
||||
await RecomputeAsync(uow, items, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the warehouse from the documents (SPEC §11.6, <i>ricostruzione</i>): removes every movement, posts
|
||||
/// again every document in force that moves the stock, oldest first and the delivery notes before the invoices of
|
||||
/// the same day, then runs the history of every item.
|
||||
/// </summary>
|
||||
/// <param name="uow">The unit of work of the company, in a transaction.</param>
|
||||
/// <param name="progress">Receives the documents posted and the total, then the items and their total.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
public static async Task<(int Documents, int Items)> RebuildAsync(IUnitOfWork uow, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(uow);
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entry_lines"), cancellationToken).ConfigureAwait(false);
|
||||
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM inventory_entries"), cancellationToken).ConfigureAwait(false);
|
||||
var documents = new List<(DocumentFamily Family, DocumentHeader Header)>();
|
||||
foreach (var family in new[] { DocumentFamily.SaleDocument, DocumentFamily.PurchaseDocument, DocumentFamily.InventoryDocument })
|
||||
{
|
||||
foreach (var header in await Documents.DocumentStores.Of(family).InForceAsync(uow, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (StockEffectMatrix.MovesStock(header.Kind))
|
||||
{
|
||||
documents.Add((family, header));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delivery notes and receipts first: their invoices then find the goods already moved.
|
||||
var ordered = documents
|
||||
.OrderBy(d => d.Header.DocumentDate)
|
||||
.ThenBy(d => d.Header.Kind is DocumentKind.DeliveryNote or DocumentKind.PurchaseDeliveryNote or DocumentKind.InventoryEntry ? 0 : 1)
|
||||
.ThenBy(d => d.Header.ConfirmedAt)
|
||||
.ThenBy(d => d.Header.Id)
|
||||
.ToList();
|
||||
var items = new HashSet<long>();
|
||||
for (var i = 0; i < ordered.Count; i++)
|
||||
{
|
||||
var (family, header) = ordered[i];
|
||||
var lines = await LinesAsync(uow, family, header.Id, cancellationToken).ConfigureAwait(false);
|
||||
await PostAsync(uow, family, header, lines, items, cancellationToken).ConfigureAwait(false);
|
||||
progress?.Report(new RebuildProgress(RebuildPhase.Documents, i + 1, ordered.Count));
|
||||
}
|
||||
|
||||
// Every stocked item, also those with only orders or with no movement left.
|
||||
var all = (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => i.Stocked), cancellationToken).ConfigureAwait(false)).Items.Select(i => i.Id);
|
||||
var balanced = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>(), cancellationToken).ConfigureAwait(false)).Items.Select(b => b.ItemId);
|
||||
var ids = items.Concat(all).Concat(balanced).Distinct().ToList();
|
||||
for (var i = 0; i < ids.Count; i += 50)
|
||||
{
|
||||
await RecomputeAsync(uow, ids.Skip(i).Take(50), cancellationToken).ConfigureAwait(false);
|
||||
progress?.Report(new RebuildProgress(RebuildPhase.Items, Math.Min(i + 50, ids.Count), ids.Count));
|
||||
}
|
||||
|
||||
return (ordered.Count, ids.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs again the history of items: the cost of every movement, the balances of each warehouse, the committed and
|
||||
/// ordered quantities, the average and last cost on the item card.
|
||||
@@ -480,3 +535,19 @@ public static class InventoryPoster
|
||||
private static Task<DocumentLine?> StoreLineAsync(IUnitOfWork uow, DocumentFamily family, long id, CancellationToken cancellationToken) =>
|
||||
Documents.DocumentStores.Of(family).GetLineAsync(uow, id, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The step of a rebuild.</summary>
|
||||
public enum RebuildPhase
|
||||
{
|
||||
/// <summary>Posting the documents.</summary>
|
||||
Documents = 0,
|
||||
|
||||
/// <summary>Computing the items.</summary>
|
||||
Items = 1,
|
||||
}
|
||||
|
||||
/// <summary>How far a rebuild is.</summary>
|
||||
/// <param name="Phase">The step.</param>
|
||||
/// <param name="Done">How many done.</param>
|
||||
/// <param name="Total">How many in all.</param>
|
||||
public sealed record RebuildProgress(RebuildPhase Phase, int Done, int Total);
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Jobs;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
|
||||
namespace Khaemhat.Application.Inventory;
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the warehouse of every active company from its documents, once a week at night (SPEC §11.6): a safety net
|
||||
/// that brings balances and costs back in line after imports or corrections made outside the screens.
|
||||
/// </summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
public sealed class InventoryRebuildJob(IUnitOfWorkFactory factory, ICompanyRegistry companies) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "inventory.rebuild";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
int documents = 0, items = 0, done = 0;
|
||||
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (company.Status is CompanyStatus.Disabled)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var (d, i) = await InventoryService.RebuildCompanyAsync(factory, company.Code, null, cancellationToken).ConfigureAwait(false);
|
||||
documents += d;
|
||||
items += i;
|
||||
done++;
|
||||
}
|
||||
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {documents} documenti, {items} articoli ricalcolati.");
|
||||
}
|
||||
}
|
||||
@@ -314,6 +314,37 @@ public sealed class InventoryService
|
||||
return [.. rows.OrderByDescending(r => r.Level).ThenBy(r => r.Available - (r.MinimumStock ?? r.ReorderPoint ?? 0m)).ThenBy(r => r.Code, StringComparer.Ordinal).Take(limit)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the warehouse of the company from its documents (SPEC §11.6): every movement is written again and every
|
||||
/// item computed again, in one transaction.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who rebuilds: needs <c>inventory.entry.post</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="progress">How far it is.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
public async Task<(int Documents, int Items)> RebuildAsync(Actor actor, string companyCode, IProgress<RebuildProgress>? progress = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, PostPermission, cancellationToken).ConfigureAwait(false);
|
||||
return await RebuildCompanyAsync(_factory, company, progress, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the warehouse of a company, without checks (the scheduled job).</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="progress">How far it is.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The documents posted and the items computed.</returns>
|
||||
internal static async Task<(int Documents, int Items)> RebuildCompanyAsync(
|
||||
IUnitOfWorkFactory factory, string company, IProgress<RebuildProgress>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var result = await InventoryPoster.RebuildAsync(uow, progress, cancellationToken).ConfigureAwait(false);
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The level of an item: out when nothing is available (or less than nothing), under stock below the minimum,
|
||||
/// to reorder when what is available and on order no longer covers the reorder point.
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Inventory;
|
||||
|
||||
/// <summary>An item to reorder (mockup 039).</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="Available">On hand less committed.</param>
|
||||
/// <param name="Ordered">Already ordered.</param>
|
||||
/// <param name="MinimumStock">The minimum stock.</param>
|
||||
/// <param name="ReorderPoint">The reorder point.</param>
|
||||
/// <param name="Quantity">The quantity proposed.</param>
|
||||
/// <param name="SupplierId">The usual supplier, if any.</param>
|
||||
/// <param name="SupplierName">Its name.</param>
|
||||
/// <param name="Price">Its price.</param>
|
||||
/// <param name="ExpectedDate">When it would arrive, from the lead time.</param>
|
||||
public sealed record ReorderProposal(
|
||||
long ItemId, string Code, string Description, long? UnitOfMeasureId, decimal Available, decimal Ordered, decimal? MinimumStock, decimal? ReorderPoint,
|
||||
decimal Quantity, long? SupplierId, string? SupplierName, decimal? Price, DateOnly? ExpectedDate);
|
||||
|
||||
/// <summary>A proposal the user accepts, perhaps with another quantity or supplier.</summary>
|
||||
/// <param name="ItemId">The item.</param>
|
||||
/// <param name="SupplierId">The supplier.</param>
|
||||
/// <param name="Quantity">The quantity.</param>
|
||||
public sealed record ReorderChoice(long ItemId, long SupplierId, decimal Quantity);
|
||||
|
||||
/// <summary>
|
||||
/// The reorder proposal (SPEC §11.6, mockup 039): the items whose available and ordered quantity no longer covers the
|
||||
/// reorder point (or the minimum stock), with the quantity to order (the lot, or what brings back to the threshold, at
|
||||
/// least the minimum of the supplier) and the usual supplier; accepted, the proposals become draft supplier orders,
|
||||
/// one per supplier.
|
||||
/// </summary>
|
||||
public sealed class ReorderService
|
||||
{
|
||||
/// <summary>Error: a chosen line without a supplier or a quantity.</summary>
|
||||
public const string ChoiceInvalid = "inventory.reorder.choice-invalid";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly DocumentEngine _engine;
|
||||
private readonly DocumentEditor _editor;
|
||||
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="engine">The document engine.</param>
|
||||
/// <param name="editor">The editor (prices and terms of the supplier).</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public ReorderService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, DocumentEditor editor, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(engine);
|
||||
ArgumentNullException.ThrowIfNull(editor);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_engine = engine;
|
||||
_editor = editor;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The items to reorder, by supplier and code.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The proposals.</returns>
|
||||
public async Task<IReadOnlyList<ReorderProposal>> ProposalsAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.StockPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(
|
||||
Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled && (i.MinimumStock != null || i.ReorderPoint != null)).OrderBy(i => i.Code), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
if (items.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var balances = await InventoryService.BalancesByItemAsync(uow, null, cancellationToken).ConfigureAwait(false);
|
||||
var ids = items.Select(i => i.Id).ToList();
|
||||
var suppliers = (await uow.Repository<ItemSupplier, long>().ListAsync(Query.For<ItemSupplier>().Where(s => ids.Contains(s.ItemId)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.GroupBy(s => s.ItemId).ToDictionary(g => g.Key, g => g.OrderByDescending(s => s.IsDefault).ThenBy(s => s.Id).First());
|
||||
var partyIds = suppliers.Values.Select(s => s.PartyId).Distinct().ToList();
|
||||
var names = partyIds.Count == 0 ? [] : (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => partyIds.Contains(p.Id)), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(p => p.Id, p => p.Name);
|
||||
var today = DateOnly.FromDateTime(_clock.GetLocalNow().DateTime);
|
||||
var result = new List<ReorderProposal>();
|
||||
foreach (var item in items)
|
||||
{
|
||||
var mine = balances.GetValueOrDefault(item.Id) ?? [];
|
||||
var available = mine.Sum(b => b.OnHand - b.Committed);
|
||||
var ordered = mine.Sum(b => b.Ordered);
|
||||
var supplier = suppliers.GetValueOrDefault(item.Id);
|
||||
var quantity = Quantity(available + ordered, item.MinimumStock, item.ReorderPoint, item.ReorderLot, supplier?.MinimumQuantity);
|
||||
if (quantity <= 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
result.Add(new ReorderProposal(
|
||||
item.Id, item.Code, item.Description, item.UnitOfMeasureId, available, ordered, item.MinimumStock, item.ReorderPoint, quantity,
|
||||
supplier?.PartyId, supplier is null ? null : names.GetValueOrDefault(supplier.PartyId), supplier?.Price ?? item.LastCost,
|
||||
supplier?.LeadTimeDays is { } days ? today.AddDays(days) : null));
|
||||
}
|
||||
|
||||
return [.. result.OrderBy(r => r.SupplierName is null).ThenBy(r => r.SupplierName, StringComparer.CurrentCulture).ThenBy(r => r.Code, StringComparer.Ordinal)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The quantity to order: nothing while what is available and ordered covers the reorder point (or the minimum);
|
||||
/// otherwise the lot of the item, or what brings back to the higher of the two thresholds, at least the minimum
|
||||
/// quantity of the supplier.
|
||||
/// </summary>
|
||||
/// <param name="cover">Available plus ordered.</param>
|
||||
/// <param name="minimum">The minimum stock.</param>
|
||||
/// <param name="reorderPoint">The reorder point.</param>
|
||||
/// <param name="lot">The reorder lot.</param>
|
||||
/// <param name="supplierMinimum">The minimum of the supplier.</param>
|
||||
/// <returns>The quantity.</returns>
|
||||
public static decimal Quantity(decimal cover, decimal? minimum, decimal? reorderPoint, decimal? lot, decimal? supplierMinimum)
|
||||
{
|
||||
var threshold = reorderPoint ?? minimum;
|
||||
if (threshold is not { } point || cover > point || (reorderPoint is null && cover >= point))
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
var target = Math.Max(minimum ?? 0m, reorderPoint ?? 0m);
|
||||
var quantity = lot is > 0m ? lot.Value : Math.Max(target - cover, 0m);
|
||||
if (lot is > 0m && cover + quantity < target)
|
||||
{
|
||||
// One lot is not enough: as many lots as it takes.
|
||||
quantity = Math.Ceiling((target - cover) / lot.Value) * lot.Value;
|
||||
}
|
||||
|
||||
return Math.Max(quantity, supplierMinimum ?? 0m);
|
||||
}
|
||||
|
||||
/// <summary>Creates the draft supplier orders of the chosen proposals, one per supplier.</summary>
|
||||
/// <param name="actor">Who orders: needs <c>purchases.order.write</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="choices">The proposals accepted.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The orders, saved as drafts.</returns>
|
||||
public async Task<IReadOnlyList<DocumentRecord>> CreateOrdersAsync(Actor actor, string companyCode, IReadOnlyList<ReorderChoice> choices, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(choices);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "purchases.order.write", cancellationToken).ConfigureAwait(false);
|
||||
if (choices.Any(c => c.Quantity <= 0m || c.SupplierId <= 0))
|
||||
{
|
||||
throw new ValidationFailedException([":" + ChoiceInvalid]);
|
||||
}
|
||||
|
||||
var result = new List<DocumentRecord>();
|
||||
foreach (var group in choices.GroupBy(c => c.SupplierId))
|
||||
{
|
||||
var order = await _engine.NewAsync(actor, company, "OF", cancellationToken).ConfigureAwait(false);
|
||||
await _editor.ApplyPartyAsync(actor, company, order, group.Key, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var choice in group)
|
||||
{
|
||||
var line = new PurchaseOrderLine { Kind = DocumentLineKind.Item, ItemId = choice.ItemId, Quantity = choice.Quantity };
|
||||
order.Lines.Add(line);
|
||||
await _editor.FillLineAsync(actor, company, order, line, choice.ItemId, cancellationToken).ConfigureAwait(false);
|
||||
line.Quantity = choice.Quantity;
|
||||
}
|
||||
|
||||
result.Add(await _engine.SaveAsync(actor, company, order, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Application.Tables;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Tables;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Inventory;
|
||||
|
||||
/// <summary>A line of a stock take with its item.</summary>
|
||||
/// <param name="Line">The line.</param>
|
||||
/// <param name="Code">The code of the item.</param>
|
||||
/// <param name="Description">Its description.</param>
|
||||
/// <param name="UnitOfMeasureId">Its base unit.</param>
|
||||
public sealed record StockTakeLineView(StockTakeLine Line, string Code, string Description, long? UnitOfMeasureId);
|
||||
|
||||
/// <summary>A stock take with its lines.</summary>
|
||||
/// <param name="Take">The stock take.</param>
|
||||
/// <param name="Lines">Its lines, by code.</param>
|
||||
public sealed record StockTakeView(StockTake Take, IReadOnlyList<StockTakeLineView> Lines)
|
||||
{
|
||||
/// <summary>How many lines are counted.</summary>
|
||||
public int Counted => Lines.Count(l => l.Line.CountedQuantity is not null);
|
||||
|
||||
/// <summary>The value of the differences at the cost of the lines.</summary>
|
||||
public decimal DifferenceValue => Lines.Sum(l => StockCostCalculator.Value(l.Line.Difference, l.Line.UnitCost));
|
||||
}
|
||||
|
||||
/// <summary>What the import of the counts found.</summary>
|
||||
/// <param name="Applied">The lines counted.</param>
|
||||
/// <param name="Unknown">The codes not on the list, with their row.</param>
|
||||
public sealed record StockCountImport(int Applied, IReadOnlyList<string> Unknown);
|
||||
|
||||
/// <summary>
|
||||
/// The physical inventory (SPEC §11.6, mockup 038): a list of the items of a warehouse with what the books say at the
|
||||
/// date, the counts typed or read from a file, and the posting that writes the differences as two warehouse movements
|
||||
/// (gains with reason INVP, losses with INVN) through the document engine.
|
||||
/// </summary>
|
||||
/// <remarks>Permissions <c>inventory.entry.read</c>, <c>write</c> (lists and counts) and <c>post</c>.</remarks>
|
||||
public sealed class StockTakeService
|
||||
{
|
||||
/// <summary>Error: the stock take is no longer open.</summary>
|
||||
public const string NotOpen = "inventory.stock-take.not-open";
|
||||
|
||||
/// <summary>Error: nothing is counted.</summary>
|
||||
public const string NothingCounted = "inventory.stock-take.nothing-counted";
|
||||
|
||||
/// <summary>Error: a counted quantity below zero.</summary>
|
||||
public const string NegativeCount = "inventory.stock-take.negative";
|
||||
|
||||
/// <summary>Error: the reasons of the adjustments are missing from the base tables.</summary>
|
||||
public const string ReasonMissing = "inventory.stock-take.reason-missing";
|
||||
|
||||
/// <summary>The reason of the gains.</summary>
|
||||
public const string GainReason = "INVP";
|
||||
|
||||
/// <summary>The reason of the losses.</summary>
|
||||
public const string LossReason = "INVN";
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly PermissionService _permissions;
|
||||
private readonly DocumentEngine _engine;
|
||||
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="engine">The document engine, for the adjustments.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public StockTakeService(IUnitOfWorkFactory factory, PermissionService permissions, DocumentEngine engine, TimeProvider clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(permissions);
|
||||
ArgumentNullException.ThrowIfNull(engine);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_factory = factory;
|
||||
_permissions = permissions;
|
||||
_engine = engine;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
/// <summary>The stock takes, the latest first.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock takes.</returns>
|
||||
public async Task<IReadOnlyList<StockTake>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return (await uow.Repository<StockTake, long>().ListAsync(Query.For<StockTake>().OrderByDescending(t => t.TakeDate).OrderByDescending(t => t.Id), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>A stock take with its lines.</summary>
|
||||
/// <param name="actor">Who reads.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take, or none.</returns>
|
||||
public async Task<StockTakeView?> GetAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.EntryReadPermission, cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
return await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a stock take: the stocked goods of the warehouse (of a category, if given) with the quantity the books
|
||||
/// give at the date and the average cost.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who opens it.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="warehouseId">The warehouse.</param>
|
||||
/// <param name="date">The day of the count.</param>
|
||||
/// <param name="categoryId">Only a category.</param>
|
||||
/// <param name="description">A description; the warehouse and date when empty.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new stock take.</returns>
|
||||
public async Task<StockTakeView> CreateAsync(
|
||||
Actor actor, string companyCode, long warehouseId, DateOnly date, long? categoryId, string? description, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
var warehouse = await uow.Repository<Warehouse, long>().GetAsync(warehouseId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ValidationFailedException([nameof(StockTake.WarehouseId) + ":" + "inventory.warehouse.missing"]);
|
||||
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
|
||||
if (categoryId is { } category)
|
||||
{
|
||||
query = query.Where(i => i.CategoryId == category);
|
||||
}
|
||||
|
||||
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var book = await BookAsync(uow, warehouseId, date, cancellationToken).ConfigureAwait(false);
|
||||
var balances = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.WarehouseId == warehouseId), cancellationToken)
|
||||
.ConfigureAwait(false)).Items.ToDictionary(b => b.ItemId);
|
||||
var take = new StockTake
|
||||
{
|
||||
TakeDate = date,
|
||||
WarehouseId = warehouseId,
|
||||
CategoryId = categoryId,
|
||||
Description = string.IsNullOrWhiteSpace(description)
|
||||
? "Inventario " + warehouse.Code + " al " + date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
|
||||
: description.Trim()[..Math.Min(description.Trim().Length, 100)],
|
||||
Status = StockTakeStatus.Open,
|
||||
};
|
||||
await uow.Repository<StockTake, long>().InsertAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
var lines = uow.Repository<StockTakeLine, long>();
|
||||
var order = 0;
|
||||
foreach (var item in items)
|
||||
{
|
||||
await lines.InsertAsync(
|
||||
new StockTakeLine
|
||||
{
|
||||
StockTakeId = take.Id,
|
||||
ItemId = item.Id,
|
||||
BookQuantity = book.GetValueOrDefault(item.Id),
|
||||
UnitCost = balances.TryGetValue(item.Id, out var balance) ? balance.AverageCost : item.AverageCost ?? item.StandardCost ?? 0m,
|
||||
SortOrder = ++order,
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return (await ViewAsync(uow, take.Id, cancellationToken).ConfigureAwait(false))!;
|
||||
}
|
||||
|
||||
/// <summary>Writes the counts typed on the list; an empty count means not counted yet.</summary>
|
||||
/// <param name="actor">Who counts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="counts">The counted quantity of each line, by line.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take.</returns>
|
||||
public async Task<StockTakeView> SaveCountsAsync(
|
||||
Actor actor, string companyCode, long id, IReadOnlyDictionary<long, decimal?> counts, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(counts);
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
|
||||
if (counts.Values.Any(v => v < 0m))
|
||||
{
|
||||
throw new ValidationFailedException(["CountedQuantity:" + NegativeCount]);
|
||||
}
|
||||
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
var repository = uow.Repository<StockTakeLine, long>();
|
||||
foreach (var line in (await repository.ListAsync(Query.For<StockTakeLine>().Where(l => l.StockTakeId == id), cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
if (counts.TryGetValue(line.Id, out var counted) && counted != line.CountedQuantity)
|
||||
{
|
||||
line.CountedQuantity = counted;
|
||||
await repository.UpdateAsync(line, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the counts from a text file (from a barcode reader or a spreadsheet): one row per item, the code and the
|
||||
/// quantity separated by semicolon, tab or comma; a header and empty rows are skipped; the same code twice adds up.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who counts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="content">The file.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>How many lines were counted and the codes not on the list.</returns>
|
||||
public async Task<StockCountImport> ImportCountsAsync(Actor actor, string companyCode, long id, Stream content, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var view = await GetAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
|
||||
var byCode = view.Lines.ToDictionary(l => l.Code, l => l.Line.Id, StringComparer.OrdinalIgnoreCase);
|
||||
var counts = new Dictionary<long, decimal?>();
|
||||
var unknown = new List<string>();
|
||||
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
|
||||
var row = 0;
|
||||
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } text)
|
||||
{
|
||||
row++;
|
||||
if (ParseCount(text) is not { } parsed)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var (code, quantity) = parsed;
|
||||
|
||||
if (byCode.TryGetValue(code, out var lineId))
|
||||
{
|
||||
counts[lineId] = (counts.GetValueOrDefault(lineId) ?? 0m) + quantity;
|
||||
}
|
||||
else
|
||||
{
|
||||
unknown.Add(row.ToString(CultureInfo.InvariantCulture) + ": " + code);
|
||||
}
|
||||
}
|
||||
|
||||
if (counts.Count > 0)
|
||||
{
|
||||
await SaveCountsAsync(actor, companyCode, id, counts, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new StockCountImport(counts.Count, unknown);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts a stock take: the counted lines that differ from the books become a movement of gains (INVP, at the cost
|
||||
/// of the line) and one of losses (INVN), confirmed at the date of the count. The lines not counted are left as
|
||||
/// they are.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who posts: needs <c>inventory.entry.post</c>.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stock take as posted.</returns>
|
||||
public async Task<StockTakeView> PostAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, InventoryService.PostPermission, cancellationToken).ConfigureAwait(false);
|
||||
StockTakeView view;
|
||||
long? gainReason, lossReason;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
view = (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
|
||||
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items;
|
||||
gainReason = reasons.FirstOrDefault(r => r.Code == GainReason)?.Id;
|
||||
lossReason = reasons.FirstOrDefault(r => r.Code == LossReason)?.Id;
|
||||
}
|
||||
|
||||
if (view.Counted == 0)
|
||||
{
|
||||
throw new ValidationFailedException([":" + NothingCounted]);
|
||||
}
|
||||
|
||||
if (gainReason is null || lossReason is null)
|
||||
{
|
||||
throw new ValidationFailedException([":" + ReasonMissing]);
|
||||
}
|
||||
|
||||
var take = view.Take;
|
||||
var gains = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference > 0m).ToList();
|
||||
var losses = view.Lines.Where(l => l.Line.CountedQuantity is not null && l.Line.Difference < 0m).ToList();
|
||||
take.AdjustmentDocumentId = await AdjustAsync(actor, company, take, gainReason.Value, gains, cancellationToken).ConfigureAwait(false);
|
||||
take.LossDocumentId = await AdjustAsync(actor, company, take, lossReason.Value, losses, cancellationToken).ConfigureAwait(false);
|
||||
take.Status = StockTakeStatus.Posted;
|
||||
take.PostedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
take.PostedBy = actor.UserName;
|
||||
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await uow.Repository<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
return (await ViewAsync(uow, id, cancellationToken).ConfigureAwait(false))!;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Cancels an open stock take; its counts stay for the record.</summary>
|
||||
/// <param name="actor">Who cancels.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="id">The stock take.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task CancelAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, "inventory.entry.write", cancellationToken).ConfigureAwait(false);
|
||||
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
||||
var take = await OpenTakeAsync(uow, id, cancellationToken).ConfigureAwait(false);
|
||||
take.Status = StockTakeStatus.Cancelled;
|
||||
await uow.Repository<StockTake, long>().UpdateAsync(take, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A code and a quantity from a row of a count file, or none for a header or an empty row.</summary>
|
||||
/// <param name="text">The row.</param>
|
||||
/// <returns>The code and the quantity.</returns>
|
||||
public static (string Code, decimal Quantity)? ParseCount(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var separator = text.Contains(';', StringComparison.Ordinal) ? ';' : text.Contains('\t', StringComparison.Ordinal) ? '\t' : ',';
|
||||
var parts = text.Split(separator, StringSplitOptions.TrimEntries);
|
||||
if (parts.Length < 2 || parts[0].Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var number = parts[1].Trim('"');
|
||||
|
||||
// With a comma as separator the quantity is in the invariant form; otherwise the Italian one is accepted too.
|
||||
var parsed = separator == ','
|
||||
? decimal.TryParse(number, NumberStyles.Number, CultureInfo.InvariantCulture, out var value)
|
||||
: decimal.TryParse(number.Replace(".", string.Empty, StringComparison.Ordinal), NumberStyles.Number, CultureInfo.GetCultureInfo("it-IT"), out value);
|
||||
return parsed && value >= 0m ? (parts[0].Trim('"'), value) : null;
|
||||
}
|
||||
|
||||
// The quantity of each item in a warehouse at the end of a day.
|
||||
internal static async Task<Dictionary<long, decimal>> BookAsync(IUnitOfWork uow, long warehouseId, DateOnly date, CancellationToken cancellationToken) =>
|
||||
(await uow.Repository<InventoryEntryLine, long>().ListAsync(
|
||||
Query.For<InventoryEntryLine>().Where(l => l.WarehouseId == warehouseId && l.EntryDate <= date), cancellationToken).ConfigureAwait(false)).Items
|
||||
.GroupBy(l => l.ItemId).ToDictionary(g => g.Key, g => g.Sum(l => l.Quantity));
|
||||
|
||||
private async Task<long?> AdjustAsync(
|
||||
Actor actor, string company, StockTake take, long reasonId, List<StockTakeLineView> lines, CancellationToken cancellationToken)
|
||||
{
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var entry = await _engine.NewAsync(actor, company, "MM", cancellationToken).ConfigureAwait(false);
|
||||
entry.Header.DocumentDate = take.TakeDate;
|
||||
entry.Header.InventoryReasonId = reasonId;
|
||||
entry.Header.WarehouseId = take.WarehouseId;
|
||||
entry.Header.ExternalReference = take.Description.Length > 40 ? take.Description[..40] : take.Description;
|
||||
entry.Header.IsDemo = take.IsDemo;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
entry.Lines.Add(new InventoryDocumentLine
|
||||
{
|
||||
Kind = DocumentLineKind.Item,
|
||||
ItemId = line.Line.ItemId,
|
||||
Description = line.Description,
|
||||
UnitOfMeasureId = line.UnitOfMeasureId,
|
||||
Quantity = Math.Abs(line.Line.Difference),
|
||||
Price = line.Line.UnitCost,
|
||||
WarehouseId = take.WarehouseId,
|
||||
});
|
||||
}
|
||||
|
||||
entry = await _engine.SaveAsync(actor, company, entry, cancellationToken).ConfigureAwait(false);
|
||||
return (await _engine.ConfirmAsync(actor, company, DocumentFamily.InventoryDocument, entry.Header.Id, cancellationToken).ConfigureAwait(false)).Header.Id;
|
||||
}
|
||||
|
||||
private static async Task<StockTake> OpenTakeAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
var take = await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotOpen);
|
||||
return take.Status == StockTakeStatus.Open ? take : throw new ValidationFailedException([":" + NotOpen]);
|
||||
}
|
||||
|
||||
private static async Task<StockTakeView?> ViewAsync(IUnitOfWork uow, long id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await uow.Repository<StockTake, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } take)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var lines = (await uow.Repository<StockTakeLine, long>().ListAsync(Query.For<StockTakeLine>().Where(l => l.StockTakeId == id).OrderBy(l => l.SortOrder), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var ids = lines.Select(l => l.ItemId).Distinct().ToList();
|
||||
var items = ids.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => ids.Contains(i.Id)), cancellationToken).ConfigureAwait(false))
|
||||
.Items.ToDictionary(i => i.Id);
|
||||
return new StockTakeView(take, [.. lines.Select(l => items.TryGetValue(l.ItemId, out var item)
|
||||
? new StockTakeLineView(l, item.Code, item.Description, item.UnitOfMeasureId)
|
||||
: new StockTakeLineView(l, "?", string.Empty, null))]);
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
|
||||
/// </summary>
|
||||
public sealed class JobScheduler
|
||||
{
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
|
||||
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4, warehouse rebuild from M6).</summary>
|
||||
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
|
||||
[
|
||||
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
|
||||
@@ -58,6 +58,7 @@ public sealed class JobScheduler
|
||||
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
|
||||
new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800),
|
||||
new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true),
|
||||
new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600),
|
||||
];
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
|
||||
@@ -148,9 +148,12 @@ public sealed class StockTake : Entity<long>, IDemoMarkable
|
||||
/// <summary>The state.</summary>
|
||||
public StockTakeStatus Status { get; set; }
|
||||
|
||||
/// <summary>The warehouse entry with the adjustments, once posted.</summary>
|
||||
/// <summary>The warehouse entry that loads what was found more than the books, once posted.</summary>
|
||||
public long? AdjustmentDocumentId { get; set; }
|
||||
|
||||
/// <summary>The warehouse entry that unloads what was found less than the books, once posted.</summary>
|
||||
public long? LossDocumentId { get; set; }
|
||||
|
||||
/// <summary>When it was posted.</summary>
|
||||
public DateTime? PostedAt { get; set; }
|
||||
|
||||
|
||||
@@ -106,6 +106,7 @@ public sealed class M20261113_001_CreateInventory : IMigration
|
||||
t.Int64("category_id");
|
||||
t.String("status", 40).NotNull();
|
||||
t.Int64("adjustment_document_id");
|
||||
t.Int64("loss_document_id");
|
||||
t.DateTimeUtc("posted_at");
|
||||
t.String("posted_by", 100);
|
||||
t.Text("notes");
|
||||
|
||||
@@ -148,6 +148,9 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<Khaemhat.Application.Items.ItemService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.InventoryService>();
|
||||
services.AddSingleton<Khaemhat.Application.Purchases.PurchaseService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.StockTakeService>();
|
||||
services.AddSingleton<Khaemhat.Application.Inventory.ReorderService>();
|
||||
services.AddSingleton<IScheduledJob, Khaemhat.Application.Inventory.InventoryRebuildJob>();
|
||||
services.AddSingleton<Khaemhat.Application.Items.PriceListService>();
|
||||
|
||||
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
|
||||
|
||||
@@ -13,5 +13,19 @@
|
||||
"Hints": {
|
||||
"Movement": "La causale decide se il movimento carica, scarica o trasferisce; senza deposito vale quello dell’articolo."
|
||||
}
|
||||
},
|
||||
"inventory": {
|
||||
"stock-take": {
|
||||
"not-open": "L'inventario è già stato registrato o annullato: non si può più modificare.",
|
||||
"nothing-counted": "Non hai contato nessun articolo: inserisci almeno una quantità prima di registrare.",
|
||||
"negative": "Una quantità contata non può essere negativa.",
|
||||
"reason-missing": "Mancano le causali di rettifica inventariale INVP e INVN: aggiornale da Tabelle azienda, Aggiorna tabelle di base."
|
||||
},
|
||||
"warehouse": {
|
||||
"missing": "Il deposito non esiste più."
|
||||
},
|
||||
"reorder": {
|
||||
"choice-invalid": "Ogni riga da ordinare deve avere un fornitore e una quantità maggiore di zero."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,5 +11,16 @@
|
||||
"SupplierNumber": "Il numero scritto dal fornitore sulla sua fattura o sul DDT.",
|
||||
"VatDate": "Il mese in cui l’IVA entra in detrazione; vuota, vale la data di registrazione."
|
||||
}
|
||||
},
|
||||
"purchase": {
|
||||
"self-invoice": {
|
||||
"not-needed": "Per questa fattura non serve un'autofattura: il fornitore applica già l'IVA italiana."
|
||||
}
|
||||
},
|
||||
"incoming": {
|
||||
"not-readable": "Il file non è una fattura elettronica leggibile: carica un XML FatturaPA, un file firmato .p7m o uno ZIP che li contiene.",
|
||||
"not-invoice": "Il file XML non è una FatturaPA.",
|
||||
"signature-broken": "La firma del file .p7m non è valida: il contenuto potrebbe essere stato alterato.",
|
||||
"invalid": "La fattura elettronica non è conforme al tracciato FatturaPA."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Application.Documents;
|
||||
using Khaemhat.Application.Inventory;
|
||||
using Khaemhat.Application.Items;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Documents;
|
||||
using Khaemhat.Core.Inventory;
|
||||
using Khaemhat.Core.Items;
|
||||
using Khaemhat.Core.Parties;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Web.Tests.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Inventory;
|
||||
|
||||
/// <summary>
|
||||
/// The physical stock take, the reorder proposal and the rebuild of the warehouse on a real instance (issue #60).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class StockTakeAndReorderTests
|
||||
{
|
||||
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
|
||||
[TestMethod]
|
||||
public async Task StockTake_PostsGainsAndLosses_AtTheDateOfTheCount()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
var takes = app.Services.GetRequiredService<StockTakeService>();
|
||||
var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
|
||||
var valve = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null);
|
||||
var pipe = await InventoryFlowTests.ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", null);
|
||||
var day = new DateOnly(DateTime.Now.Year, 6, 1);
|
||||
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, valve, day, 10m, 4m);
|
||||
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, pipe, day, 100m, 1.5m);
|
||||
var warehouse = (await stock.BalancesAsync(Root, company, valve)).Single().WarehouseId;
|
||||
|
||||
var take = await takes.CreateAsync(Root, company, warehouse, day.AddDays(1), null, null);
|
||||
Assert.AreEqual(10m, take.Lines.Single(l => l.Code == "VALV-01").Line.BookQuantity);
|
||||
Assert.AreEqual(4m, take.Lines.Single(l => l.Code == "VALV-01").Line.UnitCost);
|
||||
|
||||
// Nothing counted, nothing to post.
|
||||
var empty = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => takes.PostAsync(Root, company, take.Take.Id));
|
||||
CollectionAssert.Contains(empty.Errors.ToArray(), ":" + StockTakeService.NothingCounted);
|
||||
|
||||
// The counts come from a reader file: 12 valves (2 more), 95 pipes (5 less), an unknown code.
|
||||
using var file = new MemoryStream(Encoding.UTF8.GetBytes("Codice;Quantità\nVALV-01;12\nTUBO-16;90\nTUBO-16;5\nXX-99;1\n"));
|
||||
var imported = await takes.ImportCountsAsync(Root, company, take.Take.Id, file);
|
||||
Assert.AreEqual(2, imported.Applied);
|
||||
Assert.AreEqual("5: XX-99", imported.Unknown.Single());
|
||||
take = (await takes.GetAsync(Root, company, take.Take.Id))!;
|
||||
Assert.AreEqual(2, take.Counted);
|
||||
Assert.AreEqual(2m * 4m - 5m * 1.5m, take.DifferenceValue);
|
||||
|
||||
take = await takes.PostAsync(Root, company, take.Take.Id);
|
||||
Assert.AreEqual(StockTakeStatus.Posted, take.Take.Status);
|
||||
Assert.IsNotNull(take.Take.AdjustmentDocumentId);
|
||||
Assert.IsNotNull(take.Take.LossDocumentId);
|
||||
var rows = await stock.StockAsync(Root, company, new StockFilter());
|
||||
Assert.AreEqual(12m, rows.Single(r => r.ItemId == valve).OnHand);
|
||||
Assert.AreEqual(95m, rows.Single(r => r.ItemId == pipe).OnHand);
|
||||
var moves = await stock.MovementsAsync(Root, company, pipe, null, null, null);
|
||||
Assert.AreEqual((-5m, day.AddDays(1)), (moves[^1].Quantity, moves[^1].Date));
|
||||
|
||||
// A posted take is closed.
|
||||
var closed = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => takes.SaveCountsAsync(Root, company, take.Take.Id, new Dictionary<long, decimal?>()));
|
||||
CollectionAssert.Contains(closed.Errors.ToArray(), ":" + StockTakeService.NotOpen);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CountRows_AcceptItalianAndInvariantNumbers()
|
||||
{
|
||||
Assert.AreEqual(("A-1", 1234.5m), StockTakeService.ParseCount("A-1;1.234,5"));
|
||||
Assert.AreEqual(("A-1", 3m), StockTakeService.ParseCount("A-1\t3"));
|
||||
Assert.AreEqual(("A-1", 2.5m), StockTakeService.ParseCount("\"A-1\",2.5"));
|
||||
Assert.IsNull(StockTakeService.ParseCount("Codice;Quantità"));
|
||||
Assert.IsNull(StockTakeService.ParseCount("A-1;-3"));
|
||||
Assert.IsNull(StockTakeService.ParseCount(" "));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ReorderQuantity_UsesTheLotAndTheSupplierMinimum()
|
||||
{
|
||||
Assert.AreEqual(0m, ReorderService.Quantity(11m, 5m, 10m, null, null), "Covered above the reorder point.");
|
||||
Assert.AreEqual(4m, ReorderService.Quantity(6m, 5m, 10m, null, null), "Back to the reorder point.");
|
||||
Assert.AreEqual(25m, ReorderService.Quantity(6m, 5m, 10m, 25m, null), "One lot.");
|
||||
Assert.AreEqual(30m, ReorderService.Quantity(-12m, 5m, 10m, 10m, null), "As many lots as it takes: 22 missing, three lots.");
|
||||
Assert.AreEqual(50m, ReorderService.Quantity(6m, 5m, 10m, null, 50m), "At least the supplier minimum.");
|
||||
Assert.AreEqual(0m, ReorderService.Quantity(5m, 5m, null, null, null), "At the minimum, without a reorder point.");
|
||||
Assert.AreEqual(1m, ReorderService.Quantity(4m, 5m, null, null, null));
|
||||
Assert.AreEqual(0m, ReorderService.Quantity(-3m, null, null, null, null), "No thresholds, no proposal.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Reorder_ProposesTheItemsUnderTheirPoint_AndOrdersThemBySupplier()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
||||
var reorder = app.Services.GetRequiredService<ReorderService>();
|
||||
var items = app.Services.GetRequiredService<ItemService>();
|
||||
var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
|
||||
var other = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Ferramenta Sud S.p.A.", "00743110157");
|
||||
var valve = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", 5m);
|
||||
var record = await items.GetAsync(Root, company, valve);
|
||||
record!.Item.ReorderPoint = 10m;
|
||||
record.Item.ReorderLot = 24m;
|
||||
record.Suppliers.Add(new ItemSupplier { PartyId = supplier, SupplierCode = "VS-12", Price = 3.8m, LeadTimeDays = 7, IsDefault = true });
|
||||
await items.SaveAsync(Root, company, record);
|
||||
var pipe = await InventoryFlowTests.ItemAsync(app, company, "TUBO-16", "Tubo multistrato 16 mm", 50m);
|
||||
var plenty = await InventoryFlowTests.ItemAsync(app, company, "RACC-20", "Raccordo 20 mm", 5m);
|
||||
var day = new DateOnly(DateTime.Now.Year, 7, 1);
|
||||
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, valve, day, 6m, 4m);
|
||||
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, plenty, day, 30m, 1m);
|
||||
|
||||
var proposals = await reorder.ProposalsAsync(Root, company);
|
||||
Assert.HasCount(2, proposals);
|
||||
var first = proposals[0];
|
||||
Assert.AreEqual((valve, 24m, supplier, 3.8m), (first.ItemId, first.Quantity, first.SupplierId, first.Price));
|
||||
Assert.IsNotNull(first.ExpectedDate);
|
||||
Assert.AreEqual((pipe, 50m), (proposals[1].ItemId, proposals[1].Quantity), "No supplier: last, to be chosen.");
|
||||
Assert.IsNull(proposals[1].SupplierId);
|
||||
|
||||
var invalid = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => reorder.CreateOrdersAsync(Root, company, [new ReorderChoice(pipe, 0, 50m)]));
|
||||
CollectionAssert.Contains(invalid.Errors.ToArray(), ":" + ReorderService.ChoiceInvalid);
|
||||
|
||||
var orders = await reorder.CreateOrdersAsync(Root, company, [new ReorderChoice(valve, supplier, 24m), new ReorderChoice(pipe, other, 60m)]);
|
||||
Assert.HasCount(2, orders);
|
||||
Assert.IsTrue(orders.All(o => o.Header.Kind == DocumentKind.PurchaseOrder && o.Header.Status == DocumentStatus.Draft));
|
||||
var valveLine = orders.Single(o => o.Header.PartyId == supplier).Lines.Single(l => l.Kind == DocumentLineKind.Item);
|
||||
Assert.AreEqual((valve, 24m, 3.8m), (valveLine.ItemId, valveLine.Quantity, valveLine.Price));
|
||||
Assert.AreEqual(60m, orders.Single(o => o.Header.PartyId == other).Lines.Single(l => l.Kind == DocumentLineKind.Item).Quantity);
|
||||
|
||||
// Confirmed, the order covers the valve: it is no longer proposed.
|
||||
await engine.ConfirmAsync(Root, company, DocumentFamily.PurchaseOrder, orders.Single(o => o.Header.PartyId == supplier).Header.Id);
|
||||
Assert.IsFalse((await reorder.ProposalsAsync(Root, company)).Any(p => p.ItemId == valve));
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Rebuild_WritesTheSameStockAgain_AndTheJobRunsForEveryCompany()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var engine = app.Services.GetRequiredService<DocumentEngine>();
|
||||
var stock = app.Services.GetRequiredService<InventoryService>();
|
||||
var supplier = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Supplier, "Idrotermica Nord S.r.l.", "01234567897");
|
||||
var customer = await InventoryFlowTests.PartyAsync(app, company, PartyKind.Customer, "Rossi Impianti S.r.l.", "02987654304");
|
||||
var item = await InventoryFlowTests.ItemAsync(app, company, "VALV-01", "Valvola a sfera 1/2", null);
|
||||
var day = new DateOnly(DateTime.Now.Year, 8, 1);
|
||||
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, item, day, 10m, 10m);
|
||||
await InventoryFlowTests.ReceiptAsync(engine, company, supplier, item, day.AddDays(1), 10m, 13m);
|
||||
var note = await engine.NewAsync(Root, company, "DDT");
|
||||
note.Header.PartyId = customer;
|
||||
note.Header.DocumentDate = day.AddDays(2);
|
||||
note.Lines.Add(new SaleDocumentLine { Kind = DocumentLineKind.Item, ItemId = item, Description = "Valvola", Quantity = 4m, Price = 20m });
|
||||
await engine.ConfirmAsync(Root, company, DocumentFamily.SaleDocument, (await engine.SaveAsync(Root, company, note)).Header.Id);
|
||||
var before = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
|
||||
var movesBefore = await stock.MovementsAsync(Root, company, item, null, null, null);
|
||||
|
||||
var phases = new List<RebuildPhase>();
|
||||
var (documents, items) = await stock.RebuildAsync(Root, company, new SyncProgress(p => phases.Add(p.Phase)));
|
||||
Assert.AreEqual(3, documents);
|
||||
Assert.IsGreaterThanOrEqualTo(1, items);
|
||||
CollectionAssert.Contains(phases, RebuildPhase.Documents);
|
||||
CollectionAssert.Contains(phases, RebuildPhase.Items);
|
||||
var after = (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item);
|
||||
Assert.AreEqual((before.OnHand, before.AverageCost, before.Value), (after.OnHand, after.AverageCost, after.Value));
|
||||
var movesAfter = await stock.MovementsAsync(Root, company, item, null, null, null);
|
||||
CollectionAssert.AreEqual(movesBefore.Select(m => (m.Date, m.Quantity, m.UnitCost)).ToList(), movesAfter.Select(m => (m.Date, m.Quantity, m.UnitCost)).ToList());
|
||||
|
||||
// Without the right to post, no rebuild.
|
||||
var reader = new Actor("lucia", UserLevel.Standard, null, 999, company);
|
||||
await Assert.ThrowsExactlyAsync<AccessDeniedException>(() => stock.RebuildAsync(reader, company));
|
||||
|
||||
var job = app.Services.GetServices<Khaemhat.Application.Jobs.IScheduledJob>().Single(j => j.Type == InventoryRebuildJob.JobType);
|
||||
var summary = await job.RunAsync(null!, CancellationToken.None);
|
||||
StringAssert.Contains(summary, "3 documenti");
|
||||
Assert.AreEqual(after.OnHand, (await stock.StockAsync(Root, company, new StockFilter())).Single(r => r.ItemId == item).OnHand);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
// Reports at once, unlike Progress<T> which posts to the thread pool.
|
||||
private sealed class SyncProgress(Action<RebuildProgress> report) : IProgress<RebuildProgress>
|
||||
{
|
||||
public void Report(RebuildProgress value) => report(value);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user