BonusCalc.php 172 KB

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