浏览代码

分润分新政

lcl 1 月之前
父节点
当前提交
a5c2e2a2f7

+ 1 - 0
Entity/SubUser.cs

@@ -7,6 +7,7 @@ namespace MySystem
         public int Id { get; set; }
         public int ParentUserId { get; set; }
         public string ParentNav { get; set; }
+        public int Level { get; set; }
         public int UserLevel { get; set; }
         public int PreUserLevel { get; set; }
         public int PreLeaderLevel { get; set; }

+ 26 - 27
Util/HaoDa/ProfitAfterHelper.cs

@@ -65,7 +65,8 @@ namespace MySystem
             function.WritePage("/ProfitFlag/", TradeMonth + "-after.txt", DateTime.Now.ToString());
             Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
             WebCMSEntities dbnew = new WebCMSEntities();
-            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount),Sort from UserAmountSummaryAfter where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId,Sort", AppConfig.Base.SqlConnStr);
+            KxsUserModels.WebCMSEntities udb = new KxsUserModels.WebCMSEntities();
+            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount),Sort from UserAmountSummaryOldAfter where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId,Sort", AppConfig.Base.SqlConnStr);
             foreach (DataRow dr in dt.Rows)
             {
                 int UserId = int.Parse(dr["UserId"].ToString());
@@ -74,14 +75,14 @@ namespace MySystem
                 decimal TotalAmount = decimal.Parse(dr[2].ToString());
                 List<ProfitUsers> users = new List<ProfitUsers>();
                 int TopUserId = 0; //顶级创客Id
-                Models.KxsMain.Users us = kxsdb.Users.FirstOrDefault(a => a.Id == UserId);
+                KxsUserModels.KxsUser us = udb.KxsUser.FirstOrDefault(a => a.Id == UserId);
                 if (us != null)
                 {
                     string uidstring = us.Id.ToString();
-                    if (!string.IsNullOrEmpty(us.ParentNav))
+                    if (!string.IsNullOrEmpty(us.PidPath))
                     {
-                        uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
-                        string[] parents = us.ParentNav.Trim(',').Replace(",,", ",").Split(',');
+                        uidstring = us.PidPath.Trim(',').Replace(",,", ",") + "," + uidstring;
+                        string[] parents = us.PidPath.Trim(',').Replace(",,", ",").Split(',');
                         if (parents.Length > 1)
                         {
                             TopUserId = int.Parse(function.CheckInt(parents[1]));
@@ -96,22 +97,22 @@ namespace MySystem
                     foreach (string uidstr in uidlist)
                     {
                         int puid = int.Parse(function.CheckInt(uidstr));
-                        Models.KxsMain.Users pus = kxsdb.Users.FirstOrDefault(a => a.Id == puid);
+                        KxsUserModels.KxsUser pus = udb.KxsUser.FirstOrDefault(a => a.Id == puid);
                         if (pus != null)
                         {
                             users.Add(new ProfitUsers()
                             {
                                 UserId = pus.Id,
-                                MakerCode = pus.MakerCode,
-                                RealName = pus.RealName,
-                                UserNav = pus.ParentNav,
+                                MakerCode = pus.UserCode,
+                                RealName = pus.Username,
+                                UserNav = pus.PidPath,
                                 UserLevel = pus.UserLevel,
-                                CreateDate = pus.CreateDate.Value,
+                                CreateDate = pus.CreateTime.Value,
                             });
                         }
                     }
                 }
-                Models.KxsMain.Users topUser = kxsdb.Users.FirstOrDefault(a => a.Id == TopUserId) ?? new Models.KxsMain.Users();
+                KxsUserModels.KxsUser topUser = udb.KxsUser.FirstOrDefault(a => a.Id == TopUserId) ?? new KxsUserModels.KxsUser();
                 LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + ";", "来客吧分润日志");
                 List<ProfitResult> list = new List<ProfitResult>();
                 list = StartProft(TotalAmount, 1, users, Sort, IsActive);
@@ -133,9 +134,9 @@ namespace MySystem
                                 TradeMonth = TradeMonth, //交易月
                                 TopUserId = TopUserId, //顶级创客
                                 CreateMan = sub.MakerCode, //创客编号
-                                UpdateMan = topUser.MakerCode, //顶级编号
+                                UpdateMan = topUser.UserCode, //顶级编号
                                 SeoTitle = sub.RealName, //创客姓名
-                                SeoKeyword = topUser.RealName, //创客姓名
+                                SeoKeyword = topUser.Username, //创客姓名
                                 Sort = Sort,
                             }).Entity;
                             dbnew.SaveChanges();
@@ -171,6 +172,7 @@ namespace MySystem
             }
             dbnew.Dispose();
             kxsdb.Dispose();
+            udb.Dispose();
         }
 
         #endregion
