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>
184 lines
9.7 KiB
C#
184 lines
9.7 KiB
C#
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;
|
|
}
|
|
}
|