BonusCalc.php 182 KB

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