ProfitBeforeHelper.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 ProfitBeforeHelper
  15. {
  16. public readonly static ProfitBeforeHelper Instance = new ProfitBeforeHelper();
  17. private ProfitBeforeHelper()
  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 + "-before.txt");
  54. if (!string.IsNullOrEmpty(check))
  55. {
  56. return;
  57. }
  58. function.WritePage("/ProfitFlag/", TradeMonth + "-before.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 UserAmountSummaryBefore 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. Models.KxsMain.Users us = kxsdb.Users.FirstOrDefault(a => a.Id == UserId);
  72. if (us != null)
  73. {
  74. string uidstring = us.Id.ToString();
  75. if (!string.IsNullOrEmpty(us.ParentNav))
  76. {
  77. uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
  78. string[] parents = us.ParentNav.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. Models.KxsMain.Users pus = kxsdb.Users.FirstOrDefault(a => a.Id == puid);
  94. if (pus != null)
  95. {
  96. users.Add(new ProfitUsers()
  97. {
  98. UserId = pus.Id,
  99. MakerCode = pus.MakerCode,
  100. RealName = pus.RealName,
  101. UserNav = pus.ParentNav,
  102. UserLevel = pus.UserLevel,
  103. CreateDate = pus.CreateDate.Value,
  104. });
  105. }
  106. }
  107. }
  108. Models.KxsMain.Users topUser = kxsdb.Users.FirstOrDefault(a => a.Id == TopUserId) ?? new Models.KxsMain.Users();
  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.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.MakerCode, //顶级编号
  131. SeoTitle = sub.RealName, //创客姓名
  132. SeoKeyword = topUser.RealName, //创客姓名
  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. AddJavaProfitRecord(udb, sub.UserId, sub.Money, TradeMonth, 1, "", ProfitType);
  159. }
  160. dbnew.SaveChanges();
  161. }
  162. catch (Exception ex)
  163. {
  164. LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
  165. }
  166. }
  167. dbnew.Dispose();
  168. kxsdb.Dispose();
  169. udb.Dispose();
  170. }
  171. #endregion
  172. #region 分润算法
  173. public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, int Sort, bool IsActive = true)
  174. {
  175. LogHelper.Instance.WriteLog("\n\nTotalAmount:" + TotalAmount + ";", "来客吧分润日志");
  176. string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
  177. WebCMSEntities db = new WebCMSEntities();
  178. List<UserLevelSet> levels = db.UserLevelSet.ToList();
  179. List<ProfitResult> result = new List<ProfitResult>();
  180. ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
  181. if (obj.Status == 1) //判断分润是否开启
  182. {
  183. int maxLevel = obj.MaxLevel; //最大等级
  184. int maxFloor = obj.MaxFloor; //最大层级
  185. decimal diffLevelProfit = 0; //等级级差
  186. ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == 9) ?? new ProfitObjectLevels(); //获取最高等级参数
  187. decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
  188. LogHelper.Instance.WriteLog("maxPercent:" + maxPercent + ";", "来客吧分润日志");
  189. decimal maxLevelProfit = TotalAmount * maxPercent;
  190. LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
  191. maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
  192. LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
  193. // decimal diffDiviProfit = 0; //分红级差
  194. //0.38分万15 0.25分万2 0.3分万7,成本0.23
  195. if(Sort == 30 || Sort == 25)
  196. {
  197. decimal profit = 0;
  198. if(Sort == 25) profit = TotalAmount * 0.0002M;
  199. if(Sort == 30) profit = TotalAmount * 0.0005M;
  200. ProfitUsers user = users[0];
  201. result.Add(new ProfitResult()
  202. {
  203. UserId = user.UserId,
  204. MakerCode = user.MakerCode,
  205. RealName = user.RealName,
  206. UserNav = user.UserNav,
  207. Money = PublicFunction.NumberFormat(profit),
  208. ProfitRate = Sort / 10000,
  209. Fee = Sort,
  210. });
  211. }
  212. else
  213. {
  214. int curLevel = 0; //当前层级的会员等级
  215. for (int curFloor = 1; curFloor <= users.Count; curFloor++)
  216. {
  217. ProfitUsers user = new ProfitUsers();
  218. if (curFloor <= users.Count)
  219. {
  220. user = users[curFloor - 1];
  221. }
  222. SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
  223. int UserLevel = GetUserLevel(selfUser); //当前会员等级
  224. //判断当前创客是否有直推的激活机具,并且在活动时间内
  225. if (curLevel == maxLevel)
  226. {
  227. break;
  228. }
  229. if (UserLevel <= maxLevel && UserLevel >= curLevel)
  230. {
  231. ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel && m.Sort == Sort); //获取当前等级参数
  232. if (objlevel != null)
  233. {
  234. decimal getLevelProfit = 0; //等级分润
  235. UserProfitSet profitSet = new UserProfitSet();
  236. decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
  237. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitPercent + ";", "来客吧分润日志");
  238. if (profitPercent > 0)
  239. {
  240. decimal profitTmp = TotalAmount * profitPercent;
  241. getLevelProfit += profitTmp;
  242. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitTmp + ";", "来客吧分润日志");
  243. }
  244. decimal money = getLevelProfit;
  245. getLevelProfit -= diffLevelProfit;
  246. if (objlevel.LevelDiff == 1) //判断是否有级差
  247. {
  248. diffLevelProfit = money;
  249. }
  250. if (getLevelProfit >= obj.MinProfitVal)
  251. {
  252. result.Add(new ProfitResult()
  253. {
  254. UserId = user.UserId,
  255. MakerCode = user.MakerCode,
  256. RealName = user.RealName,
  257. UserNav = user.UserNav,
  258. Money = PublicFunction.NumberFormat(getLevelProfit),
  259. ProfitRate = profitSet.ProfitRate,
  260. ProfitPercent = profitSet.ProfitPercent,
  261. AddOrSubRate = profitSet.AddOrSubRate,
  262. ProfitRateBase = profitSet.ProfitRateBase,
  263. Fee = Sort,
  264. });
  265. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + PublicFunction.NumberFormat(getLevelProfit) + ";", "来客吧分润日志");
  266. }
  267. }
  268. }
  269. if (curLevel < UserLevel)
  270. {
  271. curLevel = UserLevel;
  272. }
  273. }
  274. }
  275. }
  276. db.Dispose();
  277. return result;
  278. }
  279. public SubUser GetUser(int UserId, string Month)
  280. {
  281. SubUser user = new SubUser();
  282. DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
  283. if (dt.Rows.Count > 0)
  284. {
  285. user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
  286. user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
  287. user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
  288. user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
  289. user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
  290. user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
  291. user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
  292. user.PreUserLevelBefore = int.Parse(dt.Rows[0]["PreUserLevelBefore"].ToString());
  293. }
  294. return user;
  295. }
  296. public int GetUserLevel(SubUser user)
  297. {
  298. int level = user.UserLevel;
  299. if(user.PreUserLevelBefore > level) level = user.PreUserLevelBefore;
  300. return level;
  301. }
  302. public DataTable GetDataTable(string sqlstr)
  303. {
  304. DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
  305. return dt;
  306. }
  307. #endregion
  308. public void StartSetDivi()
  309. {
  310. Thread th = new Thread(StartSetDiviDo);
  311. th.IsBackground = true;
  312. th.Start();
  313. }
  314. public void StartSetDiviDo()
  315. {
  316. while (true)
  317. {
  318. string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDiviHd");
  319. if (!string.IsNullOrEmpty(content))
  320. {
  321. SetDivi(content);
  322. }
  323. else
  324. {
  325. Thread.Sleep(10000);
  326. }
  327. }
  328. }
  329. public void SetDivi(string content)
  330. {
  331. try
  332. {
  333. JsonData jsonObj = JsonMapper.ToObject(content);
  334. int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
  335. decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
  336. WebCMSEntities db = new WebCMSEntities();
  337. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
  338. if (order != null)
  339. {
  340. order.CurDivi = diviAmt;
  341. db.SaveChanges();
  342. }
  343. db.Dispose();
  344. }
  345. catch (Exception ex)
  346. {
  347. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
  348. }
  349. }
  350. //奖励入库给java数据库
  351. private void AddJavaProfitRecord(KxsUserModels.WebCMSEntities db, int UserId, decimal Prize, string TradeMonth, int RewardType, string Remark, int IsTeam)
  352. {
  353. int ProfitMonth = int.Parse(TradeMonth);
  354. KxsUserModels.KxsUserProfitLkb item = db.KxsUserProfitLkb.FirstOrDefault(m => m.UserId == UserId && m.TradeType == RewardType && m.ProfitMonth == ProfitMonth);
  355. if(item == null)
  356. {
  357. item = db.KxsUserProfitLkb.Add(new KxsUserModels.KxsUserProfitLkb()
  358. {
  359. IsTeam = IsTeam,
  360. TradeType = RewardType,
  361. Remark = Remark,
  362. ProfitMonth = ProfitMonth,
  363. ProfitAmt = Prize,
  364. UserId = UserId,
  365. UpdateTime = DateTime.Now,
  366. CreateTime = DateTime.Now,
  367. }).Entity;
  368. db.SaveChanges();
  369. }
  370. item.ProfitAmt += Prize;
  371. db.SaveChanges();
  372. }
  373. }
  374. }