新增MES模块,包含供应商、客户、车辆和地磅数据记录管理功能,支持免密接口和数据同步。更新相关控制器、实体、服务和数据库配置,优化权限管理和数据字典支持,确保系统的灵活性和可扩展性。

This commit is contained in:
geht
2026-04-30 15:28:20 +08:00
parent 142a0bdaba
commit b03cbeff9b
121 changed files with 10540 additions and 424 deletions

View File

@@ -67,6 +67,21 @@ public class ConfigConst
/// </summary>
public const string SysRefreshTokenExpire = "sys_refresh_token_expire";
/// <summary>
/// 用户操作时会话剩余不足该分钟数则续期为「Token过期时间」整段桌面端
/// </summary>
public const string SysTokenIdleExtendMinutes = "sys_token_idle_extend_minutes";
/// <summary>
/// 登录状态检查间隔(分钟),用于检测是否过期
/// </summary>
public const string SysTokenCheckIntervalMinutes = "sys_token_check_interval_minutes";
/// <summary>
/// 是否启用永不过期(桌面端)
/// </summary>
public const string SysTokenNeverExpire = "sys_token_never_expire";
/// <summary>
/// 发送异常日志邮件
/// </summary>

View File

@@ -0,0 +1,11 @@
using Prism.Events;
namespace YY.Admin.Core.Events;
public class CustomerChangedPayload
{
public string Action { get; set; } = string.Empty;
public string? CustomerId { get; set; }
}
public class CustomerChangedEvent : PubSubEvent<CustomerChangedPayload> { }

View File

@@ -0,0 +1,11 @@
using Prism.Events;
namespace YY.Admin.Core.Events;
public class SupplierChangedPayload
{
public string Action { get; set; } = string.Empty;
public string? SupplierId { get; set; }
}
public class SupplierChangedEvent : PubSubEvent<SupplierChangedPayload> { }

View File

@@ -0,0 +1,13 @@
using Prism.Events;
namespace YY.Admin.Core.Events;
public class SyncConflictPayload
{
public string EntityName { get; set; } = string.Empty;
public int PushedCount { get; set; }
public int ConflictCount { get; set; }
public int NewRecordsPushed { get; set; }
}
public class SyncConflictEvent : PubSubEvent<SyncConflictPayload> { }

View File

@@ -0,0 +1,11 @@
using Prism.Events;
namespace YY.Admin.Core.Events;
public class VehicleChangedPayload
{
public string Action { get; set; } = string.Empty;
public string? VehicleId { get; set; }
}
public class VehicleChangedEvent : PubSubEvent<VehicleChangedPayload> { }

View File

@@ -0,0 +1,19 @@
using YY.Admin.Core.Entity;
namespace YY.Admin.Core.Services;
public interface ICustomerService
{
Task<CustomerPageResult> PageAsync(int pageNo, int pageSize,
string? customerCode = null, string? customerName = null,
string? status = null, string? customerRegion = null,
CancellationToken ct = default);
Task<MesXslCustomer?> GetByIdAsync(string id, CancellationToken ct = default);
Task<bool> AddAsync(MesXslCustomer customer, CancellationToken ct = default);
Task<bool> EditAsync(MesXslCustomer customer, CancellationToken ct = default);
Task<bool> DeleteAsync(string id, CancellationToken ct = default);
Task<bool> UpdateStatusAsync(string id, string status, CancellationToken ct = default);
}
public record CustomerPageResult(List<MesXslCustomer> Records, long Total, int PageNo, int PageSize);

View File

@@ -5,4 +5,9 @@ public interface INetworkMonitor
bool IsOnline { get; }
event Action<bool>? StatusChanged;
Task StartAsync(CancellationToken cancellationToken = default);
/// <summary>
/// 由 STOMP 设备通道在连接成功/断开时回写,与 HTTP 探活结果取或,统一 <see cref="IsOnline"/> 与网络事件。
/// </summary>
void SetStompTransportOnline(bool online);
}

View File

@@ -10,4 +10,9 @@ public interface ISignalRService
Task ConnectUnifiedDeviceChannelAsync(CancellationToken cancellationToken = default);
Task SendDeviceStatusAsync(object status, CancellationToken cancellationToken = default);
/// <summary>
/// 主动断开 STOMP 连接并停止重连。
/// </summary>
Task DisconnectAsync(CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,26 @@
using YY.Admin.Core.Entity;
namespace YY.Admin.Core.Services;
public interface ISupplierService
{
Task<SupplierPageResult> PageAsync(int pageNo, int pageSize,
string? supplierCode = null, string? supplierName = null,
string? supplierShortName = null, string? erpCode = null,
string? status = null, CancellationToken ct = default);
Task<MesXslSupplier?> GetByIdAsync(string id, CancellationToken ct = default);
Task<bool> AddAsync(MesXslSupplier supplier, CancellationToken ct = default);
Task<bool> EditAsync(MesXslSupplier supplier, CancellationToken ct = default);
Task<bool> DeleteAsync(string id, CancellationToken ct = default);
Task<bool> UpdateStatusAsync(string id, string status, CancellationToken ct = default);
/// <summary>
/// 重连后将离线期间的本地改动推送到后端,并检测冲突。
/// </summary>
Task<PushPendingResult> PushPendingOnReconnectAsync(CancellationToken ct = default);
}
public record SupplierPageResult(List<MesXslSupplier> Records, long Total, int PageNo, int PageSize);
public record PushPendingResult(int PushedCount, int ConflictCount, int NewRecordsPushed);

View File

@@ -0,0 +1,13 @@
namespace YY.Admin.Core.Services;
/// <summary>
/// 将桌面端用户 CRUD 操作写入 Outbox异步反同步到 Jeecg 后端。
/// </summary>
public interface IUserSyncOutbox
{
Task EnqueueCreateAsync(string userId, string account, string? realName, int? sex, DateTime? birthday, string? phone, string? email, int status, string? updateBy, CancellationToken cancellationToken = default);
Task EnqueueUpdateAsync(string userId, string account, string? realName, int? sex, DateTime? birthday, string? phone, string? email, int status, string? updateBy, CancellationToken cancellationToken = default);
Task EnqueueToggleStatusAsync(string userId, int status, string? updateBy, CancellationToken cancellationToken = default);
Task EnqueueDeleteAsync(string userId, CancellationToken cancellationToken = default);
Task EnqueueBatchDeleteAsync(IReadOnlyList<string> userIds, CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,16 @@
using YY.Admin.Core.Entity;
namespace YY.Admin.Core.Services;
public record VehiclePageResult(List<MesXslVehicle> Records, long Total, int Current, int Size);
public interface IVehicleService
{
Task<VehiclePageResult> PageAsync(int pageNo, int pageSize, string? plateNumber = null, string? vehicleBelong = null, string? status = null, CancellationToken ct = default);
Task<MesXslVehicle?> GetByIdAsync(string id, CancellationToken ct = default);
Task<bool> AddAsync(MesXslVehicle vehicle, CancellationToken ct = default);
Task<bool> EditAsync(MesXslVehicle vehicle, CancellationToken ct = default);
Task<bool> DeleteAsync(string id, CancellationToken ct = default);
Task<bool> DeleteBatchAsync(string ids, CancellationToken ct = default);
Task<bool> UpdateStatusAsync(string id, string status, CancellationToken ct = default);
}

View File

@@ -0,0 +1,16 @@
namespace YY.Admin.Core.Sync;
/// <summary>
/// 桌面→后端用户反同步在 Outbox 中的聚合类型常量。
/// 走 /sys/sync/batch 而非本地拉取路径。
/// </summary>
public static class SysUserSyncOutbox
{
public const string AggregateType = "SYS_USER";
public const string EventCreate = "CREATE";
public const string EventUpdate = "UPDATE";
public const string EventToggleStatus = "TOGGLE_STATUS";
public const string EventDelete = "DELETE";
public const string EventBatchDelete = "BATCH_DELETE";
}

View File

@@ -0,0 +1,25 @@
using System;
namespace YY.Admin.Core.Entity;
public class MesXslCustomer
{
public string? Id { get; set; }
public string? CustomerCode { get; set; }
public string? CustomerName { get; set; }
public string? CustomerShortName { get; set; }
public string? CustomerRegion { get; set; } // Dict: xslmes_customer_region
public string? ErpCode { get; set; }
public string? Status { get; set; } // Dict: xslmes_customer_status "0"启用 "1"停用
public int? IzEnable { get; set; } // 与 Status 联动,由服务端写入,本端只读
public string? CustomerDesc { get; set; }
public int? TenantId { get; set; }
public string? CreateBy { get; set; }
public DateTime? CreateTime { get; set; }
public string? UpdateBy { get; set; }
public DateTime? UpdateTime { get; set; }
public string? SysOrgCode { get; set; }
public int? Version { get; set; }
public string StatusText => Status == "1" ? "停用" : "启用";
}

View File

@@ -0,0 +1,23 @@
using System;
namespace YY.Admin.Core.Entity;
public class MesXslSupplier
{
public string? Id { get; set; }
public string? SupplierCode { get; set; }
public string? SupplierName { get; set; }
public string? SupplierShortName { get; set; }
public string? ErpCode { get; set; }
public string? Remark { get; set; }
public string? Status { get; set; } // Dict: xslmes_supplier_status "0"启用 "1"停用
public int? TenantId { get; set; }
public string? CreateBy { get; set; }
public DateTime? CreateTime { get; set; }
public string? UpdateBy { get; set; }
public DateTime? UpdateTime { get; set; }
public string? SysOrgCode { get; set; }
public int? Version { get; set; }
public string StatusText => Status == "1" ? "停用" : "启用";
}

View File

@@ -0,0 +1,46 @@
namespace YY.Admin.Core.Entity;
public class MesXslVehicle
{
public string? Id { get; set; }
public string? PlateNumber { get; set; }
/// <summary>车辆归属1客户 2供应商 3本公司</summary>
public string? VehicleBelong { get; set; }
public decimal? TareWeightKg { get; set; }
public decimal? LoadCapacity { get; set; }
public string? UnitId { get; set; }
public string? LoadUnit { get; set; }
public string? CustomerIds { get; set; }
public string? CustomerShortName { get; set; }
public string? SupplierId { get; set; }
public string? SupplierName { get; set; }
public string? SupplierShortName { get; set; }
public decimal? VehicleLength { get; set; }
public decimal? VehicleWidth { get; set; }
public decimal? VehicleHeight { get; set; }
public string? DriverName { get; set; }
public string? DriverPhone { get; set; }
/// <summary>状态0启用 1停用</summary>
public string? Status { get; set; }
public int? TenantId { get; set; }
public string? CreateBy { get; set; }
public DateTime? CreateTime { get; set; }
public string? UpdateBy { get; set; }
public DateTime? UpdateTime { get; set; }
public string? SysOrgCode { get; set; }
public int? Version { get; set; }
public string VehicleBelongText => VehicleBelong switch
{
"1" => "客户",
"2" => "供应商",
"3" => "本公司",
_ => VehicleBelong ?? ""
};
public string StatusText => Status == "1" ? "停用" : "启用";
}

View File

@@ -30,6 +30,9 @@ public class SysConfigSeedData : ISqlSugarEntitySeedData<SysConfig>
new SysConfig{ Id=1300000000172, Name="登录时隐藏租户", Code=ConfigConst.SysHideTenantLogin, Value="True", SysFlag=YesNoEnum.Y, Remark="登录时隐藏租户", OrderNo=90, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000181, Name="Token过期时间", Code=ConfigConst.SysTokenExpire, Value="30", SysFlag=YesNoEnum.Y, Remark="Token过期时间分钟", OrderNo=100, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000191, Name="RefreshToken过期时间", Code=ConfigConst.SysRefreshTokenExpire, Value="20160", SysFlag=YesNoEnum.Y, Remark="刷新Token过期时间分钟一般 refresh_token 的有效时间 > 2 * access_token 的有效时间)", OrderNo=110, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000192, Name="会话续期阈值", Code=ConfigConst.SysTokenIdleExtendMinutes, Value="20", SysFlag=YesNoEnum.Y, Remark="桌面端用户有操作时若会话剩余不足该分钟数则续期为「Token过期时间」整段", OrderNo=115, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000193, Name="登录状态检查间隔", Code=ConfigConst.SysTokenCheckIntervalMinutes, Value="1", SysFlag=YesNoEnum.Y, Remark="桌面端:定时检查登录是否过期的间隔(分钟)", OrderNo=118, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000194, Name="登录永不过期", Code=ConfigConst.SysTokenNeverExpire, Value="False", SysFlag=YesNoEnum.Y, Remark="桌面端:开启后不触发登录过期提示与自动踢回登录页", OrderNo=119, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000201, Name="发送异常日志邮件", Code=ConfigConst.SysErrorMail, Value="False", SysFlag=YesNoEnum.Y, Remark="是否发送异常日志邮件", OrderNo=120, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000211, Name="域登录验证", Code=ConfigConst.SysDomainLogin, Value="False", SysFlag=YesNoEnum.Y, Remark="是否开启域登录验证", OrderNo=130, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },
new SysConfig{ Id=1300000000221, Name="数据校验日志", Code=ConfigConst.SysValidationLog, Value="True", SysFlag=YesNoEnum.Y, Remark="是否数据校验日志", OrderNo=140, GroupCode=ConfigConst.SysDefaultGroup, CreateTime=DateTime.Parse("2022-02-10 00:00:00") },

View File

@@ -21,6 +21,20 @@ public class SysMenuSeedData : ISqlSugarEntitySeedData<SysMenu>
// 建议此处Id范围之间放置具体业务应用菜单
#region
new SysMenu{ Id=1300150000101, Pid=0, Title="基础资料", Path="/base", Name="base", Component="Layout", Icon="&#xe7c4;", Type=MenuTypeEnum.Dir, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=9000 },
// 车辆管理
new SysMenu{ Id=1300150010101, Pid=1300150000101, Title="车辆管理", Path="/xslmes/mesXslVehicle", Name="mesXslVehicle", Component="VehicleListView", Icon="&#xe7d2;", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },
// 客户管理
new SysMenu{ Id=1300150010201, Pid=1300150000101, Title="客户管理", Path="/xslmes/mesXslCustomer", Name="mesXslCustomer", Component="CustomerListView", Icon="&#xe7ce;", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=101 },
// 供应商管理
new SysMenu{ Id=1300150010301, Pid=1300150000101, Title="供应商管理", Path="/xslmes/mesXslSupplier", Name="mesXslSupplier", Component="SupplierListView", Icon="&#xe7ce;", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=102 },
#endregion
#region
new SysMenu{ Id=1300200000101, Pid=0, Title="系统管理", Path="", Name="system", Component="Layout", Icon="&#xe7a3;", Type=MenuTypeEnum.Dir, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=10000 },
@@ -43,6 +57,9 @@ public class SysMenuSeedData : ISqlSugarEntitySeedData<SysMenu>
new SysMenu{ Id=1300200012011, Pid=1300200012001, Title="查询", Permission="sysDict:page", Type=MenuTypeEnum.Btn, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },
new SysMenu{ Id=1300200012021, Pid=1300200012001, Title="同步", Permission="sysDict:sync", Type=MenuTypeEnum.Btn, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },
// 登录设置(桌面端会话与检查间隔)
new SysMenu{ Id=1300200013001, Pid=1300200000101, Title="登录设置", Path="LoginSettingsView", Name="loginSettings", Component="LoginSettingsView", Icon="&#xe7c1;", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=107 },
// 角色管理
new SysMenu{ Id=1300200020101, Pid=1300200000101, Title="角色管理", Path="RoleManagementView", Name="sysRole", Component="/system/role/index", Icon="&#xe7e0;", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=110 },
new SysMenu{ Id=1300200020201, Pid=1300200020101, Title="查询", Permission="sysRole:page", Type=MenuTypeEnum.Btn, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },
@@ -114,7 +131,7 @@ public class SysMenuSeedData : ISqlSugarEntitySeedData<SysMenu>
new SysMenu{ Id=1300300011201, Pid=1300300010101, Title="进入租管端", Permission="sysTenant:goTenant", Type=MenuTypeEnum.Btn, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },
// 菜单管理
new SysMenu{ Id=1300300030101, Pid=1300300000101, Title="菜单管理", Path="/platform/menu", Name="sysMenu", Component="/system/menu/index", Icon="&#xe8f1;", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=110 },
new SysMenu{ Id=1300300030101, Pid=1300300000101, Title="菜单管理", Path="MenuManagementView", Name="sysMenu", Component="MenuManagementView", Icon="&#xe8f1;", Type=MenuTypeEnum.Menu, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=110 },
new SysMenu{ Id=1300300030201, Pid=1300300030101, Title="查询", Permission="sysMenu:list", Type=MenuTypeEnum.Btn, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },
new SysMenu{ Id=1300300030301, Pid=1300300030101, Title="编辑", Permission="sysMenu:update", Type=MenuTypeEnum.Btn, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },
new SysMenu{ Id=1300300030401, Pid=1300300030101, Title="增加", Permission="sysMenu:add", Type=MenuTypeEnum.Btn, CreateTime=DateTime.Parse("2022-02-10 00:00:00"), OrderNo=100 },

View File

@@ -21,6 +21,9 @@ public class SysTenantMenuSeedData : ISqlSugarEntitySeedData<SysTenantMenu>
return new[]
{
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300100000101},
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300150000101},
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300150010101},
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300150010201},
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300200010701 },
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300300100601 },
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300200090401 },
@@ -42,6 +45,7 @@ public class SysTenantMenuSeedData : ISqlSugarEntitySeedData<SysTenantMenu>
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300300090201 },
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300200011101 },
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300200010101 },
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300200013001 },
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300500010101 },
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300500030101 },
new SysTenantMenu(){ TenantId=1300000000001,MenuId=1300300051301 },

View File

@@ -0,0 +1,11 @@
using Yitter.IdGenerator;
namespace YY.Admin.Core;
/// <summary>
/// 分布式雪花 Id依赖应用启动时 SqlSugarSetup 中对 YitIdHelper 的初始化)
/// </summary>
public static class SnowflakeId
{
public static long Next() => YitIdHelper.NextId();
}

View File

@@ -15,13 +15,6 @@ namespace YY.Admin.Services.Service.Auth
{
public class SysAuthService : ISysAuthService, ISingletonDependency
{
/// <summary>
///token过期时间(分)
/// </summary>
//private const int _refreshExpires = 30;
// token过期剩余时间(分)
private readonly TimeSpan _idleTimeout = TimeSpan.FromMinutes(20);
private SysUser? _currentUser;
public SysUser? CurrentUser => _currentUser;
public event EventHandler<SysUser?>? UserChanged;
@@ -2324,7 +2317,25 @@ namespace YY.Admin.Services.Service.Auth
private async Task<int> getSysTokenExpireAsync()
{
return await _sysConfigService.GetConfigValue<int>(ConfigConst.SysTokenExpire);
var v = await _sysConfigService.GetConfigValue<int>(ConfigConst.SysTokenExpire);
return v > 0 ? v : 30;
}
/// <summary>
/// 用户操作时续期阈值(分钟),默认 20
/// </summary>
private async Task<int> getSysTokenIdleExtendMinutesAsync()
{
var v = await _sysConfigService.GetConfigValue<int>(ConfigConst.SysTokenIdleExtendMinutes);
return v > 0 ? v : 20;
}
/// <summary>
/// 是否开启永不过期
/// </summary>
private async Task<bool> getSysTokenNeverExpireAsync()
{
return await _sysConfigService.GetConfigValue<bool>(ConfigConst.SysTokenNeverExpire);
}
@@ -2338,8 +2349,9 @@ namespace YY.Admin.Services.Service.Auth
// 生成访问令牌实际项目应使用JWT
var accessToken = GenerateSecureToken(32);
var refreshToken = GenerateSecureToken(32);
var neverExpire = await getSysTokenNeverExpireAsync();
var refreshExpires = await getSysTokenExpireAsync();
var refreshExpiration = DateTime.Now.AddMinutes(refreshExpires);
var refreshExpiration = neverExpire ? DateTime.MaxValue : DateTime.Now.AddMinutes(refreshExpires);
// 存储Token关联信息
_tokenStore[accessToken] = new UserContext
{
@@ -2380,6 +2392,9 @@ namespace YY.Admin.Services.Service.Auth
if (string.IsNullOrEmpty(accessToken))
return false;
if (getSysTokenNeverExpireAsync().GetAwaiter().GetResult())
return _tokenStore.ContainsKey(accessToken);
return _tokenStore.TryGetValue(accessToken, out var tokenInfo) &&
tokenInfo.Token.RefreshExpires >= DateTime.Now;
}
@@ -2388,9 +2403,13 @@ namespace YY.Admin.Services.Service.Auth
{
if (string.IsNullOrEmpty(accessToken))
return;
if (await getSysTokenNeverExpireAsync())
return;
if (_tokenStore.TryGetValue(accessToken, out var tokenInfo))
{
if (tokenInfo.Token.RefreshExpires - DateTime.Now <= _idleTimeout)
var idleMin = await getSysTokenIdleExtendMinutesAsync();
var idleSpan = TimeSpan.FromMinutes(idleMin);
if (tokenInfo.Token.RefreshExpires - DateTime.Now <= idleSpan)
{
var refreshExpires = await getSysTokenExpireAsync();
tokenInfo.Token.RefreshExpires = DateTime.Now.AddMinutes(refreshExpires);
@@ -2430,6 +2449,7 @@ namespace YY.Admin.Services.Service.Auth
_tokenStore.TryRemove(accessToken, out _);
var refreshExpires = await getSysTokenExpireAsync();
var neverExpire = await getSysTokenNeverExpireAsync();
_tokenStore[newToken] = new UserContext
{
UserId = user.Id,
@@ -2442,7 +2462,7 @@ namespace YY.Admin.Services.Service.Auth
Token = new UserToken()
{
RefreshToken = refreshToken,
RefreshExpires = DateTime.Now.AddMinutes(refreshExpires),
RefreshExpires = neverExpire ? DateTime.MaxValue : DateTime.Now.AddMinutes(refreshExpires),
}
};

View File

@@ -9,5 +9,10 @@ namespace YY.Admin.Services.Service.Config
public interface ISysConfigService
{
Task<T> GetConfigValue<T>(string code);
/// <summary>
/// 按编码更新配置值并清除该项缓存
/// </summary>
Task<(bool ok, string message)> SetConfigValueAsync(string code, string value);
}
}

View File

@@ -1,9 +1,6 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YY.Admin.Core;
using YY.Admin.Core.Const;
namespace YY.Admin.Services.Service.Config
{
@@ -31,5 +28,23 @@ namespace YY.Admin.Services.Service.Config
if (string.IsNullOrWhiteSpace(value)) return default;
return (T)Convert.ChangeType(value, typeof(T));
}
/// <inheritdoc />
public async Task<(bool ok, string message)> SetConfigValueAsync(string code, string value)
{
if (string.IsNullOrWhiteSpace(code))
return (false, "配置编码无效");
var n = await _dbContext.Updateable<SysConfig>()
.SetColumns(c => new SysConfig { Value = value, UpdateTime = DateTime.Now })
.Where(c => c.Code == code)
.ExecuteCommandAsync();
if (n <= 0)
return (false, "未找到对应配置项或无需更新");
_sysCacheService.Remove($"{CacheConst.KeyConfig}{code}");
return (true, "保存成功");
}
}
}

View File

@@ -0,0 +1,790 @@
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Web;
using Prism.Events;
using YY.Admin.Core;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
namespace YY.Admin.Services.Service.Customer;
public class CustomerService : ICustomerService, ISingletonDependency
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
private readonly INetworkMonitor _networkMonitor;
private readonly IEventAggregator _eventAggregator;
private readonly ILoggerService _logger;
private readonly SemaphoreSlim _syncLock = new(1, 1);
private readonly object _cacheLock = new();
private readonly string _pendingOpsFilePath;
private readonly string _cacheFilePath;
private List<CustomerPendingOperation> _pendingOps = new();
private List<MesXslCustomer> _localCache = new();
private static readonly JsonSerializerOptions _jsonOpts = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new NullableDateTimeJsonConverter() }
};
public CustomerService(
IHttpClientFactory httpClientFactory,
IConfiguration configuration,
INetworkMonitor networkMonitor,
IEventAggregator eventAggregator,
ILoggerService logger)
{
_httpClientFactory = httpClientFactory;
_configuration = configuration;
_networkMonitor = networkMonitor;
_eventAggregator = eventAggregator;
_logger = logger;
var appDataDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"YY.Admin", "sync-cache");
Directory.CreateDirectory(appDataDir);
_pendingOpsFilePath = Path.Combine(appDataDir, "mes-xsl-customer-pending-ops.json");
_cacheFilePath = Path.Combine(appDataDir, "mes-xsl-customer-cache.json");
LoadPendingOpsFromDisk();
LoadCacheFromDisk();
_logger.Information($"[客户同步] 服务初始化,缓存={_localCache.Count},待上传={_pendingOps.Count},在线={_networkMonitor.IsOnline}");
_networkMonitor.StatusChanged += OnNetworkStatusChanged;
if (_networkMonitor.IsOnline)
_ = Task.Run(() => SyncAfterReconnectAsync(CancellationToken.None));
}
private const int MaxPendingRetries = 5;
private string BaseUrl => (_configuration.GetValue<string>("JeecgIntegration:BaseUrl") ?? "http://localhost:8080/jeecg-boot").TrimEnd('/');
private int DefaultTenantId => (int?)_configuration.GetValue<long?>("JeecgIntegration:DefaultTenantId") ?? 1002;
private HttpClient CreateClient() => _httpClientFactory.CreateClient("JeecgApi");
// ── 分页 ──────────────────────────────────────────────────────────────
public async Task<CustomerPageResult> PageAsync(int pageNo, int pageSize,
string? customerCode = null, string? customerName = null,
string? status = null, string? customerRegion = null,
CancellationToken ct = default)
{
List<MesXslCustomer>? source = null;
if (_networkMonitor.IsOnline)
{
try
{
source = await FetchRemoteListAsync(ct).ConfigureAwait(false);
lock (_cacheLock)
{
_localCache = source.Select(Clone).ToList();
SaveCacheToDiskUnsafe();
}
_logger.Information($"[客户列表] 远端拉取成功 count={source.Count}");
}
catch (Exception ex)
{
source = null;
_logger.Warning($"[客户列表] 远端拉取失败,回退缓存:{ex.Message}");
}
}
lock (_cacheLock)
{
source ??= _localCache.Select(Clone).ToList();
source = ApplyPendingOpsSnapshotUnsafe(source);
}
var filtered = ApplyFilters(source, customerCode, customerName, status, customerRegion);
var total = filtered.Count;
var records = filtered.Skip(Math.Max(0, (pageNo - 1) * pageSize)).Take(pageSize).ToList();
return new CustomerPageResult(records, total, pageNo, pageSize);
}
// ── 详情 ──────────────────────────────────────────────────────────────
public async Task<MesXslCustomer?> GetByIdAsync(string id, CancellationToken ct = default)
{
if (_networkMonitor.IsOnline)
{
try
{
var url = $"{BaseUrl}/xslmes/mesXslCustomer/anon/queryById?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
var resp = await client.GetAsync(url, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return null;
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("result", out var resultEl)) return null;
return resultEl.Deserialize<MesXslCustomer>(_jsonOpts);
}
catch (Exception ex)
{
_logger.Warning($"[客户详情] 远端查询失败 id={id},回退缓存:{ex.Message}");
}
}
lock (_cacheLock)
{
return _localCache.FirstOrDefault(c => string.Equals(c.Id, id, StringComparison.OrdinalIgnoreCase)) is { } found
? Clone(found) : null;
}
}
// ── 新增 ──────────────────────────────────────────────────────────────
public async Task<bool> AddAsync(MesXslCustomer customer, CancellationToken ct = default)
{
if (!customer.TenantId.HasValue || customer.TenantId.Value <= 0)
customer.TenantId = DefaultTenantId;
var local = Clone(customer);
if (string.IsNullOrWhiteSpace(local.Id))
local.Id = $"local-{Guid.NewGuid():N}";
if (string.IsNullOrWhiteSpace(local.Status))
local.Status = "0";
SyncIzEnable(local);
if (_networkMonitor.IsOnline)
{
try
{
var ok = await RemoteAddAsync(local, ct).ConfigureAwait(false);
if (ok) { UpsertLocalCache(local); return true; }
return false;
}
catch (Exception ex)
{
_logger.Warning($"[客户新增] 远端失败,转离线入队:{ex.Message}");
}
}
EnqueuePendingOperation(new CustomerPendingOperation
{ OpType = CustomerOperationType.Add, CustomerId = local.Id, Customer = local });
UpsertLocalCache(local);
return true;
}
// ── 编辑 ──────────────────────────────────────────────────────────────
public async Task<bool> EditAsync(MesXslCustomer customer, CancellationToken ct = default)
{
if (!customer.TenantId.HasValue || customer.TenantId.Value <= 0)
customer.TenantId = DefaultTenantId;
var local = Clone(customer);
SyncIzEnable(local);
if (_networkMonitor.IsOnline)
{
try
{
var (ok, _) = await RemoteEditAsync(local, ct).ConfigureAwait(false);
if (ok) { UpsertLocalCache(local); return true; }
return false;
}
catch (Exception ex)
{
_logger.Warning($"[客户编辑] 远端失败,转离线入队:{ex.Message}");
}
}
EnqueuePendingOperation(new CustomerPendingOperation
{
OpType = CustomerOperationType.Edit,
CustomerId = local.Id,
Customer = local,
AnchorUpdateTime = local.UpdateTime
});
UpsertLocalCache(local);
return true;
}
// ── 删除 ──────────────────────────────────────────────────────────────
public async Task<bool> DeleteAsync(string id, CancellationToken ct = default)
{
if (_networkMonitor.IsOnline)
{
try
{
var ok = await RemoteDeleteAsync(id, ct).ConfigureAwait(false);
if (ok) { RemoveFromLocalCache(id); return true; }
return false;
}
catch (Exception ex)
{
_logger.Warning($"[客户删除] 远端失败,转离线入队:{ex.Message}");
}
}
DateTime? anchor;
lock (_cacheLock)
{
anchor = _localCache.FirstOrDefault(c => string.Equals(c.Id, id, StringComparison.OrdinalIgnoreCase))?.UpdateTime;
}
EnqueuePendingOperation(new CustomerPendingOperation
{
OpType = CustomerOperationType.Delete,
CustomerId = id,
AnchorUpdateTime = anchor
});
RemoveFromLocalCache(id);
return true;
}
// ── 状态切换 ──────────────────────────────────────────────────────────
public async Task<bool> UpdateStatusAsync(string id, string status, CancellationToken ct = default)
{
if (_networkMonitor.IsOnline)
{
try
{
var ok = await RemoteUpdateStatusAsync(id, status, ct).ConfigureAwait(false);
if (ok) { UpdateLocalStatus(id, status); return true; }
return false;
}
catch (Exception ex)
{
_logger.Warning($"[客户状态] 远端失败,转离线入队:{ex.Message}");
}
}
DateTime? anchor;
lock (_cacheLock)
{
anchor = _localCache.FirstOrDefault(c => string.Equals(c.Id, id, StringComparison.OrdinalIgnoreCase))?.UpdateTime;
}
EnqueuePendingOperation(new CustomerPendingOperation
{
OpType = CustomerOperationType.UpdateStatus,
CustomerId = id,
Status = status,
AnchorUpdateTime = anchor
});
UpdateLocalStatus(id, status);
return true;
}
// ── 远端调用 ──────────────────────────────────────────────────────────
private async Task<List<MesXslCustomer>> FetchRemoteListAsync(CancellationToken ct)
{
var query = HttpUtility.ParseQueryString(string.Empty);
query["pageNo"] = "1";
query["pageSize"] = "10000";
query["tenantId"] = DefaultTenantId.ToString();
var url = $"{BaseUrl}/xslmes/mesXslCustomer/anon/list?{query}";
using var client = CreateClient();
var resp = await client.GetAsync(url, ct).ConfigureAwait(false);
resp.EnsureSuccessStatusCode();
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
return doc.RootElement.GetProperty("result").GetProperty("records")
.Deserialize<List<MesXslCustomer>>(_jsonOpts) ?? new();
}
private async Task<bool> RemoteAddAsync(MesXslCustomer customer, CancellationToken ct)
{
var url = $"{BaseUrl}/xslmes/mesXslCustomer/anon/add?tenantId={DefaultTenantId}";
var payload = Clone(customer);
if (IsLocalTempId(payload.Id)) payload.Id = null;
return await PostJsonAsync(url, payload, ct).ConfigureAwait(false);
}
private async Task<(bool Ok, bool IsVersionConflict)> RemoteEditAsync(MesXslCustomer customer, CancellationToken ct)
{
var url = $"{BaseUrl}/xslmes/mesXslCustomer/anon/edit?tenantId={DefaultTenantId}";
return await PostJsonCheckVersionAsync(url, customer, ct).ConfigureAwait(false);
}
private async Task<bool> RemoteDeleteAsync(string id, CancellationToken ct)
{
var url = $"{BaseUrl}/xslmes/mesXslCustomer/anon/delete?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
var resp = await client.DeleteAsync(url, ct).ConfigureAwait(false);
return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
}
private async Task<bool> RemoteUpdateStatusAsync(string id, string status, CancellationToken ct)
{
var url = $"{BaseUrl}/xslmes/mesXslCustomer/anon/updateStatus?id={Uri.EscapeDataString(id)}&status={Uri.EscapeDataString(status)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
var resp = await client.PostAsync(url, null, ct).ConfigureAwait(false);
return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
}
private async Task<bool> PostJsonAsync(string url, object body, CancellationToken ct)
{
var content = new StringContent(JsonSerializer.Serialize(body, _jsonOpts), Encoding.UTF8, "application/json");
using var client = CreateClient();
var resp = await client.PostAsync(url, content, ct).ConfigureAwait(false);
return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
}
private async Task<(bool Ok, bool IsVersionConflict)> PostJsonCheckVersionAsync(string url, object body, CancellationToken ct)
{
var content = new StringContent(JsonSerializer.Serialize(body, _jsonOpts), Encoding.UTF8, "application/json");
using var client = CreateClient();
var resp = await client.PostAsync(url, content, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return (false, false);
try
{
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
int code = 200;
if (doc.RootElement.TryGetProperty("code", out var codeEl)) code = codeEl.GetInt32();
if (code == 200) return (true, false);
if (doc.RootElement.TryGetProperty("message", out var msgEl))
{
var msg = msgEl.GetString() ?? "";
if (msg.Contains("已被他人修改")) return (false, true);
}
return (false, false);
}
catch { return (true, false); }
}
private static async Task<bool> IsSuccessResultAsync(HttpResponseMessage resp, CancellationToken ct)
{
try
{
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("code", out var code)) return code.GetInt32() == 200;
if (doc.RootElement.TryGetProperty("success", out var success)) return success.GetBoolean();
return true;
}
catch { return true; }
}
// ── 断线续连 ──────────────────────────────────────────────────────────
private void OnNetworkStatusChanged(bool isOnline)
{
if (!isOnline) return;
_ = Task.Run(() => SyncAfterReconnectAsync(CancellationToken.None));
}
private async Task SyncAfterReconnectAsync(CancellationToken ct)
{
var pushResult = await PushPendingOnReconnectAsync(ct).ConfigureAwait(false);
if (!_networkMonitor.IsOnline) return;
try
{
var remote = await FetchRemoteListAsync(ct).ConfigureAwait(false);
lock (_cacheLock)
{
_localCache = remote.Select(Clone).ToList();
SaveCacheToDiskUnsafe();
}
_eventAggregator.GetEvent<CustomerChangedEvent>()
.Publish(new CustomerChangedPayload { Action = "pull" });
_logger.Information($"[客户重连] 全量回拉成功 count={remote.Count}");
}
catch (Exception ex)
{
_logger.Warning($"[客户重连] 全量回拉失败:{ex.Message}");
}
var hasActivity = pushResult.PushedCount > 0
|| pushResult.ConflictCount > 0
|| pushResult.NewRecordsPushed > 0;
if (hasActivity)
{
_eventAggregator.GetEvent<SyncConflictEvent>()
.Publish(new SyncConflictPayload
{
EntityName = "客户",
PushedCount = pushResult.PushedCount,
ConflictCount = pushResult.ConflictCount,
NewRecordsPushed = pushResult.NewRecordsPushed
});
}
}
private async Task<PushPendingResult> PushPendingOnReconnectAsync(CancellationToken ct)
{
if (!await _syncLock.WaitAsync(0, ct).ConfigureAwait(false))
return new PushPendingResult(0, 0, 0);
try
{
List<CustomerPendingOperation> snapshot;
lock (_cacheLock) { snapshot = _pendingOps.OrderBy(x => x.CreatedAt).ToList(); }
_logger.Information($"[客户回放] pending={snapshot.Count}");
int pushed = 0, conflicts = 0, newPushed = 0;
foreach (var op in snapshot)
{
if (!_networkMonitor.IsOnline) break;
// 如果该 op 已在上一条冲突处理中被清理,则跳过
lock (_cacheLock)
{
if (!_pendingOps.Any(x => x.Id == op.Id)) continue;
}
var result = await ExecutePendingOpWithConflictAsync(op, ct).ConfigureAwait(false);
if (!result.Ok)
{
lock (_cacheLock)
{
op.RetryCount++;
if (op.RetryCount >= MaxPendingRetries)
{
_logger.Warning($"[客户回放] op={op.OpType} 超过最大重试次数({MaxPendingRetries}),放弃 customerId={op.CustomerId}");
_pendingOps.RemoveAll(x => x.Id == op.Id);
SavePendingOpsToDiskUnsafe();
continue;
}
SavePendingOpsToDiskUnsafe();
}
break;
}
if (result.IsConflict)
{
conflicts++;
// 冲突时:以服务器版本为准,直接丢弃同一条记录的所有 pending
if (!string.IsNullOrWhiteSpace(result.EntityId))
RemovePendingOpsByCustomerId(result.EntityId);
}
else if (op.OpType == CustomerOperationType.Add)
{
newPushed++;
lock (_cacheLock)
{
_pendingOps.RemoveAll(x => x.Id == op.Id);
SavePendingOpsToDiskUnsafe();
}
}
else
{
pushed++;
lock (_cacheLock)
{
_pendingOps.RemoveAll(x => x.Id == op.Id);
SavePendingOpsToDiskUnsafe();
}
}
}
return new PushPendingResult(pushed, conflicts, newPushed);
}
finally { _syncLock.Release(); }
}
private sealed record PendingReplayResult(bool Ok, bool IsConflict, string? EntityId);
private async Task<PendingReplayResult> ExecutePendingOpWithConflictAsync(CustomerPendingOperation op, CancellationToken ct)
{
try
{
return op.OpType switch
{
CustomerOperationType.Add => await ExecuteAddAsync(op, ct).ConfigureAwait(false),
CustomerOperationType.Edit => await ExecuteEditWithConflictAsync(op, ct).ConfigureAwait(false),
CustomerOperationType.Delete => await ExecuteDeleteWithConflictAsync(op, ct).ConfigureAwait(false),
CustomerOperationType.UpdateStatus => await ExecuteUpdateStatusWithConflictAsync(op, ct).ConfigureAwait(false),
_ => new PendingReplayResult(true, false, null)
};
}
catch (Exception ex)
{
_logger.Warning($"[客户回放] 执行失败 op={op.OpType}{ex.Message}");
return new PendingReplayResult(false, false, null);
}
}
private async Task<PendingReplayResult> ExecuteAddAsync(CustomerPendingOperation op, CancellationToken ct)
{
var ok = op.Customer != null && await RemoteAddAsync(op.Customer, ct).ConfigureAwait(false);
return ok
? new PendingReplayResult(true, false, op.CustomerId)
: new PendingReplayResult(false, false, null);
}
private async Task<PendingReplayResult> ExecuteEditWithConflictAsync(CustomerPendingOperation op, CancellationToken ct)
{
var id = op.Customer?.Id;
if (string.IsNullOrWhiteSpace(id))
return new PendingReplayResult(false, false, null);
// 冲突检测:服务器 UpdateTime != 本地 AnchorUpdateTime
var remote = await FetchRemoteSingleAsync(id!, ct).ConfigureAwait(false);
if (remote != null && op.AnchorUpdateTime != null && remote.UpdateTime != op.AnchorUpdateTime)
{
UpsertLocalCache(remote);
return new PendingReplayResult(true, true, id);
}
var (ok, isVersionConflict) = await RemoteEditAsync(op.Customer!, ct).ConfigureAwait(false);
if (isVersionConflict)
{
var fresh = await FetchRemoteSingleAsync(id!, ct).ConfigureAwait(false);
if (fresh != null) UpsertLocalCache(fresh);
return new PendingReplayResult(true, true, id);
}
return ok
? new PendingReplayResult(true, false, id)
: new PendingReplayResult(false, false, null);
}
private async Task<PendingReplayResult> ExecuteDeleteWithConflictAsync(CustomerPendingOperation op, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(op.CustomerId))
return new PendingReplayResult(false, false, null);
var id = op.CustomerId!;
var remote = await FetchRemoteSingleAsync(id, ct).ConfigureAwait(false);
if (remote == null)
{
// 后端已不存在:删除无需操作,也视为“成功清理 pending”
return new PendingReplayResult(true, false, id);
}
if (op.AnchorUpdateTime != null && remote.UpdateTime != op.AnchorUpdateTime)
{
// 冲突:服务器版本获胜,恢复到服务器版本
UpsertLocalCache(remote);
return new PendingReplayResult(true, true, id);
}
var ok = await RemoteDeleteAsync(id, ct).ConfigureAwait(false);
return ok
? new PendingReplayResult(true, false, id)
: new PendingReplayResult(false, false, null);
}
private async Task<PendingReplayResult> ExecuteUpdateStatusWithConflictAsync(CustomerPendingOperation op, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(op.CustomerId) || string.IsNullOrWhiteSpace(op.Status))
return new PendingReplayResult(false, false, null);
var id = op.CustomerId!;
var remote = await FetchRemoteSingleAsync(id, ct).ConfigureAwait(false);
if (remote != null && op.AnchorUpdateTime != null && remote.UpdateTime != op.AnchorUpdateTime)
{
UpsertLocalCache(remote);
return new PendingReplayResult(true, true, id);
}
var ok = await RemoteUpdateStatusAsync(id, op.Status!, ct).ConfigureAwait(false);
return ok
? new PendingReplayResult(true, false, id)
: new PendingReplayResult(false, false, null);
}
private void RemovePendingOpsByCustomerId(string customerId)
{
lock (_cacheLock)
{
_pendingOps.RemoveAll(x =>
(x.CustomerId != null && string.Equals(x.CustomerId, customerId, StringComparison.OrdinalIgnoreCase)) ||
(x.Customer?.Id != null && string.Equals(x.Customer.Id, customerId, StringComparison.OrdinalIgnoreCase)));
SavePendingOpsToDiskUnsafe();
}
}
private async Task<MesXslCustomer?> FetchRemoteSingleAsync(string id, CancellationToken ct)
{
try
{
var url = $"{BaseUrl}/xslmes/mesXslCustomer/anon/queryById?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
var resp = await client.GetAsync(url, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return null;
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("result", out var resultEl))
return resultEl.Deserialize<MesXslCustomer>(_jsonOpts);
return null;
}
catch
{
return null;
}
}
// ── 本地缓存操作 ──────────────────────────────────────────────────────
private static List<MesXslCustomer> ApplyFilters(List<MesXslCustomer> source,
string? customerCode, string? customerName, string? status, string? customerRegion)
{
IEnumerable<MesXslCustomer> q = source;
if (!string.IsNullOrWhiteSpace(customerCode))
q = q.Where(c => (c.CustomerCode ?? "").Contains(customerCode, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(customerName))
q = q.Where(c => (c.CustomerName ?? "").Contains(customerName, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(status))
q = q.Where(c => string.Equals(c.Status, status, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(customerRegion))
q = q.Where(c => string.Equals(c.CustomerRegion, customerRegion, StringComparison.OrdinalIgnoreCase));
return q.OrderByDescending(c => c.CreateTime ?? DateTime.MinValue).ToList();
}
private List<MesXslCustomer> ApplyPendingOpsSnapshotUnsafe(List<MesXslCustomer> source)
{
var map = source.Where(c => !string.IsNullOrWhiteSpace(c.Id))
.ToDictionary(c => c.Id!, Clone, StringComparer.OrdinalIgnoreCase);
foreach (var op in _pendingOps.OrderBy(x => x.CreatedAt))
{
switch (op.OpType)
{
case CustomerOperationType.Add:
case CustomerOperationType.Edit:
if (op.Customer?.Id != null) map[op.Customer.Id] = Clone(op.Customer);
break;
case CustomerOperationType.Delete:
if (op.CustomerId != null) map.Remove(op.CustomerId);
break;
case CustomerOperationType.UpdateStatus:
if (op.CustomerId != null && op.Status != null && map.TryGetValue(op.CustomerId, out var c))
{
c.Status = op.Status;
SyncIzEnable(c);
}
break;
}
}
return map.Values.ToList();
}
private void EnqueuePendingOperation(CustomerPendingOperation op)
{
lock (_cacheLock) { _pendingOps.Add(op); SavePendingOpsToDiskUnsafe(); }
}
private void UpsertLocalCache(MesXslCustomer customer)
{
lock (_cacheLock)
{
var idx = _localCache.FindIndex(c => string.Equals(c.Id, customer.Id, StringComparison.OrdinalIgnoreCase));
if (idx >= 0) _localCache[idx] = Clone(customer);
else _localCache.Insert(0, Clone(customer));
SaveCacheToDiskUnsafe();
}
}
private void RemoveFromLocalCache(string id)
{
lock (_cacheLock)
{
_localCache.RemoveAll(c => string.Equals(c.Id, id, StringComparison.OrdinalIgnoreCase));
SaveCacheToDiskUnsafe();
}
}
private void UpdateLocalStatus(string id, string status)
{
lock (_cacheLock)
{
var item = _localCache.FirstOrDefault(c => string.Equals(c.Id, id, StringComparison.OrdinalIgnoreCase));
if (item != null) { item.Status = status; SyncIzEnable(item); SaveCacheToDiskUnsafe(); }
}
}
private void LoadPendingOpsFromDisk()
{
try
{
if (!File.Exists(_pendingOpsFilePath)) return;
_pendingOps = JsonSerializer.Deserialize<List<CustomerPendingOperation>>(
File.ReadAllText(_pendingOpsFilePath), _jsonOpts) ?? new();
}
catch { _pendingOps = new(); }
}
private void LoadCacheFromDisk()
{
try
{
if (!File.Exists(_cacheFilePath)) return;
_localCache = JsonSerializer.Deserialize<List<MesXslCustomer>>(
File.ReadAllText(_cacheFilePath), _jsonOpts) ?? new();
}
catch { _localCache = new(); }
}
private void SavePendingOpsToDiskUnsafe() =>
File.WriteAllText(_pendingOpsFilePath, JsonSerializer.Serialize(_pendingOps, _jsonOpts));
private void SaveCacheToDiskUnsafe() =>
File.WriteAllText(_cacheFilePath, JsonSerializer.Serialize(_localCache, _jsonOpts));
// ── 辅助方法 ──────────────────────────────────────────────────────────
// status "0"启用 → izEnable=1status "1"停用 → izEnable=0
private static void SyncIzEnable(MesXslCustomer c) =>
c.IzEnable = c.Status == "1" ? 0 : 1;
private static bool IsLocalTempId(string? id) =>
!string.IsNullOrWhiteSpace(id) && id.StartsWith("local-", StringComparison.OrdinalIgnoreCase);
private static MesXslCustomer Clone(MesXslCustomer c) => new()
{
Id = c.Id, CustomerCode = c.CustomerCode, CustomerName = c.CustomerName,
CustomerShortName = c.CustomerShortName, CustomerRegion = c.CustomerRegion,
ErpCode = c.ErpCode, Status = c.Status, IzEnable = c.IzEnable,
CustomerDesc = c.CustomerDesc, TenantId = c.TenantId,
CreateBy = c.CreateBy, CreateTime = c.CreateTime,
UpdateBy = c.UpdateBy, UpdateTime = c.UpdateTime, SysOrgCode = c.SysOrgCode
};
// ── 内部类型 ──────────────────────────────────────────────────────────
private sealed class CustomerPendingOperation
{
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public CustomerOperationType OpType { get; set; }
public string? CustomerId { get; set; }
public string? Status { get; set; }
public MesXslCustomer? Customer { get; set; }
// 冲突检测用的版本锚点:当本地首次针对该记录产生修改时,记录当时的服务器 UpdateTime
public DateTime? AnchorUpdateTime { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public int RetryCount { get; set; } = 0;
}
private enum CustomerOperationType { Add = 1, Edit = 2, Delete = 3, UpdateStatus = 4 }
private sealed class NullableDateTimeJsonConverter : JsonConverter<DateTime?>
{
private static readonly string[] Formats =
[
"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:ss.fffZ"
];
public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null) return null;
if (reader.TokenType == JsonTokenType.String)
{
var raw = reader.GetString();
if (string.IsNullOrWhiteSpace(raw)) return null;
if (DateTime.TryParseExact(raw, Formats, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeLocal, out var dt)) return dt;
if (DateTime.TryParse(raw, out var fb)) return fb;
}
throw new JsonException($"无法转换为 DateTime?token={reader.TokenType}");
}
public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
{
if (value.HasValue) writer.WriteStringValue(value.Value.ToString("yyyy-MM-dd HH:mm:ss"));
else writer.WriteNullValue();
}
}
}

View File

@@ -0,0 +1,60 @@
using Prism.Events;
using System.Text.Json;
using YY.Admin.Core;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
namespace YY.Admin.Services.Service.Customer;
public class CustomerSyncCoordinator : ISingletonDependency
{
private readonly IEventAggregator _eventAggregator;
private readonly ILoggerService _logger;
public CustomerSyncCoordinator(IEventAggregator eventAggregator, ILoggerService logger)
{
_eventAggregator = eventAggregator;
_logger = logger;
_eventAggregator.GetEvent<RemoteCommandReceivedEvent>()
.Subscribe(OnRemoteCommand, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<NetworkStatusChangedEvent>()
.Subscribe(OnNetworkStatusChanged, ThreadOption.BackgroundThread);
_logger.Information("[客户推送] CustomerSyncCoordinator 已启动");
}
private void OnNetworkStatusChanged(NetworkStatusChangedPayload payload)
{
if (!payload.IsOnline) return;
_logger.Information("[客户推送] 网络恢复,触发补偿刷新");
_eventAggregator.GetEvent<CustomerChangedEvent>()
.Publish(new CustomerChangedPayload { Action = "reconnect" });
}
private void OnRemoteCommand(RemoteCommandPayload payload)
{
try
{
var json = payload.CommandJson ?? string.Empty;
if (string.IsNullOrWhiteSpace(json)) return;
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("cmd", out var cmdEl)) return;
if (!cmdEl.GetString().Equals("MES_CUSTOMER_CHANGED", StringComparison.OrdinalIgnoreCase)) return;
doc.RootElement.TryGetProperty("action", out var actionEl);
doc.RootElement.TryGetProperty("customerId", out var idEl);
var changed = new CustomerChangedPayload
{
Action = actionEl.GetString() ?? string.Empty,
CustomerId = idEl.ValueKind == JsonValueKind.String ? idEl.GetString() : null
};
_logger.Information($"[客户推送] action={changed.Action}, customerId={changed.CustomerId}");
_eventAggregator.GetEvent<CustomerChangedEvent>().Publish(changed);
}
catch (Exception ex)
{
_logger.Warning($"[客户推送] 处理STOMP命令失败{ex.Message}");
}
}
}

View File

@@ -8,4 +8,9 @@ public interface IJeecgDictSyncService
/// 从 Jeecg 后端同步数据字典到本地同构表
/// </summary>
Task<int> SyncFromJeecgAsync();
/// <summary>
/// 从桌面端本地字典镜像表读取指定字典编码的选项。
/// </summary>
Task<List<KeyValuePair<string, string>>> GetDictOptionsAsync(string dictCode, bool includeAll = false);
}

