using System.Linq.Expressions; using Fake.Application; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Shared; using Oms.Application.Shared; using Oms.Domain.ChannelsAggregate.Entities; using Oms.Domain.ChannelsAggregate.Repositories; namespace Oms.Application.Services.Channels; /// /// 服务渠道 API 服务。 /// [ApiExplorerSettings(GroupName = "OMS-Channel")] public partial class ServiceChannelService : ApplicationService { private const string PriceOperatorType = "price"; private const string RulesOperatorType = "rules"; private IServiceChannelRepository ServiceChannelRepository => LazyServiceProvider.GetRequiredService(); private IServiceChannelGroupRepository ServiceChannelGroupRepository => LazyServiceProvider.GetRequiredService(); private IKpiAreaRepository KpiAreaRepository => LazyServiceProvider.GetRequiredService(); private KpiAreaPackService KpiAreaPackService => LazyServiceProvider.GetRequiredService(); private AllocationProviderSnapshotEnricher AllocationProviderSnapshotEnricher => LazyServiceProvider.GetRequiredService(); private OmsRbacUserDisplayNameResolver UserDisplayNameResolver => LazyServiceProvider.GetRequiredService(); /// /// 服务渠道下拉。返回全部渠道的名称,不分页。 /// [HttpGet("/channel/service-channel/options")] public async Task> GetOptionsAsync() { var channels = await ServiceChannelRepository.GetOptionRowsAsync(); var groupMap = await GetGroupMapAsync(); return channels.Select(channel => new ServiceChannelOptionOutput { Id = channel.Id, ChannelName = channel.ChannelName, GroupName = channel.GroupId.HasValue && groupMap.TryGetValue(channel.GroupId.Value, out var name) ? name : null }).ToList(); } /// /// 查询服务渠道列表。 /// /// 入参:服务渠道列表查询条件。 /// 服务渠道分页结果,包含列表数据和总记录数。 [HttpGet("/channel/service-channel/list")] public async Task> GetListAsync([FromQuery] ServiceChannelListInput input) { var predicate = BuildListPredicate(input); var pageIndex = OmsDocHelper.NormalizePage(input.Page); var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); var entities = await ServiceChannelRepository.GetPagedListAsync( predicate, pageIndex, pageSize, new Dictionary { [nameof(ServiceChannel.UpdateTime)] = false, [nameof(ServiceChannel.Id)] = false }); var total = await ServiceChannelRepository.CountAsync(predicate); var groupMap = await GetGroupMapAsync(); var auditUserNameMap = await UserDisplayNameResolver.ResolveManyAsync( entities.SelectMany(x => new[] { x.CreateUserId, x.UpdateUserId })); return new OmsPageResult { Items = entities.Select(entity => MapListOutput(entity, groupMap, auditUserNameMap)).ToList(), Total = total }; } /// /// 查询服务渠道详情。 /// /// 入参:目标主键。 /// 服务渠道详情。 [HttpGet("/channel/service-channel/detail")] public async Task GetDetailAsync([FromQuery] int id) { var entity = await GetEntityOrThrowAsync(id); var auditUserNameMap = await UserDisplayNameResolver.ResolveManyAsync( [entity.CreateUserId, entity.UpdateUserId]); return MapDetailOutput(entity, await GetGroupMapAsync(), auditUserNameMap); } /// /// 新增服务渠道。 /// /// 入参:服务渠道保存参数。 /// 无返回体,仅完成新增服务渠道。 [HttpPost("/channel/service-channel/create")] public async Task CreateAsync(ServiceChannelSaveInput input) { await ValidateChannelCodeAsync(input.ChannelCode, null); var code = input.ChannelCode.Trim(); var deleted = await ServiceChannelRepository.GetByChannelCodeIncludingDeletedAsync(code); if (deleted != null && deleted.IsDeleted) { deleted.IsDeleted = false; ApplyInput(deleted, input); await ServiceChannelRepository.UpdateAsync(deleted); return; } var entity = new ServiceChannel(); ApplyInput(entity, input); await ServiceChannelRepository.InsertAsync(entity); } /// /// 更新服务渠道。 /// /// 入参:服务渠道保存参数。 /// 无返回体,仅完成更新服务渠道。 [HttpPost("/channel/service-channel/update")] public async Task UpdateAsync(ServiceChannelSaveInput input) { var entity = await GetEntityOrThrowAsync(input.Id); await ValidateChannelCodeAsync(input.ChannelCode, entity.Id); await FreeSoftDeletedChannelCodeIfNeededAsync(input.ChannelCode.Trim(), entity.Id); ApplyInput(entity, input); await ServiceChannelRepository.UpdateAsync(entity); } /// /// 删除服务渠道。 /// /// 入参:目标主键。 /// 无返回体,仅完成删除服务渠道。 [HttpPost("/channel/service-channel/delete")] public async Task DeleteAsync(IdInput input) { var entity = await GetEntityOrThrowAsync(input.Id); await ServiceChannelRepository.DeleteAsync(entity); } /// /// 查询服务渠道分组列表。 /// /// 入参:分组名称、应用 ID、API 服务商 ID 等筛选条件。 /// 服务渠道分组列表,供下拉与左侧树筛选使用。 [HttpGet("/channel/service-channel/group/list")] public async Task> GetGroupListAsync([FromQuery] ServiceChannelGroupListInput input) { var predicate = BuildGroupListPredicate(input); var entities = await ServiceChannelGroupRepository.GetListAsync( predicate, new Dictionary { [nameof(ServiceChannelGroup.Id)] = false }); return entities.Select(MapGroupListOutput).ToList(); } /// /// 新增服务渠道分组。 /// /// 入参:服务渠道分组保存参数。 /// 无返回体,仅完成新增服务渠道分组。 [HttpPost("/channel/service-channel/group/create")] public async Task CreateGroupAsync(ServiceChannelGroupSaveInput input) { await ValidateGroupInputAsync(input, null); var name = input.Name.Trim(); var deleted = await ServiceChannelGroupRepository.GetByNameIncludingDeletedAsync(name); if (deleted != null && deleted.IsDeleted) { deleted.IsDeleted = false; deleted.Name = name; deleted.AppId = input.AppId; deleted.ApiServiceProviderId = input.ApiServiceProviderId; await ServiceChannelGroupRepository.UpdateAsync(deleted); return; } await ServiceChannelGroupRepository.InsertAsync(new ServiceChannelGroup { Name = name, AppId = input.AppId, ApiServiceProviderId = input.ApiServiceProviderId }); } /// /// 更新服务渠道分组。 /// /// 入参:服务渠道分组保存参数。 /// 无返回体,仅完成更新服务渠道分组。 [HttpPost("/channel/service-channel/group/update")] public async Task UpdateGroupAsync(ServiceChannelGroupSaveInput input) { var group = await GetGroupOrThrowAsync(input.Id); await ValidateGroupInputAsync(input, group.Id); var name = input.Name.Trim(); await FreeSoftDeletedNameIfNeededAsync(name, group.Id); group.Name = name; group.AppId = input.AppId; group.ApiServiceProviderId = input.ApiServiceProviderId; await ServiceChannelGroupRepository.UpdateAsync(group); } /// /// 删除服务渠道分组。 /// /// 入参:目标分组主键。 /// 无返回体,仅完成删除服务渠道分组。 [HttpPost("/channel/service-channel/group/delete")] public async Task DeleteGroupAsync(IdInput input) { var group = await GetGroupOrThrowAsync(input.Id); if (await ServiceChannelRepository.AnyAsync(x => x.GroupId == group.Id)) { throw new BusinessException("当前分组下仍有关联渠道,无法删除"); } await ServiceChannelGroupRepository.DeleteAsync(group); } /// /// 保存服务渠道配置。 /// /// 入参:服务渠道保存参数。 /// 无返回体,仅完成保存服务渠道配置。 [ApiExplorerSettings(IgnoreApi = true)] [HttpPost("/channel/service-channel/config/save")] public async Task SaveConfigAsync(ServiceChannelSaveInput input) { var entity = await GetEntityOrThrowAsync(input.Id); await ValidateChannelCodeAsync(input.ChannelCode, entity.Id); ApplyInput(entity, input); await ServiceChannelRepository.UpdateAsync(entity); } /// /// 查询服务渠道价格项列表。 /// /// 入参:serviceChannelId。 /// 是否返回价格明细矩阵;列表页建议 false。 /// 服务渠道价格项列表结果。 [HttpGet("/channel/service-channel/price/list")] public async Task> GetPriceListAsync( [FromQuery] int serviceChannelId, [FromQuery] bool includeDetails = true) { await GetEntityOrThrowAsync(serviceChannelId); return new OmsItemsResult { Items = await GetPriceOutputsAsync(serviceChannelId, includeDetails) }; } /// /// 获取单条服务渠道价格项(含计费因子与价格明细)。 /// [HttpGet("/channel/service-channel/price/get")] public async Task GetPriceAsync([FromQuery] int id) { return await GetPriceOutputByIdAsync(id); } /// /// 新增服务渠道价格项。 /// /// 入参:服务渠道价格项保存参数。 /// 无返回体,仅完成新增服务渠道价格项。 [HttpPost("/channel/service-channel/price/create")] public async Task CreatePriceAsync(ServiceChannelPriceSaveInput input) { await GetEntityOrThrowAsync(input.ServiceChannelId); ValidateBillingPriceItemRules([input]); await EnsureCostItemUniqueAsync(input.ServiceChannelId, input.CostItem, excludePriceId: null); await ServiceChannelRepository.InsertPriceAsync( new ServiceChannelPrice { ServiceChannelId = input.ServiceChannelId, SerialNumber = input.SerialNumber, Status = input.Status, PriceName = input.PriceName, CostItem = input.CostItem, CostUnit = input.CostUnit, Currency = input.Currency, ChargingCondition = input.ChargingCondition }, BuildPriceFactors(input.Factors), BuildPriceDetails(input.Details)); } /// /// 更新服务渠道价格项。 /// /// 入参:服务渠道价格项保存参数。 /// 无返回体,仅完成更新服务渠道价格项。 [HttpPost("/channel/service-channel/price/update")] public async Task UpdatePriceAsync(ServiceChannelPriceSaveInput input) { var price = await GetPriceOrThrowAsync(input.Id); if (price.ServiceChannelId != input.ServiceChannelId) { throw new BusinessException("买价项归属不匹配"); } ValidateBillingPriceItemRules([input]); await EnsureCostItemUniqueAsync(input.ServiceChannelId, 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 ServiceChannelRepository.UpdatePriceAsync( price, BuildPriceFactors(input.Factors), BuildPriceDetails(input.Details)); } /// /// 删除服务渠道价格项。 /// /// 入参:目标主键。 /// 无返回体,仅完成删除服务渠道价格项。 [HttpPost("/channel/service-channel/price/delete")] public async Task DeletePriceAsync(IdInput input) { await GetPriceOrThrowAsync(input.Id); await ServiceChannelRepository.DeletePriceAsync(input.Id); } /// /// 切换服务渠道价格项状态。 /// /// 入参:目标主键和状态值。 /// 无返回体,仅完成切换服务渠道价格项状态。 [HttpPost("/channel/service-channel/price/toggleStatus")] public async Task TogglePriceStatusAsync(ToggleStatusInput input) { await GetPriceOrThrowAsync(input.Id); await ServiceChannelRepository.UpdatePriceStatusAsync(input.Id, input.Status); } /// /// 批量保存服务渠道价格项。 /// /// 入参:服务渠道价格项批量保存参数。 /// 无返回体,仅完成批量保存服务渠道价格项。 [HttpPost("/channel/service-channel/price/save")] public async Task SavePriceAsync(ServiceChannelPriceSaveAllInput input) { await GetEntityOrThrowAsync(input.ServiceChannelId); 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 ServiceChannelPrice { Id = currentTempId, ServiceChannelId = input.ServiceChannelId, SerialNumber = priceInput.SerialNumber, Status = priceInput.Status, PriceName = priceInput.PriceName, CostItem = priceInput.CostItem, CostUnit = priceInput.CostUnit, Currency = priceInput.Currency, ChargingCondition = priceInput.ChargingCondition }); factors.AddRange(BuildPriceFactors(priceInput.Factors, currentTempId)); details.AddRange(BuildPriceDetails(priceInput.Details, currentTempId)); } await ServiceChannelRepository.ReplacePricesAsync(input.ServiceChannelId, prices, factors, details); if (input.Publish) { await CreatePublishRecordAsync(input.ServiceChannelId, PriceOperatorType, "保存并发布买价"); } } /// /// 查询服务渠道发布价格列表。 /// /// 入参:服务渠道发布列表查询条件。 /// 服务渠道发布价格分页结果,包含列表数据和总记录数。 [HttpGet("/channel/service-channel/publish/price/list")] public Task> GetPricePublishListAsync([FromQuery] ServiceChannelPublishListInput input) { return GetPublishListAsync(input, PriceOperatorType); } /// /// 预览即将发布的快照 JSON(不落库),与产品卖价 publish/preview 对称。 /// [HttpGet("/channel/service-channel/publish/preview")] public async Task PreviewPublishSnapshotAsync([FromQuery] int serviceChannelId, [FromQuery] string operatorType) { var normalized = NormalizeOperatorType(operatorType); object snapshot = normalized == PriceOperatorType ? await BuildPricePublishSnapshotAsync(serviceChannelId) : await BuildRulesPublishSnapshotAsync(serviceChannelId); return OmsDocHelper.ToSnapshotApiContent(snapshot)!; } /// /// 发布同步态:当前配置 vs 最新生效发布 Content。前端只展示 pending。 /// [HttpGet("/channel/service-channel/publish/sync-status")] public async Task GetPublishSyncStatusAsync( [FromQuery] int serviceChannelId, [FromQuery] string operatorType) { var normalized = NormalizeOperatorType(operatorType); await GetEntityOrThrowAsync(serviceChannelId); string currentCanon; if (normalized == PriceOperatorType) { var current = await BuildPricePublishSnapshotForSyncAsync(serviceChannelId); currentCanon = OmsDocHelper.HashChannelPriceSnapshotForSync(current); } else { var current = await BuildRulesPublishSnapshotForSyncAsync(serviceChannelId); currentCanon = HashChannelRulesSnapshotForSync(current); } var currentHash = ComputeContentHash(currentCanon); var onlineRecord = await ServiceChannelRepository.GetEffectivePublishRecordAsync( serviceChannelId, normalized, DateTime.Now); if (onlineRecord == null || string.IsNullOrWhiteSpace(onlineRecord.Content)) { return new ServiceChannelPublishSyncStatusOutput { Pending = true, OnlineVersion = null, OnlinePublishTime = null, PendingContentHash = currentHash, OnlineContentHash = null }; } var onlineCanon = normalized == PriceOperatorType ? OmsDocHelper.HashChannelPriceSnapshotForSync( OmsDocHelper.DeserializeChannelPriceSnapshot(onlineRecord.Content)) : HashChannelRulesSnapshotForSync( OmsDocHelper.DeserializeJson(onlineRecord.Content)); var onlineHash = ComputeContentHash(onlineCanon); return new ServiceChannelPublishSyncStatusOutput { Pending = !string.Equals(currentHash, onlineHash, StringComparison.Ordinal), OnlineVersion = onlineRecord.Version, OnlinePublishTime = onlineRecord.PublishTime, PendingContentHash = currentHash, OnlineContentHash = onlineHash }; } private static string HashChannelRulesSnapshotForSync(ServiceChannelRulesPublishSnapshotDto? snapshot) { if (snapshot == null) { return string.Empty; } snapshot.RemoteAreaName = null; if (snapshot.RemoteAreaRef != null) { snapshot.RemoteAreaRef.PackVersion = string.Empty; snapshot.RemoteAreaRef.AreaName = null; } return OmsDocHelper.SerializeSnapshotJson(snapshot) ?? string.Empty; } 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(); } /// /// 查询服务渠道发布规则列表。 /// /// 入参:服务渠道发布列表查询条件。 /// 服务渠道发布规则分页结果,包含列表数据和总记录数。 [HttpGet("/channel/service-channel/publish/rules/list")] public Task> GetRulesPublishListAsync([FromQuery] ServiceChannelPublishListInput input) { return GetPublishListAsync(input, RulesOperatorType); } /// /// 执行服务渠道发布。 /// /// 入参:服务渠道发布参数。 /// 无返回体,仅完成服务渠道发布处理。 [HttpPost("/channel/service-channel/publish")] public async Task PublishAsync(ServiceChannelPublishInput input) { await CreatePublishRecordAsync(input.ServiceChannelId, NormalizeOperatorType(input.OperatorType), input.Description); } /// /// 回滚服务渠道发布版本。 /// /// 入参:服务渠道发布回滚参数。 /// 无返回体,仅完成回滚服务渠道发布版本。 [HttpPost("/channel/service-channel/publish/rollback")] public Task RollbackAsync(ServiceChannelRollbackInput input) { return RollbackCoreAsync(input); } private static Expression> BuildListPredicate(ServiceChannelListInput input) { var keyword = input.Keyword?.Trim(); var hasGroupFilter = input.GroupId.HasValue; var groupIdValue = input.GroupId.GetValueOrDefault(); var hasIsActiveFilter = input.IsActive.HasValue; var isActiveValue = input.IsActive.GetValueOrDefault(); return entity => (!hasGroupFilter || entity.GroupId == groupIdValue) && (string.IsNullOrWhiteSpace(keyword) || entity.ChannelCode.Contains(keyword) || entity.ChannelName.Contains(keyword)) && (!hasIsActiveFilter || entity.IsActive == isActiveValue); } private static Expression> BuildGroupListPredicate(ServiceChannelGroupListInput input) { var keyword = input.Keyword?.Trim(); var hasAppId = input.AppId.HasValue; var appId = input.AppId.GetValueOrDefault(); var hasApiServiceProviderId = input.ApiServiceProviderId.HasValue; var apiServiceProviderId = input.ApiServiceProviderId.GetValueOrDefault(); return entity => (string.IsNullOrWhiteSpace(keyword) || entity.Name.Contains(keyword)) && (!hasAppId || entity.AppId == appId) && (!hasApiServiceProviderId || entity.ApiServiceProviderId == apiServiceProviderId); } }