BonusCalc.php 173 KB

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