OEM 分级

佣金价格设置 数据库存放修改
This commit is contained in:
chfei committed 2026-11-17 19:10:29 +08:00
1 parent ea0cbd6b92
commit 2de3d0dc92
24 files changed
+1224 -10

No files matched your search

+3 -1
View File
@@ -37,12 +37,13 @@ namespace KJD_Web.BLL.WXXD
var oem_id = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_id")?.Replace("'", "\\'")); var oem_id = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_id")?.Replace("'", "\\'"));
var oem_name = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_name")?.Replace("'", "\\'")); var oem_name = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_name")?.Replace("'", "\\'"));
var oem_owner = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_owner")?.Replace("'", "\\'")); var oem_owner = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_owner")?.Replace("'", "\\'"));
var parent_oemid = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "parent_oemid")?.Replace("'", "\\'"));
if (oem_id.IsNullOrEmpty() || oem_name.IsNullOrEmpty()) if (oem_id.IsNullOrEmpty() || oem_name.IsNullOrEmpty())
return "{\"code\":500,\"msg\":\"oem信息不能为空\"}"; return "{\"code\":500,\"msg\":\"oem信息不能为空\"}";
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString; string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
MysqlUtils mySql = new MysqlUtils(conn); MysqlUtils mySql = new MysqlUtils(conn);
string sql = "INSERT INTO wxxd.oem (oem_id,oem_name,oem_owner) VALUES('" + oem_id + "','" + oem_name + "','" + oem_owner + "')" + string sql = "INSERT INTO wxxd.oem (oem_id,oem_name,oem_owner,parent_oem_id) VALUES('" + oem_id + "','" + oem_name + "','" + oem_owner + "','" + parent_oemid + "')" +
"ON DUPLICATE KEY UPDATE oem_name=VALUES(oem_name),oem_owner=VALUES(oem_owner);"; "ON DUPLICATE KEY UPDATE oem_name=VALUES(oem_name),oem_owner=VALUES(oem_owner);";
var rst = mySql.ExecuteAffectedRows(sql); var rst = mySql.ExecuteAffectedRows(sql);
@@ -135,6 +136,7 @@ namespace KJD_Web.BLL.WXXD
oem_img = null, oem_img = null,
oem_name = row["oem_name"].ParseToString(), oem_name = row["oem_name"].ParseToString(),
oem_owner = row["oem_owner"].ParseToString(), oem_owner = row["oem_owner"].ParseToString(),
parent_oem_id = row["parent_oem_id"].ParseToString(),
available_balance = row.Table.Columns.Contains("available_balance") ? row["available_balance"].ParseToLong() : 0, available_balance = row.Table.Columns.Contains("available_balance") ? row["available_balance"].ParseToLong() : 0,
frozen_balance = row.Table.Columns.Contains("frozen_balance") ? row["frozen_balance"].ParseToLong() : 0, frozen_balance = row.Table.Columns.Contains("frozen_balance") ? row["frozen_balance"].ParseToLong() : 0,
total_rebate_amount = row.Table.Columns.Contains("total_rebate_amount") ? row["total_rebate_amount"].ParseToLong() : 0, total_rebate_amount = row.Table.Columns.Contains("total_rebate_amount") ? row["total_rebate_amount"].ParseToLong() : 0,
+30 -1
View File
@@ -1,10 +1,14 @@
using KJD_Web.Model; using KJD_Web.Model;
using KJD_Web.Model.PddModel; using KJD_Web.Model.PddModel;
using KJD_Web.Model.WxModel; using KJD_Web.Model.WxModel;
using KJD_Web.Services.Users;
using KJD_Web.Utils; using KJD_Web.Utils;
using MAX.Core.DependencyInjection;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using Mysqlx.Crud; using Mysqlx.Crud;
using NaiBa.Util.Extension; using NaiBa.Util.Extension;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
@@ -14,13 +18,18 @@ using System.Reflection;
using System.Threading; using System.Threading;
using System.Web; using System.Web;
using System.Web.ApplicationServices; using System.Web.ApplicationServices;
using System.Web.Http;
using System.Web.Security; using System.Web.Security;
using System.Web.UI.WebControls; using System.Web.UI.WebControls;
namespace KJD_Web.BLL.WXXD namespace KJD_Web.BLL.WXXD
{ {
public class WXUserManage public class WXUserManage : ITransientDependency
{ {
public WXUserManage()
{
_userService =(UserService) GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(UserService));
}
public static bool GetSign(string signData, bool isUserLogin = false) public static bool GetSign(string signData, bool isUserLogin = false)
{ {
if (string.IsNullOrEmpty(signData)) { return false; } if (string.IsNullOrEmpty(signData)) { return false; }
@@ -45,6 +54,8 @@ namespace KJD_Web.BLL.WXXD
public static DateTime dtAuthorizationExpireTime = DateTime.Now; public static DateTime dtAuthorizationExpireTime = DateTime.Now;
public static string e57Authorization = ""; public static string e57Authorization = "";
private readonly UserService _userService;
public string GetE57Authorization(string inputData) public string GetE57Authorization(string inputData)
{ {
if (!string.IsNullOrEmpty(inputData)) if (!string.IsNullOrEmpty(inputData))
@@ -590,6 +601,24 @@ namespace KJD_Web.BLL.WXXD
} }
userList.Add(user); userList.Add(user);
} }
#region 返回新的OEM加价
var mainUsers = userList.Where(a => a.group_id == "3").ToList();
var prices = _userService.GetUserFinalPrices(mainUsers.Select(a => new UserEntity
{
UserName = a.user_name,
OemId = a.oem_id
}));
foreach (var user in mainUsers)
{
var userPrices = prices[user.user_name];
// 批量价格单位为分,旧版列表字段单位为元。
user.postage_per_order = userPrices[UserPaymentTypes.中转仓扣费支出] / 100m;
user.refund_postage_per_order = userPrices[UserPaymentTypes.退货包裹扣费支出] / 100m;
user.gift_oem_amount_per_order = userPrices[UserPaymentTypes.礼物单支出] / 100m;
user.sync_logistics_per_order = userPrices[UserPaymentTypes.同步物流] / 100m;
}
#endregion
var data = JsonUtils.SerializeObjectToString(userList); var data = JsonUtils.SerializeObjectToString(userList);
return "{\"code\":200,\"msg\":\"success\",\"data\":" + data + ",\"count\":" + count + "}"; return "{\"code\":200,\"msg\":\"success\",\"data\":" + data + ",\"count\":" + count + "}";
} }
@@ -3,6 +3,8 @@ using KJD_Web.BLL.WXXD;
using KJD_Web.Requests.Users; using KJD_Web.Requests.Users;
using KJD_Web.Utils; using KJD_Web.Utils;
using NaiBa.Util.Extension; using NaiBa.Util.Extension;
using Org.BouncyCastle.Asn1.Ocsp;
using Store.Contracts.User.Enums;
using Store.Framework.Dtos; using Store.Framework.Dtos;
using Store.Framework.Models; using Store.Framework.Models;
using System; using System;
@@ -24,7 +26,12 @@ namespace KJD_Web.Controllers
[Route("{action}")] [Route("{action}")]
public partial class WXUserController : AsmxApiController public partial class WXUserController : AsmxApiController
{ {
private readonly WXUserManage _wxUserManage;
public WXUserController(WXUserManage wxUserManage)
{
_wxUserManage = wxUserManage;
}
//GetE57Authorization //GetE57Authorization
public IHttpActionResult get_e57_authorization() public IHttpActionResult get_e57_authorization()
{ {
@@ -134,8 +141,18 @@ namespace KJD_Web.Controllers
if (uu != true) if (uu != true)
{ {
var result = new WXUserManage().UpdateUser(inputData); try
return JsonString(result); {
var result = new WXUserManage().UpdateUser(inputData);
_userService.SetMarkupRule(inputData);
return JsonString(result);
}
catch (Exception ex)
{
return Ok(ApiResult.Fail(ex.Message));
}
} }
else else
{ {
@@ -25,6 +25,72 @@ namespace KJD_Web.Controllers
_userService = userService ?? throw new ArgumentNullException(nameof(userService)); _userService = userService ?? throw new ArgumentNullException(nameof(userService));
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger = logger ?? throw new ArgumentNullException(nameof(logger));
} }
[HttpPost]
public IHttpActionResult SetMarkupRule(SetMarkupRuleRequest request)
{
if (!ValidateSign(request)) return Ok(ApiResult.Fail("校验失败", 999));
try
{
if (request.TargetType == Store.Contracts.User.Enums.OEMMarkupTargetType.OEM)
{
request.PaymentType = Store.Contracts.User.Enums.UserPaymentTypes.中转仓扣费支出;
_userService.SetMarkupRule(request);
request.PaymentType = Store.Contracts.User.Enums.UserPaymentTypes.退货包裹扣费支出;
_userService.SetMarkupRule(request);
request.PaymentType = Store.Contracts.User.Enums.UserPaymentTypes.礼物单支出;
_userService.SetMarkupRule(request);
request.PaymentType = Store.Contracts.User.Enums.UserPaymentTypes.同步物流;
_userService.SetMarkupRule(request);
}
else
{
_userService.SetMarkupRule(request);
}
return Ok(ApiResult.Success("加价规则设置成功"));
}
catch (UnauthorizedAccessException ex)
{
return Ok(ApiResult.Fail(ex.Message, ResultCode.Forbidden));
}
catch (ArgumentException ex)
{
return Ok(ApiResult.Fail(ex.Message, ResultCode.ValidationError));
}
catch (InvalidOperationException ex)
{
return Ok(ApiResult.Fail(ex.Message, ResultCode.BusinessError));
}
catch (Exception ex)
{
_logger.Error(ex, "设置加价规则失败, UserName=" + request.UserName + ", TargetId=" + request.TargetId);
return Ok(ApiResult.Fail("设置加价规则失败,请稍后重试", ResultCode.ServerError));
}
}
[HttpPost]
public IHttpActionResult GetUserMarkups( GetUserMarkupsRequest request)
{
//if (!ValidateSign(request)) return Ok(ApiResult.Fail("校验失败", 999));
//if (!ModelState.IsValid) return Ok(ApiResult.Fail("请求参数格式错误", ResultCode.ValidationError));
try
{
return Ok(ApiResult.Success(data: _userService.GetUserMarkups(request.UserName, request.PaymentType)));
}
catch (ArgumentException ex)
{
return Ok(ApiResult.Fail(ex.Message, ResultCode.ValidationError));
}
catch (InvalidOperationException ex)
{
return Ok(ApiResult.Fail(ex.Message, ResultCode.BusinessError));
}
catch (Exception ex)
{
_logger.Error(ex, "查询代理加价失败, UserName=" + request.UserName);
return Ok(ApiResult.Fail("查询代理加价失败,请稍后重试", ResultCode.ServerError));
}
}
[HttpPost] [HttpPost]
public IHttpActionResult GetUserConfig(SignRequestBase request) public IHttpActionResult GetUserConfig(SignRequestBase request)
{ {
+1 -1
View File
@@ -36,7 +36,7 @@ namespace KJD_Web
// 让 Web API 用 Autofac 解析 Controller // 让 Web API 用 Autofac 解析 Controller
GlobalConfiguration.Configuration.DependencyResolver = GlobalConfiguration.Configuration.DependencyResolver =
new AutofacWebApiDependencyResolver(container); new AutofacWebApiDependencyResolver(container);
bool BackgroundJobs = System.Configuration.ConfigurationManager.AppSettings["BackgroundJobs"].ParseToBool(); bool BackgroundJobs = System.Configuration.ConfigurationManager.AppSettings["BackgroundJobs"].ParseToBool();
if (BackgroundJobs) if (BackgroundJobs)
{ {
+5 -1
View File
@@ -231,6 +231,9 @@
<Compile Include="Requests\Users\PurchaseImageQuotaRequest.cs" /> <Compile Include="Requests\Users\PurchaseImageQuotaRequest.cs" />
<Compile Include="Requests\Users\RebateRecordRequest.cs" /> <Compile Include="Requests\Users\RebateRecordRequest.cs" />
<Compile Include="Requests\Users\UserConfigRequest.cs" /> <Compile Include="Requests\Users\UserConfigRequest.cs" />
<Compile Include="Requests\Users\SetMarkupRuleRequest.cs" />
<Compile Include="Requests\Users\GetUserMarkupsRequest.cs" />
<Compile Include="Responses\Users\UserMarkupResponse.cs" />
<Compile Include="Responses\Shops\ShopOrderDetailResponse.cs" /> <Compile Include="Responses\Shops\ShopOrderDetailResponse.cs" />
<Compile Include="Responses\Shops\ShopStatsResponse.cs" /> <Compile Include="Responses\Shops\ShopStatsResponse.cs" />
<Compile Include="Responses\Shops\ShopStatsTrendResponse.cs" /> <Compile Include="Responses\Shops\ShopStatsTrendResponse.cs" />
@@ -284,6 +287,7 @@
<Compile Include="Services\Shops\ShopService.cs" /> <Compile Include="Services\Shops\ShopService.cs" />
<Compile Include="Services\Shops\ShopStatsJob.cs" /> <Compile Include="Services\Shops\ShopStatsJob.cs" />
<Compile Include="Services\Users\UserService.FeeRecord.cs" /> <Compile Include="Services\Users\UserService.FeeRecord.cs" />
<Compile Include="Services\Users\OEMMarkupBaseFeeSettings.cs" />
<Compile Include="Services\Users\UserService.OEM.cs" /> <Compile Include="Services\Users\UserService.OEM.cs" />
<Compile Include="Services\Users\UserService.cs" /> <Compile Include="Services\Users\UserService.cs" />
<Compile Include="SignValidateFilterAttribute.cs" /> <Compile Include="SignValidateFilterAttribute.cs" />
@@ -400,4 +404,4 @@
<Target Name="AfterBuild"> <Target Name="AfterBuild">
</Target> </Target>
--> -->
</Project> </Project>
+1
View File
@@ -11,6 +11,7 @@ namespace KJD_Web.Model.WxModel
public string oem_id { get; set; } public string oem_id { get; set; }
public string oem_name { get; set; } public string oem_name { get; set; }
public string oem_owner { get; set; } public string oem_owner { get; set; }
public string parent_oem_id { get; set; }
public string oem_icon { get; set; } public string oem_icon { get; set; }
public string oem_img { get; set; } public string oem_img { get; set; }
public DateTime add_time { get; set; } public DateTime add_time { get; set; }
@@ -0,0 +1,10 @@
using Store.Contracts.User.Enums;
using Store.Framework.Dtos;
namespace KJD_Web.Requests.Users;
/// <summary>按 user_name 和消费类型查询两级代理加价。</summary>
public class GetUserMarkupsRequest : SignRequestBase
{
public UserPaymentTypes PaymentType { get; set; }
}
@@ -0,0 +1,14 @@
using Store.Contracts.User.Enums;
using Store.Framework.Dtos;
namespace KJD_Web.Requests.Users;
public class SetMarkupRuleRequest : SignRequestBase
{
public OEMMarkupTargetType TargetType { get; set; }
/// <summary>用户规则传主账号用户名,OEM 规则传目标 OEM ID。</summary>
public string TargetId { get; set; }
public UserPaymentTypes PaymentType { get; set; }
/// <summary>加价金额,单位:分;必须传入,0 表示不加价。</summary>
public int? Markup { get; set; }
}
@@ -0,0 +1,11 @@
namespace KJD_Web.Responses.Users;
public class UserMarkupResponse
{
/// <summary>1:上级代理对所属 OEM 的加价;2:所属 OEM 对用户的加价。</summary>
public int Level { get; set; }
/// <summary>该级代理的 OEM ID;不存在对应代理时为 null。</summary>
public string OemId { get; set; }
/// <summary>加价金额,单位:分;未设置时为 0。</summary>
public int Markup { get; set; }
}
@@ -0,0 +1,32 @@
using Store.Contracts.User.Enums;
using System;
using System.Configuration;
using System.Globalization;
namespace KJD_Web.Services.Users;
/// <summary>从 appSettings 读取每单基础费用,单位:分。</summary>
public static class OEMMarkupBaseFeeSettings
{
public static int PostagePerOrder => ReadFee("postage_per_order");
public static int RefundPostagePerOrder => ReadFee("refund_postage_per_order");
public static int GiftOemAmountPerOrder => ReadFee("gift_oem_amount_per_order");
public static int SyncLogisticsPerOrder => ReadFee("sync_logistics_per_order");
public static int GetBaseFee(UserPaymentTypes paymentType) => paymentType switch
{
UserPaymentTypes.中转仓扣费支出 => PostagePerOrder,
UserPaymentTypes.退货包裹扣费支出 => RefundPostagePerOrder,
UserPaymentTypes.礼物单支出 => GiftOemAmountPerOrder,
UserPaymentTypes.同步物流 => SyncLogisticsPerOrder,
_ => throw new ArgumentOutOfRangeException(nameof(paymentType), "不支持的加价交易类型")
};
private static int ReadFee(string key)
{
if (!int.TryParse(ConfigurationManager.AppSettings[key], NumberStyles.Integer,
CultureInfo.InvariantCulture, out int fee) || fee < 0)
throw new ConfigurationErrorsException($"appSettings 配置项 '{key}' 必须为非负整数,单位:分。");
return fee;
}
}
@@ -1,10 +1,13 @@
using FreeSql.Internal.Model; using FreeSql.Internal.Model;
using KJD_Web.Model.WxModel;
using KJD_Web.Requests.Users; using KJD_Web.Requests.Users;
using KJD_Web.Responses.Users; using KJD_Web.Responses.Users;
using MAX.Core.DependencyInjection; using MAX.Core.DependencyInjection;
using Store.Contracts.User.Entitys; using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Web; using System.Web;
@@ -156,4 +159,393 @@ public partial class UserService
} }
return (list, total); return (list, total);
} }
/// <summary>
/// 获取父代理
/// </summary>
/// <param name="oemId"></param>
/// <param name="isCache"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public OEMEntity GetParentOem(string oemId, bool isCache = true)
{
if (string.IsNullOrEmpty(oemId)) throw new ArgumentNullException(nameof(oemId));
var oem = GetOEMByOemId(oemId, isCache);
if (oem == null) throw new Exception("错误的OEM");
if (string.IsNullOrEmpty(oem.ParentOemId)) return oem;
return GetOEMByOemId(oem.ParentOemId, isCache);
}
/// <summary>
/// 获取所有子代理
/// </summary>
/// <param name="oemId"></param>
/// <param name="isCache"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public List<OEMEntity> GetSubOems(string oemId, bool isCache = true)
{
if (string.IsNullOrEmpty(oemId)) throw new ArgumentNullException(nameof(oemId));
return OEMData.Where(a => a.ParentOemId == oemId).ToList();
}
#region 加价规则
private const string DefaultMarkupOemId = "00000000";
private static string GetMarkupOemId(string oemId) =>
string.IsNullOrWhiteSpace(oemId) ? DefaultMarkupOemId : oemId;
/// <summary>
/// 兼容旧版查询字符串:id 为目标用户ID,user_name 为操作人,费用单位为元。
/// 四个费用字段依次对应交易类型 20、26、16、55;二级加价为费用转分后减去基础费及一级 OEM 加价,未传字段不修改。
/// </summary>
/// <param name="inputData">旧版表单字符串;调用方须先完成签名和身份校验。</param>
public void SetMarkupRule(string inputData)
{
var (userId, actorUserName, fees) = ParseLegacyMarkupInput(inputData);
var requests = new List<SetMarkupRuleRequest>();
foreach (var (paymentType, amount) in fees)
{
int markup = amount - GetDefaultFloorPrice(paymentType);
if (markup < 0) throw new ArgumentException($"交易类型 {(int)paymentType} 的费用不能低于基础费");
requests.Add(new SetMarkupRuleRequest
{
UserName = actorUserName,
TargetType = OEMMarkupTargetType.User,
PaymentType = paymentType,
Markup = markup
});
}
if (requests.Count == 0) return;
_freeSql.Transaction(() =>
{
var user = _freeSql.Select<UserEntity>().Where(a => a.Id == userId).ForUpdate().First()
?? throw new InvalidOperationException("目标用户不存在");
var oemId = GetMarkupOemId(user.OemId);
var paymentTypes = requests.Select(a => a.PaymentType).ToArray();
var oemRules = _freeSql.Select<OEMMarkupRuleEntity>()
.Where(a => a.TargetType == OEMMarkupTargetType.OEM && a.TargetId == oemId
&& paymentTypes.Contains(a.PaymentType)).ForUpdate().ToList();
// 先校验所有消费类型,避免后面的金额不足时已保存前面的规则。
DeductOemMarkup(requests, oemRules, oemId);
foreach (var request in requests)
{
request.TargetId = user.UserName;
SetMarkupRule(request);
}
});
}
/// <summary>从已扣除基础费的金额中扣除一级 OEM 加价,得到要保存的二级用户加价。</summary>
private static void DeductOemMarkup(List<SetMarkupRuleRequest> requests, List<OEMMarkupRuleEntity> oemRules, string oemId)
{
foreach (var request in requests)
{
int oemMarkup = GetMarkup(oemRules, null, OEMMarkupTargetType.OEM, oemId, request.PaymentType);
int markup = checked(request.Markup.Value - oemMarkup);
if (markup < 0)
throw new ArgumentException($"交易类型 {request.PaymentType} 的费用不能低于基础费用");
request.Markup = markup;
}
}
private static (int UserId, string ActorUserName, List<(UserPaymentTypes PaymentType, int Amount)> Fees) ParseLegacyMarkupInput(string inputData)
{
if (string.IsNullOrWhiteSpace(inputData)) throw new ArgumentException("输入不能为空", nameof(inputData));
var values = HttpUtility.ParseQueryString(inputData);
if (!int.TryParse(values["id"], NumberStyles.None, CultureInfo.InvariantCulture, out int userId) || userId <= 0)
throw new ArgumentException("id 必须为有效的用户ID");
var actorUserName = values["user_name"];
if (string.IsNullOrWhiteSpace(actorUserName) || values.GetValues("user_name")?.Length != 1)
throw new ArgumentException("操作人 user_name 必须传入且只能传入一次");
var fields = new[]
{
("postage_per_order", UserPaymentTypes.中转仓扣费支出),
("refund_postage_per_order", UserPaymentTypes.退货包裹扣费支出),
("gift_oem_amount_per_order", UserPaymentTypes.礼物单支出),
("sync_logistics_per_order", UserPaymentTypes.同步物流)
};
var fees = new List<(UserPaymentTypes PaymentType, int Amount)>();
foreach (var (key, paymentType) in fields)
{
var value = values[key];
if (value == null) continue;
if (!decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out decimal amount)
|| amount < 0 || amount > int.MaxValue / 100m || decimal.Truncate(amount * 100m) != amount * 100m)
throw new ArgumentException($"{key} 必须为非负金额,单位:元,精确到分且不能超出范围");
fees.Add((paymentType, (int)(amount * 100m)));
}
return (userId, actorUserName, fees);
}
/// <summary>
/// 校验操作权限,并新增或更新指定主用户、下级 OEM 的加价规则。
/// OEM 管理人只能设置自己直属主用户的规则;管理员可以设置指定主用户或下级 OEM 的规则。
/// </summary>
/// <param name="request">
/// UserName 为操作人用户名,调用方须先完成身份认证;TargetId 为目标主用户的用户名或目标 OEM ID。
/// PaymentType 为交易类型,Markup 为加价金额(分),必须传入非负整数,0 表示不加价。
/// </param>
/// <remarks>
/// setter_oem_id 根据目标归属关系确定,不使用管理员身份作为设置者。
/// 保存时会在事务中再次检查目标与设置者的直属关系。
/// </remarks>
/// <exception cref="ArgumentException">请求为空、必填参数缺失、类型不支持或金额不合法。</exception>
/// <exception cref="UnauthorizedAccessException">操作人不存在或无权设置目标规则。</exception>
/// <exception cref="InvalidOperationException">目标或所属 OEM 无效、目标不是主用户、直属关系不符或保存失败。</exception>
public void SetMarkupRule(SetMarkupRuleRequest request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
if (string.IsNullOrWhiteSpace(request.UserName)) throw new ArgumentException("操作人不能为空");
if (string.IsNullOrWhiteSpace(request.TargetId)) throw new ArgumentException("设置目标不能为空");
if (request.TargetType != OEMMarkupTargetType.User && request.TargetType != OEMMarkupTargetType.OEM)
throw new ArgumentException("不支持的加价目标类型");
if (!request.Markup.HasValue || request.Markup < 0) throw new ArgumentException("加价金额必须为非负整数,单位:分");
GetDefaultFloorPrice(request.PaymentType);
var actor = _freeSql.Select<UserEntity>().Where(a => a.UserName == request.UserName).First()
?? throw new UnauthorizedAccessException("操作人不存在");
var actorOem = actor.SaLevel == 1 ? null : GetOEMByUserName(actor.UserName, false);
var targetUser = request.TargetType == OEMMarkupTargetType.User
? _freeSql.Select<UserEntity>().Where(a => a.UserName == request.TargetId).First() : null;
var targetOem = request.TargetType == OEMMarkupTargetType.OEM ? GetOEMByOemId(request.TargetId, false) : null;
var setterOemId = ResolveMarkupSetter(request.TargetType, actor, actorOem, targetUser, targetOem);
if (request.TargetType == OEMMarkupTargetType.User)
SetUserMarkup(setterOemId, request.TargetId, request.PaymentType, request.Markup.Value);
else
SetOEMMarkup(setterOemId, request.TargetId, request.PaymentType, request.Markup.Value);
}
/// <summary>
/// 根据操作人权限和目标归属,确定加价规则的收益方 OEM(setter_oem_id)
/// </summary>
/// <param name="targetType">目标类型:主用户或下级 OEM。</param>
/// <param name="actor">已查询到的操作人;SaLevel 为 1 时按管理员处理,不能为空。</param>
/// <param name="actorOem">操作人作为管理人拥有的 OEM;管理员场景可为空。</param>
/// <param name="targetUser">用户规则的目标主用户;OEM 规则场景可为空。</param>
/// <param name="targetOem">OEM 规则的目标 OEM;用户规则场景可为空。</param>
/// <returns>
/// 用户规则返回目标用户的 OemId,未挂载时返回 00000000;OEM 规则仅允许管理员设置,返回目标 OEM 的 ParentOemId。
/// </returns>
/// <exception cref="ArgumentException">目标类型不支持。</exception>
/// <exception cref="UnauthorizedAccessException">非管理员设置其他 OEM 的用户,或尝试设置 OEM 规则。</exception>
/// <exception cref="InvalidOperationException">目标用户不存在、不是主用户;目标 OEM 不存在、已删除或没有上级。</exception>
private static string ResolveMarkupSetter(OEMMarkupTargetType targetType, UserEntity actor,
OEMEntity actorOem, UserEntity targetUser, OEMEntity targetOem)
{
if (targetType == OEMMarkupTargetType.User)
{
if (targetUser == null) throw new InvalidOperationException("目标用户不存在");
if (!targetUser.IsMainUser) throw new InvalidOperationException("只能设置主用户的加价规则");
var setterOemId = GetMarkupOemId(targetUser.OemId);
if (actor.SaLevel != 1 && (actorOem == null || actorOem.IsDel != 0
|| actorOem.OemOwner != actor.UserName || actorOem.OemId != setterOemId))
throw new UnauthorizedAccessException("只能设置自己OEM下主用户的加价规则");
return setterOemId;
}
if (targetType != OEMMarkupTargetType.OEM) throw new ArgumentException("不支持的加价目标类型");
if (actor.SaLevel != 1) throw new UnauthorizedAccessException("只有管理员可以设置OEM加价规则");
if (targetOem == null || targetOem.IsDel != 0) throw new InvalidOperationException("目标OEM不存在或已删除");
if (string.IsNullOrWhiteSpace(targetOem.ParentOemId)) throw new InvalidOperationException("目标OEM没有上级OEM");
return targetOem.ParentOemId;
}
/// <summary>获取交易类型的默认地板价,单位:分。</summary>
public int GetDefaultFloorPrice(UserPaymentTypes paymentType) => OEMMarkupBaseFeeSettings.GetBaseFee(paymentType);
/// <summary>设置直属主用户的加价(分),0 表示不加价,不允许传入子账号。</summary>
public void SetUserMarkup(string setterOemId, string userName, UserPaymentTypes paymentType, int markup)
{
ValidateMarkup(setterOemId, paymentType, markup);
if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentException("用户名不能为空", nameof(userName));
var user = _freeSql.Select<UserEntity>().Where(a => a.UserName == userName).First()
?? throw new InvalidOperationException("用户不存在");
if (!user.IsMainUser) throw new InvalidOperationException("只能设置主用户的加价规则");
SaveMarkup(setterOemId, OEMMarkupTargetType.User, user.UserName, paymentType, markup);
}
/// <summary>设置直属下级 OEM 的加价,单位:分,0 表示不加价。</summary>
public void SetOEMMarkup(string setterOemId, string oemId, UserPaymentTypes paymentType, int markup)
{
ValidateMarkup(setterOemId, paymentType, markup);
if (string.IsNullOrWhiteSpace(oemId)) throw new ArgumentException("OEM不能为空", nameof(oemId));
if (setterOemId == oemId) throw new ArgumentException("不能设置自身的OEM加价", nameof(oemId));
SaveMarkup(setterOemId, OEMMarkupTargetType.OEM, oemId, paymentType, markup);
}
private void ValidateMarkup(string setterOemId, UserPaymentTypes paymentType, int markup)
{
if (string.IsNullOrWhiteSpace(setterOemId)) throw new ArgumentException("设置者OEM不能为空", nameof(setterOemId));
GetDefaultFloorPrice(paymentType);
if (markup < 0) throw new ArgumentOutOfRangeException(nameof(markup), "加价金额不能为负数");
}
private void SaveMarkup(string setterOemId, OEMMarkupTargetType targetType, string targetId, UserPaymentTypes paymentType, int markup)
{
_freeSql.Transaction(() =>
{
// 无归属用户使用平台默认标识,不要求存在对应的 OEM 记录。
if (!(targetType == OEMMarkupTargetType.User && setterOemId == DefaultMarkupOemId)
&& !_freeSql.Select<OEMEntity>().Where(a => a.OemId == setterOemId && a.IsDel == 0).Any())
throw new InvalidOperationException("设置者OEM不存在或已删除");
// 锁定目标行,使不同进程首次设置同一目标时也不会重复插入规则。
if (targetType == OEMMarkupTargetType.User)
{
var user = _freeSql.Select<UserEntity>().Where(a => a.UserName == targetId).ForUpdate().First();
if (user == null || !user.IsMainUser || GetMarkupOemId(user.OemId) != setterOemId)
throw new InvalidOperationException("只能设置直属主账号的加价");
}
else
{
var oem = _freeSql.Select<OEMEntity>().Where(a => a.OemId == targetId).ForUpdate().First();
if (oem == null || oem.IsDel != 0 || oem.ParentOemId != setterOemId)
throw new InvalidOperationException("只能设置直属下级OEM的加价");
}
var rule = _freeSql.Select<OEMMarkupRuleEntity>()
.Where(a => a.SetterOemId == setterOemId && a.TargetType == targetType
&& a.TargetId == targetId && a.PaymentType == paymentType).First();
if (rule != null && rule.Markup == markup) return;
var now = DateTime.Now;
int affected = rule == null
? _freeSql.Insert(new OEMMarkupRuleEntity
{
SetterOemId = setterOemId,
TargetType = targetType,
TargetId = targetId,
PaymentType = paymentType,
Markup = markup,
UpdatedAt = now
}).ExecuteAffrows()
: _freeSql.Update<OEMMarkupRuleEntity>().Where(a => a.Id == rule.Id)
.Set(a => a.Markup, markup).Set(a => a.UpdatedAt, now).ExecuteAffrows();
if (affected != 1) throw new InvalidOperationException("保存加价规则失败");
});
}
/// <summary>查询用户最终价格(分):地板价 + A对B的加价 + B对主账号的加价。</summary>
public int GetUserFinalPrice(string userName, UserPaymentTypes paymentType)
{
int price = GetDefaultFloorPrice(paymentType);
if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentException("用户名不能为空", nameof(userName));
var user = GetUserByUserName(userName) ?? throw new InvalidOperationException("用户不存在");
return CalculateUserPrice(GetUserMarkupRules(user, paymentType), user, paymentType, price);
}
/// <summary>
/// 批量计算用户四种最终价格(分),返回用户名到消费类型、价格的映射。
/// 复用已查询的用户列表;加价规则只查一次,子账号的主账号归属另作一次批量查询,不使用缓存。
/// </summary>
public Dictionary<string, Dictionary<UserPaymentTypes, int>> GetUserFinalPrices(IEnumerable<UserEntity> users)
{
if (users == null) throw new ArgumentNullException(nameof(users));
var userList = users.ToList();
if (userList.Any(a => a == null || string.IsNullOrWhiteSpace(a.UserName)))
throw new ArgumentException("用户及用户名不能为空", nameof(users));
if (userList.Select(a => a.UserName).Distinct().Count() != userList.Count)
throw new ArgumentException("用户列表中存在重复用户名", nameof(users));
if (userList.Count == 0) return new();
var parentNames = userList.Where(a => !a.IsMainUser).Select(a => a.ParentUserName).Distinct().ToList();
if (parentNames.Count > 0)
{
var parents = _freeSql.Select<UserEntity>().Where(a => parentNames.Contains(a.UserName))
.ToList().ToDictionary(a => a.UserName);
// 与单用户查询一致:子账号继承主账号的 OEM,但仍按自己的用户名匹配规则。
userList = userList.Select(a => new UserEntity
{
UserName = a.UserName,
OemId = !a.IsMainUser && parents.TryGetValue(a.ParentUserName, out var parent) ? parent.OemId : a.OemId
}).ToList();
}
userList = userList.Select(a => new UserEntity { UserName = a.UserName, OemId = GetMarkupOemId(a.OemId) }).ToList();
UserPaymentTypes[] paymentTypes = [UserPaymentTypes.中转仓扣费支出, UserPaymentTypes.退货包裹扣费支出,
UserPaymentTypes.礼物单支出, UserPaymentTypes.同步物流];
var floorPrices = paymentTypes.ToDictionary(a => a, GetDefaultFloorPrice);
var oemIds = userList.Select(a => a.OemId).Where(a => !string.IsNullOrWhiteSpace(a)).Distinct().ToList();
var userNames = userList.Where(a => !string.IsNullOrWhiteSpace(a.OemId)).Select(a => a.UserName).ToList();
var rules = oemIds.Count == 0 ? new List<OEMMarkupRuleEntity>() : _freeSql.Select<OEMMarkupRuleEntity>()
.Where(a => paymentTypes.Contains(a.PaymentType) &&
((a.TargetType == OEMMarkupTargetType.User && userNames.Contains(a.TargetId) && oemIds.Contains(a.SetterOemId))
|| (a.TargetType == OEMMarkupTargetType.OEM && oemIds.Contains(a.TargetId))))
.ToList();
return CalculateUserPrices(userList, rules, floorPrices);
}
private static Dictionary<string, Dictionary<UserPaymentTypes, int>> CalculateUserPrices(List<UserEntity> users,
List<OEMMarkupRuleEntity> rules, Dictionary<UserPaymentTypes, int> floorPrices)
{
var rulesByTarget = rules.ToLookup(a => (a.TargetType, a.TargetId));
var result = new Dictionary<string, Dictionary<UserPaymentTypes, int>>();
foreach (var user in users)
{
var userRules = rulesByTarget[(OEMMarkupTargetType.User, user.UserName)]
.Concat(rulesByTarget[(OEMMarkupTargetType.OEM, GetMarkupOemId(user.OemId))]).ToList();
result.Add(user.UserName, floorPrices.ToDictionary(a => a.Key,
a => CalculateUserPrice(userRules, user, a.Key, a.Value)));
}
return result;
}
/// <summary>实时查询用户两级代理加价(分),按一级、二级返回,未设置的级别金额为 0。</summary>
public UserMarkupResponse[] GetUserMarkups(string userName, UserPaymentTypes paymentType)
{
GetDefaultFloorPrice(paymentType);
if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentException("用户名不能为空", nameof(userName));
var user = GetUserByUserName(userName) ?? throw new InvalidOperationException("用户不存在");
var rules = GetUserMarkupRules(user, paymentType);
var parentOemId = string.IsNullOrWhiteSpace(user.OemId)
? null : GetOEMByOemId(user.OemId, false)?.ParentOemId;
return BuildUserMarkups(rules, user, paymentType, parentOemId);
}
private List<OEMMarkupRuleEntity> GetUserMarkupRules(UserEntity user, UserPaymentTypes paymentType)
{
var oemId = GetMarkupOemId(user.OemId);
return _freeSql.Select<OEMMarkupRuleEntity>()
.Where(a => a.PaymentType == paymentType &&
((a.TargetType == OEMMarkupTargetType.User && a.SetterOemId == oemId && a.TargetId == user.UserName)
|| (a.TargetType == OEMMarkupTargetType.OEM && a.TargetId == oemId))).ToList();
}
private static UserMarkupResponse[] BuildUserMarkups(List<OEMMarkupRuleEntity> rules, UserEntity user, UserPaymentTypes paymentType, string parentOemId)
{
int oemMarkup = GetMarkup(rules, null, OEMMarkupTargetType.OEM, GetMarkupOemId(user.OemId), paymentType);
var oemRule = rules.FirstOrDefault(a => a.TargetType == OEMMarkupTargetType.OEM
&& a.TargetId == GetMarkupOemId(user.OemId) && a.PaymentType == paymentType);
// 已有规则时,代理 ID 与金额必须来自同一条规则。
var oemId = oemRule == null ? parentOemId : oemRule.SetterOemId;
return
[
new() { Level = 1, OemId = string.IsNullOrWhiteSpace(oemId) ? null : oemId, Markup = oemMarkup },
new() { Level = 2, OemId = GetMarkupOemId(user.OemId),
Markup = GetMarkup(rules, GetMarkupOemId(user.OemId), OEMMarkupTargetType.User, user.UserName, paymentType) }
];
}
private static int CalculateUserPrice(List<OEMMarkupRuleEntity> rules, UserEntity user, UserPaymentTypes paymentType, int floorPrice)
{
// 按当前OEM筛选用户规则,避免用户换OEM后使用旧设置者的加价。
int userMarkup = GetMarkup(rules, GetMarkupOemId(user.OemId), OEMMarkupTargetType.User, user.UserName, paymentType);
int oemMarkup = GetMarkup(rules, null, OEMMarkupTargetType.OEM, GetMarkupOemId(user.OemId), paymentType);
return checked(floorPrice + userMarkup + oemMarkup);
}
private static int GetMarkup(List<OEMMarkupRuleEntity> rules, string setterOemId, OEMMarkupTargetType targetType, string targetId, UserPaymentTypes paymentType)
{
var matches = rules.Where(a => (setterOemId == null || a.SetterOemId == setterOemId) && a.TargetType == targetType
&& a.TargetId == targetId && a.PaymentType == paymentType).ToList();
if (matches.Count > 1) throw new InvalidOperationException("存在重复的加价规则,请检查数据");
int markup = matches.FirstOrDefault()?.Markup ?? 0;
if (markup < 0) throw new InvalidOperationException("加价规则金额不能为负数");
return markup;
}
#endregion
} }
@@ -1,5 +1,4 @@
//using MAX.Core.Autofac; //using MAX.Core.Interfaces;
//using MAX.Core.Infrastructure;
//using System; //using System;
//using System.Collections.Concurrent; //using System.Collections.Concurrent;
@@ -90,4 +90,10 @@ public class OEMEntity
/// </summary> /// </summary>
[Column(Name = "total_withdraw_amount")] [Column(Name = "total_withdraw_amount")]
public long TotalWithdrawAmount { get; set; } public long TotalWithdrawAmount { get; set; }
/// <summary>
/// 父级OEMid
/// </summary>
[Column(Name = "parent_oem_id")]
public string ParentOemId { get; set; }
} }
@@ -0,0 +1,59 @@
using FreeSql.DataAnnotations;
using Store.Contracts.User.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Contracts.User.Entitys;
[Table(Name = "wxxd.oem_markup_rule")]
public class OEMMarkupRuleEntity
{
/// <summary>
/// 自增主键
/// </summary>
[Column(Name = "id", IsPrimary = true, IsIdentity = true)]
public long Id { get; set; }
/// <summary>
/// 设置者(上级),也是该笔加价的收益方
/// </summary>
[Column(Name = "setter_oem_id")]
public string SetterOemId { get; set; }
/// <summary>
/// 目标类型 1=下级OEM 2=用户
/// </summary>
[Column(Name = "target_type", MapType = typeof(sbyte))]
public OEMMarkupTargetType TargetType { get; set; }
/// <summary>
/// 目标ID:type=1 是oem_id, type=2 是user_name
/// </summary>
[Column(Name = "target_id")]
public string TargetId { get; set; }
/// <summary>
/// 交易类型
/// 20 快递
/// 26 退货快递
/// 16 礼物单
/// 55 同步物流
/// </summary>
[Column(Name = "payment_type", MapType = typeof(sbyte))]
public UserPaymentTypes PaymentType { get; set; }
/// <summary>
/// 加价金额,单位:分
/// </summary>
[Column(Name = "markup")]
public int Markup { get; set; }
/// <summary>
/// 更新时间
/// </summary>
[Column(Name = "updated_at")]
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,8 @@
namespace Store.Contracts.User.Enums;
/// <summary>OEM 加价规则的目标类型。</summary>
public enum OEMMarkupTargetType : sbyte
{
OEM = 1,
User = 2,
}
@@ -11,6 +11,16 @@ namespace Store.Contracts.User.Interfaces;
public interface IUserService public interface IUserService
{ {
/// <summary>交易类型默认地板价,单位:分。</summary>
int GetDefaultFloorPrice(UserPaymentTypes paymentType);
/// <summary>设置直属主用户加价,单位:分,不允许传入子账号。</summary>
void SetUserMarkup(string setterOemId, string userName, UserPaymentTypes paymentType, int markup);
/// <summary>设置直属下级OEM加价,单位:分。</summary>
void SetOEMMarkup(string setterOemId, string oemId, UserPaymentTypes paymentType, int markup);
/// <summary>地板价加上A对B的加价、B对用户的加价,缺失规则按0计算,单位:分。</summary>
int GetUserFinalPrice(string userName, UserPaymentTypes paymentType);
/// <summary>批量查询四种最终价格,返回用户名到消费类型、价格(分)的映射。</summary>
Dictionary<string, Dictionary<UserPaymentTypes, int>> GetUserFinalPrices(IEnumerable<UserEntity> users);
bool CanAfford(string userName, UserPaymentTypes type, decimal consumeAmount); bool CanAfford(string userName, UserPaymentTypes type, decimal consumeAmount);
OEMEntity GetOEMByOemId(string oemId, bool isCache = true); OEMEntity GetOEMByOemId(string oemId, bool isCache = true);
OEMEntity GetOEMByUserName(string userName, bool isCache = true); OEMEntity GetOEMByUserName(string userName, bool isCache = true);
+8 -2
View File
@@ -4,10 +4,16 @@
https://go.microsoft.com/fwlink/?LinkId=169433 https://go.microsoft.com/fwlink/?LinkId=169433
--> -->
<configuration> <configuration>
<appSettings>
<add key="postage_per_order" value="220"/>
<add key="refund_postage_per_order" value="250"/>
<add key="gift_oem_amount_per_order" value="160"/>
<add key="sync_logistics_per_order" value="190"/>
</appSettings>
<connectionStrings> <connectionStrings>
<add name="ConnKJD" connectionString="Max Pool Size=512;Database='kjd';Data Source='nj-cynosdbmysql-grp-hl51pkfr.sql.tencentcdb.com';Port=27660;User Id='kjd';Password='Temukjd0625';Charset=utf8mb4;"/> <!--<add name="ConnKJD" connectionString="Max Pool Size=512;Database='kjd';Data Source='nj-cynosdbmysql-grp-hl51pkfr.sql.tencentcdb.com';Port=27660;User Id='kjd';Password='Temukjd0625';Charset=utf8mb4;"/>-->
<!--<add name="ConnKJD" connectionString="Server=192.168.0.200;Port=3306;Database=mysql;Uid=root;Pwd=123456;"/>--> <add name="ConnKJD" connectionString="Server=192.168.0.200;Port=3306;Database=mysql;Uid=root;Pwd=123456;"/>
<add name="ConnKJDBAK" connectionString="Max Pool Size=512;Database='kjd';Data Source='nj-cynosdbmysql-grp-9s7x16mt.sql.tencentcdb.com';Port=24049;User Id='kjdbak';Password='Temukjd0126';Charset=utf8mb4;"/> <add name="ConnKJDBAK" connectionString="Max Pool Size=512;Database='kjd';Data Source='nj-cynosdbmysql-grp-9s7x16mt.sql.tencentcdb.com';Port=24049;User Id='kjdbak';Password='Temukjd0126';Charset=utf8mb4;"/>
<add name="UpdateVersion" connectionString="525"/> <add name="UpdateVersion" connectionString="525"/>
@@ -0,0 +1,83 @@
using KJD_Web.Services.Users;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using System.Reflection;
namespace WebServiceTest;
[TestFixture]
public class BatchMarkupPriceTest
{
private static readonly Dictionary<UserPaymentTypes, int> Floors = new()
{
[UserPaymentTypes.中转仓扣费支出] = 220,
[UserPaymentTypes.退货包裹扣费支出] = 250,
[UserPaymentTypes.礼物单支出] = 160,
[UserPaymentTypes.同步物流] = 190
};
private static Dictionary<string, Dictionary<UserPaymentTypes, int>> Calculate(List<UserEntity> users, List<OEMMarkupRuleEntity> rules)
{
try
{
return (Dictionary<string, Dictionary<UserPaymentTypes, int>>)typeof(UserService)
.GetMethod("CalculateUserPrices", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { users, rules, Floors })!;
}
catch (TargetInvocationException ex) { throw ex.InnerException!; }
}
[Test]
public void FourPricesMatchSingleCalculationAndDoNotMixUsersOrOems()
{
var users = new List<UserEntity>
{
new() { UserName = "user1", OemId = "B" },
new() { UserName = "user2", OemId = "C" },
new() { UserName = "plain" }
};
var rules = new List<OEMMarkupRuleEntity>();
foreach (var type in Floors.Keys)
{
rules.Add(new() { TargetType = OEMMarkupTargetType.OEM, TargetId = "B", SetterOemId = "A", PaymentType = type, Markup = 10 });
rules.Add(new() { TargetType = OEMMarkupTargetType.User, TargetId = "user1", SetterOemId = "B", PaymentType = type, Markup = 20 });
rules.Add(new() { TargetType = OEMMarkupTargetType.User, TargetId = "user1", SetterOemId = "C", PaymentType = type, Markup = 99 });
}
var result = Calculate(users, rules);
Assert.That(result.Count, Is.EqualTo(3));
foreach (var user in users)
{
Assert.That(result[user.UserName].Count, Is.EqualTo(4));
foreach (var floor in Floors)
{
Assert.That(result[user.UserName][floor.Key], Is.EqualTo(floor.Value + (user.UserName == "user1" ? 30 : 0)));
var single = typeof(UserService).GetMethod("CalculateUserPrice", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { rules, user, floor.Key, floor.Value });
Assert.That(result[user.UserName][floor.Key], Is.EqualTo(single));
}
}
}
[TestCase(-1, 1, typeof(InvalidOperationException))]
[TestCase(10, 2, typeof(InvalidOperationException))]
[TestCase(int.MaxValue, 1, typeof(OverflowException))]
public void InvalidRuleDataStillFails(int markup, int copies, Type exceptionType)
{
var rule = new OEMMarkupRuleEntity { TargetType = OEMMarkupTargetType.User, TargetId = "user",
SetterOemId = "B", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = markup };
Assert.Throws(exceptionType, () => Calculate(new() { new() { UserName = "user", OemId = "B" } },
Enumerable.Repeat(rule, copies).ToList()));
}
[Test]
public void EmptyAndInvalidUserListsDoNotAccessDatabase()
{
using var sql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Server=127.0.0.1;Database=unused;User Id=unused;Password=unused;").Build();
var service = new UserService(sql, null!);
Assert.That(service.GetUserFinalPrices(Array.Empty<UserEntity>()), Is.Empty);
Assert.Throws<ArgumentNullException>(() => service.GetUserFinalPrices(null!));
Assert.Throws<ArgumentException>(() => service.GetUserFinalPrices(new[] { new UserEntity() }));
Assert.Throws<ArgumentException>(() => service.GetUserFinalPrices(new[] { new UserEntity { UserName = "same" }, new UserEntity { UserName = "same" } }));
}
}
@@ -0,0 +1,49 @@
using KJD_Web.Services.Users;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using System.Reflection;
namespace WebServiceTest;
[TestFixture]
public class DefaultMarkupOemTest
{
[TestCase(null)]
[TestCase("")]
[TestCase(" ")]
public void AdminCanSetUnassignedUserAndOrdinaryOemCannot(string? oemId)
{
var method = typeof(UserService).GetMethod("ResolveMarkupSetter", BindingFlags.NonPublic | BindingFlags.Static)!;
var actor = new UserEntity { UserName = "admin", SaLevel = 1 };
var user = new UserEntity { UserName = "user", OemId = oemId };
Assert.That(method.Invoke(null, new object?[] { OEMMarkupTargetType.User, actor, null, user, null }), Is.EqualTo("00000000"));
actor.SaLevel = 0;
var error = Assert.Throws<TargetInvocationException>(() => method.Invoke(null, new object?[]
{
OEMMarkupTargetType.User, actor, new OEMEntity { OemId = "other", OemOwner = "admin" }, user, null
}));
Assert.That(error!.InnerException, Is.TypeOf<UnauthorizedAccessException>());
Assert.That(user.OemId, Is.EqualTo(oemId), "不修改用户原始归属");
}
[TestCase(null)]
[TestCase("")]
[TestCase(" ")]
public void SingleAndBatchPricesIncludeDefaultOemUserMarkup(string? oemId)
{
var user = new UserEntity { UserName = "user", OemId = oemId };
var type = UserPaymentTypes.中转仓扣费支出;
var rules = new List<OEMMarkupRuleEntity>
{
new() { SetterOemId = "00000000", TargetType = OEMMarkupTargetType.User, TargetId = "user", PaymentType = type, Markup = 12 },
new() { SetterOemId = "old", TargetType = OEMMarkupTargetType.User, TargetId = "user", PaymentType = type, Markup = 99 }
};
var single = typeof(UserService).GetMethod("CalculateUserPrice", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { rules, user, type, 220 });
Assert.That(single, Is.EqualTo(232));
var batch = (Dictionary<string, Dictionary<UserPaymentTypes, int>>)typeof(UserService)
.GetMethod("CalculateUserPrices", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { new List<UserEntity> { user }, rules, new Dictionary<UserPaymentTypes, int> { [type] = 220 } })!;
Assert.That(batch["user"][type], Is.EqualTo(232));
}
}
@@ -0,0 +1,99 @@
using KJD_Web.Services.Users;
using KJD_Web.Requests.Users;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using System.Reflection;
namespace WebServiceTest;
[TestFixture]
public class LegacyMarkupInputTest
{
[TestCase(250, 220, 12, 18)]
[TestCase(232, 220, 12, 0)]
[TestCase(250, 220, 0, 30)]
public void FinalPriceDeductsFloorAndUpstreamMarkup(int amount, int floor, int upstream, int expected)
{
var request = new SetMarkupRuleRequest { PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = amount - floor };
var rules = new List<OEMMarkupRuleEntity>();
if (upstream != 0) rules.Add(new() { TargetType = OEMMarkupTargetType.OEM, TargetId = "B",
SetterOemId = "A", PaymentType = request.PaymentType, Markup = upstream });
// 其他类型、目标及已有二级加价不应参与扣除。
rules.Add(new() { TargetType = OEMMarkupTargetType.OEM, TargetId = "B", PaymentType = UserPaymentTypes.同步物流, Markup = 99 });
rules.Add(new() { TargetType = OEMMarkupTargetType.User, TargetId = "B", PaymentType = request.PaymentType, Markup = 99 });
rules.Add(new() { TargetType = OEMMarkupTargetType.OEM, TargetId = "other", PaymentType = request.PaymentType, Markup = 99 });
typeof(UserService).GetMethod("DeductOemMarkup", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { new List<SetMarkupRuleRequest> { request }, rules, "B" });
Assert.That(request.Markup, Is.EqualTo(expected));
}
[TestCase(11, 12, 1, typeof(ArgumentException))]
[TestCase(30, -1, 1, typeof(InvalidOperationException))]
[TestCase(30, 12, 2, typeof(InvalidOperationException))]
public void InsufficientAmountAndCorruptUpstreamRulesAreRejected(int afterFloor, int upstream, int count, Type errorType)
{
var request = new SetMarkupRuleRequest { PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = afterFloor };
var rule = new OEMMarkupRuleEntity { TargetType = OEMMarkupTargetType.OEM, TargetId = "00000000",
PaymentType = request.PaymentType, Markup = upstream };
var error = Assert.Throws<TargetInvocationException>(() => typeof(UserService)
.GetMethod("DeductOemMarkup", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { new List<SetMarkupRuleRequest> { request }, Enumerable.Repeat(rule, count).ToList(), "00000000" }));
Assert.That(error!.InnerException, Is.TypeOf(errorType));
}
private static (int UserId, string ActorUserName, List<(UserPaymentTypes PaymentType, int Amount)> Fees) Parse(string input)
{
try
{
return ((int, string, List<(UserPaymentTypes, int)>))typeof(UserService)
.GetMethod("ParseLegacyMarkupInput", BindingFlags.NonPublic | BindingFlags.Static)!.Invoke(null, new object[] { input })!;
}
catch (TargetInvocationException ex) { throw ex.InnerException!; }
}
[Test]
public void MapsAllFourTypesAndConvertsYuanToCents()
{
var result = Parse("id=739&user_name=operator%2Bname&postage_per_order=2.2&refund_postage_per_order=2.50&gift_oem_amount_per_order=1.60&sync_logistics_per_order=1.90");
Assert.That(result.UserId, Is.EqualTo(739));
Assert.That(result.ActorUserName, Is.EqualTo("operator+name"));
Assert.That(result.Fees.Select(a => (int)a.PaymentType), Is.EqualTo(new[] { 20, 26, 16, 55 }));
Assert.That(result.Fees.Select(a => a.Amount), Is.EqualTo(new[] { 220, 250, 160, 190 }));
}
[Test]
public void MissingFieldsAreNotOverwrittenAndZeroIsPreserved()
{
Assert.That(Parse("id=739&user_name=operator").Fees, Is.Empty);
Assert.That(Parse("id=739&user_name=operator&postage_per_order=0").Fees,
Is.EqualTo(new[] { (UserPaymentTypes.中转仓扣费支出, 0) }));
}
[TestCase("")]
[TestCase("-1")]
[TestCase("abc")]
[TestCase("2.201")]
[TestCase("21474836.48")]
[TestCase("2%2C2")]
[TestCase("2.2&postage_per_order=3")]
public void InvalidAmountsAreRejected(string value) =>
Assert.Throws<ArgumentException>(() => Parse("id=739&user_name=operator&postage_per_order=" + value));
[TestCase("")]
[TestCase("id=0&user_name=operator")]
[TestCase("id=739")]
[TestCase("id=739&user_name=operator&user_name=admin")]
[TestCase("id=739&id=740&user_name=operator")]
public void InvalidIdentityFieldsAreRejected(string input) =>
Assert.Throws<ArgumentException>(() => Parse(input));
[Test]
public void FeeBelowFloorIsRejectedBeforeDatabaseAccess()
{
using var sql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Server=127.0.0.1;Database=unused;User Id=unused;Password=unused;").Build();
var service = new UserService(sql, null!);
Assert.Throws<ArgumentException>(() => service.SetMarkupRule("id=739&user_name=operator&postage_per_order=0"));
Assert.DoesNotThrow(() => service.SetMarkupRule("id=739&user_name=operator"));
}
}
@@ -0,0 +1,92 @@
using KJD_Web.Requests.Users;
using KJD_Web.Services.Users;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using System.Reflection;
namespace WebServiceTest;
[TestFixture]
public class MarkupRulePermissionTest
{
private static string Resolve(OEMMarkupTargetType type, UserEntity actor, OEMEntity? owner,
UserEntity? user = null, OEMEntity? oem = null)
{
try
{
return (string)typeof(UserService).GetMethod("ResolveMarkupSetter", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object?[] { type, actor, owner, user, oem })!;
}
catch (TargetInvocationException ex) { throw ex.InnerException!; }
}
[TestCase(0)]
[TestCase(1)]
public void UserRuleSetterIsTargetUsersOem(int adminLevel)
{
var actor = new UserEntity { UserName = "operator", SaLevel = (short)adminLevel, OemId = "operator-oem" };
var owner = new OEMEntity { OemId = "target-oem", OemOwner = "operator" };
var user = new UserEntity { UserName = "main-user", OemId = "target-oem" };
Assert.That(Resolve(OEMMarkupTargetType.User, actor, adminLevel == 1 ? null : owner, user), Is.EqualTo("target-oem"));
}
[TestCase(null)]
[TestCase("another-oem")]
public void OrdinaryUserAndUnrelatedOemCannotSetUserRule(string? ownerOemId)
{
var actor = new UserEntity { UserName = "operator", SaLevel = 0 };
var owner = ownerOemId == null ? null : new OEMEntity { OemId = ownerOemId, OemOwner = actor.UserName };
Assert.Throws<UnauthorizedAccessException>(() => Resolve(OEMMarkupTargetType.User, actor, owner,
new UserEntity { UserName = "main-user", OemId = "target-oem" }));
}
[TestCase(0)]
[TestCase(1)]
public void SubUserCannotBeTarget(int adminLevel)
{
Assert.Throws<InvalidOperationException>(() => Resolve(OEMMarkupTargetType.User,
new UserEntity { UserName = "operator", SaLevel = (short)adminLevel },
new OEMEntity { OemId = "target-oem", OemOwner = "operator" },
new UserEntity { UserName = "sub-user", ParentUserName = "main-user", OemId = "target-oem" }));
}
[Test]
public void AdminOemRuleUsesParentOem()
{
Assert.That(Resolve(OEMMarkupTargetType.OEM,
new UserEntity { UserName = "admin", SaLevel = 1, OemId = "admin-oem" }, null,
oem: new OEMEntity { OemId = "child", ParentOemId = "parent" }), Is.EqualTo("parent"));
}
[Test]
public void OemOwnerCannotSetOemRule()
{
Assert.Throws<UnauthorizedAccessException>(() => Resolve(OEMMarkupTargetType.OEM,
new UserEntity { UserName = "owner", SaLevel = 0 }, new OEMEntity { OemId = "parent", OemOwner = "owner" },
oem: new OEMEntity { OemId = "child", ParentOemId = "parent" }));
}
[TestCase(null, 0)]
[TestCase("parent", 1)]
public void RootOrDeletedOemCannotBeTarget(string? parent, int isDeleted)
{
Assert.Throws<InvalidOperationException>(() => Resolve(OEMMarkupTargetType.OEM,
new UserEntity { SaLevel = 1 }, null,
oem: new OEMEntity { OemId = "child", ParentOemId = parent, IsDel = (byte)isDeleted }));
}
//[TestCase(null)]
//[TestCase(-1)]
[TestCase(12)]
public void MissingOrNegativeMarkupIsRejectedBeforeDatabaseAccess(int? markup)
{
using var sql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Server=192.168.0.200;Port=3306;Database=mysql;Uid=root;Pwd=123456;").Build();
var service = new UserService(sql, null!);
Assert.Throws<ArgumentException>(() => service.SetMarkupRule(new SetMarkupRuleRequest
{
UserName = "13388889999", TargetType = OEMMarkupTargetType.User, TargetId = "13313717678",
PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = markup
}));
}
}
+135
View File
@@ -0,0 +1,135 @@
using Autofac;
using Autofac.Integration.WebApi;
using KJD_Web;
using KJD_Web.Services.Shops;
using KJD_Web.Services.Users;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using Store.Framework.DependencyInjection;
using System.Diagnostics;
using System.Reflection;
using System.Web.Http;
namespace WebServiceTest;
[TestFixture]
public class MarkupRuleTest
{
private IFreeSql _sql = null!;
private UserService _service = null!;
private IContainer _container;
[SetUp]
public void Setup()
{
var config = new HttpConfiguration();
_container = ContainerConfig.BuildContainer();
config.DependencyResolver = new AutofacWebApiDependencyResolver(_container);
WebApiConfig.Register(config);
//// 仅构造 ORM;这些测试不连接数据库。
//_sql = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.MySql, "Server=127.0.0.1;Database=unused;User Id=unused;Password=unused;")
// .Build();
_service = _container.Resolve<UserService>();
}
[TearDown]
public void TearDown()
{
_container?.Dispose();
}
[TestCase(UserPaymentTypes.中转仓扣费支出, 220)]
[TestCase(UserPaymentTypes.退货包裹扣费支出, 250)]
[TestCase(UserPaymentTypes.礼物单支出, 160)]
[TestCase(UserPaymentTypes.同步物流, 190)]
public void DefaultFloorPrice(UserPaymentTypes type, int expected) =>
Assert.That(_service.GetDefaultFloorPrice(type), Is.EqualTo(expected));
[Test]
public void MissingBaseFeeConfigurationFailsExplicitly()
{
var error = Assert.Throws<TargetInvocationException>(() => typeof(OEMMarkupBaseFeeSettings)
.GetMethod("ReadFee", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { "missing_base_fee_test" }));
Assert.That(error!.InnerException, Is.TypeOf<System.Configuration.ConfigurationErrorsException>());
Assert.That(error.InnerException!.Message, Does.Contain("missing_base_fee_test"));
}
[Test]
[TestCase("15266666662")]
[TestCase("18199116224")]
[TestCase("13313717678")]
[TestCase("18990991234")]
public void QueryUserActualPrice(string userName)
{
var ruleQueries = new List<string>();
_container.Resolve<IFreeSql>().Aop.CommandBefore += (_, e) =>
{
if (e.Command.CommandText.Contains("oem_markup_rule"))
ruleQueries.Add(e.Command.CommandText);
};
var price = _service.GetUserFinalPrice(userName, UserPaymentTypes.中转仓扣费支出);
TestContext.WriteLine($"用户 {userName} 的中转仓快递最终价格:{price} 分({price / 100m:F2} 元)");
Assert.That(price, Is.GreaterThanOrEqualTo(0));
Assert.That(ruleQueries.Count, Is.LessThanOrEqualTo(1));
foreach (var sql in ruleQueries)
{
TestContext.WriteLine(sql);
Assert.That(sql, Does.Contain("WHERE").And.Contain("target_id").And.Contain("payment_type"));
}
var queryCount = ruleQueries.Count;
_service.GetUserFinalPrice(userName, UserPaymentTypes.中转仓扣费支出);
Assert.That(ruleQueries.Count, Is.EqualTo(queryCount * 2), "再次查询应重新读取加价规则");
}
[Test]
public void RuleLookupMatchesEntireKeyAndDefaultsToZero()
{
var rules = new List<OEMMarkupRuleEntity>
{
new() { SetterOemId = "parent", TargetType = OEMMarkupTargetType.User, TargetId = "main-user", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 30 },
new() { SetterOemId = "old-parent", TargetType = OEMMarkupTargetType.User, TargetId = "main-user", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 90 },
new() { SetterOemId = "parent", TargetType = OEMMarkupTargetType.OEM, TargetId = "main-user", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 40 },
new() { SetterOemId = "parent", TargetType = OEMMarkupTargetType.User, TargetId = "other-user", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 50 },
new() { SetterOemId = "parent", TargetType = OEMMarkupTargetType.User, TargetId = "main-user", PaymentType = UserPaymentTypes.退货包裹扣费支出, Markup = 60 }
};
Assert.That(Lookup(rules), Is.EqualTo(30));
Assert.That(Lookup(new List<OEMMarkupRuleEntity>()), Is.Zero);
rules[0].Markup = 0;
Assert.That(Lookup(rules), Is.Zero);
}
[Test]
public void CorruptRulesFailInsteadOfSilentlyChangingPrice()
{
var rule = new OEMMarkupRuleEntity { SetterOemId = "parent", TargetType = OEMMarkupTargetType.User, TargetId = "main-user", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = -1 };
var negative = Assert.Throws<TargetInvocationException>(() => Lookup(new List<OEMMarkupRuleEntity> { rule }));
Assert.That(negative!.InnerException, Is.TypeOf<InvalidOperationException>());
rule.Markup = 10;
var duplicate = Assert.Throws<TargetInvocationException>(() => Lookup(new List<OEMMarkupRuleEntity> { rule, rule }));
Assert.That(duplicate!.InnerException, Is.TypeOf<InvalidOperationException>());
}
[TestCase(false, false, 220)]
[TestCase(true, false, 250)]
[TestCase(false, true, 240)]
[TestCase(true, true, 270)]
public void TwoLevelPriceAllowsEitherRuleToBeMissing(bool hasUserRule, bool hasOemRule, int expected)
{
var rules = new List<OEMMarkupRuleEntity>
{
new() { SetterOemId = "old", TargetType = OEMMarkupTargetType.User, TargetId = "main-user", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 100 },
new() { SetterOemId = "A", TargetType = OEMMarkupTargetType.OEM, TargetId = "B", PaymentType = UserPaymentTypes.退货包裹扣费支出, Markup = 100 }
};
if (hasUserRule) rules.Add(new() { SetterOemId = "B", TargetType = OEMMarkupTargetType.User, TargetId = "main-user", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 30 });
if (hasOemRule) rules.Add(new() { SetterOemId = "A", TargetType = OEMMarkupTargetType.OEM, TargetId = "B", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 20 });
var price = typeof(UserService).GetMethod("CalculateUserPrice", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { rules, new UserEntity { Id = 123, UserName = "main-user", OemId = "B" }, UserPaymentTypes.中转仓扣费支出, 220 });
Assert.That(price, Is.EqualTo(expected));
}
private static int Lookup(List<OEMMarkupRuleEntity> rules) => (int)typeof(UserService)
.GetMethod("GetMarkup", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { rules, "parent", OEMMarkupTargetType.User, "main-user", UserPaymentTypes.中转仓扣费支出 })!;
}
+90
View File
@@ -0,0 +1,90 @@
using KJD_Web.Services.Users;
using KJD_Web.Responses.Users;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using System.Reflection;
namespace WebServiceTest;
[TestFixture]
public class MarkupUserNameTest
{
[TestCase(false, false)]
[TestCase(false, true)]
[TestCase(true, false)]
[TestCase(true, true)]
public void MarkupArrayContainsBothLevelsAndDefaultsMissingRulesToZero(bool hasOemRule, bool hasUserRule)
{
var rules = new List<OEMMarkupRuleEntity>
{
new() { SetterOemId = "old-oem", TargetType = OEMMarkupTargetType.User, TargetId = "main-user",
PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 99 },
new() { SetterOemId = "A", TargetType = OEMMarkupTargetType.OEM, TargetId = "B",
PaymentType = UserPaymentTypes.退货包裹扣费支出, Markup = 88 }
};
if (hasOemRule) rules.Add(new() { SetterOemId = "A", TargetType = OEMMarkupTargetType.OEM,
TargetId = "B", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 10 });
if (hasUserRule) rules.Add(new() { SetterOemId = "B", TargetType = OEMMarkupTargetType.User,
TargetId = "main-user", PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 20 });
var result = (UserMarkupResponse[])typeof(UserService)
.GetMethod("BuildUserMarkups", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { rules, new UserEntity { UserName = "main-user", OemId = "B" },
UserPaymentTypes.中转仓扣费支出, "A" })!;
Assert.That(result.Select(a => a.Level), Is.EqualTo(new[] { 1, 2 }));
Assert.That(result.Select(a => a.OemId), Is.EqualTo(new[] { "A", "B" }));
Assert.That(result.Select(a => a.Markup), Is.EqualTo(new[] { hasOemRule ? 10 : 0, hasUserRule ? 20 : 0 }));
}
[TestCase(null, null)]
[TestCase("", " ")]
[TestCase("B", null)]
public void MissingParentIsNullAndUnassignedUserUsesDefaultOem(string? oemId, string? parentOemId)
{
var result = (UserMarkupResponse[])typeof(UserService)
.GetMethod("BuildUserMarkups", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object?[] { new List<OEMMarkupRuleEntity>(),
new UserEntity { UserName = "main-user", OemId = oemId },
UserPaymentTypes.中转仓扣费支出, parentOemId })!;
Assert.That(result[0].OemId, Is.Null);
Assert.That(result[1].OemId, Is.EqualTo(string.IsNullOrWhiteSpace(oemId) ? "00000000" : oemId));
Assert.That(result.Select(a => a.Markup), Is.EqualTo(new[] { 0, 0 }));
}
[TestCase(null)]
[TestCase("different-parent")]
public void FirstLevelUsesRuleSetterEvenWhenParentIsMissingOrDifferent(string? parentOemId)
{
var rules = new List<OEMMarkupRuleEntity>
{
new() { SetterOemId = "wrong-type", TargetType = OEMMarkupTargetType.OEM, TargetId = "B",
PaymentType = UserPaymentTypes.退货包裹扣费支出, Markup = 99 },
new() { SetterOemId = "A", TargetType = OEMMarkupTargetType.OEM, TargetId = "B",
PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 12 }
};
var result = (UserMarkupResponse[])typeof(UserService)
.GetMethod("BuildUserMarkups", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object?[] { rules, new UserEntity { UserName = "main-user", OemId = "B" },
UserPaymentTypes.中转仓扣费支出, parentOemId })!;
Assert.That(result[0].OemId, Is.EqualTo("A"));
Assert.That(result[0].Markup, Is.EqualTo(12));
}
[TestCase(false, 220)]
[TestCase(true, 250)]
public void UserRuleMatchesUserNameInsteadOfNumericId(bool hasUserRule, int expected)
{
var rules = new List<OEMMarkupRuleEntity>
{
new() { SetterOemId = "B", TargetType = OEMMarkupTargetType.User, TargetId = "123",
PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 90 }
};
if (hasUserRule)
rules.Add(new() { SetterOemId = "B", TargetType = OEMMarkupTargetType.User, TargetId = "main-user",
PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 30 });
var price = typeof(UserService).GetMethod("CalculateUserPrice", BindingFlags.NonPublic | BindingFlags.Static)!
.Invoke(null, new object[] { rules, new UserEntity { Id = 123, UserName = "main-user", OemId = "B" },
UserPaymentTypes.中转仓扣费支出, 220 });
Assert.That(price, Is.EqualTo(expected));
}
}