添加updateversion字段 做乐观锁

添加测试出库单分解,和出库拣货路径规划
This commit is contained in:
Mac mini git server 2024-12-27 12:26:32 +08:00
parent 795b9d6d10
commit 3eb8252e55
11 changed files with 1224 additions and 10 deletions

View File

@ -4,7 +4,6 @@ using AutoMapper;
using HHWMS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SqlSugar;
using WalkingTec.Mvvm.Core;
namespace HHWMS.Web
@ -19,12 +18,12 @@ namespace HHWMS.Web
[Route("api/[controller]/[action]"), ApiExplorerSettings(GroupName = "User")]
public class IWCSController : ApiController
{
private readonly IUnitWork _unitwork;
private readonly IUnitWork _unitWork;
private readonly IMapper _mapper;
public IWCSController(IUnitWork unitwork, IMapper mapper)
public IWCSController(IUnitWork unitWork, IMapper mapper)
{
_unitwork = unitwork;
_unitWork = unitWork;
_mapper = mapper;
}
@ -149,16 +148,16 @@ namespace HHWMS.Web
private IActionResult UpdateLocationAndContainer(string locationCode, string palletNo)
{
var location = _unitwork.Find<Location>(x => x.Code == locationCode).FirstOrDefault();
var location = _unitWork.Find<Location>(x => x.Code == locationCode).FirstOrDefault();
location.ContainerCode = palletNo;
location.Status = LocationStatus.任务锁;
_unitwork.Update(location);
_unitWork.Update(location);
var container = _unitwork.Find<Container>(x => x.Code == palletNo).FirstOrDefault();
var container = _unitWork.Find<Container>(x => x.Code == palletNo).FirstOrDefault();
if (container != null)
{
container.LocationCode = location.Code;
_unitwork.Update(container);
_unitWork.Update(container);
}
return ApiResult(new { LocationCode = location.Code });

View File

@ -248,5 +248,17 @@ namespace HHWMS.Web.Controllers
}
return FFResult().RefreshGrid().Message("启动成功!");
}
public ActionResult Analyse(string id)
{
var vm = Wtm.CreateVM<ShipmentHeaderVM>(id);
return PartialView(vm);
}
public ActionResult PickRoute(string id)
{
var vm = Wtm.CreateVM<ShipmentHeaderVM>(id);
return PartialView(vm);
}
}
}

View File

