A physical stock take freezes the book quantity and cost of a warehouse at a date, takes counts typed or read from a scanner file, and posts the gains and losses as INVP/INVN movements at that date. The reorder proposal lists the items whose available and ordered quantity no longer covers the reorder point and turns the accepted lines into draft supplier orders, one per supplier. The warehouse can be rebuilt from its documents on demand and every Sunday night, as a safety net after imports or corrections. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
406 lines
21 KiB
C#
406 lines
21 KiB
C#
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))]);
|
|
}
|
|
}
|