CI / Build and test (SQLite) (pull_request) Successful in 4m35s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Successful in 1m24s
M10 gives the ledger its year end. Fixed assets get categories with the ministerial coefficients, a civil and a fiscal plan, depreciation posted per category and undoable, disposals with gain or loss and the register print (ADR 0041). Intrastat lists are generated from confirmed invoices with the due periodicity and the SCAMBI.CEE file; declarations of intent get their own register and the N3.5 ceiling is checked when an invoice is confirmed (ADR 0042). Accruals, deferrals and exchange differences feed a nine-step guided closing that can repeat or undo its last step until the final prints, reopens the next year and locks the closed one; the CEE statements (ordinary, abbreviated, micro), the reclassified statements, the ratios and the accountant export read the year's balances (ADR 0043). The demo seed now opens the year with assets, stock, bank and capital, so the integration test closes the demo year from the checks to the lock on SQLite and PostgreSQL. Docs: wiki pages with screenshots, ADR 0041-0043, MODULES, STATUS, DATA-MODEL and the 0.10.0 changelog. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
430 lines
23 KiB
C#
430 lines
23 KiB
C#
using Khaemhat.Application.Items;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Application.Tables;
|
|
using Khaemhat.Core.Documents;
|
|
using Khaemhat.Core.Inventory;
|
|
using Khaemhat.Core.Items;
|
|
using Khaemhat.Core.Parties;
|
|
using Khaemhat.Core.Tables;
|
|
using Khaemhat.Data;
|
|
using Khaemhat.Data.Querying;
|
|
|
|
namespace Khaemhat.Application.Inventory;
|
|
|
|
/// <summary>What the stock screen asks (mockup 036).</summary>
|
|
public sealed record StockFilter
|
|
{
|
|
/// <summary>Code, description or brand.</summary>
|
|
public string? Search { get; init; }
|
|
|
|
/// <summary>One warehouse, or all together.</summary>
|
|
public long? WarehouseId { get; init; }
|
|
|
|
/// <summary>One category.</summary>
|
|
public long? CategoryId { get; init; }
|
|
|
|
/// <summary>Only the items under their minimum stock or reorder point.</summary>
|
|
public bool UnderstockOnly { get; init; }
|
|
|
|
/// <summary>Also the items with nothing on hand, committed or ordered.</summary>
|
|
public bool IncludeEmpty { get; init; }
|
|
}
|
|
|
|
/// <summary>The state of an item under its thresholds.</summary>
|
|
public enum StockLevel
|
|
{
|
|
/// <summary>Enough.</summary>
|
|
Ok = 0,
|
|
|
|
/// <summary>The available quantity reached the reorder point.</summary>
|
|
Reorder = 1,
|
|
|
|
/// <summary>The available quantity is under the minimum stock.</summary>
|
|
Understock = 2,
|
|
|
|
/// <summary>Nothing left, or less than nothing.</summary>
|
|
Out = 3,
|
|
}
|
|
|
|
/// <summary>A row of the stock screen: an item in one warehouse or in all.</summary>
|
|
/// <param name="ItemId">The item.</param>
|
|
/// <param name="Code">Its code.</param>
|
|
/// <param name="Description">Its description.</param>
|
|
/// <param name="CategoryId">Its category.</param>
|
|
/// <param name="UnitOfMeasureId">Its base unit.</param>
|
|
/// <param name="OnHand">On hand.</param>
|
|
/// <param name="Committed">Committed to customers.</param>
|
|
/// <param name="Ordered">Ordered from suppliers.</param>
|
|
/// <param name="Available">On hand less committed.</param>
|
|
/// <param name="MinimumStock">The minimum stock.</param>
|
|
/// <param name="ReorderPoint">The reorder point.</param>
|
|
/// <param name="AverageCost">The weighted average cost (none without the permission on costs).</param>
|
|
/// <param name="Value">The value at the average (none without the permission).</param>
|
|
/// <param name="LastLoad">The last load.</param>
|
|
/// <param name="LastUnload">The last unload.</param>
|
|
/// <param name="Level">The state under the thresholds.</param>
|
|
public sealed record StockRow(
|
|
long ItemId, string Code, string Description, long? CategoryId, long? UnitOfMeasureId, decimal OnHand, decimal Committed, decimal Ordered, decimal Available,
|
|
decimal? MinimumStock, decimal? ReorderPoint, decimal? AverageCost, decimal? Value, DateOnly? LastLoad, DateOnly? LastUnload, StockLevel Level);
|
|
|
|
/// <summary>A movement of an item, with the balance after it.</summary>
|
|
/// <param name="Id">The movement.</param>
|
|
/// <param name="Date">The date.</param>
|
|
/// <param name="Family">The family of the document.</param>
|
|
/// <param name="DocumentId">The document.</param>
|
|
/// <param name="Kind">Its kind.</param>
|
|
/// <param name="Number">Its number.</param>
|
|
/// <param name="ReasonCode">The warehouse reason.</param>
|
|
/// <param name="PartyName">The customer or supplier.</param>
|
|
/// <param name="WarehouseId">The warehouse.</param>
|
|
/// <param name="Quantity">Positive loads, negative unloads.</param>
|
|
/// <param name="UnitCost">The cost (none without the permission).</param>
|
|
/// <param name="Value">The value (none without the permission).</param>
|
|
/// <param name="Balance">The balance after the movement, in the warehouses shown.</param>
|
|
public sealed record MovementRow(
|
|
long Id, DateOnly Date, DocumentFamily? Family, long? DocumentId, DocumentKind? Kind, string? Number, string? ReasonCode, string? PartyName, long WarehouseId,
|
|
decimal Quantity, decimal? UnitCost, decimal? Value, decimal Balance);
|
|
|
|
/// <summary>The value of an item at a date (closing stock, libro inventari).</summary>
|
|
/// <param name="ItemId">The item.</param>
|
|
/// <param name="Code">Its code.</param>
|
|
/// <param name="Description">Its description.</param>
|
|
/// <param name="Quantity">On hand at the date.</param>
|
|
/// <param name="UnitCost">The cost of the method.</param>
|
|
/// <param name="Value">Quantity times cost.</param>
|
|
/// <param name="AbcClass">A (the first 80% of the value), B (up to 95%) or C.</param>
|
|
public sealed record ValuationRow(long ItemId, string Code, string Description, decimal Quantity, decimal UnitCost, decimal Value, char AbcClass);
|
|
|
|
/// <summary>
|
|
/// The warehouse as people read it (SPEC §11.6, mockups 036-037): stock and availability, the movements of an item,
|
|
/// the value at a date. The balances are kept by <see cref="InventoryPoster"/>; this service only reads them.
|
|
/// </summary>
|
|
/// <remarks>Permission <c>inventory.stock.read</c>, movements <c>inventory.entry.read</c>; costs only with <c>items.cost.read</c>.</remarks>
|
|
public sealed class InventoryService
|
|
{
|
|
/// <summary>Permission to read the stock.</summary>
|
|
public const string StockPermission = "inventory.stock.read";
|
|
|
|
/// <summary>Permission to read the movements.</summary>
|
|
public const string EntryReadPermission = "inventory.entry.read";
|
|
|
|
/// <summary>Permission to post movements, stock takes and the rebuild.</summary>
|
|
public const string PostPermission = "inventory.entry.post";
|
|
|
|
private readonly IUnitOfWorkFactory _factory;
|
|
private readonly PermissionService _permissions;
|
|
|
|
/// <summary>Creates the service.</summary>
|
|
/// <param name="factory">The units of work.</param>
|
|
/// <param name="permissions">The permissions.</param>
|
|
public InventoryService(IUnitOfWorkFactory factory, PermissionService permissions)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(factory);
|
|
ArgumentNullException.ThrowIfNull(permissions);
|
|
_factory = factory;
|
|
_permissions = permissions;
|
|
}
|
|
|
|
/// <summary>The stock of the items, in a warehouse or in all.</summary>
|
|
/// <param name="actor">Who reads.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="filter">What to show.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The rows, by code.</returns>
|
|
public async Task<IReadOnlyList<StockRow>> StockAsync(Actor actor, string companyCode, StockFilter filter, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(filter);
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
|
|
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
var query = Query.For<Item>().Where(i => i.Stocked && i.Kind == ItemKind.Goods && !i.Disabled);
|
|
if (filter.CategoryId is { } category)
|
|
{
|
|
query = query.Where(i => i.CategoryId == category);
|
|
}
|
|
|
|
if (filter.Search?.Trim() is { Length: > 0 } text)
|
|
{
|
|
query = query.Where(i => i.Code.Contains(text) || i.Description.Contains(text) || (i.Brand != null && i.Brand.Contains(text)));
|
|
}
|
|
|
|
var items = (await uow.Repository<Item, long>().ListAsync(query.OrderBy(i => i.Code), cancellationToken).ConfigureAwait(false)).Items;
|
|
var balances = await BalancesByItemAsync(uow, filter.WarehouseId, cancellationToken).ConfigureAwait(false);
|
|
var rows = new List<StockRow>();
|
|
foreach (var item in items)
|
|
{
|
|
var mine = balances.GetValueOrDefault(item.Id) ?? [];
|
|
var row = RowOf(item, mine, costs);
|
|
if (!filter.IncludeEmpty && mine.Count == 0)
|
|
{
|
|
// No movement and no order: shown only when asked, or when it has a minimum to keep.
|
|
if (row.Level == StockLevel.Ok)
|
|
{
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (filter.UnderstockOnly && row.Level == StockLevel.Ok)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
rows.Add(row);
|
|
}
|
|
|
|
return rows;
|
|
}
|
|
|
|
/// <summary>The balances of an item in each warehouse.</summary>
|
|
/// <param name="actor">Who reads.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="itemId">The item.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The balances, costs hidden without the permission.</returns>
|
|
public async Task<IReadOnlyList<ItemBalance>> BalancesAsync(Actor actor, string companyCode, long itemId, CancellationToken cancellationToken = default)
|
|
{
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
|
|
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
var rows = (await uow.Repository<ItemBalance, long>().ListAsync(Query.For<ItemBalance>().Where(b => b.ItemId == itemId), cancellationToken).ConfigureAwait(false)).Items;
|
|
if (!costs)
|
|
{
|
|
foreach (var row in rows)
|
|
{
|
|
row.AverageCost = 0m;
|
|
row.Value = 0m;
|
|
row.LastCost = null;
|
|
}
|
|
}
|
|
|
|
return rows;
|
|
}
|
|
|
|
/// <summary>The movements of an item in a period, with the running balance (mockup 036, dialog of the item).</summary>
|
|
/// <param name="actor">Who reads.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="itemId">The item.</param>
|
|
/// <param name="warehouseId">One warehouse, or all.</param>
|
|
/// <param name="from">The first day, or the beginning.</param>
|
|
/// <param name="to">The last day, or today.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The movements, oldest first; the balance starts from what was on hand before <paramref name="from"/>.</returns>
|
|
public async Task<IReadOnlyList<MovementRow>> MovementsAsync(
|
|
Actor actor, string companyCode, long itemId, long? warehouseId, DateOnly? from, DateOnly? to, CancellationToken cancellationToken = default)
|
|
{
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EntryReadPermission, cancellationToken).ConfigureAwait(false);
|
|
var costs = await CostsAsync(actor, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
var query = Query.For<InventoryEntryLine>().Where(l => l.ItemId == itemId);
|
|
if (warehouseId is { } warehouse)
|
|
{
|
|
query = query.Where(l => l.WarehouseId == warehouse);
|
|
}
|
|
|
|
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(query.OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
|
|
.ConfigureAwait(false)).Items;
|
|
var entryIds = lines.Select(l => l.EntryId).Distinct().ToList();
|
|
var entries = entryIds.Count == 0 ? [] : (await uow.Repository<InventoryEntry, long>().ListAsync(Query.For<InventoryEntry>().Where(e => entryIds.Contains(e.Id)), cancellationToken)
|
|
.ConfigureAwait(false)).Items.ToDictionary(e => e.Id);
|
|
var reasons = (await uow.Repository<InventoryReason, long>().ListAsync(Query.For<InventoryReason>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id, r => r.Code);
|
|
var partyIds = entries.Values.Where(e => e.PartyId is not null).Select(e => e.PartyId!.Value).Distinct().ToList();
|
|
var parties = 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 result = new List<MovementRow>();
|
|
var balance = 0m;
|
|
foreach (var line in lines)
|
|
{
|
|
balance += line.Quantity;
|
|
if ((from is { } first && line.EntryDate < first) || (to is { } last && line.EntryDate > last))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var entry = entries.GetValueOrDefault(line.EntryId);
|
|
result.Add(new MovementRow(
|
|
line.Id, line.EntryDate, entry?.SourceFamily, entry?.SourceDocumentId, entry?.SourceKind, entry?.SourceNumber,
|
|
entry?.InventoryReasonId is { } r ? reasons.GetValueOrDefault(r) : null,
|
|
entry?.PartyId is { } p ? parties.GetValueOrDefault(p) : null,
|
|
line.WarehouseId, line.Quantity, costs ? line.UnitCost : null, costs ? line.Value : null, balance));
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The value of the stock at a date (closing stock, libro inventari): the history of each item up to that day,
|
|
/// valued with a method, with its ABC class by value.
|
|
/// </summary>
|
|
/// <param name="actor">Who reads: needs the permission on costs too.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="date">The day.</param>
|
|
/// <param name="warehouseId">One warehouse, or all.</param>
|
|
/// <param name="method">The cost used.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The items with something on hand, by value.</returns>
|
|
public async Task<IReadOnlyList<ValuationRow>> ValuationAsync(
|
|
Actor actor, string companyCode, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken = default)
|
|
{
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, StockPermission, cancellationToken).ConfigureAwait(false);
|
|
await _permissions.DemandAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
return await ValuationAsync(uow, date, warehouseId, method, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>The value of the stock at a date inside a unit of work (the closing values the inventory with it).</summary>
|
|
internal static async Task<IReadOnlyList<ValuationRow>> ValuationAsync(
|
|
IUnitOfWork uow, DateOnly date, long? warehouseId, StockValuationMethod method, CancellationToken cancellationToken)
|
|
{
|
|
var lines = (await uow.Repository<InventoryEntryLine, long>().ListAsync(
|
|
Query.For<InventoryEntryLine>().Where(l => l.EntryDate <= date).OrderBy(l => l.EntryDate).OrderBy(l => l.EntryId).OrderBy(l => l.SortOrder), cancellationToken)
|
|
.ConfigureAwait(false)).Items;
|
|
var itemIds = lines.Select(l => l.ItemId).Distinct().ToList();
|
|
var items = itemIds.Count == 0 ? [] : (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken)
|
|
.ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
|
|
var rows = new List<ValuationRow>();
|
|
foreach (var group in lines.GroupBy(l => l.ItemId))
|
|
{
|
|
if (!items.TryGetValue(group.Key, out var item))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
// The costs written on the movements are those of the last run: the history up to the day gives the average then.
|
|
var history = StockCostCalculator.Run(group.Select(l => new CostedMovement(l.Id, l.EntryDate, l.WarehouseId, l.Quantity, l.Valued, l.Valued ? l.UnitCost : 0m)), item.StandardCost ?? 0m);
|
|
var quantity = warehouseId is { } w ? history.Warehouses.GetValueOrDefault(w)?.OnHand ?? 0m : history.OnHand;
|
|
if (quantity == 0m)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var cost = method switch
|
|
{
|
|
StockValuationMethod.LastCost => history.LastCost ?? history.AverageCost,
|
|
StockValuationMethod.StandardCost => item.StandardCost ?? history.AverageCost,
|
|
_ => history.AverageCost,
|
|
};
|
|
rows.Add(new ValuationRow(item.Id, item.Code, item.Description, quantity, cost, StockCostCalculator.Value(quantity, cost), 'C'));
|
|
}
|
|
|
|
return Classify(rows);
|
|
}
|
|
|
|
/// <summary>The items under their thresholds, the most urgent first (dashboard widget and reorder).</summary>
|
|
/// <param name="actor">Who reads.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="limit">How many.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The rows.</returns>
|
|
public async Task<IReadOnlyList<StockRow>> UnderstockAsync(Actor actor, string companyCode, int limit = 10, CancellationToken cancellationToken = default)
|
|
{
|
|
var rows = await StockAsync(actor, companyCode, new StockFilter { UnderstockOnly = true }, cancellationToken).ConfigureAwait(false);
|
|
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.
|
|
/// </summary>
|
|
/// <param name="available">On hand less committed.</param>
|
|
/// <param name="ordered">Ordered from suppliers.</param>
|
|
/// <param name="minimum">The minimum stock.</param>
|
|
/// <param name="reorderPoint">The reorder point.</param>
|
|
/// <returns>The level.</returns>
|
|
public static StockLevel LevelOf(decimal available, decimal ordered, decimal? minimum, decimal? reorderPoint)
|
|
{
|
|
var watched = minimum is not null || reorderPoint is not null;
|
|
if (available < 0m || (watched && available <= 0m))
|
|
{
|
|
return StockLevel.Out;
|
|
}
|
|
|
|
if (minimum is { } min && available < min)
|
|
{
|
|
return StockLevel.Understock;
|
|
}
|
|
|
|
return reorderPoint is { } point && available + ordered <= point ? StockLevel.Reorder : StockLevel.Ok;
|
|
}
|
|
|
|
/// <summary>Gives the ABC class by value: A up to 80% of the total, B up to 95%, C the rest.</summary>
|
|
/// <param name="rows">The rows.</param>
|
|
/// <returns>The rows by value, with their class.</returns>
|
|
public static IReadOnlyList<ValuationRow> Classify(IEnumerable<ValuationRow> rows)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(rows);
|
|
var sorted = rows.OrderByDescending(r => r.Value).ThenBy(r => r.Code, StringComparer.Ordinal).ToList();
|
|
var total = sorted.Where(r => r.Value > 0m).Sum(r => r.Value);
|
|
var running = 0m;
|
|
var result = new List<ValuationRow>(sorted.Count);
|
|
foreach (var row in sorted)
|
|
{
|
|
// The class of an item is where its value starts: the first item is always A.
|
|
var share = total <= 0m ? 1m : running / total;
|
|
running += Math.Max(row.Value, 0m);
|
|
result.Add(row with { AbcClass = share < 0.80m ? 'A' : share < 0.95m ? 'B' : 'C' });
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
internal static StockRow RowOf(Item item, IReadOnlyList<ItemBalance> balances, bool costs)
|
|
{
|
|
var onHand = balances.Sum(b => b.OnHand);
|
|
var committed = balances.Sum(b => b.Committed);
|
|
var ordered = balances.Sum(b => b.Ordered);
|
|
var available = onHand - committed;
|
|
var average = balances.Count > 0 ? balances[0].AverageCost : item.AverageCost ?? 0m;
|
|
return new StockRow(
|
|
item.Id, item.Code, item.Description, item.CategoryId, item.UnitOfMeasureId, onHand, committed, ordered, available, item.MinimumStock, item.ReorderPoint,
|
|
costs ? average : null, costs ? balances.Sum(b => b.Value) : null,
|
|
balances.Max(b => b.LastLoadDate), balances.Max(b => b.LastUnloadDate),
|
|
LevelOf(available, ordered, item.MinimumStock, item.ReorderPoint));
|
|
}
|
|
|
|
internal static async Task<Dictionary<long, List<ItemBalance>>> BalancesByItemAsync(IUnitOfWork uow, long? warehouseId, CancellationToken cancellationToken)
|
|
{
|
|
var query = Query.For<ItemBalance>();
|
|
if (warehouseId is { } warehouse)
|
|
{
|
|
query = query.Where(b => b.WarehouseId == warehouse);
|
|
}
|
|
|
|
return (await uow.Repository<ItemBalance, long>().ListAsync(query, cancellationToken).ConfigureAwait(false)).Items
|
|
.GroupBy(b => b.ItemId).ToDictionary(g => g.Key, g => g.ToList());
|
|
}
|
|
|
|
private async Task<bool> CostsAsync(Actor actor, CancellationToken cancellationToken) =>
|
|
(await _permissions.CheckAsync(actor, ItemService.CostPermission, cancellationToken).ConfigureAwait(false)).Allowed;
|
|
}
|