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;
/// An item to reorder (mockup 039).
/// The item.
/// Its code.
/// Its description.
/// Its unit.
/// On hand less committed.
/// Already ordered.
/// The minimum stock.
/// The reorder point.
/// The quantity proposed.
/// The usual supplier, if any.
/// Its name.
/// Its price.
/// When it would arrive, from the lead time.
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);
/// A proposal the user accepts, perhaps with another quantity or supplier.
/// The item.
/// The supplier.
/// The quantity.
public sealed record ReorderChoice(long ItemId, long SupplierId, decimal Quantity);
///
/// 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.
///
public sealed class ReorderService
{
/// Error: a chosen line without a supplier or a quantity.
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;
/// Creates the service.
/// The units of work.
/// The permissions.
/// The document engine.
/// The editor (prices and terms of the supplier).
/// The clock.
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;
}
/// The items to reorder, by supplier and code.
/// Who reads.
/// The company.
/// Cancellation.
/// The proposals.
public async Task> 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- ().ListAsync(
Query.For
- ().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().ListAsync(Query.For().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().ListAsync(Query.For().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();
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)];
}
///
/// 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.
///
/// Available plus ordered.
/// The minimum stock.
/// The reorder point.
/// The reorder lot.
/// The minimum of the supplier.
/// The quantity.
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);
}
/// Creates the draft supplier orders of the chosen proposals, one per supplier.
/// Who orders: needs purchases.order.write.
/// The company.
/// The proposals accepted.
/// Cancellation.
/// The orders, saved as drafts.
public async Task> CreateOrdersAsync(Actor actor, string companyCode, IReadOnlyList 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();
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;
}
}