using Admin.NET.Plugin.AiDOP.Dto.S0.Warehouse; using Admin.NET.Plugin.AiDOP.Entity.S0.Warehouse; using Admin.NET.Plugin.AiDOP.Infrastructure; using Microsoft.Extensions.Logging; namespace Admin.NET.Plugin.AiDOP.Controllers.S0.Warehouse; /// /// S0 货架主数据(LocationShelfMaster 语义) /// [ApiController] [Route("api/s0/warehouse/location-shelves")] [AllowAnonymous] [NonUnify] public class AdoS0LocationShelvesController : ControllerBase { private readonly SqlSugarRepository _rep; private readonly SqlSugarRepository _locRep; private readonly AdoS0ReferenceChecker _refChecker; private readonly ILogger _logger; public AdoS0LocationShelvesController( SqlSugarRepository rep, SqlSugarRepository locRep, AdoS0ReferenceChecker refChecker, ILogger logger) { _rep = rep; _locRep = locRep; _refChecker = refChecker; _logger = logger; } [HttpGet] public async Task GetPagedAsync([FromQuery] AdoS0LocationShelfQueryDto q) { (q.Page, q.PageSize) = PagingGuard.Normalize(q.Page, q.PageSize); var query = _rep.AsQueryable() .WhereIF(q.CompanyRefId.HasValue, x => x.CompanyRefId == q.CompanyRefId!.Value) .WhereIF(q.FactoryRefId.HasValue, x => x.FactoryRefId == q.FactoryRefId!.Value) .WhereIF(!string.IsNullOrWhiteSpace(q.DomainCode), x => x.DomainCode == q.DomainCode) .WhereIF(!string.IsNullOrWhiteSpace(q.Location), x => x.Location == q.Location) .WhereIF(!string.IsNullOrWhiteSpace(q.Keyword), x => x.InvShelf.Contains(q.Keyword!) || x.Location.Contains(q.Keyword!)); var total = await query.CountAsync(); var list = await query .OrderBy(x => x.Location) .OrderBy(x => x.InvShelf) .Skip((q.Page - 1) * q.PageSize) .Take(q.PageSize) .ToListAsync(); await ApplyLocationDescrAsync(list); return Ok(new { total, page = q.Page, pageSize = q.PageSize, list }); } [HttpGet("{id:long}")] public async Task GetAsync(long id) { var item = await _rep.GetByIdAsync(id); if (item == null) return NotFound(); await ApplyLocationDescrAsync(new List { item }); return Ok(item); } [HttpPost] public async Task CreateAsync([FromBody] AdoS0LocationShelfUpsertDto dto) { if (await _rep.IsAnyAsync(x => x.FactoryRefId == dto.FactoryRefId && x.Location == dto.Location && x.InvShelf == dto.InvShelf)) return AdoS0ApiErrors.Conflict(AdoS0ErrorCodes.DuplicateCode, "货架编码已存在"); // B2:Create 一律严格作用域校验,禁止降级(参 AdoS0MfgRoutingOpDetailsController)。 var locResult = await _refChecker.LocationExistsInScopeAsync(dto.Location, dto.CompanyRefId, dto.FactoryRefId); switch (locResult) { case MaterialScopeCheck.NotFound: return AdoS0ApiErrors.InvalidReference(AdoS0ErrorCodes.ReferenceNotFound, $"库位编码 '{dto.Location}' 不存在于库位主数据"); case MaterialScopeCheck.ScopeMiss: return AdoS0ApiErrors.InvalidReference(AdoS0ErrorCodes.InvalidReferenceScope, $"库位编码 '{dto.Location}' 不属于当前公司/工厂 (CompanyRefId={dto.CompanyRefId}, FactoryRefId={dto.FactoryRefId})"); } var entity = new AdoS0LocationShelfMaster { CompanyRefId = dto.CompanyRefId, FactoryRefId = dto.FactoryRefId, DomainCode = dto.DomainCode ?? string.Empty, Location = dto.Location, InvShelf = dto.InvShelf, Descr = dto.Descr, Area = dto.Area, CreateUser = dto.CreateUser, CreateTime = DateTime.Now }; await _rep.AsInsertable(entity).ExecuteReturnEntityAsync(); return Ok(entity); } [HttpPut("{id:long}")] public async Task UpdateAsync(long id, [FromBody] AdoS0LocationShelfUpsertDto dto) { var entity = await _rep.GetByIdAsync(id); if (entity == null) return NotFound(); if (await _rep.IsAnyAsync(x => x.Id != id && x.FactoryRefId == dto.FactoryRefId && x.Location == dto.Location && x.InvShelf == dto.InvShelf)) return AdoS0ApiErrors.Conflict(AdoS0ErrorCodes.DuplicateCode, "货架编码已存在"); // B2 + 历史兼容降级(D-03 严格条件,参 AdoS0MfgRoutingOpDetailsController) var locResult = await _refChecker.LocationExistsInScopeAsync(dto.Location, dto.CompanyRefId, dto.FactoryRefId); if (locResult == MaterialScopeCheck.NotFound) return AdoS0ApiErrors.InvalidReference(AdoS0ErrorCodes.ReferenceNotFound, $"库位编码 '{dto.Location}' 不存在于库位主数据"); if (locResult == MaterialScopeCheck.ScopeMiss) { // 降级条件(全部满足才允许): // 1. 是 Update(已满足) // 2. DB 原记录 scope 为 0/0 // 3. 本次未修改 Location 引用值 var originScopeEmpty = entity.CompanyRefId == 0 && entity.FactoryRefId == 0; var locationUnchanged = string.Equals(entity.Location, dto.Location?.Trim(), StringComparison.Ordinal); if (originScopeEmpty && locationUnchanged) { _logger.LogWarning( "[B2 Downgrade] Table={TableName} PrimaryKey={PrimaryKey} ReferenceField={ReferenceField} " + "OldValue={OldValue} NewValue={NewValue} CompanyRefId={CompanyRefId} FactoryRefId={FactoryRefId} " + "DowngradeReason={DowngradeReason}", "LocationShelfMaster", entity.Id, "Location", entity.Location, dto.Location, dto.CompanyRefId, dto.FactoryRefId, "LegacyRecord_OriginScopeZero_LocationUnchanged"); // 放行,继续执行写入 } else { return AdoS0ApiErrors.InvalidReference(AdoS0ErrorCodes.InvalidReferenceScope, $"库位编码 '{dto.Location}' 不属于当前公司/工厂 (CompanyRefId={dto.CompanyRefId}, FactoryRefId={dto.FactoryRefId})"); } } entity.CompanyRefId = dto.CompanyRefId; entity.FactoryRefId = dto.FactoryRefId; entity.DomainCode = dto.DomainCode ?? string.Empty; entity.Location = dto.Location; entity.InvShelf = dto.InvShelf; entity.Descr = dto.Descr; entity.Area = dto.Area; entity.UpdateUser = dto.UpdateUser; entity.UpdateTime = DateTime.Now; await _rep.AsUpdateable(entity).ExecuteCommandAsync(); return Ok(entity); } [HttpDelete("{id:long}")] public async Task DeleteAsync(long id) { var item = await _rep.GetByIdAsync(id); if (item == null) return NotFound(); await _rep.DeleteAsync(item); return Ok(new { message = "删除成功" }); } private async Task ApplyLocationDescrAsync(List shelves) { if (shelves.Count == 0) return; var domainCodes = shelves.Select(s => s.DomainCode).Distinct().ToList(); var locations = await _locRep.AsQueryable() .Where(l => domainCodes.Contains(l.DomainCode)) .ToListAsync(); foreach (var shelf in shelves) { var loc = locations.Find(l => string.Equals(l.DomainCode, shelf.DomainCode, StringComparison.OrdinalIgnoreCase) && string.Equals(l.Location, shelf.Location, StringComparison.OrdinalIgnoreCase)); shelf.LocationDescr = loc?.Descr; shelf.KwhjName = $"{shelf.Location}:{shelf.InvShelf}"; } } }