admin/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs
zzh 7d14c0e5d9
All checks were successful
Build and Deploy / deploy (push) Successful in 59s
fix: sync-status 只比当前配置与生效 Content,前端不参与计算
当前侧与发布同源组装但不 Ensure;两侧同一套规范化并忽略 PackVersion/AreaName。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 19:38:58 +08:00

757 lines
29 KiB
C#

using Oms.Application.Dtos.Channels;
using Oms.Application.Dtos.Orders;
using Oms.Application.Dtos.Shared;
using Oms.Application.Shared;
using Oms.Domain.ChannelsAggregate.Entities;
using Oms.Domain.Shared;
using Oms.Domain.Shared.Enums;
namespace Oms.Application.Services.Channels;
public partial class ServiceChannelService
{
/// <summary>
/// 读取渠道组映射,给列表和详情补充 groupName。
/// </summary>
private async Task<Dictionary<int, string>> GetGroupMapAsync()
{
return (await ServiceChannelGroupRepository.GetListAsync()).ToDictionary(x => x.Id, x => x.Name);
}
/// <summary>
/// 获取服务渠道分组,不存在时直接抛异常。
/// </summary>
private async Task<ServiceChannelGroup> GetGroupOrThrowAsync(int? id)
{
if (!id.HasValue || id.Value <= 0)
{
throw new Fake.Application.BusinessException("服务渠道分组不存在");
}
var group = await ServiceChannelGroupRepository.FirstOrDefaultAsync(x => x.Id == id.Value);
if (group == null)
{
throw new Fake.Application.BusinessException("服务渠道分组不存在");
}
return group;
}
/// <summary>
/// 校验服务渠道分组基础信息和名称唯一性。
/// </summary>
private async Task ValidateGroupInputAsync(ServiceChannelGroupSaveInput input, int? id)
{
if (string.IsNullOrWhiteSpace(input.Name))
{
throw new Fake.Application.BusinessException("分组名称不能为空");
}
if (input.AppId <= 0)
{
throw new Fake.Application.BusinessException("应用ID不能为空");
}
if (input.ApiServiceProviderId <= 0)
{
throw new Fake.Application.BusinessException("API服务商ID不能为空");
}
var existed = await ServiceChannelGroupRepository.GetByNameAsync(input.Name.Trim());
if (existed != null && existed.Id != id)
{
throw new Fake.Application.BusinessException("分组名称已存在");
}
}
/// <summary>
/// 更新时若目标名称被软删记录占用,则改名释放唯一键,避免 uk_scg_name 冲突。
/// </summary>
private async Task FreeSoftDeletedNameIfNeededAsync(string name, int currentId)
{
var conflict = await ServiceChannelGroupRepository.GetByNameIncludingDeletedAsync(name);
if (conflict == null || !conflict.IsDeleted || conflict.Id == currentId)
{
return;
}
conflict.Name = $"{name}__deleted_{conflict.Id}";
await ServiceChannelGroupRepository.UpdateAsync(conflict);
}
/// <summary>
/// 校验渠道编码唯一性。
/// </summary>
private async Task ValidateChannelCodeAsync(string channelCode, int? id)
{
var existed = await ServiceChannelRepository.GetByChannelCodeAsync(channelCode);
if (existed != null && existed.Id != id)
{
throw new Fake.Application.BusinessException("渠道编码已存在");
}
}
/// <summary>
/// 更新时若目标编码被软删记录占用,改名释放 uk_sc_code。
/// </summary>
private async Task FreeSoftDeletedChannelCodeIfNeededAsync(string channelCode, int currentId)
{
var conflict = await ServiceChannelRepository.GetByChannelCodeIncludingDeletedAsync(channelCode);
if (conflict == null || !conflict.IsDeleted || conflict.Id == currentId)
{
return;
}
conflict.ChannelCode = $"{channelCode}__deleted_{conflict.Id}";
await ServiceChannelRepository.UpdateAsync(conflict);
}
/// <summary>
/// 获取服务渠道,不存在时直接抛异常。
/// </summary>
private async Task<ServiceChannel> GetEntityOrThrowAsync(int? id)
{
if (!id.HasValue || id.Value <= 0)
{
throw new Fake.Application.BusinessException("服务渠道不存在");
}
var entity = await ServiceChannelRepository.FirstOrDefaultAsync(x => x.Id == id.Value);
if (entity == null)
{
throw new Fake.Application.BusinessException("服务渠道不存在");
}
return entity;
}
/// <summary>
/// 获取买价项,不存在时直接抛异常。
/// </summary>
private async Task<ServiceChannelPrice> GetPriceOrThrowAsync(int? id)
{
if (!id.HasValue || id.Value <= 0)
{
throw new Fake.Application.BusinessException("买价项不存在");
}
var entity = await ServiceChannelRepository.GetPriceByIdAsync(id.Value);
if (entity == null)
{
throw new Fake.Application.BusinessException("买价项不存在");
}
return entity;
}
/// <summary>
/// 一次性装配买价项、因子和明细,避免接口层 N+1 查询。
/// includeDetails=false 时跳过明细(列表页首屏),显著减小载荷。
/// </summary>
private async Task<List<ServiceChannelPriceListOutput>> GetPriceOutputsAsync(
int serviceChannelId,
bool includeDetails = true)
{
var prices = await ServiceChannelRepository.GetPricesAsync(serviceChannelId);
var priceIds = prices.Select(x => x.Id).ToArray();
var factorMap = (await ServiceChannelRepository.GetPriceFactorsAsync(priceIds))
.GroupBy(x => x.PriceId)
.ToDictionary(x => x.Key, x => x.OrderBy(item => item.SerialNumber).ToList());
var detailMap = includeDetails
? (await ServiceChannelRepository.GetPriceDetailsAsync(priceIds))
.GroupBy(x => x.PriceId)
.ToDictionary(x => x.Key, x => x.OrderBy(item => item.Id).ToList())
: new Dictionary<int, List<ServiceChannelPriceDetail>>();
return prices.Select(price => new ServiceChannelPriceListOutput
{
Id = price.Id,
ServiceChannelId = price.ServiceChannelId,
SerialNumber = price.SerialNumber,
Status = (byte)price.Status,
PriceName = price.PriceName,
CostItem = price.CostItem,
CostUnit = price.CostUnit,
Currency = price.Currency,
ChargingCondition = price.ChargingCondition,
Factors = factorMap.TryGetValue(price.Id, out var factors) ? factors.Select(MapPriceFactorOutput).ToList() : [],
Details = includeDetails && detailMap.TryGetValue(price.Id, out var details)
? details.Select(MapPriceDetailOutput).ToList()
: [],
CreateTime = price.CreateTime,
UpdateTime = OmsDocHelper.NullIfDefault(price.UpdateTime)
}).ToList();
}
/// <summary>
/// 单条买价项(含因子+明细),供编辑弹窗按需加载。
/// </summary>
private async Task<ServiceChannelPriceListOutput> GetPriceOutputByIdAsync(int priceId)
{
var price = await GetPriceOrThrowAsync(priceId);
var priceIds = new[] { price.Id };
var factors = await ServiceChannelRepository.GetPriceFactorsAsync(priceIds);
var details = await ServiceChannelRepository.GetPriceDetailsAsync(priceIds);
return new ServiceChannelPriceListOutput
{
Id = price.Id,
ServiceChannelId = price.ServiceChannelId,
SerialNumber = price.SerialNumber,
Status = (byte)price.Status,
PriceName = price.PriceName,
CostItem = price.CostItem,
CostUnit = price.CostUnit,
Currency = price.Currency,
ChargingCondition = price.ChargingCondition,
Factors = factors.OrderBy(item => item.SerialNumber).Select(MapPriceFactorOutput).ToList(),
Details = details.OrderBy(item => item.Id).Select(MapPriceDetailOutput).ToList(),
CreateTime = price.CreateTime,
UpdateTime = OmsDocHelper.NullIfDefault(price.UpdateTime)
};
}
/// <summary>
/// 获取指定类型的发布记录。
/// </summary>
private async Task<OmsPageResult<ServiceChannelPublishRecordOutput>> GetPublishListAsync(ServiceChannelPublishListInput input, string operatorType)
{
await GetEntityOrThrowAsync(input.ServiceChannelId);
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
var entities = await ServiceChannelRepository.GetPublishRecordsAsync(input.ServiceChannelId, operatorType, pageIndex, pageSize);
var total = await ServiceChannelRepository.CountPublishRecordsAsync(input.ServiceChannelId, operatorType);
return new OmsPageResult<ServiceChannelPublishRecordOutput>
{
Items = entities.Select(entity => new ServiceChannelPublishRecordOutput
{
Id = entity.Id,
ServiceChannelId = entity.ServiceChannelId,
Version = entity.Version,
OperatorType = entity.OperatorType,
Status = EnumDisplayNames.Of(entity.Status),
PublishUser = entity.PublishUser,
PublishTime = entity.PublishTime,
Description = entity.Description,
Content = operatorType == PriceOperatorType
? OmsDocHelper.ParseChannelPricePublishContentForApi(entity.Content)
: OmsDocHelper.ToSnapshotApiContent(OmsDocHelper.DeserializeJson<ServiceChannelRulesPublishSnapshotDto>(entity.Content)),
CreateTime = entity.CreateTime
}).ToList(),
Total = total
};
}
/// <summary>
/// 组装买价发布快照(不落库):钉渠道自有价区包。
/// </summary>
private async Task<ServiceChannelPricePublishSnapshotDto> BuildPricePublishSnapshotAsync(int serviceChannelId)
{
var snapshot = new ServiceChannelPricePublishSnapshotDto
{
ServiceChannelId = serviceChannelId,
Prices = (await GetPriceOutputsAsync(serviceChannelId))
.Select(PublishSnapshotSlimmer.SlimChannelPrice)
.ToList()
};
await PriceAreaSnapshotHelper.ApplyChannelPriceAreaToSnapshotAsync(
snapshot,
KpiAreaRepository,
KpiAreaPackService,
ResolvePublishUser());
return snapshot;
}
/// <summary>
/// 买价同步态:不 Ensure 新分区包。
/// </summary>
private async Task<ServiceChannelPricePublishSnapshotDto> BuildPricePublishSnapshotForSyncAsync(int serviceChannelId)
{
var snapshot = new ServiceChannelPricePublishSnapshotDto
{
ServiceChannelId = serviceChannelId,
Prices = (await GetPriceOutputsAsync(serviceChannelId))
.Select(PublishSnapshotSlimmer.SlimChannelPrice)
.ToList()
};
await PriceAreaSnapshotHelper.ApplyChannelPriceAreaRefsForSyncAsync(
snapshot,
KpiAreaRepository,
KpiAreaPackService);
return snapshot;
}
/// <summary>
/// 组装渠道规则发布快照(不落库):钉偏远分区包。
/// </summary>
private async Task<ServiceChannelRulesPublishSnapshotDto> BuildRulesPublishSnapshotAsync(int serviceChannelId)
{
var entity = await GetEntityOrThrowAsync(serviceChannelId);
ServiceChannelDownstreamSnapshotDto? downstream = null;
if (entity.GroupId is > 0)
{
var group = await ServiceChannelGroupRepository.FirstOrDefaultAsync(x => x.Id == entity.GroupId.Value);
if (group != null)
{
downstream = await AllocationProviderSnapshotEnricher.BuildDownstreamFromGroupAsync(group);
}
}
var snapshot = new ServiceChannelRulesPublishSnapshotDto
{
Channel = MapChannelToSaveInput(entity),
Downstream = downstream,
RemoteAreaInfos = []
};
if (entity.RemoteAreaId is > 0)
{
var packRef = await KpiAreaPackService.EnsurePackAsync(
entity.RemoteAreaId.Value,
KpiAreaPackService.AreaTypeRemote,
ResolvePublishUser(),
description: "service-channel-rules-publish");
snapshot.RemoteAreaId = entity.RemoteAreaId;
snapshot.RemoteAreaName = packRef.AreaName;
snapshot.RemoteAreaRef = packRef;
}
else
{
snapshot.RemoteAreaId = null;
snapshot.RemoteAreaName = null;
snapshot.RemoteAreaRef = null;
}
return snapshot;
}
/// <summary>
/// 渠道规则同步态:偏远分区不 Ensure。
/// </summary>
private async Task<ServiceChannelRulesPublishSnapshotDto> BuildRulesPublishSnapshotForSyncAsync(int serviceChannelId)
{
var entity = await GetEntityOrThrowAsync(serviceChannelId);
ServiceChannelDownstreamSnapshotDto? downstream = null;
if (entity.GroupId is > 0)
{
var group = await ServiceChannelGroupRepository.FirstOrDefaultAsync(x => x.Id == entity.GroupId.Value);
if (group != null)
{
downstream = await AllocationProviderSnapshotEnricher.BuildDownstreamFromGroupAsync(group);
}
}
var snapshot = new ServiceChannelRulesPublishSnapshotDto
{
Channel = MapChannelToSaveInput(entity),
Downstream = downstream,
RemoteAreaInfos = []
};
if (entity.RemoteAreaId is > 0)
{
var packRef = await KpiAreaPackService.ResolvePackRefForSyncAsync(entity.RemoteAreaId.Value);
snapshot.RemoteAreaId = entity.RemoteAreaId;
snapshot.RemoteAreaName = packRef.AreaName;
snapshot.RemoteAreaRef = packRef;
}
else
{
snapshot.RemoteAreaId = null;
snapshot.RemoteAreaName = null;
snapshot.RemoteAreaRef = null;
}
return snapshot;
}
private string ResolvePublishUser() =>
string.IsNullOrWhiteSpace(CurrentUser.UserName)
? CurrentUser.GetId<int>().ToString()
: CurrentUser.UserName!;
private static ServiceChannelSaveInput MapChannelToSaveInput(ServiceChannel entity) =>
new()
{
Id = entity.Id,
GroupId = entity.GroupId,
ChannelCode = entity.ChannelCode,
ChannelName = entity.ChannelName,
MinTime = entity.MinTime,
MaxTime = entity.MaxTime,
ForecastType = entity.ForecastType,
ForecastCode = entity.ForecastCode,
Description = entity.Description,
RemoteAreaId = entity.RemoteAreaId,
PreScript = entity.PreScript,
IsActive = entity.IsActive
};
/// <summary>
/// 为当前配置生成发布快照。
/// </summary>
private async Task CreatePublishRecordAsync(int serviceChannelId, string operatorType, string? description)
{
object snapshot = operatorType == PriceOperatorType
? await BuildPricePublishSnapshotAsync(serviceChannelId)
: await BuildRulesPublishSnapshotAsync(serviceChannelId);
var content = operatorType == PriceOperatorType
? OmsDocHelper.CanonicalizeChannelPriceSnapshotJson(snapshot)
: OmsDocHelper.SerializeSnapshotJson(snapshot);
// Content 存 canonical 形态,与 sync-status 对比口径一致。
await ServiceChannelRepository.InsertPublishRecordAsync(new ServiceChannelPublishRecord
{
ServiceChannelId = serviceChannelId,
Version = DateTime.Now.ToString("yyyyMMddHHmmss"),
OperatorType = operatorType,
Status = EsSnapshotStatus.Active,
PublishUser = string.IsNullOrWhiteSpace(CurrentUser.UserName) ? CurrentUser.GetId<int>().ToString() : CurrentUser.UserName!,
PublishTime = DateTime.Now,
Description = description,
Content = content
});
}
/// <summary>
/// 按发布记录回滚价格或规则配置。
/// </summary>
private async Task RollbackCoreAsync(ServiceChannelRollbackInput input)
{
var operatorType = NormalizeOperatorType(input.OperatorType);
await GetEntityOrThrowAsync(input.ServiceChannelId);
var record = await ServiceChannelRepository.GetPublishRecordByIdAsync(input.RecordId);
if (record == null || record.ServiceChannelId != input.ServiceChannelId || !string.Equals(record.OperatorType, operatorType, StringComparison.OrdinalIgnoreCase))
{
throw new Fake.Application.BusinessException("发布记录不存在");
}
if (operatorType == PriceOperatorType)
{
var snapshot = OmsDocHelper.DeserializeChannelPriceSnapshot(record.Content);
if (snapshot == null)
{
throw new Fake.Application.BusinessException("发布快照无效");
}
// 价格回滚直接恢复完整买价树。
await SavePriceAsync(new ServiceChannelPriceSaveAllInput
{
ServiceChannelId = input.ServiceChannelId,
Prices = snapshot.Prices.Select(MapPriceSaveInput).ToList()
});
return;
}
var rulesSnapshot = OmsDocHelper.DeserializeJson<ServiceChannelRulesPublishSnapshotDto>(record.Content);
if (rulesSnapshot?.Channel == null)
{
throw new Fake.Application.BusinessException("发布快照无效");
}
var entity = await GetEntityOrThrowAsync(input.ServiceChannelId);
ApplyInput(entity, rulesSnapshot.Channel);
await ServiceChannelRepository.UpdateAsync(entity);
}
/// <summary>
/// 将保存入参映射到服务渠道实体。
/// </summary>
private static void ApplyInput(ServiceChannel entity, ServiceChannelSaveInput input)
{
entity.GroupId = input.GroupId;
entity.ChannelCode = input.ChannelCode;
entity.ChannelName = input.ChannelName;
entity.MinTime = input.MinTime;
entity.MaxTime = input.MaxTime;
entity.ForecastType = input.ForecastType;
entity.ForecastCode = input.ForecastCode;
entity.Description = input.Description;
entity.RemoteAreaId = input.RemoteAreaId;
entity.PreScript = input.PreScript;
entity.IsActive = input.IsActive;
}
/// <summary>
/// 买价偏远费等附加费用项的计费条件校验;同一提交批次内费用项不可重复。
/// </summary>
private static void ValidateBillingPriceItemRules(IReadOnlyList<ServiceChannelPriceSaveInput> prices)
{
EnsureUniqueCostItemsInBatch(prices.Select(x => x.CostItem));
foreach (var price in prices)
{
var costItem = price.CostItem?.Trim() ?? string.Empty;
var condition = price.ChargingCondition?.Trim() ?? string.Empty;
if (costItem.Equals("remoteFee", StringComparison.OrdinalIgnoreCase)
|| costItem.Equals("remote_fee", StringComparison.OrdinalIgnoreCase)
|| costItem.Contains("偏远", StringComparison.OrdinalIgnoreCase))
{
if (!condition.Contains("是否偏远", StringComparison.Ordinal))
{
throw new Fake.Application.BusinessException("偏远费用项的计费条件必须包含「是否偏远」");
}
}
}
}
/// <summary>
/// 同一服务渠道下每种费用项只能有一条买价配置。
/// </summary>
private async Task EnsureCostItemUniqueAsync(int serviceChannelId, string? costItem, int? excludePriceId)
{
var trimmed = costItem?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(trimmed))
{
throw new Fake.Application.BusinessException("费用项不能为空");
}
var existing = await ServiceChannelRepository.GetPricesAsync(serviceChannelId);
var duplicated = existing.Any(p =>
(!excludePriceId.HasValue || p.Id != excludePriceId.Value)
&& string.Equals(p.CostItem?.Trim(), trimmed, StringComparison.OrdinalIgnoreCase));
if (duplicated)
{
throw new Fake.Application.BusinessException(
$"该渠道已存在费用项「{trimmed}」,同一渠道下每种费用项只能有一条");
}
}
private static void EnsureUniqueCostItemsInBatch(IEnumerable<string?> costItems)
{
var duplicates = costItems
.Select(x => x?.Trim() ?? string.Empty)
.Where(x => !string.IsNullOrWhiteSpace(x))
.GroupBy(x => x, StringComparer.OrdinalIgnoreCase)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
if (duplicates.Count > 0)
{
throw new Fake.Application.BusinessException(
$"同一渠道下费用项不能重复:{string.Join("、", duplicates)}");
}
}
private static ServiceChannelGroupListOutput MapGroupListOutput(ServiceChannelGroup entity)
{
return new ServiceChannelGroupListOutput
{
Id = entity.Id,
Name = entity.Name,
AppId = entity.AppId,
ApiServiceProviderId = entity.ApiServiceProviderId,
CreateTime = entity.CreateTime,
UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime)
};
}
private static ServiceChannelListOutput MapListOutput(
ServiceChannel entity,
IReadOnlyDictionary<int, string> groupMap,
IReadOnlyDictionary<int, string> auditUserNameMap)
{
return new ServiceChannelListOutput
{
Id = entity.Id,
GroupId = entity.GroupId,
GroupName = entity.GroupId.HasValue && groupMap.TryGetValue(entity.GroupId.Value, out var groupName) ? groupName : null,
ChannelCode = entity.ChannelCode,
ChannelName = entity.ChannelName,
MinTime = entity.MinTime,
MaxTime = entity.MaxTime,
ForecastType = entity.ForecastType,
ForecastCode = entity.ForecastCode,
Description = entity.Description,
RemoteAreaId = entity.RemoteAreaId,
IsActive = (byte)entity.IsActive,
CreateTime = entity.CreateTime,
CreateBy = OmsRbacUserDisplayNameResolver.FormatUserId(entity.CreateUserId, auditUserNameMap),
UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime),
UpdateBy = OmsRbacUserDisplayNameResolver.FormatUserId(entity.UpdateUserId, auditUserNameMap)
};
}
private static ServiceChannelDetailOutput MapDetailOutput(
ServiceChannel entity,
IReadOnlyDictionary<int, string> groupMap,
IReadOnlyDictionary<int, string> auditUserNameMap)
{
return new ServiceChannelDetailOutput
{
Id = entity.Id,
GroupId = entity.GroupId,
GroupName = entity.GroupId.HasValue && groupMap.TryGetValue(entity.GroupId.Value, out var groupName) ? groupName : null,
ChannelCode = entity.ChannelCode,
ChannelName = entity.ChannelName,
MinTime = entity.MinTime,
MaxTime = entity.MaxTime,
ForecastType = entity.ForecastType,
ForecastCode = entity.ForecastCode,
Description = entity.Description,
RemoteAreaId = entity.RemoteAreaId,
PreScript = entity.PreScript,
IsActive = (byte)entity.IsActive,
CreateTime = entity.CreateTime,
CreateBy = OmsRbacUserDisplayNameResolver.FormatUserId(entity.CreateUserId, auditUserNameMap),
UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime),
UpdateBy = OmsRbacUserDisplayNameResolver.FormatUserId(entity.UpdateUserId, auditUserNameMap)
};
}
private static ChannelPriceFactorOutput MapPriceFactorOutput(ServiceChannelPriceFactor entity)
{
return new ChannelPriceFactorOutput
{
Id = entity.Id,
PriceId = entity.PriceId,
SerialNumber = entity.SerialNumber,
Factor = entity.Factor,
FactorValues = OmsDocHelper.DeserializeJson<List<string>>(entity.FactorValues) ?? []
};
}
private static ChannelPriceDetailOutput MapPriceDetailOutput(ServiceChannelPriceDetail entity)
{
return new ChannelPriceDetailOutput
{
Id = entity.Id,
PriceId = entity.PriceId,
FactorValuesJson = OmsDocHelper.DeserializeJsonObject(entity.FactorValuesJson),
CalculationFormula = entity.CalculationFormula,
CalculatedValue = entity.CalculatedValue,
CustomerGroupValues = OmsDocHelper.DeserializeJsonObject(entity.CustomerGroupValues)
};
}
private static List<ServiceChannelPriceFactor> BuildPriceFactors(IEnumerable<ChannelPriceFactorInput> inputs, int? priceId = null)
{
return inputs
.Where(input => !IsCustomerPricingFactor(input.Factor))
.Select(input => new ServiceChannelPriceFactor
{
PriceId = priceId ?? 0,
SerialNumber = input.SerialNumber,
Factor = input.Factor,
FactorValues = OmsDocHelper.SerializeJson(input.FactorValues)
}).ToList();
}
private static List<ServiceChannelPriceDetail> BuildPriceDetails(IEnumerable<ChannelPriceDetailInput> inputs, int? priceId = null)
{
return inputs.Select(input =>
{
var calculatedValue = input.CalculatedValue;
if ((calculatedValue == null || calculatedValue == 0) && input.CustomerGroupValues != null)
{
calculatedValue = ExtractFirstCustomerGroupPrice(input.CustomerGroupValues);
}
return new ServiceChannelPriceDetail
{
PriceId = priceId ?? 0,
FactorValuesJson = OmsDocHelper.SerializeJson(input.FactorValuesJson),
CalculationFormula = input.CalculationFormula,
CalculatedValue = calculatedValue,
CustomerGroupValues = null
};
}).ToList();
}
/// <summary>
/// 渠道买价不含客户组因素;保存时丢弃客户组列,并将历史数据首价迁移到 CalculatedValue。
/// </summary>
private static bool IsCustomerPricingFactor(string? factor)
{
if (string.IsNullOrWhiteSpace(factor))
{
return false;
}
var value = factor.Trim();
return value.Equals("customer", StringComparison.OrdinalIgnoreCase)
|| value.Equals("客户", StringComparison.Ordinal)
|| value.Equals("客户组", StringComparison.Ordinal);
}
private static decimal? ExtractFirstCustomerGroupPrice(object? customerGroupValues)
{
if (customerGroupValues == null)
{
return null;
}
var json = OmsDocHelper.SerializeJson(customerGroupValues);
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
try
{
var map = OmsDocHelper.DeserializeJson<Dictionary<string, decimal>>(json);
if (map == null || map.Count == 0)
{
return null;
}
foreach (var pair in map)
{
if (pair.Value > 0)
{
return pair.Value;
}
}
return map.Values.FirstOrDefault();
}
catch
{
return null;
}
}
private static ServiceChannelPriceSaveInput MapPriceSaveInput(ServiceChannelPriceSnapshotItemDto output)
{
return new ServiceChannelPriceSaveInput
{
Id = output.Id,
ServiceChannelId = output.ServiceChannelId,
SerialNumber = output.SerialNumber,
Status = (EnableStatus)output.Status,
PriceName = output.PriceName,
CostItem = output.CostItem,
CostUnit = output.CostUnit,
Currency = output.Currency,
ChargingCondition = output.ChargingCondition,
Factors = output.Factors.Select(item => new ChannelPriceFactorInput
{
Id = item.Id,
SerialNumber = item.SerialNumber,
Factor = item.Factor,
FactorValues = item.FactorValues
}).ToList(),
Details = output.Details.Select(item => new ChannelPriceDetailInput
{
Id = item.Id,
FactorValuesJson = item.FactorValuesJson,
CalculationFormula = item.CalculationFormula,
CalculatedValue = item.CalculatedValue,
CustomerGroupValues = item.CustomerGroupValues
}).ToList()
};
}
private static string NormalizeOperatorType(string? operatorType)
{
var normalized = operatorType?.Trim().ToLowerInvariant();
return normalized switch
{
PriceOperatorType => PriceOperatorType,
RulesOperatorType => RulesOperatorType,
_ => throw new Fake.Application.BusinessException("不支持的发布类型")
};
}
}