ProfitHelper.cs 135 KB

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