BonusCalc.php 177 KB

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