BonusCalc.php 182 KB

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