BonusCalc.php 161 KB

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