BonusCalc.php 177 KB

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