@ -20,7 +20,10 @@ namespace HHWMS.Web
{
this.MakeAction("ShipmentHeader","StartOut",Localizer["ShipmentHeader.StartOut"],"",GridActionParameterTypesEnum.SingleId,"shipment"),
this.MakeAction("ShipmentHeader","Analyse",Localizer["ShipmentHeader.Analyse"],Localizer["ShipmentHeader.Analyse"],GridActionParameterTypesEnum.SingleId,"shipment")
.SetShowInRow().SetHideOnToolBar().SetButtonClass("layui-btn-Warm").SetSize(1200,800),
.SetShowInRow().SetHideOnToolBar().SetButtonClass("layui-btn-Warm").SetMax(),
this.MakeAction("ShipmentHeader","PickRoute",Localizer["ShipmentHeader.PickRoute"],Localizer["ShipmentHeader.PickRoute"],GridActionParameterTypesEnum.SingleId,"shipment")
.SetShowInRow().SetHideOnToolBar().SetButtonClass("layui-btn-Warm").SetMax(),
this.MakeAction("ShipmentHeader","ShelfInv",Localizer["ShipmentHeader.ShelfInv"],Localizer["ShipmentHeader.ShelfInv"],GridActionParameterTypesEnum.SingleId,"shipment")
.SetShowInRow().SetHideOnToolBar().SetButtonClass("layui-btn-Warm").SetSize(1200,800),

View File

@ -7,6 +7,8 @@ using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using HHWMS.Web;
using HHWMS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Z.EntityFramework.Plus;
namespace HHWMS.Web
{
@ -14,6 +16,7 @@ namespace HHWMS.Web
{
public ShipmentDetailListVM Details = new ShipmentDetailListVM();
public List<ComboSelectListItem> ShipTypes { get; set; }
public ShipmentHeaderVM()
{
}
@ -32,6 +35,148 @@ namespace HHWMS.Web
}).ToList();
}
/// <summary>
/// 分解出库单
/// </summary>
/// <returns>处理结果</returns>
public ResponseResult<dynamic> DecomposeShipment()
{
try
{
using var transaction = DC.BeginTransaction();
try
{
var details = DC.Set<ShipmentDetail>()
.Where(x => x.HeaderId == Entity.ID && x.Status != ShipStatusEnum.分配完成)
.ToList();
if (!details.Any())
{
return ResponseResult<dynamic>.Error("没有需要分配的出库单明细");
}
foreach (var detail in details)
{
var availableInventories = DC.Set<Inventory>()
.Where(x => x.MaterialCode == detail.MaterialCode
&& x.TaskStatus == InventoryTaskStatus.无任务
&& x.Qty > x.TaskQty
)
.OrderBy(x => x.CreateTime)
.ToList();
decimal remainingQty = (decimal)(detail.Qty - (detail.DividedQty ?? 0));
decimal dividedQty = 0;
foreach (var inventory in availableInventories)
{
if (remainingQty <= 0) break;
var currentInventory = DC.Set<Inventory>()
.FirstOrDefault(x => x.ID == inventory.ID);
if (currentInventory == null || currentInventory.UpdateVersion != inventory.UpdateVersion)
{
continue;
}
decimal availableQty = (decimal)(currentInventory.Qty - (currentInventory.TaskQty ?? 0));
if (availableQty <= 0) continue;
decimal qtyToDivide = Math.Min(remainingQty, availableQty);
// 更新库存分配数量
currentInventory.TaskQty = (currentInventory.TaskQty ?? 0) + qtyToDivide;
currentInventory.Status = InventoryTaskStatus.任务中;
currentInventory.UpdateVersion++;
DC.UpdateEntity(currentInventory);
remainingQty -= qtyToDivide;
dividedQty += qtyToDivide;
/*var allocation = new InventoryAllocation
{
InventoryId = currentInventory.ID,
ShipmentDetailId = detail.ID,
DividedQty = qtyToDivide,
Status = ShipStatusEnum.分配完成.ToString()
};
DC.AddEntity(allocation);*/
}
if (dividedQty > 0)
{
var currentDetail = DC.Set<ShipmentDetail>()
.FirstOrDefault(x => x.ID == detail.ID);
if (currentDetail != null && currentDetail.UpdateVersion == detail.UpdateVersion)
{
currentDetail.DividedQty = (currentDetail.DividedQty ?? 0) + dividedQty;
currentDetail.Status = currentDetail.DividedQty >= currentDetail.Qty ?
ShipStatusEnum.分配完成 :
ShipStatusEnum.分配中;
currentDetail.UpdateVersion++;
DC.UpdateEntity(currentDetail);
}
}
}
var currentHeader = DC.Set<ShipmentHeader>()
.FirstOrDefault(x => x.ID == Entity.ID);
if (currentHeader != null && currentHeader.UpdateVersion == Entity.UpdateVersion)
{
var allDetails = DC.Set<ShipmentDetail>()
.Where(x => x.HeaderId == Entity.ID)
.ToList();
bool allDivided = allDetails.All(x => x.Status == ShipStatusEnum.分配完成);
currentHeader.FirstStatus = allDivided ?
ShipStatusEnum.分配完成 :
ShipStatusEnum.分配中;
currentHeader.UpdateVersion++;
DC.UpdateEntity(currentHeader);
}
DC.SaveChanges();
transaction.Commit();
var unallocatedDetails = details.Where(x => x.Status != ShipStatusEnum.分配完成).ToList();
if (unallocatedDetails.Any())
{
var errorMsg = string.Join("\n", unallocatedDetails.Select(x =>
$"物料{x.MaterialCode}缺少{x.Qty - (x.DividedQty ?? 0)}个"));
return ResponseResult<dynamic>.Error($"部分物料库存不足,请检查:\n{errorMsg}");
}
return ResponseResult<dynamic>.Success(new
{
message = "出库单分解完成",
headerId = Entity.ID,
status = Entity.FirstStatus,
allocatedDetails = details.Select(x => new
{
x.ID,
x.MaterialCode,
x.Qty,
DividedQty = x.DividedQty,
x.Status
}).ToList()
});
}
catch (Exception ex)
{
transaction.Rollback();
throw new Exception($"处理出库单时发生错误: {ex.Message}");
}
}
catch (Exception ex)
{
return ResponseResult<dynamic>.Error($"分解出库单失败:{ex.Message}");
}
}
public override void DoAdd()
{
base.DoAdd();
@ -46,5 +191,151 @@ namespace HHWMS.Web
{
base.DoDelete();
}
/// <summary>
/// 获取分配库存对应的货架列表
/// </summary>
/// <returns>货架列表</returns>
public ResponseResult<List<string>> GetAllocatedLocations()
{
try
{
// 获取已分配的出库单明细
var details = DC.Set<ShipmentDetail>()
.Where(x => x.HeaderId == Entity.ID
&& (x.Status == ShipStatusEnum.分配完成 || x.Status == ShipStatusEnum.分配中))
.ToList();
if (!details.Any())
{
return ResponseResult<List<string>>.Error("没有已分配的出库单明细");
}
// 获取明细对应的所有库存记录
var allocatedInventories = DC.Set<Inventory>()
.Where(x => x.TaskStatus == InventoryTaskStatus.任务中
&& details.Select(d => d.MaterialCode).Contains(x.MaterialCode))
.ToList();
// 获取去重后的货架编码列表
var locations = allocatedInventories
.Where(x => !string.IsNullOrEmpty(x.LocationCode))
.Select(x => x.LocationCode)
.Distinct()
.OrderBy(x => x)
.ToList();
if (!locations.Any())
{
return ResponseResult<List<string>>.Error("未找到相关库存的货架信息");
}
// 返回货架列表,并包含统计信息
return ResponseResult<List<string>>.Success(locations);
}
catch (Exception ex)
{
return ResponseResult<List<string>>.Error($"获取货架列表失败:{ex.Message}");
}
}
/// <summary>
/// 获取分配库存的详细信息
/// </summary>
/// <returns>库存详细信息</returns>
public ResponseResult<List<InventoryLocationInfo>> GetAllocatedInventoryDetails()
{
try
{
// 获取已分配的出库单明细
var details = DC.Set<ShipmentDetail>()
.Where(x => x.HeaderId == Entity.ID
&& (x.Status == ShipStatusEnum.分配完成 || x.Status == ShipStatusEnum.分配中))
.ToList();
if (!details.Any())
{
return ResponseResult<List<InventoryLocationInfo>>.Error("没有已分配的出库单明细");
}
// 获取明细对应的所有库存记录,并按货架分组
var inventoryGroups = DC.Set<Inventory>()
.Where(x => x.TaskStatus == InventoryTaskStatus.任务中
&& details.Select(d => d.MaterialCode).Contains(x.MaterialCode))
.GroupBy(x => x.LocationCode)
.Select(g => new InventoryLocationInfo
{
LocationCode = g.Key,
Inventories = g.Select(inv => new InventoryInfo
{
MaterialCode = inv.MaterialCode,
MaterialName = inv.MaterialName,
Qty = (decimal)inv.Qty,
TaskQty = inv.TaskQty ?? 0,
BatchCode = inv.Batch
}).ToList()
})
.OrderBy(x => x.LocationCode)
.ToList();
if (!inventoryGroups.Any())
{
return ResponseResult<List<InventoryLocationInfo>>.Error("未找到相关库存信息");
}
return ResponseResult<List<InventoryLocationInfo>>.Success(inventoryGroups);
}
catch (Exception ex)
{
return ResponseResult<List<InventoryLocationInfo>>.Error($"获取库存详细信息失败:{ex.Message}");
}
}
/// <summary>
/// 库存位置信息
/// </summary>
public class InventoryLocationInfo
{
/// <summary>
/// 货架编码
/// </summary>
public string LocationCode { get; set; }
/// <summary>
/// 该货架上的库存列表
/// </summary>
public List<InventoryInfo> Inventories { get; set; }
}
/// <summary>
/// 库存信息
/// </summary>
public class InventoryInfo
{
/// <summary>
/// 物料编码
/// </summary>
public string MaterialCode { get; set; }
/// <summary>
/// 物料名称
/// </summary>
public string MaterialName { get; set; }
/// <summary>
/// 总数量
/// </summary>
public decimal Qty { get; set; }
/// <summary>
/// 任务数量
/// </summary>
public decimal TaskQty { get; set; }
/// <summary>
/// 批次号
/// </summary>
public string BatchCode { get; set; }
}
}
}

