BonusCalc.php 153 KB

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