BonusCalc.php 175 KB

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