@@ -235,7 +237,7 @@ namespace MySystem
                         }
                         if (UserLevel <= maxLevel && UserLevel >= curLevel)
                         {
-                            ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel); //获取当前等级参数
+                            ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel && m.Version == 0); //获取当前等级参数
                             if (objlevel != null)
                             {
                                 decimal getLevelProfit = 0;  //等级分润
@@ -287,32 +289,29 @@ namespace MySystem
         public SubUser GetUser(int UserId, string Month)
         {
             SubUser user = new SubUser();
-            DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
+            DataTable dt = GetDataTable("select * from kxs_trade_level_log where trade_month=" + Month + " where user_id=" + UserId);
             if (dt.Rows.Count > 0)
             {
-                user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
+                user.Id = int.Parse(dt.Rows[0]["user_id"].ToString());
                 user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
-                user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
-                user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
-                user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
-                user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
-                user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
+                user.Level = int.Parse(dt.Rows[0]["level"].ToString());
+                user.ParentNav = dt.Rows[0]["pid_path"].ToString();
+                user.UserLevel = int.Parse(dt.Rows[0]["user_level"].ToString());
+                user.PreUserLevel = int.Parse(dt.Rows[0]["pre_level"].ToString());
+                user.PreLeaderLevel = int.Parse(dt.Rows[0]["leader_level"].ToString());
             }
             return user;
         }
 
         public int GetUserLevel(SubUser user)
         {
-            int level = user.UserLevel;
-            if (user.PreUserLevel > level) level = user.PreUserLevel;
-            if (user.PreLeaderLevel > level) level = user.PreLeaderLevel;
-            if (user.PreOpLevel > level) level = user.PreOpLevel;
-            return level;
+            int[] levels = new int[] { user.Level, user.UserLevel, user.PreUserLevel, user.PreLeaderLevel };
+            return levels.ToList().Max();
         }
 
         public DataTable GetDataTable(string sqlstr)
         {
-            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
+            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsUserSqlConnStr"].ToString());
             return dt;
         }
         #endregion

+ 366 - 0
Util/HaoDa/ProfitAfterNewHelper.cs

@@ -0,0 +1,366 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Data;
+using MySystem.Models.Main;
+using Library;
+using System.Threading;
+using Microsoft.Extensions.Hosting;
+using System.Threading.Tasks;
+using LitJson;
+using MySystem.Models;
+
+namespace MySystem
+{
+    public class ProfitAfterNewHelper
+    {
+        public readonly static ProfitAfterNewHelper Instance = new ProfitAfterNewHelper();
+        private ProfitAfterNewHelper()
+        {
+        }
+
+
+
+        #region 分润
+
+        public void StartListenProfit()
+        {
+            Thread th = new Thread(StartListenProfitDo);
+            th.IsBackground = true;
+            th.Start();
+        }
+
+        public void StartListenProfitDo()
+        {
+            while (true)
+            {
+                if (DateTime.Now.Day < 25 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 23)
+                {
+                    try
+                    {
+                        DoProfit();
+                    }
+                    catch (Exception ex)
+                    {
+                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧分润异常");
+                    }
+                    Thread.Sleep(600000);
+                }
+                else
+                {
+                    Thread.Sleep(3600000);
+                }
+            }
+        }
+
+        //分润算法
+        public void DoProfit()
+        {
+            string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
+            string check = function.ReadInstance("/ProfitFlag/" + TradeMonth + "-after-new.txt");
+            if (!string.IsNullOrEmpty(check))
+            {
+                return;
+            }
+            function.WritePage("/ProfitFlag/", TradeMonth + "-after-new.txt", DateTime.Now.ToString());
+            Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
+            WebCMSEntities dbnew = new WebCMSEntities();
+            KxsUserModels.WebCMSEntities udb = new KxsUserModels.WebCMSEntities();
+            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount),Sort from UserAmountSummaryNewAfter where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId,Sort", AppConfig.Base.SqlConnStr);
+            foreach (DataRow dr in dt.Rows)
+            {
+                int UserId = int.Parse(dr["UserId"].ToString());
+                bool IsActive = dr["IsAct"].ToString() == "1";
+                int Sort = int.Parse(dr["Sort"].ToString());
+                decimal TotalAmount = decimal.Parse(dr[2].ToString());
+                List<ProfitUsers> users = new List<ProfitUsers>();
+                int TopUserId = 0; //顶级创客Id
+                KxsUserModels.KxsUser us = udb.KxsUser.FirstOrDefault(a => a.Id == UserId);
+                if (us != null)
+                {
+                    string uidstring = us.Id.ToString();
+                    if (!string.IsNullOrEmpty(us.PidPath))
+                    {
+                        uidstring = us.PidPath.Trim(',').Replace(",,", ",") + "," + uidstring;
+                        string[] parents = us.PidPath.Trim(',').Replace(",,", ",").Split(',');
+                        if (parents.Length > 1)
+                        {
+                            TopUserId = int.Parse(function.CheckInt(parents[1]));
+                        }
+                        else
+                        {
+                            TopUserId = int.Parse(function.CheckInt(parents[0]));
+                        }
+                    }
+                    string[] uidlist = uidstring.Split(',');
+                    Array.Reverse(uidlist);
+                    foreach (string uidstr in uidlist)
+                    {
+                        int puid = int.Parse(function.CheckInt(uidstr));
+                        KxsUserModels.KxsUser pus = udb.KxsUser.FirstOrDefault(a => a.Id == puid);
+                        if (pus != null)
+                        {
+                            users.Add(new ProfitUsers()
+                            {
+                                UserId = pus.Id,
+                                MakerCode = pus.UserCode,
+                                RealName = pus.Username,
+                                UserNav = pus.PidPath,
+                                UserLevel = pus.UserLevel,
+                                CreateDate = pus.CreateTime.Value,
+                            });
+                        }
+                    }
+                }
+                KxsUserModels.KxsUser topUser = udb.KxsUser.FirstOrDefault(a => a.Id == TopUserId) ?? new KxsUserModels.KxsUser();
+                LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + ";", "来客吧分润日志");
+                List<ProfitResult> list = new List<ProfitResult>();
+                list = StartProft(TotalAmount, 1, users, Sort, IsActive);
+                LogHelper.Instance.WriteLog("---list:" + list.Count + ";", "来客吧分润日志");
+                try
+                {
+                    foreach (ProfitResult sub in list)
+                    {
+                        int ProfitType = sub.UserId == UserId ? 0 : 1;
+                        ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth && m.Sort == Sort);
+                        if (editprofitrecord == null)
+                        {
+                            editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
+                            {
+                                CreateDate = DateTime.Now,
+                                UserId = sub.UserId, //创客
+                                BrandId = 1, //品牌
+                                ProfitType = ProfitType, //创客分润类型
+                                TradeMonth = TradeMonth, //交易月
+                                TopUserId = TopUserId, //顶级创客
+                                CreateMan = sub.MakerCode, //创客编号
+                                UpdateMan = topUser.UserCode, //顶级编号
+                                SeoTitle = sub.RealName, //创客姓名
+                                SeoKeyword = topUser.Username, //创客姓名
+                                Sort = Sort,
+                            }).Entity;
+                            dbnew.SaveChanges();
+                            string RecordNo = "KPM";
+                            int RecordId = editprofitrecord.Id;
+                            string RecordIdString = RecordId.ToString();
+                            for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
+                            {
+                                RecordIdString = "0" + RecordIdString;
+                            }
+                            RecordNo += RecordIdString;
+                            editprofitrecord.RecordNo = RecordNo;
+                            dbnew.SaveChanges();
+                        }
+                        if (IsActive)
+                        {
+                            editprofitrecord.CreditTradeAmt += TotalAmount;
+                            editprofitrecord.CreditTradeProfit += sub.Money;
+                        }
+                        else
+                        {
+                            editprofitrecord.TradeAmt += TotalAmount;
+                            editprofitrecord.TradeProfit += sub.Money;
+                        }
+                        dbnew.SaveChanges();
+                    }
+                    dbnew.SaveChanges();
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
+                }
+            }
+            dbnew.Dispose();
+            kxsdb.Dispose();
+            udb.Dispose();
+        }
+
+        #endregion
+
+        #region 分润算法
+        public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, int Sort, bool IsActive = true)
+        {
+            LogHelper.Instance.WriteLog("\n\nTotalAmount:" + TotalAmount + ";", "来客吧分润日志");
+            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
+            WebCMSEntities db = new WebCMSEntities();
+            List<UserLevelSet> levels = db.UserLevelSet.ToList();
+            List<ProfitResult> result = new List<ProfitResult>();
+            ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
+            if (obj.Status == 1) //判断分润是否开启
+            {
+                int maxLevel = obj.MaxLevel; //最大等级
+                int maxFloor = obj.MaxFloor; //最大层级
+                decimal diffLevelProfit = 0;  //等级级差
+                ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == 9) ?? new ProfitObjectLevels(); //获取最高等级参数
+                decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
+                LogHelper.Instance.WriteLog("maxPercent:" + maxPercent + ";", "来客吧分润日志");
+                decimal maxLevelProfit = TotalAmount * maxPercent;
+                LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
+                maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
+                LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
+                // decimal diffDiviProfit = 0; //分红级差
+                
+                //0.38分万15  0.25分万2  0.3分万7,成本0.23
+                if(Sort == 30 || Sort == 25)
+                {
+                    decimal profit = 0;
+                    if(Sort == 25) profit = TotalAmount * 0.0002M;
+                    if(Sort == 30) profit = TotalAmount * 0.0005M;
+                    ProfitUsers user = users[0];
+                    result.Add(new ProfitResult()
+                    {
+                        UserId = user.UserId,
+                        MakerCode = user.MakerCode,
+                        RealName = user.RealName,
+                        UserNav = user.UserNav,
+                        Money = PublicFunction.NumberFormat(profit),
+                        ProfitRate = Sort / 10000,
+                        Fee = Sort,
+                    });
+                }
+                else
+                {
+                    int curLevel = 0; //当前层级的会员等级
+                    for (int curFloor = 1; curFloor <= users.Count; curFloor++)
+                    {
+                        ProfitUsers user = new ProfitUsers();
+                        if (curFloor <= users.Count)
+                        {
+                            user = users[curFloor - 1];
+                        }
+                        SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
+                        int UserLevel = GetUserLevel(selfUser); //当前会员等级
+                        //判断当前创客是否有直推的激活机具,并且在活动时间内
+                        if (curLevel == maxLevel)
+                        {
+                            break;
+                        }
+                        if (UserLevel <= maxLevel && UserLevel >= curLevel)
+                        {
+                            ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel && m.Version == 1); //获取当前等级参数
+                            if (objlevel != null)
+                            {
+                                decimal getLevelProfit = 0;  //等级分润
+                                UserProfitSet profitSet = new UserProfitSet();
+                                decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
+                                LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitPercent + ";", "来客吧分润日志");
+                                if (profitPercent > 0)
+                                {
+                                    decimal profitTmp = TotalAmount * profitPercent;
+                                    getLevelProfit += profitTmp;
+                                    LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitTmp + ";", "来客吧分润日志");
+                                }
+                                decimal money = getLevelProfit;
+                                getLevelProfit -= diffLevelProfit;
+                                if (objlevel.LevelDiff == 1)  //判断是否有级差
+                                {
+                                    diffLevelProfit = money;
+                                }
+                                if (getLevelProfit >= obj.MinProfitVal)
+                                {
+                                    result.Add(new ProfitResult()
+                                    {
+                                        UserId = user.UserId,
+                                        MakerCode = user.MakerCode,
+                                        RealName = user.RealName,
+                                        UserNav = user.UserNav,
+                                        Money = PublicFunction.NumberFormat(getLevelProfit),
+                                        ProfitRate = profitSet.ProfitRate,
+                                        ProfitPercent = profitSet.ProfitPercent,
+                                        AddOrSubRate = profitSet.AddOrSubRate,
+                                        ProfitRateBase = profitSet.ProfitRateBase,
+                                        Fee = Sort,
+                                    });
+                                    LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + PublicFunction.NumberFormat(getLevelProfit) + ";", "来客吧分润日志");
+                                }
+                            }
+                        }
+                        if (curLevel < UserLevel)
+                        {
+                            curLevel = UserLevel;
+                        }
+                    }
+                }
+            }
+            db.Dispose();
+            return result;
+        }
+
+        public SubUser GetUser(int UserId, string Month)
+        {
+            SubUser user = new SubUser();
+            DataTable dt = GetDataTable("select * from kxs_trade_level_log where trade_month=" + Month + " where user_id=" + UserId);
+            if (dt.Rows.Count > 0)
+            {
+                user.Id = int.Parse(dt.Rows[0]["user_id"].ToString());
+                user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
+                user.Level = int.Parse(dt.Rows[0]["level"].ToString());
+                user.ParentNav = dt.Rows[0]["pid_path"].ToString();
+                user.UserLevel = int.Parse(dt.Rows[0]["user_level"].ToString());
+                user.PreUserLevel = int.Parse(dt.Rows[0]["pre_level"].ToString());
+                user.PreLeaderLevel = int.Parse(dt.Rows[0]["leader_level"].ToString());
+            }
+            return user;
+        }
+
+        public int GetUserLevel(SubUser user)
+        {
+            int[] levels = new int[] { user.Level, user.UserLevel, user.PreUserLevel, user.PreLeaderLevel };
+            return levels.ToList().Max();
+        }
+
+        public DataTable GetDataTable(string sqlstr)
+        {
+            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsUserSqlConnStr"].ToString());
+            return dt;
+        }
+        #endregion
+
+
+
+
+        public void StartSetDivi()
+        {
+            Thread th = new Thread(StartSetDiviDo);
+            th.IsBackground = true;
+            th.Start();
+        }
+        public void StartSetDiviDo()
+        {
+            while (true)
+            {
+                string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDiviHd");
+                if (!string.IsNullOrEmpty(content))
+                {
+                    SetDivi(content);
+                }
+                else
+                {
+                    Thread.Sleep(10000);
+                }
+            }
+        }
+
+        public void SetDivi(string content)
+        {
+            try
+            {
+                JsonData jsonObj = JsonMapper.ToObject(content);
+                int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
+                decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
+                WebCMSEntities db = new WebCMSEntities();
+                ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
+                if (order != null)
+                {
+                    order.CurDivi = diviAmt;
+                    db.SaveChanges();
+                }
+                db.Dispose();
+            }
+            catch (Exception ex)
+            {
+                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
+            }
+        }
+    }
+}

