ProfitHelper.cs 135 KB

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