ProfitHelper.cs 126 KB

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