Files
WMSlite/WmsLite.Api/Services/InventoryService.cs
T
zhougfandCursor fa1b286463 Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 14:17:47 +08:00

370 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Inventory;
using WmsLite.Api.Enums;
using WmsLite.Api.Infrastructure.Auth;
using WmsLite.Api.Models;
using WmsLite.Api.Repositories.Interfaces;
using WmsLite.Api.Services.Interfaces;
namespace WmsLite.Api.Services;
public class InventoryService : IInventoryService
{
private readonly IInventoryRepository _inventoryRepository;
private readonly ISysTemplateRepository _sysTemplateRepository;
private readonly ILocationRepository _locationRepository;
private readonly IMaterialRepository _materialRepository;
private readonly IContainerRepository _containerRepository;
private readonly IWarehouseRepository _warehouseRepository;
private readonly IAreaRepository _areaRepository;
private readonly IZoneRepository _zoneRepository;
private readonly ITemplateFieldValidationService _templateFieldValidationService;
private readonly IInventoryMovementService _inventoryMovementService;
private readonly ICurrentUserContext _userContext;
public InventoryService(
IInventoryRepository inventoryRepository,
ISysTemplateRepository sysTemplateRepository,
ILocationRepository locationRepository,
IMaterialRepository materialRepository,
IContainerRepository containerRepository,
IWarehouseRepository warehouseRepository,
IAreaRepository areaRepository,
IZoneRepository zoneRepository,
ITemplateFieldValidationService templateFieldValidationService,
IInventoryMovementService inventoryMovementService,
ICurrentUserContext userContext)
{
_inventoryRepository = inventoryRepository;
_sysTemplateRepository = sysTemplateRepository;
_locationRepository = locationRepository;
_materialRepository = materialRepository;
_containerRepository = containerRepository;
_warehouseRepository = warehouseRepository;
_areaRepository = areaRepository;
_zoneRepository = zoneRepository;
_templateFieldValidationService = templateFieldValidationService;
_inventoryMovementService = inventoryMovementService;
_userContext = userContext;
}
public async Task<PagedResult<InventoryViewDto>> GetPagedListAsync(InventoryPagedQuery query)
{
query.TenantId = _userContext.TenantId.Trim();
query.OwnerCode = _userContext.OwnerCode.Trim();
var pageData = await _inventoryRepository.GetPagedListAsync(query);
var template = await _templateFieldValidationService.ValidateSearchParamAsync(
_userContext.TenantId.Trim(),
_userContext.OwnerCode.Trim(),
query.BizType,
query.SearchParam);
var viewItems = new List<InventoryViewDto>(pageData.Items.Count);
var tenant = _userContext.TenantId.Trim();
var owner = _userContext.OwnerCode.Trim();
var whCodes = pageData.Items.Select(x => x.WarehouseCode).Distinct(StringComparer.Ordinal).ToList();
var materialCodes = pageData.Items
.Where(x => !string.IsNullOrWhiteSpace(x.MaterialCode))
.Select(x => x.MaterialCode!.Trim())
.Distinct(StringComparer.Ordinal)
.ToList();
var warehouseNames = await _warehouseRepository.GetNameMapByCodesAsync(tenant, owner, whCodes);
var areaNames = await _areaRepository.GetNameMapByWarehouseCodesAsync(tenant, owner, whCodes);
var zoneNames = await _zoneRepository.GetNameMapByWarehouseCodesAsync(tenant, owner, whCodes);
var materialNames = await _materialRepository.GetNameMapByCodesAsync(tenant, owner, materialCodes);
foreach (var item in pageData.Items)
{
var areaKey = $"{item.WarehouseCode}\0{item.AreaCode}";
var zoneKey = $"{item.WarehouseCode}\0{item.AreaCode}\0{item.ZoneCode}";
viewItems.Add(MapToView(
item,
template,
warehouseNames.GetValueOrDefault(item.WarehouseCode, string.Empty),
areaNames.GetValueOrDefault(areaKey, string.Empty),
zoneNames.GetValueOrDefault(zoneKey, string.Empty),
string.IsNullOrWhiteSpace(item.MaterialCode)
? string.Empty
: materialNames.GetValueOrDefault(item.MaterialCode!, string.Empty)));
}
return new PagedResult<InventoryViewDto>
{
PageIndex = pageData.PageIndex,
PageSize = pageData.PageSize,
TotalCount = pageData.TotalCount,
Items = viewItems
};
}
public async Task<InventoryViewDto> CreateAsync(InventorySaveRequest request)
{
var template = await _templateFieldValidationService.ValidateAttrsAsync(
_userContext.TenantId.Trim(),
_userContext.OwnerCode.Trim(),
request.BizType,
request.Attrs);
await EnsureLocationExistsAsync(
_userContext.TenantId.Trim(),
_userContext.OwnerCode.Trim(),
request.WarehouseCode,
request.AreaCode,
request.ZoneCode,
request.LocationCode);
if (request.InventoryKind == InventoryKind.Material)
{
var material = await _materialRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request.MaterialCode!.Trim());
if (material is null)
{
throw new BusinessException($"物料编码不存在: {request.MaterialCode!.Trim()}");
}
}
else
{
var container = await _containerRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request.ContainerCode!.Trim());
if (container is null)
{
throw new BusinessException($"容器编码不存在: {request.ContainerCode!.Trim()}");
}
}
var entity = new Inventory
{
TenantId = _userContext.TenantId.Trim(),
OwnerCode = _userContext.OwnerCode.Trim(),
InventoryKind = request.InventoryKind,
InventoryStatus = request.InventoryStatus,
MaterialCode = request.InventoryKind == InventoryKind.Material ? request.MaterialCode!.Trim() : null,
ContainerCode = request.InventoryKind == InventoryKind.EmptyContainer ? request.ContainerCode!.Trim() : null,
WarehouseCode = request.WarehouseCode.Trim(),
AreaCode = request.AreaCode.Trim(),
ZoneCode = request.ZoneCode.Trim(),
LocationCode = request.LocationCode.Trim(),
Qty = request.Qty,
PendingInboundQty = request.PendingInboundQty,
PendingOutboundQty = request.PendingOutboundQty,
FrozenQty = request.FrozenQty,
Unit = request.Unit.Trim(),
Attrs = request.Attrs ?? new Dictionary<string, object>()
};
await _inventoryMovementService.ApplySnapshotAsync(entity, null, InventoryMovementType.Adjust);
return MapToView(entity, template);
}
public async Task<InventoryViewDto?> UpdateAsync(InventoryUpdateRequest request)
{
var template = await _templateFieldValidationService.ValidateAttrsAsync(
_userContext.TenantId.Trim(),
_userContext.OwnerCode.Trim(),
request.BizType,
request.Attrs);
var entity = await _inventoryRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (entity is null)
{
return null;
}
var before = Clone(entity);
await EnsureLocationExistsAsync(
_userContext.TenantId.Trim(),
_userContext.OwnerCode.Trim(),
request.WarehouseCode,
request.AreaCode,
request.ZoneCode,
request.LocationCode);
if (request.InventoryKind == InventoryKind.Material)
{
var material = await _materialRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request.MaterialCode!.Trim());
if (material is null)
{
throw new BusinessException($"物料编码不存在: {request.MaterialCode!.Trim()}");
}
}
else
{
var container = await _containerRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request.ContainerCode!.Trim());
if (container is null)
{
throw new BusinessException($"容器编码不存在: {request.ContainerCode!.Trim()}");
}
}
entity.InventoryKind = request.InventoryKind;
entity.InventoryStatus = request.InventoryStatus;
entity.MaterialCode = request.InventoryKind == InventoryKind.Material ? request.MaterialCode!.Trim() : null;
entity.ContainerCode = request.InventoryKind == InventoryKind.EmptyContainer ? request.ContainerCode!.Trim() : null;
entity.WarehouseCode = request.WarehouseCode.Trim();
entity.AreaCode = request.AreaCode.Trim();
entity.ZoneCode = request.ZoneCode.Trim();
entity.LocationCode = request.LocationCode.Trim();
entity.Qty = request.Qty;
entity.PendingInboundQty = request.PendingInboundQty;
entity.PendingOutboundQty = request.PendingOutboundQty;
entity.FrozenQty = request.FrozenQty;
entity.Unit = request.Unit.Trim();
entity.Attrs = request.Attrs ?? new Dictionary<string, object>();
await _inventoryMovementService.ApplySnapshotAsync(entity, before, InventoryMovementType.Adjust);
return MapToView(entity, template);
}
public async Task<int> DeleteAsync(long id, string tenantId, string ownerCode)
{
return await _inventoryRepository.SoftDeleteAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
}
public async Task<InventoryViewDto?> MoveAsync(InventoryMoveRequest request)
{
var inventory = await _inventoryRepository.GetByIdAsync(request.InventoryId, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (inventory is null)
{
return null;
}
throw new BusinessException(
"冻结、解冻及待入/入库确认/待出/出库确认请通过对应业务单据完成,不能从库存界面直接操作。");
}
private async Task EnsureLocationExistsAsync(
string tenantId,
string ownerCode,
string warehouseCode,
string areaCode,
string zoneCode,
string locationCode)
{
var loc = await _locationRepository.GetByWarehouseAreaZoneAndLocationCodeAsync(
tenantId, ownerCode, warehouseCode, areaCode.Trim(), zoneCode.Trim(), locationCode.Trim());
if (loc is null)
{
throw new BusinessException(
$"储位不存在: 仓库 {warehouseCode.Trim()} / 库区 {areaCode.Trim()} / 分区 {zoneCode.Trim()} / 储位 {locationCode.Trim()}");
}
}
private static InventoryViewDto MapToView(Inventory item, SysTemplate? template)
=> MapToView(item, template, string.Empty, string.Empty, string.Empty, string.Empty);
private static InventoryViewDto MapToView(
Inventory item,
SysTemplate? template,
string warehouseName,
string areaName,
string zoneName,
string materialName)
{
var view = new InventoryViewDto
{
Id = item.Id,
TenantId = item.TenantId,
OwnerCode = item.OwnerCode,
InventoryKind = item.InventoryKind,
InventoryStatus = item.InventoryStatus,
MaterialCode = item.MaterialCode,
ContainerCode = item.ContainerCode,
WarehouseCode = item.WarehouseCode,
WarehouseName = warehouseName,
AreaCode = item.AreaCode,
AreaName = areaName,
ZoneCode = item.ZoneCode,
ZoneName = zoneName,
LocationCode = item.LocationCode,
MaterialName = materialName,
Qty = item.Qty,
PendingInboundQty = item.PendingInboundQty,
PendingOutboundQty = item.PendingOutboundQty,
FrozenQty = item.FrozenQty,
Unit = item.Unit,
Attrs = item.Attrs
};
if (template is null || string.IsNullOrWhiteSpace(template.ConfigJson))
{
return view;
}
view.ConfigFields = ParseTemplateFields(template.ConfigJson, item.Attrs);
return view;
}
private static List<TemplateFieldDto>? ParseTemplateFields(string configJson, Dictionary<string, object>? attrs)
{
try
{
var doc = JsonDocument.Parse(configJson);
if (doc.RootElement.ValueKind != JsonValueKind.Array)
{
return null;
}
var fields = new List<TemplateFieldDto>();
foreach (var fieldElement in doc.RootElement.EnumerateArray())
{
var field = fieldElement.TryGetProperty("field", out var fieldProp) ? fieldProp.GetString() : null;
if (string.IsNullOrWhiteSpace(field))
{
continue;
}
var label = fieldElement.TryGetProperty("label", out var labelProp) ? labelProp.GetString() : field;
var type = fieldElement.TryGetProperty("type", out var typeProp) ? typeProp.GetString() : "text";
object? value = null;
if (attrs?.TryGetValue(field, out var attrValue) == true)
{
value = attrValue;
}
fields.Add(new TemplateFieldDto
{
Field = field,
Label = label ?? field,
Type = type ?? "text",
Value = value
});
}
return fields.Count == 0 ? null : fields;
}
catch
{
return null;
}
}
private static Inventory Clone(Inventory inventory)
{
return new Inventory
{
Id = inventory.Id,
TenantId = inventory.TenantId,
OwnerCode = inventory.OwnerCode,
InventoryKind = inventory.InventoryKind,
InventoryStatus = inventory.InventoryStatus,
MaterialCode = inventory.MaterialCode,
ContainerCode = inventory.ContainerCode,
WarehouseCode = inventory.WarehouseCode,
AreaCode = inventory.AreaCode,
ZoneCode = inventory.ZoneCode,
LocationCode = inventory.LocationCode,
Qty = inventory.Qty,
PendingInboundQty = inventory.PendingInboundQty,
PendingOutboundQty = inventory.PendingOutboundQty,
FrozenQty = inventory.FrozenQty,
Unit = inventory.Unit,
Attrs = inventory.Attrs
};
}
}