BonusCalc.php 188 KB

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