feat: 定价工作台买价反推卖价预览与草稿回写
All checks were successful
Build and Deploy / deploy (push) Successful in 1m16s
All checks were successful
Build and Deploy / deploy (push) Successful in 1m16s
支持多渠道最低买价对齐合成、毛利率硬计算预览,以及回写销售产品草稿卖价(不自动发布)。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
8a4a0787cd
commit
d1beefb2be
23
docs/定价工作台.md
Normal file
23
docs/定价工作台.md
Normal file
@ -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`。渠道模块其它接口同样主要靠前端菜单权限;本服务未强制服务端拦截,避免未同步权限码时不可用。
|
||||
276
src/Oms.Application/Dtos/Channels/PricingWorkbenchDtos.cs
Normal file
276
src/Oms.Application/Dtos/Channels/PricingWorkbenchDtos.cs
Normal file
@ -0,0 +1,276 @@
|
||||
namespace Oms.Application.Dtos.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 定价工作台:渠道买价摘要(多选拼盘)。
|
||||
/// </summary>
|
||||
public class PricingWorkbenchChannelSummaryOutput
|
||||
{
|
||||
/// <summary>服务渠道主键。</summary>
|
||||
public int ServiceChannelId { get; set; }
|
||||
|
||||
/// <summary>渠道名称。</summary>
|
||||
public string ChannelName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>币种(取首个启用价格项)。</summary>
|
||||
public string Currency { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>费用项。</summary>
|
||||
public string CostItem { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>价格项名称。</summary>
|
||||
public string PriceName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>分区数量(去重)。</summary>
|
||||
public int ZoneCount { get; set; }
|
||||
|
||||
/// <summary>重量段数量(去重)。</summary>
|
||||
public int WeightSegmentCount { get; set; }
|
||||
|
||||
/// <summary>明细格数。</summary>
|
||||
public int DetailCount { get; set; }
|
||||
|
||||
/// <summary>是否来自已发布买价快照。</summary>
|
||||
public bool FromPublishedSnapshot { get; set; }
|
||||
|
||||
/// <summary>最近发布时间(有快照时)。</summary>
|
||||
public DateTime? LastPublishTime { get; set; }
|
||||
|
||||
/// <summary>发布版本号。</summary>
|
||||
public string? PublishVersion { get; set; }
|
||||
|
||||
/// <summary>无快照时读草稿的警告。</summary>
|
||||
public string? Warning { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 定价工作台预览入参。
|
||||
/// </summary>
|
||||
public class PricingWorkbenchPreviewInput
|
||||
{
|
||||
/// <summary>参与合成的服务渠道主键列表。</summary>
|
||||
public List<int> ServiceChannelIds { get; set; } = [];
|
||||
|
||||
/// <summary>默认毛利率(0~1,例 0.25 = 25%)。</summary>
|
||||
public decimal MarginRate { get; set; } = 0.25m;
|
||||
|
||||
/// <summary>按分区覆盖毛利率(key=分区键)。</summary>
|
||||
public Dictionary<string, decimal>? ZoneMarginRates { get; set; }
|
||||
|
||||
/// <summary>按重量带覆盖毛利率(key=重量段文本)。</summary>
|
||||
public Dictionary<string, decimal>? WeightMarginRates { get; set; }
|
||||
|
||||
/// <summary>排除的渠道(AI 调规则后重算)。</summary>
|
||||
public List<int>? ExcludeChannelIds { get; set; }
|
||||
|
||||
/// <summary>可选:限定费用项;为空则各渠道取首个启用价格项。</summary>
|
||||
public string? CostItem { get; set; }
|
||||
|
||||
/// <summary>金额小数位(默认 2,向上取分)。</summary>
|
||||
public int MoneyScale { get; set; } = 2;
|
||||
|
||||
/// <summary>
|
||||
/// 相对现网卖价差异阈值(绝对值比例,例 0.15=15%);大于阈值的格进入风险列表。
|
||||
/// </summary>
|
||||
public decimal DiffThreshold { get; set; } = 0.15m;
|
||||
|
||||
/// <summary>可选:对比用的销售产品(填了才算现网卖价差异)。</summary>
|
||||
public int? CompareSalesProductId { get; set; }
|
||||
|
||||
/// <summary>可选:对比用的卖价价格项。</summary>
|
||||
public int? ComparePriceId { get; set; }
|
||||
|
||||
/// <summary>对比客户组键(CustomerGroupValues 的 key)。</summary>
|
||||
public string? CompareCustomerGroupKey { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 定价工作台预览出参。
|
||||
/// </summary>
|
||||
public class PricingWorkbenchPreviewOutput
|
||||
{
|
||||
/// <summary>合成币种。</summary>
|
||||
public string Currency { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>实际使用的毛利率(默认)。</summary>
|
||||
public decimal MarginRate { get; set; }
|
||||
|
||||
/// <summary>成本策略说明。</summary>
|
||||
public string CostStrategy { get; set; } = "min";
|
||||
|
||||
/// <summary>参与渠道摘要。</summary>
|
||||
public List<PricingWorkbenchChannelSummaryOutput> Channels { get; set; } = [];
|
||||
|
||||
/// <summary>对齐后的分区键(行)。</summary>
|
||||
public List<string> Zones { get; set; } = [];
|
||||
|
||||
/// <summary>对齐后的重量段文本(列,左开右闭区间)。</summary>
|
||||
public List<string> WeightSegments { get; set; } = [];
|
||||
|
||||
/// <summary>单元格(成本/建议卖价/来源)。</summary>
|
||||
public List<PricingWorkbenchCellOutput> Cells { get; set; } = [];
|
||||
|
||||
/// <summary>阻断级问题(如币种不一致)。</summary>
|
||||
public List<string> Blockers { get; set; } = [];
|
||||
|
||||
/// <summary>警告(无快照、无法安全对齐等)。</summary>
|
||||
public List<string> Warnings { get; set; } = [];
|
||||
|
||||
/// <summary>相对现网卖价超阈值的差异行。</summary>
|
||||
public List<PricingWorkbenchDiffRiskOutput> DiffRisks { get; set; } = [];
|
||||
|
||||
/// <summary>简短中文说明(可供 AI 报告引用)。</summary>
|
||||
public string Summary { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>审计摘要(渠道、毛利、策略)。</summary>
|
||||
public PricingWorkbenchAuditInfo Audit { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 预览矩阵单元格。
|
||||
/// </summary>
|
||||
public class PricingWorkbenchCellOutput
|
||||
{
|
||||
/// <summary>分区键。</summary>
|
||||
public string Zone { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>重量段文本。</summary>
|
||||
public string WeightSegment { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>成本底价(最低买价);无报价时为空。</summary>
|
||||
public decimal? BuyPrice { get; set; }
|
||||
|
||||
/// <summary>建议卖价。</summary>
|
||||
public decimal? SellPrice { get; set; }
|
||||
|
||||
/// <summary>实际使用的毛利率。</summary>
|
||||
public decimal? AppliedMarginRate { get; set; }
|
||||
|
||||
/// <summary>反校验毛利率 (sell-buy)/sell。</summary>
|
||||
public decimal? VerifiedMargin { get; set; }
|
||||
|
||||
/// <summary>最低买价来源渠道。</summary>
|
||||
public int? SourceChannelId { get; set; }
|
||||
|
||||
/// <summary>来源渠道名。</summary>
|
||||
public string? SourceChannelName { get; set; }
|
||||
|
||||
/// <summary>计算公式(继承自来源买价明细)。</summary>
|
||||
public string CalculationFormula { get; set; } = "unit";
|
||||
|
||||
/// <summary>无报价 / 对齐失败等标记。</summary>
|
||||
public string? Flag { get; set; }
|
||||
|
||||
/// <summary>相对现网卖价涨跌幅(有对比时)。</summary>
|
||||
public decimal? OnlineDeltaRatio { get; set; }
|
||||
|
||||
/// <summary>现网卖价。</summary>
|
||||
public decimal? OnlineSellPrice { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 相对现网卖价的差异风险行。
|
||||
/// </summary>
|
||||
public class PricingWorkbenchDiffRiskOutput
|
||||
{
|
||||
/// <summary>分区。</summary>
|
||||
public string Zone { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>重量段。</summary>
|
||||
public string WeightSegment { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>现网卖价。</summary>
|
||||
public decimal? OnlineSell { get; set; }
|
||||
|
||||
/// <summary>建议卖价。</summary>
|
||||
public decimal? SuggestedSell { get; set; }
|
||||
|
||||
/// <summary>涨跌幅(建议相对现网)。</summary>
|
||||
public decimal DeltaRatio { get; set; }
|
||||
|
||||
/// <summary>风险说明。</summary>
|
||||
public string Message { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审计信息。
|
||||
/// </summary>
|
||||
public class PricingWorkbenchAuditInfo
|
||||
{
|
||||
/// <summary>操作时间(UTC 本地服务器时间)。</summary>
|
||||
public DateTime OperatedAt { get; set; }
|
||||
|
||||
/// <summary>操作人用户 Id。</summary>
|
||||
public int OperatorUserId { get; set; }
|
||||
|
||||
/// <summary>参与渠道 Id。</summary>
|
||||
public List<int> ServiceChannelIds { get; set; } = [];
|
||||
|
||||
/// <summary>排除渠道 Id。</summary>
|
||||
public List<int> ExcludeChannelIds { get; set; } = [];
|
||||
|
||||
/// <summary>默认毛利率。</summary>
|
||||
public decimal MarginRate { get; set; }
|
||||
|
||||
/// <summary>成本策略。</summary>
|
||||
public string CostStrategy { get; set; } = "min";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 回写销售产品草稿卖价入参。
|
||||
/// </summary>
|
||||
public class PricingWorkbenchApplyInput
|
||||
{
|
||||
/// <summary>预览入参(服务端按相同规则重算,不以客户端数字为唯一真相)。</summary>
|
||||
public PricingWorkbenchPreviewInput Preview { get; set; } = new();
|
||||
|
||||
/// <summary>目标销售产品。</summary>
|
||||
public int SalesProductId { get; set; }
|
||||
|
||||
/// <summary>目标价格项;为空则新建一条运费价。</summary>
|
||||
public int? PriceId { get; set; }
|
||||
|
||||
/// <summary>新建时价格项名称。</summary>
|
||||
public string? PriceName { get; set; }
|
||||
|
||||
/// <summary>新建时费用项(默认 freight)。</summary>
|
||||
public string? CostItem { get; set; }
|
||||
|
||||
/// <summary>新建时计费单位。</summary>
|
||||
public string? CostUnit { get; set; }
|
||||
|
||||
/// <summary>客户组键(写入 CustomerGroupValues)。</summary>
|
||||
public string CustomerGroupKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>可选:AI/人工说明,写入审计日志。</summary>
|
||||
public string? AnalysisNote { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 可选:前端编辑后的卖价覆盖(仅覆盖有值的格;仍须通过服务端重算校验结构)。
|
||||
/// key = zone|weightSegment。
|
||||
/// </summary>
|
||||
public Dictionary<string, decimal>? SellOverrides { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 回写出参。
|
||||
/// </summary>
|
||||
public class PricingWorkbenchApplyOutput
|
||||
{
|
||||
/// <summary>销售产品 Id。</summary>
|
||||
public int SalesProductId { get; set; }
|
||||
|
||||
/// <summary>写入的价格项 Id。</summary>
|
||||
public int PriceId { get; set; }
|
||||
|
||||
/// <summary>写入明细行数。</summary>
|
||||
public int DetailCount { get; set; }
|
||||
|
||||
/// <summary>是否新建价格项。</summary>
|
||||
public bool CreatedPrice { get; set; }
|
||||
|
||||
/// <summary>提示:未发布,需走销售产品现有发布/审批。</summary>
|
||||
public string Message { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>审计信息。</summary>
|
||||
public PricingWorkbenchAuditInfo Audit { get; set; } = new();
|
||||
}
|
||||
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 定价工作台硬计算:分区/重量段对齐、最低买价合成、毛利率反推卖价。
|
||||
/// AI 只调规则后调用本类重算,禁止模型数字当唯一真相。
|
||||
/// </summary>
|
||||
public static class PricingWorkbenchCalculator
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 卖价 = 买价 ÷ (1 - 毛利率),向上取到指定小数位(默认分)。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 反校验毛利率 (sell - buy) / sell。
|
||||
/// </summary>
|
||||
public static decimal CalcVerifiedMargin(decimal sell, decimal buy)
|
||||
{
|
||||
if (sell <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.Round((sell - buy) / sell, 6, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从明细因子字典取分区键。
|
||||
/// </summary>
|
||||
public static bool TryGetZone(Dictionary<string, string> factors, out string zone) =>
|
||||
TryGetFactor(factors, out zone, "分区", "价格分区", "zone");
|
||||
|
||||
/// <summary>
|
||||
/// 从明细因子字典取重量段文本。
|
||||
/// </summary>
|
||||
public static bool TryGetWeight(Dictionary<string, string> factors, out string weight) =>
|
||||
TryGetFactor(factors, out weight, "重量", "weight");
|
||||
|
||||
/// <summary>
|
||||
/// 解析 FactorValuesJson 为字典。
|
||||
/// </summary>
|
||||
public static Dictionary<string, string> ParseFactors(object? factorValuesJson)
|
||||
{
|
||||
if (factorValuesJson == null)
|
||||
{
|
||||
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
if (factorValuesJson is JsonElement element)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return element.EnumerateObject()
|
||||
.ToDictionary(x => x.Name, x => x.Value.ToString(), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
if (factorValuesJson is Dictionary<string, string> dict)
|
||||
{
|
||||
return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
if (factorValuesJson is IDictionary<string, object> 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<Dictionary<string, string>>(json, JsonOptions)
|
||||
?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从客户组取值中解析指定键的价格。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析明细金额:优先 CalculatedValue,否则客户组首价。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重量段边界取并集,生成细段文本列表(左开右闭展示为 start-end)。
|
||||
/// </summary>
|
||||
public static List<string> BuildAlignedWeightSegments(IEnumerable<string> rawSegments)
|
||||
{
|
||||
var bounds = new SortedSet<decimal>();
|
||||
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<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 格式化重量段。
|
||||
/// </summary>
|
||||
public static string FormatWeightSegment(decimal start, decimal end) =>
|
||||
$"{TrimDecimal(start)}-{TrimDecimal(end)}";
|
||||
|
||||
/// <summary>
|
||||
/// 在原段列表中查找覆盖细段中点的买价格。
|
||||
/// </summary>
|
||||
public static bool TryResolvePriceForSegment(
|
||||
IReadOnlyList<SourceBuyCell> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析分区毛利覆盖。
|
||||
/// </summary>
|
||||
public static decimal ResolveMarginRate(
|
||||
decimal defaultRate,
|
||||
string zone,
|
||||
string weightSegment,
|
||||
IReadOnlyDictionary<string, decimal>? zoneRates,
|
||||
IReadOnlyDictionary<string, decimal>? 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<string, string> 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<string, decimal> ParseDecimalMap(object? raw)
|
||||
{
|
||||
var result = new Dictionary<string, decimal>(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<Dictionary<string, decimal>>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渠道侧原始买价格。
|
||||
/// </summary>
|
||||
public readonly record struct SourceBuyCell(
|
||||
int ChannelId,
|
||||
string ChannelName,
|
||||
string Zone,
|
||||
string WeightSegment,
|
||||
decimal BuyPrice,
|
||||
string CalculationFormula);
|
||||
}
|
||||
816
src/Oms.Application/Services/Channels/PricingWorkbenchService.cs
Normal file
816
src/Oms.Application/Services/Channels/PricingWorkbenchService.cs
Normal file
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 定价工作台:多渠道买价对齐合成 → 毛利率反推卖价草稿 → 回写销售产品(不自动发布)。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Channel")]
|
||||
public class PricingWorkbenchService : ApplicationService
|
||||
{
|
||||
private const string PriceOperatorType = "price";
|
||||
private const string CostStrategyMin = "min";
|
||||
|
||||
private IServiceChannelRepository ServiceChannelRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IServiceChannelRepository>();
|
||||
|
||||
private ISalesProductRepository SalesProductRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ISalesProductRepository>();
|
||||
|
||||
private SalesProductService SalesProductAppService =>
|
||||
LazyServiceProvider.GetRequiredService<SalesProductService>();
|
||||
|
||||
private ILogger WorkbenchLogger =>
|
||||
LazyServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(PricingWorkbenchService));
|
||||
|
||||
/// <summary>
|
||||
/// 批量查询渠道买价摘要(优先已发布快照;无快照则读草稿并警告)。
|
||||
/// </summary>
|
||||
/// <param name="serviceChannelIds">服务渠道主键,逗号分隔或重复 query。</param>
|
||||
[HttpGet("/channel/pricing-workbench/channel-summaries")]
|
||||
public async Task<List<PricingWorkbenchChannelSummaryOutput>> GetChannelSummariesAsync(
|
||||
[FromQuery] string? serviceChannelIds)
|
||||
{
|
||||
var ids = ParseIdList(serviceChannelIds);
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var result = new List<PricingWorkbenchChannelSummaryOutput>();
|
||||
foreach (var id in ids.Distinct())
|
||||
{
|
||||
var loaded = await LoadChannelPriceAsync(id, costItem: null);
|
||||
result.Add(loaded.Summary);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 预览:对齐分区/重量段,最低买价合成,按毛利率硬计算建议卖价;可选对比现网卖价差异。
|
||||
/// </summary>
|
||||
/// <param name="input">渠道列表、毛利率、排除渠道、对比目标等。</param>
|
||||
/// <returns>对齐后的成本/卖价矩阵;币种不一致时 blockers 阻断。</returns>
|
||||
[HttpPost("/channel/pricing-workbench/preview")]
|
||||
public async Task<PricingWorkbenchPreviewOutput> PreviewAsync(PricingWorkbenchPreviewInput input)
|
||||
{
|
||||
return await BuildPreviewAsync(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将预览结果回写到销售产品草稿卖价(指定客户组);不发布,需走现有发布/审批。
|
||||
/// </summary>
|
||||
/// <param name="input">预览参数 + 目标销售产品/价格项/客户组。</param>
|
||||
/// <returns>写入的价格项与审计信息。</returns>
|
||||
[HttpPost("/channel/pricing-workbench/apply")]
|
||||
public async Task<PricingWorkbenchApplyOutput> 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<PricingWorkbenchPreviewOutput> 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<int>(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<LoadedChannelPrice>();
|
||||
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<PricingWorkbenchCalculator.SourceBuyCell>();
|
||||
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<LoadedChannelPrice> 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<ChannelPriceDetailOutput> 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<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var weights = new HashSet<string>(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<Dictionary<string, decimal>> LoadOnlineSellMapAsync(
|
||||
int? salesProductId,
|
||||
int? priceId,
|
||||
string? customerGroupKey)
|
||||
{
|
||||
var map = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);
|
||||
if (salesProductId is not > 0)
|
||||
{
|
||||
return map;
|
||||
}
|
||||
|
||||
List<ChannelPriceDetailOutput> 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<List<SalesProductPriceSaveInput>> 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<List<string>>(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<string, decimal>? sellOverrides)
|
||||
{
|
||||
EnsureFactors(target, preview, customerGroupKey);
|
||||
|
||||
var detailByKey = new Dictionary<string, ChannelPriceDetailInput>(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<string, string>
|
||||
{
|
||||
["分区"] = cell.Zone,
|
||||
["重量"] = cell.WeightSegment
|
||||
},
|
||||
CalculationFormula = string.IsNullOrWhiteSpace(cell.CalculationFormula)
|
||||
? "unit"
|
||||
: cell.CalculationFormula,
|
||||
CalculatedValue = sell,
|
||||
CustomerGroupValues = new Dictionary<string, decimal>()
|
||||
};
|
||||
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<string> 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<string>(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<string, decimal> ToMutableDecimalMap(object? raw)
|
||||
{
|
||||
var result = new Dictionary<string, decimal>(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<string, decimal> dict)
|
||||
{
|
||||
foreach (var pair in dict)
|
||||
{
|
||||
result[pair.Key] = pair.Value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = JsonSerializer.Serialize(raw);
|
||||
var map = JsonSerializer.Deserialize<Dictionary<string, decimal>>(json);
|
||||
if (map != null)
|
||||
{
|
||||
foreach (var pair in map)
|
||||
{
|
||||
result[pair.Key] = pair.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignore
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static PricePick? PickPriceItem(List<PricePick> prices, string? costItem)
|
||||
{
|
||||
IEnumerable<PricePick> 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<int>();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<int> 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<ChannelPriceDetailOutput> Details);
|
||||
|
||||
private sealed record PricePick(
|
||||
int SerialNumber,
|
||||
byte Status,
|
||||
string PriceName,
|
||||
string CostItem,
|
||||
string Currency,
|
||||
List<ChannelPriceDetailOutput> Details);
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
namespace Oms.Domain.ChannelsAggregate.Consts;
|
||||
|
||||
/// <summary>
|
||||
/// 定价工作台权限码(与前端 pageButtonCatalog / menuPermission 对齐)。
|
||||
/// </summary>
|
||||
public static class PricingWorkbenchCodes
|
||||
{
|
||||
/// <summary>菜单与查询。</summary>
|
||||
public const string Query = "Channel.PricingWorkbench.Query";
|
||||
|
||||
/// <summary>预览合成卖价草稿。</summary>
|
||||
public const string Preview = "Channel.PricingWorkbench.Preview";
|
||||
|
||||
/// <summary>回写销售产品草稿卖价。</summary>
|
||||
public const string Apply = "Channel.PricingWorkbench.Apply";
|
||||
|
||||
/// <summary>AI 辅助调规则 / 差异说明。</summary>
|
||||
public const string AiAssist = "Channel.PricingWorkbench.AiAssist";
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user