BonusCalc.php 186 KB

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