BonusCalc.php 164 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601
  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. $shareOutTimes = Config::find()
  1314. ->where(
  1315. 'CONFIG_NAME="shareOutTimes"'
  1316. )
  1317. ->indexBy('CONFIG_NAME')
  1318. ->asArray()
  1319. ->all();// 获取向上找五次超过次数限制
  1320. $shareOutTimes = isset($shareOutTimes['shareOutTimes']) ? $shareOutTimes['shareOutTimes']['VALUE'] : 5;
  1321. foreach ($allData as $userId) {
  1322. $bonusUserData = [];
  1323. $bonusPercentOne = $this->_sysConfig['shareRecPercent']['VALUE'] / 100;
  1324. $bonusPercentTwo = $this->_sysConfig['sharePercent']['VALUE'] / 100;
  1325. // 从缓存中获取会员的收入信息
  1326. $incomeBonus = CalcCache::bonus($userId, $this->_periodNum);
  1327. $lastTwoIncome = $incomeBonus['ORI_BONUS_QY_BD'] ?? 0;
  1328. $shareBonusOne = $lastTwoIncome * $bonusPercentOne;
  1329. unset($lastTwoIncome);
  1330. //找到上2代 新增个人+推荐团队业绩 加权平均分配 这个奖
  1331. if( $shareBonusOne > 0) {
  1332. $bonusOneData = $this->gxLastTwoBonusData($userId, 1, $shareBonusOne);
  1333. $bonusTwoData = $this->gxLastTwoBonusData($userId, 2, $shareBonusOne);
  1334. $bonusUserData = array_merge($bonusUserData, $bonusOneData);
  1335. $bonusUserData = array_merge($bonusUserData, $bonusTwoData);
  1336. unset($bonusOneData, $bonusTwoData);
  1337. }
  1338. $nextFiveIncome = $incomeBonus['ORI_BONUS_QY_BD'] ?? 0;
  1339. $shareBonusTwo = $nextFiveIncome * $bonusPercentTwo;
  1340. unset($nextFiveIncome);
  1341. //找到下5代(安置网) 紧缩 相对偶数层2、4、6、8、10层
  1342. if( $shareBonusTwo > 0 ) {
  1343. $validDeep = 1;
  1344. $periodNum = $this->_periodNum;
  1345. $this->loopNetworkParentDo($userId, function ($parent) use ($shareOutTimes, $periodNum, $userId, $shareBonusTwo, &$validDeep, &$bonusUserData) {
  1346. if ( $validDeep % 2 === 0 ) {
  1347. $shareTimes = CalcCache::gxShareTimes($userId, $periodNum);
  1348. // 增加判断,是否分共享奖奖金次数超过了五次,如果超过五次则不进行循环了
  1349. if ($shareTimes > $shareOutTimes) {
  1350. return self::LOOP_FINISH;
  1351. }
  1352. $bonusUserData[] = [
  1353. 'bonusUid' => $parent['PARENT_UID'],
  1354. 'bonus' => $shareBonusTwo,
  1355. 'validMinPv' => true,
  1356. ];
  1357. }
  1358. //判断$parent是否有首单团队奖
  1359. $parentBonus = CalcCache::bonus($parent['PARENT_UID'], $this->_periodNum);
  1360. if( $parentBonus['ORI_BONUS_QY_BD'] > 0 ) {//有效层
  1361. $validDeep += 1;
  1362. }
  1363. unset($parent, $parentBonus);
  1364. if ( $validDeep >= 11 ) {
  1365. return self::LOOP_FINISH;
  1366. }
  1367. });
  1368. unset($validDeep);
  1369. }
  1370. if ( !$bonusUserData ) continue;
  1371. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1372. $userEmpLevel = $userBaseInfo['EMP_LV'];
  1373. foreach ($bonusUserData as $bonusUserDataEvery) {
  1374. $bonusUserId = $bonusUserDataEvery['bonusUid'];
  1375. //判断 是否本期小市场(安置关系)新增980pv 能否得奖->20220407改成判断得奖人此期是否有报单团队奖金
  1376. // if ( $bonusUserDataEvery['validMinPv'] && !$this->checkSmallMarketPerf($bonusUserId) ) { 20220407
  1377. if ( $bonusUserDataEvery['validMinPv'] && !$this->checkHasOriBonusQyBd($bonusUserId) ) {
  1378. // unset($bonusUserDataEvery, $bonusUserId);
  1379. // continue;
  1380. //得奖人不满足980就找一个满足980的人来得这个奖
  1381. // 20220407改成判断得奖人此期是否有报单团队奖金,如果没有则找一个此期有报单团队奖金得人
  1382. $bonusUserId = $this->getMinBdPvNetworkParent($bonusUserId, $openFindLimit, $findLimitTimes);
  1383. if ( !$bonusUserId ) {
  1384. unset($bonusUserDataEvery, $bonusUserId);
  1385. continue;
  1386. }
  1387. }
  1388. $bonus = Tool::formatPrice($bonusUserDataEvery['bonus']);
  1389. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  1390. //总金额限制
  1391. $bonus = $this->bonusTotalLimit($bonus, $bonusUserId, $bonusUserBaseInfo['REC_NUM'], $bonusUserBaseInfo['ZC_AMOUNT']);
  1392. if( $bonus <= 0 ) continue;
  1393. //扣除相应的复消积分和管理费
  1394. $deductData = $this->deduct($bonusUserId, $bonus);
  1395. CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_GX', $bonus, $deductData);
  1396. CalcCache::addHasMonthBonusUsers($bonusUserId, $this->_periodNum);
  1397. //共享奖流水
  1398. $insertBonusData[] = [
  1399. 'ID' => SnowFake::instance()->generateId(),
  1400. 'USER_ID' => $bonusUserId,
  1401. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  1402. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  1403. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  1404. 'FROM_USER_ID' => $userId,
  1405. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  1406. 'LAST_FROM_EMP_LV' => $userEmpLevel,
  1407. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  1408. 'AMOUNT' => $deductData['surplus'],
  1409. 'ORI_BONUS' => $bonus,
  1410. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  1411. 'MANAGE_TAX' => $deductData['manageTax'],
  1412. 'PERIOD_NUM' => $this->_periodNum,
  1413. 'CALC_YEAR' => $this->_calcYear,
  1414. 'CALC_MONTH' => $this->_calcYearMonth,
  1415. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1416. 'CREATED_AT' => Date::nowTime(),
  1417. 'LOGS' => json_encode([
  1418. 'sharePercent' => $bonusPercentOne,
  1419. 'incomeBonus' => $incomeBonus,
  1420. 'recNum' => $userBaseInfo['REC_NUM'],
  1421. 'decAmount' => $userBaseInfo['ZC_AMOUNT'],
  1422. 'bonusTotalLimit' => [
  1423. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  1424. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  1425. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  1426. ],
  1427. ]),
  1428. ];
  1429. unset($bonusUserDataEvery, $bonusUserId, $bonus, $bonusUserBaseInfo, $deductData);
  1430. }
  1431. unset($userId, $bonusUserData, $userBaseInfo, $userEmpLevel, $bonusPercentOne, $bonusPercentTwo, $incomeBonus, $sharePerson);
  1432. // echo ('内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  1433. }
  1434. if($insertBonusData) CalcBonusGX::batchInsert($insertBonusData);
  1435. unset($allData, $insertBonusData);
  1436. return $this->calcBonusGX($offset + $this->_gxLimit);
  1437. }
  1438. unset($allData);
  1439. return true;
  1440. }
  1441. // 执行蓝星管理奖金的存储过程
  1442. public function calcBsProcedure() {
  1443. if( !$this->_isCalcMonth ) {
  1444. // 不是结算月,则不进行计算
  1445. return false;
  1446. }
  1447. $result = \Yii::$app->db->createCommand("CALL CalcBlue(:periodNum)")
  1448. ->bindValue(':periodNum' , $this->_periodNum )
  1449. ->execute();
  1450. return $result;
  1451. }
  1452. /**
  1453. * 蓝星管理奖金
  1454. * @param int $offset
  1455. * @return bool
  1456. * @throws \yii\db\Exception
  1457. */
  1458. public function calcBonusBsGL(int $offset = 0) {
  1459. if( !$this->_isCalcMonth ) {
  1460. // 不是结算月,则不进行计算
  1461. return false;
  1462. }
  1463. // 从缓存获取分页有收入的会员信息
  1464. $allData = CalcBonusBS::findUseDbCalc()
  1465. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  1466. ->groupBy('USER_ID')
  1467. ->offset($offset)
  1468. ->limit($this->_limit)
  1469. ->asArray()
  1470. ->all();
  1471. if ($allData) {
  1472. foreach ($allData as $user) {
  1473. // 添加到有奖励信息的数据中
  1474. CalcCache::addHasBonusUsers($user['USER_ID'], $this->_periodNum);
  1475. //CalcCache::addHasMonthBonusUsers($user['USER_ID'], $this->_periodNum);
  1476. $fxStatus = $this->_isMonthPerfLimit($user['USER_ID']);
  1477. if ($fxStatus) {
  1478. //扣除相应的复消积分和管理费
  1479. $deductData = $this->deduct($user['USER_ID'], $user['ORI_BONUS']);
  1480. // 把对碰后的奖金存入缓存中
  1481. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS', $user['ORI_BONUS'], $deductData);
  1482. $realBonusBs = $deductData['surplus']; // 扣除管理费和复消积分后的实发蓝星奖金
  1483. $manageTax = $deductData['manageTax']; // 管理费
  1484. $point = $deductData['reConsumePoints'];// 复消积分
  1485. } else {
  1486. // 如果未满足月消费,则不扣除管理费和复消积分了
  1487. CalcCache::bonus($user['USER_ID'], $this->_periodNum, 'BONUS_BS', $user['ORI_BONUS']);
  1488. $realBonusBs = $user['ORI_BONUS'];
  1489. $manageTax = 0; // 管理费
  1490. $point = 0;// 复消积分
  1491. }
  1492. // 更新蓝星奖金存储过程的实发金额数据
  1493. CalcBonusBS::updateAll(['AMOUNT' => $realBonusBs, 'MANAGE_TAX' => $manageTax, 'RECONSUME_POINTS' => $point],
  1494. 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  1495. [':USER_ID' => $user['USER_ID'], ':PERIOD_NUM' => $this->_periodNum]);
  1496. }
  1497. return $this->calcBonusBsGL($offset + $this->_limit);
  1498. }
  1499. unset($allData);
  1500. return true;
  1501. }
  1502. /**
  1503. * 报单管理奖
  1504. * @param int $offset
  1505. * @return bool
  1506. * @throws \yii\db\Exception
  1507. */
  1508. public function calcBonusBdGL(int $offset = 0) {
  1509. // 从缓存获取分页有收入的会员信息
  1510. $allData = CalcCache::getHasIncomeUsers($this->_periodNum, $offset, $this->_limit);
  1511. if ($allData) {
  1512. $insertBonusData = [];
  1513. foreach ($allData as $userId) {
  1514. $bonusUserData = [];
  1515. //会员信息
  1516. $validDeep = 1;
  1517. $this->loopRelationParentDo($userId, function ($parent) use ($userId, &$validDeep, &$bonusUserData) {
  1518. //判断$parent是否有首单团队奖
  1519. $bonusUserId = $parent['PARENT_UID'];
  1520. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  1521. $nowDecLevelConfig = $this->_decLevelConfig[$bonusUserBaseInfo['DEC_LV']];
  1522. $recNum = $bonusUserBaseInfo['REC_NUM'];
  1523. if( $recNum <= 0 ) {
  1524. $maxOddLayer = 0;
  1525. }else if( $recNum == 1 ) {
  1526. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_ONE'] ?? 0;
  1527. }else if( $recNum == 2 ) {
  1528. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_TWO'] ?? 0;
  1529. }else {
  1530. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_THREE'] ?? 0;
  1531. }
  1532. if ( $validDeep < 2 * $maxOddLayer && $validDeep % 2 === 1 ) {//奇数层
  1533. $bonusUserData[] = [
  1534. 'bonusUid' => $parent['PARENT_UID'],
  1535. 'validDeep' => $validDeep
  1536. ];
  1537. }
  1538. $parentBonus = CalcCache::bonus($bonusUserId, $this->_periodNum);
  1539. if( $parentBonus['ORI_BONUS_QY_BD'] > 0 ) {//有效层
  1540. $validDeep += 1;
  1541. }
  1542. unset($parent, $parentBonus, $bonusUserId, $bonusUserBaseInfo, $nowDecLevelConfig, $recNum, $maxOddLayer);
  1543. //超过代数上限则结束
  1544. if ( $validDeep >= 18 ) {
  1545. return self::LOOP_FINISH;
  1546. }
  1547. });
  1548. //发奖
  1549. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1550. $userBonus = CalcCache::bonus($userId, $this->_periodNum);
  1551. foreach ($bonusUserData as $everyData) {
  1552. $bonusUserId = $everyData['bonusUid'];
  1553. //判断 是否本期小市场(安置关系)新增980pv 能否得奖
  1554. if ( !$this->checkSmallMarketPerf($bonusUserId) ) {
  1555. // unset($bonusUserId);
  1556. // continue;
  1557. //得奖人不满足980就找一个满足980的人来得这个奖
  1558. $bonusUserId = $this->getMinBdPvRelationParent($bonusUserId);
  1559. if ( !$bonusUserId ) {
  1560. unset($bonusUserId);
  1561. continue;
  1562. }
  1563. }
  1564. $parentOddPercentValue = floor($everyData['validDeep']/6);
  1565. $parentOddPercentName = sprintf('parentOddPercent_%s', $parentOddPercentValue);
  1566. if( !isset($this->_sysConfig[$parentOddPercentName]) ) continue;
  1567. $bonusPercent = $this->_sysConfig[$parentOddPercentName]['VALUE'];
  1568. $manageBonus = Tool::formatPrice($userBonus['ORI_BONUS_QY_BD'] * $bonusPercent / 100);
  1569. if ($manageBonus <= 0) continue;
  1570. //总金额限制
  1571. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  1572. $recNum = $bonusUserBaseInfo['REC_NUM'];
  1573. $manageBonus = $this->bonusTotalLimit($manageBonus, $bonusUserId, $recNum, $bonusUserBaseInfo['ZC_AMOUNT']);
  1574. if( $manageBonus <= 0 ) continue;
  1575. //扣除相应的复消积分和管理费
  1576. $deductData = $this->deduct($bonusUserId, $manageBonus);
  1577. CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_GL', $manageBonus, $deductData, CalcCache::FROM_MEANS_BD);
  1578. CalcCache::addHasMonthBonusUsers($bonusUserId, $this->_periodNum);
  1579. //管理奖流水
  1580. $insertBonusData[] = [
  1581. 'ID' => SnowFake::instance()->generateId(),
  1582. 'USER_ID' => $bonusUserId,
  1583. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  1584. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  1585. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  1586. 'FROM_USER_ID' => $userId,
  1587. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  1588. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  1589. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  1590. 'AMOUNT' => $deductData['surplus'],
  1591. 'ORI_BONUS' => $manageBonus,
  1592. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  1593. 'MANAGE_TAX' => $deductData['manageTax'],
  1594. 'PERIOD_NUM' => $this->_periodNum,
  1595. 'CALC_YEAR' => $this->_calcYear,
  1596. 'CALC_MONTH' => $this->_calcYearMonth,
  1597. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1598. 'CREATED_AT' => Date::nowTime(),
  1599. 'LOGS' => json_encode([
  1600. $parentOddPercentName => $this->_sysConfig[$parentOddPercentName]['VALUE'],
  1601. 'validDeep' => $everyData['validDeep'],
  1602. 'recNum' => $bonusUserBaseInfo['REC_NUM'],
  1603. 'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
  1604. 'fromUserId' => $userId,
  1605. 'decLevel' => $bonusUserBaseInfo['DEC_LV'],
  1606. 'bonusTotalLimit' => [
  1607. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  1608. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  1609. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  1610. ],
  1611. ]),
  1612. ];
  1613. unset($everyData, $bonusUserId, $parentOddPercentValue, $parentOddPercentName, $bonusPercent, $manageBonus, $deductData);
  1614. }
  1615. unset($userId, $validDeep, $userBaseInfo, $userBonus, $bonusUserData);
  1616. }
  1617. if($insertBonusData) CalcBonusGL::batchInsert($insertBonusData);
  1618. unset($allData, $insertBonusData);
  1619. return $this->calcBonusBdGL($offset + $this->_limit);
  1620. }
  1621. unset($allData);
  1622. return true;
  1623. }
  1624. /**
  1625. * 复消管理奖
  1626. * @param int $offset
  1627. * @return bool
  1628. * @throws \yii\db\Exception
  1629. */
  1630. public function calcBonusFxGL(int $offset = 0) {
  1631. $periodNum = $this->_periodNum;
  1632. // 从缓存获取分页有收入的会员信息
  1633. $allData = CalcCache::getHasIncomeUsers($this->_periodNum, $offset, $this->_limit);
  1634. if ($allData) {
  1635. $insertBonusData = [];
  1636. foreach ($allData as $userId) {
  1637. //会员信息
  1638. $decLevelConfig = $this->_decLevelConfig;
  1639. $netWorkParents = Cache::getAllRelationParents($userId);
  1640. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1641. $userEmpLevel = $userBaseInfo['EMP_LV'];
  1642. foreach ($netWorkParents as $netWorkParent) {
  1643. //自已距顶端的深度减去父级距顶端的深度
  1644. $diffLayer = $netWorkParent['TOP_DEEP'] - $netWorkParent['PARENT_DEEP'];
  1645. if( $diffLayer <= 0) continue;
  1646. //@todo 超过最大代数就跳出本次循环
  1647. //偶数代跳过
  1648. if( $diffLayer % 2 == 0 ) continue;
  1649. // 获取会员的报单级别
  1650. $bonusUserId = $netWorkParent['PARENT_UID'];
  1651. if( !$bonusUserId ) continue;
  1652. $bonusUserBaseInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  1653. $nowDecLevelConfig = $decLevelConfig[$bonusUserBaseInfo['DEC_LV']];
  1654. if( !$nowDecLevelConfig ) continue;
  1655. //推荐人数
  1656. $recNum = $bonusUserBaseInfo['REC_NUM'];
  1657. if( $recNum <= 0 ) continue;
  1658. if( $recNum == 1 ) {
  1659. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_ONE'];
  1660. }else if( $recNum == 2 ) {
  1661. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_TWO'];
  1662. }else {
  1663. $maxOddLayer = $nowDecLevelConfig['GL_ODD_DEEP_THREE'];
  1664. }
  1665. //超过代数上限也跳过
  1666. if( $diffLayer >= 2 * $maxOddLayer ) continue;
  1667. // $everyLayer = floor(2 * $nowDecLevelConfig['GL_ODD_DEEP_THREE'] / $nowDecLevelConfig['SORT']);
  1668. //多少代
  1669. // $theLayer = $diffLayer % $everyLayer;
  1670. // $theLayerLevel = floor($diffLayer/$everyLayer);
  1671. $theLayerLevel = floor($diffLayer/6);
  1672. $parentOddPercentName = sprintf('parentOddPercent_%s', $theLayerLevel);
  1673. if( !isset($this->_sysConfig[$parentOddPercentName]) ) continue;
  1674. $bonusPercent = $this->_sysConfig[$parentOddPercentName]['VALUE'];
  1675. // 从缓存中获取会员的收入信息
  1676. $incomeBonus = CalcCache::bonus($userId, $periodNum);
  1677. $parentOddIncomeFromName = sprintf('parentOddIncomeFrom_%s', $theLayerLevel);
  1678. $parentOddIncomeFrom = explode(',', $this->_sysConfig[$parentOddIncomeFromName]['VALUE']);
  1679. $parentOddIncome = 0;
  1680. foreach ($parentOddIncomeFrom as $incomeType) {
  1681. if( $incomeType === 'XF' ) {
  1682. $incomeTypeName = sprintf('ORI_BONUS_%s', $incomeType);
  1683. }else {
  1684. $incomeTypeName = sprintf('ORI_BONUS_%s_FX', $incomeType);
  1685. }
  1686. $incomeTypeValue = $incomeBonus[$incomeTypeName] ?? 0;
  1687. $parentOddIncome += $incomeTypeValue;
  1688. unset($incomeType, $incomeTypeName, $incomeTypeValue);
  1689. }
  1690. unset($parentOddIncomeFrom);
  1691. $manageBonus = Tool::formatPrice($parentOddIncome * $bonusPercent / 100);
  1692. if ($manageBonus <= 0) continue;
  1693. //总金额限制
  1694. $manageBonus = $this->bonusTotalLimit($manageBonus, $bonusUserId, $recNum, $bonusUserBaseInfo['ZC_AMOUNT']);
  1695. if( $manageBonus <= 0 ) continue;
  1696. //扣除相应的复消积分和管理费
  1697. $deductData = $this->deduct($bonusUserId, $manageBonus);
  1698. CalcCache::bonus($bonusUserId, $periodNum, 'BONUS_GL', $manageBonus, $deductData, CalcCache::FROM_MEANS_FX);
  1699. //管理奖流水
  1700. $insertBonusData[] = [
  1701. 'ID' => SnowFake::instance()->generateId(),
  1702. 'USER_ID' => $bonusUserId,
  1703. 'LAST_DEC_LV' => $bonusUserBaseInfo['DEC_LV'],
  1704. 'LAST_EMP_LV' => $bonusUserBaseInfo['EMP_LV'],
  1705. 'LAST_STATUS' => $bonusUserBaseInfo['STATUS'],
  1706. 'FROM_USER_ID' => $userId,
  1707. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  1708. 'LAST_FROM_EMP_LV' => $userEmpLevel,
  1709. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  1710. 'AMOUNT' => $deductData['surplus'],
  1711. 'ORI_BONUS' => $manageBonus,
  1712. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  1713. 'MANAGE_TAX' => $deductData['manageTax'],
  1714. 'PERIOD_NUM' => $this->_periodNum,
  1715. 'CALC_YEAR' => $this->_calcYear,
  1716. 'CALC_MONTH' => $this->_calcYearMonth,
  1717. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1718. 'CREATED_AT' => Date::nowTime(),
  1719. 'LOGS' => json_encode([
  1720. $parentOddPercentName => $this->_sysConfig[$parentOddPercentName]['VALUE'],
  1721. $parentOddIncomeFromName => $this->_sysConfig[$parentOddIncomeFromName]['VALUE'],
  1722. 'decLevelConfig' => $nowDecLevelConfig,
  1723. 'recNum' => $bonusUserBaseInfo['REC_NUM'],
  1724. 'decAmount' => $bonusUserBaseInfo['ZC_AMOUNT'],
  1725. 'fromUserId' => $userId,
  1726. 'decLevel' => $bonusUserBaseInfo['DEC_LV'],
  1727. 'bonusTotalLimit' => [
  1728. $this->_sysConfig['bonusTotalZeroLimit']['VALUE'],
  1729. $this->_sysConfig['bonusTotalOneLimit']['VALUE'],
  1730. $this->_sysConfig['bonusTotalTwoLimit']['VALUE'],
  1731. ],
  1732. ]),
  1733. ];
  1734. unset($netWorkParent, $diffLayer, $bonusUserId, $bonusUserBaseInfo, $bonusPercent, $nowDecLevelConfig, $manageBonus, $incomeBonus, $maxOddLayer, $theLayerLevel, $recNum, $parentOddPercentName, $parentOddIncomeFromName, $deductData);
  1735. }
  1736. unset($userId, $userBaseInfo, $userEmpLevel, $netWorkParents, $decLevelConfig);
  1737. }
  1738. CalcBonusGL::batchInsert($insertBonusData);
  1739. unset($allData, $insertBonusData);
  1740. return $this->calcBonusFxGL($offset + $this->_limit);
  1741. }
  1742. unset($allData);
  1743. return true;
  1744. }
  1745. /**
  1746. * 结算荣衔奖第一步
  1747. * @param int $offset
  1748. * @return bool
  1749. * @throws \yii\db\Exception
  1750. * @throws \Exception
  1751. */
  1752. public function calcBonusYCStepOne(int $offset = 0) {
  1753. // 月结,如果不是月结点,则直接退出
  1754. if (!$this->_isCalcMonth) {
  1755. return true;
  1756. }
  1757. echo sprintf("时间:[%s]荣衔奖第【1】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1758. //从缓存获取分页有本月业绩的会员
  1759. $allData = CalcCache::getHasMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  1760. if ($allData) {
  1761. $maxLevelId = EmployLevel::SHX_ZJ_LEVEL_ID;
  1762. $maxLevel = $this->_empLevelConfig[$maxLevelId];
  1763. $maxLevelPercent = $maxLevel['RX_PERCENT'] ?? 0;
  1764. unset($maxLevelId, $maxLevel);
  1765. foreach ($allData as $userId) {
  1766. // echo sprintf("时间:[%s]荣衔奖,当前用户ID为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $userId);
  1767. $nowMonthPerf = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  1768. $monthPvPcs = $nowMonthPerf['PV_PCS'] ?? 0;
  1769. if( $monthPvPcs <= 0 ) continue;
  1770. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1771. //个人业绩的奖金
  1772. $empLevelId = $userBaseInfo['EMP_LV'];
  1773. $empLevel = $this->_empLevelConfig[$empLevelId];
  1774. $rxPercent = $empLevel['RX_PERCENT'] ?? 0;
  1775. $empBonus = $monthPvPcs * $rxPercent / 100;
  1776. if( $empBonus > 0 ) {
  1777. //给本人添加聘级比例
  1778. CalcCache::ycMaxBonusPercent($userId, $this->_periodNum, $rxPercent);
  1779. //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  1780. CalcCache::saveYCBonusList($userId, $this->_periodNum, $empBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$monthPvPcs]);
  1781. CalcCache::addHasYcBonusUsers($userId, $this->_periodNum);
  1782. //达到最大的比例其它人就得不到了
  1783. if( $rxPercent >= $maxLevelPercent ) continue;
  1784. }
  1785. unset($empLevelId, $empLevel, $rxPercent, $empBonus);
  1786. //获取所有的父级
  1787. $this->loopRelationParentDo($userId, function ($parent) use ($userId, $monthPvPcs, $maxLevelPercent) {
  1788. $bonusUserId = $parent['PARENT_UID'];
  1789. //计算级别之后更新过userInfo的缓存,缓存中级别发生了变化
  1790. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  1791. $parentEmpLevelId = $bonusUserInfo['EMP_LV'];
  1792. $parentEmpLevel = $this->_empLevelConfig[$parentEmpLevelId];
  1793. $parentRxPercent = $parentEmpLevel['RX_PERCENT'] ?? 0;
  1794. $cacheMaxPercent = CalcCache::ycMaxBonusPercent($userId, $this->_periodNum);
  1795. $diffPercent = $parentRxPercent - $cacheMaxPercent;
  1796. if( $diffPercent <= 0 ) return self::LOOP_CONTINUE;
  1797. $empBonus = $monthPvPcs * $diffPercent / 100;
  1798. if( $empBonus <= 0 ) return self::LOOP_CONTINUE;
  1799. //给本人添加聘级比例
  1800. CalcCache::ycMaxBonusPercent($userId, $this->_periodNum, $parentRxPercent);
  1801. //记录奖金和奖金来源到缓存 并实现在缓存中奖金累加
  1802. CalcCache::saveYCBonusList($bonusUserId, $this->_periodNum, $empBonus, ['fromUid'=>$userId, 'fromPvPcs'=>$monthPvPcs]);
  1803. CalcCache::addHasYcBonusUsers($bonusUserId, $this->_periodNum);
  1804. unset($cacheMaxPercent, $diffPercent, $parentEmpLevel, $bonusUserId, $bonusUserInfo, $parentEmpLevelId, $empBonus);
  1805. //达到最大的比例就不在向上找了
  1806. if( $parentRxPercent >= $maxLevelPercent ) return self::LOOP_FINISH;
  1807. unset($parentRxPercent);
  1808. });
  1809. unset($nowMonthPerf, $monthPvPcs);
  1810. }
  1811. unset($allData, $maxLevelPercent);
  1812. $this->calcBonusYCStepOne($offset + $this->_limit);
  1813. }
  1814. unset($periodNum, $allData);
  1815. return true;
  1816. }
  1817. /**
  1818. * 结算荣衔奖第二步
  1819. * @param int $offset
  1820. * @return bool
  1821. * @throws \yii\db\Exception
  1822. */
  1823. public function calcBonusYCStepTwo(int $offset = 0) {
  1824. // 月结,如果不是月结点,则直接退出
  1825. if (!$this->_isCalcMonth) {
  1826. return true;
  1827. }
  1828. echo sprintf("时间:[%s]荣衔奖第【2】步,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  1829. $allData = CalcCache::getHasYcBonusUsers($this->_periodNum, $offset, $this->_limit);
  1830. if ($allData) {
  1831. $insertBonusData = [];
  1832. foreach ($allData as $userId) {
  1833. $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  1834. $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  1835. unset($monthPerfData);
  1836. if( !$fxPvStatus ) continue;
  1837. unset($fxPvStatus);
  1838. $ycBonusData = CalcCache::getYCBonusList($userId, $this->_periodNum);
  1839. if( !$ycBonusData ) continue;
  1840. $empBonus = $ycBonusData['empBonus'] ?? 0;
  1841. if( $empBonus <=0 ) continue;
  1842. //总金额限制
  1843. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1844. $empBonus = $this->bonusTotalLimit($empBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  1845. if( $empBonus <= 0 ) continue;
  1846. //扣除相应的复消积分和管理费
  1847. $empBonus = Tool::formatPrice($empBonus);
  1848. $deductData = $this->deduct($userId, $empBonus);
  1849. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_YC', $empBonus, $deductData);
  1850. $empLevelId = $userBaseInfo['EMP_LV'];
  1851. $insertBonusData[] = [
  1852. 'ID' => SnowFake::instance()->generateId(),
  1853. 'USER_ID' => $userId,
  1854. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  1855. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  1856. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  1857. 'FROM_USER_ID' => $userId,
  1858. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  1859. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  1860. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  1861. 'DEEP' => 0,
  1862. 'AMOUNT' => $deductData['surplus'],
  1863. 'ORI_BONUS' => $empBonus,
  1864. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  1865. 'MANAGE_TAX' => $deductData['manageTax'],
  1866. 'BONUS_TYPE' => CalcBonusYC::BONUS_TYPE_YC,
  1867. 'PERIOD_NUM' => $this->_periodNum,
  1868. 'CALC_MONTH' => $this->_calcYearMonth,
  1869. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1870. 'CREATED_AT' => Date::nowTime(),
  1871. 'LOGS' => json_encode([
  1872. 'empLevelId' => $empLevelId,
  1873. ])
  1874. // 'FROM_DATA' => json_encode($ycBonusData['fromData']),
  1875. ];
  1876. unset($ycBonusData, $deductData);
  1877. //如果是总监以上拿平级2代
  1878. $empLevel = $this->_empLevelConfig[$empLevelId];
  1879. $userEmpLevelSort = $empLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  1880. // if( $userEmpLevelSort >= EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {}
  1881. $newInsertBonusData = $this->calcParentYC($userId, $userBaseInfo, $userEmpLevelSort, $empBonus);
  1882. $insertBonusData = array_merge($insertBonusData, $newInsertBonusData);
  1883. unset($newInsertBonusData);
  1884. unset($userId, $userBaseInfo, $empLevel, $empLevelId, $userEmpLevelSort, $empBonus);
  1885. }
  1886. CalcBonusYC::batchInsert($insertBonusData);
  1887. unset($insertBonusData, $allData);
  1888. $this->calcBonusYCStepTwo($offset + $this->_limit);
  1889. }
  1890. unset($allData);
  1891. return true;
  1892. }
  1893. /**
  1894. * VIP奖
  1895. * @param int $offset
  1896. * @return bool
  1897. * @throws \yii\db\Exception
  1898. */
  1899. public function calcBonusVIP(int $offset = 0)
  1900. {
  1901. // 月结,如果不是月结点,则直接退出
  1902. if (!$this->_isCalcMonth) {
  1903. return true;
  1904. }
  1905. echo sprintf("时间:[%s]VIP奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $offset);
  1906. //从缓存获取分页有本月业绩的会员
  1907. $allData = CalcCache::getHasMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  1908. if ($allData) {
  1909. $insertBonusData = [];
  1910. foreach ($allData as $userId) {
  1911. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  1912. //条件一:级别必须为VIP
  1913. $isVip = false;
  1914. if( $userBaseInfo['DEC_LV'] === DeclarationLevel::VIP_LEVEL_ID ) {
  1915. $isVip= true;
  1916. }
  1917. if( $this->_sysConfig['vipBonusGoldDecLevel']['VALUE'] && $userBaseInfo['DEC_LV'] === DeclarationLevel::JIN_ZUAN_LEVEL_ID ) {
  1918. $isVip = true;
  1919. }
  1920. if ( !$isVip ) {
  1921. unset($userId, $userBaseInfo);
  1922. continue;
  1923. }
  1924. //判断其它两个条件,满足则计算月团队奖,不满足则留下大区剩余业绩,清除其它区的剩余业绩
  1925. //获取本月的业绩
  1926. $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  1927. // 从缓存中获取会员的上期结余业绩信息
  1928. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  1929. // 本期 + 上期结余
  1930. $perfArr = [
  1931. 'VIP_SURPLUS_1L_ZC' => $monthPerfData['VIP_PV_1L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_1L_ZC'],
  1932. 'VIP_SURPLUS_2L_ZC' => $monthPerfData['VIP_PV_2L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_2L_ZC'],
  1933. 'VIP_SURPLUS_3L_ZC' => $monthPerfData['VIP_PV_3L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_3L_ZC'],
  1934. 'VIP_SURPLUS_4L_ZC' => $monthPerfData['VIP_PV_4L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_4L_ZC'],
  1935. 'VIP_SURPLUS_5L_ZC' => $monthPerfData['VIP_PV_5L_ZC'] + $pervSurplusPerf['VIP_SURPLUS_5L_ZC'],
  1936. ];
  1937. //条件二:本月复消金额达到300元
  1938. //fix-2021-03-26修改 条件二:本月个人复消PV300
  1939. $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  1940. unset($monthPerfData, $pervSurplusPerf);
  1941. if( !$fxPvStatus ) {
  1942. $this->dealWithMaxPerf($userId, $perfArr);
  1943. unset($userBaseInfo, $userId, $perfArr, $fxPvStatus);
  1944. continue;
  1945. }
  1946. //条件三:其它市场业绩
  1947. $isCanOtherDepartPerf = $this->_isCanVipBonusOtherAreaPerf($perfArr);
  1948. if ( !$isCanOtherDepartPerf ) {
  1949. $this->dealWithMaxPerf($userId, $perfArr);
  1950. unset($userBaseInfo, $userId, $perfArr, $isCanOtherDepartPerf);
  1951. continue;
  1952. }
  1953. $oriPerfArr = [
  1954. 'perfArr' => $perfArr,
  1955. 'touchBonus' => 0,
  1956. ];
  1957. // 对碰
  1958. $touchBonusArr = $this->touchPerf($oriPerfArr, $perfArr, $this->_sysConfig['vipBonusPercent']['VALUE']/100);
  1959. unset($oriPerfArr, $perfArr);
  1960. $touchPerfArr = [];
  1961. foreach ($touchBonusArr['perfArr'] as $keyR => $perfR) {
  1962. $touchPerfArr[$keyR] = $perfR;
  1963. }
  1964. // 对碰完成后把结余的业绩存入本期业绩缓存中
  1965. // CalcCache::nowPeriodPerf($userId, $this->_periodNum, $touchPerfArr);
  1966. //更新数据库
  1967. PerfMonth::updateAll($touchPerfArr, 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [
  1968. 'USER_ID' => $userId,
  1969. 'CALC_MONTH' => $this->_calcYearMonth,
  1970. ]);
  1971. if ($touchBonusArr['touchBonus'] <= 0) continue;
  1972. $vipBonus = $touchBonusArr['touchBonus'];
  1973. //判断级别上限
  1974. $vipBonus = $this->declarationLevelCap($vipBonus, $userId, $userBaseInfo['DEC_LV']);
  1975. if( $vipBonus <= 0 ) continue;
  1976. $vipBonus = $this->bonusTotalLimit($vipBonus, $userId, $userBaseInfo['REC_NUM'], $userBaseInfo['ZC_AMOUNT']);
  1977. if( $vipBonus <= 0 ) continue;
  1978. //扣除相应的复消积分和管理费
  1979. $deductData = $this->deduct($userId, $vipBonus);
  1980. CalcCache::bonus($userId, $this->_periodNum, 'BONUS_VIP', $vipBonus, $deductData);
  1981. $insertBonusData[] = [
  1982. 'ID' => SnowFake::instance()->generateId(),
  1983. 'USER_ID' => $userId,
  1984. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  1985. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  1986. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  1987. 'FROM_USER_ID' => $userId,
  1988. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  1989. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  1990. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  1991. 'AMOUNT' => $deductData['surplus'],
  1992. 'ORI_BONUS' => $vipBonus,
  1993. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  1994. 'MANAGE_TAX' => $deductData['manageTax'],
  1995. 'PERIOD_NUM' => $this->_periodNum,
  1996. 'CALC_YEAR' => $this->_calcYear,
  1997. 'CALC_MONTH' => $this->_calcYearMonth,
  1998. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  1999. 'CREATED_AT' => Date::nowTime(),
  2000. 'LOGS' => json_encode($touchPerfArr)
  2001. ];
  2002. unset($userBaseInfo, $userId, $perfArr, $fxAmountStatus, $isCanOtherDepartPerf, $touchBonusArr, $touchPerfArr, $vipBonus, $deductData);
  2003. }
  2004. if( $insertBonusData ) CalcBonusVIP::batchInsert($insertBonusData);
  2005. unset($insertBonusData, $allData);
  2006. $this->calcBonusVIP($offset + $this->_limit);
  2007. }
  2008. unset($allData);
  2009. return true;
  2010. }
  2011. /**
  2012. * 见习达标奖
  2013. * @param int $offset
  2014. * @return bool
  2015. * @throws \yii\db\Exception
  2016. */
  2017. public function calcBonusStandard(int $offset = 0)
  2018. {
  2019. // 月结,如果不是月结点,则直接退出
  2020. if (!$this->_isCalcMonth) {
  2021. return true;
  2022. }
  2023. echo sprintf("时间:[%s]见习达标奖,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $offset);
  2024. //从缓存获取分页有本月业绩的会员
  2025. $allData = CalcCache::getHasStandardMonthPerfUsers($this->_periodNum, $offset, $this->_limit);
  2026. if ($allData) {
  2027. $minSaleCondition = $this->_jxStandardMinSaleCondition();
  2028. $insertBonusData = [];
  2029. foreach ($allData as $userId) {
  2030. $userBaseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2031. //条件一:聘级必须为见习主任
  2032. if( $userBaseInfo['EMP_LV'] != EmployLevel::JX_ZR_LEVEL_ID ) {
  2033. unset($userId, $userBaseInfo);
  2034. continue;
  2035. }
  2036. $standardMonthPerf = CalcCache::nowStandardMonthPerf($userId, $this->_periodNum);
  2037. $totalAmount = $standardMonthPerf['AMOUNT_PCS'] + $standardMonthPerf['AMOUNT_PSS'];
  2038. if( $totalAmount < $minSaleCondition ) {
  2039. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount);
  2040. continue;
  2041. }
  2042. $standardBonus = $this->_jxStandardAwardAmount($totalAmount);
  2043. if( $standardBonus <= 0 ) {
  2044. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount, $standardBonus);
  2045. continue;
  2046. }
  2047. CalcCache::standardBonus($userId, $this->_periodNum, $standardBonus);
  2048. $insertBonusData[] = [
  2049. 'ID' => SnowFake::instance()->generateId(),
  2050. 'USER_ID' => $userId,
  2051. 'LAST_DEC_LV' => $userBaseInfo['DEC_LV'],
  2052. 'LAST_EMP_LV' => $userBaseInfo['EMP_LV'],
  2053. 'LAST_STATUS' => $userBaseInfo['STATUS'],
  2054. 'FROM_USER_ID' => $userId,
  2055. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2056. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2057. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2058. 'AMOUNT' => $standardBonus,
  2059. 'ORI_BONUS' => $standardBonus,
  2060. 'RECONSUME_POINTS' => 0,
  2061. 'MANAGE_TAX' => 0,
  2062. 'PERIOD_NUM' => $this->_periodNum,
  2063. 'CALC_YEAR' => $this->_calcYear,
  2064. 'CALC_MONTH' => $this->_calcYearMonth,
  2065. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2066. 'CREATED_AT' => Date::nowTime(),
  2067. 'LOGS' => json_encode($standardMonthPerf)
  2068. ];
  2069. unset($userId, $userBaseInfo, $standardMonthPerf, $totalAmount);
  2070. }
  2071. if( $insertBonusData ) CalcBonusStandard::batchInsert($insertBonusData);
  2072. unset($insertBonusData, $minSaleCondition, $insertBonusData, $allData);
  2073. $this->calcBonusStandard($offset + $this->_limit);
  2074. }
  2075. unset($allData);
  2076. return true;
  2077. }
  2078. /**
  2079. * === 运算相关的辅助功能开始 ===
  2080. */
  2081. /**
  2082. * 获取上2代的得奖人信息
  2083. * @param $userId
  2084. * @param $validDeep
  2085. * @param $shareBonusOne
  2086. * @return array
  2087. */
  2088. protected function gxLastTwoBonusData($userId, $validDeep, $shareBonusOne) {
  2089. $bonusUserList = CalcCache::getShareBonusOneRelation($userId, $this->_periodNum, $validDeep);
  2090. if( !$bonusUserList ) {
  2091. unset($bonusUserList);
  2092. return [];
  2093. }
  2094. $bonusUserData = [];
  2095. $bonusUserTotalPerf = 0;
  2096. $bonusUserRealList = [];
  2097. foreach ($bonusUserList as $bonusUserId) {
  2098. //查看该用户的个人业绩和团队新增业绩总和
  2099. $nowPeriodData = CalcCache::nowPeriodPerf($bonusUserId, $this->_periodNum);
  2100. //本期新增业绩
  2101. $bonusUserPerf = $nowPeriodData['PV_PCS'] + $nowPeriodData['PV_PSS'];
  2102. if ($bonusUserPerf <= 0) {
  2103. unset($bonusUserId, $nowPeriodData, $bonusUserPerf);
  2104. continue;
  2105. }
  2106. $bonusUserTotalPerf += $bonusUserPerf;
  2107. $bonusUserRealList[] = [
  2108. 'bonusUserId' => $bonusUserId,
  2109. 'bonusUserPerf' => $bonusUserPerf,
  2110. ];
  2111. unset($bonusUserId, $nowPeriodData, $bonusUserPerf);
  2112. }
  2113. unset($bonusUserList);
  2114. foreach ($bonusUserRealList as $everyData) {
  2115. $bonusUserData[] = [
  2116. 'bonusUid' => $everyData['bonusUserId'],
  2117. 'bonus' => $shareBonusOne * $everyData['bonusUserPerf'] / $bonusUserTotalPerf,
  2118. 'validMinPv' => false
  2119. ];
  2120. unset($everyData);
  2121. }
  2122. unset($bonusUserRealList);
  2123. return $bonusUserData;
  2124. }
  2125. /**
  2126. * 获取达标奖的金额
  2127. * @param $amount
  2128. * @return int|mixed
  2129. */
  2130. private function _jxStandardAwardAmount($amount) {
  2131. // $jxStandardConfig = Json::decode($this->_sysConfig['jxStandard']['VALUE']);
  2132. // $awardAmount = 0;
  2133. // foreach ($jxStandardConfig as $everyData) {
  2134. // if( $amount >= $everyData['salesCondition'] ) {
  2135. // $awardAmount = $everyData['awardAmount'];
  2136. // }
  2137. // unset($everyData);
  2138. // }
  2139. //
  2140. // return $awardAmount;
  2141. $realTimes = floor($amount/self::JX_STANDARD_BASE_AMOUNT);
  2142. $calcTimes = min($realTimes, self::JX_STANDARD_MAX_TIMES);
  2143. $awardAmount = $calcTimes * self::JX_STANDARD_BASE_AMOUNT * self::JX_STANDARD_BONUS_PERCENT / 100;
  2144. unset($amount, $realTimes, $calcTimes);
  2145. return $awardAmount;
  2146. }
  2147. /**
  2148. * 获取达标奖的最小条件
  2149. * @return int|mixed
  2150. */
  2151. private function _jxStandardMinSaleCondition() {
  2152. return self::JX_STANDARD_BASE_AMOUNT;
  2153. }
  2154. /**
  2155. * 处理只留最大业绩的逻辑
  2156. * @param $userId
  2157. * @param $perfArr
  2158. */
  2159. private function dealWithMaxPerf($userId, $perfArr) {
  2160. $maxPerf = max($perfArr);
  2161. $hitMaxPerf = false;
  2162. foreach ($perfArr as $key=>$everyPerf) {
  2163. if( !$hitMaxPerf && $everyPerf == $maxPerf ) {
  2164. $hitMaxPerf = true;
  2165. }else {
  2166. $perfArr[$key] = 0;
  2167. }
  2168. unset($key, $everyPerf);
  2169. }
  2170. //更新数据库
  2171. PerfMonth::updateAll($perfArr, 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [
  2172. 'USER_ID' => $userId,
  2173. 'CALC_MONTH' => $this->_calcYearMonth
  2174. ]);
  2175. unset($userId, $maxPerf, $hitMaxPerf, $perfArr);
  2176. }
  2177. /**
  2178. * VIP奖其它市场的报单业绩是否能满足
  2179. * @param $perfArr
  2180. * @return bool
  2181. */
  2182. private function _isCanVipBonusOtherAreaPerf($perfArr) {
  2183. $maxAreaPerf = max($perfArr);
  2184. $totalAreaPerf = array_sum($perfArr);
  2185. $diffAreaPerf = strval($totalAreaPerf - $maxAreaPerf);
  2186. if( $diffAreaPerf >= $this->_sysConfig['vipBonusOtherDepartPvCondition']['VALUE'] ) {
  2187. unset($maxAreaPerf, $totalAreaPerf, $perfArr);
  2188. return true;
  2189. }else {
  2190. unset($maxAreaPerf, $totalAreaPerf, $perfArr);
  2191. return false;
  2192. }
  2193. }
  2194. /**
  2195. * 给父级计算的荣衔奖
  2196. * @param $userId
  2197. * @param $userBaseInfo
  2198. * @param $userEmpLevelSort
  2199. * @param $qyBonus
  2200. * @return array
  2201. */
  2202. public function calcParentYC($userId, $userBaseInfo, $userEmpLevelSort, $qyBonus) {
  2203. if( $userEmpLevelSort <= EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'] ) return [];
  2204. $validDeep = 0;
  2205. $bonusDataList = [];
  2206. $this->loopRelationParentDo($userId, function ($parent) use ($userId, $userEmpLevelSort, &$validDeep, &$bonusDataList) {
  2207. $bonusUserId = $parent['PARENT_UID'];
  2208. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2209. $bonusUserEmpLevel = $this->_empLevelConfig[$bonusUserInfo['EMP_LV']];
  2210. $bonusUserEmpLevelSort = $bonusUserEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  2211. unset($bonusUserInfo, $bonusUserEmpLevel);
  2212. //必须是有聘级的用户
  2213. if( $bonusUserEmpLevelSort <= EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'] ) return self::LOOP_CONTINUE;
  2214. //超过级别就停止
  2215. if( $bonusUserEmpLevelSort > $userEmpLevelSort) return self::LOOP_FINISH;
  2216. //级别小于就跳过
  2217. if( $bonusUserEmpLevelSort < $userEmpLevelSort ) return self::LOOP_CONTINUE;
  2218. $validDeep++;
  2219. array_push($bonusDataList, [
  2220. 'bonusUserId' => $bonusUserId,
  2221. 'bonusType' => $validDeep,
  2222. ]);
  2223. if( $validDeep >= 2 ) return self::LOOP_FINISH;
  2224. unset($bonusUserId, $bonusUserEmpLevelSort);
  2225. });
  2226. $insertBonusData = [];
  2227. foreach ($bonusDataList as $bonusUserData) {
  2228. $bonusUserId = $bonusUserData['bonusUserId'];
  2229. $bonusMonthPerfData = CalcCache::nowMonthPerf($bonusUserId, $this->_periodNum);
  2230. $fxPvStatus = $bonusMonthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2231. unset($bonusMonthPerfData);
  2232. if( !$fxPvStatus ) continue;
  2233. unset($fxPvStatus);
  2234. $bonusUserInfo = CalcCache::getUserInfo($bonusUserId, $this->_periodNum);
  2235. $bonusEmpLevelId = $bonusUserInfo['EMP_LV'];
  2236. $newEmpBonus = Tool::formatPrice($qyBonus * $this->_sysConfig['sameEmpLevelPercent']['VALUE'] / 100);
  2237. //总金额限制
  2238. $newEmpBonus = $this->bonusTotalLimit($newEmpBonus, $bonusUserId, $bonusUserInfo['REC_NUM'], $bonusUserInfo['ZC_AMOUNT']);
  2239. if( $newEmpBonus <= 0 ) continue;
  2240. //扣除相应的复消积分和管理费
  2241. $newEmpBonus = Tool::formatPrice($newEmpBonus);
  2242. $deductData = $this->deduct($bonusUserId, $newEmpBonus);
  2243. CalcCache::bonus($bonusUserId, $this->_periodNum, 'BONUS_YC_EXTRA', $newEmpBonus, $deductData);
  2244. // 把育成津贴追加到育成津贴结算表,以便奖金追溯育成津贴用
  2245. $insertBonusData[] = [
  2246. 'ID' => SnowFake::instance()->generateId(),
  2247. 'USER_ID' => $bonusUserId,
  2248. 'LAST_DEC_LV' => $bonusUserInfo['DEC_LV'],
  2249. 'LAST_EMP_LV' => $bonusUserInfo['EMP_LV'],
  2250. 'LAST_STATUS' => $bonusUserInfo['STATUS'],
  2251. 'FROM_USER_ID' => $userId,
  2252. 'LAST_FROM_DEC_LV' => $userBaseInfo['DEC_LV'],
  2253. 'LAST_FROM_EMP_LV' => $userBaseInfo['EMP_LV'],
  2254. 'LAST_FROM_STATUS' => $userBaseInfo['STATUS'],
  2255. 'DEEP' => 1,
  2256. 'AMOUNT' => $deductData['surplus'],
  2257. 'ORI_BONUS' => $newEmpBonus,
  2258. 'RECONSUME_POINTS' => $deductData['reConsumePoints'],
  2259. 'MANAGE_TAX' => $deductData['manageTax'],
  2260. 'BONUS_TYPE' => $bonusUserData['bonusType'],
  2261. 'PERIOD_NUM' => $this->_periodNum,
  2262. 'CALC_MONTH' => $this->_calcYearMonth,
  2263. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  2264. 'CREATED_AT' => Date::nowTime(),
  2265. 'LOGS' => json_encode([
  2266. 'empLevelId' => $bonusEmpLevelId,
  2267. 'qyBonus' => $qyBonus,
  2268. 'sameEmpLevelPercent' => $this->_sysConfig['sameEmpLevelPercent']['VALUE'],
  2269. ]),
  2270. ];
  2271. unset($newEmpBonus, $bonusEmpLevelId, $bonusUserId, $bonusUserInfo, $deductData);
  2272. }
  2273. unset($userId, $userBaseInfo, $userEmpLevelSort, $qyBonus, $bonusDataList);
  2274. return $insertBonusData;
  2275. }
  2276. /**
  2277. * 对碰
  2278. * @param array $oriPerfArr
  2279. * @param array $perfArr
  2280. * @param $percent
  2281. * @param $loopTimes
  2282. * @return array
  2283. */
  2284. public function touchPerf(array $oriPerfArr, array $perfArr, $percent, $loopTimes=1) {
  2285. $resultArr = $oriPerfArr;
  2286. foreach ($perfArr as $keyT => $perfT) {
  2287. if ($perfT <= 0) {
  2288. unset($perfArr[$keyT]);
  2289. }
  2290. }
  2291. if (count($perfArr) >= 2 && $loopTimes < 6) {
  2292. arsort($perfArr, SORT_NUMERIC);
  2293. $onePerf = null;
  2294. $oneKey = null;
  2295. // $touchSurplusAmount = 0;
  2296. $touchAmount = 0;
  2297. // 前两个进行对碰
  2298. foreach ($perfArr as $key => $perf) {
  2299. if ($onePerf === null) {
  2300. $oneKey = $key;
  2301. $onePerf = $perf;
  2302. } else {
  2303. $touchSurplusAmount = $perf - $onePerf;
  2304. if ($touchSurplusAmount > 0) {
  2305. unset($perfArr[$oneKey]);
  2306. $resultArr['perfArr'][$oneKey] = 0;
  2307. $perfArr[$key] = $touchSurplusAmount;
  2308. $touchAmount = $onePerf;
  2309. } elseif ($touchSurplusAmount < 0) {
  2310. unset($perfArr[$key]);
  2311. $resultArr['perfArr'][$key] = 0;
  2312. $perfArr[$oneKey] = abs($touchSurplusAmount);
  2313. $touchAmount = $perf;
  2314. } else {
  2315. unset($perfArr[$oneKey], $perfArr[$key]);
  2316. $resultArr['perfArr'][$oneKey] = 0;
  2317. $resultArr['perfArr'][$key] = 0;
  2318. $touchAmount = $perf;
  2319. }
  2320. break;
  2321. }
  2322. }
  2323. /*if ($touchAmount > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2324. $touchAmount = $nowDecLevelConfig['QY_TOUCH_CAP'];
  2325. }*/
  2326. $touchBonus = Tool::formatPrice($touchAmount * $percent);
  2327. // if ($touchBonus > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2328. // $resultArr['touchBonus'] += $nowDecLevelConfig['QY_TOUCH_CAP'];
  2329. // } else {
  2330. // $resultArr['touchBonus'] += $touchBonus;
  2331. // }
  2332. $resultArr['touchBonus'] += $touchBonus;
  2333. foreach ($perfArr as $keyR => $perfR) {
  2334. $resultArr['perfArr'][$keyR] = $perfR;
  2335. }
  2336. return $this->touchPerf($resultArr, $perfArr, $percent, $loopTimes+1);
  2337. }
  2338. return $resultArr;
  2339. }
  2340. /**
  2341. * 对碰
  2342. * @param array $oriPerfArr
  2343. * @param array $perfArr
  2344. * @param $decLevel
  2345. * @param $decLevelConfig
  2346. * @param $loopTimes
  2347. * @return array
  2348. */
  2349. public function touchPerfBefore(array $oriPerfArr, array $perfArr, $decLevel, $decLevelConfig, $loopTimes=1) {
  2350. $resultArr = $oriPerfArr;
  2351. foreach ($perfArr as $keyT => $perfT) {
  2352. if ($perfT <= 0) {
  2353. unset($perfArr[$keyT]);
  2354. }
  2355. }
  2356. if (count($perfArr) >= 2 && $loopTimes < 6) {
  2357. $nowDecLevelConfig = $decLevelConfig[$decLevel];
  2358. arsort($perfArr, SORT_NUMERIC);
  2359. $onePerf = null;
  2360. $oneKey = null;
  2361. // $touchSurplusAmount = 0;
  2362. $touchAmount = 0;
  2363. // 前两个进行对碰
  2364. foreach ($perfArr as $key => $perf) {
  2365. if ($onePerf === null) {
  2366. $oneKey = $key;
  2367. $onePerf = $perf;
  2368. } else {
  2369. $touchSurplusAmount = $perf - $onePerf;
  2370. if ($touchSurplusAmount > 0) {
  2371. unset($perfArr[$oneKey]);
  2372. $resultArr['perfArr'][$oneKey] = 0;
  2373. $perfArr[$key] = $touchSurplusAmount;
  2374. $touchAmount = $onePerf;
  2375. } elseif ($touchSurplusAmount < 0) {
  2376. unset($perfArr[$key]);
  2377. $resultArr['perfArr'][$key] = 0;
  2378. $perfArr[$oneKey] = abs($touchSurplusAmount);
  2379. $touchAmount = $perf;
  2380. } else {
  2381. unset($perfArr[$oneKey], $perfArr[$key]);
  2382. $resultArr['perfArr'][$oneKey] = 0;
  2383. $resultArr['perfArr'][$key] = 0;
  2384. $touchAmount = $perf;
  2385. }
  2386. break;
  2387. }
  2388. }
  2389. /*if ($touchAmount > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2390. $touchAmount = $nowDecLevelConfig['QY_TOUCH_CAP'];
  2391. }*/
  2392. $touchBonus = Tool::formatPrice($touchAmount * 2 / 100);
  2393. // if ($touchBonus > $nowDecLevelConfig['QY_TOUCH_CAP']) {
  2394. // $resultArr['touchBonus'] += $nowDecLevelConfig['QY_TOUCH_CAP'];
  2395. // } else {
  2396. // $resultArr['touchBonus'] += $touchBonus;
  2397. // }
  2398. $resultArr['touchBonus'] += $touchBonus;
  2399. foreach ($perfArr as $keyR => $perfR) {
  2400. $resultArr['perfArr'][$keyR] = $perfR;
  2401. }
  2402. return $this->touchPerfBefore($resultArr, $perfArr, $decLevel, $decLevelConfig, $loopTimes+1);
  2403. }
  2404. return $resultArr;
  2405. }
  2406. /**
  2407. * 循环父级并执行回调函数
  2408. * @param $userId
  2409. * @param callable $callbackFunc
  2410. * @param int $offset
  2411. * @return bool
  2412. */
  2413. public function loopNetworkParentDo($userId, callable $callbackFunc, int $offset = 0) {
  2414. $allParents = Cache::getAllNetworkParents($userId);
  2415. $allData = array_slice($allParents, $offset, $this->_limit);
  2416. unset($allParents);
  2417. if ($allData) {
  2418. foreach ($allData as $data) {
  2419. $funcResult = $callbackFunc($data);
  2420. if ($funcResult === self::LOOP_FINISH) {
  2421. return true;
  2422. } elseif ($funcResult === self::LOOP_CONTINUE) {
  2423. continue;
  2424. }
  2425. unset($data, $funcResult);
  2426. }
  2427. unset($allData);
  2428. return $this->loopNetworkParentDo($userId, $callbackFunc, $offset + $this->_limit);
  2429. }
  2430. return true;
  2431. }
  2432. /**
  2433. * 循环推荐网络的父级
  2434. * @param $userId
  2435. * @param callable $callbackFunc
  2436. * @param int $offset
  2437. * @return bool
  2438. */
  2439. public function loopRelationParentDo($userId, callable $callbackFunc, int $offset = 0) {
  2440. $allParents = Cache::getAllRelationParents($userId);
  2441. $allData = array_slice($allParents, $offset, $this->_limit);
  2442. unset($allParents);
  2443. if ($allData) {
  2444. foreach ($allData as $data) {
  2445. $funcResult = $callbackFunc($data);
  2446. if ($funcResult === self::LOOP_FINISH) {
  2447. return true;
  2448. } elseif ($funcResult === self::LOOP_CONTINUE) {
  2449. continue;
  2450. }
  2451. unset($data, $funcResult);
  2452. }
  2453. unset($allData);
  2454. return $this->loopRelationParentDo($userId, $callbackFunc, $offset + $this->_limit);
  2455. }
  2456. return true;
  2457. }
  2458. /**
  2459. * 共享奖,判断当期此用户,是否有原报单团队奖金
  2460. */
  2461. public function checkHasOriBonusQyBd($userId) {
  2462. //判断$parent是否有首单团队奖
  2463. $bonus = CalcCache::bonus($userId, $this->_periodNum);
  2464. if( isset($bonus['ORI_BONUS_QY_BD']) && $bonus['ORI_BONUS_QY_BD'] > 0 ) {
  2465. return true;
  2466. }
  2467. return false;
  2468. }
  2469. /**
  2470. * 判断除大市场外 其它市场的报单业绩
  2471. * @param $userId
  2472. * @return bool
  2473. * @throws \yii\db\Exception
  2474. */
  2475. public function checkSmallMarketPerf($userId) {
  2476. // 从缓存中获取会员的上期结余业绩信息
  2477. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  2478. //判断出大市场
  2479. $areaNums = [1, 2, 3];
  2480. $maxArea = 0;
  2481. $maxSurplusPerf = 0;
  2482. foreach ($areaNums as $area) {
  2483. $areaKey = sprintf('SURPLUS_%dL', $area);
  2484. if ( isset($pervSurplusPerf[$areaKey]) && $pervSurplusPerf[$areaKey] > $maxSurplusPerf ) {
  2485. $maxArea = $area;
  2486. $maxSurplusPerf = $pervSurplusPerf[$areaKey];
  2487. }
  2488. unset($area, $areaKey);
  2489. }
  2490. unset($pervSurplusPerf, $maxSurplusPerf);
  2491. $otherAreaZcPv = 0;
  2492. $nowPeriodPerf = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  2493. foreach ($areaNums as $area) {
  2494. if( $maxArea > 0 && $area === $maxArea ) continue;
  2495. $areaKey = sprintf('PV_%dL_ZC', $area);
  2496. if ( isset($nowPeriodPerf[$areaKey]) && $nowPeriodPerf[$areaKey] > 0 ) {
  2497. $otherAreaZcPv += $nowPeriodPerf[$areaKey];
  2498. }
  2499. unset($area, $areaKey);
  2500. }
  2501. unset($nowPeriodPerf, $areaNums, $maxArea);
  2502. return $otherAreaZcPv >= self::MIN_BD_PV;
  2503. }
  2504. /**
  2505. * 获取有最小报单PV的用效父级
  2506. * @param $userId
  2507. * @return string
  2508. */
  2509. public function getMinBdPvRelationParent($userId) {
  2510. $validParentId = '';
  2511. $this->loopRelationParentDo($userId, function ($parent) use(&$validParentId) {
  2512. if ( $this->checkSmallMarketPerf($parent['PARENT_UID']) ) {
  2513. $validParentId = $parent['PARENT_UID'];
  2514. unset($parent);
  2515. return self::LOOP_FINISH;
  2516. }
  2517. unset($parent);
  2518. });
  2519. return$validParentId;
  2520. }
  2521. /**
  2522. * 获取有最小报单PV的用效父级 20220407修改成是否此期此用户有原报单团队奖金
  2523. * @param $userId
  2524. * @return string
  2525. */
  2526. public function getMinBdPvNetworkParent($userId, $openFindLimit = 1, $findLimitTimes = 5) {
  2527. $validParentId = '';
  2528. $validDeep = 1;
  2529. $this->loopNetworkParentDo($userId, function ($parent) use(&$validParentId,&$validDeep,$openFindLimit,$findLimitTimes) {
  2530. if ( $this->checkHasOriBonusQyBd($parent['PARENT_UID']) ) {
  2531. $validParentId = $parent['PARENT_UID'];
  2532. unset($parent);
  2533. return self::LOOP_FINISH;
  2534. }
  2535. // 只找5层
  2536. if ( $openFindLimit && $validDeep >= $findLimitTimes ) {
  2537. unset($parent);
  2538. return self::LOOP_FINISH;
  2539. }
  2540. $validDeep += 1;
  2541. unset($parent);
  2542. });
  2543. return$validParentId;
  2544. }
  2545. // public function getMinBdPvNetworkParent($userId, $openFindLimit = 1, $findLimitTimes = 5) {
  2546. // $validParentId = '';
  2547. // $validDeep = 1;
  2548. // $this->loopNetworkParentDo($userId, function ($parent) use(&$validParentId,&$validDeep,$openFindLimit,$findLimitTimes) {
  2549. // if ( $this->checkSmallMarketPerf($parent['PARENT_UID']) ) {
  2550. // $validParentId = $parent['PARENT_UID'];
  2551. // unset($parent);
  2552. // return self::LOOP_FINISH;
  2553. // }
  2554. // // 只找5层
  2555. // if ( $openFindLimit && $validDeep >= $findLimitTimes ) {
  2556. // unset($parent);
  2557. // return self::LOOP_FINISH;
  2558. // }
  2559. // $validDeep += 1;
  2560. // unset($parent);
  2561. // });
  2562. // return$validParentId;
  2563. // }
  2564. /**
  2565. * 按级别的收入上限
  2566. * 新的需求调整: 改成不按月进行限制,并且去掉vip奖
  2567. * @param $bonus
  2568. * @param $userId
  2569. * @param $declarationLevel
  2570. * @return float
  2571. */
  2572. public function declarationLevelCap($bonus, $userId, $declarationLevel) {
  2573. $decLevelConfig = $this->_decLevelConfig;
  2574. $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
  2575. unset($decLevelConfig);
  2576. $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'];
  2577. if( $bonus <= $maxGetBonus) {
  2578. return $bonus;
  2579. }else {
  2580. return $maxGetBonus;
  2581. }
  2582. }
  2583. // public function declarationLevelCap($bonus, $userId, $declarationLevel) {
  2584. // $decLevelConfig = $this->_decLevelConfig;
  2585. // $nowDecLevelConfig = $decLevelConfig[$declarationLevel];
  2586. // unset($decLevelConfig);
  2587. // //本月往期奖金 这里执行速度可能慢一些,但需求如此没有办法
  2588. // $lastData = CalcCache::lastPeriodMonthCalcBonus($userId, $this->_periodNum, $this->_calcMonth);
  2589. // $lastTotal = $lastData['ORI_BONUS_QY_SUM'] + $lastData['ORI_BONUS_VIP_SUM'];
  2590. // // 从缓存中获取用户的奖金
  2591. // $bonusData = CalcCache::bonus($userId, $this->_periodNum);
  2592. // $thisTotal = $bonusData['ORI_BONUS_QY'] + $bonusData['ORI_BONUS_VIP'];
  2593. // $maxGetBonus = $nowDecLevelConfig['INCOME_CAP'] * $this->_calcMonthPeriodNumCount - $lastTotal - $thisTotal;
  2594. // unset($lastData, $lastTotal, $bonusData, $thisTotal);
  2595. // if( $maxGetBonus <= 0 ) return 0.00;
  2596. // if( $bonus <= $maxGetBonus) {
  2597. // return $bonus;
  2598. // }else {
  2599. // return $maxGetBonus;
  2600. // }
  2601. // }
  2602. /**
  2603. * 总奖金限制
  2604. * @param $bonus
  2605. * @param $userId
  2606. * @param $recNum
  2607. * @param $decAmount
  2608. * @return float
  2609. */
  2610. public function bonusTotalLimit($bonus, $userId, $recNum, $decAmount) {
  2611. //@todo 临时不做总奖金限制
  2612. return $bonus;
  2613. if( $recNum >= 3 ) return $bonus;
  2614. $limitAmount = 0;
  2615. switch ($recNum) {
  2616. case 0:
  2617. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalZeroLimit']['VALUE'];
  2618. break;
  2619. case 1:
  2620. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalOneLimit']['VALUE'];
  2621. break;
  2622. case 2:
  2623. $limitAmount = $decAmount * $this->_sysConfig['bonusTotalTwoLimit']['VALUE'];
  2624. break;
  2625. default:
  2626. break;
  2627. }
  2628. // 从缓存中获取用户的奖金
  2629. $lastUserBonus = CalcCache::LastUserBonus($userId, $this->_periodNum);//往期的总金额
  2630. $bonusData = CalcCache::bonus($userId, $this->_periodNum);
  2631. $bonusTotal = $bonusData['BONUS_TOTAL'] + $lastUserBonus['BONUS_TOTAL'];
  2632. unset($lastUserBonus, $userId, $recNum, $decAmount, $bonusData);
  2633. if( $bonusTotal >= $limitAmount ) return 0.00;
  2634. if( $bonusTotal + $bonus <= $limitAmount) {
  2635. return $bonus;
  2636. }else {
  2637. return $limitAmount - $bonusTotal;
  2638. }
  2639. }
  2640. /**
  2641. * 扣除复消积分和管理费
  2642. * @param $userId
  2643. * @param $bonus
  2644. * @return array
  2645. * @throws \yii\db\Exception
  2646. */
  2647. public function deductNoReconsumePoints($userId, $bonus): array
  2648. {
  2649. $manageTax = $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
  2650. $surplus = $bonus - $manageTax;
  2651. return [
  2652. 'reConsumePoints' => 0.00,
  2653. 'manageTax' => Tool::formatPrice($manageTax),
  2654. 'surplus' => Tool::formatPrice($surplus),
  2655. ];
  2656. }
  2657. /**
  2658. * 扣除复消积分和管理费
  2659. * @param $userId
  2660. * @param $bonus
  2661. * @return array
  2662. * @throws \yii\db\Exception
  2663. */
  2664. public function deduct($userId, $bonus) {
  2665. //判断是否达到了本月扣除复消的上限
  2666. $cacheData = CalcCache::monthLastPeriodReconsumePoints($userId, $this->_periodNum, $this->_calcYearMonth);
  2667. $bonusCache = CalcCache::bonus($userId, $this->_periodNum);
  2668. $reConsumePointsTotal = $bonusCache['RECONSUME_POINTS'] + $cacheData['RECONSUME_POINTS_SUM'];
  2669. $reConsumePointsCap = $this->_sysConfig['reConsumePointsMonthCap']['VALUE'];
  2670. unset($cacheData, $bonusCache);
  2671. $reConsumePoints = 0;
  2672. if( $reConsumePointsTotal < $reConsumePointsCap ) {
  2673. $reConsumePoints = $bonus * $this->_sysConfig['reConsumePointsPercent']['VALUE'] / 100;
  2674. // 2022/05/17 复消积分去掉限制,config reConsumePointsMonthCap上限改成大值如5000000
  2675. //$reConsumePoints = min($reConsumePoints, $reConsumePointsCap-$reConsumePointsTotal);
  2676. }
  2677. unset($reConsumePointsTotal, $reConsumePointsCap);
  2678. $manageTax = $bonus * $this->_sysConfig['manageTaxPercent']['VALUE'] / 100;
  2679. $surplus = $bonus - $reConsumePoints - $manageTax;
  2680. return [
  2681. 'reConsumePoints' => Tool::formatPrice($reConsumePoints),
  2682. 'manageTax' => Tool::formatPrice($manageTax),
  2683. 'surplus' => Tool::formatPrice($surplus),
  2684. ];
  2685. }
  2686. /**
  2687. * 更新百分比并发送
  2688. * @param $percent
  2689. */
  2690. private function _updatePercent($percent) {
  2691. // 把数据写入数据库中
  2692. Period::updateAll(['CALC_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  2693. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'CALC_PERCENT']);
  2694. }
  2695. /**
  2696. * 把往期有月奖金的会员加到本期有奖会员缓存列表中
  2697. * @param int $offset
  2698. * @return bool
  2699. */
  2700. public function loopMonthBonusUserFromDbToCache($offset = 0) {
  2701. if (!$this->_isCalcMonth) {
  2702. return true;
  2703. }
  2704. $allData = CalcMonthBonusUser::findUseDbCalc()->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->offset($offset)->limit($this->_limit)->asArray()->all();
  2705. if ( $allData ) {
  2706. foreach ($allData as $everyData) {
  2707. CalcCache::addHasBonusUsers($everyData['USER_ID'], $this->_periodNum);
  2708. unset($everyData);
  2709. }
  2710. unset($allData);
  2711. $this->loopMonthBonusUserFromDbToCache($offset + $this->_limit);
  2712. }
  2713. unset($allData);
  2714. return true;
  2715. }
  2716. /**
  2717. * 把缓存中的月奖用户信息存到数据库
  2718. * @param int $offset
  2719. * @return bool
  2720. * @throws \yii\db\Exception
  2721. */
  2722. public function loopMonthBonusUserToDb($offset = 0) {
  2723. echo sprintf("时间:[%s]月奖会员入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  2724. $allData = CalcCache::getHasMonthBonusUsers($this->_periodNum, $offset, $this->_limit);
  2725. if($allData) {
  2726. $insertDataBonusUser = [];
  2727. foreach($allData as $userId){
  2728. $insertDataBonusUser[] = [
  2729. 'ID' => SnowFake::instance()->generateId(),
  2730. 'USER_ID' => $userId,
  2731. 'CALC_MONTH' => $this->_calcYearMonth,
  2732. 'PERIOD_NUM' => $this->_periodNum,
  2733. 'CREATED_AT' => Date::nowTime()
  2734. ];
  2735. unset($userId);
  2736. }
  2737. if( $insertDataBonusUser ) CalcMonthBonusUser::batchInsert($insertDataBonusUser);
  2738. unset($insertDataBonus, $allData);
  2739. return $this->loopMonthBonusUserToDb($offset + $this->_limit);
  2740. }
  2741. unset($allData);
  2742. return true;
  2743. }
  2744. //奖金入库
  2745. /**
  2746. * 循环奖服务奖金会员,并入库
  2747. * @param int $offset
  2748. * @return bool
  2749. * @throws \yii\db\Exception
  2750. */
  2751. public function loopBonusUsers($offset = 0) {
  2752. echo sprintf("时间:[%s]缓存奖金数据入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  2753. // 从缓存列表里面从底层往上倒序获取会员
  2754. // 这里有问题,因为蓝星奖,是存储过程计算的,并没有加入缓存,这里需要修改.
  2755. // 给用户发送兑换积分,也需要进行调整查看。
  2756. // CalcCache::addHasBonusUsers($everyData['USER_ID'], $this->_periodNum);
  2757. $allData = CalcCache::getHasBonusUsers($this->_periodNum, $offset, $this->_limit);
  2758. if($allData){
  2759. $insertDataBonus = [];
  2760. foreach($allData as $userId){
  2761. $tempBonusData = $this->bonusData($userId);
  2762. if(!empty($tempBonusData['result'])){
  2763. $insertDataBonus[] = $tempBonusData['result'];
  2764. }
  2765. unset($userId, $tempBonusData);
  2766. }
  2767. CalcBonus::batchInsert($insertDataBonus);
  2768. unset($insertDataBonus, $allData);
  2769. return $this->loopBonusUsers($offset + $this->_limit);
  2770. }
  2771. return true;
  2772. }
  2773. // 奖金入库完成,将各个奖金计算流水会员聘级,更新成蓝星奖当时计算的聘级
  2774. public function loopCalcBlueEmpLv($offset = 0) {
  2775. if( !$this->_isCalcMonth ) {
  2776. // 不是结算月,则不需要进行聘级调整
  2777. return false;
  2778. }
  2779. // 从缓存获取分页有收入的会员信息
  2780. $allData = CalcBonusBS::findUseDbCalc()
  2781. ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])
  2782. ->groupBy('USER_ID')
  2783. ->offset($offset)
  2784. ->limit($this->_limit)
  2785. ->asArray()
  2786. ->all();
  2787. if ($allData) {
  2788. foreach ($allData as $data) {
  2789. $nowBsEmpLv = $data['LEVEL_ID']; // 当前蓝星奖计算(即管理奖) 的等级
  2790. // 修改AR_CALC_BONUS的LAST_EMP_LV聘级,修改奖金流水的聘级AR_FLOW_BONUS表的LAST_EMP_LV
  2791. // 期结算结果
  2792. CalcBonus::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2793. [
  2794. ':USER_ID' => $data['USER_ID'],
  2795. ':PERIOD_NUM' => $this->_periodNum
  2796. ]
  2797. );
  2798. // 奖金流水
  2799. FlowBonus::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2800. [
  2801. ':USER_ID' => $data['USER_ID'],
  2802. ':PERIOD_NUM' => $this->_periodNum
  2803. ]
  2804. );
  2805. // 共享奖流水
  2806. CalcBonusGX::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2807. [
  2808. ':USER_ID' => $data['USER_ID'],
  2809. ':PERIOD_NUM' => $this->_periodNum
  2810. ]
  2811. );
  2812. // 推广奖流水
  2813. CalcBonusTG::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2814. [
  2815. ':USER_ID' => $data['USER_ID'],
  2816. ':PERIOD_NUM' => $this->_periodNum
  2817. ]
  2818. );
  2819. // 团队奖流水
  2820. CalcBonusQY::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2821. [
  2822. ':USER_ID' => $data['USER_ID'],
  2823. ':PERIOD_NUM' => $this->_periodNum
  2824. ]
  2825. );
  2826. // 服务奖流水
  2827. CalcBonusBD::updateAll(['LAST_EMP_LV' => $nowBsEmpLv], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2828. [
  2829. ':USER_ID' => $data['USER_ID'],
  2830. ':PERIOD_NUM' => $this->_periodNum
  2831. ]
  2832. );
  2833. // 更新form的聘级
  2834. CalcBonusGX::updateAll(['LAST_FROM_EMP_LV' => $nowBsEmpLv], 'FROM_USER_ID=:FROM_USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2835. [
  2836. ':FROM_USER_ID' => $data['USER_ID'],
  2837. ':PERIOD_NUM' => $this->_periodNum
  2838. ]
  2839. );
  2840. CalcBonusTG::updateAll(['LAST_FROM_EMP_LV' => $nowBsEmpLv], 'FROM_USER_ID=:FROM_USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2841. [
  2842. ':FROM_USER_ID' => $data['USER_ID'],
  2843. ':PERIOD_NUM' => $this->_periodNum
  2844. ]
  2845. );
  2846. CalcBonusBD::updateAll(['LAST_FROM_EMP_LV' => $nowBsEmpLv], 'FROM_USER_ID=:FROM_USER_ID AND PERIOD_NUM=:PERIOD_NUM',
  2847. [
  2848. ':FROM_USER_ID' => $data['USER_ID'],
  2849. ':PERIOD_NUM' => $this->_periodNum
  2850. ]
  2851. );
  2852. }
  2853. unset($allData);
  2854. return $this->loopCalcBlueEmpLv($offset + $this->_limit);
  2855. }
  2856. unset($allData);
  2857. return true;
  2858. }
  2859. /**
  2860. * 奖金
  2861. * @param $userId
  2862. * @return array
  2863. * @throws \yii\db\Exception
  2864. */
  2865. public function bonusData($userId) {
  2866. // 从缓存中获取用户的奖金
  2867. $bonus = CalcCache::bonus($userId, $this->_periodNum);
  2868. $standardBonus = CalcCache::standardBonus($userId, $this->_periodNum);
  2869. $baseInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  2870. $perfData = CalcCache::nowPeriodPerf($userId, $this->_periodNum);
  2871. $empLv = $baseInfo['EMP_LV'];
  2872. // if($this->_isCalcMonth){
  2873. // $empLv = $this->nowMonthPerfData($userId)['LAST_EMP_LV'];
  2874. // }
  2875. $pervSurplusPerf = CalcCache::surplusPerf($userId, $this->_periodNum);
  2876. // //没有共享和管理奖 以前的管理奖和共享奖逻辑
  2877. // $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;
  2878. // $realBonusGx = 0;
  2879. // $realBonusGl = 0;
  2880. // if( $this->_isCalcMonth ) {
  2881. // //查看是否复消300
  2882. // $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  2883. // $fxPvStatus = $monthPerfData['PV_PCS_FX'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2884. // if ( $fxPvStatus ) {//加上本期和往期的共享和管理奖
  2885. // $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();
  2886. // $bonusGxSum = $monthSumData['BONUS_GX_SUM'] ?? 0;
  2887. // $bonusGlSum = $monthSumData['BONUS_GL_SUM'] ?? 0;
  2888. // $realBonusGx += $bonusGxSum + $bonus['BONUS_GX'];
  2889. // $realBonusGl += $bonusGlSum + $bonus['BONUS_GL'];
  2890. // $bonusReal += $realBonusGx + $realBonusGl;
  2891. // unset($monthSumData, $bonusGxSum, $bonusGlSum);
  2892. // }
  2893. // }
  2894. //没有共享和管理奖
  2895. $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;
  2896. $realBonusGx = 0;
  2897. $realBonusGl = 0;
  2898. $realBonusBs = 0; // 蓝星管理奖. BlueStar
  2899. $blueStartAmount = 0;
  2900. $buleStartOriBonus = 0;
  2901. $buleStartManageTax = 0;
  2902. $exchangePoints = 0; // 蓝星奖管理奖. 产生的兑换积分
  2903. if( $this->_isCalcMonth ) {
  2904. // 查看是否复消300
  2905. // $monthPerfData = CalcCache::nowMonthPerf($userId, $this->_periodNum);
  2906. // $monthPerf = $monthPerfData['PV_PCS_FX'];
  2907. // // $fxPvStatus 改成月报单+复消之和是否300
  2908. // $decPvInfo = PerfPeriod::findUseSlaves()->select('SUM(PV_PCS_ZC) AS ZC_SUM')
  2909. // ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth])
  2910. // ->asArray()
  2911. // ->one();
  2912. // $decPv = isset($decPvInfo['ZC_SUM']) && $decPvInfo['ZC_SUM'] > 0 ? $decPvInfo['ZC_SUM'] : 0;
  2913. // $totalCheckPv = $monthPerf + $decPv;
  2914. // $fxPvStatus = $totalCheckPv >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE'];
  2915. // 逻辑改成,用户此月累计消费总额大于等于配置,取消订单类型的配置
  2916. $fxPvStatus = $this->_isMonthPerfLimit($userId);
  2917. // BONUS_REAL 字段是发到用户的真实奖金
  2918. if ( $fxPvStatus ) {
  2919. // 管理奖改成了蓝星奖,但是对于用户来说依旧叫管理奖.字段改成bs.
  2920. // 因为管理奖(即蓝星奖,是用存储过程计算的,则此处直接取AR_CALC_BONUS_BS表中计算的结果数据使用,
  2921. // 并将管理奖结果同步到当前结算月的CalcBonus中)
  2922. // 由于单独奖金流水记录每次都插入,所以倒叙找最新的数据.
  2923. $userBS = CalcBonusBS::find()
  2924. ->where(
  2925. 'PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID',
  2926. [
  2927. ':PERIOD_NUM' => $this->_periodNum,
  2928. ':USER_ID' => $userId
  2929. ]
  2930. )
  2931. ->select('AMOUNT,ORI_BONUS,MANAGE_TAX,LEVEL_ID,PRODUCT_POINT')
  2932. ->limit(1)
  2933. ->orderBy('CREATED_AT DESC')
  2934. ->asArray()
  2935. ->all();
  2936. $userBS = is_array($userBS) ? reset($userBS) : [];
  2937. $blueStartAmount = isset($userBS['AMOUNT']) && !empty($userBS['AMOUNT']) ? $userBS['AMOUNT'] : 0; // 奖金
  2938. $buleStartOriBonus = isset($userBS['ORI_BONUS']) && !empty($userBS['ORI_BONUS']) ? $userBS['ORI_BONUS'] : 0; // 原奖金
  2939. // $buleStartManageTax = isset($userBS['MANAGE_TAX']) && !empty($userBS['MANAGE_TAX']) ? $userBS['MANAGE_TAX'] : 0; // 管理费
  2940. $monthSumData = CalcBonus::findUseSlaves()
  2941. ->select('SUM(BONUS_GX) AS BONUS_GX_SUM, SUM(BONUS_GL) AS BONUS_GL_SUM')
  2942. ->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
  2943. [
  2944. 'USER_ID'=>$userId,
  2945. 'CALC_MONTH'=>$this->_calcYearMonth
  2946. ]
  2947. )
  2948. ->asArray()
  2949. ->one();
  2950. $bonusGxSum = $monthSumData['BONUS_GX_SUM'] ?? 0;
  2951. $bonusGlSum = $monthSumData['BONUS_GL_SUM'] ?? 0;
  2952. $realBonusGx += $bonusGxSum + $bonus['BONUS_GX'];
  2953. $realBonusGl += $bonusGlSum + $bonus['BONUS_GL'];
  2954. $realBonusBs = $blueStartAmount; // 蓝星奖直接取数据库中算好的值PRODUCT_POINT
  2955. $bonusReal += $realBonusGx + $realBonusBs + $realBonusGl;
  2956. $exchangePoints = isset($userBS['PRODUCT_POINT']) && !empty($userBS['PRODUCT_POINT']) ? $userBS['PRODUCT_POINT'] : 0; // 兑换积分
  2957. unset($monthSumData, $bonusGxSum, $bonusGlSum);
  2958. } else {
  2959. // 蓝星奖原奖金在扣管理费的时候被加入到了BONUS_TOTAL,需要再减去原奖金
  2960. $oriBonusBs = isset($bonus['ORI_BONUS_BS']) && $bonus['ORI_BONUS_BS'] > 0 ? $bonus['ORI_BONUS_BS'] : 0;
  2961. $bonus['BONUS_TOTAL'] = $bonus['BONUS_TOTAL'] - $oriBonusBs;
  2962. }
  2963. }
  2964. // if( $this->_isCalcMonth ) {
  2965. // // 将查看是否复消300的逻辑,改成月结时判断当前月有一周活跃则本月活跃
  2966. // // 1. 获取此业绩期的月份
  2967. // $periodInfo = Period::getInfoByPeriodNum($this->_periodNum);
  2968. // $calcMonth = $periodInfo['CALC_YEAR'].'-'.$periodInfo['CALC_MONTH']; // 2025-7
  2969. // // 获取此月的第一天和最后一天时间戳
  2970. // $fday = date('Y-m-01', strtotime($calcMonth));
  2971. // $lday = date('Y-m-d', strtotime("$fday +1 month -1 day"));
  2972. // $ftime = strtotime($fday);
  2973. // $ltime = strtotime($lday.' 23:59:59');
  2974. // // 2. 根据业绩期的月份,判断用户是否是活跃状态.
  2975. // $fxPvStatus = PerfActiveUser::findUseDbCalc()
  2976. // ->select('USER_ID')
  2977. // ->where("USER_ID=:USER_ID ", [':USER_ID' => $userId])
  2978. // ->andWhere(['or',
  2979. // [
  2980. // 'and',
  2981. // ['>=', 'SRATR_AT', $ftime],
  2982. // ['<=', 'SRATR_AT', $ltime]
  2983. // ],
  2984. // [
  2985. // 'and',
  2986. // ['>=', 'END_AT', $ftime],
  2987. // ['<=', 'END_AT', $ltime]
  2988. // ]
  2989. // ])
  2990. // ->asArray()
  2991. // ->all();
  2992. // if ( !empty($fxPvStatus) ) {//加上本期和往期的共享和管理奖
  2993. // $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();
  2994. // $bonusGxSum = $monthSumData['BONUS_GX_SUM'] ?? 0;
  2995. // $bonusGlSum = $monthSumData['BONUS_GL_SUM'] ?? 0;
  2996. // $realBonusGx += $bonusGxSum + $bonus['BONUS_GX'];
  2997. // $realBonusGl += $bonusGlSum + $bonus['BONUS_GL'];
  2998. // $bonusReal += $realBonusGx + $realBonusGl;
  2999. // unset($monthSumData, $bonusGxSum, $bonusGlSum);
  3000. // }
  3001. // }
  3002. $result = [
  3003. 'USER_ID' => $userId,
  3004. 'LAST_USER_NAME' => $baseInfo['USER_NAME'],
  3005. 'LAST_REAL_NAME' => $baseInfo['REAL_NAME'],
  3006. 'LAST_DEC_LV' => $baseInfo['DEC_LV'],
  3007. 'LAST_EMP_LV' => $empLv,
  3008. 'LAST_STATUS' => $baseInfo['STATUS'],
  3009. 'LAST_MOBILE' => $baseInfo['MOBILE'],
  3010. 'LAST_PERIOD_AT' => $baseInfo['PERIOD_NUM'],
  3011. 'LAST_CREATED_AT' => $baseInfo['CREATED_AT'],
  3012. 'LAST_SUB_COM_ID' => $baseInfo['SUB_COM_ID'],
  3013. 'LAST_PROVINCE' => $baseInfo['PROVINCE'],
  3014. 'LAST_CITY' => $baseInfo['CITY'],
  3015. 'LAST_COUNTY' => $baseInfo['COUNTY'],
  3016. 'LAST_SYSTEM_ID' => $baseInfo['SYSTEM_ID'] ? $baseInfo['SYSTEM_ID'] : '',
  3017. 'LAST_IS_DIRECT_SELLER' => $baseInfo['IS_DIRECT_SELLER'],
  3018. 'LAST_REC_USER_NAME' => $baseInfo['REC_USER_NAME'],
  3019. 'LAST_REC_REAL_NAME' => $baseInfo['REC_REAL_NAME'],
  3020. 'LAST_CON_USER_NAME' => $baseInfo['CON_USER_NAME'],
  3021. 'LAST_CON_REAL_NAME' => $baseInfo['CON_REAL_NAME'],
  3022. 'EXCHANGE_POINTS' => $exchangePoints, // 兑换积分
  3023. // 'LAST_LOCATION' => $baseInfo['LOCATION'] ? $baseInfo['LOCATION'] : 1,
  3024. //@todo
  3025. 'LAST_LOCATION' => 1,
  3026. 'BONUS_BD' => $bonus['BONUS_BD'],
  3027. 'BONUS_TG' => $bonus['BONUS_TG'],
  3028. 'BONUS_XF' => $bonus['BONUS_XF'],
  3029. 'BONUS_YJ' => $bonus['BONUS_YJ'],
  3030. 'BONUS_GX' => $bonus['BONUS_GX'],
  3031. 'BONUS_GL' => $bonus['BONUS_GL'],
  3032. 'BONUS_QY' => $bonus['BONUS_QY'],
  3033. 'BONUS_YC' => $bonus['BONUS_YC'] + $bonus['BONUS_YC_EXTRA'],
  3034. 'BONUS_VIP' => $bonus['BONUS_VIP'],
  3035. 'RECONSUME_POINTS' => $bonus['RECONSUME_POINTS'],
  3036. 'MANAGE_TAX' => $bonus['MANAGE_TAX'],
  3037. 'BONUS_INCOME'=>$bonus['INCOME_TOTAL'],
  3038. 'BONUS_REAL'=> $bonusReal,
  3039. 'BONUS_TOTAL'=>$bonus['BONUS_TOTAL'],
  3040. 'ORI_BONUS_BD' => $bonus['ORI_BONUS_BD'],
  3041. 'ORI_BONUS_TG' => $bonus['ORI_BONUS_TG'],
  3042. 'ORI_BONUS_XF' => $bonus['ORI_BONUS_XF'],
  3043. 'ORI_BONUS_YJ' => $bonus['ORI_BONUS_YJ'],
  3044. 'ORI_BONUS_YJ_BD' => $bonus['ORI_BONUS_YJ_BD'],
  3045. 'ORI_BONUS_YJ_FX' => $bonus['ORI_BONUS_YJ_FX'],
  3046. 'ORI_BONUS_GX' => $bonus['ORI_BONUS_GX'],
  3047. 'REAL_BONUS_GX' => $realBonusGx,
  3048. 'ORI_BONUS_GL' => $bonus['ORI_BONUS_GL'],
  3049. 'REAL_BONUS_GL' => $realBonusGl,
  3050. 'BONUS_BS' => $realBonusBs, // 新的管理奖金,即蓝星管理奖
  3051. 'ORI_BONUS_BS' => $buleStartOriBonus, // 蓝星管理奖金原奖金,即包含管理费
  3052. 'REAL_BONUS_BS' => $realBonusBs, // 实发蓝星管理奖金
  3053. 'ORI_BONUS_GL_BD' => $bonus['ORI_BONUS_GL_BD'],
  3054. 'ORI_BONUS_GL_FX' => $bonus['ORI_BONUS_GL_FX'],
  3055. 'ORI_BONUS_QY' => $bonus['ORI_BONUS_QY'],
  3056. 'ORI_BONUS_QY_BD' => $bonus['ORI_BONUS_QY_BD'],
  3057. 'ORI_BONUS_QY_FX' => $bonus['ORI_BONUS_QY_FX'],
  3058. 'ORI_BONUS_YC' => $bonus['ORI_BONUS_YC'] + $bonus['ORI_BONUS_YC_EXTRA'],
  3059. 'ORI_BONUS_VIP' => $bonus['ORI_BONUS_VIP'],
  3060. 'ORI_BONUS_STANDARD' => $standardBonus,
  3061. //以下没有用
  3062. 'BONUS_FW' => 0,
  3063. 'BONUS_FX' => $bonus['BONUS_FX'],
  3064. 'BONUS_LS' => $bonus['BONUS_LS'],
  3065. 'BONUS_BT' => $bonus['BONUS_BT'],
  3066. 'BONUS_BT_PROD' => $bonus['BONUS_BT_PROD'],
  3067. 'BONUS_BT_TOOL' => $bonus['BONUS_BT_TOOL'],
  3068. 'DEDUCT_ZR' => $bonus['DEDUCT_ZR'],
  3069. 'BONUS_FL' => $bonus['BONUS_FL'],
  3070. 'BONUS_CF' => $bonus['BONUS_CF'],
  3071. 'BONUS_LX' => $bonus['BONUS_LX'],
  3072. 'SHOULD_QY' => $bonus['BONUS_QY'],
  3073. 'SHOULD_DEDUCT_ZR' => $bonus['DEDUCT_ZR'],
  3074. 'PV_1L' => $perfData['PV_1L_TOUCH'],//TOUCH为碰业绩
  3075. 'QY_1L' => $perfData['PV_1L_TOUCH'] + $pervSurplusPerf['SURPLUS_1L'],
  3076. 'SURPLUS_1L' => $perfData['SURPLUS_1L'],
  3077. 'PV_2L' => $perfData['PV_2L_TOUCH'],
  3078. 'QY_2L' => $perfData['PV_2L_TOUCH'] + $pervSurplusPerf['SURPLUS_2L'],
  3079. 'SURPLUS_2L' => $perfData['SURPLUS_2L'],
  3080. 'PV_3L' => $perfData['PV_3L_TOUCH'],
  3081. 'QY_3L' => $perfData['PV_3L_TOUCH'] + $pervSurplusPerf['SURPLUS_3L'],
  3082. 'SURPLUS_3L' => $perfData['SURPLUS_3L'],
  3083. 'PV_4L' => $perfData['PV_4L_TOUCH'],
  3084. 'QY_4L' => $perfData['PV_4L_TOUCH'] + $pervSurplusPerf['SURPLUS_4L'],
  3085. 'SURPLUS_4L' => $perfData['SURPLUS_4L'],
  3086. 'PV_5L' => $perfData['PV_5L_TOUCH'],
  3087. 'QY_5L' => $perfData['PV_5L_TOUCH'] + $pervSurplusPerf['SURPLUS_5L'],
  3088. 'SURPLUS_5L' => $perfData['SURPLUS_5L'],
  3089. 'PV_PCS' => $perfData['PV_PCS'],
  3090. 'PV_LS_TOUCH' => 0.00,
  3091. 'SURPLUS_LS' => 0.00,
  3092. 'QY_LS' => 0.00,
  3093. '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']),
  3094. 'PERIOD_NUM' => $this->_periodNum,
  3095. 'CALC_YEAR' => $this->_calcYear,
  3096. 'CALC_MONTH' => $this->_calcYearMonth,
  3097. 'CALCULATED_AT' => Date::nowTime(),
  3098. 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH),
  3099. 'CREATED_AT' => Date::nowTime(),
  3100. ];
  3101. $resend = [];
  3102. unset($bonus, $realBonusGx, $realBonusGl, $bonusReal);
  3103. return ['result'=>$result,'resend'=>$resend];
  3104. }
  3105. /**
  3106. * 根据本有收入计算基础积分
  3107. * @param int $offset
  3108. * @return bool
  3109. */
  3110. public function calcBaseScore(int $offset=0) {
  3111. if (!$this->_isCalcMonth) {
  3112. return true;
  3113. }
  3114. echo sprintf("时间:[%s]基础积分,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3115. //查询本月的,每人的累计总收入
  3116. $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();
  3117. if ($allData) {
  3118. foreach ($allData as $everyData) {
  3119. $validTotalSum = $everyData['TOTAL_SUM'] - $everyData['BD_TOTAL_SUM'];
  3120. if( $validTotalSum <=0 ) continue;
  3121. //达不到 见习主任级别,不产生基础积分
  3122. $userBaseInfo = CalcCache::getUserInfo($everyData['USER_ID'], $this->_periodNum);
  3123. $userEmpLevel = $this->_empLevelConfig[$userBaseInfo['EMP_LV']];
  3124. $userEmpLevelSort = $userEmpLevel['SORT'] ?? EmployLevel::EMP_LEVEL_SORT['NO_LEVEL'];
  3125. unset($userBaseInfo, $userEmpLevel);
  3126. if( $userEmpLevelSort < EmployLevel::EMP_LEVEL_SORT['JX_ZR_LEVEL'] ) {
  3127. unset($userEmpLevelSort);
  3128. continue;
  3129. }
  3130. unset($userEmpLevelSort);
  3131. //根据总收入获取积分
  3132. $baseScore = $this->_getBaseScoreByTotalBonus($validTotalSum);
  3133. //根据用户的级别判断 能否得到级别积分
  3134. if( $baseScore > 0 ) {
  3135. CalcCache::nowMonthScore($everyData['USER_ID'], $this->_periodNum, [
  3136. 'BASE_SCORE' => $baseScore,
  3137. ]);
  3138. CalcCache::addHasScoreUsers($everyData['USER_ID'], $this->_periodNum);
  3139. }
  3140. unset($everyData, $validTotalSum, $baseScore);
  3141. }
  3142. unset($allData);
  3143. return $this->calcBaseScore($offset + $this->_limit);
  3144. }
  3145. unset($allData);
  3146. return true;
  3147. }
  3148. /**
  3149. * 循环积分入库
  3150. * @param int $offset
  3151. * @return bool
  3152. * @throws \yii\db\Exception
  3153. */
  3154. public function loopWriteScore(int $offset = 0) {
  3155. if(!$this->_isCalcMonth){
  3156. return true;
  3157. }
  3158. echo sprintf("时间:[%s]积分入库,当前offset为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()) , $offset);
  3159. // 从缓存列表里面从底层往上倒序获取会员
  3160. $allData = CalcCache::getHasScoreUsers($this->_periodNum, $offset, $this->_limit);
  3161. if($allData){
  3162. $insertDataMonthScore = [];
  3163. foreach($allData as $userId){
  3164. $monthScoreData = CalcCache::nowMonthScore($userId, $this->_periodNum);
  3165. $totalScore = $monthScoreData['BASE_SCORE'] + $monthScoreData['LEVEL_SCORE'] + $monthScoreData['UPGRADE_SCORE'];
  3166. if( $totalScore <= 0 ) continue;
  3167. $insertDataMonthScore[] = [
  3168. 'USER_ID' => $userId,
  3169. 'BASE_SCORE' => $monthScoreData['BASE_SCORE'],
  3170. 'LEVEL_SCORE' => $monthScoreData['LEVEL_SCORE'],
  3171. 'UPGRADE_SCORE' => $monthScoreData['UPGRADE_SCORE'],
  3172. 'TOTAL_SCORE' => $totalScore,
  3173. 'PERIOD_NUM' => $this->_periodNum,
  3174. 'CALC_MONTH' => $this->_calcYearMonth,
  3175. 'CREATED_AT' => Date::nowTime(),
  3176. ];
  3177. unset($userId, $monthScoreData, $totalScore);
  3178. }
  3179. ScoreMonth::batchInsert($insertDataMonthScore);
  3180. unset($insertDataMonthScore, $allData);
  3181. return $this->loopWriteScore($offset + $this->_limit);
  3182. }
  3183. unset($allData);
  3184. return true;
  3185. }
  3186. /**
  3187. * 根据总收入获取相应的基础积分
  3188. * @param $totalBonus
  3189. * @return int|mixed
  3190. */
  3191. private function _getBaseScoreByTotalBonus($totalBonus) {
  3192. $baseScoreConfig = Json::decode($this->_sysConfig['baseScore']['VALUE']);
  3193. $baseScore = 0;
  3194. foreach ($baseScoreConfig as $everyScoreData) {
  3195. if( $totalBonus < $everyScoreData['monthTotalPvMin'] ) continue;
  3196. if( $everyScoreData['monthTotalPvMax'] != 0 && $totalBonus >= $everyScoreData['monthTotalPvMax'] ) continue;
  3197. $baseScore = $everyScoreData['score'];
  3198. unset($everyScoreData);
  3199. break;
  3200. }
  3201. unset($baseScoreConfig, $totalBonus);
  3202. return $baseScore;
  3203. }
  3204. // 判断是否满足月最低消费
  3205. public function _isMonthPerfLimit($userId) {
  3206. $userMonthTotal = PerfMonth::find()->where(
  3207. 'USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH',
  3208. ['USER_ID'=>$userId, 'CALC_MONTH'=>$this->_calcYearMonth]
  3209. )
  3210. ->asArray()
  3211. ->one();
  3212. $fxPvStatus = false;
  3213. if (isset($userMonthTotal['PV_PCS']) && $userMonthTotal['PV_PCS'] >= $this->_sysConfig['monthPcsPvFxCondition']['VALUE']) {
  3214. $fxPvStatus = true;
  3215. }
  3216. return $fxPvStatus;
  3217. }
  3218. }