ProfitHelper.cs 133 KB

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