BonusCalc.php 172 KB

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