测试多数据库访问和erp相关修改

This commit is contained in:
Mac mini git server 2026-01-10 15:07:51 +08:00
parent 68419bf7de
commit 22bfe9d015
14 changed files with 478 additions and 294 deletions

View File

@ -406,7 +406,7 @@ namespace HHWMS.Web
{
Main = new FinishInMain
{
ErpCode = "002", // 账套号
ErpCode = "003", // 账套号
InCode = _unitWork.GetSerialNumber("RW"), // 报工单号(上游单号)
InDate = (inventory.CreateTime ?? DateTime.Now)
.ToString("yyyy-MM-dd"), // 报工日期

View File

@ -549,7 +549,7 @@ namespace HHWMS.Web.Controllers
{
return FFResult().Alert("所选库存没关联订单,无需回传!").RefreshGrid();
}
if (inv.UploadErpFlag == 0)
if (inv.UploadErpFlag is 1)
{
return FFResult().Alert("所选库存已报工回传,无需再次回传!").RefreshGrid();
}
@ -566,7 +566,7 @@ namespace HHWMS.Web.Controllers
{
Main = new FinishInMain
{
ErpCode = "002", // 账套号
ErpCode = "003", // 账套号
InCode = _unitWork.GetSerialNumber("RW"), // 报工单号(上游单号)
InDate = (inv.CreateTime ?? DateTime.Now).ToString("yyyy-MM-dd"), // 报工日期
StepCode = inv.BatchCode, // 工序(批次编码)
@ -587,7 +587,7 @@ namespace HHWMS.Web.Controllers
// 调用ERP接口
var apiResult = await Wtm.CallAPI<FinishInResponse>("ERP", "FinishIn", HttpMethodEnum.POST, request);
if (apiResult.Data != null && apiResult.Data.Result)
if (apiResult.Data is { Result: true })
{
inv.UploadErpFlag = 1;
_unitWork.Update(inv);

View File

@ -0,0 +1,36 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using HHWMS.Web.Models;
using System.Collections.Generic;
using System;
using System.Linq;
namespace HHWMS.Web.Controllers
{
[Public]
[Area("receipt")]
[ActionDescription("CP入库单明细")]
[ApiController]
[Route("api/Detail")]
[FixConnection(DBOperationEnum.Read,"cp")]
public partial class CPReceiptDetailController : BaseApiController
{
private readonly IUnitWork _unitwork;
public CPReceiptDetailController(IUnitWork unitwork)
{
_unitwork = unitwork;
}
[ActionDescription("Sys.Search")]
[HttpPost("Search")]
[Public]
public List<ReceiptDetail> Search()
{
var data = _unitwork.Find<ReceiptDetail>(x => x.Batch == "1").ToList();
return data;
}
}
}

View File

@ -9,6 +9,7 @@ using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using HHWMS.Web;
using HHWMS.Web.Models;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
namespace HHWMS.Web.Controllers
@ -239,7 +240,7 @@ namespace HHWMS.Web.Controllers
[ActionDescription("GetReceiptDetails")]
public ActionResult GetReceiptDetails()
{
var vm = Wtm.CreateVM<ReceiptHeaderVM>();
var vm = Wtm.CreateVM<ReceiptDetailVM>();
return PartialView(vm);
}
/// <summary>
@ -247,28 +248,31 @@ namespace HHWMS.Web.Controllers
/// </summary>
[HttpPost]
[ActionDescription("GetReceiptDetails")]
public async Task<IActionResult> GetReceiptDetails(ReceiptHeaderVM vm)
public async Task<IActionResult> GetReceiptDetails(ReceiptDetailVM vm)
{
string receiptCode = vm.Entity.SourceCode;
string tuhao = vm.Entity.MaterialType;
try
{
if (string.IsNullOrWhiteSpace(receiptCode))
{
return FFResult().Alert($"入库单单号不能为空");
}
// if (string.IsNullOrWhiteSpace(receiptCode))
// {
// return FFResult().Alert($"入库单单号不能为空");
// }
// 根据入库单单号查找对应的 SourceCode(生产订单号)
var header = _unitwork.FindSingle<ReceiptHeader>(h => h.SourceCode == receiptCode);
if (header != null)
{
return FFResult().Alert($"已存在此入库单,单号:{receiptCode}");
}
// var header = _unitwork.FindSingle<ReceiptHeader>(h => h.SourceCode == receiptCode);
// if (header != null)
// {
// return FFResult().Alert($"已存在此入库单,单号:{receiptCode}");
// }
// 调用 ERP 接口获取该订单的最新数据
var request = new LoadMoDetailListRequest
{
ErpCode = "002",
MoCode = receiptCode, // 使用生产订单号查询
ErpCode = "003",
MoCode = receiptCode ?? "", // 使用生产订单号查询
InvCode = vm.Entity?.MaterialCode ?? "",
InvDefine1 = vm.Entity?.MaterialType ?? "",
Size = 100,
Page = 1
};

View File

@ -60,7 +60,7 @@ namespace HHWMS.Web.Controllers
{
var request = new LoadInventoryRequest
{
ErpCode = "002",
ErpCode = "003",
InvDefine1 = keyword,
Size = 15,
Page = 1
@ -235,9 +235,34 @@ namespace HHWMS.Web.Controllers
/// <param name="materialCode"></param>
/// <returns></returns>
[HttpPost]
public IActionResult GetOrdersByMaterial(string materialCode)
public async Task<IActionResult> GetOrdersByMaterial(string materialCode)
{
// 查询包含这个物料的入库单单号
var request = new LoadMoDetailListRequest
{
ErpCode = "003",
InvCode = materialCode,
Size = 100,
Page = 1
};
var apiResult = await Wtm.CallAPI<LoadMoDetailListResponse>("ERP", "LoadMoDetailList", HttpMethodEnum.POST, request);
if (apiResult?.Data != null && apiResult.Data.Code == 0 && apiResult.Data.Data?.Count > 0)
{
Wtm.DoLog("获取ERP订单数据", ActionLogTypesEnum.Normal, "GetReceiptDetails",
request: $"物料:{materialCode},获取到 {apiResult.Data.Data.Count} 条明细",
result: "开始处理订单数据");
// 使用相同的逻辑处理订单数据
await ProcessOrderData(_unitWork, apiResult.Data.Data);
Wtm.DoLog("获取ERP订单数据", ActionLogTypesEnum.Normal, "GetReceiptDetails",
request: $"订单号:{materialCode}",
result: "订单数据处理完成");
}
var orders = _unitWork.Find<ReceiptDetail>(x => x.MaterialCode == materialCode)
.Select(x => new
@ -249,6 +274,328 @@ namespace HHWMS.Web.Controllers
return Json(new { Code = 200, Data = orders });
}
/// <summary>
/// 处理订单数据并保存到本地数据库(照搬 LoadErpOrderJob)
/// </summary>
private async Task ProcessOrderData(IUnitWork unitWork, List<MoDetailItem> orderList)
{
// 按订单号分组
var orderGroups = orderList.GroupBy(x => x.MoCode);
foreach (var group in orderGroups)
{
var moCode = group.Key;
var orderDetails = group.ToList();
// 检查订单是否已存在
var existingHeader = unitWork.FindSingle<ReceiptHeader>(h => h.SourceCode == moCode);
if (existingHeader == null)
{
// 创建新的入库单头
var header = new ReceiptHeader
{
SourceCode = moCode, // 生产订单号
Code = unitWork.GetSerialNumber("REC", 8), // 生成入库单号
BillType = "生产订单",
TotalQty = orderDetails.Sum(x => x.Qty),
TotalLines = orderDetails.Count,
FirstStatus = ReceiptStatusEnum.新建,
LastStatus = ReceiptStatusEnum.新建,
Remark = orderDetails.First().Memo,
CreateTime = DateTime.Now,
CreateBy = Wtm.LoginUserInfo?.ITCode ?? "系统",
UpdateVersion = 1
};
unitWork.Add(header); // 保存以获取 HeaderId
// 获取订单明细中的所有物料编码
var invCodes = orderDetails
.Where(x => !string.IsNullOrWhiteSpace(x.InvCode))
.Select(x => x.InvCode)
.Distinct()
.ToList();
// 一次性查询本地数据库中已存在的物料(优化性能)
var existingMaterials = unitWork.Find<Material>(m => invCodes.Contains(m.MaterialCode))
.ToList();
// 待新增的物料列表
var newMaterials = new List<Material>();
// 创建入库单明细
var details = new List<ReceiptDetail>();
foreach (var item in orderDetails)
{
// 判断物料是否存在,不存在则创建
if (!string.IsNullOrWhiteSpace(item.InvCode))
{
var existingMaterial = existingMaterials.FirstOrDefault(m => m.MaterialCode == item.InvCode);
if (existingMaterial == null)
{
// 检查是否已在待新增列表中
if (!newMaterials.Any(m => m.MaterialCode == item.InvCode))
{
// 物料不存在,创建新物料
var newMaterial = new Material
{
MaterialCode = item.InvCode,
MaterialName = item.InvName,
MaterialSpec = item.InvStd,
MaterialType = item.InvDefine1, // 图号
Qty = 0,
CreateTime = DateTime.Now,
CreateBy = Wtm.LoginUserInfo?.ITCode ?? "系统"
};
newMaterials.Add(newMaterial);
}
}
}
var detail = new ReceiptDetail
{
HeaderId = header.ID,
SourceCode = header.SourceCode,
MaterialCode = item.InvCode,
MaterialType = item.InvDefine1, // 图号
MaterialName = item.InvName,
Lot = item.MoDetailId, // 明细id
MaterialSpec = item.InvStd,
Qty = item.Qty,
CompletedQty = 0,
Status = ReceiptStatusEnum.新建,
CreateTime = DateTime.Now,
CreateBy = Wtm.LoginUserInfo?.ITCode ?? "系统",
UpdateVersion = 1
};
details.Add(detail);
// 保存工序路线到 MaterialProcess 表
if (item.ProcessRoute != null && item.ProcessRoute.Count > 0)
{
await SaveProcessRoute(unitWork, item.InvCode, item.ProcessRoute);
}
}
// 批量新增物料
if (newMaterials.Count > 0)
{
unitWork.BatchAdd(newMaterials);
}
unitWork.BatchAdd(details);
Wtm.DoLog("保存订单数据", ActionLogTypesEnum.Normal, "ProcessOrderData",
request: $"订单号:{moCode}",
result: $"成功创建入库单 {header.Code},明细 {details.Count} 条");
}
else
{
// 订单已存在,更新数据
existingHeader.TotalQty = orderDetails.Sum(x => x.Qty);
existingHeader.TotalLines = orderDetails.Count;
existingHeader.Remark = orderDetails.First().Memo;
existingHeader.UpdateVersion++;
existingHeader.UpdateTime = DateTime.Now;
existingHeader.UpdateBy = Wtm.LoginUserInfo?.ITCode ?? "系统";
unitWork.Update(existingHeader);
// 更新明细
var oldDetails = unitWork.Find<ReceiptDetail>(d => d.HeaderId == existingHeader.ID).ToList();
// 获取订单明细中的所有物料编码
var invCodes = orderDetails
.Where(x => !string.IsNullOrWhiteSpace(x.InvCode))
.Select(x => x.InvCode)
.Distinct()
.ToList();
// 一次性查询本地数据库中已存在的物料(优化性能)
var existingMaterials = unitWork.Find<Material>(m => invCodes.Contains(m.MaterialCode))
.ToList();
// 待新增的物料列表
var newMaterials = new List<Material>();
var newDetails = new List<ReceiptDetail>();
foreach (var item in orderDetails)
{
// 判断明细是否存在 用MoDetailId 判断
if (!oldDetails.Any(x => x.Lot == item.MoDetailId))
{
// 判断物料是否存在,不存在则创建
if (!string.IsNullOrWhiteSpace(item.InvCode))
{
var existingMaterial = existingMaterials.FirstOrDefault(m => m.MaterialCode == item.InvCode);
if (existingMaterial == null)
{
// 检查是否已在待新增列表中
if (!newMaterials.Any(m => m.MaterialCode == item.InvCode))
{
// 物料不存在,创建新物料
var newMaterial = new Material
{
MaterialCode = item.InvCode,
MaterialName = item.InvName,
MaterialSpec = item.InvStd,
MaterialType = item.InvDefine1, // 图号
Qty = 0,
CreateTime = DateTime.Now,
CreateBy = Wtm.LoginUserInfo?.ITCode ?? "系统"
};
newMaterials.Add(newMaterial);
}
}
}
var detail = new ReceiptDetail
{
HeaderId = existingHeader.ID,
SourceCode = existingHeader.SourceCode,
MaterialCode = item.InvCode,
MaterialType = item.InvDefine1, // 图号
MaterialName = item.InvName,
Lot = item.MoDetailId, // 明细id
MaterialSpec = item.InvStd,
Qty = item.Qty,
CompletedQty = 0,
Status = ReceiptStatusEnum.新建,
Batch = item.Version,
CreateTime = DateTime.Now,
CreateBy = Wtm.LoginUserInfo?.ITCode ?? "系统",
UpdateVersion = 1
};
newDetails.Add(detail);
// 更新工序路线
if (item.ProcessRoute != null && item.ProcessRoute.Count > 0)
{
await SaveProcessRoute(unitWork, item.InvCode, item.ProcessRoute);
}
}
}
// 批量新增物料
if (newMaterials.Count > 0)
{
unitWork.BatchAdd(newMaterials);
}
unitWork.BatchAdd(newDetails);
Wtm.DoLog("更新订单数据", ActionLogTypesEnum.Normal, "ProcessOrderData",
request: $"订单号:{moCode}",
result: $"成功更新入库单 {existingHeader.Code},新增明细 {newDetails.Count} 条");
}
}
}
/// <summary>
/// 保存工序路线到 MaterialProcess 表
/// </summary>
private async Task SaveProcessRoute(IUnitWork unitWork, string materialCode, List<ProcessRouteItem> processRoute)
{
// 查询已存在的工序路线
var existingProcesses = unitWork.Find<MaterialProcess>(p => p.MaterialCode == materialCode).ToList();
// 待新增的工序
var processesToAdd = new List<MaterialProcess>();
// 待更新的工序
var processesToUpdate = new List<MaterialProcess>();
var processConfigs = unitWork.Find<ProcessConfig>(x => x.Code != "").ToList();
// 遍历新的工序路线
foreach (var route in processRoute)
{
// 检查工艺是否存在于ProcessConfig中,不存在则添加
var processConfig = processConfigs.Any(p => p.Code == route.ProcessCode);
if (!processConfig)
{
unitWork.Add(new ProcessConfig
{
Code = route.ProcessCode,
Name = route.ProcessName,
Zone = "Zone2",
Port = "EnterExit_P2005"
});
}
// 查找是否存在相同工序名称的记录
var existing = existingProcesses.FirstOrDefault(p =>
p.ProcessName == route.ProcessName);
if (existing != null)
{
// 已存在,检查是否需要更新
bool needUpdate = false;
if (existing.ProcessCode != route.ProcessCode || existing.ProcessOrder != route.Sort)
{
existing.ProcessCode = route.ProcessCode;
existing.ProcessOrder = route.Sort;
needUpdate = true;
}
if (!existing.IsActive)
{
existing.IsActive = true;
needUpdate = true;
}
if (needUpdate)
{
existing.UpdateTime = DateTime.Now;
existing.UpdateBy = Wtm.LoginUserInfo?.ITCode ?? "系统";
processesToUpdate.Add(existing);
}
}
else
{
// 不存在,新增
var newProcess = new MaterialProcess
{
MaterialCode = materialCode,
ProcessCode = route.ProcessCode,
ProcessName = route.ProcessName,
ProcessOrder = route.Sort,
Weight = 0,
IsActive = true,
CreateTime = DateTime.Now,
CreateBy = Wtm.LoginUserInfo?.ITCode ?? "系统"
};
processesToAdd.Add(newProcess);
}
}
// 查找需要删除的工序(旧的多余的)
var processesToDelete = existingProcesses.Where(existing =>
!processRoute.Any(route =>
route.ProcessName == existing.ProcessName)
).ToList();
// 执行数据库操作
if (processesToAdd.Count > 0)
{
unitWork.BatchAdd(processesToAdd);
}
if (processesToUpdate.Count > 0)
{
unitWork.BatchUpdate(processesToUpdate);
}
if (processesToDelete.Count > 0)
{
unitWork.BatchDelete(processesToDelete);
}
await Task.CompletedTask;
}
/// <summary>
/// 获取托盘类型信息
@ -664,4 +1011,4 @@ namespace HHWMS.Web.Controllers
public int BeginLine { get; set; }
public int EndLine { get; set; }
}
}
}

View File

@ -1,9 +1,10 @@
@model HHWMS.Web.ReceiptHeaderVM
@model HHWMS.Web.ReceiptDetailVM
@inject IStringLocalizer<Program> Localizer;
<wt:form vm="@Model">
<wt:row items-per-row="ItemsPerRowEnum.One">
<wt:textbox field="Entity.SourceCode" />
<wt:textbox field="Entity.SourceCode" />
<wt:textbox field="Entity.MaterialType" />
</wt:row>
<wt:hidden field="Entity.ID" />
<wt:row align="AlignEnum.Right">

View File

@ -163,6 +163,9 @@
type: [
{ required: true, message: '请选择托盘类型', trigger: ['change', 'blur'] }
],
//sourceCode: [
//{ required: true, message: '请选择单据', trigger: ['change', 'blur'] }
//],
processId: [
{ required: true, message: '请选择工序', trigger: ['change', 'blur'] }
],
@ -225,7 +228,7 @@
if (orderOptions.value.length === 0) {
Message.warning('该物料暂无关联订单');
}
console.log(orderOptions.value);
//console.log(orderOptions.value);
} else {
Message.error(json.Msg || "获取订单列表失败");
}
@ -319,10 +322,13 @@
// 先清空当前工序选择,避免显示旧数据
form.processId = '';
form.processName = '';
form.sourceCode = '';
form.orderId = '';
// 清除现有工序选项,触发重新渲染
processOptions.value = [];
orderOptions.value = [];
// 延迟加载新工序,确保先清空再加载
nextTick(() => {
loadProcessesByMaterial(selectedMaterial.MaterialCode);

View File

@ -29,7 +29,7 @@ namespace HHWMS.Web
{
Main = new FinishInMain
{
ErpCode = "002", // 账套号
ErpCode = "003", // 账套号
InCode = _unitwork.GetSerialNumber("RW"), // 报工单号(上游单号)
InDate = (inv.CreateTime ?? DateTime.Now).ToString("yyyy-MM-dd"), // 报工日期
StepCode = inv.BatchCode, // 工序(批次编码)

View File

@ -23,7 +23,7 @@ namespace HHWMS.Web
// 调用接口获取ERP订单数据
var request = new LoadMoDetailListRequest
{
ErpCode = "002",
ErpCode = "003",
Size = 100,
Page = 1
};

View File

@ -23,7 +23,7 @@ namespace HHWMS.Web
// 调用接口获取ERP用户数据
var request = new LoadPersonRequest
{
ErpCode = "002",
ErpCode = "003",
Size = 1000,
Page = 1
};

View File

@ -0,0 +1,46 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using HHWMS.Web.Controllers;
using HHWMS.Web.Models;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Core.Support.Quartz;
namespace HHWMS.Web
{
public class SyncReceiptJob : WtmJob
{
public override Task Execute(IJobExecutionContext context)
{
try
{
var unitwork = new UnitWork(Wtm);
var cp = new CPReceiptDetailController(unitwork);
// 获取所有已成品库已完成的明细,更新线边库数据库,限制用户入库的时候选择已入库的订单
// 或者 建立线边库的库存,完成成品库的入库后,同步更新线边库的订单明细 todo
var data = cp.Search();
var t = "";
/*var _unitwork = new UnitWork(Wtm);
var sql = $"DELETE FROM {this.Wtm.DC.GetTableName<PersistedGrant>()} WHERE Expiration<'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}'";
this.Wtm.DC.RunSQL(sql);
Wtm.DoLog("清理过期的refreshToken", ActionLogTypesEnum.Job, "JwtRefreshJob");
#region 更新时间
var job = _unitwork.FindSingle<SysJob>(x => x.JobName == context.JobDetail.Key.Name);
job.LastFireTime = TimeZoneInfo.ConvertTimeFromUtc(context.FireTimeUtc.DateTime, TimeZoneInfo.Local);
job.NextFireTime = TimeZoneInfo.ConvertTimeFromUtc(context.NextFireTimeUtc.Value.DateTime, TimeZoneInfo.Local);
_unitwork.Update<SysJob>(job);
#endregion*/
}
catch { }
return Task.CompletedTask;
}
}
}

View File

@ -14,6 +14,11 @@ namespace HHWMS.Web.Models
/// 生产订单号,非必填
/// </summary>
public string MoCode { get; set; }
/// <summary>
/// 图号
/// </summary>
public string InvDefine1 { get; set; }
/// <summary>
/// 存货编码,非必填

View File

@ -1,267 +1 @@
<script>layui.use('index')</script>
<script src="/front/signalr.min.js"></script>
<script>
// 全局变量(新增关键标记)
let loginConnection = null;
let heartbeatTimer = null;
let reconnectTimer = null;
const userId = '@ViewData["ITCode"]';
let isForceLogout = false;
let isManualStop = false; // 标记是否主动调用stop(),解决竞态条件
let registerRetryCount = 0; // Register方法重试次数
const maxRegisterRetries = 2; // Register最大重试次数
let heartbeatFailureCount = 0; // 心跳失败计数
const maxHeartbeatFailures = 3; // 最大心跳失败次数
let connectionRetryCount = 0; // 连接重试计数
const maxConnectionRetries = 5; // 最大连接重试次数
// 初始化SignalR连接
function initLoginHub() {
if (loginConnection) {
// 主动停止前标记 + 移除监听器,避免onclose触发
isManualStop = true;
try {
loginConnection.off('ForceLogout');
loginConnection.off('RegisterSuccess');
loginConnection.off('HeartbeatResponse');
loginConnection.off('close'); // 移除onclose监听器
stopHeartbeat();
loginConnection.stop();
} catch (err) {
console.error("销毁旧连接失败:", err);
} finally {
isManualStop = false; // 恢复标记
loginConnection = null;
}
}
if (!userId) {
console.warn("用户未登录,跳过SignalR初始化");
return;
}
loginConnection = new signalR.HubConnectionBuilder()
.withUrl("/loginHub", { timeout: 10000 })
.build();
registerHubEvents(); // 重新注册监听器
startConnection();
}
// 注册Hub事件(核心:区分主动/被动断开)
function registerHubEvents() {
// 强制登出事件
loginConnection.on("ForceLogout", (message) => {
isForceLogout = true;
stopAllResources(true); // 主动停止,避免onclose触发重定向
layer.alert(message || "您的账号已在其他设备登录,请重新登录", {
icon: 0,
title: "登录提示",
closeBtn: 0,
btn: ['确定'],
yes: (index) => {
layer.close(index);
window.location.href = '/Login/Login';
}
});
});
// 注册成功事件
loginConnection.on("RegisterSuccess", (message) => {
console.log("SignalR注册成功:", message);
registerRetryCount = 0; // 重置重试次数
connectionRetryCount = 0; // 重置连接重试次数
heartbeatFailureCount = 0; // 重置心跳失败次数
startHeartbeat();
});
// 心跳响应事件
loginConnection.on("HeartbeatResponse", (serverTime) => {
console.debug("心跳响应:", serverTime);
heartbeatFailureCount = 0; // 心跳成功,重置失败计数
});
// 连接关闭事件(核心:区分主动/被动断开)
loginConnection.onclose((error) => {
console.log("SignalR连接关闭:", error);
stopHeartbeat();
// 1. 主动停止(如initLoginHub中销毁旧连接):不处理
if (isManualStop || isForceLogout) return;
// 2. 被动断开:尝试重连而不是立即踢下线
attemptReconnect();
});
}
// 启动连接(修复stop()竞态 + Register失败处理)
async function startConnection() {
if (isForceLogout || !loginConnection) return;
// 状态检查:非Disconnected时主动停止
if (loginConnection.state !== signalR.HubConnectionState.Disconnected) {
console.log("SignalR当前状态:", loginConnection.state, ",主动停止旧连接");
isManualStop = true; // 标记主动停止
try {
// 移除onclose监听器,避免stop()触发
loginConnection.off('close');
await loginConnection.stop();
} catch (err) {
console.error("停止旧连接失败:", err);
} finally {
isManualStop = false; // 恢复标记
registerHubEvents(); // 重新注册监听器
}
}
try {
await loginConnection.start();
console.log("SignalR连接建立成功");
// 调用Register方法(关键:失败后重试/重定向)
const registerSuccess = await tryRegisterUser();
if (!registerSuccess) {
// Register失败视为连接失败,主动断开 + 重定向
isManualStop = true;
await loginConnection.stop();
isManualStop = false;
layer.alert('即时通信服务注册失败,请重新登录', {
icon: 2,
title: "服务异常",
closeBtn: 0,
yes: () => window.location.href = '/Login/Login'
});
}
} catch (err) {
console.error("SignalR连接启动失败:", err);
if (!isForceLogout) {
window.location.href = '/Login/Login';
}
}
}
// Register方法重试逻辑(核心修复:失败处理)
async function tryRegisterUser() {
if (!loginConnection || loginConnection.state !== signalR.HubConnectionState.Connected) {
console.warn("连接未就绪,无法注册用户");
return false;
}
try {
await loginConnection.invoke("Register", userId);
return true; // 注册成功
} catch (err) {
console.error(`Register调用失败(第${registerRetryCount+1}次):`, err);
registerRetryCount++;
// 未达最大重试次数则延迟重试
if (registerRetryCount < maxRegisterRetries) {
await new Promise(resolve => setTimeout(resolve, 1000 * registerRetryCount));
return tryRegisterUser(); // 递归重试
}
// 重试耗尽,注册失败
layer.msg(`即时通信注册失败:${err.message}`, {icon: 2, time: 3000});
return false;
}
}
// 心跳管理
function startHeartbeat() {
stopHeartbeat();
heartbeatTimer = setInterval(() => {
if (loginConnection && loginConnection.state === signalR.HubConnectionState.Connected) {
loginConnection.invoke("Heartbeat", userId).catch((err) => {
console.error("心跳发送失败:", err);
heartbeatFailureCount++;
// 达到最大失败次数才视为连接异常
if (heartbeatFailureCount >= maxHeartbeatFailures) {
console.log("心跳连续失败次数过多,尝试重新连接");
attemptReconnect();
} else {
console.warn(`心跳失败(${heartbeatFailureCount}/${maxHeartbeatFailures}),继续尝试`);
}
});
}
}, 30000);
}
function stopHeartbeat() {
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
heartbeatTimer = null;
}
}
// 重连机制
function attemptReconnect() {
if (isForceLogout || isManualStop) return;
if (connectionRetryCount >= maxConnectionRetries) {
console.log("连接重试次数已达上限,跳转登录页");
layer.alert('与服务器的连接多次失败,请重新登录', {
icon: 2,
title: "连接异常",
closeBtn: 0,
btn: ['确定'],
yes: (index) => {
layer.close(index);
window.location.href = '/Login/Login';
},
end: () => {
window.location.href = '/Login/Login';
}
});
return;
}
connectionRetryCount++;
const delay = Math.min(1000 * Math.pow(2, connectionRetryCount), 30000); // 指数退避,最大30秒
console.log(`第${connectionRetryCount}次重连尝试,${delay/1000}秒后执行`);
reconnectTimer = setTimeout(() => {
if (!isForceLogout && !isManualStop) {
console.log("开始重连...");
initLoginHub(); // 重新初始化连接
}
}, delay);
}
// 资源清理(支持标记主动停止)
async function stopAllResources(isManual = false) {
isManualStop = isManual; // 标记主动停止
// 清理重连定时器
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
stopHeartbeat();
if (loginConnection) {
try {
loginConnection.off('close'); // 移除监听器避免竞态
await loginConnection.stop();
} catch (err) {
console.error("停止连接失败:", err);
} finally {
loginConnection = null;
isManualStop = false; // 恢复标记
}
}
}
// 页面生命周期
$(document).ready(() => {
if (userId) {
initLoginHub();
}
window.addEventListener('beforeunload', async (e) => {
await stopAllResources(true); // 主动停止,避免onclose触发
});
});
</script>

View File

@ -26,6 +26,11 @@
"Key": "default",
"Value": "Server=127.0.0.1;Port=3306;Database=WMS2;Uid=root;Password=abc123*;Character Set=utf8mb4;",
"DBType": "mysql"
},
{
"Key": "cp",
"Value": "Server=127.0.0.1;Port=3306;Database=wms3;Uid=root;Password=abc123*;Character Set=utf8mb4;",
"DBType": "mysql"
}
],
"CookiePre": "HHWMS", //cookie前缀
@ -96,7 +101,7 @@
"Address": "http://192.168.30.220:65533/api/WCS/"
},
"ERP": {
"Address": "http://192.168.16.4:8081/Api/"
"Address": "http://127.0.0.1:4523/m1/1364541-1434451-default/"
}
},
"AppSettings": {