+ 25 - 28
Util/HaoDa/ProfitBeforeHelper.cs

@@ -66,7 +66,7 @@ namespace MySystem
             Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
             WebCMSEntities dbnew = new WebCMSEntities();
             KxsUserModels.WebCMSEntities udb = new KxsUserModels.WebCMSEntities();
-            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount),Sort from UserAmountSummaryBefore where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId,Sort", AppConfig.Base.SqlConnStr);
+            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount),Sort from UserAmountSummaryOldBefore where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId,Sort", AppConfig.Base.SqlConnStr);
             foreach (DataRow dr in dt.Rows)
             {
                 int UserId = int.Parse(dr["UserId"].ToString());
@@ -75,21 +75,21 @@ namespace MySystem
                 decimal TotalAmount = decimal.Parse(dr[2].ToString());
                 List<ProfitUsers> users = new List<ProfitUsers>();
                 int TopUserId = 0; //顶级创客Id
-                Models.KxsMain.Users us = kxsdb.Users.FirstOrDefault(a => a.Id == UserId);
+                KxsUserModels.KxsUser us = udb.KxsUser.FirstOrDefault(a => a.Id == UserId);
                 if (us != null)
                 {
                     string uidstring = us.Id.ToString();
-                    if (!string.IsNullOrEmpty(us.ParentNav))
+                    if (!string.IsNullOrEmpty(us.PidPath))
                     {
-                        uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
-                        string[] parents = us.ParentNav.Trim(',').Replace(",,", ",").Split(',');
+                        uidstring = us.PidPath.Trim(',').Replace(",,", ",") + "," + uidstring;
+                        string[] parents = us.PidPath.Trim(',').Replace(",,", ",").Split(',');
                         if (parents.Length > 1)
                         {
-                            TopUserId = int.Parse(function.CheckInt(parents[1]));
+                            TopUserId = int.Parse(function.CheckInt(parents[2]));
                         }
                         else
                         {
-                            TopUserId = int.Parse(function.CheckInt(parents[0]));
+                            TopUserId = int.Parse(function.CheckInt(parents[1]));
                         }
                     }
                     string[] uidlist = uidstring.Split(',');
@@ -97,22 +97,22 @@ namespace MySystem
                     foreach (string uidstr in uidlist)
                     {
                         int puid = int.Parse(function.CheckInt(uidstr));
-                        Models.KxsMain.Users pus = kxsdb.Users.FirstOrDefault(a => a.Id == puid);
+                        KxsUserModels.KxsUser pus = udb.KxsUser.FirstOrDefault(a => a.Id == puid);
                         if (pus != null)
                         {
                             users.Add(new ProfitUsers()
                             {
                                 UserId = pus.Id,
-                                MakerCode = pus.MakerCode,
-                                RealName = pus.RealName,
-                                UserNav = pus.ParentNav,
+                                MakerCode = pus.UserCode,
+                                RealName = pus.Username,
+                                UserNav = pus.PidPath,
                                 UserLevel = pus.UserLevel,
-                                CreateDate = pus.CreateDate.Value,
+                                CreateDate = pus.CreateTime.Value,
                             });
                         }
                     }
                 }
-                Models.KxsMain.Users topUser = kxsdb.Users.FirstOrDefault(a => a.Id == TopUserId) ?? new Models.KxsMain.Users();
+                KxsUserModels.KxsUser topUser = udb.KxsUser.FirstOrDefault(a => a.Id == TopUserId) ?? new KxsUserModels.KxsUser();
                 LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + ";", "来客吧分润日志");
                 List<ProfitResult> list = new List<ProfitResult>();
                 list = StartProft(TotalAmount, 1, users, Sort, IsActive);
