BonusCalc.php 189 KB

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