ProfitHelper.cs 131 KB

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