ProfitAfterHelper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Data;
  5. using MySystem.Models.Main;
  6. using Library;
  7. using System.Threading;
  8. using Microsoft.Extensions.Hosting;
  9. using System.Threading.Tasks;
  10. using LitJson;
  11. using MySystem.Models;
  12. namespace MySystem
  13. {
  14. public class ProfitAfterHelper
  15. {
  16. public readonly static ProfitAfterHelper Instance = new ProfitAfterHelper();
  17. private ProfitAfterHelper()
  18. {
  19. }
  20. #region 分润
  21. public void StartListenProfit()
  22. {
  23. Thread th = new Thread(StartListenProfitDo);
  24. th.IsBackground = true;
  25. th.Start();
  26. }
  27. public void StartListenProfitDo()
  28. {
  29. while (true)
  30. {
  31. if (DateTime.Now.Day < 10 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 23)
  32. {
  33. try
  34. {
  35. DoProfit();
  36. }
  37. catch (Exception ex)
  38. {
  39. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧分润异常");
  40. }
  41. Thread.Sleep(600000);
  42. }
  43. else
  44. {
  45. Thread.Sleep(3600000);
  46. }
  47. }
  48. }
  49. //分润算法
  50. public void DoProfit()
  51. {
  52. string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
  53. string check = function.ReadInstance("/ProfitFlag/" + TradeMonth + "-after.txt");
  54. if (!string.IsNullOrEmpty(check))
  55. {
  56. return;
  57. }
  58. function.WritePage("/ProfitFlag/", TradeMonth + "-after.txt", DateTime.Now.ToString());
  59. Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
  60. WebCMSEntities dbnew = new WebCMSEntities();
  61. 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);
  62. foreach (DataRow dr in dt.Rows)
  63. {
  64. int UserId = int.Parse(dr["UserId"].ToString());
  65. bool IsActive = dr["IsAct"].ToString() == "1";
  66. int Sort = int.Parse(dr["Sort"].ToString());
  67. decimal TotalAmount = decimal.Parse(dr[2].ToString());
  68. List<ProfitUsers> users = new List<ProfitUsers>();
  69. int TopUserId = 0; //顶级创客Id
  70. Models.KxsMain.Users us = kxsdb.Users.FirstOrDefault(a => a.Id == UserId);
  71. if (us != null)
  72. {
  73. string uidstring = us.Id.ToString();
  74. if (!string.IsNullOrEmpty(us.ParentNav))
  75. {
  76. uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
  77. string[] parents = us.ParentNav.Trim(',').Replace(",,", ",").Split(',');
  78. if (parents.Length > 1)
  79. {
  80. TopUserId = int.Parse(function.CheckInt(parents[1]));
  81. }
  82. else
  83. {
  84. TopUserId = int.Parse(function.CheckInt(parents[0]));
  85. }
  86. }
  87. string[] uidlist = uidstring.Split(',');
  88. Array.Reverse(uidlist);
  89. foreach (string uidstr in uidlist)
  90. {
  91. int puid = int.Parse(function.CheckInt(uidstr));
  92. Models.KxsMain.Users pus = kxsdb.Users.FirstOrDefault(a => a.Id == puid);
  93. if (pus != null)
  94. {
  95. users.Add(new ProfitUsers()
  96. {
  97. UserId = pus.Id,
  98. MakerCode = pus.MakerCode,
  99. RealName = pus.RealName,
  100. UserNav = pus.ParentNav,
  101. UserLevel = pus.UserLevel,
  102. CreateDate = pus.CreateDate.Value,
  103. });
  104. }
  105. }
  106. }
  107. Models.KxsMain.Users topUser = kxsdb.Users.FirstOrDefault(a => a.Id == TopUserId) ?? new Models.KxsMain.Users();
  108. LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + ";", "来客吧分润日志");
  109. List<ProfitResult> list = new List<ProfitResult>();
  110. list = StartProft(TotalAmount, 1, users, Sort, IsActive);
  111. LogHelper.Instance.WriteLog("---list:" + list.Count + ";", "来客吧分润日志");
  112. try
  113. {
  114. foreach (ProfitResult sub in list)
  115. {
  116. int ProfitType = sub.UserId == UserId ? 0 : 1;
  117. ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth);
  118. if (editprofitrecord == null)
  119. {
  120. editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
  121. {
  122. CreateDate = DateTime.Now,
  123. UserId = sub.UserId, //创客
  124. BrandId = 1, //品牌
  125. ProfitType = ProfitType, //创客分润类型
  126. TradeMonth = TradeMonth, //交易月
  127. TopUserId = TopUserId, //顶级创客
  128. CreateMan = sub.MakerCode, //创客编号
  129. UpdateMan = topUser.MakerCode, //顶级编号
  130. SeoTitle = sub.RealName, //创客姓名
  131. SeoKeyword = topUser.RealName, //创客姓名
  132. }).Entity;
  133. dbnew.SaveChanges();
  134. string RecordNo = "KPM";
  135. int RecordId = editprofitrecord.Id;
  136. string RecordIdString = RecordId.ToString();
  137. for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
  138. {
  139. RecordIdString = "0" + RecordIdString;
  140. }
  141. RecordNo += RecordIdString;
  142. editprofitrecord.RecordNo = RecordNo;
  143. dbnew.SaveChanges();
  144. }
  145. if (IsActive)
  146. {
  147. editprofitrecord.CreditTradeAmt += TotalAmount;
  148. editprofitrecord.CreditTradeProfit += sub.Money;
  149. }
  150. else
  151. {
  152. editprofitrecord.TradeAmt += TotalAmount;
  153. editprofitrecord.TradeProfit += sub.Money;
  154. }
  155. dbnew.SaveChanges();
  156. }
  157. dbnew.SaveChanges();
  158. }
  159. catch (Exception ex)
  160. {
  161. LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
  162. }
  163. }
  164. dbnew.Dispose();
  165. kxsdb.Dispose();
  166. }
  167. #endregion
  168. #region 分润算法
  169. public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, int Sort, bool IsActive = true)
  170. {
  171. LogHelper.Instance.WriteLog("\n\nTotalAmount:" + TotalAmount + ";", "来客吧分润日志");
  172. string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
  173. WebCMSEntities db = new WebCMSEntities();
  174. List<UserLevelSet> levels = db.UserLevelSet.ToList();
  175. List<ProfitResult> result = new List<ProfitResult>();
  176. ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
  177. if (obj.Status == 1) //判断分润是否开启
  178. {
  179. int maxLevel = obj.MaxLevel; //最大等级
  180. int maxFloor = obj.MaxFloor; //最大层级
  181. decimal diffLevelProfit = 0; //等级级差
  182. ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == 9) ?? new ProfitObjectLevels(); //获取最高等级参数
  183. decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
  184. LogHelper.Instance.WriteLog("maxPercent:" + maxPercent + ";", "来客吧分润日志");
  185. decimal maxLevelProfit = TotalAmount * maxPercent;
  186. LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
  187. maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
  188. LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
  189. // decimal diffDiviProfit = 0; //分红级差
  190. int curLevel = 0; //当前层级的会员等级
  191. for (int curFloor = 1; curFloor <= users.Count; curFloor++)
  192. {
  193. ProfitUsers user = new ProfitUsers();
  194. if (curFloor <= users.Count)
  195. {
  196. user = users[curFloor - 1];
  197. }
  198. SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
  199. int UserLevel = GetUserLevel(selfUser); //当前会员等级
  200. //判断当前创客是否有直推的激活机具,并且在活动时间内
  201. if (curLevel == maxLevel)
  202. {
  203. break;
  204. }
  205. if (UserLevel <= maxLevel && UserLevel >= curLevel)
  206. {
  207. ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel && m.Sort == Sort); //获取当前等级参数
  208. if (objlevel != null)
  209. {
  210. decimal getLevelProfit = 0; //等级分润
  211. UserProfitSet profitSet = new UserProfitSet();
  212. decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
  213. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitPercent + ";", "来客吧分润日志");
  214. if (profitPercent > 0)
  215. {
  216. decimal profitTmp = TotalAmount * profitPercent;
  217. getLevelProfit += profitTmp;
  218. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitTmp + ";", "来客吧分润日志");
  219. }
  220. decimal money = getLevelProfit;
  221. getLevelProfit -= diffLevelProfit;
  222. if (objlevel.LevelDiff == 1) //判断是否有级差
  223. {
  224. diffLevelProfit = money;
  225. }
  226. if (getLevelProfit >= obj.MinProfitVal)
  227. {
  228. result.Add(new ProfitResult()
  229. {
  230. UserId = user.UserId,
  231. MakerCode = user.MakerCode,
  232. RealName = user.RealName,
  233. UserNav = user.UserNav,
  234. Money = PublicFunction.NumberFormat(getLevelProfit),
  235. ProfitRate = profitSet.ProfitRate,
  236. ProfitPercent = profitSet.ProfitPercent,
  237. AddOrSubRate = profitSet.AddOrSubRate,
  238. ProfitRateBase = profitSet.ProfitRateBase,
  239. Fee = Sort,
  240. });
  241. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + PublicFunction.NumberFormat(getLevelProfit) + ";", "来客吧分润日志");
  242. }
  243. }
  244. }
  245. if (curLevel < UserLevel)
  246. {
  247. curLevel = UserLevel;
  248. }
  249. }
  250. }
  251. db.Dispose();
  252. return result;
  253. }
  254. public SubUser GetUser(int UserId, string Month)
  255. {
  256. SubUser user = new SubUser();
  257. DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
  258. if (dt.Rows.Count > 0)
  259. {
  260. user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
  261. user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
  262. user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
  263. user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
  264. user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
  265. user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
  266. user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
  267. }
  268. return user;
  269. }
  270. public int GetUserLevel(SubUser user)
  271. {
  272. int level = user.UserLevel;
  273. if (user.PreUserLevel > level) level = user.PreUserLevel;
  274. if (user.PreLeaderLevel > level) level = user.PreLeaderLevel;
  275. if (user.PreOpLevel > level) level = user.PreOpLevel;
  276. return level;
  277. }
  278. public DataTable GetDataTable(string sqlstr)
  279. {
  280. DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
  281. return dt;
  282. }
  283. #endregion
  284. public void StartSetDivi()
  285. {
  286. Thread th = new Thread(StartSetDiviDo);
  287. th.IsBackground = true;
  288. th.Start();
  289. }
  290. public void StartSetDiviDo()
  291. {
  292. while (true)
  293. {
  294. string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDiviHd");
  295. if (!string.IsNullOrEmpty(content))
  296. {
  297. SetDivi(content);
  298. }
  299. else
  300. {
  301. Thread.Sleep(10000);
  302. }
  303. }
  304. }
  305. public void SetDivi(string content)
  306. {
  307. try
  308. {
  309. JsonData jsonObj = JsonMapper.ToObject(content);
  310. int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
  311. decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
  312. WebCMSEntities db = new WebCMSEntities();
  313. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
  314. if (order != null)
  315. {
  316. order.CurDivi = diviAmt;
  317. db.SaveChanges();
  318. }
  319. db.Dispose();
  320. }
  321. catch (Exception ex)
  322. {
  323. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
  324. }
  325. }
  326. }
  327. }