using System.Linq.Expressions; using Fake.Application; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Shared; using Oms.Application.Services.Approval.Contracts; using Oms.Application.Shared; using Oms.Domain.ApprovalAggregate.Consts; using Oms.Domain.ApprovalAggregate.Enums; using Oms.Domain.ApprovalAggregate.Repositories; using Oms.Domain.ChannelsAggregate.Entities; using Oms.Domain.ChannelsAggregate.Repositories; namespace Oms.Application.Services.Channels; /// /// 销售产品 API 服务。 /// [ApiExplorerSettings(GroupName = "OMS-Channel")] public partial class SalesProductService : ApplicationService { private const string PriceOperatorType = "price"; private const string RulesOperatorType = "rules"; private ISalesProductRepository SalesProductRepository => LazyServiceProvider.GetRequiredService(); private IServiceChannelRepository ServiceChannelRepository => LazyServiceProvider.GetRequiredService(); private IKpiAreaRepository KpiAreaRepository => LazyServiceProvider.GetRequiredService(); private IWeightRuleRepository WeightRuleRepository => LazyServiceProvider.GetRequiredService(); private IWeightRoundingRepository WeightRoundingRepository => LazyServiceProvider.GetRequiredService(); private KpiAreaPackService KpiAreaPackService => LazyServiceProvider.GetRequiredService(); private AllocationProviderSnapshotEnricher AllocationProviderSnapshotEnricher => LazyServiceProvider.GetRequiredService(); private OmsRbacUserDisplayNameResolver UserDisplayNameResolver => LazyServiceProvider.GetRequiredService(); private IApprovalGate ApprovalGate => LazyServiceProvider.GetRequiredService(); private IApprovalInstanceRepository ApprovalInstanceRepository => LazyServiceProvider.GetRequiredService(); private IApprovalTaskRepository ApprovalTaskRepository => LazyServiceProvider.GetRequiredService(); private IApprovalDefinitionRepository ApprovalDefinitionRepository => LazyServiceProvider.GetRequiredService(); /// /// 查询销售产品列表。 /// /// 入参:销售产品列表查询条件。 /// 销售产品分页结果,包含列表数据和总记录数。 [HttpGet("/channel/sales-product/list")] public async Task> GetListAsync([FromQuery] SalesProductListInput input) { var predicate = BuildListPredicate(input); var pageIndex = OmsDocHelper.NormalizePage(input.Page); var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); var entities = await SalesProductRepository.GetPagedListAsync( predicate, pageIndex, pageSize, new Dictionary { [nameof(SalesProduct.UpdateTime)] = false, [nameof(SalesProduct.Id)] = false }); var total = await SalesProductRepository.CountAsync(predicate); var auditUserNameMap = await UserDisplayNameResolver.ResolveManyAsync( entities.SelectMany(x => new[] { x.CreateUserId, x.UpdateUserId })); return new OmsPageResult { Items = entities.Select(entity => MapListOutput(entity, auditUserNameMap)).ToList(), Total = total }; } /// /// 查询销售产品详情。 /// /// 入参:目标主键。 /// 销售产品详情。 [HttpGet("/channel/sales-product/detail")] public async Task GetDetailAsync([FromQuery] int id) { var entity = await GetProductOrThrowAsync(id); var auditUserNameMap = await UserDisplayNameResolver.ResolveManyAsync( [entity.CreateUserId, entity.UpdateUserId]); return MapDetailOutput(entity, auditUserNameMap); } /// /// 新增销售产品。 /// /// 入参:销售产品保存参数。 /// 无返回体,仅完成新增销售产品。 [HttpPost("/channel/sales-product/create")] public async Task CreateAsync(SalesProductSaveInput input) { var code = NormalizeProductCode(input.ProductCode); await ValidateProductCodeAsync(code, null); var deleted = await SalesProductRepository.GetByProductCodeIncludingDeletedAsync(code); if (deleted != null && deleted.IsDeleted) { deleted.IsDeleted = false; ApplyProductInput(deleted, input); await SalesProductRepository.UpdateAsync(deleted); return; } var entity = new SalesProduct(); ApplyProductInput(entity, input); await SalesProductRepository.InsertAsync(entity); } /// /// 更新销售产品。 /// /// 入参:销售产品保存参数。 /// 无返回体,仅完成更新销售产品。 [HttpPost("/channel/sales-product/update")] public async Task UpdateAsync(SalesProductSaveInput input) { var entity = await GetProductOrThrowAsync(input.Id); ApplyProductInput(entity, input, updateProductCode: false); await SalesProductRepository.UpdateAsync(entity); } /// /// 单独修改销售产品代码。 /// /// 入参:产品主键与新代码。 /// 无返回体,仅完成产品代码更新。 [HttpPost("/channel/sales-product/product-code/update")] public async Task UpdateProductCodeAsync(SalesProductUpdateCodeInput input) { var entity = await GetProductOrThrowAsync(input.Id); var code = NormalizeProductCode(input.ProductCode); if (string.Equals(entity.ProductCode, code, StringComparison.Ordinal)) { return; } await ValidateProductCodeAsync(code, entity.Id); await FreeSoftDeletedProductCodeIfNeededAsync(code, entity.Id); entity.ProductCode = code; await SalesProductRepository.UpdateAsync(entity); } /// /// 删除销售产品。 /// /// 入参:目标主键。 /// 无返回体,仅完成删除销售产品。 [HttpPost("/channel/sales-product/delete")] public async Task DeleteAsync(IdInput input) { var entity = await GetProductOrThrowAsync(input.Id); await SalesProductRepository.DeleteAsync(entity); } /// /// 保存销售产品配置。 /// /// 入参:销售产品保存参数。 /// 无返回体,仅完成保存销售产品配置。 [ApiExplorerSettings(IgnoreApi = true)] [HttpPost("/channel/sales-product/config/save")] public async Task SaveConfigAsync(SalesProductSaveInput input) { var entity = await GetProductOrThrowAsync(input.Id); ApplyProductInput(entity, input, updateProductCode: false); await SalesProductRepository.UpdateAsync(entity); } /// /// 保存销售产品对客说明。 /// /// 入参:对客说明 Markdown。 /// 无返回体,仅完成保存对客说明。 [HttpPost("/channel/sales-product/customer-guide/save")] public async Task SaveCustomerGuideAsync(SalesProductCustomerGuideSaveInput input) { var entity = await GetProductOrThrowAsync(input.SalesProductId); entity.CustomerGuideMarkdown = input.CustomerGuideMarkdown; await SalesProductRepository.UpdateAsync(entity); } /// /// 查询销售产品价格项列表。 /// /// 入参:销售产品主键。 /// 是否返回价格明细矩阵;列表页建议 false。 /// 销售产品价格项列表结果。 [HttpGet("/channel/sales-product/price/list")] public async Task> GetPriceListAsync( [FromQuery] int salesProductId, [FromQuery] bool includeDetails = true) { await GetProductOrThrowAsync(salesProductId); return new OmsItemsResult { Items = await GetPriceOutputsAsync(salesProductId, includeDetails) }; } /// /// 获取单条销售产品价格项(含计费因子与价格明细)。 /// [HttpGet("/channel/sales-product/price/get")] public async Task GetPriceAsync([FromQuery] int id) { return await GetPriceOutputByIdAsync(id); } /// /// 新增销售产品价格项。 /// /// 入参:销售产品价格项保存参数。 /// 无返回体,仅完成新增销售产品价格项。 [HttpPost("/channel/sales-product/price/create")] public async Task CreatePriceAsync(SalesProductPriceSaveInput input) { await GetProductOrThrowAsync(input.SalesProductId); ValidateBillingPriceItemRules([input]); await EnsureCostItemUniqueAsync(input.SalesProductId, input.CostItem, excludePriceId: null); await SalesProductRepository.InsertPriceAsync( new SalesProductPrice { SalesProductId = input.SalesProductId, SerialNumber = input.SerialNumber, Status = input.Status, PriceName = input.PriceName, CostItem = input.CostItem, CostUnit = input.CostUnit, Currency = input.Currency, ChargingCondition = input.ChargingCondition }, BuildSalesProductPriceFactors(input.Factors), BuildSalesProductPriceDetails(input.Details)); } /// /// 更新销售产品价格项。 /// /// 入参:销售产品价格项保存参数。 /// 无返回体,仅完成更新销售产品价格项。 [HttpPost("/channel/sales-product/price/update")] public async Task UpdatePriceAsync(SalesProductPriceSaveInput input) { var price = await GetPriceOrThrowAsync(input.Id); if (price.SalesProductId != input.SalesProductId) { throw new BusinessException("价格项归属不匹配"); } ValidateBillingPriceItemRules([input]); await EnsureCostItemUniqueAsync(input.SalesProductId, input.CostItem, excludePriceId: price.Id); price.SerialNumber = input.SerialNumber; price.Status = input.Status; price.PriceName = input.PriceName; price.CostItem = input.CostItem; price.CostUnit = input.CostUnit; price.Currency = input.Currency; price.ChargingCondition = input.ChargingCondition; await SalesProductRepository.UpdatePriceAsync( price, BuildSalesProductPriceFactors(input.Factors), BuildSalesProductPriceDetails(input.Details)); } /// /// 删除销售产品价格项。 /// /// 入参:目标主键。 /// 无返回体,仅完成删除销售产品价格项。 [HttpPost("/channel/sales-product/price/delete")] public async Task DeletePriceAsync(IdInput input) { await GetPriceOrThrowAsync(input.Id); await SalesProductRepository.DeletePriceAsync(input.Id); } /// /// 切换销售产品价格项状态。 /// /// 入参:目标主键和状态值。 /// 无返回体,仅完成切换销售产品价格项状态。 [HttpPost("/channel/sales-product/price/toggleStatus")] public async Task TogglePriceStatusAsync(ToggleStatusInput input) { await GetPriceOrThrowAsync(input.Id); await SalesProductRepository.UpdatePriceStatusAsync(input.Id, input.Status); } /// /// 批量保存销售产品价格项。 /// /// 入参:销售产品价格项批量保存参数。 /// 无返回体,仅完成批量保存销售产品价格项。 [HttpPost("/channel/sales-product/price/save")] public async Task SavePriceAsync(SalesProductPriceSaveAllInput input) { await GetProductOrThrowAsync(input.SalesProductId); ValidateBillingPriceItemRules(input.Prices); var prices = new List(); var factors = new List(); var details = new List(); var tempId = -1; // 为每棵价格子树分配临时负数 Id,仓储层再据此回填真实主键。 foreach (var priceInput in input.Prices.OrderBy(x => x.SerialNumber)) { var currentTempId = tempId--; prices.Add(new SalesProductPrice { Id = currentTempId, SalesProductId = input.SalesProductId, SerialNumber = priceInput.SerialNumber, Status = priceInput.Status, PriceName = priceInput.PriceName, CostItem = priceInput.CostItem, CostUnit = priceInput.CostUnit, Currency = priceInput.Currency, ChargingCondition = priceInput.ChargingCondition }); factors.AddRange(BuildSalesProductPriceFactors(priceInput.Factors, currentTempId)); details.AddRange(BuildSalesProductPriceDetails(priceInput.Details, currentTempId)); } await SalesProductRepository.ReplacePricesAsync(input.SalesProductId, prices, factors, details); if (input.Publish) { if (string.IsNullOrWhiteSpace(input.AiAnalysisReport)) { throw new Fake.Application.BusinessException("价格发布前须完成 AI 风险分析并保存报告"); } await PublishPriceWithApprovalAsync( input.SalesProductId, "保存并发布价格", input.AiAnalysisReport); } } /// /// 查询销售产品分配配置。 /// /// 入参:销售产品主键。 /// 销售产品分配配置。 [HttpGet("/channel/sales-product/allocation/get")] public Task GetAllocationAsync([FromQuery] int salesProductId) { return GetAllocationCoreAsync(salesProductId); } /// /// 保存销售产品分配配置。 /// /// 入参:销售产品分配配置保存参数。 /// 无返回体,仅完成保存销售产品分配配置。 [HttpPost("/channel/sales-product/allocation/save")] public async Task SaveAllocationAsync(SalesProductAllocationSaveInput input) { var product = await GetProductOrThrowAsync(input.SalesProductId); product.Scheme = input.Scheme; await SalesProductRepository.UpdateAsync(product); var providers = input.Providers.Select(provider => new SalesProductAllocationProvider { SalesProductId = input.SalesProductId, SerialNumber = provider.SerialNumber, ProviderName = provider.ProviderName, ServiceChannelId = provider.ServiceChannelId, Weight = provider.Weight, CustomerIds = OmsDocHelper.SerializeJson(provider.CustomerIds), MatchCondition = provider.MatchCondition }).ToList(); await SalesProductRepository.ReplaceAllocationProvidersAsync(input.SalesProductId, providers); if (input.Publish) { await CreatePublishRecordAsync(input.SalesProductId, RulesOperatorType, "保存并发布规则"); } } /// /// 查询销售产品发布价格列表。 /// /// 入参:销售产品发布列表查询条件。 /// 销售产品发布价格分页结果,包含列表数据和总记录数。 [HttpGet("/channel/sales-product/publish/price/list")] public Task> GetPricePublishListAsync([FromQuery] SalesProductPublishListInput input) { return GetPublishListAsync(input, PriceOperatorType); } /// /// 查询销售产品发布规则列表。 /// /// 入参:销售产品发布列表查询条件。 /// 销售产品发布规则分页结果,包含列表数据和总记录数。 [HttpGet("/channel/sales-product/publish/rules/list")] public Task> GetRulesPublishListAsync([FromQuery] SalesProductPublishListInput input) { return GetPublishListAsync(input, RulesOperatorType); } /// /// 查询单条发布记录,含快照正文。 /// [HttpGet("/channel/sales-product/publish/get")] public Task GetPublishRecordAsync([FromQuery] int id) { return GetPublishRecordCoreAsync(id); } /// /// 预览即将发布的快照 JSON(不落库),用于核对黑名单/计重等是否已固化进 Content。 /// [HttpGet("/channel/sales-product/publish/preview")] public async Task PreviewPublishSnapshotAsync([FromQuery] int salesProductId, [FromQuery] string operatorType) { var normalized = NormalizeOperatorType(operatorType); object snapshot = normalized == PriceOperatorType ? await BuildPricePublishSnapshotAsync(salesProductId) : await BuildRulesPublishSnapshotAsync(salesProductId); return OmsDocHelper.ToSnapshotApiContent(snapshot)!; } /// /// 发布同步态:当前配置 vs 最新生效发布 Content。前端只展示 pending,不算差异。 /// [HttpGet("/channel/sales-product/publish/sync-status")] public async Task GetPublishSyncStatusAsync( [FromQuery] int salesProductId, [FromQuery] string operatorType) { var normalized = NormalizeOperatorType(operatorType); await GetProductOrThrowAsync(salesProductId); // 当前 = 与发布同源的快照组装(分区只解析哈希,不 Ensure 写库) object currentSnapshot = normalized == PriceOperatorType ? await BuildPricePublishSnapshotForSyncAsync(salesProductId) : await BuildRulesPublishSnapshotForSyncAsync(salesProductId); var currentHash = ComputeContentHash( normalized == PriceOperatorType ? OmsDocHelper.HashSalesProductPriceSnapshotForSync(currentSnapshot) : OmsDocHelper.HashSalesProductRulesSnapshotForSync(currentSnapshot)); // 价格:是否启用审批定义 + 在途/失败终态 var approvalRequired = false; var approvalPending = false; var approvalFailed = false; int? approvalInstanceId = null; string? approvalInstanceNo = null; string? approvalStatusName = null; string? approvalComment = null; if (normalized == PriceOperatorType) { var enabledDef = await ApprovalDefinitionRepository.FirstOrDefaultAsync(x => x.OperationCode == ApprovalCodes.SalesProductPublishPrice && x.IsEnabled); approvalRequired = enabledDef != null; 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 var onlineRecord = await SalesProductRepository.GetEffectivePublishRecordAsync( salesProductId, normalized, DateTime.Now); bool contentPending; string? onlineVersion = null; DateTime? onlinePublishTime = null; string? onlineContentHash = null; if (onlineRecord == null || string.IsNullOrWhiteSpace(onlineRecord.Content)) { 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); } // 内容已与线上一致时,旧驳回/撤回不再当失败引导;执行失败仍展示(可能空跑未落库) if (!contentPending && approvalFailed && !string.Equals(approvalStatusName, "执行失败", StringComparison.Ordinal)) { approvalFailed = false; approvalInstanceId = null; approvalInstanceNo = null; approvalStatusName = null; approvalComment = null; } return new SalesProductPublishSyncStatusOutput { Pending = contentPending, OnlineVersion = onlineVersion, OnlinePublishTime = onlinePublishTime, PendingContentHash = currentHash, OnlineContentHash = onlineContentHash, ApprovalRequired = approvalRequired, ApprovalPending = approvalPending, ApprovalFailed = approvalFailed, ApprovalInstanceId = approvalInstanceId, ApprovalInstanceNo = approvalInstanceNo, ApprovalStatusName = approvalStatusName, ApprovalComment = approvalComment }; } /// /// 解析价格发布审批态:优先 Pending;否则最近一条驳回/撤回/执行失败。 /// 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( global::System.Text.Encoding.UTF8.GetBytes(content)); return Convert.ToHexString(hash).ToLowerInvariant(); } /// /// 执行销售产品发布。价格发布会走审批门面:未配置/未命中则直接发布,否则创建审批单。 /// /// 入参:销售产品发布参数。 /// 发布结果(直接发布或待审批)。 [HttpPost("/channel/sales-product/publish")] public async Task PublishAsync(SalesProductPublishInput input) { var operatorType = NormalizeOperatorType(input.OperatorType); if (operatorType == PriceOperatorType) { if (string.IsNullOrWhiteSpace(input.AiAnalysisReport)) { throw new Fake.Application.BusinessException("价格发布前须完成 AI 风险分析并保存报告"); } return await PublishPriceWithApprovalAsync( input.SalesProductId, input.Description, input.AiAnalysisReport); } await CreatePublishRecordAsync( input.SalesProductId, operatorType, input.Description, input.AiAnalysisReport); return new SalesProductPublishResultOutput { Decision = "Bypass", Message = "规则发布已完成" }; } /// /// 回滚销售产品发布版本。 /// /// 入参:销售产品发布回滚参数。 /// 无返回体,仅完成回滚销售产品发布版本。 [HttpPost("/channel/sales-product/publish/rollback")] public Task RollbackAsync(SalesProductRollbackInput input) { return RollbackCoreAsync(input); } private static Expression> BuildListPredicate(SalesProductListInput input) { var productGroup = input.ProductGroup?.Trim(); var keyword = input.Keyword?.Trim(); var hasIsActiveFilter = input.IsActive.HasValue; var isActiveValue = input.IsActive.GetValueOrDefault(); return entity => (string.IsNullOrWhiteSpace(productGroup) || entity.ProductGroup == productGroup) && (string.IsNullOrWhiteSpace(keyword) || entity.ProductCode.Contains(keyword) || entity.ProductName.Contains(keyword)) && (!hasIsActiveFilter || entity.IsActive == isActiveValue); } }