BonusCalc.php 187 KB

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