View File

@ -0,0 +1,899 @@
@model HHWMS.Web.ShipmentHeaderVM
<input type="hidden" id="shipmentId" value="@Model.Entity.ID" />
<div id="pickRoute">
<div class="picking-route">
<div class="route-info">
<h3>最优拣货路径</h3>
<div class="route-summary">
<span class="total-distance">总距离:{{state.totalDistance}} 格</span>
<span class="total-points">拣货点数:{{state.pickingPoints}} 个</span>
</div>
<div class="route-steps">
<span v-for="(loc, index) in state.route" :key="index"
:class="['route-step',
index === 0 ? 'start' :
(index === state.route.length - 1 ? 'end' : 'point')]">
{{index + 1}}. {{loc}}
<template v-if="index < state.route.length - 1">→</template>
</span>
</div>
</div>
<div class="route-visual">
<canvas id="routeCanvas" width="800" height="800"></canvas>
</div>
</div>
</div>
<script>
// 定义货架之间的距离关系(邻接矩阵)
const INFINITY = Number.MAX_SAFE_INTEGER;
// 计算两个货架之间的曼哈顿距离
function calculateDistance(loc1, loc2) {
// 解析位置编码
const [area1, row1Str, col1Str] = loc1.split('-');
const [area2, row2Str, col2Str] = loc2.split('-');
// 转换为实际的网格位置
const row1 = parseInt(row1Str) * 2 - 1;
const row2 = parseInt(row2Str) * 2 - 1;
const col1 = parseInt(col1Str);
const col2 = parseInt(col2Str);
// 如果不在同一区域,增加额外距离
const areaPenalty = area1 !== area2 ? 100 : 0;
// 计算曼哈顿距离,考虑通道
const rowDist = Math.abs(row1 - row2) +
(row1 !== row2 ? 2 : 0); // 如果跨行,需要额外通过通道
const colDist = Math.abs(col1 - col2);
return rowDist + colDist + areaPenalty;
}
// 计算路径距离
function calculatePathDistance(points) {
let distance = 0;
for (let i = 0; i < points.length - 1; i++) {
const [row1, col1] = points[i];
const [row2, col2] = points[i + 1];
// 计算两点间的曼哈顿距离
distance += Math.abs(row2 - row1) + Math.abs(col2 - col1);
}
return distance;
}
// 构建邻接矩阵
function buildAdjacencyMatrix(locations) {
const n = locations.length;
const matrix = Array(n).fill().map(() => Array(n).fill(INFINITY));
// 填充距离
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (i === j) {
matrix[i][i] = 0;
continue;
}
matrix[i][j] = calculateDistance(locations[i], locations[j]);
}
}
return matrix;
}
// Dijkstra算法实现
function dijkstra(graph, start, locations) {
const n = graph.length;
const dist = Array(n).fill(INFINITY);
const visited = Array(n).fill(false);
const prev = Array(n).fill(-1);
dist[start] = 0;
for (let count = 0; count < n - 1; count++) {
let minDist = INFINITY;
let minIndex = -1;
for (let v = 0; v < n; v++) {
if (!visited[v] && dist[v] < minDist) {
minDist = dist[v];
minIndex = v;
}
}
if (minIndex === -1) break;
visited[minIndex] = true;
for (let v = 0; v < n; v++) {
if (!visited[v] &&
graph[minIndex][v] !== INFINITY &&
dist[minIndex] + graph[minIndex][v] < dist[v]) {
dist[v] = dist[minIndex] + graph[minIndex][v];
prev[v] = minIndex;
}
}
}
return { dist, prev };
}
// 获取最短路径
function getShortestPath(prev, end, locations) {
const path = [];
let current = end;
while (current !== -1) {
path.unshift(locations[current]);
current = prev[current];
}
return path;
}
// 绘制路径
function drawRoute(route, totalRows, totalCols) {
const canvas = document.getElementById('routeCanvas');
const ctx = canvas.getContext('2d');
const padding = 50;
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 计算网格大小
totalRows = totalRows * 2;
totalCols = totalCols + 2;
const gridSize = Math.min(
(canvas.width - padding * 2) / totalCols,
(canvas.height - padding * 2) / totalRows
);
// 修改路径颜色方案
const pathColors = [
'#2196F3', // 蓝色
'#FF5722', // 橙色
'#9C27B0', // 紫色
'#009688', // 青色
'#E91E63', // 粉色
'#673AB7', // 深紫色
'#4CAF50', // 绿色
'#FFC107' // 琥珀色
];
// 绘制网格函数
function drawGrid() {
ctx.strokeStyle = '#ddd';
ctx.lineWidth = 1;
// 绘制所有格子
for (let row = 0; row < totalRows; row++) {
for (let col = 0; col < totalCols; col++) {
const x = padding + col * gridSize;
const y = padding + row * gridSize;
// 判断是否是通道
const isAisle = row === 0 || row === totalRows - 1 || // 顶部和底部通道
col === 0 || col === totalCols - 1 || // 左右通道
row % 2 === 0; // 货架间通道
if (!isAisle) {
// 绘制货架背景
ctx.fillStyle = '#f0f0f0';
ctx.fillRect(x, y, gridSize, gridSize);
// 绘制货架外框
ctx.strokeStyle = '#999';
ctx.lineWidth = 2;
ctx.strokeRect(x, y, gridSize, gridSize);
// 绘制货架内部结构
const innerPadding = 4;
const shelfWidth = (gridSize - innerPadding * 2) / 3;
ctx.fillStyle = '#e0e0e0';
ctx.strokeStyle = '#bbb';
ctx.lineWidth = 1;
// 绘制三层货架
for (let i = 0; i < 3; i++) {
const shelfX = x + innerPadding + i * shelfWidth;
const shelfY = y + innerPadding;
const shelfHeight = gridSize - innerPadding * 2;
ctx.fillRect(shelfX, shelfY, shelfWidth - 1, shelfHeight);
ctx.strokeRect(shelfX, shelfY, shelfWidth - 1, shelfHeight);
}
// 修改货架编号显示
const shelfRow = Math.ceil(row/2);
const shelfCode = `A-${shelfRow.toString().padStart(2, '0')}-${col.toString().padStart(2, '0')}`;
// 使用更小的字体
ctx.font = '10px Arial';
const textWidth = ctx.measureText(shelfCode).width + 6;
const textHeight = 16;
// 调整位置到货架底部中间
const textX = x + (gridSize - textWidth) / 2;
const textY = y + gridSize - textHeight - 2;
// 绘制半透明背景
ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
ctx.fillRect(textX, textY, textWidth, textHeight);
// 绘制编号文字
ctx.fillStyle = '#666';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(shelfCode, x + gridSize/2, y + gridSize - textHeight/2 - 2);
} else {
// 绘制通道
ctx.fillStyle = '#f8f9fa';
ctx.fillRect(x, y, gridSize, gridSize);
// 添加通道标记
if (row % 2 === 0 && col > 0 && col < totalCols - 1) {
// 水平通道标记
ctx.strokeStyle = '#e9ecef';
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.moveTo(x, y + gridSize/2);
ctx.lineTo(x + gridSize, y + gridSize/2);
ctx.stroke();
ctx.setLineDash([]);
}
if ((col === 0 || col === totalCols - 1) && row > 0 && row < totalRows - 1) {
// 垂直通道标记
ctx.strokeStyle = '#e9ecef';
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.moveTo(x + gridSize/2, y);
ctx.lineTo(x + gridSize/2, y + gridSize);
ctx.stroke();
ctx.setLineDash([]);
}
}
}
}
}
// 绘制路径函数
function drawPath() {
ctx.lineWidth = 3;
let lastEndPoint = null;
// 绘制路径线和方向
for (let i = 0; i < route.length - 1; i++) {
const pathPoints = getPathPoints(route[i], route[i + 1], lastEndPoint);
// 使用预定义的颜色,循环使用
const pathColor = pathColors[i % pathColors.length];
ctx.strokeStyle = pathColor;
// 绘制路径线
ctx.beginPath();
pathPoints.forEach((point, index) => {
const [row, col] = point;
const x = padding + col * gridSize + gridSize / 2;
const y = padding + row * gridSize + gridSize / 2;
if (index === 0) {
if (lastEndPoint && i > 0) {
const [lastRow, lastCol] = lastEndPoint;
const lastX = padding + lastCol * gridSize + gridSize / 2;
const lastY = padding + lastRow * gridSize + gridSize / 2;
ctx.moveTo(lastX, lastY);
} else {
ctx.moveTo(x, y);
}
}
ctx.lineTo(x, y);
// 在路径段中间绘制箭头
if (index > 0) {
const prevPoint = pathPoints[index - 1];
const [prevRow, prevCol] = prevPoint;
const prevX = padding + prevCol * gridSize + gridSize / 2;
const prevY = padding + prevRow * gridSize + gridSize / 2;
// 只在直线段的中间绘制箭头
const dx = x - prevX;
const dy = y - prevY;
const distance = Math.sqrt(dx * dx + dy * dy);
// 如果路径段足够长,才绘制箭头
if (distance > gridSize * 1.5) {
// 计算箭头位置(在路径段中间)
const midX = (x + prevX) / 2;
const midY = (y + prevY) / 2;
// 计算方向角度
const angle = Math.atan2(dy, dx);
// 绘制箭头
drawArrow(midX, midY, angle, pathColor);
}
}
});
ctx.stroke();
lastEndPoint = pathPoints[pathPoints.length - 1];
}
// 绘制节点和序号
route.forEach((loc, index) => {
const [_, rowStr, colStr] = loc.split('-');
const row = parseInt(rowStr) * 2 - 1; // 修正行号计算
const col = parseInt(colStr);
const x = padding + col * gridSize + gridSize / 2;
const y = padding + row * gridSize + gridSize / 2;
// 修改节点样式
ctx.fillStyle = index === 0 ? '#4CAF50' :
(index === route.length - 1 ? '#f44336' : '#1976D2');
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fill();
// 添加白色边框
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.stroke();
// 绘制序号
ctx.fillStyle = '#fff';
ctx.font = 'bold 11px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(index + 1, x, y);
});
}
// 绘制箭头函数
function drawArrow(x, y, angle, color) {
const arrowLength = 15; // 增加箭头长度
const arrowWidth = 10; // 增加箭头宽度
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
// 绘制箭头
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(-arrowLength, arrowWidth/2);
ctx.lineTo(-arrowLength, -arrowWidth/2);
ctx.closePath();
ctx.fill();
// 添加白色边框
ctx.strokeStyle = '#fff';
ctx.lineWidth = 1;
ctx.stroke();
ctx.restore();
}
// 绘制图例函数
function drawLegend() {
const legendX = padding;
const legendY = canvas.height - padding/2;
ctx.font = 'bold 14px Arial';
ctx.textBaseline = 'middle';
// 起点
ctx.fillStyle = '#4CAF50';
ctx.beginPath();
ctx.arc(legendX, legendY, 10, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.stroke();
ctx.fillStyle = '#333';
ctx.fillText('起点', legendX + 20, legendY);
// 拣货点
ctx.fillStyle = '#1976D2';
ctx.beginPath();
ctx.arc(legendX + 100, legendY, 10, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.fillStyle = '#333';
ctx.fillText('拣货点', legendX + 120, legendY);
// 终点
ctx.fillStyle = '#f44336';
ctx.beginPath();
ctx.arc(legendX + 200, legendY, 10, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.fillStyle = '#333';
ctx.fillText('终点', legendX + 220, legendY);
// 通道
ctx.fillStyle = '#f8f9fa';
ctx.fillRect(legendX + 300, legendY - 10, 20, 20);
ctx.strokeStyle = '#ddd';
ctx.strokeRect(legendX + 300, legendY - 10, 20, 20);
ctx.fillStyle = '#333';
ctx.fillText('通道', legendX + 330, legendY);
// 路径示例
const arrowX = legendX + 400;
const arrowY = legendY;
ctx.strokeStyle = '#1976D2';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(arrowX, arrowY);
ctx.lineTo(arrowX + 40, arrowY);
ctx.stroke();
drawArrow(arrowX + 20, arrowY, 0, '#1976D2');
ctx.fillStyle = '#333';
ctx.fillText('移动方向', arrowX + 60, arrowY);
}
// 执行绘制
drawGrid();
drawPath();
drawLegend();
}
// 计算最优拣货路径
function calculateOptimalPickingRoute(locations) {
if (!locations || locations.length === 0) {
return { route: [], totalDistance: 0 };
}
const startLocation = 'A-01-01';
// 按行分组并排序货架位置
const groupedLocations = {};
locations.forEach(loc => {
const [area, rowStr, colStr] = loc.split('-');
const row = parseInt(rowStr);
const col = parseInt(colStr);
if (!groupedLocations[row]) {
groupedLocations[row] = [];
}
groupedLocations[row].push({ loc, col });
});
// 按行号排序
const sortedRows = Object.keys(groupedLocations).map(Number).sort((a, b) => a - b);
// 构建最终路径
const route = [startLocation];
let totalDistance = 0;
let currentLoc = startLocation;
let lastEndPoint = null;
let currentSide = 'left'; // 记录当前在左侧还是右侧
// 处理每一行
for (let i = 0; i < sortedRows.length; i++) {
const row = sortedRows[i];
let locations = groupedLocations[row];
// 对每一行的位置按列号排序
locations.sort((a, b) => a.col - b.col);
// 确定这一行的访问顺序
const leftmostCol = locations[0].col;
const rightmostCol = locations[locations.length - 1].col;
const midpoint = 7;
// 判断这一行的位置主要分布在左侧还是右侧
const avgCol = locations.reduce((sum, loc) => sum + loc.col, 0) / locations.length;
const isMainlyLeft = avgCol < midpoint;
// 根据当前位置和主要分布确定访问顺序
let orderedLocations;
if (currentSide === 'left') {
// 当前在左侧,优先处理左侧的货架
orderedLocations = isMainlyLeft ? locations : [...locations].reverse();
currentSide = isMainlyLeft ? 'right' : 'left';
} else {
// 当前在右侧,优先处理右侧的货架
orderedLocations = isMainlyLeft ? locations : [...locations].reverse();
currentSide = isMainlyLeft ? 'right' : 'left';
}
// 添加路径点
orderedLocations.forEach(({ loc }) => {
route.push(loc);
const points = getPathPoints(currentLoc, loc, lastEndPoint);
totalDistance += calculatePathDistance(points);
lastEndPoint = points[points.length - 1];
currentLoc = loc;
});
}
return {
route,
totalDistance: Math.round(totalDistance * 10) / 10
};
}
// 最近邻策略
function nearestNeighbor(graph, locations) {
const n = locations.length;
const visited = new Set([0]);
const route = [locations[0]];
let currentNode = 0;
while (visited.size < n) {
let minDist = INFINITY;
let nextNode = -1;
for (let i = 0; i < n; i++) {
if (!visited.has(i) && graph[currentNode][i] < minDist) {
minDist = graph[currentNode][i];
nextNode = i;
}
}
visited.add(nextNode);
route.push(locations[nextNode]);
currentNode = nextNode;
}
return route;
}
// 最远插入策略
function farthestInsertion(graph, locations) {
const n = locations.length;
const route = [locations[0]];
const unused = new Set(locations.slice(1));
while (unused.size > 0) {
let maxDist = -1;
let bestLoc = null;
let bestPos = -1;
// 找到距离当前路径最远的点
for (const loc of unused) {
for (let i = 0; i < route.length; i++) {
const dist = calculateDistance(route[i], loc);
if (dist > maxDist) {
maxDist = dist;
bestLoc = loc;
bestPos = i + 1;
}
}
}
// 插入到最优位置
route.splice(bestPos, 0, bestLoc);
unused.delete(bestLoc);
}
return route;
}
// 最近插入策略
function nearestInsertion(graph, locations) {
const n = locations.length;
const route = [locations[0]];
const unused = new Set(locations.slice(1));
while (unused.size > 0) {
let minDist = INFINITY;
let bestLoc = null;
let bestPos = -1;
// 找到距离当前路径最近的点
for (const loc of unused) {
for (let i = 0; i < route.length; i++) {
const dist = calculateDistance(route[i], loc);
if (dist < minDist) {
minDist = dist;
bestLoc = loc;
bestPos = i + 1;
}
}
}
// 插入到最优位置
route.splice(bestPos, 0, bestLoc);
unused.delete(bestLoc);
}
return route;
}
// 2-opt优化
function twoOptImprovement(route, graph) {
let improved = true;
while (improved) {
improved = false;
for (let i = 0; i < route.length - 2; i++) {
for (let j = i + 2; j < route.length - 1; j++) {
const delta = calculateDelta(route, i, j, graph);
if (delta < 0) {
// 如果交换能减少距离,则进行交换
reverse(route, i + 1, j);
improved = true;
}
}
}
}
return route;
}
// 计算2-opt交换的距离变化
function calculateDelta(route, i, j, graph) {
const a = route[i];
const b = route[i + 1];
const c = route[j];
const d = route[j + 1];
const d1 = calculateDistance(a, b) + calculateDistance(c, d);
const d2 = calculateDistance(a, c) + calculateDistance(b, d);
return d2 - d1;
}
// 反转子路径
function reverse(route, start, end) {
while (start < end) {
[route[start], route[end]] = [route[end], route[start]];
start++;
end--;
}
}
// 计算路径总距离
function calculateTotalDistance(route, graph) {
let distance = 0;
for (let i = 0; i < route.length - 1; i++) {
distance += calculateDistance(route[i], route[i + 1]);
}
return distance;
}
// 添加getPathPoints函数
function getPathPoints(fromLoc, toLoc, lastEndPoint = null) {
const [_, fromRowStr, fromColStr] = fromLoc.split('-');
const [__, toRowStr, toColStr] = toLoc.split('-');
const fromRow = parseInt(fromRowStr);
const toRow = parseInt(toRowStr);
const fromCol = parseInt(fromColStr);
const toCol = parseInt(toColStr);
const points = [];
const midpoint = 7;
// 如果有上一段路径的终点,从那里开始
if (lastEndPoint) {
points.push(lastEndPoint);
} else {
points.push([fromRow * 2 - 1, fromCol]);
}
const currentPoint = lastEndPoint || [fromRow * 2 - 1, fromCol];
const [currentRow, currentCol] = currentPoint;
// 首先移动到最近的通道
points.push([fromRow * 2 - 2, currentCol]);
if (fromRow !== toRow) {
// 跨行移动时,根据起点和终点的位置选择最优通道
const fromSide = fromCol <= midpoint ? 'left' : 'right';
const toSide = toCol <= midpoint ? 'left' : 'right';
// 计算使用左右通道的总距离
const leftPathDist = Math.abs(currentCol - 0) + Math.abs(toCol - 0); // 使用左通道的距离
const rightPathDist = Math.abs(currentCol - 14) + Math.abs(toCol - 14); // 使用右通道的距离
// 选择最短路径的通道
let useLeftAisle = leftPathDist <= rightPathDist;
// 如果起点和终点都在同一侧,优先使用该侧通道
if (fromSide === toSide) {
useLeftAisle = fromSide === 'left';
}
// 如果目标点在最左侧(列号小于3),强制使用左通道
if (toCol <= 3) {
useLeftAisle = true;
}
// 如果目标点在最右侧(列号大于11),强制使用右通道
else if (toCol >= 11) {
useLeftAisle = false;
}
const aisleCol = useLeftAisle ? 0 : 14;
// 移动到选定的通道
points.push([fromRow * 2 - 2, aisleCol]);
// 在通道中移动到目标行
points.push([toRow * 2 - 2, aisleCol]);
// 移动到目标列
points.push([toRow * 2 - 2, toCol]);
} else if (currentCol !== toCol) {
// 同行移动时,在通道内移动到目标列
points.push([fromRow * 2 - 2, toCol]);
}
// 最后移动到目标货架
points.push([toRow * 2 - 1, toCol]);
return points;
}
const { createApp, reactive, onMounted, nextTick } = Vue;
const app = createApp({
setup() {
// 响应式状态
const state = reactive({
route: [], // 拣货路径
totalDistance: 0, // 总距离
pickingPoints: 0, // 拣货点数
maxRow: 7, // 最大行数
maxCol: 13 // 最大列数
});
// 计算网格大小
const calculateGridSize = (locations) => {
state.maxRow = Math.max(...locations.map(loc => parseInt(loc.split('-')[1]))) + 1;
state.maxCol = Math.max(...locations.map(loc => parseInt(loc.split('-')[2])));
};
// 获取货架位置并计算路径
const getLocationsAndCalculateRoute = () => {
const shipmentId = document.getElementById('shipmentId').value;
$.ajax({
url: '/Shipment/ShipmentHeader/GetAllocatedLocations',
type: 'POST',
data: { id: shipmentId },
success: (response) => {
if (response.code === 200) {
// 计算最优拣货路径
const result = calculateOptimalPickingRoute(response.data);
// 更新状态
state.route = result.route;
state.totalDistance = result.totalDistance;
state.pickingPoints = result.route.length - 1;
// 计算最大行列数
calculateGridSize(response.data);
// 绘制路径
nextTick(() => {
drawRoute(result.route, state.maxRow, state.maxCol);
});
} else {
layer.alert(response.message || '获取货架位置失败', { icon: 5 });
}
},
error: (xhr, status, error) => {
layer.alert('获取货架位置失败:' + error, { icon: 5 });
}
});
};
// 组件挂载时执行
onMounted(() => {
const locations = [
"A-01-02", "A-01-03",
"A-02-04", "A-02-08",
"A-03-02", "A-03-06",
"A-04-08", "A-04-09",
"A-05-02", "A-05-06",
"A-06-13"
];
const result = calculateOptimalPickingRoute(locations);
// 更新状态
state.route = result.route;
state.totalDistance = result.totalDistance;
state.pickingPoints = result.route.length - 1; // 减1是因为要排除起点
// 计算最大行列数
calculateGridSize(locations);
// 绘制路径
nextTick(() => {
drawRoute(result.route, state.maxRow, state.maxCol);
});
});
// 返回模板需要使用的数据和方法
return {
state,
getLocationsAndCalculateRoute,
calculateGridSize
};
}
});
// 挂载应用
app.mount('#pickRoute');
// 添加CSS样式
const style = document.createElement('style');
style.textContent = `
.picking-route {
padding: 20px;
background: #fff;
max-width: 1200px;
margin: 0 auto;
}
.route-info {
margin-bottom: 20px;
padding: 15px;
background: #f8f9fa;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.route-summary {
margin: 10px 0;
padding: 10px;
background: #fff;
border-radius: 4px;
display: flex;
gap: 20px;
}
.total-distance, .total-points {
font-size: 16px;
color: #333;
font-weight: bold;
}
.route-steps {
margin-top: 15px;
line-height: 1.8;
font-size: 14px;
color: #666;
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.route-step {
display: inline-flex;
align-items: center;
padding: 4px 8px;
background: #fff;
border: 1px solid #e9ecef;
border-radius: 3px;
box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
.route-step.start {
background: #e8f5e9;
border-color: #4CAF50;
}
.route-step.end {
background: #ffebee;
border-color: #f44336;
}
.route-step.point {
background: #e3f2fd;
border-color: #1976D2;
}
.route-visual {
border: 1px solid #dee2e6;
padding: 15px;
border-radius: 4px;
background: #fff;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
overflow: auto;
}
#routeCanvas {
display: block;
margin: 0 auto;
}
`;
document.head.appendChild(style);
</script>

View File

@ -29,7 +29,6 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SoapCore" Version="1.1.0.38" />
<PackageReference Include="SqlSugarCore" Version="5.1.4.143" />
<PackageReference Include="System.Reactive.Linq" Version="6.0.0" />
<PackageReference Include="System.ServiceModel.Duplex" Version="4.10.*" />
<PackageReference Include="System.ServiceModel.Federation" Version="4.10.*" />

View File

@ -95,5 +95,7 @@ namespace HHWMS.Web.Models
[Display(Name = "Inventory.Flag", Description = "格数")]
public int Flag { get; set; }
public int UpdateVersion { get; set; }
}
}

View File

@ -75,5 +75,7 @@ namespace HHWMS.Web.Models
[Display(Name = "Receipt.Status", Description = "状态")]
public ReceiptStatusEnum? Status { get; set; }
public int UpdateVersion { get; set; }
}
}

View File

@ -53,5 +53,7 @@ namespace HHWMS.Web.Models
[Display(Name = "_Admin.Remark", Description = "备注")]
public string Remark { get; set; }
public int UpdateVersion { get; set; }
}
}

View File

@ -80,5 +80,8 @@ namespace HHWMS.Web.Models
[Display(Name = "Receipt.Status", Description = "状态")]
[StringLength(50, ErrorMessage = "Validate.{0}stringmax{1}")]
public ShipStatusEnum? Status { get; set; }
public int UpdateVersion { get; set; }
}
}

View File

@ -49,5 +49,7 @@ namespace HHWMS.Web.Models
[Display(Name = "_Admin.Remark", Description = "备注")]
public string Remark { get; set; }
public int UpdateVersion { get; set; }
}
}