BonusCalc.php 163 KB

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