BonusCalc.php 191 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/8/2
  6. * Time: 上午10:32
  7. */
  8. namespace common\helpers\bonus;
  9. use common\helpers\Cache;
  10. use common\helpers\Date;
  11. use common\helpers\LoggerTool;
  12. use common\helpers\snowflake\SnowFake;
  13. use common\helpers\Tool;
  14. use common\models\CalcBonus;
  15. use common\models\CalcBonusBD;
  16. use common\models\CalcBonusBS;
  17. use common\models\CalcBonusQuarter;
  18. use common\models\CalcBonusBT;
  19. use common\models\CalcBonusCF;
  20. use common\models\CalcBonusFL;
  21. use common\models\CalcBonusFW;
  22. use common\models\CalcBonusFX;
  23. use common\models\CalcBonusGarage;
  24. use common\models\CalcBonusGL;
  25. use common\models\CalcBonusGX;
  26. use common\models\CalcBonusHB;
  27. use common\models\CalcBonusLS;
  28. use common\models\CalcBonusLX;
  29. use common\models\CalcBonusQY;
  30. use common\models\CalcBonusStandard;
  31. use common\models\CalcBonusTG;
  32. use common\models\CalcBonusTourism;
  33. use common\models\CalcBonusVilla;
  34. use common\models\CalcBonusVIP;
  35. use common\models\CalcBonusXF;
  36. use common\models\CalcBonusYC;
  37. use common\models\CalcBonusYJ;
  38. use common\models\CalcMonthBonusUser;
  39. use common\models\Config;
  40. use common\models\FlowDeductZR;
  41. use common\models\Order;
  42. use common\models\OrderGoods;
  43. use common\models\OrderShop;
  44. use common\models\PerfCompany;
  45. use common\models\PerfMonth;
  46. use common\models\PerfPeriod;
  47. use common\models\Period;
  48. use common\models\ResendQY;
  49. use common\models\DeclarationLevel;
  50. use common\models\DecOrder;
  51. use common\models\EmployLevel;
  52. use common\models\FlowBonus;
  53. use common\models\PerfActiveUser;
  54. use common\models\ScoreMonth;
  55. use common\models\ShopGoods;
  56. use common\models\StarCrownLevel;
  57. use common\models\User;
  58. use common\models\UserInfo;
  59. use common\models\UserPerf;
  60. use SebastianBergmann\CodeCoverage\Report\PHP;
  61. use yii\base\BaseObject;
  62. use yii\base\Exception;
  63. use yii\base\StaticInstanceTrait;
  64. use yii\helpers\Json;
  65. use yii\db\Query;
  66. class BonusCalc extends BaseObject {
  67. use StaticInstanceTrait;
  68. private $_limit = 10000;
  69. private $_gxLimit = 500;
  70. private $_handleUserId;
  71. private $_companyMonthPerf = 0;
  72. private $_cfTotalPercent = 0;
  73. private $_lxTotalPercent = 0;
  74. private $_sysConfig = [];
  75. private $_decLevelConfig = [];
  76. private $_empLevelConfig = [];
  77. private $_starCrownLevelConfig = [];
  78. private $_decRoleConfig = [];
  79. private $_errors = [];
  80. private $_periodNum = 0;
  81. private $_periodId;
  82. private $_isCalcMonth = 0;
  83. private $_calcYear;
  84. private $_calcMonth;
  85. private $_calcYearMonth;
  86. private $_calcMonthPeriodNumCount = 0;
  87. private $_lastCalcYear;
  88. private $_lastCalcMonth;
  89. private $_lastCalcYearMonth;
  90. private $_lastPeriodNum;
  91. private $_lastPeriodYear;
  92. private $_lastPeriodMonth;
  93. private $_lastPeriodYearMonth;
  94. //pv
  95. private $_pvRatio;
  96. private $_calcZone = ['openTravel', 'openCar', 'openHouse'];
  97. const LOOP_FINISH = 1;
  98. const LOOP_CONTINUE = 2;
  99. const GX_FLOOR_LIMIT = 5; // 共享奖向上找的最大层级
  100. const GX_LIMIT_SWITCH = true; // 是否开启共享奖向上找的最大限制 true 为开启 false 关闭
  101. const ORDER_TYPE_TO_FW_COEFFICIENT = [
  102. 'ZC' => 'fwCoefficientFromZc',
  103. 'FX_CASH' => 'fwCoefficientFromFxCash',
  104. 'FX_POINT' => 'fwCoefficientFromFxPoint',
  105. ];
  106. const JX_STANDARD_BASE_AMOUNT = 10000;
  107. const JX_STANDARD_MAX_TIMES = 50;
  108. const JX_STANDARD_BONUS_PERCENT = 15;
  109. //最小报单pv
  110. const MIN_BD_PV = 980;
  111. /**
  112. * 1、抓取所有报单、订单,把能当时产生业绩的报单存入业绩单。例如注册单,订单
  113. * 2、从业绩单中循环,并计算上下级业绩
  114. * 3、计算级别
  115. * 4、计算各个奖项
  116. * 5、给会员追加总业绩,在结算中不妥,打算把追加总业绩放到挂网中,因为结算完成以后的业绩都不是最终的,有可能还会变
  117. */
  118. /**
  119. * 初始化
  120. */
  121. public function init() {
  122. parent::init();
  123. }
  124. /**
  125. * 设置期数
  126. * @param int $periodNum
  127. * @return int
  128. */
  129. public function setPeriodNum(int $periodNum) {
  130. return $this->_periodNum = $periodNum;
  131. }
  132. /**
  133. * 获取期数
  134. * @return int
  135. */
  136. public function getPeriodNum() {
  137. return $this->_periodNum;
  138. }
  139. /**
  140. * 加入错误错误
  141. * @param $attr
  142. * @param $error
  143. */
  144. public function addError($attr, $error) {
  145. $this->_errors[$attr][] = $error;
  146. }
  147. /**
  148. * 获取错误信息
  149. * @return array
  150. */
  151. public function getErrors() {
  152. return $this->_errors;
  153. }
  154. /**
  155. * 开始执行结算步骤
  156. * @param $periodNum
  157. * @param null $handleUserId
  158. * @return bool
  159. */
  160. public function calcStep($periodNum, $handleUserId = null) {
  161. try {
  162. $this->_errors = [];
  163. $this->setPeriodNum($periodNum);
  164. $this->_handleUserId = $handleUserId;
  165. $t1 = microtime(true);
  166. // 初始化结算任务
  167. $this->initCalcTask();
  168. // 设置结算状态
  169. $this->setCalcStatus('start');
  170. // 清空所有本期结算用到的缓存
  171. CalcCache::clearCalcBonusCache($this->_periodNum);
  172. // 清空相关表数据
  173. $this->clearCalcTableData();
  174. $t2 = microtime(true);
  175. echo('初始化、清空缓存及相关数据表完成,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  176. $this->_updatePercent(5);
  177. $t3 = microtime(true);
  178. $this->_updatePercent(10);
  179. // 奖金部分
  180. if($this->_sysConfig['openFW']['VALUE']) {
  181. $this->calcBonusBDStepOne();
  182. $this->calcBonusBDStepTwo();
  183. }
  184. $t4 = microtime(true);
  185. echo('计算服务奖'.($this->_sysConfig['openFW']['VALUE']?'完成':'关闭').',耗时:' . round($t4 - $t3, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  186. $this->_updatePercent(15);
  187. // 销售奖/推广奖
  188. if($this->_sysConfig['openTG']['VALUE']) {
  189. $this->calcBonusTG();
  190. }
  191. $t5 = microtime(true);
  192. echo('计算推广奖'.($this->_sysConfig['openTG']['VALUE']?'完成':'关闭').',耗时:' . round($t5 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  193. $this->_updatePercent(20);
  194. // if($this->_sysConfig['openXF']['VALUE']) {
  195. // if( $this->_sysConfig['consumeRecPercent']['VALUE'] > 0 ) {
  196. // $this->calcBonusXFToRec();
  197. // }
  198. // if( $this->_sysConfig['consumeSelfPercent']['VALUE'] > 0 ) {
  199. // $this->calcBonusXFToSelf();
  200. // }
  201. // }
  202. // $t6 = microtime(true);
  203. // echo('计算消费奖'.($this->_sysConfig['openXF']['VALUE']?'完成':'关闭').',耗时:' . round($t6 - $t5, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  204. // $this->_updatePercent(25);
  205. //
  206. // if($this->_sysConfig['openYJ']['VALUE']) {
  207. // $this->calcBonusBdYJ();
  208. // }
  209. // $t7 = microtime(true);
  210. // echo('计算报单业绩奖'.($this->_sysConfig['openYJ']['VALUE']?'完成':'关闭').',耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  211. // $this->_updatePercent(30);
  212. //
  213. // if($this->_sysConfig['fxOpenYJ']['VALUE']) {
  214. // $this->calcBonusFxYJ();
  215. // }
  216. $t8 = microtime(true);
  217. // echo('计算复消业绩奖'.($this->_sysConfig['fxOpenYJ']['VALUE']?'完成':'关闭').',耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  218. // $this->_updatePercent(35);
  219. // 绩效奖/团队奖
  220. if($this->_sysConfig['openQY']['VALUE']) {
  221. $this->calcBonusQY();
  222. // $this->calcBonusBdQY();
  223. // $this->calcBonusFxQY();
  224. }
  225. $t9 = microtime(true);
  226. echo('计算团队奖'.($this->_sysConfig['openQY']['VALUE']?'完成':'关闭').',耗时:' . round($t9 - $t8, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  227. $this->_updatePercent(65);
  228. // if($this->_sysConfig['openGX']['VALUE']) {
  229. // $this->calcBonusGXBefore();
  230. // $this->calcBonusGX();
  231. // }
  232. // $t11 = microtime(true);
  233. // echo('计算共享奖'.($this->_sysConfig['openGX']['VALUE']?'完成':'关闭').',耗时:' . round($t11 - $t9, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  234. // $this->_updatePercent(68);
  235. //
  236. // if($this->_sysConfig['openGL']['VALUE']) {
  237. // $this->calcBonusBdGL();
  238. // }
  239. // $t13 = microtime(true);
  240. // echo('计算报单管理奖'.($this->_sysConfig['openGL']['VALUE']?'完成':'关闭').',耗时:' . round($t13 - $t11, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  241. // $this->_updatePercent(50);
  242. //
  243. // if($this->_sysConfig['fxOpenGL']['VALUE']) {
  244. // $this->calcBonusFxGL();
  245. // }
  246. // $t14 = microtime(true);
  247. // echo('计算复消管理奖'.($this->_sysConfig['fxOpenGL']['VALUE']?'完成':'关闭').',耗时:' . round($t14 - $t13, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  248. // $this->_updatePercent(70);
  249. //
  250. // if($this->_sysConfig['openYC']['VALUE']) {
  251. // $this->calcBonusYCStepOne();
  252. // $this->calcBonusYCStepTwo();
  253. // }
  254. // $t16 = microtime(true);
  255. // echo('计算荣衔奖'.($this->_sysConfig['openYC']['VALUE']?'完成':'关闭').',耗时:' . round($t16 - $t13, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  256. // $this->_updatePercent(55);
  257. //
  258. // if($this->_sysConfig['openVIP']['VALUE']) {
  259. // $this->calcBonusVIP();
  260. // }
  261. // $t17 = microtime(true);
  262. // echo('计算VIP奖'.($this->_sysConfig['openVIP']['VALUE']?'完成':'关闭').',耗时:' . round($t17 - $t16, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  263. // $this->_updatePercent(60);
  264. //
  265. // if($this->_sysConfig['openJXS']['VALUE']) {
  266. // $this->calcBonusStandard();
  267. // }
  268. // $t18 = microtime(true);
  269. // echo('计算达标奖'.($this->_sysConfig['openJXS']['VALUE']?'完成':'关闭').',耗时:' . round($t18 - $t17, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  270. // $this->_updatePercent(65);
  271. $t19 = microtime(true);
  272. // 蓝星奖入库,实际上是插入有奖金会员数据缓存中.
  273. echo('计算蓝星奖开始,' . date('Y-m-d H:i:s', $t19) . PHP_EOL);
  274. // 调用存储过程,计算蓝星管理奖金
  275. $this->calcBsProcedure();
  276. // 将有【蓝星业绩奖金】的用户加入到有奖金缓存用户中
  277. $this->calcBonusBsYJ();
  278. // 将有【蓝星管理奖金】的用户加入到有奖金缓存用户中
  279. $this->calcBonusBsGL();
  280. $t20 = microtime(true);
  281. echo('计算蓝星奖'.($this->_sysConfig['openGL']['VALUE']?'完成':'关闭').',耗时:' . round($t20 - $t19, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  282. $this->_updatePercent(67);
  283. // $this->calcBonusTourism($this->_sysConfig['openTourism']);
  284. $t21 = microtime(true);
  285. // echo('计算旅游奖' . ($this->_sysConfig['openTourism']['VALUE'] ? '完成' : '关闭') . ',耗时:' . round($t21 - $t20, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  286. // $this->_updatePercent(68);
  287. $this->calcBonusVilla();
  288. $t22 = microtime(true);
  289. echo('计算房奖' . ($this->_sysConfig['openVilla']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t22 - $t21, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  290. $this->_updatePercent(69);
  291. $this->calcBonusGarage();
  292. $t23 = microtime(true);
  293. echo('计算车奖' . ($this->_sysConfig['openGarage']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t23 - $t22, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  294. $this->_updatePercent(69);
  295. // 计算季度奖
  296. $this->calcQuarter();
  297. // 将用户写入缓存
  298. $this->calcQuarterUser();
  299. $t24 = microtime(true);
  300. echo('计算季度奖' . ($this->_sysConfig['openQuarter']['VALUE'] ? '完成' : '关闭').',耗时:' . round($t24 - $t23, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
  301. //把奖金会员写入缓存
  302. $this->loopMonthBonusUserFromDbToCache();
  303. $t30 = microtime(true);
  304. echo('奖金会员写入缓存完成,耗时:' . round($t30 - $t22, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  305. $this->_updatePercent(70);
  306. //奖金写库
  307. // 这里增加新的奖金入库操作.
  308. $this->loopBonusUsers();
  309. // 入库完成,将各个奖金计算流水会员聘级,更新成蓝星奖当时计算的聘级
  310. $this->loopCalcBlueEmpLv();
  311. $this->_updatePercent(75);
  312. unset($calcWrite);
  313. $t31 = microtime(true);
  314. echo('奖金写库操作完成,耗时:' . round($t31 - $t30, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  315. //把本期奖金会员入库 - 把缓存中的月奖用户信息存到数据库.存储过程的入库不在这里进行,这里代码取的缓存,存储过程没有缓存,在上面进行入库
  316. $this->loopMonthBonusUserToDb();
  317. $t32 = microtime(true);
  318. echo('奖金会员入库完成,耗时:' . round($t32 - $t31, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  319. $this->_updatePercent(80);
  320. // 计算基础积分,不可以奖金入库之前计算这样可能会丢掉只有本期的奖金的会员
  321. $this->calcBaseScore();
  322. $this->_updatePercent(90);
  323. $t33 = microtime(true);
  324. echo('计算基础积分,耗时:' . round($t33 - $t32, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  325. //积分入库
  326. $this->loopWriteScore();
  327. $this->_updatePercent(100);
  328. $t34 = microtime(true);
  329. echo('积分写库操作完成,耗时:' . round($t34 - $t33, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  330. $t35 = microtime(true);
  331. echo('结算全部完成,共耗时:' . round($t35 - $t34, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL . PHP_EOL);
  332. } catch (\Exception $e) {
  333. $this->errorCalcTask();
  334. LoggerTool::error('calcBonus' . sprintf('File【%s】, Line【%s】, Msg【%s】', $e->getFile(), $e->getLine(), $e->getMessage()));
  335. $this->addError('calcBonus', sprintf('%s',$e->getMessage()));
  336. return false;
  337. }
  338. return true;
  339. }
  340. /**
  341. * 结算完成
  342. */
  343. public function endCalcTask() {
  344. // 更新结算状态
  345. $this->setCalcStatus('end');
  346. }
  347. /**
  348. * 结算错误
  349. */
  350. public function errorCalcTask() {
  351. // 清空所有本期结算用到的缓存
  352. CalcCache::clearCalcBonusCache($this->_periodNum);
  353. // 更新结算状态
  354. $this->setCalcStatus('fail');
  355. }
  356. /**
  357. * 初始化结算任务
  358. * @throws \yii\db\Exception
  359. */
  360. public function initCalcTask() {
  361. $this->_sysConfig = Cache::getSystemConfig();
  362. $this->_decLevelConfig = Cache::getDecLevelConfig();
  363. $this->_empLevelConfig = Cache::getEmpLevelConfig();
  364. $this->_starCrownLevelConfig = Cache::getStarCrownLevelConfig();
  365. $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
  366. $periodNum = $this->_periodNum;
  367. // 获取本年月和上年月
  368. $periodObj = Period::instance();
  369. $periodDataArr = $periodObj->setPeriodNum($periodNum);
  370. $this->_periodId = $periodDataArr['ID'];
  371. $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
  372. $this->_calcYear = $periodObj->getYear($periodNum);
  373. $this->_calcMonth = $periodObj->getMonth($periodNum);
  374. $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
  375. $this->_calcMonthPeriodNumCount = $periodObj->getYearMonthAllPeriodNumCount($this->_calcYear, $this->_calcMonth);
  376. $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
  377. $this->_lastCalcYear = $lastYearMonthArr['year'];
  378. $this->_lastCalcMonth = $lastYearMonthArr['month'];
  379. $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
  380. $this->_lastPeriodNum = $periodNum - 1;
  381. if (Period::isExistsPeriodNum($this->_lastPeriodNum)) {
  382. $this->_lastPeriodYear = $periodObj->getYear($this->_lastPeriodNum);
  383. $this->_lastPeriodMonth = $periodObj->getMonth($this->_lastPeriodNum);
  384. $this->_lastPeriodYearMonth = $periodObj->getYearMonth($this->_lastPeriodNum);
  385. } else {
  386. $this->_lastPeriodYear = 0;
  387. $this->_lastPeriodMonth = 0;
  388. $this->_lastPeriodYearMonth = 0;
  389. }
  390. $this->_cfTotalPercent = CalcCache::getCFTotalPercent($this->_periodNum);
  391. $this->_lxTotalPercent = CalcCache::getLXTotalPercent($this->_periodNum);
  392. $this->_pvRatio = $this->_sysConfig['pvRatio']['VALUE'];
  393. if($perfCompany = PerfCompany::findOne(['CALC_MONTH' => $this->_calcYearMonth])){
  394. $this->_companyMonthPerf = $perfCompany['PV'];
  395. }
  396. }
  397. /**
  398. * 设置结算状态
  399. * @param $type
  400. * start|end|fail
  401. */
  402. public function setCalcStatus($type) {
  403. if ($type == 'start') {
  404. Period::updateAll(['IS_CALCING' => 1, 'IS_CALCULATED' => Period::CALCULATE_NONE, 'CALCULATE_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  405. } elseif ($type == 'end') {
  406. Period::updateAll(['IS_CALCING' => 0, 'IS_CALCULATED' => Period::CALCULATE_FINISH, 'CALCULATED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  407. } elseif ($type == 'fail') {
  408. Period::updateAll(['IS_CALCING' => 0, 'IS_CALCULATED' => Period::CALCULATE_FAIL, 'CALCULATED_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  409. }
  410. }
  411. /**
  412. * 清空相关表数据
  413. */
  414. public function clearCalcTableData() {
  415. // 奖金表
  416. CalcBonus::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  417. CalcBonusQY::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  418. CalcBonusBD::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  419. CalcBonusTG::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  420. CalcBonusYJ::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  421. CalcBonusGX::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  422. CalcBonusGL::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  423. // 月结时要清空的数据
  424. if ($this->_isCalcMonth) {
  425. CalcBonusYC::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  426. CalcBonusVIP::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  427. CalcBonusStandard::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  428. ScoreMonth::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  429. CalcBonusTourism::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  430. CalcBonusGarage::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  431. CalcBonusVilla::pageDeleteAll('PERIOD_NUM='.$this->_periodNum);
  432. }
  433. }
  434. /**
  435. * === 奖金结算部分 ===
  436. */
  437. /**
  438. * 服务奖
  439. * @param int $offset
  440. * @return bool
  441. * @throws \yii\db\Exception
  442. */
  443. public function calcBonusBD(int $offset = 0) {
  444. $periodNum = $this->_periodNum;
  445. // 从缓存获取分页有业绩的会员信息
  446. $allData = CalcCache::getHasBDUsers($this->_periodNum, $offset, $this->_limit);
  447. if ($allData) {
  448. $insertBonusData = [];
  449. foreach ($allData as $userId) {
  450. $decInfo = CalcCache::getBDUsersInfo($userId, $this->_periodNum);
  451. if( !$decInfo ) continue;
  452. //服务奖使用报单原金额
  453. $decBonus = Tool::formatPrice($decInfo['DEC_AMOUNT'] * $this->_sysConfig['decPercent']['VALUE'] / 100);
  454. if ($decBonus <= 0) continue;
  455. $bonusUserId = $decInfo['DEC_ID'];
  456. if( !$bonusUserId ) continue;
  457. // 获取会员的报单级别
  458. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  459. //总金额限制
  460. $decBonus = $this->bonusTotalLimit($decBonus, $bonusUserId, $bonusUserInfo['REC_NUM'], $bonusUserInfo['ZC_AMOUNT']);
  461. if( $decBonus <= 0 ) continue;
  462. //扣除相应的复消积分和管理费
  463. $deductData = $this->deduct($bonusUserId, $decBonus);
  464. // 把对碰后的奖金存入缓存中
  465. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_BD', $decBonus, $deductData);
  466. //来源会员信息
  467. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  468. //服务奖流水
  469. $insertBonusData[] = [
  470. 'ID' => SnowFake::instance()->generateId(),
  471. 'USER_ID' => $bonusUserId,
  472. 'LAST_DEC_LV' => $bonusUserInfo['DEC_LV'],
  473. 'LAST_EMP_LV' => $bonusUserInfo['EMP_LV'],
  474. 'LAST_STATUS' => $bonusUserInfo['STATUS'],
  475. 'FROM_USER_ID' => $userId,
  476. 'LAST_FROM_DEC_LV' => $fromUserInfo['DEC_LV'],
  477. 'LAST_FROM_EMP_LV' => $fromUserInfo['EMP_LV'],
  478. 'LAST_FROM_STATUS' => $fromUserInfo['STATUS'],
  479. 'AMOUNT' => $deductData['surplus'],
  480. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  481. 'MANAGE_TAX' => $deductData['manageTax'],
  482. 'ORI_BONUS' => $decBonus,
  483. 'PERIOD_NUM' => $this->_periodNum,
  484. 'CALC_YEAR' => $this->_calcYear,
  485. 'CALC_MONTH' => $this->_calcYearMonth,
  486. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  487. 'CREATED_AT' => Date::nowTime(),
  488. 'LOGS' => json_encode([
  489. 'decInfoArr' => $decInfo,
  490. 'decPercentConfig' => $this->_sysConfig['decPercent']['VALUE'],
  491. 'recNum' => $bonusUserInfo['REC_NUM'],
  492. 'decAmount' => $bonusUserInfo['ZC_AMOUNT'],
  493. ]),
  494. ];
  495. unset($decInfo, $decBonus, $bonusUserId, $bonusUserInfo, $userId, $deductData, $fromUserInfo);
  496. }
  497. CalcBonusBD::batchInsert($insertBonusData);
  498. unset($allData, $insertBonusData);
  499. return $this->calcBonusBD($offset + $this->_limit);
  500. }
  501. unset($allData);
  502. return true;
  503. }
  504. /**
  505. * 推广奖
  506. * @param int $offset
  507. * @return bool
  508. * @throws \yii\db\Exception
  509. */
  510. public function calcBonusTG(int $offset = 0) {
  511. $periodNum = $this->_periodNum;
  512. // 从缓存获取分页有业绩的会员信息
  513. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  514. if ($allData) {
  515. $insertBonusData = [];
  516. foreach ($allData as $userId) {
  517. // 从缓存中获取会员的业绩信息
  518. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  519. if( !$perfData ) continue;
  520. //个人业绩都算推荐奖,包括报单和复消、二次购物
  521. $perfPv = $perfData['PV_PCS_ZC'] ?? 0;
  522. if( $perfPv <= 0 ) continue;
  523. //推广奖使用个人PCS
  524. $recBonus = Tool::formatPrice($perfPv * $this->_sysConfig['recPercent']['VALUE'] / 100);
  525. if ($recBonus <= 0) continue;
  526. // 把对碰后的奖金存入缓存中
  527. $perfUserInfo = CalcCache::getUserInfo($userId, $periodNum);
  528. $bonusUserId = $perfUserInfo['REC_UID'] ?? '';
  529. if( !$bonusUserId ) continue;
  530. // 获取会员的报单级别
  531. $userBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  532. //判断级别上限
  533. // $recBonus = $this->declarationLevelCap($recBonus, $bonusUserId, $userBaseInfo['DEC_LV']);
  534. // if( $recBonus <= 0 ) continue;
  535. $recBonus = $this->bonusTotalLimit($recBonus, $bonusUserId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  536. if( $recBonus <= 0 ) continue;
  537. //扣除相应的复消积分和管理费
  538. $deductData = $this->deduct($bonusUserId, $recBonus);
  539. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_TG', $recBonus, $deductData);
  540. //来源会员信息
  541. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  542. //推广奖流水
  543. $insertBonusData[] = [
  544. 'ID' => SnowFake::instance()->generateId(),
  545. 'USER_ID' => $bonusUserId,
  546. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  547. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  548. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  549. 'FROM_USER_ID' => $userId,
  550. 'LAST_FROM_DEC_LV' => $fromUserInfo['DEC_LV'],
  551. 'LAST_FROM_EMP_LV' => $fromUserInfo['EMP_LV'],
  552. 'LAST_FROM_STATUS' => $fromUserInfo['STATUS'],
  553. 'AMOUNT' => $deductData['surplus'],
  554. 'ORI_BONUS' => $recBonus,
  555. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  556. 'MANAGE_TAX' => $deductData['manageTax'],
  557. 'PERIOD_NUM' => $this->_periodNum,
  558. 'CALC_YEAR' => $this->_calcYear,
  559. 'CALC_MONTH' => $this->_calcYearMonth,
  560. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  561. 'CREATED_AT' => Date::nowTime(),
  562. 'LOGS' => json_encode([
  563. 'perfPv' => $perfPv,
  564. 'recPercentConfig' => $this->_sysConfig['recPercent']['VALUE'],
  565. 'recNum' => $userBaseInfo['REC_NUM'],
  566. 'decAmount' => $userBaseInfo['ZC_AMOUNT'],
  567. 'decLevel' => $userBaseInfo['DEC_LV'],
  568. ]),
  569. ];
  570. unset($perfData, $perfPv, $perfUserInfo, $recBonus, $bonusUserId, $userBaseInfo, $userId, $deductData, $fromUserInfo);
  571. }
  572. CalcBonusTG::batchInsert($insertBonusData);
  573. unset($allData, $insertBonusData);
  574. return $this->calcBonusTG($offset + $this->_limit);
  575. }
  576. unset($allData);
  577. return true;
  578. }
  579. /**
  580. * 消费奖-推荐人
  581. * @param int $offset
  582. * @return bool
  583. * @throws \yii\db\Exception
  584. */
  585. public function calcBonusXFToRec(int $offset = 0) {
  586. $periodNum = $this->_periodNum;
  587. // 从缓存获取分页有业绩的会员信息
  588. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  589. if ($allData) {
  590. $insertBonusData = [];
  591. foreach ($allData as $userId) {
  592. // 从缓存中获取会员的业绩信息
  593. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  594. if( !$perfData ) continue;
  595. //个人业绩都算推荐奖,包括报单和复消、二次购物
  596. $perfPv = $perfData['PV_PCS_FX'] ?? 0;
  597. if( $perfPv <= 0 ) continue;
  598. //推广奖使用个人PCS
  599. $recBonus = Tool::formatPrice($perfPv * $this->_sysConfig['consumeRecPercent']['VALUE'] / 100);
  600. if ($recBonus <= 0) continue;
  601. // 把对碰后的奖金存入缓存中
  602. $perfUserInfo = CalcCache::getUserInfo($userId, $periodNum);
  603. $bonusUserId = $perfUserInfo['REC_UID'] ?? '';
  604. if( !$bonusUserId ) continue;
  605. // 获取会员的报单级别
  606. $userBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  607. //判断级别上限
  608. // $recBonus = $this->declarationLevelCap($recBonus, $bonusUserId, $userBaseInfo['DEC_LV']);
  609. // if( $recBonus <= 0 ) continue;
  610. $recBonus = $this->bonusTotalLimit($recBonus, $bonusUserId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  611. if( $recBonus <= 0 ) continue;
  612. //扣除相应的复消积分和管理费
  613. $deductData = $this->deduct($bonusUserId, $recBonus);
  614. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_XF', $recBonus, $deductData);
  615. //来源会员信息
  616. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  617. //推广奖流水
  618. $insertBonusData[] = [
  619. 'ID' => SnowFake::instance()->generateId(),
  620. 'USER_ID' => $bonusUserId,
  621. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  622. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  623. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  624. 'FROM_USER_ID' => $userId,
  625. 'LAST_FROM_DEC_LV' => $fromUserInfo['DEC_LV'],
  626. 'LAST_FROM_EMP_LV' => $fromUserInfo['EMP_LV'],
  627. 'LAST_FROM_STATUS' => $fromUserInfo['STATUS'],
  628. 'AMOUNT' => $deductData['surplus'],
  629. 'ORI_BONUS' => $recBonus,
  630. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  631. 'MANAGE_TAX' => $deductData['manageTax'],
  632. 'PERIOD_NUM' => $this->_periodNum,
  633. 'CALC_YEAR' => $this->_calcYear,
  634. 'CALC_MONTH' => $this->_calcYearMonth,
  635. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  636. 'CREATED_AT' => Date::nowTime(),
  637. 'LOGS' => json_encode([
  638. 'perfPv' => $perfPv,
  639. 'recPercentConfig' => $this->_sysConfig['consumeRecPercent']['VALUE'],
  640. 'recNum' => $userBaseInfo['REC_NUM'],
  641. 'decAmount' => $userBaseInfo['ZC_AMOUNT'],
  642. 'decLevel' => $userBaseInfo['DEC_LV'],
  643. 'bonusTotalLimit' => [
  644. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  645. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  646. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  647. ],
  648. ]),
  649. ];
  650. unset($perfData, $perfPv, $perfUserInfo, $recBonus, $bonusUserId, $userBaseInfo, $userId, $deductData, $fromUserInfo);
  651. }
  652. CalcBonusXF::batchInsert($insertBonusData);
  653. unset($allData, $insertBonusData);
  654. return $this->calcBonusXFToRec($offset + $this->_limit);
  655. }
  656. unset($allData);
  657. return true;
  658. }
  659. /**
  660. * 消费奖-自己
  661. * @param int $offset
  662. * @return bool
  663. * @throws \yii\db\Exception
  664. */
  665. public function calcBonusXFToSelf(int $offset = 0) {
  666. $periodNum = $this->_periodNum;
  667. // 从缓存获取分页有业绩的会员信息
  668. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  669. if ($allData) {
  670. $insertBonusData = [];
  671. foreach ($allData as $userId) {
  672. // 从缓存中获取会员的业绩信息
  673. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  674. if( !$perfData ) continue;
  675. //个人业绩都算推荐奖,包括报单和复消、二次购物
  676. $perfPv = $perfData['PV_PCS_FX'] ?? 0;
  677. if( $perfPv <= 0 ) continue;
  678. //推广奖使用个人PCS
  679. $recBonus = Tool::formatPrice($perfPv * $this->_sysConfig['consumeSelfPercent']['VALUE'] / 100);
  680. if ($recBonus <= 0) continue;
  681. // 把对碰后的奖金存入缓存中
  682. // $perfUserInfo = CalcCache::getUserInfo($userId, $periodNum);
  683. $bonusUserId = $userId;
  684. if( !$bonusUserId ) continue;
  685. // 获取会员的报单级别
  686. $userBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  687. //判断级别上限
  688. // $recBonus = $this->declarationLevelCap($recBonus, $bonusUserId, $userBaseInfo['DEC_LV']);
  689. // if( $recBonus <= 0 ) continue;
  690. $recBonus = $this->bonusTotalLimit($recBonus, $bonusUserId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  691. if( $recBonus <= 0 ) continue;
  692. //扣除相应的复消积分和管理费
  693. $deductData = $this->deduct($bonusUserId, $recBonus);
  694. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_XF', $recBonus, $deductData);
  695. //来源会员信息
  696. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  697. //推广奖流水
  698. $insertBonusData[] = [
  699. 'ID' => SnowFake::instance()->generateId(),
  700. 'USER_ID' => $bonusUserId,
  701. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  702. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  703. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  704. 'FROM_USER_ID' => $userId,
  705. 'LAST_FROM_DEC_LV' => $fromUserInfo['DEC_LV'],
  706. 'LAST_FROM_EMP_LV' => $fromUserInfo['EMP_LV'],
  707. 'LAST_FROM_STATUS' => $fromUserInfo['STATUS'],
  708. 'AMOUNT' => $deductData['surplus'],
  709. 'ORI_BONUS' => $recBonus,
  710. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  711. 'MANAGE_TAX' => $deductData['manageTax'],
  712. 'PERIOD_NUM' => $this->_periodNum,
  713. 'CALC_YEAR' => $this->_calcYear,
  714. 'CALC_MONTH' => $this->_calcYearMonth,
  715. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  716. 'CREATED_AT' => Date::nowTime(),
  717. 'LOGS' => json_encode([
  718. 'perfPv' => $perfPv,
  719. 'recPercentConfig' => $this->_sysConfig['consumeSelfPercent']['VALUE'],
  720. 'recNum' => $userBaseInfo['REC_NUM'],
  721. 'decAmount' => $userBaseInfo['ZC_AMOUNT'],
  722. 'decLevel' => $userBaseInfo['DEC_LV'],
  723. 'bonusTotalLimit' => [
  724. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  725. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  726. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  727. ],
  728. ]),
  729. ];
  730. unset($perfData, $perfPv, $recBonus, $bonusUserId, $userBaseInfo, $userId, $deductData, $fromUserInfo);
  731. }
  732. CalcBonusXF::batchInsert($insertBonusData);
  733. unset($allData, $insertBonusData);
  734. return $this->calcBonusXFToSelf($offset + $this->_limit);
  735. }
  736. unset($allData);
  737. return true;
  738. }
  739. /**
  740. * 服务奖第一步
  741. * @param int $offset
  742. * @return bool
  743. * @throws \yii\db\Exception
  744. */
  745. public function calcBonusBDStepOne(int $offset = 0) {
  746. echo sprintf("时间:[%s]服务奖第【1】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  747. $periodNum = $this->_periodNum;
  748. // 从缓存获取分页有业绩的会员信息
  749. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  750. if ($allData) {
  751. $insertBonusData = [];
  752. foreach ($allData as $userId) {
  753. // 从缓存中获取会员的业绩信息
  754. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  755. if( !$perfData ) continue;
  756. //
  757. $decRoleBonusFrom = explode(',', $this->_sysConfig['decRoleBonusFrom']['VALUE']);
  758. $validPvPcs = 0;
  759. foreach ($decRoleBonusFrom as $orderType) {
  760. $orderTypeName = sprintf('PV_PCS_%s', $orderType);
  761. $orderTypeValue = $perfData[$orderTypeName] ?? 0;
  762. $coefficientName = self::ORDER_TYPE_TO_FW_COEFFICIENT[$orderType];
  763. $coefficient = $this->_sysConfig[$coefficientName]['VALUE'] ?? 1;
  764. $validPvPcs += $orderTypeValue * $coefficient;
  765. unset($orderType, $orderTypeName, $orderTypeValue, $coefficientName, $coefficient);
  766. }
  767. unset($perfData, $decRoleBonusFrom);
  768. if ( $validPvPcs <= 0 ) continue;
  769. // 查询会员产生时,填写的报单中心
  770. $bonusUserId = DecOrder::find()->where('TO_USER_ID=:TO_USER_ID', [':TO_USER_ID' => $userId])->select('DEC_ID')->column();
  771. echo 'BonusCalcFw. ' . json_encode(['bonusCalc', $userId, $bonusUserId]);
  772. //判断parent的报单中心级别 和 服务奖比例
  773. //计算级别之后更新过userInfo的缓存,缓存中级别发生了变化
  774. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  775. $isDec = $bonusUserInfo['IS_DEC'];
  776. if ($isDec == 0) {
  777. return self::LOOP_CONTINUE; // 如果不是报单中心则跳过循环
  778. }
  779. $decRoleId = $bonusUserInfo['DEC_ROLE_ID'];
  780. if( !$decRoleId ) return self::LOOP_CONTINUE;
  781. if( !isset($this->_decRoleConfig[$decRoleId]) ) return self::LOOP_CONTINUE;
  782. // 取报单中心级别对应的拿奖比例
  783. $parentDecRoleLevel = $this->_decRoleConfig[$decRoleId];
  784. $parentFwBonusPercent = $parentDecRoleLevel['FW_BONUS_PERCENT'] ?? 0;
  785. $cacheMaxPercent = CalcCache::fwMaxBonusPercent($userId, $this->_periodNum);
  786. $diffPercent = $parentFwBonusPercent - $cacheMaxPercent;
  787. if( $diffPercent <= 0 ) return self::LOOP_CONTINUE;
  788. $fwBonus = $validPvPcs * $diffPercent / 100;
  789. if( $fwBonus <= 0 ) return self::LOOP_CONTINUE;
  790. //给本人添加服务奖比例
  791. CalcCache::fwMaxBonusPercent($userId, $this->_periodNum, $parentFwBonusPercent);
  792. //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  793. CalcCache::saveFwBonusList($bonusUserId, $this->_periodNum, $fwBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$validPvPcs]);
  794. CalcCache::addHasFwBonusUsers($bonusUserId, $this->_periodNum);
  795. // $this->loopRelationParentDo($userId, function ($parent) use($userId, $validPvPcs) {
  796. // //判断parent的报单中心级别 和 服务奖比例
  797. // $bonusUserId = $parent['PARENT_UID'];
  798. // //计算级别之后更新过userInfo的缓存,缓存中级别发生了变化
  799. // $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  800. // $isDec = $bonusUserInfo['IS_DEC'];
  801. // if($isDec == 0) return self::LOOP_CONTINUE;
  802. // $decRoleId = $bonusUserInfo['DEC_ROLE_ID'];
  803. // if( !$decRoleId ) return self::LOOP_CONTINUE;
  804. // if( !isset($this->_decRoleConfig[$decRoleId]) ) return self::LOOP_CONTINUE;
  805. //
  806. // $parentDecRoleLevel = $this->_decRoleConfig[$decRoleId];
  807. // $parentFwBonusPercent = $parentDecRoleLevel['FW_BONUS_PERCENT'] ?? 0;
  808. // $cacheMaxPercent = CalcCache::fwMaxBonusPercent($userId, $this->_periodNum);
  809. // $diffPercent = $parentFwBonusPercent - $cacheMaxPercent;
  810. // if( $diffPercent <= 0 ) return self::LOOP_CONTINUE;
  811. //
  812. // $fwBonus = $validPvPcs * $diffPercent / 100;
  813. // if( $fwBonus <= 0 ) return self::LOOP_CONTINUE;
  814. //
  815. // //给本人添加服务奖比例
  816. // CalcCache::fwMaxBonusPercent($userId, $this->_periodNum, $parentFwBonusPercent);
  817. // //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  818. // CalcCache::saveFwBonusList($bonusUserId, $this->_periodNum, $fwBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$validPvPcs]);
  819. // CalcCache::addHasFwBonusUsers($bonusUserId, $this->_periodNum);
  820. //
  821. // //达到最大的比例就不在向上找了
  822. //// if( $parentFwBonusPercent >= $maxLevelPercent ) return self::LOOP_FINISH;
  823. // unset($bonusUserId, $bonusUserInfo, $isDec, $decRoleId, $parentDecRoleLevel, $parentFwBonusPercent, $cacheMaxPercent, $diffPercent, $fwBonus);
  824. // });
  825. unset($userId, $validPvPcs);
  826. }
  827. unset($allData, $insertBonusData);
  828. return $this->calcBonusBDStepOne($offset + $this->_limit);
  829. }
  830. unset($allData);
  831. return true;
  832. }
  833. /**
  834. * 服务奖第二步
  835. * @param int $offset
  836. * @return bool
  837. * @throws \yii\db\Exception
  838. */
  839. public function calcBonusBDStepTwo(int $offset = 0) {
  840. echo sprintf("时间:[%s]服务奖第【2】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  841. $allData = CalcCache::getHasFwBonusUsers($this->_periodNum, $offset, $this->_limit);
  842. if ($allData) {
  843. $insertBonusData = [];
  844. foreach ($allData as $userId) {
  845. $fwBonusData = CalcCache::getFwBonusList($userId, $this->_periodNum);
  846. if( !$fwBonusData ) continue;
  847. $fwBonus = $fwBonusData['fwBonus'] ?? 0;
  848. if( $fwBonus <=0 ) continue;
  849. //总金额限制
  850. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  851. $fwBonus = $this->bonusTotalLimit($fwBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  852. if( $fwBonus <= 0 ) continue;
  853. //扣除相应的复消积分和管理费
  854. // $deductData = $this->deduct($userId, $fwBonus);
  855. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_BD', $fwBonus);
  856. $decRoleId = $userBaseInfo['DEC_ROLE_ID'];
  857. $insertBonusData[] = [
  858. 'ID' => SnowFake::instance()->generateId(),
  859. 'USER_ID' => $userId,
  860. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  861. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  862. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  863. 'FROM_USER_ID' => $userId,
  864. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  865. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  866. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  867. 'AMOUNT' => $fwBonus,
  868. 'ORI_BONUS' => $fwBonus,
  869. 'RECONSUME_POINTS' => 0,
  870. 'MANAGE_TAX' => 0,
  871. 'PERIOD_NUM' => $this->_periodNum,
  872. 'CALC_YEAR' => $this->_calcYear,
  873. 'CALC_MONTH' => $this->_calcYearMonth,
  874. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  875. 'CREATED_AT' => Date::nowTime(),
  876. 'LOGS' => json_encode([
  877. 'decRoleId' => $decRoleId,
  878. ])
  879. // 'FROM_DATA' => json_encode($ycBonusData['fromData']),
  880. ];
  881. unset($userId, $fwBonusData, $userBaseInfo, $decRoleId, $fwBonus);
  882. }
  883. CalcBonusBD::batchInsert($insertBonusData);
  884. unset($insertBonusData, $allData);
  885. $this->calcBonusBDStepTwo($offset + $this->_limit);
  886. }
  887. unset($allData);
  888. return true;
  889. }
  890. /**
  891. * 报单业绩奖
  892. * @param int $offset
  893. * @return bool
  894. * @throws \yii\db\Exception
  895. */
  896. public function calcBonusBdYJ(int $offset = 0) {
  897. $periodNum = $this->_periodNum;
  898. // 从缓存获取分页有业绩的会员信息
  899. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  900. if ($allData) {
  901. foreach ($allData as $userId) {
  902. $insertBonusData = [];
  903. // 从缓存中获取会员的业绩信息
  904. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  905. if( !$perfData ) continue;
  906. //个人业绩都算见点奖,包括报单和复消、二次购物
  907. $perfPv = $perfData['PV_PCS_ZC'] ?? 0;
  908. if( $perfPv <= 0 ) continue;
  909. //业绩奖使用报单PV
  910. // $oriPointsBonus = Tool::formatPrice($perfPv * $this->_sysConfig['pointsPercent']['VALUE'] / 100);
  911. // if ($oriPointsBonus <= 0) continue;
  912. //偶数层数
  913. $pointsEvenLayer = $this->_sysConfig['pointsLayer']['VALUE'];
  914. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  915. $userEmpLevel = $userBaseInfo['EMP_LV'];
  916. $netWorkParents = Cache::getAllNetworkParents($userId);
  917. foreach ($netWorkParents as $netWorkParent) {
  918. // $pointsBonus = $oriPointsBonus;
  919. //自已距顶端的深度减去父级距顶端的深度
  920. $diffLayer = $netWorkParent['TOP_DEEP'] - $netWorkParent['PARENT_DEEP'];
  921. if( $diffLayer <= 0) continue;
  922. if( $diffLayer > 2 * $pointsEvenLayer ) continue;
  923. if( $diffLayer % 2 == 1 ) continue;
  924. $pointsPercentName = sprintf('pointsPercent_%d', $diffLayer);
  925. if( isset($this->_sysConfig[$pointsPercentName]['VALUE']) ) {
  926. $diffLayerPercent = $this->_sysConfig[$pointsPercentName]['VALUE'];
  927. }else {
  928. $diffLayerPercent = $this->_sysConfig['pointsPercent']['VALUE'];
  929. }
  930. $pointsBonus = Tool::formatPrice($perfPv * $diffLayerPercent / 100);
  931. if( $pointsBonus <= 0 ) continue;
  932. // 把对碰后的奖金存入缓存中
  933. $bonusUserId = $netWorkParent['PARENT_UID'];
  934. if( !$bonusUserId ) continue;
  935. // 获取会员的报单级别
  936. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  937. //判断上限 包括级别奖金上限和总上限
  938. // $pointsBonus = $this->declarationLevelCap($pointsBonus, $bonusUserId, $bonusUserBaseInfo['DEC_LV']);
  939. // if( $pointsBonus <= 0 ) continue;
  940. //总金额限制
  941. $pointsBonus = $this->bonusTotalLimit($pointsBonus, $bonusUserId, $bonusUserBaseInfo['REC_NUM'], $bonusUserBaseInfo['ZC_AMOUNT']);
  942. if( $pointsBonus <= 0 ) continue;
  943. //扣除相应的复消积分和管理费
  944. $deductData = $this->deduct($bonusUserId, $pointsBonus);
  945. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_YJ', $pointsBonus, $deductData, CalcCache::FROM_MEANS_BD);
  946. //业绩奖流水
  947. $insertBonusData[] = [
  948. 'ID' => SnowFake::instance()->generateId(),
  949. 'USER_ID' => $bonusUserId,
  950. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  951. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  952. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  953. 'FROM_USER_ID' => $userId,
  954. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  955. 'LAST_FROM_EMP_LV' => $userEmpLevel,
  956. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  957. 'AMOUNT' => $deductData['surplus'],
  958. 'ORI_BONUS' => $pointsBonus,
  959. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  960. 'MANAGE_TAX' => $deductData['manageTax'],
  961. 'PERIOD_NUM' => $this->_periodNum,
  962. 'CALC_YEAR' => $this->_calcYear,
  963. 'CALC_MONTH' => $this->_calcYearMonth,
  964. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  965. 'CREATED_AT' => Date::nowTime(),
  966. 'LOGS' => json_encode([
  967. 'perfPv' => $perfPv,
  968. 'pointsLayerConfig' => $this->_sysConfig['pointsLayer']['VALUE'],
  969. 'pointsPercentConfig' => $diffLayerPercent,
  970. 'recNum' => $bonusUserBaseInfo['REC_NUM'],
  971. 'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
  972. 'decLevel' => $bonusUserBaseInfo['DEC_LV'],
  973. 'bonusTotalLimit' => [
  974. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  975. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  976. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  977. ],
  978. ]),
  979. ];
  980. unset($netWorkParent, $pointsBonus, $diffLayer, $bonusUserId, $bonusUserBaseInfo, $deductData, $diffLayerPercent, $pointsPercentName);
  981. }
  982. CalcBonusYJ::batchInsert($insertBonusData);
  983. unset($insertBonusData, $userId, $perfData, $perfPv, $oriPointsBonus, $pointsEvenLayer, $userBaseInfo, $userEmpLevel, $netWorkParents);
  984. }
  985. unset($allData);
  986. return $this->calcBonusBdYJ($offset + $this->_limit);
  987. }
  988. unset($allData);
  989. return true;
  990. }
  991. /**
  992. * 复消业绩奖
  993. * @param int $offset
  994. * @return bool
  995. * @throws \yii\db\Exception
  996. */
  997. public function calcBonusFxYJ(int $offset = 0) {
  998. $periodNum = $this->_periodNum;
  999. // 从缓存获取分页有业绩的会员信息
  1000. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  1001. if ($allData) {
  1002. foreach ($allData as $userId) {
  1003. $insertBonusData = [];
  1004. // 从缓存中获取会员的业绩信息
  1005. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  1006. if( !$perfData ) continue;
  1007. //个人业绩都算见点奖,包括报单和复消、二次购物
  1008. $perfPv = $perfData['PV_PCS_FX'] ?? 0;
  1009. if( $perfPv <= 0 ) continue;
  1010. //业绩奖使用报单PV
  1011. // $oriPointsBonus = Tool::formatPrice($perfPv * $this->_sysConfig['pointsPercent']['VALUE'] / 100);
  1012. // if ($oriPointsBonus <= 0) continue;
  1013. //偶数层数
  1014. $pointsEvenLayer = $this->_sysConfig['fxPointsLayer']['VALUE'];
  1015. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1016. $userEmpLevel = $userBaseInfo['EMP_LV'];
  1017. $netWorkParents = Cache::getAllNetworkParents($userId);
  1018. foreach ($netWorkParents as $netWorkParent) {
  1019. // $pointsBonus = $oriPointsBonus;
  1020. //自已距顶端的深度减去父级距顶端的深度
  1021. $diffLayer = $netWorkParent['TOP_DEEP'] - $netWorkParent['PARENT_DEEP'];
  1022. if( $diffLayer <= 0) continue;
  1023. if( $diffLayer > 2 * $pointsEvenLayer ) continue;
  1024. if( $diffLayer % 2 == 1 ) continue;
  1025. $pointsPercentName = sprintf('fxPointsPercent_%d', $diffLayer);
  1026. if( isset($this->_sysConfig[$pointsPercentName]['VALUE']) ) {
  1027. $diffLayerPercent = $this->_sysConfig[$pointsPercentName]['VALUE'];
  1028. }else {
  1029. $diffLayerPercent = $this->_sysConfig['fxPointsPercent']['VALUE'];
  1030. }
  1031. $pointsBonus = Tool::formatPrice($perfPv * $diffLayerPercent / 100);
  1032. if( $pointsBonus <= 0 ) continue;
  1033. // 把对碰后的奖金存入缓存中
  1034. $bonusUserId = $netWorkParent['PARENT_UID'];
  1035. if( !$bonusUserId ) continue;
  1036. // 获取会员的报单级别
  1037. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  1038. //判断上限 包括级别奖金上限和总上限
  1039. // $pointsBonus = $this->declarationLevelCap($pointsBonus, $bonusUserId, $bonusUserBaseInfo['DEC_LV']);
  1040. // if( $pointsBonus <= 0 ) continue;
  1041. //总金额限制
  1042. $pointsBonus = $this->bonusTotalLimit($pointsBonus, $bonusUserId, $bonusUserBaseInfo['REC_NUM'], $bonusUserBaseInfo['ZC_AMOUNT']);
  1043. if( $pointsBonus <= 0 ) continue;
  1044. //扣除相应的复消积分和管理费
  1045. $deductData = $this->deduct($bonusUserId, $pointsBonus);
  1046. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_YJ', $pointsBonus, $deductData, CalcCache::FROM_MEANS_FX);
  1047. //业绩奖流水
  1048. $insertBonusData[] = [
  1049. 'ID' => SnowFake::instance()->generateId(),
  1050. 'USER_ID' => $bonusUserId,
  1051. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  1052. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  1053. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  1054. 'FROM_USER_ID' => $userId,
  1055. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  1056. 'LAST_FROM_EMP_LV' => $userEmpLevel,
  1057. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  1058. 'AMOUNT' => $deductData['surplus'],
  1059. 'ORI_BONUS' => $pointsBonus,
  1060. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  1061. 'MANAGE_TAX' => $deductData['manageTax'],
  1062. 'PERIOD_NUM' => $this->_periodNum,
  1063. 'CALC_YEAR' => $this->_calcYear,
  1064. 'CALC_MONTH' => $this->_calcYearMonth,
  1065. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1066. 'CREATED_AT' => Date::nowTime(),
  1067. 'LOGS' => json_encode([
  1068. 'perfPv' => $perfPv,
  1069. 'pointsLayerConfig' => $this->_sysConfig['fxPointsLayer']['VALUE'],
  1070. 'pointsPercentConfig' => $diffLayerPercent,
  1071. 'recNum' => $bonusUserBaseInfo['REC_NUM'],
  1072. 'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
  1073. 'decLevel' => $bonusUserBaseInfo['DEC_LV'],
  1074. 'bonusTotalLimit' => [
  1075. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  1076. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  1077. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  1078. ],
  1079. ]),
  1080. ];
  1081. unset($netWorkParent, $pointsBonus, $diffLayer, $bonusUserId, $bonusUserBaseInfo, $deductData, $diffLayerPercent, $pointsPercentName);
  1082. }
  1083. CalcBonusYJ::batchInsert($insertBonusData);
  1084. unset($insertBonusData, $userId, $perfData, $perfPv, $oriPointsBonus, $pointsEvenLayer, $userBaseInfo, $userEmpLevel, $netWorkParents);
  1085. }
  1086. unset($allData);
  1087. return $this->calcBonusFxYJ($offset + $this->_limit);
  1088. }
  1089. unset($allData);
  1090. return true;
  1091. }
  1092. /**
  1093. * 团队奖
  1094. * @param int $offset
  1095. * @return bool
  1096. * @throws \yii\db\Exception
  1097. */
  1098. public function calcBonusQY(int $offset = 0) {
  1099. echo sprintf("时间:[%s]团队奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1100. $periodNum = $this->_periodNum;
  1101. // 从缓存获取分页有业绩的会员信息
  1102. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  1103. if ($allData) {
  1104. $insertBonusData = [];
  1105. foreach ($allData as $userId) {
  1106. // 从缓存中获取会员的业绩信息
  1107. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  1108. // 从缓存中获取会员的上期结余业绩信息
  1109. $pervSurplusPerf = CalcCache::surplusPerf($userId, $periodNum);
  1110. // 本期 + 上期结余
  1111. $perfArr = [
  1112. 'SURPLUS_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
  1113. 'SURPLUS_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
  1114. 'SURPLUS_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
  1115. 'SURPLUS_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
  1116. 'SURPLUS_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
  1117. ];
  1118. $oriPerfArr = [
  1119. 'perfArr' => $perfArr,
  1120. 'touchBonus' => 0,
  1121. ];
  1122. // 获取会员的报单级别
  1123. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1124. $decLevelConfig = $this->_decLevelConfig;
  1125. $nowDecLevelConfig = $decLevelConfig[$userBaseInfo['DEC_LV']];
  1126. // 对碰
  1127. $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $nowDecLevelConfig['QY_PERCENT']/100);
  1128. $touchPerfArr = [];
  1129. foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
  1130. $touchPerfArr[$keyR] = $perfR;
  1131. }
  1132. // 对碰完成后把结余的业绩存入本期业绩缓存中
  1133. CalcCache::nowPeriodPerf($userId, $periodNum, $touchPerfArr);
  1134. //更新数据库
  1135. PerfPeriod::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  1136. 'USER_ID' => $userId,
  1137. 'PERIOD_NUM' => $periodNum,
  1138. ]);
  1139. if ($touchBonusArr['touchBonus'] <= 0) continue;
  1140. $teamBonus = $touchBonusArr['touchBonus'];
  1141. $capBonusQy = $teamBonus; // 封顶前的奖金
  1142. //判断级别上限,个人奖金封顶限制
  1143. $teamBonus = $this->declarationLevelCap($teamBonus, $userId, $userBaseInfo['DEC_LV']);
  1144. if( $teamBonus <= 0 ) continue;
  1145. // 将封顶前的金额加入用户奖金缓存中,此金额不能发放(总奖金,总实际奖金)
  1146. CalcCache::bonus($userId, $periodNum, 'CAPPED_BONUS_QY', $capBonusQy);
  1147. $teamBonus = $this->bonusTotalLimit($teamBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  1148. if( $teamBonus <= 0 ) continue;
  1149. //扣除相应的复消积分和管理费
  1150. $deductData = $this->deduct($userId, $teamBonus);
  1151. // 取小腿值
  1152. $payLeg = min([$perfArr['SURPLUS_1L'], $perfArr['SURPLUS_2L']]);
  1153. // 计算荣衔星级
  1154. $starCrown = StarCrownLevel::getStarCrown($payLeg);
  1155. // 是否活跃
  1156. $isActive = $this->_isPerfActive($userId);
  1157. $oriBonus = $isActive ? $teamBonus : 0;
  1158. $lastCrownLv = $isActive ? $starCrown['ID'] : StarCrownLevel::getDefaultLevelId();
  1159. //团队奖流水
  1160. $insertBonusData[] = [
  1161. 'ID' => SnowFake::instance()->generateId(),
  1162. 'USER_ID' => $userId,
  1163. 'ORI_CAPPED_BONUS_QY' => $capBonusQy,
  1164. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  1165. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  1166. 'LAST_CROWN_LV' => $lastCrownLv,
  1167. 'CROWN_LV' => $userBaseInfo['CROWN_LV'],
  1168. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  1169. 'AMOUNT' => $deductData['surplus'],
  1170. 'ORI_BONUS' => $oriBonus,
  1171. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  1172. 'MANAGE_TAX' => $deductData['manageTax'],
  1173. 'PERIOD_NUM' => $this->_periodNum,
  1174. 'CALC_YEAR' => $this->_calcYear,
  1175. 'CALC_MONTH' => $this->_calcYearMonth,
  1176. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1177. 'CREATED_AT' => Date::nowTime(),
  1178. 'LOGS' => json_encode([
  1179. 'perfArr' => $perfArr,
  1180. 'touchPerfArrOri' => $touchBonusArr['perfArr'],
  1181. 'touchPerfArr' => $touchPerfArr,
  1182. 'nowDecLevelConfig' => $nowDecLevelConfig,
  1183. 'decLevel' => $userBaseInfo['DEC_LV'],
  1184. ]),
  1185. 'IS_ACTIVE' => (int)$isActive,
  1186. 'HOPE_CROWN_LV' => $starCrown['ID'],
  1187. 'HOPE_BONUS' => $teamBonus,
  1188. ];
  1189. // 星级放入缓存
  1190. CalcCache::addUserStarCrown($userId, $periodNum, $lastCrownLv);
  1191. if ($oriBonus > 0) {
  1192. // 把对碰后的奖金存入缓存中
  1193. CalcCache::bonus($userId, $periodNum, 'BONUS_QY', $oriBonus, $deductData);
  1194. }
  1195. unset($perfData, $pervSurplusPerf, $perfArr, $oriPerfArr, $touchPerfArr, $userBaseInfo, $decLevelConfig, $touchBonusArr, $userId, $nowDecLevelConfig, $teamBonus, $deductData);
  1196. }
  1197. CalcBonusQY::batchInsert($insertBonusData);
  1198. unset($allData, $insertBonusData);
  1199. return $this->calcBonusQY($offset + $this->_limit);
  1200. }
  1201. unset($allData);
  1202. return true;
  1203. }
  1204. /**
  1205. * 报单团队奖
  1206. * @param int $offset
  1207. * @return bool
  1208. * @throws \yii\db\Exception
  1209. */
  1210. public function calcBonusBdQY(int $offset = 0) {
  1211. echo sprintf("时间:[%s]报单团队奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1212. $periodNum = $this->_periodNum;
  1213. // 从缓存获取分页有业绩的会员信息
  1214. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  1215. if ($allData) {
  1216. $insertBonusData = [];
  1217. foreach ($allData as $userId) {
  1218. // 从缓存中获取会员的业绩信息
  1219. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  1220. // 从缓存中获取会员的上期结余业绩信息
  1221. $pervSurplusPerf = CalcCache::surplusPerf($userId, $periodNum);
  1222. // 本期 + 上期结余
  1223. $perfArr = [
  1224. 'SURPLUS_1L_ZC' => $perfData['PV_1L_ZC'] + $pervSurplusPerf['SURPLUS_1L_ZC'],
  1225. 'SURPLUS_2L_ZC' => $perfData['PV_2L_ZC'] + $pervSurplusPerf['SURPLUS_2L_ZC'],
  1226. 'SURPLUS_3L_ZC' => $perfData['PV_3L_ZC'] + $pervSurplusPerf['SURPLUS_3L_ZC'],
  1227. 'SURPLUS_4L_ZC' => $perfData['PV_4L_ZC'] + $pervSurplusPerf['SURPLUS_4L_ZC'],
  1228. 'SURPLUS_5L_ZC' => $perfData['PV_5L_ZC'] + $pervSurplusPerf['SURPLUS_5L_ZC'],
  1229. ];
  1230. $oriPerfArr = [
  1231. 'perfArr' => $perfArr,
  1232. 'touchBonus' => 0,
  1233. ];
  1234. // 获取会员的报单级别
  1235. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1236. $decLevelConfig = $this->_decLevelConfig;
  1237. $nowDecLevelConfig = $decLevelConfig[$userBaseInfo['DEC_LV']];
  1238. // 对碰
  1239. $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $nowDecLevelConfig['QY_PERCENT']/100);
  1240. $touchPerfArr = [];
  1241. foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
  1242. $touchPerfArr[$keyR] = $perfR;
  1243. }
  1244. // 对碰完成后把结余的业绩存入本期业绩缓存中
  1245. CalcCache::nowPeriodPerf($userId, $periodNum, $touchPerfArr);
  1246. //更新数据库
  1247. PerfPeriod::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  1248. 'USER_ID' => $userId,
  1249. 'PERIOD_NUM' => $periodNum,
  1250. ]);
  1251. if ($touchBonusArr['touchBonus'] <= 0) continue;
  1252. $teamBonus = $touchBonusArr['touchBonus'];
  1253. //判断级别上限
  1254. // $teamBonus = $this->declarationLevelCap($teamBonus, $userId, $userBaseInfo['DEC_LV']);
  1255. // if( $teamBonus <= 0 ) continue;
  1256. // $teamBonus = $this->bonusTotalLimit($teamBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  1257. // if( $teamBonus <= 0 ) continue;
  1258. //扣除相应的复消积分和管理费
  1259. // $deductData = $this->deduct($userId, $teamBonus);
  1260. // 把对碰后的奖金存入缓存中
  1261. CalcCache::bonus($userId, $periodNum, 'BONUS_QY_BD', $teamBonus);
  1262. unset($perfData, $pervSurplusPerf, $perfArr, $oriPerfArr, $touchPerfArr, $userBaseInfo, $decLevelConfig, $touchBonusArr, $userId, $nowDecLevelConfig, $teamBonus, $deductData);
  1263. }
  1264. unset($allData, $insertBonusData);
  1265. return $this->calcBonusBdQY($offset + $this->_limit);
  1266. }
  1267. unset($allData);
  1268. return true;
  1269. }
  1270. /**
  1271. * 复消团队奖
  1272. * @param int $offset
  1273. * @return bool
  1274. * @throws \yii\db\Exception
  1275. */
  1276. public function calcBonusFxQY(int $offset = 0) {
  1277. echo sprintf("时间:[%s]复消团队奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1278. $periodNum = $this->_periodNum;
  1279. // 从缓存获取分页有业绩的会员信息
  1280. $allData = CalcCache::getHasPerfUsers($this->_periodNum, $offset, $this->_limit);
  1281. if ($allData) {
  1282. $insertBonusData = [];
  1283. foreach ($allData as $userId) {
  1284. // 从缓存中获取会员的业绩信息
  1285. $perfData = CalcCache::nowPeriodPerf($userId, $periodNum);
  1286. // 从缓存中获取会员的上期结余业绩信息
  1287. $pervSurplusPerf = CalcCache::surplusPerf($userId, $periodNum);
  1288. // 本期 + 上期结余
  1289. $perfArr = [
  1290. 'SURPLUS_1L_FX' => $perfData['PV_1L_FX'] + $pervSurplusPerf['SURPLUS_1L_FX'],
  1291. 'SURPLUS_2L_FX' => $perfData['PV_2L_FX'] + $pervSurplusPerf['SURPLUS_2L_FX'],
  1292. 'SURPLUS_3L_FX' => $perfData['PV_3L_FX'] + $pervSurplusPerf['SURPLUS_3L_FX'],
  1293. 'SURPLUS_4L_FX' => $perfData['PV_4L_FX'] + $pervSurplusPerf['SURPLUS_4L_FX'],
  1294. 'SURPLUS_5L_FX' => $perfData['PV_5L_FX'] + $pervSurplusPerf['SURPLUS_5L_FX'],
  1295. ];
  1296. $oriPerfArr = [
  1297. 'perfArr' => $perfArr,
  1298. 'touchBonus' => 0,
  1299. ];
  1300. // 获取会员的报单级别
  1301. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1302. $decLevelConfig = $this->_decLevelConfig;
  1303. $nowDecLevelConfig = $decLevelConfig[$userBaseInfo['DEC_LV']];
  1304. // 对碰
  1305. $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $nowDecLevelConfig['QY_PERCENT']/100);
  1306. //大区封顶
  1307. $touchPerfArr = [];
  1308. foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
  1309. // if ($perfR > $nowDecLevelConfig['QY_BIG_CAP']) $perfR = $nowDecLevelConfig['QY_BIG_CAP'];
  1310. $touchPerfArr[$keyR] = $perfR;
  1311. }
  1312. // 对碰完成后把结余的业绩存入本期业绩缓存中
  1313. CalcCache::nowPeriodPerf($userId, $periodNum, $touchPerfArr);
  1314. //更新数据库
  1315. PerfPeriod::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [
  1316. 'USER_ID' => $userId,
  1317. 'PERIOD_NUM' => $periodNum,
  1318. ]);
  1319. if ($touchBonusArr['touchBonus'] <= 0) continue;
  1320. $teamBonus = $touchBonusArr['touchBonus'];
  1321. //判断级别上限
  1322. // $teamBonus = $this->declarationLevelCap($teamBonus, $userId, $userBaseInfo['DEC_LV']);
  1323. // if( $teamBonus <= 0 ) continue;
  1324. //
  1325. // $teamBonus = $this->bonusTotalLimit($teamBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  1326. // if( $teamBonus <= 0 ) continue;
  1327. //扣除相应的复消积分和管理费
  1328. // $deductData = $this->deduct($userId, $teamBonus);
  1329. // 把对碰后的奖金存入缓存中
  1330. CalcCache::bonus($userId, $periodNum, 'BONUS_QY_FX', $teamBonus);
  1331. unset($perfData, $pervSurplusPerf, $perfArr, $oriPerfArr, $touchPerfArr, $userBaseInfo, $decLevelConfig, $touchBonusArr, $userId, $nowDecLevelConfig, $teamBonus, $deductData);
  1332. }
  1333. unset($allData, $insertBonusData);
  1334. return $this->calcBonusFxQY($offset + $this->_limit);
  1335. }
  1336. unset($allData);
  1337. return true;
  1338. }
  1339. /**
  1340. * 计算共享奖之前的操作
  1341. * @param int $offset
  1342. * @return bool
  1343. */
  1344. public function calcBonusGXBefore(int $offset = 0) {
  1345. //获取所有激活会员
  1346. $allData = CalcCache::getActiveUsers($this->_periodNum, $offset, $this->_limit);
  1347. if ($allData) {
  1348. echo sprintf("时间:[%s]共享奖之前,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1349. foreach ($allData as $userId) {
  1350. //判断$userId 能否得共享奖
  1351. // //判断 是否本期小市场(安置关系)新增980pv 能否得奖
  1352. // if ( !$this->checkSmallMarketPerf($userId) ) {
  1353. // unset($userId);
  1354. // continue;
  1355. // }
  1356. // 20220407 小市场980判断->改成判断此期用户是否有原报单团队奖金
  1357. if ( !$this->checkHasOriBonusQyBd($userId) ) {
  1358. unset($userId);
  1359. continue;
  1360. }
  1361. //获取当前会员所有的推荐上级, 并查看是否有首单团队奖
  1362. $validDeep = 0;
  1363. $this->loopRelationParentDo($userId, function ($parent) use ($userId, &$validDeep) {
  1364. //判断$parent是否有首单团队奖
  1365. $parentBonus = CalcCache::bonus($parent['PARENT_UID'], $this->_periodNum);
  1366. if( $parentBonus['ORI_BONUS_QY_BD'] > 0 ) {
  1367. $validDeep += 1;
  1368. //记录得奖缓存
  1369. CalcCache::addShareBonusOneRelation($userId, $parent['PARENT_UID'], $this->_periodNum, $validDeep);
  1370. }
  1371. unset($parent, $parentBonus);
  1372. if ( $validDeep >= 2 ) {
  1373. return self::LOOP_FINISH;
  1374. }
  1375. });
  1376. unset($userId, $validDeep);
  1377. }
  1378. unset($allData);
  1379. return $this->calcBonusGXBefore($offset + $this->_limit);
  1380. }
  1381. unset($allData);
  1382. return true;
  1383. }
  1384. /**
  1385. * 共享奖
  1386. * @param int $offset
  1387. * @return bool
  1388. * @throws \yii\db\Exception
  1389. */
  1390. public function calcBonusGX(int $offset = 0) {
  1391. // 从缓存获取分页有的会员信息
  1392. $allData = CalcCache::getHasIncomeUsers($this->_periodNum, $offset, $this->_gxLimit);
  1393. if ($allData) {
  1394. echo sprintf("时间:[%s]共享奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1395. $insertBonusData = [];
  1396. // 获取线上找几层和是否开启找几层的限制
  1397. $configsGx = Config::find()->where(
  1398. 'CONFIG_NAME="gxNoPvFindLimitSwitch" OR CONFIG_NAME="gxNoPvFindLimitTimes"'
  1399. )->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
  1400. $openFindLimit = isset($configsGx['gxNoPvFindLimitSwitch']) ? $configsGx['gxNoPvFindLimitSwitch']['VALUE'] : 1; // 是否开放了 得奖人不满足980就找一个满足980的人来得这个奖 的最大向上循环次数
  1401. $findLimitTimes = isset($configsGx['gxNoPvFindLimitTimes']) ? $configsGx['gxNoPvFindLimitTimes']['VALUE'] : 5 ; // 开放的限制层数
  1402. foreach ($allData as $userId) {
  1403. $bonusUserData = [];
  1404. $bonusPercentOne = $this->_sysConfig['shareRecPercent']['VALUE'] / 100;
  1405. $bonusPercentTwo = $this->_sysConfig['sharePercent']['VALUE'] / 100;
  1406. // 从缓存中获取会员的收入信息
  1407. $incomeBonus = CalcCache::bonus($userId, $this->_periodNum);
  1408. $lastTwoIncome = $incomeBonus['ORI_BONUS_QY_BD'] ?? 0;
  1409. $shareBonusOne = $lastTwoIncome * $bonusPercentOne;
  1410. unset($lastTwoIncome);
  1411. //找到上2代 新增个人+推荐团队业绩 加权平均分配 这个奖
  1412. if( $shareBonusOne > 0) {
  1413. $bonusOneData = $this->gxLastTwoBonusData($userId, 1, $shareBonusOne);
  1414. $bonusTwoData = $this->gxLastTwoBonusData($userId, 2, $shareBonusOne);
  1415. $bonusUserData = array_merge($bonusUserData, $bonusOneData);
  1416. $bonusUserData = array_merge($bonusUserData, $bonusTwoData);
  1417. unset($bonusOneData, $bonusTwoData);
  1418. }
  1419. $nextFiveIncome = $incomeBonus['ORI_BONUS_QY_BD'] ?? 0;
  1420. $shareBonusTwo = $nextFiveIncome * $bonusPercentTwo;
  1421. unset($nextFiveIncome);
  1422. //找到下5代(安置网) 紧缩 相对偶数层2、4、6、8、10层
  1423. if( $shareBonusTwo > 0 ) {
  1424. $validDeep = 1;
  1425. $this->loopNetworkParentDo($userId, function ($parent) use ($userId, $shareBonusTwo, &$validDeep, &$bonusUserData) {
  1426. if ( $validDeep % 2 === 0 ) {
  1427. $bonusUserData[] = [
  1428. 'bonusUid' => $parent['PARENT_UID'],
  1429. 'bonus' => $shareBonusTwo,
  1430. 'validMinPv' => true,
  1431. ];
  1432. }
  1433. //判断$parent是否有首单团队奖
  1434. $parentBonus = CalcCache::bonus($parent['PARENT_UID'], $this->_periodNum);
  1435. if( $parentBonus['ORI_BONUS_QY_BD'] > 0 ) {//有效层
  1436. $validDeep += 1;
  1437. }
  1438. unset($parent, $parentBonus);
  1439. if ( $validDeep >= 11 ) {
  1440. return self::LOOP_FINISH;
  1441. }
  1442. });
  1443. unset($validDeep);
  1444. }
  1445. if ( !$bonusUserData ) continue;
  1446. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1447. $userEmpLevel = $userBaseInfo['EMP_LV'];
  1448. foreach ($bonusUserData as $bonusUserDataEvery) {
  1449. $bonusUserId = $bonusUserDataEvery['bonusUid'];
  1450. //判断 是否本期小市场(安置关系)新增980pv 能否得奖->20220407改成判断得奖人此期是否有报单团队奖金
  1451. // if ( $bonusUserDataEvery['validMinPv'] && !$this->checkSmallMarketPerf($bonusUserId) ) { 20220407
  1452. if ( $bonusUserDataEvery['validMinPv'] && !$this->checkHasOriBonusQyBd($bonusUserId) ) {
  1453. // unset($bonusUserDataEvery, $bonusUserId);
  1454. // continue;
  1455. //得奖人不满足980就找一个满足980的人来得这个奖
  1456. // 20220407改成判断得奖人此期是否有报单团队奖金,如果没有则找一个此期有报单团队奖金得人
  1457. $bonusUserId = $this->getMinBdPvNetworkParent($bonusUserId, $openFindLimit, $findLimitTimes);
  1458. if ( !$bonusUserId ) {
  1459. unset($bonusUserDataEvery, $bonusUserId);
  1460. continue;
  1461. }
  1462. }
  1463. $bonus = Tool::formatPrice($bonusUserDataEvery['bonus']);
  1464. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  1465. //总金额限制
  1466. $bonus = $this->bonusTotalLimit($bonus, $bonusUserId, $bonusUserBaseInfo['REC_NUM'], $bonusUserBaseInfo['ZC_AMOUNT']);
  1467. if( $bonus <= 0 ) continue;
  1468. //扣除相应的复消积分和管理费
  1469. $deductData = $this->deduct($bonusUserId, $bonus);
  1470. CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_GX', $bonus, $deductData);
  1471. CalcCache::addHasMonthBonusUsers($bonusUserId, $this->_periodNum);
  1472. //共享奖流水
  1473. $insertBonusData[] = [
  1474. 'ID' => SnowFake::instance()->generateId(),
  1475. 'USER_ID' => $bonusUserId,
  1476. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  1477. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  1478. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  1479. 'FROM_USER_ID' => $userId,
  1480. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  1481. 'LAST_FROM_EMP_LV' => $userEmpLevel,
  1482. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  1483. 'AMOUNT' => $deductData['surplus'],
  1484. 'ORI_BONUS' => $bonus,
  1485. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  1486. 'MANAGE_TAX' => $deductData['manageTax'],
  1487. 'PERIOD_NUM' => $this->_periodNum,
  1488. 'CALC_YEAR' => $this->_calcYear,
  1489. 'CALC_MONTH' => $this->_calcYearMonth,
  1490. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1491. 'CREATED_AT' => Date::nowTime(),
  1492. 'LOGS' => json_encode([
  1493. 'sharePercent' => $bonusPercentOne,
  1494. 'incomeBonus' => $incomeBonus,
  1495. 'recNum' => $userBaseInfo['REC_NUM'],
  1496. 'decAmount' => $userBaseInfo['ZC_AMOUNT'],
  1497. ]),
  1498. ];
  1499. unset($bonusUserDataEvery, $bonusUserId, $bonus, $bonusUserBaseInfo, $deductData);
  1500. }
  1501. unset($userId, $bonusUserData, $userBaseInfo, $userEmpLevel, $bonusPercentOne, $bonusPercentTwo, $incomeBonus, $sharePerson);
  1502. // echo ('内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  1503. }
  1504. if($insertBonusData) CalcBonusGX::batchInsert($insertBonusData);
  1505. unset($allData, $insertBonusData);
  1506. return $this->calcBonusGX($offset + $this->_gxLimit);
  1507. }
  1508. unset($allData);
  1509. return true;
  1510. }
  1511. /**
  1512. * 季度奖计算
  1513. *
  1514. */
  1515. public function calcQuarter() {
  1516. if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
  1517. // 不是结算月,则不进行计算
  1518. // echo('不是季结点,进这里,不计算季度奖'. PHP_EOL);
  1519. return false;
  1520. }
  1521. $result = \Yii::$app->db->createCommand("CALL QtrCalc(:periodNum)")
  1522. ->bindValue(':periodNum' , $this->_periodNum )
  1523. ->execute();
  1524. return $result;
  1525. }
  1526. // 执行蓝星管理奖金的存储过程
  1527. public function calcBsProcedure() {
  1528. if( !$this->_isCalcMonth ) {
  1529. // 不是结算月,则不进行计算
  1530. return false;
  1531. }
  1532. $result = \Yii::$app->db->createCommand("CALL CalcBlue(:periodNum)")
  1533. ->bindValue(':periodNum' , $this->_periodNum )
  1534. ->execute();
  1535. return $result;
  1536. }
  1537. // 执行旅游奖的计算
  1538. public function calcBonusTourism() {
  1539. // 月结,如果不是月结点,则直接退出
  1540. if (!$this->_isCalcMonth) {
  1541. return true;
  1542. }
  1543. $bonusConfig = $this->_sysConfig['openTourism'];
  1544. // 达标条件:聘级、级别、奖项比例
  1545. $config = json_decode($bonusConfig['OPTIONS'], true);
  1546. // 奖金总比例
  1547. $mate = $bonusConfig['VALUE'] / 100;
  1548. // 会员级别
  1549. $minDecLevel = $config['OPTIONS']['declarationLevel'] ?? [];
  1550. // 月度公司总PV
  1551. $monthTotalPV = PerfMonth::find()
  1552. ->yearMonth($this->_calcYearMonth)
  1553. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1554. ->sum('PV_PCS');
  1555. // 用于分发的奖金总数
  1556. $transferAmount = $monthTotalPV * $mate;
  1557. // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
  1558. $userStarDirector = CalcBonusBS::find()
  1559. ->yearMonth($this->_calcYearMonth)
  1560. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1561. ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STATUS')
  1562. ->groupBy('USER_ID')
  1563. ->asArray()
  1564. ->all();
  1565. $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
  1566. // 基于团队奖/绩效奖结果计算会员的StarCrown
  1567. $userStarCrown = CalcBonusQY::find()
  1568. ->yearMonth($this->_calcYearMonth)
  1569. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1570. ->select('USER_ID,LAST_CROWN_LV')
  1571. ->groupBy('USER_ID')
  1572. ->asArray()
  1573. ->all();
  1574. $userStarCrownObj = array_column($userStarCrown, NULL, 'USER_ID');
  1575. // 合并用户ID,去重
  1576. $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
  1577. // 奖金点数综合
  1578. $bonusPointComplex = 0;
  1579. $insertBonusData = [];
  1580. foreach($bonusUsers as $userId) {
  1581. // 计算奖金:取starDirectorPoint和starCrownPoint的大个值
  1582. $starDirectorPoint = $this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['TOURISM_PERCENT'] ?? 0;
  1583. $starCrownPoint = $this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_CROWN_LV']]['TOURISM_PERCENT'] ?? 0;
  1584. // 奖金比例:
  1585. $bonusPoint = max($starDirectorPoint, $starCrownPoint);
  1586. if ($bonusPoint <= 0) {
  1587. continue;
  1588. }
  1589. $insertBonusData[] = [
  1590. 'ID' => SnowFake::instance()->generateId(),
  1591. 'USER_ID' => $userId,
  1592. 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'],
  1593. 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LAST_EMP_LV'],
  1594. 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'],
  1595. 'LAST_CROWN_LV' => $userStarCrownObj[$userId]['LAST_CROWN_LV'],
  1596. 'AMOUNT_STANDARD' => 0,
  1597. 'POINT' => $bonusPoint,
  1598. 'PERIOD_NUM' => $this->_periodNum,
  1599. 'CALC_YEAR' => $this->_calcYear,
  1600. 'CALC_MONTH' => $this->_calcYearMonth,
  1601. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1602. 'CREATED_AT' => Date::nowTime(),
  1603. 'PERF' => $monthTotalPV,
  1604. 'TRANSFER_RATE' => $mate,
  1605. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  1606. 'CAP_AMOUNT' => 0,
  1607. 'POINT_COMPLEX' => 0,
  1608. ];
  1609. $bonusPointComplex += $bonusPoint;
  1610. }
  1611. // 数据写入总表
  1612. if ($insertBonusData) {
  1613. foreach ($insertBonusData as &$bonusData) {
  1614. // 计算奖金
  1615. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  1616. if ($amount <= 0) {
  1617. continue;
  1618. }
  1619. // 会员级别达到要求才会发放奖金
  1620. if ($bonusData['LAST_DEC_LV'] == $minDecLevel) {
  1621. // 放入缓存
  1622. CalcCache::tourismBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  1623. // 加入月奖的会员
  1624. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  1625. }
  1626. $bonusData['AMOUNT'] = $amount;
  1627. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  1628. }
  1629. CalcBonusTourism::batchInsert($insertBonusData);
  1630. }
  1631. return true;
  1632. }
  1633. // 执行房奖的计算
  1634. public function calcBonusVilla() {
  1635. // 月结,如果不是月结点,则直接退出
  1636. if (!$this->_isCalcMonth) {
  1637. return true;
  1638. }
  1639. $bonusConfig = $this->_sysConfig['openVilla'];
  1640. // 达标条件:聘级、级别、奖项比例
  1641. $config = json_decode($bonusConfig['OPTIONS'], true);
  1642. // 奖金总比例
  1643. $mate = $bonusConfig['VALUE'] / 100;
  1644. // 个人奖金封顶
  1645. $capBonus = intval($this->_sysConfig['openVillaCap']['VALUE'] ?? 0);
  1646. // 会员级别
  1647. $minDecLevel = $config['declarationLevel'] ?? [];
  1648. // 月度公司总PV
  1649. $monthTotalPV = PerfMonth::find()
  1650. ->yearMonth($this->_calcYearMonth)
  1651. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1652. ->sum('PV_PCS');
  1653. // 用于分发的奖金总数
  1654. $transferAmount = $monthTotalPV * $mate;
  1655. // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
  1656. $subQuery = CalcBonusQY::find()
  1657. ->yearMonth($this->_calcYearMonth)
  1658. ->where('CALC_MONTH = :CALC_MONTH AND LAST_CROWN_LV <> :NO_CROWN_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_CROWN_LV' => StarCrownLevel::NO_LEVEL_ID])
  1659. ->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_EMP_LV,LAST_STATUS,LEVEL_NAME,SORT')
  1660. ->joinWith(['starCrown' => function($query) {
  1661. $query->select(['LEVEL_NAME', 'SORT']);
  1662. }])
  1663. ->having(1)
  1664. ->orderBy('USER_ID ASC, SORT DESC');
  1665. $userStarCrownObj = (new Query())->from(['u' => $subQuery])->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_EMP_LV,LAST_STATUS,LEVEL_NAME,SORT')->groupBy('USER_ID')->indexBy('USER_ID')->all();
  1666. // 奖金点数综合
  1667. $bonusPointComplex = 0;
  1668. $insertBonusData = [];
  1669. foreach($userStarCrownObj as $item) {
  1670. // 奖金比例
  1671. $bonusPoint = $this->_starCrownLevelConfig[$item['LAST_CROWN_LV']]['VILLA_PERCENT'] ?? 0;
  1672. if (!$bonusPoint) {
  1673. continue;
  1674. }
  1675. // 会员级别达到要求才会发放奖金
  1676. if ($item['LAST_DEC_LV'] != $minDecLevel) {
  1677. continue;
  1678. }
  1679. $insertBonusData[] = [
  1680. 'ID' => SnowFake::instance()->generateId(),
  1681. 'USER_ID' => $item['USER_ID'],
  1682. 'LAST_DEC_LV' => $item['LAST_DEC_LV'] ?? '',
  1683. 'LAST_EMP_LV' => $item['LAST_EMP_LV'] ?? '',
  1684. 'LAST_STATUS' => $item['LAST_STATUS'] ?? 0,
  1685. 'LAST_CROWN_LV' => $item['LAST_CROWN_LV'] ?? '',
  1686. 'AMOUNT' => 0,
  1687. 'POINT' => $bonusPoint,
  1688. 'PERIOD_NUM' => $this->_periodNum,
  1689. 'CALC_YEAR' => $this->_calcYear,
  1690. 'CALC_MONTH' => $this->_calcYearMonth,
  1691. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1692. 'CREATED_AT' => Date::nowTime(),
  1693. 'PERF' => $monthTotalPV,
  1694. 'TRANSFER_RATE' => $mate,
  1695. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  1696. 'CAP_AMOUNT' => 0,
  1697. 'POINT_COMPLEX' => 0,
  1698. ];
  1699. $bonusPointComplex += $bonusPoint;
  1700. }
  1701. // 数据写入总表
  1702. if ($insertBonusData) {
  1703. // 计算个人奖金
  1704. foreach ($insertBonusData as &$bonusData) {
  1705. // 计算奖金
  1706. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  1707. if ($amount <= 0) {
  1708. continue;
  1709. }
  1710. // 封顶前奖金数
  1711. $capAmount = $amount;
  1712. // 奖金数不能大于封顶值
  1713. $amount = ($amount > $capBonus) ? $capBonus : $amount;
  1714. $bonusData['AMOUNT'] = $amount;
  1715. $bonusData['CAP_AMOUNT'] = $capAmount;
  1716. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  1717. // 放入缓存
  1718. CalcCache::villaBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  1719. // 加入月奖的会员
  1720. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  1721. }
  1722. CalcBonusVilla::batchInsert($insertBonusData);
  1723. }
  1724. return true;
  1725. }
  1726. // 执行车奖的计算
  1727. public function calcBonusGarage() {
  1728. // 月结,如果不是月结点,则直接退出
  1729. if (!$this->_isCalcMonth) {
  1730. return true;
  1731. }
  1732. $bonusConfig = $this->_sysConfig['openGarage'];
  1733. // 达标条件:聘级、级别、奖项比例
  1734. $config = json_decode($bonusConfig['OPTIONS'], true);
  1735. // 奖金总比例
  1736. $mate = $bonusConfig['VALUE'] / 100;
  1737. // 会员级别
  1738. $minDecLevel = $config['declarationLevel'] ?? [];
  1739. // 个人奖金封顶
  1740. $capBonus = intval($this->_sysConfig['openGarageCap']['VALUE'] ?? 0);
  1741. // 月度公司总PV
  1742. $monthTotalPV = PerfMonth::find()
  1743. ->yearMonth($this->_calcYearMonth)
  1744. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1745. ->sum('PV_PCS');
  1746. // 用于分发的奖金总数
  1747. $transferAmount = $monthTotalPV * $mate;
  1748. // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
  1749. $userStarDirector = CalcBonusBS::find()
  1750. ->yearMonth($this->_calcYearMonth)
  1751. ->where('CALC_MONTH = :CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1752. ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_STATUS')
  1753. ->groupBy('USER_ID')
  1754. ->asArray()
  1755. ->all();
  1756. $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
  1757. // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
  1758. $subQuery = CalcBonusQY::find()
  1759. ->yearMonth($this->_calcYearMonth)
  1760. ->where('CALC_MONTH = :CALC_MONTH AND LAST_CROWN_LV <> :NO_CROWN_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_CROWN_LV' => StarCrownLevel::NO_LEVEL_ID])
  1761. ->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')
  1762. ->joinWith(['starCrown' => function($query) {
  1763. $query->select(['LEVEL_NAME', 'SORT']);
  1764. }])
  1765. ->having(1)
  1766. ->orderBy('USER_ID ASC, SORT DESC');
  1767. $userStarCrownObj = (new Query())->from(['u' => $subQuery])->select('USER_ID,LAST_DEC_LV,LAST_CROWN_LV,LAST_STATUS,LEVEL_NAME,SORT')->groupBy('USER_ID')->indexBy('USER_ID')->all();
  1768. // 合并用户ID,去重
  1769. $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
  1770. sort($bonusUsers);
  1771. // 奖金点数综合
  1772. $bonusPointComplex = 0;
  1773. $insertBonusData = [];
  1774. foreach($bonusUsers as $userId) {
  1775. // 计算奖金:取starDirectorPoint和starCrownPoint的大个值
  1776. $starDirectorPoint = !isset($userStarDirectorObj[$userId]['LEVEL_ID']) ? 0 : ($this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['GARAGE_PERCENT'] ?? 0);
  1777. $starCrownPoint = !isset($userStarCrownObj[$userId]['LAST_CROWN_LV']) ? 0: ($this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_CROWN_LV']]['GARAGE_PERCENT'] ?? 0);
  1778. // 奖金比例:
  1779. $bonusPoint = max($starDirectorPoint, $starCrownPoint);
  1780. if ($bonusPoint <= 0) {
  1781. continue;
  1782. }
  1783. // 会员级别达到要求才会发放奖金
  1784. $lastDecLv = $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? '');
  1785. if ($lastDecLv != $minDecLevel) {
  1786. continue;
  1787. }
  1788. $insertBonusData[] = [
  1789. 'ID' => SnowFake::instance()->generateId(),
  1790. 'USER_ID' => $userId,
  1791. 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? ''),
  1792. 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LEVEL_ID'] ?? '',
  1793. 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'] ?? ($userStarCrownObj[$userId]['LAST_STATUS'] ?? 1),
  1794. 'LAST_CROWN_LV' => $userStarCrownObj[$userId]['LAST_CROWN_LV'] ?? '',
  1795. 'AMOUNT' => 0,
  1796. 'POINT' => $bonusPoint,
  1797. 'PERIOD_NUM' => $this->_periodNum,
  1798. 'CALC_YEAR' => $this->_calcYear,
  1799. 'CALC_MONTH' => $this->_calcYearMonth,
  1800. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1801. 'CREATED_AT' => Date::nowTime(),
  1802. 'PERF' => $monthTotalPV,
  1803. 'TRANSFER_RATE' => $mate,
  1804. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  1805. 'CAP_AMOUNT' => 0,
  1806. 'POINT_COMPLEX' => 0,
  1807. ];
  1808. $bonusPointComplex += $bonusPoint;
  1809. }
  1810. // 数据写入总表
  1811. if ($insertBonusData) {
  1812. foreach ($insertBonusData as &$bonusData) {
  1813. // 计算奖金
  1814. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  1815. if ($amount <= 0) {
  1816. continue;
  1817. }
  1818. // 封顶前奖金数
  1819. $capAmount = $amount;
  1820. // 奖金数不能大于封顶值
  1821. $amount = ($amount > $capBonus) ? $capBonus : $amount;
  1822. $bonusData['AMOUNT'] = $amount;
  1823. $bonusData['CAP_AMOUNT'] = $capAmount;
  1824. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  1825. // 放入缓存
  1826. CalcCache::garageBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  1827. // 加入月奖的会员
  1828. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  1829. }
  1830. CalcBonusGarage::batchInsert($insertBonusData);
  1831. }
  1832. return true;
  1833. }
  1834. /**
  1835. * 季度奖写用户缓存
  1836. *
  1837. */
  1838. public function calcQuarterUser(int $offset = 0) {
  1839. if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
  1840. // 不是结算月,则不进行计算
  1841. return false;
  1842. }
  1843. $allData = CalcBonusQuarter::finduseDbCalc()
  1844. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1845. ->groupBy('USER_ID')
  1846. ->offset($offset)
  1847. ->limit($this->_limit)
  1848. ->asArray()
  1849. ->all();
  1850. if ($allData){
  1851. // 达标条件:会员级别:钻卡
  1852. $config = json_decode($this->_sysConfig['openQuarter']['OPTIONS'], true);
  1853. $minDecLevel = $config['declarationLevel'] ?? [];
  1854. foreach ($allData as $user) {
  1855. // 扣除相应的复消积分和管理费
  1856. $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS']);
  1857. $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  1858. $manageTax = $deductData['manageTax']; // 管理费
  1859. $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  1860. // 管理奖钻卡发放
  1861. if ($user['LAST_DEC_LV'] == $minDecLevel) {
  1862. // 把对碰后的奖金存入缓存中
  1863. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_QUARTER', $user['ORI_BONUS'], $deductData);
  1864. // 加入月奖的会员
  1865. CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  1866. }
  1867. // 更新奖金存储过程的实发金额数据
  1868. CalcBonusQuarter::updateAll([
  1869. 'RECONSUME_POINTS' => $point,
  1870. 'AMOUNT' => $realBonusBs,
  1871. 'MANAGE_TAX' => $manageTax],
  1872. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1873. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1874. }
  1875. return $this->calcQuarterUser($offset + $this->_limit);
  1876. }
  1877. unset($allData);
  1878. return true;
  1879. }
  1880. /**
  1881. * 蓝星管理奖金
  1882. * @param int $offset
  1883. * @return bool
  1884. * @throws \yii\db\Exception
  1885. */
  1886. public function calcBonusBsGL(int $offset = 0) {
  1887. if( !$this->_isCalcMonth ) {
  1888. // 不是结算月,则不进行计算
  1889. return false;
  1890. }
  1891. // 从缓存获取分页有收入的会员信息
  1892. $allData = CalcBonusBS::findUseDbCalc()
  1893. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1894. ->groupBy('USER_ID')
  1895. ->offset($offset)
  1896. ->limit($this->_limit)
  1897. ->asArray()
  1898. ->all();
  1899. if ($allData) {
  1900. // 达标条件:会员级别:钻卡
  1901. $config = json_decode($this->_sysConfig['openGL']['OPTIONS'], true);
  1902. $minDecLevel = $config['mntDec'] ?? [];
  1903. foreach ($allData as $user) {
  1904. //扣除相应的复消积分和管理费
  1905. $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS_MNT']);
  1906. $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  1907. $manageTax = $deductData['manageTax']; // 管理费
  1908. $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  1909. // 是否活跃会员
  1910. $isActive = $this->_isPerfActive($user['USER_ID']);
  1911. $oriBonus = $isActive ? $user['ORI_BONUS_MNT'] : 0;
  1912. $lastEmpLv = $isActive ? $user['LEVEL_ID'] : EmployLevel::getDefaultLevelId();
  1913. // 管理奖钻卡发放
  1914. // if (in_array($user['LAST_DEC_LV'], $minDecLevel)) {
  1915. if ($oriBonus > 0) {
  1916. // 把对碰后的奖金存入缓存中
  1917. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS_MNT', $oriBonus, $deductData);
  1918. // 加入月奖的会员
  1919. CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  1920. }
  1921. // }
  1922. // 更新蓝星奖金存储过程的实发金额数据
  1923. CalcBonusBS::updateAll(
  1924. [
  1925. 'ORI_BONUS' => $user['ORI_BONUS'] + $oriBonus,
  1926. 'RECONSUME_POINTS' => $point,
  1927. 'AMOUNT_MNT' => $realBonusBs,
  1928. 'MANAGE_TAX_MNT' => $manageTax,
  1929. 'IS_ACTIVE' => (int)$isActive,
  1930. 'HOPE_BONUS' => $user['ORI_BONUS_MNT'] + $user['HOPE_BONUS_ABBR'],
  1931. 'HOPE_EMP_LV' => $user['LEVEL_ID'],
  1932. 'HOPE_BONUS_MNT' => $user['ORI_BONUS_MNT'],
  1933. 'ORI_BONUS_MNT' => $oriBonus,
  1934. 'LEVEL_ID' => $lastEmpLv,
  1935. ],
  1936. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1937. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1938. }
  1939. return $this->calcBonusBsGL($offset + $this->_limit);
  1940. }
  1941. unset($allData);
  1942. return true;
  1943. }
  1944. /**
  1945. * 蓝星业绩奖金
  1946. * @param int $offset
  1947. * @return bool
  1948. * @throws \yii\db\Exception
  1949. */
  1950. public function calcBonusBsYJ(int $offset = 0) {
  1951. if( !$this->_isCalcMonth ) {
  1952. // 不是结算月,则不进行计算
  1953. return false;
  1954. }
  1955. // 从缓存获取分页有收入的会员信息
  1956. $allData = CalcBonusBS::findUseDbCalc()
  1957. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1958. ->groupBy('USER_ID')
  1959. ->offset($offset)
  1960. ->limit($this->_limit)
  1961. ->asArray()
  1962. ->all();
  1963. if ($allData) {
  1964. // 达标条件:会员级别:金卡、钻卡
  1965. $config = json_decode($this->_sysConfig['openGL']['OPTIONS'], true);
  1966. $minDecLevel = $config['abbrDec'] ?? [];
  1967. foreach ($allData as $user) {
  1968. //扣除相应的复消积分和管理费
  1969. $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS_ABBR']);
  1970. $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  1971. $manageTax = $deductData['manageTax']; // 管理费
  1972. $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  1973. // 是否活跃会员
  1974. $isActive = $this->_isPerfActive($user['USER_ID']);
  1975. $oriBonus = $isActive ? $user['ORI_BONUS_ABBR'] : 0;
  1976. $lastEmpLv = $isActive ? $user['LEVEL_ID'] : EmployLevel::getDefaultLevelId();
  1977. // 业绩奖金卡、钻卡发放
  1978. // if (in_array($user['LAST_DEC_LV'], $minDecLevel)) {
  1979. // 把对碰后的奖金存入缓存中
  1980. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS_ABBR', $oriBonus, $deductData);
  1981. if ($oriBonus > 0) {
  1982. // 加入月奖的会员
  1983. CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  1984. }
  1985. // }
  1986. // 更新蓝星业绩奖金存储过程的实发金额数据
  1987. CalcBonusBS::updateAll(
  1988. [
  1989. 'ORI_BONUS' => $oriBonus,
  1990. 'AMOUNT_ABBR' => $realBonusBs,
  1991. 'MANAGE_TAX_ABBR' => $manageTax,
  1992. 'RECONSUME_POINTS' => $point,
  1993. 'IS_ACTIVE' => (int)$isActive,
  1994. 'HOPE_BONUS' => $user['ORI_BONUS_ABBR'],
  1995. 'HOPE_EMP_LV' => $user['LEVEL_ID'],
  1996. 'HOPE_BONUS_ABBR' => $user['ORI_BONUS_ABBR'],
  1997. 'ORI_BONUS_ABBR' => $oriBonus,
  1998. 'LEVEL_ID' => $lastEmpLv,
  1999. ],
  2000. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2001. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  2002. }
  2003. return $this->calcBonusBsYJ($offset + $this->_limit);
  2004. }
  2005. unset($allData);
  2006. return true;
  2007. }
  2008. /**
  2009. * 报单管理奖
  2010. * @param int $offset
  2011. * @return bool
  2012. * @throws \yii\db\Exception
  2013. */
  2014. public function calcBonusBdGL(int $offset = 0) {
  2015. // 从缓存获取分页有收入的会员信息
  2016. $allData = CalcCache::getHasIncomeUsers($this->_periodNum, $offset, $this->_limit);
  2017. if ($allData) {
  2018. $insertBonusData = [];
  2019. foreach ($allData as $userId) {
  2020. $bonusUserData = [];
  2021. //会员信息
  2022. $validDeep = 1;
  2023. $this->loopRelationParentDo($userId, function ($parent) use ($userId, &$validDeep, &$bonusUserData) {
  2024. //判断$parent是否有首单团队奖
  2025. $bonusUserId = $parent['PARENT_UID'];
  2026. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2027. $nowDecLevelConfig = $this->_decLevelConfig[$bonusUserBaseInfo['DEC_LV']];
  2028. $recNum = $bonusUserBaseInfo['REC_NUM'];
  2029. if( $recNum <= 0 ) {
  2030. $maxOddLayer = 0;
  2031. }else if( $recNum == 1 ) {
  2032. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_ONE'] ?? 0;
  2033. }else if( $recNum == 2 ) {
  2034. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_TWO'] ?? 0;
  2035. }else {
  2036. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_THREE'] ?? 0;
  2037. }
  2038. if ( $validDeep < 2 * $maxOddLayer && $validDeep % 2 === 1 ) {//奇数层
  2039. $bonusUserData[] = [
  2040. 'bonusUid' => $parent['PARENT_UID'],
  2041. 'validDeep' => $validDeep
  2042. ];
  2043. }
  2044. $parentBonus = CalcCache::bonus($bonusUserId, $this->_periodNum);
  2045. if( $parentBonus['ORI_BONUS_QY_BD'] > 0 ) {//有效层
  2046. $validDeep += 1;
  2047. }
  2048. unset($parent, $parentBonus, $bonusUserId, $bonusUserBaseInfo, $nowDecLevelConfig, $recNum, $maxOddLayer);
  2049. //超过代数上限则结束
  2050. if ( $validDeep >= 18 ) {
  2051. return self::LOOP_FINISH;
  2052. }
  2053. });
  2054. //发奖
  2055. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2056. $userBonus = CalcCache::bonus($userId, $this->_periodNum);
  2057. foreach ($bonusUserData as $everyData) {
  2058. $bonusUserId = $everyData['bonusUid'];
  2059. //判断 是否本期小市场(安置关系)新增980pv 能否得奖
  2060. if ( !$this->checkSmallMarketPerf($bonusUserId) ) {
  2061. // unset($bonusUserId);
  2062. // continue;
  2063. //得奖人不满足980就找一个满足980的人来得这个奖
  2064. $bonusUserId = $this->getMinBdPvRelationParent($bonusUserId);
  2065. if ( !$bonusUserId ) {
  2066. unset($bonusUserId);
  2067. continue;
  2068. }
  2069. }
  2070. $parentOddPercentValue = floor($everyData['validDeep']/6);
  2071. $parentOddPercentName = sprintf('parentOddPercent_%s', $parentOddPercentValue);
  2072. if( !isset($this->_sysConfig[$parentOddPercentName]) ) continue;
  2073. $bonusPercent = $this->_sysConfig[$parentOddPercentName]['VALUE'];
  2074. $manageBonus = Tool::formatPrice($userBonus['ORI_BONUS_QY_BD'] * $bonusPercent / 100);
  2075. if ($manageBonus <= 0) continue;
  2076. //总金额限制
  2077. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2078. $recNum = $bonusUserBaseInfo['REC_NUM'];
  2079. $manageBonus = $this->bonusTotalLimit($manageBonus, $bonusUserId, $recNum, $bonusUserBaseInfo['ZC_AMOUNT']);
  2080. if( $manageBonus <= 0 ) continue;
  2081. //扣除相应的复消积分和管理费
  2082. $deductData = $this->deduct($bonusUserId, $manageBonus);
  2083. // 钻卡会员奖金记入缓存
  2084. $decLevelConfig = $this->_decLevelConfig;
  2085. $nowDecLevelConfig = $decLevelConfig[$userBaseInfo['DEC_LV']];
  2086. if ($nowDecLevelConfig == '67ABCE0ECE705575E055736AECE8644D') {
  2087. CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_GL', $manageBonus, $deductData, CalcCache::FROM_MEANS_BD);
  2088. CalcCache::addHasMonthBonusUsers($bonusUserId, $this->_periodNum);
  2089. }
  2090. //管理奖流水
  2091. $insertBonusData[] = [
  2092. 'ID' => SnowFake::instance()->generateId(),
  2093. 'USER_ID' => $bonusUserId,
  2094. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  2095. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  2096. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  2097. 'FROM_USER_ID' => $userId,
  2098. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2099. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2100. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2101. 'AMOUNT' => $deductData['surplus'],
  2102. 'ORI_BONUS' => $manageBonus,
  2103. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2104. 'MANAGE_TAX' => $deductData['manageTax'],
  2105. 'PERIOD_NUM' => $this->_periodNum,
  2106. 'CALC_YEAR' => $this->_calcYear,
  2107. 'CALC_MONTH' => $this->_calcYearMonth,
  2108. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2109. 'CREATED_AT' => Date::nowTime(),
  2110. 'LOGS' => json_encode([
  2111. $parentOddPercentName => $this->_sysConfig[$parentOddPercentName]['VALUE'],
  2112. 'validDeep' => $everyData['validDeep'],
  2113. 'recNum' => $bonusUserBaseInfo['REC_NUM'],
  2114. 'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
  2115. 'fromUserId' => $userId,
  2116. 'decLevel' => $bonusUserBaseInfo['DEC_LV'],
  2117. 'bonusTotalLimit' => [
  2118. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  2119. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  2120. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  2121. ],
  2122. ]),
  2123. ];
  2124. unset($everyData, $bonusUserId, $parentOddPercentValue, $parentOddPercentName, $bonusPercent, $manageBonus, $deductData);
  2125. }
  2126. unset($userId, $validDeep, $userBaseInfo, $userBonus, $bonusUserData);
  2127. }
  2128. if($insertBonusData) CalcBonusGL::batchInsert($insertBonusData);
  2129. unset($allData, $insertBonusData);
  2130. return $this->calcBonusBdGL($offset + $this->_limit);
  2131. }
  2132. unset($allData);
  2133. return true;
  2134. }
  2135. /**
  2136. * 复消管理奖
  2137. * @param int $offset
  2138. * @return bool
  2139. * @throws \yii\db\Exception
  2140. */
  2141. public function calcBonusFxGL(int $offset = 0) {
  2142. $periodNum = $this->_periodNum;
  2143. // 从缓存获取分页有收入的会员信息
  2144. $allData = CalcCache::getHasIncomeUsers($this->_periodNum, $offset, $this->_limit);
  2145. if ($allData) {
  2146. $insertBonusData = [];
  2147. foreach ($allData as $userId) {
  2148. //会员信息
  2149. $decLevelConfig = $this->_decLevelConfig;
  2150. $netWorkParents = Cache::getAllRelationParents($userId);
  2151. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2152. $userEmpLevel = $userBaseInfo['EMP_LV'];
  2153. foreach ($netWorkParents as $netWorkParent) {
  2154. //自已距顶端的深度减去父级距顶端的深度
  2155. $diffLayer = $netWorkParent['TOP_DEEP'] - $netWorkParent['PARENT_DEEP'];
  2156. if( $diffLayer <= 0) continue;
  2157. //@todo 超过最大代数就跳出本次循环
  2158. //偶数代跳过
  2159. if( $diffLayer % 2 == 0 ) continue;
  2160. // 获取会员的报单级别
  2161. $bonusUserId = $netWorkParent['PARENT_UID'];
  2162. if( !$bonusUserId ) continue;
  2163. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2164. $nowDecLevelConfig = $decLevelConfig[$bonusUserBaseInfo['DEC_LV']];
  2165. if( !$nowDecLevelConfig ) continue;
  2166. //推荐人数
  2167. $recNum = $bonusUserBaseInfo['REC_NUM'];
  2168. if( $recNum <= 0 ) continue;
  2169. if( $recNum == 1 ) {
  2170. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_ONE'];
  2171. }else if( $recNum == 2 ) {
  2172. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_TWO'];
  2173. }else {
  2174. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_THREE'];
  2175. }
  2176. //超过代数上限也跳过
  2177. if( $diffLayer >= 2 * $maxOddLayer ) continue;
  2178. // $everyLayer = floor(2 * $nowDecLevelConfig['GL_ODD_DEEP_THREE'] / $nowDecLevelConfig['SORT']);
  2179. //多少代
  2180. // $theLayer = $diffLayer % $everyLayer;
  2181. // $theLayerLevel = floor($diffLayer/$everyLayer);
  2182. $theLayerLevel = floor($diffLayer/6);
  2183. $parentOddPercentName = sprintf('parentOddPercent_%s', $theLayerLevel);
  2184. if( !isset($this->_sysConfig[$parentOddPercentName]) ) continue;
  2185. $bonusPercent = $this->_sysConfig[$parentOddPercentName]['VALUE'];
  2186. // 从缓存中获取会员的收入信息
  2187. $incomeBonus = CalcCache::bonus($userId, $periodNum);
  2188. $parentOddIncomeFromName = sprintf('parentOddIncomeFrom_%s', $theLayerLevel);
  2189. $parentOddIncomeFrom = explode(',', $this->_sysConfig[$parentOddIncomeFromName]['VALUE']);
  2190. $parentOddIncome = 0;
  2191. foreach ($parentOddIncomeFrom as $incomeType) {
  2192. if( $incomeType === 'XF' ) {
  2193. $incomeTypeName = sprintf('ORI_BONUS_%s', $incomeType);
  2194. }else {
  2195. $incomeTypeName = sprintf('ORI_BONUS_%s_FX', $incomeType);
  2196. }
  2197. $incomeTypeValue = $incomeBonus[$incomeTypeName] ?? 0;
  2198. $parentOddIncome += $incomeTypeValue;
  2199. unset($incomeType, $incomeTypeName, $incomeTypeValue);
  2200. }
  2201. unset($parentOddIncomeFrom);
  2202. $manageBonus = Tool::formatPrice($parentOddIncome * $bonusPercent / 100);
  2203. if ($manageBonus <= 0) continue;
  2204. //总金额限制
  2205. $manageBonus = $this->bonusTotalLimit($manageBonus, $bonusUserId, $recNum, $bonusUserBaseInfo['ZC_AMOUNT']);
  2206. if( $manageBonus <= 0 ) continue;
  2207. //扣除相应的复消积分和管理费
  2208. $deductData = $this->deduct($bonusUserId, $manageBonus);
  2209. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_GL', $manageBonus, $deductData, CalcCache::FROM_MEANS_FX);
  2210. //管理奖流水
  2211. $insertBonusData[] = [
  2212. 'ID' => SnowFake::instance()->generateId(),
  2213. 'USER_ID' => $bonusUserId,
  2214. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  2215. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  2216. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  2217. 'FROM_USER_ID' => $userId,
  2218. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2219. 'LAST_FROM_EMP_LV' => $userEmpLevel,
  2220. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2221. 'AMOUNT' => $deductData['surplus'],
  2222. 'ORI_BONUS' => $manageBonus,
  2223. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2224. 'MANAGE_TAX' => $deductData['manageTax'],
  2225. 'PERIOD_NUM' => $this->_periodNum,
  2226. 'CALC_YEAR' => $this->_calcYear,
  2227. 'CALC_MONTH' => $this->_calcYearMonth,
  2228. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2229. 'CREATED_AT' => Date::nowTime(),
  2230. 'LOGS' => json_encode([
  2231. $parentOddPercentName => $this->_sysConfig[$parentOddPercentName]['VALUE'],
  2232. $parentOddIncomeFromName => $this->_sysConfig[$parentOddIncomeFromName]['VALUE'],
  2233. 'decLevelConfig' => $nowDecLevelConfig,
  2234. 'recNum' => $bonusUserBaseInfo['REC_NUM'],
  2235. 'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
  2236. 'fromUserId' => $userId,
  2237. 'decLevel' => $bonusUserBaseInfo['DEC_LV'],
  2238. ]),
  2239. ];
  2240. unset($netWorkParent, $diffLayer, $bonusUserId, $bonusUserBaseInfo, $bonusPercent, $nowDecLevelConfig, $manageBonus, $incomeBonus, $maxOddLayer, $theLayerLevel, $recNum, $parentOddPercentName, $parentOddIncomeFromName, $deductData);
  2241. }
  2242. unset($userId, $userBaseInfo, $userEmpLevel, $netWorkParents, $decLevelConfig);
  2243. }
  2244. CalcBonusGL::batchInsert($insertBonusData);
  2245. unset($allData, $insertBonusData);
  2246. return $this->calcBonusFxGL($offset + $this->_limit);
  2247. }
  2248. unset($allData);
  2249. return true;
  2250. }
  2251. /**
  2252. * 结算荣衔奖第一步
  2253. * @param int $offset
  2254. * @return bool
  2255. * @throws \yii\db\Exception
  2256. * @throws \Exception
  2257. */
  2258. public function calcBonusYCStepOne(int $offset = 0) {
  2259. // 月结,如果不是月结点,则直接退出
  2260. if (!$this->_isCalcMonth) {
  2261. return true;
  2262. }
  2263. echo sprintf("时间:[%s]荣衔奖第【1】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  2264. //从缓存获取分页有本月业绩的会员
  2265. $allData = CalcCache::getHasMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  2266. if ($allData) {
  2267. $maxLevelId = EmployLevel::SHX_ZJ_LEVEL_ID;
  2268. $maxLevel = $this->_empLevelConfig[$maxLevelId];
  2269. $maxLevelPercent = $maxLevel['RX_PERCENT'] ?? 0;
  2270. unset($maxLevelId, $maxLevel);
  2271. foreach ($allData as $userId) {
  2272. // echo sprintf("时间:[%s]荣衔奖,当前用户ID为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $userId);
  2273. $nowMonthPerf = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  2274. $monthPvPcs = $nowMonthPerf['PV_PCS'] ?? 0;
  2275. if( $monthPvPcs <= 0 ) continue;
  2276. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2277. //个人业绩的奖金
  2278. $empLevelId = $userBaseInfo['EMP_LV'];
  2279. $empLevel = $this->_empLevelConfig[$empLevelId];
  2280. $rxPercent = $empLevel['RX_PERCENT'] ?? 0;
  2281. $empBonus = $monthPvPcs * $rxPercent / 100;
  2282. if( $empBonus > 0 ) {
  2283. //给本人添加聘级比例
  2284. CalcCache::ycMaxBonusPercent($userId, $this->_periodNum, $rxPercent);
  2285. //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  2286. CalcCache::saveYCBonusList($userId, $this->_periodNum, $empBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$monthPvPcs]);
  2287. CalcCache::addHasYcBonusUsers($userId, $this->_periodNum);
  2288. //达到最大的比例其它人就得不到了
  2289. if( $rxPercent >= $maxLevelPercent ) continue;
  2290. }
  2291. unset($empLevelId, $empLevel, $rxPercent, $empBonus);
  2292. //获取所有的父级
  2293. $this->loopRelationParentDo($userId, function ($parent) use ($userId, $monthPvPcs, $maxLevelPercent) {
  2294. $bonusUserId = $parent['PARENT_UID'];
  2295. //计算级别之后更新过userInfo的缓存,缓存中级别发生了变化
  2296. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2297. $parentEmpLevelId = $bonusUserInfo['EMP_LV'];
  2298. $parentEmpLevel = $this->_empLevelConfig[$parentEmpLevelId];
  2299. $parentRxPercent = $parentEmpLevel['RX_PERCENT'] ?? 0;
  2300. $cacheMaxPercent = CalcCache::ycMaxBonusPercent($userId, $this->_periodNum);
  2301. $diffPercent = $parentRxPercent - $cacheMaxPercent;
  2302. if( $diffPercent <= 0 ) return self::LOOP_CONTINUE;
  2303. $empBonus = $monthPvPcs * $diffPercent / 100;
  2304. if( $empBonus <= 0 ) return self::LOOP_CONTINUE;
  2305. //给本人添加聘级比例
  2306. CalcCache::ycMaxBonusPercent($userId, $this->_periodNum, $parentRxPercent);
  2307. //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  2308. CalcCache::saveYCBonusList($bonusUserId, $this->_periodNum, $empBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$monthPvPcs]);
  2309. CalcCache::addHasYcBonusUsers($bonusUserId, $this->_periodNum);
  2310. unset($cacheMaxPercent, $diffPercent, $parentEmpLevel, $bonusUserId, $bonusUserInfo, $parentEmpLevelId, $empBonus);
  2311. //达到最大的比例就不在向上找了
  2312. if( $parentRxPercent >= $maxLevelPercent ) return self::LOOP_FINISH;
  2313. unset($parentRxPercent);
  2314. });
  2315. unset($nowMonthPerf, $monthPvPcs);
  2316. }
  2317. unset($allData, $maxLevelPercent);
  2318. $this->calcBonusYCStepOne($offset + $this->_limit);
  2319. }
  2320. unset($periodNum, $allData);
  2321. return true;
  2322. }
  2323. /**
  2324. * 结算荣衔奖第二步
  2325. * @param int $offset
  2326. * @return bool
  2327. * @throws \yii\db\Exception
  2328. */
  2329. public function calcBonusYCStepTwo(int $offset = 0) {
  2330. // 月结,如果不是月结点,则直接退出
  2331. if (!$this->_isCalcMonth) {
  2332. return true;
  2333. }
  2334. echo sprintf("时间:[%s]荣衔奖第【2】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  2335. $allData = CalcCache::getHasYcBonusUsers($this->_periodNum, $offset, $this->_limit);
  2336. if ($allData) {
  2337. $insertBonusData = [];
  2338. foreach ($allData as $userId) {
  2339. $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  2340. $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2341. unset($monthPerfData);
  2342. if( !$fxPvStatus ) continue;
  2343. unset($fxPvStatus);
  2344. $ycBonusData = CalcCache::getYCBonusList($userId, $this->_periodNum);
  2345. if( !$ycBonusData ) continue;
  2346. $empBonus = $ycBonusData['empBonus'] ?? 0;
  2347. if( $empBonus <=0 ) continue;
  2348. //总金额限制
  2349. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2350. $empBonus = $this->bonusTotalLimit($empBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  2351. if( $empBonus <= 0 ) continue;
  2352. //扣除相应的复消积分和管理费
  2353. $empBonus = Tool::formatPrice($empBonus);
  2354. $deductData = $this->deduct($userId, $empBonus);
  2355. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_YC', $empBonus, $deductData);
  2356. $empLevelId = $userBaseInfo['EMP_LV'];
  2357. $insertBonusData[] = [
  2358. 'ID' => SnowFake::instance()->generateId(),
  2359. 'USER_ID' => $userId,
  2360. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  2361. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  2362. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  2363. 'FROM_USER_ID' => $userId,
  2364. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2365. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2366. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2367. 'DEEP' => 0,
  2368. 'AMOUNT' => $deductData['surplus'],
  2369. 'ORI_BONUS' => $empBonus,
  2370. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2371. 'MANAGE_TAX' => $deductData['manageTax'],
  2372. 'BONUS_TYPE' => CalcBonusYC::BONUS_TYPE_YC,
  2373. 'PERIOD_NUM' => $this->_periodNum,
  2374. 'CALC_MONTH' => $this->_calcYearMonth,
  2375. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2376. 'CREATED_AT' => Date::nowTime(),
  2377. 'LOGS' => json_encode([
  2378. 'empLevelId' => $empLevelId,
  2379. ])
  2380. // 'FROM_DATA' => json_encode($ycBonusData['fromData']),
  2381. ];
  2382. unset($ycBonusData, $deductData);
  2383. //如果是总监以上拿平级2代
  2384. $empLevel = $this->_empLevelConfig[$empLevelId];
  2385. $userEmpLevelSort = $empLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  2386. // if( $userEmpLevelSort >= EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {}
  2387. $newInsertBonusData = $this->calcParentYC($userId, $userBaseInfo, $userEmpLevelSort, $empBonus);
  2388. $insertBonusData = array_merge($insertBonusData, $newInsertBonusData);
  2389. unset($newInsertBonusData);
  2390. unset($userId, $userBaseInfo, $empLevel, $empLevelId, $userEmpLevelSort, $empBonus);
  2391. }
  2392. CalcBonusYC::batchInsert($insertBonusData);
  2393. unset($insertBonusData, $allData);
  2394. $this->calcBonusYCStepTwo($offset + $this->_limit);
  2395. }
  2396. unset($allData);
  2397. return true;
  2398. }
  2399. /**
  2400. * VIP奖
  2401. * @param int $offset
  2402. * @return bool
  2403. * @throws \yii\db\Exception
  2404. */
  2405. public function calcBonusVIP(int $offset = 0)
  2406. {
  2407. // 月结,如果不是月结点,则直接退出
  2408. if (!$this->_isCalcMonth) {
  2409. return true;
  2410. }
  2411. echo sprintf("时间:[%s]VIP奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $offset);
  2412. //从缓存获取分页有本月业绩的会员
  2413. $allData = CalcCache::getHasMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  2414. if ($allData) {
  2415. $insertBonusData = [];
  2416. foreach ($allData as $userId) {
  2417. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2418. //条件一:级别必须为VIP
  2419. $isVip = false;
  2420. if( $userBaseInfo['DEC_LV'] === DeclarationLevel::VIP_LEVEL_ID ) {
  2421. $isVip= true;
  2422. }
  2423. if( $this->_sysConfig['vipBonusGoldDecLevel']['VALUE'] && $userBaseInfo['DEC_LV'] === DeclarationLevel::JIN_ZUAN_LEVEL_ID ) {
  2424. $isVip = true;
  2425. }
  2426. if ( !$isVip ) {
  2427. unset($userId, $userBaseInfo);
  2428. continue;
  2429. }
  2430. //判断其它两个条件,满足则计算月团队奖,不满足则留下大区剩余业绩,清除其它区的剩余业绩
  2431. //获取本月的业绩
  2432. $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  2433. // 从缓存中获取会员的上期结余业绩信息
  2434. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  2435. // 本期 + 上期结余
  2436. $perfArr = [
  2437. 'VIP_SURPLUS_1L_ZC' => $monthPerfData['VIP_PV_1L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_1L_ZC'],
  2438. 'VIP_SURPLUS_2L_ZC' => $monthPerfData['VIP_PV_2L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_2L_ZC'],
  2439. 'VIP_SURPLUS_3L_ZC' => $monthPerfData['VIP_PV_3L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_3L_ZC'],
  2440. 'VIP_SURPLUS_4L_ZC' => $monthPerfData['VIP_PV_4L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_4L_ZC'],
  2441. 'VIP_SURPLUS_5L_ZC' => $monthPerfData['VIP_PV_5L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_5L_ZC'],
  2442. ];
  2443. //条件二:本月复消金额达到300元
  2444. //fix-2021-03-26修改 条件二:本月个人复消PV300
  2445. $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2446. unset($monthPerfData, $pervSurplusPerf);
  2447. if( !$fxPvStatus ) {
  2448. $this->dealWithMaxPerf($userId, $perfArr);
  2449. unset($userBaseInfo, $userId, $perfArr, $fxPvStatus);
  2450. continue;
  2451. }
  2452. //条件三:其它市场业绩
  2453. $isCanOtherDepartPerf = $this->_isCanVipBonusOtherAreaPerf($perfArr);
  2454. if ( !$isCanOtherDepartPerf ) {
  2455. $this->dealWithMaxPerf($userId, $perfArr);
  2456. unset($userBaseInfo, $userId, $perfArr, $isCanOtherDepartPerf);
  2457. continue;
  2458. }
  2459. $oriPerfArr = [
  2460. 'perfArr' => $perfArr,
  2461. 'touchBonus' => 0,
  2462. ];
  2463. // 对碰
  2464. $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $this->_sysConfig['vipBonusPercent']['VALUE']/100);
  2465. unset($oriPerfArr, $perfArr);
  2466. $touchPerfArr = [];
  2467. foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
  2468. $touchPerfArr[$keyR] = $perfR;
  2469. }
  2470. // 对碰完成后把结余的业绩存入本期业绩缓存中
  2471. // CalcCache::nowPeriodPerf($userId, $this->_periodNum, $touchPerfArr);
  2472. //更新数据库
  2473. PerfMonth::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [
  2474. 'USER_ID' => $userId,
  2475. 'CALC_MONTH' => $this->_calcYearMonth,
  2476. ]);
  2477. if ($touchBonusArr['touchBonus'] <= 0) continue;
  2478. $vipBonus = $touchBonusArr['touchBonus'];
  2479. //判断级别上限
  2480. $vipBonus = $this->declarationLevelCap($vipBonus, $userId, $userBaseInfo['DEC_LV']);
  2481. if( $vipBonus <= 0 ) continue;
  2482. $vipBonus = $this->bonusTotalLimit($vipBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  2483. if( $vipBonus <= 0 ) continue;
  2484. //扣除相应的复消积分和管理费
  2485. $deductData = $this->deduct($userId, $vipBonus);
  2486. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_VIP', $vipBonus, $deductData);
  2487. $insertBonusData[] = [
  2488. 'ID' => SnowFake::instance()->generateId(),
  2489. 'USER_ID' => $userId,
  2490. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  2491. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  2492. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  2493. 'FROM_USER_ID' => $userId,
  2494. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2495. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2496. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2497. 'AMOUNT' => $deductData['surplus'],
  2498. 'ORI_BONUS' => $vipBonus,
  2499. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2500. 'MANAGE_TAX' => $deductData['manageTax'],
  2501. 'PERIOD_NUM' => $this->_periodNum,
  2502. 'CALC_YEAR' => $this->_calcYear,
  2503. 'CALC_MONTH' => $this->_calcYearMonth,
  2504. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2505. 'CREATED_AT' => Date::nowTime(),
  2506. 'LOGS' => json_encode($touchPerfArr)
  2507. ];
  2508. unset($userBaseInfo, $userId, $perfArr, $fxAmountStatus, $isCanOtherDepartPerf, $touchBonusArr, $touchPerfArr, $vipBonus, $deductData);
  2509. }
  2510. if( $insertBonusData ) CalcBonusVIP::batchInsert($insertBonusData);
  2511. unset($insertBonusData, $allData);
  2512. $this->calcBonusVIP($offset + $this->_limit);
  2513. }
  2514. unset($allData);
  2515. return true;
  2516. }
  2517. /**
  2518. * 见习达标奖
  2519. * @param int $offset
  2520. * @return bool
  2521. * @throws \yii\db\Exception
  2522. */
  2523. public function calcBonusStandard(int $offset = 0)
  2524. {
  2525. // 月结,如果不是月结点,则直接退出
  2526. if (!$this->_isCalcMonth) {
  2527. return true;
  2528. }
  2529. echo sprintf("时间:[%s]见习达标奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $offset);
  2530. //从缓存获取分页有本月业绩的会员
  2531. $allData = CalcCache::getHasStandardMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  2532. if ($allData) {
  2533. $minSaleCondition = $this->_jxStandardMinSaleCondition();
  2534. $insertBonusData = [];
  2535. foreach ($allData as $userId) {
  2536. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2537. //条件一:聘级必须为见习主任
  2538. if( $userBaseInfo['EMP_LV'] != EmployLevel::JX_ZR_LEVEL_ID ) {
  2539. unset($userId, $userBaseInfo);
  2540. continue;
  2541. }
  2542. $standardMonthPerf = CalcCache::nowStandardMonthPerf($userId, $this->_periodNum);
  2543. $totalAmount = $standardMonthPerf['AMOUNT_PCS'] + $standardMonthPerf['AMOUNT_PSS'];
  2544. if( $totalAmount < $minSaleCondition ) {
  2545. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount);
  2546. continue;
  2547. }
  2548. $standardBonus = $this->_jxStandardAwardAmount($totalAmount);
  2549. if( $standardBonus <= 0 ) {
  2550. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount, $standardBonus);
  2551. continue;
  2552. }
  2553. CalcCache::standardBonus($userId, $this->_periodNum, $standardBonus);
  2554. $insertBonusData[] = [
  2555. 'ID' => SnowFake::instance()->generateId(),
  2556. 'USER_ID' => $userId,
  2557. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  2558. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  2559. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  2560. 'FROM_USER_ID' => $userId,
  2561. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2562. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2563. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2564. 'AMOUNT' => $standardBonus,
  2565. 'ORI_BONUS' => $standardBonus,
  2566. 'RECONSUME_POINTS' => 0,
  2567. 'MANAGE_TAX' => 0,
  2568. 'PERIOD_NUM' => $this->_periodNum,
  2569. 'CALC_YEAR' => $this->_calcYear,
  2570. 'CALC_MONTH' => $this->_calcYearMonth,
  2571. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2572. 'CREATED_AT' => Date::nowTime(),
  2573. 'LOGS' => json_encode($standardMonthPerf)
  2574. ];
  2575. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount);
  2576. }
  2577. if( $insertBonusData ) CalcBonusStandard::batchInsert($insertBonusData);
  2578. unset($insertBonusData, $minSaleCondition, $insertBonusData, $allData);
  2579. $this->calcBonusStandard($offset + $this->_limit);
  2580. }
  2581. unset($allData);
  2582. return true;
  2583. }
  2584. /**
  2585. * === 运算相关的辅助功能开始 ===
  2586. */
  2587. /**
  2588. * 获取上2代的得奖人信息
  2589. * @param $userId
  2590. * @param $validDeep
  2591. * @param $shareBonusOne
  2592. * @return array
  2593. */
  2594. protected function gxLastTwoBonusData($userId, $validDeep, $shareBonusOne) {
  2595. $bonusUserList = CalcCache::getShareBonusOneRelation($userId, $this->_periodNum, $validDeep);
  2596. if( !$bonusUserList ) {
  2597. unset($bonusUserList);
  2598. return [];
  2599. }
  2600. $bonusUserData = [];
  2601. $bonusUserTotalPerf = 0;
  2602. $bonusUserRealList = [];
  2603. foreach ($bonusUserList as $bonusUserId) {
  2604. //查看该用户的个人业绩和团队新增业绩总和
  2605. $nowPeriodData = CalcCache::nowPeriodPerf($bonusUserId, $this->_periodNum);
  2606. //本期新增业绩
  2607. $bonusUserPerf = $nowPeriodData['PV_PCS'] + $nowPeriodData['PV_PSS'];
  2608. if ($bonusUserPerf <= 0) {
  2609. unset($bonusUserId, $nowPeriodData, $bonusUserPerf);
  2610. continue;
  2611. }
  2612. $bonusUserTotalPerf += $bonusUserPerf;
  2613. $bonusUserRealList[] = [
  2614. 'bonusUserId' => $bonusUserId,
  2615. 'bonusUserPerf' => $bonusUserPerf,
  2616. ];
  2617. unset($bonusUserId, $nowPeriodData, $bonusUserPerf);
  2618. }
  2619. unset($bonusUserList);
  2620. foreach ($bonusUserRealList as $everyData) {
  2621. $bonusUserData[] = [
  2622. 'bonusUid' => $everyData['bonusUserId'],
  2623. 'bonus' => $shareBonusOne * $everyData['bonusUserPerf'] / $bonusUserTotalPerf,
  2624. 'validMinPv' => false
  2625. ];
  2626. unset($everyData);
  2627. }
  2628. unset($bonusUserRealList);
  2629. return $bonusUserData;
  2630. }
  2631. /**
  2632. * 获取达标奖的金额
  2633. * @param $amount
  2634. * @return int|mixed
  2635. */
  2636. private function _jxStandardAwardAmount($amount) {
  2637. // $jxStandardConfig = Json::decode($this->_sysConfig['jxStandard']['VALUE']);
  2638. // $awardAmount = 0;
  2639. // foreach ($jxStandardConfig as $everyData) {
  2640. // if( $amount >= $everyData['salesCondition'] ) {
  2641. // $awardAmount = $everyData['awardAmount'];
  2642. // }
  2643. // unset($everyData);
  2644. // }
  2645. //
  2646. // return $awardAmount;
  2647. $realTimes = floor($amount/self::JX_STANDARD_BASE_AMOUNT);
  2648. $calcTimes = min($realTimes, self::JX_STANDARD_MAX_TIMES);
  2649. $awardAmount = $calcTimes * self::JX_STANDARD_BASE_AMOUNT * self::JX_STANDARD_BONUS_PERCENT / 100;
  2650. unset($amount, $realTimes, $calcTimes);
  2651. return $awardAmount;
  2652. }
  2653. /**
  2654. * 获取达标奖的最小条件
  2655. * @return int|mixed
  2656. */
  2657. private function _jxStandardMinSaleCondition() {
  2658. return self::JX_STANDARD_BASE_AMOUNT;
  2659. }
  2660. /**
  2661. * 处理只留最大业绩的逻辑
  2662. * @param $userId
  2663. * @param $perfArr
  2664. */
  2665. private function dealWithMaxPerf($userId, $perfArr) {
  2666. $maxPerf = max($perfArr);
  2667. $hitMaxPerf = false;
  2668. foreach ($perfArr as $key=>$everyPerf) {
  2669. if( !$hitMaxPerf && $everyPerf == $maxPerf ) {
  2670. $hitMaxPerf = true;
  2671. }else {
  2672. $perfArr[$key] = 0;
  2673. }
  2674. unset($key, $everyPerf);
  2675. }
  2676. //更新数据库
  2677. PerfMonth::updateAll($perfArr, 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [
  2678. 'USER_ID' => $userId,
  2679. 'CALC_MONTH' => $this->_calcYearMonth
  2680. ]);
  2681. unset($userId, $maxPerf, $hitMaxPerf, $perfArr);
  2682. }
  2683. /**
  2684. * VIP奖其它市场的报单业绩是否能满足
  2685. * @param $perfArr
  2686. * @return bool
  2687. */
  2688. private function _isCanVipBonusOtherAreaPerf($perfArr) {
  2689. $maxAreaPerf = max($perfArr);
  2690. $totalAreaPerf = array_sum($perfArr);
  2691. $diffAreaPerf = strval($totalAreaPerf - $maxAreaPerf);
  2692. if( $diffAreaPerf >= $this->_sysConfig['vipBonusOtherDepartPvCondition']['VALUE'] ) {
  2693. unset($maxAreaPerf, $totalAreaPerf, $perfArr);
  2694. return true;
  2695. }else {
  2696. unset($maxAreaPerf, $totalAreaPerf, $perfArr);
  2697. return false;
  2698. }
  2699. }
  2700. /**
  2701. * 给父级计算的荣衔奖
  2702. * @param $userId
  2703. * @param $userBaseInfo
  2704. * @param $userEmpLevelSort
  2705. * @param $qyBonus
  2706. * @return array
  2707. */
  2708. public function calcParentYC($userId, $userBaseInfo, $userEmpLevelSort, $qyBonus) {
  2709. if( $userEmpLevelSort <= EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'] ) return [];
  2710. $validDeep = 0;
  2711. $bonusDataList = [];
  2712. $this->loopRelationParentDo($userId, function ($parent) use ($userId, $userEmpLevelSort, &$validDeep, &$bonusDataList) {
  2713. $bonusUserId = $parent['PARENT_UID'];
  2714. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2715. $bonusUserEmpLevel = $this->_empLevelConfig[$bonusUserInfo['EMP_LV']];
  2716. $bonusUserEmpLevelSort = $bonusUserEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  2717. unset($bonusUserInfo, $bonusUserEmpLevel);
  2718. //必须是有聘级的用户
  2719. if( $bonusUserEmpLevelSort <= EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'] ) return self::LOOP_CONTINUE;
  2720. //超过级别就停止
  2721. if( $bonusUserEmpLevelSort > $userEmpLevelSort) return self::LOOP_FINISH;
  2722. //级别小于就跳过
  2723. if( $bonusUserEmpLevelSort < $userEmpLevelSort ) return self::LOOP_CONTINUE;
  2724. $validDeep++;
  2725. array_push($bonusDataList, [
  2726. 'bonusUserId' => $bonusUserId,
  2727. 'bonusType' => $validDeep,
  2728. ]);
  2729. if( $validDeep >= 2 ) return self::LOOP_FINISH;
  2730. unset($bonusUserId, $bonusUserEmpLevelSort);
  2731. });
  2732. $insertBonusData = [];
  2733. foreach ($bonusDataList as $bonusUserData) {
  2734. $bonusUserId = $bonusUserData['bonusUserId'];
  2735. $bonusMonthPerfData = CalcCache::nowMonthPerf($bonusUserId, $this->_periodNum);
  2736. $fxPvStatus = $bonusMonthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2737. unset($bonusMonthPerfData);
  2738. if( !$fxPvStatus ) continue;
  2739. unset($fxPvStatus);
  2740. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2741. $bonusEmpLevelId = $bonusUserInfo['EMP_LV'];
  2742. $newEmpBonus = Tool::formatPrice($qyBonus * $this->_sysConfig['sameEmpLevelPercent']['VALUE'] / 100);
  2743. //总金额限制
  2744. $newEmpBonus = $this->bonusTotalLimit($newEmpBonus, $bonusUserId, $bonusUserInfo['REC_NUM'], $bonusUserInfo['ZC_AMOUNT']);
  2745. if( $newEmpBonus <= 0 ) continue;
  2746. //扣除相应的复消积分和管理费
  2747. $newEmpBonus = Tool::formatPrice($newEmpBonus);
  2748. $deductData = $this->deduct($bonusUserId, $newEmpBonus);
  2749. CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_YC_EXTRA', $newEmpBonus, $deductData);
  2750. // 把育成津贴追加到育成津贴结算表,以便奖金追溯育成津贴用
  2751. $insertBonusData[] = [
  2752. 'ID' => SnowFake::instance()->generateId(),
  2753. 'USER_ID' => $bonusUserId,
  2754. 'LAST_DEC_LV' => $bonusUserInfo['DEC_LV'],
  2755. 'LAST_EMP_LV' => $bonusUserInfo['EMP_LV'],
  2756. 'LAST_STATUS' => $bonusUserInfo['STATUS'],
  2757. 'FROM_USER_ID' => $userId,
  2758. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2759. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2760. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2761. 'DEEP' => 1,
  2762. 'AMOUNT' => $deductData['surplus'],
  2763. 'ORI_BONUS' => $newEmpBonus,
  2764. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2765. 'MANAGE_TAX' => $deductData['manageTax'],
  2766. 'BONUS_TYPE' => $bonusUserData['bonusType'],
  2767. 'PERIOD_NUM' => $this->_periodNum,
  2768. 'CALC_MONTH' => $this->_calcYearMonth,
  2769. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2770. 'CREATED_AT' => Date::nowTime(),
  2771. 'LOGS' => json_encode([
  2772. 'empLevelId' => $bonusEmpLevelId,
  2773. 'qyBonus' => $qyBonus,
  2774. 'sameEmpLevelPercent' => $this->_sysConfig['sameEmpLevelPercent']['VALUE'],
  2775. ]),
  2776. ];
  2777. unset($newEmpBonus, $bonusEmpLevelId, $bonusUserId, $bonusUserInfo, $deductData);
  2778. }
  2779. unset($userId, $userBaseInfo, $userEmpLevelSort, $qyBonus, $bonusDataList);
  2780. return $insertBonusData;
  2781. }
  2782. /**
  2783. * 对碰
  2784. * @param array $oriPerfArr
  2785. * @param array $perfArr
  2786. * @param $percent
  2787. * @param $loopTimes
  2788. * @return array
  2789. */
  2790. public function touchPerf(array $oriPerfArr, array $perfArr, $percent, $loopTimes=1) {
  2791. $resultArr = $oriPerfArr;
  2792. foreach ($perfArr as $keyT => $perfT) {
  2793. if ($perfT <= 0) {
  2794. unset($perfArr[$keyT]);
  2795. }
  2796. }
  2797. if (count($perfArr) >= 2 && $loopTimes < 6) {
  2798. arsort($perfArr, SORT_NUMERIC);
  2799. $onePerf = null;
  2800. $oneKey = null;
  2801. // $touchSurplusAmount = 0;
  2802. $touchAmount = 0;
  2803. // 前两个进行对碰
  2804. foreach ($perfArr as $key => $perf) {
  2805. if ($onePerf === null) {
  2806. $oneKey = $key;
  2807. $onePerf = $perf;
  2808. } else {
  2809. $touchSurplusAmount = $perf - $onePerf;
  2810. if ($touchSurplusAmount > 0) {
  2811. unset($perfArr[$oneKey]);
  2812. $resultArr['perfArr'][$oneKey] = 0;
  2813. $perfArr[$key] = $touchSurplusAmount;
  2814. $touchAmount = $onePerf;
  2815. } elseif ($touchSurplusAmount < 0) {
  2816. unset($perfArr[$key]);
  2817. $resultArr['perfArr'][$key] = 0;
  2818. $perfArr[$oneKey] = abs($touchSurplusAmount);
  2819. $touchAmount = $perf;
  2820. } else {
  2821. unset($perfArr[$oneKey], $perfArr[$key]);
  2822. $resultArr['perfArr'][$oneKey] = 0;
  2823. $resultArr['perfArr'][$key] = 0;
  2824. $touchAmount = $perf;
  2825. }
  2826. break;
  2827. }
  2828. }
  2829. /*if ($touchAmount > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2830. $touchAmount = $nowDecLevelConfig['QY_TOUCH_CAP'];
  2831. }*/
  2832. $touchBonus = Tool::formatPrice($touchAmount * $percent);
  2833. // if ($touchBonus > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2834. // $resultArr['touchBonus'] += $nowDecLevelConfig['QY_TOUCH_CAP'];
  2835. // } else {
  2836. // $resultArr['touchBonus'] += $touchBonus;
  2837. // }
  2838. $resultArr['touchBonus'] += $touchBonus;
  2839. foreach ($perfArr as $keyR => $perfR) {
  2840. $resultArr['perfArr'][$keyR] = $perfR;
  2841. }
  2842. return $this->touchPerf($resultArr, $perfArr, $percent, $loopTimes+1);
  2843. }
  2844. return $resultArr;
  2845. }
  2846. /**
  2847. * 对碰
  2848. * @param array $oriPerfArr
  2849. * @param array $perfArr
  2850. * @param $decLevel
  2851. * @param $decLevelConfig
  2852. * @param $loopTimes
  2853. * @return array
  2854. */
  2855. public function touchPerfBefore(array $oriPerfArr, array $perfArr, $decLevel, $decLevelConfig, $loopTimes=1) {
  2856. $resultArr = $oriPerfArr;
  2857. foreach ($perfArr as $keyT => $perfT) {
  2858. if ($perfT <= 0) {
  2859. unset($perfArr[$keyT]);
  2860. }
  2861. }
  2862. if (count($perfArr) >= 2 && $loopTimes < 6) {
  2863. $nowDecLevelConfig = $decLevelConfig[$decLevel];
  2864. arsort($perfArr, SORT_NUMERIC);
  2865. $onePerf = null;
  2866. $oneKey = null;
  2867. // $touchSurplusAmount = 0;
  2868. $touchAmount = 0;
  2869. // 前两个进行对碰
  2870. foreach ($perfArr as $key => $perf) {
  2871. if ($onePerf === null) {
  2872. $oneKey = $key;
  2873. $onePerf = $perf;
  2874. } else {
  2875. $touchSurplusAmount = $perf - $onePerf;
  2876. if ($touchSurplusAmount > 0) {
  2877. unset($perfArr[$oneKey]);
  2878. $resultArr['perfArr'][$oneKey] = 0;
  2879. $perfArr[$key] = $touchSurplusAmount;
  2880. $touchAmount = $onePerf;
  2881. } elseif ($touchSurplusAmount < 0) {
  2882. unset($perfArr[$key]);
  2883. $resultArr['perfArr'][$key] = 0;
  2884. $perfArr[$oneKey] = abs($touchSurplusAmount);
  2885. $touchAmount = $perf;
  2886. } else {
  2887. unset($perfArr[$oneKey], $perfArr[$key]);
  2888. $resultArr['perfArr'][$oneKey] = 0;
  2889. $resultArr['perfArr'][$key] = 0;
  2890. $touchAmount = $perf;
  2891. }
  2892. break;
  2893. }
  2894. }
  2895. /*if ($touchAmount > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2896. $touchAmount = $nowDecLevelConfig['QY_TOUCH_CAP'];
  2897. }*/
  2898. $touchBonus = Tool::formatPrice($touchAmount * 2 / 100);
  2899. // if ($touchBonus > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2900. // $resultArr['touchBonus'] += $nowDecLevelConfig['QY_TOUCH_CAP'];
  2901. // } else {
  2902. // $resultArr['touchBonus'] += $touchBonus;
  2903. // }
  2904. $resultArr['touchBonus'] += $touchBonus;
  2905. foreach ($perfArr as $keyR => $perfR) {
  2906. $resultArr['perfArr'][$keyR] = $perfR;
  2907. }
  2908. return $this->touchPerfBefore($resultArr, $perfArr, $decLevel, $decLevelConfig, $loopTimes+1);
  2909. }
  2910. return $resultArr;
  2911. }
  2912. /**
  2913. * 循环父级并执行回调函数
  2914. * @param $userId
  2915. * @param callable $callbackFunc
  2916. * @param int $offset
  2917. * @return bool
  2918. */
  2919. public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
  2920. $allParents = Cache::getAllNetworkParents($userId);
  2921. $allData = array_slice($allParents, $offset, $this->_limit);
  2922. unset($allParents);
  2923. if ($allData) {
  2924. foreach ($allData as $data) {
  2925. $funcResult = $callbackFunc($data);
  2926. if ($funcResult === self::LOOP_FINISH) {
  2927. return true;
  2928. } elseif ($funcResult === self::LOOP_CONTINUE) {
  2929. continue;
  2930. }
  2931. unset($data, $funcResult);
  2932. }
  2933. unset($allData);
  2934. return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
  2935. }
  2936. return true;
  2937. }
  2938. /**
  2939. * 循环推荐网络的父级
  2940. * @param $userId
  2941. * @param callable $callbackFunc
  2942. * @param int $offset
  2943. * @return bool
  2944. */
  2945. public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
  2946. $allParents = Cache::getAllRelationParents($userId);
  2947. $allData = array_slice($allParents, $offset, $this->_limit);
  2948. unset($allParents);
  2949. if ($allData) {
  2950. foreach ($allData as $data) {
  2951. $funcResult = $callbackFunc($data);
  2952. if ($funcResult === self::LOOP_FINISH) {
  2953. return true;
  2954. } elseif ($funcResult === self::LOOP_CONTINUE) {
  2955. continue;
  2956. }
  2957. unset($data, $funcResult);
  2958. }
  2959. unset($allData);
  2960. return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
  2961. }
  2962. return true;
  2963. }
  2964. /**
  2965. * 共享奖,判断当期此用户,是否有原报单团队奖金
  2966. */
  2967. public function checkHasOriBonusQyBd($userId) {
  2968. //判断$parent是否有首单团队奖
  2969. $bonus = CalcCache::bonus($userId, $this->_periodNum);
  2970. if( isset($bonus['ORI_BONUS_QY_BD']) && $bonus['ORI_BONUS_QY_BD'] > 0 ) {
  2971. return true;
  2972. }
  2973. return false;
  2974. }
  2975. /**
  2976. * 判断除大市场外 其它市场的报单业绩
  2977. * @param $userId
  2978. * @return bool
  2979. * @throws \yii\db\Exception
  2980. */
  2981. public function checkSmallMarketPerf($userId) {
  2982. // 从缓存中获取会员的上期结余业绩信息
  2983. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  2984. //判断出大市场
  2985. $areaNums = [1, 2, 3];
  2986. $maxArea = 0;
  2987. $maxSurplusPerf = 0;
  2988. foreach ($areaNums as $area) {
  2989. $areaKey = sprintf('SURPLUS_%dL', $area);
  2990. if ( isset($pervSurplusPerf[$areaKey]) && $pervSurplusPerf[$areaKey] > $maxSurplusPerf ) {
  2991. $maxArea = $area;
  2992. $maxSurplusPerf = $pervSurplusPerf[$areaKey];
  2993. }
  2994. unset($area, $areaKey);
  2995. }
  2996. unset($pervSurplusPerf, $maxSurplusPerf);
  2997. $otherAreaZcPv = 0;
  2998. $nowPeriodPerf = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  2999. foreach ($areaNums as $area) {
  3000. if( $maxArea > 0 && $area === $maxArea ) continue;
  3001. $areaKey = sprintf('PV_%dL_ZC', $area);
  3002. if ( isset($nowPeriodPerf[$areaKey]) && $nowPeriodPerf[$areaKey] > 0 ) {
  3003. $otherAreaZcPv += $nowPeriodPerf[$areaKey];
  3004. }
  3005. unset($area, $areaKey);
  3006. }
  3007. unset($nowPeriodPerf, $areaNums, $maxArea);
  3008. return $otherAreaZcPv >= self::MIN_BD_PV;
  3009. }
  3010. /**
  3011. * 获取有最小报单PV的用效父级
  3012. * @param $userId
  3013. * @return string
  3014. */
  3015. public function getMinBdPvRelationParent($userId) {
  3016. $validParentId = '';
  3017. $this->loopRelationParentDo($userId, function ($parent) use(&$validParentId) {
  3018. if ( $this->checkSmallMarketPerf($parent['PARENT_UID']) ) {
  3019. $validParentId = $parent['PARENT_UID'];
  3020. unset($parent);
  3021. return self::LOOP_FINISH;
  3022. }
  3023. unset($parent);
  3024. });
  3025. return$validParentId;
  3026. }
  3027. /**
  3028. * 获取有最小报单PV的用效父级 20220407修改成是否此期此用户有原报单团队奖金
  3029. * @param $userId
  3030. * @return string
  3031. */
  3032. public function getMinBdPvNetworkParent($userId, $openFindLimit = 1, $findLimitTimes = 5) {
  3033. $validParentId = '';
  3034. $validDeep = 1;
  3035. $this->loopNetworkParentDo($userId, function ($parent) use(&$validParentId,&$validDeep,$openFindLimit,$findLimitTimes) {
  3036. if ( $this->checkHasOriBonusQyBd($parent['PARENT_UID']) ) {
  3037. $validParentId = $parent['PARENT_UID'];
  3038. unset($parent);
  3039. return self::LOOP_FINISH;
  3040. }
  3041. // 只找5层
  3042. if ( $openFindLimit && $validDeep >= $findLimitTimes ) {
  3043. unset($parent);
  3044. return self::LOOP_FINISH;
  3045. }
  3046. $validDeep += 1;
  3047. unset($parent);
  3048. });
  3049. return$validParentId;
  3050. }
  3051. // public function getMinBdPvNetworkParent($userId, $openFindLimit = 1, $findLimitTimes = 5) {
  3052. // $validParentId = '';
  3053. // $validDeep = 1;
  3054. // $this->loopNetworkParentDo($userId, function ($parent) use(&$validParentId,&$validDeep,$openFindLimit,$findLimitTimes) {
  3055. // if ( $this->checkSmallMarketPerf($parent['PARENT_UID']) ) {
  3056. // $validParentId = $parent['PARENT_UID'];
  3057. // unset($parent);
  3058. // return self::LOOP_FINISH;
  3059. // }
  3060. // // 只找5层
  3061. // if ( $openFindLimit && $validDeep >= $findLimitTimes ) {
  3062. // unset($parent);
  3063. // return self::LOOP_FINISH;
  3064. // }
  3065. // $validDeep += 1;
  3066. // unset($parent);
  3067. // });
  3068. // return$validParentId;
  3069. // }
  3070. /**
  3071. * 按级别的收入上限
  3072. * 新的需求调整: 改成不按月进行限制,并且去掉vip奖
  3073. * @param $bonus
  3074. * @param $userId
  3075. * @param $declarationLevel
  3076. * @return float
  3077. */
  3078. public function declarationLevelCap($bonus, $userId, $declarationLevel) {
  3079. $decLevelConfig = $this->_decLevelConfig;
  3080. $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
  3081. unset($decLevelConfig);
  3082. $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'];
  3083. if( $bonus <= $maxGetBonus) {
  3084. return $bonus;
  3085. }else {
  3086. return $maxGetBonus;
  3087. }
  3088. }
  3089. // public function declarationLevelCap($bonus, $userId, $declarationLevel) {
  3090. // $decLevelConfig = $this->_decLevelConfig;
  3091. // $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
  3092. // unset($decLevelConfig);
  3093. // //本月往期奖金 这里执行速度可能慢一些,但需求如此没有办法
  3094. // $lastData = CalcCache::lastPeriodMonthCalcBonus($userId, $this->_periodNum, $this->_calcMonth);
  3095. // $lastTotal = $lastData['ORI_BONUS_QY_SUM'] + $lastData['ORI_BONUS_VIP_SUM'];
  3096. // // 从缓存中获取用户的奖金
  3097. // $bonusData = CalcCache::bonus($userId, $this->_periodNum);
  3098. // $thisTotal = $bonusData['ORI_BONUS_QY'] + $bonusData['ORI_BONUS_VIP'];
  3099. // $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'] * $this->_calcMonthPeriodNumCount - $lastTotal - $thisTotal;
  3100. // unset($lastData, $lastTotal, $bonusData, $thisTotal);
  3101. // if( $maxGetBonus <= 0 ) return 0.00;
  3102. // if( $bonus <= $maxGetBonus) {
  3103. // return $bonus;
  3104. // }else {
  3105. // return $maxGetBonus;
  3106. // }
  3107. // }
  3108. /**
  3109. * 总奖金限制
  3110. * @param $bonus
  3111. * @param $userId
  3112. * @param $recNum
  3113. * @param $decAmount
  3114. * @return float
  3115. */
  3116. public function bonusTotalLimit($bonus, $userId, $recNum, $decAmount) {
  3117. //@todo 临时不做总奖金限制
  3118. return $bonus;
  3119. if( $recNum >= 3 ) return $bonus;
  3120. $limitAmount = 0;
  3121. switch ($recNum) {
  3122. case 0:
  3123. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalZeroLimit']['VALUE'];
  3124. break;
  3125. case 1:
  3126. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalOneLimit']['VALUE'];
  3127. break;
  3128. case 2:
  3129. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalTwoLimit']['VALUE'];
  3130. break;
  3131. default:
  3132. break;
  3133. }
  3134. // 从缓存中获取用户的奖金
  3135. $lastUserBonus = CalcCache::LastUserBonus($userId, $this->_periodNum);//往期的总金额
  3136. $bonusData = CalcCache::bonus($userId, $this->_periodNum);
  3137. $bonusTotal = $bonusData['BONUS_TOTAL'] + $lastUserBonus['BONUS_TOTAL'];
  3138. unset($lastUserBonus, $userId, $recNum, $decAmount, $bonusData);
  3139. if( $bonusTotal >= $limitAmount ) return 0.00;
  3140. if( $bonusTotal + $bonus <= $limitAmount) {
  3141. return $bonus;
  3142. }else {
  3143. return $limitAmount - $bonusTotal;
  3144. }
  3145. }
  3146. /**
  3147. * 扣除复消积分和管理费
  3148. * @param $userId
  3149. * @param $bonus
  3150. * @return array
  3151. * @throws \yii\db\Exception
  3152. */
  3153. public function deductNoReconsumePoints($userId, $bonus): array
  3154. {
  3155. $manageTax = $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
  3156. $surplus = $bonus - $manageTax;
  3157. return [
  3158. 'reConsumePoints' => 0.00,
  3159. 'manageTax' => Tool::formatPrice($manageTax),
  3160. 'surplus' => Tool::formatPrice($surplus),
  3161. ];
  3162. }
  3163. /**
  3164. * 扣除复消积分和管理费
  3165. * @param $userId
  3166. * @param $bonus
  3167. * @return array
  3168. * @throws \yii\db\Exception
  3169. */
  3170. public function deduct($userId, $bonus) {
  3171. //判断是否达到了本月扣除复消的上限
  3172. $cacheData = CalcCache::monthLastPeriodReconsumePoints($userId, $this->_periodNum, $this->_calcYearMonth);
  3173. $bonusCache = CalcCache::bonus($userId, $this->_periodNum);
  3174. $reConsumePointsTotal = $bonusCache['RECONSUME_POINTS'] + $cacheData['RECONSUME_POINTS_SUM'];
  3175. $reConsumePointsCap = $this->_sysConfig['reConsumePointsMonthCap']['VALUE'];
  3176. unset($cacheData, $bonusCache);
  3177. $reConsumePoints = 0;
  3178. if( $reConsumePointsTotal < $reConsumePointsCap ) {
  3179. $reConsumePoints = $bonus * $this->_sysConfig['reConsumePointsPercent']['VALUE'] / 100;
  3180. $reConsumePoints = min($reConsumePoints, $reConsumePointsCap-$reConsumePointsTotal);
  3181. }
  3182. unset($reConsumePointsTotal, $reConsumePointsCap);
  3183. $manageTax = $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
  3184. $surplus = $bonus - $reConsumePoints - $manageTax;
  3185. return [
  3186. 'reConsumePoints' => Tool::formatPrice($reConsumePoints),//复效积分
  3187. 'manageTax' => Tool::formatPrice($manageTax),//管理费
  3188. 'surplus' => Tool::formatPrice($surplus),//真实奖金
  3189. ];
  3190. }
  3191. /**
  3192. * 更新百分比并发送
  3193. * @param $percent
  3194. */
  3195. private function _updatePercent($percent) {
  3196. // 把数据写入数据库中
  3197. Period::updateAll(['CALC_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  3198. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'CALC_PERCENT']);
  3199. }
  3200. /**
  3201. * 把往期有月奖金的会员加到本期有奖会员缓存列表中
  3202. * @param int $offset
  3203. * @return bool
  3204. */
  3205. public function loopMonthBonusUserFromDbToCache($offset = 0) {
  3206. if (!$this->_isCalcMonth) {
  3207. return true;
  3208. }
  3209. $allData = CalcMonthBonusUser::findUseDbCalc()->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->offset($offset)->limit($this->_limit)->asArray()->all();
  3210. if ( $allData ) {
  3211. foreach ($allData as $everyData) {
  3212. CalcCache::addHasBonusUsers($everyData['USER_ID'], $this->_periodNum);
  3213. unset($everyData);
  3214. }
  3215. unset($allData);
  3216. $this->loopMonthBonusUserFromDbToCache($offset + $this->_limit);
  3217. }
  3218. unset($allData);
  3219. return true;
  3220. }
  3221. /**
  3222. * 把缓存中的月奖用户信息存到数据库
  3223. * @param int $offset
  3224. * @return bool
  3225. * @throws \yii\db\Exception
  3226. */
  3227. public function loopMonthBonusUserToDb($offset = 0) {
  3228. echo sprintf("时间:[%s]月奖会员入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3229. $allData = CalcCache::getHasMonthBonusUsers($this->_periodNum, $offset, $this->_limit);
  3230. if($allData) {
  3231. $insertDataBonusUser = [];
  3232. foreach($allData as $userId){
  3233. $insertDataBonusUser[] = [
  3234. 'ID' => SnowFake::instance()->generateId(),
  3235. 'USER_ID' => $userId,
  3236. 'CALC_MONTH' => $this->_calcYearMonth,
  3237. 'PERIOD_NUM' => $this->_periodNum,
  3238. 'CREATED_AT' => Date::nowTime()
  3239. ];
  3240. unset($userId);
  3241. }
  3242. if( $insertDataBonusUser ) CalcMonthBonusUser::batchInsert($insertDataBonusUser);
  3243. unset($insertDataBonus, $allData);
  3244. return $this->loopMonthBonusUserToDb($offset + $this->_limit);
  3245. }
  3246. unset($allData);
  3247. return true;
  3248. }
  3249. //奖金入库
  3250. /**
  3251. * 循环奖服务奖金会员,并入库
  3252. * @param int $offset
  3253. * @return bool
  3254. * @throws \yii\db\Exception
  3255. */
  3256. public function loopBonusUsers($offset = 0) {
  3257. echo sprintf("时间:[%s]缓存奖金数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3258. // 从缓存列表里面从底层往上倒序获取会员
  3259. // 这里有问题,因为蓝星奖,是存储过程计算的,并没有加入缓存,这里需要修改.
  3260. // 给用户发送兑换积分,也需要进行调整查看。
  3261. // CalcCache::addHasBonusUsers($everyData['USER_ID'], $this->_periodNum);
  3262. $allData = CalcCache::getHasBonusUsers($this->_periodNum, $offset, $this->_limit);
  3263. if($allData){
  3264. $insertDataBonus = [];
  3265. foreach($allData as $userId){
  3266. $tempBonusData = $this->bonusData($userId);
  3267. if(!empty($tempBonusData['result'])){
  3268. $insertDataBonus[] = $tempBonusData['result'];
  3269. }
  3270. unset($userId, $tempBonusData);
  3271. }
  3272. CalcBonus::batchInsert($insertDataBonus);
  3273. unset($insertDataBonus, $allData);
  3274. return $this->loopBonusUsers($offset + $this->_limit);
  3275. }
  3276. return true;
  3277. }
  3278. // 奖金入库完成,将各个奖金计算流水会员聘级,更新成蓝星奖当时计算的聘级
  3279. public function loopCalcBlueEmpLv($offset = 0) {
  3280. if( !$this->_isCalcMonth ) {
  3281. // 不是结算月,则不需要进行聘级调整
  3282. return false;
  3283. }
  3284. // 从缓存获取分页有收入的会员信息
  3285. $allData = CalcBonusBS::findUseDbCalc()
  3286. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  3287. ->groupBy('USER_ID')
  3288. ->offset($offset)
  3289. ->limit($this->_limit)
  3290. ->asArray()
  3291. ->all();
  3292. if ($allData) {
  3293. foreach ($allData as $data) {
  3294. $nowBsEmpLv = $data['LEVEL_ID']; // 当前蓝星奖计算(即管理奖) 的等级
  3295. // 修改AR_CALC_BONUS的LAST_EMP_LV聘级,修改奖金流水的聘级AR_FLOW_BONUS表的LAST_EMP_LV
  3296. // 期结算结果
  3297. CalcBonus::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3298. [
  3299. ':USER_ID' => $data['USER_ID'],
  3300. ':PERIOD_NUM' => $this->_periodNum
  3301. ]
  3302. );
  3303. // // 奖金流水
  3304. // FlowBonus::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3305. // [
  3306. // ':USER_ID' => $data['USER_ID'],
  3307. // ':PERIOD_NUM' => $this->_periodNum
  3308. // ]
  3309. // );
  3310. // // 共享奖流水
  3311. // CalcBonusGX::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3312. // [
  3313. // ':USER_ID' => $data['USER_ID'],
  3314. // ':PERIOD_NUM' => $this->_periodNum
  3315. // ]
  3316. // );
  3317. // 推广奖流水
  3318. CalcBonusTG::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3319. [
  3320. ':USER_ID' => $data['USER_ID'],
  3321. ':PERIOD_NUM' => $this->_periodNum
  3322. ]
  3323. );
  3324. // 团队奖流水
  3325. CalcBonusQY::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3326. [
  3327. ':USER_ID' => $data['USER_ID'],
  3328. ':PERIOD_NUM' => $this->_periodNum
  3329. ]
  3330. );
  3331. // // 服务奖流水
  3332. // CalcBonusBD::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3333. // [
  3334. // ':USER_ID' => $data['USER_ID'],
  3335. // ':PERIOD_NUM' => $this->_periodNum
  3336. // ]
  3337. // );
  3338. // // 更新form的聘级
  3339. // CalcBonusGX::updateAll(['LAST_FROM_EMP_LV' => $nowBsEmpLv], 'FROM_USER_ID=:FROM_USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3340. // [
  3341. // ':FROM_USER_ID' => $data['USER_ID'],
  3342. // ':PERIOD_NUM' => $this->_periodNum
  3343. // ]
  3344. // );
  3345. CalcBonusTG::updateAll(['LAST_FROM_EMP_LV' => $nowBsEmpLv], 'FROM_USER_ID=:FROM_USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3346. [
  3347. ':FROM_USER_ID' => $data['USER_ID'],
  3348. ':PERIOD_NUM' => $this->_periodNum
  3349. ]
  3350. );
  3351. // CalcBonusBD::updateAll(['LAST_FROM_EMP_LV' => $nowBsEmpLv], 'FROM_USER_ID=:FROM_USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3352. // [
  3353. // ':FROM_USER_ID' => $data['USER_ID'],
  3354. // ':PERIOD_NUM' => $this->_periodNum
  3355. // ]
  3356. // );
  3357. }
  3358. unset($allData);
  3359. return $this->loopCalcBlueEmpLv($offset + $this->_limit);
  3360. }
  3361. unset($allData);
  3362. return true;
  3363. }
  3364. /**
  3365. * 奖金
  3366. * @param $userId
  3367. * @return array
  3368. * @throws \yii\db\Exception
  3369. */
  3370. public function bonusData($userId) {
  3371. // 从缓存中获取用户的奖金
  3372. $bonus = CalcCache::bonus($userId, $this->_periodNum);
  3373. $standardBonus = CalcCache::standardBonus($userId, $this->_periodNum);
  3374. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  3375. $perfData = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  3376. $tourismBonus = CalcCache::tourismBonus($userId, $this->_periodNum);
  3377. $garageBonus = CalcCache::garageBonus($userId, $this->_periodNum);
  3378. $villaBonus = CalcCache::villaBonus($userId, $this->_periodNum);
  3379. $nowDirectorLv = $baseInfo['EMP_LV'];
  3380. // if($this->_isCalcMonth){
  3381. // $empLv = $this->nowMonthPerfData($userId)['LAST_EMP_LV'];
  3382. // }
  3383. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  3384. // 星级
  3385. $starCrownLv = CalcCache::getUserStarCrown($userId, $this->_periodNum);
  3386. // //没有共享和管理奖 以前的管理奖和共享奖逻辑
  3387. // $bonusReal = $bonus['BONUS_BD'] + $bonus['BONUS_TG'] + $bonus['BONUS_XF'] + $bonus['BONUS_YJ'] + $bonus['BONUS_QY'] + $bonus['BONUS_YC'] + $bonus['BONUS_YC_EXTRA'] + $bonus['BONUS_VIP'] + $standardBonus;
  3388. // $realBonusGx = 0;
  3389. // $realBonusGl = 0;
  3390. // if( $this->_isCalcMonth ) {
  3391. // //查看是否复消300
  3392. // $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  3393. // $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  3394. // if ( $fxPvStatus ) {//加上本期和往期的共享和管理奖
  3395. // $monthSumData = CalcBonus::findUseSlaves()->select('SUM(BONUS_GX) AS BONUS_GX_SUM, SUM(BONUS_GL) AS BONUS_GL_SUM')->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth])->asArray()->one();
  3396. // $bonusGxSum = $monthSumData['BONUS_GX_SUM'] ?? 0;
  3397. // $bonusGlSum = $monthSumData['BONUS_GL_SUM'] ?? 0;
  3398. // $realBonusGx += $bonusGxSum + $bonus['BONUS_GX'];
  3399. // $realBonusGl += $bonusGlSum + $bonus['BONUS_GL'];
  3400. // $bonusReal += $realBonusGx + $realBonusGl;
  3401. // unset($monthSumData, $bonusGxSum, $bonusGlSum);
  3402. // }
  3403. // }
  3404. //没有共享和管理奖
  3405. $bonusReal = $bonus['BONUS_BD'] + $bonus['BONUS_TG'] + $bonus['BONUS_XF'] + $bonus['BONUS_YJ'] + $bonus['BONUS_QY'] + $bonus['BONUS_YC'] + $bonus['BONUS_YC_EXTRA'] + $bonus['BONUS_VIP'] + $standardBonus + $bonus['BONUS_BS_MNT'] + $bonus['BONUS_BS_ABBR'] + $bonus['BONUS_QUARTER'];
  3406. $realBonusGx = 0;
  3407. $realBonusGl = 0;
  3408. $realBonusBs = 0; // 蓝星管理奖. BlueStar
  3409. $blueStartOriBonus = 0;
  3410. $blueStartManageTax = 0;
  3411. $exchangePoints = 0; // 蓝星奖管理奖. 产生的兑换积分
  3412. $realBonusBsMnt = 0; // 蓝星管理奖——实发奖金
  3413. $blueStartOriBonusMnt = 0; // 蓝星管理奖——原奖金
  3414. $blueStartManageTaxMnt = 0; // 蓝星管理奖——管理费
  3415. $realBonusBsAbbr = 0; // 蓝星业绩奖——实发奖金
  3416. $blueStartOriBonusAbbr = 0; // 蓝星业绩奖——原奖金
  3417. $blueStartManageTaxAbbr = 0; // 蓝星业绩奖——管理费
  3418. if( $this->_isCalcMonth ) {
  3419. // 个人月消费PV大于配置值,才会计算发放蓝星奖
  3420. $fxPvStatus = $this->_isMonthPerfLimit($userId);
  3421. $nowDirectorLv = EmployLevel::getDefaultLevelId();
  3422. // BONUS_REAL 字段是发到用户的真实奖金
  3423. if ( $fxPvStatus ) {
  3424. // 管理奖改成了蓝星奖,但是对于用户来说依旧叫管理奖.字段改成bs.
  3425. // 因为管理奖(即蓝星奖,是用存储过程计算的,则此处直接取AR_CALC_BONUS_BS表中计算的结果数据使用,
  3426. // 并将管理奖结果同步到当前结算月的CalcBonus中)
  3427. // 由于单独奖金流水记录每次都插入,所以倒叙找最新的数据.
  3428. $userBS = CalcBonusBS::find()
  3429. ->where(
  3430. 'PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID',
  3431. [
  3432. ':PERIOD_NUM' => $this->_periodNum,
  3433. ':USER_ID' => $userId
  3434. ]
  3435. )
  3436. ->select('AMOUNT,ORI_BONUS,MANAGE_TAX,LEVEL_ID,PRODUCT_POINT,AMOUNT_MNT,ORI_BONUS_MNT,MANAGE_TAX_MNT,AMOUNT_ABBR,ORI_BONUS_ABBR,MANAGE_TAX_ABBR')
  3437. ->limit(1)
  3438. ->orderBy('CREATED_AT DESC')
  3439. ->asArray()
  3440. ->all();
  3441. $userBS = is_array($userBS) ? reset($userBS) : [];
  3442. $blueStartAmount = isset($userBS['AMOUNT']) && !empty($userBS['AMOUNT']) ? $userBS['AMOUNT'] : 0; // 奖金
  3443. $blueStartOriBonus = isset($userBS['ORI_BONUS']) && !empty($userBS['ORI_BONUS']) ? $userBS['ORI_BONUS'] : 0; // 原奖金
  3444. $blueStartManageTax = isset($userBS['MANAGE_TAX']) && !empty($userBS['MANAGE_TAX']) ? $userBS['MANAGE_TAX'] : 0; // 管理费
  3445. $realBonusBsMnt = $userBS['AMOUNT_MNT'] ?? 0; // 蓝星管理奖. 实发奖金
  3446. $blueStartOriBonusMnt = $userBS['ORI_BONUS_MNT'] ?? 0; // 蓝星管理奖. 原奖金
  3447. $blueStartManageTaxMnt = $userBS['MANAGE_TAX_MNT'] ?? 0; // 蓝星管理奖. 管理费
  3448. $realBonusBsAbbr = $userBS['AMOUNT_ABBR'] ?? 0; // 蓝星业绩奖. 奖金
  3449. $blueStartOriBonusAbbr = $userBS['ORI_BONUS_ABBR'] ?? 0; // 蓝星业绩奖. 原奖金
  3450. $blueStartManageTaxAbbr = $userBS['MANAGE_TAX_ABBR'] ?? 0; // 蓝星业绩奖. 管理费
  3451. $blueStartManageTax += $blueStartManageTaxMnt + $blueStartManageTaxAbbr; // 管理费
  3452. $monthSumData = CalcBonus::findUseSlaves()
  3453. ->select('SUM(BONUS_GX) AS BONUS_GX_SUM, SUM(BONUS_GL) AS BONUS_GL_SUM')
  3454. ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
  3455. [
  3456. 'USER_ID' => $userId,
  3457. 'CALC_MONTH' => $this->_calcYearMonth
  3458. ]
  3459. )
  3460. ->asArray()
  3461. ->one();
  3462. $realBonusBs = $blueStartAmount; // 蓝星奖直接取数据库中算好的值PRODUCT_POINT
  3463. $exchangePoints = isset($userBS['PRODUCT_POINT']) && !empty($userBS['PRODUCT_POINT']) ? $userBS['PRODUCT_POINT'] : 0; // 兑换积分
  3464. // 会员最新$nowDirectorLv
  3465. $nowDirectorLv = $userBS['LEVEL_ID'] ?? $nowDirectorLv;
  3466. // 蓝星奖总奖金:管理奖+业绩奖
  3467. // $blueStartOriBonus = $blueStartOriBonusMnt + $blueStartOriBonusAbbr;
  3468. // $bonus['BONUS_TOTAL'] = $bonus['BONUS_TOTAL'] + $blueStartOriBonus; // 管理奖在存储过程计算,这里单独加上管理奖(即蓝星奖)
  3469. unset($monthSumData, $bonusGxSum, $bonusGlSum);
  3470. }
  3471. }
  3472. if( $this->_isCalcMonth ) { //季度奖
  3473. if(in_array($this->_calcMonth, [3,6,9,12])){ // 季度奖
  3474. }
  3475. }
  3476. // 查询会员本期是否有团队奖
  3477. $userBonusQY = CalcBonusQY::findOneAsArray('PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID',
  3478. [
  3479. ':PERIOD_NUM' => $this->_periodNum,
  3480. ':USER_ID' => $userId
  3481. ]);
  3482. // 会员本期最新CrownLV
  3483. $nowCrownLv = $userBonusQY['LAST_CROWN_LV'] ?? StarCrownLevel::getDefaultLevelId();
  3484. $result = [
  3485. 'USER_ID' => $userId,
  3486. 'LAST_USER_NAME' => $baseInfo['USER_NAME'],
  3487. 'LAST_REAL_NAME' => $baseInfo['REAL_NAME'],
  3488. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  3489. 'LAST_EMP_LV' => $nowDirectorLv,
  3490. 'LAST_CROWN_LV' => $nowCrownLv,
  3491. 'LAST_STATUS' => $baseInfo['STATUS'],
  3492. 'LAST_MOBILE' => $baseInfo['MOBILE'],
  3493. 'LAST_PERIOD_AT' => $baseInfo['PERIOD_NUM'],
  3494. 'LAST_CREATED_AT' => $baseInfo['CREATED_AT'],
  3495. 'LAST_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
  3496. 'LAST_PROVINCE' => $baseInfo['PROVINCE'],
  3497. 'LAST_CITY' => $baseInfo['CITY'],
  3498. 'LAST_COUNTY' => $baseInfo['COUNTY'],
  3499. 'LAST_SYSTEM_ID' => $baseInfo['SYSTEM_ID'] ? $baseInfo['SYSTEM_ID'] : '',
  3500. 'LAST_IS_DIRECT_SELLER' => $baseInfo['IS_DIRECT_SELLER'],
  3501. 'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
  3502. 'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
  3503. 'LAST_CON_USER_NAME' => $baseInfo['CON_USER_NAME'],
  3504. 'LAST_CON_REAL_NAME' => $baseInfo['CON_REAL_NAME'],
  3505. 'EXCHANGE_POINTS' => $exchangePoints, // 兑换积分
  3506. // 'LAST_LOCATION' => $baseInfo['LOCATION'] ? $baseInfo['LOCATION'] : 1,
  3507. //@todo
  3508. 'LAST_LOCATION' => 1,
  3509. 'BONUS_BD' => $bonus['BONUS_BD'],
  3510. 'BONUS_TG' => $bonus['BONUS_TG'],
  3511. 'BONUS_XF' => $bonus['BONUS_XF'],
  3512. 'BONUS_YJ' => $bonus['BONUS_YJ'],
  3513. 'BONUS_GX' => $bonus['BONUS_GX'],
  3514. 'BONUS_GL' => $bonus['BONUS_GL'],
  3515. 'BONUS_QY' => $bonus['BONUS_QY'],
  3516. 'BONUS_YC' => $bonus['BONUS_YC'] + $bonus['BONUS_YC_EXTRA'],
  3517. 'BONUS_VIP' => $bonus['BONUS_VIP'],
  3518. 'RECONSUME_POINTS' => $bonus['RECONSUME_POINTS'],
  3519. 'MANAGE_TAX' => $blueStartManageTax, // 管理费
  3520. 'BONUS_INCOME'=>$bonus['INCOME_TOTAL'],
  3521. 'BONUS_REAL'=> $bonusReal,
  3522. 'BONUS_TOTAL'=>$bonus['BONUS_TOTAL'],
  3523. 'ORI_BONUS_BD' => $bonus['ORI_BONUS_BD'],
  3524. 'ORI_BONUS_TG' => $bonus['ORI_BONUS_TG'],
  3525. 'ORI_BONUS_XF' => $bonus['ORI_BONUS_XF'],
  3526. 'ORI_BONUS_YJ' => $bonus['ORI_BONUS_YJ'],
  3527. 'ORI_BONUS_YJ_BD' => $bonus['ORI_BONUS_YJ_BD'],
  3528. 'ORI_BONUS_YJ_FX' => $bonus['ORI_BONUS_YJ_FX'],
  3529. 'ORI_BONUS_GX' => $bonus['ORI_BONUS_GX'],
  3530. 'REAL_BONUS_GX' => $realBonusGx,
  3531. 'ORI_BONUS_GL' => $bonus['ORI_BONUS_GL'],
  3532. 'REAL_BONUS_GL' => $realBonusGl,
  3533. 'BONUS_BS' => $realBonusBs, // 新的管理奖金,即蓝星管理奖
  3534. 'ORI_BONUS_BS' => $blueStartOriBonus, // 蓝星管理奖金原奖金,即包含管理费
  3535. 'REAL_BONUS_BS' => $realBonusBs, // 实发蓝星管理奖金
  3536. 'BONUS_BS_MNT' => $realBonusBsMnt, // 蓝星管理奖
  3537. 'ORI_BONUS_BS_MNT' => $blueStartOriBonusMnt, // 蓝星管理奖金原奖金,即包含管理费
  3538. 'REAL_BONUS_BS_MNT' => $realBonusBsMnt, // 实发蓝星管理奖金
  3539. 'MANAGE_TAX_MNT' => $blueStartManageTaxMnt, // 实发蓝星管理——管理费
  3540. 'BONUS_BS_ABBR' => $realBonusBsAbbr, // 蓝星业绩奖
  3541. 'ORI_BONUS_BS_ABBR' => $blueStartOriBonusAbbr, // 蓝星业绩奖金原奖金,即包含管理费
  3542. 'REAL_BONUS_BS_ABBR' => $realBonusBsAbbr, // 实发蓝星业绩奖金
  3543. 'MANAGE_TAX_ABBR' => $blueStartManageTaxAbbr, // 实发蓝星业绩奖——管理费
  3544. 'ORI_BONUS_GL_BD' => $bonus['ORI_BONUS_GL_BD'],
  3545. 'ORI_BONUS_GL_FX' => $bonus['ORI_BONUS_GL_FX'],
  3546. 'ORI_BONUS_QY' => $bonus['ORI_BONUS_QY'],
  3547. 'ORI_BONUS_QY_BD' => $bonus['ORI_BONUS_QY_BD'],
  3548. 'ORI_BONUS_QY_FX' => $bonus['ORI_BONUS_QY_FX'],
  3549. 'ORI_BONUS_YC' => $bonus['ORI_BONUS_YC'] + $bonus['ORI_BONUS_YC_EXTRA'],
  3550. 'ORI_BONUS_VIP' => $bonus['ORI_BONUS_VIP'],
  3551. 'ORI_BONUS_STANDARD' => $standardBonus,
  3552. 'ORI_CAPPED_BONUS_QY' => $bonus['ORI_CAPPED_BONUS_QY'], // 团队奖封顶前的奖金
  3553. 'BONUS_QUARTER' => $bonus['BONUS_QUARTER'],
  3554. 'ORI_BONUS_QUARTER' => $bonus['ORI_BONUS_QUARTER'],
  3555. 'BONUS_TOURISM' => $tourismBonus, // 旅游奖
  3556. 'BONUS_VILLA' => $villaBonus, // 房奖
  3557. 'BONUS_GARAGE' => $garageBonus, // 车奖
  3558. //以下没有用
  3559. 'BONUS_FW' => 0,
  3560. 'BONUS_FX' => $bonus['BONUS_FX'],
  3561. 'BONUS_LS' => $bonus['BONUS_LS'],
  3562. 'BONUS_BT' => $bonus['BONUS_BT'],
  3563. 'BONUS_BT_PROD' => $bonus['BONUS_BT_PROD'],
  3564. 'BONUS_BT_TOOL' => $bonus['BONUS_BT_TOOL'],
  3565. 'DEDUCT_ZR' => $bonus['DEDUCT_ZR'],
  3566. 'BONUS_FL' => $bonus['BONUS_FL'],
  3567. 'BONUS_CF' => $bonus['BONUS_CF'],
  3568. 'BONUS_LX' => $bonus['BONUS_LX'],
  3569. 'SHOULD_QY' => $bonus['BONUS_QY'],
  3570. 'SHOULD_DEDUCT_ZR' => $bonus['DEDUCT_ZR'],
  3571. 'PV_1L' => $perfData['PV_1L_TOUCH'],//TOUCH为碰业绩
  3572. 'QY_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
  3573. 'SURPLUS_1L' => $perfData['SURPLUS_1L'],
  3574. 'PV_2L' => $perfData['PV_2L_TOUCH'],
  3575. 'QY_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
  3576. 'SURPLUS_2L' => $perfData['SURPLUS_2L'],
  3577. 'PV_3L' => $perfData['PV_3L_TOUCH'],
  3578. 'QY_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
  3579. 'SURPLUS_3L' => $perfData['SURPLUS_3L'],
  3580. 'PV_4L' => $perfData['PV_4L_TOUCH'],
  3581. 'QY_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
  3582. 'SURPLUS_4L' => $perfData['SURPLUS_4L'],
  3583. 'PV_5L' => $perfData['PV_5L_TOUCH'],
  3584. 'QY_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
  3585. 'SURPLUS_5L' => $perfData['SURPLUS_5L'],
  3586. 'PV_PCS' => $perfData['PV_PCS'],
  3587. 'PV_LS_TOUCH' => 0.00,
  3588. 'SURPLUS_LS' => 0.00,
  3589. 'QY_LS' => 0.00,
  3590. 'PV_TOUCH' => Tool::formatPrice($perfData['PV_1L_TOUCH'] + $perfData['PV_2L_TOUCH'] + $perfData['PV_3L_TOUCH'] + $perfData['PV_4L_TOUCH'] + $perfData['PV_5L_TOUCH'] + $perfData['PV_LS_TOUCH']),
  3591. 'PERIOD_NUM' => $this->_periodNum,
  3592. 'CALC_YEAR' => $this->_calcYear,
  3593. 'CALC_MONTH' => $this->_calcYearMonth,
  3594. 'CALCULATED_AT' => Date::nowTime(),
  3595. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  3596. 'CREATED_AT' => Date::nowTime(),
  3597. ];
  3598. $resend = [];
  3599. unset($bonus, $realBonusGx, $realBonusGl, $bonusReal);
  3600. return ['result'=>$result,'resend'=>$resend];
  3601. }
  3602. /**
  3603. * 根据本有收入计算基础积分
  3604. * @param int $offset
  3605. * @return bool
  3606. */
  3607. public function calcBaseScore(int $offset=0) {
  3608. if (!$this->_isCalcMonth) {
  3609. return true;
  3610. }
  3611. echo sprintf("时间:[%s]基础积分,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3612. //查询本月的,每人的累计总收入
  3613. $allData = CalcBonus::findUseDbCalc()->select('USER_ID, SUM(BONUS_TOTAL) AS TOTAL_SUM, SUM(ORI_BONUS_BD) AS BD_TOTAL_SUM')->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->groupBy('USER_ID')->orderBy('USER_ID DESC')->offset($offset)->limit($this->_limit)->asArray()->all();
  3614. if ($allData) {
  3615. foreach ($allData as $everyData) {
  3616. $validTotalSum = $everyData['TOTAL_SUM'] - $everyData['BD_TOTAL_SUM'];
  3617. if( $validTotalSum <=0 ) continue;
  3618. //达不到 见习主任级别,不产生基础积分
  3619. $userBaseInfo = CalcCache::getUserInfo($everyData['USER_ID'], $this->_periodNum);
  3620. $userEmpLevel = $this->_empLevelConfig[$userBaseInfo['EMP_LV']];
  3621. $userEmpLevelSort = $userEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  3622. unset($userBaseInfo, $userEmpLevel);
  3623. if( $userEmpLevelSort < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {
  3624. unset($userEmpLevelSort);
  3625. continue;
  3626. }
  3627. unset($userEmpLevelSort);
  3628. //根据总收入获取积分
  3629. $baseScore = $this->_getBaseScoreByTotalBonus($validTotalSum);
  3630. //根据用户的级别判断 能否得到级别积分
  3631. if( $baseScore > 0 ) {
  3632. CalcCache::nowMonthScore($everyData['USER_ID'], $this->_periodNum, [
  3633. 'BASE_SCORE' => $baseScore,
  3634. ]);
  3635. CalcCache::addHasScoreUsers($everyData['USER_ID'], $this->_periodNum);
  3636. }
  3637. unset($everyData, $validTotalSum, $baseScore);
  3638. }
  3639. unset($allData);
  3640. return $this->calcBaseScore($offset + $this->_limit);
  3641. }
  3642. unset($allData);
  3643. return true;
  3644. }
  3645. /**
  3646. * 循环积分入库
  3647. * @param int $offset
  3648. * @return bool
  3649. * @throws \yii\db\Exception
  3650. */
  3651. public function loopWriteScore(int $offset = 0) {
  3652. if(!$this->_isCalcMonth){
  3653. return true;
  3654. }
  3655. echo sprintf("时间:[%s]积分入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3656. // 从缓存列表里面从底层往上倒序获取会员
  3657. $allData = CalcCache::getHasScoreUsers($this->_periodNum, $offset, $this->_limit);
  3658. if($allData){
  3659. $insertDataMonthScore = [];
  3660. foreach($allData as $userId){
  3661. $monthScoreData = CalcCache::nowMonthScore($userId, $this->_periodNum);
  3662. $totalScore = $monthScoreData['BASE_SCORE'] + $monthScoreData['LEVEL_SCORE'] + $monthScoreData['UPGRADE_SCORE'];
  3663. if( $totalScore <= 0 ) continue;
  3664. $insertDataMonthScore[] = [
  3665. 'USER_ID' => $userId,
  3666. 'BASE_SCORE' => $monthScoreData['BASE_SCORE'],
  3667. 'LEVEL_SCORE' => $monthScoreData['LEVEL_SCORE'],
  3668. 'UPGRADE_SCORE' => $monthScoreData['UPGRADE_SCORE'],
  3669. 'TOTAL_SCORE' => $totalScore,
  3670. 'PERIOD_NUM' => $this->_periodNum,
  3671. 'CALC_MONTH' => $this->_calcYearMonth,
  3672. 'CREATED_AT' => Date::nowTime(),
  3673. ];
  3674. unset($userId, $monthScoreData, $totalScore);
  3675. }
  3676. ScoreMonth::batchInsert($insertDataMonthScore);
  3677. unset($insertDataMonthScore, $allData);
  3678. return $this->loopWriteScore($offset + $this->_limit);
  3679. }
  3680. unset($allData);
  3681. return true;
  3682. }
  3683. /**
  3684. * 根据总收入获取相应的基础积分
  3685. * @param $totalBonus
  3686. * @return int|mixed
  3687. */
  3688. private function _getBaseScoreByTotalBonus($totalBonus) {
  3689. $baseScoreConfig = Json::decode($this->_sysConfig['baseScore']['VALUE']);
  3690. $baseScore = 0;
  3691. foreach ($baseScoreConfig as $everyScoreData) {
  3692. if( $totalBonus < $everyScoreData['monthTotalPvMin'] ) continue;
  3693. if( $everyScoreData['monthTotalPvMax'] != 0 && $totalBonus >= $everyScoreData['monthTotalPvMax'] ) continue;
  3694. $baseScore = $everyScoreData['score'];
  3695. unset($everyScoreData);
  3696. break;
  3697. }
  3698. unset($baseScoreConfig, $totalBonus);
  3699. return $baseScore;
  3700. }
  3701. // 判断是否满足月最低消费
  3702. public function _isMonthPerfLimit($userId) {
  3703. $userMonthTotal = PerfMonth::find()->where(
  3704. 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
  3705. ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth]
  3706. )
  3707. ->asArray()
  3708. ->one();
  3709. $fxPvStatus = false;
  3710. if (isset($userMonthTotal['PV_PCS']) && $userMonthTotal['PV_PCS'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE']) {
  3711. $fxPvStatus = true;
  3712. }
  3713. return $fxPvStatus;
  3714. }
  3715. // 判断会员是否活跃:1. 当月消费30BV. 2.任意水机+150粒的EKSP. (满足任意条件即可)
  3716. public function _isPerfActive($userId): bool
  3717. {
  3718. // 条件1: 当月消费30BV
  3719. $pv = PerfPeriod::find()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND PERIOD_NUM<=:PERIOD_NUM',
  3720. ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth, 'PERIOD_NUM'=>$this->_periodNum])
  3721. ->SUM('PV_PCS');
  3722. if ($pv >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE']) {
  3723. return true;
  3724. }
  3725. $calcMonth = $this->_calcYear . ($this->_calcMonth == 1 ? '0' . $this->_calcMonth : $this->_calcMonth);
  3726. // 条件2: 任意水机+150粒的EKSP(HES150N)
  3727. $orderEKSP = Order::find()
  3728. ->alias('O')
  3729. ->join('INNER JOIN', OrderGoods::tableName() . ' AS G', 'O.SN = G.ORDER_SN')
  3730. ->where("O.IS_DELETE=0 AND O.USER_ID=:USER_ID AND LEFT(O.P_CALC_MONTH, 7)=:P_CALC_MONTH AND O.PERIOD_NUM<=:PERIOD_NUM AND G.SKU_CODE=:SKU_CODE",
  3731. ['USER_ID' => $userId, 'P_CALC_MONTH' => $calcMonth, 'PERIOD_NUM' => $this->_periodNum, ':SKU_CODE' => 'HES150N'])
  3732. ->count();
  3733. if (!$orderEKSP) {
  3734. return false;
  3735. }
  3736. // 所有分期商品
  3737. $instalmentShopGoods = ShopGoods::find()->where('INSTALMENT>0 AND STATUS=1')->select('GOODS_NO')->column();
  3738. $instalmentShopGoods = implode("','", $instalmentShopGoods);
  3739. $orderInstalment = Order::find()
  3740. ->alias('O')
  3741. ->join('INNER JOIN', OrderGoods::tableName() . ' AS G', 'O.SN = G.ORDER_SN')
  3742. ->where("O.IS_DELETE=0 AND O.USER_ID=:USER_ID AND LEFT(O.P_CALC_MONTH, 7)=:P_CALC_MONTH AND O.PERIOD_NUM<=:PERIOD_NUM AND G.SKU_CODE IN ('{$instalmentShopGoods}')",
  3743. ['USER_ID' => $userId, 'P_CALC_MONTH' => $calcMonth, 'PERIOD_NUM' => $this->_periodNum])
  3744. ->count();
  3745. if (!$orderInstalment) {
  3746. return false;
  3747. }
  3748. return true;
  3749. }
  3750. }