Files
WMS/HHWMS.Web/Services/Agv/AgvTaskService.cs
T
sunwang c76e7bb681 fix:永丰售后修复BUG,
1,物料库存获取不到ERP:重新调整触发查询逻辑
2,工序变更导致物料无法出库:配置旧工序
3,测试出库订单ERP推送,任务下发
2026-10-29 13:12:11 +08:00

1009 lines
45 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using HHWMS.Web;
using HHWMS.Web.Models;
using HHWMS.Web.Models.Agv;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
namespace HHWMS.Web.Services.Agv
{
/// <summary>
/// AGV 平库任务核心服务(方案 4.1)
/// 负责:接单(幂等+校验+锁)、下发、取消、回调状态推进、完成联动(9.4)、联动失败重试
/// </summary>
public class AgvTaskService
{
private readonly IUnitWork _unitWork;
private readonly WTMContext _wtm;
private readonly AgvApiClient _agvClient;
private readonly IMapper _mapper;
private readonly AgvOption _option;
public AgvTaskService(IUnitWork unitWork, WTMContext wtm, AgvApiClient agvClient,
IMapper mapper, IOptions<AgvOption> option)
{
_unitWork = unitWork;
_wtm = wtm;
_agvClient = agvClient;
_mapper = mapper;
_option = option.Value;
}
#region 接单
/// <summary>
/// 接单:幂等 + 校验 + LS临时容器 + SKU可选补建 + 接单落库即锁(方案 9.1/9.2)
/// SourceSystem 为空时默认 "WMS"(页面手动下发;API 入口会先覆盖成 "THIRD_PARTY")
/// </summary>
public async Task<AgvTask> CreateTaskAsync(AgvReceiveRequest dto)
{
// SourceSystem 非必填:空则默认 WMS(API 入口会先处理成 THIRD_PARTY)
if (string.IsNullOrWhiteSpace(dto.SourceSystem))
{
dto.SourceSystem = "WMS";
}
ValidateReceiveRequest(dto);
// 任务类型/场景映射(2)
var scene = ResolveSceneConfig(dto.TaskType);
var taskType = scene.AgvTaskType;
// 幂等(9.1.2)
var exists = FindBySource(dto.SourceCode, dto.SourceSystem);
if (exists != null)
{
CheckIdempotent(exists, dto, taskType);
return exists;
}
// 点位有效性(3)+ 楼层取值(7/8,仅取值不校验)
var fromLoc = ValidateFromLocation(dto.FromLocation);
var toLoc = ValidateToLocation(dto.ToLocation);
var (fromFloor, toFloor) = ResolveFloors(fromLoc, toLoc);
// 容器号(9.1.1):
// 不给:起点有容器用起点的,没有则生成 LS 临时容器;
// 给 :起点有容器则必须一致,否则报错;起点无容器则用输入的。
string containerCode;
if (string.IsNullOrWhiteSpace(dto.ContainerCode))
{
containerCode = string.IsNullOrWhiteSpace(fromLoc.ContainerCode)
? "LS" + _unitWork.GetSerialNumber("AGV", 8).Substring(3)
: fromLoc.ContainerCode;
}
else
{
containerCode = dto.ContainerCode.Trim();
}
// 源场景一致性(4)+ 锁定冲突(5/6)
ValidateContainerAndLocks(fromLoc, toLoc, containerCode);
// SKU 可选:带明细则校验并补建物料
var details = dto.Details?.Where(x => !string.IsNullOrWhiteSpace(x.MaterialCode)).ToList();
if (details != null && details.Count > 0)
{
await EnsureMaterialsAsync(details);
}
var priority = dto.Priority ?? 0;
var taskNo = string.IsNullOrWhiteSpace(dto.SourceCode)
? _unitWork.GetSerialNumber("AGV", 8)
: dto.SourceCode.Trim();
var task = new AgvTask
{
TaskNo = taskNo,
SourceCode = string.IsNullOrWhiteSpace(dto.SourceCode) ? null : dto.SourceCode.Trim(),
SourceSystem = dto.SourceSystem.Trim(),
AgvTaskType = taskType,
FromLocation = fromLoc.Code,
ToLocation = toLoc.Code,
FromFloor = fromFloor,
ToFloor = toFloor,
ContainerCode = containerCode,
Priority = priority,
AgvStatus = AgvTaskStatusEnum.新建,
BillType = taskType.ToBillType().ToString(),
Details = details == null ? null : JsonConvert.SerializeObject(details),
CreateBy = _wtm.LoginUserInfo?.ITCode ?? _option.SysUser
};
// 接单落库 + 锁定(同一事务,方案 9.2 方案 A)
using (var transaction = _wtm.DC.BeginTransaction())
{
try
{
_unitWork.Add(task);
LockResources(task, fromLoc, toLoc, details);
WriteAgvLog(taskNo, null, AgvTaskStatusEnum.新建, "Receive", "up", null,
"接单落库并锁定");
await transaction.CommitAsync();
}
catch (AgvBizException)
{
// LockResources 的锁定冲突保持原错误码(lock)返回,不再包装
await transaction.RollbackAsync();
throw;
}
catch (Exception ex)
{
await transaction.RollbackAsync();
throw new AgvBizException("error", $"接单落库失败: {ex.Message}");
}
}
return task;
}
/// <summary>
/// 校验请求必填项(1):taskType/fromLocation/toLocation 必填(sourceSystem 非必填,Service 层已兜底)
/// </summary>
private static void ValidateReceiveRequest(AgvReceiveRequest dto)
{
if (dto == null)
{
throw new AgvBizException("param", "请求参数无效");
}
if (string.IsNullOrWhiteSpace(dto.TaskType))
{
throw new AgvBizException("param", "任务类型 taskType 必填");
}
if (string.IsNullOrWhiteSpace(dto.FromLocation) || string.IsNullOrWhiteSpace(dto.ToLocation))
{
throw new AgvBizException("param", "起点/终点库位必填");
}
if (dto.FromLocation == dto.ToLocation)
{
throw new AgvBizException("param", "起点与终点不能相同");
}
}
/// <summary>
/// 解析任务场景配置(2):字符串类型按 SourceTaskType 匹配,数字枚举 1~6 按 AgvTaskType 兼容
/// </summary>
private AgvTaskSceneConfig ResolveSceneConfig(string taskType)
{
var scene = _unitWork.FindSingle<AgvTaskSceneConfig>(x => x.SourceTaskType == taskType.Trim());
if (scene != null)
{
return scene;
}
if (int.TryParse(taskType.Trim(), out var typeValue) &&
Enum.IsDefined(typeof(AgvTaskTypeEnum), typeValue))
{
scene = _unitWork.FindSingle<AgvTaskSceneConfig>(
x => x.AgvTaskType == (AgvTaskTypeEnum)typeValue);
}
if (scene == null)
{
throw new AgvBizException("param", $"未配置 AGV 任务类型/场景: {taskType}");
}
return scene;
}
/// <summary>
/// 幂等检查(9.1.2):同键不同内容拒绝
/// </summary>
private static void CheckIdempotent(AgvTask exists, AgvReceiveRequest dto, AgvTaskTypeEnum taskType)
{
var contentDirty = exists.FromLocation != dto.FromLocation
|| exists.ToLocation != dto.ToLocation
|| exists.AgvTaskType != taskType
|| (!string.IsNullOrWhiteSpace(dto.ContainerCode) && exists.ContainerCode != dto.ContainerCode.Trim());
if (contentDirty)
{
throw new AgvBizException("status", $"任务[{exists.TaskNo}]已存在且内容不一致,拒绝重复接单");
}
}
/// <summary>
/// 校验起点点位(3):存在、Type=P、非禁用
/// </summary>
private Location ValidateFromLocation(string code)
{
return ValidatePoint(code, "起点");
}
/// <summary>
/// 校验终点点位(3):存在、Type=P、非禁用、目标位未锁定
/// </summary>
private Location ValidateToLocation(string code)
{
return ValidatePoint(code, "终点");
}
/// <summary>
/// 点位通用校验(3):库位必须存在、类型为平库AGV点位(P)、未停用
/// </summary>
private Location ValidatePoint(string code, string name)
{
var location = _unitWork.FindSingle<Location>(x => x.Code == code.Trim());
if (location == null)
{
throw new AgvBizException("param", $"{name}库位[{code}]不存在");
}
if (location.Type != LocationTypeEnum.P)
{
throw new AgvBizException("param", $"{name}库位[{code}]不是AGV点位(Type=P)");
}
if (location.IsStop)
{
throw new AgvBizException("param", $"{name}库位[{code}]已停用");
}
return location;
}
/// <summary>
/// 楼层取值(7/8):仅从库区读取 Floor 作为业务记录字段,返回给任务保存。
/// 平库现场虽有两层,但 WMS 不按楼层做管控,取不到楼层返回 null 并继续执行,不做任何强校验。
/// </summary>
private (int? FromFloor, int? ToFloor) ResolveFloors(Location fromLoc, Location toLoc)
{
var fromZone = _unitWork.FindSingle<LocationZone>(x => x.ID == fromLoc.ZoneId);
var toZone = _unitWork.FindSingle<LocationZone>(x => x.ID == toLoc.ZoneId);
return (fromZone?.Floor, toZone?.Floor);
}
/// <summary>
/// 源场景一致性(4)+ 锁定冲突(5/6):接单前校验,冲突拒绝
/// </summary>
private void ValidateContainerAndLocks(Location fromLoc, Location toLoc, string containerCode)
{
// 源库位容器一致性(4):起点有容器时必须与输入一致,否则报错
if (!string.IsNullOrWhiteSpace(fromLoc.ContainerCode) && fromLoc.ContainerCode != containerCode)
{
throw new AgvBizException("lock", $"输入的容器[{containerCode}]和起点[{fromLoc.Code}]当前绑定的容器[{fromLoc.ContainerCode}]不一致");
}
// 锁定冲突(6)
if (fromLoc.Status == LocationStatusEnum.锁定)
{
throw new AgvBizException("lock", $"源库位[{fromLoc.Code}]已被锁定");
}
if (toLoc.Status == LocationStatusEnum.锁定)
{
throw new AgvBizException("lock", $"目标库位[{toLoc.Code}]已被锁定");
}
if (toLoc.ContainerStatus == LocationStatus.有货)
{
throw new AgvBizException("lock", $"目标库位[{toLoc.Code}]已有货");
}
// 容器锁定冲突(6)
var container = _unitWork.FindSingle<Container>(x => x.Code == containerCode);
if (container != null && container.IsLock != ContainerLockEnum.未锁)
{
throw new AgvBizException("lock", $"容器[{containerCode}]已被锁定");
}
}
/// <summary>
/// 带 SKU 的接单必须保证物料本地存在:不存在则调 ERP LoadInventory 补建,补不到拒绝(9.1)
/// 日志全链路记录:入参物料、本地已有、缺哪些、ERP 请求/响应、补建结果、失败原因,
/// 现场排查"为什么某物料没同步"时可直接在「操作日志」页按模块=物料 筛选
/// </summary>
private async Task EnsureMaterialsAsync(List<AgvReceiveDetail> details)
{
var codes = details.Select(x => x.MaterialCode).Distinct().ToList();
var existing = _unitWork.Find<Material>(m => codes.Contains(m.MaterialCode))
.Select(m => m.MaterialCode)
.ToHashSet();
var missing = codes.Where(c => !existing.Contains(c)).ToList();
_wtm.DoLog($"ERP物料查询: AGV接单带SKU{codes.Count}个", ActionLogTypesEnum.Normal,
"物料", $"all=[{string.Join(",", codes)}], existing=[{string.Join(",", existing)}], missing=[{string.Join(",", missing)}]");
if (missing.Count == 0)
{
return;
}
var request = new LoadInventoryRequest { ErpCode = "003", InvDefine1 = string.Join(",", missing), Size = 50, Page = 1 };
try
{
_wtm.DoLog($"ERP物料查询: 调用ERP LoadInventory", ActionLogTypesEnum.Normal,
"物料", $"missing=[{string.Join(",", missing)}], ErpCode=003");
var apiResult = await _wtm.CallAPI<LoadInventoryResponse>("ERP", "LoadInventory",
HttpMethodEnum.POST, request, _option.CallTimeoutSeconds);
if (apiResult?.Data?.Data == null || apiResult.Data.Code != 0)
{
var errMsg = $"ERP返回异常: Code={apiResult?.Data?.Code}, Msg={apiResult?.Data?.Msg}, ErrorMsg={apiResult?.ErrorMsg}";
_wtm.DoLog($"ERP物料查询: ERP查询失败", ActionLogTypesEnum.Normal, "物料", result: errMsg);
throw new AgvBizException("param", $"ERP 物料查询失败: {apiResult?.Data?.Msg ?? apiResult?.ErrorMsg}");
}
var items = apiResult.Data.Data.Where(x => missing.Contains(x.InvCode)).ToList();
var notFound = missing.Except(items.Select(x => x.InvCode)).ToList();
_wtm.DoLog($"ERP物料查询: ERP返回结果", ActionLogTypesEnum.Normal, "物料",
result: $"ERP返回{apiResult.Data.Data.Count}条, 匹配缺失{items.Count}条, 未找到=[{string.Join(",", notFound)}]");
if (items.Count != missing.Count)
{
_wtm.DoLog($"ERP物料查询: ERP不存在", ActionLogTypesEnum.Normal, "物料",
result: $"notFound=[{string.Join(",", notFound)}]");
throw new AgvBizException("param", $"ERP 物料不存在: {string.Join(",", notFound)}");
}
var newMaterials = items.Select(item => new Material
{
MaterialCode = item.InvCode,
MaterialName = item.InvName,
MaterialSpec = item.InvStd,
MaterialUnit = item.UnitName,
MaterialType = item.InvDefine1,
SupplierCode = item.InvDefine4,
Qty = 0,
CreateBy = _wtm.LoginUserInfo?.ITCode ?? _option.SysUser,
CreateTime = DateTime.Now
}).ToList();
_unitWork.BatchAdd(newMaterials);
_wtm.DoLog($"ERP物料查询: 补建成功{newMaterials.Count}个", ActionLogTypesEnum.Normal, "物料",
result: $"codes=[{string.Join(",", newMaterials.Select(m => m.MaterialCode))}]");
}
catch (AgvBizException)
{
throw;
}
catch (Exception ex)
{
_wtm.DoLog($"ERP物料查询: 补建异常", ActionLogTypesEnum.Normal, "物料", result: ex.ToString());
throw new AgvBizException("error", $"物料补建失败: {ex.Message}");
}
}
/// <summary>
/// 按 SourceCode+SourceSystem 查已存在任务(幂等)
/// </summary>
private AgvTask FindBySource(string sourceCode, string sourceSystem)
{
if (string.IsNullOrWhiteSpace(sourceCode))
{
return null;
}
return _unitWork.FindSingle<AgvTask>(x =>
x.SourceCode == sourceCode.Trim() && x.SourceSystem == sourceSystem.Trim());
}
/// <summary>
/// 接单落库即锁:源容器 + 源库位 + 目标库位 + 对应 Inventory(9.2 方案 A)
/// 库位/容器用条件更新(WHERE 当前未锁)兜底并发:两个接单同时抢同一资源时,
/// 后到的影响行数为 0 抛锁定冲突回滚,消除"先校验后加锁"的竞态窗口
/// </summary>
private void LockResources(AgvTask task, Location fromLoc, Location toLoc,
List<AgvReceiveDetail> details)
{
var containerStatus = details != null && details.Count > 0 ? ContainerStatus.有 : ContainerStatus.空;
// 源容器锁定(LS 临时容器无 Container 档案时跳过;ContainerLockEnum:未锁=0、任务锁=1)
var container = _unitWork.FindSingle<Container>(x => x.Code == task.ContainerCode);
if (container != null)
{
var rows = _wtm.DC.Database.ExecuteSqlRaw(
"UPDATE `Container` SET `IsLock` = 1, `Status` = {1} WHERE `Code` = {0} AND `IsLock` = 0",
task.ContainerCode, containerStatus);
if (rows == 0)
{
throw new AgvBizException("lock", $"容器[{task.ContainerCode}]已被锁定");
}
}
// 源库位与目标库位锁定(条件更新,LocationStatusEnum:未锁=0、锁定=1)
var fromRows = _wtm.DC.Database.ExecuteSqlRaw(
"UPDATE `Location` SET `Status` = 1, `ContainerCode` = {1}, `Version` = {2} WHERE `Code` = {0} AND `Status` = 0",
fromLoc.Code, task.ContainerCode, Guid.NewGuid());
if (fromRows == 0)
{
throw new AgvBizException("lock", $"源库位[{fromLoc.Code}]已被锁定");
}
var toRows = _wtm.DC.Database.ExecuteSqlRaw(
"UPDATE `Location` SET `Status` = 1, `ContainerCode` = {1}, `Version` = {2} WHERE `Code` = {0} AND `Status` = 0",
toLoc.Code, task.ContainerCode, Guid.NewGuid());
if (toRows == 0)
{
throw new AgvBizException("lock", $"目标库位[{toLoc.Code}]已被锁定");
}
// 有货业务锁定对应库存
var inventories = _unitWork.Find<Inventory>(x => x.ContainerCode == task.ContainerCode).ToList();
foreach (var inv in inventories)
{
inv.TaskStatus = InventoryTaskStatusEnum.Locked;
_unitWork.Update(inv);
}
}
#endregion
#region 下发 / 取消
/// <summary>
/// 下发任务:组两步报文(起点取货+终点放货)调 AGV 创建运单(6.3/11.2)
/// 成功→已下发(5);失败→保持新建(0)+ErrorMsg,页面可重试。
/// 状态推进用条件更新(仅 新建0/异常90 可推进为 已下发5):
/// 页面与定时 Job 并发下发时后到者影响行数为 0,不会重复推进状态(厂商侧按 TaskNo 幂等)
/// </summary>
public async Task DispatchTaskAsync(string taskNo)
{
var task = GetTaskForUpdate(taskNo);
if (task == null)
{
throw new AgvBizException("notfound", $"任务[{taskNo}]不存在");
}
if (task.AgvStatus != AgvTaskStatusEnum.新建 && task.AgvStatus != AgvTaskStatusEnum.异常)
{
throw new AgvBizException("status", $"任务[{taskNo}]当前状态[{task.AgvStatus}]不可下发");
}
var scene = _unitWork.FindSingle<AgvTaskSceneConfig>(x => x.AgvTaskType == task.AgvTaskType);
if (scene == null)
{
throw new AgvBizException("param", $"任务[{taskNo}]未配置 AGV 场景");
}
var fromStatus = task.AgvStatus;
var request = BuildCreateOrderRequest(task, scene);
try
{
var result = await _agvClient.CreateOrderAsync(request, task.TaskNo);
var rows = await _wtm.DC.Database.ExecuteSqlRawAsync(
"UPDATE `AgvTask` SET `AgvStatus` = 5, `ErrorMsg` = NULL WHERE `TaskNo` = {0} AND `AgvStatus` IN (0, 90)",
taskNo);
if (rows == 0)
{
WriteAgvLog(task.TaskNo, fromStatus, fromStatus, "Dispatch", "down", null,
$"下发成功但状态已被并发处理,跳过状态更新 orderId={result?.OrderId}");
}
else
{
WriteAgvLog(task.TaskNo, fromStatus, AgvTaskStatusEnum.已下发, "Dispatch", "down",
result?.OrderId, $"下发成功 orderId={result?.OrderId}");
}
}
catch (Exception ex)
{
var msg = $"下发失败: {ex.Message}";
await _wtm.DC.Database.ExecuteSqlRawAsync(
"UPDATE `AgvTask` SET `ErrorMsg` = {1} WHERE `TaskNo` = {0} AND `AgvStatus` IN (0, 90)",
taskNo, msg);
WriteAgvLog(task.TaskNo, fromStatus, fromStatus, "Dispatch", "down", null, msg);
throw new AgvBizException("error", msg);
}
}
/// <summary>
/// 构造下发报文(11.2):只发"起点取货(Load)+终点放货(Unload)"两步
/// </summary>
private static AgvCreateOrderRequest BuildCreateOrderRequest(AgvTask task, AgvTaskSceneConfig scene)
{
return new AgvCreateOrderRequest
{
Id = task.TaskNo,
SceneId = scene.SceneId,
SceneName = scene.SceneName,
ExternalId = task.SourceCode,
Priority = task.Priority ?? 0,
ContainerId = task.ContainerCode,
StepFixed = true,
Steps = new List<AgvOrderStep>
{
new AgvOrderStep
{
Location = task.FromLocation,
RbkArgs = new AgvStepRbkArgs { BinTask = string.IsNullOrWhiteSpace(scene.BinTaskLoad) ? "Load" : scene.BinTaskLoad },
ForLoad = true,
ForUnload = false
},
new AgvOrderStep
{
Location = task.ToLocation,
RbkArgs = new AgvStepRbkArgs { BinTask = string.IsNullOrWhiteSpace(scene.BinTaskUnload) ? "Unload" : scene.BinTaskUnload },
ForLoad = false,
ForUnload = true
}
}
};
}
/// <summary>
/// 取消任务(人工/页面):仅 新建/已下发/执行中/完成联动失败 允许;先调 AGV 取消接口再释放锁(9.3)。
/// 99(完成联动失败)表示 AGV 已实际卸货完成,不再调 AGV 取消,仅本地释放锁。
/// 事务内行锁复核:防止 AGV 取消调用期间并发回调已推进终态(如已完成联动并释放锁)
/// </summary>
public async Task CancelTaskAsync(string taskNo)
{
var task = GetTaskForUpdate(taskNo);
if (task == null)
{
throw new AgvBizException("notfound", $"任务[{taskNo}]不存在");
}
var allowed = task.AgvStatus == AgvTaskStatusEnum.新建
|| task.AgvStatus == AgvTaskStatusEnum.已下发
|| task.AgvStatus == AgvTaskStatusEnum.执行中
|| task.AgvStatus == AgvTaskStatusEnum.完成联动失败;
if (!allowed)
{
throw new AgvBizException("status", $"任务[{taskNo}]当前状态[{task.AgvStatus}]不可取消");
}
// 已下发/执行中先通知 AGV 取消(失败阻断);99 无需通知(AGV 侧已完成)
if (task.AgvStatus == AgvTaskStatusEnum.已下发 || task.AgvStatus == AgvTaskStatusEnum.执行中)
{
var scene = _unitWork.FindSingle<AgvTaskSceneConfig>(x => x.AgvTaskType == task.AgvTaskType);
if (scene != null)
{
await _agvClient.CancelOrderAsync(scene.SceneId, task.TaskNo);
}
}
using (var transaction = _wtm.DC.BeginTransaction())
{
try
{
// 行锁复核:AGV 取消调用期间并发回调可能已推进终态,此时不再重复取消
var locked = GetTaskForUpdateInTx(taskNo);
if (locked == null)
{
throw new AgvBizException("notfound", $"任务[{taskNo}]不存在");
}
var stillAllowed = locked.AgvStatus == AgvTaskStatusEnum.新建
|| locked.AgvStatus == AgvTaskStatusEnum.已下发
|| locked.AgvStatus == AgvTaskStatusEnum.执行中
|| locked.AgvStatus == AgvTaskStatusEnum.完成联动失败;
if (!stillAllowed)
{
WriteAgvLog(locked.TaskNo, locked.AgvStatus, locked.AgvStatus, "Cancel", "down", null,
$"取消时任务已到终态[{locked.AgvStatus}],跳过取消");
await transaction.CommitAsync();
return;
}
var fromStatus = locked.AgvStatus;
ReleaseLocks(locked);
locked.AgvStatus = AgvTaskStatusEnum.取消;
_unitWork.Update(locked);
WriteAgvLog(locked.TaskNo, fromStatus, AgvTaskStatusEnum.取消, "Cancel", "down", null, "人工/页面取消");
await transaction.CommitAsync();
}
catch (Exception ex)
{
await transaction.RollbackAsync();
throw new AgvBizException("error", $"取消任务失败: {ex.Message}");
}
}
}
/// <summary>
/// 释放锁(9.3 与锁定口径相反):容器/源库位/目标库位/库存回滚为未锁
/// </summary>
private void ReleaseLocks(AgvTask task)
{
var container = _unitWork.FindSingle<Container>(x => x.Code == task.ContainerCode);
if (container != null)
{
container.IsLock = ContainerLockEnum.未锁;
_unitWork.Update(container);
}
var fromLoc = _unitWork.FindSingle<Location>(x => x.Code == task.FromLocation);
if (fromLoc != null)
{
fromLoc.Status = LocationStatusEnum.未锁;
fromLoc.Version = Guid.NewGuid();
_unitWork.Update(fromLoc);
}
var toLoc = _unitWork.FindSingle<Location>(x => x.Code == task.ToLocation);
if (toLoc != null)
{
toLoc.Status = LocationStatusEnum.未锁;
toLoc.ContainerCode = string.IsNullOrWhiteSpace(toLoc.ContainerCode) || toLoc.ContainerCode == task.ContainerCode
? null : toLoc.ContainerCode;
toLoc.ContainerStatus = string.IsNullOrWhiteSpace(toLoc.ContainerCode) ? LocationStatus.空仓位 : toLoc.ContainerStatus;
toLoc.Version = Guid.NewGuid();
_unitWork.Update(toLoc);
}
var inventories = _unitWork.Find<Inventory>(x => x.ContainerCode == task.ContainerCode).ToList();
foreach (var inv in inventories)
{
inv.TaskStatus = InventoryTaskStatusEnum.Idle;
_unitWork.Update(inv);
}
}
#endregion
#region 回调 / 完成联动
/// <summary>
/// 处理 AGV 回调(6.2 状态机单调推进):Unloaded 触发完成联动;Cancel 释放锁;其余仅留痕推进
/// </summary>
public async Task HandleCallbackAsync(AgvCallbackRequest dto)
{
if (dto == null || string.IsNullOrWhiteSpace(dto.TaskNo) || string.IsNullOrWhiteSpace(dto.Event))
{
throw new AgvBizException("param", "回调参数无效");
}
var task = GetTaskForUpdate(dto.TaskNo);
if (task == null)
{
throw new AgvBizException("notfound", $"任务[{dto.TaskNo}]不存在");
}
// 终态任务收到任何事件:返回成功但标注已处理(规则1)
if (task.AgvStatus == AgvTaskStatusEnum.完成
|| task.AgvStatus == AgvTaskStatusEnum.取消
|| task.AgvStatus == AgvTaskStatusEnum.完成联动失败)
{
WriteAgvLog(task.TaskNo, task.AgvStatus, task.AgvStatus, dto.Event, "up", null,
"终态收到事件,仅留痕");
return;
}
switch (dto.Event)
{
case "Accepted":
Advance(task, AgvTaskStatusEnum.执行中, dto, "AGV已接单");
break;
case "ArrivedLoad":
case "Loaded":
case "ArrivedUnload":
Advance(task, AgvTaskStatusEnum.执行中, dto, $"回调事件[{dto.Event}]");
break;
case "Unloaded":
await CompleteTaskAsync(task, dto);
break;
case "Error":
{
var fromStatus = task.AgvStatus;
task.AgvStatus = AgvTaskStatusEnum.异常;
task.ErrorMsg = $"{dto.ErrorCode} {dto.ErrorMsg}".Trim();
task.AgvCarNo = dto.AgvCarNo;
_unitWork.Update(task);
WriteAgvLog(task.TaskNo, fromStatus, AgvTaskStatusEnum.异常, dto.Event, "up", null, task.ErrorMsg);
}
break;
case "Cancel":
using (var transaction = _wtm.DC.BeginTransaction())
{
try
{
// 行锁复核:并发 Unloaded 可能已完成联动并释放锁,此时不再重复释放/覆盖状态
var locked = GetTaskForUpdateInTx(task.TaskNo);
if (locked == null)
{
throw new AgvBizException("notfound", $"任务[{dto.TaskNo}]不存在");
}
if (locked.AgvStatus == AgvTaskStatusEnum.完成
|| locked.AgvStatus == AgvTaskStatusEnum.取消
|| locked.AgvStatus == AgvTaskStatusEnum.完成联动失败)
{
WriteAgvLog(locked.TaskNo, locked.AgvStatus, locked.AgvStatus, dto.Event, "up", null,
"回调取消时任务已终态,仅留痕");
await transaction.CommitAsync();
break;
}
var fromStatus = locked.AgvStatus;
ReleaseLocks(locked);
locked.AgvStatus = AgvTaskStatusEnum.取消;
locked.ErrorMsg = dto.ErrorMsg;
_unitWork.Update(locked);
WriteAgvLog(locked.TaskNo, fromStatus, AgvTaskStatusEnum.取消, dto.Event, "up", null, "AGV回调取消");
await transaction.CommitAsync();
}
catch (Exception ex)
{
await transaction.RollbackAsync();
throw new AgvBizException("error", $"AGV 回调取消失败: {ex.Message}");
}
}
break;
default:
throw new AgvBizException("param", $"未知回调事件: {dto.Event}");
}
}
/// <summary>
/// 状态推进(规则3):用 FOR UPDATE 行锁保证原子性,迟到/乱序事件不回退状态
/// </summary>
private void Advance(AgvTask task, AgvTaskStatusEnum target, AgvCallbackRequest dto, string remark)
{
// 单调推进:目标值必须大于当前值;等于则仅留痕
if (task.AgvStatus == target)
{
WriteAgvLog(task.TaskNo, task.AgvStatus, task.AgvStatus, dto.Event, "up", null, remark + "(状态不变)");
return;
}
if (task.AgvStatus != null && task.AgvStatus.Value >= target)
{
WriteAgvLog(task.TaskNo, task.AgvStatus, task.AgvStatus, dto.Event, "up", null,
$"迟到/乱序事件,不回退状态(当前[{task.AgvStatus}],目标[{target}])");
return;
}
var fromStatus = task.AgvStatus;
task.AgvStatus = target;
task.AgvCarNo = dto.AgvCarNo;
_unitWork.Update(task);
WriteAgvLog(task.TaskNo, fromStatus, target, dto.Event, "up", null, remark);
}
/// <summary>
/// 完成联动(9.4):事务内更新库存/容器/库位 + 生成流水 + ERP 通道置位
/// 成功→完成(100);失败→完成联动失败(99) 且可重试
/// </summary>
private async Task CompleteTaskAsync(AgvTask task, AgvCallbackRequest dto)
{
// 仅已下发/执行中可完成(6.2 Unloaded 前置)
if (task.AgvStatus != AgvTaskStatusEnum.已下发 && task.AgvStatus != AgvTaskStatusEnum.执行中)
{
WriteAgvLog(task.TaskNo, task.AgvStatus, task.AgvStatus, dto.Event, "up", null,
$"状态[{task.AgvStatus}]不可执行完成联动");
return;
}
var actualLocation = string.IsNullOrWhiteSpace(dto.ActualLocation) ? task.ToLocation : dto.ActualLocation.Trim();
using (var transaction = _wtm.DC.BeginTransaction())
{
try
{
await ExecuteCompleteLinkAsync(task, actualLocation, dto.AgvCarNo);
task.AgvStatus = AgvTaskStatusEnum.完成;
task.AgvCarNo = dto.AgvCarNo;
task.ErrorMsg = null;
_unitWork.Update(task);
WriteAgvLog(task.TaskNo, AgvTaskStatusEnum.执行中, AgvTaskStatusEnum.完成, dto.Event, "up", null,
$"完成联动成功,实际落位[{actualLocation}]");
await transaction.CommitAsync();
}
catch (Exception ex)
{
await transaction.RollbackAsync();
// 联动失败:置 99(终态),页面可重试
task.AgvStatus = AgvTaskStatusEnum.完成联动失败;
task.ErrorMsg = $"完成联动失败: {ex.Message}";
_unitWork.Update(task);
WriteAgvLog(task.TaskNo, AgvTaskStatusEnum.执行中, AgvTaskStatusEnum.完成联动失败, dto.Event, "up", null, task.ErrorMsg);
throw new AgvBizException("error", task.ErrorMsg);
}
}
}
/// <summary>
/// 完成联动事务主体(9.4 + 15.3.1):库存只更新不删除、容器/库位解锁、流水、ERP 置位
/// </summary>
private async Task ExecuteCompleteLinkAsync(AgvTask task, string actualLocation, string agvCarNo)
{
var billType = ParseBillType(task.BillType);
var isInbound = billType == AgvBillTypeEnum.In_AGV;
// 是否需 ERP 回传(15.3-1):1 入库报工(FinishIn)、3/4 出库回传(AddOtherOut);2/5/6 不回传
var reportBack = IsErpReportBack(task.AgvTaskType);
var details = ParseDetails(task.Details);
var sysUser = _wtm.LoginUserInfo?.ITCode ?? _option.SysUser;
// 库存 UploadErpFlag 置位(15.3-1):入库报工类置0走 FinishInJob、不回传类置1;
// 出库类一律置1(出库回传走流水 AddOtherOut 通道,库存不置0,防止被 FinishInJob 误当入库上送)
var invErpFlag = isInbound ? (reportBack ? 0 : 1) : 1;
// 1. 库存:只更新不删除;带 SKU 且本地无库存时补建
var inventories = _unitWork.Find<Inventory>(x => x.ContainerCode == task.ContainerCode).ToList();
if (inventories.Count == 0 && details != null && details.Count > 0)
{
foreach (var d in details)
{
inventories.Add(new Inventory
{
ZoneId = _unitWork.FindSingle<Location>(x => x.Code == actualLocation)?.ZoneId ?? 0,
ContainerCode = task.ContainerCode,
LocationCode = actualLocation,
MaterialCode = d.MaterialCode,
Qty = isInbound ? (d.Qty ?? 0) : 0,
TaskQty = d.Qty,
BatchCode = d.Batch,
ReceiptDetailId = d.ErpDetailId,
TaskStatus = InventoryTaskStatusEnum.Idle,
UploadErpFlag = invErpFlag,
CreateBy = sysUser,
CreateTime = DateTime.Now
});
}
}
foreach (var inv in inventories)
{
inv.LocationCode = actualLocation;
inv.TaskStatus = InventoryTaskStatusEnum.Idle;
inv.UploadErpFlag = inv.UploadErpFlag ?? invErpFlag;
_unitWork.Update(inv);
}
// 2. 流水:入库 1 条 in / 出库 1 条 out(15.3-1 六类均为 1 条)
if (inventories.Count > 0)
{
// 出库回传流水需携带库区编码,供 AddOtherOutJob 回传时按库区映射 WhCode
var locZoneId = _unitWork.FindSingle<Location>(x => x.Code == actualLocation)?.ZoneId;
var zoneCode = locZoneId.HasValue
? _unitWork.FindSingle<LocationZone>(x => x.ID == locZoneId.Value)?.ZoneCode
: null;
foreach (var inv in inventories)
{
var tran = _mapper.Map<InventoryTransaction>(inv);
tran.Type = isInbound ? InventoryTranType.入库 : InventoryTranType.出库;
// 出库回传类(3/4)挂 AddOtherOut 置 0 走 AddOtherOutJob;其余用 AGV 自身流水类型且置 1 不回传
tran.BillType = isInbound ? billType.ToString()
: (reportBack ? InventoryTransaction.ErpOtherOutBillType : billType.ToString());
tran.UploadErpFlag = isInbound ? 1 : (reportBack ? 0 : 1);
tran.ZoneCode = zoneCode;
tran.CreateTime = DateTime.Now;
_unitWork.Add(tran);
}
}
// 3. 容器:更新库位 + 解锁
var container = _unitWork.FindSingle<Container>(x => x.Code == task.ContainerCode);
if (container != null)
{
container.LocationCode = actualLocation;
container.IsLock = ContainerLockEnum.未锁;
container.Status = isInbound ? ContainerStatus.有 : ContainerStatus.空;
_unitWork.Update(container);
}
// 4. 库位:源位清空,目标位落容器,刷新并发版本
var fromLoc = _unitWork.FindSingle<Location>(x => x.Code == task.FromLocation);
if (fromLoc != null)
{
fromLoc.ContainerCode = string.IsNullOrWhiteSpace(fromLoc.ContainerCode) || fromLoc.ContainerCode == task.ContainerCode
? null : fromLoc.ContainerCode;
fromLoc.Status = LocationStatusEnum.未锁;
fromLoc.ContainerStatus = string.IsNullOrWhiteSpace(fromLoc.ContainerCode) ? LocationStatus.空仓位 : fromLoc.ContainerStatus;
fromLoc.Version = Guid.NewGuid();
_unitWork.Update(fromLoc);
}
var toLoc = _unitWork.FindSingle<Location>(x => x.Code == actualLocation);
if (toLoc != null)
{
toLoc.ContainerCode = task.ContainerCode;
toLoc.Status = LocationStatusEnum.未锁;
toLoc.ContainerStatus = isInbound ? LocationStatus.有货 : LocationStatus.空容器;
toLoc.Version = Guid.NewGuid();
_unitWork.Update(toLoc);
}
// 5. ERP 通道:仅入库报工类(业务1)在线报工 FinishIn;出库回传类(3/4)由 AddOtherOutJob 补传;不回传类(2/5/6)跳过
if (isInbound && reportBack && inventories.Count > 0)
{
var invVM = _wtm.CreateVM<InventoryVM>();
foreach (var inv in inventories)
{
await invVM.ProcessErpFinishIn(inv, TaskTypeEnum.入库);
}
}
}
/// <summary>
/// 重试完成联动(99 → 重新执行完成联动)
/// </summary>
public async Task RetryFinishLinkAsync(string taskNo)
{
var task = GetTaskForUpdate(taskNo);
if (task == null)
{
throw new AgvBizException("notfound", $"任务[{taskNo}]不存在");
}
if (task.AgvStatus != AgvTaskStatusEnum.完成联动失败)
{
throw new AgvBizException("status", $"任务[{taskNo}]当前状态[{task.AgvStatus}]不可重试完成联动");
}
await CompleteTaskAsync(task, new AgvCallbackRequest
{
TaskNo = task.TaskNo,
Event = "Unloaded",
ActualLocation = task.ToLocation,
AgvCarNo = task.AgvCarNo
});
}
#endregion
#region 辅助
/// <summary>
/// 按 TaskNo 查询任务(FOR UPDATE 行锁,保证并发互斥)
/// </summary>
private AgvTask GetTaskForUpdate(string taskNo)
{
return _wtm.DC.Set<AgvTask>()
.FromSqlRaw("SELECT * FROM `AgvTask` WHERE `TaskNo` = {0} FOR UPDATE", taskNo)
.AsNoTracking()
.SingleOrDefault();
}
/// <summary>
/// 事务内复核任务:与 GetTaskForUpdate 同一实现,
/// 区别只是调用时已处于事务中,FOR UPDATE 行锁会保持到事务提交,用于取消/回调的并发复核
/// </summary>
private AgvTask GetTaskForUpdateInTx(string taskNo)
{
return GetTaskForUpdate(taskNo);
}
/// <summary>
/// 解析流水类型
/// </summary>
private static AgvBillTypeEnum ParseBillType(string billType)
{
if (Enum.TryParse<AgvBillTypeEnum>(billType, out var result))
{
return result;
}
return AgvBillTypeEnum.In_AGV;
}
/// <summary>
/// 判断是否需 ERP 回传(15.3-1):1 入库报工(FinishIn)、3/4 出库回传(AddOtherOut);2/5/6 不回传
/// </summary>
private static bool IsErpReportBack(AgvTaskTypeEnum? taskType)
{
return taskType == AgvTaskTypeEnum.原材料入库
|| taskType == AgvTaskTypeEnum.原料满托出库
|| taskType == AgvTaskTypeEnum.混料满桶上线;
}
/// <summary>
/// 解析任务物料明细 JSON
/// </summary>
private static List<AgvReceiveDetail> ParseDetails(string details)
{
if (string.IsNullOrWhiteSpace(details))
{
return null;
}
try
{
return JsonConvert.DeserializeObject<List<AgvReceiveDetail>>(details);
}
catch
{
return null;
}
}
/// <summary>
/// 写 AGV 任务状态/报文日志(9.6)
/// </summary>
private void WriteAgvLog(string taskNo, AgvTaskStatusEnum? fromStatus, AgvTaskStatusEnum? toStatus,
string @event, string direction, string orderId, string remark)
{
try
{
var log = new AgvTaskLog
{
TaskNo = taskNo,
OrderId = orderId,
FromStatus = fromStatus,
ToStatus = toStatus,
Event = @event,
Direction = direction,
Operator = _wtm.LoginUserInfo?.ITCode ?? "AGV",
Remark = remark,
CreateTime = DateTime.Now,
CreateBy = _wtm.LoginUserInfo?.ITCode ?? "AGV"
};
_unitWork.Add(log);
}
catch (Exception ex)
{
_wtm.DoLog("写 AGV 任务日志失败", ActionLogTypesEnum.Normal, "AgvTaskService",
request: taskNo, result: ex.Message);
}
}
#endregion
}
}