BonusCalc.php 174 KB

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