ProfitHelper.cs 132 KB

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