ProfitHelper.cs 127 KB

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