feat: 接入ERP成品发货出库流程

This commit is contained in:
mtf committed 2026-07-18 13:41:54 +08:00
1 parent 66a1f60428
commit 7c2722c88d
25 files changed
+2547 -22

No files matched your search

@@ -0,0 +1,409 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HHWMS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
namespace HHWMS.Web.Controllers
{
public partial class SimpleReceiptInController
{
private bool TryGetShipmentContainerData(string containerCode, out object rows)
{
rows = null;
var task = _unitWork.FindSingle<TaskHeader>(x =>
x.ContainerCode == containerCode
&& x.TaskType == TaskTypeEnum.出库
&& x.Status == TaskStatusEnum.到站台);
if (task == null)
{
return false;
}
var taskDetails = _unitWork.Find<TaskDetail>(x =>
x.HeaderId == task.ID
&& x.Status == TaskStatusEnum.到站台)
.OrderBy(x => x.ID)
.ToList();
if (!taskDetails.Any())
{
return false;
}
var inventoryIds = taskDetails.Where(x => x.InventoryId.HasValue)
.Select(x => x.InventoryId.Value)
.Distinct()
.ToList();
var inventories = _unitWork.Find<Inventory>(x => inventoryIds.Contains(x.ID))
.ToDictionary(x => x.ID);
var shipmentDetailIds = taskDetails.Where(x => x.OrderDetailId.HasValue)
.Select(x => x.OrderDetailId.Value)
.Distinct()
.ToList();
var shipmentDetails = _unitWork.Find<ShipmentDetail>(x => shipmentDetailIds.Contains(x.ID))
.ToDictionary(x => x.ID);
if (shipmentDetails.Count != shipmentDetailIds.Count
|| shipmentDetails.Values.Any(x => !x.DLsID.HasValue))
{
return false;
}
var shipmentHeaderIds = shipmentDetails.Values.Select(x => x.HeaderId).Distinct().ToList();
var shipmentHeaders = _unitWork.Find<ShipmentHeader>(x => shipmentHeaderIds.Contains(x.ID))
.ToDictionary(x => x.ID);
rows = taskDetails.Select(taskDetail =>
{
inventories.TryGetValue(taskDetail.InventoryId ?? 0, out var inventory);
shipmentDetails.TryGetValue(taskDetail.OrderDetailId ?? 0, out var shipmentDetail);
ShipmentHeader shipmentHeader = null;
if (shipmentDetail != null)
{
shipmentHeaders.TryGetValue(shipmentDetail.HeaderId, out shipmentHeader);
}
return new
{
TaskDetailId = taskDetail.ID,
Id = inventory?.ID ?? taskDetail.InventoryId,
taskDetail.ContainerCode,
taskDetail.MaterialCode,
MaterialName = inventory?.MaterialType ?? taskDetail.MaterialName,
MaterialSpec = inventory?.MaterialSpec ?? taskDetail.MaterialSpec,
Batch = inventory?.Batch ?? taskDetail.Batch,
CompanyCode = inventory?.CompanyCode,
SourceCode = shipmentHeader?.SourceCode,
ShipmentCode = shipmentHeader?.SourceCode ?? shipmentHeader?.Code,
ShipmentDetailId = shipmentDetail?.ID,
RequiredQty = shipmentDetail?.Qty ?? 0,
CompletedQty = shipmentDetail?.CompletedQty ?? 0,
AllocatedQty = taskDetail.Qty ?? 0,
Qty = inventory?.Qty ?? 0,
ActualQty = taskDetail.Qty ?? 0
};
}).ToList();
return true;
}
[HttpPost]
public async Task<ActionResult> ConfirmShipment([FromBody] ShipmentConfirmRequest request)
{
if (request == null || string.IsNullOrWhiteSpace(request.ContainerCode)
|| request.Rows == null)
{
return JsonMore(null, 500, "确认发货参数不完整");
}
var erpGroups = new Dictionary<int, List<InventoryTransaction>>();
using (var transaction = DC.BeginTransaction())
{
try
{
// 锁定到站任务,避免重复点击或多实例同时确认造成库存重复扣减。
var task = DC.Set<TaskHeader>()
.FromSqlRaw(
"SELECT * FROM `TaskHeader` WHERE `ContainerCode` = {0} AND `TaskType` = {1} AND `Status` = {2} FOR UPDATE",
request.ContainerCode, TaskTypeEnum.出库, TaskStatusEnum.到站台)
.AsNoTracking()
.FirstOrDefault();
if (task == null)
{
return JsonMore(null, 500, "未找到待确认的ERP发货托盘任务");
}
var taskDetails = _unitWork.Find<TaskDetail>(x =>
x.HeaderId == task.ID
&& x.Status == TaskStatusEnum.到站台)
.ToList();
if (!taskDetails.Any())
{
return JsonMore(null, 500, "托盘没有待确认的发货分配");
}
if (request.Rows.Any(x => x.ActualQty < 0)
|| request.Rows.GroupBy(x => x.TaskDetailId).Any(x => x.Count() > 1)
|| request.Rows.Select(x => x.TaskDetailId).OrderBy(x => x)
.SequenceEqual(taskDetails.Select(x => x.ID).OrderBy(x => x)) == false)
{
return JsonMore(null, 500, "必须逐条提交当前托盘全部分配,实际数量不能小于0");
}
var inventoryIds = taskDetails.Where(x => x.InventoryId.HasValue)
.Select(x => x.InventoryId.Value)
.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, "部分已分配库存不存在,请先排查数据,系统未做扣减");
}
foreach (var inventoryGroup in taskDetails.GroupBy(x => x.InventoryId.Value))
{
var inventory = inventories.First(x => x.ID == inventoryGroup.Key);
var actualQty = inventoryGroup.Sum(x =>
request.Rows.First(y => y.TaskDetailId == x.ID).ActualQty);
if (actualQty > (inventory.Qty ?? 0))
{
return JsonMore(null, 500,
$"库存 {inventory.ID} 的本次实际出库合计 {actualQty} 超过当前库存 {inventory.Qty ?? 0}");
}
}
var shipmentDetailIds = taskDetails.Where(x => x.OrderDetailId.HasValue)
.Select(x => x.OrderDetailId.Value)
.Distinct()
.ToList();
var shipmentDetails = new Dictionary<int, ShipmentDetail>();
foreach (var shipmentDetailId in shipmentDetailIds.OrderBy(x => x))
{
var shipmentDetail = DC.Set<ShipmentDetail>()
.FromSqlRaw("SELECT * FROM `ShipmentDetail` WHERE `ID` = {0} FOR UPDATE", shipmentDetailId)
.AsNoTracking()
.SingleOrDefault();
if (shipmentDetail != null)
{
shipmentDetails.Add(shipmentDetail.ID, shipmentDetail);
}
}
if (shipmentDetails.Count != shipmentDetailIds.Count
|| shipmentDetails.Values.Any(x => !x.DLsID.HasValue))
{
return JsonMore(null, 500, "部分出库明细不存在,请先排查数据,系统未做扣减");
}
foreach (var shipmentDetailId in shipmentDetailIds)
{
var shipmentDetail = shipmentDetails[shipmentDetailId];
var currentActualQty = taskDetails.Where(x => x.OrderDetailId == shipmentDetailId)
.Sum(x => request.Rows.First(y => y.TaskDetailId == x.ID).ActualQty);
var otherAllocatedQty = _unitWork.Find<TaskDetail>(x =>
x.OrderDetailId == shipmentDetailId
&& x.HeaderId != task.ID
&& x.Status != TaskStatusEnum.完成)
.Sum(x => x.Qty) ?? 0;
var maxCurrentQty = (shipmentDetail.Qty ?? 0)
- (shipmentDetail.CompletedQty ?? 0)
- otherAllocatedQty;
if (currentActualQty > maxCurrentQty)
{
return JsonMore(null, 500,
$"出库明细 {shipmentDetailId} 的本次实际数量最多为 {maxCurrentQty},其他托盘分配已保留");
}
}
var shipmentHeaderIds = shipmentDetails.Values.Select(x => x.HeaderId).Distinct().ToList();
var shipmentHeaders = _unitWork.Find<ShipmentHeader>(x => shipmentHeaderIds.Contains(x.ID))
.ToDictionary(x => x.ID);
var groupCodes = shipmentHeaderIds.ToDictionary(x => x, x => $"SALE-{Guid.NewGuid():N}");
var now = DateTime.Now;
var operatorCode = Wtm.LoginUserInfo?.ITCode ?? "WMS";
foreach (var taskDetail in taskDetails)
{
var actualQty = request.Rows.First(x => x.TaskDetailId == taskDetail.ID).ActualQty;
var shipmentDetail = shipmentDetails[taskDetail.OrderDetailId.Value];
var shipmentHeader = shipmentHeaders[shipmentDetail.HeaderId];
var inventory = inventories.First(x => x.ID == taskDetail.InventoryId.Value);
if (actualQty > 0)
{
var inventoryTransaction = _mapper.Map<InventoryTransaction>(inventory);
inventoryTransaction.Type = InventoryTranType.出库;
inventoryTransaction.Qty = actualQty;
inventoryTransaction.BillType = InventoryTransaction.ErpSaleOutBillType;
inventoryTransaction.SourceCode = shipmentHeader.SourceCode;
inventoryTransaction.BillCode = groupCodes[shipmentHeader.ID];
inventoryTransaction.BillDetailId = shipmentDetail.ID;
inventoryTransaction.UploadErpFlag = 0;
inventoryTransaction.CreateBy = operatorCode;
inventoryTransaction.CreateTime = now;
_unitWork.Add(inventoryTransaction);
if (!erpGroups.TryGetValue(shipmentHeader.ID, out var groupTransactions))
{
groupTransactions = new List<InventoryTransaction>();
erpGroups[shipmentHeader.ID] = groupTransactions;
}
groupTransactions.Add(inventoryTransaction);
}
shipmentDetail.CompletedQty = (shipmentDetail.CompletedQty ?? 0) + actualQty;
shipmentDetail.UpdateVersion++;
shipmentDetail.UpdateBy = operatorCode;
shipmentDetail.UpdateTime = now;
taskDetail.Status = TaskStatusEnum.完成;
taskDetail.UpdateBy = operatorCode;
taskDetail.UpdateTime = now;
var taskDetailHistory = _mapper.Map<TaskDetailHistory>(taskDetail);
_unitWork.Add(taskDetailHistory);
_unitWork.Delete(taskDetail);
}
foreach (var inventoryGroup in taskDetails.GroupBy(x => x.InventoryId.Value))
{
var inventory = inventories.First(x => x.ID == inventoryGroup.Key);
var actualQty = inventoryGroup.Sum(x =>
request.Rows.First(y => y.TaskDetailId == x.ID).ActualQty);
inventory.Qty = (inventory.Qty ?? 0) - actualQty;
inventory.TaskStatus = InventoryTaskStatusEnum.Idle;
inventory.UpdateBy = operatorCode;
inventory.UpdateTime = now;
if (inventory.Qty <= 0)
{
_unitWork.Delete(inventory);
}
else
{
_unitWork.Update(inventory);
}
}
var remainingInventories = _unitWork.Find<Inventory>(x => x.ContainerCode == task.ContainerCode)
.ToList();
foreach (var inventory in remainingInventories)
{
inventory.TaskStatus = InventoryTaskStatusEnum.Idle;
inventory.UpdateBy = operatorCode;
inventory.UpdateTime = now;
}
_unitWork.BatchUpdate(remainingInventories);
foreach (var shipmentDetail in shipmentDetails.Values)
{
shipmentDetail.DividedQty = _unitWork.Find<TaskDetail>(x =>
x.OrderDetailId == shipmentDetail.ID
&& x.Status != TaskStatusEnum.完成)
.Sum(x => x.Qty) ?? 0;
UpdateShipmentDetailStatus(shipmentDetail);
_unitWork.Update(shipmentDetail);
}
foreach (var shipmentHeaderId in shipmentHeaderIds)
{
UpdateShipmentHeaderStatus(shipmentHeaders[shipmentHeaderId]);
}
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);
}
task.Status = TaskStatusEnum.完成;
task.UpdateBy = operatorCode;
task.UpdateTime = now;
var taskHistory = _mapper.Map<TaskHeaderHistory>(task);
_unitWork.Add(taskHistory);
_unitWork.Delete(task);
await transaction.CommitAsync();
}
catch (Exception ex)
{
await transaction.RollbackAsync();
return JsonMore(null, 500, ex.InnerException?.Message ?? ex.Message);
}
}
var erpSuccess = true;
var inventoryVm = Wtm.CreateVM<InventoryVM>();
foreach (var group in erpGroups.Values)
{
if (!await inventoryVm.ProcessErpSaleOut(group, false))
{
erpSuccess = false;
}
}
var resultMessage = erpGroups.Count == 0
? "发货确认完成,本次实际出库数量为0,无需回传ERP"
: erpSuccess
? "发货确认完成,ERP回传成功"
: "实物出库已完成,ERP回传失败,已进入补传队列";
return JsonMore(new
{
ErpSuccess = erpSuccess,
Message = resultMessage
});
}
private void UpdateShipmentDetailStatus(ShipmentDetail detail)
{
var qty = detail.Qty ?? 0;
var completedQty = detail.CompletedQty ?? 0;
var dividedQty = detail.DividedQty ?? 0;
detail.Status = completedQty >= qty
? ShipStatusEnum.拣货完成
: completedQty > 0
? ShipStatusEnum.拣货中
: dividedQty >= qty && qty > 0
? ShipStatusEnum.分配完成
: dividedQty > 0
? ShipStatusEnum.分配中
: ShipStatusEnum.新建;
}
private void UpdateShipmentHeaderStatus(int shipmentHeaderId)
{
var header = _unitWork.FindSingle<ShipmentHeader>(x => x.ID == shipmentHeaderId);
if (header == null)
{
return;
}
UpdateShipmentHeaderStatus(header);
}
private void UpdateShipmentHeaderStatus(ShipmentHeader header)
{
var details = _unitWork.Find<ShipmentDetail>(x => x.HeaderId == header.ID).ToList();
var status = details.Any() && details.All(x => (x.CompletedQty ?? 0) >= (x.Qty ?? 0))
? ShipStatusEnum.拣货完成
: details.Any(x => (x.CompletedQty ?? 0) > 0)
? ShipStatusEnum.拣货中
: details.Any() && details.All(x =>
(x.CompletedQty ?? 0) + (x.DividedQty ?? 0) >= (x.Qty ?? 0))
? ShipStatusEnum.分配完成
: details.Any(x => (x.DividedQty ?? 0) > 0)
? ShipStatusEnum.分配中
: ShipStatusEnum.新建;
header.FirstStatus = status;
header.LastStatus = status;
header.UpdateBy = Wtm.LoginUserInfo?.ITCode ?? "WMS";
header.UpdateTime = DateTime.Now;
_unitWork.Update(header);
}
}
public class ShipmentConfirmRequest
{
public string ContainerCode { get; set; }
public List<ShipmentConfirmRow> Rows { get; set; }
}
public class ShipmentConfirmRow
{
public int TaskDetailId { get; set; }
public decimal ActualQty { get; set; }
}
}
@@ -57,6 +57,17 @@ namespace HHWMS.Web.Controllers
return Json(new { Code = 400, Msg = $"{containerCode} 容器状态不正确!已存在任务或者已在库内" });
}
if (TryGetShipmentContainerData(containerCode, out var shipmentRows))
{
return Json(new
{
Code = 200,
Msg = "已加载ERP发货分配,请确认实际出库数量",
Data = shipmentRows,
IsShipment = true
});
}
// var task = _unitWork.FindSingle<TaskHeader>(u => u.ContainerCode == containerCode);
// if (task != null && !string.IsNullOrWhiteSpace(task.ToLocation))
// {
@@ -82,7 +93,8 @@ namespace HHWMS.Web.Controllers
return Json(new {
Code = 200,
Msg = "验证成功",
Data = inventories
Data = inventories,
IsShipment = false
});
}
catch (Exception ex)
@@ -72,13 +72,20 @@
<a-button @@click="handleClick" :loading="loading1" type="primary">入库</a-button>
<a-button @@click="emptyIn" :loading="loading1" type="success">空托入库</a-button>
<a-button @@click="outClick" :loading="loading1" type="primary">呼叫出库</a-button>
<a-button v-if="isShipment" @@click="confirmShipment" :loading="shipmentLoading"
type="primary" status="success">确认发货</a-button>
</a-space>
</a-form-item>
</a-form>
<a-table :data="bindList" :columns="columns" :pagination="false">
<a-alert v-if="isShipment" type="warning">
当前托盘来自ERP发货任务。请逐条填写实际出库数量(可以为0),确认后系统一次完成库存扣减、释放分配并回传ERP。
</a-alert>
<a-table :data="bindList" :columns="displayColumns" :pagination="false"
:row-key="record => isShipment ? record.TaskDetailId : record.Id">
<template #operations="{ record }">
<a-space>
<a-space v-if="!isShipment">
<a-button type="text" status="danger" @@click="handleDelete(record)">删除</a-button>
@* <a-button type="text" @@click="handleEdit(record)">修改</a-button> *@
<a-button type="text" @@click="handleDeduct(record)">扣料</a-button>
@@ -87,6 +94,10 @@
<template #qty="{ record }">
{{ Math.floor(record.Qty) }}
</template>
<template #actualQty="{ record }">
<a-input-number v-if="isShipment" v-model="record.ActualQty" :min="0"
:precision="4" style="width: 130px" />
</template>
</a-table>
<a-modal v-model:visible="editModalVisible" title="修改数量" @@ok="handleEditConfirm" @@cancel="handleEditCancel">
@@ -131,6 +142,8 @@
data() {
return {
loading1: false,
shipmentLoading: false,
isShipment: false,
materialOptions: [],
orderOptions: [],
searchTimer: null,
@@ -197,10 +210,41 @@
dataIndex: 'CompanyCode',
},
{
title: '数量',
title: 'ERP发货单',
dataIndex: 'ShipmentCode',
shipmentOnly: true,
width: 150
},
{
title: '需求数量',
dataIndex: 'RequiredQty',
shipmentOnly: true,
width: 100
},
{
title: '已出库',
dataIndex: 'CompletedQty',
shipmentOnly: true,
width: 100
},
{
title: '本托分配',
dataIndex: 'AllocatedQty',
shipmentOnly: true,
width: 100
},
{
title: '当前库存',
dataIndex: 'Qty',
slotName: 'Qty'
},
{
title: '实际出库',
dataIndex: 'ActualQty',
slotName: 'actualQty',
shipmentOnly: true,
width: 150
},
{
title: '操作',
slotName: 'operations',
@@ -232,6 +276,9 @@
this.history.batch = JSON.parse(localStorage.getItem('batchHistory') || '[]');
},
computed: {
displayColumns() {
return this.columns.filter(column => !column.shipmentOnly || this.isShipment);
},
// 部件名称提示列表
batchTips() {
return this.getFilteredTips('batch', this.formData.batch);
@@ -465,6 +512,10 @@
},
handleClick() {
if (this.isShipment) {
this.$notification.error('请先确认当前ERP发货,确认后才能将余料回库!');
return;
}
if (!this.formData.containerCode) {
this.$notification.error('请扫描箱号!');
return;
@@ -510,6 +561,7 @@
const json = response.data;
if (json.Code == 200) {
this.$message.success("容器验证成功");
this.isShipment = json.IsShipment === true;
// 更新绑定列表
this.bindList = json.Data;
// 验证成功后,将焦点设置到物料编码输入框
@@ -520,6 +572,7 @@
this.$message.error(json.Msg || "容器验证失败");
this.formData.containerCode = '';
this.bindList = [];
this.isShipment = false;
}
})
.catch((error) => {
@@ -527,9 +580,48 @@
this.$message.error("容器验证失败: " + (error.message || '网络错误'));
this.formData.containerCode = '';
this.bindList = [];
this.isShipment = false;
});
},
confirmShipment() {
if (!this.isShipment || !this.formData.containerCode) {
this.$notification.error('当前没有待确认的ERP发货托盘!');
return;
}
if (this.bindList.some(item => item.ActualQty === null || item.ActualQty === undefined || Number(item.ActualQty) < 0)) {
this.$notification.error('请填写全部实际出库数量,数量可以为0但不能小于0!');
return;
}
this.shipmentLoading = true;
axios.post('/receipt/SimpleReceiptIn/ConfirmShipment', {
ContainerCode: this.formData.containerCode,
Rows: this.bindList.map(item => ({
TaskDetailId: item.TaskDetailId,
ActualQty: Number(item.ActualQty)
}))
}).then(response => {
const json = response.data;
if (Number(json.Code) === 200) {
const message = json.Data?.Message || '发货确认完成';
if (json.Data?.ErpSuccess === false) {
this.$notification.warning({ content: message, duration: 8000, closable: true });
} else {
this.$notification.success(message);
}
this.isShipment = false;
this.validateContainer();
} else {
this.$notification.error({ content: json.Msg || '确认发货失败', duration: 8000, closable: true });
}
}).catch(error => {
this.$notification.error({ content: error.message || '确认发货失败', duration: 8000, closable: true });
}).finally(() => {
this.shipmentLoading = false;
});
},
handleDelete(record) {
if (!record || !record.Id) {
this.$message.error("无效的记录");