Files
KJD_WebService/KJD_WebService/Services/Users/UserService.FeeRecord.cs
T

426 lines
12 KiB
C#

using KJD_Web.Model.WxModel;
using MySqlX.XDevAPI;
using Newtonsoft.Json;
using Store.Contracts.User.Entitys;
using Store.Contracts.User.Enums;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using static FreeSql.Internal.GlobalFilter;
namespace KJD_Web.Services.Users
{
/// <summary>
/// 消费
/// </summary>
public partial class UserService
{
/// <summary>
/// 店铺续费手续费 15
/// </summary>
private const int ShopRenewFee = 15;
/// <summary>
/// 结算OEM流水
/// </summary>
public OEMEntity SettleOemFlows(string userName, DbTransaction tarn = null)
{
var oem = GetOEMByUserName(userName);
if (oem == null)
{
throw new Exception("错误的账号");
}
using var work = tarn != null ? _freeSql.CreateUnitOfWork(tarn) : _freeSql.CreateUnitOfWork();
var trFreeSql = work.Orm;
// 获取OEM下面的所有用户
var users = GetOEMUsers(oem.OemId, true);
if (users.Count == 0)
{//todo
throw new Exception("没有用户");
}
/*
* OEM结算规则:
*
* 只结算OEM创建之后产生的流水。
*
* CreateTime > oem.AddTime
*/
long totalFen = SettleFlowsInternal(
trFreeSql,
users,
oem.AddTime);
long rebateFen = totalFen;
if (totalFen != 0 || rebateFen != 0)
{
var affrows = trFreeSql
.Update<OEMEntity>()
.Set(a => new
{
AvailableBalance =
a.AvailableBalance + totalFen,
TotalRebateAmount =
a.TotalRebateAmount + rebateFen
})
.Where(a => a.OemId == oem.OemId)
.ExecuteAffrows();
if (affrows != 1)
{
throw new Exception("OEM余额更新失败");
}
}
work.Commit();
oem = GetOEMByUserName(userName, false);
return oem;
}
/// <summary>
/// 结算用户流水
/// </summary>
/// <param name="userName"></param>
public long SettleUserFlows(string userName, DbTransaction tarn = null)
{
var users = GetUserAndSubUser(userName);
if (users == null)
{
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);
/* * 普通用户没有余额, * 所以不做任何金额更新。 */
Debug.WriteLine($"用户流水结算:{totalAmount}");
work.Commit();
return totalAmount;
}
/// <summary>
/// 1. 查询支付流水
/// 2. 计算OEM结算金额
/// 3. 查询续费流水
/// 4. 标记流水为已结算
/// </summary>
/// <param name="orm">当前事务ORM</param>
/// <param name="userNames">需要结算的用户</param>
/// <param name="oemAddTime">
private long SettleFlowsInternal(IFreeSql tr_freeSql, ICollection<UserEntity> users, DateTime? oemAddTime)
{
if (users == null || users.Count == 0) { throw new Exception("没有用户"); }
IEnumerable<string> 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<UserPaymentRecordEntity>()
.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<UserPaymentRecordEntity>()
.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<UserPointsRecordEntity>()
.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<long> 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<UserPointsRecordEntity>()
.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);
//long rebate_fen = (long)Math.Round(rebate_amount * 100m);
return total_fen;
}
/// <summary>
/// 获取用户金额统计
/// </summary>
/// <param name="userName"></param>
public UserAmountSummary GetUserAmountSummary(string userName)
{
UserAmountSummary summary = new UserAmountSummary();
var user = GetUserByUserName(userName);
if (user == null) throw new Exception("错误的用户");
summary.RechargeTotal = (long)Math.Round((user.RechargeAmountTotal ?? 0) * 100m);
summary.Balance = (long)Math.Round((user.Balance ?? 0) * 100m);
List<int> types = new List<int> { 16, 20, 23, 24, 26, 31, 34, 35, 36, 55 };
var sql = _freeSql.Select<UserPaymentRecordEntity>().Where(a => types.Contains(a.Type)).Where(a => a.UserName == userName).ToSql();
var data = _freeSql.Select<UserPaymentRecordEntity>()
.Where(a => types.Contains(a.Type))
.Where(a => a.UserName == userName)
.ToList();
var negativeTypes = new[] { 23, 34, 36 };
decimal sum = data.Sum(r => negativeTypes.Contains(r.Type) ? -(r.Amount ?? 0) : r.Amount ?? 0);
summary.ConsumeTotal = (long)Math.Round(sum * 100m);
return summary;
}
// /// <summary>
// /// 填充历史数据
// /// </summary>
// public void FillHistoryOemAmount()
// {
// List<UserPaymentRecordSmall> data = new List<UserPaymentRecordSmall>();
// string path = @"d:\ddddd.json";
// if (File.Exists(path))
// {
// data = JsonConvert.DeserializeObject<List<UserPaymentRecordSmall>>(File.ReadAllText(path));
// }
// else
// {
// data = _freeSql.Select<UserPaymentRecordSmall>()
// .Where(a => a.type == 20 || a.type == 26)
// .Where(a => a.create_time < DateTime.Parse("2026-09-01 00:00:00"))
// .OrderBy(a => a.id)
// .ToList();
// }
// Debug.WriteLine($"共;{data.Count}");
// int max = 500;
// int count = 0;
// List<UserPaymentRecordSmall> list = new List<UserPaymentRecordSmall>();
// foreach (var item in data)
// {
// //if (item.IsFill) continue;
// try
// {
// if (!string.IsNullOrEmpty(item.remark))
// {
// var ls = item.remark.Split(':');
// if (ls.Length != 2) continue;
// item.OrderId = ls[1];
// list.Add(item);
// if (list.Count == max)
// {
// var orderNames = list.Select(a => a.OrderId);
// List<weiOrder> orders = _freeSql.Select<weiOrder>()
// .Where(a => orderNames.Contains(a.order_id))
// .ToList();
// fillOemAmount(list, orders);
// var uCount = _freeSql.Update<UserPaymentRecordSmall>()
// .SetSource(list)
// .UpdateColumns(a => new { a.oem_amount })
// .ExecuteAffrows();
// if (uCount != list.Count)
// {
// Debug.WriteLine("数量不对");
// }
// list.ForEach(a => a.IsFill = true);
// File.WriteAllText(path, JsonConvert.SerializeObject(data));
// count += list.Count;
// Debug.WriteLine($"成功修改;{list.Count}");
// list.Clear();
// Debug.WriteLine($"共修改;{count}");
// }
// }
// }
// finally
// {
// }
// }
// }
// private void fillOemAmount(List<UserPaymentRecordSmall> list, List<weiOrder> orders)
// {
// foreach (var item in list)
// {
// var order = orders.FirstOrDefault(a => a.order_id == item.OrderId);
// if (order != null)
// {
// item.oem_amount = getoemamount(order.province_name, item.amount.Value, item.type);
// }
// }
// }
// private Dictionary<string, decimal> DicWarehousePostage = new Dictionary<string, decimal>
// {
// { "湖北", 2.2m },
//{ "湖南", 2.2m },
//{ "江西", 2.2m },
//{ "河南", 2.2m },
//{ "上海", 3m },
//{ "浙江", 2.2m },
//{ "安徽", 2.2m },
//{ "江苏", 2.2m },
//{ "河北", 2.2m },
//{ "山东", 2.2m },
//{ "福建", 2.2m },
//{ "广东", 2.2m },
//{ "深圳", 2.8m },
//{ "天津", 2.2m },
//{ "北京", 3.2m },
//{ "山西", 2.2m },
//{ "陕西", 2.2m },
//{ "广西", 2.2m },
//{ "云南", 2.2m },
//{ "贵州", 2.2m },
//{ "四川", 2.2m },
//{ "重庆", 2.2m },
//{ "黑龙江", 2.7m },
//{ "吉林", 2.7m },
//{ "辽宁", 2.7m },
//{ "青海", 2.7m },
//{ "宁夏", 2.7m },
//{ "甘肃", 2.7m },
//{ "内蒙", 4.5m },
//{ "海南", 4.5m },
//{ "新疆", 12.5m },
//{ "西藏", 12.5m },
// };
// private decimal getoemamount(string province, decimal amount, int type)
// {
// foreach (var item in DicWarehousePostage)
// {
// if (province.StartsWith(item.Key))
// {
// if (type == 20)
// return amount - item.Value;
// if (type == 26)
// return amount - item.Value - 0.3m;
// }
// }
// return amount;
// }
}
[FreeSql.DataAnnotations.Table(Name = "wxxd.user_payment_record")]
public class UserPaymentRecordSmall()
{
public long id { get; set; }
public int type { get; set; }
/// <summary>
/// 金额(元)
/// </summary>
public decimal? amount { get; set; }
/// <summary>
/// 归属oem用户的金额
/// </summary>
public decimal? oem_amount { get; set; }
public string remark { get; set; }
public DateTime create_time { get; set; }
[FreeSql.DataAnnotations.Column(IsIgnore = true)]
public bool IsFill { get; set; }
[FreeSql.DataAnnotations.Column(IsIgnore = true)]
public string OrderId { get; set; }
}
[FreeSql.DataAnnotations.Table(Name = "erp.oms_wei_order")]
public class weiOrder
{
public string order_id { get; set; }
public string province_name { get; set; }
}
public class UserAmountSummary
{
/// <summary>
/// 充值总额
/// </summary>
public long RechargeTotal { get; set; }
/// <summary>
/// 消费总额
/// </summary>
public long ConsumeTotal { get; set; }
/// <summary>
/// 剩余余额
/// </summary>
public long Balance { get; set; }
}
}