View File

@@ -164,6 +164,37 @@ public class JeecgDictSyncService : IJeecgDictSyncService, ISingletonDependency
return synced;
}
public async Task<List<KeyValuePair<string, string>>> GetDictOptionsAsync(string dictCode, bool includeAll = false)
{
var result = new List<KeyValuePair<string, string>>();
if (includeAll)
{
result.Add(new KeyValuePair<string, string>("全部", ""));
}
if (string.IsNullOrWhiteSpace(dictCode))
{
return result;
}
var rows = await _dbContext.Queryable<JeecgSysDictItem>()
.ClearFilter()
.Where(x => x.DictCode == dictCode)
.Where(x => x.Status == null || x.Status == 1)
.OrderBy(x => SqlFunc.IsNull(x.SortOrder, 0))
.OrderBy(x => SqlFunc.Asc(x.ItemValue))
.ToListAsync();
foreach (var row in rows)
{
if (string.IsNullOrWhiteSpace(row.ItemValue))
{
continue;
}
result.Add(new KeyValuePair<string, string>(row.ItemText ?? row.ItemValue, row.ItemValue));
}
return result;
}
private static string? GetString(JsonElement row, string propertyName)
{
if (!row.TryGetProperty(propertyName, out var el))

View File

@@ -20,6 +20,7 @@ public class JeecgUserSyncCoordinator : IJeecgUserSyncCoordinator, ISingletonDep
private CancellationTokenSource? _cts;
private readonly object _lifecycleLock = new();
private SubscriptionToken? _remoteCommandSubscription;
private SubscriptionToken? _networkStatusSubscription;
public JeecgUserSyncCoordinator(
IConfiguration configuration,
@@ -52,7 +53,9 @@ public class JeecgUserSyncCoordinator : IJeecgUserSyncCoordinator, ISingletonDep
{
CancelAndDisposeCts();
UnsubscribeRemoteCommand();
UnsubscribeNetworkStatus();
_remoteCommandSubscription = _eventAggregator.GetEvent<RemoteCommandReceivedEvent>().Subscribe(OnRemoteCommand, ThreadOption.BackgroundThread);
_networkStatusSubscription = _eventAggregator.GetEvent<NetworkStatusChangedEvent>().Subscribe(OnNetworkStatusChanged, ThreadOption.BackgroundThread);
_cts = new CancellationTokenSource();
token = _cts.Token;
@@ -83,6 +86,7 @@ public class JeecgUserSyncCoordinator : IJeecgUserSyncCoordinator, ISingletonDep
lock (_lifecycleLock)
{
UnsubscribeRemoteCommand();
UnsubscribeNetworkStatus();
CancelAndDisposeCts();
}
}
@@ -115,6 +119,36 @@ public class JeecgUserSyncCoordinator : IJeecgUserSyncCoordinator, ISingletonDep
}
}
private void UnsubscribeNetworkStatus()
{
if (_networkStatusSubscription != null)
{
_eventAggregator.GetEvent<NetworkStatusChangedEvent>().Unsubscribe(_networkStatusSubscription);
_networkStatusSubscription = null;
}
}
private void OnNetworkStatusChanged(NetworkStatusChangedPayload payload)
{
if (payload is null || !payload.IsOnline)
{
return;
}
try
{
_logger.Information("检测到网络恢复,入队一次用户全量拉取(断线重连补偿)。");
_ = _mirrorOutbox.EnqueuePullAsync(
JeecgUserMirrorOutbox.EventBoot,
"{\"reason\":\"network-reconnected\"}",
CancellationToken.None);
}
catch (Exception ex)
{
_logger.Warning($"网络恢复后入队用户同步失败: {ex.Message}");
}
}
private void CancelAndDisposeCts()
{
try

View File

@@ -1,13 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YY.Admin.Core;
using YY.Admin.Services;
namespace YY.Admin.Services.Service.Menu
namespace YY.Admin.Services.Service.Menu;
public interface ISysMenuService
{
public interface ISysMenuService
{
Task<List<MenuOutput>> GetLoginMenuTree();
}
Task<List<MenuOutput>> GetLoginMenuTree();
/// <summary>
/// 菜单管理:加载全部菜单(含按钮类型),按排序与 Id 排序
/// </summary>
Task<List<SysMenu>> GetAllMenusForManageAsync();
/// <summary>
/// 新增菜单并可选关联当前用户租户
/// </summary>
Task<(bool ok, string message, long id)> CreateMenuAsync(SysMenu input);
/// <summary>
/// 更新菜单
/// </summary>
Task<(bool ok, string message)> UpdateMenuAsync(SysMenu input);
/// <summary>
/// 删除菜单(无子节点时)
/// </summary>
Task<(bool ok, string message)> DeleteMenuAsync(long id);
}

View File

@@ -1,10 +1,6 @@
using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YY.Admin.Core;
using YY.Admin.Core.Session;
using YY.Admin.Services.Service.Role;
using YY.Admin.Services.Service.User;
@@ -132,5 +128,137 @@ namespace YY.Admin.Services.Service.Menu
.ToTreeAsync(u => u.Children, u => u.Pid, 0);
}
/// <inheritdoc />
public async Task<List<SysMenu>> GetAllMenusForManageAsync()
{
return await _dbContext.Queryable<SysMenu>()
.OrderBy(m => m.OrderNo)
.OrderBy(m => m.Id)
.ToListAsync();
}
/// <inheritdoc />
public async Task<(bool ok, string message, long id)> CreateMenuAsync(SysMenu input)
{
if (string.IsNullOrWhiteSpace(input.Title))
return (false, "菜单名称不能为空", 0);
var all = await GetAllMenusForManageAsync();
if (input.Pid != 0 && all.All(m => m.Id != input.Pid))
return (false, "父级菜单不存在", 0);
var id = SnowflakeId.Next();
input.Id = id;
input.CreateTime = DateTime.Now;
input.UpdateTime = null;
input.Children = new List<SysMenu>();
var n = await _dbContext.Insertable(input).ExecuteCommandAsync();
if (n <= 0)
return (false, "保存失败", 0);
await TryLinkCurrentTenantMenuAsync(id);
return (true, "保存成功", id);
}
/// <inheritdoc />
public async Task<(bool ok, string message)> UpdateMenuAsync(SysMenu input)
{
if (input.Id <= 0)
return (false, "无效的菜单 Id");
if (string.IsNullOrWhiteSpace(input.Title))
return (false, "菜单名称不能为空");
var all = await GetAllMenusForManageAsync();
var existing = all.FirstOrDefault(m => m.Id == input.Id);
if (existing == null)
return (false, "菜单不存在");
if (input.Pid != 0 && all.All(m => m.Id != input.Pid))
return (false, "父级菜单不存在");
if (NewParentIsInsideMenuSubtree(input.Id, input.Pid, all))
return (false, "不能将父级设为当前菜单或其子菜单");
existing.Pid = input.Pid;
existing.Type = input.Type;
existing.Name = input.Name;
existing.Path = input.Path;
existing.Component = input.Component;
existing.Redirect = input.Redirect;
existing.Permission = input.Permission;
existing.Title = input.Title.Trim();
existing.Icon = input.Icon;
existing.IsIframe = input.IsIframe;
existing.OutLink = input.OutLink;
existing.IsHide = input.IsHide;
existing.IsKeepAlive = input.IsKeepAlive;
existing.IsAffix = input.IsAffix;
existing.OrderNo = input.OrderNo;
existing.Status = input.Status;
existing.Remark = input.Remark;
existing.UpdateTime = DateTime.Now;
var n = await _dbContext.Updateable(existing).ExecuteCommandAsync();
return n > 0 ? (true, "保存成功") : (false, "更新失败");
}
/// <inheritdoc />
public async Task<(bool ok, string message)> DeleteMenuAsync(long id)
{
if (id <= 0)
return (false, "无效的菜单 Id");
var childCount = await _dbContext.Queryable<SysMenu>().Where(m => m.Pid == id).CountAsync();
if (childCount > 0)
return (false, "存在子菜单,请先删除子节点");
await _dbContext.Deleteable<SysRoleMenu>().Where(r => r.MenuId == id).ExecuteCommandAsync();
await _dbContext.Deleteable<SysTenantMenu>().Where(t => t.MenuId == id).ExecuteCommandAsync();
var n = await _dbContext.Deleteable<SysMenu>().Where(m => m.Id == id).ExecuteCommandAsync();
return n > 0 ? (true, "已删除") : (false, "删除失败");
}
private async Task TryLinkCurrentTenantMenuAsync(long menuId)
{
var tenantId = AppSession.CurrentUser?.TenantId;
if (tenantId == null || tenantId <= 0)
return;
var exists = await _dbContext.Queryable<SysTenantMenu>()
.AnyAsync(t => t.TenantId == tenantId && t.MenuId == menuId);
if (exists)
return;
await _dbContext.Insertable(new SysTenantMenu
{
Id = SnowflakeId.Next(),
TenantId = tenantId.Value,
MenuId = menuId
}).ExecuteCommandAsync();
}
/// <summary>
/// 判断 newPid 是否位于以 menuId 为根的子树内(含自身),用于防止环状父级
/// </summary>
private static bool NewParentIsInsideMenuSubtree(long menuId, long newPid, List<SysMenu> all)
{
if (newPid == 0)
return false;
if (newPid == menuId)
return true;
var cur = all.FirstOrDefault(x => x.Id == newPid);
for (var i = 0; i < 5000 && cur != null; i++)
{
if (cur.Pid == menuId)
return true;
if (cur.Pid == 0)
return false;
cur = all.FirstOrDefault(x => x.Id == cur.Pid);
}
return false;
}
}
}

View File

@@ -0,0 +1,685 @@
using Microsoft.Extensions.Configuration;
using Prism.Events;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Web;
using YY.Admin.Core;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
namespace YY.Admin.Services.Service.Supplier;
public class SupplierService : ISupplierService, ISingletonDependency
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
private readonly INetworkMonitor _networkMonitor;
private readonly IEventAggregator _eventAggregator;
private readonly ILoggerService _logger;
private readonly object _cacheLock = new();
private readonly string _cacheFilePath;
private readonly string _pendingFilePath;
private List<MesXslSupplier> _localCache = new();
private const int MaxPendingRetries = 5;
// 断开期间被本地修改的条目(含版本锚点),重连后推送到后端
private readonly HashSet<string> _pendingLocalModifiedIds = new(StringComparer.OrdinalIgnoreCase);
// 断开期间被本地删除的条目
private readonly HashSet<string> _pendingLocalDeletedIds = new(StringComparer.OrdinalIgnoreCase);
// 版本锚点:最后一次从后端同步时该条目的 UpdateTime用于冲突检测
private readonly Dictionary<string, DateTime?> _anchors = new(StringComparer.OrdinalIgnoreCase);
// 每条待推送记录的重试次数,超过上限后放弃
private readonly Dictionary<string, int> _pendingRetryCount = new(StringComparer.OrdinalIgnoreCase);
private static readonly JsonSerializerOptions _jsonOpts = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new NullableDateTimeJsonConverter() }
};
public SupplierService(
IHttpClientFactory httpClientFactory,
IConfiguration configuration,
INetworkMonitor networkMonitor,
IEventAggregator eventAggregator,
ILoggerService logger)
{
_httpClientFactory = httpClientFactory;
_configuration = configuration;
_networkMonitor = networkMonitor;
_eventAggregator = eventAggregator;
_logger = logger;
var appDataDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"YY.Admin", "sync-cache");
Directory.CreateDirectory(appDataDir);
_cacheFilePath = Path.Combine(appDataDir, "mes-xsl-supplier-cache.json");
_pendingFilePath = Path.Combine(appDataDir, "mes-xsl-supplier-pending.json");
LoadCacheFromDisk();
LoadPendingFromDisk();
}
// ── 配置 ──────────────────────────────────────────────────────────────────
private string BaseUrl =>
(_configuration.GetValue<string>("JeecgIntegration:BaseUrl") ?? "http://localhost:8080/jeecg-boot").TrimEnd('/');
private int DefaultTenantId =>
(int?)_configuration.GetValue<long?>("JeecgIntegration:DefaultTenantId") ?? 1002;
private HttpClient CreateClient() => _httpClientFactory.CreateClient("JeecgApi");
// ── 公开接口 ──────────────────────────────────────────────────────────────
public async Task<SupplierPageResult> PageAsync(
int pageNo, int pageSize,
string? supplierCode = null, string? supplierName = null,
string? supplierShortName = null, string? erpCode = null,
string? status = null, CancellationToken ct = default)
{
List<MesXslSupplier> source;
try
{
source = _networkMonitor.IsOnline
? await FetchRemoteListAsync(ct).ConfigureAwait(false)
: GetCacheSnapshot();
lock (_cacheLock)
{
MergeIntoCache(source);
SaveCacheToDiskUnsafe();
}
source = GetCacheSnapshot();
}
catch
{
source = GetCacheSnapshot();
}
IEnumerable<MesXslSupplier> q = source;
if (!string.IsNullOrWhiteSpace(supplierCode))
q = q.Where(x => (x.SupplierCode ?? "").Contains(supplierCode, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(supplierName))
q = q.Where(x => (x.SupplierName ?? "").Contains(supplierName, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(supplierShortName))
q = q.Where(x => (x.SupplierShortName ?? "").Contains(supplierShortName, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(erpCode))
q = q.Where(x => (x.ErpCode ?? "").Contains(erpCode, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(status))
q = q.Where(x => string.Equals(x.Status, status, StringComparison.OrdinalIgnoreCase));
var ordered = q.OrderByDescending(x => x.CreateTime ?? DateTime.MinValue).ToList();
var total = ordered.Count;
var records = ordered.Skip(Math.Max(0, (pageNo - 1) * pageSize)).Take(pageSize).ToList();
return new SupplierPageResult(records, total, pageNo, pageSize);
}
public async Task<MesXslSupplier?> GetByIdAsync(string id, CancellationToken ct = default)
{
// 有本地待同步改动时优先返回本地版本,避免编辑弹窗被后端旧版本覆盖
if (_networkMonitor.IsOnline && !_pendingLocalModifiedIds.Contains(id))
{
var url = $"{BaseUrl}/xslmes/mesXslSupplier/anon/queryById?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
var resp = await client.GetAsync(url, ct).ConfigureAwait(false);
if (resp.IsSuccessStatusCode)
{
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("result", out var resultEl))
return resultEl.Deserialize<MesXslSupplier>(_jsonOpts);
}
}
return GetCacheSnapshot().FirstOrDefault(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase));
}
public Task<bool> AddAsync(MesXslSupplier supplier, CancellationToken ct = default) =>
PostAndRefreshAsync(
$"{BaseUrl}/xslmes/mesXslSupplier/anon/add?tenantId={DefaultTenantId}",
supplier, "add", supplier.Id, ct);
public Task<bool> EditAsync(MesXslSupplier supplier, CancellationToken ct = default) =>
PostAndRefreshAsync(
$"{BaseUrl}/xslmes/mesXslSupplier/anon/edit?tenantId={DefaultTenantId}",
supplier, "edit", supplier.Id, ct);
public async Task<bool> DeleteAsync(string id, CancellationToken ct = default)
{
using var client = CreateClient();
var url = $"{BaseUrl}/xslmes/mesXslSupplier/anon/delete?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
var resp = await client.DeleteAsync(url, ct).ConfigureAwait(false);
if (IsDisconnectedResponse(resp))
{
var anchor = GetCacheSnapshot()
.FirstOrDefault(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase))?.UpdateTime;
RemoveFromLocalCache(id);
MarkLocalDeleted(id, anchor);
_eventAggregator.GetEvent<SupplierChangedEvent>()
.Publish(new SupplierChangedPayload { Action = "delete", SupplierId = id });
return true;
}
var ok = resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
if (ok)
{
RemoveFromLocalCache(id);
ClearPending(id);
_eventAggregator.GetEvent<SupplierChangedEvent>()
.Publish(new SupplierChangedPayload { Action = "delete", SupplierId = id });
}
return ok;
}
public async Task<bool> UpdateStatusAsync(string id, string status, CancellationToken ct = default)
{
using var client = CreateClient();
var url = $"{BaseUrl}/xslmes/mesXslSupplier/anon/updateStatus?id={Uri.EscapeDataString(id)}&status={Uri.EscapeDataString(status)}&tenantId={DefaultTenantId}";
var resp = await client.PostAsync(url, null, ct).ConfigureAwait(false);
if (IsDisconnectedResponse(resp))
{
var anchor = GetCacheSnapshot()
.FirstOrDefault(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase))?.UpdateTime;
UpdateLocalStatus(id, status);
MarkLocalModified(id, anchor);
_eventAggregator.GetEvent<SupplierChangedEvent>()
.Publish(new SupplierChangedPayload { Action = "status", SupplierId = id });
return true;
}
var ok = resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
if (ok)
{
UpdateLocalStatus(id, status);
ClearPending(id);
_eventAggregator.GetEvent<SupplierChangedEvent>()
.Publish(new SupplierChangedPayload { Action = "status", SupplierId = id });
}
return ok;
}
/// <summary>
/// 重连后将离线期间的本地改动推送到后端,并检测冲突。
/// 调用方应在此方法完成后再触发 UI 刷新,确保页面看到的是推送结果。
/// </summary>
public async Task<PushPendingResult> PushPendingOnReconnectAsync(CancellationToken ct = default)
{
int pushed = 0, conflicts = 0, newPushed = 0;
// ── 1. 推送离线期间修改的现有记录 ─────────────────────────────────────
foreach (var id in new List<string>(_pendingLocalModifiedIds))
{
try
{
var local = GetCacheSnapshot()
.FirstOrDefault(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase));
if (local == null) { ClearPending(id); continue; }
var remote = await FetchRemoteSingleAsync(id, ct);
if (remote != null && HasConflict(id, remote.UpdateTime))
{
// 后端也改了 → 后端版本获胜MES 多用户安全策略)
UpsertLocalCache(remote);
ClearPending(id);
conflicts++;
_logger.Warning($"[供应商同步] 冲突:{local.SupplierName}{id}),后端版本获胜");
}
else
{
// 仅本地改了 → 安全推送
var (ok, isVersionConflict) = await PushEditAsync(local, ct);
if (isVersionConflict)
{
var fresh = await FetchRemoteSingleAsync(id, ct);
if (fresh != null) UpsertLocalCache(fresh);
ClearPending(id);
conflicts++;
_logger.Warning($"[供应商同步] 服务端版本冲突:{local.SupplierName}{id}),后端版本获胜");
}
else if (ok)
{
ClearPending(id);
pushed++;
_logger.Information($"[供应商同步] 推送成功:{local.SupplierName}{id}");
}
else
{
_pendingRetryCount.TryGetValue(id, out var retries);
retries++;
if (retries >= MaxPendingRetries)
{
_logger.Warning($"[供应商同步] 推送超过最大重试次数({MaxPendingRetries}),放弃:{id}");
ClearPending(id);
}
else
{
_pendingRetryCount[id] = retries;
_logger.Warning($"[供应商同步] 推送失败,下次重连重试({retries}/{MaxPendingRetries}){id}");
}
}
}
}
catch (Exception ex)
{
_logger.Warning($"[供应商同步] 处理修改记录 {id} 时异常:{ex.Message}");
}
}
// ── 2. 推送离线期间删除的记录 ──────────────────────────────────────────
foreach (var id in new List<string>(_pendingLocalDeletedIds))
{
try
{
var remote = await FetchRemoteSingleAsync(id, ct);
if (remote == null) { ClearPending(id); continue; } // 后端已不存在,无需操作
if (HasConflict(id, remote.UpdateTime))
{
// 后端改动了但本地要删 → 保守策略:后端版本获胜,恢复到本地
UpsertLocalCache(remote);
ClearPending(id);
conflicts++;
_logger.Warning($"[供应商同步] 冲突:删除操作与后端改动冲突,已恢复记录 {id}");
}
else
{
if (await PushDeleteAsync(id, ct))
{
ClearPending(id);
pushed++;
}
else
{
_logger.Warning($"[供应商同步] 删除推送失败,下次重连重试:{id}");
}
}
}
catch (Exception ex)
{
_logger.Warning($"[供应商同步] 处理删除记录 {id} 时异常:{ex.Message}");
}
}
// ── 3. 推送离线期间新增的 local- 记录 ─────────────────────────────────
var localOnlyRecords = GetCacheSnapshot()
.Where(x => (x.Id ?? "").StartsWith("local-", StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var record in localOnlyRecords)
{
try
{
if (await PushAddAsync(record, ct))
{
RemoveFromLocalCache(record.Id!);
newPushed++;
// 下次 FetchRemoteListAsync 时后端会返回真实 ID 版本
}
else
{
_logger.Warning($"[供应商同步] 新增推送失败,下次重连重试:{record.SupplierName}");
}
}
catch (Exception ex)
{
_logger.Warning($"[供应商同步] 推送新增 {record.SupplierName} 时异常:{ex.Message}");
}
}
return new PushPendingResult(pushed, conflicts, newPushed);
}
// ── 私有:写操作核心 ──────────────────────────────────────────────────────
private async Task<bool> PostAndRefreshAsync(
string url, MesXslSupplier supplier, string action, string? supplierId, CancellationToken ct)
{
if (!supplier.TenantId.HasValue || supplier.TenantId <= 0) supplier.TenantId = DefaultTenantId;
if (string.IsNullOrWhiteSpace(supplier.Status)) supplier.Status = "0";
var content = new StringContent(JsonSerializer.Serialize(supplier, _jsonOpts), Encoding.UTF8, "application/json");
using var client = CreateClient();
var resp = await client.PostAsync(url, content, ct).ConfigureAwait(false);
if (IsDisconnectedResponse(resp))
{
if (string.IsNullOrWhiteSpace(supplier.Id))
{
// 新增:分配 local- ID不进 pendingModifiedIds通过 local- 前缀识别)
supplier.Id = $"local-{Guid.NewGuid():N}";
supplier.UpdateTime = DateTime.Now;
UpsertLocalCache(supplier);
}
else
{
// 编辑已有记录:捕获版本锚点(修改前的后端 UpdateTime
var anchor = GetCacheSnapshot()
.FirstOrDefault(x => string.Equals(x.Id, supplier.Id, StringComparison.OrdinalIgnoreCase))?.UpdateTime;
supplier.UpdateTime = DateTime.Now;
UpsertLocalCache(supplier);
MarkLocalModified(supplier.Id, anchor);
}
_eventAggregator.GetEvent<SupplierChangedEvent>()
.Publish(new SupplierChangedPayload { Action = action, SupplierId = supplierId ?? supplier.Id });
return true;
}
var ok = resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
if (ok)
{
UpsertLocalCache(supplier);
ClearPending(supplierId ?? supplier.Id ?? "");
_eventAggregator.GetEvent<SupplierChangedEvent>()
.Publish(new SupplierChangedPayload { Action = action, SupplierId = supplierId ?? supplier.Id });
}
return ok;
}
// ── 私有:重连推送方法 ────────────────────────────────────────────────────
private async Task<(bool Ok, bool IsVersionConflict)> PushEditAsync(MesXslSupplier supplier, CancellationToken ct)
{
var content = new StringContent(
JsonSerializer.Serialize(supplier, _jsonOpts), Encoding.UTF8, "application/json");
using var client = CreateClient();
var resp = await client.PostAsync(
$"{BaseUrl}/xslmes/mesXslSupplier/anon/edit?tenantId={DefaultTenantId}", content, ct)
.ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return (false, false);
try
{
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
int code = 200;
if (doc.RootElement.TryGetProperty("code", out var codeEl)) code = codeEl.GetInt32();
if (code == 200) return (true, false);
if (doc.RootElement.TryGetProperty("message", out var msgEl))
{
var msg = msgEl.GetString() ?? "";
if (msg.Contains("已被他人修改")) return (false, true);
}
return (false, false);
}
catch { return (true, false); }
}
private async Task<bool> PushDeleteAsync(string id, CancellationToken ct)
{
using var client = CreateClient();
var url = $"{BaseUrl}/xslmes/mesXslSupplier/anon/delete?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
var resp = await client.DeleteAsync(url, ct).ConfigureAwait(false);
return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
}
private async Task<bool> PushAddAsync(MesXslSupplier supplier, CancellationToken ct)
{
var payload = Clone(supplier);
payload.Id = null; // 让后端生成真实 ID
var content = new StringContent(
JsonSerializer.Serialize(payload, _jsonOpts), Encoding.UTF8, "application/json");
using var client = CreateClient();
var resp = await client.PostAsync(
$"{BaseUrl}/xslmes/mesXslSupplier/anon/add?tenantId={DefaultTenantId}", content, ct)
.ConfigureAwait(false);
return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
}
private async Task<MesXslSupplier?> FetchRemoteSingleAsync(string id, CancellationToken ct)
{
try
{
var url = $"{BaseUrl}/xslmes/mesXslSupplier/anon/queryById?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
var resp = await client.GetAsync(url, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return null;
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("result", out var resultEl))
return resultEl.Deserialize<MesXslSupplier>(_jsonOpts);
return null;
}
catch { return null; }
}
// ── 私有:冲突检测 ────────────────────────────────────────────────────────
/// <summary>
/// 判断后端是否在断开期间修改了该记录:
/// 后端当前 UpdateTime 与本地锚点不同 → 两端都改了 → 冲突。
/// </summary>
private bool HasConflict(string id, DateTime? remoteUpdateTime)
{
if (!_anchors.TryGetValue(id, out var anchor)) return false;
return remoteUpdateTime != anchor;
}
private static bool IsDisconnectedResponse(HttpResponseMessage resp) =>
(int)resp.StatusCode == 499;
// ── 私有pending 状态管理 ────────────────────────────────────────────────
private void MarkLocalModified(string id, DateTime? anchor)
{
lock (_cacheLock)
{
_pendingLocalDeletedIds.Remove(id);
_pendingLocalModifiedIds.Add(id);
if (!_anchors.ContainsKey(id)) _anchors[id] = anchor; // 只记第一次(保留原始锚点)
SavePendingToDiskUnsafe();
}
}
private void MarkLocalDeleted(string id, DateTime? anchor)
{
lock (_cacheLock)
{
_pendingLocalModifiedIds.Remove(id);
_pendingLocalDeletedIds.Add(id);
if (!_anchors.ContainsKey(id)) _anchors[id] = anchor;
SavePendingToDiskUnsafe();
}
}
private void ClearPending(string id)
{
lock (_cacheLock)
{
_pendingLocalModifiedIds.Remove(id);
_pendingLocalDeletedIds.Remove(id);
_anchors.Remove(id);
_pendingRetryCount.Remove(id);
SavePendingToDiskUnsafe();
}
}
// ── 私有:缓存合并 ────────────────────────────────────────────────────────
/// <summary>
/// 后端全量数据与本地 pending 改动合并,保证本地未同步改动不被覆盖。
/// </summary>
private void MergeIntoCache(List<MesXslSupplier> backendList)
{
bool hasPending = _pendingLocalModifiedIds.Count > 0 || _pendingLocalDeletedIds.Count > 0;
if (!hasPending)
{
_localCache = backendList.Select(Clone).ToList();
return;
}
var localById = _localCache.ToDictionary(x => x.Id ?? "", StringComparer.OrdinalIgnoreCase);
var merged = new List<MesXslSupplier>(backendList.Count + 8);
foreach (var remote in backendList)
{
var id = remote.Id ?? "";
if (_pendingLocalDeletedIds.Contains(id)) continue; // 保持本地删除状态
if (_pendingLocalModifiedIds.Contains(id) && localById.TryGetValue(id, out var local))
merged.Add(Clone(local)); // 本地版本优先(尚未推送成功)
else
merged.Add(Clone(remote));
}
// 保留本地新增local- 前缀,尚未推送到后端)
foreach (var local in _localCache)
{
if ((local.Id ?? "").StartsWith("local-", StringComparison.OrdinalIgnoreCase))
merged.Add(Clone(local));
}
// 安全保留pending-modified 中后端未返回的条目(后端异常情况)
foreach (var modId in _pendingLocalModifiedIds)
{
if (!merged.Any(x => string.Equals(x.Id, modId, StringComparison.OrdinalIgnoreCase))
&& localById.TryGetValue(modId, out var orphan))
merged.Add(Clone(orphan));
}
_localCache = merged;
}
// ── 私有:磁盘持久化 ──────────────────────────────────────────────────────
private async Task<List<MesXslSupplier>> FetchRemoteListAsync(CancellationToken ct)
{
var query = HttpUtility.ParseQueryString(string.Empty);
query["pageNo"] = "1";
query["pageSize"] = "10000";
query["tenantId"] = DefaultTenantId.ToString();
var url = $"{BaseUrl}/xslmes/mesXslSupplier/anon/list?{query}";
using var client = CreateClient();
var resp = await client.GetAsync(url, ct).ConfigureAwait(false);
resp.EnsureSuccessStatusCode();
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
return doc.RootElement.GetProperty("result").GetProperty("records")
.Deserialize<List<MesXslSupplier>>(_jsonOpts) ?? new();
}
private List<MesXslSupplier> GetCacheSnapshot()
{
lock (_cacheLock) return _localCache.Select(Clone).ToList();
}
private void LoadCacheFromDisk()
{
try
{
if (!File.Exists(_cacheFilePath)) return;
_localCache = JsonSerializer.Deserialize<List<MesXslSupplier>>(
File.ReadAllText(_cacheFilePath), _jsonOpts) ?? new();
}
catch { _localCache = new(); }
}
private void SaveCacheToDiskUnsafe() =>
File.WriteAllText(_cacheFilePath, JsonSerializer.Serialize(_localCache, _jsonOpts));
private void LoadPendingFromDisk()
{
try
{
if (!File.Exists(_pendingFilePath)) return;
var state = JsonSerializer.Deserialize<PendingState>(File.ReadAllText(_pendingFilePath)) ?? new();
foreach (var id in state.Modified) _pendingLocalModifiedIds.Add(id);
foreach (var id in state.Deleted) _pendingLocalDeletedIds.Add(id);
foreach (var (id, timeStr) in state.Anchors)
_anchors[id] = timeStr != null && DateTime.TryParse(timeStr, out var dt) ? dt : null;
}
catch { }
}
private void SavePendingToDiskUnsafe()
{
var state = new PendingState
{
Modified = _pendingLocalModifiedIds.ToList(),
Deleted = _pendingLocalDeletedIds.ToList(),
Anchors = _anchors.ToDictionary(
kv => kv.Key,
kv => kv.Value?.ToString("yyyy-MM-dd HH:mm:ss"))
};
File.WriteAllText(_pendingFilePath, JsonSerializer.Serialize(state));
}
private void UpsertLocalCache(MesXslSupplier supplier)
{
lock (_cacheLock)
{
if (string.IsNullOrWhiteSpace(supplier.Id))
{
_localCache.Insert(0, Clone(supplier));
}
else
{
var idx = _localCache.FindIndex(x =>
string.Equals(x.Id, supplier.Id, StringComparison.OrdinalIgnoreCase));
if (idx >= 0) _localCache[idx] = Clone(supplier);
else _localCache.Insert(0, Clone(supplier));
}
SaveCacheToDiskUnsafe();
}
}
private void RemoveFromLocalCache(string id)
{
lock (_cacheLock)
{
_localCache.RemoveAll(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase));
SaveCacheToDiskUnsafe();
}
}
private void UpdateLocalStatus(string id, string status)
{
lock (_cacheLock)
{
var item = _localCache.FirstOrDefault(x =>
string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase));
if (item != null) { item.Status = status; SaveCacheToDiskUnsafe(); }
}
}
private static async Task<bool> IsSuccessResultAsync(HttpResponseMessage resp, CancellationToken ct)
{
try
{
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("code", out var code)) return code.GetInt32() == 200;
if (doc.RootElement.TryGetProperty("success", out var success)) return success.GetBoolean();
}
catch { }
return true;
}
private static MesXslSupplier Clone(MesXslSupplier x) => new()
{
Id = x.Id, SupplierCode = x.SupplierCode, SupplierName = x.SupplierName,
SupplierShortName = x.SupplierShortName, ErpCode = x.ErpCode, Remark = x.Remark,
Status = x.Status, TenantId = x.TenantId, CreateBy = x.CreateBy,
CreateTime = x.CreateTime, UpdateBy = x.UpdateBy, UpdateTime = x.UpdateTime,
SysOrgCode = x.SysOrgCode
};
private sealed class PendingState
{
public List<string> Modified { get; set; } = new();
public List<string> Deleted { get; set; } = new();
public Dictionary<string, string?> Anchors { get; set; } = new();
}
private sealed class NullableDateTimeJsonConverter : JsonConverter<DateTime?>
{
public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> reader.TokenType == JsonTokenType.String
&& DateTime.TryParse(reader.GetString(), out var dt) ? dt : null;
public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
=> writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss"));
}
}

