ProfitHelper.cs 121 KB

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