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>
This commit is contained in:
zhougfandCursor committed 2026-05-24 14:17:47 +08:00
commit fa1b286463
241 files changed
+31188

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Area;
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 AreaService : IAreaService
{
private readonly IAreaRepository _areaRepository;
private readonly IWarehouseRepository _warehouseRepository;
private readonly ICurrentUserContext _userContext;
public AreaService(
IAreaRepository areaRepository,
IWarehouseRepository warehouseRepository,
ICurrentUserContext userContext)
{
_areaRepository = areaRepository;
_warehouseRepository = warehouseRepository;
_userContext = userContext;
}
public async Task<PagedResult<AreaViewDto>> GetPagedListAsync(AreaPagedQuery query)
{
query.TenantId = _userContext.TenantId.Trim();
query.OwnerCode = _userContext.OwnerCode.Trim();
var page = await _areaRepository.GetPagedListAsync(query);
var items = page.Items.ConvertAll(MapToView);
return new PagedResult<AreaViewDto>
{
PageIndex = page.PageIndex,
PageSize = page.PageSize,
TotalCount = page.TotalCount,
Items = items
};
}
public async Task<AreaViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode)
{
var entity = await _areaRepository.GetByIdAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
return entity is null ? null : MapToView(entity);
}
public async Task<AreaViewDto> CreateAsync(AreaSaveRequest request)
{
var warehouseCode = request.WarehouseCode.Trim();
var code = request.Code.Trim();
var name = request.Name.Trim();
if (await _warehouseRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode) is null)
{
throw new BusinessException($"仓库不存在: {warehouseCode}");
}
if (await _areaRepository.GetByWarehouseAndAreaCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, code) is not null)
{
throw new BusinessException($"该仓库下库区编码已存在: {code}");
}
var entity = new Area
{
TenantId = _userContext.TenantId.Trim(),
OwnerCode = _userContext.OwnerCode.Trim(),
WarehouseCode = warehouseCode,
Code = code,
Name = name,
Attrs = request.Attrs
};
await _areaRepository.InsertAsync(entity);
return MapToView(entity);
}
public async Task<AreaViewDto?> UpdateAsync(AreaUpdateRequest request)
{
var entity = await _areaRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (entity is null)
{
return null;
}
var warehouseCode = request.WarehouseCode.Trim();
var code = request.Code.Trim();
var name = request.Name.Trim();
if (await _warehouseRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode) is null)
{
throw new BusinessException($"仓库不存在: {warehouseCode}");
}
var duplicate = await _areaRepository.GetByWarehouseAndAreaCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, code);
if (duplicate is not null && duplicate.Id != entity.Id)
{
throw new BusinessException($"该仓库下库区编码已被占用: {code}");
}
entity.WarehouseCode = warehouseCode;
entity.Code = code;
entity.Name = name;
entity.Attrs = request.Attrs;
await _areaRepository.UpdateAsync(entity);
return MapToView(entity);
}
public Task<int> DeleteAsync(long id, string tenantId, string ownerCode)
{
return _areaRepository.SoftDeleteAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
}
private static AreaViewDto MapToView(Area entity)
{
return new AreaViewDto
{
Id = entity.Id,
TenantId = entity.TenantId,
OwnerCode = entity.OwnerCode,
WarehouseCode = entity.WarehouseCode,
Code = entity.Code,
Name = entity.Name,
Attrs = entity.Attrs
};
}
}
+65
View File
@@ -0,0 +1,65 @@
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Auth;
using WmsLite.Api.Infrastructure.Auth;
using WmsLite.Api.Repositories.Interfaces;
using WmsLite.Api.Services.Interfaces;
namespace WmsLite.Api.Services;
public class AuthService : IAuthService
{
private readonly ISysUserRepository _userRepository;
private readonly IJwtTokenService _jwtTokenService;
public AuthService(ISysUserRepository userRepository, IJwtTokenService jwtTokenService)
{
_userRepository = userRepository;
_jwtTokenService = jwtTokenService;
}
public async Task<LoginResponseDto> LoginAsync(LoginRequest request)
{
var tenantId = string.IsNullOrWhiteSpace(request.TenantId) ? "default" : request.TenantId.Trim();
var ownerCode = string.IsNullOrWhiteSpace(request.OwnerCode) ? "default" : request.OwnerCode.Trim();
var username = request.Username?.Trim() ?? string.Empty;
var password = request.Password ?? string.Empty;
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
throw new BusinessException("用户名或密码不能为空。");
}
var user = await _userRepository.GetByUsernameAsync(tenantId, ownerCode, username);
if (user is null || !user.IsEnabled)
{
throw new BusinessException("用户名或密码错误。");
}
if (!BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
{
throw new BusinessException("用户名或密码错误。");
}
var (token, expiresAt) = _jwtTokenService.CreateToken(user);
return new LoginResponseDto
{
Token = token,
ExpiresAt = expiresAt,
UserId = user.Id.ToString(),
TenantId = user.TenantId,
OwnerCode = user.OwnerCode,
DisplayName = user.DisplayName ?? user.Username,
};
}
public MeResponseDto GetCurrentUser(ICurrentUserContext userContext)
{
return new MeResponseDto
{
UserId = userContext.UserId,
TenantId = userContext.TenantId,
OwnerCode = userContext.OwnerCode,
DisplayName = userContext.DisplayName ?? userContext.UserId,
};
}
}
+110
View File
@@ -0,0 +1,110 @@
using System;
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Container;
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 ContainerService : IContainerService
{
private readonly IContainerRepository _containerRepository;
private readonly ICurrentUserContext _userContext;
public ContainerService(IContainerRepository containerRepository, ICurrentUserContext userContext)
{
_containerRepository = containerRepository;
_userContext = userContext;
}
public async Task<PagedResult<ContainerViewDto>> GetPagedListAsync(ContainerPagedQuery query)
{
query.TenantId = _userContext.TenantId.Trim();
query.OwnerCode = _userContext.OwnerCode.Trim();
var page = await _containerRepository.GetPagedListAsync(query);
var items = page.Items.ConvertAll(MapToView);
return new PagedResult<ContainerViewDto>
{
PageIndex = page.PageIndex,
PageSize = page.PageSize,
TotalCount = page.TotalCount,
Items = items
};
}
public async Task<ContainerViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode)
{
var entity = await _containerRepository.GetByIdAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
return entity is null ? null : MapToView(entity);
}
public async Task<ContainerViewDto> CreateAsync(ContainerSaveRequest request)
{
var code = request.Code.Trim();
if (await _containerRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), code) is not null)
{
throw new BusinessException($"容器编码已存在: {code}");
}
var entity = new Container
{
TenantId = _userContext.TenantId.Trim(),
OwnerCode = _userContext.OwnerCode.Trim(),
Code = code,
Name = string.IsNullOrWhiteSpace(request.Name) ? null : request.Name.Trim(),
ContainerType = string.IsNullOrWhiteSpace(request.ContainerType) ? null : request.ContainerType.Trim(),
Attrs = request.Attrs
};
await _containerRepository.InsertAsync(entity);
return MapToView(entity);
}
public async Task<ContainerViewDto?> UpdateAsync(ContainerUpdateRequest request)
{
var entity = await _containerRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (entity is null)
{
return null;
}
var code = request.Code.Trim();
var existing = await _containerRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), code);
if (existing is not null && existing.Id != entity.Id)
{
throw new BusinessException($"容器编码已被占用: {code}");
}
entity.Code = code;
entity.Name = string.IsNullOrWhiteSpace(request.Name) ? null : request.Name.Trim();
entity.ContainerType = string.IsNullOrWhiteSpace(request.ContainerType) ? null : request.ContainerType.Trim();
entity.Attrs = request.Attrs;
await _containerRepository.UpdateAsync(entity);
return MapToView(entity);
}
public Task<int> DeleteAsync(long id, string tenantId, string ownerCode)
{
return _containerRepository.SoftDeleteAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
}
private static ContainerViewDto MapToView(Container entity)
{
return new ContainerViewDto
{
Id = entity.Id,
TenantId = entity.TenantId,
OwnerCode = entity.OwnerCode,
Code = entity.Code,
Name = entity.Name,
ContainerType = entity.ContainerType,
Attrs = entity.Attrs
};
}
}
@@ -0,0 +1,18 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Area;
namespace WmsLite.Api.Services.Interfaces;
public interface IAreaService
{
Task<PagedResult<AreaViewDto>> GetPagedListAsync(AreaPagedQuery query);
Task<AreaViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode);
Task<AreaViewDto> CreateAsync(AreaSaveRequest request);
Task<AreaViewDto?> UpdateAsync(AreaUpdateRequest request);
Task<int> DeleteAsync(long id, string tenantId, string ownerCode);
}
@@ -0,0 +1,11 @@
using WmsLite.Api.Dtos.Auth;
using WmsLite.Api.Infrastructure.Auth;
namespace WmsLite.Api.Services.Interfaces;
public interface IAuthService
{
Task<LoginResponseDto> LoginAsync(LoginRequest request);
MeResponseDto GetCurrentUser(ICurrentUserContext userContext);
}
@@ -0,0 +1,18 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Container;
namespace WmsLite.Api.Services.Interfaces;
public interface IContainerService
{
Task<PagedResult<ContainerViewDto>> GetPagedListAsync(ContainerPagedQuery query);
Task<ContainerViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode);
Task<ContainerViewDto> CreateAsync(ContainerSaveRequest request);
Task<ContainerViewDto?> UpdateAsync(ContainerUpdateRequest request);
Task<int> DeleteAsync(long id, string tenantId, string ownerCode);
}
@@ -0,0 +1,22 @@
using System.Threading.Tasks;
using WmsLite.Api.Enums;
using WmsLite.Api.Models;
namespace WmsLite.Api.Services.Interfaces;
public interface IInventoryMovementService
{
Task ApplySnapshotAsync(Inventory inventory, Inventory? existing, InventoryMovementType movementType, string? bizNo = null);
Task PendingInboundAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null);
Task ConfirmInboundAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null);
Task PendingOutboundAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null);
Task ConfirmOutboundAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null);
Task FreezeAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null);
Task UnfreezeAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null);
}
@@ -0,0 +1,19 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Inventory;
namespace WmsLite.Api.Services.Interfaces;
public interface IInventoryService
{
Task<PagedResult<InventoryViewDto>> GetPagedListAsync(InventoryPagedQuery query);
Task<InventoryViewDto> CreateAsync(InventorySaveRequest request);
Task<InventoryViewDto?> UpdateAsync(InventoryUpdateRequest request);
Task<int> DeleteAsync(long id, string tenantId, string ownerCode);
/// <summary>通过库存动作服务执行调整;不直接改写数量字段。</summary>
Task<InventoryViewDto?> MoveAsync(InventoryMoveRequest request);
}
@@ -0,0 +1,10 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Inventory;
namespace WmsLite.Api.Services.Interfaces;
public interface IInventoryTransactionService
{
Task<PagedResult<InventoryTransactionViewDto>> GetPagedListAsync(InventoryTransactionPagedQuery query);
}
@@ -0,0 +1,20 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Location;
namespace WmsLite.Api.Services.Interfaces;
public interface ILocationService
{
Task<PagedResult<LocationViewDto>> GetPagedListAsync(LocationPagedQuery query);
Task<LocationViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode);
Task<LocationViewDto> CreateAsync(LocationSaveRequest request);
Task<LocationViewDto?> UpdateAsync(LocationUpdateRequest request);
Task<int> DeleteAsync(long id, string tenantId, string ownerCode);
Task<LocationBatchCreateResultDto> BatchCreateAsync(LocationBatchCreateRequest request);
}
@@ -0,0 +1,18 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Material;
namespace WmsLite.Api.Services.Interfaces;
public interface IMaterialService
{
Task<PagedResult<MaterialViewDto>> GetPagedListAsync(MaterialPagedQuery query);
Task<MaterialViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode);
Task<MaterialViewDto> CreateAsync(MaterialSaveRequest request);
Task<MaterialViewDto?> UpdateAsync(MaterialUpdateRequest request);
Task<int> DeleteAsync(long id, string tenantId, string ownerCode);
}
@@ -0,0 +1,6 @@
namespace WmsLite.Api.Services.Interfaces;
public interface IOrderNumberGenerator
{
Task<string> NextInboundOrderNoAsync(string tenantId, string ownerCode, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,54 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Orders;
namespace WmsLite.Api.Services.Interfaces;
public interface IInboundOrderService
{
Task<PagedResult<OrderViewDto>> GetPagedListAsync(InboundOrderPagedQuery query);
Task<List<InventoryOrderLineViewDto>?> GetLinesAsync(long orderId, string tenantId, string ownerCode);
Task<OrderViewDto> CreateAsync(InboundOrderCreateRequest request);
Task<InboundConfirmLineResultDto?> ConfirmLineAsync(InboundOrderLineConfirmRequest request);
}
public interface IOutboundOrderService
{
Task<PagedResult<OrderViewDto>> GetPagedListAsync(OutboundOrderPagedQuery query);
Task<List<InventoryOrderLineViewDto>?> GetLinesAsync(long orderId, string tenantId, string ownerCode);
Task<OrderViewDto> CreateAsync(OutboundOrderSaveRequest request);
Task<OrderViewDto?> PendingAsync(OrderActionRequest request);
Task<OrderViewDto?> ConfirmAsync(OrderActionRequest request);
}
public interface ITransferOrderService
{
Task<PagedResult<OrderViewDto>> GetPagedListAsync(TransferOrderPagedQuery query);
Task<List<TransferOrderLineViewDto>?> GetLinesAsync(long orderId, string tenantId, string ownerCode);
Task<OrderViewDto> CreateAsync(TransferOrderSaveRequest request);
Task<OrderViewDto?> PendingAsync(OrderActionRequest request);
Task<OrderViewDto?> ConfirmAsync(OrderActionRequest request);
}
public interface IStocktakeOrderService
{
Task<PagedResult<OrderViewDto>> GetPagedListAsync(StocktakeOrderPagedQuery query);
Task<List<StocktakeOrderLineViewDto>?> GetLinesAsync(long orderId, string tenantId, string ownerCode);
Task<OrderViewDto> CreateAsync(StocktakeOrderSaveRequest request);
Task<OrderViewDto?> ConfirmAsync(OrderActionRequest request);
}
@@ -0,0 +1,10 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using WmsLite.Api.Dtos.Dictionary;
namespace WmsLite.Api.Services.Interfaces;
public interface ISysDictService
{
Task<Dictionary<string, Dictionary<string, string>>> GetMergedMapAsync(SysDictionaryMapRequest request);
}
@@ -0,0 +1,16 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Template;
namespace WmsLite.Api.Services.Interfaces;
public interface ISysTemplateService
{
Task<PagedResult<SysTemplateViewDto>> GetPagedListAsync(SysTemplatePagedQuery query);
Task<SysTemplateViewDto> CreateAsync(SysTemplateSaveRequest request);
Task<SysTemplateViewDto?> UpdateAsync(SysTemplateUpdateRequest request);
Task<int> DeleteAsync(long id, string tenantId, string ownerCode);
}
@@ -0,0 +1,20 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using WmsLite.Api.Models;
namespace WmsLite.Api.Services.Interfaces;
public interface ITemplateFieldValidationService
{
Task<SysTemplate?> ValidateAttrsAsync(
string tenantId,
string ownerCode,
string? bizType,
Dictionary<string, object>? attrs);
Task<SysTemplate?> ValidateSearchParamAsync(
string tenantId,
string ownerCode,
string? bizType,
Dictionary<string, object>? searchParam);
}
@@ -0,0 +1,18 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Warehouse;
namespace WmsLite.Api.Services.Interfaces;
public interface IWarehouseService
{
Task<PagedResult<WarehouseViewDto>> GetPagedListAsync(WarehousePagedQuery query);
Task<WarehouseViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode);
Task<WarehouseViewDto> CreateAsync(WarehouseSaveRequest request);
Task<WarehouseViewDto?> UpdateAsync(WarehouseUpdateRequest request);
Task<int> DeleteAsync(long id, string tenantId, string ownerCode);
}
@@ -0,0 +1,18 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Zone;
namespace WmsLite.Api.Services.Interfaces;
public interface IZoneService
{
Task<PagedResult<ZoneViewDto>> GetPagedListAsync(ZonePagedQuery query);
Task<ZoneViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode);
Task<ZoneViewDto> CreateAsync(ZoneSaveRequest request);
Task<ZoneViewDto?> UpdateAsync(ZoneUpdateRequest request);
Task<int> DeleteAsync(long id, string tenantId, string ownerCode);
}
@@ -0,0 +1,237 @@
using System.Collections.Generic;
using WmsLite.Api.Common;
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 InventoryMovementService : IInventoryMovementService
{
private readonly IInventoryRepository _inventoryRepository;
private readonly IInventoryTransactionRepository _transactionRepository;
private readonly ICurrentUserContext _userContext;
public InventoryMovementService(
IInventoryRepository inventoryRepository,
IInventoryTransactionRepository transactionRepository,
ICurrentUserContext userContext)
{
_inventoryRepository = inventoryRepository;
_transactionRepository = transactionRepository;
_userContext = userContext;
}
public async Task ApplySnapshotAsync(Inventory inventory, Inventory? existing, InventoryMovementType movementType, string? bizNo = null)
{
ValidateQuantities(inventory);
if (existing is null)
{
await _inventoryRepository.InsertAsync(inventory);
await WriteTransactionAsync(null, inventory, movementType, inventory.Qty, bizNo, null);
return;
}
await _inventoryRepository.UpdateAsync(inventory);
await WriteTransactionAsync(existing, inventory, movementType, inventory.Qty - existing.Qty, bizNo, null);
}
public async Task PendingInboundAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null)
{
EnsurePositive(qty);
var before = Clone(inventory);
inventory.PendingInboundQty += qty;
inventory.InventoryStatus = ResolveStatus(inventory);
await _inventoryRepository.UpdateAsync(inventory);
await WriteTransactionAsync(before, inventory, InventoryMovementType.PendingInbound, qty, bizNo, remark);
}
public async Task ConfirmInboundAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null)
{
EnsurePositive(qty);
if (inventory.PendingInboundQty < qty)
{
throw new BusinessException("PendingInboundQty is not enough.");
}
var before = Clone(inventory);
inventory.PendingInboundQty -= qty;
inventory.Qty += qty;
inventory.InventoryStatus = ResolveStatus(inventory);
await _inventoryRepository.UpdateAsync(inventory);
await WriteTransactionAsync(before, inventory, InventoryMovementType.InboundConfirm, qty, bizNo, remark);
}
public async Task PendingOutboundAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null)
{
EnsurePositive(qty);
if (AvailableQty(inventory) < qty)
{
throw new BusinessException("Available quantity is not enough.");
}
var before = Clone(inventory);
inventory.PendingOutboundQty += qty;
inventory.InventoryStatus = ResolveStatus(inventory);
await _inventoryRepository.UpdateAsync(inventory);
await WriteTransactionAsync(before, inventory, InventoryMovementType.PendingOutbound, qty, bizNo, remark);
}
public async Task ConfirmOutboundAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null)
{
EnsurePositive(qty);
if (inventory.PendingOutboundQty < qty || inventory.Qty < qty)
{
throw new BusinessException("PendingOutboundQty or Qty is not enough.");
}
var before = Clone(inventory);
inventory.PendingOutboundQty -= qty;
inventory.Qty -= qty;
inventory.InventoryStatus = ResolveStatus(inventory);
await _inventoryRepository.UpdateAsync(inventory);
await WriteTransactionAsync(before, inventory, InventoryMovementType.OutboundConfirm, -qty, bizNo, remark);
}
public async Task FreezeAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null)
{
EnsurePositive(qty);
if (AvailableQty(inventory) < qty)
{
throw new BusinessException("Available quantity is not enough.");
}
var before = Clone(inventory);
inventory.FrozenQty += qty;
inventory.InventoryStatus = ResolveStatus(inventory);
await _inventoryRepository.UpdateAsync(inventory);
await WriteTransactionAsync(before, inventory, InventoryMovementType.Freeze, qty, bizNo, remark);
}
public async Task UnfreezeAsync(Inventory inventory, decimal qty, string? bizNo = null, string? remark = null)
{
EnsurePositive(qty);
if (inventory.FrozenQty < qty)
{
throw new BusinessException("FrozenQty is not enough.");
}
var before = Clone(inventory);
inventory.FrozenQty -= qty;
inventory.InventoryStatus = ResolveStatus(inventory);
await _inventoryRepository.UpdateAsync(inventory);
await WriteTransactionAsync(before, inventory, InventoryMovementType.Unfreeze, -qty, bizNo, remark);
}
private async Task WriteTransactionAsync(Inventory? before, Inventory after, InventoryMovementType movementType, decimal changeQty, string? bizNo, string? remark)
{
var transaction = new InventoryTransaction
{
TenantId = after.TenantId,
OwnerCode = after.OwnerCode,
InventoryId = after.Id,
MovementType = movementType,
InventoryStatus = after.InventoryStatus,
BizNo = string.IsNullOrWhiteSpace(bizNo) ? null : bizNo.Trim(),
BeforeQty = before?.Qty ?? 0,
AfterQty = after.Qty,
BeforePendingInboundQty = before?.PendingInboundQty ?? 0,
AfterPendingInboundQty = after.PendingInboundQty,
BeforePendingOutboundQty = before?.PendingOutboundQty ?? 0,
AfterPendingOutboundQty = after.PendingOutboundQty,
BeforeFrozenQty = before?.FrozenQty ?? 0,
AfterFrozenQty = after.FrozenQty,
ChangeQty = changeQty,
MaterialCode = after.MaterialCode,
ContainerCode = after.ContainerCode,
WarehouseCode = after.WarehouseCode,
AreaCode = after.AreaCode,
ZoneCode = after.ZoneCode,
LocationCode = after.LocationCode,
Attrs = MergeTransactionAttrs(after.Attrs, remark)
};
await _transactionRepository.InsertAsync(transaction);
}
private static Dictionary<string, object>? MergeTransactionAttrs(Dictionary<string, object>? inventoryAttrs, string? remark)
{
if (string.IsNullOrWhiteSpace(remark))
{
return inventoryAttrs;
}
var dict = inventoryAttrs is null
? new Dictionary<string, object>()
: new Dictionary<string, object>(inventoryAttrs);
dict["remark"] = remark.Trim();
return dict;
}
private static Inventory Clone(Inventory inventory)
{
return new Inventory
{
Id = inventory.Id,
TenantId = inventory.TenantId,
OwnerCode = inventory.OwnerCode,
InventoryKind = inventory.InventoryKind,
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,
InventoryStatus = inventory.InventoryStatus,
Unit = inventory.Unit,
Attrs = inventory.Attrs
};
}
private static InventoryStatus ResolveStatus(Inventory inventory)
{
if (inventory.FrozenQty > 0)
{
return InventoryStatus.Frozen;
}
if (inventory.PendingOutboundQty > 0)
{
return InventoryStatus.PendingOutbound;
}
if (inventory.PendingInboundQty > 0)
{
return InventoryStatus.PendingInbound;
}
return InventoryStatus.Available;
}
private static decimal AvailableQty(Inventory inventory)
{
return inventory.Qty - inventory.PendingOutboundQty - inventory.FrozenQty;
}
private static void EnsurePositive(decimal qty)
{
if (qty <= 0)
{
throw new BusinessException("Movement quantity must be greater than 0.");
}
}
private static void ValidateQuantities(Inventory inventory)
{
if (inventory.Qty < 0 || inventory.PendingInboundQty < 0 || inventory.PendingOutboundQty < 0 || inventory.FrozenQty < 0)
{
throw new BusinessException("Inventory quantities cannot be negative.");
}
}
}
+369
View File
@@ -0,0 +1,369 @@
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
};
}
}
@@ -0,0 +1,60 @@
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Inventory;
using WmsLite.Api.Models;
using WmsLite.Api.Repositories.Interfaces;
using WmsLite.Api.Services.Interfaces;
namespace WmsLite.Api.Services;
public class InventoryTransactionService : IInventoryTransactionService
{
private readonly IInventoryTransactionRepository _repository;
public InventoryTransactionService(IInventoryTransactionRepository repository)
{
_repository = repository;
}
public async Task<PagedResult<InventoryTransactionViewDto>> GetPagedListAsync(InventoryTransactionPagedQuery query)
{
var page = await _repository.GetPagedListAsync(query);
return new PagedResult<InventoryTransactionViewDto>
{
PageIndex = page.PageIndex,
PageSize = page.PageSize,
TotalCount = page.TotalCount,
Items = page.Items.ConvertAll(Map)
};
}
private static InventoryTransactionViewDto Map(InventoryTransaction entity)
{
return new InventoryTransactionViewDto
{
Id = entity.Id,
TenantId = entity.TenantId,
OwnerCode = entity.OwnerCode,
InventoryId = entity.InventoryId,
MovementType = entity.MovementType,
InventoryStatus = entity.InventoryStatus,
BizNo = entity.BizNo,
BeforeQty = entity.BeforeQty,
AfterQty = entity.AfterQty,
BeforePendingInboundQty = entity.BeforePendingInboundQty,
AfterPendingInboundQty = entity.AfterPendingInboundQty,
BeforePendingOutboundQty = entity.BeforePendingOutboundQty,
AfterPendingOutboundQty = entity.AfterPendingOutboundQty,
BeforeFrozenQty = entity.BeforeFrozenQty,
AfterFrozenQty = entity.AfterFrozenQty,
ChangeQty = entity.ChangeQty,
MaterialCode = entity.MaterialCode,
ContainerCode = entity.ContainerCode,
WarehouseCode = entity.WarehouseCode,
AreaCode = entity.AreaCode,
ZoneCode = entity.ZoneCode,
LocationCode = entity.LocationCode,
Attrs = entity.Attrs,
CreateTime = entity.CreateTime
};
}
}
+347
View File
@@ -0,0 +1,347 @@
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Location;
using WmsLite.Api.Enums;
using WmsLite.Api.Infrastructure;
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 LocationService : ILocationService
{
private readonly ITransactionRunner _tx;
private readonly ILocationRepository _locationRepository;
private readonly IZoneRepository _zoneRepository;
private readonly ICurrentUserContext _userContext;
public LocationService(
ITransactionRunner tx,
ILocationRepository locationRepository,
IZoneRepository zoneRepository,
ICurrentUserContext userContext)
{
_tx = tx;
_locationRepository = locationRepository;
_zoneRepository = zoneRepository;
_userContext = userContext;
}
public async Task<PagedResult<LocationViewDto>> GetPagedListAsync(LocationPagedQuery query)
{
query.TenantId = _userContext.TenantId.Trim();
query.OwnerCode = _userContext.OwnerCode.Trim();
var page = await _locationRepository.GetPagedListAsync(query);
var items = page.Items.ConvertAll(MapToView);
return new PagedResult<LocationViewDto>
{
PageIndex = page.PageIndex,
PageSize = page.PageSize,
TotalCount = page.TotalCount,
Items = items
};
}
public async Task<LocationViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode)
{
var entity = await _locationRepository.GetByIdAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
return entity is null ? null : MapToView(entity);
}
public async Task<LocationViewDto> CreateAsync(LocationSaveRequest request)
{
var warehouseCode = request.WarehouseCode.Trim();
var areaCode = request.AreaCode.Trim();
var zoneCode = request.ZoneCode.Trim();
var code = request.Code.Trim();
if (await _zoneRepository.GetByWarehouseAreaAndZoneCodeAsync(
_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, areaCode, zoneCode) is null)
{
throw new BusinessException($"分区不存在: {warehouseCode} / {areaCode} / {zoneCode}");
}
if (await _locationRepository.GetByWarehouseAreaZoneAndLocationCodeAsync(
_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, areaCode, zoneCode, code) is not null)
{
throw new BusinessException($"储位编码已存在: {code}");
}
var entity = new Location
{
TenantId = _userContext.TenantId.Trim(),
OwnerCode = _userContext.OwnerCode.Trim(),
WarehouseCode = warehouseCode,
AreaCode = areaCode,
ZoneCode = zoneCode,
AisleCode = string.IsNullOrWhiteSpace(request.AisleCode) ? null : request.AisleCode.Trim(),
Code = code,
Name = request.Name?.Trim(),
RowNo = request.RowNo,
ColumnNo = request.ColumnNo,
LayerNo = request.LayerNo,
Height = request.Height,
LocationStatus = request.LocationStatus,
IsOuter = request.IsOuter,
ContainerCode = string.IsNullOrWhiteSpace(request.ContainerCode) ? null : request.ContainerCode.Trim(),
Attrs = request.Attrs
};
await _locationRepository.InsertAsync(entity);
return MapToView(entity);
}
public async Task<LocationViewDto?> UpdateAsync(LocationUpdateRequest request)
{
var entity = await _locationRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (entity is null)
{
return null;
}
var warehouseCode = request.WarehouseCode.Trim();
var areaCode = request.AreaCode.Trim();
var zoneCode = request.ZoneCode.Trim();
var code = request.Code.Trim();
if (await _zoneRepository.GetByWarehouseAreaAndZoneCodeAsync(
_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, areaCode, zoneCode) is null)
{
throw new BusinessException($"分区不存在: {warehouseCode} / {areaCode} / {zoneCode}");
}
var duplicate = await _locationRepository.GetByWarehouseAreaZoneAndLocationCodeAsync(
_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, areaCode, zoneCode, code);
if (duplicate is not null && duplicate.Id != entity.Id)
{
throw new BusinessException($"储位编码已被占用: {code}");
}
entity.WarehouseCode = warehouseCode;
entity.AreaCode = areaCode;
entity.ZoneCode = zoneCode;
entity.Code = code;
entity.Name = request.Name?.Trim();
entity.AisleCode = string.IsNullOrWhiteSpace(request.AisleCode) ? null : request.AisleCode.Trim();
entity.RowNo = request.RowNo;
entity.ColumnNo = request.ColumnNo;
entity.LayerNo = request.LayerNo;
entity.Height = request.Height;
entity.LocationStatus = request.LocationStatus;
entity.IsOuter = request.IsOuter;
entity.ContainerCode = string.IsNullOrWhiteSpace(request.ContainerCode) ? null : request.ContainerCode.Trim();
entity.Attrs = request.Attrs;
await _locationRepository.UpdateAsync(entity);
return MapToView(entity);
}
public Task<int> DeleteAsync(long id, string tenantId, string ownerCode)
{
return _locationRepository.SoftDeleteAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
}
/// <inheritdoc />
public async Task<LocationBatchCreateResultDto> BatchCreateAsync(LocationBatchCreateRequest request)
{
var tenant = _userContext.TenantId.Trim();
var owner = _userContext.OwnerCode.Trim();
var warehouseCode = request.WarehouseCode.Trim();
var areaCode = request.AreaCode.Trim();
var zoneCode = request.ZoneCode.Trim();
var aisleCode = request.AisleCode.Trim();
if (request.ColumnFrom > request.ColumnTo)
{
throw new BusinessException("列起始不能大于列结束。");
}
if (request.LayerFrom > request.LayerTo)
{
throw new BusinessException("层起始不能大于层结束。");
}
var rows = LocationShelfBatchHelper.RowsForShelf(request.ShelfDepthKind);
checked
{
long totalLength = rows.LongLength;
var colSpan = (long)(request.ColumnTo - request.ColumnFrom + 1);
var layerSpan = (long)(request.LayerTo - request.LayerFrom + 1);
var total = totalLength * colSpan * layerSpan;
if (total > LocationShelfBatchHelper.MaxGeneratedLocationsPerRequest)
{
throw new BusinessException(
$"本次生成数量为 {total},超过单次上限 {LocationShelfBatchHelper.MaxGeneratedLocationsPerRequest},请缩小列/层范围或分批生成。");
}
}
if (await _zoneRepository.GetByWarehouseAreaAndZoneCodeAsync(tenant, owner, warehouseCode, areaCode, zoneCode) is null)
{
throw new BusinessException($"分区不存在: {warehouseCode} / {areaCode} / {zoneCode}");
}
var toGenerate = BuildBatchLocations(
request, tenant, owner, warehouseCode, areaCode, zoneCode, aisleCode, rows);
var plannedCodes = new List<string>(toGenerate.Count);
var seenCodes = new HashSet<string>(StringComparer.Ordinal);
foreach (var loc in toGenerate)
{
if (!seenCodes.Add(loc.Code))
{
throw new BusinessException($"生成的库位编码在批次内重复:{loc.Code}。请检查模板是否包含行列层等区分字段。");
}
plannedCodes.Add(loc.Code);
}
var existingInDb =
await _locationRepository.GetExistingCodesAsync(tenant, owner, warehouseCode, areaCode, zoneCode, plannedCodes);
if (request.DuplicatePolicy == LocationBatchDuplicatePolicy.AbortOnDuplicate && existingInDb.Count > 0)
{
var sample = string.Join(", ", existingInDb.OrderBy(static x => x, StringComparer.Ordinal).Take(20));
var more = existingInDb.Count > 20 ? $" 等共 {existingInDb.Count} 条" : string.Empty;
throw new BusinessException($"存在已入库位编码(重复策略:整批中止)。示例:{sample}{more}");
}
List<Location> toInsert =
request.DuplicatePolicy == LocationBatchDuplicatePolicy.SkipExisting ?
toGenerate.Where(loc => !existingInDb.Contains(loc.Code)).ToList() :
toGenerate;
if (toInsert.Count == 0)
{
return new LocationBatchCreateResultDto
{
CreatedCount = 0,
SkippedCodes = existingInDb.OrderBy(static x => x, StringComparer.Ordinal).ToList()
};
}
return await _tx.ExecuteAsync(async () =>
{
await _locationRepository.InsertManyAsync(toInsert);
return new LocationBatchCreateResultDto
{
CreatedCount = toInsert.Count,
SkippedCodes =
request.DuplicatePolicy == LocationBatchDuplicatePolicy.SkipExisting ?
existingInDb.OrderBy(static x => x, StringComparer.Ordinal).ToList() :
new List<string>()
};
});
}
private static List<Location> BuildBatchLocations(
LocationBatchCreateRequest request,
string tenantId,
string ownerCode,
string warehouseCode,
string areaCode,
string zoneCode,
string aisleCode,
int[] rows)
{
var list = new List<Location>();
foreach (var rowNo in rows)
{
for (var column = request.ColumnFrom; column <= request.ColumnTo; column++)
{
for (var layer = request.LayerFrom; layer <= request.LayerTo; layer++)
{
var code = LocationShelfBatchHelper.FormatTemplate(
request.CodeTemplate.Trim(),
warehouseCode,
areaCode,
zoneCode,
aisleCode,
rowNo,
column,
layer);
code = code.Trim();
if (string.IsNullOrEmpty(code))
{
throw new BusinessException("模板生成的储位编码为空。");
}
if (code.Length > LocationShelfBatchHelper.MaxLocationCodeLength)
{
throw new BusinessException(
$"生成的储位编码长度 {code.Length} 超过上限 {LocationShelfBatchHelper.MaxLocationCodeLength}(示例:{code})");
}
string? name = null;
if (!string.IsNullOrWhiteSpace(request.NameTemplate))
{
name = LocationShelfBatchHelper.FormatTemplate(
request.NameTemplate!.Trim(),
warehouseCode,
areaCode,
zoneCode,
aisleCode,
rowNo,
column,
layer).Trim();
if (name.Length > LocationShelfBatchHelper.MaxLocationNameLength)
{
throw new BusinessException(
$"生成的库位名称长度 {name.Length} 超过上限 {LocationShelfBatchHelper.MaxLocationNameLength}(示例:{name})");
}
}
var isOuter = LocationShelfBatchHelper.ResolveIsOuter(request.ShelfDepthKind, rowNo);
list.Add(new Location
{
TenantId = tenantId,
OwnerCode = ownerCode,
WarehouseCode = warehouseCode,
AreaCode = areaCode,
ZoneCode = zoneCode,
AisleCode = aisleCode,
Code = code,
Name = string.IsNullOrEmpty(name) ? null : name,
RowNo = rowNo,
ColumnNo = column,
LayerNo = layer,
Height = request.Height,
LocationStatus = request.LocationStatus,
IsOuter = isOuter,
ContainerCode = null,
Attrs = null
});
}
}
}
return list;
}
private static LocationViewDto MapToView(Location entity)
{
return new LocationViewDto
{
Id = entity.Id,
TenantId = entity.TenantId,
OwnerCode = entity.OwnerCode,
WarehouseCode = entity.WarehouseCode,
AreaCode = entity.AreaCode,
ZoneCode = entity.ZoneCode,
AisleCode = entity.AisleCode,
Code = entity.Code,
Name = entity.Name,
RowNo = entity.RowNo,
ColumnNo = entity.ColumnNo,
LayerNo = entity.LayerNo,
Height = entity.Height,
LocationStatus = entity.LocationStatus,
IsOuter = entity.IsOuter,
ContainerCode = entity.ContainerCode,
Attrs = entity.Attrs
};
}
}
+117
View File
@@ -0,0 +1,117 @@
using System;
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Material;
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 MaterialService : IMaterialService
{
private readonly IMaterialRepository _materialRepository;
private readonly ICurrentUserContext _userContext;
public MaterialService(IMaterialRepository materialRepository, ICurrentUserContext userContext)
{
_materialRepository = materialRepository;
_userContext = userContext;
}
public async Task<PagedResult<MaterialViewDto>> GetPagedListAsync(MaterialPagedQuery query)
{
query.TenantId = _userContext.TenantId.Trim();
query.OwnerCode = _userContext.OwnerCode.Trim();
var page = await _materialRepository.GetPagedListAsync(query);
var items = page.Items.ConvertAll(MapToView);
return new PagedResult<MaterialViewDto>
{
PageIndex = page.PageIndex,
PageSize = page.PageSize,
TotalCount = page.TotalCount,
Items = items
};
}
public async Task<MaterialViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode)
{
var entity = await _materialRepository.GetByIdAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
return entity is null ? null : MapToView(entity);
}
public async Task<MaterialViewDto> CreateAsync(MaterialSaveRequest request)
{
var code = request.Code.Trim();
var name = request.Name.Trim();
var unit = request.Unit.Trim();
if (await _materialRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), code) is not null)
{
throw new BusinessException($"物料编码已存在: {code}");
}
var entity = new Material
{
TenantId = _userContext.TenantId.Trim(),
OwnerCode = _userContext.OwnerCode.Trim(),
Code = code,
Name = name,
Spec = string.IsNullOrWhiteSpace(request.Spec) ? null : request.Spec.Trim(),
Unit = unit,
Attrs = request.Attrs
};
await _materialRepository.InsertAsync(entity);
return MapToView(entity);
}
public async Task<MaterialViewDto?> UpdateAsync(MaterialUpdateRequest request)
{
var entity = await _materialRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (entity is null)
{
return null;
}
var code = request.Code.Trim();
var name = request.Name.Trim();
var unit = request.Unit.Trim();
var existing = await _materialRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), code);
if (existing is not null && existing.Id != entity.Id)
{
throw new BusinessException($"物料编码已被占用: {code}");
}
entity.Code = code;
entity.Name = name;
entity.Spec = string.IsNullOrWhiteSpace(request.Spec) ? null : request.Spec.Trim();
entity.Unit = unit;
entity.Attrs = request.Attrs;
await _materialRepository.UpdateAsync(entity);
return MapToView(entity);
}
public Task<int> DeleteAsync(long id, string tenantId, string ownerCode)
{
return _materialRepository.SoftDeleteAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
}
private static MaterialViewDto MapToView(Material entity)
{
return new MaterialViewDto
{
Id = entity.Id,
TenantId = entity.TenantId,
OwnerCode = entity.OwnerCode,
Code = entity.Code,
Name = entity.Name,
Spec = entity.Spec,
Unit = entity.Unit,
Attrs = entity.Attrs
};
}
}
@@ -0,0 +1,107 @@
using System.Globalization;
using SqlSugar;
using WmsLite.Api.Common;
using WmsLite.Api.Services.Interfaces;
namespace WmsLite.Api.Services;
public class OrderNumberGenerator : IOrderNumberGenerator
{
private readonly ISqlSugarClient _db;
public OrderNumberGenerator(ISqlSugarClient db)
{
_db = db;
}
public async Task<string> NextInboundOrderNoAsync(string tenantId, string ownerCode, CancellationToken cancellationToken = default)
{
var tenant = tenantId.Trim();
var owner = ownerCode.Trim();
var prefix = "IN";
var datePart = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
const int maxAttempts = 5;
for (var attempt = 0; attempt < maxAttempts; attempt++)
{
var seq = await AllocateSequenceAsync(tenant, owner, prefix, datePart);
var no = $"{prefix}{datePart}{seq.ToString("D5", CultureInfo.InvariantCulture)}";
var exists = await _db.Queryable<Models.InboundOrder>()
.Where(x => !x.IsDeleted && x.TenantId == tenant && x.OwnerCode == owner && x.OrderNo == no)
.AnyAsync();
if (!exists)
{
return no;
}
}
throw new BusinessException("生成唯一入库单单号失败,请重试。");
}
private async Task<int> AllocateSequenceAsync(string tenantId, string ownerCode, string prefix, string dateYyyyMmDd)
{
try
{
_db.Ado.BeginTran();
var row = await _db.Ado.SqlQuerySingleAsync<OrderNoCounterRow>(
"""
SELECT id, last_seq AS LastSeq
FROM order_no_counter
WHERE tenant_id = @tenant AND owner_code = @owner AND prefix = @prefix AND date_yyyymmdd = @date
FOR UPDATE
""",
new { tenant = tenantId, owner = ownerCode, prefix, date = dateYyyyMmDd });
int next;
if (row is null)
{
next = 1;
await _db.Ado.ExecuteCommandAsync(
"""
INSERT INTO order_no_counter (id, tenant_id, owner_code, prefix, date_yyyymmdd, last_seq, create_time, update_time)
VALUES (@id, @tenant, @owner, @prefix, @date, @seq, NOW(), NOW())
""",
new
{
id = SnowFlakeSingle.Instance.NextId(),
tenant = tenantId,
owner = ownerCode,
prefix,
date = dateYyyyMmDd,
seq = next,
});
}
else
{
next = row.LastSeq + 1;
if (next > 99999)
{
throw new BusinessException("当日入库单单号序号已超过最大值(99999),请稍后重试或联系管理员。");
}
await _db.Ado.ExecuteCommandAsync(
"""
UPDATE order_no_counter SET last_seq = @seq, update_time = NOW()
WHERE id = @id
""",
new { id = row.Id, seq = next });
}
_db.Ado.CommitTran();
return next;
}
catch
{
_db.Ado.RollbackTran();
throw;
}
}
private sealed class OrderNoCounterRow
{
public long Id { get; set; }
public int LastSeq { get; set; }
}
}
File diff suppressed because it is too large. Load diff
+60
View File
@@ -0,0 +1,60 @@
using WmsLite.Api.Dtos.Dictionary;
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 SysDictService : ISysDictService
{
private readonly ISysDictItemRepository _repository;
private readonly ICurrentUserContext _userContext;
public SysDictService(ISysDictItemRepository repository, ICurrentUserContext userContext)
{
_repository = repository;
_userContext = userContext;
}
public async Task<Dictionary<string, Dictionary<string, string>>> GetMergedMapAsync(SysDictionaryMapRequest request)
{
IReadOnlyList<string>? filter = request.Categories?.Where(static c => !string.IsNullOrWhiteSpace(c))
.Select(static c => c.Trim())
.Distinct(StringComparer.Ordinal)
.ToList();
var rows = await _repository.ListEnabledAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), filter);
var platform = rows.Where(static r =>
string.Equals(r.TenantId, "system", StringComparison.OrdinalIgnoreCase)
&& string.Equals(r.OwnerCode, "system", StringComparison.OrdinalIgnoreCase))
.ToList();
var tenantOwned = rows.Where(r =>
!string.Equals(r.TenantId, "system", StringComparison.OrdinalIgnoreCase)
|| !string.Equals(r.OwnerCode, "system", StringComparison.OrdinalIgnoreCase))
.ToList();
var merged = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
void Apply(IEnumerable<SysDictItem> source)
{
foreach (var row in source)
{
if (!merged.TryGetValue(row.Category, out var inner))
{
inner = new Dictionary<string, string>(StringComparer.Ordinal);
merged[row.Category] = inner;
}
inner[row.Code.Trim()] = row.Label.Trim();
}
}
Apply(platform);
Apply(tenantOwned);
return merged;
}
}
@@ -0,0 +1,96 @@
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Template;
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 SysTemplateService : ISysTemplateService
{
private readonly ISysTemplateRepository _repository;
private readonly ICurrentUserContext _userContext;
public SysTemplateService(ISysTemplateRepository repository, ICurrentUserContext userContext)
{
_repository = repository;
_userContext = userContext;
}
public async Task<PagedResult<SysTemplateViewDto>> GetPagedListAsync(SysTemplatePagedQuery query)
{
query.TenantId = _userContext.TenantId.Trim();
query.OwnerCode = _userContext.OwnerCode.Trim();
var page = await _repository.GetPagedListAsync(query);
return new PagedResult<SysTemplateViewDto>
{
PageIndex = page.PageIndex,
PageSize = page.PageSize,
TotalCount = page.TotalCount,
Items = page.Items.ConvertAll(Map)
};
}
public async Task<SysTemplateViewDto> CreateAsync(SysTemplateSaveRequest request)
{
TemplateConfigJsonValidator.ValidateAndParse(request.ConfigJson);
var bizType = request.BizType.Trim();
if (await _repository.GetByBizTypeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), bizType) is not null)
{
throw new BusinessException($"Template '{bizType}' already exists.");
}
var entity = new SysTemplate
{
TenantId = _userContext.TenantId.Trim(),
OwnerCode = _userContext.OwnerCode.Trim(),
BizType = bizType,
BizName = request.BizName.Trim(),
ConfigJson = request.ConfigJson
};
await _repository.InsertAsync(entity);
return Map(entity);
}
public async Task<SysTemplateViewDto?> UpdateAsync(SysTemplateUpdateRequest request)
{
TemplateConfigJsonValidator.ValidateAndParse(request.ConfigJson);
var entity = await _repository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (entity is null)
{
return null;
}
var bizType = request.BizType.Trim();
var duplicate = await _repository.GetByBizTypeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), bizType);
if (duplicate is not null && duplicate.Id != entity.Id)
{
throw new BusinessException($"Template '{bizType}' already exists.");
}
entity.BizType = bizType;
entity.BizName = request.BizName.Trim();
entity.ConfigJson = request.ConfigJson;
await _repository.UpdateAsync(entity);
return Map(entity);
}
public Task<int> DeleteAsync(long id, string tenantId, string ownerCode)
{
return _repository.SoftDeleteAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
}
private static SysTemplateViewDto Map(SysTemplate entity)
{
return new SysTemplateViewDto
{
Id = entity.Id,
TenantId = entity.TenantId,
OwnerCode = entity.OwnerCode,
BizType = entity.BizType,
BizName = entity.BizName,
ConfigJson = entity.ConfigJson
};
}
}
@@ -0,0 +1,186 @@
using System.Collections.Generic;
using System.Text.Json;
using WmsLite.Api.Common;
using WmsLite.Api.Models;
using WmsLite.Api.Repositories.Interfaces;
using WmsLite.Api.Services.Interfaces;
namespace WmsLite.Api.Services;
public class TemplateFieldValidationService : ITemplateFieldValidationService
{
private readonly ISysTemplateRepository _sysTemplateRepository;
public TemplateFieldValidationService(ISysTemplateRepository sysTemplateRepository)
{
_sysTemplateRepository = sysTemplateRepository;
}
public async Task<SysTemplate?> ValidateAttrsAsync(
string tenantId,
string ownerCode,
string? bizType,
Dictionary<string, object>? attrs)
{
if (attrs is null || attrs.Count == 0)
{
return await _sysTemplateRepository.GetByBizTypeAsync(tenantId, ownerCode, bizType);
}
var template = await RequireTemplateAsync(tenantId, ownerCode, bizType);
var fields = ParseFields(template);
foreach (var key in attrs.Keys)
{
if (!fields.TryGetValue(key, out var field))
{
throw new BusinessException($"Attrs field '{key}' is not defined in template '{bizType}'.");
}
if (!MatchesType(attrs[key], field.Type))
{
throw new BusinessException($"Attrs field '{key}' does not match template type '{field.Type}'.");
}
}
foreach (var field in fields.Values)
{
if (field.Required && (!attrs.TryGetValue(field.Field, out var value) || IsEmpty(value)))
{
throw new BusinessException($"Attrs field '{field.Field}' is required by template '{bizType}'.");
}
}
return template;
}
public async Task<SysTemplate?> ValidateSearchParamAsync(
string tenantId,
string ownerCode,
string? bizType,
Dictionary<string, object>? searchParam)
{
if (searchParam is null || searchParam.Count == 0)
{
return await _sysTemplateRepository.GetByBizTypeAsync(tenantId, ownerCode, bizType);
}
var template = await RequireTemplateAsync(tenantId, ownerCode, bizType);
var fields = ParseFields(template);
foreach (var entry in searchParam)
{
if (!fields.TryGetValue(entry.Key, out var field))
{
throw new BusinessException($"SearchParam field '{entry.Key}' is not defined in template '{bizType}'.");
}
if (!field.AllowQuery)
{
throw new BusinessException($"SearchParam field '{entry.Key}' is not queryable.");
}
if (!MatchesType(entry.Value, field.Type))
{
throw new BusinessException($"SearchParam field '{entry.Key}' does not match template type '{field.Type}'.");
}
}
return template;
}
private async Task<SysTemplate> RequireTemplateAsync(string tenantId, string ownerCode, string? bizType)
{
if (string.IsNullOrWhiteSpace(bizType))
{
throw new BusinessException("BizType is required when attrs or SearchParam is provided.");
}
var template = await _sysTemplateRepository.GetByBizTypeAsync(tenantId, ownerCode, bizType);
if (template is null || string.IsNullOrWhiteSpace(template.ConfigJson))
{
throw new BusinessException($"Template '{bizType}' is not configured.");
}
return template;
}
private static Dictionary<string, TemplateFieldDefinition> ParseFields(SysTemplate template)
{
var fields = new Dictionary<string, TemplateFieldDefinition>(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrWhiteSpace(template.ConfigJson))
{
return fields;
}
var parsed = TemplateConfigJsonValidator.ValidateAndParse(template.ConfigJson);
foreach (var f in parsed)
{
fields[f.Field] = new TemplateFieldDefinition(
f.Field,
f.Type,
f.Required,
f.AllowQuery);
}
return fields;
}
internal static bool MatchesType(object? value, string type)
{
if (value is null)
{
return true;
}
var normalized = type.Trim().ToLowerInvariant();
if (value is JsonElement json)
{
return normalized switch
{
"number" or "decimal" => json.ValueKind == JsonValueKind.Number || IsDecimalString(json),
"int" => json.ValueKind == JsonValueKind.Number
? json.TryGetInt32(out _)
: int.TryParse(json.ToString(), out _),
"bool" => json.ValueKind is JsonValueKind.True or JsonValueKind.False || bool.TryParse(json.ToString(), out _),
"date" or "datetime" => DateTime.TryParse(json.ToString(), out _),
_ => json.ValueKind is JsonValueKind.String or JsonValueKind.Number or JsonValueKind.True or JsonValueKind.False
};
}
return normalized switch
{
"number" or "decimal" => value is byte or short or int or long or float or double or decimal || IsDecimalString(value.ToString()),
"int" => value switch
{
byte or short or int or long => true,
_ => int.TryParse(value.ToString(), out _)
},
"bool" => value is bool || bool.TryParse(value.ToString(), out _),
"date" or "datetime" => value is DateTime || DateTime.TryParse(value.ToString(), out _),
_ => true
};
}
private static bool IsDecimalString(string? s)
{
return !string.IsNullOrWhiteSpace(s) && decimal.TryParse(s, out _);
}
private static bool IsDecimalString(JsonElement json)
{
if (json.ValueKind == JsonValueKind.Number)
{
return true;
}
return json.ValueKind == JsonValueKind.String && decimal.TryParse(json.GetString(), out _);
}
private static bool IsEmpty(object? value)
{
return value is null || string.IsNullOrWhiteSpace(value.ToString());
}
private sealed record TemplateFieldDefinition(string Field, string Type, bool Required, bool AllowQuery);
}
+109
View File
@@ -0,0 +1,109 @@
using System;
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Warehouse;
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 WarehouseService : IWarehouseService
{
private readonly IWarehouseRepository _warehouseRepository;
private readonly ICurrentUserContext _userContext;
public WarehouseService(IWarehouseRepository warehouseRepository, ICurrentUserContext userContext)
{
_warehouseRepository = warehouseRepository;
_userContext = userContext;
}
public async Task<PagedResult<WarehouseViewDto>> GetPagedListAsync(WarehousePagedQuery query)
{
query.TenantId = _userContext.TenantId.Trim();
query.OwnerCode = _userContext.OwnerCode.Trim();
var page = await _warehouseRepository.GetPagedListAsync(query);
var items = page.Items.ConvertAll(MapToView);
return new PagedResult<WarehouseViewDto>
{
PageIndex = page.PageIndex,
PageSize = page.PageSize,
TotalCount = page.TotalCount,
Items = items
};
}
public async Task<WarehouseViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode)
{
var entity = await _warehouseRepository.GetByIdAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
return entity is null ? null : MapToView(entity);
}
public async Task<WarehouseViewDto> CreateAsync(WarehouseSaveRequest request)
{
var code = request.Code.Trim();
var name = request.Name.Trim();
if (await _warehouseRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), code) is not null)
{
throw new BusinessException($"仓库编码已存在: {code}");
}
var entity = new Warehouse
{
TenantId = _userContext.TenantId.Trim(),
OwnerCode = _userContext.OwnerCode.Trim(),
Code = code,
Name = name,
Attrs = request.Attrs
};
await _warehouseRepository.InsertAsync(entity);
return MapToView(entity);
}
public async Task<WarehouseViewDto?> UpdateAsync(WarehouseUpdateRequest request)
{
var entity = await _warehouseRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (entity is null)
{
return null;
}
var code = request.Code.Trim();
var name = request.Name.Trim();
var existing = await _warehouseRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), code);
if (existing is not null && existing.Id != entity.Id)
{
throw new BusinessException($"仓库编码已被占用: {code}");
}
entity.Code = code;
entity.Name = name;
entity.Attrs = request.Attrs;
await _warehouseRepository.UpdateAsync(entity);
return MapToView(entity);
}
public Task<int> DeleteAsync(long id, string tenantId, string ownerCode)
{
return _warehouseRepository.SoftDeleteAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
}
private static WarehouseViewDto MapToView(Warehouse entity)
{
return new WarehouseViewDto
{
Id = entity.Id,
TenantId = entity.TenantId,
OwnerCode = entity.OwnerCode,
Code = entity.Code,
Name = entity.Name,
Attrs = entity.Attrs
};
}
}
+148
View File
@@ -0,0 +1,148 @@
using System.Threading.Tasks;
using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Zone;
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 ZoneService : IZoneService
{
private readonly IZoneRepository _zoneRepository;
private readonly IWarehouseRepository _warehouseRepository;
private readonly IAreaRepository _areaRepository;
private readonly ICurrentUserContext _userContext;
public ZoneService(
IZoneRepository zoneRepository,
IWarehouseRepository warehouseRepository,
IAreaRepository areaRepository,
ICurrentUserContext userContext)
{
_zoneRepository = zoneRepository;
_warehouseRepository = warehouseRepository;
_areaRepository = areaRepository;
_userContext = userContext;
}
public async Task<PagedResult<ZoneViewDto>> GetPagedListAsync(ZonePagedQuery query)
{
query.TenantId = _userContext.TenantId.Trim();
query.OwnerCode = _userContext.OwnerCode.Trim();
var page = await _zoneRepository.GetPagedListAsync(query);
var items = page.Items.ConvertAll(MapToView);
return new PagedResult<ZoneViewDto>
{
PageIndex = page.PageIndex,
PageSize = page.PageSize,
TotalCount = page.TotalCount,
Items = items
};
}
public async Task<ZoneViewDto?> GetByIdAsync(long id, string tenantId, string ownerCode)
{
var entity = await _zoneRepository.GetByIdAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
return entity is null ? null : MapToView(entity);
}
public async Task<ZoneViewDto> CreateAsync(ZoneSaveRequest request)
{
var warehouseCode = request.WarehouseCode.Trim();
var areaCode = request.AreaCode.Trim();
var code = request.Code.Trim();
var name = request.Name.Trim();
if (await _warehouseRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode) is null)
{
throw new BusinessException($"仓库不存在: {warehouseCode}");
}
if (await _areaRepository.GetByWarehouseAndAreaCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, areaCode) is null)
{
throw new BusinessException($"库区不存在: {warehouseCode} / {areaCode}");
}
if (await _zoneRepository.GetByWarehouseAreaAndZoneCodeAsync(
_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, areaCode, code) is not null)
{
throw new BusinessException($"该库区下分区编码已存在: {code}");
}
var entity = new Zone
{
TenantId = _userContext.TenantId.Trim(),
OwnerCode = _userContext.OwnerCode.Trim(),
WarehouseCode = warehouseCode,
AreaCode = areaCode,
Code = code,
Name = name,
Attrs = request.Attrs
};
await _zoneRepository.InsertAsync(entity);
return MapToView(entity);
}
public async Task<ZoneViewDto?> UpdateAsync(ZoneUpdateRequest request)
{
var entity = await _zoneRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
if (entity is null)
{
return null;
}
var warehouseCode = request.WarehouseCode.Trim();
var areaCode = request.AreaCode.Trim();
var code = request.Code.Trim();
var name = request.Name.Trim();
if (await _warehouseRepository.GetByCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode) is null)
{
throw new BusinessException($"仓库不存在: {warehouseCode}");
}
if (await _areaRepository.GetByWarehouseAndAreaCodeAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, areaCode) is null)
{
throw new BusinessException($"库区不存在: {warehouseCode} / {areaCode}");
}
var duplicate = await _zoneRepository.GetByWarehouseAreaAndZoneCodeAsync(
_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), warehouseCode, areaCode, code);
if (duplicate is not null && duplicate.Id != entity.Id)
{
throw new BusinessException($"该库区下分区编码已被占用: {code}");
}
entity.WarehouseCode = warehouseCode;
entity.AreaCode = areaCode;
entity.Code = code;
entity.Name = name;
entity.Attrs = request.Attrs;
await _zoneRepository.UpdateAsync(entity);
return MapToView(entity);
}
public Task<int> DeleteAsync(long id, string tenantId, string ownerCode)
{
return _zoneRepository.SoftDeleteAsync(id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim());
}
private static ZoneViewDto MapToView(Zone entity)
{
return new ZoneViewDto
{
Id = entity.Id,
TenantId = entity.TenantId,
OwnerCode = entity.OwnerCode,
WarehouseCode = entity.WarehouseCode,
AreaCode = entity.AreaCode,
Code = entity.Code,
Name = entity.Name,
Attrs = entity.Attrs
};
}
}