View File

@@ -0,0 +1,87 @@
using Prism.Events;
using System.Text.Json;
using YY.Admin.Core;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
namespace YY.Admin.Services.Service.Supplier;
public class SupplierSyncCoordinator : ISingletonDependency
{
private readonly IEventAggregator _eventAggregator;
private readonly ISupplierService _supplierService;
private readonly ILoggerService _logger;
public SupplierSyncCoordinator(
IEventAggregator eventAggregator,
ISupplierService supplierService,
ILoggerService logger)
{
_eventAggregator = eventAggregator;
_supplierService = supplierService;
_logger = logger;
_eventAggregator.GetEvent<RemoteCommandReceivedEvent>()
.Subscribe(OnRemoteCommand, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<NetworkStatusChangedEvent>()
.Subscribe(OnNetworkStatusChanged, ThreadOption.BackgroundThread);
}
private async void OnNetworkStatusChanged(NetworkStatusChangedPayload payload)
{
if (!payload.IsOnline) return;
// 先推送本地 pending 改动到后端,再通知 UI 刷新列表
PushPendingResult result;
try
{
result = await _supplierService.PushPendingOnReconnectAsync();
}
catch (Exception ex)
{
_logger.Warning($"[供应商同步] 重连推送异常:{ex.Message}");
result = new PushPendingResult(0, 0, 0);
}
// 通知列表刷新
_eventAggregator.GetEvent<SupplierChangedEvent>()
.Publish(new SupplierChangedPayload { Action = "reconnect" });
// 若有推送结果,通知 UI 显示摘要
bool hasActivity = result.PushedCount > 0
|| result.ConflictCount > 0
|| result.NewRecordsPushed > 0;
if (hasActivity)
{
_eventAggregator.GetEvent<SyncConflictEvent>().Publish(new SyncConflictPayload
{
EntityName = "供应商",
PushedCount = result.PushedCount,
ConflictCount = result.ConflictCount,
NewRecordsPushed = result.NewRecordsPushed
});
}
}
private void OnRemoteCommand(RemoteCommandPayload payload)
{
try
{
var json = payload.CommandJson ?? string.Empty;
if (string.IsNullOrWhiteSpace(json)) return;
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("cmd", out var cmdEl)) return;
if (!cmdEl.GetString().Equals("MES_SUPPLIER_CHANGED", StringComparison.OrdinalIgnoreCase)) return;
doc.RootElement.TryGetProperty("action", out var actionEl);
doc.RootElement.TryGetProperty("supplierId", out var idEl);
_eventAggregator.GetEvent<SupplierChangedEvent>().Publish(new SupplierChangedPayload
{
Action = actionEl.GetString() ?? string.Empty,
SupplierId = idEl.ValueKind == JsonValueKind.String ? idEl.GetString() : null
});
}
catch (Exception ex)
{
_logger.Warning($"[供应商推送] 处理失败:{ex.Message}");
}
}
}

View File

@@ -1,9 +1,8 @@
using Dm.util;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System.Globalization;
using YY.Admin.Core;
using YY.Admin.Core.SeedData;
using YY.Admin.Core.Services;
using YY.Admin.Core.Session;
using YY.Admin.Core.Util;
@@ -11,27 +10,33 @@ namespace YY.Admin.Services.Service.User
{
public class SysUserService : ISysUserService, ISingletonDependency
{
private readonly ISysOrgService _sysOrgService;
private readonly ISqlSugarClient _dbContext;
public SysUserService(ISysOrgService orgService, ISqlSugarClient dbContext)
private readonly IConfiguration _configuration;
private readonly IUserSyncOutbox _userSyncOutbox;
public SysUserService(ISqlSugarClient dbContext, IConfiguration configuration, IUserSyncOutbox userSyncOutbox)
{
_sysOrgService = orgService;
_dbContext = dbContext;
_configuration = configuration;
_userSyncOutbox = userSyncOutbox;
}
public async Task<List<SysUser>> GetUsersAsync()
{
await Task.Delay(200);
await Task.CompletedTask;
return new List<SysUser>();
}
// ── 查询 ──────────────────────────────────────────────────────────────
public async Task<SqlSugarPagedList<UserOutput>> PageAsync(PageUserInput input)
{
var sexFilter = input.Sex.HasValue ? (int?)input.Sex.Value : null;
var statusFilter = input.Status.HasValue ? (int?)input.Status.Value : null;
// 账号管理查询改为从 Jeecg 同构账号表读取
var query = _dbContext.Queryable<JeecgSysUser>().ClearFilter()
// 只显示未软删除的记录
.Where(u => u.DelFlag == null || u.DelFlag == 0)
.WhereIF(input.TenantId > 0, u => u.LoginTenantId == input.TenantId)
.WhereIF(!string.IsNullOrWhiteSpace(input.Account), u => u.Username != null && u.Username.Contains(input.Account))
.WhereIF(!string.IsNullOrWhiteSpace(input.RealName), u => u.Realname != null && u.Realname.Contains(input.RealName))
@@ -39,6 +44,7 @@ namespace YY.Admin.Services.Service.User
.WhereIF(input.BeginTime.HasValue, u => u.CreateTime >= input.BeginTime)
.WhereIF(input.EndTime.HasValue, u => u.CreateTime <= input.EndTime)
.OrderBy(u => SqlFunc.Desc(u.CreateTime));
if (sexFilter.HasValue)
{
var sexValue = sexFilter.Value;
@@ -51,35 +57,7 @@ namespace YY.Admin.Services.Service.User
}
var pageData = await query.ToPagedListAsync(input.Page, input.PageSize);
var mapped = pageData.Items.Select(u =>
{
long id = 0;
long.TryParse(u.Id, NumberStyles.Integer, CultureInfo.InvariantCulture, out id);
var sex = GenderEnum.Unknown;
if (u.Sex == 1) sex = GenderEnum.Male;
if (u.Sex == 2) sex = GenderEnum.Female;
var status = u.Status == 1 ? StatusEnum.Enable : StatusEnum.Disable;
return new UserOutput
{
Id = id,
Account = u.Username ?? string.Empty,
RealName = u.Realname ?? string.Empty,
// Jeecg 同构表无 nickname 字段,昵称回退为真实姓名,避免页面显示被“清空”
NickName = string.IsNullOrWhiteSpace(u.Realname) ? (u.Username ?? string.Empty) : u.Realname,
Avatar = u.Avatar,
Sex = sex,
Birthday = u.Birthday,
Phone = u.Phone,
Email = u.Email,
OfficePhone = u.Telephone,
Status = status,
CreateTime = u.CreateTime,
OrgName = u.OrgCode ?? string.Empty,
PosName = u.PositionType ?? string.Empty,
RoleName = string.Empty,
AccountType = AccountTypeEnum.NormalUser
};
}).ToList();
var mapped = pageData.Items.Select(MapToOutput).ToList();
return new SqlSugarPagedList<UserOutput>
{
@@ -93,147 +71,205 @@ namespace YY.Admin.Services.Service.User
};
}
public async Task<int> BatchDeleteAsync(List<long> ids)
public async Task<bool> AccountExistsAsync(string account, long? excludeUserId = null)
{
int count = 0;
if (ids == null || ids.isEmpty())
var query = _dbContext.Queryable<JeecgSysUser>().ClearFilter()
.Where(u => (u.DelFlag == null || u.DelFlag == 0) && u.Username == account);
if (excludeUserId.HasValue && excludeUserId.Value != 0)
{
return count;
}
try
{
await _dbContext.AsTenant().BeginTranAsync();
count = await _dbContext.Deleteable<SysUser>().In(ids).ExecuteCommandAsync();
await _dbContext.AsTenant().CommitTranAsync();
}
catch (Exception)
{
await _dbContext.AsTenant().RollbackTranAsync();
}
return count;
}
public async Task<int> DeleteAsync(long id)
{
int count = 0;
try
{
await _dbContext.AsTenant().BeginTranAsync();
count = await _dbContext.Deleteable<SysUser>().In(id).ExecuteCommandAsync();
await _dbContext.AsTenant().CommitTranAsync();
}
catch (Exception)
{
await _dbContext.AsTenant().RollbackTranAsync();
}
return count;
}
public async Task<int> CreateAsync(SysUser sysUser)
{
long maxId = await ReadMaxIdAsync();
sysUser.Id = ++maxId;
sysUser.Password = CryptogramUtil.Encrypt(sysUser.Password);
sysUser.CardType = CardTypeEnum.IdCard;
sysUser.CultureLevel = CultureLevelEnum.Level0;
sysUser.PosId = new SysPosSeedData().HasData().ToList()[0].Id;
sysUser.TenantId = SqlSugarConst.DefaultTenantId;
sysUser.CreateTime = DateTime.Now;
sysUser.CreateUserId = AppSession.UserId;
sysUser.CreateUserName = AppSession.CurrentUser!.Account;
int count = 0;
try
{
await _dbContext.AsTenant().BeginTranAsync();
count = await _dbContext.Insertable(sysUser).ExecuteCommandAsync();
await _dbContext.AsTenant().CommitTranAsync();
}
catch (Exception)
{
await _dbContext.AsTenant().RollbackTranAsync();
}
return count;
}
public async Task<int> UpdateAsync(SysUser sysUser)
{
sysUser.UpdateUserId = AppSession.UserId; ;
sysUser.UpdateUserName = AppSession.CurrentUser!.Account;
sysUser.UpdateTime = DateTime.Now;
int count = 0;
try
{
await _dbContext.AsTenant().BeginTranAsync();
count = await _dbContext.Updateable(sysUser)
.UpdateColumns(it => new { it.RealName, it.NickName, it.Sex, it.Birthday, it.Age, it.Status, it.UpdateUserId, it.UpdateUserName, it.UpdateTime })
.ExecuteCommandAsync();
await _dbContext.AsTenant().CommitTranAsync();
}
catch (Exception)
{
await _dbContext.AsTenant().RollbackTranAsync();
}
return count;
}
public async Task<long> ReadMaxIdAsync()
{
return await _dbContext.Queryable<SysUser>().MaxAsync<long>("Id");
}
public async Task<bool> AccountExistsAsync(string account, long? excludeUserId)
{
var query = _dbContext.Queryable<SysUser>()
. Where(u => u.Account == account);
// excludeUserId不等于null && 不等于 0
if (excludeUserId.HasValue && excludeUserId != 0)
{
query = query.Where(u => u.Id != excludeUserId.Value);
var excludeIdStr = excludeUserId.Value.ToString(CultureInfo.InvariantCulture);
query = query.Where(u => u.Id != excludeIdStr);
}
return await query.AnyAsync();
}
// ── 新增 ──────────────────────────────────────────────────────────────
public async Task<int> CreateAsync(SysUser sysUser)
{
var defaultTenantId = (int?)_configuration.GetValue<long?>("JeecgIntegration:DefaultTenantId") ?? 1002;
var now = DateTime.Now;
var jeecgUser = new JeecgSysUser
{
// 用毫秒时间戳生成本地唯一 ID数值型字符串与 PageAsync 的 long.TryParse 兼容)
Id = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture),
Username = sysUser.Account,
Realname = sysUser.RealName,
// 本地创建账号使用 CryptogramUtil 加密,无 salt登录时走 CryptogramUtil 路径
Password = string.IsNullOrWhiteSpace(sysUser.Password)
? string.Empty
: CryptogramUtil.Encrypt(sysUser.Password),
Salt = null,
Sex = ToJeecgSex(sysUser.Sex),
Birthday = sysUser.Birthday,
Phone = sysUser.Phone,
Email = sysUser.Email,
Status = 1, // 默认启用
DelFlag = 0,
LoginTenantId = defaultTenantId,
CreateBy = AppSession.CurrentUser?.Account,
CreateTime = now,
UpdateTime = now,
};
var affected = await _dbContext.Insertable(jeecgUser).ExecuteCommandAsync();
if (affected > 0)
{
_ = _userSyncOutbox.EnqueueCreateAsync(
jeecgUser.Id,
jeecgUser.Username ?? string.Empty,
jeecgUser.Realname,
jeecgUser.Sex,
jeecgUser.Birthday,
jeecgUser.Phone,
jeecgUser.Email,
jeecgUser.Status ?? 1,
jeecgUser.CreateBy);
}
return affected;
}
// ── 修改 ──────────────────────────────────────────────────────────────
public async Task<int> UpdateAsync(SysUser sysUser)
{
var idStr = sysUser.Id.ToString(CultureInfo.InvariantCulture);
var now = DateTime.Now;
var updater = AppSession.CurrentUser?.Account;
var jeecgStatus = sysUser.Status == StatusEnum.Enable ? 1 : 2;
var jeecgSex = ToJeecgSex(sysUser.Sex);
var account = (sysUser.Account ?? string.Empty).Trim();
var affected = await _dbContext.Updateable<JeecgSysUser>()
.SetColumns(u => new JeecgSysUser
{
Username = account,
Realname = sysUser.RealName,
Sex = jeecgSex,
Birthday = sysUser.Birthday,
Phone = sysUser.Phone,
Email = sysUser.Email,
Status = jeecgStatus,
UpdateBy = updater,
UpdateTime = now,
})
.Where(u => u.Id == idStr)
.ExecuteCommandAsync();
if (affected > 0)
{
_ = _userSyncOutbox.EnqueueUpdateAsync(idStr, account, sysUser.RealName, jeecgSex, sysUser.Birthday, sysUser.Phone, sysUser.Email, jeecgStatus, updater);
}
return affected;
}
// ── 状态切换 ──────────────────────────────────────────────────────────
public async Task<int> ToggleStatus(SysUser sysUser)
{
sysUser.UpdateUserId = AppSession.UserId; ;
sysUser.UpdateUserName = AppSession.CurrentUser!.Account;
sysUser.UpdateTime = DateTime.Now;
var idStr = sysUser.Id.ToString(CultureInfo.InvariantCulture);
// Jeecg 约定1=正常2=冻结
var jeecgStatus = sysUser.Status == StatusEnum.Enable ? 1 : 2;
var now = DateTime.Now;
var updater = AppSession.CurrentUser?.Account;
int count = 0;
try
var affected = await _dbContext.Updateable<JeecgSysUser>()
.SetColumns(u => new JeecgSysUser
{
Status = jeecgStatus,
UpdateBy = updater,
UpdateTime = now,
})
.Where(u => u.Id == idStr)
.ExecuteCommandAsync();
if (affected > 0)
{
await _dbContext.AsTenant().BeginTranAsync();
count = await _dbContext.Updateable(sysUser)
.UpdateColumns(it => new { it.Status, it.UpdateUserId, it.UpdateUserName, it.UpdateTime })
.ExecuteCommandAsync();
await _dbContext.AsTenant().CommitTranAsync();
_ = _userSyncOutbox.EnqueueToggleStatusAsync(idStr, jeecgStatus, updater);
}
catch (Exception)
{
await _dbContext.AsTenant().RollbackTranAsync();
}
return count;
return affected;
}
// ── 删除 ──────────────────────────────────────────────────────────────
public async Task<int> DeleteAsync(long id)
{
var idStr = id.ToString(CultureInfo.InvariantCulture);
// 软删除保留记录供审计PageAsync 已过滤 del_flag=1
var affected = await _dbContext.Updateable<JeecgSysUser>()
.SetColumns(u => new JeecgSysUser { DelFlag = 1 })
.Where(u => u.Id == idStr)
.ExecuteCommandAsync();
if (affected > 0)
{
_ = _userSyncOutbox.EnqueueDeleteAsync(idStr);
}
return affected;
}
public async Task<int> BatchDeleteAsync(List<long> ids)
{
if (ids == null || ids.Count == 0)
{
return 0;
}
var idStrings = ids.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList();
var affected = await _dbContext.Updateable<JeecgSysUser>()
.SetColumns(u => new JeecgSysUser { DelFlag = 1 })
.Where(u => idStrings.Contains(u.Id))
.ExecuteCommandAsync();
if (affected > 0)
{
_ = _userSyncOutbox.EnqueueBatchDeleteAsync(idStrings);
}
return affected;
}
// ── 辅助 ──────────────────────────────────────────────────────────────
public async Task<long> ReadMaxIdAsync()
{
// jeecg_sys_user 使用字符串ID此方法不再适用保留签名兼容旧调用
await Task.CompletedTask;
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
private static UserOutput MapToOutput(JeecgSysUser u)
{
long.TryParse(u.Id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id);
var sex = u.Sex == 1 ? GenderEnum.Male : u.Sex == 2 ? GenderEnum.Female : GenderEnum.Unknown;
var status = u.Status == 1 ? StatusEnum.Enable : StatusEnum.Disable;
return new UserOutput
{
Id = id,
Account = u.Username ?? string.Empty,
RealName = u.Realname ?? string.Empty,
NickName = string.IsNullOrWhiteSpace(u.Realname) ? (u.Username ?? string.Empty) : u.Realname,
Avatar = u.Avatar,
Sex = sex,
Birthday = u.Birthday,
Phone = u.Phone,
Email = u.Email,
OfficePhone = u.Telephone,
Status = status,
CreateTime = u.CreateTime,
OrgName = u.OrgCode ?? string.Empty,
PosName = u.PositionType ?? string.Empty,
RoleName = string.Empty,
AccountType = AccountTypeEnum.NormalUser
};
}
private static int? ToJeecgSex(GenderEnum? sex) => sex switch
{
GenderEnum.Male => 1,
GenderEnum.Female => 2,
_ => null
};
}
}

View File

