ProfitHelper.cs 127 KB

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