@@ -134,9 +134,9 @@ namespace MySystem
                                 TradeMonth = TradeMonth, //交易月
                                 TopUserId = TopUserId, //顶级创客
                                 CreateMan = sub.MakerCode, //创客编号
-                                UpdateMan = topUser.MakerCode, //顶级编号
+                                UpdateMan = topUser.UserCode, //顶级编号
                                 SeoTitle = sub.RealName, //创客姓名
-                                SeoKeyword = topUser.RealName, //创客姓名
+                                SeoKeyword = topUser.Username, //创客姓名
                                 Sort = Sort,
                             }).Entity;
                             dbnew.SaveChanges();
@@ -239,7 +239,7 @@ namespace MySystem
                         }
                         if (UserLevel <= maxLevel && UserLevel >= curLevel)
                         {
-                            ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel && m.Sort == Sort); //获取当前等级参数
+                            ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel && m.Version == 0); //获取当前等级参数
                             if (objlevel != null)
                             {
                                 decimal getLevelProfit = 0;  //等级分润
@@ -291,31 +291,28 @@ namespace MySystem
         public SubUser GetUser(int UserId, string Month)
         {
             SubUser user = new SubUser();
-            DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
+            DataTable dt = GetDataTable("select * from kxs_trade_level_log where trade_month=" + Month + " where user_id=" + UserId);
             if (dt.Rows.Count > 0)
             {
-                user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
+                user.Id = int.Parse(dt.Rows[0]["user_id"].ToString());
                 user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
-                user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
-                user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
-                user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
-                user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
-                user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
-                user.PreUserLevelBefore = int.Parse(dt.Rows[0]["PreUserLevelBefore"].ToString());
+                user.Level = int.Parse(dt.Rows[0]["level"].ToString());
+                user.ParentNav = dt.Rows[0]["pid_path"].ToString();
+                user.UserLevel = int.Parse(dt.Rows[0]["user_level"].ToString());
+                user.PreUserLevelBefore = int.Parse(dt.Rows[0]["before_pre_level"].ToString());
             }
             return user;
         }
 
         public int GetUserLevel(SubUser user)
         {
-            int level = user.UserLevel;
-            if(user.PreUserLevelBefore > level) level = user.PreUserLevelBefore;
-            return level;
+            int[] levels = new int[] { user.Level, user.UserLevel, user.PreUserLevelBefore };
+            return levels.ToList().Max();
         }
 
         public DataTable GetDataTable(string sqlstr)
         {
-            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
+            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsUserSqlConnStr"].ToString());
             return dt;
         }
         #endregion

+ 393 - 0
Util/HaoDa/ProfitBeforeNewHelper.cs

@@ -0,0 +1,393 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Data;
+using MySystem.Models.Main;
+using Library;
+using System.Threading;
+using Microsoft.Extensions.Hosting;
+using System.Threading.Tasks;
+using LitJson;
+using MySystem.Models;
+
+namespace MySystem
+{
+    public class ProfitBeforeNewHelper
+    {
+        public readonly static ProfitBeforeNewHelper Instance = new ProfitBeforeNewHelper();
+        private ProfitBeforeNewHelper()
+        {
+        }
+
+
+
+        #region 分润
+
+        public void StartListenProfit()
+        {
+            Thread th = new Thread(StartListenProfitDo);
+            th.IsBackground = true;
+            th.Start();
+        }
+
+        public void StartListenProfitDo()
+        {
+            while (true)
+            {
+                if (DateTime.Now.Day < 25 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 23)
+                {
+                    try
+                    {
+                        DoProfit();
+                    }
+                    catch (Exception ex)
+                    {
+                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧分润异常");
+                    }
+                    Thread.Sleep(600000);
+                }
+                else
+                {
+                    Thread.Sleep(3600000);
+                }
+            }
+        }
+
+        //分润算法
+        public void DoProfit()
+        {
+            string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
+            string check = function.ReadInstance("/ProfitFlag/" + TradeMonth + "-before-new.txt");
+            if (!string.IsNullOrEmpty(check))
+            {
+                return;
+            }
+            function.WritePage("/ProfitFlag/", TradeMonth + "-before-new.txt", DateTime.Now.ToString());
+            Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
+            WebCMSEntities dbnew = new WebCMSEntities();
+            KxsUserModels.WebCMSEntities udb = new KxsUserModels.WebCMSEntities();
+            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount),Sort from UserAmountSummaryNewBefore where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId,Sort", AppConfig.Base.SqlConnStr);
+            foreach (DataRow dr in dt.Rows)
+            {
+                int UserId = int.Parse(dr["UserId"].ToString());
+                bool IsActive = dr["IsAct"].ToString() == "1";
+                int Sort = int.Parse(dr["Sort"].ToString());
+                decimal TotalAmount = decimal.Parse(dr[2].ToString());
+                List<ProfitUsers> users = new List<ProfitUsers>();
+                int TopUserId = 0; //顶级创客Id
+                KxsUserModels.KxsUser us = udb.KxsUser.FirstOrDefault(a => a.Id == UserId);
+                if (us != null)
+                {
+                    string uidstring = us.Id.ToString();
+                    if (!string.IsNullOrEmpty(us.PidPath))
+                    {
+                        uidstring = us.PidPath.Trim(',').Replace(",,", ",") + "," + uidstring;
+                        string[] parents = us.PidPath.Trim(',').Replace(",,", ",").Split(',');
+                        if (parents.Length > 1)
+                        {
+                            TopUserId = int.Parse(function.CheckInt(parents[2]));
+                        }
+                        else
+                        {
+                            TopUserId = int.Parse(function.CheckInt(parents[1]));
+                        }
+                    }
+                    string[] uidlist = uidstring.Split(',');
+                    Array.Reverse(uidlist);
+                    foreach (string uidstr in uidlist)
+                    {
+                        int puid = int.Parse(function.CheckInt(uidstr));
+                        KxsUserModels.KxsUser pus = udb.KxsUser.FirstOrDefault(a => a.Id == puid);
+                        if (pus != null)
+                        {
+                            users.Add(new ProfitUsers()
+                            {
+                                UserId = pus.Id,
+                                MakerCode = pus.UserCode,
+                                RealName = pus.Username,
+                                UserNav = pus.PidPath,
+                                UserLevel = pus.UserLevel,
+                                CreateDate = pus.CreateTime.Value,
+                            });
+                        }
+                    }
+                }
+                KxsUserModels.KxsUser topUser = udb.KxsUser.FirstOrDefault(a => a.Id == TopUserId) ?? new KxsUserModels.KxsUser();
+                LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + ";", "来客吧分润日志");
+                List<ProfitResult> list = new List<ProfitResult>();
+                list = StartProft(TotalAmount, 1, users, Sort, IsActive);
+                LogHelper.Instance.WriteLog("---list:" + list.Count + ";", "来客吧分润日志");
+                try
+                {
+                    foreach (ProfitResult sub in list)
+                    {
+                        int ProfitType = sub.UserId == UserId ? 0 : 1;
+                        ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth && m.Sort == Sort);
+                        if (editprofitrecord == null)
+                        {
+                            editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
+                            {
+                                CreateDate = DateTime.Now,
+                                UserId = sub.UserId, //创客
+                                BrandId = 1, //品牌
+                                ProfitType = ProfitType, //创客分润类型
+                                TradeMonth = TradeMonth, //交易月
+                                TopUserId = TopUserId, //顶级创客
+                                CreateMan = sub.MakerCode, //创客编号
+                                UpdateMan = topUser.UserCode, //顶级编号
+                                SeoTitle = sub.RealName, //创客姓名
+                                SeoKeyword = topUser.Username, //创客姓名
+                                Sort = Sort,
+                            }).Entity;
+                            dbnew.SaveChanges();
+                            string RecordNo = "KPM";
+                            int RecordId = editprofitrecord.Id;
+                            string RecordIdString = RecordId.ToString();
+                            for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
+                            {
+                                RecordIdString = "0" + RecordIdString;
+                            }
+                            RecordNo += RecordIdString;
+                            editprofitrecord.RecordNo = RecordNo;
+                            dbnew.SaveChanges();
+                        }
+                        if (IsActive)
+                        {
+                            editprofitrecord.CreditTradeAmt += TotalAmount;
+                            editprofitrecord.CreditTradeProfit += sub.Money;
+                        }
+                        else
+                        {
+                            editprofitrecord.TradeAmt += TotalAmount;
+                            editprofitrecord.TradeProfit += sub.Money;
+                        }
+                        dbnew.SaveChanges();
+
+                        AddJavaProfitRecord(udb, sub.UserId, sub.Money, TradeMonth, 1, "", ProfitType);
+                    }
+                    dbnew.SaveChanges();
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
+                }
+            }
+            dbnew.Dispose();
+            kxsdb.Dispose();
+            udb.Dispose();
+        }
+
+        #endregion
+
+        #region 分润算法
+        public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, int Sort, bool IsActive = true)
+        {
+            LogHelper.Instance.WriteLog("\n\nTotalAmount:" + TotalAmount + ";", "来客吧分润日志");
+            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
+            WebCMSEntities db = new WebCMSEntities();
+            List<UserLevelSet> levels = db.UserLevelSet.ToList();
+            List<ProfitResult> result = new List<ProfitResult>();
+            ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
+            if (obj.Status == 1) //判断分润是否开启
+            {
+                int maxLevel = obj.MaxLevel; //最大等级
+                int maxFloor = obj.MaxFloor; //最大层级
+                decimal diffLevelProfit = 0;  //等级级差
+                ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == 9) ?? new ProfitObjectLevels(); //获取最高等级参数
+                decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
+                LogHelper.Instance.WriteLog("maxPercent:" + maxPercent + ";", "来客吧分润日志");
+                decimal maxLevelProfit = TotalAmount * maxPercent;
+                LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
+                maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
+                LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
+                // decimal diffDiviProfit = 0; //分红级差
+
+                //0.38分万15  0.25分万2  0.3分万7,成本0.23
+                if(Sort == 30 || Sort == 25)
+                {
+                    decimal profit = 0;
+                    if(Sort == 25) profit = TotalAmount * 0.0002M;
+                    if(Sort == 30) profit = TotalAmount * 0.0005M;
+                    ProfitUsers user = users[0];
+                    result.Add(new ProfitResult()
+                    {
+                        UserId = user.UserId,
+                        MakerCode = user.MakerCode,
+                        RealName = user.RealName,
+                        UserNav = user.UserNav,
+                        Money = PublicFunction.NumberFormat(profit),
+                        ProfitRate = Sort / 10000,
+                        Fee = Sort,
+                    });
+                }
+                else
+                {
+                    int curLevel = 0; //当前层级的会员等级
+                    for (int curFloor = 1; curFloor <= users.Count; curFloor++)
+                    {
+                        ProfitUsers user = new ProfitUsers();
+                        if (curFloor <= users.Count)
+                        {
+                            user = users[curFloor - 1];
+                        }
+                        SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
+                        int UserLevel = GetUserLevel(selfUser); //当前会员等级
+                        //判断当前创客是否有直推的激活机具,并且在活动时间内
+                        if (curLevel == maxLevel)
+                        {
+                            break;
+                        }
+                        if (UserLevel <= maxLevel && UserLevel >= curLevel)
+                        {
+                            ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel && m.Version == 1); //获取当前等级参数
+                            if (objlevel != null)
+                            {
+                                decimal getLevelProfit = 0;  //等级分润
+                                UserProfitSet profitSet = new UserProfitSet();
+                                decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
+                                LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitPercent + ";", "来客吧分润日志");
+                                if (profitPercent > 0)
+                                {
+                                    decimal profitTmp = TotalAmount * profitPercent;
+                                    getLevelProfit += profitTmp;
+                                    LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitTmp + ";", "来客吧分润日志");
+                                }
+                                decimal money = getLevelProfit;
+                                getLevelProfit -= diffLevelProfit;
+                                if (objlevel.LevelDiff == 1)  //判断是否有级差
+                                {
+                                    diffLevelProfit = money;
+                                }
+                                if (getLevelProfit >= obj.MinProfitVal)
+                                {
+                                    result.Add(new ProfitResult()
+                                    {
+                                        UserId = user.UserId,
+                                        MakerCode = user.MakerCode,
+                                        RealName = user.RealName,
+                                        UserNav = user.UserNav,
+                                        Money = PublicFunction.NumberFormat(getLevelProfit),
+                                        ProfitRate = profitSet.ProfitRate,
+                                        ProfitPercent = profitSet.ProfitPercent,
+                                        AddOrSubRate = profitSet.AddOrSubRate,
+                                        ProfitRateBase = profitSet.ProfitRateBase,
+                                        Fee = Sort,
+                                    });
+                                    LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + PublicFunction.NumberFormat(getLevelProfit) + ";", "来客吧分润日志");
+                                }
+                            }
+                        }
+                        if (curLevel < UserLevel)
+                        {
+                            curLevel = UserLevel;
+                        }
+                    }
+                }
+            }
+            db.Dispose();
+            return result;
+        }
+
+        public SubUser GetUser(int UserId, string Month)
+        {
+            SubUser user = new SubUser();
+            DataTable dt = GetDataTable("select * from kxs_trade_level_log where trade_month=" + Month + " where user_id=" + UserId);
+            if (dt.Rows.Count > 0)
+            {
+                user.Id = int.Parse(dt.Rows[0]["user_id"].ToString());
+                user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
+                user.Level = int.Parse(dt.Rows[0]["level"].ToString());
+                user.ParentNav = dt.Rows[0]["pid_path"].ToString();
+                user.UserLevel = int.Parse(dt.Rows[0]["user_level"].ToString());
+                user.PreUserLevelBefore = int.Parse(dt.Rows[0]["before_pre_level"].ToString());
+            }
+            return user;
+        }
+
+        public int GetUserLevel(SubUser user)
+        {
+            int[] levels = new int[] { user.Level, user.UserLevel, user.PreUserLevelBefore };
+            return levels.ToList().Max();
+        }
+
+        public DataTable GetDataTable(string sqlstr)
+        {
+            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsUserSqlConnStr"].ToString());
+            return dt;
+        }
+        #endregion
+
+
+
+
+        public void StartSetDivi()
+        {
+            Thread th = new Thread(StartSetDiviDo);
+            th.IsBackground = true;
+            th.Start();
+        }
+        public void StartSetDiviDo()
+        {
+            while (true)
+            {
+                string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDiviHd");
+                if (!string.IsNullOrEmpty(content))
+                {
+                    SetDivi(content);
+                }
+                else
+                {
+                    Thread.Sleep(10000);
+                }
+            }
+        }
+
+        public void SetDivi(string content)
+        {
+            try
+            {
+                JsonData jsonObj = JsonMapper.ToObject(content);
+                int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
+                decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
+                WebCMSEntities db = new WebCMSEntities();
+                ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
+                if (order != null)
+                {
+                    order.CurDivi = diviAmt;
+                    db.SaveChanges();
+                }
+                db.Dispose();
+            }
+            catch (Exception ex)
+            {
+                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
+            }
+        }
+
+
+
+        //奖励入库给java数据库
+        private void AddJavaProfitRecord(KxsUserModels.WebCMSEntities db, int UserId, decimal Prize, string TradeMonth, int RewardType, string Remark, int IsTeam)
+        {
+            int ProfitMonth = int.Parse(TradeMonth);
+            KxsUserModels.KxsUserProfitLkb item = db.KxsUserProfitLkb.FirstOrDefault(m => m.UserId == UserId && m.TradeType == RewardType && m.ProfitMonth == ProfitMonth);
+            if(item == null)
+            {
+                item = db.KxsUserProfitLkb.Add(new KxsUserModels.KxsUserProfitLkb()
+                {
+                    IsTeam = IsTeam,
+                    TradeType = RewardType,
+                    Remark = Remark,
+                    ProfitMonth = ProfitMonth,
+                    ProfitAmt = Prize,
+                    UserId = UserId,
+                    UpdateTime = DateTime.Now,
+                    CreateTime = DateTime.Now,
+                }).Entity;
+                db.SaveChanges();
+            }
+            item.ProfitAmt += Prize;
+            db.SaveChanges();
+        }
+    }
+}