BonusCalc.php 154 KB

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