ProfitHelper.cs 125 KB

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