BonusCalc.php 170 KB

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