854 lines
39 KiB
C#
854 lines
39 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Threading.Tasks;
|
||
using HHWMS.Web.Models;
|
||
using HHWMS.Web.Support;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using WalkingTec.Mvvm.Core;
|
||
using WalkingTec.Mvvm.Core.Extensions;
|
||
using WalkingTec.Mvvm.Mvc;
|
||
|
||
namespace HHWMS.Web.Controllers
|
||
{
|
||
public partial class ShipmentHeaderController
|
||
{
|
||
private static readonly string[] FinishedGoodsOutPorts =
|
||
{
|
||
"EnterExit_P1001",
|
||
"EnterExit_P1004",
|
||
"EnterExit_P1007",
|
||
"EnterExit_P1008",
|
||
"EnterExit_P1009",
|
||
"EnterExit_P1010"
|
||
};
|
||
|
||
[ActionDescription("获取ERP发货通知单")]
|
||
public ActionResult GetShipmentDetails()
|
||
{
|
||
return PartialView(Wtm.CreateVM<ShipmentHeaderVM>());
|
||
}
|
||
|
||
[HttpPost]
|
||
[ActionDescription("获取ERP发货通知单")]
|
||
public async Task<IActionResult> GetShipmentDetails(ShipmentHeaderVM vm)
|
||
{
|
||
var dispatchCode = vm?.Entity?.SourceCode?.Trim();
|
||
if (string.IsNullOrWhiteSpace(dispatchCode))
|
||
{
|
||
return FFResult().Alert("请输入ERP发货通知单号");
|
||
}
|
||
|
||
var result = await LoadDispatch(dispatchCode);
|
||
return result.Success
|
||
? FFResult().CloseDialog().RefreshGrid().Alert($"拉取成功,共处理 {result.Data} 条明细")
|
||
: FFResult().Alert($"拉取失败:{result.Msg}");
|
||
}
|
||
|
||
[ActionDescription("分配库存")]
|
||
public ActionResult Allocate(string id)
|
||
{
|
||
if (!int.TryParse(id, out var headerId))
|
||
{
|
||
return FFResult().Alert("出库单参数错误").RefreshGrid();
|
||
}
|
||
|
||
var vm = Wtm.CreateVM<ShipmentHeaderVM>(headerId);
|
||
if (vm.Entity == null || vm.Entity.ID == 0)
|
||
{
|
||
return FFResult().Alert("出库单不存在").RefreshGrid();
|
||
}
|
||
|
||
if (!_unitwork.IsExit<ShipmentDetail>(x => x.HeaderId == headerId && x.DLsID.HasValue))
|
||
{
|
||
return FFResult().Alert("只有ERP发货通知单允许使用分配/下发").RefreshGrid();
|
||
}
|
||
|
||
return PartialView(vm);
|
||
}
|
||
|
||
[HttpGet]
|
||
public ActionResult GetAllocationData(int headerId)
|
||
{
|
||
var header = _unitwork.FindSingle<ShipmentHeader>(x => x.ID == headerId);
|
||
if (header == null)
|
||
{
|
||
return JsonMore(null, 500, "出库单不存在");
|
||
}
|
||
|
||
if (!_unitwork.IsExit<ShipmentDetail>(x => x.HeaderId == headerId && x.DLsID.HasValue))
|
||
{
|
||
return JsonMore(null, 500, "只有ERP发货通知单允许使用分配/下发");
|
||
}
|
||
|
||
// 明细的图号/物料名称可能因 ERP 未返回或历史数据为空,展示时用物料表兜底(不修改库内数据)
|
||
var detailList = _unitwork.Find<ShipmentDetail>(x => x.HeaderId == headerId && x.DLsID.HasValue)
|
||
.OrderBy(x => x.ID)
|
||
.ToList();
|
||
var detailMaterialCodes = detailList
|
||
.Where(x => !string.IsNullOrWhiteSpace(x.MaterialCode))
|
||
.Select(x => x.MaterialCode)
|
||
.Distinct()
|
||
.ToList();
|
||
var detailMaterials = detailMaterialCodes.Count > 0
|
||
? _unitwork.Find<Material>(x => detailMaterialCodes.Contains(x.MaterialCode))
|
||
.ToDictionary(x => x.MaterialCode)
|
||
: new Dictionary<string, Material>();
|
||
|
||
// 图号/物料名称统一从物料表取(物料表取不到时再退回明细自带的值)
|
||
var details = detailList.Select(x =>
|
||
{
|
||
detailMaterials.TryGetValue(x.MaterialCode ?? "", out var material);
|
||
return new
|
||
{
|
||
x.ID,
|
||
x.DLsID,
|
||
x.MaterialCode,
|
||
MaterialName = material?.MaterialName ?? x.MaterialName,
|
||
MaterialType = material?.MaterialType ?? x.MaterialType,
|
||
Qty = x.Qty ?? 0,
|
||
CompletedQty = x.CompletedQty ?? 0,
|
||
DividedQty = x.DividedQty ?? 0,
|
||
RemainingQty = (x.Qty ?? 0) - (x.CompletedQty ?? 0) - (x.DividedQty ?? 0),
|
||
Status = x.Status.ToString()
|
||
};
|
||
})
|
||
.ToList();
|
||
|
||
var detailIds = details.Select(x => x.ID).ToList();
|
||
var relatedTaskIds = _unitwork.Find<TaskDetail>(x =>
|
||
x.OrderDetailId.HasValue
|
||
&& detailIds.Contains(x.OrderDetailId.Value)
|
||
&& x.Status != TaskStatusEnum.完成)
|
||
.Select(x => x.HeaderId)
|
||
.Distinct()
|
||
.ToList();
|
||
|
||
var taskHeaders = _unitwork.Find<TaskHeader>(x => relatedTaskIds.Contains(x.ID))
|
||
.OrderBy(x => x.ID)
|
||
.ToList();
|
||
var allTaskDetails = _unitwork.Find<TaskDetail>(x =>
|
||
relatedTaskIds.Contains(x.HeaderId)
|
||
&& x.Status != TaskStatusEnum.完成)
|
||
.OrderBy(x => x.ID)
|
||
.ToList();
|
||
var allShipmentDetailIds = allTaskDetails
|
||
.Where(x => x.OrderDetailId.HasValue)
|
||
.Select(x => x.OrderDetailId.Value)
|
||
.Distinct()
|
||
.ToList();
|
||
var shipmentDetails = _unitwork.Find<ShipmentDetail>(x => allShipmentDetailIds.Contains(x.ID))
|
||
.ToDictionary(x => x.ID);
|
||
var shipmentHeaderIds = shipmentDetails.Values.Select(x => x.HeaderId).Distinct().ToList();
|
||
var shipmentHeaders = _unitwork.Find<ShipmentHeader>(x => shipmentHeaderIds.Contains(x.ID))
|
||
.ToDictionary(x => x.ID);
|
||
|
||
// 托盘任务 → 库位:按任务明细里的库存ID取库存所在库位(同一托盘的库存库位一致),取不到时退回任务起点库位
|
||
var taskInventoryIds = allTaskDetails
|
||
.Where(x => x.InventoryId.HasValue)
|
||
.Select(x => x.InventoryId.Value)
|
||
.Distinct()
|
||
.ToList();
|
||
var inventoryLocations = taskInventoryIds.Count > 0
|
||
? _unitwork.Find<Inventory>(x => taskInventoryIds.Contains(x.ID))
|
||
.ToDictionary(x => x.ID, x => x.LocationCode)
|
||
: new Dictionary<int, string>();
|
||
var taskLocations = new Dictionary<int, string>();
|
||
foreach (var task in taskHeaders)
|
||
{
|
||
var locationCode = allTaskDetails
|
||
.Where(x => x.HeaderId == task.ID && x.InventoryId.HasValue)
|
||
.Select(x => inventoryLocations.TryGetValue(x.InventoryId.Value, out var loc) ? loc : null)
|
||
.FirstOrDefault(l => !string.IsNullOrWhiteSpace(l));
|
||
taskLocations[task.ID] = string.IsNullOrWhiteSpace(locationCode) ? task.FromLocation : locationCode;
|
||
}
|
||
|
||
var tasks = taskHeaders.Select(task => new
|
||
{
|
||
task.ID,
|
||
task.TaskNo,
|
||
task.ContainerCode,
|
||
LocationCode = taskLocations[task.ID],
|
||
task.FromLocation,
|
||
task.ToLocation,
|
||
Status = task.Status.ToString(),
|
||
CanDispatch = task.Status == TaskStatusEnum.待下发,
|
||
CanCancel = task.Status == TaskStatusEnum.待下发,
|
||
Details = allTaskDetails.Where(x => x.HeaderId == task.ID).Select(x =>
|
||
{
|
||
shipmentDetails.TryGetValue(x.OrderDetailId ?? 0, out var shipmentDetail);
|
||
ShipmentHeader shipmentHeader = null;
|
||
if (shipmentDetail != null)
|
||
{
|
||
shipmentHeaders.TryGetValue(shipmentDetail.HeaderId, out shipmentHeader);
|
||
}
|
||
|
||
return new
|
||
{
|
||
x.ID,
|
||
x.InventoryId,
|
||
x.MaterialCode,
|
||
x.ContainerCode,
|
||
Qty = x.Qty ?? 0,
|
||
ShipmentCode = shipmentHeader?.SourceCode ?? shipmentHeader?.Code,
|
||
ShipmentDetailId = shipmentDetail?.ID,
|
||
Status = x.Status.ToString(),
|
||
CanCancel = task.Status == TaskStatusEnum.待下发
|
||
};
|
||
}).ToList()
|
||
}).ToList();
|
||
|
||
return JsonMore(new
|
||
{
|
||
Header = new
|
||
{
|
||
header.ID,
|
||
header.Code,
|
||
header.SourceCode,
|
||
Status = header.FirstStatus.ToString()
|
||
},
|
||
Details = details,
|
||
Tasks = tasks,
|
||
OutPorts = FinishedGoodsOutPorts.Select((x, index) => new
|
||
{
|
||
Label = $"拣货口{index + 1}",
|
||
Value = x
|
||
})
|
||
});
|
||
}
|
||
|
||
[HttpGet]
|
||
public ActionResult GetAvailableInventories(int detailId)
|
||
{
|
||
var detail = _unitwork.FindSingle<ShipmentDetail>(x => x.ID == detailId);
|
||
if (detail == null || !detail.DLsID.HasValue)
|
||
{
|
||
return JsonMore(null, 500, "ERP出库明细不存在");
|
||
}
|
||
|
||
var inventories = _unitwork.Find<Inventory>(x =>
|
||
x.ZoneId == 1028
|
||
&& x.MaterialCode == detail.MaterialCode
|
||
&& x.Qty > 0
|
||
&& !string.IsNullOrEmpty(x.LocationCode))
|
||
.OrderBy(x => x.ExpirationDate)
|
||
.ThenBy(x => x.ID)
|
||
.ToList();
|
||
var inventoryIds = inventories.Select(x => x.ID).ToList();
|
||
var containerCodes = inventories.Select(x => x.ContainerCode).Distinct().ToList();
|
||
var allocations = _unitwork.Find<TaskDetail>(x =>
|
||
x.InventoryId.HasValue
|
||
&& inventoryIds.Contains(x.InventoryId.Value)
|
||
&& x.Status != TaskStatusEnum.完成)
|
||
.ToList()
|
||
.GroupBy(x => x.InventoryId.Value)
|
||
.ToDictionary(x => x.Key, x => x.Sum(y => y.Qty ?? 0));
|
||
var activeTasks = _unitwork.Find<TaskHeader>(x => containerCodes.Contains(x.ContainerCode))
|
||
.ToList();
|
||
var activeTaskIds = activeTasks.Select(x => x.ID).ToList();
|
||
var activeTaskDetails = _unitwork.Find<TaskDetail>(x =>
|
||
activeTaskIds.Contains(x.HeaderId) && x.OrderDetailId.HasValue)
|
||
.ToList();
|
||
var activeOrderDetailIds = activeTaskDetails.Select(x => x.OrderDetailId.Value)
|
||
.Distinct()
|
||
.ToList();
|
||
var erpShipmentDetailIds = _unitwork.Find<ShipmentDetail>(x =>
|
||
activeOrderDetailIds.Contains(x.ID) && x.DLsID.HasValue)
|
||
.Select(x => x.ID)
|
||
.ToHashSet();
|
||
var shipmentTaskIds = activeTaskDetails
|
||
.Where(x => erpShipmentDetailIds.Contains(x.OrderDetailId.Value))
|
||
.Select(x => x.HeaderId)
|
||
.Distinct()
|
||
.ToHashSet();
|
||
var containers = _unitwork.Find<Container>(x => containerCodes.Contains(x.Code))
|
||
.ToDictionary(x => x.Code);
|
||
var locationCodes = inventories.Select(x => x.LocationCode).Distinct().ToList();
|
||
var locations = _unitwork.Find<Location>(x => locationCodes.Contains(x.Code))
|
||
.ToDictionary(x => x.Code);
|
||
// 公司名称从本地客商表(Customer)取,取不到则回退显示公司编码
|
||
var companyCodes = inventories.Select(x => x.CompanyCode)
|
||
.Where(x => !string.IsNullOrWhiteSpace(x))
|
||
.Distinct()
|
||
.ToList();
|
||
var customers = _unitwork.Find<Customer>(x => companyCodes.Contains(x.Code))
|
||
.ToDictionary(x => x.Code, x => x.Name);
|
||
|
||
var result = inventories.Select(inventory =>
|
||
{
|
||
allocations.TryGetValue(inventory.ID, out var allocatedQty);
|
||
var task = activeTasks.FirstOrDefault(x => x.ContainerCode == inventory.ContainerCode);
|
||
containers.TryGetValue(inventory.ContainerCode, out var container);
|
||
locations.TryGetValue(inventory.LocationCode, out var location);
|
||
customers.TryGetValue(inventory.CompanyCode ?? "", out var companyName);
|
||
var isPendingShipmentTask = task != null
|
||
&& task.Status == TaskStatusEnum.待下发
|
||
&& shipmentTaskIds.Contains(task.ID);
|
||
var isFree = task == null
|
||
&& inventory.TaskStatus == InventoryTaskStatusEnum.Idle
|
||
&& container?.IsLock != ContainerLockEnum.任务锁
|
||
&& location?.Status != LocationStatusEnum.锁定;
|
||
var availableQty = (inventory.Qty ?? 0) - allocatedQty;
|
||
return new
|
||
{
|
||
inventory.ID,
|
||
inventory.ContainerCode,
|
||
inventory.LocationCode,
|
||
inventory.CompanyCode,
|
||
CompanyName = string.IsNullOrWhiteSpace(companyName) ? inventory.CompanyCode : companyName,
|
||
inventory.MaterialCode,
|
||
inventory.MaterialName,
|
||
inventory.MaterialType,
|
||
inventory.Batch,
|
||
inventory.Lot,
|
||
Qty = inventory.Qty ?? 0,
|
||
AllocatedQty = allocatedQty,
|
||
AvailableQty = availableQty,
|
||
CanSelect = availableQty > 0 && (isFree || isPendingShipmentTask)
|
||
};
|
||
})
|
||
.Where(x => x.CanSelect)
|
||
.ToList();
|
||
|
||
return JsonMore(result);
|
||
}
|
||
|
||
[HttpPost]
|
||
public async Task<ActionResult> AllocateInventories([FromBody] ShipmentAllocationRequest request)
|
||
{
|
||
if (request?.Rows == null || request.Rows.Count == 0)
|
||
{
|
||
return JsonMore(null, 500, "请选择库存并填写分配数量");
|
||
}
|
||
|
||
if (request.Rows.Any(x => x.Qty <= 0)
|
||
|| request.Rows.GroupBy(x => x.InventoryId).Any(x => x.Count() > 1))
|
||
{
|
||
return JsonMore(null, 500, "分配数量必须大于0,且库存不能重复提交");
|
||
}
|
||
|
||
using (var transaction = DC.BeginTransaction())
|
||
{
|
||
try
|
||
{
|
||
// 锁定当前明细,避免两名操作员同时分配时都按旧的剩余数量通过校验。
|
||
var detail = DC.Set<ShipmentDetail>()
|
||
.FromSqlRaw("SELECT * FROM `ShipmentDetail` WHERE `ID` = {0} FOR UPDATE", request.DetailId)
|
||
.AsNoTracking()
|
||
.SingleOrDefault();
|
||
if (detail == null)
|
||
{
|
||
return JsonMore(null, 500, "出库明细不存在");
|
||
}
|
||
|
||
if (!detail.DLsID.HasValue)
|
||
{
|
||
return JsonMore(null, 500, "只有ERP发货明细允许分配库存");
|
||
}
|
||
|
||
var header = _unitwork.FindSingle<ShipmentHeader>(x => x.ID == detail.HeaderId);
|
||
var inventoryIds = request.Rows.Select(x => x.InventoryId).Distinct().ToList();
|
||
// 按固定顺序锁定所选库存,兼容多实例部署并降低交叉分配时的死锁概率。
|
||
var inventories = new List<Inventory>();
|
||
foreach (var inventoryId in inventoryIds.OrderBy(x => x))
|
||
{
|
||
var inventory = DC.Set<Inventory>()
|
||
.FromSqlRaw("SELECT * FROM `Inventory` WHERE `ID` = {0} FOR UPDATE", inventoryId)
|
||
.AsNoTracking()
|
||
.SingleOrDefault();
|
||
if (inventory != null)
|
||
{
|
||
inventories.Add(inventory);
|
||
}
|
||
}
|
||
if (inventories.Count != inventoryIds.Count)
|
||
{
|
||
return JsonMore(null, 500, "部分库存已不存在,请刷新后重试");
|
||
}
|
||
|
||
if (inventories.Any(x => x.MaterialCode != detail.MaterialCode))
|
||
{
|
||
return JsonMore(null, 500, "所选库存物料与出库明细不一致");
|
||
}
|
||
|
||
if (inventories.Any(x => x.ZoneId != 1028))
|
||
{
|
||
return JsonMore(null, 500, "只能选择成品库库存");
|
||
}
|
||
|
||
detail.DividedQty = _unitwork.Find<TaskDetail>(x =>
|
||
x.OrderDetailId == detail.ID
|
||
&& x.Status != TaskStatusEnum.完成)
|
||
.Sum(x => x.Qty) ?? 0;
|
||
var detailRemaining = (detail.Qty ?? 0) - (detail.CompletedQty ?? 0) - (detail.DividedQty ?? 0);
|
||
if (request.Rows.Sum(x => x.Qty) > detailRemaining)
|
||
{
|
||
return JsonMore(null, 500, $"本次分配数量超过明细剩余可分配数量 {detailRemaining}");
|
||
}
|
||
|
||
var activeAllocations = _unitwork.Find<TaskDetail>(x =>
|
||
x.InventoryId.HasValue
|
||
&& inventoryIds.Contains(x.InventoryId.Value)
|
||
&& x.Status != TaskStatusEnum.完成)
|
||
.AsNoTracking()
|
||
.ToList()
|
||
.GroupBy(x => x.InventoryId.Value)
|
||
.ToDictionary(x => x.Key, x => x.Sum(y => y.Qty ?? 0));
|
||
foreach (var row in request.Rows)
|
||
{
|
||
var inventory = inventories.First(x => x.ID == row.InventoryId);
|
||
activeAllocations.TryGetValue(inventory.ID, out var allocatedQty);
|
||
if (allocatedQty + row.Qty > (inventory.Qty ?? 0))
|
||
{
|
||
return JsonMore(null, 500,
|
||
$"库存 {inventory.ID} 的累计分配数量不能超过当前库存 {(inventory.Qty ?? 0)}");
|
||
}
|
||
}
|
||
|
||
var now = DateTime.Now;
|
||
var operatorCode = Wtm.LoginUserInfo?.ITCode ?? "WMS";
|
||
foreach (var containerGroup in inventories.GroupBy(x => x.ContainerCode))
|
||
{
|
||
var containerCode = containerGroup.Key;
|
||
// 锁定托盘的活动任务范围,保证同一托盘只会生成一个待下发任务。
|
||
var activeTasks = DC.Set<TaskHeader>()
|
||
.FromSqlRaw("SELECT * FROM `TaskHeader` WHERE `ContainerCode` = {0} FOR UPDATE", containerCode)
|
||
.AsNoTracking()
|
||
.ToList();
|
||
if (activeTasks.Count > 1)
|
||
{
|
||
return JsonMore(null, 500, $"托盘 {containerCode} 存在多个活动任务,请先排查");
|
||
}
|
||
|
||
var task = activeTasks.SingleOrDefault();
|
||
if (task != null)
|
||
{
|
||
var taskOrderDetailIds = _unitwork.Find<TaskDetail>(x =>
|
||
x.HeaderId == task.ID && x.OrderDetailId.HasValue)
|
||
.Select(x => x.OrderDetailId.Value)
|
||
.Distinct()
|
||
.ToList();
|
||
var isPendingShipmentTask = task.Status == TaskStatusEnum.待下发
|
||
&& _unitwork.IsExit<ShipmentDetail>(x =>
|
||
taskOrderDetailIds.Contains(x.ID) && x.DLsID.HasValue);
|
||
if (!isPendingShipmentTask)
|
||
{
|
||
return JsonMore(null, 500, $"托盘 {containerCode} 已有任务,不能重复分配");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
var firstInventory = containerGroup.First();
|
||
var container = _unitwork.FindSingle<Container>(x => x.Code == containerCode);
|
||
var location = _unitwork.FindSingle<Location>(x => x.Code == firstInventory.LocationCode);
|
||
if (container == null || location == null)
|
||
{
|
||
return JsonMore(null, 500, $"托盘 {containerCode} 的容器或库位数据不存在");
|
||
}
|
||
|
||
if (container.IsLock == ContainerLockEnum.任务锁
|
||
|| location.Status == LocationStatusEnum.锁定)
|
||
{
|
||
return JsonMore(null, 500, $"托盘 {containerCode} 已被其他任务锁定");
|
||
}
|
||
|
||
task = new TaskHeader
|
||
{
|
||
TaskNo = _unitwork.GetSerialNumber("Out", 6),
|
||
ZoneId = firstInventory.ZoneId,
|
||
TaskType = TaskTypeEnum.出库,
|
||
FromLocation = firstInventory.LocationCode,
|
||
ToLocation = "",
|
||
ContainerCode = containerCode,
|
||
RoadWay = 2,
|
||
Status = TaskStatusEnum.待下发,
|
||
CreateBy = operatorCode,
|
||
CreateTime = now
|
||
};
|
||
_unitwork.Add(task);
|
||
|
||
container.IsLock = ContainerLockEnum.任务锁;
|
||
container.UpdateBy = operatorCode;
|
||
container.UpdateTime = now;
|
||
_unitwork.Update(container);
|
||
|
||
location.Status = LocationStatusEnum.锁定;
|
||
location.UpdateBy = operatorCode;
|
||
location.UpdateTime = now;
|
||
_unitwork.Update(location);
|
||
}
|
||
|
||
var allPalletInventories = _unitwork.Find<Inventory>(x => x.ContainerCode == containerCode).ToList();
|
||
foreach (var palletInventory in allPalletInventories)
|
||
{
|
||
palletInventory.TaskStatus = InventoryTaskStatusEnum.Locked;
|
||
palletInventory.UpdateBy = operatorCode;
|
||
palletInventory.UpdateTime = now;
|
||
}
|
||
_unitwork.BatchUpdate(allPalletInventories);
|
||
|
||
foreach (var inventory in containerGroup)
|
||
{
|
||
var row = request.Rows.First(x => x.InventoryId == inventory.ID);
|
||
var taskDetail = _unitwork.FindSingle<TaskDetail>(x =>
|
||
x.HeaderId == task.ID
|
||
&& x.OrderDetailId == detail.ID
|
||
&& x.InventoryId == inventory.ID
|
||
&& x.Status == TaskStatusEnum.待下发);
|
||
if (taskDetail == null)
|
||
{
|
||
taskDetail = new TaskDetail
|
||
{
|
||
HeaderId = task.ID,
|
||
OrderCode = header.Code,
|
||
OrderDetailId = detail.ID,
|
||
MaterialCode = inventory.MaterialCode,
|
||
MaterialName = inventory.MaterialName,
|
||
MaterialSpec = inventory.MaterialSpec,
|
||
MaterialUnit = inventory.MaterialUnit,
|
||
Batch = inventory.Batch,
|
||
Lot = inventory.Lot,
|
||
ContainerCode = inventory.ContainerCode,
|
||
Qty = row.Qty,
|
||
InventoryId = inventory.ID,
|
||
FromLocation = task.FromLocation,
|
||
ToLocation = task.ToLocation,
|
||
Status = TaskStatusEnum.待下发,
|
||
CreateBy = operatorCode,
|
||
CreateTime = now
|
||
};
|
||
_unitwork.Add(taskDetail);
|
||
}
|
||
else
|
||
{
|
||
taskDetail.Qty = (taskDetail.Qty ?? 0) + row.Qty;
|
||
taskDetail.UpdateBy = operatorCode;
|
||
taskDetail.UpdateTime = now;
|
||
_unitwork.Update(taskDetail);
|
||
}
|
||
}
|
||
}
|
||
|
||
RecalculateShipmentDetail(detail);
|
||
RecalculateShipmentHeader(header);
|
||
await transaction.CommitAsync();
|
||
return JsonMore(null);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
await transaction.RollbackAsync();
|
||
return JsonMore(null, 500, ex.InnerException?.Message ?? ex.Message);
|
||
}
|
||
}
|
||
}
|
||
|
||
[HttpPost]
|
||
public async Task<ActionResult> CancelAllocation(int id)
|
||
{
|
||
using (var transaction = DC.BeginTransaction())
|
||
{
|
||
try
|
||
{
|
||
var snapshot = _unitwork.FindSingle<TaskDetail>(x => x.ID == id);
|
||
if (snapshot == null)
|
||
{
|
||
return JsonMore(null, 500, "分配记录不存在");
|
||
}
|
||
|
||
// 与任务下发使用相同的任务行锁,避免取消和下发同时通过状态校验。
|
||
var task = DC.Set<TaskHeader>()
|
||
.FromSqlRaw("SELECT * FROM `TaskHeader` WHERE `ID` = {0} FOR UPDATE", snapshot.HeaderId)
|
||
.AsNoTracking()
|
||
.SingleOrDefault();
|
||
var taskDetail = DC.Set<TaskDetail>()
|
||
.FromSqlRaw("SELECT * FROM `TaskDetail` WHERE `ID` = {0} FOR UPDATE", id)
|
||
.AsNoTracking()
|
||
.SingleOrDefault();
|
||
if (task == null || taskDetail == null || taskDetail.HeaderId != task.ID
|
||
|| task.Status != TaskStatusEnum.待下发
|
||
|| taskDetail.Status != TaskStatusEnum.待下发)
|
||
{
|
||
return JsonMore(null, 500, "只有尚未下发WCS的分配允许取消");
|
||
}
|
||
|
||
var shipmentDetailId = taskDetail.OrderDetailId;
|
||
_unitwork.Delete(taskDetail);
|
||
if (!_unitwork.IsExit<TaskDetail>(x => x.HeaderId == task.ID))
|
||
{
|
||
ReleasePendingPallet(task);
|
||
_unitwork.Delete(task);
|
||
}
|
||
|
||
if (shipmentDetailId.HasValue)
|
||
{
|
||
var shipmentDetail = _unitwork.FindSingle<ShipmentDetail>(x => x.ID == shipmentDetailId.Value);
|
||
if (shipmentDetail != null)
|
||
{
|
||
RecalculateShipmentDetail(shipmentDetail);
|
||
RecalculateShipmentHeader(shipmentDetail.HeaderId);
|
||
}
|
||
}
|
||
|
||
await transaction.CommitAsync();
|
||
Wtm.DoLog("取消成品出库分配", ActionLogTypesEnum.Normal, "CancelAllocation",
|
||
request: id.ToString(), result: "取消成功");
|
||
return JsonMore(null);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
await transaction.RollbackAsync();
|
||
return JsonMore(null, 500, ex.InnerException?.Message ?? ex.Message);
|
||
}
|
||
}
|
||
}
|
||
|
||
[HttpPost]
|
||
public async Task<ActionResult> CancelPendingTask(int id)
|
||
{
|
||
using (var transaction = DC.BeginTransaction())
|
||
{
|
||
try
|
||
{
|
||
var task = DC.Set<TaskHeader>()
|
||
.FromSqlRaw("SELECT * FROM `TaskHeader` WHERE `ID` = {0} FOR UPDATE", id)
|
||
.AsNoTracking()
|
||
.SingleOrDefault();
|
||
if (task == null || task.Status != TaskStatusEnum.待下发)
|
||
{
|
||
return JsonMore(null, 500, "只有尚未下发WCS的托盘任务允许取消");
|
||
}
|
||
|
||
var taskDetails = _unitwork.Find<TaskDetail>(x => x.HeaderId == task.ID).ToList();
|
||
var shipmentDetailIds = taskDetails.Where(x => x.OrderDetailId.HasValue)
|
||
.Select(x => x.OrderDetailId.Value)
|
||
.Distinct()
|
||
.ToList();
|
||
_unitwork.BatchDelete(taskDetails);
|
||
ReleasePendingPallet(task);
|
||
_unitwork.Delete(task);
|
||
|
||
foreach (var shipmentDetailId in shipmentDetailIds)
|
||
{
|
||
RecalculateShipmentDetail(shipmentDetailId);
|
||
}
|
||
var shipmentHeaderIds = _unitwork.Find<ShipmentDetail>(x => shipmentDetailIds.Contains(x.ID))
|
||
.Select(x => x.HeaderId)
|
||
.Distinct()
|
||
.ToList();
|
||
foreach (var shipmentHeaderId in shipmentHeaderIds)
|
||
{
|
||
RecalculateShipmentHeader(shipmentHeaderId);
|
||
}
|
||
|
||
await transaction.CommitAsync();
|
||
Wtm.DoLog("取消成品出库托盘任务", ActionLogTypesEnum.Normal, "CancelPendingTask",
|
||
request: id.ToString(), result: "取消成功");
|
||
return JsonMore(null);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
await transaction.RollbackAsync();
|
||
return JsonMore(null, 500, ex.InnerException?.Message ?? ex.Message);
|
||
}
|
||
}
|
||
}
|
||
|
||
[HttpPost]
|
||
public ActionResult DispatchPendingTask(int id, string outPort)
|
||
{
|
||
if (!FinishedGoodsOutPorts.Contains(outPort))
|
||
{
|
||
return JsonMore(null, 500, "请选择有效的成品库出库口");
|
||
}
|
||
|
||
using (var transaction = DC.BeginTransaction())
|
||
{
|
||
try
|
||
{
|
||
// 持有任务行锁直到WCS响应,避免重复点击向WCS下发两次同一任务。
|
||
var task = DC.Set<TaskHeader>()
|
||
.FromSqlRaw("SELECT * FROM `TaskHeader` WHERE `ID` = {0} FOR UPDATE", id)
|
||
.AsNoTracking()
|
||
.SingleOrDefault();
|
||
if (task == null || task.Status != TaskStatusEnum.待下发)
|
||
{
|
||
return JsonMore(null, 500, "任务不存在或已下发,请刷新后重试");
|
||
}
|
||
|
||
var taskDetails = _unitwork.Find<TaskDetail>(x => x.HeaderId == task.ID).ToList();
|
||
if (!taskDetails.Any())
|
||
{
|
||
return JsonMore(null, 500, "任务没有分配明细,不能下发");
|
||
}
|
||
|
||
task.ToLocation = outPort;
|
||
task.ErrorMsg = null;
|
||
var locationVm = Wtm.CreateVM<LocationVM>();
|
||
var result = locationVm.SendWcsTask(task);
|
||
if (!result.Status)
|
||
{
|
||
task.Status = TaskStatusEnum.待下发;
|
||
// 记录最后一次下发失败原因,列表中可直接看出"从未下发成功"的任务
|
||
task.ErrorMsg = string.IsNullOrWhiteSpace(result.Message)
|
||
? "WCS任务下发失败"
|
||
: result.Message;
|
||
_unitwork.Update(task);
|
||
transaction.Commit();
|
||
return JsonMore(null, 500, result.Message ?? "WCS任务下发失败");
|
||
}
|
||
|
||
foreach (var taskDetail in taskDetails)
|
||
{
|
||
taskDetail.ToLocation = outPort;
|
||
taskDetail.Status = TaskStatusEnum.已下发;
|
||
taskDetail.UpdateBy = Wtm.LoginUserInfo?.ITCode ?? "WMS";
|
||
taskDetail.UpdateTime = DateTime.Now;
|
||
}
|
||
_unitwork.BatchUpdate(taskDetails);
|
||
transaction.Commit();
|
||
return JsonMore(null);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
transaction.Rollback();
|
||
return JsonMore(null, 500, ex.InnerException?.Message ?? ex.Message);
|
||
}
|
||
}
|
||
}
|
||
|
||
private async Task<ApiJsonResult<int>> LoadDispatch(string dispatchCode)
|
||
{
|
||
try
|
||
{
|
||
var items = new List<DispatchItem>();
|
||
const int pageSize = 100;
|
||
var page = 1;
|
||
var total = 0;
|
||
var fetchedCount = 0;
|
||
do
|
||
{
|
||
var request = new LoadDispatchRequest
|
||
{
|
||
ErpCode = "003",
|
||
BReturnFlag = 0,
|
||
DLCode = dispatchCode,
|
||
Size = pageSize,
|
||
Page = page
|
||
};
|
||
var apiResult = await Wtm.CallAPI<LoadDispatchResponse>("ERP", "LoadDispatch",
|
||
HttpMethodEnum.POST, request);
|
||
if (apiResult?.Data == null || apiResult.Data.Code != 0)
|
||
{
|
||
return new ApiJsonResult<int>
|
||
{
|
||
Success = false,
|
||
Msg = apiResult?.Data?.Msg ?? apiResult?.ErrorMsg ?? "ERP未返回有效数据"
|
||
};
|
||
}
|
||
|
||
total = apiResult.Data.Count;
|
||
if (apiResult.Data.Data != null)
|
||
{
|
||
fetchedCount += apiResult.Data.Data.Count;
|
||
items.AddRange(apiResult.Data.Data.Where(x => x == null || !x.BReturnFlag));
|
||
}
|
||
page++;
|
||
} while (fetchedCount < total && page <= 100);
|
||
|
||
if (!items.Any())
|
||
{
|
||
return new ApiJsonResult<int> { Success = false, Msg = "未查询到发货通知单" };
|
||
}
|
||
|
||
if (fetchedCount < total)
|
||
return new ApiJsonResult<int> { Success = false, Msg = "ERP分页数据未获取完整,请稍后重试" };
|
||
if (items.Any(x => x == null || x.DLCode != dispatchCode))
|
||
return new ApiJsonResult<int> { Success = false, Msg = "ERP返回的通知单号与请求不一致" };
|
||
var count = await _dispatchImport.ImportAsync(items, Wtm.LoginUserInfo?.ITCode ?? "WMS");
|
||
return new ApiJsonResult<int> { Success = true, Status = true, Data = count };
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Wtm.DoLog("获取ERP发货通知单失败", ActionLogTypesEnum.Normal, "LoadDispatch",
|
||
request: dispatchCode, result: ex.Message);
|
||
return new ApiJsonResult<int> { Success = false, Msg = ex.InnerException?.Message ?? ex.Message };
|
||
}
|
||
}
|
||
|
||
private void ReleasePendingPallet(TaskHeader task)
|
||
{
|
||
var operatorCode = Wtm.LoginUserInfo?.ITCode ?? "WMS";
|
||
var now = DateTime.Now;
|
||
var inventories = _unitwork.Find<Inventory>(x => x.ContainerCode == task.ContainerCode).ToList();
|
||
foreach (var inventory in inventories)
|
||
{
|
||
inventory.TaskStatus = InventoryTaskStatusEnum.Idle;
|
||
inventory.UpdateBy = operatorCode;
|
||
inventory.UpdateTime = now;
|
||
}
|
||
_unitwork.BatchUpdate(inventories);
|
||
|
||
var container = _unitwork.FindSingle<Container>(x => x.Code == task.ContainerCode);
|
||
if (container != null)
|
||
{
|
||
container.IsLock = ContainerLockEnum.未锁;
|
||
container.UpdateBy = operatorCode;
|
||
container.UpdateTime = now;
|
||
_unitwork.Update(container);
|
||
}
|
||
|
||
var location = _unitwork.FindSingle<Location>(x => x.Code == task.FromLocation);
|
||
if (location != null && location.ContainerCode == task.ContainerCode)
|
||
{
|
||
location.Status = LocationStatusEnum.未锁;
|
||
location.UpdateBy = operatorCode;
|
||
location.UpdateTime = now;
|
||
_unitwork.Update(location);
|
||
}
|
||
}
|
||
|
||
private void RecalculateShipmentDetail(int shipmentDetailId)
|
||
{
|
||
ShipmentStatusCalculator.RecalculateDetail(_unitwork, shipmentDetailId, GetOperatorCode());
|
||
}
|
||
|
||
private void RecalculateShipmentDetail(ShipmentDetail detail)
|
||
{
|
||
ShipmentStatusCalculator.RecalculateDetail(_unitwork, detail, GetOperatorCode());
|
||
}
|
||
|
||
private void RecalculateShipmentHeader(int shipmentHeaderId)
|
||
{
|
||
ShipmentStatusCalculator.RecalculateHeader(_unitwork, shipmentHeaderId, GetOperatorCode());
|
||
}
|
||
|
||
private void RecalculateShipmentHeader(ShipmentHeader header)
|
||
{
|
||
ShipmentStatusCalculator.RecalculateHeader(_unitwork, header, GetOperatorCode());
|
||
}
|
||
|
||
/// <summary>
|
||
/// 当前操作人账号,用于写更新人
|
||
/// </summary>
|
||
private string GetOperatorCode()
|
||
{
|
||
return Wtm.LoginUserInfo?.ITCode ?? "WMS";
|
||
}
|
||
}
|
||
|
||
public class ShipmentAllocationRequest
|
||
{
|
||
public int DetailId { get; set; }
|
||
|
||
public List<ShipmentAllocationRow> Rows { get; set; }
|
||
}
|
||
|
||
public class ShipmentAllocationRow
|
||
{
|
||
public int InventoryId { get; set; }
|
||
|
||
public decimal Qty { get; set; }
|
||
}
|
||
}
|