ProfitHelper.cs 131 KB

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