BonusCalc.php 188 KB

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