ProfitHelper.cs 130 KB

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