BonusCalc.php 182 KB

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