ProfitHelper.cs 126 KB

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