ProfitHelper.cs 129 KB

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