BonusCalc.php 185 KB

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