BonusCalc.php 181 KB

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