ProfitBeforeHelper.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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);
  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. }).Entity;
  134. dbnew.SaveChanges();
  135. string RecordNo = "KPM";
  136. int RecordId = editprofitrecord.Id;
  137. string RecordIdString = RecordId.ToString();
  138. for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
  139. {
  140. RecordIdString = "0" + RecordIdString;
  141. }
  142. RecordNo += RecordIdString;
  143. editprofitrecord.RecordNo = RecordNo;
  144. dbnew.SaveChanges();
  145. }
  146. if (IsActive)
  147. {
  148. editprofitrecord.CreditTradeAmt += TotalAmount;
  149. editprofitrecord.CreditTradeProfit += sub.Money;
  150. }
  151. else
  152. {
  153. editprofitrecord.TradeAmt += TotalAmount;
  154. editprofitrecord.TradeProfit += sub.Money;
  155. }
  156. dbnew.SaveChanges();
  157. AddJavaProfitRecord(udb, sub.UserId, sub.Money, TradeMonth, 1, "", ProfitType);
  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.Id == 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.0007M;
  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.Id == UserLevel && m.Sort == Sort); //获取当前等级参数
  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 Users" + Month + " where Id=" + UserId);
  282. if (dt.Rows.Count > 0)
  283. {
  284. user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
  285. user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
  286. user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
  287. user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
  288. user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
  289. user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
  290. user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
  291. user.PreUserLevelBefore = int.Parse(dt.Rows[0]["PreUserLevelBefore"].ToString());
  292. }
  293. return user;
  294. }
  295. public int GetUserLevel(SubUser user)
  296. {
  297. int level = user.UserLevel;
  298. if(user.PreUserLevelBefore > level) level = user.PreUserLevelBefore;
  299. return level;
  300. }
  301. public DataTable GetDataTable(string sqlstr)
  302. {
  303. DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
  304. return dt;
  305. }
  306. #endregion
  307. public void StartSetDivi()
  308. {
  309. Thread th = new Thread(StartSetDiviDo);
  310. th.IsBackground = true;
  311. th.Start();
  312. }
  313. public void StartSetDiviDo()
  314. {
  315. while (true)
  316. {
  317. string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDiviHd");
  318. if (!string.IsNullOrEmpty(content))
  319. {
  320. SetDivi(content);
  321. }
  322. else
  323. {
  324. Thread.Sleep(10000);
  325. }
  326. }
  327. }
  328. public void SetDivi(string content)
  329. {
  330. try
  331. {
  332. JsonData jsonObj = JsonMapper.ToObject(content);
  333. int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
  334. decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
  335. WebCMSEntities db = new WebCMSEntities();
  336. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
  337. if (order != null)
  338. {
  339. order.CurDivi = diviAmt;
  340. db.SaveChanges();
  341. }
  342. db.Dispose();
  343. }
  344. catch (Exception ex)
  345. {
  346. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
  347. }
  348. }
  349. //奖励入库给java数据库
  350. private void AddJavaProfitRecord(KxsUserModels.WebCMSEntities db, int UserId, decimal Prize, string TradeMonth, int RewardType, string Remark, int IsTeam)
  351. {
  352. int ProfitMonth = int.Parse(TradeMonth);
  353. KxsUserModels.KxsUserProfitLkb item = db.KxsUserProfitLkb.FirstOrDefault(m => m.UserId == UserId && m.TradeType == RewardType && m.ProfitMonth == ProfitMonth);
  354. if(item == null)
  355. {
  356. item = db.KxsUserProfitLkb.Add(new KxsUserModels.KxsUserProfitLkb()
  357. {
  358. IsTeam = IsTeam,
  359. TradeType = RewardType,
  360. Remark = Remark,
  361. ProfitMonth = ProfitMonth,
  362. ProfitAmt = Prize,
  363. UserId = UserId,
  364. UpdateTime = DateTime.Now,
  365. CreateTime = DateTime.Now,
  366. }).Entity;
  367. db.SaveChanges();
  368. }
  369. item.ProfitAmt += Prize;
  370. db.SaveChanges();
  371. }
  372. }
  373. }