@@ -0,0 +1,984 @@
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Web;
using Prism.Events;
using YY.Admin.Core;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
namespace YY.Admin.Services.Service.Vehicle;
public class VehicleService : IVehicleService, ISingletonDependency
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
private readonly INetworkMonitor _networkMonitor;
private readonly IEventAggregator _eventAggregator;
private readonly ILoggerService _logger;
private readonly SemaphoreSlim _syncLock = new(1, 1);
private readonly object _cacheLock = new();
private readonly string _pendingOpsFilePath;
private readonly string _cacheFilePath;
private List<VehiclePendingOperation> _pendingOps = new();
private List<MesXslVehicle> _localCache = new();
private static readonly JsonSerializerOptions _jsonOpts = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters =
{
new NullableDateTimeJsonConverter()
}
};
public VehicleService(
IHttpClientFactory httpClientFactory,
IConfiguration configuration,
INetworkMonitor networkMonitor,
IEventAggregator eventAggregator,
ILoggerService logger)
{
_httpClientFactory = httpClientFactory;
_configuration = configuration;
_networkMonitor = networkMonitor;
_eventAggregator = eventAggregator;
_logger = logger;
var appDataDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"YY.Admin",
"sync-cache");
Directory.CreateDirectory(appDataDir);
_pendingOpsFilePath = Path.Combine(appDataDir, "vehicle-pending-ops.json");
_cacheFilePath = Path.Combine(appDataDir, "vehicle-cache.json");
LoadPendingOpsFromDisk();
LoadCacheFromDisk();
_logger.Information($"[车辆同步] 服务初始化完成,缓存目录={appDataDir}, 本地缓存={_localCache.Count}, 待上传={_pendingOps.Count}, 在线={_networkMonitor.IsOnline}");
_networkMonitor.StatusChanged += OnNetworkStatusChanged;
if (_networkMonitor.IsOnline)
{
_ = Task.Run(() => SyncAfterReconnectAsync(CancellationToken.None));
}
}
private const int MaxPendingRetries = 5;
private string BaseUrl => (_configuration.GetValue<string>("JeecgIntegration:BaseUrl") ?? "http://localhost:8080/jeecg-boot").TrimEnd('/');
private int DefaultTenantId => (int?)_configuration.GetValue<long?>("JeecgIntegration:DefaultTenantId") ?? 1002;
private HttpClient CreateClient()
{
var client = _httpClientFactory.CreateClient("JeecgApi");
return client;
}
public async Task<VehiclePageResult> PageAsync(int pageNo, int pageSize, string? plateNumber = null, string? vehicleBelong = null, string? status = null, CancellationToken ct = default)
{
List<MesXslVehicle>? source = null;
_logger.Information($"[车辆列表] 请求分页 pageNo={pageNo}, pageSize={pageSize}, plate={plateNumber}, belong={vehicleBelong}, status={status}, online={_networkMonitor.IsOnline}");
if (_networkMonitor.IsOnline)
{
try
{
source = await FetchRemoteListAsync(ct).ConfigureAwait(false);
lock (_cacheLock)
{
_localCache = source.Select(CloneVehicle).ToList();
SaveCacheToDiskUnsafe();
}
_logger.Information($"[车辆列表] 远端拉取成功,记录数={source.Count},已刷新本地缓存");
}
catch (Exception ex)
{
source = null;
_logger.Warning($"[车辆列表] 远端拉取失败,回退本地缓存:{ex.Message}");
}
}
lock (_cacheLock)
{
source ??= _localCache.Select(CloneVehicle).ToList();
source = ApplyPendingOpsSnapshotUnsafe(source);
}
var filtered = ApplyFilters(source, plateNumber, vehicleBelong, status);
var total = filtered.Count;
var pageRecords = filtered
.Skip(Math.Max(0, (pageNo - 1) * pageSize))
.Take(pageSize)
.ToList();
_logger.Information($"[车辆列表] 返回记录 total={total}, pageRecords={pageRecords.Count}, pending={_pendingOps.Count}");
return new VehiclePageResult(pageRecords, total, pageNo, pageSize);
}
public async Task<MesXslVehicle?> GetByIdAsync(string id, CancellationToken ct = default)
{
_logger.Information($"[车辆详情] 查询 id={id}, online={_networkMonitor.IsOnline}");
if (_networkMonitor.IsOnline)
{
try
{
var url = $"{BaseUrl}/xslmes/mesXslVehicle/anon/queryById?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
var resp = await client.GetAsync(url, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return null;
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("result", out var resultEl)) return null;
var result = resultEl.Deserialize<MesXslVehicle>(_jsonOpts);
_logger.Information($"[车辆详情] 远端查询成功 id={id}, found={result != null}");
return result;
}
catch (Exception ex)
{
_logger.Warning($"[车辆详情] 远端查询异常,回退本地缓存 id={id}, err={ex.Message}");
}
}
lock (_cacheLock)
{
return _localCache.FirstOrDefault(v => string.Equals(v.Id, id, StringComparison.OrdinalIgnoreCase)) is { } found
? CloneVehicle(found)
: null;
}
}
public async Task<bool> AddAsync(MesXslVehicle vehicle, CancellationToken ct = default)
{
if (!vehicle.TenantId.HasValue || vehicle.TenantId.Value <= 0)
{
vehicle.TenantId = DefaultTenantId;
}
var local = CloneVehicle(vehicle);
if (string.IsNullOrWhiteSpace(local.Id))
{
local.Id = $"local-{Guid.NewGuid():N}";
}
if (_networkMonitor.IsOnline)
{
try
{
_logger.Information($"[车辆新增] 尝试远端新增 id={local.Id}, plate={local.PlateNumber}");
var ok = await RemoteAddAsync(local, ct).ConfigureAwait(false);
if (ok)
{
UpsertLocalCache(local);
_logger.Information($"[车辆新增] 远端新增成功 id={local.Id}");
return true;
}
_logger.Warning($"[车辆新增] 远端新增返回失败 id={local.Id}");
return false;
}
catch (Exception ex)
{
_logger.Warning($"[车辆新增] 远端新增异常,转离线入队 id={local.Id}, err={ex.Message}");
}
}
EnqueuePendingOperation(new VehiclePendingOperation
{
OpType = VehicleOperationType.Add,
VehicleId = local.Id,
Vehicle = local,
CreatedAt = DateTime.UtcNow
});
UpsertLocalCache(local);
_logger.Information($"[车辆新增] 已离线入队 id={local.Id}, pending={_pendingOps.Count}");
return true;
}
public async Task<bool> EditAsync(MesXslVehicle vehicle, CancellationToken ct = default)
{
if (!vehicle.TenantId.HasValue || vehicle.TenantId.Value <= 0)
{
vehicle.TenantId = DefaultTenantId;
}
var local = CloneVehicle(vehicle);
if (_networkMonitor.IsOnline)
{
try
{
_logger.Information($"[车辆修改] 尝试远端修改 id={local.Id}, plate={local.PlateNumber}");
var (ok, _) = await RemoteEditAsync(local, ct).ConfigureAwait(false);
if (ok)
{
UpsertLocalCache(local);
_logger.Information($"[车辆修改] 远端修改成功 id={local.Id}");
return true;
}
_logger.Warning($"[车辆修改] 远端修改返回失败 id={local.Id}");
return false;
}
catch (Exception ex)
{
_logger.Warning($"[车辆修改] 远端修改异常,转离线入队 id={local.Id}, err={ex.Message}");
}
}
EnqueuePendingOperation(new VehiclePendingOperation
{
OpType = VehicleOperationType.Edit,
VehicleId = local.Id,
Vehicle = local,
AnchorUpdateTime = local.UpdateTime,
CreatedAt = DateTime.UtcNow
});
UpsertLocalCache(local);
_logger.Information($"[车辆修改] 已离线入队 id={local.Id}, pending={_pendingOps.Count}");
return true;
}
public async Task<bool> DeleteAsync(string id, CancellationToken ct = default)
{
if (_networkMonitor.IsOnline)
{
try
{
_logger.Information($"[车辆删除] 尝试远端删除 id={id}");
var ok = await RemoteDeleteAsync(id, ct).ConfigureAwait(false);
if (ok)
{
RemoveFromLocalCache(id);
_logger.Information($"[车辆删除] 远端删除成功 id={id}");
return true;
}
_logger.Warning($"[车辆删除] 远端删除返回失败 id={id}");
return false;
}
catch (Exception ex)
{
_logger.Warning($"[车辆删除] 远端删除异常,转离线入队 id={id}, err={ex.Message}");
}
}
DateTime? anchor;
lock (_cacheLock)
{
anchor = _localCache.FirstOrDefault(v => string.Equals(v.Id, id, StringComparison.OrdinalIgnoreCase))?.UpdateTime;
}
EnqueuePendingOperation(new VehiclePendingOperation
{
OpType = VehicleOperationType.Delete,
VehicleId = id,
AnchorUpdateTime = anchor,
CreatedAt = DateTime.UtcNow
});
RemoveFromLocalCache(id);
_logger.Information($"[车辆删除] 已离线入队 id={id}, pending={_pendingOps.Count}");
return true;
}
public async Task<bool> DeleteBatchAsync(string ids, CancellationToken ct = default)
{
var idList = ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var allSuccess = true;
foreach (var id in idList)
{
var ok = await DeleteAsync(id, ct).ConfigureAwait(false);
allSuccess &= ok;
}
return allSuccess;
}
public async Task<bool> UpdateStatusAsync(string id, string status, CancellationToken ct = default)
{
if (_networkMonitor.IsOnline)
{
try
{
_logger.Information($"[车辆状态] 尝试远端更新 id={id}, status={status}");
var ok = await RemoteUpdateStatusAsync(id, status, ct).ConfigureAwait(false);
if (ok)
{
UpdateLocalStatus(id, status);
_logger.Information($"[车辆状态] 远端更新成功 id={id}, status={status}");
return true;
}
_logger.Warning($"[车辆状态] 远端更新返回失败 id={id}, status={status}");
return false;
}
catch (Exception ex)
{
_logger.Warning($"[车辆状态] 远端更新异常,转离线入队 id={id}, status={status}, err={ex.Message}");
}
}
DateTime? anchor;
lock (_cacheLock)
{
anchor = _localCache.FirstOrDefault(v => string.Equals(v.Id, id, StringComparison.OrdinalIgnoreCase))?.UpdateTime;
}
EnqueuePendingOperation(new VehiclePendingOperation
{
OpType = VehicleOperationType.UpdateStatus,
VehicleId = id,
Status = status,
AnchorUpdateTime = anchor,
CreatedAt = DateTime.UtcNow
});
UpdateLocalStatus(id, status);
_logger.Information($"[车辆状态] 已离线入队 id={id}, status={status}, pending={_pendingOps.Count}");
return true;
}
private async Task<List<MesXslVehicle>> FetchRemoteListAsync(CancellationToken ct)
{
var query = HttpUtility.ParseQueryString(string.Empty);
query["pageNo"] = "1";
query["pageSize"] = "10000";
query["tenantId"] = DefaultTenantId.ToString();
var url = $"{BaseUrl}/xslmes/mesXslVehicle/anon/list?{query}";
using var client = CreateClient();
_logger.Information($"[车辆远端] GET {url}");
var resp = await client.GetAsync(url, ct).ConfigureAwait(false);
resp.EnsureSuccessStatusCode();
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
var result = doc.RootElement.GetProperty("result");
var records = result.GetProperty("records").Deserialize<List<MesXslVehicle>>(_jsonOpts) ?? new();
_logger.Information($"[车辆远端] 列表拉取成功 count={records.Count}");
return records;
}
private async Task<bool> RemoteAddAsync(MesXslVehicle vehicle, CancellationToken ct)
{
var url = $"{BaseUrl}/xslmes/mesXslVehicle/anon/add?tenantId={DefaultTenantId}";
var payload = CloneVehicle(vehicle);
// 离线本地临时ID不能直接入后端主键需置空让Jeecg自动生成雪花ID
if (IsLocalTempId(payload.Id))
{
_logger.Information($"[车辆远端] 新增检测到本地临时ID自动清空 id={payload.Id}");
payload.Id = null;
}
return await PostJsonAsync(url, payload, ct).ConfigureAwait(false);
}
private async Task<(bool Ok, bool IsVersionConflict)> RemoteEditAsync(MesXslVehicle vehicle, CancellationToken ct)
{
var url = $"{BaseUrl}/xslmes/mesXslVehicle/anon/edit?tenantId={DefaultTenantId}";
return await PostJsonCheckVersionAsync(url, vehicle, ct).ConfigureAwait(false);
}
private async Task<bool> RemoteDeleteAsync(string id, CancellationToken ct)
{
var url = $"{BaseUrl}/xslmes/mesXslVehicle/anon/delete?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
_logger.Information($"[车辆远端] DELETE {url}");
var resp = await client.DeleteAsync(url, ct).ConfigureAwait(false);
return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
}
private async Task<bool> RemoteUpdateStatusAsync(string id, string status, CancellationToken ct)
{
var url = $"{BaseUrl}/xslmes/mesXslVehicle/anon/updateStatus?id={Uri.EscapeDataString(id)}&status={Uri.EscapeDataString(status)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
_logger.Information($"[车辆远端] POST {url}");
var resp = await client.PostAsync(url, null, ct).ConfigureAwait(false);
return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
}
private async Task<bool> PostJsonAsync(string url, object body, CancellationToken ct)
{
var content = new StringContent(JsonSerializer.Serialize(body, _jsonOpts), Encoding.UTF8, "application/json");
using var client = CreateClient();
_logger.Information($"[车辆远端] POST {url}, bodyType={body.GetType().Name}");
var resp = await client.PostAsync(url, content, ct).ConfigureAwait(false);
var ok = resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false);
_logger.Information($"[车辆远端] POST完成 url={url}, status={(int)resp.StatusCode}, ok={ok}");
return ok;
}
private async Task<(bool Ok, bool IsVersionConflict)> PostJsonCheckVersionAsync(string url, object body, CancellationToken ct)
{
var content = new StringContent(JsonSerializer.Serialize(body, _jsonOpts), Encoding.UTF8, "application/json");
using var client = CreateClient();
_logger.Information($"[车辆远端] POST {url}, bodyType={body.GetType().Name}");
var resp = await client.PostAsync(url, content, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode)
return (false, false);
try
{
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
int code = 200;
if (doc.RootElement.TryGetProperty("code", out var codeEl))
code = codeEl.GetInt32();
if (code == 200)
return (true, false);
if (doc.RootElement.TryGetProperty("message", out var msgEl))
{
var msg = msgEl.GetString() ?? "";
if (msg.Contains("已被他人修改"))
return (false, true);
}
return (false, false);
}
catch
{
return (true, false);
}
}
private static async Task<bool> IsSuccessResultAsync(HttpResponseMessage resp, CancellationToken ct)
{
try
{
var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("code", out var code))
{
return code.GetInt32() == 200;
}
if (doc.RootElement.TryGetProperty("success", out var success))
{
return success.GetBoolean();
}
return true;
}
catch
{
return true;
}
}
private void OnNetworkStatusChanged(bool isOnline)
{
_logger.Information($"[车辆网络] 状态变化 online={isOnline}");
if (!isOnline) return;
_ = Task.Run(() => SyncAfterReconnectAsync(CancellationToken.None));
}
private async Task SyncAfterReconnectAsync(CancellationToken cancellationToken)
{
_logger.Information("[车辆重连] 开始执行重连同步");
var pushResult = await PushPendingOnReconnectAsync(cancellationToken).ConfigureAwait(false);
if (!_networkMonitor.IsOnline)
{
return;
}
try
{
var remote = await FetchRemoteListAsync(cancellationToken).ConfigureAwait(false);
lock (_cacheLock)
{
_localCache = remote.Select(CloneVehicle).ToList();
SaveCacheToDiskUnsafe();
}
// 拉取成功后主动通知页面刷新,避免用户手动点查询
_eventAggregator.GetEvent<VehicleChangedEvent>().Publish(new VehicleChangedPayload
{
Action = "pull",
VehicleId = null
});
_logger.Information($"[车辆重连] 全量回拉成功 count={remote.Count},已发布刷新事件");
}
catch (Exception ex)
{
_logger.Warning($"[车辆重连] 全量回拉失败,继续使用本地缓存:{ex.Message}");
}
var hasActivity = pushResult.PushedCount > 0
|| pushResult.ConflictCount > 0
|| pushResult.NewRecordsPushed > 0;
if (hasActivity)
{
_eventAggregator.GetEvent<SyncConflictEvent>()
.Publish(new SyncConflictPayload
{
EntityName = "车辆",
PushedCount = pushResult.PushedCount,
ConflictCount = pushResult.ConflictCount,
NewRecordsPushed = pushResult.NewRecordsPushed
});
}
}
private sealed record PendingReplayResult(bool Ok, bool IsConflict, string? EntityId);
private async Task<PushPendingResult> PushPendingOnReconnectAsync(CancellationToken cancellationToken)
{
if (!await _syncLock.WaitAsync(0, cancellationToken).ConfigureAwait(false))
{
_logger.Information("[车辆回放] 已有回放任务在执行,本次跳过");
return new PushPendingResult(0, 0, 0);
}
try
{
List<VehiclePendingOperation> snapshot;
lock (_cacheLock)
{
snapshot = _pendingOps.OrderBy(x => x.CreatedAt).ToList();
}
_logger.Information($"[车辆推送] 开始推送 pending={snapshot.Count}");
int pushed = 0, conflicts = 0, newPushed = 0;
foreach (var op in snapshot)
{
if (!_networkMonitor.IsOnline)
{
break;
}
// 如果该条 pending 在上一轮冲突中已被清理,则跳过
lock (_cacheLock)
{
if (!_pendingOps.Any(x => x.Id == op.Id))
continue;
}
var result = await ExecutePendingOperationWithConflictAsync(op, cancellationToken).ConfigureAwait(false);
if (!result.Ok)
{
lock (_cacheLock)
{
op.RetryCount++;
if (op.RetryCount >= MaxPendingRetries)
{
_logger.Warning($"[车辆推送] op={op.OpType} 超过最大重试次数({MaxPendingRetries}),放弃 vehicleId={op.VehicleId}");
_pendingOps.RemoveAll(x => x.Id == op.Id);
SavePendingOpsToDiskUnsafe();
continue;
}
SavePendingOpsToDiskUnsafe();
}
_logger.Warning($"[车辆推送] 推送中断 op={op.OpType}, vehicleId={op.VehicleId}, retry={op.RetryCount}");
break;
}
if (result.IsConflict)
{
conflicts++;
if (!string.IsNullOrWhiteSpace(result.EntityId))
RemovePendingOpsByVehicleId(result.EntityId!);
continue;
}
lock (_cacheLock)
{
if (op.OpType == VehicleOperationType.Add)
newPushed++;
else
pushed++;
_pendingOps.RemoveAll(x => x.Id == op.Id);
SavePendingOpsToDiskUnsafe();
}
_logger.Information($"[车辆推送] 推送成功 op={op.OpType}, vehicleId={op.VehicleId}, remain={_pendingOps.Count}");
}
return new PushPendingResult(pushed, conflicts, newPushed);
}
finally
{
_syncLock.Release();
}
}
private async Task<PendingReplayResult> ExecutePendingOperationWithConflictAsync(VehiclePendingOperation op, CancellationToken cancellationToken)
{
try
{
_logger.Information($"[车辆推送] 执行 op={op.OpType}, vehicleId={op.VehicleId}");
switch (op.OpType)
{
case VehicleOperationType.Add:
{
var ok = op.Vehicle != null && await RemoteAddAsync(op.Vehicle, cancellationToken).ConfigureAwait(false);
return ok
? new PendingReplayResult(true, false, op.VehicleId)
: new PendingReplayResult(false, false, null);
}
case VehicleOperationType.Edit:
{
if (op.Vehicle == null || string.IsNullOrWhiteSpace(op.Vehicle.Id))
return new PendingReplayResult(false, false, null);
var id = op.Vehicle.Id;
var remote = await FetchRemoteSingleAsync(id, cancellationToken).ConfigureAwait(false);
if (remote != null && op.AnchorUpdateTime != null && remote.UpdateTime != op.AnchorUpdateTime)
{
// 冲突:后端版本获胜(服务器覆盖本地)
UpsertLocalCache(remote);
return new PendingReplayResult(true, true, id);
}
var (ok, isVersionConflict) = await RemoteEditAsync(op.Vehicle, cancellationToken).ConfigureAwait(false);
if (isVersionConflict)
{
var fresh = await FetchRemoteSingleAsync(id, cancellationToken).ConfigureAwait(false);
if (fresh != null) UpsertLocalCache(fresh);
return new PendingReplayResult(true, true, id);
}
return ok
? new PendingReplayResult(true, false, id)
: new PendingReplayResult(false, false, null);
}
case VehicleOperationType.Delete:
{
if (string.IsNullOrWhiteSpace(op.VehicleId))
return new PendingReplayResult(false, false, null);
var id = op.VehicleId!;
var remote = await FetchRemoteSingleAsync(id, cancellationToken).ConfigureAwait(false);
if (remote == null)
{
// 后端已不存在:删除无需操作,视为成功
return new PendingReplayResult(true, false, id);
}
if (op.AnchorUpdateTime != null && remote.UpdateTime != op.AnchorUpdateTime)
{
UpsertLocalCache(remote);
return new PendingReplayResult(true, true, id);
}
var ok = await RemoteDeleteAsync(id, cancellationToken).ConfigureAwait(false);
return ok
? new PendingReplayResult(true, false, id)
: new PendingReplayResult(false, false, null);
}
case VehicleOperationType.UpdateStatus:
{
if (string.IsNullOrWhiteSpace(op.VehicleId) || string.IsNullOrWhiteSpace(op.Status))
return new PendingReplayResult(false, false, null);
var id = op.VehicleId!;
var remote = await FetchRemoteSingleAsync(id, cancellationToken).ConfigureAwait(false);
if (remote != null && op.AnchorUpdateTime != null && remote.UpdateTime != op.AnchorUpdateTime)
{
UpsertLocalCache(remote);
return new PendingReplayResult(true, true, id);
}
var ok = await RemoteUpdateStatusAsync(id, op.Status!, cancellationToken).ConfigureAwait(false);
return ok
? new PendingReplayResult(true, false, id)
: new PendingReplayResult(false, false, null);
}
default:
return new PendingReplayResult(true, false, null);
}
}
catch (Exception ex)
{
_logger.Warning($"[车辆推送] 执行异常 op={op.OpType}, vehicleId={op.VehicleId}, err={ex.Message}");
return new PendingReplayResult(false, false, null);
}
}
private void RemovePendingOpsByVehicleId(string vehicleId)
{
lock (_cacheLock)
{
_pendingOps.RemoveAll(x =>
(!string.IsNullOrWhiteSpace(x.VehicleId) &&
string.Equals(x.VehicleId, vehicleId, StringComparison.OrdinalIgnoreCase)) ||
(x.Vehicle?.Id != null && string.Equals(x.Vehicle.Id, vehicleId, StringComparison.OrdinalIgnoreCase)));
SavePendingOpsToDiskUnsafe();
}
}
private async Task<MesXslVehicle?> FetchRemoteSingleAsync(string id, CancellationToken cancellationToken)
{
try
{
var url = $"{BaseUrl}/xslmes/mesXslVehicle/anon/queryById?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}";
using var client = CreateClient();
var resp = await client.GetAsync(url, cancellationToken).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return null;
var json = await resp.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("result", out var resultEl))
return resultEl.Deserialize<MesXslVehicle>(_jsonOpts);
return null;
}
catch
{
return null;
}
}
private static List<MesXslVehicle> ApplyFilters(
List<MesXslVehicle> source,
string? plateNumber,
string? vehicleBelong,
string? status)
{
IEnumerable<MesXslVehicle> query = source;
if (!string.IsNullOrWhiteSpace(plateNumber))
{
query = query.Where(v => (v.PlateNumber ?? string.Empty).Contains(plateNumber, StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrWhiteSpace(vehicleBelong))
{
query = query.Where(v => string.Equals(v.VehicleBelong, vehicleBelong, StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrWhiteSpace(status))
{
query = query.Where(v => string.Equals(v.Status, status, StringComparison.OrdinalIgnoreCase));
}
return query.OrderByDescending(v => v.CreateTime ?? DateTime.MinValue).ToList();
}
private List<MesXslVehicle> ApplyPendingOpsSnapshotUnsafe(List<MesXslVehicle> source)
{
var map = source
.Where(v => !string.IsNullOrWhiteSpace(v.Id))
.ToDictionary(v => v.Id!, CloneVehicle, StringComparer.OrdinalIgnoreCase);
foreach (var op in _pendingOps.OrderBy(x => x.CreatedAt))
{
switch (op.OpType)
{
case VehicleOperationType.Add:
case VehicleOperationType.Edit:
if (op.Vehicle != null && !string.IsNullOrWhiteSpace(op.Vehicle.Id))
{
map[op.Vehicle.Id] = CloneVehicle(op.Vehicle);
}
break;
case VehicleOperationType.Delete:
if (!string.IsNullOrWhiteSpace(op.VehicleId))
{
map.Remove(op.VehicleId);
}
break;
case VehicleOperationType.UpdateStatus:
if (!string.IsNullOrWhiteSpace(op.VehicleId)
&& !string.IsNullOrWhiteSpace(op.Status)
&& map.TryGetValue(op.VehicleId, out var v))
{
v.Status = op.Status;
}
break;
}
}
return map.Values.ToList();
}
private void EnqueuePendingOperation(VehiclePendingOperation op)
{
lock (_cacheLock)
{
_pendingOps.Add(op);
SavePendingOpsToDiskUnsafe();
_logger.Information($"[车辆入队] op={op.OpType}, vehicleId={op.VehicleId}, pending={_pendingOps.Count}");
}
}
private void UpsertLocalCache(MesXslVehicle vehicle)
{
lock (_cacheLock)
{
var idx = _localCache.FindIndex(v => string.Equals(v.Id, vehicle.Id, StringComparison.OrdinalIgnoreCase));
if (idx >= 0)
{
_localCache[idx] = CloneVehicle(vehicle);
}
else
{
_localCache.Insert(0, CloneVehicle(vehicle));
}
SaveCacheToDiskUnsafe();
}
}
private void RemoveFromLocalCache(string id)
{
lock (_cacheLock)
{
_localCache.RemoveAll(v => string.Equals(v.Id, id, StringComparison.OrdinalIgnoreCase));
SaveCacheToDiskUnsafe();
}
}
private void UpdateLocalStatus(string id, string status)
{
lock (_cacheLock)
{
var item = _localCache.FirstOrDefault(v => string.Equals(v.Id, id, StringComparison.OrdinalIgnoreCase));
if (item != null)
{
item.Status = status;
SaveCacheToDiskUnsafe();
}
}
}
private void LoadPendingOpsFromDisk()
{
try
{
if (!File.Exists(_pendingOpsFilePath)) return;
var json = File.ReadAllText(_pendingOpsFilePath);
var data = JsonSerializer.Deserialize<List<VehiclePendingOperation>>(json, _jsonOpts);
_pendingOps = data ?? new List<VehiclePendingOperation>();
_logger.Information($"[车辆本地] 载入待上传成功 count={_pendingOps.Count}");
}
catch (Exception ex)
{
_pendingOps = new List<VehiclePendingOperation>();
_logger.Warning($"[车辆本地] 载入待上传失败,已清空:{ex.Message}");
}
}
private void LoadCacheFromDisk()
{
try
{
if (!File.Exists(_cacheFilePath)) return;
var json = File.ReadAllText(_cacheFilePath);
var data = JsonSerializer.Deserialize<List<MesXslVehicle>>(json, _jsonOpts);
_localCache = data ?? new List<MesXslVehicle>();
_logger.Information($"[车辆本地] 载入缓存成功 count={_localCache.Count}");
}
catch (Exception ex)
{
_localCache = new List<MesXslVehicle>();
_logger.Warning($"[车辆本地] 载入缓存失败,已清空:{ex.Message}");
}
}
private void SavePendingOpsToDiskUnsafe()
{
var json = JsonSerializer.Serialize(_pendingOps, _jsonOpts);
File.WriteAllText(_pendingOpsFilePath, json);
}
private void SaveCacheToDiskUnsafe()
{
var json = JsonSerializer.Serialize(_localCache, _jsonOpts);
File.WriteAllText(_cacheFilePath, json);
}
private static MesXslVehicle CloneVehicle(MesXslVehicle input)
{
return new MesXslVehicle
{
Id = input.Id,
PlateNumber = input.PlateNumber,
VehicleBelong = input.VehicleBelong,
TareWeightKg = input.TareWeightKg,
LoadCapacity = input.LoadCapacity,
UnitId = input.UnitId,
LoadUnit = input.LoadUnit,
CustomerIds = input.CustomerIds,
CustomerShortName = input.CustomerShortName,
SupplierId = input.SupplierId,
SupplierName = input.SupplierName,
SupplierShortName = input.SupplierShortName,
VehicleLength = input.VehicleLength,
VehicleWidth = input.VehicleWidth,
VehicleHeight = input.VehicleHeight,
DriverName = input.DriverName,
DriverPhone = input.DriverPhone,
Status = input.Status,
TenantId = input.TenantId,
CreateBy = input.CreateBy,
CreateTime = input.CreateTime,
UpdateBy = input.UpdateBy,
UpdateTime = input.UpdateTime,
SysOrgCode = input.SysOrgCode
};
}
private static bool IsLocalTempId(string? id)
{
return !string.IsNullOrWhiteSpace(id)
&& id.StartsWith("local-", StringComparison.OrdinalIgnoreCase);
}
private sealed class VehiclePendingOperation
{
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public VehicleOperationType OpType { get; set; }
public string? VehicleId { get; set; }
public string? Status { get; set; }
public MesXslVehicle? Vehicle { get; set; }
// 冲突检测用的版本锚点:当本地首次针对该车辆产生修改时,记录当时的服务器 UpdateTime
public DateTime? AnchorUpdateTime { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public int RetryCount { get; set; } = 0;
}
private enum VehicleOperationType
{
Add = 1,
Edit = 2,
Delete = 3,
UpdateStatus = 4
}
/// <summary>
/// 兼容 Jeecg 常见时间字符串格式yyyy-MM-dd HH:mm:ss
/// </summary>
private sealed class NullableDateTimeJsonConverter : JsonConverter<DateTime?>
{
private static readonly string[] SupportedFormats =
[
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ssZ",
"yyyy-MM-ddTHH:mm:ss.fffZ"
];
public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
return null;
}
if (reader.TokenType == JsonTokenType.String)
{
var raw = reader.GetString();
if (string.IsNullOrWhiteSpace(raw))
{
return null;
}
if (DateTime.TryParseExact(raw, SupportedFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal, out var exact))
{
return exact;
}
if (DateTime.TryParse(raw, out var fallback))
{
return fallback;
}
}
throw new JsonException($"无法将 JSON 值转换为 DateTime?token={reader.TokenType}");
}
public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
{
if (value.HasValue)
{
writer.WriteStringValue(value.Value.ToString("yyyy-MM-dd HH:mm:ss"));
return;
}
writer.WriteNullValue();
}
}
}

View File

@@ -0,0 +1,81 @@
using Prism.Events;
using System.Text.Json;
using YY.Admin.Core;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
namespace YY.Admin.Services.Service.Vehicle;
/// <summary>
/// 监听 STOMP 收到的车辆变更信号,转发为桌面端 Prism 事件,触发列表刷新。
/// </summary>
public class VehicleSyncCoordinator : ISingletonDependency
{
private readonly IEventAggregator _eventAggregator;
private readonly ILoggerService _logger;
private SubscriptionToken? _remoteCommandToken;
private SubscriptionToken? _networkStatusToken;
public VehicleSyncCoordinator(IEventAggregator eventAggregator, ILoggerService logger)
{
_eventAggregator = eventAggregator;
_logger = logger;
_remoteCommandToken = _eventAggregator
.GetEvent<RemoteCommandReceivedEvent>()
.Subscribe(OnRemoteCommand, ThreadOption.BackgroundThread);
// 断线重连后补拉一次,覆盖离线期间漏掉的 STOMP 事件
_networkStatusToken = _eventAggregator
.GetEvent<NetworkStatusChangedEvent>()
.Subscribe(OnNetworkStatusChanged, ThreadOption.BackgroundThread);
_logger.Information("[车辆推送] VehicleSyncCoordinator 已启动,开始监听 RemoteCommandReceivedEvent");
}
private void OnNetworkStatusChanged(NetworkStatusChangedPayload payload)
{
if (!payload.IsOnline) return;
_logger.Information("[车辆推送] 网络恢复,触发补偿刷新");
_eventAggregator.GetEvent<VehicleChangedEvent>().Publish(new VehicleChangedPayload { Action = "reconnect" });
}
private void OnRemoteCommand(RemoteCommandPayload payload)
{
try
{
var json = payload.CommandJson ?? string.Empty;
if (string.IsNullOrWhiteSpace(json))
{
_logger.Information("[车辆推送] 收到空命令,忽略");
return;
}
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("cmd", out var cmdEl))
{
_logger.Information("[车辆推送] 命令无cmd字段忽略");
return;
}
var cmd = cmdEl.GetString() ?? string.Empty;
if (!cmd.Equals("MES_VEHICLE_CHANGED", StringComparison.OrdinalIgnoreCase))
{
_logger.Information($"[车辆推送] 非车辆命令 cmd={cmd},忽略");
return;
}
doc.RootElement.TryGetProperty("action", out var actionEl);
doc.RootElement.TryGetProperty("vehicleId", out var idEl);
var changedPayload = new VehicleChangedPayload
{
Action = actionEl.GetString() ?? string.Empty,
VehicleId = idEl.ValueKind == JsonValueKind.String ? idEl.GetString() : null,
};
_logger.Information($"收到车辆变更信号: action={changedPayload.Action}, vehicleId={changedPayload.VehicleId}");
_eventAggregator.GetEvent<VehicleChangedEvent>().Publish(changedPayload);
}
catch (Exception ex)
{
_logger.Warning($"处理 STOMP 车辆变更信号失败: {ex.Message}");
}
}
}

View File

@@ -18,6 +18,10 @@
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="Configuration\appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>

View File

@@ -0,0 +1,10 @@
using Prism.Events;
namespace YY.Admin.Event;
/// <summary>
/// 本地 sys_menu 结构变更后通知左侧菜单树重新加载
/// </summary>
public class MenuStructureChangedEvent : PubSubEvent<bool>
{
}

View File

@@ -20,8 +20,7 @@ namespace YY.Admin.FluentValidation
{
var exists = await _userService.AccountExistsAsync(account, user.Id);
return !exists;
}).WithMessage("账号已存在")
.When(x => x.Id == 0);
}).WithMessage("账号已存在");
RuleFor(x => x.RealName)
.NotEmpty().WithMessage("姓名不能为空")

View File

@@ -19,6 +19,10 @@ namespace YY.Admin.Helper
public string BasePath { get; set; } = "/jeecg-boot";
public string WebSocketUrl { get; set; } = string.Empty;
public string WebSocketPath { get; set; } = DefaultWebSocketPath;
/// <summary>
/// 是否断开连接true=断开false=连接)
/// </summary>
public bool DisconnectConnection { get; set; } = false;
}
public static string GetConfigPath()
@@ -54,6 +58,7 @@ namespace YY.Admin.Helper
model.WebSocketUrl = jeecg.Value<string>("WebSocketUrl") ?? string.Empty;
model.WebSocketPath = NormalizeWebSocketPath(jeecg.Value<string>("WebSocketPath"));
model.DisconnectConnection = jeecg.Value<bool?>("DisconnectConnection") ?? false;
return model;
}
@@ -88,6 +93,7 @@ namespace YY.Admin.Helper
jeecg["BaseUrl"] = baseUrl;
jeecg["WebSocketUrl"] = webSocketUrl;
jeecg["WebSocketPath"] = webSocketPath;
jeecg["DisconnectConnection"] = model.DisconnectConnection;
File.WriteAllText(path, root.ToString(Formatting.Indented));
}

View File

@@ -3,29 +3,62 @@ using Prism.Events;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Timers;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
using YY.Admin.Core.Session;
using YY.Admin.Helper;
using YY.Admin.Infrastructure.Storage;
namespace YY.Admin.Infrastructure.Hubs;
public class StompWebSocketService : ISignalRService
{
// STOMP heart-beat: send \n every 10 s, declare we want to receive every 10 s
private const int HeartbeatMs = 10_000;
// Watchdog: if nothing received in 3 × HeartbeatMs, treat connection as zombie
private const int WatchdogMs = 30_000;
private readonly IConfiguration _configuration;
private readonly IEventAggregator _eventAggregator;
private readonly TokenStore _tokenStore;
private readonly INetworkMonitor _networkMonitor;
private ClientWebSocket? _socket;
private string _deviceId = "default-device";
private string _token = string.Empty;
private CancellationTokenSource? _connectionCts;
private System.Timers.Timer? _heartbeatTimer;
private System.Timers.Timer? _watchdogTimer;
private volatile int _lastReceivedTick = Environment.TickCount;
public StompWebSocketService(
IConfiguration configuration,
IEventAggregator eventAggregator,
TokenStore tokenStore)
TokenStore tokenStore,
INetworkMonitor networkMonitor)
{
_configuration = configuration;
_eventAggregator = eventAggregator;
_tokenStore = tokenStore;
_networkMonitor = networkMonitor;
// When the network comes back online, reconnect the STOMP channel if it is down.
eventAggregator.GetEvent<NetworkStatusChangedEvent>()
.Subscribe(OnNetworkStatusChanged, ThreadOption.BackgroundThread);
}
private void OnNetworkStatusChanged(NetworkStatusChangedPayload payload)
{
if (!payload.IsOnline || IsDisconnectedByUser())
{
return;
}
if (_socket == null || _socket.State != WebSocketState.Open)
{
_ = Task.Run(() => ConnectUnifiedDeviceChannelAsync(CancellationToken.None));
}
}
/// <inheritdoc />
@@ -38,6 +71,12 @@ public class StompWebSocketService : ISignalRService
/// <inheritdoc />
public async Task ConnectUnifiedDeviceChannelAsync(CancellationToken cancellationToken = default)
{
if (IsDisconnectedByUser())
{
await DisconnectAsync(cancellationToken).ConfigureAwait(false);
return;
}
var anonymous = _configuration.GetValue("JeecgIntegration:AnonymousMode", true);
if (anonymous)
{
@@ -61,41 +100,70 @@ public class StompWebSocketService : ISignalRService
try
{
// Tear down previous session before opening a new one.
var oldCts = Interlocked.Exchange(ref _connectionCts, null);
oldCts?.Cancel();
oldCts?.Dispose();
StopTimers();
_socket?.Dispose();
_socket = new ClientWebSocket();
_socket.Options.AddSubProtocol("v12.stomp");
await _socket.ConnectAsync(new Uri(wsUrl), cancellationToken).ConfigureAwait(false);
var connectFrame = anonymous || string.IsNullOrWhiteSpace(_token)
? "CONNECT\naccept-version:1.2\nheart-beat:10000,10000\n\n\0"
: BuildConnectFrame(_token);
? BuildConnectFrame(null, _deviceId)
: BuildConnectFrame(_token, _deviceId);
await SendFrameAsync(connectFrame, cancellationToken).ConfigureAwait(false);
// 用户镜像变更:与后端 /topic/sync/jeecg-users 对齐(设备同步统一线路)
await SendFrameAsync(BuildSubscribeFrame("sub-jeecg-users", "/topic/sync/jeecg-users"), cancellationToken).ConfigureAwait(false);
// 用户镜像变更:订阅 /topic/sync/jeecg-users
await SendFrameAsync(
BuildSubscribeFrame("sub-jeecg-users", "/topic/sync/jeecg-users"),
cancellationToken).ConfigureAwait(false);
// 车辆数据变更:订阅 /topic/sync/mes-vehicles
await SendFrameAsync(
BuildSubscribeFrame("sub-mes-vehicles", "/topic/sync/mes-vehicles"),
cancellationToken).ConfigureAwait(false);
// 客户数据变更:订阅 /topic/sync/mes-customers
await SendFrameAsync(
BuildSubscribeFrame("sub-mes-customers", "/topic/sync/mes-customers"),
cancellationToken).ConfigureAwait(false);
// 供应商数据变更:订阅 /topic/sync/mes-suppliers
await SendFrameAsync(
BuildSubscribeFrame("sub-mes-suppliers", "/topic/sync/mes-suppliers"),
cancellationToken).ConfigureAwait(false);
// 订阅服务端 PONG 回复(应用层假在线检测)
await SendFrameAsync(
BuildSubscribeFrame("sub-device-pong", $"/topic/device/{_deviceId}/pong"),
cancellationToken).ConfigureAwait(false);
// 非免密时同时订阅设备点对点指令队列
if (!anonymous && !string.IsNullOrWhiteSpace(_token))
{
await SendFrameAsync(BuildSubscribeFrame("sub-device-command", $"/user/{_deviceId}/queue/command"), cancellationToken).ConfigureAwait(false);
await SendFrameAsync(
BuildSubscribeFrame("sub-device-command", $"/user/{_deviceId}/queue/command"),
cancellationToken).ConfigureAwait(false);
}
_eventAggregator.GetEvent<NetworkStatusChangedEvent>().Publish(new NetworkStatusChangedPayload
{
IsOnline = true,
ChangedAt = DateTime.UtcNow
});
// Reset watchdog baseline to now.
_lastReceivedTick = Environment.TickCount;
_ = Task.Run(() => ReceiveLoopAsync(cancellationToken), cancellationToken);
var cts = new CancellationTokenSource();
_connectionCts = cts;
StartHeartbeatTimer(cts.Token);
StartWatchdogTimer(cts.Token);
_networkMonitor.SetStompTransportOnline(true);
_ = Task.Run(() => ReceiveLoopAsync(cts.Token), cts.Token);
return;
}
catch
{
_eventAggregator.GetEvent<NetworkStatusChangedEvent>().Publish(new NetworkStatusChangedPayload
{
IsOnline = false,
ChangedAt = DateTime.UtcNow
});
_networkMonitor.SetStompTransportOnline(false);
}
}
}
@@ -103,19 +171,149 @@ public class StompWebSocketService : ISignalRService
/// <inheritdoc />
public async Task SendDeviceStatusAsync(object status, CancellationToken cancellationToken = default)
{
if (_socket == null || _socket.State != WebSocketState.Open)
if (IsDisconnectedByUser() || _socket == null || _socket.State != WebSocketState.Open)
{
return;
}
var json = System.Text.Json.JsonSerializer.Serialize(status);
var frame = $"SEND\n" +
$"destination:/app/device/status\n" +
$"content-type:application/json\n" +
var frame = "SEND\n" +
"destination:/app/device/status\n" +
"content-type:application/json\n" +
$"content-length:{Encoding.UTF8.GetByteCount(json)}\n\n" +
$"{json}\0";
await SendFrameAsync(frame, cancellationToken).ConfigureAwait(false);
}
public async Task DisconnectAsync(CancellationToken cancellationToken = default)
{
var cts = Interlocked.Exchange(ref _connectionCts, null);
cts?.Cancel();
cts?.Dispose();
StopTimers();
var socket = _socket;
_socket = null;
if (socket == null)
{
_networkMonitor.SetStompTransportOnline(false);
return;
}
try
{
if (socket.State == WebSocketState.Open || socket.State == WebSocketState.CloseReceived)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "manual disconnect", cancellationToken).ConfigureAwait(false);
}
}
catch
{
socket.Abort();
}
finally
{
socket.Dispose();
_networkMonitor.SetStompTransportOnline(false);
}
}
// ── Heartbeat ──────────────────────────────────────────────────────────
private void StartHeartbeatTimer(CancellationToken cancellationToken)
{
_heartbeatTimer = new System.Timers.Timer(HeartbeatMs) { AutoReset = true };
_heartbeatTimer.Elapsed += async (_, _) =>
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
// STOMP protocol keepalive (\n frame)
await SendStompHeartbeatAsync(cancellationToken).ConfigureAwait(false);
// Application-layer PING: server replies to /topic/device/{id}/pong
await SendAppPingAsync(cancellationToken).ConfigureAwait(false);
};
_heartbeatTimer.Start();
}
private async Task SendStompHeartbeatAsync(CancellationToken cancellationToken)
{
if (_socket == null || _socket.State != WebSocketState.Open)
{
return;
}
try
{
// STOMP spec: a single LF (0x0A) constitutes a heartbeat frame.
await _socket.SendAsync(
new ArraySegment<byte>(new byte[] { 0x0A }),
WebSocketMessageType.Text,
true,
cancellationToken).ConfigureAwait(false);
}
catch
{
// Send failure will be caught by the watchdog.
}
}
private async Task SendAppPingAsync(CancellationToken cancellationToken)
{
if (_socket == null || _socket.State != WebSocketState.Open)
{
return;
}
try
{
var body = $"{{\"cmd\":\"PING_DEVICE\",\"deviceId\":\"{_deviceId}\",\"ts\":{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}}}";
var frame = "SEND\n" +
"destination:/app/device/ping\n" +
"content-type:application/json\n" +
$"content-length:{Encoding.UTF8.GetByteCount(body)}\n\n" +
$"{body}\0";
await SendFrameAsync(frame, cancellationToken).ConfigureAwait(false);
}
catch
{
// Watchdog handles reconnect.
}
}
// ── Watchdog ───────────────────────────────────────────────────────────
private void StartWatchdogTimer(CancellationToken cancellationToken)
{
_watchdogTimer = new System.Timers.Timer(WatchdogMs) { AutoReset = true };
_watchdogTimer.Elapsed += (_, _) =>
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
// TickCount wraps; unchecked subtraction handles it correctly.
var silenceMs = unchecked(Environment.TickCount - _lastReceivedTick);
if (silenceMs >= WatchdogMs)
{
// No frame (heartbeat or MESSAGE) received for WatchdogMs — zombie connection.
_ = Task.Run(() => ConnectUnifiedDeviceChannelAsync(CancellationToken.None));
}
};
_watchdogTimer.Start();
}
private void StopTimers()
{
_heartbeatTimer?.Stop();
_heartbeatTimer?.Dispose();
_heartbeatTimer = null;
_watchdogTimer?.Stop();
_watchdogTimer?.Dispose();
_watchdogTimer = null;
}
// ── Receive loop ───────────────────────────────────────────────────────
private async Task ReceiveLoopAsync(CancellationToken cancellationToken)
{
if (_socket == null)
@@ -132,17 +330,16 @@ public class StompWebSocketService : ISignalRService
result = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
{
_eventAggregator.GetEvent<NetworkStatusChangedEvent>().Publish(new NetworkStatusChangedPayload
{
IsOnline = false,
ChangedAt = DateTime.UtcNow
});
_networkMonitor.SetStompTransportOnline(false);
await ConnectUnifiedDeviceChannelAsync(cancellationToken).ConfigureAwait(false);
return;
}
ms.Write(buffer, 0, result.Count);
} while (!result.EndOfMessage);
// Any received frame (heartbeat \n or MESSAGE) resets the watchdog.
_lastReceivedTick = Environment.TickCount;
var text = Encoding.UTF8.GetString(ms.ToArray());
if (!text.StartsWith("MESSAGE", StringComparison.OrdinalIgnoreCase))
{
@@ -169,21 +366,27 @@ public class StompWebSocketService : ISignalRService
return;
}
var data = Encoding.UTF8.GetBytes(frame);
await _socket.SendAsync(new ArraySegment<byte>(data), WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false);
await _socket.SendAsync(
new ArraySegment<byte>(data),
WebSocketMessageType.Text,
true,
cancellationToken).ConfigureAwait(false);
}
// ── Helpers ────────────────────────────────────────────────────────────
private string ResolveWsUrl()
{
var baseUrl = _configuration.GetValue<string>("JeecgIntegration:BaseUrl")?.TrimEnd('/');
if (string.IsNullOrWhiteSpace(baseUrl))
{
return "ws://127.0.0.1:8080/jeecg-boot/ws/device/websocket";
return "ws://127.0.0.1:8080/jeecg-boot/ws/device";
}
if (baseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return "wss://" + baseUrl["https://".Length..] + "/ws/device/websocket";
return "wss://" + baseUrl["https://".Length..] + "/ws/device";
}
return "ws://" + baseUrl["http://".Length..] + "/ws/device/websocket";
return "ws://" + baseUrl["http://".Length..] + "/ws/device";
}
private static string ResolveDeviceId(string token)
@@ -215,12 +418,22 @@ public class StompWebSocketService : ISignalRService
}
}
private static string BuildConnectFrame(string token)
private static string BuildConnectFrame(string? token, string deviceId)
{
return "CONNECT\n" +
"accept-version:1.2\n" +
"heart-beat:10000,10000\n" +
$"Authorization:Bearer {token}\n\n\0";
var user = AppSession.CurrentUser;
var sb = new System.Text.StringBuilder();
sb.Append("CONNECT\n");
sb.Append("accept-version:1.2\n");
sb.Append($"heart-beat:{HeartbeatMs},{HeartbeatMs}\n");
if (!string.IsNullOrWhiteSpace(token))
sb.Append($"Authorization:Bearer {token}\n");
sb.Append("platform:desktop\n");
sb.Append($"hostName:{Environment.MachineName}\n");
sb.Append($"deviceId:{deviceId}\n");
sb.Append($"userName:{user?.Account ?? "unknown"}\n");
sb.Append($"realName:{user?.RealName ?? ""}\n");
sb.Append("\n\0");
return sb.ToString();
}
private static string BuildSubscribeFrame(string subscriptionId, string destination)
@@ -230,4 +443,16 @@ public class StompWebSocketService : ISignalRService
$"destination:{destination}\n" +
"ack:auto\n\n\0";
}
private static bool IsDisconnectedByUser()
{
try
{
return ServerSettingsStore.Load().DisconnectConnection;
}
catch
{
return false;
}
}
}

View File

@@ -0,0 +1,26 @@
using System.Net;
using System.Net.Http;
using YY.Admin.Helper;
namespace YY.Admin.Infrastructure.Network;
/// <summary>
/// 全局断开保护:用户勾选"断开连接"时,直接短路所有后端 HTTP 请求,
/// 返回 499 而不发起真实网络调用,各服务的 catch/IsSuccessStatusCode 分支自行降级。
/// </summary>
internal sealed class DisconnectGuardHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (ServerSettingsStore.Load().DisconnectConnection)
{
return Task.FromResult(new HttpResponseMessage((HttpStatusCode)499)
{
ReasonPhrase = "User Disconnected"
});
}
return base.SendAsync(request, cancellationToken);
}
}

View File

@@ -3,6 +3,7 @@ using Prism.Events;
using System.Net.Http;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
using YY.Admin.Helper;
namespace YY.Admin.Infrastructure.Network;
@@ -12,8 +13,11 @@ public class NetworkMonitor : INetworkMonitor
private readonly IConfiguration _configuration;
private readonly IEventAggregator _eventAggregator;
private readonly SemaphoreSlim _startLock = new(1, 1);
private readonly object _aggregateLock = new();
private Task? _loopTask;
private CancellationTokenSource? _cts;
private volatile bool _httpProbeOnline;
private volatile bool _stompTransportOnline;
private volatile bool _isOnline;
public NetworkMonitor(
@@ -30,6 +34,13 @@ public class NetworkMonitor : INetworkMonitor
public event Action<bool>? StatusChanged;
/// <inheritdoc />
public void SetStompTransportOnline(bool online)
{
_stompTransportOnline = online;
RecomputeAggregatedOnline();
}
public async Task StartAsync(CancellationToken cancellationToken = default)
{
await _startLock.WaitAsync(cancellationToken).ConfigureAwait(false);
@@ -51,27 +62,63 @@ public class NetworkMonitor : INetworkMonitor
private async Task MonitorLoopAsync(CancellationToken cancellationToken)
{
// 启动后立即探活一次,避免首屏 10 秒内 IsOnline 恒为 false
await RunHttpProbeAndRecomputeAsync(cancellationToken).ConfigureAwait(false);
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false))
{
var online = await ProbeAsync(cancellationToken).ConfigureAwait(false);
if (online == _isOnline)
await RunHttpProbeAndRecomputeAsync(cancellationToken).ConfigureAwait(false);
}
}
private async Task RunHttpProbeAndRecomputeAsync(CancellationToken cancellationToken)
{
var httpOk = await ProbeAsync(cancellationToken).ConfigureAwait(false);
_httpProbeOnline = httpOk;
RecomputeAggregatedOnline();
}
private void RecomputeAggregatedOnline()
{
var combined = ComputeCombinedOnline();
bool newValue;
lock (_aggregateLock)
{
if (combined == _isOnline)
{
continue;
return;
}
_isOnline = online;
StatusChanged?.Invoke(online);
_eventAggregator.GetEvent<NetworkStatusChangedEvent>().Publish(new NetworkStatusChangedPayload
{
IsOnline = online,
ChangedAt = DateTime.UtcNow
});
_isOnline = combined;
newValue = combined;
}
StatusChanged?.Invoke(newValue);
_eventAggregator.GetEvent<NetworkStatusChangedEvent>().Publish(new NetworkStatusChangedPayload
{
IsOnline = newValue,
ChangedAt = DateTime.UtcNow
});
}
private bool ComputeCombinedOnline()
{
if (IsDisconnectedByUser())
{
return false;
}
return _httpProbeOnline || _stompTransportOnline;
}
private async Task<bool> ProbeAsync(CancellationToken cancellationToken)
{
if (IsDisconnectedByUser())
{
return false;
}
var baseUrl = _configuration.GetValue<string>("JeecgIntegration:BaseUrl")?.TrimEnd('/');
if (string.IsNullOrWhiteSpace(baseUrl))
{
@@ -108,4 +155,16 @@ public class NetworkMonitor : INetworkMonitor
return false;
}
private static bool IsDisconnectedByUser()
{
try
{
return ServerSettingsStore.Load().DisconnectConnection;
}
catch
{
return false;
}
}
}

