BonusCalc.php 152 KB

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