From d1beefb2be9136e59c4da35db67171e98d65b664 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 12 Nov 2026 11:19:36 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9A=E4=BB=B7=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E5=8F=B0=E4=B9=B0=E4=BB=B7=E5=8F=8D=E6=8E=A8=E5=8D=96=E4=BB=B7?= =?UTF-8?q?=E9=A2=84=E8=A7=88=E4=B8=8E=E8=8D=89=E7=A8=BF=E5=9B=9E=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持多渠道最低买价对齐合成、毛利率硬计算预览,以及回写销售产品草稿卖价(不自动发布)。 Co-authored-by: Cursor --- docs/定价工作台.md | 23 + .../Dtos/Channels/PricingWorkbenchDtos.cs | 276 ++++++ .../Channels/PricingWorkbenchCalculator.cs | 367 ++++++++ .../Channels/PricingWorkbenchService.cs | 816 ++++++++++++++++++ .../Consts/PricingWorkbenchCodes.cs | 19 + 5 files changed, 1501 insertions(+) create mode 100644 docs/定价工作台.md create mode 100644 src/Oms.Application/Dtos/Channels/PricingWorkbenchDtos.cs create mode 100644 src/Oms.Application/Services/Channels/PricingWorkbenchCalculator.cs create mode 100644 src/Oms.Application/Services/Channels/PricingWorkbenchService.cs create mode 100644 src/Oms.Domain/ChannelsAggregate/Consts/PricingWorkbenchCodes.cs diff --git a/docs/定价工作台.md b/docs/定价工作台.md new file mode 100644 index 0000000..25aee72 --- /dev/null +++ b/docs/定价工作台.md @@ -0,0 +1,23 @@ +# 定价工作台(后端) + +对应前端:`/channel/pricingWorkbench`,说明见前端仓库 `docs/定价工作台说明.md`。 + +## 服务 + +`PricingWorkbenchService`(`OMS-Channel`) + +| 方法 | 路径 | 说明 | +|------|------|------| +| GetChannelSummariesAsync | GET `/channel/pricing-workbench/channel-summaries` | 买价摘要(发布快照优先) | +| PreviewAsync | POST `/channel/pricing-workbench/preview` | 对齐 + 最低买价 + 毛利硬计算 | +| ApplyAsync | POST `/channel/pricing-workbench/apply` | 回写销售产品草稿,调用 `SalesProductService.SavePriceAsync(Publish=false)` | + +硬计算:`PricingWorkbenchCalculator`(可单测)。 + +## 审计 + +`apply` 写入 `ILogger` 结构化信息(用户、产品、价格项、渠道、毛利率、明细数、备注),响应含 `audit`。 + +## 权限码(RBAC 目录同步) + +见 `PricingWorkbenchCodes`:`Channel.PricingWorkbench.Query|Preview|Apply|AiAssist`。渠道模块其它接口同样主要靠前端菜单权限;本服务未强制服务端拦截,避免未同步权限码时不可用。 diff --git a/src/Oms.Application/Dtos/Channels/PricingWorkbenchDtos.cs b/src/Oms.Application/Dtos/Channels/PricingWorkbenchDtos.cs new file mode 100644 index 0000000..9309769 --- /dev/null +++ b/src/Oms.Application/Dtos/Channels/PricingWorkbenchDtos.cs @@ -0,0 +1,276 @@ +namespace Oms.Application.Dtos.Channels; + +/// +/// 定价工作台:渠道买价摘要(多选拼盘)。 +/// +public class PricingWorkbenchChannelSummaryOutput +{ + /// 服务渠道主键。 + public int ServiceChannelId { get; set; } + + /// 渠道名称。 + public string ChannelName { get; set; } = string.Empty; + + /// 币种(取首个启用价格项)。 + public string Currency { get; set; } = string.Empty; + + /// 费用项。 + public string CostItem { get; set; } = string.Empty; + + /// 价格项名称。 + public string PriceName { get; set; } = string.Empty; + + /// 分区数量(去重)。 + public int ZoneCount { get; set; } + + /// 重量段数量(去重)。 + public int WeightSegmentCount { get; set; } + + /// 明细格数。 + public int DetailCount { get; set; } + + /// 是否来自已发布买价快照。 + public bool FromPublishedSnapshot { get; set; } + + /// 最近发布时间(有快照时)。 + public DateTime? LastPublishTime { get; set; } + + /// 发布版本号。 + public string? PublishVersion { get; set; } + + /// 无快照时读草稿的警告。 + public string? Warning { get; set; } +} + +/// +/// 定价工作台预览入参。 +/// +public class PricingWorkbenchPreviewInput +{ + /// 参与合成的服务渠道主键列表。 + public List ServiceChannelIds { get; set; } = []; + + /// 默认毛利率(0~1,例 0.25 = 25%)。 + public decimal MarginRate { get; set; } = 0.25m; + + /// 按分区覆盖毛利率(key=分区键)。 + public Dictionary? ZoneMarginRates { get; set; } + + /// 按重量带覆盖毛利率(key=重量段文本)。 + public Dictionary? WeightMarginRates { get; set; } + + /// 排除的渠道(AI 调规则后重算)。 + public List? ExcludeChannelIds { get; set; } + + /// 可选:限定费用项;为空则各渠道取首个启用价格项。 + public string? CostItem { get; set; } + + /// 金额小数位(默认 2,向上取分)。 + public int MoneyScale { get; set; } = 2; + + /// + /// 相对现网卖价差异阈值(绝对值比例,例 0.15=15%);大于阈值的格进入风险列表。 + /// + public decimal DiffThreshold { get; set; } = 0.15m; + + /// 可选:对比用的销售产品(填了才算现网卖价差异)。 + public int? CompareSalesProductId { get; set; } + + /// 可选:对比用的卖价价格项。 + public int? ComparePriceId { get; set; } + + /// 对比客户组键(CustomerGroupValues 的 key)。 + public string? CompareCustomerGroupKey { get; set; } +} + +/// +/// 定价工作台预览出参。 +/// +public class PricingWorkbenchPreviewOutput +{ + /// 合成币种。 + public string Currency { get; set; } = string.Empty; + + /// 实际使用的毛利率(默认)。 + public decimal MarginRate { get; set; } + + /// 成本策略说明。 + public string CostStrategy { get; set; } = "min"; + + /// 参与渠道摘要。 + public List Channels { get; set; } = []; + + /// 对齐后的分区键(行)。 + public List Zones { get; set; } = []; + + /// 对齐后的重量段文本(列,左开右闭区间)。 + public List WeightSegments { get; set; } = []; + + /// 单元格(成本/建议卖价/来源)。 + public List Cells { get; set; } = []; + + /// 阻断级问题(如币种不一致)。 + public List Blockers { get; set; } = []; + + /// 警告(无快照、无法安全对齐等)。 + public List Warnings { get; set; } = []; + + /// 相对现网卖价超阈值的差异行。 + public List DiffRisks { get; set; } = []; + + /// 简短中文说明(可供 AI 报告引用)。 + public string Summary { get; set; } = string.Empty; + + /// 审计摘要(渠道、毛利、策略)。 + public PricingWorkbenchAuditInfo Audit { get; set; } = new(); +} + +/// +/// 预览矩阵单元格。 +/// +public class PricingWorkbenchCellOutput +{ + /// 分区键。 + public string Zone { get; set; } = string.Empty; + + /// 重量段文本。 + public string WeightSegment { get; set; } = string.Empty; + + /// 成本底价(最低买价);无报价时为空。 + public decimal? BuyPrice { get; set; } + + /// 建议卖价。 + public decimal? SellPrice { get; set; } + + /// 实际使用的毛利率。 + public decimal? AppliedMarginRate { get; set; } + + /// 反校验毛利率 (sell-buy)/sell。 + public decimal? VerifiedMargin { get; set; } + + /// 最低买价来源渠道。 + public int? SourceChannelId { get; set; } + + /// 来源渠道名。 + public string? SourceChannelName { get; set; } + + /// 计算公式(继承自来源买价明细)。 + public string CalculationFormula { get; set; } = "unit"; + + /// 无报价 / 对齐失败等标记。 + public string? Flag { get; set; } + + /// 相对现网卖价涨跌幅(有对比时)。 + public decimal? OnlineDeltaRatio { get; set; } + + /// 现网卖价。 + public decimal? OnlineSellPrice { get; set; } +} + +/// +/// 相对现网卖价的差异风险行。 +/// +public class PricingWorkbenchDiffRiskOutput +{ + /// 分区。 + public string Zone { get; set; } = string.Empty; + + /// 重量段。 + public string WeightSegment { get; set; } = string.Empty; + + /// 现网卖价。 + public decimal? OnlineSell { get; set; } + + /// 建议卖价。 + public decimal? SuggestedSell { get; set; } + + /// 涨跌幅(建议相对现网)。 + public decimal DeltaRatio { get; set; } + + /// 风险说明。 + public string Message { get; set; } = string.Empty; +} + +/// +/// 审计信息。 +/// +public class PricingWorkbenchAuditInfo +{ + /// 操作时间(UTC 本地服务器时间)。 + public DateTime OperatedAt { get; set; } + + /// 操作人用户 Id。 + public int OperatorUserId { get; set; } + + /// 参与渠道 Id。 + public List ServiceChannelIds { get; set; } = []; + + /// 排除渠道 Id。 + public List ExcludeChannelIds { get; set; } = []; + + /// 默认毛利率。 + public decimal MarginRate { get; set; } + + /// 成本策略。 + public string CostStrategy { get; set; } = "min"; +} + +/// +/// 回写销售产品草稿卖价入参。 +/// +public class PricingWorkbenchApplyInput +{ + /// 预览入参(服务端按相同规则重算,不以客户端数字为唯一真相)。 + public PricingWorkbenchPreviewInput Preview { get; set; } = new(); + + /// 目标销售产品。 + public int SalesProductId { get; set; } + + /// 目标价格项;为空则新建一条运费价。 + public int? PriceId { get; set; } + + /// 新建时价格项名称。 + public string? PriceName { get; set; } + + /// 新建时费用项(默认 freight)。 + public string? CostItem { get; set; } + + /// 新建时计费单位。 + public string? CostUnit { get; set; } + + /// 客户组键(写入 CustomerGroupValues)。 + public string CustomerGroupKey { get; set; } = string.Empty; + + /// 可选:AI/人工说明,写入审计日志。 + public string? AnalysisNote { get; set; } + + /// + /// 可选:前端编辑后的卖价覆盖(仅覆盖有值的格;仍须通过服务端重算校验结构)。 + /// key = zone|weightSegment。 + /// + public Dictionary? SellOverrides { get; set; } +} + +/// +/// 回写出参。 +/// +public class PricingWorkbenchApplyOutput +{ + /// 销售产品 Id。 + public int SalesProductId { get; set; } + + /// 写入的价格项 Id。 + public int PriceId { get; set; } + + /// 写入明细行数。 + public int DetailCount { get; set; } + + /// 是否新建价格项。 + public bool CreatedPrice { get; set; } + + /// 提示:未发布,需走销售产品现有发布/审批。 + public string Message { get; set; } = string.Empty; + + /// 审计信息。 + public PricingWorkbenchAuditInfo Audit { get; set; } = new(); +} diff --git a/src/Oms.Application/Services/Channels/PricingWorkbenchCalculator.cs b/src/Oms.Application/Services/Channels/PricingWorkbenchCalculator.cs new file mode 100644 index 0000000..ad06aeb --- /dev/null +++ b/src/Oms.Application/Services/Channels/PricingWorkbenchCalculator.cs @@ -0,0 +1,367 @@ +using System.Globalization; +using System.Text.Json; +using Oms.Application.Dtos.Channels; +using Oms.Application.Services.Orders; + +namespace Oms.Application.Services.Channels; + +/// +/// 定价工作台硬计算:分区/重量段对齐、最低买价合成、毛利率反推卖价。 +/// AI 只调规则后调用本类重算,禁止模型数字当唯一真相。 +/// +public static class PricingWorkbenchCalculator +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// 卖价 = 买价 ÷ (1 - 毛利率),向上取到指定小数位(默认分)。 + /// + public static decimal CalcSell(decimal buy, decimal marginRate, int moneyScale = 2) + { + if (buy <= 0) + { + return 0; + } + + if (marginRate < 0 || marginRate >= 1m) + { + throw new ArgumentOutOfRangeException(nameof(marginRate), "毛利率须满足 0 ≤ m < 1"); + } + + var sell = buy / (1m - marginRate); + var factor = (decimal)Math.Pow(10, Math.Max(0, moneyScale)); + return Math.Ceiling(sell * factor) / factor; + } + + /// + /// 反校验毛利率 (sell - buy) / sell。 + /// + public static decimal CalcVerifiedMargin(decimal sell, decimal buy) + { + if (sell <= 0) + { + return 0; + } + + return Math.Round((sell - buy) / sell, 6, MidpointRounding.AwayFromZero); + } + + /// + /// 从明细因子字典取分区键。 + /// + public static bool TryGetZone(Dictionary factors, out string zone) => + TryGetFactor(factors, out zone, "分区", "价格分区", "zone"); + + /// + /// 从明细因子字典取重量段文本。 + /// + public static bool TryGetWeight(Dictionary factors, out string weight) => + TryGetFactor(factors, out weight, "重量", "weight"); + + /// + /// 解析 FactorValuesJson 为字典。 + /// + public static Dictionary ParseFactors(object? factorValuesJson) + { + if (factorValuesJson == null) + { + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + if (factorValuesJson is JsonElement element) + { + if (element.ValueKind != JsonValueKind.Object) + { + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + return element.EnumerateObject() + .ToDictionary(x => x.Name, x => x.Value.ToString(), StringComparer.OrdinalIgnoreCase); + } + + if (factorValuesJson is Dictionary dict) + { + return new Dictionary(dict, StringComparer.OrdinalIgnoreCase); + } + + if (factorValuesJson is IDictionary objDict) + { + return objDict.ToDictionary( + x => x.Key, + x => x.Value?.ToString() ?? string.Empty, + StringComparer.OrdinalIgnoreCase); + } + + try + { + var json = JsonSerializer.Serialize(factorValuesJson, JsonOptions); + return JsonSerializer.Deserialize>(json, JsonOptions) + ?? new Dictionary(StringComparer.OrdinalIgnoreCase); + } + catch + { + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + } + + /// + /// 从客户组取值中解析指定键的价格。 + /// + public static decimal? TryGetCustomerGroupPrice(object? customerGroupValues, string? key) + { + if (customerGroupValues == null || string.IsNullOrWhiteSpace(key)) + { + return null; + } + + var map = ParseDecimalMap(customerGroupValues); + if (map.TryGetValue(key.Trim(), out var v)) + { + return v; + } + + // 宽松:忽略大小写再找一次 + foreach (var pair in map) + { + if (string.Equals(pair.Key, key.Trim(), StringComparison.OrdinalIgnoreCase)) + { + return pair.Value; + } + } + + return null; + } + + /// + /// 解析明细金额:优先 CalculatedValue,否则客户组首价。 + /// + public static decimal? ResolveBuyAmount(ChannelPriceDetailOutput detail) + { + if (detail.CalculatedValue is > 0) + { + return detail.CalculatedValue; + } + + var map = ParseDecimalMap(detail.CustomerGroupValues); + foreach (var pair in map) + { + if (pair.Value > 0) + { + return pair.Value; + } + } + + return detail.CalculatedValue; + } + + /// + /// 重量段边界取并集,生成细段文本列表(左开右闭展示为 start-end)。 + /// + public static List BuildAlignedWeightSegments(IEnumerable rawSegments) + { + var bounds = new SortedSet(); + var parsed = new List<(decimal Start, decimal End, string Text)>(); + foreach (var raw in rawSegments) + { + if (!ParcelBillingCalculator.TryParseWeightInterval(raw, out var start, out var end)) + { + continue; + } + + bounds.Add(start); + bounds.Add(end); + parsed.Add((start, end, FormatWeightSegment(start, end))); + } + + if (bounds.Count < 2) + { + return parsed.Select(x => x.Text).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(x => x).ToList(); + } + + var list = bounds.ToList(); + var result = new List(); + for (var i = 0; i < list.Count - 1; i++) + { + var a = list[i]; + var b = list[i + 1]; + if (b <= a) + { + continue; + } + + result.Add(FormatWeightSegment(a, b)); + } + + return result; + } + + /// + /// 格式化重量段。 + /// + public static string FormatWeightSegment(decimal start, decimal end) => + $"{TrimDecimal(start)}-{TrimDecimal(end)}"; + + /// + /// 在原段列表中查找覆盖细段中点的买价格。 + /// + public static bool TryResolvePriceForSegment( + IReadOnlyList sourceCells, + string zone, + string fineSegment, + out SourceBuyCell hit) + { + hit = default!; + if (!ParcelBillingCalculator.TryParseWeightInterval(fineSegment, out var fineStart, out var fineEnd)) + { + return false; + } + + var mid = (fineStart + fineEnd) / 2m; + SourceBuyCell? best = null; + foreach (var cell in sourceCells) + { + if (!string.Equals(cell.Zone, zone, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (!ParcelBillingCalculator.TryParseWeightInterval(cell.WeightSegment, out var s, out var e)) + { + continue; + } + + if (!ParcelBillingCalculator.WeightInLeftOpenRightClosedInterval(mid, s, e)) + { + continue; + } + + if (best == null || cell.BuyPrice < best.Value.BuyPrice) + { + best = cell; + } + } + + if (best == null) + { + return false; + } + + hit = best.Value; + return true; + } + + /// + /// 解析分区毛利覆盖。 + /// + public static decimal ResolveMarginRate( + decimal defaultRate, + string zone, + string weightSegment, + IReadOnlyDictionary? zoneRates, + IReadOnlyDictionary? weightRates) + { + if (zoneRates != null) + { + foreach (var pair in zoneRates) + { + if (string.Equals(pair.Key, zone, StringComparison.OrdinalIgnoreCase)) + { + return pair.Value; + } + } + } + + if (weightRates != null) + { + foreach (var pair in weightRates) + { + if (string.Equals(pair.Key, weightSegment, StringComparison.OrdinalIgnoreCase)) + { + return pair.Value; + } + } + } + + return defaultRate; + } + + private static bool TryGetFactor(Dictionary factors, out string value, params string[] keys) + { + foreach (var key in keys) + { + if (factors.TryGetValue(key, out var raw) && !string.IsNullOrWhiteSpace(raw)) + { + value = raw.Trim(); + return true; + } + } + + value = string.Empty; + return false; + } + + private static Dictionary ParseDecimalMap(object? raw) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (raw == null) + { + return result; + } + + if (raw is JsonElement el && el.ValueKind == JsonValueKind.Object) + { + foreach (var prop in el.EnumerateObject()) + { + if (TryParseDecimal(prop.Value.ToString(), out var d)) + { + result[prop.Name] = d; + } + } + + return result; + } + + try + { + var json = JsonSerializer.Serialize(raw, JsonOptions); + var map = JsonSerializer.Deserialize>(json, JsonOptions); + if (map != null) + { + foreach (var pair in map) + { + result[pair.Key] = pair.Value; + } + } + } + catch + { + // ignore + } + + return result; + } + + private static bool TryParseDecimal(string? text, out decimal value) => + decimal.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value) + || decimal.TryParse(text, NumberStyles.Any, CultureInfo.CurrentCulture, out value); + + private static string TrimDecimal(decimal value) + { + var s = value.ToString("0.####", CultureInfo.InvariantCulture); + return s; + } + + /// + /// 渠道侧原始买价格。 + /// + public readonly record struct SourceBuyCell( + int ChannelId, + string ChannelName, + string Zone, + string WeightSegment, + decimal BuyPrice, + string CalculationFormula); +} diff --git a/src/Oms.Application/Services/Channels/PricingWorkbenchService.cs b/src/Oms.Application/Services/Channels/PricingWorkbenchService.cs new file mode 100644 index 0000000..84392d7 --- /dev/null +++ b/src/Oms.Application/Services/Channels/PricingWorkbenchService.cs @@ -0,0 +1,816 @@ +using System.Text.Json; +using Fake.Application; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Oms.Application.Dtos.Channels; +using Oms.Application.Shared; +using Oms.Domain.ChannelsAggregate.Entities; +using Oms.Domain.ChannelsAggregate.Repositories; +using Oms.Domain.Shared.Enums; + +namespace Oms.Application.Services.Channels; + +/// +/// 定价工作台:多渠道买价对齐合成 → 毛利率反推卖价草稿 → 回写销售产品(不自动发布)。 +/// +[ApiExplorerSettings(GroupName = "OMS-Channel")] +public class PricingWorkbenchService : ApplicationService +{ + private const string PriceOperatorType = "price"; + private const string CostStrategyMin = "min"; + + private IServiceChannelRepository ServiceChannelRepository => + LazyServiceProvider.GetRequiredService(); + + private ISalesProductRepository SalesProductRepository => + LazyServiceProvider.GetRequiredService(); + + private SalesProductService SalesProductAppService => + LazyServiceProvider.GetRequiredService(); + + private ILogger WorkbenchLogger => + LazyServiceProvider.GetRequiredService().CreateLogger(typeof(PricingWorkbenchService)); + + /// + /// 批量查询渠道买价摘要(优先已发布快照;无快照则读草稿并警告)。 + /// + /// 服务渠道主键,逗号分隔或重复 query。 + [HttpGet("/channel/pricing-workbench/channel-summaries")] + public async Task> GetChannelSummariesAsync( + [FromQuery] string? serviceChannelIds) + { + var ids = ParseIdList(serviceChannelIds); + if (ids.Count == 0) + { + return []; + } + + var result = new List(); + foreach (var id in ids.Distinct()) + { + var loaded = await LoadChannelPriceAsync(id, costItem: null); + result.Add(loaded.Summary); + } + + return result; + } + + /// + /// 预览:对齐分区/重量段,最低买价合成,按毛利率硬计算建议卖价;可选对比现网卖价差异。 + /// + /// 渠道列表、毛利率、排除渠道、对比目标等。 + /// 对齐后的成本/卖价矩阵;币种不一致时 blockers 阻断。 + [HttpPost("/channel/pricing-workbench/preview")] + public async Task PreviewAsync(PricingWorkbenchPreviewInput input) + { + return await BuildPreviewAsync(input); + } + + /// + /// 将预览结果回写到销售产品草稿卖价(指定客户组);不发布,需走现有发布/审批。 + /// + /// 预览参数 + 目标销售产品/价格项/客户组。 + /// 写入的价格项与审计信息。 + [HttpPost("/channel/pricing-workbench/apply")] + public async Task ApplyAsync(PricingWorkbenchApplyInput input) + { + if (input.SalesProductId <= 0) + { + throw new BusinessException("请指定目标销售产品"); + } + + if (string.IsNullOrWhiteSpace(input.CustomerGroupKey)) + { + throw new BusinessException("请指定客户组键(CustomerGroupValues 的 key)"); + } + + var preview = await BuildPreviewAsync(input.Preview); + if (preview.Blockers.Count > 0) + { + throw new BusinessException(string.Join(";", preview.Blockers)); + } + + _ = await SalesProductRepository.FirstOrDefaultAsync(x => x.Id == input.SalesProductId) + ?? throw new BusinessException("销售产品不存在"); + + var existingPrices = await LoadSalesProductPriceSaveInputsAsync(input.SalesProductId); + var created = false; + SalesProductPriceSaveInput target; + + if (input.PriceId is > 0) + { + target = existingPrices.FirstOrDefault(x => x.Id == input.PriceId) + ?? throw new BusinessException("目标价格项不存在"); + } + else + { + created = true; + var nextSerial = existingPrices.Count == 0 ? 1 : existingPrices.Max(x => x.SerialNumber) + 1; + target = new SalesProductPriceSaveInput + { + SalesProductId = input.SalesProductId, + SerialNumber = nextSerial, + Status = EnableStatus.Enabled, + PriceName = string.IsNullOrWhiteSpace(input.PriceName) ? "运费" : input.PriceName!.Trim(), + CostItem = string.IsNullOrWhiteSpace(input.CostItem) + ? (string.IsNullOrWhiteSpace(input.Preview.CostItem) ? "freight" : input.Preview.CostItem!.Trim()) + : input.CostItem!.Trim(), + CostUnit = string.IsNullOrWhiteSpace(input.CostUnit) ? "kg" : input.CostUnit!.Trim(), + Currency = preview.Currency, + ChargingCondition = null, + Factors = [], + Details = [] + }; + existingPrices.Add(target); + } + + ApplyPreviewToPrice(target, preview, input.CustomerGroupKey.Trim(), input.SellOverrides); + target.Currency = string.IsNullOrWhiteSpace(target.Currency) ? preview.Currency : target.Currency; + + await SalesProductAppService.SavePriceAsync(new SalesProductPriceSaveAllInput + { + SalesProductId = input.SalesProductId, + Publish = false, + Prices = existingPrices + }); + + // 重新读取以获得真实 PriceId(新建场景) + var after = await LoadSalesProductPriceSaveInputsAsync(input.SalesProductId); + var saved = after.FirstOrDefault(x => + (!created && input.PriceId is > 0 && x.Id == input.PriceId) + || (created && string.Equals(x.PriceName, target.PriceName, StringComparison.Ordinal) + && string.Equals(x.CostItem, target.CostItem, StringComparison.OrdinalIgnoreCase))) + ?? after.OrderByDescending(x => x.SerialNumber).FirstOrDefault() + ?? target; + + var audit = preview.Audit; + audit.OperatedAt = DateTime.Now; + audit.OperatorUserId = ResolveOperatorUserId(); + + WorkbenchLogger.LogInformation( + "PricingWorkbench apply: user={UserId} product={ProductId} price={PriceId} channels={Channels} margin={Margin} note={Note} details={Details}", + audit.OperatorUserId, + input.SalesProductId, + saved.Id, + string.Join(',', audit.ServiceChannelIds), + audit.MarginRate, + input.AnalysisNote, + saved.Details.Count); + + return new PricingWorkbenchApplyOutput + { + SalesProductId = input.SalesProductId, + PriceId = saved.Id ?? 0, + DetailCount = saved.Details.Count, + CreatedPrice = created, + Message = "已写入草稿卖价,未发布。请到销售产品完成 AI 风险分析后发布/审批。", + Audit = audit + }; + } + + private async Task BuildPreviewAsync(PricingWorkbenchPreviewInput input) + { + var output = new PricingWorkbenchPreviewOutput + { + MarginRate = input.MarginRate, + CostStrategy = CostStrategyMin, + Audit = new PricingWorkbenchAuditInfo + { + OperatedAt = DateTime.Now, + OperatorUserId = ResolveOperatorUserId(), + ServiceChannelIds = input.ServiceChannelIds?.Distinct().ToList() ?? [], + ExcludeChannelIds = input.ExcludeChannelIds?.Distinct().ToList() ?? [], + MarginRate = input.MarginRate, + CostStrategy = CostStrategyMin + } + }; + + if (input.MarginRate < 0 || input.MarginRate >= 1m) + { + output.Blockers.Add("毛利率须满足 0 ≤ m < 1(例:25% 填 0.25)"); + return output; + } + + var exclude = new HashSet(input.ExcludeChannelIds ?? []); + var channelIds = (input.ServiceChannelIds ?? []) + .Where(id => id > 0 && !exclude.Contains(id)) + .Distinct() + .ToList(); + + if (channelIds.Count == 0) + { + output.Blockers.Add("请至少选择一个服务渠道"); + return output; + } + + var loadedList = new List(); + foreach (var id in channelIds) + { + loadedList.Add(await LoadChannelPriceAsync(id, input.CostItem)); + } + + output.Channels = loadedList.Select(x => x.Summary).ToList(); + foreach (var w in loadedList.Select(x => x.Summary.Warning).Where(x => !string.IsNullOrWhiteSpace(x))) + { + output.Warnings.Add(w!); + } + + var currencies = loadedList + .Select(x => x.Summary.Currency?.Trim() ?? string.Empty) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + if (currencies.Count > 1) + { + output.Blockers.Add($"买价币种不一致:{string.Join(" / ", currencies)},请先统一币种后再合成"); + return output; + } + + output.Currency = currencies.FirstOrDefault() ?? string.Empty; + if (string.IsNullOrWhiteSpace(output.Currency)) + { + output.Warnings.Add("未能识别币种,请检查渠道买价价格项"); + } + + var sourceCells = new List(); + foreach (var loaded in loadedList) + { + foreach (var detail in loaded.Details) + { + var factors = PricingWorkbenchCalculator.ParseFactors(detail.FactorValuesJson); + if (!PricingWorkbenchCalculator.TryGetZone(factors, out var zone)) + { + continue; + } + + if (!PricingWorkbenchCalculator.TryGetWeight(factors, out var weightText)) + { + output.Warnings.Add($"渠道 {loaded.Summary.ChannelName} 分区 {zone} 存在无重量段明细,已跳过"); + continue; + } + + var buy = PricingWorkbenchCalculator.ResolveBuyAmount(detail); + if (buy is null or <= 0) + { + continue; + } + + sourceCells.Add(new PricingWorkbenchCalculator.SourceBuyCell( + loaded.Summary.ServiceChannelId, + loaded.Summary.ChannelName, + zone, + weightText, + buy.Value, + string.IsNullOrWhiteSpace(detail.CalculationFormula) ? "unit" : detail.CalculationFormula)); + } + } + + if (sourceCells.Count == 0) + { + output.Blockers.Add("所选渠道没有可用的分区×重量买价明细"); + return output; + } + + var zones = sourceCells + .Select(x => x.Zone) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(x => x, StringComparer.OrdinalIgnoreCase) + .ToList(); + + var weightSegments = PricingWorkbenchCalculator.BuildAlignedWeightSegments( + sourceCells.Select(x => x.WeightSegment)); + + if (weightSegments.Count == 0) + { + output.Blockers.Add("无法解析重量段,请检查买价重量因子格式(如 0-0.5)"); + return output; + } + + output.Zones = zones; + output.WeightSegments = weightSegments; + + var moneyScale = input.MoneyScale <= 0 ? 2 : input.MoneyScale; + var onlineMap = await LoadOnlineSellMapAsync( + input.CompareSalesProductId, + input.ComparePriceId, + input.CompareCustomerGroupKey); + + foreach (var zone in zones) + { + foreach (var seg in weightSegments) + { + var cell = new PricingWorkbenchCellOutput + { + Zone = zone, + WeightSegment = seg + }; + + if (!PricingWorkbenchCalculator.TryResolvePriceForSegment(sourceCells, zone, seg, out var hit)) + { + cell.Flag = "无报价"; + output.Cells.Add(cell); + continue; + } + + var margin = PricingWorkbenchCalculator.ResolveMarginRate( + input.MarginRate, + zone, + seg, + input.ZoneMarginRates, + input.WeightMarginRates); + + try + { + var sell = PricingWorkbenchCalculator.CalcSell(hit.BuyPrice, margin, moneyScale); + cell.BuyPrice = hit.BuyPrice; + cell.SellPrice = sell; + cell.AppliedMarginRate = margin; + cell.VerifiedMargin = PricingWorkbenchCalculator.CalcVerifiedMargin(sell, hit.BuyPrice); + cell.SourceChannelId = hit.ChannelId; + cell.SourceChannelName = hit.ChannelName; + cell.CalculationFormula = hit.CalculationFormula; + + var key = CellKey(zone, seg); + if (onlineMap.TryGetValue(key, out var online) && online > 0 && sell > 0) + { + cell.OnlineSellPrice = online; + cell.OnlineDeltaRatio = Math.Round((sell - online) / online, 6, MidpointRounding.AwayFromZero); + if (Math.Abs(cell.OnlineDeltaRatio.Value) >= input.DiffThreshold) + { + output.DiffRisks.Add(new PricingWorkbenchDiffRiskOutput + { + Zone = zone, + WeightSegment = seg, + OnlineSell = online, + SuggestedSell = sell, + DeltaRatio = cell.OnlineDeltaRatio.Value, + Message = + $"分区 {zone} 段 {seg}:现网 {online} → 建议 {sell}({cell.OnlineDeltaRatio:P1})" + }); + } + } + } + catch (Exception ex) + { + cell.Flag = "计算失败"; + output.Warnings.Add($"{zone}/{seg}: {ex.Message}"); + } + + output.Cells.Add(cell); + } + } + + var priced = output.Cells.Count(x => x.SellPrice is > 0); + var missing = output.Cells.Count(x => x.Flag == "无报价"); + output.Summary = + $"合成 {channelIds.Count} 个渠道最低买价,默认毛利 {input.MarginRate:P0}," + + $"生成 {priced} 格建议卖价" + + (missing > 0 ? $",{missing} 格无报价" : string.Empty) + + (output.DiffRisks.Count > 0 ? $";相对现网超阈值 {output.DiffRisks.Count} 格" : string.Empty) + + "。"; + + return output; + } + + private async Task LoadChannelPriceAsync(int serviceChannelId, string? costItem) + { + var channel = await ServiceChannelRepository.FirstOrDefaultAsync(x => x.Id == serviceChannelId) + ?? throw new BusinessException($"服务渠道不存在:{serviceChannelId}"); + + var summary = new PricingWorkbenchChannelSummaryOutput + { + ServiceChannelId = serviceChannelId, + ChannelName = channel.ChannelName + }; + + List details = []; + string currency = string.Empty; + string priceName = string.Empty; + string resolvedCostItem = string.Empty; + + var publish = await ServiceChannelRepository.GetEffectivePublishRecordAsync( + serviceChannelId, + PriceOperatorType, + DateTime.Now); + + if (publish?.Content != null) + { + var snapshot = OmsDocHelper.DeserializeChannelPriceSnapshot(publish.Content); + var price = PickPriceItem( + snapshot?.Prices?.Select(p => new PricePick( + p.SerialNumber, + p.Status, + p.PriceName, + p.CostItem, + p.Currency, + p.Details)).ToList() ?? [], + costItem); + + if (price != null) + { + details = price.Details; + currency = price.Currency; + priceName = price.PriceName; + resolvedCostItem = price.CostItem; + summary.FromPublishedSnapshot = true; + summary.LastPublishTime = publish.PublishTime; + summary.PublishVersion = publish.Version; + } + } + + if (details.Count == 0) + { + var draftPrices = await ServiceChannelRepository.GetPricesAsync(serviceChannelId); + var enabled = draftPrices + .Where(x => x.Status == EnableStatus.Enabled) + .OrderBy(x => x.SerialNumber) + .ToList(); + if (!string.IsNullOrWhiteSpace(costItem)) + { + enabled = enabled + .Where(x => string.Equals(x.CostItem, costItem, StringComparison.OrdinalIgnoreCase)) + .ToList(); + } + + var pick = enabled.FirstOrDefault() ?? draftPrices.OrderBy(x => x.SerialNumber).FirstOrDefault(); + if (pick != null) + { + var priceIds = new[] { pick.Id }; + var rawDetails = await ServiceChannelRepository.GetPriceDetailsAsync(priceIds); + details = rawDetails.Select(d => new ChannelPriceDetailOutput + { + Id = d.Id, + PriceId = d.PriceId, + FactorValuesJson = OmsDocHelper.DeserializeJsonObject(d.FactorValuesJson), + CalculationFormula = d.CalculationFormula, + CalculatedValue = d.CalculatedValue, + CustomerGroupValues = OmsDocHelper.DeserializeJsonObject(d.CustomerGroupValues) + }).ToList(); + currency = pick.Currency; + priceName = pick.PriceName; + resolvedCostItem = pick.CostItem; + summary.FromPublishedSnapshot = false; + summary.Warning = $"渠道「{channel.ChannelName}」无生效买价快照,已使用草稿价"; + } + else + { + summary.Warning = $"渠道「{channel.ChannelName}」无买价数据"; + } + } + + var zones = new HashSet(StringComparer.OrdinalIgnoreCase); + var weights = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var d in details) + { + var factors = PricingWorkbenchCalculator.ParseFactors(d.FactorValuesJson); + if (PricingWorkbenchCalculator.TryGetZone(factors, out var z)) + { + zones.Add(z); + } + + if (PricingWorkbenchCalculator.TryGetWeight(factors, out var w)) + { + weights.Add(w); + } + } + + summary.Currency = currency; + summary.CostItem = resolvedCostItem; + summary.PriceName = priceName; + summary.ZoneCount = zones.Count; + summary.WeightSegmentCount = weights.Count; + summary.DetailCount = details.Count; + + return new LoadedChannelPrice(summary, details); + } + + private async Task> LoadOnlineSellMapAsync( + int? salesProductId, + int? priceId, + string? customerGroupKey) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (salesProductId is not > 0) + { + return map; + } + + List details = []; + + var publish = await SalesProductRepository.GetEffectivePublishRecordAsync( + salesProductId.Value, + PriceOperatorType, + DateTime.Now); + + if (publish?.Content != null) + { + var snapshot = OmsDocHelper.DeserializePriceSnapshot(publish.Content); + var prices = snapshot?.Prices ?? []; + var price = priceId is > 0 + ? prices.FirstOrDefault(x => x.Id == priceId.Value) + : prices.OrderBy(x => x.SerialNumber).FirstOrDefault(); + if (price != null) + { + details = price.Details; + } + } + + if (details.Count == 0) + { + var drafts = await SalesProductRepository.GetPricesAsync(salesProductId.Value); + var pick = priceId is > 0 + ? drafts.FirstOrDefault(x => x.Id == priceId.Value) + : drafts.OrderBy(x => x.SerialNumber).FirstOrDefault(); + if (pick != null) + { + var raw = await SalesProductRepository.GetPriceDetailsAsync([pick.Id]); + details = raw.Select(d => new ChannelPriceDetailOutput + { + FactorValuesJson = OmsDocHelper.DeserializeJsonObject(d.FactorValuesJson), + CalculatedValue = d.CalculatedValue, + CustomerGroupValues = OmsDocHelper.DeserializeJsonObject(d.CustomerGroupValues), + CalculationFormula = d.CalculationFormula + }).ToList(); + } + } + + foreach (var d in details) + { + var factors = PricingWorkbenchCalculator.ParseFactors(d.FactorValuesJson); + if (!PricingWorkbenchCalculator.TryGetZone(factors, out var zone) + || !PricingWorkbenchCalculator.TryGetWeight(factors, out var weight)) + { + continue; + } + + decimal? amount = null; + if (!string.IsNullOrWhiteSpace(customerGroupKey)) + { + amount = PricingWorkbenchCalculator.TryGetCustomerGroupPrice(d.CustomerGroupValues, customerGroupKey); + } + + amount ??= d.CalculatedValue; + if (amount is > 0) + { + map[CellKey(zone, weight)] = amount.Value; + } + } + + return map; + } + + private async Task> LoadSalesProductPriceSaveInputsAsync(int salesProductId) + { + var prices = await SalesProductRepository.GetPricesAsync(salesProductId); + var priceIds = prices.Select(x => x.Id).ToArray(); + var factorMap = (await SalesProductRepository.GetPriceFactorsAsync(priceIds)) + .GroupBy(x => x.PriceId) + .ToDictionary(x => x.Key, x => x.OrderBy(f => f.SerialNumber).ToList()); + var detailMap = (await SalesProductRepository.GetPriceDetailsAsync(priceIds)) + .GroupBy(x => x.PriceId) + .ToDictionary(x => x.Key, x => x.OrderBy(d => d.Id).ToList()); + + return prices.OrderBy(x => x.SerialNumber).Select(p => new SalesProductPriceSaveInput + { + Id = p.Id, + SalesProductId = salesProductId, + SerialNumber = p.SerialNumber, + Status = p.Status, + PriceName = p.PriceName, + CostItem = p.CostItem, + CostUnit = p.CostUnit, + Currency = p.Currency, + ChargingCondition = p.ChargingCondition, + Factors = factorMap.TryGetValue(p.Id, out var factors) + ? factors.Select(f => new ChannelPriceFactorInput + { + Id = f.Id, + SerialNumber = f.SerialNumber, + Factor = f.Factor, + FactorValues = OmsDocHelper.DeserializeJson>(f.FactorValues) ?? [] + }).ToList() + : [], + Details = detailMap.TryGetValue(p.Id, out var details) + ? details.Select(d => new ChannelPriceDetailInput + { + Id = d.Id, + FactorValuesJson = OmsDocHelper.DeserializeJsonObject(d.FactorValuesJson), + CalculationFormula = d.CalculationFormula, + CalculatedValue = d.CalculatedValue, + CustomerGroupValues = OmsDocHelper.DeserializeJsonObject(d.CustomerGroupValues) + }).ToList() + : [] + }).ToList(); + } + + private static void ApplyPreviewToPrice( + SalesProductPriceSaveInput target, + PricingWorkbenchPreviewOutput preview, + string customerGroupKey, + Dictionary? sellOverrides) + { + EnsureFactors(target, preview, customerGroupKey); + + var detailByKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var d in target.Details) + { + var factors = PricingWorkbenchCalculator.ParseFactors(d.FactorValuesJson); + if (!PricingWorkbenchCalculator.TryGetZone(factors, out var z) + || !PricingWorkbenchCalculator.TryGetWeight(factors, out var w)) + { + continue; + } + + detailByKey[CellKey(z, w)] = d; + } + + foreach (var cell in preview.Cells) + { + if (cell.SellPrice is null or <= 0 && cell.Flag == "无报价") + { + continue; + } + + var key = CellKey(cell.Zone, cell.WeightSegment); + var sell = cell.SellPrice ?? 0; + if (sellOverrides != null && sellOverrides.TryGetValue(key, out var ov) && ov > 0) + { + sell = ov; + } + + if (sell <= 0) + { + continue; + } + + if (!detailByKey.TryGetValue(key, out var detail)) + { + detail = new ChannelPriceDetailInput + { + FactorValuesJson = new Dictionary + { + ["分区"] = cell.Zone, + ["重量"] = cell.WeightSegment + }, + CalculationFormula = string.IsNullOrWhiteSpace(cell.CalculationFormula) + ? "unit" + : cell.CalculationFormula, + CalculatedValue = sell, + CustomerGroupValues = new Dictionary() + }; + target.Details.Add(detail); + detailByKey[key] = detail; + } + + var cg = ToMutableDecimalMap(detail.CustomerGroupValues); + cg[customerGroupKey] = sell; + detail.CustomerGroupValues = cg; + detail.CalculatedValue = sell; + if (string.IsNullOrWhiteSpace(detail.CalculationFormula)) + { + detail.CalculationFormula = cell.CalculationFormula ?? "unit"; + } + } + } + + private static void EnsureFactors( + SalesProductPriceSaveInput target, + PricingWorkbenchPreviewOutput preview, + string customerGroupKey) + { + void EnsureFactor(string name, IEnumerable values) + { + var existing = target.Factors.FirstOrDefault(f => + string.Equals(f.Factor, name, StringComparison.OrdinalIgnoreCase) + || (name == "分区" && (f.Factor is "zone" or "价格分区")) + || (name == "重量" && f.Factor is "weight") + || (name == "客户组" && f.Factor is "customer" or "客户")); + + if (existing == null) + { + target.Factors.Add(new ChannelPriceFactorInput + { + SerialNumber = target.Factors.Count + 1, + Factor = name, + FactorValues = values.Distinct(StringComparer.OrdinalIgnoreCase).ToList() + }); + } + else + { + var set = new HashSet(existing.FactorValues ?? [], StringComparer.OrdinalIgnoreCase); + foreach (var v in values) + { + set.Add(v); + } + + existing.FactorValues = set.ToList(); + } + } + + EnsureFactor("分区", preview.Zones); + EnsureFactor("重量", preview.WeightSegments); + EnsureFactor("客户组", [customerGroupKey]); + } + + private static Dictionary ToMutableDecimalMap(object? raw) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (raw == null) + { + return result; + } + + if (raw is JsonElement el && el.ValueKind == JsonValueKind.Object) + { + foreach (var p in el.EnumerateObject()) + { + if (decimal.TryParse(p.Value.ToString(), out var d)) + { + result[p.Name] = d; + } + } + + return result; + } + + if (raw is Dictionary dict) + { + foreach (var pair in dict) + { + result[pair.Key] = pair.Value; + } + + return result; + } + + try + { + var json = JsonSerializer.Serialize(raw); + var map = JsonSerializer.Deserialize>(json); + if (map != null) + { + foreach (var pair in map) + { + result[pair.Key] = pair.Value; + } + } + } + catch + { + // ignore + } + + return result; + } + + private static PricePick? PickPriceItem(List prices, string? costItem) + { + IEnumerable q = prices.OrderBy(x => x.SerialNumber); + if (!string.IsNullOrWhiteSpace(costItem)) + { + q = q.Where(x => string.Equals(x.CostItem, costItem, StringComparison.OrdinalIgnoreCase)); + } + + return q.FirstOrDefault(x => x.Status == (byte)EnableStatus.Enabled) ?? q.FirstOrDefault(); + } + + private int ResolveOperatorUserId() + { + try + { + return CurrentUser.GetId(); + } + catch + { + return 0; + } + } + + private static List ParseIdList(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) + { + return []; + } + + return raw.Split([',', ' ', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(x => int.TryParse(x, out var id) ? id : 0) + .Where(x => x > 0) + .ToList(); + } + + private static string CellKey(string zone, string weight) => $"{zone}|{weight}"; + + private sealed record LoadedChannelPrice( + PricingWorkbenchChannelSummaryOutput Summary, + List Details); + + private sealed record PricePick( + int SerialNumber, + byte Status, + string PriceName, + string CostItem, + string Currency, + List Details); +} diff --git a/src/Oms.Domain/ChannelsAggregate/Consts/PricingWorkbenchCodes.cs b/src/Oms.Domain/ChannelsAggregate/Consts/PricingWorkbenchCodes.cs new file mode 100644 index 0000000..0888588 --- /dev/null +++ b/src/Oms.Domain/ChannelsAggregate/Consts/PricingWorkbenchCodes.cs @@ -0,0 +1,19 @@ +namespace Oms.Domain.ChannelsAggregate.Consts; + +/// +/// 定价工作台权限码(与前端 pageButtonCatalog / menuPermission 对齐)。 +/// +public static class PricingWorkbenchCodes +{ + /// 菜单与查询。 + public const string Query = "Channel.PricingWorkbench.Query"; + + /// 预览合成卖价草稿。 + public const string Preview = "Channel.PricingWorkbench.Preview"; + + /// 回写销售产品草稿卖价。 + public const string Apply = "Channel.PricingWorkbench.Apply"; + + /// AI 辅助调规则 / 差异说明。 + public const string AiAssist = "Channel.PricingWorkbench.AiAssist"; +}