View File

@@ -0,0 +1,74 @@
using YY.Admin.Core.Services;
using YY.Admin.Core.Sync;
namespace YY.Admin.Infrastructure.Sync;
/// <summary>
/// 将桌面用户 CRUD 写入 Outbox通过 /sys/sync/batch 反同步到 Jeecg 后端。
/// 断网时自动持久化,联网后续传。
/// </summary>
public sealed class UserSyncOutbox : IUserSyncOutbox
{
private readonly OutboxProcessor _outboxProcessor;
public UserSyncOutbox(OutboxProcessor outboxProcessor)
{
_outboxProcessor = outboxProcessor;
}
public Task EnqueueCreateAsync(
string userId, string account, string? realName, int? sex, DateTime? birthday, string? phone, string? email, int status, string? updateBy,
CancellationToken cancellationToken = default)
{
return _outboxProcessor.EnqueueAsync(
SysUserSyncOutbox.AggregateType,
userId,
SysUserSyncOutbox.EventCreate,
new { userId, account, realName, sex, birthday, phone, email, status, updateBy },
cancellationToken);
}
public Task EnqueueUpdateAsync(
string userId, string account, string? realName, int? sex, DateTime? birthday, string? phone, string? email, int status, string? updateBy,
CancellationToken cancellationToken = default)
{
return _outboxProcessor.EnqueueAsync(
SysUserSyncOutbox.AggregateType,
userId,
SysUserSyncOutbox.EventUpdate,
new { userId, account, realName, sex, birthday, phone, email, status, updateBy },
cancellationToken);
}
public Task EnqueueToggleStatusAsync(
string userId, int status, string? updateBy,
CancellationToken cancellationToken = default)
{
return _outboxProcessor.EnqueueAsync(
SysUserSyncOutbox.AggregateType,
userId,
SysUserSyncOutbox.EventToggleStatus,
new { userId, status, updateBy },
cancellationToken);
}
public Task EnqueueDeleteAsync(string userId, CancellationToken cancellationToken = default)
{
return _outboxProcessor.EnqueueAsync(
SysUserSyncOutbox.AggregateType,
userId,
SysUserSyncOutbox.EventDelete,
new { userId },
cancellationToken);
}
public Task EnqueueBatchDeleteAsync(IReadOnlyList<string> userIds, CancellationToken cancellationToken = default)
{
return _outboxProcessor.EnqueueAsync(
SysUserSyncOutbox.AggregateType,
string.Join(",", userIds),
SysUserSyncOutbox.EventBatchDelete,
new { userIds },
cancellationToken);
}
}

View File

@@ -7,6 +7,10 @@ using YY.Admin.Views;
using YY.Admin.Views.Control;
using YY.Admin.Views.Dialogs;
using YY.Admin.Views.SysManage;
using YY.Admin.Views.Customer;
using YY.Admin.Views.Supplier;
using YY.Admin.ViewModels.Vehicle;
using YY.Admin.Views.Vehicle;
namespace YY.Admin
{
@@ -49,7 +53,14 @@ namespace YY.Admin
containerRegistry.RegisterForNavigation<DataDictionaryManagementView>();
containerRegistry.RegisterForNavigation<RoleManagementView>();
containerRegistry.RegisterForNavigation<TenantManagementView>();
containerRegistry.RegisterForNavigation<MenuManagementView>();
containerRegistry.RegisterForNavigation<LoginSettingsView>();
// 车辆管理
containerRegistry.RegisterForNavigation<VehicleListView>();
// 客户管理
containerRegistry.RegisterForNavigation<CustomerListView>();
// 供应商管理
containerRegistry.RegisterForNavigation<SupplierListView>();
}
}
public class DialogWindow : Window, IDialogWindow

View File

@@ -5,11 +5,17 @@ using Polly.Extensions.Http;
using Prism.Ioc;
using Prism.Modularity;
using System.Net.Http;
using System.Text;
using YY.Admin.Core.Services;
using YY.Admin.Core.Session;
using YY.Admin.EventBus;
using YY.Admin.Infrastructure.Hubs;
using YY.Admin.Infrastructure.Network;
using YY.Admin.Infrastructure.Storage;
using YY.Admin.Infrastructure.Sync;
using YY.Admin.Services.Service.Customer;
using YY.Admin.Services.Service.Supplier;
using YY.Admin.Services.Service.Vehicle;
namespace YY.Admin.Module;
@@ -23,8 +29,22 @@ public class SyncModule : IModule
containerRegistry.RegisterSingleton<IJeecgUserMirrorPullOutbox, JeecgUserMirrorPullOutbox>();
containerRegistry.RegisterSingleton<INetworkMonitor, NetworkMonitor>();
containerRegistry.RegisterSingleton<ISignalRService, StompWebSocketService>();
containerRegistry.RegisterSingleton<IUserSyncOutbox, UserSyncOutbox>();
// 本地用户事件订阅器:将增删改操作入 Outbox 回传后端
containerRegistry.RegisterSingleton<SysUserEventSubscriber>();
// 车辆管理:免密 API 直连 + STOMP 实时通知
containerRegistry.RegisterSingleton<IVehicleService, VehicleService>();
containerRegistry.RegisterSingleton<VehicleSyncCoordinator>();
// 客户管理:免密 API 直连 + STOMP 实时通知
containerRegistry.RegisterSingleton<ICustomerService, CustomerService>();
containerRegistry.RegisterSingleton<CustomerSyncCoordinator>();
// 供应商管理:免密 API 直连 + STOMP 实时通知
containerRegistry.RegisterSingleton<ISupplierService, SupplierService>();
containerRegistry.RegisterSingleton<SupplierSyncCoordinator>();
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient<DisconnectGuardHandler>();
serviceCollection.AddHttpClient("JeecgApi", (sp, client) =>
{
var config = containerRegistry.GetContainer().Resolve<IConfiguration>();
@@ -40,7 +60,14 @@ public class SyncModule : IModule
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}
}).AddPolicyHandler(GetRetryPolicy());
client.DefaultRequestHeaders.TryAddWithoutValidation("X-Platform", "desktop");
// .NET HttpClient 要求请求头值为 ASCII主机名/中文姓名否则会报 Request headers must contain only ASCII characters
client.DefaultRequestHeaders.TryAddWithoutValidation("X-Host-Name", ToAsciiHttpHeaderValue(Environment.MachineName));
var currentUser = AppSession.CurrentUser;
client.DefaultRequestHeaders.TryAddWithoutValidation("X-User-Name", ToAsciiHttpHeaderValue(currentUser?.Account ?? "unknown"));
client.DefaultRequestHeaders.TryAddWithoutValidation("X-Real-Name", ToAsciiHttpHeaderValue(currentUser?.RealName ?? ""));
}).AddPolicyHandler(GetRetryPolicy())
.AddHttpMessageHandler<DisconnectGuardHandler>();
var provider = serviceCollection.BuildServiceProvider();
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
@@ -57,6 +84,14 @@ public class SyncModule : IModule
_ = outboxProcessor.StartConsumerAsync(CancellationToken.None);
// 用户镜像 + 设备指令:统一 STOMP/ws/device免密与设备 Token 模式均启动
_ = Task.Run(() => signalService.ConnectUnifiedDeviceChannelAsync(CancellationToken.None));
// 强制实例化事件订阅器(单例,构造函数内完成订阅注册)
_ = containerProvider.Resolve<SysUserEventSubscriber>();
// 强制实例化车辆同步协调器(构造函数内订阅 STOMP 车辆变更事件)
_ = containerProvider.Resolve<VehicleSyncCoordinator>();
// 强制实例化客户同步协调器
_ = containerProvider.Resolve<CustomerSyncCoordinator>();
// 强制实例化供应商同步协调器
_ = containerProvider.Resolve<SupplierSyncCoordinator>();
}
private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
@@ -66,4 +101,24 @@ public class SyncModule : IModule
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}
/// <summary>
/// 将自定义请求头转为 ASCII含非 ASCII 时整体做 UTF-8 Base64前缀 B64. 便于后端按需解码)。
/// </summary>
private static string ToAsciiHttpHeaderValue(string? value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
foreach (var c in value)
{
if (c > 127)
{
return "B64." + Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
}
}
return value;
}
}

View File

