1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Data;
- using MySystem.Models;
- using Library;
- using System.Threading;
- using Microsoft.Extensions.Hosting;
- using System.Threading.Tasks;
- namespace MySystem
- {
- public class ProfitHelper
- {
- public readonly static ProfitHelper Instance = new ProfitHelper();
- private ProfitHelper()
- {
- }
-
- #region 激活队列
- public void StartActive()
- {
- Thread th = new Thread(StartListenActive);
- th.IsBackground = true;
- th.Start();
- }
- public void StartListenActive()
- {
- while (true)
- {
- string content = RedisDbconn.Instance.RPop<string>("ActProfitQueue");
- if (!string.IsNullOrEmpty(content))
- {
- StartListenActiveDo(content);
- }
- else
- {
- Thread.Sleep(60000);
- }
- }
- }
- public void StartListenActiveDo(string content)
- {
- try
- {
- int MerchantId = int.Parse(content);
- KxsMainModels.WebCMSEntities kxsdb = new KxsMainModels.WebCMSEntities();
- WebCMSEntities db = new WebCMSEntities();
- bool check = db.ActiveReward.Any(m => m.MerchantId == MerchantId);
- if (!check)
- {
- decimal ActPrize = 50;
- MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
- PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMachinesTwo();
- db.ActiveReward.Add(new ActiveReward()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- UserId = merchant.UserId, //创客
- MerchantId = merchant.Id, //商户
- StandardDate = DateTime.Now, //达标日期
- RewardAmount = ActPrize, //奖励金额
- DirectBuddyNo = merchant.UserId, //商户直属创客
- KqSnNo = pos.PosSn, //渠道SN号
- SnType = pos.PosSnType, //机具类型
- SnApplyUserId = pos.BuyUserId, //机具申请创客
- SnStoreId = pos.StoreId, //SN仓库
- RewardTips = "达标奖励", //奖励描述
- Remark = "达标奖励", //备注
- ActDate = pos.ActivationTime, //激活时间
- });
- db.SaveChanges();
- string IdBrand = merchant.UserId + "_0";
- UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
- if (userData == null)
- {
- userData = db.UserMachineData.Add(new UserMachineData()
- {
- IdBrand = IdBrand,
- }).Entity;
- db.SaveChanges();
- }
- userData.ActProfit += ActPrize;
- db.SaveChanges();
- int GetUserId = merchant.UserId;
- KxsMainModels.UserAccount account = kxsdb.UserAccount.FirstOrDefault(m => m.Id == GetUserId);
- if (account == null)
- {
- account = kxsdb.UserAccount.Add(new KxsMainModels.UserAccount()
- {
- Id = GetUserId,
- UserId = GetUserId,
- }).Entity;
- kxsdb.SaveChanges();
- }
- decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
- decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
- decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
- account.BalanceAmount += ActPrize;
- account.TotalAmount += ActPrize;
- decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
- decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
- decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
- KxsMainModels.UserAccountRecord userAccountRecord = kxsdb.UserAccountRecord.Add(new KxsMainModels.UserAccountRecord()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- UserId = GetUserId, //创客
- ChangeType = 131, //变动类型
- ChangeAmount = ActPrize, //变更金额
- BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
- AfterTotalAmount = AfterTotalAmount, //变更后总金额
- BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
- AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
- BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
- AfterBalanceAmount = AfterBalanceAmount, //变更后余额
- }).Entity;
- kxsdb.SaveChanges();
- }
- kxsdb.Dispose();
- db.Dispose();
- }
- catch (Exception ex)
- {
- LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "激活奖励服务异常");
- }
- }
- #endregion
- #region 消费队列(执行消费退款金额的统计)
- public void StartListenTrade()
- {
- Thread th = new Thread(StartListenTradeDo);
- th.IsBackground = true;
- th.Start();
- }
- public void StartListenTradeDo()
- {
- while (true)
- {
- string orderidstring = RedisDbconn.Instance.RPop<string>("ConsumerOrders:Divi:1:List");
- if (!string.IsNullOrEmpty(orderidstring))
- {
- ReturnStat(orderidstring, 1);
- }
- else
- {
- Thread.Sleep(60000);
- }
- }
- }
- public void StartListenWxTrade()
- {
- Thread th = new Thread(StartListenWxTradeDo);
- th.IsBackground = true;
- th.Start();
- }
- public void StartListenWxTradeDo()
- {
- while (true)
- {
- string orderidstring = RedisDbconn.Instance.RPop<string>("ConsumerOrders:Divi:2:List");
- if (!string.IsNullOrEmpty(orderidstring))
- {
- ReturnStat(orderidstring, 2);
- }
- else
- {
- Thread.Sleep(10000);
- }
- }
- }
- public void ReturnStat(string orderidstring, int PayMode)
- {
- int OrderId = int.Parse(function.CheckInt(orderidstring));
- WebCMSEntities db = new WebCMSEntities();
- using (var tran = db.Database.BeginTransaction())
- {
- try
- {
- ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == OrderId);
- if (order != null)
- {
- decimal PayMoney = order.PayMoney;
- int MerchantId = order.MerchantId;
- MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
- if (merchant != null)
- {
- int UserId = merchant.UserId;
- List<CustomTagSet> customTagSets = db.CustomTagSet.ToList(); //获取公用配置参数集和
- //获取参数
- CustomTagSet profitPercentSet = customTagSets.FirstOrDefault(m => m.Tags == "CusumerProfitPercent") ?? new CustomTagSet();
- decimal profitPercent = decimal.Parse(function.CheckNum(profitPercentSet.Contents)); //基于收款金额的总分润比例;
- CustomTagSet cusumerFeePercentSet = customTagSets.FirstOrDefault(m => m.Tags == "CusumerFeePercent") ?? new CustomTagSet();
- decimal cusumerFeePercent = decimal.Parse(function.CheckNum(cusumerFeePercentSet.Contents)); //费率;
- CustomTagSet minProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "MinProfit") ?? new CustomTagSet();
- decimal minProfit = decimal.Parse(function.CheckNum(minProfitSet.Contents)); //最小分润值;
- MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
- int DiviPersons = set.DiviPersons; //单笔订单分红人数
- decimal DiviPercent = set.DiviPercent; //单人最大分红比例
- int ProfitDays = set.ProfitDays; //分红期限(天)
- decimal GetPercent = set.GetPercent / 100; //商家实收比例
- decimal MinPayMoney = set.MinPayMoney; //订单参与门槛
- int IsAll = set.IsAll; //是否收全额
- // decimal TotalActual = 0;
- if (IsAll == 0 && PayMoney >= MinPayMoney && GetPercent < 1)
- {
- decimal DiviMoney = PayMoney * (1 - GetPercent - cusumerFeePercent - profitPercent);
- if (DiviMoney > 0)
- {
- RedisDbconn.Instance.AddRightList("ConsumerOrders:Divi:" + PayMode + ":" + order.MerchantId, order);
- DiviMoney = DiviMoney / DiviPersons;
- List<int> deletes = new List<int>();
- long CurDiviPersons = DiviPersons;
- long QueueCount = RedisDbconn.Instance.Count("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId);
- long CurQueueCount = QueueCount;
- // int CheckNum = 0; //判断活动人数是否大于当前队列订单数来确认while循环的数量,如果是就少循环一次,判处自己的订单名额
- if (CurDiviPersons >= CurQueueCount)
- {
- CurDiviPersons = CurQueueCount;
- }
- if (DiviPersons < QueueCount)
- {
- QueueCount = DiviPersons;
- }
- decimal OtherMoney = 0; // 退款金额>最大退款金额-当前退款金额,次金额应归还给商户
- // List<ConsumerOrders> orders = RedisDbconn.Instance.GetList<ConsumerOrders>("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId);
- // foreach(ConsumerOrders sub in orders)
- // {
- // LogHelper.Instance.WriteLog(sub.Id.ToString(), "返现队列");
- // }
- // LogHelper.Instance.WriteLog("\n\n", "返现队列");
- // 减去自己付的订单
- // CurDiviPersons = CurDiviPersons - 1;
- int OutCount = 0; // 出局人数
- List<int> orderids = new List<int>();
- while (CurDiviPersons > 0)
- {
- ConsumerOrders suborder = RedisDbconn.Instance.RPop<ConsumerOrders>("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId);
- if (suborder != null)
- {
- MerchantParamSet subset = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
- int subProfitDays = subset.ProfitDays; //分红期限(天)
- bool IsOut = suborder.UpdateDate.Value.AddDays(subProfitDays) < DateTime.Now ? true : false;
- if (suborder.CurDivi < suborder.MaxDivi && !IsOut)
- {
- //如果没过期并且当前退款金额没超过最大退款金额,就执行
- decimal GetMoney = suborder.MaxDivi - suborder.CurDivi;
- decimal DiffMoney = 0;
- if (GetMoney >= DiviMoney)
- {
- GetMoney = DiviMoney;
- }
- else
- {
- DiffMoney = DiviMoney - GetMoney;
- }
- if (GetMoney > minProfit)
- {
- suborder.CurDivi += GetMoney;
- if (DiffMoney > 0)
- {
- OtherMoney += DiffMoney;
- }
- ConsumerProfit cprofit = db.ConsumerProfit.Add(new ConsumerProfit()
- {
- CreateDate = DateTime.Now,
- ConsumerId = suborder.ConsumerId,
- MerchantId = suborder.MerchantId,
- OrderId = suborder.Id,
- GetMoney = Math.Round(GetMoney, 2),
- QueryCount = PayMode,
- Sort = OrderId,
- SeoTitle = suborder.OrderNo,
- SeoKeyword = suborder.PayMoney.ToString(),
- }).Entity;
- db.SaveChanges();
- MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == suborder.MerchantId) ?? new MerchantAddInfo();
- if(!orderids.Contains(suborder.Id))
- {
- if(order.PayMode == 1)
- {
- AlipayFunction.Instance.Refund(suborder.SeoTitle, Math.Round(GetMoney, 2).ToString(), "门店消费补贴", merchantAdd.AlipayAuthToken);
- }
- else
- {
- Dictionary<string, string> dic = WeChatFunction.Instance.Refund(merchantAdd.SubMchid, Math.Round(GetMoney, 2), suborder.PayMoney, suborder.OrderNo, DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8), "门店消费补贴");
- }
- orderids.Add(suborder.Id);
- }
- merchant.ActCurrentAmount += Math.Round(GetMoney, 2); //活动已返金额
- db.SaveChanges();
- if (suborder.CurDivi < suborder.MaxDivi)
- {
- RedisDbconn.Instance.AddList("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId, suborder);
- }
- else
- {
- OutCount += 1;
- }
- }
- }
- else
- {
- //否者计算人数不计入退款名额
- CurDiviPersons += 1;
- }
- }
- CurDiviPersons -= 1;
- QueueCount = RedisDbconn.Instance.Count("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId);
- if (QueueCount == 0)
- {
- CurDiviPersons = 0;
- }
- }
- // long DoCount = DiviPersons > (QueueCount + OutCount) ? DiviPersons - QueueCount : 0;
- // decimal MerchantGetMoney = PayMoney * GetPercent;
- // decimal DoMoney = DoCount * DiviMoney;
- // TotalActual = PayMoney * GetPercent + DoCount * DiviMoney + OtherMoney;
- // LogHelper.Instance.WriteLog("返现金额:" + DiviMoney + ";返现人数:" + DiviPersons + ";返现商户:" + TotalActual + ";返现溢出:" + OtherMoney + ";商户应得金额:" + MerchantGetMoney + ";返现差额:" + DoMoney + ";", "消费者返现日志");
- //代理商分润
- // AgentProfit(db, order);
- }
- }
- }
- }
- tran.Commit();
- }
- catch (Exception ex)
- {
- LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "自定义分润程序监听队列异常");
- tran.Rollback();
- }
- }
- db.Dispose();
- }
- public void StartListenProfit()
- {
- Thread th = new Thread(StartListenProfitDo);
- th.IsBackground = true;
- th.Start();
- }
- public void StartListenProfitDo()
- {
- while(true)
- {
- if(DateTime.Now.Day < 10 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 5)
- {
- DoProfit();
- Thread.Sleep(600000);
- }
- else
- {
- Thread.Sleep(3600000);
- }
- }
- }
- //分润算法
- public void DoProfit()
- {
- string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
- string check = function.ReadInstance("/ProfitFlag/" + TradeMonth + ".txt");
- if(!string.IsNullOrEmpty(check))
- {
- return;
- }
- function.WritePage("/ProfitFlag/", TradeMonth + ".txt", DateTime.Now.ToString());
- KxsMainModels.WebCMSEntities kxsdb = new KxsMainModels.WebCMSEntities();
- WebCMSEntities dbnew = new WebCMSEntities();
- DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount) from UserAmountSummary where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId", MysqlConn.SqlConnStr);
- foreach(DataRow dr in dt.Rows)
- {
- int UserId = int.Parse(dr["UserId"].ToString());
- bool IsActive = dr["IsAct"].ToString() == "1";
- decimal TotalAmount = decimal.Parse(dr[2].ToString());
- List<ProfitUsers> users = new List<ProfitUsers>();
- int TopUserId = 0; //顶级创客Id
- KxsMainModels.Users us = kxsdb.Users.FirstOrDefault(a => a.Id == UserId);
- if (us != null)
- {
- string uidstring = us.Id.ToString();
- if (!string.IsNullOrEmpty(us.ParentNav))
- {
- uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
- string[] parents = us.ParentNav.Trim(',').Replace(",,", ",").Split(',');
- if(parents.Length > 1)
- {
- TopUserId = int.Parse(function.CheckInt(parents[1]));
- }
- else
- {
- TopUserId = int.Parse(function.CheckInt(parents[0]));
- }
- }
- string[] uidlist = uidstring.Split(',');
- Array.Reverse(uidlist);
- foreach (string uidstr in uidlist)
- {
- int puid = int.Parse(function.CheckInt(uidstr));
- KxsMainModels.Users pus = kxsdb.Users.FirstOrDefault(a => a.Id == puid);
- if (pus != null)
- {
- users.Add(new ProfitUsers()
- {
- UserId = pus.Id,
- MakerCode = pus.MakerCode,
- RealName = pus.RealName,
- UserNav = pus.ParentNav,
- UserLevel = pus.UserLevel,
- CreateDate = pus.CreateDate.Value,
- });
- }
- }
- }
- KxsMainModels.Users topUser = kxsdb.Users.FirstOrDefault(a => a.Id == TopUserId) ?? new KxsMainModels.Users();
- List<ProfitResult> list = new List<ProfitResult>();
- list = StartProft(TotalAmount, 1, users, IsActive);
- try
- {
- foreach (ProfitResult sub in list)
- {
- int ProfitType = sub.UserId == UserId ? 0 : 1;
- ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth);
- if (editprofitrecord == null)
- {
- editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
- {
- CreateDate = DateTime.Now,
- UserId = sub.UserId, //创客
- BrandId = 1, //品牌
- ProfitType = ProfitType, //创客分润类型
- TradeMonth = TradeMonth, //交易月
- TopUserId = TopUserId, //顶级创客
- CreateMan = sub.MakerCode, //创客编号
- UpdateMan = topUser.MakerCode, //顶级编号
- SeoTitle = sub.RealName, //创客姓名
- SeoKeyword = topUser.RealName, //创客姓名
- }).Entity;
- dbnew.SaveChanges();
- string RecordNo = "KPM";
- int RecordId = editprofitrecord.Id;
- string RecordIdString = RecordId.ToString();
- for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
- {
- RecordIdString = "0" + RecordIdString;
- }
- RecordNo += RecordIdString;
- editprofitrecord.RecordNo = RecordNo;
- dbnew.SaveChanges();
- }
- if(IsActive)
- {
- editprofitrecord.CreditTradeAmt += TotalAmount;
- editprofitrecord.CreditTradeProfit += sub.Money;
- }
- else
- {
- editprofitrecord.TradeAmt += TotalAmount;
- editprofitrecord.TradeProfit += sub.Money;
- }
- dbnew.SaveChanges();
- }
- dbnew.SaveChanges();
- }
- catch (Exception ex)
- {
- LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
- }
- }
- dbnew.Dispose();
- kxsdb.Dispose();
- }
- public void DoActives(WebCMSEntities dbnew, TradeRecord trade_record)
- {
- if (RedisDbconn.Instance.CheckKey("pobjact" + trade_record.Sort))
- {
- List<ProfitObjectsActives> objactives = RedisDbconn.Instance.GetList<ProfitObjectsActives>("pobjact" + trade_record.Sort);
- if (objactives.Count > 0)
- {
- string OtherCondition = " and Type=1";
- if (trade_record.Sort == 1) OtherCondition = " and Type<>1";
- else if (trade_record.Sort == 2) OtherCondition = " and Type<>1";
- else if (trade_record.Sort == 4) OtherCondition = " and Type=2";
- else if (trade_record.Sort == 11) OtherCondition = " and Type=2";
- else if (trade_record.Sort == 14) OtherCondition = " and (Type=1 or Type=3)";
- else if (trade_record.Sort == 6 || trade_record.Sort == 7 || trade_record.Sort == 18) OtherCondition = "";
- else if (trade_record.Sort == 29) OtherCondition = " and Type=2";
- PosMachinesTwo machine = dbnew.PosMachinesTwo.FirstOrDefault(m => m.PosSn == trade_record.SnNo) ?? new PosMachinesTwo();
- if (machine.ActivationState == 0)
- {
- return;
- }
- if (machine.BrandId == 0)
- {
- return;
- }
- Users user = dbnew.Users.FirstOrDefault(m => m.Id == machine.UserId) ?? new Users();
- Users buyuser = dbnew.Users.FirstOrDefault(m => m.Id == machine.BuyUserId) ?? new Users();
- Dictionary<string, ProfitUsers> Users = new Dictionary<string, ProfitUsers>();
- Users.Add("UserId", new ProfitUsers()
- {
- UserId = user.Id,
- UserNav = user.ParentNav,
- UserLevel = user.UserLevel,
- });
- Users.Add("BuyUserId", new ProfitUsers()
- {
- UserId = buyuser.Id,
- UserNav = buyuser.ParentNav,
- UserLevel = buyuser.UserLevel,
- });
- List<ProfitResult> list = StartActiveProft(dbnew, machine, trade_record.SnNo, trade_record.Sort, Users, new ActiveCheckData()
- {
- TableName = "TransactionRecord",
- StatField = "Money",
- CheckField = "pos_sn",
- OtherCondition = OtherCondition,
- });
- foreach (ProfitResult sub in list)
- {
- // dbnew.MybillTable.Add(new MybillTable()
- // {
- // Content = sub.Message,
- // Money = sub.Money,
- // Type = 1,
- // UserId = sub.UserId,
- // UserNav = sub.UserNav,
- // Kind = 2,
- // CreateDate = DateTime.Now,
- // SeoTitle = trade_record.SeoTitle,
- // SeoKeyword = trade_record.SnNo,
- // Sort = trade_record.Sort,
- // Status = -3,
- // });
- }
- dbnew.SaveChanges();
- }
- }
- }
- //代理商分润算法
- public void AgentProfit(WebCMSEntities db, ConsumerOrders order)
- {
- int MerchantId = order.MerchantId;
- decimal PayMoney = order.PayMoney;
- MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
- if (merchant != null)
- {
- List<CustomTagSet> customTagSets = RedisDbconn.Instance.GetList<CustomTagSet>("CustomTagSet", 1, 1000); //获取公用配置参数集和 // TODO: 后台配置
- //获取代理商参数
- CustomTagSet profitPercentSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentProfitPercent") ?? new CustomTagSet();
- decimal profitPercent = decimal.Parse(function.CheckNum(profitPercentSet.Contents)); //基于收款金额的总分润比例;
- CustomTagSet makerProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentMakerProfit") ?? new CustomTagSet();
- decimal makerProfit = decimal.Parse(function.CheckNum(makerProfitSet.Contents)); //创客分润比例;
- CustomTagSet directProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentDirectProfit") ?? new CustomTagSet();
- decimal directProfit = decimal.Parse(function.CheckNum(directProfitSet.Contents)); //直推分润比例;
- CustomTagSet minProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "MinProfit") ?? new CustomTagSet();
- decimal minProfit = decimal.Parse(function.CheckNum(minProfitSet.Contents)); //最小分润值;
- string MerAreas = merchant.Areas;
- MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
- decimal ProfitMoney = PayMoney * (1 - set.DiviPercent) * profitPercent;
- Users user = db.Users.FirstOrDefault(m => m.Id == merchant.UserId);
- if (user != null)
- {
- decimal ProfitAmount = ProfitMoney * makerProfit;
- if (ProfitAmount >= minProfit)
- {
- db.ProfitRecord.Add(new ProfitRecord()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- Remark = "分润奖励",
- UserId = user.Id, //创客
- MerchantId = MerchantId, //商户
- SnNo = order.SnNo, //SN号
- TradeDate = order.CreateDate, //交易日期
- ProfitAmount = ProfitAmount, //分润金额
- BrandId = 1, //品牌
- ParentNav = user.ParentNav, //上级创客集
- TradeId = order.Id, //交易记录Id
- });
- db.SaveChanges();
- }
- }
- Users puser = db.Users.FirstOrDefault(m => m.Id == user.ParentUserId);
- if (puser != null)
- {
- decimal ProfitAmount = ProfitMoney * directProfit;
- if (ProfitAmount >= minProfit)
- {
- db.ProfitRecord.Add(new ProfitRecord()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- Remark = "分润奖励",
- UserId = puser.Id, //创客
- MerchantId = MerchantId, //商户
- SnNo = order.SnNo, //SN号
- TradeDate = order.CreateDate, //交易日期
- ProfitAmount = ProfitAmount, //分润金额
- BrandId = 1, //品牌
- ParentNav = puser.ParentNav, //上级创客集
- TradeId = order.Id, //交易记录Id
- });
- db.SaveChanges();
- }
- }
- string[] areaList = MerAreas.Split(',');
- decimal GetMoneyFlag = 0;
- for (int i = 0; i < areaList.Length; i++)
- {
- string CurAreas = "";
- for (int j = 0; j < areaList.Length - i; j++)
- {
- CurAreas += areaList[j] + ",";
- }
- CurAreas = CurAreas.TrimEnd(',');
- int AgentLevel = CurAreas.Split(',').Length;
- Users areaUser = db.Users.FirstOrDefault(m => m.AgentAreas == CurAreas && m.AgentLevel > AgentLevel);
- if (areaUser != null)
- {
- AgentLevelSet agentset = db.AgentLevelSet.FirstOrDefault(m => m.Id == AgentLevel) ?? new AgentLevelSet();
- decimal ProfitAmount = ProfitMoney * agentset.ProfitPercent;
- if (agentset.LevelDiff == 1)
- {
- ProfitAmount -= GetMoneyFlag;
- }
- if (ProfitAmount >= minProfit)
- {
- db.ProfitRecord.Add(new ProfitRecord()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- Remark = "分润奖励",
- UserId = puser.Id, //创客
- MerchantId = MerchantId, //商户
- SnNo = order.SnNo, //SN号
- TradeDate = order.CreateDate, //交易日期
- ProfitAmount = ProfitAmount, //分润金额
- BrandId = 1, //品牌
- ParentNav = puser.ParentNav, //上级创客集
- TradeId = order.Id, //交易记录Id
- });
- db.SaveChanges();
- GetMoneyFlag = ProfitAmount;
- }
- ProfitAmount = ProfitMoney * agentset.AreasProfitPercent;
- if (ProfitAmount >= minProfit)
- {
- db.ProfitRecord.Add(new ProfitRecord()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- Remark = "分润奖励",
- UserId = puser.Id, //创客
- MerchantId = MerchantId, //商户
- SnNo = order.SnNo, //SN号
- TradeDate = order.CreateDate, //交易日期
- ProfitAmount = ProfitAmount, //分润金额
- BrandId = 1, //品牌
- ParentNav = puser.ParentNav, //上级创客集
- TradeId = order.Id, //交易记录Id
- });
- db.SaveChanges();
- }
- }
- }
- }
- }
- // 收款金额:100
- // 单笔退款金额 = (收款金额*返现比例 - 已返现金额) > (收款金额 - 收款金额*商家实收比例 - 收款金额*(1 - 商家实收比例)*10% - 手续费(收款金额*0.38%) ) / 返现人数 ? (收款金额 - 收款金额*商家实收比例 - 收款金额*(1 - 商家实收比例)*10% - 手续费(收款金额*0.38%)) / 返现人数 : (收款金额*返现比例 - 已返现金额)
- // 分账金额: 收款金额*(1 - 商家实收比例)*10%
- // 代理分润金额: 省:75% 市:65% 区县:55% 创客:30% 直推创客:5%
- // 区域保护分润金额:省:5% 市:5% 区县:5%
- // QE:
- /*
- 条件1(跨区域开发商家):
- A为四川省成都市金牛区代理,B为金牛区创客,C为B推荐的金牛区创客,D为四川省成都市代理,E为四川省代理,F为广东省深圳市南山区代理,G为广东省深圳市代理,H为广东省代理。
- C推荐一个广东省深圳市南山区商家,交易金额1000元。
- 则:
- C可得分润 = 分账金额 * 30%
- B可得直推分润 = 分账金额 * 5%
- A可得分润 = 分账金额 * (55% - 30%)
- G可得分润 = 分账金额 * (65% - 55%)
- H可得分润 = 分账金额 * (75% - 65%)
- F、G、H可再得区域保护分润 = 分账金额 * 5%
-
- 条件2(同区域):
- A为四川省成都市金牛区代理,B为金牛区创客,C为B推荐的金牛区创客,D为四川省成都市代理,E为四川省代理
- C推荐一个四川省成都市金牛区商家,交易金额1000元。
- 则:
- C可得分润 = 分账金额 * 30%
- B可得直推分润 = 分账金额 * 5%
- A可得分润 = 分账金额 * (55% - 30%)
- D可得分润 = 分账金额 * (65% - 55%)
- E可得分润 = 分账金额 * (75% - 65%)
- A、D、E可再得区域保护分润 = 分账金额 * 5%
- 条件3(代理断级):
- B为金牛区创客,C为B推荐的金牛区创客,D为四川省成都市代理,E为四川省代理,F为广东省深圳市南山区代理,G为广东省深圳市代理,H为广东省代理。
- C推荐一个广东省深圳市南山区商家,交易金额1000元。
- 则:
- C可得分润 = 分账金额 * 30%
- B可得直推分润 = 分账金额 * 5%
- D可得分润 = 分账金额 * (65% - 30%)
- H可得分润 = 分账金额 * (75% - 65%)
- F、G、H可再得区域保护分润 = 分账金额 * 5%
- */
- #endregion
- #region 商户队列
- public void StartListenMerchantDo(Dictionary<string, string> data, bool bind = false)
- {
-
- }
- #endregion
- #region 绑定队列
- public void StartListenBindDo(Dictionary<string, string> data)
- {
- }
- #endregion
- #region 分润算法
- public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, bool IsActive = true)
- {
- LogHelper.Instance.WriteLog("\n\nTotalAmount:" + TotalAmount + ";", "来客吧分润日志");
- string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
- WebCMSEntities db = new WebCMSEntities();
- List<UserLevelSet> levels = db.UserLevelSet.ToList();
- List<ProfitResult> result = new List<ProfitResult>();
- ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
- if (obj.Status == 1) //判断分润是否开启
- {
- int maxLevel = obj.MaxLevel; //最大等级
- int maxFloor = obj.MaxFloor; //最大层级
- decimal diffLevelProfit = 0; //等级级差
- ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == 9) ?? new ProfitObjectLevels(); //获取最高等级参数
- decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
- LogHelper.Instance.WriteLog("maxPercent:" + maxPercent + ";", "来客吧分润日志");
- decimal maxLevelProfit = TotalAmount * maxPercent;
- LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
- maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
- LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
- // decimal diffDiviProfit = 0; //分红级差
- int curLevel = 0; //当前层级的会员等级
- for (int curFloor = 1; curFloor <= users.Count; curFloor++)
- {
- ProfitUsers user = new ProfitUsers();
- if (curFloor <= users.Count)
- {
- user = users[curFloor - 1];
- }
- SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
- int UserLevel = selfUser.PreUserLevel > selfUser.UserLevel ? selfUser.PreUserLevel : selfUser.UserLevel; //当前会员等级
- //判断当前创客是否有直推的激活机具,并且在活动时间内
- if (curLevel == maxLevel)
- {
- break;
- }
- if (UserLevel <= maxLevel && UserLevel >= curLevel)
- {
- ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel); //获取当前等级参数
- if (objlevel != null)
- {
- decimal getLevelProfit = 0; //等级分润
- UserProfitSet profitSet = new UserProfitSet();
- decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
- LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitPercent + ";", "来客吧分润日志");
- if (profitPercent > 0)
- {
- decimal profitTmp = TotalAmount * profitPercent;
- getLevelProfit += profitTmp;
- LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitTmp + ";", "来客吧分润日志");
- }
- decimal money = getLevelProfit;
- getLevelProfit -= diffLevelProfit;
- if (objlevel.LevelDiff == 1) //判断是否有级差
- {
- diffLevelProfit = money;
- }
- if (getLevelProfit >= obj.MinProfitVal)
- {
- result.Add(new ProfitResult()
- {
- UserId = user.UserId,
- MakerCode = user.MakerCode,
- RealName = user.RealName,
- UserNav = user.UserNav,
- Money = PublicFunction.NumberFormat(getLevelProfit),
- ProfitRate = profitSet.ProfitRate,
- ProfitPercent = profitSet.ProfitPercent,
- AddOrSubRate = profitSet.AddOrSubRate,
- ProfitRateBase = profitSet.ProfitRateBase,
- });
- LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + PublicFunction.NumberFormat(getLevelProfit) + ";", "来客吧分润日志");
- }
- }
- }
- if(curLevel < UserLevel)
- {
- curLevel = UserLevel;
- }
- }
- }
- db.Dispose();
- return result;
- }
- public SubUser GetUser(int UserId, string Month)
- {
- SubUser user = new SubUser();
- DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
- if(dt.Rows.Count > 0)
- {
- user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
- user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
- user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
- user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
- user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
- }
- return user;
- }
- public DataTable GetDataTable(string sqlstr)
- {
- DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
- return dt;
- }
- #endregion
- #region 活动奖励算法
- public List<ProfitResult> StartActiveProft(WebCMSEntities dbnew, PosMachinesTwo machine, string CheckObject, int ObjectId, Dictionary<string, ProfitUsers> Users, ActiveCheckData StatParam)
- {
- DateTime Start = machine.ActivationTime.Value;
- List<ProfitResult> result = new List<ProfitResult>();
- ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + ObjectId);
- if (obj.Status == 1) //判断分润是否开启
- {
- List<ProfitObjectsActives> objactives = RedisDbconn.Instance.GetList<ProfitObjectsActives>("pobjact" + ObjectId);
- foreach (ProfitObjectsActives objactive in objactives)
- {
- if (objactive.StartDate <= DateTime.Now && objactive.EndDate >= DateTime.Now)
- {
- string UserKey = "UserId";
- decimal ProfitMoney = objactive.ProfitNumber; //获得数
- decimal FinishNumber = objactive.FinishNumber; //完成数
- string CheckKey = CheckObject + "-" + objactive.Id;
- ProfitObjectsActiveCheck check = dbnew.ProfitObjectsActiveCheck.FirstOrDefault(m => m.CheckData == CheckKey);
- if (ProfitMoney > 0 && check == null)
- {
- int LimitDateKind = objactive.LimitDateKind; //时间限制类型 日月年/自定义
- if (LimitDateKind == 4)
- {
- DateTime LimitCustomerDate = objactive.LimitCustomerDate.Value; //过期时间
- if (LimitCustomerDate >= DateTime.Now)
- {
- decimal totalTradeMoney = 0;
- OtherMySqlConn.connstr = ConfigurationManager.AppSettings["OldSqlConnStr"].ToString();
- 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") + "'";
- DataTable dt = OtherMySqlConn.dtable(sqlstr);
- if (dt.Rows.Count > 0)
- {
- totalTradeMoney = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
- }
- // OtherMySqlConn.connstr = ;
- if (totalTradeMoney >= FinishNumber && ProfitMoney >= obj.MinProfitVal) //达到完成数,发放奖励
- {
- result.Add(new ProfitResult()
- {
- UserId = Users[UserKey].UserId,
- UserNav = Users[UserKey].UserNav,
- Money = ProfitMoney,
- });
- dbnew.ProfitObjectsActiveCheck.Add(new ProfitObjectsActiveCheck()
- {
- CheckData = CheckKey
- });
- dbnew.SaveChanges();
- }
- }
- }
- else
- {
- int LimitDateVal = objactive.LimitDateVal; //时间限制值 日月年
- DateTime checkDate = Start;
- if (LimitDateKind == 1)
- {
- checkDate = checkDate.AddDays(LimitDateVal);
- }
- else if (LimitDateKind == 2)
- {
- checkDate = checkDate.AddMonths(LimitDateVal);
- }
- else if (LimitDateKind == 3)
- {
- checkDate = checkDate.AddYears(LimitDateVal);
- }
- if (checkDate >= DateTime.Now)
- {
- decimal totalTradeMoney = 0;
- OtherMySqlConn.connstr = ConfigurationManager.AppSettings["OldSqlConnStr"].ToString();
- 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") + "'";
- DataTable dt = OtherMySqlConn.dtable(sql);
- if (dt.Rows.Count > 0)
- {
- totalTradeMoney = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
- }
- // OtherMySqlConn.connstr = ;
- if (totalTradeMoney >= FinishNumber && ProfitMoney >= obj.MinProfitVal) //达到完成数,发放奖励
- {
- result.Add(new ProfitResult()
- {
- UserId = Users[UserKey].UserId,
- UserNav = Users[UserKey].UserNav,
- Money = ProfitMoney,
- });
- dbnew.ProfitObjectsActiveCheck.Add(new ProfitObjectsActiveCheck()
- {
- CheckData = CheckKey
- });
- dbnew.SaveChanges();
- }
- }
- }
- }
- }
- }
- }
- return result;
- }
- #endregion
- #region 激活奖励算法
- public ProfitResult ActivationProft(PosMachinesTwo machine, ProfitUsers User)
- {
- int BrandId = machine.BrandId;
- DateTime Start = machine.ActivationTime.Value;
- ProfitResult result = new ProfitResult();
- if (machine.PosSnType == 1 && machine.UserId != machine.BuyUserId) //循环机具,划拨给其他人,没有激活返现没有循环
- {
- return result;
- }
- ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
- if (obj.Status == 1) //判断分润是否开启
- {
- ProfitObjectActivations objact = RedisDbconn.Instance.Get<ProfitObjectActivations>("pobjacti" + BrandId);
- if (objact.StartDate <= DateTime.Now && objact.EndDate >= DateTime.Now)
- {
- int LimitDateKind = objact.LimitDateKind; //时间限制类型 日月年/自定义
- int LimitDateVal = objact.LimitDateVal; //时间限制值 日月年
- decimal ProfitMoney = objact.ProfitNumber;
- int MachineCount = objact.MachineCount;
- DateTime checkDate = Start;
- if (LimitDateKind == 1)
- {
- checkDate = checkDate.AddDays(LimitDateVal);
- }
- else if (LimitDateKind == 2)
- {
- checkDate = checkDate.AddMonths(LimitDateVal);
- }
- else if (LimitDateKind == 3)
- {
- checkDate = checkDate.AddYears(LimitDateVal);
- }
- else if (LimitDateKind == 4)
- {
- checkDate = objact.LimitCustomerDate.Value;
- }
- // if (DateTime.Now > checkDate && ProfitMoney > objact.ExpiredNumber)
- // {
- // ProfitMoney = objact.ExpiredNumber;
- // }
- if (ProfitMoney >= obj.MinProfitVal)
- {
- result = new ProfitResult()
- {
- UserId = User.UserId,
- UserNav = User.UserNav,
- Money = ProfitMoney,
- MachineCount = MachineCount,
- };
- }
- }
- }
- return result;
- }
- #endregion
- #region 获取分润规则Id
- private int GetLevelKindId(int BrandId, int Help, int BankCardType)
- {
- return RedisDbconn.Instance.Get<int>("pobjlv:kid:" + BrandId + ":" + Help + ":" + BankCardType);
- }
- #endregion
- #region POS统计交易额
- public void StartListenTradeDo(int tradeId, bool profit = true)
- {
- try
- {
- WebCMSEntities dbnew = new WebCMSEntities();
- TradeRecord trade_record = dbnew.TradeRecord.FirstOrDefault(m => m.Id == tradeId);
- if (trade_record != null)
- {
- int BrandId = trade_record.BrandId;
- decimal TradeAmt = trade_record.TradeAmount;
- int BankCardTypeNum = trade_record.BankCardType; //1-贷记卡,0-借记卡,2-准贷记卡
- DateTime TradeDateTime = trade_record.CreateDate.Value;
- string monthString = TradeDateTime.ToString("yyyyMM");
- string dayString = TradeDateTime.ToString("yyyyMMdd");
- string NaturalMonthString = RedisDbconn.Instance.Get<string>("pobjrule:" + BrandId + ":HelpPolicy:NaturalMonth");
- int NaturalMonth = int.Parse(NaturalMonthString); //自然月
- MachineForSnNo machinefor = dbnew.MachineForSnNo.FirstOrDefault(m => m.SnNo == trade_record.SnNo) ?? new MachineForSnNo();
- PosMachinesTwo machine = dbnew.PosMachinesTwo.FirstOrDefault(m => m.Id == machinefor.SnId) ?? new PosMachinesTwo();
- Users user = dbnew.Users.FirstOrDefault(m => m.Id == machine.UserId) ?? new Users();
- int TopUserId = 0;
- if (!string.IsNullOrEmpty(user.ParentNav))
- {
- string[] navList = user.ParentNav.Trim(',').Replace(",,", ",").Split(',');
- if (navList.Length > 1)
- {
- TopUserId = int.Parse(navList[1]);
- }
- else
- {
- TopUserId = int.Parse(navList[0]);
- }
- }
- PosMerchantInfo merchant = dbnew.PosMerchantInfo.FirstOrDefault(m => m.Id == machine.BindMerchantId) ?? new PosMerchantInfo();
- List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();
- using (var tran = dbnew.Database.BeginTransaction())
- {
- try
- {
- ulong DirectFlag = merchant.UserId == machine.UserId ? 1u : 0u; //是否直营
- ulong MerHelpFlag = 1; //扶持期、稳定期
- if (merchant.CreateDate.Value < DateTime.Now.AddMonths(-NaturalMonth))
- {
- MerHelpFlag = 0;
- }
- int HelpMonthCount = DateTime.Now.Month - merchant.CreateDate.Value.Month; //扶持期第几月
- if (HelpMonthCount < 0)
- {
- HelpMonthCount = 12 + DateTime.Now.Month - merchant.CreateDate.Value.Month;
- }
- int QrPayFlag = trade_record.QrPayFlag;
- decimal CreditTradeAmt = 0;
- decimal DebitNotCapTradeAmt = 0;
- decimal DebitCapTradeAmt = 0;
- int DebitCapTradeNum = 0;
- if (BankCardTypeNum == 1)
- {
- CreditTradeAmt = TradeAmt;
- }
- else if (BankCardTypeNum == 0)
- {
- //累计借记卡封顶或非封顶交易 // TODO:需优化,判断不太科学
- // decimal profitrate = 0;
- // if (user.CreateDate.Value.AddMonths(NaturalMonth) >= DateTime.Now)
- // {
- // UserProfitSet profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardTypeNum && m.HelpFlag == 1) ?? new UserProfitSet(); //获取创客分润规则-扶持期
- // profitrate = profitSet.ProfitRate;
- // }
- // else
- // {
- // UserProfitSet profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardTypeNum && m.HelpFlag == 0) ?? new UserProfitSet(); //获取创客分润规则-非扶持期
- // profitrate = profitSet.ProfitRate;
- // }
- // profitrate = profitrate / 100;
- // int UserLevel = user.UserLevel; //当前会员等级
- // decimal utrade = RedisDbconn.Instance.Get<decimal>("TeamTradeStat:" + user.Id + ":" + BrandId + ":" + DateTime.Now.ToString("yyMM"));
- // UserLevelSet checklevel = levels.Where(m => m.UpLevelIntegral < utrade).OrderBy(m => m.Id).FirstOrDefault();
- // if (checklevel != null)
- // {
- // UserLevel = checklevel.Id + 1;
- // }
- // ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + GetLevelKindId(BrandId) + ":" + UserLevel); //获取当前等级参数
- // decimal getLevelProfit = TradeAmt * objlevel.Percents * profitrate;
- // if (getLevelProfit < 1)
- // {
- // DebitNotCapTradeAmt = TradeAmt;
- // }
- // else
- // {
- // DebitCapTradeAmt = TradeAmt;
- // DebitCapTradeNum = 1;
- // trade_record.CapFlag = 1;
- // dbnew.SaveChanges();
- // }
- DebitNotCapTradeAmt = TradeAmt;
- }
- UserTradeMonthSummary editsummary = dbnew.UserTradeMonthSummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeMonth == monthString && m.BrandId == BrandId && m.StatType == 0);
- if (editsummary == null)
- {
- dbnew.UserTradeMonthSummary.Add(new UserTradeMonthSummary()
- {
- CreateDate = DateTime.Now,
- UserId = user.Id, //创客
- TradeMonth = monthString, //交易月
- BrandId = BrandId, //品牌
- StatType = 0, //交易统计类型
- TradeAmt = TradeAmt, //商户交易总额
- CreditTradeAmt = CreditTradeAmt, //商户贷记卡交易总金额
- DebitNotCapTradeAmt = DebitNotCapTradeAmt, //商户非封顶借记卡交易总金额
- DebitCapTradeAmt = DebitCapTradeAmt, //商户借记卡封顶交易总额
- DebitCapTradeNum = DebitCapTradeNum, //商户借记卡封顶交易总笔数
- MallPosOrderStatus = machine.PosSnType == 1 ? 0 : 1, //商城兑换机具状态
- ActiveBuddyMerStatus = user.RealName == merchant.MerchantName ? 0 : 1, //激活创客同名商户
- });
- }
- else
- {
- editsummary.TradeAmt += TradeAmt;
- editsummary.CreditTradeAmt += CreditTradeAmt;
- editsummary.DebitNotCapTradeAmt += DebitNotCapTradeAmt;
- editsummary.DebitCapTradeAmt += DebitCapTradeAmt;
- editsummary.DebitCapTradeNum += DebitCapTradeNum;
- }
- TradeDaySummary editdaysum = dbnew.TradeDaySummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeDate == dayString && m.BrandId == BrandId);
- if (editdaysum == null)
- {
- editdaysum = dbnew.TradeDaySummary.Add(new TradeDaySummary()
- {
- CreateDate = DateTime.Now,
- UserId = user.Id, //创客
- TradeDate = dayString, //交易日
- TradeMonth = monthString, //交易月
- BrandId = BrandId, //品牌
- TopUserId = TopUserId, //顶级创客
- }).Entity;
- dbnew.SaveChanges();
- }
- //分类统计交易额
- if (MerHelpFlag == 0)
- {
- if (DirectFlag == 1)
- {
- editdaysum.NotHelpDirectTradeAmt = TradeAmt; //直营商户交易总额(非扶持期)
- if (BankCardTypeNum == 1)
- {
- editdaysum.NotHelpDirectCreditTradeAmt += TradeAmt; //直营贷记卡交易总额(非扶持期)
- if (QrPayFlag == 1)
- {
- editdaysum.NotHelpDirectQrCreditTradeAmt += TradeAmt; //直营云闪付贷记卡交易额(非扶持期)
- }
- else
- {
- editdaysum.NotHelpDirectNonQrCreditTradeAmt += TradeAmt; //直营非云闪付贷记卡交易额(非扶持期)
- }
- }
- else
- {
- editdaysum.NotHelpDirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额(非扶持期)
- if (DebitCapTradeNum > 0)
- {
- editdaysum.NotHelpDirectDebitCapTradeAmt += TradeAmt; //直营商户借记卡封顶交易总金额(非扶持期)
- editdaysum.NotHelpDirectDebitCapNum += 1; //直营商户借记卡封顶交易总数(非扶持期)
- }
- else
- {
- if (QrPayFlag == 1)
- {
- editdaysum.NotHelpDirectQrDebitTradeAmt += TradeAmt; //直营云闪付非封顶借记卡(非扶持期)
- }
- else
- {
- editdaysum.NotHelpDirectNonQrDebitTradeAmt += TradeAmt; //直营非云闪付非封顶借记卡(非扶持期)
- }
- }
- }
- }
- else
- {
- editdaysum.NotHelpNonDirectTradeAmt += TradeAmt; //非直营商户交易总额(非扶持期)
- if (BankCardTypeNum == 1)
- {
- editdaysum.NotHelpNonDirectCreditTradeAmt += TradeAmt; //非直营贷记卡交易总额(非扶持期)
- if (QrPayFlag == 1)
- {
- editdaysum.NotHelpNonDirectQrCreditTradeAmt += TradeAmt; //非直营云闪付贷记卡交易额(非扶持期)
- }
- else
- {
- editdaysum.NotHelpNonDirectNonQrCreditTradeAmt += TradeAmt; //非直营非云闪付贷记卡交易额(非扶持期)
- }
- }
- else
- {
- editdaysum.NotHelpNonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额(非扶持期)
- if (DebitCapTradeNum > 0)
- {
- editdaysum.NotHelpNonDirectDebitCapTradeAmt += TradeAmt; //非直营商户借记卡封顶交易总金额(非扶持期)
- editdaysum.NotHelpNonDirectDebitCapNum += 1; //非直营商户借记卡封顶交易总数(非扶持期)
- }
- else
- {
- if (QrPayFlag == 1)
- {
- editdaysum.NotHelpNonDirectQrDebitTradeAmt += TradeAmt; //非直营云闪付非封顶借记卡(非扶持期)
- }
- else
- {
- editdaysum.NotHelpNonDirectNonQrDebitTradeAmt += TradeAmt; //非直营非云闪付非封顶借记卡(非扶持期)
- }
- }
- }
- }
- }
- else
- {
- if (DirectFlag == 1)
- {
- editdaysum.HelpDirectTradeAmt += TradeAmt; //直营商户交易总额(扶持期)
- if (BankCardTypeNum == 1)
- {
- editdaysum.HelpDirectCreditTradeAmt += TradeAmt; //直营贷记卡交易总额(扶持期)
- if (QrPayFlag == 1)
- {
- editdaysum.HelpDirectQrCreditTradeAmt += TradeAmt; //直营云闪付贷记卡交易额(扶持期)
- }
- else
- {
- editdaysum.HelpDirectNonQrCreditTradeAmt += TradeAmt; //直营非云闪付贷记卡交易额(扶持期)
- }
- }
- else
- {
- editdaysum.HelpDirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额(扶持期)
- if (DebitCapTradeNum > 0)
- {
- editdaysum.HelpDirectDebitCapTradeAmt += TradeAmt; //直营商户借记卡封顶交易总金额(扶持期)
- editdaysum.HelpDirectDebitCapNum += 1; //直营商户借记卡封顶交易总数(扶持期)
- }
- else
- {
- if (QrPayFlag == 1)
- {
- editdaysum.HelpDirectQrDebitTradeAmt += TradeAmt; //直营云闪付非封顶借记卡(扶持期)
- }
- else
- {
- editdaysum.HelpDirectNonQrDebitTradeAmt += TradeAmt; //直营非云闪付非封顶借记卡(扶持期)
- }
- }
- }
- }
- else
- {
- editdaysum.HelpNonDirectTradeAmt += TradeAmt; //非直营商户交易总额(扶持期)
- if (BankCardTypeNum == 1)
- {
- editdaysum.HelpNonDirectCreditTradeAmt += TradeAmt; //非直营贷记卡交易总额(扶持期)
- if (QrPayFlag == 1)
- {
- editdaysum.HelpNonDirectQrCreditTradeAmt += TradeAmt; //非直营云闪付贷记卡交易额(扶持期)
- }
- else
- {
- editdaysum.HelpNonDirectNonQrCreditTradeAmt += TradeAmt; //非直营非云闪付贷记卡交易额(扶持期)
- }
- }
- else
- {
- editdaysum.HelpNonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额(扶持期)
- if (DebitCapTradeNum > 0)
- {
- editdaysum.HelpNonDirectDebitCapTradeAmt += TradeAmt; //非直营商户借记卡封顶交易总金额(扶持期)
- editdaysum.HelpNonDirectDebitCapNum += 1; //非直营商户借记卡封顶交易总数(扶持期)
- }
- else
- {
- if (QrPayFlag == 1)
- {
- editdaysum.HelpNonDirectQrDebitTradeAmt += TradeAmt; //非直营云闪付非封顶借记卡(扶持期)
- }
- else
- {
- editdaysum.HelpNonDirectNonQrDebitTradeAmt += TradeAmt; //非直营非云闪付非封顶借记卡(扶持期)
- }
- }
- }
- }
- }
- UserTradeDaySummary userdaysum = dbnew.UserTradeDaySummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeDate == dayString && m.BrandId == BrandId);
- if (userdaysum == null)
- {
- userdaysum = dbnew.UserTradeDaySummary.Add(new UserTradeDaySummary()
- {
- CreateDate = DateTime.Now,
- UserId = user.Id, //创客
- TradeDate = dayString, //交易日
- TradeMonth = monthString, //交易月
- BrandId = BrandId, //品牌
- }).Entity;
- dbnew.SaveChanges();
- }
- if (DirectFlag == 1)
- {
- userdaysum.DirectTradeAmt += TradeAmt; //直营商户交易总额
- if (BankCardTypeNum == 0)
- {
- userdaysum.DirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额
- }
- }
- else
- {
- userdaysum.NonDirectTradeAmt += TradeAmt; //非直营商户交易总额
- if (BankCardTypeNum == 0)
- {
- userdaysum.NonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额
- }
- }
- dbnew.SaveChanges();
- if (profit)
- {
- DoProfitForPos(dbnew, trade_record);
- }
- tran.Commit();
- }
- catch (Exception ex)
- {
- LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "自定义分润程序监听队列异常");
- tran.Rollback();
- }
- }
- }
- dbnew.Dispose();
- }
- catch (Exception ex)
- {
- LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "自定义分润程序监听队列异常");
- }
- }
- public void DoProfitForPos(WebCMSEntities dbnew, TradeRecord trade_record)
- {
- List<ProfitUsers> users = new List<ProfitUsers>();
- int TopUserId = 0; //顶级创客Id
- Users us = dbnew.Users.FirstOrDefault(a => a.Id == trade_record.UserId);
- if (us != null)
- {
- string uidstring = us.Id.ToString();
- string[] uidlist = { };
- if (!string.IsNullOrEmpty(us.ParentNav))
- {
- uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
- uidlist = uidstring.Split(',');
- if (uidlist.Length > 1)
- {
- TopUserId = int.Parse(function.CheckInt(uidlist[1]));
- }
- else
- {
- TopUserId = int.Parse(function.CheckInt(uidlist[0]));
- }
- }
- Array.Reverse(uidlist);
- foreach (string uidstr in uidlist)
- {
- int puid = int.Parse(function.CheckInt(uidstr));
- Users pus = dbnew.Users.FirstOrDefault(a => a.Id == puid);
- if (pus != null)
- {
- users.Add(new ProfitUsers()
- {
- UserId = pus.Id,
- UserNav = pus.ParentNav,
- UserLevel = pus.UserLevel,
- CreateDate = pus.CreateDate.Value,
- });
- }
- }
- }
- string TradeMonth = trade_record.TradeDate.Value.ToString("yyyyMM");
- List<ProfitResult> list = new List<ProfitResult>();
- list = StartProftForPos(dbnew, trade_record, users);
- using (var tran = dbnew.Database.BeginTransaction())
- {
- try
- {
- foreach (ProfitResult sub in list)
- {
- if (sub.Message == "分红奖励")
- {
- UserAccountRecord accountRecord = dbnew.UserAccountRecord.Add(new UserAccountRecord()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- UserId = sub.UserId, //创客
- ChangeType = 11, //变动类型
- ProductType = trade_record.BrandId, //产品类型
- ChangeAmount = sub.Money, //变更金额
- Status = -1,
- }).Entity;
- dbnew.SaveChanges();
- }
- else
- {
- int ProfitType = sub.UserId == trade_record.UserId ? 0 : 1;
- 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);
- if (editprofitrecord == null)
- {
- editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
- {
- CreateDate = DateTime.Now,
- UserId = sub.UserId, //创客
- MerchantId = trade_record.MerchantId, //商户
- BrandId = trade_record.BrandId, //品牌
- ProfitType = ProfitType, //创客分润类型
- TradeMonth = TradeMonth, //交易月
- TopUserId = TopUserId, //顶级创客
- }).Entity;
- dbnew.SaveChanges();
- string RecordNo = "KPM";
- int RecordId = editprofitrecord.Id;
- string RecordIdString = RecordId.ToString();
- for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
- {
- RecordIdString = "0" + RecordIdString;
- }
- RecordNo += RecordIdString;
- editprofitrecord.RecordNo = RecordNo;
- dbnew.SaveChanges();
- }
- // editprofitrecord.OtherTradeAmt = 0; //其他产品交易总金额
- // editprofitrecord.OtherCreditTradeAmt = 0; //其他产品贷记卡交易总金额
- // editprofitrecord.OtherDebitNotCapTradeAmt = 0; //其他产品借记卡非封顶交易总金额
- decimal TradeAmount = trade_record.TradeAmount;
- editprofitrecord.TradeAmt += TradeAmount; //商户交易总额
- if (trade_record.BankCardType == 0) editprofitrecord.CreditTradeAmt += TradeAmount; //贷记卡交易总金额
- if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditTradeAmt += TradeAmount; //(云闪付)贷记卡交易总金额
- if (trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NonQrCreditTradeAmt += TradeAmount; //(非云闪付)贷记卡交易总金额
- if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditTradeAmt += TradeAmount; //(非扶持期)(非云闪付)贷记卡交易总金额
- if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditTradeAmt += TradeAmount; //(扶持期)(非云闪付)贷记卡交易总金额
- if (sub.Money < 1 && trade_record.BankCardType == 1) editprofitrecord.DebitNonCapTradeAmt += TradeAmount; //商户非封顶借记卡交易总额
- if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitNotCapTradeAmt += TradeAmount; //(云闪付)商户非封顶借记卡交易总额
- if (sub.Money < 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NonQrDebitNotCapTradeAmt += TradeAmount; //(非云闪付)商户非封顶借记卡交易总额
- if (sub.Money < 1 && trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitNonCapTradeAmt += TradeAmount; //(非扶持期)(非云闪付)借记卡非封顶交易总金额
- if (sub.Money < 1 && trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitNonCapTradeAmt += TradeAmount; //(扶持期)(非云闪付)借记卡非封顶交易总金额
- if (sub.Money == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitCapTradeAmt = TradeAmount; //商户借记卡封顶交易总额
- editprofitrecord.DebitCapTradeNum += 1; //商户借记卡封顶交易总笔数
- decimal ProfitMoney = sub.Money;
- ulong DirectFlag = trade_record.DirectFlag;
- editprofitrecord.TradeProfit += ProfitMoney; //交易分润
- if (trade_record.BankCardType == 0) editprofitrecord.CreditTradeProfit += ProfitMoney; //贷记卡分润总金额
- if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditTradeProfit += ProfitMoney; //(云闪付)贷记卡交易分润
- if (trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NonQrCreditTradeProfit += ProfitMoney; //(非云闪付)贷记卡交易分润
- if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditTradeProfit += ProfitMoney; //(非扶持期)(非云闪付)贷记卡分润总金额
- if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditTradeProfit += ProfitMoney; //(扶持期)(非云闪付)贷记卡分润总金额
- if (sub.Money < 1 && trade_record.BankCardType == 1) editprofitrecord.DebitNonTradeCapProfit += ProfitMoney; //借记卡非封顶交易分润总金额
- if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitNonTradeCapProfit += ProfitMoney; //(云闪付)借记卡非封顶交易分润总金额
- if (sub.Money < 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NonQrDebitNonTradeCapProfit += ProfitMoney; //(非云闪付)借记卡非封顶交易分润总金额
- if (sub.Money < 1 && trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitNonTradeCapProfit += ProfitMoney; //(非扶持期)(非云闪付)借记卡非封顶交易分润总金额
- if (sub.Money < 1 && trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitNonTradeCapProfit += ProfitMoney; //(扶持期)(非云闪付)借记卡非封顶交易分润总金额
- if (sub.Money == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitTradeCapProfit += ProfitMoney; //借记卡封顶交易分润总金额
- if (sub.Money < 1 && DirectFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitCapSingleReward += ProfitMoney; //借记卡合伙人直营封顶交易奖励金额
- if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditProfitRate = sub.ProfitRate; //(非扶持期)(非云闪付)贷记卡商户交易对应分润比例
- if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditProfitStandardRate = sub.ProfitPercent; //(非扶持期)(非云闪付)贷记卡标准分润比例
- if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditAddOrSubRate = sub.AddOrSubRate; //(非扶持期)(非云闪付)贷记卡成本或增或减比例
- if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditProfitRate = sub.ProfitRate; //(扶持期)(非云闪付)贷记卡商户交易对应分润比例
- if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditProfitStandardRate = sub.ProfitPercent; //(扶持期)(非云闪付)贷记卡-标准分润比例
- if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditAddOrSubRate = sub.AddOrSubRate; //(扶持期)(非云闪付)贷记卡成本或增或减比例
- if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitProfitRate = sub.ProfitRate; //(非扶持期)(非云闪付)借记卡商户交易对应分润比例
- if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitProfitStandardRate = sub.ProfitPercent; //(非扶持期)(非云闪付)借记卡标准分润比例
- if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitAddOrSubRate = sub.AddOrSubRate; //(非扶持期)(非云闪付)借记卡成本或增或减比例
- if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitProfitRate = sub.ProfitRate; //(扶持期)(非云闪付)借记卡商户交易对应分润比例
- if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitProfitStandardRate = sub.ProfitPercent; //(扶持期)(非云闪付)借记卡-标准分润比例
- if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitAddOrSubRate = sub.AddOrSubRate; //(扶持期)(非云闪付)借记卡成本或增或减比例
- if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditProfitRate = sub.ProfitRate; //(云闪付)贷记卡交易分润比例
- if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditProfitStandardRate = sub.ProfitRateBase; //(云闪付)贷记卡分润基准
- editprofitrecord.QrCreditAddOrSubRate = sub.AddOrSubRate; //(云闪付)贷记卡分润比例或增或减
- if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitProfitRate = sub.ProfitRate; //(云闪付)借记卡非封顶交易分润比例
- if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitProfitStandardRate = sub.ProfitRateBase; //(云闪付)借记卡非封顶交易分润基准
- if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitAddOrSubRate = sub.AddOrSubRate; //(云闪付)借记卡非封顶交易分润比例或增或减
- dbnew.SaveChanges();
- dbnew.ProfitRecord.Add(new ProfitRecord()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- UserId = sub.UserId, //创客
- MerchantId = trade_record.MerchantId, //商户
- MerNo = trade_record.MerNo, //渠道商户编号
- MerHelpFlag = trade_record.MerHelpFlag, //是否属于扶持周期内商户
- HelpMonthCount = trade_record.HelpMonthCount, //扶持第几个月
- MerBuddyType = trade_record.MerBuddyType, //商户创客类型
- SnNo = trade_record.SnNo, //SN号
- TradeDate = trade_record.TradeDate, //交易日期
- ProfitAmount = sub.Money, //分润金额
- QrPayFlag = trade_record.QrPayFlag, //云闪付标识
- CapFlag = trade_record.CapFlag, //借记卡封顶交易标志
- DirectFlag = trade_record.DirectFlag, //是否直营
- BrandId = trade_record.BrandId, //品牌
- ParentNav = us.ParentNav, //上级创客集
- TradeId = trade_record.Id, //交易记录Id
- });
- dbnew.SaveChanges();
- // Users user = dbnew.Users.FirstOrDefault(m => m.Id == sub.UserId);
- // if (user != null)
- // {
- // if (!string.IsNullOrEmpty(user.CloudPushDeviceId))
- // {
- // new AliyunPushOld().Push("鑫创客通知", "您有一笔分润收益:" + sub.Money.ToString("f2"), "30", "NOTICE", user.DeviceType, user.CloudPushDeviceId, "1");
- // }
- // TODO:发送阿里云推送消息
- // }
- }
- }
- dbnew.SaveChanges();
- tran.Commit();
- }
- catch (Exception ex)
- {
- tran.Rollback();
- LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "POS分润异常");
- }
- }
- }
- #endregion
-
- #region POS分润算法
- public List<ProfitResult> StartProftForPos(WebCMSEntities dbnew, TradeRecord trade, List<ProfitUsers> users)
- {
- // 级差
- /*
-
- K1 - K5:无大小市场要求,无押机分润比例为有押金机的70%,如K1的有押金机分润比例为万6,则无押机的分润比例为万4.2
- 机具激活大于90天,分润比例为原比例的70%
- if(is0y){
- 分润比例为原比例的70%
- }
- if(ActivityDate > now - 90){
- 分润比例为原比例的70%
- }
- K6 - K9:
- K6:至少有1个直推大于3000万,且总交易额减去3000万大于1200万,则获得分红奖(月月红)直接级差
- K7:总交易额减去最大交易额的直推,大于4000万,则获得分红奖(月月红)直接级差
- K8:总交易额减去最大交易额的直推,大于12000万,则获得分红奖(月月红)直接级差
- K9:总交易额减去最大交易额的直推,大于32000万,则获得分红奖(月月红)直接级差
- 补贴:
- 0押金无补贴
- 机具激活90天内,机具所属创客获得万10置顶
- 若创客为商户型创客,则机具UserId的创客获得万4分润
- */
- List<ProfitResult> result = new List<ProfitResult>();
- int BrandId = trade.BrandId;
- ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
- if (obj.Status == 1) //判断分润是否开启
- {
- decimal TradeMoney = trade.TradeAmount;
- int BankCardType = trade.BankCardType; //银行卡类型:贷记卡-1,借记卡-0
- int MerHelpFlag = (int)trade.MerHelpFlag; //扶持期-1,稳定期=0
- List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();
- int IncludeCurrentMonth = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":HelpPolicy:IncludeCurrentMonth")); //是否包含当前月
- int NaturalMonth = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":HelpPolicy:NaturalMonth")); //自然月
- if(IncludeCurrentMonth == 1) NaturalMonth -= 1;
- if (BankCardType == 0)
- {
- Users user = dbnew.Users.FirstOrDefault(m => m.Id == trade.UserId) ?? new Users();
- // UserProfitSet profitSet = profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardType && m.HelpFlag == MerHelpFlag) ?? new UserProfitSet(); //获取创客分润规则-扶持期
- // profitrate = profitSet.ProfitRate;
- // profitrate = profitrate / 100;
- int UserLevel = user.UserLevel; //当前会员等级
- int HelpTime = 0;
- if (user.CreateDate.Value.AddMonths(NaturalMonth) > DateTime.Now)
- {
- HelpTime = 1;
- }
- int LevelKindId = GetLevelKindId(trade.BrandId, HelpTime, BankCardType);
- ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
- decimal getLevelProfit = TradeMoney * objlevel.Percents;
- if(getLevelProfit > 1) getLevelProfit = 1;
- result.Add(new ProfitResult()
- {
- UserId = user.Id,
- UserNav = user.ParentNav,
- Money = getLevelProfit,
- ProfitRate = objlevel.Percents,
- // ProfitPercent = profitSet.ProfitPercent,
- // AddOrSubRate = profitSet.AddOrSubRate,
- // ProfitRateBase = profitSet.ProfitRateBase,
- });
- return result;
- }
- int maxLevel = obj.MaxLevel; //最大等级
- int maxFloor = obj.MaxFloor; //最大层级
- int maxContinueFloor = RedisDbconn.Instance.Get<int>("pobjconc" + BrandId); //最大继续分润层级
- decimal diffLevelProfit = 0; //等级级差
- decimal diffDiviProfit = 0; //分红级差
- // decimal diffFloorProfit = 0; //层级级差
- // int continueFloor = 0; //继续分润层级
- int curLevel = 0; //当前层级的会员等级
- for (int curFloor = 1; curFloor <= users.Count; curFloor++)
- {
- ProfitUsers user = new ProfitUsers();
- if (curFloor <= users.Count)
- {
- user = users[curFloor - 1];
- }
- int UserLevel = user.UserLevel; //当前会员等级
- //判断当前创客是否有直推的激活机具,并且在活动时间内
- if (UserLevel == maxLevel && UserLevel == curLevel)
- {
- break;
- }
- if (UserLevel <= maxLevel && UserLevel > curLevel)
- {
- int HelpTime = 0;
- if (user.CreateDate.AddMonths(NaturalMonth) > DateTime.Now)
- {
- HelpTime = 1;
- }
- int LevelKindId = GetLevelKindId(trade.BrandId, HelpTime, BankCardType);
- ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
- if (objlevel != null)
- {
- decimal getLevelProfit = 0; //等级分润
- // UserProfitSet profitSet = new UserProfitSet();
- if (objlevel.Percents > 0)
- {
- //获取创客分润规则,注册日开始算起,3个自然月内算扶持期
- decimal profitrate = objlevel.Percents;
- // profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.UserId && m.BrandId == BrandId && m.CardType == BankCardType && m.HelpFlag == MerHelpFlag) ?? new UserProfitSet(); //获取创客分润规则-扶持期
- // profitrate = profitSet.ProfitRate;
- // profitrate = profitrate / 100;
- getLevelProfit += TradeMoney * objlevel.Percents * profitrate;
- }
- if (objlevel.AddProfitVal > 0)
- {
- //分红奖励:一个3000万,3000万以下市场总和大于1200万
- bool bigMarket = false;
- decimal smallMarket = 0;
- List<Users> directs = dbnew.Users.Where(m => m.ParentUserId == user.UserId).ToList();
- decimal BigMarketTradeAmt = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:BigMarketTradeAmt")); //大市场交易额
- decimal PassTradeAmt = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:PassTradeAmt")); //小市场交易超越额
- decimal UnitPrize = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:UnitPrize")); //单位奖励基数
- foreach (Users direct in directs)
- {
- UserData userData = dbnew.UserData.FirstOrDefault(m => m.UserId == direct.Id) ?? new UserData();
- if (userData.TotalOrderMoney >= BigMarketTradeAmt)
- {
- bigMarket = true;
- }
- else
- {
- smallMarket += userData.TotalOrderMoney;
- }
- }
- if (bigMarket && smallMarket >= PassTradeAmt)
- {
- decimal DiviPrize = objlevel.AddProfitVal * TradeMoney / UnitPrize;
- decimal checkmoney = DiviPrize;
- DiviPrize -= diffDiviProfit;
- if (objlevel.LevelDiff == 1) //判断是否有级差
- {
- diffDiviProfit = checkmoney;
- }
- if (DiviPrize >= obj.MinProfitVal)
- {
- result.Add(new ProfitResult()
- {
- UserId = user.UserId,
- UserNav = user.UserNav,
- Money = DiviPrize,
- Message = "分红奖励",
- });
- }
- }
- }
- decimal money = getLevelProfit;
- getLevelProfit -= diffLevelProfit;
- if (objlevel.LevelDiff == 1) //判断是否有级差
- {
- diffLevelProfit = money;
- }
- if (getLevelProfit >= obj.MinProfitVal)
- {
- result.Add(new ProfitResult()
- {
- UserId = user.UserId,
- UserNav = user.UserNav,
- Money = getLevelProfit,
- ProfitRate = objlevel.Percents,
- // ProfitPercent = profitSet.ProfitPercent,
- // AddOrSubRate = profitSet.AddOrSubRate,
- // ProfitRateBase = profitSet.ProfitRateBase,
- });
- }
- }
- }
- curLevel = UserLevel;
- }
- }
- return result;
- }
- public void StatProfit()
- {
- Thread th = new Thread(StatProfitDo);
- th.IsBackground = true;
- th.Start();
- }
- public void StatProfitDo()
- {
- string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
- string check = function.ReadInstance("/ProfitStat/" + Month + ".txt");
- if (!string.IsNullOrEmpty(check))
- {
- return;
- }
- function.WritePage("/ProfitStat/", Month + ".txt", DateTime.Now.ToString());
- WebCMSEntities db = new WebCMSEntities();
- for (int i = 1; i <= 9; i++) //品牌
- {
- for (int j = 0; j <= 1; j++) //卡类型
- {
- int PageNum = 1;
- bool op = true;
- while(op)
- {
- List<ProfitResult> result = StartProftForPosByMonth(i, j, Month, PageNum);
- if(result.Count > 0)
- {
- foreach (ProfitResult sub in result)
- {
- int TopUserId = 0;
- if (!string.IsNullOrEmpty(sub.UserNav))
- {
- string[] UserNavList = sub.UserNav.Trim(',').Replace(",,", ",").Split(',');
- if (UserNavList.Length > 1)
- {
- TopUserId = int.Parse(UserNavList[1]);
- }
- else
- {
- TopUserId = int.Parse(UserNavList[0]);
- }
- }
- string RecordNo = "P" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
- decimal ProfitAmt = sub.Money;
- decimal TradeAmt = sub.TradeAmount;
- decimal ProfitRate = sub.ProfitRate;
- if (sub.IsSubsidy == 1 && j == 1)
- {
- decimal CreditTradeAmt = TradeAmt; //商户贷记卡交易总金额
- decimal QrCreditTradeAmt = 0; //商户(云闪付)贷记卡交易总金额
- decimal NonQrCreditTradeAmt = 0; //商户(非云闪付)贷记卡交易总金额
- decimal CreditProfitRate = 0; //(非云闪付)贷记卡交易分润比例
- decimal SubsidyProfit = 0; //商户(非云闪付)贷记卡交易分润补贴金额
- if (sub.QrPayFlag == 1)
- {
- QrCreditTradeAmt = TradeAmt; //商户(云闪付)贷记卡交易总金额
- }
- else
- {
- NonQrCreditTradeAmt = TradeAmt; //商户(非云闪付)贷记卡交易总金额
- CreditProfitRate = ProfitRate; //(非云闪付)贷记卡交易分润比例
- SubsidyProfit = ProfitAmt; //商户(非云闪付)贷记卡交易分润补贴金额
- }
- MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == sub.PosSn) ?? new MachineForSnNo();
- PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PosMachinesTwo();
- PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == sub.MerchantId) ?? new PosMerchantInfo();
- db.ProfitSubsidyDetail.Add(new ProfitSubsidyDetail()
- {
- CreateDate = DateTime.Now,
- UpdateDate = DateTime.Now,
- RecordNo = RecordNo, //流水号
- BrandId = sub.BrandId, //品牌
- ProductName = RelationClass.GetKqProductBrandInfo(sub.BrandId), //产品名称
- TradeMonth = Month, //交易月份
- MerchantId = sub.MerchantId, //商户
- MerNo = merchant.KqMerNo, //渠道商户编号
- SnNo = sub.PosSn, //渠道SN号
- MerRegTime = pos.BindingTime, //渠道注册时间
- MerStandardDate = merchant.MerStandardDate, //商户激活时间
- BelongUserId = merchant.UserId, //商户归属人
- MerHelpFlag = sub.HelpFlag == 1 ? 1u : 0u, //是否属于扶持周期内商户
- SubsidyUserId = sub.UserId, //补贴人
- SubsidyType = sub.DirectFlag, //分润补贴类型
- SubsidyProfitRate = sub.Money, //创客活动期内直营商户分润万分之十
- CreditTradeAmt = CreditTradeAmt, //商户贷记卡交易总金额
- QrCreditTradeAmt = QrCreditTradeAmt, //商户(云闪付)贷记卡交易总金额
- NonQrCreditTradeAmt = NonQrCreditTradeAmt, //商户(非云闪付)贷记卡交易总金额
- CreditProfitRate = CreditProfitRate, //(非云闪付)贷记卡交易分润比例
- SubsidyProfit = SubsidyProfit, //商户(非云闪付)贷记卡交易分润补贴金额
- });
- }
- }
- db.SaveChanges();
- PageNum += 1;
- }
- else
- {
- op = false;
- }
- }
- }
- }
- db.Dispose();
- HelpProfitHelper.Instance.StatProfitEveryDay(DateTime.Now.AddMonths(-1).ToString("yyyyMM")); //助利宝分润
- ProfitCheckHelper.Instance.Start();
- }
- public List<ProfitResult> StartProftForPosByMonth(int BrandId, int BankCardType, string Month, int PageNum = 1)
- {
- // 级差
- /*
-
- K1 - K5:无大小市场要求,无押机分润比例为有押金机的70%,如K1的有押金机分润比例为万6,则无押机的分润比例为万4.2
- 机具激活大于90天,分润比例为原比例的70%
- if(is0y){
- 分润比例为原比例的70%
- }
- if(ActivityDate > now - 90){
- 分润比例为原比例的70%
- }
- K6 - K9:
- K6:至少有1个直推大于3000万,且总交易额减去3000万大于1200万,则获得分红奖(月月红)直接级差
- K7:总交易额减去最大交易额的直推,大于4000万,则获得分红奖(月月红)直接级差
- K8:总交易额减去最大交易额的直推,大于12000万,则获得分红奖(月月红)直接级差
- K9:总交易额减去最大交易额的直推,大于32000万,则获得分红奖(月月红)直接级差
- 补贴:
- 0押金无补贴
- 机具激活90天内,机具所属创客获得万10置顶
- 若创客为商户型创客,则机具UserId的创客获得万4分润
- //查分润
- select u.MakerCode,u.RealName,u.UserLevel,r.Rank,pos.SeoKeyword,p.KqSnNo,(case when ProfitType=1 then '直营' else '团队' end) as DirectFlag,
- k.Name,CreditTradeAmt,CreditTradeProfit,DebitTradeAmt,DebitTradeProfit,QrCreditTradeAmt,QrCreditTradeProfit from (
- select UserId,ProfitType,BrandId,MerchantId,
- sum(CreditTradeAmt) as CreditTradeAmt,
- sum(CreditTradeProfit) as CreditTradeProfit,
- sum(DebitNonCapTradeAmt+DebitCapTradeAmt) as DebitTradeAmt,
- sum(DebitNonTradeCapProfit+DebitTradeCapProfit) as DebitTradeProfit,
- sum(QrCreditTradeAmt) as QrCreditTradeAmt,
- sum(QrCreditTradeProfit) as QrCreditTradeProfit
- from ProfitRewardRecord where MerchantId>0
- GROUP BY UserId,ProfitType,BrandId,MerchantId
- ) tb
- left join Users u on tb.UserId=u.Id
- LEFT JOIN KqProducts k ON k.Id=tb.BrandId
- left join PosMerchantInfo p on tb.MerchantId=p.Id
- left join MachineForSnNo fp on fp.SnNo=p.KqSnNo
- left join PosMachinesTwo pos on pos.Id=fp.SnId
- left join UserRankWhite r on u.Id=r.Id
- ORDER BY p.KqSnNo,u.MakerCode
- //查补贴
- select u.MakerCode,u.RealName,u.UserLevel,r.Rank,m.KqSnNo,m.MerchantName,(case when SubsidyType=1 then '直营' else '团队' end) as DirectFlag,
- k.Name,CreditTradeAmt,SubsidyProfit from (
- select SubsidyUserId,MerchantId,BrandId,SubsidyType,
- sum(CreditTradeAmt) as CreditTradeAmt,
- sum(SubsidyProfitRate) as SubsidyProfit
- from ProfitSubsidyDetail where TradeMonth='202208'
- GROUP BY SubsidyUserId,MerchantId,BrandId,SubsidyType
- ) tb
- left join Users u on tb.SubsidyUserId=u.Id
- LEFT JOIN KqProducts k ON k.Id=tb.BrandId
- left join PosMerchantInfo m on tb.MerchantId=m.Id
- 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'
- // TODO:做到后台查询,换绑机器遗漏交易额补差
- select UserId,sum(TradeAmount) from TradeRecord where SnNo in (
- select PosSn from PosMachinesTwo where UserId=0 and BuyUserId=0 and CreditTrade>0
- ) and CreateDate>='2022-04-01 00:00:00' and CreateDate<'2022-05-01 00:00:00' and UserId>0 group by UserId
- */
- int PageSize = 200;
- int SkipNum = (PageNum - 1) * PageSize;
- string LimitString = " limit " + PageSize;
- if(PageNum > 1)
- {
- LimitString = " limit " + SkipNum + "," + PageSize;
- }
- LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "老规则分润日志");
- LogHelper.Instance.WriteLog(BankCardType.ToString(), "老规则分润日志");
- LogHelper.Instance.WriteLog(BrandId.ToString(), "老规则分润日志");
- List<ProfitResult> result = new List<ProfitResult>();
- ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
- if (obj.Status == 1) //判断分润是否开启
- {
- string start = Month.Substring(0, 4) + "-" + Month.Substring(4, 2) + "-01 00:00:00";
- string end = DateTime.Parse(start).AddMonths(1).ToString("yyyy-MM-dd HH:mm:ss");
- DataTable dt = new DataTable();
- if (BankCardType == 1)
- {
- dt = ProfitHelperV2.Instance.GetDataTable("select SnNo,UserId,QrPayFlag,MerHelpFlag,TradeAmount,Version from TradeRecord" + Month + " where MerHelpFlag=1 and Version=0 and BrandId=" + BrandId + LimitString);
- }
- LogHelper.Instance.WriteLog("记录页数:" + PageNum.ToString(), "老规则分润日志");
- LogHelper.Instance.WriteLog("记录条数:" + dt.Rows.Count.ToString(), "老规则分润日志");
- foreach (DataRow dr in dt.Rows)
- {
- WebCMSEntities dbnew = new WebCMSEntities();
- try
- {
- string SnNo = dr["SnNo"].ToString();
- int UserId = int.Parse(dr["UserId"].ToString());
- int HelpTime = int.Parse(dr["Version"].ToString()) == 1 ? 2 : int.Parse(dr["MerHelpFlag"].ToString());
- LogHelper.Instance.WriteLog("SnNo:" + SnNo, "老规则分润日志");
- LogHelper.Instance.WriteLog("UserId:" + UserId, "老规则分润日志");
- LogHelper.Instance.WriteLog("HelpTime:" + HelpTime, "老规则分润日志");
- MachineForSnNo forSnNo = dbnew.MachineForSnNo.FirstOrDefault(m => m.SnNo == SnNo) ?? new MachineForSnNo();
- PosMachinesTwo pos = dbnew.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PosMachinesTwo();
- decimal Deposit = decimal.Parse(function.CheckNum(pos.SeoKeyword));
- if (pos.BindingState == 1)
- {
- LogHelper.Instance.WriteLog("BindingState:" + pos.BindingState, "老规则分润日志");
- int QrPayFlag = int.Parse(dr["QrPayFlag"].ToString());
- decimal TradeAmt = decimal.Parse(dr[4].ToString());
- List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();
- SubUser selfUser = ProfitHelperV2.Instance.GetUser(UserId, Month) ?? new SubUser();
- int Days = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + BrandId + ":HelpPolicy:Days")); //天数
- if (BankCardType == 0)
- {
- }
- else
- {
- int maxLevel = obj.MaxLevel; //最大等级
- decimal diffLevelProfit = 0; //等级级差
- int curLevel = 0; //当前层级的会员等级
- string ParentNav = selfUser.ParentNav;
- if (string.IsNullOrEmpty(ParentNav) && pos.BuyUserId == 1 && pos.UserId == 1)
- {
- ParentNav = ",0,";
- }
- if (!string.IsNullOrEmpty(ParentNav))
- {
- ParentNav += "," + UserId + ",";
- string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
- Array.Reverse(ParentNavList); //反转顺序
- int level = 0;
- DateTime now = DateTime.Now;
- DateTime ThisMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
- foreach (string UserIdString in ParentNavList)
- {
- level += 1;
- int uid = int.Parse(UserIdString);
- SubUser user = ProfitHelperV2.Instance.GetUser(uid, Month) ?? new SubUser();
- int UserLevel = user.PreUserLevel > user.UserLevel ? user.PreUserLevel : user.UserLevel; //当前会员等级
- if (curLevel == maxLevel) //判断当前创客是否有直推的激活机具,并且在活动时间内
- {
- break;
- }
- if (UserLevel <= maxLevel && UserLevel > curLevel)
- {
- LogHelper.Instance.WriteLog("UserLevel:" + UserLevel, "老规则分润日志");
- LogHelper.Instance.WriteLog("curLevel:" + curLevel, "老规则分润日志");
- int LevelKindId = GetLevelKindId(BrandId, HelpTime, 1);
- ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
- if (objlevel != null)
- {
- decimal getLevelProfit = 0; //等级分润
- if (objlevel.Percents > 0)
- {
- //获取创客分润规则,注册日开始算起,3个自然月内算扶持期
- getLevelProfit += TradeAmt * objlevel.Percents;
- }
- if (objlevel.AddProfitVal > 0)
- {
- getLevelProfit += objlevel.AddProfitVal;
- }
- decimal money = getLevelProfit;
- getLevelProfit -= diffLevelProfit;
- if (objlevel.LevelDiff == 1) //判断是否有级差
- {
- diffLevelProfit = money;
- }
- // 分润补贴
- if (HelpTime == 1 && level == 1)
- {
- LogHelper.Instance.WriteLog("ok", "老规则分润日志");
- int SubsidyUserId = pos.BuyUserId;
- SubUser subuser = ProfitHelperV2.Instance.GetUser(SubsidyUserId, Month) ?? new SubUser();
- int subUserLevel = subuser.PreUserLevel > subuser.UserLevel ? subuser.PreUserLevel : subuser.UserLevel;
- LogHelper.Instance.WriteLog("subUserLevel:" + subUserLevel, "老规则分润日志");
- if(subUserLevel < 5)
- {
- LogHelper.Instance.WriteLog("sub:ok:", "老规则分润日志");
- ProfitObjectLevels sublevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + subUserLevel); //获取当前等级参数
- if (sublevel != null)
- {
- decimal otherPercent = 0.001M - sublevel.Percents;
- decimal otherMoney = TradeAmt * otherPercent;
- LogHelper.Instance.WriteLog("otherPercent:" + otherPercent, "老规则分润日志");
- LogHelper.Instance.WriteLog("otherMoney:" + otherMoney, "老规则分润日志");
- if (otherMoney >= obj.MinProfitVal)
- {
- LogHelper.Instance.WriteLog("finish:" + SnNo, "老规则分润日志");
- result.Add(new ProfitResult()
- {
- UserId = subuser.Id,
- UserNav = subuser.ParentNav,
- Money = PublicFunction.NumberFormat(otherMoney),
- ProfitRate = otherPercent,
- Message = "分润补贴",
- BankCardType = BankCardType,
- QrPayFlag = QrPayFlag,
- DirectFlag = 1,
- BrandId = pos.BrandId,
- IsSubsidy = 1,
- MerchantId = pos.BindMerchantId,
- TradeAmount = TradeAmt,
- HelpFlag = HelpTime,
- PosSn = pos.PosSn,
- });
- }
- }
- }
- }
- }
- }
- curLevel = UserLevel;
- }
- }
- }
- }
- LogHelper.Instance.WriteLog("\n\n", "老规则分润日志");
- }
- catch (Exception ex)
- {
- LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "每月统计分润异常");
- }
- dbnew.Dispose();
- }
- }
- LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "老规则分润日志");
- LogHelper.Instance.WriteLog("\r\n\r\n", "老规则分润日志");
- return result;
- }
- #endregion
- }
- }
|