ProfitHelper.cs 125 KB

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