diff --git a/KJD_WebService/Services/Users/UserService.FeeRecord.cs b/KJD_WebService/Services/Users/UserService.FeeRecord.cs
index 829cb27..839f9a9 100644
--- a/KJD_WebService/Services/Users/UserService.FeeRecord.cs
+++ b/KJD_WebService/Services/Users/UserService.FeeRecord.cs
@@ -1,5 +1,6 @@
using KJD_Web.Model.WxModel;
using MySqlX.XDevAPI;
+using MySqlX.XDevAPI.Relational;
using Newtonsoft.Json;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
@@ -59,9 +60,9 @@ namespace KJD_Web.Services.Users
*/
long totalFen = SettleFlowsInternal(
trFreeSql,
+ oem,
users,
oem.AddTime);
-
long rebateFen = totalFen;
@@ -103,10 +104,11 @@ namespace KJD_Web.Services.Users
{
throw new Exception("错误的账号");
}
+
using var work = tarn != null ? _freeSql.CreateUnitOfWork(tarn) : _freeSql.CreateUnitOfWork();
var trFreeSql = work.Orm;
/* * 普通用户没有OEM创建时间限制。 * * 所以这里传null。 */
- long totalAmount = SettleFlowsInternal(trFreeSql, users, null);
+ long totalAmount = SettleFlowsInternal(trFreeSql, null, users, null);
/* * 普通用户没有余额, * 所以不做任何金额更新。 */
Debug.WriteLine($"用户流水结算:{totalAmount}");
work.Commit();
@@ -122,10 +124,116 @@ namespace KJD_Web.Services.Users
/// 当前事务ORM
/// 需要结算的用户
///
- private long SettleFlowsInternal(IFreeSql tr_freeSql, ICollection users, DateTime? oemAddTime)
+ private long SettleFlowsInternal(IFreeSql tr_freeSql, OEMEntity oem, ICollection users, DateTime? oemAddTime)
{
if (users == null || users.Count == 0) { throw new Exception("没有用户"); }
+ //IEnumerable userNames = users.Select(a => a.UserName);
+ //decimal total_amount = 0m; // 总金额(元)
+ //decimal rebate_amount = 0m; // 正数部分(累计返利)
+ //DateTime now = DateTime.Now;
+ //int[] positiveTypes = [16, 20, 26, 31, 35, 39, 55];
+ //int[] negativeTypes = [34, 23, 38, 32, 36, 40];
+ //var paymentTypes = positiveTypes.Concat(negativeTypes).ToArray();
+ //var paymentQuery = tr_freeSql.Select()
+ // .Where(a => userNames.Contains(a.UserName))
+ // .Where(a => paymentTypes.Contains(a.Type))
+ // .Where(a => a.Settlement == 0)
+ // .Where(a => a.IsDeleted == 0);
+ ////只有OEM结算才限制OEM创建时间。
+ //if (oemAddTime.HasValue)
+ //{
+ // paymentQuery = paymentQuery.Where(a => a.CreateTime > oemAddTime.Value);
+ //}
+ //var userPayments = paymentQuery.OrderBy(a => a.Id).ToList();
+ //if (userPayments.Count > 0)
+ //{
+ // var ids = userPayments.Select(a => a.Id).ToList();
+ // var userPaymentAmount = userPayments
+ // .GroupBy(a => new { a.Type, a.OrderId })
+ // .Select(group => group.First())
+ // .Sum(a =>
+ // {
+ // var amount = Math.Abs(a.OemAmount ?? 0m);
+ // return positiveTypes.Contains(a.Type) ? amount : -amount;
+ // });
+ // total_amount += userPaymentAmount;
+ // rebate_amount += userPaymentAmount;
+
+ // Debug.WriteLine($"运费流水返利:{userPaymentAmount}");
+ // var settlementCount = tr_freeSql.Update()
+ // .Set(a => a.Settlement, (byte)1)
+ // .Set(a => a.SettlementTime, now)
+ // .Where(a => ids.Contains(a.Id))
+ // .ExecuteAffrows();
+ // if (settlementCount != ids.Count)
+ // throw new Exception("运费流水结算失败");
+
+ //}
+
+
+
+ //var userPoints = tr_freeSql.Select()
+ // .Where(a => userNames.Contains(a.UserName))
+ // .Where(a => a.OptionType == "续费")
+ // .Where(a => a.Settlement == false)
+ // .ToList();
+ //if (userPoints.Count > 0)
+ //{
+ // var feeMap = users
+ // .GroupBy(a => a.UserName)
+ // .ToDictionary(g => g.Key, g => g.First().ShopRenewalPlatformFloorFee);
+
+ // List ids = userPoints.Select(a => a.Id).ToList();
+ // decimal userPointsAmount = userPoints.Sum(x =>
+ // {
+ // var fee = feeMap.TryGetValue(x.UserName, out var f) ? f : (decimal?)null;
+ // var net = x.DeltaPoints - (fee ?? ShopRenewFee); // 允许为负
+
+ // if (net < 0m)
+ // {
+ // _logger.Warn(
+ // $"续费返利出现负数:UserName={x.UserName}, DeltaPoints={x.DeltaPoints}, Fee={fee ?? ShopRenewFee}, Net={net}");
+ // }
+
+ // return net; // 允许出现负数
+ // });//累计返利
+
+
+ // total_amount += userPointsAmount;
+ // rebate_amount += userPointsAmount;
+
+ // Debug.WriteLine($"商铺月费返利:{userPointsAmount}");
+ // var settlementCount = tr_freeSql.Update()
+ // .Set(a => a.Settlement, true)
+ // .Set(a => a.SettlementTime, now)
+ // .Where(a => ids.Contains(a.Id))
+ // .ExecuteAffrows();
+ // if (settlementCount != ids.Count)
+ // throw new Exception("积分流水结算失败");
+ //}
+ //long total_fen = (long)Math.Round(total_amount * 100m);
+
+
+ DateTime now = DateTime.Now;
+ long total_fen = 0;
+ total_fen += SettlementOemUserPayment(tr_freeSql, users, oemAddTime, now);
+ if (oem != null) //非oem 无记录
+ {
+ total_fen += SettlementOemCommission(tr_freeSql, oem.OemId, oemAddTime, now);
+ }
+ total_fen += SettlementUserShopRenew(tr_freeSql, users, oemAddTime, now);
+ //long rebate_fen = (long)Math.Round(rebate_amount * 100m);
+
+ return total_fen;
+ }
+ ///
+ /// 结算OEM用户的消费 佣金
+ ///
+ ///
+ private long SettlementOemUserPayment(IFreeSql tr_freeSql, ICollection users, DateTime? oemAddTime, DateTime? settlementTime = null)
+ {
+ if (settlementTime == null) settlementTime = DateTime.Now;
IEnumerable userNames = users.Select(a => a.UserName);
decimal total_amount = 0m; // 总金额(元)
decimal rebate_amount = 0m; // 正数部分(累计返利)
@@ -168,14 +276,73 @@ namespace KJD_Web.Services.Users
throw new Exception("运费流水结算失败");
}
+ long total_fen = (long)Math.Round(total_amount * 100m);
+ //long rebate_fen = (long)Math.Round(rebate_amount * 100m);
+ return total_fen;
+ }
+ ///
+ /// OEM 返利表 结算
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ private long SettlementOemCommission(IFreeSql tr_freeSql, string oemId, DateTime? oemAddTime, DateTime? settlementTime = null)
+ {
+ long total_fen = 0;
+
+ var query = tr_freeSql.Select()
+ .Where(a => a.OemId == oemId)
+ .Where(a => a.SettleStatus == 0);
+ //只有OEM结算才限制OEM创建时间。
+ if (oemAddTime.HasValue)
+ {
+ query = query.Where(a => a.CreatedAt > oemAddTime.Value);
+ }
+ var userPayments = query.OrderBy(a => a.Id).ToList();
+ if (userPayments.Count > 0)
+ {
+ var ids = userPayments.Select(a => a.Id).ToList();
+ var userPaymentAmount = userPayments
+ .GroupBy(a => new { a.UserPaymentRecordId, a.OemId })
+ .Select(group => group.First())
+ .Sum(a => a.Amount);
+ total_fen += userPaymentAmount;
+ Debug.WriteLine($"运费流水返利:{userPaymentAmount}");
+ var settlementCount = tr_freeSql.Update()
+ .Set(a => a.SettleStatus, (sbyte)1)
+ .Set(a => a.SettledAt, DateTime.Now)
+ .Where(a => ids.Contains(a.Id))
+ .ExecuteAffrows();
+ if (settlementCount != ids.Count)
+ throw new Exception("运费流水结算失败");
+ }
+ return total_fen;
+ }
+
+ ///
+ /// 结算 OME 下用户下的商铺续费佣金
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ private long SettlementUserShopRenew(IFreeSql tr_freeSql, ICollection users, DateTime? oemAddTime, DateTime? settlementTime = null)
+ {
+ if (settlementTime == null) settlementTime = DateTime.Now;
+ IEnumerable userNames = users.Select(a => a.UserName);
+ decimal total_amount = 0m; // 总金额(元)
var userPoints = tr_freeSql.Select()
- .Where(a => userNames.Contains(a.UserName))
- .Where(a => a.OptionType == "续费")
- .Where(a => a.Settlement == false)
- .ToList();
+ .Where(a => userNames.Contains(a.UserName))
+ .Where(a => a.OptionType == "续费")
+ .Where(a => a.Settlement == false)
+ .ToList();
if (userPoints.Count > 0)
{
var feeMap = users
@@ -199,18 +366,16 @@ namespace KJD_Web.Services.Users
total_amount += userPointsAmount;
- rebate_amount += userPointsAmount;
Debug.WriteLine($"商铺月费返利:{userPointsAmount}");
var settlementCount = tr_freeSql.Update()
.Set(a => a.Settlement, true)
- .Set(a => a.SettlementTime, now)
+ .Set(a => a.SettlementTime, settlementTime.Value)
.Where(a => ids.Contains(a.Id))
.ExecuteAffrows();
if (settlementCount != ids.Count)
throw new Exception("积分流水结算失败");
}
-
long total_fen = (long)Math.Round(total_amount * 100m);
//long rebate_fen = (long)Math.Round(rebate_amount * 100m);
diff --git a/KJD_WebService/Services/Users/UserService.OEM.cs b/KJD_WebService/Services/Users/UserService.OEM.cs
index 4db34fc..33c28d6 100644
--- a/KJD_WebService/Services/Users/UserService.OEM.cs
+++ b/KJD_WebService/Services/Users/UserService.OEM.cs
@@ -199,10 +199,14 @@ public partial class UserService
{
var (userId, actorUserName, fees) = ParseLegacyMarkupInput(inputData);
var requests = new List();
+ var user = _freeSql.Select().Where(a => a.Id == userId).First()
+ ?? throw new InvalidOperationException("目标用户不存在");
foreach (var (paymentType, amount) in fees)
{
- int markup = amount - GetDefaultFloorPrice(paymentType);
- if (markup < 0) throw new ArgumentException($"交易类型 {(int)paymentType} 的费用不能低于基础费");
+ var userFloorPrice = GetUserFloorPrice(user.UserName, paymentType);
+
+ int markup = amount - userFloorPrice;
+ if (markup < 0) throw new ArgumentException($"交易类型 {paymentType} 的费用不能低于基础费用:{userFloorPrice / 100m}元");
requests.Add(new SetMarkupRuleRequest
{
UserName = actorUserName,
@@ -214,8 +218,7 @@ public partial class UserService
if (requests.Count == 0) return;
_freeSql.Transaction(() =>
{
- var user = _freeSql.Select().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()
@@ -427,6 +430,22 @@ public partial class UserService
return CalculateUserPrice(GetUserMarkupRules(user, paymentType), user, paymentType, price);
}
+ ///
+ /// 获取用户底价(分):平台基础费 + 一级 OEM 加价,不包含对该用户的二级加价。
+ /// 子账号使用主账号归属;未挂载 OEM 时按 00000000 查询,一级规则缺失时加价为 0。
+ ///
+ public int GetUserFloorPrice(string userName, UserPaymentTypes paymentType)
+ {
+ int price = GetDefaultFloorPrice(paymentType);
+ if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentException("用户名不能为空", nameof(userName));
+ var user = GetMainUser(userName) ?? throw new InvalidOperationException("用户不存在");
+ var oemId = GetMarkupOemId(user.OemId);
+ var rules = _freeSql.Select()
+ .Where(a => a.PaymentType == paymentType && a.TargetType == OEMMarkupTargetType.OEM && a.TargetId == oemId)
+ .ToList();
+ return CalculateUserFloorPrice(rules, user, paymentType, price);
+ }
+
///
/// 批量计算用户四种最终价格(分),返回用户名到消费类型、价格的映射。
/// 复用已查询的用户列表;加价规则只查一次,子账号的主账号归属另作一次批量查询,不使用缓存。
@@ -523,10 +542,12 @@ public partial class UserService
{
// 按当前OEM筛选用户规则,避免用户换OEM后使用旧设置者的加价。
int userMarkup = GetMarkup(rules, GetMarkupOemId(user.OemId), OEMMarkupTargetType.User, GetMarkupUserName(user), paymentType);
- int oemMarkup = GetMarkup(rules, null, OEMMarkupTargetType.OEM, GetMarkupOemId(user.OemId), paymentType);
- return checked(floorPrice + userMarkup + oemMarkup);
+ return checked(CalculateUserFloorPrice(rules, user, paymentType, floorPrice) + userMarkup);
}
+ private static int CalculateUserFloorPrice(List rules, UserEntity user, UserPaymentTypes paymentType, int floorPrice) =>
+ checked(floorPrice + GetMarkup(rules, null, OEMMarkupTargetType.OEM, GetMarkupOemId(user.OemId), paymentType));
+
private static string GetMarkupUserName(UserEntity user) => user.IsMainUser ? user.UserName : user.ParentUserName;
private static int GetMarkup(List rules, string setterOemId, OEMMarkupTargetType targetType, string targetId, UserPaymentTypes paymentType)
diff --git a/Store.Contracts/User/Interfaces/IUserService.cs b/Store.Contracts/User/Interfaces/IUserService.cs
index 4a600d6..49e0237 100644
--- a/Store.Contracts/User/Interfaces/IUserService.cs
+++ b/Store.Contracts/User/Interfaces/IUserService.cs
@@ -19,6 +19,8 @@ public interface IUserService
void SetOEMMarkup(string setterOemId, string oemId, UserPaymentTypes paymentType, int markup);
/// 地板价加上A对B的加价、B对用户的加价,缺失规则按0计算,单位:分。
int GetUserFinalPrice(string userName, UserPaymentTypes paymentType);
+ /// 用户底价(分):平台基础费加一级 OEM 加价,不包含二级用户加价。
+ int GetUserFloorPrice(string userName, UserPaymentTypes paymentType);
/// 批量查询四种最终价格,返回用户名到消费类型、价格(分)的映射。
Dictionary> GetUserFinalPrices(IEnumerable users);
bool CanAfford(string userName, UserPaymentTypes type);
diff --git a/test/WebServiceTest/UserFloorPriceTest.cs b/test/WebServiceTest/UserFloorPriceTest.cs
new file mode 100644
index 0000000..3a26005
--- /dev/null
+++ b/test/WebServiceTest/UserFloorPriceTest.cs
@@ -0,0 +1,45 @@
+using KJD_Web.Services.Users;
+using Store.Contracts.User.Entitys;
+using Store.Contracts.User.Enums;
+using System.Reflection;
+
+namespace WebServiceTest;
+
+[TestFixture]
+public class UserFloorPriceTest
+{
+ private static int Calculate(List rules, string? oemId) =>
+ (int)typeof(UserService).GetMethod("CalculateUserFloorPrice", BindingFlags.NonPublic | BindingFlags.Static)!
+ .Invoke(null, new object[] { rules, new UserEntity { UserName = "user", OemId = oemId },
+ UserPaymentTypes.中转仓扣费支出, 220 })!;
+
+ [TestCase("B", false, 220)]
+ [TestCase("B", true, 232)]
+ [TestCase(null, true, 232)]
+ public void FloorIncludesOnlyMatchingUpstreamMarkup(string? oemId, bool hasRule, int expected)
+ {
+ var rules = new List
+ {
+ new() { TargetType = OEMMarkupTargetType.User, TargetId = "user", SetterOemId = "B",
+ PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 50 },
+ new() { TargetType = OEMMarkupTargetType.OEM, TargetId = oemId ?? "00000000",
+ PaymentType = UserPaymentTypes.同步物流, Markup = 99 },
+ new() { TargetType = OEMMarkupTargetType.OEM, TargetId = "other",
+ PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 99 }
+ };
+ if (hasRule) rules.Add(new() { TargetType = OEMMarkupTargetType.OEM, TargetId = oemId ?? "00000000",
+ PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = 12 });
+ Assert.That(Calculate(rules, oemId), Is.EqualTo(expected));
+ }
+
+ [TestCase(-1, 1, typeof(InvalidOperationException))]
+ [TestCase(12, 2, typeof(InvalidOperationException))]
+ [TestCase(int.MaxValue, 1, typeof(OverflowException))]
+ public void CorruptRulesAndOverflowAreRejected(int markup, int count, Type errorType)
+ {
+ var rule = new OEMMarkupRuleEntity { TargetType = OEMMarkupTargetType.OEM, TargetId = "B",
+ PaymentType = UserPaymentTypes.中转仓扣费支出, Markup = markup };
+ var error = Assert.Throws(() => Calculate(Enumerable.Repeat(rule, count).ToList(), "B"));
+ Assert.That(error!.InnerException, Is.TypeOf(errorType));
+ }
+}
diff --git a/test/WebServiceTest/UserTest.cs b/test/WebServiceTest/UserTest.cs
index 34a65f8..f625da1 100644
--- a/test/WebServiceTest/UserTest.cs
+++ b/test/WebServiceTest/UserTest.cs
@@ -52,11 +52,11 @@ internal class UserTest
//[TestCase("15698175212")]
//[TestCase("18238114231")]
//[TestCase("15870095938")]
- //[TestCase("13388889999")]
+ [TestCase("13388889999")]
//[TestCase("15907090308")]
//[TestCase("17837688880")]
//[TestCase("13048056467")]
- [TestCase("17337708962")]
+ //[TestCase("17337708962")]
//[TestCase("13459139999")]
//[TestCase("18737568536")]
//[TestCase("18949822610")]