BonusCalc.php 163 KB

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