BonusCalc.php 173 KB

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