BonusCalc.php 189 KB

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