ProfitHelper.cs 134 KB

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