@@ -1,163 +1,107 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YY.Admin.Core;
using static YY.Admin.Core.SysUserEvents;
using Prism.Events;
namespace YY.Admin.EventBus
using YY.Admin.Core;
using YY.Admin.Core.Services;
using static YY.Admin.Core.SysUserEvents;
namespace YY.Admin.EventBus;
/// <summary>
/// 本地用户事件订阅器:记录本地 CRUD 操作日志。
/// 注意:本地操作不触发 mirror pull拉取会覆盖本地改动
/// 后端→桌面的实时同步由 JeecgUserSyncCoordinator 统一负责。
/// 实现 ISingletonDependency 使其由程序集扫描自动注册为单例。
/// </summary>
public class SysUserEventSubscriber : IDisposable, ISingletonDependency
{
public class SysUserEventSubscriber : IDisposable
private readonly IEventAggregator _eventAggregator;
private readonly ILoggerService _logger;
private readonly List<SubscriptionToken> _subscriptions = new();
public SysUserEventSubscriber(
IEventAggregator eventAggregator,
ILoggerService logger)
{
private readonly IEventAggregator _eventAggregator;
private readonly ILoggerService _logger;
private readonly List<SubscriptionToken> _subscriptions = new();
public SysUserEventSubscriber(
IEventAggregator eventAggregator,
ILoggerService logger)
{
_eventAggregator = eventAggregator;
_logger = logger;
SubscribeEvents();
}
public void SubscribeEvents()
{
_eventAggregator.GetEvent<AddUserEvent>().Subscribe(OnAddUser, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<UpdateUserEvent>().Subscribe(OnUpdateUser, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<DeleteUserEvent>().Subscribe(OnDeleteUser, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<SetUserStatusEvent>().Subscribe(OnSetUserStatus, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<ChangePwdEvent>().Subscribe(OnChangePwd, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<ResetPwdEvent>().Subscribe(OnResetPwd, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<UnlockUserLoginEvent>().Subscribe(OnUnlockUserLogin, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<RegisterUserEvent>().Subscribe(OnRegisterUser, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<LoginUserEvent>().Subscribe(OnLoginUser, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<LoginOutEvent>().Subscribe(OnLoginOut, ThreadOption.BackgroundThread);
_eventAggregator.GetEvent<UpdateUserRoleEvent>().Subscribe(OnUpdateUserRole, ThreadOption.BackgroundThread);
}
_eventAggregator = eventAggregator;
_logger = logger;
SubscribeEvents();
}
public void OnAddUser(SysUser payload)
{
try
{
_logger.Information($"添加新用户: {payload.Account}");
}
catch (Exception ex)
{
_logger.Error($"添加用户事件处理失败: {ex.Message}", ex);
}
}
private void SubscribeEvents()
{
_subscriptions.Add(_eventAggregator.GetEvent<AddUserEvent>().Subscribe(OnAddUser, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<UpdateUserEvent>().Subscribe(OnUpdateUser, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<DeleteUserEvent>().Subscribe(OnDeleteUser, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<SetUserStatusEvent>().Subscribe(OnSetUserStatus, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<ChangePwdEvent>().Subscribe(OnChangePwd, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<ResetPwdEvent>().Subscribe(OnResetPwd, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<UnlockUserLoginEvent>().Subscribe(OnUnlockUserLogin, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<RegisterUserEvent>().Subscribe(OnRegisterUser, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<LoginUserEvent>().Subscribe(OnLoginUser, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<LoginOutEvent>().Subscribe(OnLoginOut, ThreadOption.BackgroundThread));
_subscriptions.Add(_eventAggregator.GetEvent<UpdateUserRoleEvent>().Subscribe(OnUpdateUserRole, ThreadOption.BackgroundThread));
}
public void OnRegisterUser(SysUser payload)
{
try
{
Task.Run(() => {
});
_logger.Information($"用户注册");
}
catch (Exception ex)
{
_logger.Error($"注册用户事件处理失败: {ex.Message}", ex);
}
}
public void OnAddUser(SysUser payload)
{
_logger.Information($"[本地] 新增用户: {payload?.Account}");
}
public void OnUpdateUser((SysUser Original, SysUser Updated) payload)
{
try
{
_logger.Information($"更新用户");
}
catch (Exception ex)
{
_logger.Error($"更新用户事件处理失败: {ex.Message}", ex);
}
}
public void OnRegisterUser(SysUser payload)
{
_logger.Information($"[本地] 用户注册: {payload?.Account}");
}
public void OnDeleteUser(SysUser payload)
{
try
{
}
catch (Exception ex)
{
_logger.Error($"删除用户事件处理失败: {ex.Message}", ex);
}
}
public void OnUpdateUser((SysUser Original, SysUser Updated) payload)
{
_logger.Information($"[本地] 修改用户: {payload.Updated?.Account}");
}
public void OnSetUserStatus((SysUser User, StatusEnum NewStatus) payload)
{
try
{
}
catch (Exception ex)
{
_logger.Error($"设置用户状态事件处理失败: {ex.Message}", ex);
}
}
public void OnChangePwd(SysUser payload)
{
try
{
}
catch (Exception ex)
{
_logger.Error($"设置用户状态事件处理失败: {ex.Message}", ex);
}
}
public void OnUpdateUserRole((SysUser User, List<long> RoleIds) payload)
{
try
{
}
catch (Exception ex)
{
_logger.Error($"更新用户角色事件处理失败: {ex.Message}", ex);
}
}
public void OnDeleteUser(SysUser payload)
{
_logger.Information($"[本地] 删除用户: {payload?.Account}");
}
public void OnUnlockUserLogin(SysUser payload)
{
try
{
}
catch (Exception ex)
{
_logger.Error($"解除登录锁定事件处理失败: {ex.Message}", ex);
}
}
public void OnSetUserStatus((SysUser User, StatusEnum NewStatus) payload)
{
_logger.Information($"[本地] 设置状态: {payload.User?.Account} → {payload.NewStatus}");
}
public void OnResetPwd(SysUser payload)
{
throw new NotImplementedException();
}
public void OnChangePwd(SysUser payload)
{
_logger.Information($"[本地] 修改密码: {payload?.Account}");
}
public void OnLoginUser(SysUser payload)
{
try
{
_logger.Information($"登录成功");
}
catch (Exception ex)
{
_logger.Error($"登录处理失败: {ex.Message}", ex);
}
}
public void OnResetPwd(SysUser payload)
{
_logger.Information($"[本地] 重置密码: {payload?.Account}");
}
public void OnLoginOut(SysUser payload)
public void OnUpdateUserRole((SysUser User, List<long> RoleIds) payload)
{
_logger.Information($"[本地] 更新角色: {payload.User?.Account}");
}
public void OnUnlockUserLogin(SysUser payload)
{
_logger.Information($"[本地] 解除锁定: {payload?.Account}");
}
public void OnLoginUser(SysUser payload)
{
_logger.Information($"[本地] 登录成功: {payload?.Account ?? "<null>"}");
}
public void OnLoginOut(SysUser payload)
{
// 勿抛异常Prism 事件总线上若此处抛错,可能影响同事件其它订阅者
_logger.Information($"[本地] 用户登出: {payload?.Account ?? "<null>"}");
}
public void Dispose()
{
foreach (var token in _subscriptions)
{
// 勿抛异常Prism 事件总线上若此处抛错,可能影响同事件其它订阅者(如主窗口释放与 WS 停止)
_logger.Information($"用户登出事件: {payload?.Account ?? "<null>"}");
}
public void Dispose()
{
// 显式取消所有订阅
foreach (var token in _subscriptions)
{
token.Dispose();
}
token.Dispose();
}
}
}

View File

@@ -10,6 +10,7 @@ using YY.Admin.Core.Const;
using YY.Admin.Core.EventBus;
using YY.Admin.Core.Session;
using YY.Admin.Services.Service.Auth;
using YY.Admin.Services.Service.Config;
using YY.Admin.Views;
namespace YY.Admin.ViewModels
@@ -87,15 +88,58 @@ namespace YY.Admin.ViewModels
}
#region
/// <summary>
/// 从系统配置应用登录状态检查间隔(分钟)
/// </summary>
private static void ApplyTokenCheckIntervalFromConfig()
{
var minutes = 1;
try
{
var cfg = Prism.Ioc.ContainerLocator.Current.Resolve<ISysConfigService>();
var v = cfg.GetConfigValue<int>(ConfigConst.SysTokenCheckIntervalMinutes).GetAwaiter().GetResult();
if (v >= 1 && v <= 120)
minutes = v;
}
catch
{
// 使用默认 1 分钟
}
if (_tokenCheckTimer != null)
_tokenCheckTimer.Interval = TimeSpan.FromMinutes(minutes);
}
/// <summary>
/// 是否开启登录永不过期
/// </summary>
private static bool IsTokenNeverExpireEnabled()
{
try
{
var cfg = Prism.Ioc.ContainerLocator.Current.Resolve<ISysConfigService>();
return cfg.GetConfigValue<bool>(ConfigConst.SysTokenNeverExpire).GetAwaiter().GetResult();
}
catch
{
return false;
}
}
/// <summary>
/// 登录设置保存后刷新检查间隔(已启动定时器时立即生效)
/// </summary>
public static void RefreshTokenCheckIntervalFromConfig()
{
ApplyTokenCheckIntervalFromConfig();
}
// 启动定时器的方法
public static void StartTokenCheckTimer()
{
if (_tokenCheckTimer == null)
{
_tokenCheckTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMinutes(1)
};
_tokenCheckTimer = new DispatcherTimer();
_tokenCheckTimer.Tick += CheckTokenExpiration;
// 捕获全局用户输入事件
@@ -107,6 +151,8 @@ namespace YY.Admin.ViewModels
new KeyEventHandler(OnUserActivity));
}
ApplyTokenCheckIntervalFromConfig();
if (!_tokenCheckTimer.IsEnabled)
{
_tokenCheckTimer.Start();
@@ -124,6 +170,8 @@ namespace YY.Admin.ViewModels
private static void OnUserActivity(object sender, EventArgs e)
{
if (IsTokenNeverExpireEnabled())
return;
var authService = ContainerLocator.Current.Resolve<ISysAuthService>();
authService.RefreshToken(UserContext?.Token?.AccessToken);
}
@@ -146,6 +194,9 @@ namespace YY.Admin.ViewModels
return;
}
if (IsTokenNeverExpireEnabled())
return;
var authService = ContainerLocator.Current.Resolve<ISysAuthService>();
if (!authService.ValidateToken(UserContext.Token.AccessToken))
{

View File

@@ -4,6 +4,7 @@ using System.Windows.Threading;
using YY.Admin.Core;
using YY.Admin.Core.Util;
using YY.Admin.Event;
using Prism.Events;
using YY.Admin.Module;
using YY.Admin.Services;
using YY.Admin.Services.Service.Menu;
@@ -64,7 +65,40 @@ namespace YY.Admin.ViewModels.Control
["/system/tenant"] = "TenantManagementView",
["/system/tenant/index"] = "TenantManagementView",
["/platform/tenant"] = "TenantManagementView",
["sysTenant"] = "TenantManagementView"
["sysTenant"] = "TenantManagementView",
// 已实现页面:菜单管理
["MenuManagementView"] = "MenuManagementView",
["/platform/menu"] = "MenuManagementView",
["/system/menu/index"] = "MenuManagementView",
["sysMenu"] = "MenuManagementView",
// 已实现页面:登录设置
["LoginSettingsView"] = "LoginSettingsView",
["/system/loginSettings"] = "LoginSettingsView",
["/system/login-setting"] = "LoginSettingsView",
["/system/login-settings"] = "LoginSettingsView",
["loginSettings"] = "LoginSettingsView",
["登录设置"] = "LoginSettingsView",
["登陆设置"] = "LoginSettingsView",
// 已实现页面:车辆管理
["VehicleListView"] = "VehicleListView",
["/xslmes/mesXslVehicle"] = "VehicleListView",
["/xslmes/vehicle"] = "VehicleListView",
["mesXslVehicle"] = "VehicleListView",
// 已实现页面:客户管理
["CustomerListView"] = "CustomerListView",
["/xslmes/mesXslCustomer"] = "CustomerListView",
["/xslmes/customer"] = "CustomerListView",
["mesXslCustomer"] = "CustomerListView",
// 已实现页面:供应商管理
["SupplierListView"] = "SupplierListView",
["/xslmes/mesXslSupplier"] = "SupplierListView",
["/xslmes/supplier"] = "SupplierListView",
["mesXslSupplier"] = "SupplierListView"
};
private MenuItem? _selectedMenuItem;
@@ -83,6 +117,7 @@ namespace YY.Admin.ViewModels.Control
private SubscriptionToken? tabSelectedToken;
private SubscriptionToken? tabClosedToken;
private SubscriptionToken? _menuStructureToken;
public MenuTreeViewModel(
ISysMenuService sysMenuService,
@@ -99,10 +134,30 @@ namespace YY.Admin.ViewModels.Control
// 订阅事件
tabSelectedToken = _eventAggregator.GetEvent<TabSelectedEvent>().Subscribe(OnTabSelected);
tabClosedToken = _eventAggregator.GetEvent<TabClosedEvent>().Subscribe(OnTabClosed);
_menuStructureToken = _eventAggregator.GetEvent<MenuStructureChangedEvent>()
.Subscribe(async _ => await ReloadMenusAsync(), ThreadOption.UIThread);
}
/// <summary>
/// 菜单数据变更后刷新左侧树(不重复执行默认页签导航)
/// </summary>
private async Task ReloadMenusAsync()
{
try
{
var menuTree = await _sysMenuService.GetLoginMenuTree();
MenuItems.Clear();
ConvertMenuTreeToViewModel(menuTree);
}
catch (Exception ex)
{
_logger.Error($"菜单重新加载失败: {ex.Message}", ex);
}
}
public void OpenOrActivateTab(MenuItem menuItem)
{
_logger.Debug($"菜单点击触发: Name={menuItem?.Name}, ViewName={menuItem?.ViewName}, ChildrenCount={menuItem?.Children?.Count ?? 0}");
// 发布事件
_eventAggregator.GetEvent<TabSourceSelectedEvent>().Publish(menuItem);
}
@@ -169,6 +224,7 @@ namespace YY.Admin.ViewModels.Control
/// </summary>
private void ConvertMenuTreeToViewModel(List<MenuOutput> menuTree)
{
MenuItems.Clear();
// 过滤并排序菜单项:只包含目录和菜单类型,排除按钮类型,并按排序号排序
var rootMenus = menuTree
.Where(m => m.Type == MenuTypeEnum.Dir || m.Type == MenuTypeEnum.Menu)
@@ -244,10 +300,14 @@ namespace YY.Admin.ViewModels.Control
continue;
if (RouteToViewMap.TryGetValue(candidate.Trim(), out var viewName))
{
_logger.Debug($"菜单路由命中: Title={menu.Title}, Candidate={candidate}, View={viewName}");
return viewName;
}
}
// 保留原始Path若未注册将统一展示NotFoundView
_logger.Warning($"菜单路由未命中映射: Title={menu.Title}, Path={menu.Path}, Component={menu.Component}, Name={menu.Name}");
return menu.Path;
}
@@ -336,6 +396,12 @@ namespace YY.Admin.ViewModels.Control
.Unsubscribe(tabClosedToken);
tabClosedToken = null;
}
if (_menuStructureToken != null)
{
_eventAggregator.GetEvent<MenuStructureChangedEvent>().Unsubscribe(_menuStructureToken);
_menuStructureToken = null;
}
}
/// <summary>

View File

@@ -0,0 +1,138 @@
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using System.Collections.ObjectModel;
using YY.Admin.Core;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Services;
using YY.Admin.Services.Service;
namespace YY.Admin.ViewModels.Customer;
public class CustomerEditDialogViewModel : BaseViewModel, IDialogResultable<bool>
{
private readonly ICustomerService _customerService;
private readonly IJeecgDictSyncService _dictSyncService;
private MesXslCustomer? _customer;
public MesXslCustomer? Customer
{
get => _customer;
set => SetProperty(ref _customer, value);
}
public bool IsAddMode => string.IsNullOrWhiteSpace(Customer?.Id) || (Customer?.Id?.StartsWith("local-") ?? false);
public string DialogTitle => IsAddMode ? "新增客户" : "编辑客户";
public ObservableCollection<KeyValuePair<string, string>> StatusOptions { get; } = new();
public ObservableCollection<KeyValuePair<string, string>> CustomerRegionOptions { get; } = new();
private bool _result;
public bool Result { get => _result; set => SetProperty(ref _result, value); }
public Action? CloseAction { get; set; }
public DelegateCommand SaveCommand { get; }
public DelegateCommand CancelCommand { get; }
public CustomerEditDialogViewModel(
ICustomerService customerService,
IJeecgDictSyncService dictSyncService,
IContainerExtension container,
IRegionManager regionManager) : base(container, regionManager)
{
_customerService = customerService;
_dictSyncService = dictSyncService;
SaveCommand = new DelegateCommand(async () => await SaveAsync());
CancelCommand = new DelegateCommand(() => CloseAction?.Invoke());
_ = LoadDictOptionsAsync();
}
private async Task LoadDictOptionsAsync()
{
try
{
var statusOpts = await _dictSyncService.GetDictOptionsAsync("xslmes_customer_status");
var regionOpts = await _dictSyncService.GetDictOptionsAsync("xslmes_customer_region");
StatusOptions.Clear();
foreach (var item in statusOpts) StatusOptions.Add(item);
CustomerRegionOptions.Clear();
foreach (var item in regionOpts) CustomerRegionOptions.Add(item);
if (StatusOptions.Count == 0)
{
StatusOptions.Add(new KeyValuePair<string, string>("启用", "0"));
StatusOptions.Add(new KeyValuePair<string, string>("停用", "1"));
}
}
catch
{
StatusOptions.Clear();
StatusOptions.Add(new KeyValuePair<string, string>("启用", "0"));
StatusOptions.Add(new KeyValuePair<string, string>("停用", "1"));
CustomerRegionOptions.Clear();
}
}
public void InitializeForAdd()
{
Customer = new MesXslCustomer { Status = "0" };
RaisePropertyChanged(nameof(IsAddMode));
RaisePropertyChanged(nameof(DialogTitle));
}
public void InitializeForEdit(MesXslCustomer customer)
{
Customer = new MesXslCustomer
{
Id = customer.Id,
CustomerCode = customer.CustomerCode,
CustomerName = customer.CustomerName,
CustomerShortName = customer.CustomerShortName,
CustomerRegion = customer.CustomerRegion,
ErpCode = customer.ErpCode,
Status = customer.Status,
IzEnable = customer.IzEnable,
CustomerDesc = customer.CustomerDesc,
TenantId = customer.TenantId,
};
RaisePropertyChanged(nameof(IsAddMode));
RaisePropertyChanged(nameof(DialogTitle));
}
private async Task SaveAsync()
{
if (Customer == null) return;
if (string.IsNullOrWhiteSpace(Customer.CustomerCode))
{
HandyControl.Controls.MessageBox.Warning("客户编码不能为空!");
return;
}
if (string.IsNullOrWhiteSpace(Customer.CustomerName))
{
HandyControl.Controls.MessageBox.Warning("客户名称不能为空!");
return;
}
try
{
bool ok;
if (IsAddMode)
{
ok = await _customerService.AddAsync(Customer);
if (ok) HandyControl.Controls.MessageBox.Success("新增客户成功!");
else { HandyControl.Controls.MessageBox.Error("新增客户失败!"); return; }
}
else
{
ok = await _customerService.EditAsync(Customer);
if (!ok) { HandyControl.Controls.MessageBox.Error("编辑客户失败!"); return; }
}
Result = ok;
CloseAction?.Invoke();
}
catch (Exception ex)
{
HandyControl.Controls.MessageBox.Error($"操作失败:{ex.Message}");
}
}
}

View File

@@ -0,0 +1,288 @@
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using Prism.Events;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using YY.Admin.Core;
using YY.Admin.Core.Events;
using YY.Admin.Core.Helper;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Services;
using YY.Admin.Services.Service;
using YY.Admin.Services.Service.Customer;
using YY.Admin.Views.Customer;
namespace YY.Admin.ViewModels.Customer;
public class CustomerListViewModel : BaseViewModel
{
private readonly ICustomerService _customerService;
private readonly IJeecgDictSyncService _dictSyncService;
private readonly IDialogService _dialogService;
private SubscriptionToken? _customerChangedToken;
private SubscriptionToken? _syncConflictToken;
private ObservableCollection<MesXslCustomer> _customers = new();
public ObservableCollection<MesXslCustomer> Customers
{
get => _customers;
set => SetProperty(ref _customers, value);
}
private long _total;
public long Total { get => _total; set => SetProperty(ref _total, value); }
private int _pageNo = 1;
public int PageNo { get => _pageNo; set => SetProperty(ref _pageNo, value); }
private int _pageSize = 20;
public int PageSize { get => _pageSize; set => SetProperty(ref _pageSize, value); }
private string? _filterCustomerCode;
public string? FilterCustomerCode { get => _filterCustomerCode; set => SetProperty(ref _filterCustomerCode, value); }
private string? _filterCustomerName;
public string? FilterCustomerName { get => _filterCustomerName; set => SetProperty(ref _filterCustomerName, value); }
private string? _filterStatus;
public string? FilterStatus { get => _filterStatus; set => SetProperty(ref _filterStatus, value); }
private string? _filterCustomerRegion;
public string? FilterCustomerRegion { get => _filterCustomerRegion; set => SetProperty(ref _filterCustomerRegion, value); }
public ObservableCollection<KeyValuePair<string, string>> StatusOptions { get; } = new();
public ObservableCollection<KeyValuePair<string, string>> CustomerRegionOptions { get; } = new();
public DelegateCommand SearchCommand { get; }
public DelegateCommand ResetCommand { get; }
public DelegateCommand AddCommand { get; }
public DelegateCommand<MesXslCustomer> EditCommand { get; }
public DelegateCommand<MesXslCustomer> DeleteCommand { get; }
public DelegateCommand<MesXslCustomer> ToggleStatusCommand { get; }
public DelegateCommand PrevPageCommand { get; }
public DelegateCommand NextPageCommand { get; }
public CustomerListViewModel(
ICustomerService customerService,
IJeecgDictSyncService dictSyncService,
IContainerExtension container,
IDialogService dialogService,
IRegionManager regionManager) : base(container, regionManager)
{
_customerService = customerService;
_dictSyncService = dictSyncService;
_dialogService = dialogService;
SearchCommand = new DelegateCommand(async () => { PageNo = 1; await LoadAsync(); });
ResetCommand = new DelegateCommand(async () =>
{
FilterCustomerCode = null; FilterCustomerName = null;
FilterStatus = null; FilterCustomerRegion = null;
PageNo = 1; await LoadAsync();
});
AddCommand = new DelegateCommand(async () => await ShowAddDialogAsync());
EditCommand = new DelegateCommand<MesXslCustomer>(async c => await ShowEditDialogAsync(c));
DeleteCommand = new DelegateCommand<MesXslCustomer>(async c => await DeleteAsync(c));
ToggleStatusCommand = new DelegateCommand<MesXslCustomer>(async c => await ToggleStatusAsync(c));
PrevPageCommand = new DelegateCommand(async () => { if (PageNo > 1) { PageNo--; await LoadAsync(); } });
NextPageCommand = new DelegateCommand(async () => { if ((long)PageNo * PageSize < Total) { PageNo++; await LoadAsync(); } });
_customerChangedToken = _eventAggregator.GetEvent<CustomerChangedEvent>()
.Subscribe(async p => await OnCustomerChangedAsync(p), ThreadOption.UIThread);
_syncConflictToken = _eventAggregator.GetEvent<SyncConflictEvent>()
.Subscribe(OnSyncConflict, ThreadOption.UIThread);
_ = InitializeAsync();
}
private async Task OnCustomerChangedAsync(CustomerChangedPayload payload)
{
if (payload.Action == "edit" && !string.IsNullOrWhiteSpace(payload.CustomerId))
{
await RefreshSingleAsync(payload.CustomerId!);
}
else
{
await LoadAsync();
}
}
private async Task RefreshSingleAsync(string customerId)
{
try
{
var updated = await _customerService.GetByIdAsync(customerId);
if (updated == null) return;
var idx = Customers.ToList().FindIndex(c => string.Equals(c.Id, customerId, StringComparison.OrdinalIgnoreCase));
if (idx >= 0)
Customers[idx] = updated;
}
catch (Exception ex)
{
Debug.WriteLine($"[客户] 单条刷新失败: {ex.Message}");
}
}
private void OnSyncConflict(SyncConflictPayload payload)
{
if (!string.Equals(payload.EntityName, "客户", StringComparison.OrdinalIgnoreCase)) return;
var parts = new List<string>();
if (payload.PushedCount > 0)
parts.Add($"已同步 {payload.PushedCount} 条本地改动到服务器");
if (payload.NewRecordsPushed > 0)
parts.Add($"已上传 {payload.NewRecordsPushed} 条本地新增记录");
if (payload.ConflictCount > 0)
parts.Add($"{payload.ConflictCount} 条记录与服务器版本冲突,已保留服务器版本");
if (parts.Count == 0) return;
var message = string.Join("\n", parts);
if (payload.ConflictCount > 0)
Growl.Warning(message);
else
Growl.Success(message);
}
private async Task InitializeAsync()
{
try
{
await LoadDictOptionsAsync();
await UIHelper.WaitForRenderAsync();
await LoadAsync();
}
catch (Exception ex)
{
Debug.WriteLine($"客户列表初始化失败: {ex.Message}");
}
}
private async Task LoadDictOptionsAsync()
{
try
{
var statusOpts = await _dictSyncService.GetDictOptionsAsync("xslmes_customer_status", includeAll: true);
var regionOpts = await _dictSyncService.GetDictOptionsAsync("xslmes_customer_region", includeAll: true);
StatusOptions.Clear();
foreach (var item in statusOpts) StatusOptions.Add(item);
CustomerRegionOptions.Clear();
foreach (var item in regionOpts) CustomerRegionOptions.Add(item);
if (StatusOptions.Count == 0)
{
StatusOptions.Add(new KeyValuePair<string, string>("全部", ""));
StatusOptions.Add(new KeyValuePair<string, string>("启用", "0"));
StatusOptions.Add(new KeyValuePair<string, string>("停用", "1"));
}
if (CustomerRegionOptions.Count == 0)
CustomerRegionOptions.Add(new KeyValuePair<string, string>("全部", ""));
}
catch
{
StatusOptions.Clear();
StatusOptions.Add(new KeyValuePair<string, string>("全部", ""));
StatusOptions.Add(new KeyValuePair<string, string>("启用", "0"));
StatusOptions.Add(new KeyValuePair<string, string>("停用", "1"));
CustomerRegionOptions.Clear();
CustomerRegionOptions.Add(new KeyValuePair<string, string>("全部", ""));
}
}
public async Task LoadAsync()
{
try
{
IsLoading = true;
var result = await _customerService.PageAsync(PageNo, PageSize,
FilterCustomerCode, FilterCustomerName, FilterStatus, FilterCustomerRegion);
Customers = new ObservableCollection<MesXslCustomer>(result.Records);
Total = result.Total;
}
catch (Exception ex)
{
Growl.Error($"加载客户列表失败:{ex.Message}");
}
finally
{
IsLoading = false;
}
}
private async Task ShowAddDialogAsync()
{
try
{
var result = await HandyControl.Controls.Dialog.Show<CustomerEditDialogView>()
.Initialize<CustomerEditDialogViewModel>(vm => vm.InitializeForAdd())
.GetResultAsync<bool>();
if (result) await LoadAsync();
}
catch (Exception ex)
{
Growl.Error($"打开新增对话框失败:{ex.Message}");
}
}
private async Task ShowEditDialogAsync(MesXslCustomer customer)
{
if (customer == null) return;
try
{
var result = await HandyControl.Controls.Dialog.Show<CustomerEditDialogView>()
.Initialize<CustomerEditDialogViewModel>(vm => vm.InitializeForEdit(customer))
.GetResultAsync<bool>();
if (result) await LoadAsync();
}
catch (Exception ex)
{
Growl.Error($"打开编辑对话框失败:{ex.Message}");
}
}
private async Task DeleteAsync(MesXslCustomer customer)
{
if (customer?.Id == null) return;
var confirm = System.Windows.MessageBox.Show(
$"确定删除客户【{customer.CustomerName}】?此操作不可恢复!",
"确认删除", MessageBoxButton.OKCancel, MessageBoxImage.Question);
if (confirm != System.Windows.MessageBoxResult.OK) return;
var ok = await _customerService.DeleteAsync(customer.Id);
if (ok) { Growl.Success("删除成功!"); await LoadAsync(); }
else Growl.Error("删除失败!");
}
private async Task ToggleStatusAsync(MesXslCustomer customer)
{
if (customer?.Id == null) return;
var newStatus = customer.Status == "1" ? "0" : "1";
var ok = await _customerService.UpdateStatusAsync(customer.Id, newStatus);
if (ok)
{
// 客户列表离线场景下只改行对象字段DataGrid 对计算列(StatusText)可能不会立即重绘。
// 这里统一重载一次列表,确保状态、筛选结果和分页统计立即一致。
await LoadAsync();
}
else Growl.Error("状态切换失败!");
}
protected override void CleanUp()
{
base.CleanUp();
if (_customerChangedToken != null)
{
_eventAggregator.GetEvent<CustomerChangedEvent>().Unsubscribe(_customerChangedToken);
_customerChangedToken = null;
}
if (_syncConflictToken != null)
{
_eventAggregator.GetEvent<SyncConflictEvent>().Unsubscribe(_syncConflictToken);
_syncConflictToken = null;
}
}
}

View File

@@ -44,6 +44,27 @@ namespace YY.Admin.ViewModels.Dialogs
set => SetProperty(ref _errorMessage, value);
}
private bool _disconnectConnection;
/// <summary>
/// 是否断开连接true=断开false=连接)
/// </summary>
public bool DisconnectConnection
{
get => _disconnectConnection;
set
{
if (SetProperty(ref _disconnectConnection, value))
{
RaisePropertyChanged(nameof(IsConnectionFieldsEnabled));
}
}
}
/// <summary>
/// 连接参数是否可编辑(勾选断开连接后禁用)。
/// </summary>
public bool IsConnectionFieldsEnabled => !DisconnectConnection;
public DelegateCommand SaveCommand { get; }
public DelegateCommand CancelCommand { get; }
public DialogCloseListener RequestClose { get; private set; }
@@ -68,6 +89,7 @@ namespace YY.Admin.ViewModels.Dialogs
: settings.WebSocketUrl;
_loadedWebSocketUrl = WebSocketUrl;
BasePath = string.IsNullOrWhiteSpace(settings.BasePath) ? "/jeecg-boot" : settings.BasePath;
DisconnectConnection = settings.DisconnectConnection;
ErrorMessage = string.Empty;
}
@@ -102,7 +124,8 @@ namespace YY.Admin.ViewModels.Dialogs
BaseScheme = "http",
BasePath = basePath,
WebSocketUrl = finalWsUrl,
WebSocketPath = DefaultWebSocketPath
WebSocketPath = DefaultWebSocketPath,
DisconnectConnection = DisconnectConnection
});
RequestClose.Invoke(new DialogResult(ButtonResult.OK));
}

View File

@@ -12,6 +12,7 @@ using System.Windows.Threading;
using YY.Admin.Core;
using YY.Admin.Core.Const;
using YY.Admin.Core.Model;
using YY.Admin.Core.Services;
using YY.Admin.Core.Session;
using YY.Admin.Core.Util;
using YY.Admin.Event;
@@ -20,6 +21,7 @@ using YY.Admin.Services.Service.Auth;
using YY.Admin.Services.Service.Jeecg;
using YY.Admin.Services.Service.Menu;
using YY.Admin.ViewModels.Control;
using YY.Admin.Helper;
namespace YY.Admin.ViewModels
{
@@ -220,8 +222,9 @@ namespace YY.Admin.ViewModels
_refreshTabToken = _eventAggregator.GetEvent<TabRefreshEvent>().Subscribe(OnRefreshTab);
_loginOutToken = _eventAggregator.GetEvent<SysUserEvents.LoginOutEvent>().Subscribe(Destroy);
// Jeecg 用户增量同步:定时 + 可选 WebSocket工控机断网续传
_jeecgUserSyncCoordinator.Start();
// 首次按默认连接;后续按本地保存状态恢复
var settings = ServerSettingsStore.Load();
IsServerConnectionEnabled = !settings.DisconnectConnection;
// 主窗口底部连接状态圆点
_ = StartBackendConnectivityLoopAsync(_backendConnectivityCts.Token);
@@ -251,6 +254,30 @@ namespace YY.Admin.ViewModels
public Brush BackendConnectionStatusBrush => IsBackendConnected ? Brushes.LimeGreen : Brushes.Red;
private bool _isServerConnectionEnabled = true;
/// <summary>
/// 是否启用服务器连接(默认启用)
/// </summary>
public bool IsServerConnectionEnabled
{
get => _isServerConnectionEnabled;
set
{
if (SetProperty(ref _isServerConnectionEnabled, value))
{
if (!value)
{
IsBackendConnected = false;
_jeecgUserSyncCoordinator.Stop();
}
else
{
_jeecgUserSyncCoordinator.Start();
}
}
}
}
public DelegateCommand LogoutCommand { get; }
private void InitNavItems()
@@ -355,7 +382,8 @@ namespace YY.Admin.ViewModels
}
else
{
_logger.Error($"导航失败: {viewName}");
var exMsg = result.Exception?.Message;
_logger.Error($"导航失败: {viewName}, Region={regionName}, Exception={exMsg}");
tcs.SetResult(false);
}
}, parameters);
@@ -586,6 +614,26 @@ namespace YY.Admin.ViewModels
while (!cancellationToken.IsCancellationRequested)
{
bool connected = false;
if (!IsServerConnectionEnabled)
{
try
{
await Application.Current.Dispatcher.InvokeAsync(() => { IsBackendConnected = false; });
}
catch
{
}
try
{
await Task.Delay(TimeSpan.FromSeconds(ConnectivityCheckIntervalSeconds), cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
continue;
}
try
{
// 每轮都重新读取配置,保存服务器设置后可即时生效
@@ -631,7 +679,24 @@ namespace YY.Admin.ViewModels
private void OpenServerSettings()
{
_dialogService.ShowDialog("ServerSettingsDialog", r => { });
_dialogService.ShowDialog("ServerSettingsDialog", r =>
{
if (r.Result == ButtonResult.OK)
{
var settings = ServerSettingsStore.Load();
IsServerConnectionEnabled = !settings.DisconnectConnection;
if (settings.DisconnectConnection)
{
var signalService = _container.Resolve<ISignalRService>();
_ = signalService.DisconnectAsync();
}
else
{
var signalService = _container.Resolve<ISignalRService>();
_ = signalService.ConnectUnifiedDeviceChannelAsync(CancellationToken.None);
}
}
});
}
/// <summary>

View File

@@ -0,0 +1,111 @@
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using System.Collections.ObjectModel;
using YY.Admin.Core;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Services;
using YY.Admin.Services.Service;
namespace YY.Admin.ViewModels.Supplier;
public class SupplierEditDialogViewModel : BaseViewModel, HandyControl.Tools.Extension.IDialogResultable<bool>
{
private readonly ISupplierService _supplierService;
private readonly IJeecgDictSyncService _dictSyncService;
private bool _result;
public bool Result { get => _result; set => SetProperty(ref _result, value); }
public Action? CloseAction { get; set; }
private MesXslSupplier? _supplier;
public MesXslSupplier? Supplier
{
get => _supplier;
set => SetProperty(ref _supplier, value);
}
public bool IsAddMode => string.IsNullOrWhiteSpace(Supplier?.Id) || (Supplier?.Id?.StartsWith("local-") ?? false);
public string DialogTitle => IsAddMode ? "新增供应商" : "编辑供应商";
public ObservableCollection<KeyValuePair<string, string>> StatusOptions { get; } = new();
public DelegateCommand SaveCommand { get; }
public DelegateCommand CancelCommand { get; }
public SupplierEditDialogViewModel(ISupplierService supplierService, IJeecgDictSyncService dictSyncService, IContainerExtension container, IRegionManager regionManager) : base(container, regionManager)
{
_supplierService = supplierService;
_dictSyncService = dictSyncService;
SaveCommand = new DelegateCommand(async () => await SaveAsync());
CancelCommand = new DelegateCommand(() => CloseAction?.Invoke());
_ = LoadDictOptionsAsync();
}
private async Task LoadDictOptionsAsync()
{
try
{
var statusOpts = await _dictSyncService.GetDictOptionsAsync("xslmes_supplier_status");
StatusOptions.Clear();
foreach (var item in statusOpts) StatusOptions.Add(item);
if (StatusOptions.Count == 0)
{
StatusOptions.Add(new KeyValuePair<string, string>("启用", "0"));
StatusOptions.Add(new KeyValuePair<string, string>("停用", "1"));
}
}
catch { }
}
public void InitializeForAdd()
{
Supplier = new MesXslSupplier { Status = "0" };
RaisePropertyChanged(nameof(IsAddMode));
RaisePropertyChanged(nameof(DialogTitle));
}
public void InitializeForEdit(MesXslSupplier supplier)
{
Supplier = new MesXslSupplier
{
Id = supplier.Id,
SupplierCode = supplier.SupplierCode,
SupplierName = supplier.SupplierName,
SupplierShortName = supplier.SupplierShortName,
ErpCode = supplier.ErpCode,
Status = supplier.Status,
Remark = supplier.Remark,
TenantId = supplier.TenantId,
};
RaisePropertyChanged(nameof(IsAddMode));
RaisePropertyChanged(nameof(DialogTitle));
}
private async Task SaveAsync()
{
if (Supplier == null) return;
if (string.IsNullOrWhiteSpace(Supplier.SupplierCode))
{
HandyControl.Controls.MessageBox.Warning("供应商编码不能为空!");
return;
}
if (string.IsNullOrWhiteSpace(Supplier.SupplierName))
{
HandyControl.Controls.MessageBox.Warning("供应商名称不能为空!");
return;
}
bool ok = IsAddMode ? await _supplierService.AddAsync(Supplier) : await _supplierService.EditAsync(Supplier);
if (ok)
{
if (IsAddMode)
{
HandyControl.Controls.MessageBox.Success("新增供应商成功!");
}
Result = true;
CloseAction?.Invoke();
return;
}
else
{
HandyControl.Controls.MessageBox.Error("保存供应商失败!");
}
}
}

View File

@@ -0,0 +1,189 @@
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using Prism.Events;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using YY.Admin.Core;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Events;
using YY.Admin.Core.Services;
using YY.Admin.Services.Service;
using YY.Admin.Views.Supplier;
namespace YY.Admin.ViewModels.Supplier;
public class SupplierListViewModel : BaseViewModel
{
private readonly ISupplierService _supplierService;
private readonly IJeecgDictSyncService _dictSyncService;
private SubscriptionToken? _supplierChangedToken;
private SubscriptionToken? _syncConflictToken;
public ObservableCollection<MesXslSupplier> Suppliers { get; set; } = [];
public ObservableCollection<KeyValuePair<string, string>> StatusOptions { get; } = [];
public long Total { get; set; }
public int PageNo { get; set; } = 1;
public int PageSize { get; set; } = 20;
public string? FilterSupplierCode { get; set; }
public string? FilterSupplierName { get; set; }
public string? FilterSupplierShortName { get; set; }
public string? FilterErpCode { get; set; }
public string? FilterStatus { get; set; }
public DelegateCommand SearchCommand { get; }
public DelegateCommand ResetCommand { get; }
public DelegateCommand AddCommand { get; }
public DelegateCommand<MesXslSupplier> EditCommand { get; }
public DelegateCommand<MesXslSupplier> DeleteCommand { get; }
public DelegateCommand<MesXslSupplier> ToggleStatusCommand { get; }
public SupplierListViewModel(
ISupplierService supplierService,
IJeecgDictSyncService dictSyncService,
IContainerExtension container,
IRegionManager regionManager)
: base(container, regionManager)
{
_supplierService = supplierService;
_dictSyncService = dictSyncService;
SearchCommand = new DelegateCommand(async () => { PageNo = 1; await LoadAsync(); });
ResetCommand = new DelegateCommand(async () =>
{
FilterSupplierCode = FilterSupplierName = FilterSupplierShortName = FilterErpCode = FilterStatus = null;
PageNo = 1;
await LoadAsync();
});
AddCommand = new DelegateCommand(async () => await ShowAddDialogAsync());
EditCommand = new DelegateCommand<MesXslSupplier>(async s => await ShowEditDialogAsync(s));
DeleteCommand = new DelegateCommand<MesXslSupplier>(async s => await DeleteAsync(s));
ToggleStatusCommand = new DelegateCommand<MesXslSupplier>(async s => await ToggleStatusAsync(s));
_supplierChangedToken = _eventAggregator.GetEvent<SupplierChangedEvent>()
.Subscribe(async p => await OnSupplierChangedAsync(p), ThreadOption.UIThread);
_syncConflictToken = _eventAggregator.GetEvent<SyncConflictEvent>()
.Subscribe(OnSyncConflict, ThreadOption.UIThread);
_ = InitializeAsync();
}
private async Task InitializeAsync()
{
try
{
var statusOpts = await _dictSyncService.GetDictOptionsAsync("xslmes_supplier_status", includeAll: true);
StatusOptions.Clear();
foreach (var item in statusOpts) StatusOptions.Add(item);
if (StatusOptions.Count == 0)
{
StatusOptions.Add(new("全部", ""));
StatusOptions.Add(new("启用", "0"));
StatusOptions.Add(new("停用", "1"));
}
}
catch { }
await LoadAsync();
}
public async Task LoadAsync()
{
var result = await _supplierService.PageAsync(
PageNo, PageSize,
FilterSupplierCode, FilterSupplierName,
FilterSupplierShortName, FilterErpCode, FilterStatus);
Suppliers = new ObservableCollection<MesXslSupplier>(result.Records);
Total = result.Total;
RaisePropertyChanged(nameof(Suppliers));
RaisePropertyChanged(nameof(Total));
}
private async Task OnSupplierChangedAsync(SupplierChangedPayload payload)
{
if (payload.Action == "edit" && !string.IsNullOrWhiteSpace(payload.SupplierId))
{
await RefreshSingleAsync(payload.SupplierId!);
}
else
{
await LoadAsync();
}
}
private async Task RefreshSingleAsync(string supplierId)
{
try
{
var updated = await _supplierService.GetByIdAsync(supplierId);
if (updated == null) return;
var idx = Suppliers.ToList().FindIndex(s => string.Equals(s.Id, supplierId, StringComparison.OrdinalIgnoreCase));
if (idx >= 0)
{
Suppliers[idx] = updated;
RaisePropertyChanged(nameof(Suppliers));
}
}
catch (Exception ex)
{
Debug.WriteLine($"[供应商] 单条刷新失败: {ex.Message}");
}
}
private void OnSyncConflict(SyncConflictPayload payload)
{
if (!string.Equals(payload.EntityName, "供应商", StringComparison.Ordinal)) return;
var parts = new List<string>();
if (payload.PushedCount > 0)
parts.Add($"已同步 {payload.PushedCount} 条本地改动到服务器");
if (payload.NewRecordsPushed > 0)
parts.Add($"已上传 {payload.NewRecordsPushed} 条本地新增记录");
if (payload.ConflictCount > 0)
parts.Add($"{payload.ConflictCount} 条记录与服务器版本冲突,已保留服务器版本");
if (parts.Count == 0) return;
var message = string.Join("\n", parts);
if (payload.ConflictCount > 0)
Growl.Warning(message);
else
Growl.Success(message);
}
private async Task ShowAddDialogAsync()
{
var ok = await HandyControl.Controls.Dialog.Show<SupplierEditDialogView>()
.Initialize<SupplierEditDialogViewModel>(vm => vm.InitializeForAdd())
.GetResultAsync<bool>();
if (ok) await LoadAsync();
}
private async Task ShowEditDialogAsync(MesXslSupplier supplier)
{
if (supplier == null) return;
var ok = await HandyControl.Controls.Dialog.Show<SupplierEditDialogView>()
.Initialize<SupplierEditDialogViewModel>(vm => vm.InitializeForEdit(supplier))
.GetResultAsync<bool>();
if (ok) await LoadAsync();
}
private async Task DeleteAsync(MesXslSupplier supplier)
{
if (string.IsNullOrWhiteSpace(supplier?.Id)) return;
if (System.Windows.MessageBox.Show(
$"确定删除供应商【{supplier.SupplierName}】?",
"确认删除",
System.Windows.MessageBoxButton.OKCancel) != System.Windows.MessageBoxResult.OK) return;
if (await _supplierService.DeleteAsync(supplier.Id)) await LoadAsync();
}
private async Task ToggleStatusAsync(MesXslSupplier supplier)
{
if (string.IsNullOrWhiteSpace(supplier?.Id)) return;
var newStatus = supplier.Status == "1" ? "0" : "1";
if (await _supplierService.UpdateStatusAsync(supplier.Id, newStatus))
{
supplier.Status = newStatus;
RaisePropertyChanged(nameof(Suppliers));
}
}
}

View File

@@ -0,0 +1,166 @@
using HandyControl.Controls;
using Prism.Commands;
using Prism.Ioc;
using YY.Admin.Core.Const;
using YY.Admin.Services.Service.Config;
namespace YY.Admin.ViewModels.SysManage;
/// <summary>
/// 登录与会话相关系统配置
/// </summary>
public class LoginSettingsViewModel : BaseViewModel
{
private readonly ISysConfigService _configService;
private int _tokenExpireMinutes = 30;
public int TokenExpireMinutes
{
get => _tokenExpireMinutes;
set => SetProperty(ref _tokenExpireMinutes, value);
}
private int _refreshTokenExpireMinutes = 20160;
public int RefreshTokenExpireMinutes
{
get => _refreshTokenExpireMinutes;
set => SetProperty(ref _refreshTokenExpireMinutes, value);
}
private int _idleExtendMinutes = 20;
public int IdleExtendMinutes
{
get => _idleExtendMinutes;
set => SetProperty(ref _idleExtendMinutes, value);
}
private int _checkIntervalMinutes = 1;
public int CheckIntervalMinutes
{
get => _checkIntervalMinutes;
set => SetProperty(ref _checkIntervalMinutes, value);
}
private bool _neverExpire;
public bool NeverExpire
{
get => _neverExpire;
set
{
if (SetProperty(ref _neverExpire, value))
RaisePropertyChanged(nameof(IsConfigEditable));
}
}
public bool IsConfigEditable => !NeverExpire;
public DelegateCommand LoadCommand { get; }
public DelegateCommand SaveCommand { get; }
public LoginSettingsViewModel(
ISysConfigService configService,
IContainerExtension container,
IRegionManager regionManager) : base(container, regionManager)
{
_configService = configService;
LoadCommand = new DelegateCommand(async () => await LoadAsync());
SaveCommand = new DelegateCommand(async () => await SaveAsync());
_ = LoadAsync();
}
private async Task LoadAsync()
{
try
{
IsLoading = true;
var t = await _configService.GetConfigValue<int>(ConfigConst.SysTokenExpire);
TokenExpireMinutes = t > 0 ? t : 30;
var r = await _configService.GetConfigValue<int>(ConfigConst.SysRefreshTokenExpire);
RefreshTokenExpireMinutes = r > 0 ? r : 20160;
var i = await _configService.GetConfigValue<int>(ConfigConst.SysTokenIdleExtendMinutes);
IdleExtendMinutes = i > 0 ? i : 20;
var c = await _configService.GetConfigValue<int>(ConfigConst.SysTokenCheckIntervalMinutes);
CheckIntervalMinutes = c > 0 ? c : 1;
NeverExpire = await _configService.GetConfigValue<bool>(ConfigConst.SysTokenNeverExpire);
}
catch (Exception ex)
{
Growl.Error($"加载配置失败:{ex.Message}");
}
finally
{
IsLoading = false;
}
}
private async Task SaveAsync()
{
if (!NeverExpire && (TokenExpireMinutes < 5 || TokenExpireMinutes > 43200))
{
Growl.Warning("Token 过期时间建议在 543200 分钟之间");
return;
}
if (!NeverExpire && (IdleExtendMinutes < 1 || IdleExtendMinutes > 1440))
{
Growl.Warning("会话续期阈值建议在 11440 分钟之间");
return;
}
if (!NeverExpire && IdleExtendMinutes > TokenExpireMinutes)
{
Growl.Warning("续期阈值不应大于 Token 过期时间");
return;
}
if (!NeverExpire && (CheckIntervalMinutes < 1 || CheckIntervalMinutes > 120))
{
Growl.Warning("登录状态检查间隔建议在 1120 分钟之间");
return;
}
if (!NeverExpire && RefreshTokenExpireMinutes < TokenExpireMinutes * 2)
{
Growl.Warning("RefreshToken 过期时间建议不小于 Token 过期时间的 2 倍");
return;
}
try
{
IsLoading = true;
var pairs = new[]
{
(ConfigConst.SysTokenExpire, TokenExpireMinutes.ToString()),
(ConfigConst.SysRefreshTokenExpire, RefreshTokenExpireMinutes.ToString()),
(ConfigConst.SysTokenIdleExtendMinutes, IdleExtendMinutes.ToString()),
(ConfigConst.SysTokenCheckIntervalMinutes, CheckIntervalMinutes.ToString()),
(ConfigConst.SysTokenNeverExpire, NeverExpire.ToString()),
};
foreach (var (code, val) in pairs)
{
var (ok, msg) = await _configService.SetConfigValueAsync(code, val);
if (!ok)
{
Growl.Warning($"{code}{msg}");
return;
}
}
Growl.Success("登录相关配置已保存");
BaseViewModel.RefreshTokenCheckIntervalFromConfig();
}
catch (Exception ex)
{
Growl.Error($"保存失败:{ex.Message}");
}
finally
{
IsLoading = false;
}
}
}

View File

@@ -0,0 +1,390 @@
using System.Collections.ObjectModel;
using System.Linq;
using HandyControl.Controls;
using Prism.Commands;
using Prism.Mvvm;
using YY.Admin.Core;
using YY.Admin.Core.Extension;
using YY.Admin.Event;
using YY.Admin.Services.Service.Menu;
namespace YY.Admin.ViewModels.SysManage;
/// <summary>
/// 左侧列表一行(树形扁平展示)
/// </summary>
public sealed class MenuFlatRow
{
public SysMenu Menu { get; }
public int Depth { get; }
public string IndentTitle { get; }
public MenuFlatRow(SysMenu menu, int depth)
{
Menu = menu;
Depth = depth;
var pad = new string(' ', depth);
var tag = menu.Type == MenuTypeEnum.Dir ? "[目录] " : menu.Type == MenuTypeEnum.Btn ? "[按钮] " : "[菜单] ";
IndentTitle = pad + tag + menu.Title;
}
}
/// <summary>
/// 可编辑字段(与界面绑定)
/// </summary>
public class MenuEditorModel : BindableBase
{
private long _id;
private long _pid;
private MenuTypeEnum _type = MenuTypeEnum.Menu;
private string? _name;
private string? _path;
private string? _component;
private string? _redirect;
private string? _permission;
private string _title = string.Empty;
private string? _icon;
private bool _isIframe;
private string? _outLink;
private bool _isHide;
private bool _isKeepAlive = true;
private bool _isAffix;
private int _orderNo = 100;
private StatusEnum _status = StatusEnum.Enable;
private string? _remark;
public long Id { get => _id; set => SetProperty(ref _id, value); }
public long Pid { get => _pid; set => SetProperty(ref _pid, value); }
public MenuTypeEnum Type { get => _type; set => SetProperty(ref _type, value); }
public string? Name { get => _name; set => SetProperty(ref _name, value); }
public string? Path { get => _path; set => SetProperty(ref _path, value); }
public string? Component { get => _component; set => SetProperty(ref _component, value); }
public string? Redirect { get => _redirect; set => SetProperty(ref _redirect, value); }
public string? Permission { get => _permission; set => SetProperty(ref _permission, value); }
public string Title { get => _title; set => SetProperty(ref _title, value); }
public string? Icon { get => _icon; set => SetProperty(ref _icon, value); }
public bool IsIframe { get => _isIframe; set => SetProperty(ref _isIframe, value); }
public string? OutLink { get => _outLink; set => SetProperty(ref _outLink, value); }
public bool IsHide { get => _isHide; set => SetProperty(ref _isHide, value); }
public bool IsKeepAlive { get => _isKeepAlive; set => SetProperty(ref _isKeepAlive, value); }
public bool IsAffix { get => _isAffix; set => SetProperty(ref _isAffix, value); }
public int OrderNo { get => _orderNo; set => SetProperty(ref _orderNo, value); }
public StatusEnum Status { get => _status; set => SetProperty(ref _status, value); }
public string? Remark { get => _remark; set => SetProperty(ref _remark, value); }
public bool IsNew => Id == 0;
public void LoadFrom(SysMenu m)
{
Id = m.Id;
Pid = m.Pid;
Type = m.Type;
Name = m.Name;
Path = m.Path;
Component = m.Component;
Redirect = m.Redirect;
Permission = m.Permission;
Title = m.Title;
Icon = m.Icon;
IsIframe = m.IsIframe;
OutLink = m.OutLink;
IsHide = m.IsHide;
IsKeepAlive = m.IsKeepAlive;
IsAffix = m.IsAffix;
OrderNo = m.OrderNo;
Status = m.Status;
Remark = m.Remark;
}
public SysMenu ToSysMenu()
{
return new SysMenu
{
Id = Id,
Pid = Pid,
Type = Type,
Name = Name,
Path = Path,
Component = Component,
Redirect = Redirect,
Permission = Permission,
Title = Title.Trim(),
Icon = Icon,
IsIframe = IsIframe,
OutLink = OutLink,
IsHide = IsHide,
IsKeepAlive = IsKeepAlive,
IsAffix = IsAffix,
OrderNo = OrderNo,
Status = Status,
Remark = Remark
};
}
public void ResetForNew(long pid, MenuTypeEnum type)
{
Id = 0;
Pid = pid;
Type = type;
Name = null;
Path = null;
Component = null;
Redirect = null;
Permission = null;
Title = type == MenuTypeEnum.Dir ? "新目录" : type == MenuTypeEnum.Menu ? "新菜单" : "新按钮";
Icon = "&#xe8f1;";
IsIframe = false;
OutLink = null;
IsHide = false;
IsKeepAlive = true;
IsAffix = false;
OrderNo = 100;
Status = StatusEnum.Enable;
Remark = null;
}
}
public class MenuManagementViewModel : BaseViewModel
{
private readonly ISysMenuService _menuService;
public ObservableCollection<MenuFlatRow> FlatRows { get; } = new();
public ObservableCollection<KeyValuePair<long, string>> ParentOptions { get; } = new();
private MenuFlatRow? _selectedRow;
public MenuFlatRow? SelectedRow
{
get => _selectedRow;
set
{
if (SetProperty(ref _selectedRow, value))
{
if (value == null)
{
Editor = null;
RaisePropertyChanged(nameof(Editor));
RaisePropertyChanged(nameof(HasEditor));
}
else
{
Editor ??= new MenuEditorModel();
Editor.LoadFrom(value.Menu);
RaisePropertyChanged(nameof(Editor));
RaisePropertyChanged(nameof(HasEditor));
}
}
}
}
private MenuEditorModel? _editor;
public MenuEditorModel? Editor
{
get => _editor;
set
{
if (SetProperty(ref _editor, value))
{
RaisePropertyChanged(nameof(HasEditor));
}
}
}
public bool HasEditor => Editor != null;
public List<KeyValuePair<string, int>> StatusList =>
Enum.GetValues(typeof(StatusEnum))
.Cast<StatusEnum>()
.Select(e => new KeyValuePair<string, int>(e.GetDescription(), (int)e))
.ToList();
public List<KeyValuePair<string, int>> MenuTypeList =>
Enum.GetValues(typeof(MenuTypeEnum))
.Cast<MenuTypeEnum>()
.Select(e => new KeyValuePair<string, int>(e.GetDescription(), (int)e))
.ToList();
public DelegateCommand RefreshCommand { get; }
public DelegateCommand AddRootCommand { get; }
public DelegateCommand AddChildCommand { get; }
public DelegateCommand SaveCommand { get; }
public DelegateCommand DeleteCommand { get; }
public MenuManagementViewModel(
ISysMenuService menuService,
IContainerExtension container,
IRegionManager regionManager) : base(container, regionManager)
{
_menuService = menuService;
RefreshCommand = new DelegateCommand(async () => await RefreshAsync());
AddRootCommand = new DelegateCommand(() => BeginNew(0, MenuTypeEnum.Dir));
AddChildCommand = new DelegateCommand(BeginNewChild, () => SelectedRow != null)
.ObservesProperty(() => SelectedRow);
SaveCommand = new DelegateCommand(async () => await SaveAsync(), () => Editor != null)
.ObservesProperty(() => Editor);
DeleteCommand = new DelegateCommand(async () => await DeleteAsync(), () => SelectedRow != null && SelectedRow.Menu.Id != 0)
.ObservesProperty(() => SelectedRow);
_ = RefreshAsync();
}
private async Task RefreshAsync()
{
try
{
IsLoading = true;
var all = await _menuService.GetAllMenusForManageAsync();
RebuildFlat(all);
RebuildParentOptions(all);
}
catch (Exception ex)
{
Growl.Error($"加载菜单失败:{ex.Message}");
}
finally
{
IsLoading = false;
}
}
private void RebuildFlat(List<SysMenu> all)
{
FlatRows.Clear();
void Walk(long pid, int depth)
{
foreach (var m in all.Where(x => x.Pid == pid).OrderBy(x => x.OrderNo).ThenBy(x => x.Id))
{
FlatRows.Add(new MenuFlatRow(m, depth));
Walk(m.Id, depth + 1);
}
}
Walk(0, 0);
}
private void RebuildParentOptions(List<SysMenu> all)
{
ParentOptions.Clear();
ParentOptions.Add(new KeyValuePair<long, string>(0, "(根目录)"));
void Walk(long pid, int depth)
{
foreach (var m in all.Where(x => x.Pid == pid).OrderBy(x => x.OrderNo).ThenBy(x => x.Id))
{
var indent = new string(' ', depth);
ParentOptions.Add(new KeyValuePair<long, string>(m.Id, indent + m.Title));
Walk(m.Id, depth + 1);
}
}
Walk(0, 0);
}
private void BeginNew(long pid, MenuTypeEnum type)
{
// 先取消列表选中,避免 setter 把新建的 Editor 清空
_selectedRow = null;
RaisePropertyChanged(nameof(SelectedRow));
Editor = new MenuEditorModel();
Editor.ResetForNew(pid, type);
RaisePropertyChanged(nameof(Editor));
RaisePropertyChanged(nameof(HasEditor));
}
private void BeginNewChild()
{
if (SelectedRow == null)
return;
BeginNew(SelectedRow.Menu.Id, MenuTypeEnum.Menu);
}
private async Task SaveAsync()
{
if (Editor == null)
return;
try
{
IsLoading = true;
var entity = Editor.ToSysMenu();
if (Editor.IsNew)
{
var (ok, msg, id) = await _menuService.CreateMenuAsync(entity);
if (ok)
{
Growl.Success(msg);
_eventAggregator.GetEvent<MenuStructureChangedEvent>().Publish(true);
await RefreshAsync();
SelectedRow = FlatRows.FirstOrDefault(r => r.Menu.Id == id);
}
else
{
Growl.Warning(msg);
}
}
else
{
var (ok, msg) = await _menuService.UpdateMenuAsync(entity);
if (ok)
{
Growl.Success(msg);
_eventAggregator.GetEvent<MenuStructureChangedEvent>().Publish(true);
var keepId = entity.Id;
await RefreshAsync();
SelectedRow = FlatRows.FirstOrDefault(r => r.Menu.Id == keepId);
}
else
{
Growl.Warning(msg);
}
}
}
catch (Exception ex)
{
Growl.Error($"保存失败:{ex.Message}");
}
finally
{
IsLoading = false;
}
}
private async Task DeleteAsync()
{
if (SelectedRow == null)
return;
var r = System.Windows.MessageBox.Show(
$"确定删除「{SelectedRow.Menu.Title}」?若存在子菜单将无法删除。",
"确认删除",
System.Windows.MessageBoxButton.OKCancel,
System.Windows.MessageBoxImage.Question);
if (r != System.Windows.MessageBoxResult.OK)
return;
try
{
IsLoading = true;
var (ok, msg) = await _menuService.DeleteMenuAsync(SelectedRow.Menu.Id);
if (ok)
{
Growl.Success(msg);
_eventAggregator.GetEvent<MenuStructureChangedEvent>().Publish(true);
Editor = null;
SelectedRow = null;
await RefreshAsync();
}
else
{
Growl.Warning(msg);
}
}
catch (Exception ex)
{
Growl.Error($"删除失败:{ex.Message}");
}
finally
{
IsLoading = false;
}
}
}

View File

@@ -135,14 +135,12 @@ namespace YY.Admin.ViewModels.SysManage
SysUser = new SysUser
{
Id = user.Id,
//Account = user.Account,
Account = user.Account,
RealName = user.RealName,
NickName = user.NickName,
//Phone = user.Phone,
Sex = user.Sex,
Birthday = user.Birthday,
Age = user.Age,
//AccountType = user.AccountType,
Status = user.Status
};
}

View File

@@ -6,6 +6,7 @@ using System.Windows;
using YY.Admin.Core;
using YY.Admin.Core.Extension;
using YY.Admin.Core.Helper;
using YY.Admin.Infrastructure.Sync;
using YY.Admin.Services.Service;
using YY.Admin.Services.Service.User;
using YY.Admin.ViewModels.Control;
@@ -20,9 +21,11 @@ namespace YY.Admin.ViewModels.SysManage
private PageUserInput _userInput;
private readonly ISysUserService _sysUserService;
private readonly OutboxProcessor _outboxProcessor;
private readonly IDialogService _dialogService;
private SubscriptionToken? _jeecgSyncToken;
private bool _isManualUploading;
public PaginationDataGridViewModel<UserOutput> PaginationDataGridViewModel
{
get => _paginationDataGridViewModel;
@@ -94,6 +97,7 @@ namespace YY.Admin.ViewModels.SysManage
public DelegateCommand<UserOutput> EditCommand { get; private set; }
public DelegateCommand<UserOutput> StatusToggleCommand { get; private set; }
public DelegateCommand ManualUploadCommand { get; private set; }
// 行选择改变命令
@@ -101,12 +105,14 @@ namespace YY.Admin.ViewModels.SysManage
public UserManagementViewModel(
ISysUserService sysUserService,
OutboxProcessor outboxProcessor,
IContainerExtension container,
IDialogService dialogService,
IRegionManager regionManager
) : base(container, regionManager)
{
_sysUserService= sysUserService;
_outboxProcessor = outboxProcessor;
_dialogService = dialogService;
// 创建分页控件的 ViewModel传递一个获取数据的委托
_paginationDataGridViewModel = new PaginationDataGridViewModel<UserOutput>(FetchUsersAsync);
@@ -132,6 +138,7 @@ namespace YY.Admin.ViewModels.SysManage
EditCommand = new DelegateCommand<UserOutput>(async (user) => await ShowEditDialog(user));
StatusToggleCommand = new DelegateCommand<UserOutput>(async (user) => await ToggleStatus(user));
ManualUploadCommand = new DelegateCommand(async () => await ManualUploadAsync(), () => !_isManualUploading);
//RowSelectionChangedCommand = new DelegateCommand<UserOutput>(OnRowSelectionChanged);
@@ -457,6 +464,31 @@ namespace YY.Admin.ViewModels.SysManage
}
}
private async Task ManualUploadAsync()
{
if (_isManualUploading)
{
return;
}
_isManualUploading = true;
ManualUploadCommand.RaiseCanExecuteChanged();
try
{
await _outboxProcessor.FlushPendingAsync(CancellationToken.None);
Growl.Success("已触发手动上传,请稍后查看后端数据。");
}
catch (Exception ex)
{
Growl.Warning($"手动上传失败:{ex.Message}");
}
finally
{
_isManualUploading = false;
ManualUploadCommand.RaiseCanExecuteChanged();
}
}
// 全选/取消全选方法
//private void SelectAll(bool isSelected)
//{

View File

@@ -0,0 +1,176 @@
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using System.Collections.ObjectModel;
using YY.Admin.Core;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Services;
using YY.Admin.Services.Service;
namespace YY.Admin.ViewModels.Vehicle;
public class VehicleEditDialogViewModel : BaseViewModel, IDialogResultable<bool>
{
private readonly IVehicleService _vehicleService;
private readonly IJeecgDictSyncService _dictSyncService;
private MesXslVehicle? _vehicle;
public MesXslVehicle? Vehicle
{
get => _vehicle;
set => SetProperty(ref _vehicle, value);
}
public bool IsAddMode => string.IsNullOrWhiteSpace(Vehicle?.Id);
public string DialogTitle => IsAddMode ? "新增车辆" : "编辑车辆";
public ObservableCollection<KeyValuePair<string, string>> VehicleBelongOptions { get; } = new();
public ObservableCollection<KeyValuePair<string, string>> StatusOptions { get; } = new();
private bool _result;
public bool Result { get => _result; set => SetProperty(ref _result, value); }
public Action? CloseAction { get; set; }
public DelegateCommand SaveCommand { get; }
public DelegateCommand CancelCommand { get; }
public VehicleEditDialogViewModel(
IVehicleService vehicleService,
IJeecgDictSyncService dictSyncService,
IContainerExtension container,
IRegionManager regionManager) : base(container, regionManager)
{
_vehicleService = vehicleService;
_dictSyncService = dictSyncService;
SaveCommand = new DelegateCommand(async () => await SaveAsync());
CancelCommand = new DelegateCommand(() => CloseAction?.Invoke());
_ = LoadDictOptionsAsync();
}
private async Task LoadDictOptionsAsync()
{
try
{
var belongOptions = await _dictSyncService.GetDictOptionsAsync("xslmes_vehicle_belong");
var statusOptions = await _dictSyncService.GetDictOptionsAsync("xslmes_vehicle_status");
VehicleBelongOptions.Clear();
foreach (var item in belongOptions)
{
VehicleBelongOptions.Add(item);
}
StatusOptions.Clear();
foreach (var item in statusOptions)
{
StatusOptions.Add(item);
}
if (VehicleBelongOptions.Count == 0)
{
VehicleBelongOptions.Add(new KeyValuePair<string, string>("客户", "1"));
VehicleBelongOptions.Add(new KeyValuePair<string, string>("供应商", "2"));
VehicleBelongOptions.Add(new KeyValuePair<string, string>("本公司", "3"));
}
if (StatusOptions.Count == 0)
{
StatusOptions.Add(new KeyValuePair<string, string>("启用", "0"));
StatusOptions.Add(new KeyValuePair<string, string>("停用", "1"));
}
}
catch
{
VehicleBelongOptions.Clear();
VehicleBelongOptions.Add(new KeyValuePair<string, string>("客户", "1"));
VehicleBelongOptions.Add(new KeyValuePair<string, string>("供应商", "2"));
VehicleBelongOptions.Add(new KeyValuePair<string, string>("本公司", "3"));
StatusOptions.Clear();
StatusOptions.Add(new KeyValuePair<string, string>("启用", "0"));
StatusOptions.Add(new KeyValuePair<string, string>("停用", "1"));
}
}
public void InitializeForAdd()
{
Vehicle = new MesXslVehicle { Status = "0", VehicleBelong = "1" };
RaisePropertyChanged(nameof(IsAddMode));
RaisePropertyChanged(nameof(DialogTitle));
}
public void InitializeForEdit(MesXslVehicle vehicle)
{
Vehicle = new MesXslVehicle
{
Id = vehicle.Id,
PlateNumber = vehicle.PlateNumber,
VehicleBelong = vehicle.VehicleBelong,
TareWeightKg = vehicle.TareWeightKg,
LoadCapacity = vehicle.LoadCapacity,
UnitId = vehicle.UnitId,
LoadUnit = vehicle.LoadUnit,
CustomerIds = vehicle.CustomerIds,
CustomerShortName = vehicle.CustomerShortName,
SupplierId = vehicle.SupplierId,
SupplierName = vehicle.SupplierName,
SupplierShortName = vehicle.SupplierShortName,
VehicleLength = vehicle.VehicleLength,
VehicleWidth = vehicle.VehicleWidth,
VehicleHeight = vehicle.VehicleHeight,
DriverName = vehicle.DriverName,
DriverPhone = vehicle.DriverPhone,
Status = vehicle.Status,
TenantId = vehicle.TenantId,
};
RaisePropertyChanged(nameof(IsAddMode));
RaisePropertyChanged(nameof(DialogTitle));
}
private async Task SaveAsync()
{
if (Vehicle == null) return;
if (string.IsNullOrWhiteSpace(Vehicle.PlateNumber))
{
HandyControl.Controls.MessageBox.Warning("车牌号不能为空!");
return;
}
if (string.IsNullOrWhiteSpace(Vehicle.VehicleBelong))
{
HandyControl.Controls.MessageBox.Warning("车辆归属不能为空!");
return;
}
try
{
bool ok;
if (IsAddMode)
{
ok = await _vehicleService.AddAsync(Vehicle);
if (ok)
{
HandyControl.Controls.MessageBox.Success("新增车辆成功!");
}
else
{
HandyControl.Controls.MessageBox.Error("新增车辆失败!");
return;
}
}
else
{
ok = await _vehicleService.EditAsync(Vehicle);
if (!ok)
{
HandyControl.Controls.MessageBox.Error("编辑车辆失败!");
return;
}
}
Result = ok;
CloseAction?.Invoke();
}
catch (Exception ex)
{
HandyControl.Controls.MessageBox.Error($"操作失败:{ex.Message}");
}
}
}

View File

@@ -0,0 +1,306 @@
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using Prism.Events;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using YY.Admin.Core;
using YY.Admin.Core.Events;
using YY.Admin.Core.Helper;
using YY.Admin.Core.Entity;
using YY.Admin.Core.Services;
using YY.Admin.Services.Service;
using YY.Admin.Views.Vehicle;
namespace YY.Admin.ViewModels.Vehicle;
public class VehicleListViewModel : BaseViewModel
{
private readonly IVehicleService _vehicleService;
private readonly IJeecgDictSyncService _dictSyncService;
private readonly IDialogService _dialogService;
private SubscriptionToken? _vehicleChangedToken;
private SubscriptionToken? _syncConflictToken;
private ObservableCollection<MesXslVehicle> _vehicles = new();
public ObservableCollection<MesXslVehicle> Vehicles
{
get => _vehicles;
set => SetProperty(ref _vehicles, value);
}
private long _total;
public long Total { get => _total; set => SetProperty(ref _total, value); }
private int _pageNo = 1;
public int PageNo { get => _pageNo; set => SetProperty(ref _pageNo, value); }
private int _pageSize = 20;
public int PageSize { get => _pageSize; set => SetProperty(ref _pageSize, value); }
private string? _filterPlateNumber;
public string? FilterPlateNumber { get => _filterPlateNumber; set => SetProperty(ref _filterPlateNumber, value); }
private string? _filterVehicleBelong;
public string? FilterVehicleBelong { get => _filterVehicleBelong; set => SetProperty(ref _filterVehicleBelong, value); }
private string? _filterStatus;
public string? FilterStatus { get => _filterStatus; set => SetProperty(ref _filterStatus, value); }
public ObservableCollection<KeyValuePair<string, string>> VehicleBelongOptions { get; } = new();
public ObservableCollection<KeyValuePair<string, string>> StatusOptions { get; } = new();
public DelegateCommand SearchCommand { get; }
public DelegateCommand ResetCommand { get; }
public DelegateCommand AddCommand { get; }
public DelegateCommand<MesXslVehicle> EditCommand { get; }
public DelegateCommand<MesXslVehicle> DeleteCommand { get; }
public DelegateCommand<MesXslVehicle> ToggleStatusCommand { get; }
public DelegateCommand PrevPageCommand { get; }
public DelegateCommand NextPageCommand { get; }
public VehicleListViewModel(
IVehicleService vehicleService,
IJeecgDictSyncService dictSyncService,
IContainerExtension container,
IDialogService dialogService,
IRegionManager regionManager) : base(container, regionManager)
{
_vehicleService = vehicleService;
_dictSyncService = dictSyncService;
_dialogService = dialogService;
SearchCommand = new DelegateCommand(async () => { PageNo = 1; await LoadAsync(); });
ResetCommand = new DelegateCommand(async () =>
{
FilterPlateNumber = null;
FilterVehicleBelong = null;
FilterStatus = null;
PageNo = 1;
await LoadAsync();
});
AddCommand = new DelegateCommand(async () => await ShowAddDialogAsync());
EditCommand = new DelegateCommand<MesXslVehicle>(async v => await ShowEditDialogAsync(v));
DeleteCommand = new DelegateCommand<MesXslVehicle>(async v => await DeleteAsync(v));
ToggleStatusCommand = new DelegateCommand<MesXslVehicle>(async v => await ToggleStatusAsync(v));
PrevPageCommand = new DelegateCommand(async () => { if (PageNo > 1) { PageNo--; await LoadAsync(); } });
NextPageCommand = new DelegateCommand(async () => { if ((long)PageNo * PageSize < Total) { PageNo++; await LoadAsync(); } });
_vehicleChangedToken = _eventAggregator
.GetEvent<VehicleChangedEvent>()
.Subscribe(async p => await OnVehicleChangedAsync(p), ThreadOption.UIThread);
_syncConflictToken = _eventAggregator.GetEvent<SyncConflictEvent>()
.Subscribe(OnSyncConflict, ThreadOption.UIThread);
_ = InitializeAsync();
}
private async Task OnVehicleChangedAsync(VehicleChangedPayload payload)
{
if (payload.Action == "edit" && !string.IsNullOrWhiteSpace(payload.VehicleId))
{
await RefreshSingleAsync(payload.VehicleId!);
}
else
{
await LoadAsync();
}
}
private async Task RefreshSingleAsync(string vehicleId)
{
try
{
var updated = await _vehicleService.GetByIdAsync(vehicleId);
if (updated == null) return;
var idx = Vehicles.ToList().FindIndex(v => string.Equals(v.Id, vehicleId, StringComparison.OrdinalIgnoreCase));
if (idx >= 0)
Vehicles[idx] = updated;
}
catch (Exception ex)
{
Debug.WriteLine($"[车辆] 单条刷新失败: {ex.Message}");
}
}
private void OnSyncConflict(SyncConflictPayload payload)
{
if (!string.Equals(payload.EntityName, "车辆", StringComparison.OrdinalIgnoreCase)) return;
var parts = new List<string>();
if (payload.PushedCount > 0)
parts.Add($"已同步 {payload.PushedCount} 条本地改动到服务器");
if (payload.NewRecordsPushed > 0)
parts.Add($"已上传 {payload.NewRecordsPushed} 条本地新增记录");
if (payload.ConflictCount > 0)
parts.Add($"{payload.ConflictCount} 条记录与服务器版本冲突,已保留服务器版本");
if (parts.Count == 0) return;
var message = string.Join("\n", parts);
if (payload.ConflictCount > 0)
Growl.Warning(message);
else
Growl.Success(message);
}
private async Task InitializeAsync()
{
try
{
await LoadDictOptionsAsync();
await UIHelper.WaitForRenderAsync();
await LoadAsync();
}
catch (Exception ex)
{
Debug.WriteLine($"车辆列表初始化失败: {ex.Message}");
}
}
private async Task LoadDictOptionsAsync()
{
try
{
var belongOptions = await _dictSyncService.GetDictOptionsAsync("xslmes_vehicle_belong", includeAll: true);
var statusOptions = await _dictSyncService.GetDictOptionsAsync("xslmes_vehicle_status", includeAll: true);
VehicleBelongOptions.Clear();
foreach (var item in belongOptions)
{
VehicleBelongOptions.Add(item);
}
StatusOptions.Clear();
foreach (var item in statusOptions)
{
StatusOptions.Add(item);
}
if (VehicleBelongOptions.Count == 0)
{
VehicleBelongOptions.Add(new KeyValuePair<string, string>("全部", ""));
}
if (StatusOptions.Count == 0)
{
StatusOptions.Add(new KeyValuePair<string, string>("全部", ""));
}
}
catch
{
VehicleBelongOptions.Clear();
VehicleBelongOptions.Add(new KeyValuePair<string, string>("全部", ""));
VehicleBelongOptions.Add(new KeyValuePair<string, string>("客户", "1"));
VehicleBelongOptions.Add(new KeyValuePair<string, string>("供应商", "2"));
VehicleBelongOptions.Add(new KeyValuePair<string, string>("本公司", "3"));
StatusOptions.Clear();
StatusOptions.Add(new KeyValuePair<string, string>("全部", ""));
StatusOptions.Add(new KeyValuePair<string, string>("启用", "0"));
StatusOptions.Add(new KeyValuePair<string, string>("停用", "1"));
}
}
public async Task LoadAsync()
{
try
{
IsLoading = true;
var result = await _vehicleService.PageAsync(PageNo, PageSize, FilterPlateNumber, FilterVehicleBelong, FilterStatus);
Vehicles = new ObservableCollection<MesXslVehicle>(result.Records);
Total = result.Total;
}
catch (Exception ex)
{
Growl.Error($"加载车辆列表失败:{ex.Message}");
}
finally
{
IsLoading = false;
}
}
private async Task ShowAddDialogAsync()
{
try
{
var result = await HandyControl.Controls.Dialog.Show<VehicleEditDialogView>()
.Initialize<VehicleEditDialogViewModel>(vm => vm.InitializeForAdd())
.GetResultAsync<bool>();
if (result) await LoadAsync();
}
catch (Exception ex)
{
Growl.Error($"打开新增对话框失败:{ex.Message}");
}
}
private async Task ShowEditDialogAsync(MesXslVehicle vehicle)
{
if (vehicle == null) return;
try
{
var result = await HandyControl.Controls.Dialog.Show<VehicleEditDialogView>()
.Initialize<VehicleEditDialogViewModel>(vm => vm.InitializeForEdit(vehicle))
.GetResultAsync<bool>();
if (result) await LoadAsync();
}
catch (Exception ex)
{
Growl.Error($"打开编辑对话框失败:{ex.Message}");
}
}
private async Task DeleteAsync(MesXslVehicle vehicle)
{
if (vehicle?.Id == null) return;
var confirm = System.Windows.MessageBox.Show($"确定删除车辆 {vehicle.PlateNumber}?此操作不可恢复!", "确认删除",
MessageBoxButton.OKCancel, MessageBoxImage.Question);
if (confirm != System.Windows.MessageBoxResult.OK) return;
var ok = await _vehicleService.DeleteAsync(vehicle.Id);
if (ok)
{
Growl.Success("删除成功!");
await LoadAsync();
}
else
{
Growl.Error("删除失败!");
}
}
private async Task ToggleStatusAsync(MesXslVehicle vehicle)
{
if (vehicle?.Id == null) return;
var newStatus = vehicle.Status == "1" ? "0" : "1";
var ok = await _vehicleService.UpdateStatusAsync(vehicle.Id, newStatus);
if (ok)
{
vehicle.Status = newStatus;
RaisePropertyChanged(nameof(Vehicles));
}
else
{
Growl.Error("状态切换失败!");
}
}
protected override void CleanUp()
{
base.CleanUp();
if (_vehicleChangedToken != null)
{
_eventAggregator.GetEvent<VehicleChangedEvent>().Unsubscribe(_vehicleChangedToken);
_vehicleChangedToken = null;
}
if (_syncConflictToken != null)
{
_eventAggregator.GetEvent<SyncConflictEvent>().Unsubscribe(_syncConflictToken);
_syncConflictToken = null;
}
}
}

View File

@@ -0,0 +1,133 @@
<UserControl x:Class="YY.Admin.Views.Customer.CustomerEditDialogView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
Width="700"
MinHeight="400">
<Grid Background="{DynamicResource ThirdlyRegionBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- 标题栏 -->
<hc:SimplePanel Margin="20">
<TextBlock FontSize="18" Foreground="{DynamicResource PrimaryTextBrush}"
Text="{Binding DialogTitle}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Button Width="22" Height="22" Command="hc:ControlCommands.Close"
Style="{StaticResource ButtonIcon}" Foreground="{DynamicResource PrimaryBrush}"
hc:IconElement.Geometry="{StaticResource ErrorGeometry}"
Padding="0" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,4,4,0"/>
</hc:SimplePanel>
<!-- 表单区域 -->
<hc:ScrollViewer Grid.Row="1" IsInertiaEnabled="True">
<StackPanel Margin="20,0,20,0">
<hc:Row Gutter="10">
<!-- 客户编码 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Customer.CustomerCode, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="客户编码"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入客户编码(同租户内唯一)"
hc:InfoElement.Necessary="True"
hc:InfoElement.Symbol="*"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 客户名称 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Customer.CustomerName, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="客户名称"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入客户名称"
hc:InfoElement.Necessary="True"
hc:InfoElement.Symbol="*"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 客户简称 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Customer.CustomerShortName, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="客户简称"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入客户简称"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 客户区域 -->
<hc:Col Span="12">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding CustomerRegionOptions}"
SelectedValue="{Binding Customer.CustomerRegion}"
hc:InfoElement.Title="客户区域"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- ERP编码 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Customer.ErpCode, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="ERP编码"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入ERP编码"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 状态 -->
<hc:Col Span="12">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding StatusOptions}"
SelectedValue="{Binding Customer.Status}"
hc:InfoElement.Title="状态"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 客户描述 -->
<hc:Col Span="24">
<hc:TextBox Text="{Binding Customer.CustomerDesc, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="客户描述"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入客户描述"
hc:InfoElement.ShowClearButton="True"
TextWrapping="Wrap"
AcceptsReturn="True"
Height="80"
Margin="0,0,0,16"/>
</hc:Col>
</hc:Row>
</StackPanel>
</hc:ScrollViewer>
<!-- 按钮区域 -->
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" Margin="20">
<Button Content="取消" Command="{Binding CancelCommand}" Style="{StaticResource ButtonDefault}" Margin="0,0,15,0" Width="100"/>
<Button Content="确定" Command="{Binding SaveCommand}" Style="{StaticResource ButtonPrimary}" Width="100"/>
</StackPanel>
</Grid>
</UserControl>

View File

@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace YY.Admin.Views.Customer;
public partial class CustomerEditDialogView : UserControl
{
public CustomerEditDialogView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,174 @@
<UserControl x:Class="YY.Admin.Views.Customer.CustomerListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d">
<Grid Style="{StaticResource BaseViewStyle}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- 搜索条件 -->
<Border Grid.Row="0" CornerRadius="4" Margin="0 0 -10 0">
<hc:Row>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}">
<hc:TextBox Text="{Binding FilterCustomerCode, UpdateSourceTrigger=PropertyChanged}"
Margin="0 0 10 10"
hc:InfoElement.Title="客户编码"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.TitleWidth="65"
hc:InfoElement.Placeholder="请输入客户编码"
hc:InfoElement.ShowClearButton="True"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}">
<hc:TextBox Text="{Binding FilterCustomerName, UpdateSourceTrigger=PropertyChanged}"
Margin="0 0 10 10"
hc:InfoElement.Title="客户名称"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.TitleWidth="65"
hc:InfoElement.Placeholder="请输入客户名称"
hc:InfoElement.ShowClearButton="True"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding CustomerRegionOptions}"
SelectedValue="{Binding FilterCustomerRegion}"
Margin="0 0 10 10"
hc:InfoElement.Title="客户区域"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.TitleWidth="65"
hc:InfoElement.Placeholder="请选择区域"
hc:InfoElement.ShowClearButton="True"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding StatusOptions}"
SelectedValue="{Binding FilterStatus}"
Margin="0 0 10 10"
hc:InfoElement.Title="状态"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.TitleWidth="65"
hc:InfoElement.Placeholder="请选择状态"
hc:InfoElement.ShowClearButton="True"/>
</hc:Col>
</hc:Row>
</Border>
<!-- 工具栏 -->
<Border Grid.Row="1" Margin="0,10">
<hc:UniformSpacingPanel Spacing="10">
<Button Style="{StaticResource ButtonPrimary}" Command="{Binding SearchCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Search"/>
<TextBlock Text="搜索" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonDefault}" Command="{Binding ResetCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Refresh"/>
<TextBlock Text="重置" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonSuccess}" Command="{Binding AddCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Plus"/>
<TextBlock Text="新增" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
</hc:UniformSpacingPanel>
</Border>
<!-- 数据表格 -->
<DataGrid Grid.Row="2"
ItemsSource="{Binding Customers}"
AutoGenerateColumns="False"
IsReadOnly="True"
CanUserAddRows="False"
SelectionMode="Extended"
SelectionUnit="FullRow"
RowHeaderWidth="55"
GridLinesVisibility="Horizontal"
HorizontalGridLinesBrush="#FFEDEDED"
VerticalGridLinesBrush="Transparent"
HeadersVisibility="All"
ColumnHeaderStyle="{StaticResource CusDataGridColumnHeaderStyle}"
Style="{StaticResource CusDataGridStyle}"
hc:DataGridAttach.ShowSelectAllButton="True"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto">
<DataGrid.RowHeaderTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
</DataTemplate>
</DataGrid.RowHeaderTemplate>
<DataGrid.Columns>
<DataGridTextColumn Header="客户编码" Binding="{Binding CustomerCode}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="130"/>
<DataGridTextColumn Header="客户名称" Binding="{Binding CustomerName}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="160"/>
<DataGridTextColumn Header="客户简称" Binding="{Binding CustomerShortName}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="120"/>
<DataGridTextColumn Header="客户区域" Binding="{Binding CustomerRegion}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="100"/>
<DataGridTextColumn Header="ERP编码" Binding="{Binding ErpCode}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="120"/>
<DataGridTextColumn Header="状态" Binding="{Binding StatusText}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="80"/>
<DataGridTextColumn Header="描述" Binding="{Binding CustomerDesc}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="180"/>
<DataGridTemplateColumn Header="操作" Width="200" CellStyle="{StaticResource CusOperDataGridCellStyle}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<hc:UniformSpacingPanel Spacing="5">
<Border Style="{DynamicResource DataGridOpeButtonStyle}">
<Border.InputBindings>
<MouseBinding Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}" MouseAction="LeftClick"/>
</Border.InputBindings>
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="SquareEditOutline" VerticalAlignment="Center"/>
<TextBlock Text="修改" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border Style="{DynamicResource DataGridOpeButtonStyle}">
<Border.InputBindings>
<MouseBinding Command="{Binding DataContext.ToggleStatusCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}" MouseAction="LeftClick"/>
</Border.InputBindings>
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="ToggleSwitch" VerticalAlignment="Center"/>
<TextBlock Text="启/停" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border Style="{DynamicResource DataGridOpeButtonStyle}">
<Border.InputBindings>
<MouseBinding Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}" MouseAction="LeftClick"/>
</Border.InputBindings>
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="TrashCanOutline" VerticalAlignment="Center"/>
<TextBlock Text="删除" VerticalAlignment="Center"/>
</StackPanel>
</Border>
</hc:UniformSpacingPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<!-- 分页 -->
<StackPanel Grid.Row="3" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,10,0,0">
<TextBlock Text="{Binding Total, StringFormat=共 {0} 条}" VerticalAlignment="Center" Margin="0,0,16,0"
Foreground="{DynamicResource SecondaryTextBrush}"/>
<Button Content="上一页" Command="{Binding PrevPageCommand}" Style="{StaticResource ButtonDefault}" Margin="0,0,4,0" Width="80"/>
<TextBlock Text="{Binding PageNo, StringFormat=第 {0} 页}" VerticalAlignment="Center" Margin="8,0"
Foreground="{DynamicResource PrimaryTextBrush}"/>
<Button Content="下一页" Command="{Binding NextPageCommand}" Style="{StaticResource ButtonDefault}" Width="80"/>
</StackPanel>
</Grid>
</UserControl>

View File

@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace YY.Admin.Views.Customer;
public partial class CustomerListView : UserControl
{
public CustomerListView()
{
InitializeComponent();
}
}

View File

@@ -2,7 +2,8 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctls="clr-namespace:YY.Admin.Core.Controls;assembly=YY.Admin.Core"
Width="460" Height="360">
Width="520" Height="420"
Loaded="UserControl_Loaded">
<Border Background="White" BorderBrush="#f0f0f0" BorderThickness="1" CornerRadius="4">
<Grid Margin="0">
<Grid.RowDefinitions>
@@ -19,16 +20,23 @@
<StackPanel Grid.Row="1" Margin="20,16,20,0">
<TextBlock Text="IP" Margin="0,0,0,6"/>
<TextBox Text="{Binding Ip, UpdateSourceTrigger=PropertyChanged}" Height="32"/>
<TextBox Text="{Binding Ip, UpdateSourceTrigger=PropertyChanged}" Height="32" IsEnabled="{Binding IsConnectionFieldsEnabled}"/>
<TextBlock Text="端口" Margin="0,12,0,6"/>
<TextBox Text="{Binding Port, UpdateSourceTrigger=PropertyChanged}" Height="32"/>
<TextBox Text="{Binding Port, UpdateSourceTrigger=PropertyChanged}" Height="32" IsEnabled="{Binding IsConnectionFieldsEnabled}"/>
<TextBlock Text="WebSocket 地址(可选)" Margin="0,12,0,6"/>
<TextBox Text="{Binding WebSocketUrl, UpdateSourceTrigger=PropertyChanged}" Height="32"/>
<TextBox Text="{Binding WebSocketUrl, UpdateSourceTrigger=PropertyChanged}" Height="32" IsEnabled="{Binding IsConnectionFieldsEnabled}"/>
<TextBlock Text="后端上下文路径" Margin="0,12,0,6"/>
<TextBox Text="{Binding BasePath, UpdateSourceTrigger=PropertyChanged}" Height="32"/>
<TextBox Text="{Binding BasePath, UpdateSourceTrigger=PropertyChanged}" Height="32" IsEnabled="{Binding IsConnectionFieldsEnabled}"/>
<DockPanel Margin="0,12,0,0" LastChildFill="False">
<TextBlock Text="断开连接" VerticalAlignment="Center"/>
<ToggleButton DockPanel.Dock="Right"
IsChecked="{Binding DisconnectConnection, Mode=TwoWay}"
Style="{StaticResource ToggleButtonSwitch}"/>
</DockPanel>
<TextBlock Text="{Binding ErrorMessage}" Foreground="Red" Margin="0,12,0,0"/>
</StackPanel>

View File

@@ -1,4 +1,5 @@
using System.Windows.Controls;
using System.Windows;
namespace YY.Admin.Views.Dialogs
{
@@ -11,5 +12,22 @@ namespace YY.Admin.Views.Dialogs
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var win = Window.GetWindow(this);
if (win == null) return;
// 必须先关闭 AllowsTransparency再改 WindowStyle否则会抛出
// 「当 AllowsTransparency 为 true 时WindowStyle.None 是唯一有效值」)
win.AllowsTransparency = false;
win.WindowStyle = WindowStyle.SingleBorderWindow;
win.ResizeMode = ResizeMode.CanResizeWithGrip;
win.SizeToContent = SizeToContent.Manual;
win.MinWidth = 520;
win.MinHeight = 420;
if (win.Width < 520) win.Width = 520;
if (win.Height < 420) win.Height = 420;
}
}
}

