BonusCalc.php 186 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083
  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 = 1000;
  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::addUserStartCrown($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_STAR_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. print_r('不是季结点,进这里,不计算季度奖');
  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_STAR_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和startCrownPoint的大个值
  1552. $starDirectorPoint = $this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['TOURISM_PERCENT'] ?? 0;
  1553. $startCrownPoint = $this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_STAR_LV']]['TOURISM_PERCENT'] ?? 0;
  1554. // 奖金比例:
  1555. $bonusPoint = max($starDirectorPoint, $startCrownPoint);
  1556. $insertBonusData[] = [
  1557. 'ID' => SnowFake::instance()->generateId(),
  1558. 'USER_ID' => $userId,
  1559. 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'],
  1560. 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LAST_EMP_LV'],
  1561. 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'],
  1562. 'LAST_STAR_LV' => $userStarCrownObj[$userId]['LAST_STAR_LV'],
  1563. 'AMOUNT_STANDARD' => 0,
  1564. 'POINT' => $bonusPoint,
  1565. 'PERIOD_NUM' => $this->_periodNum,
  1566. 'CALC_YEAR' => $this->_calcYear,
  1567. 'CALC_MONTH' => $this->_calcYearMonth,
  1568. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1569. 'CREATED_AT' => Date::nowTime(),
  1570. 'PERF' => $monthTotalPV,
  1571. 'TRANSFER_RATE' => $mate,
  1572. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  1573. 'CAP_AMOUNT' => 0,
  1574. 'POINT_COMPLEX' => 0,
  1575. ];
  1576. $bonusPointComplex += $bonusPoint;
  1577. }
  1578. // 数据写入总表
  1579. if ($insertBonusData) {
  1580. foreach ($insertBonusData as &$bonusData) {
  1581. // 计算奖金
  1582. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  1583. if ($amount <= 0) {
  1584. continue;
  1585. }
  1586. // 会员级别达到要求才会发放奖金
  1587. if ($bonusData['LAST_DEC_LV'] == $minDecLevel) {
  1588. // 放入缓存
  1589. CalcCache::tourismBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  1590. // 加入月奖的会员
  1591. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  1592. }
  1593. $bonusData['AMOUNT'] = $amount;
  1594. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  1595. }
  1596. CalcBonusTourism::batchInsert($insertBonusData);
  1597. }
  1598. return true;
  1599. }
  1600. // 执行房奖的计算
  1601. public function calcBonusVilla() {
  1602. // 月结,如果不是月结点,则直接退出
  1603. if (!$this->_isCalcMonth) {
  1604. return true;
  1605. }
  1606. $bonusConfig = $this->_sysConfig['openVilla'];
  1607. // 达标条件:聘级、级别、奖项比例
  1608. $config = json_decode($bonusConfig['OPTIONS'], true);
  1609. // 奖金总比例
  1610. $mate = $bonusConfig['VALUE'] / 100;
  1611. // 个人奖金封顶
  1612. $capBonus = intval($this->_sysConfig['openVillaCap']['VALUE'] ?? 0);
  1613. // 会员级别
  1614. $minDecLevel = $config['declarationLevel'] ?? [];
  1615. // 月度公司总PV
  1616. $monthTotalPV = PerfMonth::find()
  1617. ->yearMonth($this->_calcYearMonth)
  1618. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1619. ->sum('PV_PCS');
  1620. // 用于分发的奖金总数
  1621. $transferAmount = $monthTotalPV * $mate;
  1622. // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
  1623. $subQuery = CalcBonusQY::find()
  1624. ->yearMonth($this->_calcYearMonth)
  1625. ->where('CALC_MONTH = :CALC_MONTH AND LAST_STAR_LV <> :NO_STAR_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_STAR_LV' => StarCrownLevel::NO_LEVEL_ID])
  1626. ->select('USER_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STAR_LV,LAST_STATUS,LEVEL_NAME,SORT')
  1627. ->joinWith(['starCrown' => function($query) {
  1628. $query->select(['LEVEL_NAME', 'SORT']);
  1629. }])
  1630. ->having(1)
  1631. ->orderBy('USER_ID ASC, SORT DESC');
  1632. $userStarCrownObj = (new Query())->from(['u' => $subQuery])->select('USER_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STAR_LV,LAST_STATUS,LEVEL_NAME,SORT')->groupBy('USER_ID')->indexBy('USER_ID')->all();
  1633. // 奖金点数综合
  1634. $bonusPointComplex = 0;
  1635. $insertBonusData = [];
  1636. foreach($userStarCrownObj as $item) {
  1637. // 奖金比例
  1638. $bonusPoint = $this->_starCrownLevelConfig[$item['LAST_STAR_LV']]['VILLA_PERCENT'] ?? 0;
  1639. if (!$bonusPoint) {
  1640. continue;
  1641. }
  1642. $insertBonusData[] = [
  1643. 'ID' => SnowFake::instance()->generateId(),
  1644. 'USER_ID' => $item['USER_ID'],
  1645. 'LAST_DEC_LV' => $item['LAST_DEC_LV'],
  1646. 'LAST_EMP_LV' => $item['LAST_EMP_LV'],
  1647. 'LAST_STATUS' => $item['LAST_STATUS'],
  1648. 'LAST_STAR_LV' => $item['LAST_STAR_LV'],
  1649. 'AMOUNT' => 0,
  1650. 'POINT' => $bonusPoint,
  1651. 'PERIOD_NUM' => $this->_periodNum,
  1652. 'CALC_YEAR' => $this->_calcYear,
  1653. 'CALC_MONTH' => $this->_calcYearMonth,
  1654. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1655. 'CREATED_AT' => Date::nowTime(),
  1656. 'PERF' => $monthTotalPV,
  1657. 'TRANSFER_RATE' => $mate,
  1658. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  1659. 'CAP_AMOUNT' => 0,
  1660. 'POINT_COMPLEX' => 0,
  1661. ];
  1662. $bonusPointComplex += $bonusPoint;
  1663. }
  1664. // 数据写入总表
  1665. if ($insertBonusData) {
  1666. // 计算个人奖金
  1667. foreach ($insertBonusData as &$bonusData) {
  1668. // 计算奖金
  1669. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  1670. if ($amount <= 0) {
  1671. continue;
  1672. }
  1673. // 封顶前奖金数
  1674. $capAmount = $amount;
  1675. // 奖金数不能大于封顶值
  1676. $amount = ($amount > $capBonus) ? $capBonus : $amount;
  1677. // 会员级别达到要求才会发放奖金
  1678. if ($bonusData['LAST_DEC_LV'] == $minDecLevel) {
  1679. // 放入缓存
  1680. CalcCache::villaBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  1681. // 加入月奖的会员
  1682. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  1683. }
  1684. $bonusData['AMOUNT'] = $amount;
  1685. $bonusData['CAP_AMOUNT'] = $capAmount;
  1686. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  1687. }
  1688. CalcBonusVilla::batchInsert($insertBonusData);
  1689. }
  1690. return true;
  1691. }
  1692. // 执行车奖的计算
  1693. public function calcBonusGarage() {
  1694. // 月结,如果不是月结点,则直接退出
  1695. if (!$this->_isCalcMonth) {
  1696. return true;
  1697. }
  1698. $bonusConfig = $this->_sysConfig['openGarage'];
  1699. // 达标条件:聘级、级别、奖项比例
  1700. $config = json_decode($bonusConfig['OPTIONS'], true);
  1701. // 奖金总比例
  1702. $mate = $bonusConfig['VALUE'] / 100;
  1703. // 会员级别
  1704. $minDecLevel = $config['declarationLevel'] ?? [];
  1705. // 个人奖金封顶
  1706. $capBonus = intval($this->_sysConfig['openGarageCap']['VALUE'] ?? 0);
  1707. // 月度公司总PV
  1708. $monthTotalPV = PerfMonth::find()
  1709. ->yearMonth($this->_calcYearMonth)
  1710. ->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1711. ->sum('PV_PCS');
  1712. // 用于分发的奖金总数
  1713. $transferAmount = $monthTotalPV * $mate;
  1714. // 基于蓝星奖结果计算符合获奖条件的会员StarDirector
  1715. $userStarDirector = CalcBonusBS::find()
  1716. ->yearMonth($this->_calcYearMonth)
  1717. ->where('CALC_MONTH = :CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])
  1718. ->select('USER_ID,LEVEL_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STATUS')
  1719. ->groupBy('USER_ID')
  1720. ->asArray()
  1721. ->all();
  1722. $userStarDirectorObj = array_column($userStarDirector, NULL, 'USER_ID');
  1723. // 基于团队奖/绩效奖结果计算会员的StarCrown.StarCrown基于周期计算,一个月会产生多次,取月周期中的最高星级
  1724. $subQuery = CalcBonusQY::find()
  1725. ->yearMonth($this->_calcYearMonth)
  1726. ->where('CALC_MONTH = :CALC_MONTH AND LAST_STAR_LV <> :NO_STAR_LV', [':CALC_MONTH' => $this->_calcYearMonth, ':NO_STAR_LV' => StarCrownLevel::NO_LEVEL_ID])
  1727. ->select('USER_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STAR_LV,LAST_STATUS,LEVEL_NAME,SORT')
  1728. ->joinWith(['starCrown' => function($query) {
  1729. $query->select(['LEVEL_NAME', 'SORT']);
  1730. }])
  1731. ->having(1)
  1732. ->orderBy('USER_ID ASC, SORT DESC');
  1733. $userStarCrownObj = (new Query())->from(['u' => $subQuery])->select('USER_ID,LAST_DEC_LV,LAST_EMP_LV,LAST_STAR_LV,LAST_STATUS,LEVEL_NAME,SORT')->groupBy('USER_ID')->indexBy('USER_ID')->all();
  1734. // 合并用户ID,去重
  1735. $bonusUsers = array_unique(array_merge(array_keys($userStarDirectorObj), array_keys($userStarCrownObj)));
  1736. sort($bonusUsers);
  1737. // 奖金点数综合
  1738. $bonusPointComplex = 0;
  1739. $insertBonusData = [];
  1740. foreach($bonusUsers as $userId) {
  1741. // 计算奖金:取starDirectorPoint和startCrownPoint的大个值
  1742. $starDirectorPoint = !isset($userStarDirectorObj[$userId]['LEVEL_ID']) ? 0 : ($this->_empLevelConfig[$userStarDirectorObj[$userId]['LEVEL_ID']]['GARAGE_PERCENT'] ?? 0);
  1743. $startCrownPoint = !isset($userStarCrownObj[$userId]['LAST_STAR_LV']) ? 0: ($this->_starCrownLevelConfig[$userStarCrownObj[$userId]['LAST_STAR_LV']]['GARAGE_PERCENT'] ?? 0);
  1744. // 奖金比例:
  1745. $bonusPoint = max($starDirectorPoint, $startCrownPoint);
  1746. $insertBonusData[] = [
  1747. 'ID' => SnowFake::instance()->generateId(),
  1748. 'USER_ID' => $userId,
  1749. 'LAST_DEC_LV' => $userStarDirectorObj[$userId]['LAST_DEC_LV'] ?? ($userStarCrownObj[$userId]['LAST_DEC_LV'] ?? ''),
  1750. 'LAST_EMP_LV' => $userStarDirectorObj[$userId]['LAST_EMP_LV'] ?? ($userStarCrownObj[$userId]['LAST_EMP_LV'] ?? ''),
  1751. 'LAST_STATUS' => $userStarDirectorObj[$userId]['LAST_STATUS'] ?? ($userStarCrownObj[$userId]['LAST_STATUS'] ?? 1),
  1752. 'LAST_STAR_LV' => $userStarCrownObj[$userId]['LAST_STAR_LV'] ?? '',
  1753. 'AMOUNT' => 0,
  1754. 'POINT' => $bonusPoint,
  1755. 'PERIOD_NUM' => $this->_periodNum,
  1756. 'CALC_YEAR' => $this->_calcYear,
  1757. 'CALC_MONTH' => $this->_calcYearMonth,
  1758. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1759. 'CREATED_AT' => Date::nowTime(),
  1760. 'PERF' => $monthTotalPV,
  1761. 'TRANSFER_RATE' => $mate,
  1762. 'TRANSFER_AMOUNT' => Tool::formatPrice($transferAmount),
  1763. 'CAP_AMOUNT' => 0,
  1764. 'POINT_COMPLEX' => 0,
  1765. ];
  1766. $bonusPointComplex += $bonusPoint;
  1767. }
  1768. // 数据写入总表
  1769. if ($insertBonusData) {
  1770. foreach ($insertBonusData as &$bonusData) {
  1771. // 计算奖金
  1772. $amount = Tool::formatPrice($transferAmount * ($bonusData['POINT'] / $bonusPointComplex));
  1773. if ($amount <= 0) {
  1774. continue;
  1775. }
  1776. // 封顶前奖金数
  1777. $capAmount = $amount;
  1778. // 奖金数不能大于封顶值
  1779. $amount = ($amount > $capBonus) ? $capBonus : $amount;
  1780. // 会员级别达到要求才会发放奖金
  1781. if ($bonusData['LAST_DEC_LV'] == $minDecLevel) {
  1782. // 放入缓存
  1783. CalcCache::garageBonus($bonusData['USER_ID'], $this->_periodNum, $amount);
  1784. // 加入月奖的会员
  1785. CalcCache::addHasMonthBonusUsers($bonusData['USER_ID'], $this->_periodNum);
  1786. }
  1787. $bonusData['AMOUNT'] = $amount;
  1788. $bonusData['CAP_AMOUNT'] = $capAmount;
  1789. $bonusData['POINT_COMPLEX'] = $bonusPointComplex;
  1790. }
  1791. CalcBonusGarage::batchInsert($insertBonusData);
  1792. }
  1793. return true;
  1794. }
  1795. /**
  1796. * 季度奖写用户缓存
  1797. *
  1798. */
  1799. public function calcQuarterUser(int $offset = 0) {
  1800. if( !$this->_isCalcMonth || !in_array($this->_calcMonth, [3,6,9,12])) {
  1801. // 不是结算月,则不进行计算
  1802. return false;
  1803. }
  1804. $allData = CalcBonusQuarter::finduseDbCalc()
  1805. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1806. ->groupBy('USER_ID')
  1807. ->offset($offset)
  1808. ->limit($this->_limit)
  1809. ->asArray()
  1810. ->all();
  1811. if ($allData){
  1812. // 达标条件:会员级别:钻卡
  1813. $config = json_decode($this->_sysConfig['openGL']['OPTIONS'], true);
  1814. $minDecLevel = $config['mntDec'] ?? [];
  1815. foreach ($allData as $user) {
  1816. // 扣除相应的复消积分和管理费
  1817. $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS']);
  1818. $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  1819. $manageTax = $deductData['manageTax']; // 管理费
  1820. $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  1821. // 管理奖钻卡发放
  1822. // if (in_array($user['LAST_DEC_LV'], $minDecLevel)) {
  1823. // 把对碰后的奖金存入缓存中
  1824. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_QUARTER', $user['ORI_BONUS'], $deductData);
  1825. // 加入月奖的会员
  1826. CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  1827. // }
  1828. // 更新蓝星奖金存储过程的实发金额数据
  1829. CalcBonusQuarter::updateAll([
  1830. 'RECONSUME_POINTS' => $point,
  1831. 'AMOUNT' => $realBonusBs,
  1832. 'MANAGE_TAX' => $manageTax],
  1833. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1834. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1835. }
  1836. return $this->calcQuarterUser($offset + $this->_limit);
  1837. }
  1838. unset($allData);
  1839. return true;
  1840. }
  1841. /**
  1842. * 蓝星管理奖金
  1843. * @param int $offset
  1844. * @return bool
  1845. * @throws \yii\db\Exception
  1846. */
  1847. public function calcBonusBsGL(int $offset = 0) {
  1848. if( !$this->_isCalcMonth ) {
  1849. // 不是结算月,则不进行计算
  1850. return false;
  1851. }
  1852. // 从缓存获取分页有收入的会员信息
  1853. $allData = CalcBonusBS::findUseDbCalc()
  1854. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1855. ->groupBy('USER_ID')
  1856. ->offset($offset)
  1857. ->limit($this->_limit)
  1858. ->asArray()
  1859. ->all();
  1860. if ($allData) {
  1861. // 达标条件:会员级别:钻卡
  1862. $config = json_decode($this->_sysConfig['openGL']['OPTIONS'], true);
  1863. $minDecLevel = $config['mntDec'] ?? [];
  1864. foreach ($allData as $user) {
  1865. //扣除相应的复消积分和管理费
  1866. $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS_MNT']);
  1867. $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  1868. $manageTax = $deductData['manageTax']; // 管理费
  1869. $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  1870. // 管理奖钻卡发放
  1871. // if (in_array($user['LAST_DEC_LV'], $minDecLevel)) {
  1872. // 把对碰后的奖金存入缓存中
  1873. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS_MNT', $user['ORI_BONUS_MNT'], $deductData);
  1874. // 加入月奖的会员
  1875. CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  1876. // }
  1877. // 更新蓝星奖金存储过程的实发金额数据
  1878. CalcBonusBS::updateAll([
  1879. 'RECONSUME_POINTS' => $point,
  1880. 'AMOUNT_MNT' => $realBonusBs,
  1881. 'MANAGE_TAX_MNT' => $manageTax],
  1882. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1883. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1884. }
  1885. return $this->calcBonusBsGL($offset + $this->_limit);
  1886. }
  1887. unset($allData);
  1888. return true;
  1889. }
  1890. /**
  1891. * 蓝星业绩奖金
  1892. * @param int $offset
  1893. * @return bool
  1894. * @throws \yii\db\Exception
  1895. */
  1896. public function calcBonusBsYJ(int $offset = 0) {
  1897. if( !$this->_isCalcMonth ) {
  1898. // 不是结算月,则不进行计算
  1899. return false;
  1900. }
  1901. // 从缓存获取分页有收入的会员信息
  1902. $allData = CalcBonusBS::findUseDbCalc()
  1903. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1904. ->groupBy('USER_ID')
  1905. ->offset($offset)
  1906. ->limit($this->_limit)
  1907. ->asArray()
  1908. ->all();
  1909. if ($allData) {
  1910. // 达标条件:会员级别:金卡、钻卡
  1911. $config = json_decode($this->_sysConfig['openGL']['OPTIONS'], true);
  1912. $minDecLevel = $config['abbrDec'] ?? [];
  1913. foreach ($allData as $user) {
  1914. //扣除相应的复消积分和管理费
  1915. $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS_ABBR']);
  1916. $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  1917. $manageTax = $deductData['manageTax']; // 管理费
  1918. $point = $deductData['reConsumePoints'] + $user['RECONSUME_POINTS'];// 复消积分
  1919. // 业绩奖金卡、钻卡发放
  1920. // if (in_array($user['LAST_DEC_LV'], $minDecLevel)) {
  1921. // 把对碰后的奖金存入缓存中
  1922. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS_ABBR', $user['ORI_BONUS_ABBR'], $deductData);
  1923. // 加入月奖的会员
  1924. CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  1925. // }
  1926. // 更新蓝星业绩奖金存储过程的实发金额数据
  1927. CalcBonusBS::updateAll([
  1928. 'AMOUNT_ABBR' => $realBonusBs,
  1929. 'MANAGE_TAX_ABBR' => $manageTax,
  1930. 'RECONSUME_POINTS' => $point],
  1931. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1932. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1933. }
  1934. return $this->calcBonusBsYJ($offset + $this->_limit);
  1935. }
  1936. unset($allData);
  1937. return true;
  1938. }
  1939. /**
  1940. * 报单管理奖
  1941. * @param int $offset
  1942. * @return bool
  1943. * @throws \yii\db\Exception
  1944. */
  1945. public function calcBonusBdGL(int $offset = 0) {
  1946. // 从缓存获取分页有收入的会员信息
  1947. $allData = CalcCache::getHasIncomeUsers($this->_periodNum, $offset, $this->_limit);
  1948. if ($allData) {
  1949. $insertBonusData = [];
  1950. foreach ($allData as $userId) {
  1951. $bonusUserData = [];
  1952. //会员信息
  1953. $validDeep = 1;
  1954. $this->loopRelationParentDo($userId, function ($parent) use ($userId, &$validDeep, &$bonusUserData) {
  1955. //判断$parent是否有首单团队奖
  1956. $bonusUserId = $parent['PARENT_UID'];
  1957. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  1958. $nowDecLevelConfig = $this->_decLevelConfig[$bonusUserBaseInfo['DEC_LV']];
  1959. $recNum = $bonusUserBaseInfo['REC_NUM'];
  1960. if( $recNum <= 0 ) {
  1961. $maxOddLayer = 0;
  1962. }else if( $recNum == 1 ) {
  1963. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_ONE'] ?? 0;
  1964. }else if( $recNum == 2 ) {
  1965. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_TWO'] ?? 0;
  1966. }else {
  1967. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_THREE'] ?? 0;
  1968. }
  1969. if ( $validDeep < 2 * $maxOddLayer && $validDeep % 2 === 1 ) {//奇数层
  1970. $bonusUserData[] = [
  1971. 'bonusUid' => $parent['PARENT_UID'],
  1972. 'validDeep' => $validDeep
  1973. ];
  1974. }
  1975. $parentBonus = CalcCache::bonus($bonusUserId, $this->_periodNum);
  1976. if( $parentBonus['ORI_BONUS_QY_BD'] > 0 ) {//有效层
  1977. $validDeep += 1;
  1978. }
  1979. unset($parent, $parentBonus, $bonusUserId, $bonusUserBaseInfo, $nowDecLevelConfig, $recNum, $maxOddLayer);
  1980. //超过代数上限则结束
  1981. if ( $validDeep >= 18 ) {
  1982. return self::LOOP_FINISH;
  1983. }
  1984. });
  1985. //发奖
  1986. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1987. $userBonus = CalcCache::bonus($userId, $this->_periodNum);
  1988. foreach ($bonusUserData as $everyData) {
  1989. $bonusUserId = $everyData['bonusUid'];
  1990. //判断 是否本期小市场(安置关系)新增980pv 能否得奖
  1991. if ( !$this->checkSmallMarketPerf($bonusUserId) ) {
  1992. // unset($bonusUserId);
  1993. // continue;
  1994. //得奖人不满足980就找一个满足980的人来得这个奖
  1995. $bonusUserId = $this->getMinBdPvRelationParent($bonusUserId);
  1996. if ( !$bonusUserId ) {
  1997. unset($bonusUserId);
  1998. continue;
  1999. }
  2000. }
  2001. $parentOddPercentValue = floor($everyData['validDeep']/6);
  2002. $parentOddPercentName = sprintf('parentOddPercent_%s', $parentOddPercentValue);
  2003. if( !isset($this->_sysConfig[$parentOddPercentName]) ) continue;
  2004. $bonusPercent = $this->_sysConfig[$parentOddPercentName]['VALUE'];
  2005. $manageBonus = Tool::formatPrice($userBonus['ORI_BONUS_QY_BD'] * $bonusPercent / 100);
  2006. if ($manageBonus <= 0) continue;
  2007. //总金额限制
  2008. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2009. $recNum = $bonusUserBaseInfo['REC_NUM'];
  2010. $manageBonus = $this->bonusTotalLimit($manageBonus, $bonusUserId, $recNum, $bonusUserBaseInfo['ZC_AMOUNT']);
  2011. if( $manageBonus <= 0 ) continue;
  2012. //扣除相应的复消积分和管理费
  2013. $deductData = $this->deduct($bonusUserId, $manageBonus);
  2014. // 钻卡会员奖金记入缓存
  2015. $decLevelConfig = $this->_decLevelConfig;
  2016. $nowDecLevelConfig = $decLevelConfig[$userBaseInfo['DEC_LV']];
  2017. if ($nowDecLevelConfig == '67ABCE0ECE705575E055736AECE8644D') {
  2018. CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_GL', $manageBonus, $deductData, CalcCache::FROM_MEANS_BD);
  2019. CalcCache::addHasMonthBonusUsers($bonusUserId, $this->_periodNum);
  2020. }
  2021. //管理奖流水
  2022. $insertBonusData[] = [
  2023. 'ID' => SnowFake::instance()->generateId(),
  2024. 'USER_ID' => $bonusUserId,
  2025. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  2026. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  2027. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  2028. 'FROM_USER_ID' => $userId,
  2029. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2030. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2031. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2032. 'AMOUNT' => $deductData['surplus'],
  2033. 'ORI_BONUS' => $manageBonus,
  2034. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2035. 'MANAGE_TAX' => $deductData['manageTax'],
  2036. 'PERIOD_NUM' => $this->_periodNum,
  2037. 'CALC_YEAR' => $this->_calcYear,
  2038. 'CALC_MONTH' => $this->_calcYearMonth,
  2039. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2040. 'CREATED_AT' => Date::nowTime(),
  2041. 'LOGS' => json_encode([
  2042. $parentOddPercentName => $this->_sysConfig[$parentOddPercentName]['VALUE'],
  2043. 'validDeep' => $everyData['validDeep'],
  2044. 'recNum' => $bonusUserBaseInfo['REC_NUM'],
  2045. 'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
  2046. 'fromUserId' => $userId,
  2047. 'decLevel' => $bonusUserBaseInfo['DEC_LV'],
  2048. 'bonusTotalLimit' => [
  2049. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  2050. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  2051. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  2052. ],
  2053. ]),
  2054. ];
  2055. unset($everyData, $bonusUserId, $parentOddPercentValue, $parentOddPercentName, $bonusPercent, $manageBonus, $deductData);
  2056. }
  2057. unset($userId, $validDeep, $userBaseInfo, $userBonus, $bonusUserData);
  2058. }
  2059. if($insertBonusData) CalcBonusGL::batchInsert($insertBonusData);
  2060. unset($allData, $insertBonusData);
  2061. return $this->calcBonusBdGL($offset + $this->_limit);
  2062. }
  2063. unset($allData);
  2064. return true;
  2065. }
  2066. /**
  2067. * 复消管理奖
  2068. * @param int $offset
  2069. * @return bool
  2070. * @throws \yii\db\Exception
  2071. */
  2072. public function calcBonusFxGL(int $offset = 0) {
  2073. $periodNum = $this->_periodNum;
  2074. // 从缓存获取分页有收入的会员信息
  2075. $allData = CalcCache::getHasIncomeUsers($this->_periodNum, $offset, $this->_limit);
  2076. if ($allData) {
  2077. $insertBonusData = [];
  2078. foreach ($allData as $userId) {
  2079. //会员信息
  2080. $decLevelConfig = $this->_decLevelConfig;
  2081. $netWorkParents = Cache::getAllRelationParents($userId);
  2082. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2083. $userEmpLevel = $userBaseInfo['EMP_LV'];
  2084. foreach ($netWorkParents as $netWorkParent) {
  2085. //自已距顶端的深度减去父级距顶端的深度
  2086. $diffLayer = $netWorkParent['TOP_DEEP'] - $netWorkParent['PARENT_DEEP'];
  2087. if( $diffLayer <= 0) continue;
  2088. //@todo 超过最大代数就跳出本次循环
  2089. //偶数代跳过
  2090. if( $diffLayer % 2 == 0 ) continue;
  2091. // 获取会员的报单级别
  2092. $bonusUserId = $netWorkParent['PARENT_UID'];
  2093. if( !$bonusUserId ) continue;
  2094. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2095. $nowDecLevelConfig = $decLevelConfig[$bonusUserBaseInfo['DEC_LV']];
  2096. if( !$nowDecLevelConfig ) continue;
  2097. //推荐人数
  2098. $recNum = $bonusUserBaseInfo['REC_NUM'];
  2099. if( $recNum <= 0 ) continue;
  2100. if( $recNum == 1 ) {
  2101. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_ONE'];
  2102. }else if( $recNum == 2 ) {
  2103. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_TWO'];
  2104. }else {
  2105. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_THREE'];
  2106. }
  2107. //超过代数上限也跳过
  2108. if( $diffLayer >= 2 * $maxOddLayer ) continue;
  2109. // $everyLayer = floor(2 * $nowDecLevelConfig['GL_ODD_DEEP_THREE'] / $nowDecLevelConfig['SORT']);
  2110. //多少代
  2111. // $theLayer = $diffLayer % $everyLayer;
  2112. // $theLayerLevel = floor($diffLayer/$everyLayer);
  2113. $theLayerLevel = floor($diffLayer/6);
  2114. $parentOddPercentName = sprintf('parentOddPercent_%s', $theLayerLevel);
  2115. if( !isset($this->_sysConfig[$parentOddPercentName]) ) continue;
  2116. $bonusPercent = $this->_sysConfig[$parentOddPercentName]['VALUE'];
  2117. // 从缓存中获取会员的收入信息
  2118. $incomeBonus = CalcCache::bonus($userId, $periodNum);
  2119. $parentOddIncomeFromName = sprintf('parentOddIncomeFrom_%s', $theLayerLevel);
  2120. $parentOddIncomeFrom = explode(',', $this->_sysConfig[$parentOddIncomeFromName]['VALUE']);
  2121. $parentOddIncome = 0;
  2122. foreach ($parentOddIncomeFrom as $incomeType) {
  2123. if( $incomeType === 'XF' ) {
  2124. $incomeTypeName = sprintf('ORI_BONUS_%s', $incomeType);
  2125. }else {
  2126. $incomeTypeName = sprintf('ORI_BONUS_%s_FX', $incomeType);
  2127. }
  2128. $incomeTypeValue = $incomeBonus[$incomeTypeName] ?? 0;
  2129. $parentOddIncome += $incomeTypeValue;
  2130. unset($incomeType, $incomeTypeName, $incomeTypeValue);
  2131. }
  2132. unset($parentOddIncomeFrom);
  2133. $manageBonus = Tool::formatPrice($parentOddIncome * $bonusPercent / 100);
  2134. if ($manageBonus <= 0) continue;
  2135. //总金额限制
  2136. $manageBonus = $this->bonusTotalLimit($manageBonus, $bonusUserId, $recNum, $bonusUserBaseInfo['ZC_AMOUNT']);
  2137. if( $manageBonus <= 0 ) continue;
  2138. //扣除相应的复消积分和管理费
  2139. $deductData = $this->deduct($bonusUserId, $manageBonus);
  2140. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_GL', $manageBonus, $deductData, CalcCache::FROM_MEANS_FX);
  2141. //管理奖流水
  2142. $insertBonusData[] = [
  2143. 'ID' => SnowFake::instance()->generateId(),
  2144. 'USER_ID' => $bonusUserId,
  2145. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  2146. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  2147. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  2148. 'FROM_USER_ID' => $userId,
  2149. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2150. 'LAST_FROM_EMP_LV' => $userEmpLevel,
  2151. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2152. 'AMOUNT' => $deductData['surplus'],
  2153. 'ORI_BONUS' => $manageBonus,
  2154. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2155. 'MANAGE_TAX' => $deductData['manageTax'],
  2156. 'PERIOD_NUM' => $this->_periodNum,
  2157. 'CALC_YEAR' => $this->_calcYear,
  2158. 'CALC_MONTH' => $this->_calcYearMonth,
  2159. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2160. 'CREATED_AT' => Date::nowTime(),
  2161. 'LOGS' => json_encode([
  2162. $parentOddPercentName => $this->_sysConfig[$parentOddPercentName]['VALUE'],
  2163. $parentOddIncomeFromName => $this->_sysConfig[$parentOddIncomeFromName]['VALUE'],
  2164. 'decLevelConfig' => $nowDecLevelConfig,
  2165. 'recNum' => $bonusUserBaseInfo['REC_NUM'],
  2166. 'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
  2167. 'fromUserId' => $userId,
  2168. 'decLevel' => $bonusUserBaseInfo['DEC_LV'],
  2169. 'bonusTotalLimit' => [
  2170. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  2171. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  2172. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  2173. ],
  2174. ]),
  2175. ];
  2176. unset($netWorkParent, $diffLayer, $bonusUserId, $bonusUserBaseInfo, $bonusPercent, $nowDecLevelConfig, $manageBonus, $incomeBonus, $maxOddLayer, $theLayerLevel, $recNum, $parentOddPercentName, $parentOddIncomeFromName, $deductData);
  2177. }
  2178. unset($userId, $userBaseInfo, $userEmpLevel, $netWorkParents, $decLevelConfig);
  2179. }
  2180. CalcBonusGL::batchInsert($insertBonusData);
  2181. unset($allData, $insertBonusData);
  2182. return $this->calcBonusFxGL($offset + $this->_limit);
  2183. }
  2184. unset($allData);
  2185. return true;
  2186. }
  2187. /**
  2188. * 结算荣衔奖第一步
  2189. * @param int $offset
  2190. * @return bool
  2191. * @throws \yii\db\Exception
  2192. * @throws \Exception
  2193. */
  2194. public function calcBonusYCStepOne(int $offset = 0) {
  2195. // 月结,如果不是月结点,则直接退出
  2196. if (!$this->_isCalcMonth) {
  2197. return true;
  2198. }
  2199. echo sprintf("时间:[%s]荣衔奖第【1】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  2200. //从缓存获取分页有本月业绩的会员
  2201. $allData = CalcCache::getHasMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  2202. if ($allData) {
  2203. $maxLevelId = EmployLevel::SHX_ZJ_LEVEL_ID;
  2204. $maxLevel = $this->_empLevelConfig[$maxLevelId];
  2205. $maxLevelPercent = $maxLevel['RX_PERCENT'] ?? 0;
  2206. unset($maxLevelId, $maxLevel);
  2207. foreach ($allData as $userId) {
  2208. // echo sprintf("时间:[%s]荣衔奖,当前用户ID为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $userId);
  2209. $nowMonthPerf = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  2210. $monthPvPcs = $nowMonthPerf['PV_PCS'] ?? 0;
  2211. if( $monthPvPcs <= 0 ) continue;
  2212. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2213. //个人业绩的奖金
  2214. $empLevelId = $userBaseInfo['EMP_LV'];
  2215. $empLevel = $this->_empLevelConfig[$empLevelId];
  2216. $rxPercent = $empLevel['RX_PERCENT'] ?? 0;
  2217. $empBonus = $monthPvPcs * $rxPercent / 100;
  2218. if( $empBonus > 0 ) {
  2219. //给本人添加聘级比例
  2220. CalcCache::ycMaxBonusPercent($userId, $this->_periodNum, $rxPercent);
  2221. //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  2222. CalcCache::saveYCBonusList($userId, $this->_periodNum, $empBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$monthPvPcs]);
  2223. CalcCache::addHasYcBonusUsers($userId, $this->_periodNum);
  2224. //达到最大的比例其它人就得不到了
  2225. if( $rxPercent >= $maxLevelPercent ) continue;
  2226. }
  2227. unset($empLevelId, $empLevel, $rxPercent, $empBonus);
  2228. //获取所有的父级
  2229. $this->loopRelationParentDo($userId, function ($parent) use ($userId, $monthPvPcs, $maxLevelPercent) {
  2230. $bonusUserId = $parent['PARENT_UID'];
  2231. //计算级别之后更新过userInfo的缓存,缓存中级别发生了变化
  2232. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2233. $parentEmpLevelId = $bonusUserInfo['EMP_LV'];
  2234. $parentEmpLevel = $this->_empLevelConfig[$parentEmpLevelId];
  2235. $parentRxPercent = $parentEmpLevel['RX_PERCENT'] ?? 0;
  2236. $cacheMaxPercent = CalcCache::ycMaxBonusPercent($userId, $this->_periodNum);
  2237. $diffPercent = $parentRxPercent - $cacheMaxPercent;
  2238. if( $diffPercent <= 0 ) return self::LOOP_CONTINUE;
  2239. $empBonus = $monthPvPcs * $diffPercent / 100;
  2240. if( $empBonus <= 0 ) return self::LOOP_CONTINUE;
  2241. //给本人添加聘级比例
  2242. CalcCache::ycMaxBonusPercent($userId, $this->_periodNum, $parentRxPercent);
  2243. //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  2244. CalcCache::saveYCBonusList($bonusUserId, $this->_periodNum, $empBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$monthPvPcs]);
  2245. CalcCache::addHasYcBonusUsers($bonusUserId, $this->_periodNum);
  2246. unset($cacheMaxPercent, $diffPercent, $parentEmpLevel, $bonusUserId, $bonusUserInfo, $parentEmpLevelId, $empBonus);
  2247. //达到最大的比例就不在向上找了
  2248. if( $parentRxPercent >= $maxLevelPercent ) return self::LOOP_FINISH;
  2249. unset($parentRxPercent);
  2250. });
  2251. unset($nowMonthPerf, $monthPvPcs);
  2252. }
  2253. unset($allData, $maxLevelPercent);
  2254. $this->calcBonusYCStepOne($offset + $this->_limit);
  2255. }
  2256. unset($periodNum, $allData);
  2257. return true;
  2258. }
  2259. /**
  2260. * 结算荣衔奖第二步
  2261. * @param int $offset
  2262. * @return bool
  2263. * @throws \yii\db\Exception
  2264. */
  2265. public function calcBonusYCStepTwo(int $offset = 0) {
  2266. // 月结,如果不是月结点,则直接退出
  2267. if (!$this->_isCalcMonth) {
  2268. return true;
  2269. }
  2270. echo sprintf("时间:[%s]荣衔奖第【2】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  2271. $allData = CalcCache::getHasYcBonusUsers($this->_periodNum, $offset, $this->_limit);
  2272. if ($allData) {
  2273. $insertBonusData = [];
  2274. foreach ($allData as $userId) {
  2275. $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  2276. $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2277. unset($monthPerfData);
  2278. if( !$fxPvStatus ) continue;
  2279. unset($fxPvStatus);
  2280. $ycBonusData = CalcCache::getYCBonusList($userId, $this->_periodNum);
  2281. if( !$ycBonusData ) continue;
  2282. $empBonus = $ycBonusData['empBonus'] ?? 0;
  2283. if( $empBonus <=0 ) continue;
  2284. //总金额限制
  2285. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2286. $empBonus = $this->bonusTotalLimit($empBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  2287. if( $empBonus <= 0 ) continue;
  2288. //扣除相应的复消积分和管理费
  2289. $empBonus = Tool::formatPrice($empBonus);
  2290. $deductData = $this->deduct($userId, $empBonus);
  2291. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_YC', $empBonus, $deductData);
  2292. $empLevelId = $userBaseInfo['EMP_LV'];
  2293. $insertBonusData[] = [
  2294. 'ID' => SnowFake::instance()->generateId(),
  2295. 'USER_ID' => $userId,
  2296. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  2297. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  2298. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  2299. 'FROM_USER_ID' => $userId,
  2300. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2301. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2302. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2303. 'DEEP' => 0,
  2304. 'AMOUNT' => $deductData['surplus'],
  2305. 'ORI_BONUS' => $empBonus,
  2306. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2307. 'MANAGE_TAX' => $deductData['manageTax'],
  2308. 'BONUS_TYPE' => CalcBonusYC::BONUS_TYPE_YC,
  2309. 'PERIOD_NUM' => $this->_periodNum,
  2310. 'CALC_MONTH' => $this->_calcYearMonth,
  2311. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2312. 'CREATED_AT' => Date::nowTime(),
  2313. 'LOGS' => json_encode([
  2314. 'empLevelId' => $empLevelId,
  2315. ])
  2316. // 'FROM_DATA' => json_encode($ycBonusData['fromData']),
  2317. ];
  2318. unset($ycBonusData, $deductData);
  2319. //如果是总监以上拿平级2代
  2320. $empLevel = $this->_empLevelConfig[$empLevelId];
  2321. $userEmpLevelSort = $empLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  2322. // if( $userEmpLevelSort >= EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {}
  2323. $newInsertBonusData = $this->calcParentYC($userId, $userBaseInfo, $userEmpLevelSort, $empBonus);
  2324. $insertBonusData = array_merge($insertBonusData, $newInsertBonusData);
  2325. unset($newInsertBonusData);
  2326. unset($userId, $userBaseInfo, $empLevel, $empLevelId, $userEmpLevelSort, $empBonus);
  2327. }
  2328. CalcBonusYC::batchInsert($insertBonusData);
  2329. unset($insertBonusData, $allData);
  2330. $this->calcBonusYCStepTwo($offset + $this->_limit);
  2331. }
  2332. unset($allData);
  2333. return true;
  2334. }
  2335. /**
  2336. * VIP奖
  2337. * @param int $offset
  2338. * @return bool
  2339. * @throws \yii\db\Exception
  2340. */
  2341. public function calcBonusVIP(int $offset = 0)
  2342. {
  2343. // 月结,如果不是月结点,则直接退出
  2344. if (!$this->_isCalcMonth) {
  2345. return true;
  2346. }
  2347. echo sprintf("时间:[%s]VIP奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $offset);
  2348. //从缓存获取分页有本月业绩的会员
  2349. $allData = CalcCache::getHasMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  2350. if ($allData) {
  2351. $insertBonusData = [];
  2352. foreach ($allData as $userId) {
  2353. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2354. //条件一:级别必须为VIP
  2355. $isVip = false;
  2356. if( $userBaseInfo['DEC_LV'] === DeclarationLevel::VIP_LEVEL_ID ) {
  2357. $isVip= true;
  2358. }
  2359. if( $this->_sysConfig['vipBonusGoldDecLevel']['VALUE'] && $userBaseInfo['DEC_LV'] === DeclarationLevel::JIN_ZUAN_LEVEL_ID ) {
  2360. $isVip = true;
  2361. }
  2362. if ( !$isVip ) {
  2363. unset($userId, $userBaseInfo);
  2364. continue;
  2365. }
  2366. //判断其它两个条件,满足则计算月团队奖,不满足则留下大区剩余业绩,清除其它区的剩余业绩
  2367. //获取本月的业绩
  2368. $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  2369. // 从缓存中获取会员的上期结余业绩信息
  2370. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  2371. // 本期 + 上期结余
  2372. $perfArr = [
  2373. 'VIP_SURPLUS_1L_ZC' => $monthPerfData['VIP_PV_1L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_1L_ZC'],
  2374. 'VIP_SURPLUS_2L_ZC' => $monthPerfData['VIP_PV_2L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_2L_ZC'],
  2375. 'VIP_SURPLUS_3L_ZC' => $monthPerfData['VIP_PV_3L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_3L_ZC'],
  2376. 'VIP_SURPLUS_4L_ZC' => $monthPerfData['VIP_PV_4L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_4L_ZC'],
  2377. 'VIP_SURPLUS_5L_ZC' => $monthPerfData['VIP_PV_5L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_5L_ZC'],
  2378. ];
  2379. //条件二:本月复消金额达到300元
  2380. //fix-2021-03-26修改 条件二:本月个人复消PV300
  2381. $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2382. unset($monthPerfData, $pervSurplusPerf);
  2383. if( !$fxPvStatus ) {
  2384. $this->dealWithMaxPerf($userId, $perfArr);
  2385. unset($userBaseInfo, $userId, $perfArr, $fxPvStatus);
  2386. continue;
  2387. }
  2388. //条件三:其它市场业绩
  2389. $isCanOtherDepartPerf = $this->_isCanVipBonusOtherAreaPerf($perfArr);
  2390. if ( !$isCanOtherDepartPerf ) {
  2391. $this->dealWithMaxPerf($userId, $perfArr);
  2392. unset($userBaseInfo, $userId, $perfArr, $isCanOtherDepartPerf);
  2393. continue;
  2394. }
  2395. $oriPerfArr = [
  2396. 'perfArr' => $perfArr,
  2397. 'touchBonus' => 0,
  2398. ];
  2399. // 对碰
  2400. $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $this->_sysConfig['vipBonusPercent']['VALUE']/100);
  2401. unset($oriPerfArr, $perfArr);
  2402. $touchPerfArr = [];
  2403. foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
  2404. $touchPerfArr[$keyR] = $perfR;
  2405. }
  2406. // 对碰完成后把结余的业绩存入本期业绩缓存中
  2407. // CalcCache::nowPeriodPerf($userId, $this->_periodNum, $touchPerfArr);
  2408. //更新数据库
  2409. PerfMonth::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [
  2410. 'USER_ID' => $userId,
  2411. 'CALC_MONTH' => $this->_calcYearMonth,
  2412. ]);
  2413. if ($touchBonusArr['touchBonus'] <= 0) continue;
  2414. $vipBonus = $touchBonusArr['touchBonus'];
  2415. //判断级别上限
  2416. $vipBonus = $this->declarationLevelCap($vipBonus, $userId, $userBaseInfo['DEC_LV']);
  2417. if( $vipBonus <= 0 ) continue;
  2418. $vipBonus = $this->bonusTotalLimit($vipBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  2419. if( $vipBonus <= 0 ) continue;
  2420. //扣除相应的复消积分和管理费
  2421. $deductData = $this->deduct($userId, $vipBonus);
  2422. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_VIP', $vipBonus, $deductData);
  2423. $insertBonusData[] = [
  2424. 'ID' => SnowFake::instance()->generateId(),
  2425. 'USER_ID' => $userId,
  2426. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  2427. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  2428. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  2429. 'FROM_USER_ID' => $userId,
  2430. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2431. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2432. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2433. 'AMOUNT' => $deductData['surplus'],
  2434. 'ORI_BONUS' => $vipBonus,
  2435. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2436. 'MANAGE_TAX' => $deductData['manageTax'],
  2437. 'PERIOD_NUM' => $this->_periodNum,
  2438. 'CALC_YEAR' => $this->_calcYear,
  2439. 'CALC_MONTH' => $this->_calcYearMonth,
  2440. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2441. 'CREATED_AT' => Date::nowTime(),
  2442. 'LOGS' => json_encode($touchPerfArr)
  2443. ];
  2444. unset($userBaseInfo, $userId, $perfArr, $fxAmountStatus, $isCanOtherDepartPerf, $touchBonusArr, $touchPerfArr, $vipBonus, $deductData);
  2445. }
  2446. if( $insertBonusData ) CalcBonusVIP::batchInsert($insertBonusData);
  2447. unset($insertBonusData, $allData);
  2448. $this->calcBonusVIP($offset + $this->_limit);
  2449. }
  2450. unset($allData);
  2451. return true;
  2452. }
  2453. /**
  2454. * 见习达标奖
  2455. * @param int $offset
  2456. * @return bool
  2457. * @throws \yii\db\Exception
  2458. */
  2459. public function calcBonusStandard(int $offset = 0)
  2460. {
  2461. // 月结,如果不是月结点,则直接退出
  2462. if (!$this->_isCalcMonth) {
  2463. return true;
  2464. }
  2465. echo sprintf("时间:[%s]见习达标奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $offset);
  2466. //从缓存获取分页有本月业绩的会员
  2467. $allData = CalcCache::getHasStandardMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  2468. if ($allData) {
  2469. $minSaleCondition = $this->_jxStandardMinSaleCondition();
  2470. $insertBonusData = [];
  2471. foreach ($allData as $userId) {
  2472. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2473. //条件一:聘级必须为见习主任
  2474. if( $userBaseInfo['EMP_LV'] != EmployLevel::JX_ZR_LEVEL_ID ) {
  2475. unset($userId, $userBaseInfo);
  2476. continue;
  2477. }
  2478. $standardMonthPerf = CalcCache::nowStandardMonthPerf($userId, $this->_periodNum);
  2479. $totalAmount = $standardMonthPerf['AMOUNT_PCS'] + $standardMonthPerf['AMOUNT_PSS'];
  2480. if( $totalAmount < $minSaleCondition ) {
  2481. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount);
  2482. continue;
  2483. }
  2484. $standardBonus = $this->_jxStandardAwardAmount($totalAmount);
  2485. if( $standardBonus <= 0 ) {
  2486. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount, $standardBonus);
  2487. continue;
  2488. }
  2489. CalcCache::standardBonus($userId, $this->_periodNum, $standardBonus);
  2490. $insertBonusData[] = [
  2491. 'ID' => SnowFake::instance()->generateId(),
  2492. 'USER_ID' => $userId,
  2493. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  2494. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  2495. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  2496. 'FROM_USER_ID' => $userId,
  2497. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2498. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2499. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2500. 'AMOUNT' => $standardBonus,
  2501. 'ORI_BONUS' => $standardBonus,
  2502. 'RECONSUME_POINTS' => 0,
  2503. 'MANAGE_TAX' => 0,
  2504. 'PERIOD_NUM' => $this->_periodNum,
  2505. 'CALC_YEAR' => $this->_calcYear,
  2506. 'CALC_MONTH' => $this->_calcYearMonth,
  2507. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2508. 'CREATED_AT' => Date::nowTime(),
  2509. 'LOGS' => json_encode($standardMonthPerf)
  2510. ];
  2511. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount);
  2512. }
  2513. if( $insertBonusData ) CalcBonusStandard::batchInsert($insertBonusData);
  2514. unset($insertBonusData, $minSaleCondition, $insertBonusData, $allData);
  2515. $this->calcBonusStandard($offset + $this->_limit);
  2516. }
  2517. unset($allData);
  2518. return true;
  2519. }
  2520. /**
  2521. * === 运算相关的辅助功能开始 ===
  2522. */
  2523. /**
  2524. * 获取上2代的得奖人信息
  2525. * @param $userId
  2526. * @param $validDeep
  2527. * @param $shareBonusOne
  2528. * @return array
  2529. */
  2530. protected function gxLastTwoBonusData($userId, $validDeep, $shareBonusOne) {
  2531. $bonusUserList = CalcCache::getShareBonusOneRelation($userId, $this->_periodNum, $validDeep);
  2532. if( !$bonusUserList ) {
  2533. unset($bonusUserList);
  2534. return [];
  2535. }
  2536. $bonusUserData = [];
  2537. $bonusUserTotalPerf = 0;
  2538. $bonusUserRealList = [];
  2539. foreach ($bonusUserList as $bonusUserId) {
  2540. //查看该用户的个人业绩和团队新增业绩总和
  2541. $nowPeriodData = CalcCache::nowPeriodPerf($bonusUserId, $this->_periodNum);
  2542. //本期新增业绩
  2543. $bonusUserPerf = $nowPeriodData['PV_PCS'] + $nowPeriodData['PV_PSS'];
  2544. if ($bonusUserPerf <= 0) {
  2545. unset($bonusUserId, $nowPeriodData, $bonusUserPerf);
  2546. continue;
  2547. }
  2548. $bonusUserTotalPerf += $bonusUserPerf;
  2549. $bonusUserRealList[] = [
  2550. 'bonusUserId' => $bonusUserId,
  2551. 'bonusUserPerf' => $bonusUserPerf,
  2552. ];
  2553. unset($bonusUserId, $nowPeriodData, $bonusUserPerf);
  2554. }
  2555. unset($bonusUserList);
  2556. foreach ($bonusUserRealList as $everyData) {
  2557. $bonusUserData[] = [
  2558. 'bonusUid' => $everyData['bonusUserId'],
  2559. 'bonus' => $shareBonusOne * $everyData['bonusUserPerf'] / $bonusUserTotalPerf,
  2560. 'validMinPv' => false
  2561. ];
  2562. unset($everyData);
  2563. }
  2564. unset($bonusUserRealList);
  2565. return $bonusUserData;
  2566. }
  2567. /**
  2568. * 获取达标奖的金额
  2569. * @param $amount
  2570. * @return int|mixed
  2571. */
  2572. private function _jxStandardAwardAmount($amount) {
  2573. // $jxStandardConfig = Json::decode($this->_sysConfig['jxStandard']['VALUE']);
  2574. // $awardAmount = 0;
  2575. // foreach ($jxStandardConfig as $everyData) {
  2576. // if( $amount >= $everyData['salesCondition'] ) {
  2577. // $awardAmount = $everyData['awardAmount'];
  2578. // }
  2579. // unset($everyData);
  2580. // }
  2581. //
  2582. // return $awardAmount;
  2583. $realTimes = floor($amount/self::JX_STANDARD_BASE_AMOUNT);
  2584. $calcTimes = min($realTimes, self::JX_STANDARD_MAX_TIMES);
  2585. $awardAmount = $calcTimes * self::JX_STANDARD_BASE_AMOUNT * self::JX_STANDARD_BONUS_PERCENT / 100;
  2586. unset($amount, $realTimes, $calcTimes);
  2587. return $awardAmount;
  2588. }
  2589. /**
  2590. * 获取达标奖的最小条件
  2591. * @return int|mixed
  2592. */
  2593. private function _jxStandardMinSaleCondition() {
  2594. return self::JX_STANDARD_BASE_AMOUNT;
  2595. }
  2596. /**
  2597. * 处理只留最大业绩的逻辑
  2598. * @param $userId
  2599. * @param $perfArr
  2600. */
  2601. private function dealWithMaxPerf($userId, $perfArr) {
  2602. $maxPerf = max($perfArr);
  2603. $hitMaxPerf = false;
  2604. foreach ($perfArr as $key=>$everyPerf) {
  2605. if( !$hitMaxPerf && $everyPerf == $maxPerf ) {
  2606. $hitMaxPerf = true;
  2607. }else {
  2608. $perfArr[$key] = 0;
  2609. }
  2610. unset($key, $everyPerf);
  2611. }
  2612. //更新数据库
  2613. PerfMonth::updateAll($perfArr, 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [
  2614. 'USER_ID' => $userId,
  2615. 'CALC_MONTH' => $this->_calcYearMonth
  2616. ]);
  2617. unset($userId, $maxPerf, $hitMaxPerf, $perfArr);
  2618. }
  2619. /**
  2620. * VIP奖其它市场的报单业绩是否能满足
  2621. * @param $perfArr
  2622. * @return bool
  2623. */
  2624. private function _isCanVipBonusOtherAreaPerf($perfArr) {
  2625. $maxAreaPerf = max($perfArr);
  2626. $totalAreaPerf = array_sum($perfArr);
  2627. $diffAreaPerf = strval($totalAreaPerf - $maxAreaPerf);
  2628. if( $diffAreaPerf >= $this->_sysConfig['vipBonusOtherDepartPvCondition']['VALUE'] ) {
  2629. unset($maxAreaPerf, $totalAreaPerf, $perfArr);
  2630. return true;
  2631. }else {
  2632. unset($maxAreaPerf, $totalAreaPerf, $perfArr);
  2633. return false;
  2634. }
  2635. }
  2636. /**
  2637. * 给父级计算的荣衔奖
  2638. * @param $userId
  2639. * @param $userBaseInfo
  2640. * @param $userEmpLevelSort
  2641. * @param $qyBonus
  2642. * @return array
  2643. */
  2644. public function calcParentYC($userId, $userBaseInfo, $userEmpLevelSort, $qyBonus) {
  2645. if( $userEmpLevelSort <= EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'] ) return [];
  2646. $validDeep = 0;
  2647. $bonusDataList = [];
  2648. $this->loopRelationParentDo($userId, function ($parent) use ($userId, $userEmpLevelSort, &$validDeep, &$bonusDataList) {
  2649. $bonusUserId = $parent['PARENT_UID'];
  2650. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2651. $bonusUserEmpLevel = $this->_empLevelConfig[$bonusUserInfo['EMP_LV']];
  2652. $bonusUserEmpLevelSort = $bonusUserEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  2653. unset($bonusUserInfo, $bonusUserEmpLevel);
  2654. //必须是有聘级的用户
  2655. if( $bonusUserEmpLevelSort <= EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'] ) return self::LOOP_CONTINUE;
  2656. //超过级别就停止
  2657. if( $bonusUserEmpLevelSort > $userEmpLevelSort) return self::LOOP_FINISH;
  2658. //级别小于就跳过
  2659. if( $bonusUserEmpLevelSort < $userEmpLevelSort ) return self::LOOP_CONTINUE;
  2660. $validDeep++;
  2661. array_push($bonusDataList, [
  2662. 'bonusUserId' => $bonusUserId,
  2663. 'bonusType' => $validDeep,
  2664. ]);
  2665. if( $validDeep >= 2 ) return self::LOOP_FINISH;
  2666. unset($bonusUserId, $bonusUserEmpLevelSort);
  2667. });
  2668. $insertBonusData = [];
  2669. foreach ($bonusDataList as $bonusUserData) {
  2670. $bonusUserId = $bonusUserData['bonusUserId'];
  2671. $bonusMonthPerfData = CalcCache::nowMonthPerf($bonusUserId, $this->_periodNum);
  2672. $fxPvStatus = $bonusMonthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2673. unset($bonusMonthPerfData);
  2674. if( !$fxPvStatus ) continue;
  2675. unset($fxPvStatus);
  2676. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2677. $bonusEmpLevelId = $bonusUserInfo['EMP_LV'];
  2678. $newEmpBonus = Tool::formatPrice($qyBonus * $this->_sysConfig['sameEmpLevelPercent']['VALUE'] / 100);
  2679. //总金额限制
  2680. $newEmpBonus = $this->bonusTotalLimit($newEmpBonus, $bonusUserId, $bonusUserInfo['REC_NUM'], $bonusUserInfo['ZC_AMOUNT']);
  2681. if( $newEmpBonus <= 0 ) continue;
  2682. //扣除相应的复消积分和管理费
  2683. $newEmpBonus = Tool::formatPrice($newEmpBonus);
  2684. $deductData = $this->deduct($bonusUserId, $newEmpBonus);
  2685. CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_YC_EXTRA', $newEmpBonus, $deductData);
  2686. // 把育成津贴追加到育成津贴结算表,以便奖金追溯育成津贴用
  2687. $insertBonusData[] = [
  2688. 'ID' => SnowFake::instance()->generateId(),
  2689. 'USER_ID' => $bonusUserId,
  2690. 'LAST_DEC_LV' => $bonusUserInfo['DEC_LV'],
  2691. 'LAST_EMP_LV' => $bonusUserInfo['EMP_LV'],
  2692. 'LAST_STATUS' => $bonusUserInfo['STATUS'],
  2693. 'FROM_USER_ID' => $userId,
  2694. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2695. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2696. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2697. 'DEEP' => 1,
  2698. 'AMOUNT' => $deductData['surplus'],
  2699. 'ORI_BONUS' => $newEmpBonus,
  2700. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2701. 'MANAGE_TAX' => $deductData['manageTax'],
  2702. 'BONUS_TYPE' => $bonusUserData['bonusType'],
  2703. 'PERIOD_NUM' => $this->_periodNum,
  2704. 'CALC_MONTH' => $this->_calcYearMonth,
  2705. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2706. 'CREATED_AT' => Date::nowTime(),
  2707. 'LOGS' => json_encode([
  2708. 'empLevelId' => $bonusEmpLevelId,
  2709. 'qyBonus' => $qyBonus,
  2710. 'sameEmpLevelPercent' => $this->_sysConfig['sameEmpLevelPercent']['VALUE'],
  2711. ]),
  2712. ];
  2713. unset($newEmpBonus, $bonusEmpLevelId, $bonusUserId, $bonusUserInfo, $deductData);
  2714. }
  2715. unset($userId, $userBaseInfo, $userEmpLevelSort, $qyBonus, $bonusDataList);
  2716. return $insertBonusData;
  2717. }
  2718. /**
  2719. * 对碰
  2720. * @param array $oriPerfArr
  2721. * @param array $perfArr
  2722. * @param $percent
  2723. * @param $loopTimes
  2724. * @return array
  2725. */
  2726. public function touchPerf(array $oriPerfArr, array $perfArr, $percent, $loopTimes=1) {
  2727. $resultArr = $oriPerfArr;
  2728. foreach ($perfArr as $keyT => $perfT) {
  2729. if ($perfT <= 0) {
  2730. unset($perfArr[$keyT]);
  2731. }
  2732. }
  2733. if (count($perfArr) >= 2 && $loopTimes < 6) {
  2734. arsort($perfArr, SORT_NUMERIC);
  2735. $onePerf = null;
  2736. $oneKey = null;
  2737. // $touchSurplusAmount = 0;
  2738. $touchAmount = 0;
  2739. // 前两个进行对碰
  2740. foreach ($perfArr as $key => $perf) {
  2741. if ($onePerf === null) {
  2742. $oneKey = $key;
  2743. $onePerf = $perf;
  2744. } else {
  2745. $touchSurplusAmount = $perf - $onePerf;
  2746. if ($touchSurplusAmount > 0) {
  2747. unset($perfArr[$oneKey]);
  2748. $resultArr['perfArr'][$oneKey] = 0;
  2749. $perfArr[$key] = $touchSurplusAmount;
  2750. $touchAmount = $onePerf;
  2751. } elseif ($touchSurplusAmount < 0) {
  2752. unset($perfArr[$key]);
  2753. $resultArr['perfArr'][$key] = 0;
  2754. $perfArr[$oneKey] = abs($touchSurplusAmount);
  2755. $touchAmount = $perf;
  2756. } else {
  2757. unset($perfArr[$oneKey], $perfArr[$key]);
  2758. $resultArr['perfArr'][$oneKey] = 0;
  2759. $resultArr['perfArr'][$key] = 0;
  2760. $touchAmount = $perf;
  2761. }
  2762. break;
  2763. }
  2764. }
  2765. /*if ($touchAmount > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2766. $touchAmount = $nowDecLevelConfig['QY_TOUCH_CAP'];
  2767. }*/
  2768. $touchBonus = Tool::formatPrice($touchAmount * $percent);
  2769. // if ($touchBonus > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2770. // $resultArr['touchBonus'] += $nowDecLevelConfig['QY_TOUCH_CAP'];
  2771. // } else {
  2772. // $resultArr['touchBonus'] += $touchBonus;
  2773. // }
  2774. $resultArr['touchBonus'] += $touchBonus;
  2775. foreach ($perfArr as $keyR => $perfR) {
  2776. $resultArr['perfArr'][$keyR] = $perfR;
  2777. }
  2778. return $this->touchPerf($resultArr, $perfArr, $percent, $loopTimes+1);
  2779. }
  2780. return $resultArr;
  2781. }
  2782. /**
  2783. * 对碰
  2784. * @param array $oriPerfArr
  2785. * @param array $perfArr
  2786. * @param $decLevel
  2787. * @param $decLevelConfig
  2788. * @param $loopTimes
  2789. * @return array
  2790. */
  2791. public function touchPerfBefore(array $oriPerfArr, array $perfArr, $decLevel, $decLevelConfig, $loopTimes=1) {
  2792. $resultArr = $oriPerfArr;
  2793. foreach ($perfArr as $keyT => $perfT) {
  2794. if ($perfT <= 0) {
  2795. unset($perfArr[$keyT]);
  2796. }
  2797. }
  2798. if (count($perfArr) >= 2 && $loopTimes < 6) {
  2799. $nowDecLevelConfig = $decLevelConfig[$decLevel];
  2800. arsort($perfArr, SORT_NUMERIC);
  2801. $onePerf = null;
  2802. $oneKey = null;
  2803. // $touchSurplusAmount = 0;
  2804. $touchAmount = 0;
  2805. // 前两个进行对碰
  2806. foreach ($perfArr as $key => $perf) {
  2807. if ($onePerf === null) {
  2808. $oneKey = $key;
  2809. $onePerf = $perf;
  2810. } else {
  2811. $touchSurplusAmount = $perf - $onePerf;
  2812. if ($touchSurplusAmount > 0) {
  2813. unset($perfArr[$oneKey]);
  2814. $resultArr['perfArr'][$oneKey] = 0;
  2815. $perfArr[$key] = $touchSurplusAmount;
  2816. $touchAmount = $onePerf;
  2817. } elseif ($touchSurplusAmount < 0) {
  2818. unset($perfArr[$key]);
  2819. $resultArr['perfArr'][$key] = 0;
  2820. $perfArr[$oneKey] = abs($touchSurplusAmount);
  2821. $touchAmount = $perf;
  2822. } else {
  2823. unset($perfArr[$oneKey], $perfArr[$key]);
  2824. $resultArr['perfArr'][$oneKey] = 0;
  2825. $resultArr['perfArr'][$key] = 0;
  2826. $touchAmount = $perf;
  2827. }
  2828. break;
  2829. }
  2830. }
  2831. /*if ($touchAmount > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2832. $touchAmount = $nowDecLevelConfig['QY_TOUCH_CAP'];
  2833. }*/
  2834. $touchBonus = Tool::formatPrice($touchAmount * 2 / 100);
  2835. // if ($touchBonus > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2836. // $resultArr['touchBonus'] += $nowDecLevelConfig['QY_TOUCH_CAP'];
  2837. // } else {
  2838. // $resultArr['touchBonus'] += $touchBonus;
  2839. // }
  2840. $resultArr['touchBonus'] += $touchBonus;
  2841. foreach ($perfArr as $keyR => $perfR) {
  2842. $resultArr['perfArr'][$keyR] = $perfR;
  2843. }
  2844. return $this->touchPerfBefore($resultArr, $perfArr, $decLevel, $decLevelConfig, $loopTimes+1);
  2845. }
  2846. return $resultArr;
  2847. }
  2848. /**
  2849. * 循环父级并执行回调函数
  2850. * @param $userId
  2851. * @param callable $callbackFunc
  2852. * @param int $offset
  2853. * @return bool
  2854. */
  2855. public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
  2856. $allParents = Cache::getAllNetworkParents($userId);
  2857. $allData = array_slice($allParents, $offset, $this->_limit);
  2858. unset($allParents);
  2859. if ($allData) {
  2860. foreach ($allData as $data) {
  2861. $funcResult = $callbackFunc($data);
  2862. if ($funcResult === self::LOOP_FINISH) {
  2863. return true;
  2864. } elseif ($funcResult === self::LOOP_CONTINUE) {
  2865. continue;
  2866. }
  2867. unset($data, $funcResult);
  2868. }
  2869. unset($allData);
  2870. return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
  2871. }
  2872. return true;
  2873. }
  2874. /**
  2875. * 循环推荐网络的父级
  2876. * @param $userId
  2877. * @param callable $callbackFunc
  2878. * @param int $offset
  2879. * @return bool
  2880. */
  2881. public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
  2882. $allParents = Cache::getAllRelationParents($userId);
  2883. $allData = array_slice($allParents, $offset, $this->_limit);
  2884. unset($allParents);
  2885. if ($allData) {
  2886. foreach ($allData as $data) {
  2887. $funcResult = $callbackFunc($data);
  2888. if ($funcResult === self::LOOP_FINISH) {
  2889. return true;
  2890. } elseif ($funcResult === self::LOOP_CONTINUE) {
  2891. continue;
  2892. }
  2893. unset($data, $funcResult);
  2894. }
  2895. unset($allData);
  2896. return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
  2897. }
  2898. return true;
  2899. }
  2900. /**
  2901. * 共享奖,判断当期此用户,是否有原报单团队奖金
  2902. */
  2903. public function checkHasOriBonusQyBd($userId) {
  2904. //判断$parent是否有首单团队奖
  2905. $bonus = CalcCache::bonus($userId, $this->_periodNum);
  2906. if( isset($bonus['ORI_BONUS_QY_BD']) && $bonus['ORI_BONUS_QY_BD'] > 0 ) {
  2907. return true;
  2908. }
  2909. return false;
  2910. }
  2911. /**
  2912. * 判断除大市场外 其它市场的报单业绩
  2913. * @param $userId
  2914. * @return bool
  2915. * @throws \yii\db\Exception
  2916. */
  2917. public function checkSmallMarketPerf($userId) {
  2918. // 从缓存中获取会员的上期结余业绩信息
  2919. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  2920. //判断出大市场
  2921. $areaNums = [1, 2, 3];
  2922. $maxArea = 0;
  2923. $maxSurplusPerf = 0;
  2924. foreach ($areaNums as $area) {
  2925. $areaKey = sprintf('SURPLUS_%dL', $area);
  2926. if ( isset($pervSurplusPerf[$areaKey]) && $pervSurplusPerf[$areaKey] > $maxSurplusPerf ) {
  2927. $maxArea = $area;
  2928. $maxSurplusPerf = $pervSurplusPerf[$areaKey];
  2929. }
  2930. unset($area, $areaKey);
  2931. }
  2932. unset($pervSurplusPerf, $maxSurplusPerf);
  2933. $otherAreaZcPv = 0;
  2934. $nowPeriodPerf = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  2935. foreach ($areaNums as $area) {
  2936. if( $maxArea > 0 && $area === $maxArea ) continue;
  2937. $areaKey = sprintf('PV_%dL_ZC', $area);
  2938. if ( isset($nowPeriodPerf[$areaKey]) && $nowPeriodPerf[$areaKey] > 0 ) {
  2939. $otherAreaZcPv += $nowPeriodPerf[$areaKey];
  2940. }
  2941. unset($area, $areaKey);
  2942. }
  2943. unset($nowPeriodPerf, $areaNums, $maxArea);
  2944. return $otherAreaZcPv >= self::MIN_BD_PV;
  2945. }
  2946. /**
  2947. * 获取有最小报单PV的用效父级
  2948. * @param $userId
  2949. * @return string
  2950. */
  2951. public function getMinBdPvRelationParent($userId) {
  2952. $validParentId = '';
  2953. $this->loopRelationParentDo($userId, function ($parent) use(&$validParentId) {
  2954. if ( $this->checkSmallMarketPerf($parent['PARENT_UID']) ) {
  2955. $validParentId = $parent['PARENT_UID'];
  2956. unset($parent);
  2957. return self::LOOP_FINISH;
  2958. }
  2959. unset($parent);
  2960. });
  2961. return$validParentId;
  2962. }
  2963. /**
  2964. * 获取有最小报单PV的用效父级 20220407修改成是否此期此用户有原报单团队奖金
  2965. * @param $userId
  2966. * @return string
  2967. */
  2968. public function getMinBdPvNetworkParent($userId, $openFindLimit = 1, $findLimitTimes = 5) {
  2969. $validParentId = '';
  2970. $validDeep = 1;
  2971. $this->loopNetworkParentDo($userId, function ($parent) use(&$validParentId,&$validDeep,$openFindLimit,$findLimitTimes) {
  2972. if ( $this->checkHasOriBonusQyBd($parent['PARENT_UID']) ) {
  2973. $validParentId = $parent['PARENT_UID'];
  2974. unset($parent);
  2975. return self::LOOP_FINISH;
  2976. }
  2977. // 只找5层
  2978. if ( $openFindLimit && $validDeep >= $findLimitTimes ) {
  2979. unset($parent);
  2980. return self::LOOP_FINISH;
  2981. }
  2982. $validDeep += 1;
  2983. unset($parent);
  2984. });
  2985. return$validParentId;
  2986. }
  2987. // public function getMinBdPvNetworkParent($userId, $openFindLimit = 1, $findLimitTimes = 5) {
  2988. // $validParentId = '';
  2989. // $validDeep = 1;
  2990. // $this->loopNetworkParentDo($userId, function ($parent) use(&$validParentId,&$validDeep,$openFindLimit,$findLimitTimes) {
  2991. // if ( $this->checkSmallMarketPerf($parent['PARENT_UID']) ) {
  2992. // $validParentId = $parent['PARENT_UID'];
  2993. // unset($parent);
  2994. // return self::LOOP_FINISH;
  2995. // }
  2996. // // 只找5层
  2997. // if ( $openFindLimit && $validDeep >= $findLimitTimes ) {
  2998. // unset($parent);
  2999. // return self::LOOP_FINISH;
  3000. // }
  3001. // $validDeep += 1;
  3002. // unset($parent);
  3003. // });
  3004. // return$validParentId;
  3005. // }
  3006. /**
  3007. * 按级别的收入上限
  3008. * 新的需求调整: 改成不按月进行限制,并且去掉vip奖
  3009. * @param $bonus
  3010. * @param $userId
  3011. * @param $declarationLevel
  3012. * @return float
  3013. */
  3014. public function declarationLevelCap($bonus, $userId, $declarationLevel) {
  3015. $decLevelConfig = $this->_decLevelConfig;
  3016. $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
  3017. unset($decLevelConfig);
  3018. $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'];
  3019. if( $bonus <= $maxGetBonus) {
  3020. return $bonus;
  3021. }else {
  3022. return $maxGetBonus;
  3023. }
  3024. }
  3025. // public function declarationLevelCap($bonus, $userId, $declarationLevel) {
  3026. // $decLevelConfig = $this->_decLevelConfig;
  3027. // $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
  3028. // unset($decLevelConfig);
  3029. // //本月往期奖金 这里执行速度可能慢一些,但需求如此没有办法
  3030. // $lastData = CalcCache::lastPeriodMonthCalcBonus($userId, $this->_periodNum, $this->_calcMonth);
  3031. // $lastTotal = $lastData['ORI_BONUS_QY_SUM'] + $lastData['ORI_BONUS_VIP_SUM'];
  3032. // // 从缓存中获取用户的奖金
  3033. // $bonusData = CalcCache::bonus($userId, $this->_periodNum);
  3034. // $thisTotal = $bonusData['ORI_BONUS_QY'] + $bonusData['ORI_BONUS_VIP'];
  3035. // $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'] * $this->_calcMonthPeriodNumCount - $lastTotal - $thisTotal;
  3036. // unset($lastData, $lastTotal, $bonusData, $thisTotal);
  3037. // if( $maxGetBonus <= 0 ) return 0.00;
  3038. // if( $bonus <= $maxGetBonus) {
  3039. // return $bonus;
  3040. // }else {
  3041. // return $maxGetBonus;
  3042. // }
  3043. // }
  3044. /**
  3045. * 总奖金限制
  3046. * @param $bonus
  3047. * @param $userId
  3048. * @param $recNum
  3049. * @param $decAmount
  3050. * @return float
  3051. */
  3052. public function bonusTotalLimit($bonus, $userId, $recNum, $decAmount) {
  3053. //@todo 临时不做总奖金限制
  3054. return $bonus;
  3055. if( $recNum >= 3 ) return $bonus;
  3056. $limitAmount = 0;
  3057. switch ($recNum) {
  3058. case 0:
  3059. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalZeroLimit']['VALUE'];
  3060. break;
  3061. case 1:
  3062. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalOneLimit']['VALUE'];
  3063. break;
  3064. case 2:
  3065. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalTwoLimit']['VALUE'];
  3066. break;
  3067. default:
  3068. break;
  3069. }
  3070. // 从缓存中获取用户的奖金
  3071. $lastUserBonus = CalcCache::LastUserBonus($userId, $this->_periodNum);//往期的总金额
  3072. $bonusData = CalcCache::bonus($userId, $this->_periodNum);
  3073. $bonusTotal = $bonusData['BONUS_TOTAL'] + $lastUserBonus['BONUS_TOTAL'];
  3074. unset($lastUserBonus, $userId, $recNum, $decAmount, $bonusData);
  3075. if( $bonusTotal >= $limitAmount ) return 0.00;
  3076. if( $bonusTotal + $bonus <= $limitAmount) {
  3077. return $bonus;
  3078. }else {
  3079. return $limitAmount - $bonusTotal;
  3080. }
  3081. }
  3082. /**
  3083. * 扣除复消积分和管理费
  3084. * @param $userId
  3085. * @param $bonus
  3086. * @return array
  3087. * @throws \yii\db\Exception
  3088. */
  3089. public function deductNoReconsumePoints($userId, $bonus): array
  3090. {
  3091. $manageTax = $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
  3092. $surplus = $bonus - $manageTax;
  3093. return [
  3094. 'reConsumePoints' => 0.00,
  3095. 'manageTax' => Tool::formatPrice($manageTax),
  3096. 'surplus' => Tool::formatPrice($surplus),
  3097. ];
  3098. }
  3099. /**
  3100. * 扣除复消积分和管理费
  3101. * @param $userId
  3102. * @param $bonus
  3103. * @return array
  3104. * @throws \yii\db\Exception
  3105. */
  3106. public function deduct($userId, $bonus) {
  3107. //判断是否达到了本月扣除复消的上限
  3108. $cacheData = CalcCache::monthLastPeriodReconsumePoints($userId, $this->_periodNum, $this->_calcYearMonth);
  3109. $bonusCache = CalcCache::bonus($userId, $this->_periodNum);
  3110. $reConsumePointsTotal = $bonusCache['RECONSUME_POINTS'] + $cacheData['RECONSUME_POINTS_SUM'];
  3111. $reConsumePointsCap = $this->_sysConfig['reConsumePointsMonthCap']['VALUE'];
  3112. unset($cacheData, $bonusCache);
  3113. $reConsumePoints = 0;
  3114. if( $reConsumePointsTotal < $reConsumePointsCap ) {
  3115. $reConsumePoints = $bonus * $this->_sysConfig['reConsumePointsPercent']['VALUE'] / 100;
  3116. $reConsumePoints = min($reConsumePoints, $reConsumePointsCap-$reConsumePointsTotal);
  3117. }
  3118. unset($reConsumePointsTotal, $reConsumePointsCap);
  3119. $manageTax = $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
  3120. $surplus = $bonus - $reConsumePoints - $manageTax;
  3121. return [
  3122. 'reConsumePoints' => Tool::formatPrice($reConsumePoints),//复效积分
  3123. 'manageTax' => Tool::formatPrice($manageTax),//管理费
  3124. 'surplus' => Tool::formatPrice($surplus),//真实奖金
  3125. ];
  3126. }
  3127. /**
  3128. * 更新百分比并发送
  3129. * @param $percent
  3130. */
  3131. private function _updatePercent($percent) {
  3132. // 把数据写入数据库中
  3133. Period::updateAll(['CALC_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  3134. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'CALC_PERCENT']);
  3135. }
  3136. /**
  3137. * 把往期有月奖金的会员加到本期有奖会员缓存列表中
  3138. * @param int $offset
  3139. * @return bool
  3140. */
  3141. public function loopMonthBonusUserFromDbToCache($offset = 0) {
  3142. if (!$this->_isCalcMonth) {
  3143. return true;
  3144. }
  3145. $allData = CalcMonthBonusUser::findUseDbCalc()->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->offset($offset)->limit($this->_limit)->asArray()->all();
  3146. if ( $allData ) {
  3147. foreach ($allData as $everyData) {
  3148. CalcCache::addHasBonusUsers($everyData['USER_ID'], $this->_periodNum);
  3149. unset($everyData);
  3150. }
  3151. unset($allData);
  3152. $this->loopMonthBonusUserFromDbToCache($offset + $this->_limit);
  3153. }
  3154. unset($allData);
  3155. return true;
  3156. }
  3157. /**
  3158. * 把缓存中的月奖用户信息存到数据库
  3159. * @param int $offset
  3160. * @return bool
  3161. * @throws \yii\db\Exception
  3162. */
  3163. public function loopMonthBonusUserToDb($offset = 0) {
  3164. echo sprintf("时间:[%s]月奖会员入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3165. $allData = CalcCache::getHasMonthBonusUsers($this->_periodNum, $offset, $this->_limit);
  3166. if($allData) {
  3167. $insertDataBonusUser = [];
  3168. foreach($allData as $userId){
  3169. $insertDataBonusUser[] = [
  3170. 'ID' => SnowFake::instance()->generateId(),
  3171. 'USER_ID' => $userId,
  3172. 'CALC_MONTH' => $this->_calcYearMonth,
  3173. 'PERIOD_NUM' => $this->_periodNum,
  3174. 'CREATED_AT' => Date::nowTime()
  3175. ];
  3176. unset($userId);
  3177. }
  3178. if( $insertDataBonusUser ) CalcMonthBonusUser::batchInsert($insertDataBonusUser);
  3179. unset($insertDataBonus, $allData);
  3180. return $this->loopMonthBonusUserToDb($offset + $this->_limit);
  3181. }
  3182. unset($allData);
  3183. return true;
  3184. }
  3185. //奖金入库
  3186. /**
  3187. * 循环奖服务奖金会员,并入库
  3188. * @param int $offset
  3189. * @return bool
  3190. * @throws \yii\db\Exception
  3191. */
  3192. public function loopBonusUsers($offset = 0) {
  3193. echo sprintf("时间:[%s]缓存奖金数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3194. // 从缓存列表里面从底层往上倒序获取会员
  3195. // 这里有问题,因为蓝星奖,是存储过程计算的,并没有加入缓存,这里需要修改.
  3196. // 给用户发送兑换积分,也需要进行调整查看。
  3197. // CalcCache::addHasBonusUsers($everyData['USER_ID'], $this->_periodNum);
  3198. $allData = CalcCache::getHasBonusUsers($this->_periodNum, $offset, $this->_limit);
  3199. if($allData){
  3200. $insertDataBonus = [];
  3201. foreach($allData as $userId){
  3202. $tempBonusData = $this->bonusData($userId);
  3203. if(!empty($tempBonusData['result'])){
  3204. $insertDataBonus[] = $tempBonusData['result'];
  3205. }
  3206. unset($userId, $tempBonusData);
  3207. }
  3208. CalcBonus::batchInsert($insertDataBonus);
  3209. unset($insertDataBonus, $allData);
  3210. return $this->loopBonusUsers($offset + $this->_limit);
  3211. }
  3212. return true;
  3213. }
  3214. // 奖金入库完成,将各个奖金计算流水会员聘级,更新成蓝星奖当时计算的聘级
  3215. public function loopCalcBlueEmpLv($offset = 0) {
  3216. if( !$this->_isCalcMonth ) {
  3217. // 不是结算月,则不需要进行聘级调整
  3218. return false;
  3219. }
  3220. // 从缓存获取分页有收入的会员信息
  3221. $allData = CalcBonusBS::findUseDbCalc()
  3222. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  3223. ->groupBy('USER_ID')
  3224. ->offset($offset)
  3225. ->limit($this->_limit)
  3226. ->asArray()
  3227. ->all();
  3228. if ($allData) {
  3229. foreach ($allData as $data) {
  3230. $nowBsEmpLv = $data['LEVEL_ID']; // 当前蓝星奖计算(即管理奖) 的等级
  3231. // 修改AR_CALC_BONUS的LAST_EMP_LV聘级,修改奖金流水的聘级AR_FLOW_BONUS表的LAST_EMP_LV
  3232. // 期结算结果
  3233. CalcBonus::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3234. [
  3235. ':USER_ID' => $data['USER_ID'],
  3236. ':PERIOD_NUM' => $this->_periodNum
  3237. ]
  3238. );
  3239. // 奖金流水
  3240. FlowBonus::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3241. [
  3242. ':USER_ID' => $data['USER_ID'],
  3243. ':PERIOD_NUM' => $this->_periodNum
  3244. ]
  3245. );
  3246. // // 共享奖流水
  3247. // CalcBonusGX::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3248. // [
  3249. // ':USER_ID' => $data['USER_ID'],
  3250. // ':PERIOD_NUM' => $this->_periodNum
  3251. // ]
  3252. // );
  3253. // 推广奖流水
  3254. CalcBonusTG::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3255. [
  3256. ':USER_ID' => $data['USER_ID'],
  3257. ':PERIOD_NUM' => $this->_periodNum
  3258. ]
  3259. );
  3260. // 团队奖流水
  3261. CalcBonusQY::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3262. [
  3263. ':USER_ID' => $data['USER_ID'],
  3264. ':PERIOD_NUM' => $this->_periodNum
  3265. ]
  3266. );
  3267. // // 服务奖流水
  3268. // CalcBonusBD::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3269. // [
  3270. // ':USER_ID' => $data['USER_ID'],
  3271. // ':PERIOD_NUM' => $this->_periodNum
  3272. // ]
  3273. // );
  3274. // // 更新form的聘级
  3275. // CalcBonusGX::updateAll(['LAST_FROM_EMP_LV' => $nowBsEmpLv], 'FROM_USER_ID=:FROM_USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  3276. // [
  3277. // ':FROM_USER_ID' => $data['USER_ID'],
  3278. // ':PERIOD_NUM' => $this->_periodNum
  3279. // ]
  3280. // );
  3281. CalcBonusTG::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. // CalcBonusBD::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. }
  3294. unset($allData);
  3295. return $this->loopCalcBlueEmpLv($offset + $this->_limit);
  3296. }
  3297. unset($allData);
  3298. return true;
  3299. }
  3300. /**
  3301. * 奖金
  3302. * @param $userId
  3303. * @return array
  3304. * @throws \yii\db\Exception
  3305. */
  3306. public function bonusData($userId) {
  3307. // 从缓存中获取用户的奖金
  3308. $bonus = CalcCache::bonus($userId, $this->_periodNum);
  3309. $standardBonus = CalcCache::standardBonus($userId, $this->_periodNum);
  3310. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  3311. $perfData = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  3312. $tourismBonus = CalcCache::tourismBonus($userId, $this->_periodNum);
  3313. $garageBonus = CalcCache::garageBonus($userId, $this->_periodNum);
  3314. $villaBonus = CalcCache::villaBonus($userId, $this->_periodNum);
  3315. $empLv = $baseInfo['EMP_LV'];
  3316. // if($this->_isCalcMonth){
  3317. // $empLv = $this->nowMonthPerfData($userId)['LAST_EMP_LV'];
  3318. // }
  3319. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  3320. // 星级
  3321. $starCrownLv = CalcCache::getUserStartCrown($userId, $this->_periodNum);
  3322. // //没有共享和管理奖 以前的管理奖和共享奖逻辑
  3323. // $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;
  3324. // $realBonusGx = 0;
  3325. // $realBonusGl = 0;
  3326. // if( $this->_isCalcMonth ) {
  3327. // //查看是否复消300
  3328. // $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  3329. // $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  3330. // if ( $fxPvStatus ) {//加上本期和往期的共享和管理奖
  3331. // $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();
  3332. // $bonusGxSum = $monthSumData['BONUS_GX_SUM'] ?? 0;
  3333. // $bonusGlSum = $monthSumData['BONUS_GL_SUM'] ?? 0;
  3334. // $realBonusGx += $bonusGxSum + $bonus['BONUS_GX'];
  3335. // $realBonusGl += $bonusGlSum + $bonus['BONUS_GL'];
  3336. // $bonusReal += $realBonusGx + $realBonusGl;
  3337. // unset($monthSumData, $bonusGxSum, $bonusGlSum);
  3338. // }
  3339. // }
  3340. //没有共享和管理奖
  3341. $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'];
  3342. $realBonusGx = 0;
  3343. $realBonusGl = 0;
  3344. $realBonusBs = 0; // 蓝星管理奖. BlueStar
  3345. $blueStartOriBonus = 0;
  3346. $blueStartManageTax = 0;
  3347. $exchangePoints = 0; // 蓝星奖管理奖. 产生的兑换积分
  3348. $realBonusBsMnt = 0; // 蓝星管理奖——实发奖金
  3349. $blueStartOriBonusMnt = 0; // 蓝星管理奖——原奖金
  3350. $blueStartManageTaxMnt = 0; // 蓝星管理奖——管理费
  3351. $realBonusBsAbbr = 0; // 蓝星业绩奖——实发奖金
  3352. $blueStartOriBonusAbbr = 0; // 蓝星业绩奖——原奖金
  3353. $blueStartManageTaxAbbr = 0; // 蓝星业绩奖——管理费
  3354. if( $this->_isCalcMonth ) {
  3355. // 个人月消费PV大于配置值,才会计算发放蓝星奖
  3356. $fxPvStatus = $this->_isMonthPerfLimit($userId);
  3357. // BONUS_REAL 字段是发到用户的真实奖金
  3358. if ( $fxPvStatus ) {
  3359. // 管理奖改成了蓝星奖,但是对于用户来说依旧叫管理奖.字段改成bs.
  3360. // 因为管理奖(即蓝星奖,是用存储过程计算的,则此处直接取AR_CALC_BONUS_BS表中计算的结果数据使用,
  3361. // 并将管理奖结果同步到当前结算月的CalcBonus中)
  3362. // 由于单独奖金流水记录每次都插入,所以倒叙找最新的数据.
  3363. $userBS = CalcBonusBS::find()
  3364. ->where(
  3365. 'PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID',
  3366. [
  3367. ':PERIOD_NUM' => $this->_periodNum,
  3368. ':USER_ID' => $userId
  3369. ]
  3370. )
  3371. ->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')
  3372. ->limit(1)
  3373. ->orderBy('CREATED_AT DESC')
  3374. ->asArray()
  3375. ->all();
  3376. $userBS = is_array($userBS) ? reset($userBS) : [];
  3377. $blueStartAmount = isset($userBS['AMOUNT']) && !empty($userBS['AMOUNT']) ? $userBS['AMOUNT'] : 0; // 奖金
  3378. $blueStartOriBonus = isset($userBS['ORI_BONUS']) && !empty($userBS['ORI_BONUS']) ? $userBS['ORI_BONUS'] : 0; // 原奖金
  3379. $blueStartManageTax = isset($userBS['MANAGE_TAX']) && !empty($userBS['MANAGE_TAX']) ? $userBS['MANAGE_TAX'] : 0; // 管理费
  3380. $realBonusBsMnt = $userBS['AMOUNT_MNT'] ?? 0; // 蓝星管理奖. 实发奖金
  3381. $blueStartOriBonusMnt = $userBS['ORI_BONUS_MNT'] ?? 0; // 蓝星管理奖. 原奖金
  3382. $blueStartManageTaxMnt = $userBS['MANAGE_TAX_MNT'] ?? 0; // 蓝星管理奖. 管理费
  3383. $realBonusBsAbbr = $userBS['AMOUNT_ABBR'] ?? 0; // 蓝星业绩奖. 奖金
  3384. $blueStartOriBonusAbbr = $userBS['ORI_BONUS_ABBR'] ?? 0; // 蓝星业绩奖. 原奖金
  3385. $blueStartManageTaxAbbr = $userBS['MANAGE_TAX_ABBR'] ?? 0; // 蓝星业绩奖. 管理费
  3386. $blueStartManageTax += $blueStartManageTaxMnt + $blueStartManageTaxAbbr; // 管理费
  3387. $monthSumData = CalcBonus::findUseSlaves()
  3388. ->select('SUM(BONUS_GX) AS BONUS_GX_SUM, SUM(BONUS_GL) AS BONUS_GL_SUM')
  3389. ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
  3390. [
  3391. 'USER_ID' => $userId,
  3392. 'CALC_MONTH' => $this->_calcYearMonth
  3393. ]
  3394. )
  3395. ->asArray()
  3396. ->one();
  3397. $realBonusBs = $blueStartAmount; // 蓝星奖直接取数据库中算好的值PRODUCT_POINT
  3398. $exchangePoints = isset($userBS['PRODUCT_POINT']) && !empty($userBS['PRODUCT_POINT']) ? $userBS['PRODUCT_POINT'] : 0; // 兑换积分
  3399. // 蓝星奖总奖金:管理奖+业绩奖
  3400. // $blueStartOriBonus = $blueStartOriBonusMnt + $blueStartOriBonusAbbr;
  3401. // $bonus['BONUS_TOTAL'] = $bonus['BONUS_TOTAL'] + $blueStartOriBonus; // 管理奖在存储过程计算,这里单独加上管理奖(即蓝星奖)
  3402. unset($monthSumData, $bonusGxSum, $bonusGlSum);
  3403. }
  3404. }
  3405. if( $this->_isCalcMonth ) { //季度奖
  3406. if(in_array($this->_calcMonth, [3,6,9,12])){ // 季度奖
  3407. }
  3408. }
  3409. $result = [
  3410. 'USER_ID' => $userId,
  3411. 'LAST_USER_NAME' => $baseInfo['USER_NAME'],
  3412. 'LAST_REAL_NAME' => $baseInfo['REAL_NAME'],
  3413. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  3414. 'LAST_EMP_LV' => $empLv,
  3415. 'LAST_STAR_LV' => $starCrownLv ?? StarCrownLevel::getDefaultLevelId(),
  3416. 'LAST_STATUS' => $baseInfo['STATUS'],
  3417. 'LAST_MOBILE' => $baseInfo['MOBILE'],
  3418. 'LAST_PERIOD_AT' => $baseInfo['PERIOD_NUM'],
  3419. 'LAST_CREATED_AT' => $baseInfo['CREATED_AT'],
  3420. 'LAST_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
  3421. 'LAST_PROVINCE' => $baseInfo['PROVINCE'],
  3422. 'LAST_CITY' => $baseInfo['CITY'],
  3423. 'LAST_COUNTY' => $baseInfo['COUNTY'],
  3424. 'LAST_SYSTEM_ID' => $baseInfo['SYSTEM_ID'] ? $baseInfo['SYSTEM_ID'] : '',
  3425. 'LAST_IS_DIRECT_SELLER' => $baseInfo['IS_DIRECT_SELLER'],
  3426. 'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
  3427. 'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
  3428. 'LAST_CON_USER_NAME' => $baseInfo['CON_USER_NAME'],
  3429. 'LAST_CON_REAL_NAME' => $baseInfo['CON_REAL_NAME'],
  3430. 'EXCHANGE_POINTS' => $exchangePoints, // 兑换积分
  3431. // 'LAST_LOCATION' => $baseInfo['LOCATION'] ? $baseInfo['LOCATION'] : 1,
  3432. //@todo
  3433. 'LAST_LOCATION' => 1,
  3434. 'BONUS_BD' => $bonus['BONUS_BD'],
  3435. 'BONUS_TG' => $bonus['BONUS_TG'],
  3436. 'BONUS_XF' => $bonus['BONUS_XF'],
  3437. 'BONUS_YJ' => $bonus['BONUS_YJ'],
  3438. 'BONUS_GX' => $bonus['BONUS_GX'],
  3439. 'BONUS_GL' => $bonus['BONUS_GL'],
  3440. 'BONUS_QY' => $bonus['BONUS_QY'],
  3441. 'BONUS_YC' => $bonus['BONUS_YC'] + $bonus['BONUS_YC_EXTRA'],
  3442. 'BONUS_VIP' => $bonus['BONUS_VIP'],
  3443. 'RECONSUME_POINTS' => $bonus['RECONSUME_POINTS'],
  3444. 'MANAGE_TAX' => $blueStartManageTax, // 管理费
  3445. 'BONUS_INCOME'=>$bonus['INCOME_TOTAL'],
  3446. 'BONUS_REAL'=> $bonusReal,
  3447. 'BONUS_TOTAL'=>$bonus['BONUS_TOTAL'],
  3448. 'ORI_BONUS_BD' => $bonus['ORI_BONUS_BD'],
  3449. 'ORI_BONUS_TG' => $bonus['ORI_BONUS_TG'],
  3450. 'ORI_BONUS_XF' => $bonus['ORI_BONUS_XF'],
  3451. 'ORI_BONUS_YJ' => $bonus['ORI_BONUS_YJ'],
  3452. 'ORI_BONUS_YJ_BD' => $bonus['ORI_BONUS_YJ_BD'],
  3453. 'ORI_BONUS_YJ_FX' => $bonus['ORI_BONUS_YJ_FX'],
  3454. 'ORI_BONUS_GX' => $bonus['ORI_BONUS_GX'],
  3455. 'REAL_BONUS_GX' => $realBonusGx,
  3456. 'ORI_BONUS_GL' => $bonus['ORI_BONUS_GL'],
  3457. 'REAL_BONUS_GL' => $realBonusGl,
  3458. 'BONUS_BS' => $realBonusBs, // 新的管理奖金,即蓝星管理奖
  3459. 'ORI_BONUS_BS' => $blueStartOriBonus, // 蓝星管理奖金原奖金,即包含管理费
  3460. 'REAL_BONUS_BS' => $realBonusBs, // 实发蓝星管理奖金
  3461. 'BONUS_BS_MNT' => $realBonusBsMnt, // 蓝星管理奖
  3462. 'ORI_BONUS_BS_MNT' => $blueStartOriBonusMnt, // 蓝星管理奖金原奖金,即包含管理费
  3463. 'REAL_BONUS_BS_MNT' => $realBonusBsMnt, // 实发蓝星管理奖金
  3464. 'MANAGE_TAX_MNT' => $blueStartManageTaxMnt, // 实发蓝星管理——管理费
  3465. 'BONUS_BS_ABBR' => $realBonusBsAbbr, // 蓝星业绩奖
  3466. 'ORI_BONUS_BS_ABBR' => $blueStartOriBonusAbbr, // 蓝星业绩奖金原奖金,即包含管理费
  3467. 'REAL_BONUS_BS_ABBR' => $realBonusBsAbbr, // 实发蓝星业绩奖金
  3468. 'MANAGE_TAX_ABBR' => $blueStartManageTaxAbbr, // 实发蓝星业绩奖——管理费
  3469. 'ORI_BONUS_GL_BD' => $bonus['ORI_BONUS_GL_BD'],
  3470. 'ORI_BONUS_GL_FX' => $bonus['ORI_BONUS_GL_FX'],
  3471. 'ORI_BONUS_QY' => $bonus['ORI_BONUS_QY'],
  3472. 'ORI_BONUS_QY_BD' => $bonus['ORI_BONUS_QY_BD'],
  3473. 'ORI_BONUS_QY_FX' => $bonus['ORI_BONUS_QY_FX'],
  3474. 'ORI_BONUS_YC' => $bonus['ORI_BONUS_YC'] + $bonus['ORI_BONUS_YC_EXTRA'],
  3475. 'ORI_BONUS_VIP' => $bonus['ORI_BONUS_VIP'],
  3476. 'ORI_BONUS_STANDARD' => $standardBonus,
  3477. 'ORI_CAPPED_BONUS_QY' => $bonus['ORI_CAPPED_BONUS_QY'], // 团队奖封顶前的奖金
  3478. 'BONUS_QUARTER' => $bonus['BONUS_QUARTER'],
  3479. 'ORI_BONUS_QUARTER' => $bonus['ORI_BONUS_QUARTER'],
  3480. 'BONUS_TOURISM' => $tourismBonus, // 旅游奖
  3481. 'BONUS_VILLA' => $villaBonus, // 房奖
  3482. 'BONUS_GARAGE' => $garageBonus, // 车奖
  3483. //以下没有用
  3484. 'BONUS_FW' => 0,
  3485. 'BONUS_FX' => $bonus['BONUS_FX'],
  3486. 'BONUS_LS' => $bonus['BONUS_LS'],
  3487. 'BONUS_BT' => $bonus['BONUS_BT'],
  3488. 'BONUS_BT_PROD' => $bonus['BONUS_BT_PROD'],
  3489. 'BONUS_BT_TOOL' => $bonus['BONUS_BT_TOOL'],
  3490. 'DEDUCT_ZR' => $bonus['DEDUCT_ZR'],
  3491. 'BONUS_FL' => $bonus['BONUS_FL'],
  3492. 'BONUS_CF' => $bonus['BONUS_CF'],
  3493. 'BONUS_LX' => $bonus['BONUS_LX'],
  3494. 'SHOULD_QY' => $bonus['BONUS_QY'],
  3495. 'SHOULD_DEDUCT_ZR' => $bonus['DEDUCT_ZR'],
  3496. 'PV_1L' => $perfData['PV_1L_TOUCH'],//TOUCH为碰业绩
  3497. 'QY_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
  3498. 'SURPLUS_1L' => $perfData['SURPLUS_1L'],
  3499. 'PV_2L' => $perfData['PV_2L_TOUCH'],
  3500. 'QY_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
  3501. 'SURPLUS_2L' => $perfData['SURPLUS_2L'],
  3502. 'PV_3L' => $perfData['PV_3L_TOUCH'],
  3503. 'QY_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
  3504. 'SURPLUS_3L' => $perfData['SURPLUS_3L'],
  3505. 'PV_4L' => $perfData['PV_4L_TOUCH'],
  3506. 'QY_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
  3507. 'SURPLUS_4L' => $perfData['SURPLUS_4L'],
  3508. 'PV_5L' => $perfData['PV_5L_TOUCH'],
  3509. 'QY_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
  3510. 'SURPLUS_5L' => $perfData['SURPLUS_5L'],
  3511. 'PV_PCS' => $perfData['PV_PCS'],
  3512. 'PV_LS_TOUCH' => 0.00,
  3513. 'SURPLUS_LS' => 0.00,
  3514. 'QY_LS' => 0.00,
  3515. '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']),
  3516. 'PERIOD_NUM' => $this->_periodNum,
  3517. 'CALC_YEAR' => $this->_calcYear,
  3518. 'CALC_MONTH' => $this->_calcYearMonth,
  3519. 'CALCULATED_AT' => Date::nowTime(),
  3520. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  3521. 'CREATED_AT' => Date::nowTime(),
  3522. ];
  3523. $resend = [];
  3524. unset($bonus, $realBonusGx, $realBonusGl, $bonusReal);
  3525. return ['result'=>$result,'resend'=>$resend];
  3526. }
  3527. /**
  3528. * 根据本有收入计算基础积分
  3529. * @param int $offset
  3530. * @return bool
  3531. */
  3532. public function calcBaseScore(int $offset=0) {
  3533. if (!$this->_isCalcMonth) {
  3534. return true;
  3535. }
  3536. echo sprintf("时间:[%s]基础积分,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3537. //查询本月的,每人的累计总收入
  3538. $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();
  3539. if ($allData) {
  3540. foreach ($allData as $everyData) {
  3541. $validTotalSum = $everyData['TOTAL_SUM'] - $everyData['BD_TOTAL_SUM'];
  3542. if( $validTotalSum <=0 ) continue;
  3543. //达不到 见习主任级别,不产生基础积分
  3544. $userBaseInfo = CalcCache::getUserInfo($everyData['USER_ID'], $this->_periodNum);
  3545. $userEmpLevel = $this->_empLevelConfig[$userBaseInfo['EMP_LV']];
  3546. $userEmpLevelSort = $userEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  3547. unset($userBaseInfo, $userEmpLevel);
  3548. if( $userEmpLevelSort < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {
  3549. unset($userEmpLevelSort);
  3550. continue;
  3551. }
  3552. unset($userEmpLevelSort);
  3553. //根据总收入获取积分
  3554. $baseScore = $this->_getBaseScoreByTotalBonus($validTotalSum);
  3555. //根据用户的级别判断 能否得到级别积分
  3556. if( $baseScore > 0 ) {
  3557. CalcCache::nowMonthScore($everyData['USER_ID'], $this->_periodNum, [
  3558. 'BASE_SCORE' => $baseScore,
  3559. ]);
  3560. CalcCache::addHasScoreUsers($everyData['USER_ID'], $this->_periodNum);
  3561. }
  3562. unset($everyData, $validTotalSum, $baseScore);
  3563. }
  3564. unset($allData);
  3565. return $this->calcBaseScore($offset + $this->_limit);
  3566. }
  3567. unset($allData);
  3568. return true;
  3569. }
  3570. /**
  3571. * 循环积分入库
  3572. * @param int $offset
  3573. * @return bool
  3574. * @throws \yii\db\Exception
  3575. */
  3576. public function loopWriteScore(int $offset = 0) {
  3577. if(!$this->_isCalcMonth){
  3578. return true;
  3579. }
  3580. echo sprintf("时间:[%s]积分入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3581. // 从缓存列表里面从底层往上倒序获取会员
  3582. $allData = CalcCache::getHasScoreUsers($this->_periodNum, $offset, $this->_limit);
  3583. if($allData){
  3584. $insertDataMonthScore = [];
  3585. foreach($allData as $userId){
  3586. $monthScoreData = CalcCache::nowMonthScore($userId, $this->_periodNum);
  3587. $totalScore = $monthScoreData['BASE_SCORE'] + $monthScoreData['LEVEL_SCORE'] + $monthScoreData['UPGRADE_SCORE'];
  3588. if( $totalScore <= 0 ) continue;
  3589. $insertDataMonthScore[] = [
  3590. 'USER_ID' => $userId,
  3591. 'BASE_SCORE' => $monthScoreData['BASE_SCORE'],
  3592. 'LEVEL_SCORE' => $monthScoreData['LEVEL_SCORE'],
  3593. 'UPGRADE_SCORE' => $monthScoreData['UPGRADE_SCORE'],
  3594. 'TOTAL_SCORE' => $totalScore,
  3595. 'PERIOD_NUM' => $this->_periodNum,
  3596. 'CALC_MONTH' => $this->_calcYearMonth,
  3597. 'CREATED_AT' => Date::nowTime(),
  3598. ];
  3599. unset($userId, $monthScoreData, $totalScore);
  3600. }
  3601. ScoreMonth::batchInsert($insertDataMonthScore);
  3602. unset($insertDataMonthScore, $allData);
  3603. return $this->loopWriteScore($offset + $this->_limit);
  3604. }
  3605. unset($allData);
  3606. return true;
  3607. }
  3608. /**
  3609. * 根据总收入获取相应的基础积分
  3610. * @param $totalBonus
  3611. * @return int|mixed
  3612. */
  3613. private function _getBaseScoreByTotalBonus($totalBonus) {
  3614. $baseScoreConfig = Json::decode($this->_sysConfig['baseScore']['VALUE']);
  3615. $baseScore = 0;
  3616. foreach ($baseScoreConfig as $everyScoreData) {
  3617. if( $totalBonus < $everyScoreData['monthTotalPvMin'] ) continue;
  3618. if( $everyScoreData['monthTotalPvMax'] != 0 && $totalBonus >= $everyScoreData['monthTotalPvMax'] ) continue;
  3619. $baseScore = $everyScoreData['score'];
  3620. unset($everyScoreData);
  3621. break;
  3622. }
  3623. unset($baseScoreConfig, $totalBonus);
  3624. return $baseScore;
  3625. }
  3626. // 判断是否满足月最低消费
  3627. public function _isMonthPerfLimit($userId) {
  3628. $userMonthTotal = PerfMonth::find()->where(
  3629. 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
  3630. ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth]
  3631. )
  3632. ->asArray()
  3633. ->one();
  3634. $fxPvStatus = false;
  3635. if (isset($userMonthTotal['PV_PCS']) && $userMonthTotal['PV_PCS'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE']) {
  3636. $fxPvStatus = true;
  3637. }
  3638. return $fxPvStatus;
  3639. }
  3640. }