BonusCalc.php 176 KB

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