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. KxsUserModels.WebCMSEntities udb = new KxsUserModels.WebCMSEntities();
  62. 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);
  63. foreach (DataRow dr in dt.Rows)
  64. {
  65. int UserId = int.Parse(dr["UserId"].ToString());
  66. bool IsActive = dr["IsAct"].ToString() == "1";
  67. int Sort = int.Parse(dr["Sort"].ToString());
  68. decimal TotalAmount = decimal.Parse(dr[2].ToString());
  69. List<ProfitUsers> users = new List<ProfitUsers>();
  70. int TopUserId = 0; //顶级创客Id
  71. KxsUserModels.KxsUser us = udb.KxsUser.FirstOrDefault(a => a.Id == UserId);
  72. if (us != null)
  73. {
  74. string uidstring = us.Id.ToString();
  75. if (!string.IsNullOrEmpty(us.PidPath))
  76. {
  77. uidstring = us.PidPath.Trim(',').Replace(",,", ",") + "," + uidstring;
  78. string[] parents = us.PidPath.Trim(',').Replace(",,", ",").Split(',');
  79. if (parents.Length > 1)
  80. {
  81. TopUserId = int.Parse(function.CheckInt(parents[1]));
  82. }
  83. else
  84. {
  85. TopUserId = int.Parse(function.CheckInt(parents[0]));
  86. }
  87. }
  88. string[] uidlist = uidstring.Split(',');
  89. Array.Reverse(uidlist);
  90. foreach (string uidstr in uidlist)
  91. {
  92. int puid = int.Parse(function.CheckInt(uidstr));
  93. KxsUserModels.KxsUser pus = udb.KxsUser.FirstOrDefault(a => a.Id == puid);
  94. if (pus != null)
  95. {
  96. users.Add(new ProfitUsers()
  97. {
  98. UserId = pus.Id,
  99. MakerCode = pus.UserCode,
  100. RealName = pus.Username,
  101. UserNav = pus.PidPath,
  102. UserLevel = pus.UserLevel,
  103. CreateDate = pus.CreateTime.Value,
  104. });
  105. }
  106. }
  107. }
  108. KxsUserModels.KxsUser topUser = udb.KxsUser.FirstOrDefault(a => a.Id == TopUserId) ?? new KxsUserModels.KxsUser();
  109. LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + ";", "来客吧分润日志");
  110. List<ProfitResult> list = new List<ProfitResult>();
  111. list = StartProft(TotalAmount, 1, users, Sort, IsActive);
  112. LogHelper.Instance.WriteLog("---list:" + list.Count + ";", "来客吧分润日志");
  113. try
  114. {
  115. foreach (ProfitResult sub in list)
  116. {
  117. int ProfitType = sub.UserId == UserId ? 0 : 1;
  118. ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.Version == 0 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth && m.Sort == Sort);
  119. if (editprofitrecord == null)
  120. {
  121. editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
  122. {
  123. CreateDate = DateTime.Now,
  124. UserId = sub.UserId, //创客
  125. BrandId = 1, //品牌
  126. ProfitType = ProfitType, //创客分润类型
  127. TradeMonth = TradeMonth, //交易月
  128. TopUserId = TopUserId, //顶级创客
  129. CreateMan = sub.MakerCode, //创客编号
  130. UpdateMan = topUser.UserCode, //顶级编号
  131. SeoTitle = sub.RealName, //创客姓名
  132. SeoKeyword = topUser.Username, //创客姓名
  133. Sort = Sort,
  134. }).Entity;
  135. dbnew.SaveChanges();
  136. string RecordNo = "KPM";
  137. int RecordId = editprofitrecord.Id;
  138. string RecordIdString = RecordId.ToString();
  139. for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
  140. {
  141. RecordIdString = "0" + RecordIdString;
  142. }
  143. RecordNo += RecordIdString;
  144. editprofitrecord.RecordNo = RecordNo;
  145. dbnew.SaveChanges();
  146. }
  147. if (IsActive)
  148. {
  149. editprofitrecord.CreditTradeAmt += TotalAmount;
  150. editprofitrecord.CreditTradeProfit += sub.Money;
  151. }
  152. else
  153. {
  154. editprofitrecord.TradeAmt += TotalAmount;
  155. editprofitrecord.TradeProfit += sub.Money;
  156. }
  157. dbnew.SaveChanges();
  158. }
  159. dbnew.SaveChanges();
  160. }
  161. catch (Exception ex)
  162. {
  163. LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
  164. }
  165. }
  166. dbnew.Dispose();
  167. kxsdb.Dispose();
  168. udb.Dispose();
  169. }
  170. #endregion
  171. #region 分润算法
  172. public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, int Sort, bool IsActive = true)
  173. {
  174. LogHelper.Instance.WriteLog("\n\nTotalAmount:" + TotalAmount + ";", "来客吧分润日志");
  175. string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
  176. WebCMSEntities db = new WebCMSEntities();
  177. List<UserLevelSet> levels = db.UserLevelSet.ToList();
  178. List<ProfitResult> result = new List<ProfitResult>();
  179. ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
  180. if (obj.Status == 1) //判断分润是否开启
  181. {
  182. int maxLevel = obj.MaxLevel; //最大等级
  183. int maxFloor = obj.MaxFloor; //最大层级
  184. decimal diffLevelProfit = 0; //等级级差
  185. ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.LevelNumber == 9) ?? new ProfitObjectLevels(); //获取最高等级参数
  186. decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
  187. LogHelper.Instance.WriteLog("maxPercent:" + maxPercent + ";", "来客吧分润日志");
  188. decimal maxLevelProfit = TotalAmount * maxPercent;
  189. LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
  190. maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
  191. LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
  192. // decimal diffDiviProfit = 0; //分红级差
  193. //0.38分万15 0.25分万2 0.3分万7,成本0.23
  194. if(Sort == 30 || Sort == 25)
  195. {
  196. decimal profit = 0;
  197. if(Sort == 25) profit = TotalAmount * 0.0002M;
  198. if(Sort == 30) profit = TotalAmount * 0.0005M;
  199. ProfitUsers user = users[0];
  200. result.Add(new ProfitResult()
  201. {
  202. UserId = user.UserId,
  203. MakerCode = user.MakerCode,
  204. RealName = user.RealName,
  205. UserNav = user.UserNav,
  206. Money = PublicFunction.NumberFormat(profit),
  207. ProfitRate = Sort / 10000,
  208. Fee = Sort,
  209. });
  210. }
  211. else
  212. {
  213. int curLevel = 0; //当前层级的会员等级
  214. for (int curFloor = 1; curFloor <= users.Count; curFloor++)
  215. {
  216. ProfitUsers user = new ProfitUsers();
  217. if (curFloor <= users.Count)
  218. {
  219. user = users[curFloor - 1];
  220. }
  221. SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
  222. int UserLevel = GetUserLevel(selfUser); //当前会员等级
  223. //判断当前创客是否有直推的激活机具,并且在活动时间内
  224. if (curLevel == maxLevel)
  225. {
  226. break;
  227. }
  228. if (UserLevel <= maxLevel && UserLevel >= curLevel)
  229. {
  230. ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.LevelNumber == UserLevel && m.Version == 0); //获取当前等级参数
  231. if (objlevel != null)
  232. {
  233. decimal getLevelProfit = 0; //等级分润
  234. UserProfitSet profitSet = new UserProfitSet();
  235. decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
  236. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitPercent + ";", "来客吧分润日志");
  237. if (profitPercent > 0)
  238. {
  239. decimal profitTmp = TotalAmount * profitPercent;
  240. getLevelProfit += profitTmp;
  241. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitTmp + ";", "来客吧分润日志");
  242. }
  243. decimal money = getLevelProfit;
  244. getLevelProfit -= diffLevelProfit;
  245. if (objlevel.LevelDiff == 1) //判断是否有级差
  246. {
  247. diffLevelProfit = money;
  248. }
  249. if (getLevelProfit >= obj.MinProfitVal)
  250. {
  251. result.Add(new ProfitResult()
  252. {
  253. UserId = user.UserId,
  254. MakerCode = user.MakerCode,
  255. RealName = user.RealName,
  256. UserNav = user.UserNav,
  257. Money = PublicFunction.NumberFormat(getLevelProfit),
  258. ProfitRate = profitSet.ProfitRate,
  259. ProfitPercent = profitSet.ProfitPercent,
  260. AddOrSubRate = profitSet.AddOrSubRate,
  261. ProfitRateBase = profitSet.ProfitRateBase,
  262. Fee = Sort,
  263. });
  264. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + PublicFunction.NumberFormat(getLevelProfit) + ";", "来客吧分润日志");
  265. }
  266. }
  267. }
  268. if (curLevel < UserLevel)
  269. {
  270. curLevel = UserLevel;
  271. }
  272. }
  273. }
  274. }
  275. db.Dispose();
  276. return result;
  277. }
  278. public SubUser GetUser(int UserId, string Month)
  279. {
  280. SubUser user = new SubUser();
  281. DataTable dt = GetDataTable("select * from kxs_trade_level_log where trade_month=" + Month + " where user_id=" + UserId);
  282. if (dt.Rows.Count > 0)
  283. {
  284. user.Id = int.Parse(dt.Rows[0]["user_id"].ToString());
  285. user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
  286. user.Level = int.Parse(dt.Rows[0]["level"].ToString());
  287. user.ParentNav = dt.Rows[0]["pid_path"].ToString();
  288. user.UserLevel = int.Parse(dt.Rows[0]["user_level"].ToString());
  289. user.PreUserLevel = int.Parse(dt.Rows[0]["pre_level"].ToString());
  290. user.PreLeaderLevel = int.Parse(dt.Rows[0]["leader_level"].ToString());
  291. }
  292. return user;
  293. }
  294. public int GetUserLevel(SubUser user)
  295. {
  296. int[] levels = new int[] { user.Level, user.UserLevel, user.PreUserLevel, user.PreLeaderLevel };
  297. return levels.ToList().Max();
  298. }
  299. public DataTable GetDataTable(string sqlstr)
  300. {
  301. DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsUserSqlConnStr"].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. }