View File

@@ -0,0 +1,99 @@
<UserControl x:Class="YY.Admin.Views.Supplier.SupplierEditDialogView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
Width="700" MinHeight="360">
<Grid Background="{DynamicResource ThirdlyRegionBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<hc:SimplePanel Margin="20">
<TextBlock FontSize="18" Foreground="{DynamicResource PrimaryTextBrush}" Text="{Binding DialogTitle}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Button Width="22" Height="22" Command="hc:ControlCommands.Close" Style="{StaticResource ButtonIcon}"
Foreground="{DynamicResource PrimaryBrush}" hc:IconElement.Geometry="{StaticResource ErrorGeometry}"
Padding="0" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,4,4,0"/>
</hc:SimplePanel>
<hc:ScrollViewer Grid.Row="1" IsInertiaEnabled="True">
<StackPanel Margin="20,0,20,0">
<hc:Row Gutter="10">
<hc:Col Span="12">
<hc:TextBox Text="{Binding Supplier.SupplierCode, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="供应商编码"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入供应商编码(同租户内唯一)"
hc:InfoElement.Necessary="True"
hc:InfoElement.Symbol="*"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<hc:Col Span="12">
<hc:TextBox Text="{Binding Supplier.SupplierName, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="供应商名称"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入供应商名称"
hc:InfoElement.Necessary="True"
hc:InfoElement.Symbol="*"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<hc:Col Span="12">
<hc:TextBox Text="{Binding Supplier.SupplierShortName, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="供应商简称"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入供应商简称"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<hc:Col Span="12">
<hc:TextBox Text="{Binding Supplier.ErpCode, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="ERP编码"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入ERP编码"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<hc:Col Span="12">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding StatusOptions}"
SelectedValue="{Binding Supplier.Status}"
hc:InfoElement.Title="状态"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
Margin="0,0,0,16"/>
</hc:Col>
<hc:Col Span="24">
<hc:TextBox Text="{Binding Supplier.Remark, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="备注"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入备注"
hc:InfoElement.ShowClearButton="True"
TextWrapping="Wrap"
AcceptsReturn="True"
Height="80"
Margin="0,0,0,16"/>
</hc:Col>
</hc:Row>
</StackPanel>
</hc:ScrollViewer>
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" Margin="20">
<Button Content="取消" Command="{Binding CancelCommand}" Style="{StaticResource ButtonDefault}" Margin="0,0,15,0" Width="100"/>
<Button Content="确定" Command="{Binding SaveCommand}" Style="{StaticResource ButtonPrimary}" Width="100"/>
</StackPanel>
</Grid>
</UserControl>

View File

@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace YY.Admin.Views.Supplier;
public partial class SupplierEditDialogView : UserControl
{
public SupplierEditDialogView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,83 @@
<UserControl x:Class="YY.Admin.Views.Supplier.SupplierListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d">
<Grid Style="{StaticResource BaseViewStyle}">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions>
<Border Grid.Row="0" CornerRadius="4" Margin="0 0 -10 0">
<hc:Row>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}"><hc:TextBox Text="{Binding FilterSupplierCode}" Margin="0 0 10 10" hc:InfoElement.Title="供应商编码"/></hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}"><hc:TextBox Text="{Binding FilterSupplierName}" Margin="0 0 10 10" hc:InfoElement.Title="供应商名称"/></hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}"><hc:TextBox Text="{Binding FilterSupplierShortName}" Margin="0 0 10 10" hc:InfoElement.Title="供应商简称"/></hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}"><hc:TextBox Text="{Binding FilterErpCode}" Margin="0 0 10 10" hc:InfoElement.Title="ERP编码"/></hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}">
<hc:ComboBox SelectedValuePath="Value" DisplayMemberPath="Key" ItemsSource="{Binding StatusOptions}" SelectedValue="{Binding FilterStatus}" Margin="0 0 10 10" hc:InfoElement.Title="状态"/>
</hc:Col>
</hc:Row>
</Border>
<Border Grid.Row="1" Margin="0,10">
<hc:UniformSpacingPanel Spacing="10">
<Button Style="{StaticResource ButtonPrimary}" Command="{Binding SearchCommand}"><StackPanel Orientation="Horizontal"><md:PackIcon Kind="Search"/><TextBlock Text="搜索" Style="{StaticResource IconButtonStyle}"/></StackPanel></Button>
<Button Style="{StaticResource ButtonDefault}" Command="{Binding ResetCommand}"><StackPanel Orientation="Horizontal"><md:PackIcon Kind="Refresh"/><TextBlock Text="重置" Style="{StaticResource IconButtonStyle}"/></StackPanel></Button>
<Button Style="{StaticResource ButtonSuccess}" Command="{Binding AddCommand}"><StackPanel Orientation="Horizontal"><md:PackIcon Kind="Plus"/><TextBlock Text="新增" Style="{StaticResource IconButtonStyle}"/></StackPanel></Button>
</hc:UniformSpacingPanel>
</Border>
<DataGrid Grid.Row="2" ItemsSource="{Binding Suppliers}" AutoGenerateColumns="False" IsReadOnly="True" Style="{StaticResource CusDataGridStyle}">
<DataGrid.Columns>
<DataGridTextColumn Header="供应商编码" Binding="{Binding SupplierCode}" Width="120"/>
<DataGridTextColumn Header="供应商名称" Binding="{Binding SupplierName}" Width="160"/>
<DataGridTextColumn Header="供应商简称" Binding="{Binding SupplierShortName}" Width="140"/>
<DataGridTextColumn Header="ERP编码" Binding="{Binding ErpCode}" Width="120"/>
<DataGridTextColumn Header="备注" Binding="{Binding Remark}" Width="180"/>
<DataGridTextColumn Header="状态" Binding="{Binding StatusText}" Width="80"/>
<DataGridTemplateColumn Header="操作" Width="200" CellStyle="{StaticResource CusOperDataGridCellStyle}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<hc:UniformSpacingPanel Spacing="5">
<Border Style="{DynamicResource DataGridOpeButtonStyle}">
<Border.InputBindings>
<MouseBinding Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}"
MouseAction="LeftClick"/>
</Border.InputBindings>
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="SquareEditOutline" VerticalAlignment="Center"/>
<TextBlock Text="修改" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border Style="{DynamicResource DataGridOpeButtonStyle}">
<Border.InputBindings>
<MouseBinding Command="{Binding DataContext.ToggleStatusCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}"
MouseAction="LeftClick"/>
</Border.InputBindings>
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="ToggleSwitch" VerticalAlignment="Center"/>
<TextBlock Text="启/停" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border Style="{DynamicResource DataGridOpeButtonStyle}">
<Border.InputBindings>
<MouseBinding Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}"
MouseAction="LeftClick"/>
</Border.InputBindings>
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="TrashCanOutline" VerticalAlignment="Center"/>
<TextBlock Text="删除" VerticalAlignment="Center"/>
</StackPanel>
</Border>
</hc:UniformSpacingPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</UserControl>

View File

@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace YY.Admin.Views.Supplier;
public partial class SupplierListView : UserControl
{
public SupplierListView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,112 @@
<UserControl x:Class="YY.Admin.Views.SysManage.LoginSettingsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:prism="http://prismlibrary.com/"
mc:Ignorable="d"
d:DesignHeight="560" d:DesignWidth="980"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid Style="{StaticResource BaseViewStyle}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" Margin="0,0,0,12">
<hc:UniformSpacingPanel Spacing="10">
<ToggleButton IsChecked="{Binding NeverExpire, Mode=TwoWay}" MinWidth="110" Height="32" Padding="12,0">
<TextBlock Text="永不过期"/>
</ToggleButton>
<Button Style="{StaticResource ButtonDefault}" Command="{Binding LoadCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Refresh"/>
<TextBlock Text="重新加载" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonPrimary}" Command="{Binding SaveCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="ContentSaveOutline"/>
<TextBlock Text="保存" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
</hc:UniformSpacingPanel>
</Border>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<StackPanel MaxWidth="980">
<TextBlock TextWrapping="Wrap" Margin="0,0,0,16" Opacity="0.85"
Text="以下参数保存在本地库 sys_config 中,保存后立即影响新登录与当前会话的续期逻辑;检查间隔会立即应用到已运行的登录状态定时器。开启“永不过期”后,下方参数将锁定为只读,且系统不再弹出登录超时重新登录提示。"/>
<StackPanel IsEnabled="{Binding IsConfigEditable}">
<Border CornerRadius="4" Padding="16" BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1">
<hc:Row>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<TextBlock FontWeight="SemiBold" Text="会话与检查" Margin="0,0,0,8"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:NumericUpDown Value="{Binding TokenExpireMinutes, Mode=TwoWay}"
Minimum="5" Maximum="43200" DecimalPlaces="0"
hc:InfoElement.Title="Token 过期时间"
hc:InfoElement.TitleWidth="140"
hc:InfoElement.TitlePlacement="Left"
Style="{StaticResource NumericUpDownPlus}"
Margin="0,0,0,12"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:NumericUpDown Value="{Binding IdleExtendMinutes, Mode=TwoWay}"
Minimum="1" Maximum="1440" DecimalPlaces="0"
hc:InfoElement.Title="操作时续期阈值"
hc:InfoElement.TitleWidth="140"
hc:InfoElement.TitlePlacement="Left"
Style="{StaticResource NumericUpDownPlus}"
Margin="0,0,0,12"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<TextBlock TextWrapping="Wrap" Opacity="0.75" Margin="0,-4,0,12"
Text="用户有鼠标或键盘操作时若距离过期不足「续期阈值」分钟则将过期时间重新延长为「Token 过期时间」整段。"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:NumericUpDown Value="{Binding CheckIntervalMinutes, Mode=TwoWay}"
Minimum="1" Maximum="120" DecimalPlaces="0"
hc:InfoElement.Title="状态检查间隔"
hc:InfoElement.TitleWidth="140"
hc:InfoElement.TitlePlacement="Left"
Style="{StaticResource NumericUpDownPlus}"
Margin="0,0,0,12"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<TextBlock TextWrapping="Wrap" Opacity="0.75" Margin="0,-4,0,0"
Text="桌面端定时检查登录是否仍有效的间隔(分钟)。间隔越大,过期后提示可能越晚出现。"/>
</hc:Col>
</hc:Row>
</Border>
<Border CornerRadius="4" Padding="12" Margin="0,16,0,0" BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1">
<hc:Row>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<TextBlock FontWeight="SemiBold" Text="RefreshToken分钟" Margin="0,0,0,8"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<hc:NumericUpDown Value="{Binding RefreshTokenExpireMinutes, Mode=TwoWay}"
Minimum="60" Maximum="999999" DecimalPlaces="0"
hc:InfoElement.Title="过期时间"
hc:InfoElement.TitleWidth="140"
hc:InfoElement.TitlePlacement="Left"
Style="{StaticResource NumericUpDownPlus}"
Margin="0,0,0,8"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<TextBlock TextWrapping="Wrap" Opacity="0.75"
Text="与 Web 端约定一致,建议 ≥ 2 × Token 过期时间。当前桌面端内存会话主要受「Token 过期时间」控制,此项仍写入配置供扩展或对接使用。"/>
</hc:Col>
</hc:Row>
</Border>
</StackPanel>
</StackPanel>
</ScrollViewer>
</Grid>
</UserControl>

View File

@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace YY.Admin.Views.SysManage;
public partial class LoginSettingsView : UserControl
{
public LoginSettingsView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,211 @@
<UserControl x:Class="YY.Admin.Views.SysManage.MenuManagementView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:core="clr-namespace:YY.Admin.Core;assembly=YY.Admin.Core"
xmlns:prism="http://prismlibrary.com/"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="980"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid Style="{StaticResource BaseViewStyle}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" Margin="0,0,0,10">
<hc:UniformSpacingPanel Spacing="10">
<Button Style="{StaticResource ButtonPrimary}" Command="{Binding RefreshCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Refresh"/>
<TextBlock Text="刷新" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonSuccess}" Command="{Binding AddRootCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="FolderPlusOutline"/>
<TextBlock Text="新增根目录" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonSuccess}" Command="{Binding AddChildCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="FileTreeOutline"/>
<TextBlock Text="新增子级" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonPrimary}" Command="{Binding SaveCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="ContentSaveOutline"/>
<TextBlock Text="保存" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonDanger}" Command="{Binding DeleteCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="DeleteOutline"/>
<TextBlock Text="删除" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
</hc:UniformSpacingPanel>
</Border>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="320" MinWidth="240"/>
<ColumnDefinition Width="12"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" CornerRadius="4" BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1" Padding="4">
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Top" Margin="4,0,4,8" Text="菜单树(点击选中后在右侧编辑)" TextWrapping="Wrap" Opacity="0.85"/>
<ListBox ItemsSource="{Binding FlatRows}"
SelectedItem="{Binding SelectedRow, Mode=TwoWay}"
DisplayMemberPath="IndentTitle"
VirtualizingStackPanel.IsVirtualizing="True"/>
</DockPanel>
</Border>
<GridSplitter Grid.Column="1" Width="12" HorizontalAlignment="Stretch" Background="Transparent"/>
<ScrollViewer Grid.Column="2" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<StackPanel>
<TextBlock Text="编辑区" FontWeight="SemiBold" Margin="0,0,0,8"/>
<TextBlock TextWrapping="Wrap" Margin="0,0,0,12" Opacity="0.75"
Text="桌面端左侧导航依赖「路径 / 组件 / 路由名」与 MenuTreeViewModel 中的路由映射。新增业务页时,请将「组件」填写为已在 Prism 中 RegisterForNavigation 的视图名(如 VehicleListView。"/>
<Border CornerRadius="4" Padding="8"
Visibility="{Binding HasEditor, Converter={StaticResource Boolean2VisibilityConverter}}">
<hc:Row DataContext="{Binding Editor}">
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="菜单名称"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:ComboBox ItemsSource="{Binding DataContext.ParentOptions, RelativeSource={RelativeSource AncestorType=UserControl}}"
DisplayMemberPath="Value"
SelectedValuePath="Key"
SelectedValue="{Binding Pid, Mode=TwoWay}"
hc:InfoElement.Title="父级"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:ComboBox ItemsSource="{Binding DataContext.MenuTypeList, RelativeSource={RelativeSource AncestorType=UserControl}}"
DisplayMemberPath="Key"
SelectedValuePath="Value"
SelectedValue="{Binding Type, Converter={StaticResource EnumToIntConverter}, ConverterParameter={x:Type core:MenuTypeEnum}}"
hc:InfoElement.Title="类型"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:ComboBox ItemsSource="{Binding DataContext.StatusList, RelativeSource={RelativeSource AncestorType=UserControl}}"
DisplayMemberPath="Key"
SelectedValuePath="Value"
SelectedValue="{Binding Status, Converter={StaticResource EnumToIntConverter}, ConverterParameter={x:Type core:StatusEnum}}"
hc:InfoElement.Title="状态"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:TextBox Text="{Binding OrderNo, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="排序号"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="路由名称"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<hc:TextBox Text="{Binding Path, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="路径"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<hc:TextBox Text="{Binding Component, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="组件/视图名"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:TextBox Text="{Binding Icon, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="图标"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=6, Lg=6, Xl=6}">
<hc:TextBox Text="{Binding Permission, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="权限标识"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<hc:TextBox Text="{Binding Redirect, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="重定向"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<hc:TextBox Text="{Binding Remark, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="备注"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=12, Lg=12, Xl=12}">
<hc:TextBox Text="{Binding OutLink, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="外链"
hc:InfoElement.TitleWidth="88"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,10"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=4, Lg=4, Xl=4}">
<CheckBox Content="内嵌 IFrame" IsChecked="{Binding IsIframe}" Margin="0,6,0,0"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=4, Lg=4, Xl=4}">
<CheckBox Content="隐藏菜单" IsChecked="{Binding IsHide}" Margin="0,6,0,0"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=4, Lg=4, Xl=4}">
<CheckBox Content="固定页签" IsChecked="{Binding IsAffix}" Margin="0,6,0,0"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=12, Md=4, Lg=4, Xl=4}">
<CheckBox Content="缓存页面" IsChecked="{Binding IsKeepAlive}" Margin="0,6,0,0"/>
</hc:Col>
</hc:Row>
</Border>
</StackPanel>
</ScrollViewer>
</Grid>
</Grid>
</UserControl>

View File

@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace YY.Admin.Views.SysManage;
public partial class MenuManagementView : UserControl
{
public MenuManagementView()
{
InitializeComponent();
}
}

View File

@@ -28,18 +28,17 @@
<hc:ScrollViewer Grid.Row="1" IsInertiaEnabled="True">
<StackPanel x:Name="RootPanel" Margin="20 0 20 0">
<hc:Row Gutter="10">
<hc:Col Span="12" Visibility="{Binding IsAddMode, Converter={StaticResource Boolean2VisibilityConverter}}">
<hc:TextBox
<hc:Col Span="12">
<hc:TextBox
Text="{Binding SysUser.Account, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.TitleWidth="70"
Margin="0,0,0,20"
hc:InfoElement.ShowClearButton="True"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入账号"
hc:InfoElement.Title="账号"
hc:InfoElement.Necessary="True"
hc:InfoElement.Symbol="*"
hc:IsEnabled="{Binding IsAddMode}"/>
hc:InfoElement.Symbol="*"/>
</hc:Col>
<hc:Col Span="12" Visibility="{Binding IsAddMode, Converter={StaticResource Boolean2VisibilityConverter}}">
<hc:PasswordBox

View File

@@ -150,6 +150,14 @@
<TextBlock Text="新增" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button
Style="{StaticResource ButtonPrimary}"
Command="{Binding ManualUploadCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Upload"/>
<TextBlock Text="手动上传" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button
Style="{StaticResource ButtonDanger}"
IsEnabled="{Binding HasSelectedItems}"

View File

@@ -0,0 +1,165 @@
<UserControl x:Class="YY.Admin.Views.Vehicle.VehicleEditDialogView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
Width="700"
MinHeight="400">
<Grid Background="{DynamicResource ThirdlyRegionBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- 标题栏 -->
<hc:SimplePanel Margin="20">
<TextBlock FontSize="18" Foreground="{DynamicResource PrimaryTextBrush}" Text="{Binding DialogTitle}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Button Width="22" Height="22" Command="hc:ControlCommands.Close" Style="{StaticResource ButtonIcon}"
Foreground="{DynamicResource PrimaryBrush}" hc:IconElement.Geometry="{StaticResource ErrorGeometry}"
Padding="0" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,4,4,0"/>
</hc:SimplePanel>
<!-- 表单区域 -->
<hc:ScrollViewer Grid.Row="1" IsInertiaEnabled="True">
<StackPanel x:Name="RootPanel" Margin="20,0,20,0">
<hc:Row Gutter="10">
<!-- 车牌号 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Vehicle.PlateNumber, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="车牌号"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入车牌号"
hc:InfoElement.Necessary="True"
hc:InfoElement.Symbol="*"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 车辆归属 -->
<hc:Col Span="12">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding VehicleBelongOptions}"
SelectedValue="{Binding Vehicle.VehicleBelong}"
hc:InfoElement.Title="车辆归属"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Necessary="True"
hc:InfoElement.Symbol="*"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 皮重 -->
<hc:Col Span="12">
<hc:NumericUpDown Value="{Binding Vehicle.TareWeightKg}"
Minimum="0"
DecimalPlaces="2"
Style="{StaticResource NumericUpDownPlus}"
hc:InfoElement.Title="皮重(KG)"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入皮重"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 装载量 -->
<hc:Col Span="12">
<hc:NumericUpDown Value="{Binding Vehicle.LoadCapacity}"
Minimum="0"
DecimalPlaces="2"
Style="{StaticResource NumericUpDownPlus}"
hc:InfoElement.Title="装载量"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入装载量"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 客户简称 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Vehicle.CustomerShortName, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="客户简称"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="客户类型车辆填写"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 供应商名称 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Vehicle.SupplierName, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="供应商名称"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="供应商类型车辆填写"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 供应商简称 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Vehicle.SupplierShortName, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="供应商简称"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 司机 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Vehicle.DriverName, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="司机"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入司机姓名"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 联系电话 -->
<hc:Col Span="12">
<hc:TextBox Text="{Binding Vehicle.DriverPhone, UpdateSourceTrigger=PropertyChanged}"
hc:InfoElement.Title="联系电话"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Placeholder="请输入联系电话"
hc:InfoElement.ShowClearButton="True"
Margin="0,0,0,16"/>
</hc:Col>
<!-- 状态 -->
<hc:Col Span="12">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding StatusOptions}"
SelectedValue="{Binding Vehicle.Status}"
hc:InfoElement.Title="状态"
hc:InfoElement.TitleWidth="80"
hc:InfoElement.TitlePlacement="Left"
Margin="0,0,0,16"/>
</hc:Col>
</hc:Row>
</StackPanel>
</hc:ScrollViewer>
<!-- 按钮区域 -->
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" Margin="20">
<Button Content="取消" Command="{Binding CancelCommand}" Style="{StaticResource ButtonDefault}" Margin="0,0,15,0" Width="100"/>
<Button Content="确定" Command="{Binding SaveCommand}" Style="{StaticResource ButtonPrimary}" Width="100"/>
</StackPanel>
</Grid>
</UserControl>

