ProfitHelper.cs 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Data;
  5. using MySystem.PxcModels;
  6. using Library;
  7. using System.Threading;
  8. using Microsoft.Extensions.Hosting;
  9. using System.Threading.Tasks;
  10. namespace MySystem
  11. {
  12. public class ProfitHelper
  13. {
  14. public readonly static ProfitHelper Instance = new ProfitHelper();
  15. private ProfitHelper()
  16. {
  17. }
  18. #region 激活队列
  19. public void StartListenActiveDo(PosMachinesTwo pos)
  20. {
  21. try
  22. {
  23. }
  24. catch (Exception ex)
  25. {
  26. function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "激活奖励服务异常");
  27. }
  28. }
  29. #endregion
  30. #region 消费队列(执行消费退款金额的统计)
  31. public void StartListenTrade()
  32. {
  33. Thread th = new Thread(StartListenTradeDo);
  34. th.IsBackground = true;
  35. th.Start();
  36. }
  37. public void StartListenTradeDo()
  38. {
  39. while (true)
  40. {
  41. string orderidstring = RedisDbconn.Instance.RPop<string>("ConsumerOrders:Divi:List");
  42. if (!string.IsNullOrEmpty(orderidstring))
  43. {
  44. ReturnStat(orderidstring);
  45. }
  46. else
  47. {
  48. Thread.Sleep(2000);
  49. }
  50. }
  51. }
  52. public void ReturnStat(string orderidstring)
  53. {
  54. int OrderId = int.Parse(function.CheckInt(orderidstring));
  55. WebCMSEntities db = new WebCMSEntities();
  56. using (var tran = db.Database.BeginTransaction())
  57. {
  58. try
  59. {
  60. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == OrderId);
  61. if (order != null)
  62. {
  63. int PayMode = order.PayMode;
  64. decimal PayMoney = order.PayMoney;
  65. int MerchantId = order.MerchantId;
  66. MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
  67. if (merchant != null)
  68. {
  69. int UserId = merchant.UserId;
  70. List<CustomTagSet> customTagSets = db.CustomTagSet.ToList(); //获取公用配置参数集和
  71. //获取参数
  72. CustomTagSet profitPercentSet = customTagSets.FirstOrDefault(m => m.Tags == "CusumerProfitPercent") ?? new CustomTagSet();
  73. decimal profitPercent = decimal.Parse(function.CheckNum(profitPercentSet.Contents)); //基于收款金额的总分润比例;
  74. CustomTagSet cusumerFeePercentSet = customTagSets.FirstOrDefault(m => m.Tags == "CusumerFeePercent") ?? new CustomTagSet();
  75. decimal cusumerFeePercent = decimal.Parse(function.CheckNum(cusumerFeePercentSet.Contents)); //费率;
  76. CustomTagSet minProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "MinProfit") ?? new CustomTagSet();
  77. decimal minProfit = decimal.Parse(function.CheckNum(minProfitSet.Contents)); //最小分润值;
  78. MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
  79. int DiviPersons = set.DiviPersons; //单笔订单分红人数
  80. decimal DiviPercent = set.DiviPercent; //单人最大分红比例
  81. int ProfitDays = set.ProfitDays; //分红期限(天)
  82. decimal GetPercent = set.GetPercent / 100; //商家实收比例
  83. decimal MinPayMoney = set.MinPayMoney; //订单参与门槛
  84. int IsAll = set.IsAll; //是否收全额
  85. decimal TotalActual = 0;
  86. if (IsAll == 0 && PayMoney >= MinPayMoney && GetPercent < 1)
  87. {
  88. decimal DiviMoney = PayMoney * (1 - GetPercent - cusumerFeePercent - profitPercent);
  89. if (DiviMoney > 0)
  90. {
  91. DiviMoney = DiviMoney / DiviPersons;
  92. //付款人获取退款返现
  93. // decimal GetMoney = order.MaxDivi - order.CurDivi;
  94. // if (GetMoney >= DiviMoney)
  95. // {
  96. // GetMoney = DiviMoney;
  97. // }
  98. // if (GetMoney > minProfit)
  99. // {
  100. // order.CurDivi += GetMoney;
  101. // ConsumerProfit cprofit = db.ConsumerProfit.Add(new ConsumerProfit()
  102. // {
  103. // CreateDate = DateTime.Now,
  104. // ConsumerId = order.ConsumerId,
  105. // MerchantId = order.MerchantId,
  106. // OrderId = OrderId,
  107. // GetMoney = GetMoney,
  108. // }).Entity;
  109. // db.SaveChanges();
  110. // RedisDbconn.Instance.AddList("ConsumerOrdersStat", new RefundItem()
  111. // {
  112. // ProfitId = cprofit.Id,
  113. // TradeNo = order.OrderNo,
  114. // RefundMoney = GetMoney,
  115. // TotalMoney = PayMoney,
  116. // PayMode = order.PayMode,
  117. // MerchantId = order.MerchantId,
  118. // });
  119. // }
  120. List<int> deletes = new List<int>();
  121. long CurDiviPersons = DiviPersons;
  122. long QueueCount = RedisDbconn.Instance.Count("ConsumerOrders:Divi:" + MerchantId);
  123. long CurQueueCount = QueueCount;
  124. // int CheckNum = 0; //判断活动人数是否大于当前队列订单数来确认while循环的数量,如果是就少循环一次,判处自己的订单名额
  125. if (CurDiviPersons >= CurQueueCount)
  126. {
  127. CurDiviPersons = CurQueueCount;
  128. }
  129. if (DiviPersons < QueueCount)
  130. {
  131. QueueCount = DiviPersons;
  132. }
  133. decimal OtherMoney = 0; // 退款金额>最大退款金额-当前退款金额,次金额应归还给商户
  134. // 减去自己付的订单
  135. // CurDiviPersons = CurDiviPersons - 1;
  136. int OutCount = 0; // 出局人数
  137. while (CurDiviPersons > 0)
  138. {
  139. ConsumerOrders suborder = RedisDbconn.Instance.RPop<ConsumerOrders>("ConsumerOrders:Divi:" + MerchantId);
  140. if (suborder != null)
  141. {
  142. MerchantParamSet subset = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
  143. int subProfitDays = subset.ProfitDays; //分红期限(天)
  144. bool IsOut = suborder.UpdateDate.Value.AddDays(subProfitDays) < DateTime.Now ? true : false;
  145. if (suborder.CurDivi < suborder.MaxDivi && !IsOut)
  146. {
  147. //如果没过期并且当前退款金额没超过最大退款金额,就执行
  148. decimal GetMoney = suborder.MaxDivi - suborder.CurDivi;
  149. decimal DiffMoney = 0;
  150. if (GetMoney >= DiviMoney)
  151. {
  152. GetMoney = DiviMoney;
  153. }
  154. else
  155. {
  156. DiffMoney = DiviMoney - GetMoney;
  157. }
  158. if (GetMoney > minProfit)
  159. {
  160. suborder.CurDivi += GetMoney;
  161. if (DiffMoney > 0)
  162. {
  163. OtherMoney += DiffMoney;
  164. }
  165. ConsumerProfit cprofit = db.ConsumerProfit.Add(new ConsumerProfit()
  166. {
  167. CreateDate = DateTime.Now,
  168. ConsumerId = suborder.ConsumerId,
  169. MerchantId = suborder.MerchantId,
  170. OrderId = OrderId,
  171. GetMoney = GetMoney,
  172. QueryCount = PayMode,
  173. SeoTitle = order.OrderNo,
  174. SeoKeyword = order.PayMoney.ToString(),
  175. }).Entity;
  176. db.SaveChanges();
  177. if (suborder.CurDivi < suborder.MaxDivi)
  178. {
  179. RedisDbconn.Instance.AddList("ConsumerOrders:Divi:" + MerchantId, suborder);
  180. }
  181. else
  182. {
  183. OutCount += 1;
  184. }
  185. }
  186. }
  187. else
  188. {
  189. //否者计算人数不计入退款名额
  190. CurDiviPersons += 1;
  191. }
  192. }
  193. CurDiviPersons -= 1;
  194. QueueCount = RedisDbconn.Instance.Count("ConsumerOrders:Divi:" + MerchantId);
  195. if (QueueCount == 0)
  196. {
  197. CurDiviPersons = 0;
  198. }
  199. }
  200. long DoCount = DiviPersons > (QueueCount + OutCount) ? DiviPersons - QueueCount : 0;
  201. decimal MerchantGetMoney = PayMoney * GetPercent;
  202. decimal DoMoney = DoCount * DiviMoney;
  203. TotalActual = PayMoney * GetPercent + DoCount * DiviMoney + OtherMoney;
  204. function.WriteLog("返现金额:" + DiviMoney + ";返现人数:" + DiviPersons + ";返现商户:" + TotalActual + ";返现溢出:" + OtherMoney + ";商户应得金额:" + MerchantGetMoney + ";返现差额:" + DoMoney + ";", "消费者返现日志");
  205. //代理商分润
  206. // AgentProfit(db, order);
  207. }
  208. }
  209. //统计商户数据
  210. // string MonthString = order.UpdateDate.Value.ToString("yyyyMM");
  211. // string DateString = order.UpdateDate.Value.ToString("yyyyMMdd");
  212. // TotalActual = PublicFunction.NumberFormat(TotalActual);
  213. // function.WriteLog(TotalActual.ToString(), "监控退款队列");
  214. // merchant.TotalActual += TotalActual;
  215. // db.SaveChanges();
  216. // List<string> Dates = RedisDbconn.Instance.GetList<string>("ConsumerStat:" + MerchantId + ":" + MonthString, 1, 1000);
  217. // if (!Dates.Contains(DateString))
  218. // {
  219. // RedisDbconn.Instance.AddList("ConsumerStat:" + MerchantId + ":" + MonthString, DateString);
  220. // }
  221. // MerchantIndexStat DateIndexStat = RedisDbconn.Instance.Get<MerchantIndexStat>("MerchantIndexStat:" + MerchantId + ":" + DateString) ?? new MerchantIndexStat();
  222. // DateIndexStat.TotalOrder += 1;
  223. // DateIndexStat.TotalAmount += PayMoney;
  224. // DateIndexStat.TotalActual += TotalActual;
  225. // if (order.PayMode == 1)
  226. // {
  227. // DateIndexStat.AlipayTotalAmount += PayMoney;
  228. // DateIndexStat.AlipayTotalActual += TotalActual;
  229. // }
  230. // else if (order.PayMode == 2)
  231. // {
  232. // DateIndexStat.WeChatTotalAmount += PayMoney;
  233. // DateIndexStat.WeChatTotalActual += TotalActual;
  234. // }
  235. // RedisDbconn.Instance.Set("MerchantIndexStat:" + MerchantId + ":" + DateString, DateIndexStat);
  236. // List<string> Months = RedisDbconn.Instance.GetList<string>("ConsumerStat:" + MerchantId, 1, 1000);
  237. // if (!Months.Contains(MonthString))
  238. // {
  239. // RedisDbconn.Instance.AddList("ConsumerStat:" + MerchantId, MonthString);
  240. // }
  241. // MerchantIndexStat MonthIndexStat = RedisDbconn.Instance.Get<MerchantIndexStat>("MerchantIndexStat:" + MerchantId + ":" + MonthString) ?? new MerchantIndexStat();
  242. // MonthIndexStat.TotalOrder += 1;
  243. // MonthIndexStat.TotalAmount += PayMoney;
  244. // MonthIndexStat.TotalActual += TotalActual;
  245. // if (order.PayMode == 1)
  246. // {
  247. // MonthIndexStat.AlipayTotalAmount += PayMoney;
  248. // MonthIndexStat.AlipayTotalActual += TotalActual;
  249. // }
  250. // else if (order.PayMode == 2)
  251. // {
  252. // MonthIndexStat.WeChatTotalAmount += PayMoney;
  253. // MonthIndexStat.WeChatTotalActual += TotalActual;
  254. // }
  255. // RedisDbconn.Instance.Set("MerchantIndexStat:" + MerchantId + ":" + MonthString, MonthIndexStat);
  256. }
  257. }
  258. tran.Commit();
  259. }
  260. catch (Exception ex)
  261. {
  262. function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "自定义分润程序监听队列异常");
  263. tran.Rollback();
  264. }
  265. }
  266. db.Dispose();
  267. }
  268. public void StartListenProfit()
  269. {
  270. Thread th = new Thread(StartListenProfitDo);
  271. th.IsBackground = true;
  272. th.Start();
  273. }
  274. public void StartListenProfitDo()
  275. {
  276. while(true)
  277. {
  278. if(DateTime.Now.Day == 1 && DateTime.Now.Hour > 0)
  279. {
  280. DoProfit();
  281. Thread.Sleep(600000);
  282. }
  283. else
  284. {
  285. Thread.Sleep(3600000);
  286. }
  287. }
  288. }
  289. //分润算法
  290. public void DoProfit()
  291. {
  292. string TradeMonth = DateTime.Now.ToString("yyyyMM");
  293. WebCMSEntities dbnew = new WebCMSEntities();
  294. DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount) from UserAmountSummary where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId", MysqlConn.SqlConnStr);
  295. foreach(DataRow dr in dt.Rows)
  296. {
  297. int UserId = int.Parse(dr["UserId"].ToString());
  298. bool IsActive = dr["IsAct"].ToString() == "1";
  299. decimal TotalAmount = decimal.Parse(dr[2].ToString());
  300. List<ProfitUsers> users = new List<ProfitUsers>();
  301. int TopUserId = 0; //顶级创客Id
  302. Users us = dbnew.Users.FirstOrDefault(a => a.Id == UserId);
  303. if (us != null)
  304. {
  305. string uidstring = us.Id.ToString();
  306. if (!string.IsNullOrEmpty(us.ParentNav))
  307. {
  308. uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
  309. TopUserId = int.Parse(function.CheckInt(us.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]));
  310. }
  311. string[] uidlist = uidstring.Split(',');
  312. Array.Reverse(uidlist);
  313. foreach (string uidstr in uidlist)
  314. {
  315. int puid = int.Parse(function.CheckInt(uidstr));
  316. Users pus = dbnew.Users.FirstOrDefault(a => a.Id == puid);
  317. if (pus != null)
  318. {
  319. users.Add(new ProfitUsers()
  320. {
  321. UserId = pus.Id,
  322. UserNav = pus.ParentNav,
  323. UserLevel = pus.UserLevel,
  324. CreateDate = pus.CreateDate.Value,
  325. });
  326. }
  327. }
  328. }
  329. List<ProfitResult> list = new List<ProfitResult>();
  330. list = StartProft(dbnew, TotalAmount, 1, users, IsActive);
  331. using (var tran = dbnew.Database.BeginTransaction())
  332. {
  333. try
  334. {
  335. foreach (ProfitResult sub in list)
  336. {
  337. if (sub.Message == "分红奖励")
  338. {
  339. UserAccountRecord accountRecord = dbnew.UserAccountRecord.Add(new UserAccountRecord()
  340. {
  341. CreateDate = DateTime.Now,
  342. UpdateDate = DateTime.Now,
  343. UserId = sub.UserId, //创客
  344. ChangeType = 11, //变动类型
  345. ProductType = 1, //产品类型
  346. ChangeAmount = sub.Money, //变更金额
  347. Status = -1,
  348. }).Entity;
  349. dbnew.SaveChanges();
  350. }
  351. else
  352. {
  353. int ProfitType = sub.UserId == UserId ? 0 : 1;
  354. ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth);
  355. if (editprofitrecord == null)
  356. {
  357. editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
  358. {
  359. CreateDate = DateTime.Now,
  360. UserId = sub.UserId, //创客
  361. BrandId = 1, //品牌
  362. ProfitType = ProfitType, //创客分润类型
  363. TradeMonth = TradeMonth, //交易月
  364. TopUserId = TopUserId, //顶级创客
  365. }).Entity;
  366. dbnew.SaveChanges();
  367. string RecordNo = "KPM";
  368. int RecordId = editprofitrecord.Id;
  369. string RecordIdString = RecordId.ToString();
  370. for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
  371. {
  372. RecordIdString = "0" + RecordIdString;
  373. }
  374. RecordNo += RecordIdString;
  375. editprofitrecord.RecordNo = RecordNo;
  376. dbnew.SaveChanges();
  377. }
  378. editprofitrecord.TradeAmt += TotalAmount; //商户交易总额
  379. editprofitrecord.DebitCapTradeNum += 1; //商户借记卡封顶交易总笔数
  380. decimal ProfitMoney = sub.Money;
  381. dbnew.SaveChanges();
  382. }
  383. }
  384. dbnew.SaveChanges();
  385. tran.Commit();
  386. }
  387. catch (Exception ex)
  388. {
  389. tran.Rollback();
  390. function.WriteLog(ex.ToString(), "分润异常");
  391. }
  392. }
  393. }
  394. dbnew.Dispose();
  395. }
  396. public void DoActives(WebCMSEntities dbnew, TradeRecord trade_record)
  397. {
  398. if (RedisDbconn.Instance.CheckKey("pobjact" + trade_record.Sort))
  399. {
  400. List<ProfitObjectsActives> objactives = RedisDbconn.Instance.GetList<ProfitObjectsActives>("pobjact" + trade_record.Sort);
  401. if (objactives.Count > 0)
  402. {
  403. string OtherCondition = " and Type=1";
  404. if (trade_record.Sort == 1) OtherCondition = " and Type<>1";
  405. else if (trade_record.Sort == 2) OtherCondition = " and Type<>1";
  406. else if (trade_record.Sort == 4) OtherCondition = " and Type=2";
  407. else if (trade_record.Sort == 11) OtherCondition = " and Type=2";
  408. else if (trade_record.Sort == 14) OtherCondition = " and (Type=1 or Type=3)";
  409. else if (trade_record.Sort == 6 || trade_record.Sort == 7 || trade_record.Sort == 18) OtherCondition = "";
  410. else if (trade_record.Sort == 29) OtherCondition = " and Type=2";
  411. PosMachinesTwo machine = dbnew.PosMachinesTwo.FirstOrDefault(m => m.PosSn == trade_record.SnNo) ?? new PosMachinesTwo();
  412. if (machine.ActivationState == 0)
  413. {
  414. return;
  415. }
  416. if (machine.BrandId == 0)
  417. {
  418. return;
  419. }
  420. Users user = dbnew.Users.FirstOrDefault(m => m.Id == machine.UserId) ?? new Users();
  421. Users buyuser = dbnew.Users.FirstOrDefault(m => m.Id == machine.BuyUserId) ?? new Users();
  422. Dictionary<string, ProfitUsers> Users = new Dictionary<string, ProfitUsers>();
  423. Users.Add("UserId", new ProfitUsers()
  424. {
  425. UserId = user.Id,
  426. UserNav = user.ParentNav,
  427. UserLevel = user.UserLevel,
  428. });
  429. Users.Add("BuyUserId", new ProfitUsers()
  430. {
  431. UserId = buyuser.Id,
  432. UserNav = buyuser.ParentNav,
  433. UserLevel = buyuser.UserLevel,
  434. });
  435. List<ProfitResult> list = StartActiveProft(dbnew, machine, trade_record.SnNo, trade_record.Sort, Users, new ActiveCheckData()
  436. {
  437. TableName = "TransactionRecord",
  438. StatField = "Money",
  439. CheckField = "pos_sn",
  440. OtherCondition = OtherCondition,
  441. });
  442. foreach (ProfitResult sub in list)
  443. {
  444. // dbnew.MybillTable.Add(new MybillTable()
  445. // {
  446. // Content = sub.Message,
  447. // Money = sub.Money,
  448. // Type = 1,
  449. // UserId = sub.UserId,
  450. // UserNav = sub.UserNav,
  451. // Kind = 2,
  452. // CreateDate = DateTime.Now,
  453. // SeoTitle = trade_record.SeoTitle,
  454. // SeoKeyword = trade_record.SnNo,
  455. // Sort = trade_record.Sort,
  456. // Status = -3,
  457. // });
  458. }
  459. dbnew.SaveChanges();
  460. }
  461. }
  462. }
  463. //代理商分润算法
  464. public void AgentProfit(WebCMSEntities db, ConsumerOrders order)
  465. {
  466. int MerchantId = order.MerchantId;
  467. decimal PayMoney = order.PayMoney;
  468. MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
  469. if (merchant != null)
  470. {
  471. List<CustomTagSet> customTagSets = RedisDbconn.Instance.GetList<CustomTagSet>("CustomTagSet", 1, 1000); //获取公用配置参数集和 // TODO: 后台配置
  472. //获取代理商参数
  473. CustomTagSet profitPercentSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentProfitPercent") ?? new CustomTagSet();
  474. decimal profitPercent = decimal.Parse(function.CheckNum(profitPercentSet.Contents)); //基于收款金额的总分润比例;
  475. CustomTagSet makerProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentMakerProfit") ?? new CustomTagSet();
  476. decimal makerProfit = decimal.Parse(function.CheckNum(makerProfitSet.Contents)); //创客分润比例;
  477. CustomTagSet directProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentDirectProfit") ?? new CustomTagSet();
  478. decimal directProfit = decimal.Parse(function.CheckNum(directProfitSet.Contents)); //直推分润比例;
  479. CustomTagSet minProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "MinProfit") ?? new CustomTagSet();
  480. decimal minProfit = decimal.Parse(function.CheckNum(minProfitSet.Contents)); //最小分润值;
  481. string MerAreas = merchant.Areas;
  482. MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
  483. decimal ProfitMoney = PayMoney * (1 - set.DiviPercent) * profitPercent;
  484. Users user = db.Users.FirstOrDefault(m => m.Id == merchant.UserId);
  485. if (user != null)
  486. {
  487. decimal ProfitAmount = ProfitMoney * makerProfit;
  488. if (ProfitAmount >= minProfit)
  489. {
  490. db.ProfitRecord.Add(new ProfitRecord()
  491. {
  492. CreateDate = DateTime.Now,
  493. UpdateDate = DateTime.Now,
  494. Remark = "分润奖励",
  495. UserId = user.Id, //创客
  496. MerchantId = MerchantId, //商户
  497. SnNo = order.SnNo, //SN号
  498. TradeDate = order.CreateDate, //交易日期
  499. ProfitAmount = ProfitAmount, //分润金额
  500. BrandId = 1, //品牌
  501. ParentNav = user.ParentNav, //上级创客集
  502. TradeId = order.Id, //交易记录Id
  503. });
  504. db.SaveChanges();
  505. }
  506. }
  507. Users puser = db.Users.FirstOrDefault(m => m.Id == user.ParentUserId);
  508. if (puser != null)
  509. {
  510. decimal ProfitAmount = ProfitMoney * directProfit;
  511. if (ProfitAmount >= minProfit)
  512. {
  513. db.ProfitRecord.Add(new ProfitRecord()
  514. {
  515. CreateDate = DateTime.Now,
  516. UpdateDate = DateTime.Now,
  517. Remark = "分润奖励",
  518. UserId = puser.Id, //创客
  519. MerchantId = MerchantId, //商户
  520. SnNo = order.SnNo, //SN号
  521. TradeDate = order.CreateDate, //交易日期
  522. ProfitAmount = ProfitAmount, //分润金额
  523. BrandId = 1, //品牌
  524. ParentNav = puser.ParentNav, //上级创客集
  525. TradeId = order.Id, //交易记录Id
  526. });
  527. db.SaveChanges();
  528. }
  529. }
  530. string[] areaList = MerAreas.Split(',');
  531. decimal GetMoneyFlag = 0;
  532. for (int i = 0; i < areaList.Length; i++)
  533. {
  534. string CurAreas = "";
  535. for (int j = 0; j < areaList.Length - i; j++)
  536. {
  537. CurAreas += areaList[j] + ",";
  538. }
  539. CurAreas = CurAreas.TrimEnd(',');
  540. int AgentLevel = CurAreas.Split(',').Length;
  541. Users areaUser = db.Users.FirstOrDefault(m => m.AgentAreas == CurAreas && m.AgentLevel > AgentLevel);
  542. if (areaUser != null)
  543. {
  544. AgentLevelSet agentset = db.AgentLevelSet.FirstOrDefault(m => m.Id == AgentLevel) ?? new AgentLevelSet();
  545. decimal ProfitAmount = ProfitMoney * agentset.ProfitPercent;
  546. if (agentset.LevelDiff == 1)
  547. {
  548. ProfitAmount -= GetMoneyFlag;
  549. }
  550. if (ProfitAmount >= minProfit)
  551. {
  552. db.ProfitRecord.Add(new ProfitRecord()
  553. {
  554. CreateDate = DateTime.Now,
  555. UpdateDate = DateTime.Now,
  556. Remark = "分润奖励",
  557. UserId = puser.Id, //创客
  558. MerchantId = MerchantId, //商户
  559. SnNo = order.SnNo, //SN号
  560. TradeDate = order.CreateDate, //交易日期
  561. ProfitAmount = ProfitAmount, //分润金额
  562. BrandId = 1, //品牌
  563. ParentNav = puser.ParentNav, //上级创客集
  564. TradeId = order.Id, //交易记录Id
  565. });
  566. db.SaveChanges();
  567. GetMoneyFlag = ProfitAmount;
  568. }
  569. ProfitAmount = ProfitMoney * agentset.AreasProfitPercent;
  570. if (ProfitAmount >= minProfit)
  571. {
  572. db.ProfitRecord.Add(new ProfitRecord()
  573. {
  574. CreateDate = DateTime.Now,
  575. UpdateDate = DateTime.Now,
  576. Remark = "分润奖励",
  577. UserId = puser.Id, //创客
  578. MerchantId = MerchantId, //商户
  579. SnNo = order.SnNo, //SN号
  580. TradeDate = order.CreateDate, //交易日期
  581. ProfitAmount = ProfitAmount, //分润金额
  582. BrandId = 1, //品牌
  583. ParentNav = puser.ParentNav, //上级创客集
  584. TradeId = order.Id, //交易记录Id
  585. });
  586. db.SaveChanges();
  587. }
  588. }
  589. }
  590. }
  591. }
  592. // 收款金额:100
  593. // 单笔退款金额 = (收款金额*返现比例 - 已返现金额) > (收款金额 - 收款金额*商家实收比例 - 收款金额*(1 - 商家实收比例)*10% - 手续费(收款金额*0.38%) ) / 返现人数 ? (收款金额 - 收款金额*商家实收比例 - 收款金额*(1 - 商家实收比例)*10% - 手续费(收款金额*0.38%)) / 返现人数 : (收款金额*返现比例 - 已返现金额)
  594. // 分账金额: 收款金额*(1 - 商家实收比例)*10%
  595. // 代理分润金额: 省:75% 市:65% 区县:55% 创客:30% 直推创客:5%
  596. // 区域保护分润金额:省:5% 市:5% 区县:5%
  597. // QE:
  598. /*
  599. 条件1(跨区域开发商家):
  600. A为四川省成都市金牛区代理,B为金牛区创客,C为B推荐的金牛区创客,D为四川省成都市代理,E为四川省代理,F为广东省深圳市南山区代理,G为广东省深圳市代理,H为广东省代理。
  601. C推荐一个广东省深圳市南山区商家,交易金额1000元。
  602. 则:
  603. C可得分润 = 分账金额 * 30%
  604. B可得直推分润 = 分账金额 * 5%
  605. A可得分润 = 分账金额 * (55% - 30%)
  606. G可得分润 = 分账金额 * (65% - 55%)
  607. H可得分润 = 分账金额 * (75% - 65%)
  608. F、G、H可再得区域保护分润 = 分账金额 * 5%
  609. 条件2(同区域):
  610. A为四川省成都市金牛区代理,B为金牛区创客,C为B推荐的金牛区创客,D为四川省成都市代理,E为四川省代理
  611. C推荐一个四川省成都市金牛区商家,交易金额1000元。
  612. 则:
  613. C可得分润 = 分账金额 * 30%
  614. B可得直推分润 = 分账金额 * 5%
  615. A可得分润 = 分账金额 * (55% - 30%)
  616. D可得分润 = 分账金额 * (65% - 55%)
  617. E可得分润 = 分账金额 * (75% - 65%)
  618. A、D、E可再得区域保护分润 = 分账金额 * 5%
  619. 条件3(代理断级):
  620. B为金牛区创客,C为B推荐的金牛区创客,D为四川省成都市代理,E为四川省代理,F为广东省深圳市南山区代理,G为广东省深圳市代理,H为广东省代理。
  621. C推荐一个广东省深圳市南山区商家,交易金额1000元。
  622. 则:
  623. C可得分润 = 分账金额 * 30%
  624. B可得直推分润 = 分账金额 * 5%
  625. D可得分润 = 分账金额 * (65% - 30%)
  626. H可得分润 = 分账金额 * (75% - 65%)
  627. F、G、H可再得区域保护分润 = 分账金额 * 5%
  628. */
  629. #endregion
  630. #region 商户队列
  631. public void StartListenMerchantDo(Dictionary<string, string> data, bool bind = false)
  632. {
  633. }
  634. #endregion
  635. #region 绑定队列
  636. public void StartListenBindDo(Dictionary<string, string> data)
  637. {
  638. }
  639. #endregion
  640. #region 待分账队列
  641. public void StartListenSplitAccount()
  642. {
  643. bool op = true;
  644. while (op)
  645. {
  646. try
  647. {
  648. string orderidstring = RedisDbconn.Instance.Get<string>("ConsumerOrders:Divi:List");
  649. if (!string.IsNullOrEmpty(orderidstring))
  650. {
  651. int OrderId = int.Parse(function.CheckInt(orderidstring));
  652. WebCMSEntities db = new WebCMSEntities();
  653. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == OrderId && m.Status == 1);
  654. if (order != null)
  655. {
  656. // TODO:
  657. }
  658. db.Dispose();
  659. }
  660. else
  661. {
  662. op = false;
  663. }
  664. }
  665. catch (Exception ex)
  666. {
  667. op = false;
  668. function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "待分账队列异常");
  669. }
  670. }
  671. }
  672. #endregion
  673. #region 分润算法
  674. public List<ProfitResult> StartProft(WebCMSEntities dbnew, decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, bool IsActive = true)
  675. {
  676. int BrandId = 1;
  677. List<UserLevelSet> levels = RedisDbconn.Instance.GetList<UserLevelSet>("pobjlevel");
  678. List<ProfitResult> result = new List<ProfitResult>();
  679. ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
  680. if (obj.Status == 1) //判断分润是否开启
  681. {
  682. int maxLevel = obj.MaxLevel; //最大等级
  683. int maxFloor = obj.MaxFloor; //最大层级
  684. int maxContinueFloor = RedisDbconn.Instance.Get<int>("pobjconc" + BrandId); //最大继续分润层级
  685. decimal diffLevelProfit = 0; //等级级差
  686. // decimal diffDiviProfit = 0; //分红级差
  687. int curLevel = 0; //当前层级的会员等级
  688. for (int curFloor = 1; curFloor <= users.Count; curFloor++)
  689. {
  690. ProfitUsers user = new ProfitUsers();
  691. if (curFloor <= users.Count)
  692. {
  693. user = users[curFloor - 1];
  694. }
  695. int UserLevel = 1; //user.UserLevel; //当前会员等级
  696. decimal utrade = RedisDbconn.Instance.Get<decimal>("TeamTradeStat:" + user.UserId + ":" + BrandId + ":" + DateTime.Now.ToString("yyMM"));
  697. UserLevelSet checklevel = levels.Where(m => m.UpLevelIntegral < utrade).OrderBy(m => m.Id).FirstOrDefault();
  698. if (checklevel != null)
  699. {
  700. UserLevel = checklevel.Id + 1;
  701. }
  702. //判断当前创客是否有直推的激活机具,并且在活动时间内
  703. if (UserLevel == maxLevel && UserLevel == curLevel)
  704. {
  705. break;
  706. }
  707. if (UserLevel <= maxLevel && UserLevel > curLevel)
  708. {
  709. ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
  710. if (objlevel != null)
  711. {
  712. decimal getLevelProfit = 0; //等级分润
  713. UserProfitSet profitSet = new UserProfitSet();
  714. decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
  715. if (profitPercent > 0)
  716. {
  717. getLevelProfit += TotalAmount * profitPercent;
  718. }
  719. decimal money = getLevelProfit;
  720. getLevelProfit -= diffLevelProfit;
  721. if (objlevel.LevelDiff == 1) //判断是否有级差
  722. {
  723. diffLevelProfit = money;
  724. }
  725. if (getLevelProfit >= obj.MinProfitVal)
  726. {
  727. result.Add(new ProfitResult()
  728. {
  729. UserId = user.UserId,
  730. UserNav = user.UserNav,
  731. Money = getLevelProfit,
  732. ProfitRate = profitSet.ProfitRate,
  733. ProfitPercent = profitSet.ProfitPercent,
  734. AddOrSubRate = profitSet.AddOrSubRate,
  735. ProfitRateBase = profitSet.ProfitRateBase,
  736. });
  737. }
  738. }
  739. }
  740. curLevel = UserLevel;
  741. }
  742. }
  743. return result;
  744. }
  745. #endregion
  746. #region 活动奖励算法
  747. public List<ProfitResult> StartActiveProft(WebCMSEntities dbnew, PosMachinesTwo machine, string CheckObject, int ObjectId, Dictionary<string, ProfitUsers> Users, ActiveCheckData StatParam)
  748. {
  749. DateTime Start = machine.ActivationTime.Value;
  750. List<ProfitResult> result = new List<ProfitResult>();
  751. ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + ObjectId);
  752. if (obj.Status == 1) //判断分润是否开启
  753. {
  754. List<ProfitObjectsActives> objactives = RedisDbconn.Instance.GetList<ProfitObjectsActives>("pobjact" + ObjectId);
  755. foreach (ProfitObjectsActives objactive in objactives)
  756. {
  757. if (objactive.StartDate <= DateTime.Now && objactive.EndDate >= DateTime.Now)
  758. {
  759. string UserKey = "UserId";
  760. decimal ProfitMoney = objactive.ProfitNumber; //获得数
  761. decimal FinishNumber = objactive.FinishNumber; //完成数
  762. string CheckKey = CheckObject + "-" + objactive.Id;
  763. ProfitObjectsActiveCheck check = dbnew.ProfitObjectsActiveCheck.FirstOrDefault(m => m.CheckData == CheckKey);
  764. if (ProfitMoney > 0 && check == null)
  765. {
  766. int LimitDateKind = objactive.LimitDateKind; //时间限制类型 日月年/自定义
  767. if (LimitDateKind == 4)
  768. {
  769. DateTime LimitCustomerDate = objactive.LimitCustomerDate.Value; //过期时间
  770. if (LimitCustomerDate >= DateTime.Now)
  771. {
  772. decimal totalTradeMoney = 0;
  773. OtherMySqlConn.connstr = ConfigurationManager.AppSettings["OldSqlConnStr"].ToString();
  774. string sqlstr = "select sum(" + StatParam.StatField + ") from " + StatParam.TableName + " where Id>=" + StatParam.StartId + " and " + StatParam.CheckField + "='" + CheckObject + "'" + StatParam.OtherCondition + " and CreateDate>='" + Start.ToString("yyyy-MM-dd HH:mm:ss") + "' and CreateDate<='" + LimitCustomerDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";
  775. DataTable dt = OtherMySqlConn.dtable(sqlstr);
  776. if (dt.Rows.Count > 0)
  777. {
  778. totalTradeMoney = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
  779. }
  780. // OtherMySqlConn.connstr = ;
  781. if (totalTradeMoney >= FinishNumber && ProfitMoney >= obj.MinProfitVal) //达到完成数,发放奖励
  782. {
  783. result.Add(new ProfitResult()
  784. {
  785. UserId = Users[UserKey].UserId,
  786. UserNav = Users[UserKey].UserNav,
  787. Money = ProfitMoney,
  788. });
  789. dbnew.ProfitObjectsActiveCheck.Add(new ProfitObjectsActiveCheck()
  790. {
  791. CheckData = CheckKey
  792. });
  793. dbnew.SaveChanges();
  794. }
  795. }
  796. }
  797. else
  798. {
  799. int LimitDateVal = objactive.LimitDateVal; //时间限制值 日月年
  800. DateTime checkDate = Start;
  801. if (LimitDateKind == 1)
  802. {
  803. checkDate = checkDate.AddDays(LimitDateVal);
  804. }
  805. else if (LimitDateKind == 2)
  806. {
  807. checkDate = checkDate.AddMonths(LimitDateVal);
  808. }
  809. else if (LimitDateKind == 3)
  810. {
  811. checkDate = checkDate.AddYears(LimitDateVal);
  812. }
  813. if (checkDate >= DateTime.Now)
  814. {
  815. decimal totalTradeMoney = 0;
  816. OtherMySqlConn.connstr = ConfigurationManager.AppSettings["OldSqlConnStr"].ToString();
  817. string sql = "select sum(" + StatParam.StatField + ") from " + StatParam.TableName + " where Id>=" + StatParam.StartId + " and " + StatParam.CheckField + "='" + CheckObject + "'" + StatParam.OtherCondition + " and CreateDate>='" + Start.ToString("yyyy-MM-dd HH:mm:ss") + "' and CreateDate<='" + checkDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";
  818. DataTable dt = OtherMySqlConn.dtable(sql);
  819. if (dt.Rows.Count > 0)
  820. {
  821. totalTradeMoney = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
  822. }
  823. // OtherMySqlConn.connstr = ;
  824. if (totalTradeMoney >= FinishNumber && ProfitMoney >= obj.MinProfitVal) //达到完成数,发放奖励
  825. {
  826. result.Add(new ProfitResult()
  827. {
  828. UserId = Users[UserKey].UserId,
  829. UserNav = Users[UserKey].UserNav,
  830. Money = ProfitMoney,
  831. });
  832. dbnew.ProfitObjectsActiveCheck.Add(new ProfitObjectsActiveCheck()
  833. {
  834. CheckData = CheckKey
  835. });
  836. dbnew.SaveChanges();
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. }
  844. return result;
  845. }
  846. #endregion
  847. #region 激活奖励算法
  848. public ProfitResult ActivationProft(PosMachinesTwo machine, ProfitUsers User)
  849. {
  850. int BrandId = machine.BrandId;
  851. DateTime Start = machine.ActivationTime.Value;
  852. ProfitResult result = new ProfitResult();
  853. if (machine.PosSnType == 1 && machine.UserId != machine.BuyUserId) //循环机具,划拨给其他人,没有激活返现没有循环
  854. {
  855. return result;
  856. }
  857. ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
  858. if (obj.Status == 1) //判断分润是否开启
  859. {
  860. ProfitObjectActivations objact = RedisDbconn.Instance.Get<ProfitObjectActivations>("pobjacti" + BrandId);
  861. if (objact.StartDate <= DateTime.Now && objact.EndDate >= DateTime.Now)
  862. {
  863. int LimitDateKind = objact.LimitDateKind; //时间限制类型 日月年/自定义
  864. int LimitDateVal = objact.LimitDateVal; //时间限制值 日月年
  865. decimal ProfitMoney = objact.ProfitNumber;
  866. int MachineCount = objact.MachineCount;
  867. DateTime checkDate = Start;
  868. if (LimitDateKind == 1)
  869. {
  870. checkDate = checkDate.AddDays(LimitDateVal);
  871. }
  872. else if (LimitDateKind == 2)
  873. {
  874. checkDate = checkDate.AddMonths(LimitDateVal);
  875. }
  876. else if (LimitDateKind == 3)
  877. {
  878. checkDate = checkDate.AddYears(LimitDateVal);
  879. }
  880. else if (LimitDateKind == 4)
  881. {
  882. checkDate = objact.LimitCustomerDate.Value;
  883. }
  884. // if (DateTime.Now > checkDate && ProfitMoney > objact.ExpiredNumber)
  885. // {
  886. // ProfitMoney = objact.ExpiredNumber;
  887. // }
  888. if (ProfitMoney >= obj.MinProfitVal)
  889. {
  890. result = new ProfitResult()
  891. {
  892. UserId = User.UserId,
  893. UserNav = User.UserNav,
  894. Money = ProfitMoney,
  895. MachineCount = MachineCount,
  896. };
  897. }
  898. }
  899. }
  900. return result;
  901. }
  902. #endregion
  903. #region 获取分润规则Id
  904. private int GetLevelKindId(int BrandId, int Help, int BankCardType)
  905. {
  906. return RedisDbconn.Instance.Get<int>("pobjlv:kid:" + BrandId + ":" + Help + ":" + BankCardType);
  907. }
  908. #endregion
  909. #region POS统计交易额
  910. public void StartListenTradeDo(int tradeId, bool profit = true)
  911. {
  912. try
  913. {
  914. WebCMSEntities dbnew = new WebCMSEntities();
  915. TradeRecord trade_record = dbnew.TradeRecord.FirstOrDefault(m => m.Id == tradeId);
  916. if (trade_record != null)
  917. {
  918. int BrandId = trade_record.BrandId;
  919. decimal TradeAmt = trade_record.TradeAmount;
  920. int BankCardTypeNum = trade_record.BankCardType; //1-贷记卡,0-借记卡,2-准贷记卡
  921. DateTime TradeDateTime = trade_record.CreateDate.Value;
  922. string monthString = TradeDateTime.ToString("yyyyMM");
  923. string dayString = TradeDateTime.ToString("yyyyMMdd");
  924. string NaturalMonthString = RedisDbconn.Instance.Get<string>("pobjrule:" + BrandId + ":HelpPolicy:NaturalMonth");
  925. int NaturalMonth = int.Parse(NaturalMonthString); //自然月
  926. MachineForSnNo machinefor = dbnew.MachineForSnNo.FirstOrDefault(m => m.SnNo == trade_record.SnNo) ?? new MachineForSnNo();
  927. PosMachinesTwo machine = dbnew.PosMachinesTwo.FirstOrDefault(m => m.Id == machinefor.SnId) ?? new PosMachinesTwo();
  928. Users user = dbnew.Users.FirstOrDefault(m => m.Id == machine.UserId) ?? new Users();
  929. int TopUserId = 0;
  930. if (!string.IsNullOrEmpty(user.ParentNav))
  931. {
  932. string[] navList = user.ParentNav.Trim(',').Replace(",,", ",").Split(',');
  933. if (navList.Length > 1)
  934. {
  935. TopUserId = int.Parse(navList[1]);
  936. }
  937. else
  938. {
  939. TopUserId = int.Parse(navList[0]);
  940. }
  941. }
  942. PosMerchantInfo merchant = dbnew.PosMerchantInfo.FirstOrDefault(m => m.Id == machine.BindMerchantId) ?? new PosMerchantInfo();
  943. List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();
  944. using (var tran = dbnew.Database.BeginTransaction())
  945. {
  946. try
  947. {
  948. ulong DirectFlag = merchant.UserId == machine.UserId ? 1u : 0u; //是否直营
  949. ulong MerHelpFlag = 1; //扶持期、稳定期
  950. if (merchant.CreateDate.Value < DateTime.Now.AddMonths(-NaturalMonth))
  951. {
  952. MerHelpFlag = 0;
  953. }
  954. int HelpMonthCount = DateTime.Now.Month - merchant.CreateDate.Value.Month; //扶持期第几月
  955. if (HelpMonthCount < 0)
  956. {
  957. HelpMonthCount = 12 + DateTime.Now.Month - merchant.CreateDate.Value.Month;
  958. }
  959. int QrPayFlag = trade_record.QrPayFlag;
  960. decimal CreditTradeAmt = 0;
  961. decimal DebitNotCapTradeAmt = 0;
  962. decimal DebitCapTradeAmt = 0;
  963. int DebitCapTradeNum = 0;
  964. if (BankCardTypeNum == 1)
  965. {
  966. CreditTradeAmt = TradeAmt;
  967. }
  968. else if (BankCardTypeNum == 0)
  969. {
  970. //累计借记卡封顶或非封顶交易 // TODO:需优化,判断不太科学
  971. // decimal profitrate = 0;
  972. // if (user.CreateDate.Value.AddMonths(NaturalMonth) >= DateTime.Now)
  973. // {
  974. // UserProfitSet profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardTypeNum && m.HelpFlag == 1) ?? new UserProfitSet(); //获取创客分润规则-扶持期
  975. // profitrate = profitSet.ProfitRate;
  976. // }
  977. // else
  978. // {
  979. // UserProfitSet profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardTypeNum && m.HelpFlag == 0) ?? new UserProfitSet(); //获取创客分润规则-非扶持期
  980. // profitrate = profitSet.ProfitRate;
  981. // }
  982. // profitrate = profitrate / 100;
  983. // int UserLevel = user.UserLevel; //当前会员等级
  984. // decimal utrade = RedisDbconn.Instance.Get<decimal>("TeamTradeStat:" + user.Id + ":" + BrandId + ":" + DateTime.Now.ToString("yyMM"));
  985. // UserLevelSet checklevel = levels.Where(m => m.UpLevelIntegral < utrade).OrderBy(m => m.Id).FirstOrDefault();
  986. // if (checklevel != null)
  987. // {
  988. // UserLevel = checklevel.Id + 1;
  989. // }
  990. // ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + GetLevelKindId(BrandId) + ":" + UserLevel); //获取当前等级参数
  991. // decimal getLevelProfit = TradeAmt * objlevel.Percents * profitrate;
  992. // if (getLevelProfit < 1)
  993. // {
  994. // DebitNotCapTradeAmt = TradeAmt;
  995. // }
  996. // else
  997. // {
  998. // DebitCapTradeAmt = TradeAmt;
  999. // DebitCapTradeNum = 1;
  1000. // trade_record.CapFlag = 1;
  1001. // dbnew.SaveChanges();
  1002. // }
  1003. DebitNotCapTradeAmt = TradeAmt;
  1004. }
  1005. UserTradeMonthSummary editsummary = dbnew.UserTradeMonthSummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeMonth == monthString && m.BrandId == BrandId && m.StatType == 0);
  1006. if (editsummary == null)
  1007. {
  1008. dbnew.UserTradeMonthSummary.Add(new UserTradeMonthSummary()
  1009. {
  1010. CreateDate = DateTime.Now,
  1011. UserId = user.Id, //创客
  1012. TradeMonth = monthString, //交易月
  1013. BrandId = BrandId, //品牌
  1014. StatType = 0, //交易统计类型
  1015. TradeAmt = TradeAmt, //商户交易总额
  1016. CreditTradeAmt = CreditTradeAmt, //商户贷记卡交易总金额
  1017. DebitNotCapTradeAmt = DebitNotCapTradeAmt, //商户非封顶借记卡交易总金额
  1018. DebitCapTradeAmt = DebitCapTradeAmt, //商户借记卡封顶交易总额
  1019. DebitCapTradeNum = DebitCapTradeNum, //商户借记卡封顶交易总笔数
  1020. MallPosOrderStatus = machine.PosSnType == 1 ? 0 : 1, //商城兑换机具状态
  1021. ActiveBuddyMerStatus = user.RealName == merchant.MerchantName ? 0 : 1, //激活创客同名商户
  1022. });
  1023. }
  1024. else
  1025. {
  1026. editsummary.TradeAmt += TradeAmt;
  1027. editsummary.CreditTradeAmt += CreditTradeAmt;
  1028. editsummary.DebitNotCapTradeAmt += DebitNotCapTradeAmt;
  1029. editsummary.DebitCapTradeAmt += DebitCapTradeAmt;
  1030. editsummary.DebitCapTradeNum += DebitCapTradeNum;
  1031. }
  1032. TradeDaySummary editdaysum = dbnew.TradeDaySummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeDate == dayString && m.BrandId == BrandId);
  1033. if (editdaysum == null)
  1034. {
  1035. editdaysum = dbnew.TradeDaySummary.Add(new TradeDaySummary()
  1036. {
  1037. CreateDate = DateTime.Now,
  1038. UserId = user.Id, //创客
  1039. TradeDate = dayString, //交易日
  1040. TradeMonth = monthString, //交易月
  1041. BrandId = BrandId, //品牌
  1042. TopUserId = TopUserId, //顶级创客
  1043. }).Entity;
  1044. dbnew.SaveChanges();
  1045. }
  1046. //分类统计交易额
  1047. if (MerHelpFlag == 0)
  1048. {
  1049. if (DirectFlag == 1)
  1050. {
  1051. editdaysum.NotHelpDirectTradeAmt = TradeAmt; //直营商户交易总额(非扶持期)
  1052. if (BankCardTypeNum == 1)
  1053. {
  1054. editdaysum.NotHelpDirectCreditTradeAmt += TradeAmt; //直营贷记卡交易总额(非扶持期)
  1055. if (QrPayFlag == 1)
  1056. {
  1057. editdaysum.NotHelpDirectQrCreditTradeAmt += TradeAmt; //直营云闪付贷记卡交易额(非扶持期)
  1058. }
  1059. else
  1060. {
  1061. editdaysum.NotHelpDirectNonQrCreditTradeAmt += TradeAmt; //直营非云闪付贷记卡交易额(非扶持期)
  1062. }
  1063. }
  1064. else
  1065. {
  1066. editdaysum.NotHelpDirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额(非扶持期)
  1067. if (DebitCapTradeNum > 0)
  1068. {
  1069. editdaysum.NotHelpDirectDebitCapTradeAmt += TradeAmt; //直营商户借记卡封顶交易总金额(非扶持期)
  1070. editdaysum.NotHelpDirectDebitCapNum += 1; //直营商户借记卡封顶交易总数(非扶持期)
  1071. }
  1072. else
  1073. {
  1074. if (QrPayFlag == 1)
  1075. {
  1076. editdaysum.NotHelpDirectQrDebitTradeAmt += TradeAmt; //直营云闪付非封顶借记卡(非扶持期)
  1077. }
  1078. else
  1079. {
  1080. editdaysum.NotHelpDirectNonQrDebitTradeAmt += TradeAmt; //直营非云闪付非封顶借记卡(非扶持期)
  1081. }
  1082. }
  1083. }
  1084. }
  1085. else
  1086. {
  1087. editdaysum.NotHelpNonDirectTradeAmt += TradeAmt; //非直营商户交易总额(非扶持期)
  1088. if (BankCardTypeNum == 1)
  1089. {
  1090. editdaysum.NotHelpNonDirectCreditTradeAmt += TradeAmt; //非直营贷记卡交易总额(非扶持期)
  1091. if (QrPayFlag == 1)
  1092. {
  1093. editdaysum.NotHelpNonDirectQrCreditTradeAmt += TradeAmt; //非直营云闪付贷记卡交易额(非扶持期)
  1094. }
  1095. else
  1096. {
  1097. editdaysum.NotHelpNonDirectNonQrCreditTradeAmt += TradeAmt; //非直营非云闪付贷记卡交易额(非扶持期)
  1098. }
  1099. }
  1100. else
  1101. {
  1102. editdaysum.NotHelpNonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额(非扶持期)
  1103. if (DebitCapTradeNum > 0)
  1104. {
  1105. editdaysum.NotHelpNonDirectDebitCapTradeAmt += TradeAmt; //非直营商户借记卡封顶交易总金额(非扶持期)
  1106. editdaysum.NotHelpNonDirectDebitCapNum += 1; //非直营商户借记卡封顶交易总数(非扶持期)
  1107. }
  1108. else
  1109. {
  1110. if (QrPayFlag == 1)
  1111. {
  1112. editdaysum.NotHelpNonDirectQrDebitTradeAmt += TradeAmt; //非直营云闪付非封顶借记卡(非扶持期)
  1113. }
  1114. else
  1115. {
  1116. editdaysum.NotHelpNonDirectNonQrDebitTradeAmt += TradeAmt; //非直营非云闪付非封顶借记卡(非扶持期)
  1117. }
  1118. }
  1119. }
  1120. }
  1121. }
  1122. else
  1123. {
  1124. if (DirectFlag == 1)
  1125. {
  1126. editdaysum.HelpDirectTradeAmt += TradeAmt; //直营商户交易总额(扶持期)
  1127. if (BankCardTypeNum == 1)
  1128. {
  1129. editdaysum.HelpDirectCreditTradeAmt += TradeAmt; //直营贷记卡交易总额(扶持期)
  1130. if (QrPayFlag == 1)
  1131. {
  1132. editdaysum.HelpDirectQrCreditTradeAmt += TradeAmt; //直营云闪付贷记卡交易额(扶持期)
  1133. }
  1134. else
  1135. {
  1136. editdaysum.HelpDirectNonQrCreditTradeAmt += TradeAmt; //直营非云闪付贷记卡交易额(扶持期)
  1137. }
  1138. }
  1139. else
  1140. {
  1141. editdaysum.HelpDirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额(扶持期)
  1142. if (DebitCapTradeNum > 0)
  1143. {
  1144. editdaysum.HelpDirectDebitCapTradeAmt += TradeAmt; //直营商户借记卡封顶交易总金额(扶持期)
  1145. editdaysum.HelpDirectDebitCapNum += 1; //直营商户借记卡封顶交易总数(扶持期)
  1146. }
  1147. else
  1148. {
  1149. if (QrPayFlag == 1)
  1150. {
  1151. editdaysum.HelpDirectQrDebitTradeAmt += TradeAmt; //直营云闪付非封顶借记卡(扶持期)
  1152. }
  1153. else
  1154. {
  1155. editdaysum.HelpDirectNonQrDebitTradeAmt += TradeAmt; //直营非云闪付非封顶借记卡(扶持期)
  1156. }
  1157. }
  1158. }
  1159. }
  1160. else
  1161. {
  1162. editdaysum.HelpNonDirectTradeAmt += TradeAmt; //非直营商户交易总额(扶持期)
  1163. if (BankCardTypeNum == 1)
  1164. {
  1165. editdaysum.HelpNonDirectCreditTradeAmt += TradeAmt; //非直营贷记卡交易总额(扶持期)
  1166. if (QrPayFlag == 1)
  1167. {
  1168. editdaysum.HelpNonDirectQrCreditTradeAmt += TradeAmt; //非直营云闪付贷记卡交易额(扶持期)
  1169. }
  1170. else
  1171. {
  1172. editdaysum.HelpNonDirectNonQrCreditTradeAmt += TradeAmt; //非直营非云闪付贷记卡交易额(扶持期)
  1173. }
  1174. }
  1175. else
  1176. {
  1177. editdaysum.HelpNonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额(扶持期)
  1178. if (DebitCapTradeNum > 0)
  1179. {
  1180. editdaysum.HelpNonDirectDebitCapTradeAmt += TradeAmt; //非直营商户借记卡封顶交易总金额(扶持期)
  1181. editdaysum.HelpNonDirectDebitCapNum += 1; //非直营商户借记卡封顶交易总数(扶持期)
  1182. }
  1183. else
  1184. {
  1185. if (QrPayFlag == 1)
  1186. {
  1187. editdaysum.HelpNonDirectQrDebitTradeAmt += TradeAmt; //非直营云闪付非封顶借记卡(扶持期)
  1188. }
  1189. else
  1190. {
  1191. editdaysum.HelpNonDirectNonQrDebitTradeAmt += TradeAmt; //非直营非云闪付非封顶借记卡(扶持期)
  1192. }
  1193. }
  1194. }
  1195. }
  1196. }
  1197. UserTradeDaySummary userdaysum = dbnew.UserTradeDaySummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeDate == dayString && m.BrandId == BrandId);
  1198. if (userdaysum == null)
  1199. {
  1200. userdaysum = dbnew.UserTradeDaySummary.Add(new UserTradeDaySummary()
  1201. {
  1202. CreateDate = DateTime.Now,
  1203. UserId = user.Id, //创客
  1204. TradeDate = dayString, //交易日
  1205. TradeMonth = monthString, //交易月
  1206. BrandId = BrandId, //品牌
  1207. }).Entity;
  1208. dbnew.SaveChanges();
  1209. }
  1210. if (DirectFlag == 1)
  1211. {
  1212. userdaysum.DirectTradeAmt += TradeAmt; //直营商户交易总额
  1213. if (BankCardTypeNum == 0)
  1214. {
  1215. userdaysum.DirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额
  1216. }
  1217. }
  1218. else
  1219. {
  1220. userdaysum.NonDirectTradeAmt += TradeAmt; //非直营商户交易总额
  1221. if (BankCardTypeNum == 0)
  1222. {
  1223. userdaysum.NonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额
  1224. }
  1225. }
  1226. dbnew.SaveChanges();
  1227. if (profit)
  1228. {
  1229. DoProfitForPos(dbnew, trade_record);
  1230. }
  1231. tran.Commit();
  1232. }
  1233. catch (Exception ex)
  1234. {
  1235. function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "自定义分润程序监听队列异常");
  1236. tran.Rollback();
  1237. }
  1238. }
  1239. }
  1240. dbnew.Dispose();
  1241. }
  1242. catch (Exception ex)
  1243. {
  1244. function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "自定义分润程序监听队列异常");
  1245. }
  1246. }
  1247. public void DoProfitForPos(WebCMSEntities dbnew, TradeRecord trade_record)
  1248. {
  1249. List<ProfitUsers> users = new List<ProfitUsers>();
  1250. int TopUserId = 0; //顶级创客Id
  1251. Users us = dbnew.Users.FirstOrDefault(a => a.Id == trade_record.UserId);
  1252. if (us != null)
  1253. {
  1254. string uidstring = us.Id.ToString();
  1255. string[] uidlist = { };
  1256. if (!string.IsNullOrEmpty(us.ParentNav))
  1257. {
  1258. uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
  1259. uidlist = uidstring.Split(',');
  1260. if (uidlist.Length > 1)
  1261. {
  1262. TopUserId = int.Parse(function.CheckInt(uidlist[1]));
  1263. }
  1264. else
  1265. {
  1266. TopUserId = int.Parse(function.CheckInt(uidlist[0]));
  1267. }
  1268. }
  1269. Array.Reverse(uidlist);
  1270. foreach (string uidstr in uidlist)
  1271. {
  1272. int puid = int.Parse(function.CheckInt(uidstr));
  1273. Users pus = dbnew.Users.FirstOrDefault(a => a.Id == puid);
  1274. if (pus != null)
  1275. {
  1276. users.Add(new ProfitUsers()
  1277. {
  1278. UserId = pus.Id,
  1279. UserNav = pus.ParentNav,
  1280. UserLevel = pus.UserLevel,
  1281. CreateDate = pus.CreateDate.Value,
  1282. });
  1283. }
  1284. }
  1285. }
  1286. string TradeMonth = trade_record.TradeDate.Value.ToString("yyyyMM");
  1287. List<ProfitResult> list = new List<ProfitResult>();
  1288. list = StartProftForPos(dbnew, trade_record, users);
  1289. using (var tran = dbnew.Database.BeginTransaction())
  1290. {
  1291. try
  1292. {
  1293. foreach (ProfitResult sub in list)
  1294. {
  1295. if (sub.Message == "分红奖励")
  1296. {
  1297. UserAccountRecord accountRecord = dbnew.UserAccountRecord.Add(new UserAccountRecord()
  1298. {
  1299. CreateDate = DateTime.Now,
  1300. UpdateDate = DateTime.Now,
  1301. UserId = sub.UserId, //创客
  1302. ChangeType = 11, //变动类型
  1303. ProductType = trade_record.BrandId, //产品类型
  1304. ChangeAmount = sub.Money, //变更金额
  1305. Status = -1,
  1306. }).Entity;
  1307. dbnew.SaveChanges();
  1308. }
  1309. else
  1310. {
  1311. int ProfitType = sub.UserId == trade_record.UserId ? 0 : 1;
  1312. ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.MerchantId == trade_record.MerchantId && m.BrandId == trade_record.BrandId && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth);
  1313. if (editprofitrecord == null)
  1314. {
  1315. editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
  1316. {
  1317. CreateDate = DateTime.Now,
  1318. UserId = sub.UserId, //创客
  1319. MerchantId = trade_record.MerchantId, //商户
  1320. BrandId = trade_record.BrandId, //品牌
  1321. ProfitType = ProfitType, //创客分润类型
  1322. TradeMonth = TradeMonth, //交易月
  1323. TopUserId = TopUserId, //顶级创客
  1324. }).Entity;
  1325. dbnew.SaveChanges();
  1326. string RecordNo = "KPM";
  1327. int RecordId = editprofitrecord.Id;
  1328. string RecordIdString = RecordId.ToString();
  1329. for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
  1330. {
  1331. RecordIdString = "0" + RecordIdString;
  1332. }
  1333. RecordNo += RecordIdString;
  1334. editprofitrecord.RecordNo = RecordNo;
  1335. dbnew.SaveChanges();
  1336. }
  1337. // editprofitrecord.OtherTradeAmt = 0; //其他产品交易总金额
  1338. // editprofitrecord.OtherCreditTradeAmt = 0; //其他产品贷记卡交易总金额
  1339. // editprofitrecord.OtherDebitNotCapTradeAmt = 0; //其他产品借记卡非封顶交易总金额
  1340. decimal TradeAmount = trade_record.TradeAmount;
  1341. editprofitrecord.TradeAmt += TradeAmount; //商户交易总额
  1342. if (trade_record.BankCardType == 0) editprofitrecord.CreditTradeAmt += TradeAmount; //贷记卡交易总金额
  1343. if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditTradeAmt += TradeAmount; //(云闪付)贷记卡交易总金额
  1344. if (trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NonQrCreditTradeAmt += TradeAmount; //(非云闪付)贷记卡交易总金额
  1345. if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditTradeAmt += TradeAmount; //(非扶持期)(非云闪付)贷记卡交易总金额
  1346. if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditTradeAmt += TradeAmount; //(扶持期)(非云闪付)贷记卡交易总金额
  1347. if (sub.Money < 1 && trade_record.BankCardType == 1) editprofitrecord.DebitNonCapTradeAmt += TradeAmount; //商户非封顶借记卡交易总额
  1348. if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitNotCapTradeAmt += TradeAmount; //(云闪付)商户非封顶借记卡交易总额
  1349. if (sub.Money < 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NonQrDebitNotCapTradeAmt += TradeAmount; //(非云闪付)商户非封顶借记卡交易总额
  1350. if (sub.Money < 1 && trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitNonCapTradeAmt += TradeAmount; //(非扶持期)(非云闪付)借记卡非封顶交易总金额
  1351. if (sub.Money < 1 && trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitNonCapTradeAmt += TradeAmount; //(扶持期)(非云闪付)借记卡非封顶交易总金额
  1352. if (sub.Money == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitCapTradeAmt = TradeAmount; //商户借记卡封顶交易总额
  1353. editprofitrecord.DebitCapTradeNum += 1; //商户借记卡封顶交易总笔数
  1354. decimal ProfitMoney = sub.Money;
  1355. ulong DirectFlag = trade_record.DirectFlag;
  1356. editprofitrecord.TradeProfit += ProfitMoney; //交易分润
  1357. if (trade_record.BankCardType == 0) editprofitrecord.CreditTradeProfit += ProfitMoney; //贷记卡分润总金额
  1358. if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditTradeProfit += ProfitMoney; //(云闪付)贷记卡交易分润
  1359. if (trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NonQrCreditTradeProfit += ProfitMoney; //(非云闪付)贷记卡交易分润
  1360. if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditTradeProfit += ProfitMoney; //(非扶持期)(非云闪付)贷记卡分润总金额
  1361. if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditTradeProfit += ProfitMoney; //(扶持期)(非云闪付)贷记卡分润总金额
  1362. if (sub.Money < 1 && trade_record.BankCardType == 1) editprofitrecord.DebitNonTradeCapProfit += ProfitMoney; //借记卡非封顶交易分润总金额
  1363. if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitNonTradeCapProfit += ProfitMoney; //(云闪付)借记卡非封顶交易分润总金额
  1364. if (sub.Money < 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NonQrDebitNonTradeCapProfit += ProfitMoney; //(非云闪付)借记卡非封顶交易分润总金额
  1365. if (sub.Money < 1 && trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitNonTradeCapProfit += ProfitMoney; //(非扶持期)(非云闪付)借记卡非封顶交易分润总金额
  1366. if (sub.Money < 1 && trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitNonTradeCapProfit += ProfitMoney; //(扶持期)(非云闪付)借记卡非封顶交易分润总金额
  1367. if (sub.Money == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitTradeCapProfit += ProfitMoney; //借记卡封顶交易分润总金额
  1368. if (sub.Money < 1 && DirectFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitCapSingleReward += ProfitMoney; //借记卡合伙人直营封顶交易奖励金额
  1369. if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditProfitRate = sub.ProfitRate; //(非扶持期)(非云闪付)贷记卡商户交易对应分润比例
  1370. if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditProfitStandardRate = sub.ProfitPercent; //(非扶持期)(非云闪付)贷记卡标准分润比例
  1371. if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditAddOrSubRate = sub.AddOrSubRate; //(非扶持期)(非云闪付)贷记卡成本或增或减比例
  1372. if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditProfitRate = sub.ProfitRate; //(扶持期)(非云闪付)贷记卡商户交易对应分润比例
  1373. if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditProfitStandardRate = sub.ProfitPercent; //(扶持期)(非云闪付)贷记卡-标准分润比例
  1374. if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditAddOrSubRate = sub.AddOrSubRate; //(扶持期)(非云闪付)贷记卡成本或增或减比例
  1375. if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitProfitRate = sub.ProfitRate; //(非扶持期)(非云闪付)借记卡商户交易对应分润比例
  1376. if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitProfitStandardRate = sub.ProfitPercent; //(非扶持期)(非云闪付)借记卡标准分润比例
  1377. if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitAddOrSubRate = sub.AddOrSubRate; //(非扶持期)(非云闪付)借记卡成本或增或减比例
  1378. if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitProfitRate = sub.ProfitRate; //(扶持期)(非云闪付)借记卡商户交易对应分润比例
  1379. if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitProfitStandardRate = sub.ProfitPercent; //(扶持期)(非云闪付)借记卡-标准分润比例
  1380. if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitAddOrSubRate = sub.AddOrSubRate; //(扶持期)(非云闪付)借记卡成本或增或减比例
  1381. if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditProfitRate = sub.ProfitRate; //(云闪付)贷记卡交易分润比例
  1382. if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditProfitStandardRate = sub.ProfitRateBase; //(云闪付)贷记卡分润基准
  1383. editprofitrecord.QrCreditAddOrSubRate = sub.AddOrSubRate; //(云闪付)贷记卡分润比例或增或减
  1384. if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitProfitRate = sub.ProfitRate; //(云闪付)借记卡非封顶交易分润比例
  1385. if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitProfitStandardRate = sub.ProfitRateBase; //(云闪付)借记卡非封顶交易分润基准
  1386. if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitAddOrSubRate = sub.AddOrSubRate; //(云闪付)借记卡非封顶交易分润比例或增或减
  1387. dbnew.SaveChanges();
  1388. dbnew.ProfitRecord.Add(new ProfitRecord()
  1389. {
  1390. CreateDate = DateTime.Now,
  1391. UpdateDate = DateTime.Now,
  1392. UserId = sub.UserId, //创客
  1393. MerchantId = trade_record.MerchantId, //商户
  1394. MerNo = trade_record.MerNo, //渠道商户编号
  1395. MerHelpFlag = trade_record.MerHelpFlag, //是否属于扶持周期内商户
  1396. HelpMonthCount = trade_record.HelpMonthCount, //扶持第几个月
  1397. MerBuddyType = trade_record.MerBuddyType, //商户创客类型
  1398. SnNo = trade_record.SnNo, //SN号
  1399. TradeDate = trade_record.TradeDate, //交易日期
  1400. ProfitAmount = sub.Money, //分润金额
  1401. QrPayFlag = trade_record.QrPayFlag, //云闪付标识
  1402. CapFlag = trade_record.CapFlag, //借记卡封顶交易标志
  1403. DirectFlag = trade_record.DirectFlag, //是否直营
  1404. BrandId = trade_record.BrandId, //品牌
  1405. ParentNav = us.ParentNav, //上级创客集
  1406. TradeId = trade_record.Id, //交易记录Id
  1407. });
  1408. dbnew.SaveChanges();
  1409. // Users user = dbnew.Users.FirstOrDefault(m => m.Id == sub.UserId);
  1410. // if (user != null)
  1411. // {
  1412. // if (!string.IsNullOrEmpty(user.CloudPushDeviceId))
  1413. // {
  1414. // new AliyunPushOld().Push("鑫创客通知", "您有一笔分润收益:" + sub.Money.ToString("f2"), "30", "NOTICE", user.DeviceType, user.CloudPushDeviceId, "1");
  1415. // }
  1416. // TODO:发送阿里云推送消息
  1417. // }
  1418. }
  1419. }
  1420. dbnew.SaveChanges();
  1421. tran.Commit();
  1422. }
  1423. catch (Exception ex)
  1424. {
  1425. tran.Rollback();
  1426. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "POS分润异常");
  1427. }
  1428. }
  1429. }
  1430. #endregion
  1431. #region POS分润算法
  1432. public List<ProfitResult> StartProftForPos(WebCMSEntities dbnew, TradeRecord trade, List<ProfitUsers> users)
  1433. {
  1434. // 级差
  1435. /*
  1436. K1 - K5:无大小市场要求,无押机分润比例为有押金机的70%,如K1的有押金机分润比例为万6,则无押机的分润比例为万4.2
  1437. 机具激活大于90天,分润比例为原比例的70%
  1438. if(is0y){
  1439. 分润比例为原比例的70%
  1440. }
  1441. if(ActivityDate > now - 90){
  1442. 分润比例为原比例的70%
  1443. }
  1444. K6 - K9:
  1445. K6:至少有1个直推大于3000万,且总交易额减去3000万大于1200万,则获得分红奖(月月红)直接级差
  1446. K7:总交易额减去最大交易额的直推,大于4000万,则获得分红奖(月月红)直接级差
  1447. K8:总交易额减去最大交易额的直推,大于12000万,则获得分红奖(月月红)直接级差
  1448. K9:总交易额减去最大交易额的直推,大于32000万,则获得分红奖(月月红)直接级差
  1449. 补贴:
  1450. 0押金无补贴
  1451. 机具激活90天内,机具所属创客获得万10置顶
  1452. 若创客为商户型创客,则机具UserId的创客获得万4分润
  1453. */
  1454. List<ProfitResult> result = new List<ProfitResult>();
  1455. int BrandId = trade.BrandId;
  1456. ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
  1457. if (obj.Status == 1) //判断分润是否开启
  1458. {
  1459. decimal TradeMoney = trade.TradeAmount;
  1460. int BankCardType = trade.BankCardType; //银行卡类型:贷记卡-1,借记卡-0
  1461. int MerHelpFlag = (int)trade.MerHelpFlag; //扶持期-1,稳定期=0
  1462. List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();
  1463. int IncludeCurrentMonth = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":HelpPolicy:IncludeCurrentMonth")); //是否包含当前月
  1464. int NaturalMonth = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":HelpPolicy:NaturalMonth")); //自然月
  1465. if(IncludeCurrentMonth == 1) NaturalMonth -= 1;
  1466. if (BankCardType == 0)
  1467. {
  1468. Users user = dbnew.Users.FirstOrDefault(m => m.Id == trade.UserId) ?? new Users();
  1469. // UserProfitSet profitSet = profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardType && m.HelpFlag == MerHelpFlag) ?? new UserProfitSet(); //获取创客分润规则-扶持期
  1470. // profitrate = profitSet.ProfitRate;
  1471. // profitrate = profitrate / 100;
  1472. int UserLevel = user.UserLevel; //当前会员等级
  1473. int HelpTime = 0;
  1474. if (user.CreateDate.Value.AddMonths(NaturalMonth) > DateTime.Now)
  1475. {
  1476. HelpTime = 1;
  1477. }
  1478. int LevelKindId = GetLevelKindId(trade.BrandId, HelpTime, BankCardType);
  1479. ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
  1480. decimal getLevelProfit = TradeMoney * objlevel.Percents;
  1481. if(getLevelProfit > 1) getLevelProfit = 1;
  1482. result.Add(new ProfitResult()
  1483. {
  1484. UserId = user.Id,
  1485. UserNav = user.ParentNav,
  1486. Money = getLevelProfit,
  1487. ProfitRate = objlevel.Percents,
  1488. // ProfitPercent = profitSet.ProfitPercent,
  1489. // AddOrSubRate = profitSet.AddOrSubRate,
  1490. // ProfitRateBase = profitSet.ProfitRateBase,
  1491. });
  1492. return result;
  1493. }
  1494. int maxLevel = obj.MaxLevel; //最大等级
  1495. int maxFloor = obj.MaxFloor; //最大层级
  1496. int maxContinueFloor = RedisDbconn.Instance.Get<int>("pobjconc" + BrandId); //最大继续分润层级
  1497. decimal diffLevelProfit = 0; //等级级差
  1498. decimal diffDiviProfit = 0; //分红级差
  1499. // decimal diffFloorProfit = 0; //层级级差
  1500. // int continueFloor = 0; //继续分润层级
  1501. int curLevel = 0; //当前层级的会员等级
  1502. for (int curFloor = 1; curFloor <= users.Count; curFloor++)
  1503. {
  1504. ProfitUsers user = new ProfitUsers();
  1505. if (curFloor <= users.Count)
  1506. {
  1507. user = users[curFloor - 1];
  1508. }
  1509. int UserLevel = user.UserLevel; //当前会员等级
  1510. //判断当前创客是否有直推的激活机具,并且在活动时间内
  1511. if (UserLevel == maxLevel && UserLevel == curLevel)
  1512. {
  1513. break;
  1514. }
  1515. if (UserLevel <= maxLevel && UserLevel > curLevel)
  1516. {
  1517. int HelpTime = 0;
  1518. if (user.CreateDate.AddMonths(NaturalMonth) > DateTime.Now)
  1519. {
  1520. HelpTime = 1;
  1521. }
  1522. int LevelKindId = GetLevelKindId(trade.BrandId, HelpTime, BankCardType);
  1523. ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
  1524. if (objlevel != null)
  1525. {
  1526. decimal getLevelProfit = 0; //等级分润
  1527. // UserProfitSet profitSet = new UserProfitSet();
  1528. if (objlevel.Percents > 0)
  1529. {
  1530. //获取创客分润规则,注册日开始算起,3个自然月内算扶持期
  1531. decimal profitrate = objlevel.Percents;
  1532. // profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.UserId && m.BrandId == BrandId && m.CardType == BankCardType && m.HelpFlag == MerHelpFlag) ?? new UserProfitSet(); //获取创客分润规则-扶持期
  1533. // profitrate = profitSet.ProfitRate;
  1534. // profitrate = profitrate / 100;
  1535. getLevelProfit += TradeMoney * objlevel.Percents * profitrate;
  1536. }
  1537. if (objlevel.AddProfitVal > 0)
  1538. {
  1539. //分红奖励:一个3000万,3000万以下市场总和大于1200万
  1540. bool bigMarket = false;
  1541. decimal smallMarket = 0;
  1542. List<Users> directs = dbnew.Users.Where(m => m.ParentUserId == user.UserId).ToList();
  1543. decimal BigMarketTradeAmt = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:BigMarketTradeAmt")); //大市场交易额
  1544. decimal PassTradeAmt = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:PassTradeAmt")); //小市场交易超越额
  1545. decimal UnitPrize = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:UnitPrize")); //单位奖励基数
  1546. foreach (Users direct in directs)
  1547. {
  1548. UserData userData = dbnew.UserData.FirstOrDefault(m => m.UserId == direct.Id) ?? new UserData();
  1549. if (userData.TotalOrderMoney >= BigMarketTradeAmt)
  1550. {
  1551. bigMarket = true;
  1552. }
  1553. else
  1554. {
  1555. smallMarket += userData.TotalOrderMoney;
  1556. }
  1557. }
  1558. if (bigMarket && smallMarket >= PassTradeAmt)
  1559. {
  1560. decimal DiviPrize = objlevel.AddProfitVal * TradeMoney / UnitPrize;
  1561. decimal checkmoney = DiviPrize;
  1562. DiviPrize -= diffDiviProfit;
  1563. if (objlevel.LevelDiff == 1) //判断是否有级差
  1564. {
  1565. diffDiviProfit = checkmoney;
  1566. }
  1567. if (DiviPrize >= obj.MinProfitVal)
  1568. {
  1569. result.Add(new ProfitResult()
  1570. {
  1571. UserId = user.UserId,
  1572. UserNav = user.UserNav,
  1573. Money = DiviPrize,
  1574. Message = "分红奖励",
  1575. });
  1576. }
  1577. }
  1578. }
  1579. decimal money = getLevelProfit;
  1580. getLevelProfit -= diffLevelProfit;
  1581. if (objlevel.LevelDiff == 1) //判断是否有级差
  1582. {
  1583. diffLevelProfit = money;
  1584. }
  1585. if (getLevelProfit >= obj.MinProfitVal)
  1586. {
  1587. result.Add(new ProfitResult()
  1588. {
  1589. UserId = user.UserId,
  1590. UserNav = user.UserNav,
  1591. Money = getLevelProfit,
  1592. ProfitRate = objlevel.Percents,
  1593. // ProfitPercent = profitSet.ProfitPercent,
  1594. // AddOrSubRate = profitSet.AddOrSubRate,
  1595. // ProfitRateBase = profitSet.ProfitRateBase,
  1596. });
  1597. }
  1598. }
  1599. }
  1600. curLevel = UserLevel;
  1601. }
  1602. }
  1603. return result;
  1604. }
  1605. public void StatProfit()
  1606. {
  1607. Thread th = new Thread(StatProfitDo);
  1608. th.IsBackground = true;
  1609. th.Start();
  1610. }
  1611. public void StatProfitDo()
  1612. {
  1613. string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
  1614. string check = function.ReadInstance("/ProfitStat/" + Month + ".txt");
  1615. if (!string.IsNullOrEmpty(check))
  1616. {
  1617. return;
  1618. }
  1619. function.WritePage("/ProfitStat/", Month + ".txt", DateTime.Now.ToString());
  1620. WebCMSEntities db = new WebCMSEntities();
  1621. for (int i = 1; i <= 9; i++) //品牌
  1622. {
  1623. for (int j = 0; j <= 1; j++) //卡类型
  1624. {
  1625. int PageNum = 1;
  1626. bool op = true;
  1627. while(op)
  1628. {
  1629. List<ProfitResult> result = StartProftForPosByMonth(i, j, Month, PageNum);
  1630. if(result.Count > 0)
  1631. {
  1632. foreach (ProfitResult sub in result)
  1633. {
  1634. int TopUserId = 0;
  1635. if (!string.IsNullOrEmpty(sub.UserNav))
  1636. {
  1637. string[] UserNavList = sub.UserNav.Trim(',').Replace(",,", ",").Split(',');
  1638. if (UserNavList.Length > 1)
  1639. {
  1640. TopUserId = int.Parse(UserNavList[1]);
  1641. }
  1642. else
  1643. {
  1644. TopUserId = int.Parse(UserNavList[0]);
  1645. }
  1646. }
  1647. string RecordNo = "P" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
  1648. decimal ProfitAmt = sub.Money;
  1649. decimal TradeAmt = sub.TradeAmount;
  1650. decimal ProfitRate = sub.ProfitRate;
  1651. if (sub.IsSubsidy == 1 && j == 1)
  1652. {
  1653. decimal CreditTradeAmt = TradeAmt; //商户贷记卡交易总金额
  1654. decimal QrCreditTradeAmt = 0; //商户(云闪付)贷记卡交易总金额
  1655. decimal NonQrCreditTradeAmt = 0; //商户(非云闪付)贷记卡交易总金额
  1656. decimal CreditProfitRate = 0; //(非云闪付)贷记卡交易分润比例
  1657. decimal SubsidyProfit = 0; //商户(非云闪付)贷记卡交易分润补贴金额
  1658. if (sub.QrPayFlag == 1)
  1659. {
  1660. QrCreditTradeAmt = TradeAmt; //商户(云闪付)贷记卡交易总金额
  1661. }
  1662. else
  1663. {
  1664. NonQrCreditTradeAmt = TradeAmt; //商户(非云闪付)贷记卡交易总金额
  1665. CreditProfitRate = ProfitRate; //(非云闪付)贷记卡交易分润比例
  1666. SubsidyProfit = ProfitAmt; //商户(非云闪付)贷记卡交易分润补贴金额
  1667. }
  1668. MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == sub.PosSn) ?? new MachineForSnNo();
  1669. PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PosMachinesTwo();
  1670. PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == sub.MerchantId) ?? new PosMerchantInfo();
  1671. db.ProfitSubsidyDetail.Add(new ProfitSubsidyDetail()
  1672. {
  1673. CreateDate = DateTime.Now,
  1674. UpdateDate = DateTime.Now,
  1675. RecordNo = RecordNo, //流水号
  1676. BrandId = sub.BrandId, //品牌
  1677. ProductName = RelationClass.GetKqProductBrandInfo(sub.BrandId), //产品名称
  1678. TradeMonth = Month, //交易月份
  1679. MerchantId = sub.MerchantId, //商户
  1680. MerNo = merchant.KqMerNo, //渠道商户编号
  1681. SnNo = sub.PosSn, //渠道SN号
  1682. MerRegTime = pos.BindingTime, //渠道注册时间
  1683. MerStandardDate = merchant.MerStandardDate, //商户激活时间
  1684. BelongUserId = merchant.UserId, //商户归属人
  1685. MerHelpFlag = sub.HelpFlag == 1 ? 1u : 0u, //是否属于扶持周期内商户
  1686. SubsidyUserId = sub.UserId, //补贴人
  1687. SubsidyType = sub.DirectFlag, //分润补贴类型
  1688. SubsidyProfitRate = sub.Money, //创客活动期内直营商户分润万分之十
  1689. CreditTradeAmt = CreditTradeAmt, //商户贷记卡交易总金额
  1690. QrCreditTradeAmt = QrCreditTradeAmt, //商户(云闪付)贷记卡交易总金额
  1691. NonQrCreditTradeAmt = NonQrCreditTradeAmt, //商户(非云闪付)贷记卡交易总金额
  1692. CreditProfitRate = CreditProfitRate, //(非云闪付)贷记卡交易分润比例
  1693. SubsidyProfit = SubsidyProfit, //商户(非云闪付)贷记卡交易分润补贴金额
  1694. });
  1695. }
  1696. }
  1697. db.SaveChanges();
  1698. PageNum += 1;
  1699. }
  1700. else
  1701. {
  1702. op = false;
  1703. }
  1704. }
  1705. }
  1706. }
  1707. db.Dispose();
  1708. HelpProfitHelper.Instance.StatProfitEveryDay(DateTime.Now.AddMonths(-1).ToString("yyyyMM")); //助利宝分润
  1709. ProfitCheckHelper.Instance.Start();
  1710. }
  1711. public List<ProfitResult> StartProftForPosByMonth(int BrandId, int BankCardType, string Month, int PageNum = 1)
  1712. {
  1713. // 级差
  1714. /*
  1715. K1 - K5:无大小市场要求,无押机分润比例为有押金机的70%,如K1的有押金机分润比例为万6,则无押机的分润比例为万4.2
  1716. 机具激活大于90天,分润比例为原比例的70%
  1717. if(is0y){
  1718. 分润比例为原比例的70%
  1719. }
  1720. if(ActivityDate > now - 90){
  1721. 分润比例为原比例的70%
  1722. }
  1723. K6 - K9:
  1724. K6:至少有1个直推大于3000万,且总交易额减去3000万大于1200万,则获得分红奖(月月红)直接级差
  1725. K7:总交易额减去最大交易额的直推,大于4000万,则获得分红奖(月月红)直接级差
  1726. K8:总交易额减去最大交易额的直推,大于12000万,则获得分红奖(月月红)直接级差
  1727. K9:总交易额减去最大交易额的直推,大于32000万,则获得分红奖(月月红)直接级差
  1728. 补贴:
  1729. 0押金无补贴
  1730. 机具激活90天内,机具所属创客获得万10置顶
  1731. 若创客为商户型创客,则机具UserId的创客获得万4分润
  1732. //查分润
  1733. select u.MakerCode,u.RealName,u.UserLevel,r.Rank,pos.SeoKeyword,p.KqSnNo,(case when ProfitType=1 then '直营' else '团队' end) as DirectFlag,
  1734. k.Name,CreditTradeAmt,CreditTradeProfit,DebitTradeAmt,DebitTradeProfit,QrCreditTradeAmt,QrCreditTradeProfit from (
  1735. select UserId,ProfitType,BrandId,MerchantId,
  1736. sum(CreditTradeAmt) as CreditTradeAmt,
  1737. sum(CreditTradeProfit) as CreditTradeProfit,
  1738. sum(DebitNonCapTradeAmt+DebitCapTradeAmt) as DebitTradeAmt,
  1739. sum(DebitNonTradeCapProfit+DebitTradeCapProfit) as DebitTradeProfit,
  1740. sum(QrCreditTradeAmt) as QrCreditTradeAmt,
  1741. sum(QrCreditTradeProfit) as QrCreditTradeProfit
  1742. from ProfitRewardRecord where MerchantId>0
  1743. GROUP BY UserId,ProfitType,BrandId,MerchantId
  1744. ) tb
  1745. left join Users u on tb.UserId=u.Id
  1746. LEFT JOIN KqProducts k ON k.Id=tb.BrandId
  1747. left join PosMerchantInfo p on tb.MerchantId=p.Id
  1748. left join MachineForSnNo fp on fp.SnNo=p.KqSnNo
  1749. left join PosMachinesTwo pos on pos.Id=fp.SnId
  1750. left join UserRankWhite r on u.Id=r.Id
  1751. ORDER BY p.KqSnNo,u.MakerCode
  1752. //查补贴
  1753. select u.MakerCode,u.RealName,u.UserLevel,r.Rank,m.KqSnNo,m.MerchantName,(case when SubsidyType=1 then '直营' else '团队' end) as DirectFlag,
  1754. k.Name,CreditTradeAmt,SubsidyProfit from (
  1755. select SubsidyUserId,MerchantId,BrandId,SubsidyType,
  1756. sum(CreditTradeAmt) as CreditTradeAmt,
  1757. sum(SubsidyProfitRate) as SubsidyProfit
  1758. from ProfitSubsidyDetail where TradeMonth='202208'
  1759. GROUP BY SubsidyUserId,MerchantId,BrandId,SubsidyType
  1760. ) tb
  1761. left join Users u on tb.SubsidyUserId=u.Id
  1762. LEFT JOIN KqProducts k ON k.Id=tb.BrandId
  1763. left join PosMerchantInfo m on tb.MerchantId=m.Id
  1764. left join UserRankWhite r on u.Id=r.Id and r.CreateDate<'2022-09-01 00:00:00' and r.UpdateDate>'2022-09-01 00:00:00'
  1765. // TODO:做到后台查询,换绑机器遗漏交易额补差
  1766. select UserId,sum(TradeAmount) from TradeRecord where SnNo in (
  1767. select PosSn from PosMachinesTwo where UserId=0 and BuyUserId=0 and CreditTrade>0
  1768. ) and CreateDate>='2022-04-01 00:00:00' and CreateDate<'2022-05-01 00:00:00' and UserId>0 group by UserId
  1769. */
  1770. int PageSize = 200;
  1771. int SkipNum = (PageNum - 1) * PageSize;
  1772. string LimitString = " limit " + PageSize;
  1773. if(PageNum > 1)
  1774. {
  1775. LimitString = " limit " + SkipNum + "," + PageSize;
  1776. }
  1777. function.WriteLog(DateTime.Now.ToString(), "老规则分润日志");
  1778. function.WriteLog(BankCardType.ToString(), "老规则分润日志");
  1779. function.WriteLog(BrandId.ToString(), "老规则分润日志");
  1780. List<ProfitResult> result = new List<ProfitResult>();
  1781. ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
  1782. if (obj.Status == 1) //判断分润是否开启
  1783. {
  1784. string start = Month.Substring(0, 4) + "-" + Month.Substring(4, 2) + "-01 00:00:00";
  1785. string end = DateTime.Parse(start).AddMonths(1).ToString("yyyy-MM-dd HH:mm:ss");
  1786. DataTable dt = new DataTable();
  1787. if (BankCardType == 1)
  1788. {
  1789. dt = ProfitHelperV2.Instance.GetDataTable("select SnNo,UserId,QrPayFlag,MerHelpFlag,TradeAmount,Version from TradeRecord" + Month + " where MerHelpFlag=1 and Version=0 and BrandId=" + BrandId + LimitString);
  1790. }
  1791. function.WriteLog("记录页数:" + PageNum.ToString(), "老规则分润日志");
  1792. function.WriteLog("记录条数:" + dt.Rows.Count.ToString(), "老规则分润日志");
  1793. foreach (DataRow dr in dt.Rows)
  1794. {
  1795. WebCMSEntities dbnew = new WebCMSEntities();
  1796. try
  1797. {
  1798. string SnNo = dr["SnNo"].ToString();
  1799. int UserId = int.Parse(dr["UserId"].ToString());
  1800. int HelpTime = int.Parse(dr["Version"].ToString()) == 1 ? 2 : int.Parse(dr["MerHelpFlag"].ToString());
  1801. function.WriteLog("SnNo:" + SnNo, "老规则分润日志");
  1802. function.WriteLog("UserId:" + UserId, "老规则分润日志");
  1803. function.WriteLog("HelpTime:" + HelpTime, "老规则分润日志");
  1804. MachineForSnNo forSnNo = dbnew.MachineForSnNo.FirstOrDefault(m => m.SnNo == SnNo) ?? new MachineForSnNo();
  1805. PosMachinesTwo pos = dbnew.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PosMachinesTwo();
  1806. decimal Deposit = decimal.Parse(function.CheckNum(pos.SeoKeyword));
  1807. if (pos.BindingState == 1)
  1808. {
  1809. function.WriteLog("BindingState:" + pos.BindingState, "老规则分润日志");
  1810. int QrPayFlag = int.Parse(dr["QrPayFlag"].ToString());
  1811. decimal TradeAmt = decimal.Parse(dr[4].ToString());
  1812. List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();
  1813. SubUser selfUser = ProfitHelperV2.Instance.GetUser(UserId, Month) ?? new SubUser();
  1814. int Days = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + BrandId + ":HelpPolicy:Days")); //天数
  1815. if (BankCardType == 0)
  1816. {
  1817. }
  1818. else
  1819. {
  1820. int maxLevel = obj.MaxLevel; //最大等级
  1821. decimal diffLevelProfit = 0; //等级级差
  1822. int curLevel = 0; //当前层级的会员等级
  1823. string ParentNav = selfUser.ParentNav;
  1824. if (string.IsNullOrEmpty(ParentNav) && pos.BuyUserId == 1 && pos.UserId == 1)
  1825. {
  1826. ParentNav = ",0,";
  1827. }
  1828. if (!string.IsNullOrEmpty(ParentNav))
  1829. {
  1830. ParentNav += "," + UserId + ",";
  1831. string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
  1832. Array.Reverse(ParentNavList); //反转顺序
  1833. int level = 0;
  1834. DateTime now = DateTime.Now;
  1835. DateTime ThisMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
  1836. foreach (string UserIdString in ParentNavList)
  1837. {
  1838. level += 1;
  1839. int uid = int.Parse(UserIdString);
  1840. SubUser user = ProfitHelperV2.Instance.GetUser(uid, Month) ?? new SubUser();
  1841. int UserLevel = user.PreUserLevel > user.UserLevel ? user.PreUserLevel : user.UserLevel; //当前会员等级
  1842. if (curLevel == maxLevel) //判断当前创客是否有直推的激活机具,并且在活动时间内
  1843. {
  1844. break;
  1845. }
  1846. if (UserLevel <= maxLevel && UserLevel > curLevel)
  1847. {
  1848. function.WriteLog("UserLevel:" + UserLevel, "老规则分润日志");
  1849. function.WriteLog("curLevel:" + curLevel, "老规则分润日志");
  1850. int LevelKindId = GetLevelKindId(BrandId, HelpTime, 1);
  1851. ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
  1852. if (objlevel != null)
  1853. {
  1854. decimal getLevelProfit = 0; //等级分润
  1855. if (objlevel.Percents > 0)
  1856. {
  1857. //获取创客分润规则,注册日开始算起,3个自然月内算扶持期
  1858. getLevelProfit += TradeAmt * objlevel.Percents;
  1859. }
  1860. if (objlevel.AddProfitVal > 0)
  1861. {
  1862. getLevelProfit += objlevel.AddProfitVal;
  1863. }
  1864. decimal money = getLevelProfit;
  1865. getLevelProfit -= diffLevelProfit;
  1866. if (objlevel.LevelDiff == 1) //判断是否有级差
  1867. {
  1868. diffLevelProfit = money;
  1869. }
  1870. // 分润补贴
  1871. if (HelpTime == 1 && level == 1)
  1872. {
  1873. function.WriteLog("ok", "老规则分润日志");
  1874. int SubsidyUserId = pos.BuyUserId;
  1875. SubUser subuser = ProfitHelperV2.Instance.GetUser(SubsidyUserId, Month) ?? new SubUser();
  1876. int subUserLevel = subuser.PreUserLevel > subuser.UserLevel ? subuser.PreUserLevel : subuser.UserLevel;
  1877. function.WriteLog("subUserLevel:" + subUserLevel, "老规则分润日志");
  1878. if(subUserLevel < 5)
  1879. {
  1880. function.WriteLog("sub:ok:", "老规则分润日志");
  1881. ProfitObjectLevels sublevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + subUserLevel); //获取当前等级参数
  1882. if (sublevel != null)
  1883. {
  1884. decimal otherPercent = 0.001M - sublevel.Percents;
  1885. decimal otherMoney = TradeAmt * otherPercent;
  1886. function.WriteLog("otherPercent:" + otherPercent, "老规则分润日志");
  1887. function.WriteLog("otherMoney:" + otherMoney, "老规则分润日志");
  1888. if (otherMoney >= obj.MinProfitVal)
  1889. {
  1890. function.WriteLog("finish:" + SnNo, "老规则分润日志");
  1891. result.Add(new ProfitResult()
  1892. {
  1893. UserId = subuser.Id,
  1894. UserNav = subuser.ParentNav,
  1895. Money = PublicFunction.NumberFormat(otherMoney),
  1896. ProfitRate = otherPercent,
  1897. Message = "分润补贴",
  1898. BankCardType = BankCardType,
  1899. QrPayFlag = QrPayFlag,
  1900. DirectFlag = 1,
  1901. BrandId = pos.BrandId,
  1902. IsSubsidy = 1,
  1903. MerchantId = pos.BindMerchantId,
  1904. TradeAmount = TradeAmt,
  1905. HelpFlag = HelpTime,
  1906. PosSn = pos.PosSn,
  1907. });
  1908. }
  1909. }
  1910. }
  1911. }
  1912. }
  1913. }
  1914. curLevel = UserLevel;
  1915. }
  1916. }
  1917. }
  1918. }
  1919. function.WriteLog("\n\n", "老规则分润日志");
  1920. }
  1921. catch (Exception ex)
  1922. {
  1923. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "每月统计分润异常");
  1924. }
  1925. dbnew.Dispose();
  1926. }
  1927. }
  1928. function.WriteLog(DateTime.Now.ToString(), "老规则分润日志");
  1929. function.WriteLog("\r\n\r\n", "老规则分润日志");
  1930. return result;
  1931. }
  1932. #endregion
  1933. }
  1934. }