BonusCalc.php 166 KB

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