View File

@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace YY.Admin.Views.Vehicle;
public partial class VehicleEditDialogView : UserControl
{
public VehicleEditDialogView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,160 @@
<UserControl x:Class="YY.Admin.Views.Vehicle.VehicleListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d">
<Grid Style="{StaticResource BaseViewStyle}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- 搜索条件区域 -->
<Border Grid.Row="0" CornerRadius="4" Margin="0 0 -10 0">
<hc:Row>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}">
<hc:TextBox Text="{Binding FilterPlateNumber, UpdateSourceTrigger=PropertyChanged}"
Margin="0 0 10 10"
hc:InfoElement.Title="车牌号"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.TitleWidth="65"
hc:InfoElement.Placeholder="请输入车牌号"
hc:InfoElement.ShowClearButton="True"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding VehicleBelongOptions}"
SelectedValue="{Binding FilterVehicleBelong}"
Margin="0 0 10 10"
hc:InfoElement.Title="车辆归属"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.TitleWidth="65"
hc:InfoElement.Placeholder="请选择车辆归属"
hc:InfoElement.ShowClearButton="True"/>
</hc:Col>
<hc:Col Layout="{hc:ColLayout Xs=12, Sm=8, Md=6, Lg=6, Xl=4}">
<hc:ComboBox SelectedValuePath="Value"
DisplayMemberPath="Key"
ItemsSource="{Binding StatusOptions}"
SelectedValue="{Binding FilterStatus}"
Margin="0 0 10 10"
hc:InfoElement.Title="状态"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.TitleWidth="65"
hc:InfoElement.Placeholder="请选择状态"
hc:InfoElement.ShowClearButton="True"/>
</hc:Col>
</hc:Row>
</Border>
<!-- 操作工具栏 -->
<Border Grid.Row="1" Margin="0,10">
<hc:UniformSpacingPanel Spacing="10">
<Button Style="{StaticResource ButtonPrimary}" Command="{Binding SearchCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Search"/>
<TextBlock Text="搜索" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonDefault}" Command="{Binding ResetCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Refresh"/>
<TextBlock Text="重置" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource ButtonSuccess}" Command="{Binding AddCommand}">
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="Plus"/>
<TextBlock Text="新增" Style="{StaticResource IconButtonStyle}"/>
</StackPanel>
</Button>
</hc:UniformSpacingPanel>
</Border>
<!-- 数据表格 -->
<DataGrid Grid.Row="2"
ItemsSource="{Binding Vehicles}"
AutoGenerateColumns="False"
IsReadOnly="True"
CanUserAddRows="False"
SelectionMode="Extended"
SelectionUnit="FullRow"
RowHeaderWidth="55"
GridLinesVisibility="Horizontal"
HorizontalGridLinesBrush="#FFEDEDED"
VerticalGridLinesBrush="Transparent"
HeadersVisibility="All"
ColumnHeaderStyle="{StaticResource CusDataGridColumnHeaderStyle}"
Style="{StaticResource CusDataGridStyle}"
hc:DataGridAttach.ShowSelectAllButton="True"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto">
<DataGrid.RowHeaderTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
</DataTemplate>
</DataGrid.RowHeaderTemplate>
<DataGrid.Columns>
<DataGridTextColumn Header="车牌号" Binding="{Binding PlateNumber}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="120"/>
<DataGridTextColumn Header="车辆归属" Binding="{Binding VehicleBelongText}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="100"/>
<DataGridTextColumn Header="皮重(KG)" Binding="{Binding TareWeightKg, StringFormat=N2}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="100"/>
<DataGridTextColumn Header="装载量" Binding="{Binding LoadCapacity, StringFormat=N2}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="100"/>
<DataGridTextColumn Header="客户简称" Binding="{Binding CustomerShortName}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="140"/>
<DataGridTextColumn Header="供应商名称" Binding="{Binding SupplierName}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="140"/>
<DataGridTextColumn Header="供应商简称" Binding="{Binding SupplierShortName}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="120"/>
<DataGridTextColumn Header="司机" Binding="{Binding DriverName}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="100"/>
<DataGridTextColumn Header="联系电话" Binding="{Binding DriverPhone}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="130"/>
<DataGridTextColumn Header="状态" Binding="{Binding StatusText}" CellStyle="{StaticResource CusDataGridCellStyle}" Width="80"/>
<DataGridTemplateColumn Header="操作" Width="150" CellStyle="{StaticResource CusOperDataGridCellStyle}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<hc:UniformSpacingPanel Spacing="5">
<Border Style="{DynamicResource DataGridOpeButtonStyle}">
<Border.InputBindings>
<MouseBinding Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}"
MouseAction="LeftClick"/>
</Border.InputBindings>
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="SquareEditOutline" VerticalAlignment="Center"/>
<TextBlock Text="修改" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<Border Style="{DynamicResource DataGridOpeButtonStyle}">
<Border.InputBindings>
<MouseBinding Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}"
MouseAction="LeftClick"/>
</Border.InputBindings>
<StackPanel Orientation="Horizontal">
<md:PackIcon Kind="TrashCanOutline" VerticalAlignment="Center"/>
<TextBlock Text="删除" VerticalAlignment="Center"/>
</StackPanel>
</Border>
</hc:UniformSpacingPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<!-- 分页 -->
<StackPanel Grid.Row="3" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,10,0,0">
<TextBlock Text="{Binding Total, StringFormat=共 {0} 条}" VerticalAlignment="Center" Margin="0,0,16,0"
Foreground="{DynamicResource SecondaryTextBrush}"/>
<Button Content="上一页" Command="{Binding PrevPageCommand}" Style="{StaticResource ButtonDefault}" Margin="0,0,4,0" Width="80"/>
<TextBlock Text="{Binding PageNo, StringFormat=第 {0} 页}" VerticalAlignment="Center" Margin="8,0"
Foreground="{DynamicResource PrimaryTextBrush}"/>
<Button Content="下一页" Command="{Binding NextPageCommand}" Style="{StaticResource ButtonDefault}" Width="80"/>
</StackPanel>
</Grid>
</UserControl>

View File

@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace YY.Admin.Views.Vehicle;
public partial class VehicleListView : UserControl
{
public VehicleListView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,197 @@
#r "nuget: Microsoft.Data.Sqlite, 8.0.0"
using Microsoft.Data.Sqlite;
var dbPath = @"D:/XSL-PROJECT/QH-MES/qhmes/yy-admin-master/YY.Admin/Admin.NET.db";
using var conn = new SqliteConnection($"Data Source={dbPath}");
conn.Open();
using var tx = conn.BeginTransaction();
long baseMenuId = 1300150000101;
long vehicleMenuId = 1300150010101;
long customerMenuId = 1300150010201;
var ensureBase = conn.CreateCommand();
ensureBase.Transaction = tx;
ensureBase.CommandText = @"
INSERT INTO sys_menu (id, pid, title, path, name, component, icon, type, status, order_no, create_time)
SELECT $id, 0, '基础资料', '/base', 'base', 'Layout', '&#xe7c4;', 0, 0, 9000, datetime('now')
WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE id = $id OR title = '基础资料');
";
ensureBase.Parameters.AddWithValue("$id", baseMenuId);
ensureBase.ExecuteNonQuery();
var locateBase = conn.CreateCommand();
locateBase.Transaction = tx;
locateBase.CommandText = "SELECT id FROM sys_menu WHERE title='基础资料' ORDER BY id LIMIT 1;";
var baseIdObj = locateBase.ExecuteScalar();
if (baseIdObj == null || baseIdObj == DBNull.Value) throw new Exception("未找到或创建‘基础资料’菜单");
baseMenuId = Convert.ToInt64(baseIdObj);
var ensureVehicle = conn.CreateCommand();
ensureVehicle.Transaction = tx;
ensureVehicle.CommandText = @"
INSERT INTO sys_menu (id, pid, title, path, name, component, icon, type, status, order_no, create_time)
SELECT $id, $pid, '车辆管理', '/xslmes/mesXslVehicle', 'mesXslVehicle', 'VehicleListView', '&#xe7d2;', 1, 0, 100, datetime('now')
WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE id = $id OR title = '车辆管理' OR name='mesXslVehicle');
";
ensureVehicle.Parameters.AddWithValue("$id", vehicleMenuId);
ensureVehicle.Parameters.AddWithValue("$pid", baseMenuId);
ensureVehicle.ExecuteNonQuery();
var ensureCustomer = conn.CreateCommand();
ensureCustomer.Transaction = tx;
ensureCustomer.CommandText = @"
INSERT INTO sys_menu (id, pid, title, path, name, component, icon, type, status, order_no, create_time)
SELECT $id, $pid, '客户管理', '/xslmes/mesXslCustomer', 'mesXslCustomer', 'CustomerListView', '&#xe7ce;', 1, 0, 101, datetime('now')
WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE id = $id OR title = '客户管理' OR name='mesXslCustomer');
";
ensureCustomer.Parameters.AddWithValue("$id", customerMenuId);
ensureCustomer.Parameters.AddWithValue("$pid", baseMenuId);
ensureCustomer.ExecuteNonQuery();
var moveVehicle = conn.CreateCommand();
moveVehicle.Transaction = tx;
moveVehicle.CommandText = @"
UPDATE sys_menu
SET pid = $pid, status = 0
WHERE title='车辆管理' OR name='mesXslVehicle' OR path='/xslmes/mesXslVehicle' OR path='/xslmes/vehicle' OR component='VehicleListView';
";
moveVehicle.Parameters.AddWithValue("$pid", baseMenuId);
moveVehicle.ExecuteNonQuery();
var moveCustomer = conn.CreateCommand();
moveCustomer.Transaction = tx;
moveCustomer.CommandText = @"
UPDATE sys_menu
SET pid = $pid, status = 0
WHERE title='客户管理' OR name='mesXslCustomer' OR path='/xslmes/mesXslCustomer' OR component='CustomerListView';
";
moveCustomer.Parameters.AddWithValue("$pid", baseMenuId);
moveCustomer.ExecuteNonQuery();
var grantTenant = conn.CreateCommand();
grantTenant.Transaction = tx;
grantTenant.CommandText = @"
INSERT INTO sys_tenant_menu (tenant_id, menu_id)
SELECT 1300000000001, m.id
FROM sys_menu m
WHERE m.id IN ($baseId, (SELECT id FROM sys_menu WHERE title='车辆管理' ORDER BY id LIMIT 1), (SELECT id FROM sys_menu WHERE title='客户管理' ORDER BY id LIMIT 1))
AND NOT EXISTS (
SELECT 1 FROM sys_tenant_menu t
WHERE t.tenant_id = 1300000000001 AND t.menu_id = m.id
);
";
grantTenant.Parameters.AddWithValue("$baseId", baseMenuId);
grantTenant.ExecuteNonQuery();
// 系统管理下「登录设置」菜单(桌面端会话配置)
long systemDirId = 1300200000101;
long loginSettingsMenuId = 1300200013001;
var ensureLoginSettings = conn.CreateCommand();
ensureLoginSettings.Transaction = tx;
ensureLoginSettings.CommandText = @"
INSERT INTO sys_menu (id, pid, title, path, name, component, icon, type, status, order_no, create_time)
SELECT $id, $pid, '登录设置', 'LoginSettingsView', 'loginSettings', 'LoginSettingsView', '&#xe7c1;', 1, 0, 107, datetime('now')
WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE id = $id OR name = 'loginSettings');
";
ensureLoginSettings.Parameters.AddWithValue("$id", loginSettingsMenuId);
ensureLoginSettings.Parameters.AddWithValue("$pid", systemDirId);
ensureLoginSettings.ExecuteNonQuery();
var normalizeLoginSettings = conn.CreateCommand();
normalizeLoginSettings.Transaction = tx;
normalizeLoginSettings.CommandText = @"
UPDATE sys_menu
SET pid = $pid,
title = '登录设置',
path = 'LoginSettingsView',
name = 'loginSettings',
component = 'LoginSettingsView',
type = 1,
status = 0,
order_no = 107
WHERE id = $id
OR name = 'loginSettings'
OR title IN ('登录设置','登陆设置');
";
normalizeLoginSettings.Parameters.AddWithValue("$id", loginSettingsMenuId);
normalizeLoginSettings.Parameters.AddWithValue("$pid", systemDirId);
normalizeLoginSettings.ExecuteNonQuery();
var grantLoginSettingsTenant = conn.CreateCommand();
grantLoginSettingsTenant.Transaction = tx;
grantLoginSettingsTenant.CommandText = @"
INSERT INTO sys_tenant_menu (tenant_id, menu_id)
SELECT 1300000000001, $menuId
WHERE NOT EXISTS (
SELECT 1 FROM sys_tenant_menu t WHERE t.tenant_id = 1300000000001 AND t.menu_id = $menuId
);
";
grantLoginSettingsTenant.Parameters.AddWithValue("$menuId", loginSettingsMenuId);
grantLoginSettingsTenant.ExecuteNonQuery();
// 补充「登录永不过期」配置项
var ensureNeverExpireConfig = conn.CreateCommand();
ensureNeverExpireConfig.Transaction = tx;
ensureNeverExpireConfig.CommandText = @"
INSERT INTO sys_config (id, name, code, value, sys_flag, remark, order_no, group_code, create_time)
SELECT 1300000000194, '登录永不过期', 'sys_token_never_expire', 'False', 'Y', '桌面端:开启后不触发登录过期提示与自动踢回登录页', 119, 'Default', datetime('now')
WHERE NOT EXISTS (SELECT 1 FROM sys_config WHERE code = 'sys_token_never_expire');
";
ensureNeverExpireConfig.ExecuteNonQuery();
// 给 admin 角色(通常为最小id角色)补 role_menu
var adminRoleCmd = conn.CreateCommand();
adminRoleCmd.Transaction = tx;
adminRoleCmd.CommandText = "SELECT id FROM sys_role ORDER BY id LIMIT 1;";
var roleObj = adminRoleCmd.ExecuteScalar();
if (roleObj != null && roleObj != DBNull.Value)
{
var adminRoleId = Convert.ToInt64(roleObj);
var grantRole = conn.CreateCommand();
grantRole.Transaction = tx;
grantRole.CommandText = @"
INSERT INTO sys_role_menu (id, role_id, menu_id)
SELECT (SELECT IFNULL(MAX(id),0)+1 FROM sys_role_menu), $roleId, m.id
FROM sys_menu m
WHERE m.id IN ($baseId, (SELECT id FROM sys_menu WHERE title='车辆管理' ORDER BY id LIMIT 1), (SELECT id FROM sys_menu WHERE title='客户管理' ORDER BY id LIMIT 1))
AND NOT EXISTS (
SELECT 1 FROM sys_role_menu r
WHERE r.role_id = $roleId AND r.menu_id = m.id
);
";
grantRole.Parameters.AddWithValue("$roleId", adminRoleId);
grantRole.Parameters.AddWithValue("$baseId", baseMenuId);
grantRole.ExecuteNonQuery();
var grantLoginSettingsRole = conn.CreateCommand();
grantLoginSettingsRole.Transaction = tx;
grantLoginSettingsRole.CommandText = @"
INSERT INTO sys_role_menu (id, role_id, menu_id)
SELECT (SELECT IFNULL(MAX(id),0)+1 FROM sys_role_menu), $roleId, $menuId
WHERE NOT EXISTS (
SELECT 1 FROM sys_role_menu r WHERE r.role_id = $roleId AND r.menu_id = $menuId
);
";
grantLoginSettingsRole.Parameters.AddWithValue("$roleId", adminRoleId);
grantLoginSettingsRole.Parameters.AddWithValue("$menuId", loginSettingsMenuId);
grantLoginSettingsRole.ExecuteNonQuery();
}
var verify = conn.CreateCommand();
verify.Transaction = tx;
verify.CommandText = @"
SELECT id, pid, title, path, name, component, type, status, order_no
FROM sys_menu
WHERE title IN ('基础资料','车辆管理','客户管理')
ORDER BY title, id;
";
using var reader = verify.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"menu: id={reader.GetInt64(0)}, pid={reader.GetInt64(1)}, title={reader.GetString(2)}, path={reader.GetString(3)}, name={reader.GetString(4)}, component={reader.GetString(5)}, type={reader.GetInt32(6)}, status={reader.GetInt32(7)}, order={reader.GetInt32(8)}");
}
tx.Commit();
Console.WriteLine("DB menu update done.");

View File

@@ -0,0 +1,186 @@
# 桌面端与后端实时交互、断线续连功能整理yy-admin ↔ jeecg-boot
## 1. 范围与目标
本文整理当前项目中“桌面端yy-admin与后端jeecg-boot”的实时交互链路重点覆盖
- 实时消息通道STOMP/WebSocket
- 用户变更同步(后端→桌面)
- 本地变更回传(桌面→后端)
- 断线检测、自动重连、离线补偿Outbox
---
## 2. 总体架构(当前实现)
### 2.1 后端 → 桌面实时触发REST 拉取落地)
1) jeecg 用户变更时,后端广播到 STOMP 主题 `/topic/sync/jeecg-users`
2) 桌面端统一 STOMP 客户端订阅该主题,收到消息后发布本地事件 `RemoteCommandReceivedEvent`
3) `JeecgUserSyncCoordinator` 识别 `SCADA_USER_CHANGED/SCADA_USERS_CHANGED` 后,不直接写库,而是“入 Outbox”。
4) Outbox 消费器执行 `TryBackgroundSyncJeecgUsersAsync`,通过 SCADA 用户列表接口拉取并写入本地镜像表 `jeecg_sys_user`
> 这条链路是“消息触发 + REST 拉全量/增量”的组合,避免只靠实时包体做复杂幂等。
### 2.2 桌面 → 后端(本地变更回传)
1) 桌面用户 CRUD`SysUserService`)成功后调用 `IUserSyncOutbox` 入队。
2) Outbox 在线时实时发送、离线时持久化。
3) 回传通过 `/sys/sync/batch` 批量提交,后端按 `aggregateType/eventType` 路由处理,并写幂等日志表避免重复消费。
---
## 3. 关键代码位置
## 3.1 后端jeecg-boot
- STOMP 配置与心跳:
`jeecg-module-device-sync/src/main/java/org/jeecg/modules/device/sync/config/WebSocketConfig.java`
- 设备消息与应用层 PING/PONG
`jeecg-module-device-sync/src/main/java/org/jeecg/modules/device/sync/controller/DeviceWebSocketController.java`
- 批量同步入口(桌面回传):
`jeecg-module-device-sync/src/main/java/org/jeecg/modules/device/sync/controller/SyncController.java`
- 用户变更触发 STOMP 广播:
`jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/controller/SysUserController.java`
### 3.2 桌面端yy-admin-master
- STOMP 统一连接、心跳、看门狗重连、网络恢复重连:
`YY.Admin/Infrastructure/Hubs/StompWebSocketService.cs`
- STOMP 信号识别并入镜像拉取 Outbox
`YY.Admin.Services/Service/Jeecg/JeecgUserSyncCoordinator.cs`
- 镜像拉取入队:
`YY.Admin/Infrastructure/Sync/JeecgUserMirrorPullOutbox.cs`
- Outbox 核心(持久化、消费、失败重试、上线刷队):
`YY.Admin/Infrastructure/Sync/OutboxProcessor.cs`
- 网络探活与状态事件:
`YY.Admin/Infrastructure/Network/NetworkMonitor.cs`
- 本地用户变更入队接口与实现:
`YY.Admin.Core/Core/Services/IUserSyncOutbox.cs`
`YY.Admin/Infrastructure/Sync/UserSyncOutbox.cs`
- 本地用户 CRUD 完成后回传入队:
`YY.Admin.Services/Service/User/SysUserService.cs`
- 模块启动装配(网络监测 / Outbox / STOMP
`YY.Admin/Module/SyncModule.cs`
- 主窗口启动同步协调器:
`YY.Admin/ViewModels/MainWindowViewModel.cs`
---
## 4. 实时链路详细说明
### 4.1 STOMP 连接与订阅(桌面端)
`StompWebSocketService` 当前行为:
- 连接地址:由 `JeecgIntegration:BaseUrl` 推导为 `ws(s)://<host>/ws/device`(纯 WebSocket
- CONNECT 心跳声明:`heart-beat:10000,10000`
- 默认订阅:
- `/topic/sync/jeecg-users`(用户变更信号)
- `/topic/device/{deviceId}/pong`(应用层保活回应)
- 认证模式额外订阅:
- `/user/{deviceId}/queue/command`
### 4.2 后端广播jeecg 用户变更)
`SysUserController` 在新增/编辑/删除/状态变更等场景调用 `notifyScadaUserChanged(...)`,并通过 `SimpMessagingTemplate``/topic/sync/jeecg-users` 广播 JSON 负载,关键 cmd 为:
- `SCADA_USER_CHANGED`
### 4.3 桌面端信号消费策略
`JeecgUserSyncCoordinator` 不直接依赖推送包体做写库,而是:
- 解析收到的 JSON支持 message/commandJson 嵌套)
- 判断 `cmd` 是否为 `SCADA_USER_CHANGED` / `SCADA_USERS_CHANGED`
- 命中后入队 `JeecgUserMirror` 类型 Outbox
- 由 Outbox 消费阶段调用 `TryBackgroundSyncJeecgUsersAsync` 做实际拉取与落库
该策略提升了一致性与容错性(尤其在断线/消息乱序时)。
---
## 5. 断线检测与自动续连
## 5.1 连接失败重试
`ConnectUnifiedDeviceChannelAsync` 内置重试退避(秒):`0, 2, 5, 10, 30`
### 5.2 协议层心跳 + 应用层 PING
- 协议层:每 10s 发送 STOMP `\n` 心跳帧。
- 应用层:每 10s 发送 `{"cmd":"PING_DEVICE"...}``/app/device/ping`
- 后端 `handlePing` 回复到 `/topic/device/{deviceId}/pong`
### 5.3 看门狗“假在线”检测
- 客户端记录 `_lastReceivedTick`
- 若 30s 内没有任何帧(含心跳或 MESSAGE则判定连接僵死主动重连。
### 5.4 网络恢复触发重连
- `NetworkMonitor` 每 10s 探活(优先 SCADA 免登录接口,失败降级 health
- 状态变更发布 `NetworkStatusChangedEvent`
- STOMP 服务在 `isOnline=true` 且 socket 非 Open 时主动重连。
---
## 6. 离线补偿与幂等
## 6.1 Outbox 持久化
`OutboxProcessor.EnqueueAsync` 先落 SQLite Outbox`OutboxMessage`),再按在线状态决定是否立即入内存通道消费。
### 6.2 消费与失败重试
- 消费失败进入 `MarkFailedAsync`
- `RetryCount + 1`
- 指数退避 `2^n` 秒(上限按实现控制)
- 最多 5 次,超过标记 `Status=2`
- 在线恢复时 `FlushPendingAsync` 会补刷所有待发送消息。
### 6.3 双通道消费分流
`OutboxProcessor` 对消息分两类处理:
1) `JeecgUserMirror`:调用 `_mirrorPullHandler.ExecutePullAsync()`(即拉取镜像)。
2) 其他业务消息(如 `SYS_USER`):走 `_httpSyncClient.SendBatchAsync()``/sys/sync/batch`
### 6.4 后端幂等
`SyncController.batch` 通过 `messageId` 检查幂等日志(`sync_idempotent_log`)避免重复消费;未处理过才路由执行。
---
## 7. 配置项(当前关键项)
配置文件:`YY.Admin.Services/Configuration/appsettings.json``JeecgIntegration` 节点。
建议重点关注:
- `Enabled`
- `BaseUrl`
- `AnonymousMode`
- `UserListPath`(当前是 `/sys/user/scada/queryUser`
- `SyncAllUsersOnJeecgLogin`
- `BackgroundSyncIntervalMinutes`
> 实时通道默认使用 `/ws/device` 统一 STOMP 端点;`WebSocketPath` 仍保留在配置中,但当前同步主链路已切到统一设备通道实现。
---
## 8. 启动时序(简版)
1) `SyncModule.OnInitialized` 启动:
- `NetworkMonitor.StartAsync`
- `OutboxProcessor.StartConsumerAsync`
- `ISignalRService.ConnectUnifiedDeviceChannelAsync`
2) 主窗口 `MainWindowViewModel` 构造中调用 `JeecgUserSyncCoordinator.Start()`
- 订阅 `RemoteCommandReceivedEvent`
- 延迟 3 秒入队一次 `EventBoot` 拉取
3) 后续由“实时消息触发 + 定时/后台同步 + Outbox 补偿”共同维持一致性。
---
## 9. 现状结论
1) 当前实现已形成“统一 STOMP 通道 + 心跳 + 看门狗 + 网络恢复重连 + Outbox 补偿 + 后端幂等”的完整闭环。
2) 用户同步策略是“实时信号触发拉取”而非“直接信号落库”,在工业网络抖动场景更稳健。
3) 本地 CRUD 回传与后端推送下行均已纳入 Outbox/幂等体系,具备断线续连后的最终一致性基础。

View File

@@ -0,0 +1,299 @@
# 桌面端后端数据交互通用模板(以车辆管理为例)
## 1. 目的与适用范围
本文将“车辆管理”已落地的同步能力抽象为可复用模板,适用于后续任意业务模块(如供应商、订单、库存、质检等)快速实现:
- 桌面端 CRUD 与后端数据交互
- 正向同步(桌面端 -> 后端)
- 反向同步(后端 -> 桌面端)
- 断线续传(离线可操作,重连自动补偿)
- 本地缓存(保证离线可查、可改)
---
## 2. 总体架构模板
建议统一采用“**信号触发 + REST 拉取 + Outbox 补偿**”架构:
1. 后端业务变更后,广播 STOMP 信号(只发变更事件,不强依赖完整数据包)。
2. 桌面端接收信号后,不直接写本地业务表,而是触发“拉取接口”同步最新数据。
3. 桌面端本地操作时,在线优先调用后端;失败或离线则先写本地缓存 + 记录待同步操作Outbox
4. 网络恢复后自动回放 Outbox成功后清理队列并全量回拉一次做一致性对齐。
**核心原则**
- 在线追求实时,离线保证可用,重连追求最终一致。
- 任何“回传动作”必须幂等。
- 同步链路必须有完整日志(请求、结果、回放、失败原因)。
---
## 3. 后端接口模板(推荐样式)
以车辆管理为例,接口分两类:业务 CRUD 接口 + 同步辅助接口。
### 3.1 业务 CRUD给桌面端直接调用
建议统一路径风格(示例):
- `GET /{module}/{entity}/anon/list?pageNo=1&pageSize=10000&tenantId=1002`
- `GET /{module}/{entity}/anon/queryById?id=xxx&tenantId=1002`
- `POST /{module}/{entity}/anon/add?tenantId=1002`
- `POST /{module}/{entity}/anon/edit?tenantId=1002`
- `DELETE /{module}/{entity}/anon/delete?id=xxx&tenantId=1002`
- `POST /{module}/{entity}/anon/updateStatus?id=xxx&status=1&tenantId=1002`
返回建议统一:
```json
{
"success": true,
"code": 200,
"message": "操作成功",
"result": {}
}
```
分页 `result` 建议统一包含:
- `records`
- `total`
- `current`
- `size`
### 3.2 后端推送信号(反向同步触发)
后端每次成功增删改后,广播 STOMP
- Topic`/topic/sync/{entity-topic}`
- Payload 示例:
```json
{
"cmd": "MES_VEHICLE_CHANGED",
"action": "add|edit|delete|status",
"entityId": "xxx",
"timestamp": 1710000000000
}
```
说明:
- `cmd` 必须唯一且稳定,桌面端按它路由处理。
- `action` 用于日志和增量策略判断。
- `entityId` 可选但建议提供。
### 3.3 桌面端正向回传批量接口(可选增强)
若使用统一 Outbox 回传通道,建议后端提供:
- `POST /sys/sync/batch`
请求体示例:
```json
[
{
"messageId": "outbox-id-1",
"aggregateType": "VEHICLE",
"aggregateId": "vehicle-id",
"eventType": "CREATE|UPDATE|DELETE|TOGGLE_STATUS",
"payload": "{...}",
"occurredAt": "2026-01-01T10:00:00Z"
}
]
```
后端必须做 `messageId` 幂等去重。
---
## 4. 桌面端数据层模板
## 4.1 必备组件
每个模块建议固定四层:
1. `EntityService`(例:`VehicleService`
- CRUD 入口
- 本地缓存 + 离线队列
- 重连回放逻辑
2. `SyncCoordinator`(例:`VehicleSyncCoordinator`
- 监听 STOMP 信号
- 识别 `cmd` 并发布本地事件或触发同步
3. `OutboxProcessor`(全局复用)
- 持久化消息
- 在线实时发、离线补发
- 失败重试 + 指数退避
4. `NetworkMonitor`(全局复用)
- 网络状态检测
- 状态变化事件发布
## 4.2 本地缓存与待同步队列
推荐本地文件结构(示例):
- `%LocalAppData%/YY.Admin/sync-cache/{entity}-cache.json`
- `%LocalAppData%/YY.Admin/sync-cache/{entity}-pending-ops.json`
建议数据结构:
- `cache`: 最新本地快照(可直接查询)
- `pendingOps`: 离线期间操作日志,按时间顺序回放
`pendingOps` 字段建议:
- `id`
- `opType`Add/Edit/Delete/UpdateStatus
- `entityId`
- `payload`
- `createdAt`
---
## 5. 同步逻辑模板(标准流程)
### 5.1 查询流程Page/List
1. 在线:先拉远端数据 -> 刷新本地缓存。
2. 远端失败:回退本地缓存。
3.`pendingOps` 叠加到查询结果(保证 UI 看到“离线后的最新本地状态”)。
### 5.2 新增/编辑/删除/状态修改
1. 若在线,优先调用远端接口。
2. 远端成功:更新本地缓存。
3. 远端失败或离线:写入 `pendingOps`,并立即更新本地缓存(保证可用)。
**注意**:新增时若本地临时 ID`local-xxx`)不符合后端主键规则,回放前需清空 ID 让后端生成。
### 5.3 网络恢复(断线续传)
触发条件:`NetworkMonitor` 从离线 -> 在线。
流程:
1. 串行回放 `pendingOps`
2. 回放中任意失败立即停止,等待下次重试。
3. 回放完成后再做一次全量拉取,覆盖本地缓存。
4. 发布 UI 刷新事件(避免用户手动点查询)。
### 5.4 后端 -> 桌面反向同步
流程:
1. STOMP 收到 `cmd`
2. `SyncCoordinator` 解析命令。
3. 触发本地“拉取并刷新缓存”。
4. UI 订阅变更事件刷新列表。
---
## 6. 可复用方法模板
后续新模块可直接复用以下模式(名称替换即可):
- `FetchRemoteListAsync()`
- `RemoteAddAsync() / RemoteEditAsync() / RemoteDeleteAsync() / RemoteUpdateStatusAsync()`
- `ApplyFilters()`
- `ApplyPendingOpsSnapshotUnsafe()`
- `EnqueuePendingOperation()`
- `ReplayPendingOperationsAsync()`
- `ExecutePendingOperationAsync()`
- `LoadPendingOpsFromDisk() / SavePendingOpsToDiskUnsafe()`
- `LoadCacheFromDisk() / SaveCacheToDiskUnsafe()`
- `CloneEntity()`
建议抽一个通用基类(后续可做):
- `OfflineSyncEntityServiceBase<TEntity, TPendingOp>`
- 负责缓存、队列、回放、网络事件订阅
- 业务子类只实现远端接口和过滤逻辑
---
## 7. 日志模板(强制建议)
每个模块建议统一日志前缀,便于检索。
车辆管理示例前缀可复用为模块名替换:
- `[车辆同步]` 服务初始化
- `[车辆列表]` 查询链路
- `[车辆新增]` `[车辆修改]` `[车辆删除]` `[车辆状态]` 本地/远端操作
- `[车辆远端]` 实际 HTTP 请求与结果
- `[车辆入队]` 离线入队
- `[车辆回放]` 重连回放
- `[车辆重连]` 全量对齐
- `[车辆推送]` STOMP 信号处理
- `[车辆网络]` 网络状态变化
每条日志建议最少包含:
- 操作类型
- 业务主键
- 在线/离线状态
- 是否成功
- 失败原因(异常 message
- 队列长度(适用时)
---
## 8. 新模块落地清单(开发步骤)
按以下顺序复制模板最稳:
1. 后端先准备 `anon` CRUD 接口(或授权接口)+ 统一返回结构。
2. 后端在 CRUD 成功后广播 STOMP 变更信号。
3. 桌面端新增 `EntityService`(先把在线 CRUD 跑通)。
4. 增加本地缓存与 `pendingOps` 持久化。
5. 加入网络状态监听与重连回放。
6. 新增 `SyncCoordinator` 处理 STOMP -> 本地刷新。
7. 全链路日志补齐。
8. 按“联调测试矩阵”逐项验证。
---
## 9. 联调测试矩阵(建议)
每个模块至少跑完以下用例:
1. 在线新增 -> 后端可见。
2. 在线编辑 -> 后端可见。
3. 在线删除 -> 后端可见。
4. 在线状态切换 -> 后端可见。
5. 离线新增/编辑/删除 -> 本地立即可见。
6. 重连后自动回放 -> 后端最终一致。
7. 后端直接改数据 -> 桌面端自动刷新。
8. 异常网络抖动 -> 不崩溃,回放可恢复。
---
## 10. 车辆管理对应实现参考(当前项目)
桌面端:
- `YY.Admin.Services/Service/Vehicle/VehicleService.cs`
- `YY.Admin.Services/Service/Vehicle/VehicleSyncCoordinator.cs`
- `YY.Admin.Core/Core/Services/IVehicleService.cs`
后端:
- `jeecg-module-xslmes/.../MesXslVehicleController.java`(业务接口 + 变更推送)
- `jeecg-module-device-sync/.../SyncController.java`(如启用统一回传通道)
基础设施:
- `YY.Admin/Infrastructure/Sync/OutboxProcessor.cs`
- `YY.Admin/Infrastructure/Network/NetworkMonitor.cs`
- `YY.Admin/Infrastructure/Hubs/StompWebSocketService.cs`
---
## 11. 推荐统一规范(后续团队约定)
1. 所有新模块都按“在线优先 + 离线入队 + 重连回放 + 全量对齐”实现。
2. 所有模块都使用统一日志前缀和字段。
3. 后端变更推送统一 `cmd` 命名:`{SYSTEM}_{ENTITY}_CHANGED`
4. 回传消息统一带 `messageId` 幂等键。
5. 同步失败不阻塞主流程,但必须可观测(日志 + 队列长度)。
6. 任意新模块上线前必须跑完“联调测试矩阵”。
---
> 结论:
> 车辆管理已经提供了完整的可复制样板。后续新模块只需替换“实体、接口、过滤字段、命令字”,其余同步骨架可直接复用,从而快速实现稳定的桌面端/后端数据交互能力。