BonusCalc.php 176 KB

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