20261109 #20

Merged
zzh merged 9 commits from test into master 2026-11-09 10:07:44 +08:00
10 changed files with 298 additions and 74 deletions
Showing only changes of commit 6e061323e9 - Show all commits

View File

@ -23,12 +23,20 @@ public class SalesProductPublishSyncStatusOutput
/// <summary>是否存在在途价格审批(Pending)。</summary>
public bool ApprovalPending { get; set; }
/// <summary>在途审批实例 Id。</summary>
/// <summary>
/// 无在途单时,最近一次终态是否为失败可重提(驳回 / 撤回 / 执行失败)。
/// </summary>
public bool ApprovalFailed { get; set; }
/// <summary>关联审批实例 Id(在途或最近失败单)。</summary>
public int? ApprovalInstanceId { get; set; }
/// <summary>在途审批单号。</summary>
/// <summary>关联审批单号。</summary>
public string? ApprovalInstanceNo { get; set; }
/// <summary>在途审批状态名。</summary>
/// <summary>审批状态名(待审批 / 已驳回 / 已撤回 / 执行失败)。</summary>
public string? ApprovalStatusName { get; set; }
/// <summary>驳回意见或执行失败信息(失败态时)。</summary>
public string? ApprovalComment { get; set; }
}

View File

@ -12,6 +12,10 @@ using Oms.Application.Integrations.Itfx;
using Oms.Application.Integrations.PlatformShop;
using Oms.Application.Labeling;
using Oms.Application.Labeling.Hiprint;
using Oms.Application.Services.Approval;
using Oms.Application.Services.Approval.Contracts;
using Oms.Application.Services.Channels;
using Oms.Application.Services.Recharge;
using Oms.Application.Services.Storage;
using Oms.Application.Shared;
using Oms.Application.Workers;
@ -53,6 +57,12 @@ public class OmsApplicationModule : FakeModule
context.Services.AddTransient<ILabelPdfRenderer, QuestPdfLabelRenderer>();
context.Services.AddTransient<LabelPdfGenerationService>();
// 审批终审 Handler:约定注册只暴露 I{类名},须显式挂到 IApprovalOperationHandler,
// 否则 Approve 会空跑成 Executed、不落发布/入账。
context.Services.AddTransient<IApprovalOperationHandler, SalesProductPricePublishApprovalHandler>();
context.Services.AddTransient<IApprovalOperationHandler, RechargeCreditApprovalHandler>();
context.Services.AddTransient<IApprovalOperationHandler, NoopApprovalHandler>();
context.Services.AddHttpClient(FileStorageService.UrlFetchClientName, client =>
{
client.Timeout = TimeSpan.FromSeconds(60);

View File

@ -341,9 +341,13 @@ public class ApprovalEngineCore(
{
var instance = await instanceRepository.FirstOrDefaultAsync(x => x.Id == instanceId)
?? throw new BusinessException("审批实例不存在");
if (instance.Status is not (ApprovalInstanceStatus.Approved or ApprovalInstanceStatus.ExecuteFailed))
// Executed 也允许重试:兼容 Handler 未注册时空跑成 Executed、业务未落库的历史单
if (instance.Status is not (
ApprovalInstanceStatus.Approved
or ApprovalInstanceStatus.ExecuteFailed
or ApprovalInstanceStatus.Executed))
{
throw new BusinessException("仅已通过或执行失败的实例可重试执行");
throw new BusinessException("仅已通过、已执行或执行失败的实例可重试执行");
}
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
@ -368,15 +372,17 @@ public class ApprovalEngineCore(
try
{
if (_handlers.TryGetValue(instance.OperationCode, out var handler))
if (!_handlers.TryGetValue(instance.OperationCode, out var handler))
{
await handler.ExecuteAsync(BuildExecutionContext(
instance,
operatorMapId,
operatorGuid,
currentUser.UserName));
throw new BusinessException($"未注册业务执行器:{instance.OperationCode}");
}
await handler.ExecuteAsync(BuildExecutionContext(
instance,
operatorMapId,
operatorGuid,
currentUser.UserName));
instance.Status = ApprovalInstanceStatus.Executed;
instance.ExecutedTime = DateTime.Now;
instance.ExecuteMessage = "执行成功";

View File

@ -7,6 +7,7 @@ namespace Oms.Application.Services.Approval;
/// <summary>
/// 模拟操作的空执行器(终审通过后仅记 Executed)。
/// </summary>
[ExposeServices(typeof(IApprovalOperationHandler))]
public class NoopApprovalHandler : IApprovalOperationHandler, ITransientDependency
{
/// <inheritdoc />

View File

@ -6,7 +6,7 @@
1. 在操作入口组装 `ApprovalSubmitRequest`,调用 `IApprovalGate.CheckAndSubmitOrBypassAsync`。
2. `Bypass`:业务立即执行;`PendingApproval`:业务进入自有「待审批」中间态,等待终审。
3. 实现 `IApprovalOperationHandler`(`OperationCode` 匹配),终审通过后引擎调用 `ExecuteAsync`;Handler 内须再次校验业务状态后落账/发布。
3. 实现 `IApprovalOperationHandler`(`OperationCode` 匹配)并 `[ExposeServices(typeof(IApprovalOperationHandler))]`(或在 `OmsApplicationModule` 显式 `AddTransient<IApprovalOperationHandler, ...>`),终审通过后引擎调用 `ExecuteAsync`;Handler 内须再次校验业务状态后落账/发布。约定注册不会自动挂到该接口,漏注册会导致 Approve 空跑成 Executed、业务不落库。
4. 若操作需条件公式,再实现 `IApprovalConditionContextFactory`,并将目录项 `SupportsCondition` 改为 true。
已接入:

View File

@ -12,14 +12,10 @@ namespace Oms.Application.Services.Channels;
/// <summary>
/// 销售产品价格发布审批终审执行器:按冻结快照写入发布记录。
/// </summary>
[ExposeServices(typeof(IApprovalOperationHandler))]
public class SalesProductPricePublishApprovalHandler(
ISalesProductRepository salesProductRepository) : IApprovalOperationHandler, ITransientDependency
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <inheritdoc />
public string OperationCode => ApprovalCodes.SalesProductPublishPrice;
@ -31,58 +27,120 @@ public class SalesProductPricePublishApprovalHandler(
throw new BusinessException("价格发布审批载荷为空");
}
var payload = JsonSerializer.Deserialize<PricePublishPayload>(context.PayloadJson, JsonOptions)
?? throw new BusinessException("价格发布审批载荷无效");
if (payload.SalesProductId <= 0 || string.IsNullOrWhiteSpace(payload.Content))
using var document = JsonDocument.Parse(context.PayloadJson);
var root = document.RootElement;
var salesProductId = ReadInt32(root, "salesProductId", "SalesProductId");
var content = ReadJsonPayload(root, "content", "Content");
if (salesProductId <= 0 || string.IsNullOrWhiteSpace(content))
{
throw new BusinessException("价格发布审批载荷缺少产品或快照");
}
var product = await salesProductRepository.FirstOrDefaultAsync(
x => x.Id == payload.SalesProductId,
x => x.Id == salesProductId,
cancellationToken);
if (product == null)
{
throw new BusinessException("销售产品不存在");
}
var publishUser = string.IsNullOrWhiteSpace(payload.ApplicantUserName)
var applicantUserName = ReadString(root, "applicantUserName", "ApplicantUserName");
var publishUser = string.IsNullOrWhiteSpace(applicantUserName)
? (string.IsNullOrWhiteSpace(context.ApplicantUserGuid)
? context.ApplicantUserId.ToString()
: context.ApplicantUserGuid)
: payload.ApplicantUserName.Trim();
: applicantUserName.Trim();
var description = string.IsNullOrWhiteSpace(payload.Description)
var descriptionRaw = ReadString(root, "description", "Description");
var description = string.IsNullOrWhiteSpace(descriptionRaw)
? $"审批通过发布 {context.InstanceNo}"
: $"{payload.Description.Trim()}(审批单 {context.InstanceNo})";
: $"{descriptionRaw.Trim()}(审批单 {context.InstanceNo})";
var aiReport = ReadString(root, "aiAnalysisReport", "AiAnalysisReport");
await salesProductRepository.InsertPublishRecordAsync(new SalesProductPublishRecord
{
SalesProductId = payload.SalesProductId,
SalesProductId = salesProductId,
Version = DateTime.Now.ToString("yyyyMMddHHmmss"),
OperatorType = "price",
Status = EsSnapshotStatus.Active,
PublishUser = publishUser,
PublishTime = DateTime.Now,
Description = description,
AiAnalysisReport = string.IsNullOrWhiteSpace(payload.AiAnalysisReport)
? null
: payload.AiAnalysisReport.Trim(),
Content = payload.Content
AiAnalysisReport = string.IsNullOrWhiteSpace(aiReport) ? null : aiReport.Trim(),
Content = content
}, cancellationToken);
}
private sealed class PricePublishPayload
private static int ReadInt32(JsonElement root, params string[] names)
{
public int SalesProductId { get; set; }
foreach (var name in names)
{
if (!root.TryGetProperty(name, out var el))
{
continue;
}
public string? Description { get; set; }
if (el.ValueKind == JsonValueKind.Number && el.TryGetInt32(out var n))
{
return n;
}
public string? AiAnalysisReport { get; set; }
if (el.ValueKind == JsonValueKind.String && int.TryParse(el.GetString(), out n))
{
return n;
}
}
public string? Content { get; set; }
return 0;
}
public string? ApplicantUserName { get; set; }
private static string? ReadString(JsonElement root, params string[] names)
{
foreach (var name in names)
{
if (!root.TryGetProperty(name, out var el))
{
continue;
}
if (el.ValueKind == JsonValueKind.String)
{
return el.GetString();
}
if (el.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined))
{
return el.GetRawText();
}
}
return null;
}
/// <summary>
/// content 可能是 JSON 字符串,也可能是对象(历史/异常序列化);统一成快照正文。
/// </summary>
private static string? ReadJsonPayload(JsonElement root, params string[] names)
{
foreach (var name in names)
{
if (!root.TryGetProperty(name, out var el))
{
continue;
}
if (el.ValueKind == JsonValueKind.String)
{
return el.GetString();
}
if (el.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
{
return el.GetRawText();
}
}
return null;
}
}

View File

@ -36,6 +36,8 @@ public partial class SalesProductService : ApplicationService
private IApprovalGate ApprovalGate => LazyServiceProvider.GetRequiredService<IApprovalGate>();
private IApprovalInstanceRepository ApprovalInstanceRepository =>
LazyServiceProvider.GetRequiredService<IApprovalInstanceRepository>();
private IApprovalTaskRepository ApprovalTaskRepository =>
LazyServiceProvider.GetRequiredService<IApprovalTaskRepository>();
/// <summary>
/// 查询销售产品列表。
@ -436,25 +438,22 @@ public partial class SalesProductService : ApplicationService
? OmsDocHelper.HashSalesProductPriceSnapshotForSync(currentSnapshot)
: OmsDocHelper.HashSalesProductRulesSnapshotForSync(currentSnapshot));
// 价格:附带在途审批,供前端展示「待审批 + 审批号」
// 价格:在途审批,或最近一次失败终态(驳回/撤回/执行失败)供重新提交引导
var approvalPending = false;
var approvalFailed = false;
int? approvalInstanceId = null;
string? approvalInstanceNo = null;
string? approvalStatusName = null;
var approvalPending = false;
string? approvalComment = null;
if (normalized == PriceOperatorType)
{
var bizKey = $"SalesProduct.PricePublish:{salesProductId}";
var pendingApproval = await ApprovalInstanceRepository.FirstOrDefaultAsync(x =>
x.OperationCode == ApprovalCodes.SalesProductPublishPrice
&& x.BizKey == bizKey
&& x.Status == ApprovalInstanceStatus.Pending);
if (pendingApproval != null)
{
approvalPending = true;
approvalInstanceId = pendingApproval.Id;
approvalInstanceNo = pendingApproval.InstanceNo;
approvalStatusName = "待审批";
}
var approvalState = await ResolvePricePublishApprovalStateAsync(salesProductId);
approvalPending = approvalState.Pending;
approvalFailed = approvalState.Failed;
approvalInstanceId = approvalState.InstanceId;
approvalInstanceNo = approvalState.InstanceNo;
approvalStatusName = approvalState.StatusName;
approvalComment = approvalState.Comment;
}
// 生效 = 最新 Active 发布记录 Content
@ -462,43 +461,113 @@ public partial class SalesProductService : ApplicationService
salesProductId,
normalized,
DateTime.Now);
bool contentPending;
string? onlineVersion = null;
DateTime? onlinePublishTime = null;
string? onlineContentHash = null;
if (onlineRecord == null || string.IsNullOrWhiteSpace(onlineRecord.Content))
{
return new SalesProductPublishSyncStatusOutput
{
Pending = true,
OnlineVersion = null,
OnlinePublishTime = null,
PendingContentHash = currentHash,
OnlineContentHash = null,
ApprovalPending = approvalPending,
ApprovalInstanceId = approvalInstanceId,
ApprovalInstanceNo = approvalInstanceNo,
ApprovalStatusName = approvalStatusName
};
contentPending = true;
}
else
{
onlineVersion = onlineRecord.Version;
onlinePublishTime = onlineRecord.PublishTime;
onlineContentHash = ComputeContentHash(
normalized == PriceOperatorType
? OmsDocHelper.HashSalesProductPriceSnapshotForSync(
OmsDocHelper.DeserializePriceSnapshot(onlineRecord.Content))
: OmsDocHelper.HashSalesProductRulesSnapshotForSync(
OmsDocHelper.DeserializeRulesSnapshot(onlineRecord.Content)));
contentPending = !string.Equals(currentHash, onlineContentHash, StringComparison.Ordinal);
}
var onlineHash = ComputeContentHash(
normalized == PriceOperatorType
? OmsDocHelper.HashSalesProductPriceSnapshotForSync(
OmsDocHelper.DeserializePriceSnapshot(onlineRecord.Content))
: OmsDocHelper.HashSalesProductRulesSnapshotForSync(
OmsDocHelper.DeserializeRulesSnapshot(onlineRecord.Content)));
// 内容已与线上一致时,旧驳回/撤回不再当失败引导;执行失败仍展示(可能空跑未落库)
if (!contentPending
&& approvalFailed
&& !string.Equals(approvalStatusName, "执行失败", StringComparison.Ordinal))
{
approvalFailed = false;
approvalInstanceId = null;
approvalInstanceNo = null;
approvalStatusName = null;
approvalComment = null;
}
return new SalesProductPublishSyncStatusOutput
{
Pending = !string.Equals(currentHash, onlineHash, StringComparison.Ordinal),
OnlineVersion = onlineRecord.Version,
OnlinePublishTime = onlineRecord.PublishTime,
Pending = contentPending,
OnlineVersion = onlineVersion,
OnlinePublishTime = onlinePublishTime,
PendingContentHash = currentHash,
OnlineContentHash = onlineHash,
OnlineContentHash = onlineContentHash,
ApprovalPending = approvalPending,
ApprovalFailed = approvalFailed,
ApprovalInstanceId = approvalInstanceId,
ApprovalInstanceNo = approvalInstanceNo,
ApprovalStatusName = approvalStatusName
ApprovalStatusName = approvalStatusName,
ApprovalComment = approvalComment
};
}
/// <summary>
/// 解析价格发布审批态:优先 Pending;否则最近一条驳回/撤回/执行失败。
/// </summary>
private async Task<(
bool Pending,
bool Failed,
int? InstanceId,
string? InstanceNo,
string? StatusName,
string? Comment)> ResolvePricePublishApprovalStateAsync(int salesProductId)
{
var bizKey = $"SalesProduct.PricePublish:{salesProductId}";
var pendingApproval = await ApprovalInstanceRepository.FirstOrDefaultAsync(x =>
x.OperationCode == ApprovalCodes.SalesProductPublishPrice
&& x.BizKey == bizKey
&& x.Status == ApprovalInstanceStatus.Pending);
if (pendingApproval != null)
{
return (true, false, pendingApproval.Id, pendingApproval.InstanceNo, "待审批", null);
}
var failedList = await ApprovalInstanceRepository.GetListAsync(x =>
x.OperationCode == ApprovalCodes.SalesProductPublishPrice
&& x.BizKey == bizKey
&& (x.Status == ApprovalInstanceStatus.Rejected
|| x.Status == ApprovalInstanceStatus.Withdrawn
|| x.Status == ApprovalInstanceStatus.ExecuteFailed));
var failed = failedList
.OrderByDescending(x => x.CompletedTime ?? x.CreateTime)
.ThenByDescending(x => x.Id)
.FirstOrDefault();
if (failed == null)
{
return (false, false, null, null, null, null);
}
var statusName = failed.Status switch
{
ApprovalInstanceStatus.Rejected => "已驳回",
ApprovalInstanceStatus.Withdrawn => "已撤回",
ApprovalInstanceStatus.ExecuteFailed => "执行失败",
_ => failed.Status.ToString()
};
string? comment = null;
if (failed.Status == ApprovalInstanceStatus.ExecuteFailed)
{
comment = string.IsNullOrWhiteSpace(failed.ExecuteMessage) ? null : failed.ExecuteMessage.Trim();
}
else if (failed.CurrentTaskId is int taskId)
{
var task = await ApprovalTaskRepository.FirstOrDefaultAsync(x => x.Id == taskId);
comment = string.IsNullOrWhiteSpace(task?.Comment) ? null : task!.Comment!.Trim();
}
return (false, true, failed.Id, failed.InstanceNo, statusName, comment);
}
private static string ComputeContentHash(string content)
{
var hash = global::System.Security.Cryptography.SHA256.HashData(

View File

@ -13,6 +13,7 @@ namespace Oms.Application.Services.Recharge;
/// <summary>
/// 充值入账审批:通过后入账;驳回/撤回同步充值记录状态。
/// </summary>
[ExposeServices(typeof(IApprovalOperationHandler))]
public class RechargeCreditApprovalHandler(
IRechargeRecordRepository rechargeRecordRepository,
ICustomerRepository customerRepository,

View File

@ -316,7 +316,9 @@ public static class OmsDocHelper
private static object? ConvertJsonElement(JsonElement element) => element.ValueKind switch
{
// MySQL JSON 列会重排 object key;按名字排序后再入 Dictionary,避免 sync-status 误报待发布
JsonValueKind.Object => element.EnumerateObject()
.OrderBy(property => property.Name, StringComparer.Ordinal)
.ToDictionary(property => property.Name, property => ConvertJsonElement(property.Value)),
JsonValueKind.Array => element.EnumerateArray()
.Select(ConvertJsonElement)

View File

@ -201,6 +201,75 @@ public class OmsDocHelperTests
liveHash.Should().NotContain("0.0000");
}
[Fact]
public void HashSalesProductPriceSnapshotForSync_ShouldIgnoreJsonObjectKeyOrder()
{
// LIVE 明细原文 key 顺序 vs MySQL JSON 列重排后的顺序
var live = """
{
"salesProductId": 8,
"priceAreaRefs": [],
"prices": [
{
"id": 13,
"serialNumber": 1,
"status": 2,
"priceName": "运费",
"costItem": "freight",
"costUnit": "kg",
"currency": "CNY",
"factors": [],
"details": [
{
"id": 1511,
"priceId": 13,
"factorValuesJson": { "仓库": "2", "重量": "(0-0.5]" },
"calculationFormula": "total",
"calculatedValue": 10,
"customerGroupValues": { "全部客户": 10, "VIP": 12 }
}
]
}
]
}
""";
var onlineFromMysqlJson = """
{
"salesProductId": 8,
"priceAreaRefs": [],
"prices": [
{
"id": 13,
"serialNumber": 1,
"status": 2,
"priceName": "运费",
"costItem": "freight",
"costUnit": "kg",
"currency": "CNY",
"factors": [],
"details": [
{
"id": 1511,
"priceId": 13,
"factorValuesJson": { "重量": "(0-0.5]", "仓库": "2" },
"calculationFormula": "total",
"calculatedValue": 10,
"customerGroupValues": { "VIP": 12, "全部客户": 10 }
}
]
}
]
}
""";
var liveHash = OmsDocHelper.HashSalesProductPriceSnapshotForSync(
OmsDocHelper.DeserializePriceSnapshot(live));
var onlineHash = OmsDocHelper.HashSalesProductPriceSnapshotForSync(
OmsDocHelper.DeserializePriceSnapshot(onlineFromMysqlJson));
liveHash.Should().Be(onlineHash);
}
[Fact]
public void DeserializeJsonObject_ShouldCoerceIntegerValuedDecimalsToLong()
{