BonusCalc.php 163 KB

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