UserRepository.php 215 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884
  1. <?php
  2. /**
  3. * @package merchant
  4. *
  5. * @author xaboy
  6. * @day 2020-04-28
  7. *
  8. *
  9. */
  10. namespace app\common\repositories\user;
  11. use alipay\aop\AlipayConfig;
  12. use alipay\aop\AopCertClient;
  13. use app\common\dao\BaseDao;
  14. use app\common\dao\user\UserDao;
  15. use app\common\enum\user\UserBillEnum;
  16. use app\common\enum\user\UserSignFugouEnum;
  17. use app\common\enum\user\UserSignJingdouEnum;
  18. use app\common\enum\user\UserSignScoreEnum;
  19. use app\common\enum\user\UserSignVrEnum;
  20. use app\common\model\merchant\order\OrderMerchant;
  21. use app\common\model\user\User;
  22. use app\common\model\wechat\WechatUser;
  23. use app\common\repositories\BaseRepository;
  24. use app\common\repositories\store\order\AgentOrderRepository;
  25. use app\common\repositories\store\order\StoreOrderRepository;
  26. use app\common\repositories\system\attachment\AttachmentRepository;
  27. use app\common\repositories\wechat\RoutineQrcodeRepository;
  28. use app\controller\api\store\product\Jd;
  29. use app\controller\api\store\product\Vip;
  30. use app\controller\api\user\Im;
  31. use app\entity\data\user\UserEntity;
  32. use app\entity\data\user\UserSignFugouEntity;
  33. use app\entity\data\user\UserSignJingdouEntity;
  34. use app\entity\data\user\UserSignScoreEntity;
  35. use app\entity\data\user\UserSignVrEntity;
  36. use app\traits\GzcApiRequest;
  37. use crmeb\exceptions\AuthException;
  38. use crmeb\jobs\SendNewPeopleCouponJob;
  39. use crmeb\services\JwtTokenService;
  40. use crmeb\services\QrcodeService;
  41. use crmeb\services\UploadService;
  42. use FormBuilder\Exception\FormBuilderException;
  43. use FormBuilder\Factory\Elm;
  44. use FormBuilder\Form;
  45. use think\Exception;
  46. use think\exception\ValidateException;
  47. use think\facade\Log;
  48. use think\facade\Queue;
  49. use function GuzzleHttp\Psr7\str;
  50. use think\db\exception\DataNotFoundException;
  51. use think\db\exception\DbException;
  52. use think\db\exception\ModelNotFoundException;
  53. use think\facade\Cache;
  54. use think\facade\Config;
  55. use think\facade\Db;
  56. use think\facade\Route;
  57. use think\Model;
  58. use app\controller\api\store\product\TaoKe;
  59. use alipay\aop\AopClient;
  60. use alipay\aop\request\AlipaySystemOauthTokenRequest;
  61. use alipay\aop\request\AlipayUserInfoShareRequest;
  62. /**
  63. * Class UserRepository
  64. * @package app\common\repositories\user
  65. * @author xaboy
  66. * @day 2020-04-28
  67. * @mixin UserDao
  68. */
  69. class UserRepository extends BaseRepository
  70. {
  71. use GzcApiRequest;
  72. /**
  73. * UserRepository constructor.
  74. * @param UserDao $dao
  75. */
  76. public function __construct(UserDao $dao)
  77. {
  78. $this->dao = $dao;
  79. }
  80. public function promoter($uid)
  81. {
  82. return $this->dao->update($uid, ['is_promoter' => 1, 'promoter_time' => date('Y-m-d H:i:s')]);
  83. }
  84. /**
  85. * 获取单条用户信息
  86. * @return array|\think\Model|null
  87. * @author php迷途小书童
  88. * @created 2021/1/16 10:45
  89. */
  90. public function getOne(array $where)
  91. {
  92. return ($this->dao->getWhere($where));
  93. }
  94. /**
  95. * @param $id
  96. * @return Form
  97. * @throws DataNotFoundException
  98. * @throws DbException
  99. * @throws FormBuilderException
  100. * @throws ModelNotFoundException
  101. * @author xaboy
  102. * @day 2020-05-09
  103. */
  104. public function userForm($id)
  105. {
  106. $user = $this->dao->get($id);
  107. $certification = Db::name('user_certification')->where("uid", $id)->find();
  108. $regions1 = Db::name('regions') -> field('id as value,name as label')->where('level',1) ->select();
  109. $regions2 = Db::name('regions') -> field('id as value,name as label,pid')->where('level',2) ->select();
  110. $regions3 = Db::name('regions') -> field('id as value,name as label,pid')->where('level',3) ->select();
  111. $regions3_data=[];
  112. foreach ($regions3 as $v){
  113. $regions3_data[$v['pid']][]=$v;
  114. }
  115. $regions2_data=[];
  116. foreach ($regions2 as $v){
  117. $v['children']=isset( $regions3_data[$v['value']])? $regions3_data[$v['value']]:[];
  118. $regions2_data[$v['pid']][]=$v;
  119. }
  120. $city_area=[];
  121. foreach ($regions1 as $v){
  122. $v['children']=isset( $regions2_data[$v['value']])? $regions2_data[$v['value']]:[];
  123. $city_area[]=$v;
  124. }
  125. $regions2_data2=[];
  126. foreach ($regions2 as $v){
  127. $regions2_data2[$v['pid']][]=$v;
  128. }
  129. $city_area_2=[];
  130. foreach ($regions1 as $v){
  131. $v['children']=isset( $regions2_data2[$v['value']])? $regions2_data2[$v['value']]:[];
  132. $city_area_2[]=$v;
  133. }
  134. $user['real_name'] = $certification['user_name'] ?? '';
  135. $user['card_id'] = $certification['user_card'] ?? '';
  136. $user['uid'] = (string)$user['uid'];
  137. $user_rich=Db::name('user_rich')->where('uid',$id)->find();
  138. $user['admin_start_level'] =$user_rich?$user_rich['admin_start_level']:'0';
  139. $user['user_rich_type'] =$user_rich?$user_rich['type']:'0';
  140. $user['area_manage_pics'] =[];
  141. $user['area_manage_obtain'] ='0';
  142. if($user_rich){
  143. $user['area_manage_obtain'] =$user_rich['obtain'];
  144. if($user_rich['pics']){
  145. $user['area_manage_pics']=explode(',',$user_rich['pics']);
  146. }
  147. }
  148. // $area_manage=Db::name('area_manage')->where('uid',$id)->find();
  149. $area_manage=null;
  150. // $area_manage_type=Db::name('area_manage')->where('uid',$id)->value('type');
  151. //类型 district-区/县代 city-市代',
  152. $user['area_manage_type'] ='0';
  153. $province = '';
  154. $city = '';
  155. $area = '';
  156. if($area_manage){
  157. if(isset($area_manage['type']) && $area_manage['type']=='district'){
  158. $user['area_manage_type']='1';
  159. }
  160. if(isset($area_manage['type']) && $area_manage['type']=='city'){
  161. $user['area_manage_type']='2';
  162. }
  163. $code_list=explode(',',$area_manage['code_list']);
  164. if(isset($code_list[0]) && $code_list[0]!=''){
  165. $province=$code_list[0];
  166. }
  167. if(isset($code_list[1]) && $code_list[1]!=''){
  168. $city=$code_list[1];
  169. }
  170. if(isset($code_list[2]) && $code_list[2]!=''){
  171. $area=$code_list[2];
  172. }
  173. }
  174. $where=[
  175. Elm::input('uid', '会员 ID', '')->disabled(true)->required(true),
  176. Elm::input('real_name', '真实姓名'),
  177. Elm::input('phone', '手机号'),
  178. Elm::date('birthday', '生日'),
  179. Elm::input('card_id', '身份证'),
  180. Elm::input('addres', '用户地址'),
  181. Elm::textarea('mark', '备注'),
  182. Elm::select('admin_start_level', '赠送消费星级')->options(function () {
  183. return array(
  184. array('value'=>'0','label'=>'普通用户'),
  185. array('value'=>'1','label'=>'1星级'),
  186. array('value'=>'2','label'=>'2星级'),
  187. array('value'=>'3','label'=>'3星级'),
  188. array('value'=>'4','label'=>'4星级'),
  189. array('value'=>'5','label'=>'5星级'),
  190. );
  191. })->className("tchakanquanyi"),
  192. Elm::select('user_rich_type', '身份')->options(function () {
  193. return array(
  194. array('value'=>'0','label'=>'请选择'),
  195. array('value'=>'1','label'=>'会员'),
  196. array('value'=>'4','label'=>'高级会员'),
  197. array('value'=>'8','label'=>'合伙人'),
  198. array('value'=>'3','label'=>'创始人'),
  199. array('value'=>'9','label'=>'联合创始人'),
  200. );
  201. }),
  202. Elm::select('area_manage_type', '代理')->options(function () {
  203. return array(
  204. array('value'=>'0','label'=>'请选择'),
  205. array('value'=>'1','label'=>'区/县代'),
  206. array('value'=>'2','label'=>'市代'),
  207. );
  208. })->control([ [
  209. 'value' => '1',
  210. 'rule' => [
  211. Elm::cityArea('city', '代理区域')->type('city_area')->options($city_area)->value([$province,$city,$area]),
  212. Elm::select('area_manage_obtain', '获得方式')->options(function () {
  213. return array(
  214. array('value'=>'0','label'=>'请选择'),
  215. array('value'=>'1','label'=>'线下支付'),
  216. array('value'=>'2','label'=>'赠送'),
  217. );
  218. })->control([[
  219. 'value'=>'1',
  220. 'rule'=>[
  221. Elm::frameImages('area_manage_pics', '支付凭证/截图', '/' . config('admin.admin_prefix') . '/setting/uploadPicture?field=area_manage_pics&type=2')
  222. ->width('896px')->height('480px')->modal(['modal' => false])->props(['footer' => false])
  223. ]
  224. ]])
  225. ]
  226. ],[
  227. 'value' => '2',
  228. 'rule' => [
  229. Elm::city('city', '代理区域')->type('city')->options($city_area_2)->value([$province,$city]),
  230. Elm::select('area_manage_obtain', '获得方式')->options(function () {
  231. return array(
  232. array('value'=>'0','label'=>'请选择'),
  233. array('value'=>'1','label'=>'线下支付'),
  234. array('value'=>'2','label'=>'赠送'),
  235. );
  236. })->control([[
  237. 'value'=>'1',
  238. 'rule'=>[
  239. Elm::frameImages('area_manage_pics', '支付凭证/截图', '/' . config('admin.admin_prefix') . '/setting/uploadPicture?field=area_manage_pics&type=2')
  240. ->width('896px')->height('480px')->modal(['modal' => false])->props(['footer' => false])
  241. ]
  242. ]])
  243. ]
  244. ]]),
  245. Elm::select('group_id', '会员分组')->options(function () {
  246. $data = app()->make(UserGroupRepository::class)->allOptions();
  247. $options = [];
  248. foreach ($data as $value => $label) {
  249. $options[] = compact('value', 'label');
  250. }
  251. return $options;
  252. }),
  253. Elm::selectMultiple('label_id', '会员标签')->options(function () {
  254. $data = app()->make(UserLabelRepository::class)->allOptions();
  255. $options = [];
  256. foreach ($data as $value => $label) {
  257. $value = (string)$value;
  258. $options[] = compact('value', 'label');
  259. }
  260. return $options;
  261. }),
  262. ];
  263. // 1 镇代 2 县代 3 市代 4 商户 5 推广员
  264. // $title="用户";
  265. // if ($user['identity']==1){
  266. // $title="镇代";
  267. // }
  268. // if ($user['identity']==2){
  269. // $title="县代";
  270. // }
  271. // if ($user['identity']==3){
  272. // $title="市代";
  273. // }
  274. // if ($user['identity']==4){
  275. // $title="商户";
  276. // }
  277. // if ($user['identity']==5){
  278. // $title="推广员";
  279. // }
  280. //
  281. // $where[] = Elm::text('identity', $title );
  282. if ($user['identity']!=0){
  283. $where[] =Elm::input('mer_rebate', "推荐商户返利");
  284. $where[] =Elm::input('promoter_rebate', "推荐代理返利");
  285. }
  286. if ($user['identity']==4){
  287. $where[] =Elm::input('agent_rebate', "推荐推广员返利");
  288. $where[] =Elm::input('cross_store', '跨店收入');
  289. }
  290. if ($user['identity']==1){
  291. $where[] =Elm::input('agent_rebate', "推荐推广员返利");
  292. // $title="镇代返利";
  293. // $where[] =Elm::input('jurisdiction', "辖区内收入");
  294. // $where[] =Elm::input('adv_fee', "广告费");
  295. $where[] =Elm::input('xqxiaofei', "自己辖区消费返利");
  296. }
  297. if ($user['identity']==2){
  298. $where[] =Elm::input('xqxiaofei', "自己辖区消费返利");
  299. $where[] =Elm::input('agent_rebate', "推荐推广员返利");
  300. $where[] =Elm::input('jurisdiction', "推荐其他区域代理费返佣:自己");
  301. $where[] =Elm::input('other_jurisdictions', "推荐其他区域代理费返佣:对应区域");
  302. }
  303. if ($user['identity']==3){
  304. $where[] =Elm::input('xqxiaofei', "自己辖区消费返利");
  305. $where[] =Elm::input('agent_rebate', "推荐推广员返利");
  306. $where[] =Elm::input('jurisdiction', "推荐其他区域代理费返佣:自己");
  307. $where[] =Elm::input('other_jurisdictions', "推荐其他区域代理费返佣:对应区域");
  308. }
  309. if ($user['identity']==5){
  310. $where[] =Elm::input('agent_rebate', "推荐推广员返利");
  311. }
  312. return Elm::createForm(Route::buildUrl('systemUserUpdate', compact('id'))->build(),$where )->setTitle('编辑')->formData($user->toArray());
  313. }
  314. /**
  315. * @param array $where
  316. * @param $page
  317. * @param $limit
  318. * @return array
  319. * @throws DataNotFoundException
  320. * @throws DbException
  321. * @throws ModelNotFoundException
  322. * @author xaboy
  323. * @day 2020-05-07
  324. */
  325. public function getAgent(array $where, $page, $limit)
  326. {
  327. //默认id排序
  328. $order = 'ua.id desc';
  329. if(isset($where['identity'])) {
  330. if ($where['identity'] == 1) {
  331. $order = 'u.identity asc';
  332. } elseif ($where['identity'] == 2) {
  333. $order = 'u.identity desc';
  334. }
  335. }
  336. $query = Db::name("user_agent")
  337. ->alias("ua")
  338. ->join("user u","u.uid=ua.user_id");
  339. if($where["keyword"]){
  340. $query = $query->whereLike("name","%".$where["keyword"]."%");
  341. }
  342. unset($where['keyword']);
  343. $list =$query->field("ua.*,u.nickname,u.avatar,u.avatar,u.brokerage_price,u.pay_count,u.spread_count,u.spread_uid")
  344. ->where($where)
  345. ->page($page, $limit)
  346. ->order($order)
  347. ->select()->toArray();
  348. $count = Db::name("user_agent")
  349. ->where($where)
  350. ->count();
  351. // $count =$query->where($where)->count();
  352. foreach($list as $k=>$value){
  353. $city['province'] = Db::name("user_province")->where(['province_id'=>$value['province_id']])->value("province_name");
  354. $city['city'] = Db::name("user_city")->where(['city_id'=>$value['city_id']])->value("city_name");
  355. $city['area'] = Db::name("user_area")->where(['area_id'=>$value['area_id']])->value("area_name");
  356. $city['street'] = Db::name("user_street")->where(['street_id'=>$value['street_id']])->value("street_name");
  357. $list[$k]['city'] = $city;
  358. }
  359. return compact('count', 'list');
  360. }
  361. /**
  362. * @param array $where
  363. * @param $page
  364. * @param $limit
  365. * @return array
  366. * @throws DataNotFoundException
  367. * @throws DbException
  368. * @throws ModelNotFoundException
  369. * @author xaboy
  370. * @day 2020-05-07
  371. */
  372. public function getAgentList(array $where, $page, $limit)
  373. {
  374. $wheres=[];
  375. $wheres['identity'] = [1,2,3,5,6];
  376. if($where["identity"]){
  377. $wheres["identity"]= $where['identity'];
  378. }
  379. $query =Db::name("user")->where($wheres);
  380. if($where["keyword"]){
  381. $query =$query->whereLike("account","%".$where['keyword']."%");
  382. }
  383. $list = $query ->field("account,uid,nickname,avatar,avatar,brokerage_price,pay_count,spread_count,spread_uid,identity")
  384. ->page($page, $limit)
  385. ->order("uid desc")
  386. ->select()->toArray();
  387. foreach($list as $k=>$value){
  388. $lis = Db::name("user")->where(['uid'=>$value['spread_uid']])->field("uid,account")->find();
  389. $list[$k]['spread'] =$lis;
  390. }
  391. $count_query = Db::name("user")->where($wheres);
  392. if($where["keyword"]){
  393. $count_query =$count_query->whereLike("account","%".$where['keyword']."%");
  394. }
  395. $count = $count_query->count();
  396. $wheres2=[];
  397. if ($where['keyword']){
  398. $wheres2[]=["account","like","%".$where['keyword']."%"];
  399. }
  400. $count1 = Db::name("user")->where($wheres2)->where("identity", 1 )->count();
  401. $count2 = Db::name("user")->where($wheres2)->where("identity", 2 )->count();
  402. $count3 = Db::name("user")->where($wheres2)->where("identity", 3 )->count();
  403. $count5 = Db::name("user")->where($wheres2)->where("identity", 5 )->count();
  404. $sart=[
  405. ['className'=> 'el-icon-s-goods', 'count'=>$count1, 'field'=>'人', 'name'=> '镇级服务商' ], [ 'className'=> 'el-icon-s-goods', 'count'=>$count2, 'field'=> '人', 'name'=>'县级服务商'], [ 'className'=> 'el-icon-s-order', 'count'=> $count3, 'field'=> '人', 'name'=> '市级服务商' ], [ 'className'=> 'el-icon-s-order', 'count'=> $count5, 'field'=> '人', 'name'=> '推广员' ]];
  406. // [{ 'className': 'el-icon-s-goods', 'count': '21.00', 'field': '元', 'name': '总支付金额' }, { 'className': 'el-icon-s-goods', 'count': '0.00', 'field': '元', 'name': '服务商返利' }, { 'className': 'el-icon-s-order', 'count': '3.24', 'field': '元', 'name': '养老金' }]
  407. return compact('count', 'list','sart','wheres');
  408. }
  409. public function getList(array $where, $page, $limit)
  410. {
  411. if (!empty($where['zero_line_uid'])) {
  412. $sql = "select getUserLevelId({$where['zero_line_uid']}) as uids";
  413. //\think\facade\Log::info("lplpDB".$sql);
  414. try {
  415. $spread_user_list = Db::query($sql);
  416. } catch (\Exception $exception) {
  417. $spread_user_list = '';
  418. }
  419. $spread_user_list = explode(",", trim($spread_user_list[0]['uids'], '$,'));
  420. $where['uid'] = $spread_user_list;
  421. }
  422. unset($where['zero_line_uid']);
  423. if(isset($where['user_card']) && $where['user_card'] !=''){
  424. $user_card = $where['user_card'];
  425. $query = $this->dao->search($where)->with(['spread' => function ($query) {
  426. $query->field('uid,account');
  427. }, 'group','certification' => function ($query) use ($user_card){
  428. $query->whereLike('user_card', "%".$user_card."%");
  429. }]);
  430. }else{
  431. $query = $this->dao->search($where)->with(['spread' => function ($query) {
  432. $query->field('uid,account');
  433. }, 'group','certification']);
  434. }
  435. $make = app()->make(UserLabelRepository::class);
  436. $count = $query->count('User.uid');
  437. $list = $query->page($page, $limit)->order("uid desc")->select()
  438. ->each(function ($item) use ($make) {
  439. $item->gzcAmount = 0;
  440. $item['lx'] = '';
  441. $vip = Db::name('da_cang_user') -> where('uid',$item['uid']) -> where('status',1) -> where('end_time','>',time())->value('type');
  442. if($vip == 1){
  443. $item['lx'] .= '【金卡会员】';
  444. }elseif ($vip == 2){
  445. $item['lx'] .= '【银卡会员】';
  446. }
  447. $channel = Db::name('channel_user') -> where('uid',$item['uid']) -> where('status',1) -> field('id') -> find();
  448. if($channel){
  449. $item['lx'] .= '【渠道商】';
  450. }
  451. //上级身份是否商户
  452. $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$item['uid'])->find();
  453. $is_shanghu2=Db::name('merchant')->where('uid',$item['uid'])->find();
  454. $is_shanghu3=Db::name('merchant_intention')->where('uid',$item['uid'])->find();
  455. if($is_shanghu1||$is_shanghu2||$is_shanghu3){
  456. $item['lx'] .= '【商户】';
  457. }
  458. if(empty($item['lx'])){
  459. $item['lx'] = '普通用户';
  460. }
  461. // try {
  462. // $certification = Db::name('user_certification')
  463. // ->where('uid', $item->uid)
  464. // ->find();
  465. // if ($certification) {
  466. // $response = $this->checkAmount($certification);
  467. // $item->gzcAmount = $response['amount'];
  468. // }
  469. // } catch (\Throwable $w) {
  470. // $item->gzcAmount = 0;
  471. // }
  472. $item->label = count($item['label_id']) ? $make->labels($item['label_id']) : [];
  473. $user_rich=Db::name('user_rich')->where('uid', $item['uid'])->find();
  474. $item->is_huitian = (isset($user_rich) && $user_rich['is_huitian']==1)?true:false;
  475. $item->user_rich_type= (isset($user_rich) )?$user_rich['type']:0;
  476. $item->stockholder= (isset($user_rich) )?$user_rich['stockholder']:0;
  477. // $area_manage_type=Db::name('area_manage')->where('uid', $item['uid'])->value('type');
  478. //类型 district-区/县代 city-市代',
  479. $item->area_manage_type=$item['user_group'];
  480. $item->user_rich=$user_rich;
  481. $item->enterprise_user=Db::name('enterprise_user')->where('uid', $item['uid'])->select();
  482. foreach ($item->enterprise_user as $k=>$v){
  483. $p_phone=Db::name('user')->where('uid', $v['puid'])->value('phone');
  484. $v['p_phone']=$p_phone?$p_phone:'';
  485. $item->enterprise_user[$k]=$v;
  486. }
  487. return $item;
  488. });
  489. return compact('count', 'list');
  490. }
  491. public function getonePromoter(array $where){
  492. $data =Db::name("user_agent")
  493. ->where($where)
  494. ->find();
  495. $city['province'] = Db::name("user_province")->where(['province_id'=>$data['province_id']])->value("province_name");
  496. $city['city'] = Db::name("user_city")->where(['city_id'=>$data['city_id']])->value("city_name");
  497. $city['area'] = Db::name("user_area")->where(['area_id'=>$data['area_id']])->value("area_name");
  498. $city['street'] = Db::name("user_street")->where(['street_id'=>$data['street_id']])->value("street_name");
  499. $data['city'] = $city;
  500. return $data;
  501. }
  502. /*代理申请线下支付
  503. @cabbage
  504. */
  505. public function xianPayAgent($id,$mark=''){
  506. $user_agent=Db::name("user_agent")->where("id",$id)->order("add_time")->find();
  507. if(!$user_agent){
  508. return ['code'=>400,'msg'=>'信息有误'];
  509. }
  510. $agent_order = [
  511. 'type'=>4,
  512. 'price'=>$user_agent['price'],
  513. 'link_id'=>$user_agent['id'],
  514. 'identity'=>$user_agent['identity'],
  515. 'uid'=>$user_agent['user_id'],
  516. 'order_sn'=>(app()->make(AgentOrderRepository::class))->getNewOrderId("DL"),
  517. 'create_time'=>date('Y-m-d H:i:s'),
  518. 'mark'=>$mark
  519. ];
  520. $agentOrder = Db::name("agent_order")->insertGetId($agent_order);
  521. //支付成功回调状态
  522. return (app()->make(AgentOrderRepository::class))->paySuccess($agentOrder);
  523. }
  524. public function updateAgent(array $where,$id){
  525. $user_agent=Db::name("user_agent")->where("id",$id)->order("add_time")->find();
  526. //审核通过
  527. if ($where['status']==1){
  528. $user= Db::name("user")->where(['uid'=>$user_agent['user_id']])->value("identity");
  529. if($user['identity']==4){
  530. return ['code'=>400,'msg'=>'该用户已是商家,请拒绝'];
  531. }
  532. try{
  533. //判断所申请的区域下是否有代理,查询需要支付的代理费用
  534. if($user_agent['identity'] == 1){
  535. if(Db::name("user_street")->where("street_id",$user_agent['street_id'])->value("uid")){
  536. return ['code'=>400,'msg'=>'该区域下已有代理'];
  537. }
  538. $where_config['config_key'] = "agency_fee_zhen" ;
  539. }elseif($user_agent['identity'] == 2){
  540. if(Db::name("user_area")->where("area_id",$user_agent['area_id'])->value("uid")){
  541. return ['code'=>400,'msg'=>'该区域下已有代理'];
  542. }
  543. $where_config['config_key'] = "agency_fee_xian" ;
  544. }elseif($user_agent['identity'] == 3){
  545. if(Db::name("user_city")->where("city_id",$user_agent['city_id'])->value("uid")){
  546. return ['code'=>400,'msg'=>'该区域下已有代理'];
  547. }
  548. $where_config['config_key'] = "agency_fee_shi" ;
  549. }elseif($user_agent['identity'] == 5){
  550. $where_config['config_key'] = "agency_fee_tui" ;
  551. }elseif ($user_agent['identity'] == 6){
  552. $where_config['config_key'] = "agency_fee_qudao" ;
  553. }
  554. $config = Db::name("system_config_value")->where($where_config)->field("value")->find();
  555. $price = str_replace('"','',$config['value']);
  556. $price = (float)$price;
  557. Db::name("user_agent")->where("id",$id)->update(["status"=>1,"update_time"=>time(),'price'=>$price]);//修改申请信息
  558. //支付金额为0,直接创建成功记录
  559. if($price <= 0){
  560. $agent_order = [
  561. 'type'=>1,
  562. 'price'=>$price,
  563. 'link_id'=>$user_agent['id'],
  564. 'identity'=>$user_agent['identity'],
  565. 'uid'=>$user_agent['user_id'],
  566. 'order_sn'=>(app()->make(AgentOrderRepository::class))->getNewOrderId("DL"),
  567. 'create_time'=>date('Y-m-d H:i:s'),
  568. ];
  569. $agentOrder = Db::name("agent_order")->insertGetId($agent_order);
  570. //支付成功回调状态
  571. (app()->make(AgentOrderRepository::class))->paySuccess($agentOrder);
  572. }
  573. }catch (Exception $e) {
  574. Db::rollback();
  575. }
  576. }
  577. //审核拒绝
  578. if ($where['status']==2){
  579. $data['promoter_time'] = date('Y-m-d H:i:s');
  580. $data['identity']=0;
  581. $data['is_promoter']=0;
  582. Db::name("user")->where("uid",$user_agent["user_id"])->update($data);
  583. Db::name("user_agent")->where("id",$id)->update(["status"=>2,"update_time"=>time(),'pay_status'=>2]);
  584. }
  585. // if ($where['status']==2){
  586. // unset($data['is_promoter'],$data['promoter_time']);
  587. // Db::name("user_agent")->where("user_id",$id)->update(["status"=>2,"update_time"=>time()]);
  588. // }
  589. return true;
  590. }
  591. /**
  592. * 推广员推广成功获得佣金
  593. * @param $order
  594. */
  595. public function promoters($user_agent){
  596. //客户本人
  597. $order_user=Db::name("user")->where("uid",$user_agent["user_id"])->find();
  598. if ($user_agent["pid"]>0){
  599. //推广的人的信息
  600. $spread_identity=Db::name("user")->where("uid",$user_agent["pid"])->field("identity,agent_fee")->find();
  601. if ($spread_identity["identity"]>0){
  602. if (($spread_identity["identity"]!=2||$spread_identity["identity"]!=3)&&($order_user["county_agent"]==$user_agent["pid"])){
  603. $agent_fee=bcdiv($spread_identity["agent_fee"],100);
  604. $spread_fee=bcmul($user_agent["price"],$agent_fee) ;
  605. $title="代理费佣金";
  606. $mark ="获得代理费佣金".$spread_identity["agent_fee"]."%";
  607. $commission_type="1";
  608. $this->add_bill($title,$spread_fee,$user_agent["pid"],$mark,$commission_type,$order_user["agent_sn"]);
  609. }
  610. //用户本人的县代与当前推广的县代不一致(跨区域推广)
  611. if ($spread_identity["identity"]==2&&$order_user["county_agent"]!=$user_agent["pid"]&&$order_user["county_agent"]>0){
  612. //跨辖区用户对应推荐人佣金
  613. $agent_feezj=bcdiv($spread_identity["agent_fee3"],100);
  614. $agent_feezj=bcmul($user_agent["price"],$agent_feezj) ;
  615. $title="代理费佣金";
  616. $mark ="获得代理费佣金".$spread_identity["agent_fee3"]."%";
  617. $commission_type="1";
  618. $this->add_bill($title,$agent_feezj,$user_agent["pid"],$mark,$commission_type,$order_user["agent_sn"]);
  619. //跨辖区用户对应辖区佣金
  620. $spread_identity=Db::name("user")->where("uid",$order_user["county_agent"])->field("identity,agent_fee2")->find();
  621. $agent_fee=bcdiv($spread_identity["agent_fee2"],100);
  622. $spread_fee=bcmul($user_agent["price"],$agent_fee) ;
  623. $title="代理费佣金";
  624. $mark ="其他区域推荐代理费返佣".$spread_identity["agent_fee2"]."%";
  625. $commission_type="1";
  626. $this->add_bill($title,$spread_fee,$order_user["county_agent"],$mark,$commission_type,$order_user["agent_sn"]);
  627. }
  628. //用户本人的市代与当前推广的市代不一致(跨区域推广)
  629. if ($spread_identity["identity"]==3&&$order_user["city_agent"]!=$user_agent["pid"]&&$order_user["city_agent"]>0){
  630. //跨辖区用户对应推荐人佣金
  631. $agent_feezj=bcdiv($spread_identity["agent_fee3"],100);
  632. $agent_feezj=bcmul($user_agent["price"],$agent_feezj) ;
  633. $title="代理费佣金";
  634. $mark ="获得代理费佣金".$spread_identity["agent_fee3"]."%";
  635. $commission_type="1";
  636. $this->add_bill($title,$agent_feezj,$user_agent["pid"],$mark,$commission_type,$order_user["agent_sn"]);
  637. //跨辖区用户对应辖区佣金
  638. $spread_identity=Db::name("user")->where("uid",$order_user["county_agent"])->field("identity,agent_fee2")->find();
  639. $agent_fee=bcdiv($spread_identity["agent_fee2"],100);
  640. $spread_fee=bcmul($user_agent["price"],$agent_fee) ;
  641. $title="代理费佣金";
  642. $mark ="其他区域推荐代理费返佣".$spread_identity["agent_fee2"]."%";
  643. $commission_type="1";
  644. $this->add_bill($title,$spread_fee,$order_user["county_agent"],$mark,$commission_type,$order_user["agent_sn"]);
  645. }
  646. }
  647. }
  648. }
  649. /**
  650. * 佣金加入账单
  651. * @param $title
  652. * @param $number
  653. * @param $uid
  654. * @param $mark
  655. * @param $commission_type
  656. * @param $order_sn
  657. */
  658. public function add_bill($title,$number,$uid,$mark,$commission_type,$order_sn,$order_id=0){
  659. // $old_number=Db::name("user")->where("uid",$uid)->value("brokerage_price");
  660. $data=[
  661. 'link_id' => $order_id,
  662. "uid"=>$uid,
  663. // "pm"=>1,
  664. "title"=>$title,
  665. "category"=>"now_money",
  666. "type"=>"commission",
  667. "number"=>$number,
  668. "balance"=>0,
  669. "mark"=>$mark,
  670. "create_time"=>time(),
  671. "status"=>0,
  672. "commission_type"=>$commission_type,
  673. "order_sn"=>$order_sn,
  674. ];
  675. Db::name("user_bill")->insert($data);
  676. // Db::name("user")->where("uid",$uid)->inc('brokerage_price', $number) ->update();
  677. }
  678. public function merList(string $keyword, $page, $limit)
  679. {
  680. $query = $this->dao->searchMerUser($keyword);
  681. $count = $query->count($this->dao->getPk());
  682. $list = $query->page($page, $limit)->setOption('field', [])->field('uid,nickname,avatar,user_type,sex')->select();
  683. return compact('count', 'list');
  684. }
  685. /**
  686. * @param $id
  687. * @return Form
  688. * @throws DataNotFoundException
  689. * @throws DbException
  690. * @throws ModelNotFoundException
  691. * @throws FormBuilderException
  692. * @author xaboy
  693. * @day 2020-05-07
  694. */
  695. public function changeGroupForm($id)
  696. {
  697. $isArray = is_array($id);
  698. if (!$isArray)
  699. $user = $this->dao->get($id);
  700. /** @var UserGroupRepository $make */
  701. $data = app()->make(UserGroupRepository::class)->allOptions();
  702. return Elm::createForm(Route::buildUrl($isArray ? 'systemUserBatchChangeGroup' : 'systemUserChangeGroup', $isArray ? [] : compact('id'))->build(), [
  703. Elm::hidden('ids', $isArray ? $id : [$id]),
  704. Elm::select('group_id', '用户分组', $isArray ? '' : $user->group_id)->options(function () use ($data) {
  705. $options = [['label' => '不设置', 'value' => '0']];
  706. foreach ($data as $value => $label) {
  707. $options[] = compact('value', 'label');
  708. }
  709. return $options;
  710. })
  711. ])->setTitle('修改用户分组');
  712. }
  713. /**
  714. * @param $id
  715. * @return Form
  716. * @throws DataNotFoundException
  717. * @throws DbException
  718. * @throws ModelNotFoundException
  719. * @throws FormBuilderException
  720. * @author xaboy
  721. * @day 2020-05-07
  722. */
  723. public function changeLabelForm($id)
  724. {
  725. $isArray = is_array($id);
  726. if (!$isArray)
  727. $user = $this->dao->get($id);
  728. /** @var UserLabelRepository $make */
  729. $data = app()->make(UserLabelRepository::class)->allOptions();
  730. return Elm::createForm(Route::buildUrl($isArray ? 'systemUserBatchChangeLabel' : 'systemUserChangeLabel', $isArray ? [] : compact('id'))->build(), [
  731. Elm::hidden('ids', $isArray ? $id : [$id]),
  732. Elm::selectMultiple('label_id', '用户标签', $isArray ? [] : $user->label_id)->options(function () use ($data) {
  733. $options = [];
  734. foreach ($data as $value => $label) {
  735. $value = (string)$value;
  736. $options[] = compact('value', 'label');
  737. }
  738. return $options;
  739. })
  740. ])->setTitle('修改用户分组');
  741. }
  742. /**
  743. * @param $id
  744. * @return Form
  745. * @throws FormBuilderException
  746. * @author xaboy
  747. * @day 2020-05-07
  748. */
  749. public function changeNowMoneyForm($id)
  750. {
  751. return Elm::createForm(Route::buildUrl('systemUserChangeNowMoney', compact('id'))->build(), [
  752. Elm::radio('type', '修改余额', 1)->options([
  753. ['label' => '增加', 'value' => 1],
  754. ['label' => '减少', 'value' => 0],
  755. ])->required(),
  756. Elm::number('now_money', '金额')->required()->min(0)
  757. ])->setTitle('修改用户余额');
  758. }
  759. /**
  760. * @param $id
  761. * @return Form
  762. * @throws FormBuilderException
  763. * @author xaboy
  764. * @day 2020-05-07
  765. */
  766. public function changeProForm($id)
  767. {
  768. $spreadId = Db::name('user')->where('uid', $id)->value('spread_uid');
  769. if ($spreadId) {
  770. $spread_message = Db::name('user')->where('uid', $spreadId)->field('uid,account,nickname')->findOrEmpty();
  771. } else {
  772. $spread_message = ['uid' => null, 'account' => '无推荐人', 'nickname' => '无推荐人'];
  773. }
  774. return Elm::createForm(Route::buildUrl('systemUserChangePro', compact('id'))->build(), [
  775. Elm::input('spread_account_old', '原推荐人')->value($spread_message['account'].'('.$spread_message['nickname'].')')->disabled(true),
  776. Elm::input('spread_account', '推荐人')->required()->placeholder("请填写推荐人手机号")
  777. ])->setTitle('修改用户推荐人');
  778. }
  779. /**
  780. * @param $id
  781. * @return Form
  782. * @throws FormBuilderException
  783. * @author xaboy
  784. * @day 2020-05-07
  785. */
  786. public function changeProFormLevel($id)
  787. {
  788. $levelId = Db::name('user')->where('uid', $id)->value('level_id');
  789. if ($levelId) {
  790. $level_message = Db::name('user')->where('uid', $levelId)->field('uid,account,nickname')->findOrEmpty();
  791. } else {
  792. $level_message = ['uid' => null, 'account' => '无节点人', 'nickname' => '无节点人'];
  793. }
  794. return Elm::createForm(Route::buildUrl('systemUserChangeLevelPro', compact('id'))->build(), [
  795. Elm::input('spread_account_old', '原推荐人')->value($level_message['account'].'('.$level_message['nickname'].')')->disabled(true),
  796. Elm::input('level_account', '节点人(上级)')->required()->placeholder("请填写节点人(上级)手机号")
  797. ])->setTitle('修改用户节点人(上级)');
  798. }
  799. public function changeProFormGroup($id)
  800. {
  801. return Elm::createForm(Route::buildUrl('systemUserChangeusergroupPro', compact('id'))->build(), [
  802. Elm::input('group_id', '新的用户身份')->required()->placeholder("请填写新的用户身份")
  803. ],[Elm::input('mark', '备注')->placeholder("请填写备注信息")])->setTitle('修改用户身份');
  804. }
  805. /**
  806. * @param $id
  807. * @return Form
  808. * @throws FormBuilderException
  809. * @author xaboy
  810. * @day 2020-05-07
  811. */
  812. public function changeAwardForm($id)
  813. {
  814. $user = $this->dao->get($id);
  815. return Elm::createForm(Route::buildUrl('systemUserChangeAward', compact('id'))->build(), [
  816. Elm::text('account','账号',$user['account'])->disabled(true),
  817. Elm::radio('type','类型',1)->options([
  818. ['label' => 'PV', 'value' => 1],
  819. ['label' => '积分', 'value' => 2],
  820. ['label' => '直推佣金', 'value' => 3],
  821. ['label' => '复购金', 'value' => 4],
  822. ['label' => '红包', 'value' => 5],
  823. ['label' => '锁客收益', 'value' => 6],
  824. ['label' => '推广店铺收益', 'value' => 7],
  825. ['label' => '贡献值', 'value' => 8],
  826. ['label' => 'VR', 'value' => 9],
  827. ['label' => '京豆', 'value' => 10],
  828. ['label' => '养老金', 'value' => 11],
  829. ['label' => '股权分红', 'value' => 12],
  830. ['label' => '联创分红', 'value' => 13],
  831. ['label' => '合伙人分红', 'value' => 14],
  832. ['label' => '直推贡献值', 'value' => 15],]),
  833. Elm::radio('award_type','奖励变更',1)->options([['label' => '增加', 'value' => 1], ['label' => '减少', 'value' => 2]]),
  834. Elm::number('num', '变动金额')->size('large')->required(),
  835. Elm::text('admin_id','操作人','管理员')->disabled(true),
  836. Elm::text('scene','操作场景','后台操作')->disabled(true),
  837. Elm::textarea('mark','备注')
  838. ])->setTitle('奖励变更');
  839. }
  840. /**
  841. *
  842. * @param $uid
  843. * @param $spread_account
  844. * @return false|int|void
  845. * @throws DataNotFoundException
  846. * @throws DbException
  847. * @throws ModelNotFoundException
  848. */
  849. public function changeAward($id,$type,$award_type,$num,$mark,$admin_id){
  850. $user = $this->dao->get($id);
  851. Db::transaction(function () use ($award_type, $user, $type, $num ,$mark,$admin_id) {
  852. $commission_type = 0;
  853. switch ($type){
  854. // PV
  855. case 1:
  856. if($award_type == 1){
  857. // 增加
  858. $isert_data = [
  859. 'uid' => $user['uid'],
  860. 'pv' => $num,
  861. 'status' => 1,
  862. 'addtime' => time(),
  863. 'mark' => empty($mark) ?'管理员调整pv值' : $mark,
  864. 'settlement_time' => date('Y-m-d H:i:s'),
  865. ];
  866. Db::name('user_pv_log')->insert($isert_data);
  867. Db::name('user')->where('uid',$user['uid'])->inc('pv', $num)->update();
  868. }else{
  869. // 减少
  870. Db::name('user')->where('uid',$user['uid'])->dec('pv', $num)->update();
  871. }
  872. break;
  873. // 积分
  874. case 2:
  875. $isert_data = [
  876. 'uid' => $user['uid'],
  877. 'reward_socre' => $num,
  878. 'status' => 1,
  879. 'mark' => empty($mark) ?'管理员调整积分' : $mark ,
  880. 'addtime' => time(),
  881. 'surplus' => $user['score'],
  882. 'settlement_time' => date('Y-m-d H:i:s'),
  883. ];
  884. if($award_type == 1){
  885. // 增加
  886. $isert_data['pm'] = 1;
  887. Db::name('user')->where('uid',$user['uid'])->inc('score', $num)->update();
  888. }else{
  889. // 减少
  890. $isert_data['pm'] = 2;
  891. Db::name('user')->where('uid',$user['uid'])->dec('score', $num)->update();
  892. }
  893. Db::name('user_sign_score')->insert($isert_data);
  894. break;
  895. // 复购金
  896. case 4:
  897. $isert_data = [
  898. 'uid' => $user['uid'],
  899. 'number' => $num,
  900. 'status' => 1,
  901. 'mark' => empty($mark) ?'管理员调整复购金' :$mark ,
  902. 'addtime' => time(),
  903. 'surplus' => $user['fugou'],
  904. 'settlement_time' => date('Y-m-d H:i:s'),
  905. ];
  906. if($award_type == 1){
  907. // 增加
  908. $isert_data['type'] = 1;
  909. Db::name('user')->where('uid',$user['uid'])->inc('fugou', $num)->update();
  910. }else{
  911. // 减少
  912. $isert_data['type'] = 2;
  913. Db::name('user')->where('uid',$user['uid'])->dec('fugou', $num)->update();
  914. }
  915. Db::name('user_sign_fugou')->insert($isert_data);
  916. break;
  917. // 红包
  918. case 5:
  919. $isert_data = [
  920. 'uid' => $user['uid'],
  921. 'number' => $num,
  922. 'status' => 1,
  923. 'mark' => empty($mark) ?'管理员调整红包':$mark ,
  924. 'addtime' => time(),
  925. 'surplus' => $user['hongbao'],
  926. 'settlement_time' => date('Y-m-d H:i:s'),
  927. ];
  928. if($award_type == 1){
  929. // 增加
  930. $isert_data['type'] = 1;
  931. Db::name('user')->where('uid',$user['uid'])->inc('hongbao', $num)->update();
  932. }else{
  933. // 减少
  934. $isert_data['type'] = 2;
  935. Db::name('user')->where('uid',$user['uid'])->dec('hongbao', $num)->update();
  936. }
  937. Db::name('user_sign_hongbao')->insert($isert_data);
  938. break;
  939. // 贡献值
  940. case 8:
  941. $isert_data = [
  942. 'uid' => $user['uid'],
  943. 'number' => $num,
  944. 'status' => 1,
  945. 'mark' => empty($mark) ?'管理员调整贡献值':$mark ,
  946. 'addtime' => time(),
  947. 'surplus' => $user['contribute'],
  948. 'settlement_time' => date('Y-m-d H:i:s'),
  949. ];
  950. if($award_type == 1){
  951. // 增加
  952. $isert_data['type'] = 1;
  953. Db::name('user')->where('uid',$user['uid'])->inc('contribute', $num)->update();
  954. }else{
  955. // 减少
  956. $isert_data['type'] = 2;
  957. Db::name('user')->where('uid',$user['uid'])->dec('contribute', $num)->update();
  958. }
  959. Db::name('user_sign_gongxian')->insert($isert_data);
  960. break;
  961. // vr
  962. case 9:
  963. $isert_data = [
  964. 'uid' => $user['uid'],
  965. 'number' => $num,
  966. 'mark' => empty($mark) ?'管理员调整vr':$mark ,
  967. 'addtime' => time(),
  968. 'surplus' => $user['vr'],
  969. 'settlement_time' => date('Y-m-d H:i:s'),
  970. ];
  971. if($award_type == 1){
  972. // 增加
  973. $isert_data['type'] = 1;
  974. Db::name('user')->where('uid',$user['uid'])->inc('vr', $num)->update();
  975. }else{
  976. // 减少
  977. $isert_data['type'] = 2;
  978. Db::name('user')->where('uid',$user['uid'])->dec('vr', $num)->update();
  979. }
  980. Db::name('user_sign_vr')->insert($isert_data);
  981. break;
  982. // 京豆
  983. case 10:
  984. $isert_data = [
  985. 'uid' => $user['uid'],
  986. 'number' => $num,
  987. 'status' => 1,
  988. 'mark' => empty($mark) ?'管理员调整京豆':$mark ,
  989. 'addtime' => time(),
  990. 'surplus' => $user['jingdou'],
  991. 'settlement_time' => date('Y-m-d H:i:s'),
  992. ];
  993. if($award_type == 1){
  994. // 增加
  995. $isert_data['type'] = 1;
  996. Db::name('user')->where('uid',$user['uid'])->inc('jingdou', $num)->update();
  997. }else{
  998. // 减少
  999. $isert_data['type'] = 2;
  1000. Db::name('user')->where('uid',$user['uid'])->dec('jingdou', $num)->update();
  1001. }
  1002. Db::name('user_sign_jingdou')->insert($isert_data);
  1003. break;
  1004. // 直推佣金
  1005. case 3:
  1006. $commission_type = 3;
  1007. // 锁客收益
  1008. case 6:
  1009. $commission_type = 7;
  1010. break;
  1011. // 推广店铺收益
  1012. case 7:
  1013. $commission_type = 10;
  1014. break;
  1015. // 养老金
  1016. case 11:
  1017. $commission_type = 5;
  1018. break;
  1019. // 股权分红
  1020. case 12:
  1021. $commission_type = 13;
  1022. break;
  1023. // 联创分红
  1024. case 13:
  1025. $commission_type = 12;
  1026. break;
  1027. // 合伙人分红
  1028. case 14:
  1029. $commission_type = 11;
  1030. break;
  1031. // 直推贡献值
  1032. case 15:
  1033. $isert_data = [
  1034. 'uid' => $user['uid'],
  1035. 'number' => $num,
  1036. 'status' => 1,
  1037. 'mark' => empty($mark) ?'管理员调整直推贡献值':$mark ,
  1038. 'addtime' => time(),
  1039. 'surplus' => $user['contribute'],
  1040. 'settlement_time' => date('Y-m-d H:i:s'),
  1041. ];
  1042. if($award_type == 1){
  1043. // 增加
  1044. $isert_data['type'] = 1;
  1045. Db::name('user')->where('uid',$user['uid'])->inc('per_contribute', $num)->update();
  1046. }else{
  1047. // 减少
  1048. $isert_data['type'] = 2;
  1049. Db::name('user')->where('uid',$user['uid'])->dec('per_contribute', $num)->update();
  1050. }
  1051. Db::name('user_sign_gongxian')->insert($isert_data);
  1052. break;
  1053. }
  1054. if($commission_type){
  1055. $isert_data = [
  1056. 'uid' => $user['uid'],
  1057. 'number' => $num,
  1058. 'status' => 1,
  1059. 'commission_type' => $commission_type,
  1060. 'mark' => empty($mark) ?'管理员调整收益':$mark ,
  1061. 'create_time' => date('Y-m-d H:i:s'),
  1062. 'take_time' => time()
  1063. ];
  1064. if($commission_type != 5){
  1065. $isert_data['balance'] = $user['brokerage_price'];
  1066. if($award_type == 1){
  1067. // 增加
  1068. $isert_data['pm'] = 1;
  1069. Db::name('user')->where('uid',$user['uid'])->inc('brokerage_price', $num)->update();
  1070. }else{
  1071. // 减少
  1072. $isert_data['pm'] = 0;
  1073. Db::name('user')->where('uid',$user['uid'])->dec('brokerage_price', $num)->update();
  1074. }
  1075. }else{
  1076. $isert_data['balance'] = $user['annuity'];
  1077. if($award_type == 1){
  1078. // 增加
  1079. $isert_data['pm'] = 1;
  1080. $isert_data['gzc'] = 1;
  1081. Db::name('user')->where('uid',$user['uid'])->inc('annuity', $num)->update();
  1082. }else{
  1083. // 减少
  1084. $isert_data['pm'] = 0;
  1085. Db::name('user')->where('uid',$user['uid'])->dec('annuity', $num)->update();
  1086. }
  1087. }
  1088. Db::name('user_bill')->insert($isert_data);
  1089. }
  1090. if ($commission_type == 5 && $award_type == 1) {
  1091. $cer = Db::name('user')
  1092. ->where('uid', $user['uid'])
  1093. ->field('real_name, phone, card_id')
  1094. ->find();
  1095. $ylj_data_log = [
  1096. 'user_name' => $cer['real_name'],
  1097. "mobile" => $cer['phone'],
  1098. "user_card" => $cer['card_id'],//身份证
  1099. "pension" => $num,//养老金
  1100. "out_trade_no" => '',
  1101. "account_type" => '',
  1102. "order_type" => 0,
  1103. "pay_time" => '',
  1104. "create_time" => date('Y-m-d H:i:s'),
  1105. "update_time" => date('Y-m-d H:i:s'),
  1106. "uid" => $user['uid'],
  1107. "platform_no" => 'IN10' . (int)(microtime(true) * 1000) . mt_rand(10000, 99999),
  1108. "link_id" => ''
  1109. ];
  1110. Db::name('gzc_logs')->insert($ylj_data_log);
  1111. }
  1112. $insert_data = [
  1113. 'uid' => $user['uid'],
  1114. 'type' => $type,
  1115. 'award_type' => $award_type,
  1116. 'num' => $num,
  1117. 'admin_id' => $admin_id,
  1118. 'mark' => empty($mark) ? '管理员操作' : $mark
  1119. ];
  1120. Db::name('change_award_log')->insert($insert_data);
  1121. });
  1122. return true;
  1123. }
  1124. public function changeProForm_yhc($id,$type=0)
  1125. {
  1126. if($type===1){
  1127. return Elm::createForm(Route::buildUrl('systemUserChangePro', compact('id'))->build(), [
  1128. Elm::input('spread_account', '业绩归属人账号')->required()->placeholder("请填写业绩归属人手机号")->info('修改业绩归属人后,用户业绩归属至所填写账号下,但邀请关系及其他邀请相关的奖励不变!'),
  1129. Elm::hidden('type', '1')
  1130. ])->setTitle('修改业绩归属人');
  1131. }
  1132. return Elm::createForm(Route::buildUrl('systemUserChangePro', compact('id'))->build(), [
  1133. Elm::input('spread_account', '推荐人')->required()->placeholder("请填写推荐人手机号")
  1134. ])->setTitle('修改用户推荐人');
  1135. }
  1136. /**
  1137. * @param $id
  1138. * @param $adminId
  1139. * @param $type
  1140. * @param $nowMoney
  1141. * @throws DataNotFoundException
  1142. * @throws DbException
  1143. * @throws ModelNotFoundException
  1144. * @author xaboy
  1145. * @day 2020-05-07
  1146. */
  1147. public function changeNowMoney($id, $adminId, $type, $nowMoney)
  1148. {
  1149. $user = $this->dao->get($id);
  1150. Db::transaction(function () use ($id, $adminId, $user, $type, $nowMoney) {
  1151. $balance = $type == 1 ? bcadd($user->now_money, $nowMoney, 2) : bcsub($user->now_money, $nowMoney, 2);
  1152. $user->save(['now_money' => $balance]);
  1153. /** @var UserBillRepository $make */
  1154. $make = app()->make(UserBillRepository::class);
  1155. if ($type == 1) {
  1156. $make->incBill($id, 'now_money', 'sys_inc_money', [
  1157. 'link_id' => $adminId,
  1158. 'status' => 1,
  1159. 'title' => '系统增加余额',
  1160. 'number' => $nowMoney,
  1161. 'mark' => '系统增加了' . floatval($nowMoney) . '余额',
  1162. 'balance' => $balance
  1163. ]);
  1164. } else {
  1165. $make->decBill($id, 'now_money', 'sys_dec_money', [
  1166. 'link_id' => $adminId,
  1167. 'status' => 1,
  1168. 'title' => '系统减少余额',
  1169. 'number' => $nowMoney,
  1170. 'mark' => '系统减少了' . floatval($nowMoney) . '余额',
  1171. 'balance' => $balance
  1172. ]);
  1173. }
  1174. });
  1175. }
  1176. /**
  1177. * @param $password
  1178. * @return false|string|null
  1179. * @author xaboy
  1180. * @day 2020/6/22
  1181. */
  1182. public function encodePassword($password)
  1183. {
  1184. return password_hash($password, PASSWORD_BCRYPT);
  1185. }
  1186. /**
  1187. * @param WechatUser $wechatUser
  1188. * @return BaseDao|array|Model|null
  1189. * @throws DataNotFoundException
  1190. * @throws DbException
  1191. * @throws ModelNotFoundException
  1192. * @author xaboy
  1193. * @day 2020-04-28
  1194. */
  1195. public function syncWechatUser(WechatUser $wechatUser, $userType = 'wechat')
  1196. {
  1197. $user = $this->dao->wechatUserIdBytUser($wechatUser->wechat_user_id);
  1198. $request = request();
  1199. if ($user) {
  1200. $user->save([
  1201. 'nickname' => $wechatUser['nickname'] ?: '',
  1202. 'avatar' => $wechatUser['headimgurl'] ?: '',
  1203. 'sex' => $wechatUser['sex'] ?: 0,
  1204. 'last_time' => date('Y-m-d H:i:s'),
  1205. 'last_ip' => $request->ip(),
  1206. ]);
  1207. }
  1208. // else
  1209. // $user = $this->create($userType, [
  1210. // 'account' => 'wx' . $wechatUser->wechat_user_id . time(),
  1211. // 'wechat_user_id' => $wechatUser->wechat_user_id,
  1212. // 'pwd' => $this->encodePassword(123456),
  1213. // 'nickname' => $wechatUser['nickname'] ?: '',
  1214. // 'avatar' => $wechatUser['headimgurl'] ?: '',
  1215. // 'sex' => $wechatUser['sex'] ?: 0,
  1216. // 'spread_uid' => 0,
  1217. // 'is_promoter' => 0,
  1218. // 'last_time' => date('Y-m-d H:i:s'),
  1219. // 'last_ip' => $request->ip()
  1220. // ]);
  1221. return $user;
  1222. }
  1223. /**
  1224. * @param string $type
  1225. * @param array $userInfo
  1226. * @param int $url 推广员的ID
  1227. * @return BaseDao|Model
  1228. * @author xaboy
  1229. * @day 2020-04-28
  1230. */
  1231. public function create(string $type, array $userInfo, $url=0,$spread_uid=null)
  1232. {
  1233. $userInfo['user_type'] = $type;
  1234. Db::startTrans();
  1235. try {
  1236. $user = $this->dao->create($userInfo); //创建用户
  1237. $this -> insterUser($user->uid, $spread_uid);
  1238. //唯品会pid
  1239. // $vip = app()->make(Vip::class);
  1240. // $vip->create_pid($user->uid);
  1241. // //拼多多pid
  1242. // $taoke = app()->make(TaoKe::class);
  1243. // $taoke->generateAd($user->uid);
  1244. // //京东pid(改成京京推推就)
  1245. // $jd = app()->make(Jd::class);
  1246. // $jd->create_pid($user->uid);
  1247. //
  1248. // Queue::push(SendNewPeopleCouponJob::class, $user->uid);
  1249. //赠送积分 注册送30积分
  1250. $this->sign_add($user['uid'], 30,1,'注册送30积分','','', '', 1, '', 1);
  1251. Db::commit();
  1252. return $user;
  1253. } catch (\Exception $e) {
  1254. Log::info($userInfo);
  1255. Db::rollback();
  1256. log::info("注册失败".$e->getFile().':'.$e->getLine().'【'.$e->getMessage().'】');
  1257. throw new AuthException('注册失败');
  1258. }
  1259. }
  1260. public function getUserLevelId($spread_uid){
  1261. if (empty($spread_uid)){
  1262. return false;
  1263. }
  1264. $sql = "select getUserLevelId($spread_uid) as count";
  1265. $getUserLevelId = Db::query($sql);
  1266. $user_level_uids=ltrim($getUserLevelId[0]['count'],'$,');
  1267. return $user_level_uids;
  1268. }
  1269. public function insterUser($uid, $spread_uid){
  1270. /**
  1271. * 查询上级人数 select * from rrx_user_count LIMIT 0,1
  1272. */
  1273. // $spread_uid = Db::name('user') -> where('uid', $uid) -> value('spread_uid');
  1274. // Db::name('log')->insert(['data'=>'公排注册:'.$uid.'======'.$spread_uid]);
  1275. // $userCount = false;
  1276. // if ($spread_uid > 0){
  1277. // //找直推上级网络里面不足5人的排进去
  1278. //
  1279. // $userCount = Db::name('user_count') -> where('level_number >= 0') -> where ('uid', $spread_uid) -> find();
  1280. // if (!$userCount){
  1281. // $userCount = $this -> getCountUId($spread_uid);
  1282. // }
  1283. //
  1284. //
  1285. // }
  1286. // Log::info("userCount:::");
  1287. // Log::info($userCount);
  1288. // Log::info($spread_uid);
  1289. // Db::name('log')->insert(['data'=>'uid:'.$uid.'公排注册:'.json_encode($userCount)]);
  1290. // if (!$userCount){
  1291. // //没有直推上级 大公排
  1292. // $userCount = Db::name('user_count') -> where('level_number >= 0') -> find();
  1293. // //增加一个只查询新账户大公排下的用户
  1294. // // $userCount = Db::name('user_count') -> where('level_number >= 0')->whereIn('uid',$this->getUserLevelId(11112)) -> find();
  1295. // }
  1296. // if ($userCount) {
  1297. // if ($userCount['level_number'] + 1 == systemConfig( 'max_level_number')) { //(33制或者55制)下级最大人数systemConfig( 'max_level_number')
  1298. // Db::name('user_count') -> where('uid',$userCount['uid'])->delete();
  1299. // } else {
  1300. // $level_number = $userCount['level_number'] + 1;
  1301. // Db::name('user_count') -> where('uid',$userCount['uid']) -> update(['level_number'=>$level_number]);
  1302. // }
  1303. // }
  1304. // dd($spread_uid);
  1305. // Db::name('user') -> where('uid',$uid)->update(['level_id'=>$userCount['uid'],'level'=>$this->level()]);
  1306. // Db::name('user_count') -> insert(['uid'=>$uid]);
  1307. }
  1308. public function getCountUId($spread_uid){
  1309. if (empty($spread_uid)){
  1310. return false;
  1311. }
  1312. //查询所有下级是否满足条件
  1313. //查询所有下级uid
  1314. $level_id = Db::name('user') -> where('level_id', $spread_uid) -> field('uid') -> select()->toArray();
  1315. $level_ids = array_column($level_id,'uid');
  1316. $check_ids = Db::name('user_count') -> where('level_number >= 0') -> where ('uid','in', $level_ids) -> find();
  1317. foreach ($level_id as $value){
  1318. //查询下级是否满足条件
  1319. $check = Db::name('user_count') -> where('level_number >= 0') -> where ('uid', $value['uid']) -> find();
  1320. if ($check){
  1321. return $check;
  1322. }else if(empty($check_ids)){
  1323. $id = $this -> getCountUId($value['uid']);
  1324. if ($id){
  1325. return $id;
  1326. }
  1327. }
  1328. }
  1329. return false;
  1330. }
  1331. private function level() {
  1332. $count = Db::name('user')->where('level > 0')->count();
  1333. switch ($count) {
  1334. case 0:
  1335. return 1;
  1336. case 1:
  1337. return 2;
  1338. }
  1339. $number = ($count + 1) - floor($count / 5);
  1340. return ceil(log($number) / log(5)) + 1;
  1341. }
  1342. /**
  1343. * @param User $user
  1344. * @return array
  1345. * @author xaboy
  1346. * @day 2020-04-29
  1347. */
  1348. public function createToken(User $user)
  1349. {
  1350. $service = new JwtTokenService();
  1351. $token = $service->createToken($user->uid, 'user');
  1352. $this->cacheToken($token['token'], $token['out'],$user->uid);
  1353. if($user -> user_number == ''){
  1354. $this -> createUserNumber($user->uid);
  1355. }
  1356. // if($user -> im == 0 && env('im',false)){
  1357. // $im = new Im();
  1358. // $im -> createIm($user -> account,$user -> user_number);
  1359. // }
  1360. return $token;
  1361. }
  1362. /**
  1363. * //TODO 登录成功后
  1364. * @param User $user
  1365. * @author xaboy
  1366. * @day 2020/6/22
  1367. */
  1368. public function loginAfter(User $user)
  1369. {
  1370. $user->last_time = date('Y-m-d H:i:s', time());
  1371. $user->last_ip = request()->ip();
  1372. $user->save();
  1373. }
  1374. /**
  1375. * @param string $token
  1376. * @param int $exp
  1377. * @author xaboy
  1378. * @day 2020-04-29
  1379. */
  1380. public function cacheToken(string $token, int $exp,$uid)
  1381. {
  1382. Cache::set('user_' . $token, time() + $exp, $exp);
  1383. Cache::set('java_' . $token, $uid, $exp);
  1384. }
  1385. /**
  1386. * @param string $token
  1387. * @author xaboy
  1388. * @day 2020-04-29
  1389. */
  1390. public function checkToken(string $token)
  1391. {
  1392. $has = Cache::has('user_' . $token);
  1393. if (!$has)
  1394. throw new AuthException('无效的token');
  1395. $lastTime = Cache::get('user_' . $token);
  1396. if (($lastTime + intval(Config::get('admin.token_valid_exp', 15)) * 60) < time())
  1397. throw new AuthException('token 已过期');
  1398. }
  1399. /**
  1400. * @param string $token
  1401. * @author xaboy
  1402. * @day 2020-04-29
  1403. */
  1404. public function updateToken(string $token)
  1405. {
  1406. Cache::set('user_' . $token, time(), intval(Config::get('admin.token_valid_exp', 15)) * 60);
  1407. }
  1408. /**
  1409. * @param string $token
  1410. * @author xaboy
  1411. * @day 2020-04-29
  1412. */
  1413. public function clearToken(string $token)
  1414. {
  1415. Cache::delete('user_' . $token);
  1416. }
  1417. /**
  1418. * @param string $key
  1419. * @param string $code
  1420. * @author xaboy
  1421. * @day 2020/6/1
  1422. */
  1423. public function checkCode(string $key, string $code)
  1424. {
  1425. $_code = Cache::get('am_captcha' . $key);
  1426. if (!$_code) {
  1427. throw new ValidateException('验证码过期');
  1428. }
  1429. if (strtolower($_code) != strtolower($code)) {
  1430. throw new ValidateException('验证码错误');
  1431. }
  1432. //删除code
  1433. Cache::delete('am_captcha' . $key);
  1434. }
  1435. /**
  1436. * @param string $code
  1437. * @return string
  1438. * @author xaboy
  1439. * @day 2020/6/1
  1440. */
  1441. public function createLoginKey(string $code)
  1442. {
  1443. $key = uniqid(microtime(true), true);
  1444. Cache::set('am_captcha' . $key, $code, Config::get('admin.captcha_exp', 5) * 60);
  1445. return $key;
  1446. }
  1447. //$repository->registr($data['phone'], $data['password'],'APP',"","",$data['spread']);
  1448. public function registr(string $phone, ?string $pwd, $user_type = 'h5',$url="",$nickname="",$external=1,$spread_uid=0)
  1449. {
  1450. $user_res = Db::name('user')->where('phone', $phone)->find();
  1451. if ($user_res && !$user_res['account']) {
  1452. $data = [
  1453. 'account' => $phone,
  1454. ];
  1455. $this->dao->update($user_res['uid'], $data);
  1456. return $this->dao->get($user_res['uid']);
  1457. }
  1458. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1459. $data = [
  1460. 'account' => $phone,
  1461. 'pwd' => $pwd,
  1462. 'nickname' =>$nickname?$nickname:'用户' . substr($phone, 7, 4),
  1463. 'avatar' => 'https://cdn.bjtdba.com/vod/image/2025-01-20/20250120125206881.png',
  1464. 'phone' => $phone,
  1465. 'last_ip' => app('request')->ip(),
  1466. "identity"=>5,
  1467. "external"=>$external,
  1468. "level_id"=>$spread_uid,
  1469. "spread_uid"=>$spread_uid
  1470. ];
  1471. return $this->create($user_type, $data, $url,$spread_uid);
  1472. }
  1473. public function addregistr($data)
  1474. {
  1475. // string $phone, ?string $pwd, $user_type = 'h5',$url,
  1476. $phone=$data['phone'];
  1477. $pwd=empty($data['password'])?time():$data['password'];
  1478. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1479. $data = [
  1480. 'account' => $phone,
  1481. 'pwd' => $pwd,
  1482. 'nickname' => '用户' . substr($phone, 7, 4),
  1483. 'avatar' => 'https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png',
  1484. 'phone' => $phone,
  1485. 'last_ip' => app('request')->ip(),
  1486. 'user_name'=>empty($data['user_name'])?0:$data['user_name'],
  1487. 'birthday'=>empty($data['birthday'])?0:$data['birthday'],
  1488. 'sex'=>empty($data['adr_id'])?0:$data['sex'],
  1489. 'spread_uid'=>$data['spread'],
  1490. 'adr_id'=>empty($data['adr_id'])?0:$data["adr_id"],
  1491. 'identity'=>empty($data['identity'])?0:$data["identity"],
  1492. ];
  1493. return $this->create("APP", $data);
  1494. }
  1495. /**
  1496. * 重置密码
  1497. * @param string $phone
  1498. * @param string|null $pwd
  1499. * @author 似水星辰 [ 2630481389@qq.com ]
  1500. * @created 2020/10/14 23:46
  1501. */
  1502. public function resetPassword(string $phone, ?string $pwd, int $userid)
  1503. {
  1504. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1505. $data = [
  1506. 'account' => $phone,
  1507. 'pwd' => $pwd,
  1508. 'phone' => $phone,
  1509. 'last_ip' => app('request')->ip()
  1510. ];
  1511. return $this->dao->update($userid, $data);
  1512. }
  1513. /*重置手机号*/
  1514. public function resetAccount(string $phone, int $userid, $identity){
  1515. $data = [
  1516. 'account' => $phone,
  1517. 'phone' => $phone,
  1518. 'last_ip' => app('request')->ip()
  1519. ];
  1520. //如果是商家
  1521. if($identity == 4){
  1522. $res = Db::name("merchant_admin")->where(['uid'=>$userid])->update(['account'=>$phone,'phone'=>$phone]);
  1523. if(!$res){
  1524. return false;
  1525. }
  1526. }
  1527. return $this->dao->update($userid, $data);
  1528. }
  1529. public function routineSpreadImage(User $user)
  1530. {
  1531. //小程序
  1532. $name = $user['uid'] . '_' . $user['is_promoter'] . '_user_routine.jpg';
  1533. $attachmentRepository = app()->make(AttachmentRepository::class);
  1534. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  1535. $spreadBanner = systemGroupData('spread_banner');
  1536. if (!count($spreadBanner)) return [];
  1537. $siteName = systemConfig('site_name');
  1538. $siteUrl = systemConfig('site_url');
  1539. $uploadType = (int)systemConfig('upload_type') ?: 1;
  1540. //检测远程文件是否存在
  1541. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  1542. $imageInfo->delete();
  1543. $imageInfo = null;
  1544. }
  1545. if (!$imageInfo) {
  1546. $routineQrcodeRepository = app()->make(RoutineQrcodeRepository::class);
  1547. $res = $routineQrcodeRepository->getShareCode($user['uid'], 'spread', '',$user['avatar']);
  1548. if (!$res) throw new ValidateException('二维码生成失败');
  1549. $upload = UploadService::create($uploadType);
  1550. $uploadRes = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
  1551. if ($uploadRes === false) {
  1552. throw new ValidateException($upload->getError());
  1553. }
  1554. $imageInfo = $upload->getUploadInfo();
  1555. $imageInfo['image_type'] = $uploadType;
  1556. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  1557. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  1558. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1559. 'attachment_category_id' => 0,
  1560. 'attachment_name' => $imageInfo['name'],
  1561. 'attachment_src' => $imageInfo['dir']
  1562. ]);
  1563. $routineQrcodeRepository->setRoutineQrcodeFind($res['id'], ['status' => 1, 'url_time' => date('Y-m-d H:i:s'), 'qrcode_url' => $imageInfo['dir']]);
  1564. $urlCode = $imageInfo['dir'];
  1565. } else $urlCode = $imageInfo['attachment_src'];
  1566. $siteUrlHttps = set_http_type($siteUrl, request()->isSsl() ? 0 : 1);
  1567. $filelink = [
  1568. 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1569. 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1570. ];
  1571. if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
  1572. if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
  1573. $resRoutine = true;
  1574. foreach ($spreadBanner as $key => &$item) {
  1575. $posterInfo = '海报生成失败:(';
  1576. $config = array(
  1577. 'image' => array(
  1578. array(
  1579. 'url' => $urlCode, //二维码资源
  1580. 'stream' => 0,
  1581. 'left' => 114,
  1582. 'top' => 790,
  1583. 'right' => 0,
  1584. 'bottom' => 0,
  1585. 'width' => 120,
  1586. 'height' => 120,
  1587. 'opacity' => 100
  1588. )
  1589. ),
  1590. 'text' => array(
  1591. array(
  1592. 'text' => $user['nickname'],
  1593. 'left' => 250,
  1594. 'top' => 840,
  1595. 'fontPath' => $filelink['Bold'], //字体文件
  1596. 'fontSize' => 16, //字号
  1597. 'fontColor' => '40,40,40', //字体颜色
  1598. 'angle' => 0,
  1599. ),
  1600. array(
  1601. 'text' => '邀请您加入' . $siteName,
  1602. 'left' => 250,
  1603. 'top' => 880,
  1604. 'fontPath' => $filelink['Normal'], //字体文件
  1605. 'fontSize' => 16, //字号
  1606. 'fontColor' => '40,40,40', //字体颜色
  1607. 'angle' => 0,
  1608. )
  1609. ),
  1610. 'background' => $item['pic']
  1611. );
  1612. $resRoutine = $resRoutine && $posterInfo = setSharePoster($config, 'routine/spread/poster');
  1613. if (!is_array($posterInfo)) throw new ValidateException($posterInfo);
  1614. $posterInfo['dir'] = path_to_url($posterInfo['dir']);
  1615. if (strpos($posterInfo['dir'], 'http') === false) $posterInfo['dir'] = request()->domain() . $posterInfo['dir'];
  1616. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1617. 'attachment_category_id' => 0,
  1618. 'attachment_name' => $posterInfo['name'],
  1619. 'attachment_src' => $posterInfo['dir']
  1620. ]);
  1621. if ($resRoutine) {
  1622. if ($posterInfo['image_type'] == 1)
  1623. $item['poster'] = rtrim($siteUrlHttps, '/') . $posterInfo['dir'];
  1624. else
  1625. $item['poster'] = set_http_type($posterInfo['dir'], request()->isSsl() ? 0 : 1);
  1626. $item['poster'] = str_replace('\\', '/', $item['poster']);
  1627. }
  1628. }
  1629. return $spreadBanner;
  1630. }
  1631. public function wxSpreadImage(User $user)
  1632. {
  1633. //公众号
  1634. $name = $user['uid'] . '_' . $user['is_promoter'] . '_user_wap.jpg';
  1635. $spreadBanner = systemGroupData('spread_banner');
  1636. if (!count($spreadBanner)) return [];
  1637. $siteName = systemConfig('site_name');
  1638. $attachmentRepository = app()->make(AttachmentRepository::class);
  1639. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  1640. $siteUrl = systemConfig('site_url');
  1641. $uploadType = (int)systemConfig('upload_type') ?: 1;
  1642. $resWap = true;
  1643. //检测远程文件是否存在
  1644. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  1645. $imageInfo->delete();
  1646. $imageInfo = null;
  1647. }
  1648. if (!$imageInfo) {
  1649. $codeUrl = set_http_type($siteUrl . '/share?spread=' . $user['uid'], request()->isSsl() ? 0 : 1);//二维码链接
  1650. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name,$user['avatar']);
  1651. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  1652. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  1653. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  1654. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -1, $user->uid, [
  1655. 'attachment_category_id' => 0,
  1656. 'attachment_name' => $imageInfo['name'],
  1657. 'attachment_src' => $imageInfo['dir']
  1658. ]);
  1659. $urlCode = $imageInfo['dir'];
  1660. } else $urlCode = $imageInfo['attachment_src'];
  1661. $siteUrl = set_http_type($siteUrl, request()->isSsl() ? 0 : 1);
  1662. $filelink = [
  1663. 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1664. 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1665. ];
  1666. if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
  1667. if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
  1668. foreach ($spreadBanner as $key => &$item) {
  1669. $posterInfo = '海报生成失败:(';
  1670. $config = array(
  1671. 'image' => array(
  1672. array(
  1673. 'url' => $urlCode, //二维码资源
  1674. 'stream' => 0,
  1675. 'left' => 160,//84
  1676. 'top' => 530,//630
  1677. 'right' => 0,
  1678. 'bottom' => 0,
  1679. 'width' => 280,
  1680. 'height' => 280,
  1681. 'opacity' => 100
  1682. )
  1683. ),
  1684. 'text' => array(
  1685. array(
  1686. 'text' => "NO:".$user['user_number'],
  1687. 'left' => 200,
  1688. 'top' => 850,
  1689. 'fontPath' => $filelink['Bold'], //字体文件
  1690. 'fontSize' => 16, //字号
  1691. 'fontColor' => '0,0,0', //字体颜色
  1692. 'angle' => 0,
  1693. ),
  1694. // array(
  1695. // 'text' => '邀请您加入' . $siteName,
  1696. // 'left' => 290,
  1697. // 'top' => 750,
  1698. // 'fontPath' => $filelink['Normal'], //字体文件
  1699. // 'fontSize' => 16, //字号
  1700. // 'fontColor' => '40,40,40', //字体颜色
  1701. // 'angle' => 0,
  1702. // )
  1703. ),
  1704. 'background' => $item['pic']
  1705. );
  1706. $resWap = $resWap && $posterInfo = setSharePoster($config, 'wap/spread/poster');
  1707. if (!is_array($posterInfo)) throw new ValidateException('海报生成失败');
  1708. $posterInfo['dir'] = path_to_url($posterInfo['dir']);
  1709. if (strpos($posterInfo['dir'], 'http') === false) $posterInfo['dir'] = request()->domain() . $posterInfo['dir'];
  1710. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1711. 'attachment_category_id' => 0,
  1712. 'attachment_name' => $posterInfo['name'],
  1713. 'attachment_src' => $posterInfo['dir']
  1714. ]);
  1715. if ($resWap) {
  1716. if ($posterInfo['image_type'] == 1)
  1717. $item['wap_poster'] = rtrim($siteUrl, '/') . $posterInfo['thumb_path'];
  1718. else
  1719. $item['wap_poster'] = set_http_type($posterInfo['thumb_path'], 1);
  1720. }
  1721. $item['wap_poster'] = str_replace('http://','https://',$item['wap_poster']);
  1722. $item["attachment_src"]= str_replace('http://','https://',$urlCode);
  1723. $item["name"]=$user['phone'];
  1724. }
  1725. return $spreadBanner;
  1726. }
  1727. public function getUsername($uid)
  1728. {
  1729. return User::getDB()->where('uid', $uid)->value('user_name');
  1730. }
  1731. /*获取用户手机号*/
  1732. public function getUserPhone($uid)
  1733. {
  1734. return User::getDB()->where('uid', $uid)->value('account');
  1735. }
  1736. /**
  1737. * @param $uid
  1738. * @param $inc
  1739. * @param string $type
  1740. * @author xaboy
  1741. * @day 2020/6/22
  1742. */
  1743. public function incBrokerage($uid, $inc, $type = '+')
  1744. {
  1745. $weekKey = 'b_top_' . date('Y-m');
  1746. $moneyKey = 'b_top_' . monday();
  1747. //TODO 佣金周榜
  1748. $brokerage = Cache::zscore($weekKey, $uid);
  1749. $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
  1750. Cache::zadd($weekKey, $brokerage, $uid);
  1751. //TODO 佣金月榜
  1752. $brokerage = Cache::zscore($moneyKey, $uid);
  1753. $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
  1754. Cache::zadd($moneyKey, $brokerage, $uid);
  1755. }
  1756. public function brokerageWeekTop($page, $limit)
  1757. {
  1758. $key = 'b_top_' . monday();
  1759. return $this->topList($key, $page, $limit);
  1760. }
  1761. public function brokerageMonthTop($page, $limit)
  1762. {
  1763. $key = 'b_top_' . date('Y-m');
  1764. return $this->topList($key, $page, $limit);
  1765. }
  1766. /**
  1767. * //TODO 绑定上下级关系
  1768. * @param User $user
  1769. * @param int $spreadUid
  1770. * @throws DbException
  1771. * @author xaboy
  1772. * @day 2020/6/22
  1773. */
  1774. public function bindSpread(User $user, int $spreadUid)
  1775. {
  1776. if ($spreadUid && !$user->spread_uid && $user->uid != $spreadUid) {
  1777. Db::transaction(function () use ($spreadUid, $user) {
  1778. $spread_user = $this ->get($spreadUid);
  1779. // //首次邀请赠送899积分
  1780. // if($spread_user['spread_count'] == 0){
  1781. // //首次邀请好友奖励积分
  1782. // $this -> sign_add($spreadUid,systemConfig('first_yq_score'),1,'首次邀请好友奖励积分','','');
  1783. // }
  1784. //邀请好友奖励积分
  1785. // $this->sign_add($spreadUid,systemConfig('invitation'),1,'邀请好友注册奖励积分','','');
  1786. //邀请好友奖励积分
  1787. $this->sign_add($spreadUid, 30,1,'邀请好友注册奖励积分','','', '', 1, '', 1);
  1788. $user->spread_uid = $spreadUid;
  1789. $user->spread_time = date('Y-m-d H:i:s');
  1790. if($spreadUid){
  1791. $user->mer_id = Db::name('user')->where('uid',$spreadUid)->value('mer_id');
  1792. }
  1793. $this->dao->update($spreadUid, [
  1794. 'spread_count' => Db::raw('spread_count +1')
  1795. ]);
  1796. $user->save();
  1797. //TODO 推广人月榜
  1798. Cache::zincrby('s_top_' . date('Y-m'), 1, $spreadUid);
  1799. //TODO 推广人周榜
  1800. Cache::zincrby('s_top_' . monday(), 1, $spreadUid);
  1801. });
  1802. $this->spread_log($user,$spreadUid);
  1803. }
  1804. //绑定上下级关系 加入推广群
  1805. // $this -> hximTg($user -> uid,$spreadUid);
  1806. }
  1807. /**
  1808. * @param $uid int 用户id
  1809. * @param $sid int 上级id
  1810. * @author Tang
  1811. * @created 2021/12/10
  1812. */
  1813. public function hximTg($uid,$sid)
  1814. {
  1815. try {
  1816. $im=new Im();
  1817. $user=Db::name('user')->where('uid',$uid)->find();
  1818. if($user['im']==0){//没有环信账户 创建
  1819. $im->createImUser($user['account'], $user['nickname']);
  1820. $user_account=$user['account'];
  1821. }else{//有环信账户 跳过创建 下一步
  1822. $user_account=$user['account'];
  1823. }
  1824. $userS=Db::name('user')->where('uid',$sid)->find();
  1825. if($userS['im']==0){//上级环信账户 创建
  1826. $im->createImUser($userS['account'], $userS['nickname']);
  1827. $s_account=$userS['account'];
  1828. }else{//有环信账户 跳过创建 下一步
  1829. $s_account=$userS['account'];
  1830. }
  1831. $group_id=Db::name("im_group")->where(['uid'=>$userS['account'],'type'=>'p'])->value('groupid');
  1832. //判断是否有群
  1833. if($group_id){//有则加入
  1834. $im->createGroupUser($group_id,$user_account,$user['uid']);
  1835. }else{
  1836. $group_id=$im->createGroup($s_account,'推广群','t');
  1837. $im->createGroupUser($group_id,$user_account,$user['uid']);
  1838. }
  1839. }catch (\Exception $e) {
  1840. Db::name("log")->insert(array('data'=>'推广群错误'.$e->getMessage()));//日志记录
  1841. }
  1842. }
  1843. //注册时成为推广员身份 记录统计及信息
  1844. public function spread_log($user,$spreadUid){
  1845. if($spreadUid){
  1846. Db::transaction(function () use ($spreadUid, $user) {
  1847. $sp = DB::name("user")->where(['uid'=>$spreadUid])->field("uid,spread_count")->find();
  1848. if($sp){
  1849. //推荐人推荐数量加1
  1850. Db::name("user")->where(['uid'=>$sp['uid']])->update(['spread_count'=>($sp['spread_count']+1)]);
  1851. //保存用户的推荐记录
  1852. $log =[
  1853. 'uid'=> $sp['uid'],
  1854. 'link_id'=>$user->uid,
  1855. 'identity'=>5,
  1856. 'create_time'=>date("Y-m-d H:i:s"),
  1857. ] ;
  1858. Db::name("user_identity_log")->insert($log);
  1859. }
  1860. });
  1861. }
  1862. }
  1863. public function topList($key, $page, $limit)
  1864. {
  1865. $res = Cache::zrevrange($key, ($page - 1) * $limit, $limit, true);
  1866. $ids = array_keys($res);
  1867. $index = array_flip($ids);
  1868. $count = Cache::zcard($key);
  1869. $list = count($ids) ? $this->dao->users($ids, 'uid,avatar,nickname')->toArray() : [];
  1870. foreach ($list as $k => $v) {
  1871. $list[$k]['count'] = $res[$v['uid']] ?? 0;
  1872. }
  1873. $sort = array_column($list, 'count');
  1874. array_multisort($sort, SORT_DESC, $list);
  1875. return compact('count', 'list');
  1876. }
  1877. public function spreadWeekTop($page, $limit)
  1878. {
  1879. $key = 's_top_' . monday();
  1880. return $this->topList($key, $page, $limit);
  1881. }
  1882. public function spreadMonthTop($page, $limit)
  1883. {
  1884. $key = 's_top_' . date('Y-m');
  1885. return $this->topList($key, $page, $limit);
  1886. }
  1887. /**
  1888. * @param $uid
  1889. * @param $nickname
  1890. * @param $sort
  1891. * @param $page
  1892. * @param $limit
  1893. * @return array
  1894. * @throws DataNotFoundException
  1895. * @throws DbException
  1896. * @throws ModelNotFoundException
  1897. * @author xaboy
  1898. * @day 2020/6/22
  1899. */
  1900. public function getOneLevelList($uid, $nickname, $sort, $page, $limit)
  1901. {
  1902. $query = $this->search(['spread_uid' => $uid, 'nickname' => $nickname, 'sort' => $sort]);
  1903. $count = $query->count();
  1904. $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
  1905. return compact('list', 'count');
  1906. }
  1907. /**
  1908. * @param $uid
  1909. * @param $nickname
  1910. * @param $sort
  1911. * @param $page
  1912. * @param $limit
  1913. * @return array
  1914. * @throws DataNotFoundException
  1915. * @throws DbException
  1916. * @throws ModelNotFoundException
  1917. * @author xaboy
  1918. * @day 2020/6/22
  1919. */
  1920. public function getTwoLevelList($uid, $nickname, $sort, $page, $limit)
  1921. {
  1922. $ids = $this->dao->getSubIds($uid);
  1923. if (count($ids)) {
  1924. $query = $this->search(['spread_uids' => $ids, 'nickname' => $nickname, 'sort' => $sort]);
  1925. $count = $query->count();
  1926. $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
  1927. } else {
  1928. $list = [];
  1929. $count = 0;
  1930. }
  1931. return compact('list', 'count');
  1932. }
  1933. public function getLevelList($uid, array $where, $page, $limit)
  1934. {
  1935. if (!$where['level']) {
  1936. // $ids = $this->dao->getSubIds($uid);
  1937. $ids[] = $uid;
  1938. $where['spread_uids'] = $ids;
  1939. } else if ($where['level'] == 2) {
  1940. $ids = $this->dao->getSubIds($uid);
  1941. if (!count($ids)) return ['list' => [], 'count' => 0];
  1942. $where['spread_uids'] = $ids;
  1943. } else {
  1944. $where['spread_uid'] = $uid;
  1945. }
  1946. $query = $this->search($where);
  1947. $count = $query->count();
  1948. $list = $query->setOption('field', [])->field('User.uid,avatar,nickname,is_promoter,pay_count,pay_price,spread_count,User.create_time')->page($page, $limit)->select();
  1949. return compact('list', 'count','where');
  1950. }
  1951. /**
  1952. * @param $uid
  1953. * @param $page
  1954. * @param $limit
  1955. * @param array $where
  1956. * @return array
  1957. * @throws DataNotFoundException
  1958. * @throws DbException
  1959. * @throws ModelNotFoundException
  1960. * @author xaboy
  1961. * @day 2020/6/26
  1962. */
  1963. public function subOrder($uid, $page, $limit, array $where = [])
  1964. {
  1965. if (isset($where['level'])) {
  1966. if (!$where['level']) {
  1967. $ids = $this->dao->getSubIds($uid);
  1968. $subIds = $this->dao->getSubAllIds($ids);
  1969. } else if ($where['level'] == 2) {
  1970. $ids = $this->dao->getSubIds($uid);
  1971. $subIds = $this->dao->getSubAllIds($ids);
  1972. $ids = [];
  1973. } else {
  1974. $ids = $this->dao->getSubIds($uid);
  1975. $subIds = [];
  1976. }
  1977. } else {
  1978. $ids = $this->dao->getSubIds($uid);
  1979. $subIds = $this->dao->getSubAllIds($ids);
  1980. }
  1981. $all = array_merge($ids, $subIds);
  1982. if (!count($all)) return ['count' => 0, 'list' => []];
  1983. $query = app()->make(StoreOrderRepository::class)->usersOrderQuery($where, $all);
  1984. $count = $query->count();
  1985. $list = $query->page($page, $limit)->field('uid,order_sn,pay_time,extension_one,extension_two')->with(['user' => function ($query) {
  1986. $query->field('avatar,nickname,uid');
  1987. }])->select()->toArray();
  1988. foreach ($list as $k => $item) {
  1989. $list[$k]['brokerage'] = in_array($item['uid'], $ids) ? $item['extension_one'] : $item['extension_two'];
  1990. unset($list[$k]['extension_one'], $list[$k]['extension_two']);
  1991. }
  1992. return compact('count', 'list');
  1993. }
  1994. /**
  1995. * @param User $user
  1996. * @return User
  1997. * @throws DataNotFoundException
  1998. * @throws DbException
  1999. * @throws ModelNotFoundException
  2000. * @author xaboy
  2001. * @day 2020/7/2
  2002. */
  2003. public function mainUser(User $user): User
  2004. {
  2005. if (!$user->main_uid || $user->uid == $user->main_uid) return $user;
  2006. $switchUser = $this->dao->get($user->main_uid);
  2007. if (!$switchUser) return $user;
  2008. if ($user->wechat_user_id && !$switchUser->wechat_user_id) {
  2009. $switchUser->wechat_user_id = $user->wechat_user_id;
  2010. $switchUser->save();
  2011. }
  2012. return $switchUser;
  2013. }
  2014. public function switchUser(User $user, $uid)
  2015. {
  2016. if ($user->uid == $uid || !$this->dao->existsWhere(['uid' => $uid, 'phone' => $user->phone]))
  2017. throw new ValidateException('操作失败');
  2018. $this->dao->update($user->uid, ['main_uid' => $uid]);
  2019. $switchUser = $this->dao->get($uid);
  2020. return $switchUser;
  2021. }
  2022. public function returnToken($user, $tokenInfo)
  2023. {
  2024. $user = $user->hidden(['label_id', 'group_id', 'main_uid', 'pwd', 'addres', 'card_id', 'last_time', 'last_ip', 'create_time', 'mark', 'status', 'spread_uid', 'spread_time', 'real_name', 'birthday', 'brokerage_price'])->toArray();
  2025. return [
  2026. 'token' => $tokenInfo['token'],
  2027. 'exp' => $tokenInfo['out'],
  2028. 'user' => $user
  2029. ];
  2030. }
  2031. public function switchBrokerage(User $user, $brokerage)
  2032. {
  2033. $user->now_money = bcadd($user->now_money, $brokerage, 2);
  2034. $user->brokerage_price = bcsub($user->brokerage_price, $brokerage, 2);
  2035. Db::transaction(function () use ($brokerage, $user) {
  2036. $user->save();
  2037. app()->make(UserBillRepository::class)->incBill($user->uid, 'now_money', 'brokerage', [
  2038. 'link_id' => 0,
  2039. 'status' => 1,
  2040. 'title' => '佣金转入余额',
  2041. 'number' => $brokerage,
  2042. 'mark' => '成功转入余额' . floatval($brokerage) . '元',
  2043. 'balance' => $user->now_money
  2044. ]);
  2045. app()->make(UserBillRepository::class)->decBill($user->uid, 'brokerage', 'now_money', [
  2046. 'link_id' => 0,
  2047. 'status' => 1,
  2048. 'title' => '佣金转入余额',
  2049. 'number' => $brokerage,
  2050. 'mark' => '成功转入余额' . floatval($brokerage) . '元',
  2051. 'balance' => $user->brokerage_price
  2052. ]);
  2053. });
  2054. }
  2055. /**
  2056. * 签到
  2057. * @param $member_id
  2058. * @throws DataNotFoundException
  2059. * @throws DbException
  2060. * @throws ModelNotFoundException
  2061. */
  2062. public function sub_signin($member_id){
  2063. $member_info = Db::name('user')->where( array('uid' => $member_id) )->find();
  2064. $config =systemConfig([
  2065. 'isopen_signinreward',
  2066. 'signinreward_day1_score',
  2067. 'signinreward_day2_score',
  2068. 'signinreward_day3_score',
  2069. 'signinreward_day4_score',
  2070. 'signinreward_day5_score',
  2071. 'signinreward_day6_score',
  2072. 'signinreward_day7_score',
  2073. ]);
  2074. //是否开启签到奖励
  2075. $isopen_signinreward = empty($config['isopen_signinreward']) ? 0 : $config['isopen_signinreward'];
  2076. if( $isopen_signinreward != 1 )
  2077. {
  2078. return array('code' => 1,'msg' => '签到奖励功能未开启');
  2079. }
  2080. //连续7天签到奖励
  2081. $signinreward_day1_score = empty($config['signinreward_day1_score']) ? 0 : $config['signinreward_day1_score'];
  2082. $signinreward_day2_score = empty($config['signinreward_day2_score']) ? 0 : $config['signinreward_day2_score'];
  2083. $signinreward_day3_score = empty($config['signinreward_day3_score']) ? 0 : $config['signinreward_day3_score'];
  2084. $signinreward_day4_score = empty($config['signinreward_day4_score']) ? 0 : $config['signinreward_day4_score'];
  2085. $signinreward_day5_score = empty($config['signinreward_day5_score']) ? 0 : $config['signinreward_day5_score'];
  2086. $signinreward_day6_score = empty($config['signinreward_day6_score']) ? 0 : $config['signinreward_day6_score'];
  2087. $signinreward_day7_score = empty($config['signinreward_day7_score']) ? 0 : $config['signinreward_day7_score'];
  2088. //准备数据
  2089. $result = array();
  2090. $result['signinreward_day1_score'] = $signinreward_day1_score;
  2091. $result['signinreward_day2_score'] = $signinreward_day2_score;
  2092. $result['signinreward_day3_score'] = $signinreward_day3_score;
  2093. $result['signinreward_day4_score'] = $signinreward_day4_score;
  2094. $result['signinreward_day5_score'] = $signinreward_day5_score;
  2095. $result['signinreward_day6_score'] = $signinreward_day6_score;
  2096. $result['signinreward_day7_score'] = $signinreward_day7_score;
  2097. $today_signintime = time();
  2098. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->whereDay('signin_time')->find();
  2099. if( !empty($today_signin_info) )
  2100. {
  2101. return array('code' => 1,'msg' => '今天已经签到过了');
  2102. }else{
  2103. //查询昨天是否已经签到了
  2104. $yes_signintime = strtotime( date('Y-m-d'). ' 00:00:00' ) - 86400;
  2105. $yes_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id, 'signin_time' => $yes_signintime ) )->find();
  2106. $has_qian = 1;
  2107. if( !empty($yes_signin_info) )
  2108. {
  2109. $has_qian = $yes_signin_info['continuity_day'] +1;
  2110. $has_qian = $has_qian > 7 ? 7 : $has_qian;
  2111. }
  2112. $get_score = $result["signinreward_day".$has_qian."_score"];
  2113. $ins_data = array();
  2114. $ins_data['member_id'] = $member_id;
  2115. $ins_data['continuity_day'] = $has_qian;
  2116. $ins_data['reward_socre'] = $get_score;
  2117. $ins_data['signin_time'] = $today_signintime;
  2118. $ins_data['addtime'] = time();
  2119. $member_info = Db::name('user')->where( array('uid' => $member_id) )->find();
  2120. $score = $member_info['now_score'];
  2121. Db::name('user_signinreward_record')->insert($ins_data);
  2122. $now_score=$score+$get_score;
  2123. app()->make(UserBillRepository::class)->incBill($member_id, 'now_money', 'recharge', [
  2124. 'link_id' => 1,
  2125. 'status' => 1,
  2126. 'title' => '签到积分',
  2127. 'number' => $get_score,
  2128. 'mark' => '连续签到'.$has_qian.'天赠送',
  2129. 'balance' =>$now_score
  2130. ]);
  2131. Db::name('user')->where( array('uid' => $member_id) )->update(['now_score'=>$now_score]);
  2132. // Db::name('log')->insert(['data'=>Db::name('user')->getLastSql(),'time'=>date('Y-m-d H:i:s',time())]);
  2133. return array('code' =>0, 'now_score' => $score, 'continuity_day' => $has_qian,'reward_socre' => $get_score );
  2134. }
  2135. }
  2136. public function get_signin($member_id,$where=[]){
  2137. if ($where){
  2138. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time', 'between', [$where['data1'], $where['data2']])->find();
  2139. $show_day_arr= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time', 'between', [$where['data1'], $where['data2']])->column('signin_time');
  2140. }else{
  2141. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time',"today")->find();
  2142. $show_day_arr= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time',"month")->column('signin_time');
  2143. }
  2144. $score= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->count('reward_socre');
  2145. $leiji= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->sum('reward_socre');
  2146. foreach ($show_day_arr as &$v){
  2147. $v=date("Y-m-d",$v);
  2148. }
  2149. $result['score'] = $score;
  2150. $result['today_is_signin'] = $today_signin_info?1:0;
  2151. $result['leiji'] = $leiji;
  2152. $result['show_day_arr'] = $show_day_arr;
  2153. return $result;
  2154. }
  2155. public function add_cer($data=[],$member_id)
  2156. {
  2157. $renzeng=Db::name("user_certification")->where("uid",$member_id)->find();
  2158. if ($renzeng){
  2159. $res = Db::name('user_certification')->where("uid",$member_id)->update($data);
  2160. }else{
  2161. $res = Db::name('user_certification')->insert($data);
  2162. }
  2163. if($res){
  2164. return [
  2165. 'user_name' => $data['user_name'],
  2166. 'age' => $this->getAgeByID($data['user_card']),
  2167. 'user_card' => preg_replace('/(\d{6})\d{8}(\d{4})/', '$1****$2', $data['user_card']),
  2168. ];
  2169. }
  2170. else{
  2171. return false;
  2172. }
  2173. }
  2174. public function get_cer($data=[])
  2175. {
  2176. $res = Db::name('user_certification')->where($data)->find();
  2177. //计算年龄
  2178. $res['age'] = $this->getAgeByID($res['user_card']);
  2179. if($res){
  2180. return $res;
  2181. }
  2182. else{
  2183. return false;
  2184. }
  2185. }
  2186. public function getAgeByID($id){
  2187. //过了这年的生日才算多了1周岁
  2188. if(empty($id)) return '';
  2189. $date=strtotime(substr($id,6,8));
  2190. //获得出生年月日的时间戳
  2191. $today=strtotime('today');
  2192. //获得今日的时间戳
  2193. $diff=floor(($today-$date)/86400/365);
  2194. //得到两个日期相差的大体年数
  2195. //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
  2196. $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
  2197. return $age;
  2198. }
  2199. /**
  2200. * @param $data
  2201. *
  2202. */
  2203. public function addagent($user){
  2204. if ($user){
  2205. $data=[
  2206. "identity"=>5,
  2207. "status"=>1,
  2208. "add_time"=>time(),
  2209. "update_time"=>time(),
  2210. "user_id"=>$user->uid,
  2211. "name"=>"推广员",
  2212. "pay_status"=>1,
  2213. "price"=>0,
  2214. "agent_sn"=>time(),
  2215. ];
  2216. Db::name("user_agent")->insert($data);
  2217. }
  2218. }
  2219. /*
  2220. * 申请代理
  2221. @cabbage
  2222. */
  2223. public function agent($data){
  2224. $user = Db::name("user")->where(['uid'=>$data['user_id']])->field("identity,account,uid")->find();
  2225. //判断所申请的区域下是否有代理
  2226. if($data['identity'] == 1){
  2227. if(Db::name("user_street")->where("street_id",$data['street_id'])->value("uid")){
  2228. return ['code'=>400,'msg'=>'该区域下已有代理'];
  2229. }
  2230. }elseif($data['identity'] == 2){
  2231. if(Db::name("user_area")->where("area_id",$data['area_id'])->value("uid")){
  2232. return ['code'=>400,'msg'=>'该区域下已有代理'];
  2233. }
  2234. }elseif($data['identity'] == 3){
  2235. if(Db::name("user_city")->where("city_id",$data['city_id'])->value("uid")){
  2236. return ['code'=>400,'msg'=>'该区域下已有代理'];
  2237. }
  2238. }
  2239. //判断是不是商户
  2240. // if($user['identity']==4){
  2241. // return ['code'=>'400','msg'=>"不符合申请代理的条件"];
  2242. // }
  2243. //判断用户是否是其他代理身份
  2244. // if(in_array($user['identity'],[1,2,3,5])){
  2245. // return ['code'=>'400','msg'=>"用户已是推广身份"];
  2246. // }
  2247. if($user['identity']==$data['identity']){
  2248. return ['code'=>'400','msg'=>"用户已是该身份,无需申请"];
  2249. }
  2250. if($data['spread_account'] == $user['account']){
  2251. return ['code'=>'400','msg'=>"推荐人不能是自己"];
  2252. }
  2253. $real = Db::name("user_certification")->where(["uid"=>$data['user_id'],'status'=>1])->find();
  2254. //判断是否实名认证
  2255. if(!$real){
  2256. return ['code'=>'400','msg'=>"请先实名认证"];
  2257. }
  2258. if($user){
  2259. if($data['identity'] == $user['identity']){
  2260. return ['code'=>'400','msg'=>"已经是该级别代理"];
  2261. }
  2262. if(!in_array($user['identity'],[4,5]) && $data['identity'] < $user['identity']){
  2263. return ['code'=>'400','msg'=>"不能申请低于现在级别的代理"];
  2264. }
  2265. }
  2266. $is_apply= Db::name("user_agent")->where(["user_id"=>$data["user_id"],'status'=>[0,2]])->find();
  2267. if ($is_apply){
  2268. if($is_apply['status'] == 0){
  2269. return ['code'=>'400','msg'=>"您有审核中的代理申清"];
  2270. }
  2271. if($is_apply['status'] == 2) {
  2272. $data['status']= 0;//恢复申请中状态
  2273. $res= Db::name("user_agent")->where("id",$is_apply['id'])->update($data);
  2274. if($res){
  2275. return true;
  2276. }
  2277. }
  2278. }
  2279. $res= Db::name("user_agent")->insert($data);
  2280. if($res){
  2281. return true;
  2282. }
  2283. }
  2284. public function isAgent($uid){
  2285. $res = Db::name("user_agent")
  2286. ->where(["user_id"=>$uid])
  2287. ->whereIn('status',[0,1,2])
  2288. ->whereIn('identity',[1,2,3,6])
  2289. ->order("add_time desc")
  2290. ->find();
  2291. if(!$res){
  2292. return json_encode([]);
  2293. }
  2294. $res['province_name'] = Db::name("user_province")->where(['province_id'=>$res['province_id']])->value("province_name");
  2295. $res['city_name'] = Db::name("user_city")->where(['city_id'=>$res['city_id']])->value("city_name");
  2296. $res['area_name'] = Db::name("user_area")->where(['area_id'=>$res['area_id']])->value("area_name");
  2297. $res['street_name'] = Db::name("user_street")->where(['street_id'=>$res['street_id']])->value("street_name");
  2298. switch ($res['identity']){
  2299. case '1':
  2300. $res['name'] = '镇级服务商';
  2301. break;
  2302. case '2':
  2303. $res['name'] = '县级服务商';
  2304. break;
  2305. case '3':
  2306. $res['name'] = '市级服务商';
  2307. break;
  2308. case '6':
  2309. $res['name'] = '渠道商';
  2310. }
  2311. return $res;
  2312. }
  2313. public function getAgentPayDetail($where=[]){
  2314. $res= Db::name("user_agent")->where($where)->find();
  2315. return $res;
  2316. }
  2317. public function get_agent_info($member_id){
  2318. $user=Db::name("user")->where("uid",$member_id)->find();
  2319. $data=[
  2320. "nickname"=>$user["nickname"],
  2321. "avatar"=>$user["avatar"],
  2322. "is_promoter"=>$user["is_promoter"],
  2323. "identity"=>$user["identity"],
  2324. "brokerage_price"=>set_price_rtrim($user["brokerage_price"]),
  2325. "uid"=>$member_id,
  2326. ];
  2327. $data["yesterday"]=(string)Db::name("user_bill")->whereDay('create_time', 'yesterday')->where(["uid"=>$member_id,"type"=>"commission","status"=>1])->where("commission_type","<>",5)->sum("number");
  2328. $data["cumulative"]=(string)Db::name("user_bill")->where(["uid"=>$member_id,"type"=>"commission","status"=>1,"is_red_brokerage"=>0])->where("commission_type","<>",5)->sum("number");
  2329. $data["extract"]=(string)Db::name("user_extract")->where(["uid"=>$member_id,"status"=>1])->sum("extract_price");
  2330. return $data;
  2331. }
  2332. /*
  2333. * 全民营销->推广统计
  2334. */
  2335. public function get_extension_info($member_id,$search,$where=[]){
  2336. $data=[];
  2337. $data["count_zong"]=Db::name("user_identity_log")->where(["uid"=>$member_id])->count();
  2338. $data["town"]=Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>1])->whereNotIn("identity","0")->count();
  2339. $data["county"]= Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>2])->whereNotIn("identity","0")->count();
  2340. $data["city"]= Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>3])->whereNotIn("identity","0")->count();
  2341. $data["shop"]=Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>4])->whereNotIn("identity","0")->count();
  2342. $data["tuiguang"]=Db::name("user_identity_log")->where(["uid"=>$member_id])->whereIn('identity','5,0')->count();
  2343. $query =Db::name("user_identity_log")->alias("a")
  2344. ->join('user s',"a.link_id=s.uid")
  2345. ->where(["a.uid"=>$member_id])
  2346. ->field("s.nickname,a.create_time,a.identity,s.phone");
  2347. if(isset($where['identity']) && $where['identity'] != ''){
  2348. $query = $query->where(['a.identity'=>$where['identity']]);
  2349. }
  2350. if(isset($search) && $search !=''){
  2351. $query =$query->whereLike('s.account','%'.$search.'%');
  2352. }
  2353. $list = $query->select();
  2354. $data["list"]=$list;
  2355. return $data;
  2356. }
  2357. public function get_profit_info($member_id,$where){
  2358. // $data["count_yj"]=Db::name("user")->where(["type"=>"commission"])->sum("number");
  2359. // $data["dlfee"]=Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");
  2360. // $data["xiaofee"]=Db::name("user")->where(["type"=>"commission","commission_type"=>2])->sum("number");;
  2361. // $data["county"] =Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");;
  2362. // $data["town"]==Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");;
  2363. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  2364. ->field("type,number,status,commission_type,create_time,uid,title,order_sn");
  2365. $order = "create_time desc";
  2366. if($where['date_on'] == 1){
  2367. $order = "create_time desc";
  2368. }elseif($where['date_off'] == 1){
  2369. $order = "create_time asc";
  2370. }
  2371. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  2372. $query = $query->where(['commission_type'=>$where['commission_type']]);
  2373. }else{
  2374. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2375. }
  2376. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2377. $query = $query->whereTime("create_time",$where['order']);
  2378. }
  2379. $list= $query->order($order)->select()->toArray();
  2380. $dangqian_yj=Db::name("user")->where("uid",$member_id)->value("brokerage_price");
  2381. $dlfee=0;
  2382. $xiaofei=0;
  2383. $tuiguang=0;
  2384. $xiaqu=0;
  2385. $weijiesuan=0;
  2386. $qudao=0;
  2387. foreach ($list as &$v){
  2388. // $count_yj=$v["number"]+$count_yj;
  2389. if ($v["status"]==0){
  2390. $v["title"]="【预估】".$v["title"].",单号:".$v["order_sn"];
  2391. $weijiesuan+=$v['number'];
  2392. }elseif($v["status"]==-1){
  2393. $v["title"]="【失效】".$v["title"].",单号:".$v["order_sn"];
  2394. }else{
  2395. if ($v["commission_type"]==1){
  2396. $dlfee+=$v["number"];
  2397. }
  2398. if ($v["commission_type"]==2){
  2399. $xiaofei+=$v["number"];
  2400. }
  2401. if ($v["commission_type"]==3){
  2402. $tuiguang+=$v["number"];
  2403. }
  2404. if ($v["commission_type"]==4){
  2405. $xiaqu+=$v["number"];
  2406. }
  2407. if ($v["commission_type"]==6||$v["commission_type"]==7){
  2408. $tuiguang+=$v["number"];
  2409. }
  2410. if ($v["commission_type"]==9){
  2411. $qudao+=$v["number"];
  2412. }
  2413. if ($v["commission_type"]==10){
  2414. $tuiguang+=$v["number"];
  2415. }
  2416. }
  2417. }
  2418. $data["count_yj"]=round($dangqian_yj,2);//当前佣金
  2419. $data["dlfee"]=round($dlfee,2); //代理非
  2420. $data["xiaofei"]=round($xiaofei,2); //消费佣金
  2421. $data["tuiguang"]= round($tuiguang,2); //推广佣金
  2422. $data["xiaqu"]=round($xiaqu,2); //辖区佣金
  2423. $data["weijiesuan"]=round($weijiesuan,2);//未结束佣金
  2424. $data["qudao"]=round($qudao,2);//渠道
  2425. $data["list"]=$list;
  2426. return $data;
  2427. }
  2428. /*
  2429. * 越攒越多统计
  2430. * */
  2431. public function get_com_all($member_id,$where){
  2432. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  2433. ->field("type,number,status,commission_type,create_time,uid,title,order_sn,type_shop");
  2434. $order = "create_time desc";
  2435. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  2436. $query = $query->where(['commission_type'=>$where['commission_type']]);
  2437. }else{
  2438. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2439. }
  2440. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2441. $query = $query->whereTime("create_time",$where['order']);
  2442. }
  2443. $query = $query->where(['status'=>1]);
  2444. $list= $query->order($order)->select()->toArray();
  2445. $dangqian_yj=Db::name("user")->where("uid",$member_id)->value("brokerage_price");
  2446. $dlfee=0;
  2447. $xiaofei=0;
  2448. $tuiguang=0;
  2449. $kuadian=0;
  2450. $xiaqu=0;
  2451. $weijiesuan=0;
  2452. $ptjl=0;
  2453. $qudao=0;
  2454. foreach ($list as &$v){
  2455. // $count_yj=$v["number"]+$count_yj;
  2456. if ($v["commission_type"]==1){
  2457. $dlfee+=$v["number"];
  2458. }
  2459. if ($v["commission_type"]==2){
  2460. $xiaofei+=$v["number"];
  2461. }
  2462. if ($v["commission_type"]==3){
  2463. $tuiguang+=$v["number"];
  2464. }
  2465. if ($v["commission_type"]==4){
  2466. $xiaqu+=$v["number"];
  2467. $v['title'] = '辖区获取佣金';
  2468. }
  2469. if ($v["commission_type"]==7){
  2470. $kuadian+=$v["number"];
  2471. $v['title'] = '跨店获取佣金';
  2472. }
  2473. if ($v["commission_type"]==8){
  2474. $ptjl+=$v["number"];
  2475. $v['title'] = '平台奖励佣金';
  2476. }
  2477. if ($v["commission_type"]==9){
  2478. $qudao+=$v["number"];
  2479. $v['title'] = '渠道商奖励佣金';
  2480. }
  2481. if ($v["commission_type"]==10){
  2482. $tuiguang+=$v["number"];
  2483. $v['title'] = '推荐商户奖励佣金';
  2484. }
  2485. // if ($v['type_shop'] >0){
  2486. // $qudao+=$v['number'];
  2487. // $v['title'] = '第三方订单获取佣金';
  2488. // }
  2489. }
  2490. $data["count_yj"]=round($dangqian_yj,2);//当前佣金
  2491. $data["dlfee"]=round($dlfee,2); //代理非
  2492. $data["xiaofei"]=round($xiaofei,2); //消费佣金
  2493. $data["tuiguang"]= round($tuiguang,2); //推广佣金
  2494. $data["xiaqu"]=round($xiaqu,2); //辖区佣金
  2495. $data["weijiesuan"]=round($weijiesuan,2);//未结束佣金
  2496. $data["kuadian"]=round($kuadian,2); //跨店
  2497. $data["ptjl"]=round($ptjl,2); //平台奖励佣金
  2498. $data["qudao"]=round($qudao,2); //渠道
  2499. return $data;
  2500. }
  2501. /*
  2502. * 越攒越多列表
  2503. * */
  2504. public function get_com_list($member_id,$where){
  2505. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  2506. ->field("type,number,status,commission_type,create_time,uid,title,order_sn,type_shop");
  2507. $order = "create_time desc";
  2508. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  2509. $query = $query->where(['commission_type'=>$where['commission_type']]);
  2510. }else{
  2511. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2512. }
  2513. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2514. $query = $query->whereTime("create_time",$where['order']);
  2515. }
  2516. $page = $where['page'] ?? 1;
  2517. $limit = $where['limit'] ?? 10;
  2518. $query = $query->where(['status'=>1]);
  2519. $list= $query->page($page,$limit)->order($order)->select()->toArray();
  2520. $data["list"]=$list;
  2521. return $data;
  2522. }
  2523. /**
  2524. * 获取推广列表
  2525. */
  2526. public function get_tuiguang_list($member_id,$where = []){
  2527. $query = Db::name("user_bill")
  2528. ->alias("ul")
  2529. ->where(["ul.type"=>"commission",'ul.uid'=>$member_id])
  2530. ->field("ul.mark,ul.bill_id,ul.type,ul.number,ul.status,ul.create_time,ul.uid,ul.order_sn,ul.create_time,ul.link_id,ul.type_shop,ul.commission_type,ul.source");
  2531. if(isset($where['type']) && in_array($where['type'],[0,1])){
  2532. $query = $query->where(['ul.source'=>$where['type']]);
  2533. }
  2534. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2535. $query = $query->whereTime("create_time",$where['order']);
  2536. }
  2537. $page = $where['page'] ?? 1;
  2538. $limit = $where['limit'] ?? 10;
  2539. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2540. $query = $query ->where("status",'>=',0);
  2541. //不显示红积分的
  2542. $query = $query ->where("is_red_brokerage",'=',0);
  2543. $list= $query->order("create_time desc")->page($page,$limit)->select()->toArray();
  2544. foreach ($list as &$v){
  2545. // $v["create_time"]=date("Y-m-d", $v["create_time"]);
  2546. //0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么
  2547. if($v['type_shop'] == 0){
  2548. if($v['source'] == 0){
  2549. if($v['commission_type'] == 9){
  2550. $this -> getContent('channel_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v);
  2551. }elseif($v['commission_type'] == 10){
  2552. $this -> getContent('merchant_annual_cost_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v);
  2553. }else{
  2554. $this -> getContent('store_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v,$v['create_time']);
  2555. }
  2556. }else{
  2557. $uid=Db::name("store_order")->where("order_sn",$v["order_sn"])->value("uid");
  2558. $v["nickname"]=$this -> getUserNickname($uid);
  2559. $v['content'] = '用户'.$v['nickname'].'到店消费,帮您攒金';
  2560. $v['xiadan'] = $v['create_time'] ?? '';
  2561. $v['jiesuan'] = $v['create_time'];
  2562. }
  2563. }elseif ($v['type_shop'] == '1'){
  2564. $this -> getContent('order_pdd',$v['order_sn'],'拼多多',$v['status'],$v['commission_type'],$v);
  2565. }elseif ($v['type_shop'] == '2'){
  2566. $this -> getContent('order_vip',$v['order_sn'],'唯品会',$v['status'],$v['commission_type'],$v);
  2567. }elseif ($v['type_shop'] == '3'){
  2568. $this -> getContent('order_su',$v['order_sn'],'苏宁易购',$v['status'],$v['commission_type'],$v);
  2569. }
  2570. elseif ($v['type_shop'] == '4'){
  2571. // $uid = Db::name('order_jd')->where("order_sn",$v["order_sn"])->value("uid");
  2572. // $v["nickname"]=$this -> getUserNickname($uid);
  2573. $v["nickname"]='';
  2574. $v['content'] = $v['nickname'].'在网易考拉消费,帮您攒金';
  2575. $v['xiadan'] = '';
  2576. $v['jiesuan'] = '';
  2577. }elseif ($v['type_shop'] == '5'){
  2578. $this -> getContent('order_tb',$v['order_sn'],'淘宝',$v['status'],$v['commission_type'],$v);
  2579. }elseif ($v['type_shop'] == '6'){
  2580. $this -> getContent('order_jd',$v['order_sn'],'京东',$v['status'],$v['commission_type'],$v);
  2581. }elseif ($v['type_shop'] == '7'){
  2582. $this -> getContent('order_tb',$v['order_sn'],'饿了么',$v['status'],$v['commission_type'],$v);
  2583. }
  2584. if($v['commission_type'] == 7){
  2585. $v['mark'] = '【跨店】'.$v['mark'];
  2586. }
  2587. $v['number'] =set_price_rtrim($v['number']);
  2588. }
  2589. return $list;
  2590. }
  2591. public function getUserNickname($uid){
  2592. return Db::name("user")->where("uid", $uid)->value("nickname");
  2593. }
  2594. public function getContent($table,$order_sn,$title,$status,$commission_type,&$v,$create_time=null){
  2595. $yugu = '';
  2596. if($status == 0){
  2597. $yugu = "【预估】";
  2598. if($commission_type == 7){
  2599. $yugu = "【跨店预估】";
  2600. }
  2601. }
  2602. switch ($table){
  2603. case 'store_order':
  2604. $res = Db::name($table)->where("order_sn",$order_sn)->field('uid,create_time,pay_time')->find();
  2605. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2606. $v['content'] = $yugu.$v['nickname'].'在'.$title.'消费,帮您攒金';
  2607. break;
  2608. case 'channel_order':
  2609. $res = Db::name($table)->where("order_no",$order_sn)->field('uid,create_time,pay_time')->find();
  2610. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2611. $v['content'] = $v['nickname'].'成为渠道商,帮您攒金';
  2612. $res['bill_end_time'] = strtotime($res['create_time']);
  2613. break;
  2614. case 'merchant_annual_cost_order':
  2615. $res = Db::name($table)->where("order_no",$order_sn)->field('uid,create_time,pay_time')->find();
  2616. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2617. $v['content'] = $v['nickname'].'成为商户,帮您攒金';
  2618. $res['bill_end_time'] = strtotime($res['create_time']);
  2619. break;
  2620. default:
  2621. $res = Db::name($table)->where("order_sn",$order_sn)->field('uid,create_time,bill_end_time,pay_time')->find();
  2622. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2623. $v['content'] = $yugu.$v['nickname'].'在'.$title.'消费,帮您攒金';
  2624. }
  2625. // $v['xiadan'] = $res['create_time'] ?? $create_time;
  2626. $v['xiadan'] = isset($res['pay_time'])?$res['pay_time']:$create_time;
  2627. $v['jiesuan'] = $v['xiadan'];
  2628. // if (empty($res['bill_end_time']) && empty($res['create_time'])){
  2629. // $v['jiesuan'] = $create_time;
  2630. // }else{
  2631. // $v['jiesuan'] = date('Y-m-d H:i:s',$res['bill_end_time']??strtotime("+10 day", strtotime($res['create_time'])));
  2632. // }
  2633. }
  2634. /**
  2635. * 获取订单数
  2636. */
  2637. public function get_tuiguang_order($member_id){
  2638. $where=["ul.type"=>"commission","ul.status"=>1,'ul.uid'=>$member_id];
  2639. $list=Db::name("user_bill")
  2640. ->alias("ul")
  2641. // ->join("user u","u.uid=ul.uid")
  2642. ->where("commission_type","<>",5)
  2643. ->where($where)
  2644. ->field("ul.mark,ul.bill_id,ul.type,ul.number,ul.status,ul.create_time,ul.uid,ul.order_sn,ul.create_time,ul.link_id")
  2645. ->select();
  2646. $num=0;
  2647. $count=0;
  2648. foreach ($list as &$v){
  2649. $num++;
  2650. // $v["create_time"]=date("Y-m-d", $v["create_time"]);
  2651. $uid=Db::name("store_order")->where("order_sn",$v["order_sn"])->value("uid");
  2652. $v["nickname"]=Db::name("user")->where("uid", $uid)->value("nickname");
  2653. $count+=$v["number"];
  2654. }
  2655. return ["num"=>$num,"count"=>round($count,2),"list"=>$list];
  2656. }
  2657. public function get_yanglao($member_id){
  2658. $data = Db::name("user")
  2659. ->where("uid",$member_id)
  2660. ->field("wechat_user_id,card_id,ali_user_id,annuity_frozen,annuity_num,annuity,create_time,birthday,birthday60,card_number,annuity_yiqu,pay_price")
  2661. ->find();
  2662. // $data['annuity'] = 0;
  2663. $certification = Db::name("user_certification")->where("uid",$member_id)->find();
  2664. $data['can_withdraw'] = 0;
  2665. if (!$certification || $certification["status"] !=1 || !$certification["user_card"]){
  2666. $data["birthday60"] = "未实名认证";
  2667. $data['is_certification'] = 0;
  2668. } else {
  2669. // try {
  2670. // $checkAmount = $this->checkAmount($certification);
  2671. // if ($checkAmount['code'] == 0) {
  2672. // $data['annuity'] = $checkAmount['extendData']['amount'];
  2673. // }
  2674. // } catch (\Throwable $e) {
  2675. // Log::info('getyanglaojin' . $e->getMessage());
  2676. // }
  2677. $data['is_certification'] = 1;
  2678. $birth_data = substr($certification["user_card"], 6, 8);
  2679. // $birth = strtotime(substr($certification["user_card"], 6, 8));
  2680. $old_age = $this->getSex($certification["user_card"])?60:55;
  2681. // $age = $this->howOld($birth);
  2682. $age=$this->calculateAge($birth_data);
  2683. if ($age < $old_age) {
  2684. // $yes = $old_age - $age;
  2685. // $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("+" . $yes . " year"));
  2686. }
  2687. if ($age == $old_age) {
  2688. $data['can_withdraw'] = 1;
  2689. // $data["birthday60"] = date("Y-m-d", $birth);
  2690. }
  2691. if ($age > $old_age) {
  2692. $data['can_withdraw'] = 1;
  2693. // $yes = $age - $old_age;
  2694. // $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("-" . $yes . " year"));
  2695. }
  2696. //收益余额
  2697. $data['annuity_num'] = 123;
  2698. $data['annuity_yiqu'] = 123;
  2699. $data["birthday60"] = $this->getFutureBirthday($birth_data,$old_age);
  2700. }
  2701. $order_merchant_price= OrderMerchant::getInstance()->where('paid', 1)
  2702. ->where(function ($query) use ($data) {
  2703. $query->where('pay_user_id', $data['wechat_user_id'])
  2704. ->whereOr('pay_user_id', $data['ali_user_id']);
  2705. })
  2706. ->sum('money');
  2707. //加上线下消费的
  2708. $data['pay_price'] = bcadd($data['pay_price'],$order_merchant_price,2);
  2709. $data["yinghang"] = "中信公证处消费养老金账户";
  2710. // $data["yinghang"]='https://app.bjtdba.com/uploads/def/20201021/8cb66944101287b8ac9c9b9fb1b13a79.png';
  2711. $data["add_up"] = 0.00;
  2712. return $data;
  2713. }
  2714. function calculateAge($birthDate) {
  2715. $today = new \DateTime();
  2716. $diff = $today->diff(new \DateTime($birthDate));
  2717. return $diff->y;
  2718. }
  2719. function getFutureBirthday($birthDate, $years) {
  2720. $date = new \DateTime($birthDate);
  2721. $date->modify("+$years years");
  2722. return $date->format('Y-m-d');
  2723. }
  2724. public function getSex($cid){
  2725. //根据身份证号,自动返回性别
  2726. $sexint = (int)substr($cid,16,1);
  2727. return $sexint % 2 === 0 ? false : true;
  2728. }
  2729. /**
  2730. * 根据时间戳计算年龄
  2731. * @param $birth
  2732. * @return mixed
  2733. */
  2734. public function howOld($birth) {
  2735. list($birthYear, $birthMonth, $birthDay) = explode('-', date('Y-m-d', $birth));
  2736. list($currentYear, $currentMonth, $currentDay) = explode('-', date('Y-m-d'));
  2737. $age = $currentYear - $birthYear - 1;
  2738. if($currentMonth > $birthMonth || $currentMonth == $birthMonth && $currentDay >= $birthDay)
  2739. $age++;
  2740. return $age;
  2741. }
  2742. public function yanglaolog($where,$page=1, $limit=10,$month='',$is_shixiao = 0){
  2743. $where1 = [];
  2744. if(!empty($where)){
  2745. foreach($where as $key => $value){
  2746. $where1['a.'.$key] = $value;
  2747. }
  2748. }
  2749. $query=Db::name("user_bill")
  2750. ->alias('a')
  2751. ->join('Merchant b', 'a.mer_id = b.mer_id','left')
  2752. ->field('a.*,b.mer_name,b.mer_avatar')
  2753. ->where($where1)
  2754. ->when($month!='',function ($q) use ($month){
  2755. $q->whereLike('a.create_time',$month.'%');
  2756. });
  2757. if($is_shixiao == 0){
  2758. $query -> where('a.status','<>','-1');
  2759. }
  2760. $query_sql1 = clone $query;
  2761. $query_sql2 = clone $query;
  2762. $query_sql3 = clone $query;
  2763. $count = $query->count();
  2764. $list = $query->page($page,$limit)->order("a.bill_id desc")->select()
  2765. ->each(function($item){
  2766. if($item['source'] == 0 && $item['type_shop'] == 0){
  2767. $item['product'] = json_decode(Db::name("store_order")
  2768. -> alias('a')
  2769. -> join('store_order_product b','a.order_id = b.order_id','left')
  2770. -> where(["a.order_sn"=>$item['order_sn']])
  2771. -> value('b.cart_info'),true);
  2772. if(empty($item['product'])){
  2773. $item['product']=[
  2774. 'product'=>[
  2775. 'image'=>'https://cdn.bjtdba.com/vod/image/2025-01-21/20250121180855764.png',
  2776. 'store_name'=>'商家年费'
  2777. ]
  2778. ];
  2779. }
  2780. }
  2781. return $item;
  2782. });
  2783. $yugu=$query_sql1->sum('number');
  2784. $yijiesuan=$query_sql1->where('a.status',1)->sum('number');
  2785. $weijiesuan=$yugu-$yijiesuan;
  2786. return compact('count','list','yugu','yijiesuan','weijiesuan');
  2787. }
  2788. /*养老金详情*/
  2789. public function yanglaoDetail($where=[],$field='*'){
  2790. $query=Db::name("user_bill")->where($where)->field($field)->find();
  2791. return $query;
  2792. }
  2793. /*提现记录 type 1佣金 2养老金*/
  2794. public function withdrawal($where){
  2795. $data=Db::name("user_extract")->where($where)->order('extract_id','desc')->select();
  2796. if(!$data->isEmpty()){
  2797. $data=$data->toArray();
  2798. }
  2799. foreach ($data as $k=>&$v){
  2800. if($v['withdrawal_type']==2){
  2801. // $name=Db::name('merchant')->where('mer_id',$v['mer_id'])->value('mer_name');
  2802. $v['title']='佣金提现';
  2803. }else if($v['withdrawal_type']==3){
  2804. if($v['extract_type']==1){
  2805. $tltle='微信';
  2806. $v['title']='提现到'.$tltle;
  2807. }else if($v['extract_type']==3){
  2808. $tltle='银行卡';
  2809. $v['title']='提现到'.$tltle;
  2810. }else if($v['extract_type']==4){
  2811. $v['title']='人工减少佣金';
  2812. }
  2813. }else{
  2814. $v['title']='幸福宝-佣金提现';
  2815. }
  2816. if($v['bank_info']!=''){
  2817. $bank_info=json_decode($v['bank_info'],true);
  2818. }
  2819. $v['extract_price']=set_price_rtrim($v['extract_price']);
  2820. $v['bank_name']=isset($bank_info['bank_name'])?$bank_info['bank_name']:'';
  2821. }
  2822. return $data;
  2823. }
  2824. /*提现记录 type 1佣金 2养老金*/
  2825. public function withdrawal_user($where){
  2826. $data=Db::name("user_extract")->where($where)->where('mer_id is null')->order('extract_id','desc')->select();
  2827. if(!$data->isEmpty()){
  2828. $data=$data->toArray();
  2829. }
  2830. foreach ($data as $k=>&$v){
  2831. if($v['withdrawal_type']==2){
  2832. // $name=Db::name('merchant')->where('mer_id',$v['mer_id'])->value('mer_name');
  2833. $v['title']='佣金提现';
  2834. }else if($v['withdrawal_type']==3){
  2835. if($v['extract_type']==1){
  2836. $tltle='微信';
  2837. $v['title']='提现到'.$tltle;
  2838. }else if($v['extract_type']==3){
  2839. $tltle='银行卡';
  2840. $v['title']='提现到'.$tltle;
  2841. }else if($v['extract_type']==4){
  2842. $v['title']='人工减少佣金';
  2843. }
  2844. }else{
  2845. $v['title']='幸福宝-佣金提现';
  2846. }
  2847. if($v['bank_info']!=''){
  2848. $bank_info=json_decode($v['bank_info'],true);
  2849. $data[$k]['bank_info']=json_decode($v['bank_info'],true);
  2850. }
  2851. $v['extract_price']=set_price_rtrim($v['extract_price']);
  2852. $v['bank_name']=isset($bank_info['bank_name'])?$bank_info['bank_name']:'';
  2853. }
  2854. return $data;
  2855. }
  2856. /*
  2857. * 提现详情
  2858. *@author cabbage
  2859. *@date 2020-10-31
  2860. * */
  2861. public function withdrawalDetail($id,$uid){
  2862. $data= Db::name("user_extract")->where(["uid"=>$uid,'extract_id'=>$id,"type"=>2])->find();
  2863. return $data;
  2864. }
  2865. /*
  2866. * 修改用户推广人id
  2867. *@author cabbage
  2868. *@date 2020-10-31
  2869. * */
  2870. public function update_spread($uid,$spread_account){
  2871. //推荐人信息
  2872. $spread = Db::name("user")->where('account',$spread_account)->field("uid")->find();
  2873. //被推荐人信息
  2874. $identity=Db::name("user")->where('uid',$uid)->field("identity,spread_uid")->find();
  2875. $user_identity_log=Db::name("user_identity_log")->where(["link_id"=>$uid])->find();
  2876. if($spread){
  2877. try{
  2878. $data= Db::name("user")->where(["uid"=>$uid])->update(['spread_uid'=>$spread['uid']]);
  2879. Db::name("merchant")->where(["uid"=>$uid])->update(['recommender'=>$spread['uid']]);
  2880. if ($user_identity_log){
  2881. Db::name("user_identity_log")->where(["id"=>$user_identity_log["id"]])->update(['uid'=>$spread['uid']]);
  2882. }else{
  2883. Db::name("user_identity_log")->insert(['uid'=>$spread['uid'],"identity"=>$identity["identity"],"create_time"=>date("Y-m-d H:i:s"),"link_id"=>$uid]);
  2884. }
  2885. Db::name("user")->where('account',$spread_account)->inc("spread_count",1)->update();
  2886. if ($identity["spread_uid"]){
  2887. Db::name("user")->where('uid',$identity["spread_uid"])->dec("spread_count")->update();
  2888. }
  2889. return $data;
  2890. }catch (Exception $e) {
  2891. Db::rollback();
  2892. }
  2893. }else{
  2894. return false;
  2895. }
  2896. }
  2897. public function update_level_uid($uid, $level_account){
  2898. $level = Db::name("user")->where('account',$level_account)->field("uid")->find();
  2899. if($level){
  2900. try{
  2901. return Db::name("user")->where(["uid"=>$uid])->update(['level_id'=>$level['uid']]);
  2902. }catch (\Exception $e) {
  2903. return false;
  2904. }
  2905. }else{
  2906. return false;
  2907. }
  2908. }
  2909. public function update_user_group($id,$group_id,$adminid,$mark)
  2910. {
  2911. try {
  2912. Db::name("user_group_record")->insert(['adminid' => $adminid,'uid' => $id,'mark' => $mark]);
  2913. return Db::name("user")->where("uid", $id)->update(['user_group' => $group_id]);
  2914. } catch (\Exception $e) {
  2915. return false;
  2916. }
  2917. }
  2918. /*获取协议列表*/
  2919. public function getXieYi(){
  2920. $data= Db::name("user_agreement")->where(["status"=>1])->select();
  2921. return $data;
  2922. }
  2923. /*积分记录*/
  2924. public function socreList($uid,$page,$limit){
  2925. $data = Db::name("user_signinreward_record")
  2926. ->where(['member_id'=>$uid])
  2927. ->field("reward_socre,addtime")
  2928. ->page($page,$limit)
  2929. ->order("addtime desc")
  2930. ->select()->toArray();
  2931. foreach ($data as $k => $v) {
  2932. $data[$k]['addtime'] = date("y-m-d H:i:s",$v['addtime']);
  2933. $data[$k]['pm'] = 1 ;
  2934. $data[$k]['mark'] = '签到获得' ;
  2935. }
  2936. $result['list'] = $data;
  2937. $result['count'] = Db::name("user_signinreward_record")->where(['member_id'=>$uid])->count();
  2938. $result['total_socre'] = Db::name("user_signinreward_record")->where(['member_id'=>$uid])->sum("reward_socre");
  2939. $result['is_use'] = 0 ;
  2940. $result['is_pass'] = 0 ;
  2941. return $result;
  2942. }
  2943. /*修改用户信息*/
  2944. public function updateUser($uid,$data,$data2=[]){
  2945. $data = Db::name("user")->where(['uid'=>$uid])->update($data);
  2946. if ($data2){
  2947. $ck= Db::name("user_account")->where(["uid"=>$uid,"type"=>$data2["type"]])->find();
  2948. if ($ck){
  2949. $data= Db::name("user_account")->where(["id"=>$ck["id"]])->update($data2);
  2950. }else{
  2951. $data= Db::name("user_account")->insert($data2);
  2952. }
  2953. }
  2954. return $data;
  2955. }
  2956. /*获取用户信息*/
  2957. public function getUser($uid,$data){
  2958. $user = Db::name("user")->where(['uid' => $uid])->field($data)->find();
  2959. $data = Db::name("user_account")->where(['uid' => $uid])->select()->toArray();
  2960. $types = array_column($data, 'type');
  2961. if (!in_array('1', $types) && $user['wechat_user_id']) {
  2962. $data[] = ['id' => 0, 'avater' => '', 'nickname' => null, 'type' => 1, 'uid' => $uid];
  2963. Db::name("user_account")->insert(['type' => 1, 'uid' => $uid]);
  2964. }
  2965. if (!in_array('2', $types) && $user['ali_user_id']) {
  2966. $data[] = ['id' => 0, 'avater' => '', 'nickname' => null, 'type' => 2, 'uid' => $uid];
  2967. Db::name("user_account")->insert(['type' => 2, 'uid' => $uid]);
  2968. }
  2969. return $data;
  2970. }
  2971. public function getAccount($uid)
  2972. {
  2973. $userAccountList = Db::name("user_account")
  2974. ->where(["uid"=>$uid])
  2975. ->select()
  2976. ->toArray();
  2977. $wxNickname = '';
  2978. $wxAvater = '';
  2979. $alNickname = '';
  2980. $alAvater = '';
  2981. foreach ($userAccountList as $userAccount) {
  2982. if ($userAccount['type'] == 1) {
  2983. $wxNickname = $userAccount['nickname'];
  2984. $wxAvater = $userAccount['avater'];
  2985. } else if ($userAccount['type'] == 2) {
  2986. $alNickname = $userAccount['nickname'];
  2987. $alAvater = $userAccount['avater'];
  2988. }
  2989. }
  2990. $res=Db::name('user_extract_openid')->where('uid',$uid)->value('openid');
  2991. $wechat_user_id = Db::name('user') -> where('uid',$uid) -> value('wechat_user_id');
  2992. if($res && !empty($wechat_user_id)){
  2993. $arr[]=array(
  2994. 'id'=>'1',
  2995. 'type'=>'1',
  2996. 'uid'=>$uid,
  2997. 'nickname'=>$wxNickname,
  2998. 'avater'=>$wxAvater,
  2999. );
  3000. }
  3001. $res = Db::name('user') -> where('uid',$uid) -> value('ali_user_id');
  3002. if($res && $res != '0' && $res != ''){
  3003. $arr[]=array(
  3004. 'id'=>'2',
  3005. 'type'=>'2',
  3006. 'uid'=>$uid,
  3007. 'nickname'=>$alNickname,
  3008. 'avater'=>$alAvater,
  3009. );
  3010. }
  3011. return isset($arr)?$arr:[];
  3012. }
  3013. /**
  3014. * 支付宝授权登录
  3015. * 文档:https://opendocs.alipay.com/open/218/105327
  3016. */
  3017. public function aliSign(){
  3018. $aop = new AopClient;
  3019. $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
  3020. $aop->appId = "2021001197654668";
  3021. $aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEAlGWxvrR9KGkheEK4kTrcKDvK3ovhwi+zc4zxa11DZgpyUk2Kr2RT08ZQPaQLm9jQFlzwzqVgbAL9DFBTRAaD4nEMHoR0ZfR9ueRirko16Kjkx8AOPVYdEIy68U01gln/N9Y0iq8YVxu4Yv8vorY7U8aSJUcAnkx9bPbhei8SZxVgC2KldextzyVh9t/tAk2WAxbLmvieF746lY1u0W6AfmBIvQWdjbw3wJUMxMYrlp501zHr7kecgcYhnOnYkO9ehpVSAYJHoDDAulBEkapiSGiP09aOe3jhsutFDIrxL4BoFyNtaAOCbh6sUa9mMNu67wRBXwitfK7wOdt1gzfmOwIDAQABAoIBAQCODzQyzfGqh8nkqGqrjN9JHMQ+e0ZpcOSnT1ulXiixPHroUxbahH7DEuuptqruTIYXgm18RVCi1dGMwjCTxHDoizQA2ufa2kypcfsNwjkNOvGYT0DScudr+mzTpwf8e08ZEtRFlw0EBqNjEct2RmFQ95zcVrY+1BaWA1kicIF7b7/Zto7x7xAnR10tfRE2bUePBzruugZRk+Z9LbcKSRDAb/JBEFKHzfiBIFyIcEj9covcNVFF8QCkraxugDxH0dxYheFz7sxvjLyo2OYW+Xs2Q95/kVZIGWdz2T4IIqdvqjWzCn+azMvpB7056ziFrit6E2JNQH+8DrWsHj2b3xnhAoGBAOFwF44Qce7c9zTnvzZZlqONuHrzhsSxvHEU2mf+FitpFFASOhJcPoK18M0ZsUX7EwVQLCKSoKcdk34Y3msM0E+aihRpwBQbR1isdnSnbTcBRRpmVHnX50qXjHabvY4lPJQssMKsf0ezitFQP1NA7oNWhJzEDTRNZxqlo4Y3JGf5AoGBAKiD4MKR24l9EJ+aMnPW50jIkNj/sWslYTZn5b7zyt3e1gj39Er5ePCgzqVmKt5SK/SnS1PxEcQurVuw2Gs4/9vAYc25QAAYhZCbgHRTUhv1+1xontLyIIXChQABJElAEkTj+bpB5ps/rwOVR3znMyS1135o4Q+DyP+SW7BZ/NTTAoGBANp+J3Y7HhGh+7489igZAFUYIDqaGH4+vSLkUSIFMztzpopMgBgXa0aITBCc3CG1TCQUJhKEBkyx76eBNuCOFL9ySm2qaM2T+rxIuq4pL0LmajFCCJHm3XaAF1VFcJx6HpKGFfM3+ExoCR0BJ77q6cBFdFXz9dBBTLKY4zpL628RAoGAUeARejen9PtA8mrXDJVjtmdMiUJij26P9wEwDUEiVf6I+76NgUgIzNE01gP33CEMnkgSP2yndyw+qogX/rCpD7o/StcxE1rWulXzaZF6GX/Aazuhv1hJGPRT7pafbL+moLYrhaWzR8b/X7xOCY/Dt5hqZU7L2t/q7tHLnrl6MGUCgYBtgaNNSrj7wyqfresYG24h0cCSAg8ctG24CgrXc+kJF0rxHXuGjMSy0K22u3X/2CHRGGCmejFhbKI4Jg8FX+mZvG+7yMsQNVrx2Qzh1OSTHmd52nt7BW7mMrO7r3KYO7WzjeHtgwMp5/ZSPxsCkqLPf9Y3yzG+zwiwwZGrsSogVQ==';
  3022. $aop->format = "json";
  3023. $aop->charset = "UTF-8";
  3024. $aop->signType = "RSA2";
  3025. $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  3026. $data = [
  3027. 'apiname'=>'com.alipay.account.auth',
  3028. 'method'=>'alipay.open.auth.sdk.code.get',
  3029. 'app_id'=>'2021001197654668',
  3030. 'app_name'=>'mc',
  3031. 'biz_type'=>'openservice',
  3032. 'pid'=>'2088931546284482', //合作伙伴身份(PID):
  3033. 'product_id'=>'APP_FAST_LOGIN',
  3034. 'scope'=>'kuaijie',
  3035. 'target_id'=>"ALI".time().rand(10000,99999),
  3036. 'auth_type'=>'AUTHACCOUNT',
  3037. 'sign_type'=>'RSA2'
  3038. ];
  3039. $sign = $aop->generateSign($data,"RSA2");
  3040. $paramStr = '';
  3041. foreach ($data as $key => $param) {
  3042. $paramStr .= "{$key}={$param}&";
  3043. }
  3044. $paramStr = $paramStr.'sign='.urlencode($sign);
  3045. return $paramStr;
  3046. }
  3047. /*
  3048. * 支付宝登录验证
  3049. * $userId 支付宝用户唯一id
  3050. * */
  3051. public function aliCheck($userId){
  3052. $user = Db::name("user")->where(['ali_user_id'=>$userId])->find();
  3053. //判断是否是第一次登录
  3054. if($user){
  3055. //成功登录业务逻辑
  3056. if (!$user['account']) {
  3057. return ['code' => 400, 'msg' => '请绑定手机号'];
  3058. } else {
  3059. return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
  3060. }
  3061. }else{
  3062. return ['code' => 400, 'msg' => '请绑定手机号'];
  3063. }
  3064. }
  3065. /*微信信息获取*/
  3066. public function getWechat(){
  3067. $data['appid'] = "wxbf753066ac8686ba";
  3068. $data['appsecret'] = "68943fc124568c4ab4c3f089b7cdf2aa";
  3069. return $data;
  3070. }
  3071. /**
  3072. * 微信登录验证
  3073. * @param $openid
  3074. * @param $nickname
  3075. * @param $headimgurl
  3076. * @return array
  3077. * @throws DataNotFoundException
  3078. * @throws DbException
  3079. * @throws ModelNotFoundException
  3080. */
  3081. public function wechatCheck($openid, $nickname = null, $headimgurl = null): array
  3082. {
  3083. // 1、判断 该openID 是否绑定多个用户
  3084. $userDataList = Db::name("user")->where(['wechat_user_id' => $openid])->select()->toArray();
  3085. $normalUserDataList = [];
  3086. $normalUserData = [];
  3087. if (!empty($userDataList)) {
  3088. $resetWechatUserIdList = [];
  3089. foreach ($userDataList as $userdata) {
  3090. if ($userdata['is_del'] == 1) {
  3091. $resetWechatUserIdList[] = $userdata['uid'];
  3092. } else {
  3093. $normalUserDataList[] = $userdata;
  3094. }
  3095. }
  3096. if (!empty($resetWechatUserIdList)) {
  3097. Db::name("user")->whereIn('uid', $resetWechatUserIdList)->update(["wechat_user_id" => 0]);
  3098. Db::name("user_extract_openid")->whereIn('uid', $resetWechatUserIdList)->delete();
  3099. Db::name("user_account")->whereIn('uid', $resetWechatUserIdList)->delete();
  3100. }
  3101. if (count($normalUserDataList) > 1) {
  3102. return ['code' => 400, 'msg' => '当前账号异常,请联系客服!'];
  3103. } else if (count($normalUserDataList) < 1) {
  3104. return ['code' => 400, 'msg' => '请绑定手机号'];
  3105. } else {
  3106. $normalUserData = array_shift($normalUserDataList);
  3107. }
  3108. } else {
  3109. return ['code' => 400, 'msg' => '请绑定手机号'];
  3110. }
  3111. // 2、更新 user_extract_openid
  3112. $existOpenIdDataList = Db::name('user_extract_openid')->where('openid', $openid)->select()->toArray();
  3113. $normalUserDataListByExtractOpenid = [];
  3114. $normalUserDataByExtractOpenid = [];
  3115. if (!empty($existOpenIdDataList)) {
  3116. $existUidList = array_column($existOpenIdDataList, 'uid');
  3117. // 查询 用户
  3118. $existUserData = Db::name("user")->whereIn("uid", $existUidList)->select()->toArray();
  3119. if (!empty($existUserData)) {
  3120. $resetWechatUserIdList = [];
  3121. $deleteUserExtractOpenidByUidList = [];
  3122. foreach ($existUserData as $userdata) {
  3123. if ($userdata['is_del'] == 1) {
  3124. $resetWechatUserIdList[] = $userdata['uid'];
  3125. } else {
  3126. // if ($userdata['wechat_user_id'] == $openid) {
  3127. $normalUserDataListByExtractOpenid[] = $userdata;
  3128. // } else {
  3129. // $deleteUserExtractOpenidByUidList[] = $userdata['uid'];
  3130. // }
  3131. }
  3132. }
  3133. // 已删除的用户
  3134. if (!empty($resetWechatUserIdList)) {
  3135. Db::name("user")->whereIn('uid', $resetWechatUserIdList)->update(["wechat_user_id" => 0]);
  3136. Db::name("user_extract_openid")->whereIn('uid', $resetWechatUserIdList)->delete();
  3137. Db::name("user_account")->whereIn('uid', $resetWechatUserIdList)->delete();
  3138. }
  3139. // // 用户表绑定的 微信ID 和 微信授权表中的不一致
  3140. // if (!empty($deleteUserExtractOpenidByUidList)) {
  3141. // Db::name("user_extract_openid")->whereIn('uid', $resetWechatUserIdList)->where('openid', $openid)->delete();
  3142. // }
  3143. if (count($normalUserDataListByExtractOpenid) > 1) {
  3144. return ['code' => 400, 'msg' => '当前账号异常,请联系客服!'];
  3145. } else {
  3146. $normalUserDataByExtractOpenid = array_shift($normalUserDataListByExtractOpenid);
  3147. }
  3148. } else {
  3149. Db::name('user_extract_openid')->where('openid', $openid)->delete();
  3150. }
  3151. }
  3152. if (empty($normalUserDataByExtractOpenid)) {
  3153. if (!empty($normalUserData)) {
  3154. Db::name("user_extract_openid")->insert([
  3155. 'uid' => $normalUserData['uid'],
  3156. 'openid' => $openid,
  3157. 'type' => 1
  3158. ]);
  3159. } else {
  3160. return ['code' => 400, 'msg' => '请绑定手机号'];
  3161. }
  3162. } else {
  3163. if ($normalUserDataByExtractOpenid['uid'] != $normalUserData['uid']) {
  3164. return ['code' => 400, 'msg' => '当前账号异常,请联系客服!'];
  3165. }
  3166. }
  3167. $data2 = [];
  3168. if (!is_null($nickname) || !is_null($headimgurl)) {
  3169. $data2 = [
  3170. "type" => 1,
  3171. "uid" => $normalUserData['uid'],
  3172. "nickname" => $nickname ?: '',
  3173. "avater" => $headimgurl ?: '',
  3174. ];
  3175. }
  3176. $this->updateUser(
  3177. $normalUserData['uid'],
  3178. ['wechat_user_id' => $openid],
  3179. $data2
  3180. );
  3181. return ['code' => 200, 'msg' => '登录成功', 'user' => $normalUserData];
  3182. }
  3183. /**
  3184. * 微信登录验证一壶茶
  3185. * @param $openid
  3186. * @return array
  3187. * @throws DataNotFoundException
  3188. * @throws DbException
  3189. * @throws ModelNotFoundException
  3190. */
  3191. public function wechatCheckYhc($openid){
  3192. $enterprise_user = Db::name("enterprise_user")->where(['openid'=>$openid])->find();
  3193. //判断是否是第一次登录,成功登录业务逻辑
  3194. if($enterprise_user && $enterprise_user['uid']!=0){
  3195. $user = Db::name("user")->where(['uid'=>$enterprise_user['uid']])->find();
  3196. return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
  3197. }
  3198. return ['code' => 400, 'msg' => '请绑定手机号'];
  3199. }
  3200. /*微信支付宝绑定*/
  3201. public function thirdBinding(string $phone, ?string $pwd, $user_type = 'APP',$third_user_id='',$type=0,$url, $spread_uid = 0)
  3202. {
  3203. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  3204. $user = $this->accountByUser($phone);
  3205. if($user){
  3206. $data = [
  3207. 'last_ip' => app('request')->ip(),
  3208. ];
  3209. }else{
  3210. $data = [
  3211. 'account' => $phone,
  3212. 'pwd' => $pwd,
  3213. 'nickname' => '用户' . substr($phone, 7, 4),
  3214. 'avatar' => $url.'/uploads/logo.jpg',
  3215. 'phone' => $phone,
  3216. 'last_ip' => app('request')->ip(),
  3217. "level_id"=>$spread_uid,
  3218. "spread_uid"=>$spread_uid
  3219. ];
  3220. }
  3221. if($type ==1){
  3222. if(isset($user->wechat_user_id) && $user->wechat_user_id){return true;}//这里可能有问题
  3223. $data['wechat_user_id'] = $third_user_id;
  3224. }elseif($type ==2){
  3225. if(isset($user->ali_user_id) && $user->ali_user_id){return true;}
  3226. // if($user->ali_user_id){return true;}
  3227. $data['ali_user_id'] = $third_user_id;
  3228. }
  3229. if(!$user){
  3230. return $this->create($user_type, $data);
  3231. }else{
  3232. Db::name("user")->where(['account'=>$phone])->update($data);
  3233. return $user;
  3234. }
  3235. }
  3236. public function getTokenByCode($authorization_code,$info=false,$type=123)
  3237. {
  3238. try {
  3239. $aop = new AopClient();
  3240. $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
  3241. if($type=='h5'){
  3242. $aop->appId = '2021001197698727';
  3243. $aop->rsaPrivateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCf1r70C/D+XWtDuuV07/41UnEHRyas0Y92TRS5eI+S4v4r8lDY8aLcWM6ssE/dVaKrGulEqG3jv12WLRP7ZDiHSzlcgrHZLm9sub+rY9r7dPMn69xaVg/wMh7SQ5yduHXr1WtjIlnb4ng29ZoQjzHy9kgQ0i92Vtk1PRsQrlUWeYGXjftBShdHMraP7km8tvA5S+tTalczzkDm5i2lXHeycAkIiTJ1dqebA74ZCe47kyG0AtNbRBOMOB0zOFcHX865Faa1hPPlug98o6D6oyR4M/rkehqtf1Y1AIuBGIDSey4BmOvIqOiu/WbLTSx7TS9OxXBoP3SFMKiVKMqR7yH5AgMBAAECggEAGf3QpVy/vo0wYR4mK+LOwpr6WEWgq1+UZZdZNGO/bRJOZJUNwolgg1ZJnVk6U3KWdh51Kj39SJiYvk/sPOfqLU31MO7rvrZHVjXKTjN5q4Qz+hzngyUViGiODIEEGb2iJ0xYHxG57QChrcY4XFL8u1aDF4EmSKcMwRSDry26FmI/uEfjuF30kl11r24CtifE/NkbnqeWzOvoXteWxb1DbUsiqjRydnqUme5BPNoFhp5maYMZVUyg+I92G39FlQ1xQSJVq68TpL7ePOf8JBrGLqHSqNAiAfFwuvUWpELBstc4GPvQeWAw8142dsQGWz2wHZjUZW9CEyfrPDXZUz2wkQKBgQDdzpWkLNSjqhzdxcWw6z4bTguRVc594s5wbMftrKEybVbutVYjVKYi3rzSRRMcbr7vkkCj7FkQsmjY5l/wrv/CBrN/OPhQ7dDGTdEjtU2pnhDOvLaXIvcinz9YeAVHGePXXyx43wo5LysCqhAIxA5lS+LOuZZxQJzYVOv18uI6NQKBgQC4eqT8DiYb81Ke5l4Q5irOOd9Q/PqtCDJAyOkZVjMKBNOJauHZdx+rFgB2GEB2EdI5rUPDLn4XBkmeHlqk15HjLGA2kl4AojB2eCfD9voYHOTOEiAGpm9AL9Ws8ALFg27W1XKu/Ih1IxHifCAeR86lnIejJCizQ/P2lilWBj9hNQKBgQC8E9cZbhYkbTOq7W9TNDXmi0gNxXehkPdBp0vkAhRxoPss0ECpFrcFLF9p4L5yxolKtXXwSZHAMbfr63SArrMZv/rmLtWIMg9sh0GGiM7Au9I+qxAcmb568hORnbvD7XUgA4i/OUj+8jsDOFb+R9h5Fl7MsduaTpJwcZnfZENl3QKBgEKMq9vp1sGag6GjBSgfgC2pHvB+cofdPxOz5rMnL35bw1v9XMAwgxIa+8uecBKn1yjLYniU2xO/Ruttk9GHmq9TINpO7u5XlBgIvH+rJwlv0vKsAzWi8Ns85l5erwFFqsSBd7+8hhWLszX7BTMnQFrqHtwxfSU+TFIWVY8c7dxJAoGAaXqh1VejqHCPLfQ7Dthx0lEkzXOdUaPVh+LW7F5RPCBBnhsaFGlKVOQYHm6oFtH9qLgZBT1IkA7HTGX9YYTX8jl1zvgUNvxFOprPyYCo5O7vsa7KfkIzZt2FnycI83NAKYDTpA8q28YI81rcHcRLRbmun2drEPyj9dG79uy6Xg8=';
  3244. $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  3245. }else if ($type == 'h5pay'){
  3246. $aop->appId = '2021003191617008';
  3247. $aop->rsaPrivateKey = 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC9fXH7s0dBJ6y7K4M9rhsAf4MMYaOb/V7rIrmh1EJB1msW9QprLEIKIlmn4289/CRTXzVAOk9xWI6ROesq/C0RVh7ZxyM4Gm++znW+eoBsWXsmsMHuvKrrI+rec0JG4d/iWhy8j2YPhn/s3xo1/lHzdo7F0y0waJZdkzFErpO0bra+TtB6QpM3EXZFZ5FAw14bGJklI4mU14B50JLKSXPUJpm+B32OAWhz7FFdC+HIT22ZOAjFicPUwmn/8kzkV6ukPXpVHdp2EBRaH7EmBYw49ICp0YotHroFJVMRqzCeff5or8CBRv528zAAB0Q+jBxIhVbQebHLnrtVy2j+e/S1AgMBAAECggEBAIdmFMVitD6VR/KyQ+QV/Utc0dpOBmdXI7Tmqjg9gF6lBP5xd9Fe3Y16QBAcDof/HEHKnTVYtR1rxut0tFqRuO5TWFYK2lqjYUe5JR9HT26cfcgGs3yQqZy9nHz5ZNlbWuvVsgT2floHpG8wd/0uzYYnKBupKvgVM6SHocPO7tIUsxw9dGYdKrZnES6YbjlpPen7VUgvvdCWlaOooQNFEdqkgFywO9qxcVZ9kiE/0QijbAnJPaf9yvYqRRPqgydBDDBiSVklwyqaNcXj7vWeJi40oXBKhzHcPhkE7pWkc1eNjCx/SpAt1dAbgXoXpJsYba6VnxVfTUw5uHewko0H1AECgYEA6I+pE5WKRxWlbe09EDaO2FIzY5HWn463P3Is8StywnHbr27mqi8WmL0Re0ptRS5G1Xw/7yfRot1eLLZ0PoAd1/+ubd3MdhfFFYKhcTDxlrC56okVFYjz9JTF5WLwNG+aoeVzfhZuurqaPowEyTRM27y0WluTCvxaINNtg5rE7QECgYEA0JaAKs8pYIHd35YnsJAPaEvQ4fWbonUkOiEpZznKr/bU8aOO4NXs9aoZ/VXmBYscyjmpjVhF+TOr7EI37dVIFNpJ0eS9H2Bpdv0B2x7++qFxOmAQBFTQyL6wQt6j7p7JXP5TlH3mRpnAnxJ9FXssJxfYGwmSOcjOZhkHXMSZY7UCgYEAjhV3TyfF27g14ftXm1g53aAbFXI8li8zdefj3VSWQIYfmgc/lio+vAKHc7P9Ho8vZ68JwKurQL3Ok7LFQoozsYvcnfMsv9m153Zv/B/S+iXu8IPgBdAue/eJEKRp7R9ichclgJtj+2GWazBQnDz/2CBqb+oS5FtZFUUXW5hrSAECgYARsWJnvzC8Tee7CmqNcHrOFvg94m50JkmPYLa5Wc6WhHJlmMEK0zqJUAdqVLnxKG6lvKRkJ+OvkrF3ldpWoyu9ERMH6cYc/jmT7TwWERgBvGX1VKanJ2aaUIp08ZuoJvHfoHcIdnFs9afAFnpjsxH4su4SxQoROrY/NMpKFScJrQKBgQClpi0+cJOqK4XHaM3jfW4+vfHKJSR/kuDp3WgDirkeD3NnS8BUMWeIYNGsF0vs6NYk5ux95RObn+Ih++NkkrSsH7+z40LXYLePYK9h7M0anRTFlBuFUM5matclvtlJiET4o+w6thQIIv0Mhmo4ZHrLBsnqsOsbWnh6o0gtWqVKxQ==';
  3248. $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuUb+0sJSNXjWiG0VJIPzn55+18af/fubYMpRLlreu34ewMgLx1zpCNpB3wrA+dylfWPMAm8PzvKnakByB+VJ/LMNhWHmF8Qkdo4astAikjlI4TMQCK/G384NzrtjHR4DGCDM5CMVt1xw5noF7kNBMYIvgDfhMCYmygdlIjuVdIlVEoQKOsT0RaNMleES0aZvbjvBGkGM0dsetqUExSjid9BF1NAO2ET+J3XMxCtMgCUVmFUvxsCKe6Rapa1/Lk3rzIeG6CRpoabuYfPM9E+3y3f3luSOMXLfH9lOSW1RA8qrF+Ms1RZv8gmzUnbyrPLmmZPmmN/Qs6DGzDVg73fpSwIDAQAB';
  3249. }else{
  3250. $aop->appId = '2021001197654668';
  3251. $aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEAlGWxvrR9KGkheEK4kTrcKDvK3ovhwi+zc4zxa11DZgpyUk2Kr2RT08ZQPaQLm9jQFlzwzqVgbAL9DFBTRAaD4nEMHoR0ZfR9ueRirko16Kjkx8AOPVYdEIy68U01gln/N9Y0iq8YVxu4Yv8vorY7U8aSJUcAnkx9bPbhei8SZxVgC2KldextzyVh9t/tAk2WAxbLmvieF746lY1u0W6AfmBIvQWdjbw3wJUMxMYrlp501zHr7kecgcYhnOnYkO9ehpVSAYJHoDDAulBEkapiSGiP09aOe3jhsutFDIrxL4BoFyNtaAOCbh6sUa9mMNu67wRBXwitfK7wOdt1gzfmOwIDAQABAoIBAQCODzQyzfGqh8nkqGqrjN9JHMQ+e0ZpcOSnT1ulXiixPHroUxbahH7DEuuptqruTIYXgm18RVCi1dGMwjCTxHDoizQA2ufa2kypcfsNwjkNOvGYT0DScudr+mzTpwf8e08ZEtRFlw0EBqNjEct2RmFQ95zcVrY+1BaWA1kicIF7b7/Zto7x7xAnR10tfRE2bUePBzruugZRk+Z9LbcKSRDAb/JBEFKHzfiBIFyIcEj9covcNVFF8QCkraxugDxH0dxYheFz7sxvjLyo2OYW+Xs2Q95/kVZIGWdz2T4IIqdvqjWzCn+azMvpB7056ziFrit6E2JNQH+8DrWsHj2b3xnhAoGBAOFwF44Qce7c9zTnvzZZlqONuHrzhsSxvHEU2mf+FitpFFASOhJcPoK18M0ZsUX7EwVQLCKSoKcdk34Y3msM0E+aihRpwBQbR1isdnSnbTcBRRpmVHnX50qXjHabvY4lPJQssMKsf0ezitFQP1NA7oNWhJzEDTRNZxqlo4Y3JGf5AoGBAKiD4MKR24l9EJ+aMnPW50jIkNj/sWslYTZn5b7zyt3e1gj39Er5ePCgzqVmKt5SK/SnS1PxEcQurVuw2Gs4/9vAYc25QAAYhZCbgHRTUhv1+1xontLyIIXChQABJElAEkTj+bpB5ps/rwOVR3znMyS1135o4Q+DyP+SW7BZ/NTTAoGBANp+J3Y7HhGh+7489igZAFUYIDqaGH4+vSLkUSIFMztzpopMgBgXa0aITBCc3CG1TCQUJhKEBkyx76eBNuCOFL9ySm2qaM2T+rxIuq4pL0LmajFCCJHm3XaAF1VFcJx6HpKGFfM3+ExoCR0BJ77q6cBFdFXz9dBBTLKY4zpL628RAoGAUeARejen9PtA8mrXDJVjtmdMiUJij26P9wEwDUEiVf6I+76NgUgIzNE01gP33CEMnkgSP2yndyw+qogX/rCpD7o/StcxE1rWulXzaZF6GX/Aazuhv1hJGPRT7pafbL+moLYrhaWzR8b/X7xOCY/Dt5hqZU7L2t/q7tHLnrl6MGUCgYBtgaNNSrj7wyqfresYG24h0cCSAg8ctG24CgrXc+kJF0rxHXuGjMSy0K22u3X/2CHRGGCmejFhbKI4Jg8FX+mZvG+7yMsQNVrx2Qzh1OSTHmd52nt7BW7mMrO7r3KYO7WzjeHtgwMp5/ZSPxsCkqLPf9Y3yzG+zwiwwZGrsSogVQ==';
  3252. $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  3253. }
  3254. $aop->apiVersion = '1.0';
  3255. $aop->signType = 'RSA2';
  3256. $aop->postCharset='UTF-8';
  3257. $aop->format='json';
  3258. $request = new AlipaySystemOauthTokenRequest ();
  3259. $request->setGrantType("authorization_code");
  3260. $request->setCode($authorization_code);
  3261. $result = $aop->execute($request);
  3262. Db::name('log')->insert(['data'=>'支付宝相关信息']);
  3263. if (isset($result->alipay_system_oauth_token_response->user_id)) {
  3264. $return['user_id'] = $result->alipay_system_oauth_token_response->user_id;
  3265. $return['msg'] = $result->alipay_system_oauth_token_response->access_token;
  3266. $access_token=$return['msg'] ;
  3267. } else {
  3268. $return['code'] = $result->error_response->code;
  3269. $return['msg'] = $result->error_response->sub_msg;
  3270. return $return;
  3271. }
  3272. if ($info){
  3273. $request = new AlipayUserInfoShareRequest();
  3274. $result = $aop->execute ( $request ,$access_token);
  3275. $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
  3276. Db::name('log')->insert(['data'=>\GuzzleHttp\json_encode($responseNode)]);
  3277. $resultCode = $result->$responseNode->code;
  3278. Db::name('log')->insert(['data'=>$resultCode]);
  3279. $userData=json_decode(json_encode($result->$responseNode),true);
  3280. if(!empty($resultCode)&&$resultCode == 10000){
  3281. return $userData;
  3282. }
  3283. }
  3284. return $return;
  3285. } catch (\Throwable $w) {
  3286. Db::name('log')->insert(['data'=>json_encode($w->getMessage())]);
  3287. return $w->getMessage();
  3288. }
  3289. }
  3290. /**
  3291. * 使用证书方式,通过 authCode 换取支付宝 AccessToken 和用户信息
  3292. *
  3293. * @param string $authorization_code 从 APP 获取的授权码
  3294. * @param bool $info 是否在获取 Token 后立即获取用户信息 (true: 获取, false: 只获取 Token)
  3295. * @return array 成功时返回包含 token 或用户信息的数组,失败时返回错误信息数组或字符串
  3296. * @throws \Exception
  3297. */
  3298. public function getTokenByCodeWithCert(string $authorization_code, bool $info = false): array
  3299. {
  3300. try {
  3301. // --- 1. 配置证书信息 ---
  3302. // *** 请确保这里的 AppID 和 PrivateKey 是你进行【授权登录】的那个支付宝应用的 ***
  3303. // *** 它可能与你进行【转账】的应用是同一个,也可能是不同的,请仔细核对 ***
  3304. $app_id = "2021003138690179"; // 例如: 20210021XXXXXXXXXX
  3305. $privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJzre792RQs7dqI/M0WxGa5U6i04uUgscfsFx1hK5DYU9xrT5wxL7ixutwxQe0Ytpt2CLwerlGs8+s9OefY5eDT4yBqlM/wypEKkxC+nC4gU4K5PRIQaIk3Hrqs7U/Fe3g1XVY7bJpRoYEWp+EWn6meJSQ53PwKPUpm7EjoKyjprAw+Uk+2U797KR/5ANIyRELsCZDHwQGG+zs4WsmJ5rvpARrTFbPxKnlp3ozBqP3J/N5PVr853wf72G2Lg8H5JOdnZfKmW+Q7Deo9EngZ51x9KHIRAb+3S1zNdRfCClUXwFK4RVMrnuGsWPcc6/o8QtuvNj9fAEC/K82NgMx3Z7LAgMBAAECggEAZFYrtuMwmgXQJKraOCOalOIiuDE4rr/thageGb6qNwsSEd2m2eqWZX2aDTiYHIHhMhstjVR9s/nV2sNSJd4YghYYYoyGIqXSD2GQty+rhNs43HvJVRbcnOQfZuXDsJQh6BLjZwViYn5js6XcATz2e/TNjxfGdXUM0+e1ORCSwm/R8D6IJ9GXW+iY+bljuT6BbGpFsVcPznR0v04aPQS0g0JitkiNsUFmi1QZZCmblr77TYzw5Sye+XC5OkC1zmjxQk5ynzP9nrFH1pMTv2LWNn+lbFRV796FOa5qfQMXd9FX1x+TPZVgpOMJwDYR1uFqgmPxfn8r2jDrD5Tg9d4XMQKBgQDq+cHlzYtdpThqqXGBX1N2BwApI7pLHsXL/5hDb3k1mC1xAnwNeehUamA6c0apxzt80cR9mUnrWDE+zG7Ysg+GIsSRDBqKy+X58nSKyV3hj1HOBn8eBjn/kOGnB0vo0uYWY5+vXWHYh6VrfnKAo5NuYMn4s3qbYeyKxyNSnne/IwKBgQCWI0WzNP4uTk/zM2oweqfSyZwvpCabHrZSQ68Xht/UxwtUkOYyddBcQksn/daxoohIgzxgt6vFa8MUTI3GFr85ccWVh3bFo3CzWIr33WuoS8eEwgiKExxuqjq0D16euymtzJxes7JYL5BXhjSMba/4DllDAIdY+KRXveEZNcSwOQKBgDMaQFYnHrEuFpfz4/Cb973KhflsgL6HocLdApNf8f966h8SyEHyCloZjHYJzgtsff6GbHJYXSAm3QboVQ8hooislQ1qkXcwIwL5/OiWJKnCjqr89LZl6kUvkDPQPW0UOOATqI3uBDKgRZScOnDJom219Rb2iaqzYEtKRd9ZAXf7AoGBAJQubf2I4RJ88oXbigQdGwR9Pez7e6sALfyVlvuGf+Z3KaSmerz08NgOCjWHYF3kR9Qhyva+cQeh62FeiVMoYkXlF5kUoVJBlNs+GbK31Ci/2kUaaOk2IYrL8rKCtOW/XkyONQt3Gh/VmgX4jGbJX7NZHhp2LB/REAsVelSyb9VpAoGAU3Yya31scUBJeyMr0GkHfbv4jQ0A895W9W7Iaku2uoZd71kefqMwyun/oOgtivp9tGEFaEy8Sa3PJ380VLy8q37RyUs+UZ4rQRsniwdHILs5PHLiF64r6K1aGrrBdnToR5muUaadx22ZhtZC7VMq+Xqof89dsJO16Diu3RXN36k="; // 从.pem文件读取 或 直接粘贴(不推荐)
  3306. // *** 证书文件路径 ***
  3307. // 建议使用绝对路径或相对于项目根目录的路径,确保PHP有读取权限
  3308. $app_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/appCertPublicKey_2021003138690179.crt'; // 应用公钥证书路径
  3309. $alipay_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/alipayCertPublicKey_RSA2_2021003138690179.crt'; // 支付宝公钥证书路径
  3310. $alipay_root_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/alipayRootCert_2021003138690179.crt'; // 支付宝根证书路径
  3311. // $app_id = "2021002194632049"; // 例如: 20210021XXXXXXXXXX
  3312. // $privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGxceDFVT6VTYClinyAdY4PxE6MadNYLZ3sbLOLV14e39kuu1lkKDBZ/KPRNruPlSPGdiRVe+L8v4rsVk6bthsS/vMk5aH1wQyt58/HvHmZ5QVo3U5UD7cgqqefTcRJjKhjjM1rU/OrOkOqyssaLRukW3jeKRlBccUgtaGsXXrbMxWYpzl1OMDhKRRUVxu3LTfqlMpHghOasQrgyD92q9wlUN7U6hBYzGUocO/N3sz97PZwptwWAW0r3CFdlLCpgnMr+xb/Zh8td1OKGl3wEghiGavgDDlc2+w/xtk1SZ3pJbnGAU+D+oyJ6r76po6vkyGIlLrKp/zQ50az7fObzgNAgMBAAECggEBAK60szERlMkaEAih92gQGTsCo5+keMnX0UjO1LvGv7rfwQ7GBVYZklGrjVRDTrHL8wJ70w+amptFDgVVMXncZzh4aG5c4heu8q+pGLyf9DlwnIWQT736O+YQqun2YGogSqwYkgYBuH2NGKKd66pytPPhutYN+WAZfesXPHrSizRJtZMfuZvvGzm6ZJLZ1LmhvkOuLrX4xrJGRs1nAwZOmOfi4MY5VASblfPj59fUim9hErocNaX4uiMVwmhQl2QuOM/EbTd1UkW+dkV/gyQMOFzpcfN+SEi+hdLN+JiR9TVEcwity6ihOG5+3X33GKzfY4WFxeHHUaqA0SQWSkKofMECgYEA5OF5Imtq8/6JjWJ0jvYCpUnj9742McGJZTWBoTn9Hp0d3bwyE3YbH8pBVJyvzlfPKB9TUjE2FzVZvQtxEu+ZxToccp/LPqlgITWNHCmEtzAgXW7ww2PafgDZJ2QRSyjLUeRIWSAkeilj64XMCEC/bEs/nb5nmUb2gnsNTvvpMLUCgYEA3lMMtaIZH1fMI4XMNaPFzeRiKc0FIcLEem/efnPetPuOCujIWQJ/x9cCDCcfqO59I1FXQuiC/E1dFvme2qs/H7h2bFu8RG0M/ZQWd9twg31Sh+R7gCQakFERag8HXc4AWfBGXCvMu1SmSovU49KecSLxYGOAUdp77j1GxtLiePkCgYAQjc45ExPVOd+w/iH4BQsD8Wgvju5Ugu7xBwGtK4iHIk36r5XfmnczwWkgOYTto6Qz/rAEDdMfspge+CjhebrhbOaJ08zbZ1ywijL+inIy3aQ5ncCEIUC4RE9wbehiSz0JWz1wVMbOnxe+/RpYrnYp2vdq7U6I430IyuWXhNjE0QKBgEtJUmd7oghEIgPxfiq37/b+HOPM4q0BGKnhkjW+JS+idAJru9SwjPbub2oQIZ+CS2wXUnZ86EZqKFjsZQflr7WdMLUXB5UgXKLOcCFcdSiB2t3b2JqXH0u5uCzzM+pnJSVPwXPa/TR+wOVDnu8bVr43OAgNCdouI4OUyo/vv/N5AoGATJaIvpsZ9v1zmhbtJbgPBM9dhD2PIp2ufZ7yvhGGzA02FqAbyAeVsI2d+W+uA6jJ1X87x27pQv//mFoFXStxX3/bhdgTWbUYEWobAhw1jBS1rMQfLuBGGI/LsHGhzau3U+59erC5sYhGgZKSdXDyjOduWQlPWAv6ufkNZ+I3FCU="; // 从.pem文件读取 或 直接粘贴(不推荐)
  3313. //
  3314. // // *** 证书文件路径 ***
  3315. // // 建议使用绝对路径或相对于项目根目录的路径,确保PHP有读取权限
  3316. // $app_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/appCertPublicKey.crt'; // 应用公钥证书路径
  3317. // $alipay_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/alipayCertPublicKey.crt'; // 支付宝公钥证书路径
  3318. // $alipay_root_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/alipayRootCert.crt'; // 支付宝根证书路径
  3319. $url = "https://openapi.alipay.com/gateway.do"; // 支付宝网关
  3320. // --- 2. 初始化支付宝配置 (使用 AlipayConfig) ---
  3321. $alipayConfig = new AlipayConfig();
  3322. $alipayConfig->setAppId($app_id);
  3323. $alipayConfig->setCharset("utf-8");
  3324. $alipayConfig->setFormat("json");
  3325. $alipayConfig->setSignType("RSA2");
  3326. $alipayConfig->setServerUrl($url);
  3327. $alipayConfig->setPrivateKey($privateKey); // 设置应用私钥
  3328. // *** 设置证书路径 ***
  3329. $alipayConfig->setAppCertPath($app_cert_path);
  3330. $alipayConfig->setAlipayPublicCertPath($alipay_cert_path);
  3331. $alipayConfig->setRootCertPath($alipay_root_cert_path);
  3332. // --- 3. 实例化证书模式客户端 (使用 AopCertClient) ---
  3333. $aop = new AopCertClient($alipayConfig);
  3334. $aop->isCheckAlipayPublicCert = true; // 强烈建议启用支付宝公钥证书校验
  3335. // --- 4. 创建并执行获取 Token 的请求 ---
  3336. $request = new AlipaySystemOauthTokenRequest();
  3337. $request->setGrantType("authorization_code");
  3338. $request->setCode($authorization_code); // 设置从 APP 获取的 authCode
  3339. // 执行请求
  3340. $result = $aop->execute($request); // R 返回的是原始响应字符串,需要解码
  3341. $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; // 结果节点的 key,例如 "alipay_system_oauth_token_response"
  3342. // 解析 JSON 响应
  3343. $resultObj = json_decode($result);
  3344. Db::name('log')->insert(['data' => '支付宝Token获取响应解析: ' . json_encode($resultObj, JSON_UNESCAPED_UNICODE)]);
  3345. // --- 5. 处理 Token 响应 ---
  3346. // 检查是否存在响应节点,并且顶层没有 error_response
  3347. if (isset($resultObj->$responseNode) && !isset($resultObj->error_response)) {
  3348. // 成功获取 Token
  3349. $response = $resultObj->$responseNode; // 获取响应数据对象
  3350. // $return_data = [
  3351. // 'code' => 200,
  3352. // 'msg' => 'Token fetched successfully',
  3353. // 'user_id' => $response->user_id, // 从 $response 获取
  3354. // 'access_token' => $response->access_token, // 从 $response 获取
  3355. // 'refresh_token' => $response->refresh_token,
  3356. // 'expires_in' => $response->expires_in,
  3357. // 're_expires_in' => $response->re_expires_in,
  3358. // // 确保 alipay_user_id 也捕获,如果需要的话 (看你的业务逻辑)
  3359. // // 'alipay_user_id' => $response->alipay_user_id,
  3360. // ];
  3361. $access_token = $response->access_token;
  3362. // --- 6. (可选) 获取用户信息 ---
  3363. if ($info) {
  3364. // ... (获取用户信息的逻辑保持不变,因为它内部的判断可能是正确的) ...
  3365. $userInfoRequest = new AlipayUserInfoShareRequest;
  3366. $userInfoResult = $aop->execute($userInfoRequest, $access_token);
  3367. $userInfoResponseNode = str_replace(".", "_", $userInfoRequest->getApiMethodName()) . "_response";
  3368. $userInfoResultObj = json_decode($userInfoResult);
  3369. Db::name('log')->insert(['data' => '支付宝UserInfo获取响应解析: ' . json_encode($userInfoResultObj, JSON_UNESCAPED_UNICODE)]); // 记录日志
  3370. // !!! 这里判断 UserInfo 响应的逻辑通常是正确的,包含 code == '10000' !!!
  3371. if (isset($userInfoResultObj->$userInfoResponseNode) && isset($userInfoResultObj->$userInfoResponseNode->code) && $userInfoResultObj->$userInfoResponseNode->code == '10000') {
  3372. // 成功获取用户信息
  3373. $userInfoResponse = $userInfoResultObj->$userInfoResponseNode;
  3374. Db::name('log')->insert(['data' => '支付宝用户信息获取成功: ' . json_encode($userInfoResponse, JSON_UNESCAPED_UNICODE)]);
  3375. return [
  3376. 'user_id' => $userInfoResponse->user_id,
  3377. 'nick_name' => $userInfoResponse->nick_name ?? null,
  3378. 'avatar' => $userInfoResponse->avatar ?? null,
  3379. // 其他字段...
  3380. // 'gender' => $userInfoResponse->gender ?? null,
  3381. // 'province' => $userInfoResponse->province ?? null,
  3382. // 'city' => $userInfoResponse->city ?? null,
  3383. ];
  3384. } else {
  3385. // 获取用户信息失败
  3386. $errorMsg = 'Failed to get user info';
  3387. $subMsg = '';
  3388. // 优先从 UserInfo 对应的 ResponseNode 获取错误信息
  3389. if (isset($userInfoResultObj->$userInfoResponseNode) && isset($userInfoResultObj->$userInfoResponseNode->sub_msg)) {
  3390. $errorMsg .= ': ' . $userInfoResultObj->$userInfoResponseNode->sub_msg;
  3391. $subMsg = $userInfoResultObj->$userInfoResponseNode->sub_msg;
  3392. }
  3393. // 否则尝试从 UserInfo 的 error_response 获取
  3394. elseif (isset($userInfoResultObj->error_response) && isset($userInfoResultObj->error_response->sub_msg)) {
  3395. $errorMsg .= ': ' . $userInfoResultObj->error_response->sub_msg;
  3396. $subMsg = $userInfoResultObj->error_response->sub_msg;
  3397. }
  3398. Db::name('log')->insert(['data' => '支付宝用户信息获取失败(Token已成功): ' . $errorMsg . ' | Raw UserInfo: ' . $userInfoResult]);
  3399. return []; // 仍然返回成功的 Token 和用户信息错误标记
  3400. }
  3401. } else {
  3402. // 不需要获取用户信息,直接返回 Token 数据
  3403. Db::name('log')->insert(['data' => '支付宝Token获取成功(无用户信息请求): ' . json_encode($response, JSON_UNESCAPED_UNICODE)]);
  3404. return [];
  3405. }
  3406. } else {
  3407. // 获取 Token 失败
  3408. $errorMsg = 'Failed to exchange token';
  3409. $subMsg = '';
  3410. // 优先检查是否有 error_response
  3411. if (isset($resultObj->error_response)) {
  3412. $errorMsg .= ': ' . ($resultObj->error_response->sub_msg ?? 'Unknown error');
  3413. $subMsg = $resultObj->error_response->sub_msg ?? '';
  3414. }
  3415. // 其次检查 responseNode 中是否有错误信息 (虽然不常见于 Token 接口)
  3416. elseif (isset($resultObj->$responseNode) && isset($resultObj->$responseNode->sub_msg)) {
  3417. $errorMsg .= ': ' . ($resultObj->$responseNode->sub_msg ?? 'Unknown error');
  3418. $subMsg = $resultObj->$responseNode->sub_msg ?? '';
  3419. }
  3420. Db::name('log')->insert(['data' => '支付宝Token获取失败: ' . $errorMsg . ' | Raw Token: ' . $result]);
  3421. return [];
  3422. }
  3423. } catch (\Exception $e) { // 捕获 SDK 或其他异常
  3424. Db::name("log")->insert(['data' => 'Alipay Token/Info Error: '.$e->getFile() . ':' . $e->getLine() . '【' . $e->getMessage() . '】']); //日志记录
  3425. return [];
  3426. }
  3427. }
  3428. // 你可以在 Controller 的其他方法中调用这个函数
  3429. public function handleAlipayCallback($authCode)
  3430. {
  3431. if (!$authCode) {
  3432. return ['status' => 'error', 'message' => 'Auth code is missing'];
  3433. }
  3434. // 调用上面封装的方法,并请求获取用户信息
  3435. $result = $this->getTokenByCodeWithCert($authCode, true); // 第二个参数为 true
  3436. // 根据 $result 处理后续逻辑 (如用户登录注册,返回 token 给 APP 等)
  3437. if ($result['code'] == 200) {
  3438. // 成功处理
  3439. // $alipay_user_id = $result['user_id'];
  3440. // $nick_name = $result['user_info']['nick_name'] ?? 'Unknown';
  3441. // $avatar = $result['user_info']['avatar'] ?? '';
  3442. return ['status' => 'success', 'data' => $result];
  3443. } else {
  3444. // 处理失败
  3445. return ['status' => 'error', 'message' => $result['msg']];
  3446. }
  3447. }
  3448. /**
  3449. * @param $id
  3450. * @return Form
  3451. * @throws DataNotFoundException
  3452. * @throws DbException
  3453. * @throws ModelNotFoundException
  3454. * @throws FormBuilderException
  3455. * @author xaboy
  3456. * @day 2020-05-07
  3457. */
  3458. public function changePassForm($id)
  3459. {
  3460. return Elm::createForm(Route::buildUrl('systemUserChangePass', compact('id'))->build(), [
  3461. Elm::input('pass_word', '用户密码')->required()->value("")
  3462. ])->setTitle('修改用户密码');
  3463. }
  3464. public function changePass($uid,$password)
  3465. {
  3466. $pass_word=$this->encodePassword($password);
  3467. $data= Db::name("user")->where(["uid"=>$uid])->update(['pwd'=>$pass_word]);
  3468. if($data){
  3469. return $data;
  3470. }else{
  3471. return false;
  3472. }
  3473. }
  3474. public function wechatGetTokenBycode()
  3475. {
  3476. }
  3477. public function createUserNumber($uid){
  3478. $t = "C";
  3479. $number = '000000000';
  3480. if($uid <= 10){
  3481. $uid = $uid . 'X';
  3482. }
  3483. $strlen = mb_strlen($uid);//id长度
  3484. $newNumber = $t.substr_replace($number,$uid,-$strlen);
  3485. $newNumber = str_replace('4','R',$newNumber);
  3486. Db::name('user') -> where(["uid"=>$uid])->update(['user_number'=>$newNumber]);
  3487. }
  3488. /**
  3489. * @param int $uid 用户ID
  3490. * @param string $score 积分
  3491. * @param int $status 积分状态
  3492. * @param string $mark 备注
  3493. * @param string $has_qian 连续签到天数
  3494. * @param string $today_signintime 签到时间
  3495. * @param int $order_id 订单ID
  3496. * @param int $pm 1-收入。2-支出
  3497. * @param string $order_type
  3498. * @throws DbException
  3499. */
  3500. public function sign_add($uid, $score, $status, $mark, $has_qian = '', $today_signintime = '', $order_id = 0, $pm = 1, $order_type = '',$type='',$settlement_time = '')
  3501. {
  3502. if(!in_array($type,[1,2])){
  3503. // 其他情况都直接返回,因为目前只有365专区购买才可以获得
  3504. return false;
  3505. }
  3506. $ins_data['uid'] = $uid;
  3507. $ins_data['continuity_day'] = $has_qian;
  3508. $ins_data['reward_socre'] = $score;
  3509. // $ins_data['source_uid'] = $uid;
  3510. $ins_data['signin_time'] = $today_signintime;
  3511. $ins_data['addtime'] = time();
  3512. $ins_data['status'] = $status;
  3513. $ins_data['mark'] = $mark;
  3514. $ins_data['source_type'] = $type;
  3515. $ins_data['settlement_time'] = $settlement_time;// 结算时间 真正到了结算时间会结算
  3516. $ins_data['order_id'] = $order_id;
  3517. $ins_data['pm'] = $pm;
  3518. $ins_data['order_type'] = $order_type;
  3519. // $ins_data['surplus'] = 0;
  3520. Db::name('user_sign_score')->insertGetId($ins_data);
  3521. if($pm == 1 && $status == 1){
  3522. Db::name('user')->where('uid',$uid)->inc('score', $score)->update();
  3523. }
  3524. if($pm == 2){
  3525. Db::name('user')->where('uid', $uid)->dec('score', $score)->update();
  3526. }
  3527. }
  3528. public function gold_add($uid,$gold,$mark,$pm=1){
  3529. $ins['uid'] = $uid;
  3530. $ins['gold'] = $gold;
  3531. $ins['mark'] = $mark;
  3532. $ins['time'] = time();
  3533. $ins['pm'] = $pm;
  3534. $id = Db::name('user_gold_log')->insertGetId($ins);
  3535. if($pm == 1){
  3536. Db::name('user_gold')->where('uid',$uid)->inc('now_gold', $gold)->inc('cumulative', $gold)->update();
  3537. }else{
  3538. Db::name('user_gold') -> where('uid',$uid) -> dec('now_gold', $gold)->update();
  3539. }
  3540. $surplus = Db::name('user_gold')->where('uid',$uid)->value('now_gold');
  3541. Db::name('user_gold_log') -> where('id',$id) -> update(['surplus'=>$surplus]);
  3542. }
  3543. function get_level_list(){
  3544. try {
  3545. $tokenInfo = (request()->tokenInfo());
  3546. if(isset($tokenInfo->jti[1]) && $tokenInfo->jti[1]=='admin') {
  3547. $admin_id = request()->adminId();
  3548. $roles_str = Db::name('system_admin')->where('admin_id', $admin_id)->value('roles');
  3549. $phone_count = Db::name('system_role')->whereIn('role_id', $roles_str)->where("phone !=''")->count();
  3550. if ($phone_count) {
  3551. return true;
  3552. }
  3553. }
  3554. }catch (Exception $e) {
  3555. return false;
  3556. }
  3557. return false;
  3558. // $phone_data=Db::name('system_role')->whereIn('role_id',$roles_str)->where("phone !=''")->group("phone")->column('phone');
  3559. // if($phone_data){
  3560. // $uid_data = Db::name('user')->whereIn('phone', $phone_data)->column('uid');
  3561. // if($uid_data){
  3562. // $uids=$this->level_list($uid_data,0);
  3563. // }
  3564. // }
  3565. // }
  3566. // return isset($uids)?$uids:[];
  3567. }
  3568. // function level_list($uid_data,$i){
  3569. // $i++;
  3570. // $uid = Db::name('user')->whereIn('level_id', $uid_data)->column('uid');
  3571. // if($uid && $i<9){
  3572. // $uid_data=array_merge($uid_data,$uid);
  3573. // return $this->level_list($uid_data,$i);
  3574. // }else{
  3575. // return $uid_data;
  3576. // }
  3577. // }
  3578. public function sign_yhc_add($uid,$mer_id,$score,$mark,$order_id=0,$pm=1,$use_uid=0){
  3579. $ins_data['uid'] = $uid;
  3580. $ins_data['mer_id'] = $mer_id;
  3581. $ins_data['mark'] = $mark;
  3582. $ins_data['order_id'] = $order_id;
  3583. $ins_data['pm'] = $pm;
  3584. $ins_data['reward_socre'] = $score;
  3585. $ins_data['use_uid'] = $use_uid;
  3586. try {
  3587. Db::transaction(function () use ($ins_data,$pm,$mer_id,$score,$uid) {
  3588. $id = Db::name('enterprise_user_score')->insertGetId($ins_data);
  3589. if($pm == 2){
  3590. Db::name('enterprise_user') -> where('uid',$uid)-> where('mer_id',$mer_id) -> dec('green_integral',$score)->update();
  3591. }else if ($pm==1){
  3592. Db::name('enterprise_user') -> where('uid',$uid)-> where('mer_id',$mer_id) -> inc('green_integral',$score)->update();
  3593. }
  3594. $green_integral=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('uid',$uid)->value('green_integral');
  3595. if($green_integral<0){
  3596. throw new \Exception('修改失败,用户红积分不足,请刷新后再试');
  3597. }
  3598. });
  3599. }catch (\Exception $e){
  3600. return false;
  3601. }
  3602. return true;
  3603. }
  3604. /**
  3605. * 获取下级所有团队列表
  3606. * @param $uid
  3607. * @return int
  3608. */
  3609. public function getSpreadUidBreak($uid){
  3610. $sql = "select getUserSpreadId($uid) as uids";
  3611. $count = Db::query($sql);
  3612. $count[0]['uids'] = trim($count[0]['uids'],'$,');
  3613. $originalArray = explode(",",$count[0]['uids']);
  3614. $resultArray = array_diff($originalArray, [$uid]);
  3615. return $resultArray;
  3616. }
  3617. /**
  3618. * 设置用户 身份
  3619. * @param $uid
  3620. * @param $identityId
  3621. * @return int|mixed|null
  3622. * @throws DbException
  3623. */
  3624. public function setUserIdentity($uid, $identityId = null)
  3625. {
  3626. if (empty($identityId)) {
  3627. $identityId = $this->getUserIdentity($uid);
  3628. }
  3629. $userData = $this->dao->get($uid)->toArray();
  3630. // 只升级 不降级
  3631. if ($identityId < $userData['user_group']) {
  3632. $identityId = $userData['user_group'];
  3633. }
  3634. $data = ['user_group' => $identityId];
  3635. if (empty($userData['identity_up_time'] ?? null) && $userData['user_group'] == 1 && $identityId > 1) {
  3636. $data['identity_up_time'] = date('Y-m-d H:i:s');
  3637. }
  3638. $this->dao->update($uid, $data);
  3639. return $identityId;
  3640. }
  3641. /**
  3642. * 获取用户 身份
  3643. * @param $uid
  3644. * @return int|mixed
  3645. * @throws DataNotFoundException
  3646. * @throws DbException
  3647. * @throws ModelNotFoundException
  3648. */
  3649. public function getUserIdentity($uid)
  3650. {
  3651. // 1、获取所有等级信息
  3652. /** @var UserIdentityRepository $identityRepository */
  3653. $identityRepository = app()->make(UserIdentityRepository::class);
  3654. $identityList = $identityRepository->getIdentityList();
  3655. // 2、获取身份需要的最深等级
  3656. $lowerLevelNumList = array_column($identityList, 'lower_level_num');
  3657. $lowerLevelNumMax = max($lowerLevelNumList);
  3658. $lowerLevelNumMin = min($lowerLevelNumList);
  3659. // 获取需要 递归最深的层数,比如 高级合伙人需要递归10层 普通用户需要递归一层
  3660. $needLower = 0;
  3661. // 0 代表要递归无限极 -1 代表一级也不查
  3662. if($lowerLevelNumMin > 0) {
  3663. $needLower = $lowerLevelNumMax;
  3664. }
  3665. // 最大等级限制
  3666. $maxLvRestrict = 0;
  3667. // 3、获取个人贡献值
  3668. $userData = $this->dao->get($uid)->toArray();
  3669. // 这一步骤是为了 确定用户升级时间,因为后边的团队贡献值,需要查询 用户 升级为业务员后 所产生的团队贡献值
  3670. $determineResult = $this->determineUserUpgradeTime($uid);
  3671. $userData['user_group'] = $determineResult['user_group'];
  3672. $userData['identity_up_time'] = $determineResult['identity_up_time'];
  3673. $startTime = $userData['identity_up_time'];
  3674. $endTime = date('Y-m-d H:i:s');
  3675. // 如果用户身份 为 用户 或者 升级成业务员的时间为空 则无法计算它的团队贡献值
  3676. if ($userData['user_group'] == 1 || empty($startTime)) {
  3677. $maxLvRestrict = 2;
  3678. $needLower = -1;
  3679. }
  3680. // 4、获取下级用户 贡献值
  3681. $userContributionSumMap = $this->getSubordinateContributeByUid($uid, $startTime, $endTime, $needLower);
  3682. // 5、将用户等级由低到高
  3683. usort($identityList, function ($a, $b) {
  3684. return $a['user_group_id'] <=> $b['user_group_id'];
  3685. });
  3686. // 循环记录 如果贡献值 满足了初级合伙人身份 并记录该身份ID,继续下一阶段循环,下一阶段不满足 则该用户身份为初级合伙人
  3687. $identityId = 0;
  3688. foreach ($identityList as $item) {
  3689. $lowerLevelNum = $item['lower_level_num']??0;
  3690. $arriveNumOwn = $userData['contribute'];
  3691. $arriveNumTeam = 0;
  3692. $subordinateContribution = [];
  3693. // 只有 业务员及以上才需要团队贡献值
  3694. if ($item['user_group_id'] > 1) {
  3695. foreach ($userContributionSumMap as $key => $value) {
  3696. $subordinateContribution[$key] = 0;
  3697. if ($lowerLevelNum != 0) {
  3698. foreach ($value as $k => $v) {
  3699. if ($k < $lowerLevelNum) {
  3700. $subordinateContribution[$key] += $v;
  3701. }
  3702. }
  3703. } else {
  3704. $subordinateContribution[$key] = array_sum($value);
  3705. }
  3706. }
  3707. if (!empty($subordinateContribution)) {
  3708. // 大区业绩
  3709. $dqYj = max($subordinateContribution);
  3710. // 总业绩
  3711. $zYj = array_sum($subordinateContribution);
  3712. // 小区团体业绩
  3713. $arriveNumTeam = bcsub($zYj, $dqYj, 2);
  3714. }
  3715. }
  3716. // 从小向大循环,满足则去 下一等级继续验证,不满足 则 返回上次循环记录的值,并结束循环
  3717. if ($item['arrive_num_own'] <= $arriveNumOwn && $item['arrive_num_team'] <= $arriveNumTeam) {
  3718. $identityId = $item['user_group_id'];
  3719. // 用户等级限制,本次获取身份 最大可获取什么身份,比如 用户没有 团队贡献值,他最高只能升到 2 级 即业务员
  3720. if ($identityId == $maxLvRestrict) {
  3721. break;
  3722. }
  3723. } else {
  3724. break;
  3725. }
  3726. }
  3727. if ($identityId < $userData['user_group']) {
  3728. $identityId = $userData['user_group'];
  3729. }
  3730. return $identityId;
  3731. }
  3732. /**
  3733. * 获取该会员的所有下级会员
  3734. * @param array $uidList
  3735. * @return array
  3736. * @throws DataNotFoundException
  3737. * @throws DbException
  3738. * @throws ModelNotFoundException
  3739. */
  3740. public function getUidContributeListByLevelIdList(array $uidList)
  3741. {
  3742. return Db::name("user")
  3743. ->whereIn("level_id", $uidList)
  3744. ->field("uid, contribute, level_id")
  3745. ->select()
  3746. ->toArray();
  3747. }
  3748. /**
  3749. * 计算指定用户下属每一层级的总贡献值。
  3750. *
  3751. * @param array $initialUserIds 初始用户ID列表 (视为第0层)。
  3752. * @param int $maxDepth 需要查询的最大深度(相对于初始列表)。
  3753. * 0 表示查询所有层级直到末端。
  3754. * 1 表示只计算第1层(直接下级)的总贡献。
  3755. * N 表示计算到第 N 层(包含第N层)的总贡献。
  3756. * @param int $is_old
  3757. * @param null $startTime
  3758. * @param null $endTime
  3759. * @return array 返回一个数组,键是层级号(从1开始),值是该层级所有用户的贡献值总和。
  3760. * 例如:[ 1 => 600, 2 => 1300 ]
  3761. * @throws DataNotFoundException
  3762. * @throws DbException
  3763. * @throws ModelNotFoundException
  3764. */
  3765. public function getContributionSumByLevel(array $initialUserIds, int $maxDepth = 0, $is_old = 0, $startTime = null, $endTime = null): array
  3766. {
  3767. $levelContributions = []; // 结果数组 [level => total_contribution]
  3768. if (empty($initialUserIds)) {
  3769. return $levelContributions;
  3770. }
  3771. $currentLevelIds = $initialUserIds; // 当前层级的用户ID (初始为第0层)
  3772. $currentLevel = 0; // 当前层级号
  3773. // 使用一个集合跟踪所有已处理过的下级用户ID,防止重复计算和循环
  3774. $processedSubordinateIds = [];
  3775. while (!empty($currentLevelIds)) {
  3776. // 计算下一层级的编号
  3777. $nextLevel = $currentLevel + 1;
  3778. // 检查是否达到最大深度限制
  3779. if ($maxDepth > 0 && $nextLevel > $maxDepth) {
  3780. break; // 停止查询更深的层级
  3781. }
  3782. // 批量查询当前层级用户的直接下级
  3783. // 使用 array_chunk 防止 WHERE IN 子句过长 (根据数据库限制调整 chunkSize)
  3784. $chunkSize = 500;
  3785. $subordinatesOfCurrentLevel = [];
  3786. foreach(array_chunk($currentLevelIds, $chunkSize) as $chunk) {
  3787. $subordinatesChunk = Db::name('user')
  3788. ->field('uid') // 只需要下级的uid
  3789. ->whereIn('level_id', $chunk) //level_id 在当前层级用户块中
  3790. ->where('status', 1)
  3791. ->select()
  3792. ->toArray();
  3793. $subordinatesOfCurrentLevel = array_merge($subordinatesOfCurrentLevel, $subordinatesChunk);
  3794. }
  3795. // 如果没有找到任何下级,结束循环
  3796. if (empty($subordinatesOfCurrentLevel)) {
  3797. break;
  3798. }
  3799. // 如果 传入 $startTime 不为空 证明当前在 确定身份的 用户已经是 业务员了
  3800. if (!empty($startTime)) {
  3801. $subordinatesOfCurrentLevelUidList = $this->getUserContributeByUidList(array_column($subordinatesOfCurrentLevel, 'uid'), $startTime, $endTime);
  3802. // // 用户有贡献值记录,我们要根据 用户的身份 从普通消费者 升级 成业务员 的时间来 查询时间范围内产生的贡献值
  3803. // $userSignGongxianList = Db::name('user_sign_gongxian')
  3804. // ->whereIn('uid', array_keys($subordinatesOfCurrentLevelUidList))
  3805. // ->where('addtime', '>=', strtotime($startTime)) // `addtime` int(10) NOT NULL COMMENT '添加时间'
  3806. // ->where('status', 1) // 贡献值状态1-有效 0-失效 -1待确认
  3807. // ->whereNotNull('settlement_time') // `settlement_time` datetime DEFAULT NULL COMMENT '结算时间',
  3808. // ->field('uid, number, type') // 只需要下级的uid和贡献值
  3809. // ->select()
  3810. // ->toArray();
  3811. // foreach ($userSignGongxianList as $value) {
  3812. // if($value['type'] == 1) {
  3813. // $subordinatesOfCurrentLevelUidList[$value['uid']] += $value['number'];
  3814. // } else {
  3815. // $subordinatesOfCurrentLevelUidList[$value['uid']] -= $value['number'];
  3816. // }
  3817. // }
  3818. //
  3819. // if ($is_old == 1) {
  3820. // // 如果是老用户,除了通过贡献值记录表 还要计算 老订单 产生的贡献值
  3821. // $oldUserOfGoodsList = Db::name('old_user_of_goods')
  3822. // ->whereIn('user_id', array_keys($subordinatesOfCurrentLevelUidList))
  3823. // ->where('create_time', '>=', strtotime($startTime)) // `addtime` int(10) NOT NULL COMMENT '添加时间'
  3824. // ->where('status', 1) // '是否完成 0, 未完成 1 已完成',
  3825. // ->field('user_id, money, status, create_time') // 只需要下级的uid和贡献值
  3826. // ->select()
  3827. // ->toArray();
  3828. //
  3829. // foreach ($oldUserOfGoodsList as $storeProductData) {
  3830. // if ($storeProductData['money'] == 1180) {
  3831. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 700;
  3832. // } else if ($storeProductData['money'] == 10620) {
  3833. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 6300;
  3834. // } else if ($storeProductData['money'] == 11800) {
  3835. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 7000;
  3836. // } else if ($storeProductData['money'] == 9440) {
  3837. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 5600;
  3838. // } else if ($storeProductData['money'] == 2360) {
  3839. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 1400;
  3840. // } else {
  3841. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += bcmul($storeProductData['money'], 0.7, 2);
  3842. // }
  3843. // }
  3844. // }
  3845. } else {
  3846. // 如果传入的 $identity_up_time 为空,说明该用户只是一个普通用户(消费者),没有团队业绩
  3847. break;
  3848. }
  3849. $nextLevelTotalContribution = 0;
  3850. $nextLevelIds = []; // 存储下一轮需要查询的用户ID
  3851. // 遍历找到的所有下级
  3852. foreach ($subordinatesOfCurrentLevel as $subordinate) {
  3853. $subordinateId = $subordinate['uid'];
  3854. $subordinateContribution = $subordinatesOfCurrentLevelUidList[$subordinate['uid']] ?? 0; // 安全获取,默认为0
  3855. // 累加下一层级的总贡献值
  3856. // 注意:这里简单累加,如果一个下级同时被当前层多个用户推荐,其贡献会被计算多次
  3857. // 如果要求每个下级只贡献一次(即使有多个上级),需要调整逻辑,
  3858. // 例如在累加前检查 $processedSubordinateIds
  3859. // --- 修改点:确保每个下级贡献只被计算一次 ---
  3860. // if (!isset($processedSubordinateIds[$subordinateId])) { // 如果这个下级还没被处理过
  3861. $nextLevelTotalContribution += (float)$subordinateContribution;
  3862. // }
  3863. // 注释掉上面的检查,因为用户描述似乎是按层级直接累加,不管这个下级是否被上层处理过。
  3864. // 如果A1和A2都属于第1层,他们各自的下级B1和B2都属于第2层,B1和B2的贡献值直接加到第2层的总和里。
  3865. // 如果需要严格按“人”计算,即使一个人出现在多层或被多人推荐也只算一次,则需要解开注释并调整
  3866. // 收集下一轮需要查询的用户ID,同样需要防止重复处理
  3867. if (!isset($processedSubordinateIds[$subordinateId])) {
  3868. $nextLevelIds[] = $subordinateId;
  3869. // 标记这个下级ID已处理过,避免在更深层级中再次将其加入查询队列
  3870. $processedSubordinateIds[$subordinateId] = true;
  3871. }
  3872. }
  3873. // 存储下一层级的总贡献值 (只有当贡献值大于0或你想记录空层级时)
  3874. // 根据例子,我们只记录有贡献的层级,或者至少有用户的层级
  3875. if (!empty($subordinatesOfCurrentLevel)) { // 只要找到了下级就记录该层
  3876. $levelContributions[$nextLevel] = $nextLevelTotalContribution;
  3877. }
  3878. // 准备下一轮迭代
  3879. $currentLevelIds = array_unique($nextLevelIds); // 去重下一层的用户ID
  3880. $currentLevel = $nextLevel; // 更新当前层级
  3881. }
  3882. return $levelContributions;
  3883. }
  3884. /**
  3885. * 获取用户 历史的 个人贡献值记录
  3886. * @param $uidList
  3887. * @return array
  3888. * @throws DataNotFoundException
  3889. * @throws DbException
  3890. * @throws ModelNotFoundException
  3891. */
  3892. public function getUserContributeTimeMapByUidList($uidList) {
  3893. $userContributeTimeMap = [];
  3894. $userSignGongxianList = Db::name('user_sign_gongxian')
  3895. ->whereIn('uid', $uidList)
  3896. ->where('status', 1) // 贡献值状态1-有效 0-失效 -1待确认
  3897. ->whereNotNull('settlement_time') // `settlement_time` datetime DEFAULT NULL COMMENT '结算时间',
  3898. ->field('uid, number, type, mark, settlement_time') // 只需要下级的uid和贡献值
  3899. ->select()
  3900. ->toArray();
  3901. foreach ($userSignGongxianList as $value) {
  3902. // 贡献表中 包含多种类型的 贡献值记录,比如 用户消费商家获得赠送贡献值 , 推广获得的贡献值(直推),这些都不能算是 用户的 直接贡献值
  3903. // 只有 用户取消费 比如:购买 ** 商品、扫码消费获得赠送贡献值 等 才算做个人贡献值
  3904. // || strpos($value['mark'], "扫码") !== false
  3905. if (strpos($value['mark'], "购买") !== false || strpos($value['mark'], "会员专区消费商品赠送贡献值") !== false) {
  3906. if($value['type'] == 1) {
  3907. $type = 1;
  3908. } else {
  3909. $type = 2;
  3910. }
  3911. $userContributeTimeMap[$value['uid']][] = [
  3912. 'type' => $type,
  3913. 'contribute' => $value['number'],
  3914. 'settlementTime' => $value['settlement_time']
  3915. ];
  3916. }
  3917. }
  3918. // // 老订单 产生的贡献值 并未在 贡献记录表中
  3919. // $oldUserOfGoodsList = Db::name('old_user_of_goods')
  3920. // ->where('status', 1) // '是否完成 0, 未完成 1 已完成',
  3921. // ->whereIn('user_id', $uidList)
  3922. // ->field('user_id, money, status, create_time') // 只需要下级的uid和贡献值
  3923. // ->select()
  3924. // ->toArray();
  3925. // // 定义一个映射数组,用于存储不同 money 对应的 contribute 值
  3926. // $contributeMapping = [
  3927. // 1180 => 700,
  3928. // 10620 => 6300,
  3929. // 11800 => 7000,
  3930. // 9440 => 5600,
  3931. // 2360 => 1400,
  3932. // ];
  3933. // // 遍历每个 $storeProductData
  3934. // foreach ($oldUserOfGoodsList as $storeProductData) {
  3935. // // 获取 money 的值
  3936. // $money = $storeProductData['money'];
  3937. // // 检查 money 是否在映射中
  3938. // if (isset($contributeMapping[$money])) {
  3939. // // 如果存在,则使用映射的值
  3940. // $contribute = $contributeMapping[$money];
  3941. // } else {
  3942. // // 否则按默认规则计算
  3943. // $contribute = bcmul($money, 0.7, 2);
  3944. // }
  3945. // // 将数据添加到 $userContributeTimeList
  3946. // $userContributeTimeMap[$storeProductData['user_id']][] = [
  3947. // 'type' => 1,
  3948. // 'contribute' => $contribute,
  3949. // 'settlementTime' => date('Y-m-d H:i:s', $storeProductData['create_time'])
  3950. // ];
  3951. // }
  3952. foreach ($userContributeTimeMap as $key => &$subArray) {
  3953. usort($subArray, function ($a, $b) {
  3954. return strtotime($a['settlementTime']) - strtotime($b['settlementTime']);
  3955. });
  3956. }
  3957. return $userContributeTimeMap;
  3958. }
  3959. /**
  3960. * 获取用户升级成业务员的时间
  3961. * @param $uid
  3962. * @return mixed|string
  3963. * @throws DataNotFoundException
  3964. * @throws DbException
  3965. * @throws ModelNotFoundException
  3966. */
  3967. public function determineUserUpgradeTime($uid) {
  3968. $userData = $this->dao->get($uid)->toArray();
  3969. if (empty($userData['identity_up_time'])) {
  3970. $upArriveNumOwn = 0;
  3971. $yeWuYuanId = 0;
  3972. // 1、获取所有等级信息
  3973. /** @var UserIdentityRepository $identityRepository */
  3974. $identityRepository = app()->make(UserIdentityRepository::class);
  3975. $identityList = $identityRepository->getIdentityList();
  3976. foreach ($identityList as $value) {
  3977. if ($value['user_group_name'] == '业务员') {
  3978. $upArriveNumOwn = $value['arrive_num_own'];
  3979. $yeWuYuanId = $value['user_group_id'];
  3980. break;
  3981. }
  3982. }
  3983. // 2、获取用户贡献值 日志记录 对应时间
  3984. $userContributeTimeMap = $this->getUserContributeTimeMapByUidList([$uid]);
  3985. $myIdentityUpTime = '';
  3986. if (!empty($userContributeTimeMap[$uid])) {
  3987. $myArriveNumOwn = 0;
  3988. foreach ($userContributeTimeMap[$uid] as $value) {
  3989. if ($value['type'] == 1) {
  3990. $myArriveNumOwn += $value['contribute'];
  3991. } else {
  3992. $myArriveNumOwn -= $value['contribute'];
  3993. }
  3994. if ($myArriveNumOwn >= $upArriveNumOwn) {
  3995. $myIdentityUpTime = $value['settlementTime'];
  3996. break;
  3997. }
  3998. }
  3999. }
  4000. if (!empty($myIdentityUpTime)) {
  4001. $data['identity_up_time'] = $userData['identity_up_time'] = $myIdentityUpTime;
  4002. // 只升级 不降级
  4003. if ($userData['user_group'] == 1) {
  4004. $userData['user_group'] = $yeWuYuanId;
  4005. }
  4006. $this->dao->update($uid, $data);
  4007. } else {
  4008. if ($userData['is_old'] == 1) {
  4009. $data['identity_up_time'] = $userData['identity_up_time'] = $userData['create_time'];
  4010. $this->dao->update($uid, $data);
  4011. }
  4012. }
  4013. }
  4014. return [
  4015. 'user_group' => $userData['user_group'],
  4016. 'identity_up_time' => $userData['identity_up_time']
  4017. ];
  4018. }
  4019. /**
  4020. * 获取用户列表中 每个人 的 个人贡献值
  4021. * @param array $uidList
  4022. * @param null $startTime
  4023. * @param null $endTime
  4024. * @return array
  4025. * @throws DataNotFoundException
  4026. * @throws DbException
  4027. * @throws ModelNotFoundException
  4028. */
  4029. public function getUserContributeByUidList($uidList = [], $startTime = null, $endTime = null)
  4030. {
  4031. $subordinatesOfCurrentLevelUidList = [];
  4032. foreach ($uidList as $uid) {
  4033. $subordinatesOfCurrentLevelUidList[$uid] = 0;
  4034. }
  4035. $userContributeTimeMap = $this->getUserContributeTimeMapByUidList($uidList);
  4036. if (!empty($userContributeTimeMap)) {
  4037. foreach ($userContributeTimeMap as $uid => $contributeInfoList) {
  4038. foreach ($contributeInfoList as $value) {
  4039. // 跳过时间范围外的 贡献值
  4040. if (!empty($startTime) && strtotime($value['settlementTime']) < strtotime($startTime)) {
  4041. continue;
  4042. }
  4043. if (!empty($endTime) && strtotime($value['settlementTime']) > strtotime($endTime)) {
  4044. break;
  4045. }
  4046. if ($value['type'] == 1) {
  4047. $subordinatesOfCurrentLevelUidList[$uid] += $value['contribute'];
  4048. } else {
  4049. $subordinatesOfCurrentLevelUidList[$uid] -= $value['contribute'];
  4050. }
  4051. }
  4052. }
  4053. }
  4054. return $subordinatesOfCurrentLevelUidList;
  4055. }
  4056. /**
  4057. * 根据时间和递归层级 获取部门下 每一层级的 贡献值
  4058. * 假设 老大的 下级是 张三和李四, 董事(最高级身份)需要循环最深的等级是 3 级 得出来的结果↓ 这样是为了计算大小部门
  4059. * $userContributionSumMap[直属下级(部门)张三] =>[0 => 张三个人贡献值, 1 => 张三所有下级用户的个人贡献值, 2 => 张三所有下级用户的下级用户贡献值]
  4060. * $userContributionSumMap[直属下级(部门)李四] =>[0 => 李四个人贡献值, 1 => 李四所有下级用户的个人贡献值, 2 => 李四所有下级用户的下级用户贡献值]
  4061. * @param $uid
  4062. * @param null $startTime
  4063. * @param null $endTime
  4064. * @param int $depth
  4065. * @return array
  4066. * @throws DataNotFoundException
  4067. * @throws DbException
  4068. * @throws ModelNotFoundException
  4069. */
  4070. public function getSubordinateContributeByUid($uid, $startTime, $endTime, $depth = 10)
  4071. {
  4072. // 4、获取下级用户 贡献值
  4073. $userContributionSumMap = [];
  4074. if ($depth >= 0 && !empty($startTime)) {
  4075. // 获取用户的直属下级
  4076. $uidContributeList = $this->getUidContributeListByLevelIdList([$uid]);
  4077. $uidContributeUidList = array_column($uidContributeList, 'uid');
  4078. $subordinatesOfCurrentLevelUidList = $this->getUserContributeByUidList($uidContributeUidList, $startTime, $endTime);
  4079. foreach ($uidContributeList as $uidContribute) {
  4080. $goOnDepth = $depth;
  4081. // 获取用户规定时间内 所产生的贡献值 第一级
  4082. $userContributionSumMap[$uidContribute['uid']]['0'] = $subordinatesOfCurrentLevelUidList[$uidContribute['uid']] ?? 0;
  4083. if ($depth == 1) {
  4084. continue;
  4085. } else if ($depth > 1){
  4086. $goOnDepth = $depth - 1;
  4087. }
  4088. // 获取每个下级(部门)的个人贡献值 $goOnDepth = 0 时表示无限递归
  4089. $contributionSumByLevel = $this->getContributionSumByLevel(
  4090. [$uidContribute['uid']],
  4091. $goOnDepth,
  4092. 0,
  4093. $startTime,
  4094. $endTime
  4095. );
  4096. $userContributionSumMap[$uidContribute['uid']] = array_merge($userContributionSumMap[$uidContribute['uid']], $contributionSumByLevel);
  4097. if (!empty($userContributionSumMap[$uidContribute['uid']])) {
  4098. ksort($userContributionSumMap[$uidContribute['uid']]);
  4099. }
  4100. // 假设 老大的 下级是 张三和李四, 董事(最高级身份)需要循环最深的等级是 3 级 得出来的结果↓ 这样是为了计算大小部门
  4101. // $userContributionSumMap[直属下级(部门)张三] =>[0 => 张三个人贡献值, 1 => 张三所有下级用户的个人贡献值, 2 => 张三所有下级用户的下级用户贡献值]
  4102. // $userContributionSumMap[直属下级(部门)李四] =>[0 => 李四个人贡献值, 1 => 李四所有下级用户的个人贡献值, 2 => 李四所有下级用户的下级用户贡献值]
  4103. }
  4104. }
  4105. return $userContributionSumMap;
  4106. }
  4107. /**
  4108. * 获取用户 团队贡献值信息
  4109. * @param $uid
  4110. * @param int $depth // 最深递归层级
  4111. * @param array $betweenTime // 贡献值获取范围
  4112. * @return array
  4113. * @throws DataNotFoundException
  4114. * @throws DbException
  4115. * @throws ModelNotFoundException
  4116. */
  4117. public function getUserContributeInfoByDepth($uid, $depth = 10, $betweenTime = [])
  4118. {
  4119. // 3、获取个人贡献值
  4120. $userData = $this->dao->get($uid)->toArray();
  4121. // 这一步骤是为了 确定用户升级时间,因为后边的团队贡献值,需要查询 用户 升级为业务员后 所产生的团队贡献值
  4122. $determineResult = $this->determineUserUpgradeTime($uid);
  4123. $userData['user_group'] = $determineResult['user_group'];
  4124. $userData['identity_up_time'] = $determineResult['identity_up_time']; // 获得的值 有可能是时间 有可能是 null
  4125. $startTime = $userData['identity_up_time'];
  4126. $endTime = date('Y-m-d H:i:s');
  4127. if (!empty($betweenTime) && !empty($betweenTime['startTime']) && !empty($betweenTime['endTime'])) {
  4128. if(empty($startTime) || strtotime($startTime) < strtotime($betweenTime['startTime'])) {
  4129. $startTime = $betweenTime['startTime'];
  4130. }
  4131. if(strtotime($betweenTime['endTime']) < strtotime($endTime)) {
  4132. $endTime = $betweenTime['endTime'];
  4133. }
  4134. }
  4135. // 如果用户身份是 用户 则
  4136. /**
  4137. * 如果用户身份是 用户,则不计算团队贡献值,因计算团队贡献值 需要升级成业务员后 再进行进行统计
  4138. * 如用户也统计团队贡献值可能会导致: 用户进入系统后,不进行消费,团队贡献值确增长迅速,等某时刻 他只要 进行消费,身份就会快速跃迁,不公平
  4139. * (1)达标贡献值=自己消费产生的贡献值
  4140. * (2)团队达标贡献值= 不计算团队
  4141. */
  4142. if ($userData['user_group'] == 1) {
  4143. $depth = -1;
  4144. }
  4145. // 4、获取下级用户 贡献值
  4146. $userContributionSumMap = $this->getSubordinateContributeByUid($uid, $startTime, $endTime, $depth);
  4147. $subordinateContribution = [];
  4148. foreach ($userContributionSumMap as $key => $value) {
  4149. $subordinateContribution[$key] = array_sum($value);
  4150. }
  4151. $dqYj = 0;
  4152. $arriveNumTeam = 0;
  4153. if (!empty($subordinateContribution)) {
  4154. // 大区业绩
  4155. $dqYj = max($subordinateContribution);
  4156. // 总业绩
  4157. $zYj = array_sum($subordinateContribution);
  4158. // 小区团体业绩
  4159. $arriveNumTeam = bcsub($zYj, $dqYj, 2);
  4160. }
  4161. return [
  4162. 'arriveNumTeam' => $arriveNumTeam, // 小部门贡献值和
  4163. 'contribute' => $userData['contribute'], // 个人贡献值
  4164. 'perContribute' => $userData['per_contribute'], // 直推贡献值
  4165. 'largeContribute' => $dqYj, // 大部门贡献值
  4166. 'subordinate' => $subordinateContribution // 各部门贡献值和
  4167. ];
  4168. }
  4169. public function stockCreateForm()
  4170. {
  4171. $data = Db::name('user')->where(['status' => 1,'is_del' => 0])->field('uid,nickname')->select()->toArray();
  4172. return Elm::createForm(Route::buildUrl('systemUserStockCreate')->build(), [
  4173. Elm::select('user_id', '用户')->options(function () use ($data) {
  4174. foreach ($data as $label) {
  4175. $options[] = ['label' => $label['nickname'],'value' => $label['uid']];
  4176. }
  4177. return $options;
  4178. })->filterable(true),
  4179. Elm::number('pack','份数')->required()
  4180. ])->setTitle('添加股权分红');
  4181. }
  4182. public function stockUpdateForm($id)
  4183. {
  4184. $stock = Db::name('old_user_stock')->where('id',$id)->field('user_id,pack')->find();
  4185. $user = Db::name('user')->where('uid',$stock['user_id'])->field('uid,nickname')->find();
  4186. return Elm::createForm(Route::buildUrl('systemUserStockUpdate',compact('id'))->build(), [
  4187. Elm::input('user_id','用户',$user['nickname'])->disabled(true),
  4188. Elm::number('pack','份数',$stock['pack'])->required()
  4189. ])->setTitle('编辑');
  4190. }
  4191. /**
  4192. * 添加用户操作记录
  4193. * @param $uid
  4194. * @param $model
  4195. * @param $type
  4196. * @param $mark
  4197. * @return void
  4198. */
  4199. public function createUserOperatingRecord($uid, $model, $type, $mark)
  4200. {
  4201. $exists = Db::name('user_operating_record')
  4202. ->where('uid', $uid)
  4203. ->value('id');
  4204. if ($exists) {
  4205. return;
  4206. }
  4207. Db::name('user_operating_record')->insert([
  4208. 'uid' => $uid,
  4209. 'operation_model' => $model,
  4210. 'operation_type' => $type,
  4211. 'mark' => $mark,
  4212. 'operation_time' => date('Y-m-d H:i:s')
  4213. ]);
  4214. }
  4215. /**
  4216. * 保存用户搜索商品关键字
  4217. * @param $uid
  4218. * @param $keyword
  4219. * @param $type
  4220. * @return void
  4221. */
  4222. public function sproductkeywordHistory($uid, $keyword, $type){
  4223. Db::name('third_history')->insert([
  4224. 'uid' => $uid,
  4225. 'keyword' => $keyword,
  4226. 'type' => $type,
  4227. ]);
  4228. }
  4229. /**
  4230. * @param int $uid
  4231. * @return UserEntity
  4232. */
  4233. public function getUserEntityByUid(int $uid): UserEntity
  4234. {
  4235. $entityList = $this->getUserEntityListByUidList([$uid]);
  4236. $entity = array_shift($entityList);
  4237. if ($entity instanceof UserEntity) {
  4238. return $entity;
  4239. } else {
  4240. /** @var UserEntity */
  4241. return UserEntity::newInstance();
  4242. }
  4243. }
  4244. /**
  4245. * 获取用户实体集合 根据 uid集合
  4246. * @param array $uidList
  4247. * @return UserEntity[]
  4248. */
  4249. public function getUserEntityListByUidList(array $uidList): array
  4250. {
  4251. return $this->dao->getUserEntityListByUidList($uidList);
  4252. }
  4253. /**
  4254. * 获取用户实体集合 根据 uid集合
  4255. * @param array $uidList
  4256. * @return UserEntity[]
  4257. */
  4258. public function getUserEntityMapByUidList(array $uidList): array
  4259. {
  4260. $userEntityList = $this->getUserEntityListByUidList($uidList);
  4261. /** @var UserEntity[] $userEntityMapByUid */
  4262. $userEntityMapByUid = array_column($userEntityList, null, 'uid');
  4263. return $userEntityMapByUid;
  4264. }
  4265. /**
  4266. * 更新用户积分 并 写入积分变动记录
  4267. * @param int $uid
  4268. * @param int $type
  4269. * @param float $score
  4270. * @param string $mark
  4271. * @param string $orderType
  4272. * @param string $orderId
  4273. * @return float
  4274. */
  4275. public function updateUserScore(int $uid, int $type, float $score, string $mark = '', string $orderType = '', string $orderId = ''): float
  4276. {
  4277. $userEntity = $this->getUserEntityByUid($uid);
  4278. if (empty($userEntity->getUid())) {
  4279. throw new ValidateException('未查询到用户信息');
  4280. }
  4281. if ($type == UserSignScoreEnum::PM['Expend']['code']) {
  4282. $surplus = bcsub($userEntity->getScore(), $score, 2);
  4283. if ($surplus < 0.00) {
  4284. throw new ValidateException('用户积分不足');
  4285. }
  4286. } else {
  4287. $surplus = bcadd($userEntity->getScore(), $score, 2);
  4288. }
  4289. try {
  4290. $this->dao->update($uid, ['score' => $surplus]);
  4291. /** @var UserSignScoreEntity $userSignScoreEntity */
  4292. $userSignScoreEntity = UserSignScoreEntity::newInstance();
  4293. $userSignScoreEntity->setUid($uid)
  4294. ->setPm($type)
  4295. ->setRewardSocre($score)
  4296. ->setAddtime(time())
  4297. ->setStatus(UserSignScoreEnum::STATUS['Valid']['code'])
  4298. ->setOrderType($orderType)
  4299. ->setOrderId($orderId)
  4300. ->setMark($mark)
  4301. ->setSurplus($surplus);
  4302. /** @var UserSignScoreRepository $userSignScoreRepository */
  4303. $userSignScoreRepository = app()->make(UserSignScoreRepository::class);
  4304. $userSignScoreRepository->create($userSignScoreEntity->toUnderlineArray());
  4305. } catch (DbException $e) {
  4306. throw new ValidateException('更新积分失败');
  4307. }
  4308. return (float)$surplus;
  4309. }
  4310. /**
  4311. * 更新用户Vr 并 写入Vr变动记录
  4312. * @param int $uid
  4313. * @param int $type
  4314. * @param float $vr
  4315. * @param string $mark
  4316. * @param string $orderType
  4317. * @param string $orderId
  4318. * @return float
  4319. */
  4320. public function updateUserVr(int $uid, int $type, float $vr, string $mark = '', string $orderType = '', string $orderId = ''): float
  4321. {
  4322. $userEntity = $this->getUserEntityByUid($uid);
  4323. if (empty($userEntity->getUid())) {
  4324. throw new ValidateException('未查询到用户信息');
  4325. }
  4326. if ($type == UserSignVrEnum::TYPE['Consume']['code']) {
  4327. $surplus = bcsub($userEntity->getVr(), $vr, 2);
  4328. if ($surplus < 0.00) {
  4329. throw new ValidateException('用户VR不足');
  4330. }
  4331. } else {
  4332. $surplus = bcadd($userEntity->getVr(), $vr, 2);
  4333. }
  4334. try {
  4335. $this->dao->update($uid, ['vr' => $surplus]);
  4336. /** @var UserSignVrEntity $userSignVrEntity */
  4337. $userSignVrEntity = UserSignVrEntity::newInstance();
  4338. $userSignVrEntity->setUid($uid)
  4339. ->setType($type)
  4340. ->setNumber($vr)
  4341. ->setAddtime(time())
  4342. ->setOrderType($orderType)
  4343. ->setOrderId($orderId)
  4344. ->setMark($mark)
  4345. ->setSurplus($surplus);
  4346. /** @var UserSignVrRepository $userSignVrRepository */
  4347. $userSignVrRepository = app()->make(UserSignVrRepository::class);
  4348. $userSignVrRepository->create($userSignVrEntity->toUnderlineArray());
  4349. } catch (DbException $e) {
  4350. throw new ValidateException('更新VR失败');
  4351. }
  4352. return (float)$surplus;
  4353. }
  4354. /**
  4355. * 更新用户京豆 并 写入 京豆变动记录
  4356. * @param int $uid
  4357. * @param int $type
  4358. * @param float $jingdou
  4359. * @param string $mark
  4360. * @param string $orderType
  4361. * @param string $orderId
  4362. * @param int $merId
  4363. * @return float
  4364. */
  4365. public function updateUserJingdou(int $uid, int $type, float $jingdou, string $mark = '', string $orderType = '', string $orderId = '', int $merId = 0): float
  4366. {
  4367. $userEntity = $this->getUserEntityByUid($uid);
  4368. if (empty($userEntity->getUid())) {
  4369. throw new ValidateException('未查询到用户信息');
  4370. }
  4371. if ($type == UserSignJingdouEnum::TYPE['Consume']['code']) {
  4372. $surplus = bcsub($userEntity->getJingdou(), $jingdou, 2);
  4373. if ($surplus < 0.00) {
  4374. throw new ValidateException('用户京豆不足');
  4375. }
  4376. } else {
  4377. $surplus = bcadd($userEntity->getJingdou(), $jingdou, 2);
  4378. }
  4379. try {
  4380. $this->dao->update($uid, ['jingdou' => $surplus]);
  4381. /** @var UserSignJingdouEntity $userSignJingdouEntity */
  4382. $userSignJingdouEntity = UserSignJingdouEntity::newInstance();
  4383. $userSignJingdouEntity->setUid($uid)
  4384. ->setType($type)
  4385. ->setStatus(UserSignJingdouEnum::STATUS['Valid']['code'])
  4386. ->setNumber($jingdou)
  4387. ->setAddtime(time())
  4388. ->setOrderType($orderType)
  4389. ->setOrderId($orderId)
  4390. ->setMark($mark)
  4391. ->setSurplus($surplus);
  4392. /** @var UserSignJingdouRepository $userSignJingdouRepository */
  4393. $userSignJingdouRepository = app()->make(UserSignJingdouRepository::class);
  4394. $userSignJingdouRepository->create($userSignJingdouEntity->toUnderlineArray());
  4395. } catch (DbException $e) {
  4396. throw new ValidateException('更新京豆失败');
  4397. }
  4398. return (float)$surplus;
  4399. }
  4400. /**
  4401. * 更新用户复购金 并 写入 复购金变动记录
  4402. * @param int $uid
  4403. * @param int $type
  4404. * @param float $fugou
  4405. * @param string $mark
  4406. * @param string $orderType
  4407. * @param string $orderId
  4408. * @return float
  4409. */
  4410. public function updateUserFugou(int $uid, int $type, float $fugou, string $mark = '', string $orderType = '', string $orderId = ''): float
  4411. {
  4412. $userEntity = $this->getUserEntityByUid($uid);
  4413. if (empty($userEntity->getUid())) {
  4414. throw new ValidateException('未查询到用户信息');
  4415. }
  4416. if ($type == UserSignFugouEnum::TYPE['Consume']['code']) {
  4417. $surplus = bcsub($userEntity->getFugou(), $fugou, 2);
  4418. if ($surplus < 0.00) {
  4419. throw new ValidateException('用户复购金不足');
  4420. }
  4421. } else {
  4422. $surplus = bcadd($userEntity->getFugou(), $fugou, 2);
  4423. }
  4424. try {
  4425. $this->dao->update($uid, ['fugou' => $surplus]);
  4426. /** @var UserSignFugouEntity $userSignFugouEntity */
  4427. $userSignFugouEntity = UserSignFugouEntity::newInstance();
  4428. $userSignFugouEntity->setUid($uid)
  4429. ->setType($type)
  4430. ->setStatus(UserSignFugouEnum::STATUS['Valid']['code'])
  4431. ->setNumber($fugou)
  4432. ->setAddtime(time())
  4433. ->setOrderType($orderType)
  4434. ->setOrderId($orderId)
  4435. ->setMark($mark)
  4436. ->setSurplus($surplus);
  4437. /** @var UserSignFugouRepository $userSignFugouRepository */
  4438. $userSignFugouRepository = app()->make(UserSignFugouRepository::class);
  4439. $userSignFugouRepository->create($userSignFugouEntity->toUnderlineArray());
  4440. } catch (DbException $e) {
  4441. throw new ValidateException('更新京豆失败');
  4442. }
  4443. return (float)$surplus;
  4444. }
  4445. /**
  4446. * 更新用户复购金 并 写入 复购金变动记录
  4447. * @param int $uid
  4448. * @param int $recordId
  4449. * @return float
  4450. */
  4451. public function updateUserBrokeragePriceByRecordId(int $uid, int $recordId): float
  4452. {
  4453. $userEntity = $this->getUserEntityByUid($uid);
  4454. if (empty($userEntity->getUid())) {
  4455. throw new ValidateException('未查询到用户信息');
  4456. }
  4457. /** @var UserBillRepository $userBillRepository */
  4458. $userBillRepository = app()->make(UserBillRepository::class);
  4459. $userBillEntity = $userBillRepository->getUserBillEntityByBillId($recordId);
  4460. if (empty($userBillEntity->getBillId())) {
  4461. throw new ValidateException('未查询到佣金记录信息');
  4462. }
  4463. if ($userBillEntity->getCommissionType() != UserBillEnum::COMMISSION_TYPE['DIRECT_REFERRAL']['code'] && $userBillEntity->getCommissionType() != UserBillEnum::COMMISSION_TYPE['SHARE_EARNINGS']['code']) {
  4464. throw new ValidateException('该记录信息非佣金记录');
  4465. }
  4466. if ($userBillEntity->getStatus() != UserBillEnum::STATUS['PENDING']['code']) {
  4467. throw new ValidateException('该记录信息非待分配状态');
  4468. }
  4469. if ($userBillEntity->getPm() == UserBillEnum::PM['EXPEND']['code']) {
  4470. $surplus = bcsub($userEntity->getBrokeragePrice(), $userBillEntity->getNumber(), 2);
  4471. if ($surplus < 0.00) {
  4472. throw new ValidateException('用户佣金不足');
  4473. }
  4474. } else {
  4475. $surplus = bcadd($userEntity->getBrokeragePrice(), $userBillEntity->getNumber(), 2);
  4476. }
  4477. try {
  4478. $this->dao->update($uid, ['brokerage_price' => $surplus]);
  4479. // 注意 单一
  4480. // $userBillRepository->updateStatusByBillId($userBillEntity->getBillId(), UserBillEnum::STATUS['VALID']['code']);
  4481. } catch (DbException $e) {
  4482. throw new ValidateException('更新京豆失败');
  4483. }
  4484. return (float)$surplus;
  4485. }
  4486. /**
  4487. * 批量更新
  4488. * @param $dataList
  4489. * @return array
  4490. */
  4491. public function batchUpdateUserDataByDataList($dataList): array
  4492. {
  4493. return $this->dao->saveAll($dataList);
  4494. }
  4495. }