BonusCalc.php 165 KB

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