ProfitHelper.cs 130 KB

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