新增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

@@ -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>