ProfitAfterHelper.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 < 25 && 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. //0.38分万15 0.25分万2 0.3分万7,成本0.23
  191. if(Sort == 30 || Sort == 25)
  192. {
  193. decimal profit = 0;
  194. if(Sort == 25) profit = TotalAmount * 0.0002M;
  195. if(Sort == 30) profit = TotalAmount * 0.0007M;
  196. ProfitUsers user = users[0];
  197. result.Add(new ProfitResult()
  198. {
  199. UserId = user.UserId,
  200. MakerCode = user.MakerCode,
  201. RealName = user.RealName,
  202. UserNav = user.UserNav,
  203. Money = PublicFunction.NumberFormat(profit),
  204. ProfitRate = Sort / 10000,
  205. Fee = Sort,
  206. });
  207. }
  208. else
  209. {
  210. int curLevel = 0; //当前层级的会员等级
  211. for (int curFloor = 1; curFloor <= users.Count; curFloor++)
  212. {
  213. ProfitUsers user = new ProfitUsers();
  214. if (curFloor <= users.Count)
  215. {
  216. user = users[curFloor - 1];
  217. }
  218. SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
  219. int UserLevel = GetUserLevel(selfUser); //当前会员等级
  220. //判断当前创客是否有直推的激活机具,并且在活动时间内
  221. if (curLevel == maxLevel)
  222. {
  223. break;
  224. }
  225. if (UserLevel <= maxLevel && UserLevel >= curLevel)
  226. {
  227. ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel); //获取当前等级参数
  228. if (objlevel != null)
  229. {
  230. decimal getLevelProfit = 0; //等级分润
  231. UserProfitSet profitSet = new UserProfitSet();
  232. decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
  233. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitPercent + ";", "来客吧分润日志");
  234. if (profitPercent > 0)
  235. {
  236. decimal profitTmp = TotalAmount * profitPercent;
  237. getLevelProfit += profitTmp;
  238. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitTmp + ";", "来客吧分润日志");
  239. }
  240. decimal money = getLevelProfit;
  241. getLevelProfit -= diffLevelProfit;
  242. if (objlevel.LevelDiff == 1) //判断是否有级差
  243. {
  244. diffLevelProfit = money;
  245. }
  246. if (getLevelProfit >= obj.MinProfitVal)
  247. {
  248. result.Add(new ProfitResult()
  249. {
  250. UserId = user.UserId,
  251. MakerCode = user.MakerCode,
  252. RealName = user.RealName,
  253. UserNav = user.UserNav,
  254. Money = PublicFunction.NumberFormat(getLevelProfit),
  255. ProfitRate = profitSet.ProfitRate,
  256. ProfitPercent = profitSet.ProfitPercent,
  257. AddOrSubRate = profitSet.AddOrSubRate,
  258. ProfitRateBase = profitSet.ProfitRateBase,
  259. Fee = Sort,
  260. });
  261. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + PublicFunction.NumberFormat(getLevelProfit) + ";", "来客吧分润日志");
  262. }
  263. }
  264. }
  265. if (curLevel < UserLevel)
  266. {
  267. curLevel = UserLevel;
  268. }
  269. }
  270. }
  271. }
  272. db.Dispose();
  273. return result;
  274. }
  275. public SubUser GetUser(int UserId, string Month)
  276. {
  277. SubUser user = new SubUser();
  278. DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
  279. if (dt.Rows.Count > 0)
  280. {
  281. user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
  282. user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
  283. user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
  284. user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
  285. user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
  286. user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
  287. user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
  288. }
  289. return user;
  290. }
  291. public int GetUserLevel(SubUser user)
  292. {
  293. int level = user.UserLevel;
  294. if (user.PreUserLevel > level) level = user.PreUserLevel;
  295. if (user.PreLeaderLevel > level) level = user.PreLeaderLevel;
  296. if (user.PreOpLevel > level) level = user.PreOpLevel;
  297. return level;
  298. }
  299. public DataTable GetDataTable(string sqlstr)
  300. {
  301. DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
  302. return dt;
  303. }
  304. #endregion
  305. public void StartSetDivi()
  306. {
  307. Thread th = new Thread(StartSetDiviDo);
  308. th.IsBackground = true;
  309. th.Start();
  310. }
  311. public void StartSetDiviDo()
  312. {
  313. while (true)
  314. {
  315. string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDiviHd");
  316. if (!string.IsNullOrEmpty(content))
  317. {
  318. SetDivi(content);
  319. }
  320. else
  321. {
  322. Thread.Sleep(10000);
  323. }
  324. }
  325. }
  326. public void SetDivi(string content)
  327. {
  328. try
  329. {
  330. JsonData jsonObj = JsonMapper.ToObject(content);
  331. int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
  332. decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
  333. WebCMSEntities db = new WebCMSEntities();
  334. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
  335. if (order != null)
  336. {
  337. order.CurDivi = diviAmt;
  338. db.SaveChanges();
  339. }
  340. db.Dispose();
  341. }
  342. catch (Exception ex)
  343. {
  344. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
  345. }
  346. }
  347. }
  348. }