BonusCalc.php 166 KB

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