| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911 |
- <?php
- /**
- * @package merchant
- *
- * @author xaboy
- * @day 2020-04-28
- *
- *
- */
- namespace app\common\repositories\user;
- use alipay\aop\AlipayConfig;
- use alipay\aop\AopCertClient;
- use app\common\dao\BaseDao;
- use app\common\dao\user\UserDao;
- use app\common\enum\user\UserBillEnum;
- use app\common\enum\user\UserSignFugouEnum;
- use app\common\enum\user\UserSignJingdouEnum;
- use app\common\enum\user\UserSignScoreEnum;
- use app\common\enum\user\UserSignVrEnum;
- use app\common\model\merchant\order\OrderMerchant;
- use app\common\model\user\User;
- use app\common\model\wechat\WechatUser;
- use app\common\repositories\BaseRepository;
- use app\common\repositories\store\order\AgentOrderRepository;
- use app\common\repositories\store\order\StoreOrderRepository;
- use app\common\repositories\system\attachment\AttachmentRepository;
- use app\common\repositories\wechat\RoutineQrcodeRepository;
- use app\controller\api\store\product\Jd;
- use app\controller\api\store\product\Vip;
- use app\controller\api\user\Im;
- use app\entity\data\user\UserEntity;
- use app\entity\data\user\UserSignFugouEntity;
- use app\entity\data\user\UserSignJingdouEntity;
- use app\entity\data\user\UserSignScoreEntity;
- use app\entity\data\user\UserSignVrEntity;
- use app\traits\GzcApiRequest;
- use crmeb\exceptions\AuthException;
- use crmeb\jobs\SendNewPeopleCouponJob;
- use crmeb\services\JwtTokenService;
- use crmeb\services\QrcodeService;
- use crmeb\services\UploadService;
- use FormBuilder\Exception\FormBuilderException;
- use FormBuilder\Factory\Elm;
- use FormBuilder\Form;
- use think\Exception;
- use think\exception\ValidateException;
- use think\facade\Log;
- use think\facade\Queue;
- use function GuzzleHttp\Psr7\str;
- use think\db\exception\DataNotFoundException;
- use think\db\exception\DbException;
- use think\db\exception\ModelNotFoundException;
- use think\facade\Cache;
- use think\facade\Config;
- use think\facade\Db;
- use think\facade\Route;
- use think\Model;
- use app\controller\api\store\product\TaoKe;
- use alipay\aop\AopClient;
- use alipay\aop\request\AlipaySystemOauthTokenRequest;
- use alipay\aop\request\AlipayUserInfoShareRequest;
- /**
- * Class UserRepository
- * @package app\common\repositories\user
- * @author xaboy
- * @day 2020-04-28
- * @mixin UserDao
- */
- class UserRepository extends BaseRepository
- {
- use GzcApiRequest;
- /**
- * UserRepository constructor.
- * @param UserDao $dao
- */
- public function __construct(UserDao $dao)
- {
- $this->dao = $dao;
- }
- public function promoter($uid)
- {
- return $this->dao->update($uid, ['is_promoter' => 1, 'promoter_time' => date('Y-m-d H:i:s')]);
- }
- /**
- * 获取单条用户信息
- * @return array|\think\Model|null
- * @author php迷途小书童
- * @created 2021/1/16 10:45
- */
- public function getOne(array $where)
- {
- return ($this->dao->getWhere($where));
- }
- /**
- * @param $id
- * @return Form
- * @throws DataNotFoundException
- * @throws DbException
- * @throws FormBuilderException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-05-09
- */
- public function userForm($id)
- {
- $user = $this->dao->get($id);
- $certification = Db::name('user_certification')->where("uid", $id)->find();
- $regions1 = Db::name('regions') -> field('id as value,name as label')->where('level',1) ->select();
- $regions2 = Db::name('regions') -> field('id as value,name as label,pid')->where('level',2) ->select();
- $regions3 = Db::name('regions') -> field('id as value,name as label,pid')->where('level',3) ->select();
- $regions3_data=[];
- foreach ($regions3 as $v){
- $regions3_data[$v['pid']][]=$v;
- }
- $regions2_data=[];
- foreach ($regions2 as $v){
- $v['children']=isset( $regions3_data[$v['value']])? $regions3_data[$v['value']]:[];
- $regions2_data[$v['pid']][]=$v;
- }
- $city_area=[];
- foreach ($regions1 as $v){
- $v['children']=isset( $regions2_data[$v['value']])? $regions2_data[$v['value']]:[];
- $city_area[]=$v;
- }
- $regions2_data2=[];
- foreach ($regions2 as $v){
- $regions2_data2[$v['pid']][]=$v;
- }
- $city_area_2=[];
- foreach ($regions1 as $v){
- $v['children']=isset( $regions2_data2[$v['value']])? $regions2_data2[$v['value']]:[];
- $city_area_2[]=$v;
- }
- $user['real_name'] = $certification['user_name'] ?? '';
- $user['card_id'] = $certification['user_card'] ?? '';
- $user['uid'] = (string)$user['uid'];
- $user_rich=Db::name('user_rich')->where('uid',$id)->find();
- $user['admin_start_level'] =$user_rich?$user_rich['admin_start_level']:'0';
- $user['user_rich_type'] =$user_rich?$user_rich['type']:'0';
- $user['area_manage_pics'] =[];
- $user['area_manage_obtain'] ='0';
- if($user_rich){
- $user['area_manage_obtain'] =$user_rich['obtain'];
- if($user_rich['pics']){
- $user['area_manage_pics']=explode(',',$user_rich['pics']);
- }
- }
- // $area_manage=Db::name('area_manage')->where('uid',$id)->find();
- $area_manage=null;
- // $area_manage_type=Db::name('area_manage')->where('uid',$id)->value('type');
- //类型 district-区/县代 city-市代',
- $user['area_manage_type'] ='0';
- $province = '';
- $city = '';
- $area = '';
- if($area_manage){
- if(isset($area_manage['type']) && $area_manage['type']=='district'){
- $user['area_manage_type']='1';
- }
- if(isset($area_manage['type']) && $area_manage['type']=='city'){
- $user['area_manage_type']='2';
- }
- $code_list=explode(',',$area_manage['code_list']);
- if(isset($code_list[0]) && $code_list[0]!=''){
- $province=$code_list[0];
- }
- if(isset($code_list[1]) && $code_list[1]!=''){
- $city=$code_list[1];
- }
- if(isset($code_list[2]) && $code_list[2]!=''){
- $area=$code_list[2];
- }
- }
- $where=[
- Elm::input('uid', '会员 ID', '')->disabled(true)->required(true),
- Elm::input('real_name', '真实姓名'),
- Elm::input('phone', '手机号'),
- Elm::date('birthday', '生日'),
- Elm::input('card_id', '身份证'),
- Elm::input('addres', '用户地址'),
- Elm::textarea('mark', '备注'),
- Elm::select('admin_start_level', '赠送消费星级')->options(function () {
- return array(
- array('value'=>'0','label'=>'普通用户'),
- array('value'=>'1','label'=>'1星级'),
- array('value'=>'2','label'=>'2星级'),
- array('value'=>'3','label'=>'3星级'),
- array('value'=>'4','label'=>'4星级'),
- array('value'=>'5','label'=>'5星级'),
- );
- })->className("tchakanquanyi"),
- Elm::select('user_rich_type', '身份')->options(function () {
- return array(
- array('value'=>'0','label'=>'请选择'),
- array('value'=>'1','label'=>'会员'),
- array('value'=>'4','label'=>'高级会员'),
- array('value'=>'8','label'=>'合伙人'),
- array('value'=>'3','label'=>'创始人'),
- array('value'=>'9','label'=>'联合创始人'),
- );
- }),
- Elm::select('area_manage_type', '代理')->options(function () {
- return array(
- array('value'=>'0','label'=>'请选择'),
- array('value'=>'1','label'=>'区/县代'),
- array('value'=>'2','label'=>'市代'),
- );
- })->control([ [
- 'value' => '1',
- 'rule' => [
- Elm::cityArea('city', '代理区域')->type('city_area')->options($city_area)->value([$province,$city,$area]),
- Elm::select('area_manage_obtain', '获得方式')->options(function () {
- return array(
- array('value'=>'0','label'=>'请选择'),
- array('value'=>'1','label'=>'线下支付'),
- array('value'=>'2','label'=>'赠送'),
- );
- })->control([[
- 'value'=>'1',
- 'rule'=>[
- Elm::frameImages('area_manage_pics', '支付凭证/截图', '/' . config('admin.admin_prefix') . '/setting/uploadPicture?field=area_manage_pics&type=2')
- ->width('896px')->height('480px')->modal(['modal' => false])->props(['footer' => false])
- ]
- ]])
- ]
- ],[
- 'value' => '2',
- 'rule' => [
- Elm::city('city', '代理区域')->type('city')->options($city_area_2)->value([$province,$city]),
- Elm::select('area_manage_obtain', '获得方式')->options(function () {
- return array(
- array('value'=>'0','label'=>'请选择'),
- array('value'=>'1','label'=>'线下支付'),
- array('value'=>'2','label'=>'赠送'),
- );
- })->control([[
- 'value'=>'1',
- 'rule'=>[
- Elm::frameImages('area_manage_pics', '支付凭证/截图', '/' . config('admin.admin_prefix') . '/setting/uploadPicture?field=area_manage_pics&type=2')
- ->width('896px')->height('480px')->modal(['modal' => false])->props(['footer' => false])
- ]
- ]])
- ]
- ]]),
- Elm::select('group_id', '会员分组')->options(function () {
- $data = app()->make(UserGroupRepository::class)->allOptions();
- $options = [];
- foreach ($data as $value => $label) {
- $options[] = compact('value', 'label');
- }
- return $options;
- }),
- Elm::selectMultiple('label_id', '会员标签')->options(function () {
- $data = app()->make(UserLabelRepository::class)->allOptions();
- $options = [];
- foreach ($data as $value => $label) {
- $value = (string)$value;
- $options[] = compact('value', 'label');
- }
- return $options;
- }),
- ];
- // 1 镇代 2 县代 3 市代 4 商户 5 推广员
- // $title="用户";
- // if ($user['identity']==1){
- // $title="镇代";
- // }
- // if ($user['identity']==2){
- // $title="县代";
- // }
- // if ($user['identity']==3){
- // $title="市代";
- // }
- // if ($user['identity']==4){
- // $title="商户";
- // }
- // if ($user['identity']==5){
- // $title="推广员";
- // }
- //
- // $where[] = Elm::text('identity', $title );
- if ($user['identity']!=0){
- $where[] =Elm::input('mer_rebate', "推荐商户返利");
- $where[] =Elm::input('promoter_rebate', "推荐代理返利");
- }
- if ($user['identity']==4){
- $where[] =Elm::input('agent_rebate', "推荐推广员返利");
- $where[] =Elm::input('cross_store', '跨店收入');
- }
- if ($user['identity']==1){
- $where[] =Elm::input('agent_rebate', "推荐推广员返利");
- // $title="镇代返利";
- // $where[] =Elm::input('jurisdiction', "辖区内收入");
- // $where[] =Elm::input('adv_fee', "广告费");
- $where[] =Elm::input('xqxiaofei', "自己辖区消费返利");
- }
- if ($user['identity']==2){
- $where[] =Elm::input('xqxiaofei', "自己辖区消费返利");
- $where[] =Elm::input('agent_rebate', "推荐推广员返利");
- $where[] =Elm::input('jurisdiction', "推荐其他区域代理费返佣:自己");
- $where[] =Elm::input('other_jurisdictions', "推荐其他区域代理费返佣:对应区域");
- }
- if ($user['identity']==3){
- $where[] =Elm::input('xqxiaofei', "自己辖区消费返利");
- $where[] =Elm::input('agent_rebate', "推荐推广员返利");
- $where[] =Elm::input('jurisdiction', "推荐其他区域代理费返佣:自己");
- $where[] =Elm::input('other_jurisdictions', "推荐其他区域代理费返佣:对应区域");
- }
- if ($user['identity']==5){
- $where[] =Elm::input('agent_rebate', "推荐推广员返利");
- }
- return Elm::createForm(Route::buildUrl('systemUserUpdate', compact('id'))->build(),$where )->setTitle('编辑')->formData($user->toArray());
- }
- /**
- * @param array $where
- * @param $page
- * @param $limit
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-05-07
- */
- public function getAgent(array $where, $page, $limit)
- {
- //默认id排序
- $order = 'ua.id desc';
- if(isset($where['identity'])) {
- if ($where['identity'] == 1) {
- $order = 'u.identity asc';
- } elseif ($where['identity'] == 2) {
- $order = 'u.identity desc';
- }
- }
- $query = Db::name("user_agent")
- ->alias("ua")
- ->join("user u","u.uid=ua.user_id");
- if($where["keyword"]){
- $query = $query->whereLike("name","%".$where["keyword"]."%");
- }
- unset($where['keyword']);
- $list =$query->field("ua.*,u.nickname,u.avatar,u.avatar,u.brokerage_price,u.pay_count,u.spread_count,u.spread_uid")
- ->where($where)
- ->page($page, $limit)
- ->order($order)
- ->select()->toArray();
- $count = Db::name("user_agent")
- ->where($where)
- ->count();
- // $count =$query->where($where)->count();
- foreach($list as $k=>$value){
- $city['province'] = Db::name("user_province")->where(['province_id'=>$value['province_id']])->value("province_name");
- $city['city'] = Db::name("user_city")->where(['city_id'=>$value['city_id']])->value("city_name");
- $city['area'] = Db::name("user_area")->where(['area_id'=>$value['area_id']])->value("area_name");
- $city['street'] = Db::name("user_street")->where(['street_id'=>$value['street_id']])->value("street_name");
- $list[$k]['city'] = $city;
- }
- return compact('count', 'list');
- }
- /**
- * @param array $where
- * @param $page
- * @param $limit
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-05-07
- */
- public function getAgentList(array $where, $page, $limit)
- {
- $wheres=[];
- $wheres['identity'] = [1,2,3,5,6];
- if($where["identity"]){
- $wheres["identity"]= $where['identity'];
- }
- $query =Db::name("user")->where($wheres);
- if($where["keyword"]){
- $query =$query->whereLike("account","%".$where['keyword']."%");
- }
- $list = $query ->field("account,uid,nickname,avatar,avatar,brokerage_price,pay_count,spread_count,spread_uid,identity")
- ->page($page, $limit)
- ->order("uid desc")
- ->select()->toArray();
- foreach($list as $k=>$value){
- $lis = Db::name("user")->where(['uid'=>$value['spread_uid']])->field("uid,account")->find();
- $list[$k]['spread'] =$lis;
- }
- $count_query = Db::name("user")->where($wheres);
- if($where["keyword"]){
- $count_query =$count_query->whereLike("account","%".$where['keyword']."%");
- }
- $count = $count_query->count();
- $wheres2=[];
- if ($where['keyword']){
- $wheres2[]=["account","like","%".$where['keyword']."%"];
- }
- $count1 = Db::name("user")->where($wheres2)->where("identity", 1 )->count();
- $count2 = Db::name("user")->where($wheres2)->where("identity", 2 )->count();
- $count3 = Db::name("user")->where($wheres2)->where("identity", 3 )->count();
- $count5 = Db::name("user")->where($wheres2)->where("identity", 5 )->count();
- $sart=[
- ['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'=> '推广员' ]];
- // [{ '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': '养老金' }]
- return compact('count', 'list','sart','wheres');
- }
- public function getList(array $where, $page, $limit)
- {
- if (!empty($where['zero_line_uid'])) {
- $sql = "select getUserLevelId({$where['zero_line_uid']}) as uids";
- //\think\facade\Log::info("lplpDB".$sql);
- try {
- $spread_user_list = Db::query($sql);
- } catch (\Exception $exception) {
- $spread_user_list = '';
- }
- $spread_user_list = explode(",", trim($spread_user_list[0]['uids'], '$,'));
- $where['uid'] = $spread_user_list;
- }
- unset($where['zero_line_uid']);
- if(isset($where['user_card']) && $where['user_card'] !=''){
- $user_card = $where['user_card'];
- $query = $this->dao->search($where)->with(['spread' => function ($query) {
- $query->field('uid,account');
- }, 'group','certification' => function ($query) use ($user_card){
- $query->whereLike('user_card', "%".$user_card."%");
- }]);
- }else{
- $query = $this->dao->search($where)->with(['spread' => function ($query) {
- $query->field('uid,account');
- }, 'group','certification']);
- }
- $make = app()->make(UserLabelRepository::class);
- $count = $query->count('User.uid');
- $list = $query->page($page, $limit)->order("uid desc")->select()
- ->each(function ($item) use ($make) {
- $item->gzcAmount = 0;
- $item['lx'] = '';
- $vip = Db::name('da_cang_user') -> where('uid',$item['uid']) -> where('status',1) -> where('end_time','>',time())->value('type');
- if($vip == 1){
- $item['lx'] .= '【金卡会员】';
- }elseif ($vip == 2){
- $item['lx'] .= '【银卡会员】';
- }
- $channel = Db::name('channel_user') -> where('uid',$item['uid']) -> where('status',1) -> field('id') -> find();
- if($channel){
- $item['lx'] .= '【渠道商】';
- }
- //上级身份是否商户
- $is_shanghu1=Db::name('merchant_annual_cost_order')->where('status',1)->where('uid',$item['uid'])->find();
- $is_shanghu2=Db::name('merchant')->where('uid',$item['uid'])->find();
- $is_shanghu3=Db::name('merchant_intention')->where('uid',$item['uid'])->find();
- if($is_shanghu1||$is_shanghu2||$is_shanghu3){
- $item['lx'] .= '【商户】';
- }
- if(empty($item['lx'])){
- $item['lx'] = '普通用户';
- }
- // try {
- // $certification = Db::name('user_certification')
- // ->where('uid', $item->uid)
- // ->find();
- // if ($certification) {
- // $response = $this->checkAmount($certification);
- // $item->gzcAmount = $response['amount'];
- // }
- // } catch (\Throwable $w) {
- // $item->gzcAmount = 0;
- // }
- $item->label = count($item['label_id']) ? $make->labels($item['label_id']) : [];
- $user_rich=Db::name('user_rich')->where('uid', $item['uid'])->find();
- $item->is_huitian = (isset($user_rich) && $user_rich['is_huitian']==1)?true:false;
- $item->user_rich_type= (isset($user_rich) )?$user_rich['type']:0;
- $item->stockholder= (isset($user_rich) )?$user_rich['stockholder']:0;
- // $area_manage_type=Db::name('area_manage')->where('uid', $item['uid'])->value('type');
- //类型 district-区/县代 city-市代',
- $item->area_manage_type=$item['user_group'];
- $item->user_rich=$user_rich;
- $item->enterprise_user=Db::name('enterprise_user')->where('uid', $item['uid'])->select();
- foreach ($item->enterprise_user as $k=>$v){
- $p_phone=Db::name('user')->where('uid', $v['puid'])->value('phone');
- $v['p_phone']=$p_phone?$p_phone:'';
- $item->enterprise_user[$k]=$v;
- }
- return $item;
- });
- return compact('count', 'list');
- }
- public function getonePromoter(array $where){
- $data =Db::name("user_agent")
- ->where($where)
- ->find();
- $city['province'] = Db::name("user_province")->where(['province_id'=>$data['province_id']])->value("province_name");
- $city['city'] = Db::name("user_city")->where(['city_id'=>$data['city_id']])->value("city_name");
- $city['area'] = Db::name("user_area")->where(['area_id'=>$data['area_id']])->value("area_name");
- $city['street'] = Db::name("user_street")->where(['street_id'=>$data['street_id']])->value("street_name");
- $data['city'] = $city;
- return $data;
- }
- /*代理申请线下支付
- @cabbage
- */
- public function xianPayAgent($id,$mark=''){
- $user_agent=Db::name("user_agent")->where("id",$id)->order("add_time")->find();
- if(!$user_agent){
- return ['code'=>400,'msg'=>'信息有误'];
- }
- $agent_order = [
- 'type'=>4,
- 'price'=>$user_agent['price'],
- 'link_id'=>$user_agent['id'],
- 'identity'=>$user_agent['identity'],
- 'uid'=>$user_agent['user_id'],
- 'order_sn'=>(app()->make(AgentOrderRepository::class))->getNewOrderId("DL"),
- 'create_time'=>date('Y-m-d H:i:s'),
- 'mark'=>$mark
- ];
- $agentOrder = Db::name("agent_order")->insertGetId($agent_order);
- //支付成功回调状态
- return (app()->make(AgentOrderRepository::class))->paySuccess($agentOrder);
- }
- public function updateAgent(array $where,$id){
- $user_agent=Db::name("user_agent")->where("id",$id)->order("add_time")->find();
- //审核通过
- if ($where['status']==1){
- $user= Db::name("user")->where(['uid'=>$user_agent['user_id']])->value("identity");
- if($user['identity']==4){
- return ['code'=>400,'msg'=>'该用户已是商家,请拒绝'];
- }
- try{
- //判断所申请的区域下是否有代理,查询需要支付的代理费用
- if($user_agent['identity'] == 1){
- if(Db::name("user_street")->where("street_id",$user_agent['street_id'])->value("uid")){
- return ['code'=>400,'msg'=>'该区域下已有代理'];
- }
- $where_config['config_key'] = "agency_fee_zhen" ;
- }elseif($user_agent['identity'] == 2){
- if(Db::name("user_area")->where("area_id",$user_agent['area_id'])->value("uid")){
- return ['code'=>400,'msg'=>'该区域下已有代理'];
- }
- $where_config['config_key'] = "agency_fee_xian" ;
- }elseif($user_agent['identity'] == 3){
- if(Db::name("user_city")->where("city_id",$user_agent['city_id'])->value("uid")){
- return ['code'=>400,'msg'=>'该区域下已有代理'];
- }
- $where_config['config_key'] = "agency_fee_shi" ;
- }elseif($user_agent['identity'] == 5){
- $where_config['config_key'] = "agency_fee_tui" ;
- }elseif ($user_agent['identity'] == 6){
- $where_config['config_key'] = "agency_fee_qudao" ;
- }
- $config = Db::name("system_config_value")->where($where_config)->field("value")->find();
- $price = str_replace('"','',$config['value']);
- $price = (float)$price;
- Db::name("user_agent")->where("id",$id)->update(["status"=>1,"update_time"=>time(),'price'=>$price]);//修改申请信息
- //支付金额为0,直接创建成功记录
- if($price <= 0){
- $agent_order = [
- 'type'=>1,
- 'price'=>$price,
- 'link_id'=>$user_agent['id'],
- 'identity'=>$user_agent['identity'],
- 'uid'=>$user_agent['user_id'],
- 'order_sn'=>(app()->make(AgentOrderRepository::class))->getNewOrderId("DL"),
- 'create_time'=>date('Y-m-d H:i:s'),
- ];
- $agentOrder = Db::name("agent_order")->insertGetId($agent_order);
- //支付成功回调状态
- (app()->make(AgentOrderRepository::class))->paySuccess($agentOrder);
- }
- }catch (Exception $e) {
- Db::rollback();
- }
- }
- //审核拒绝
- if ($where['status']==2){
- $data['promoter_time'] = date('Y-m-d H:i:s');
- $data['identity']=0;
- $data['is_promoter']=0;
- Db::name("user")->where("uid",$user_agent["user_id"])->update($data);
- Db::name("user_agent")->where("id",$id)->update(["status"=>2,"update_time"=>time(),'pay_status'=>2]);
- }
- // if ($where['status']==2){
- // unset($data['is_promoter'],$data['promoter_time']);
- // Db::name("user_agent")->where("user_id",$id)->update(["status"=>2,"update_time"=>time()]);
- // }
- return true;
- }
- /**
- * 推广员推广成功获得佣金
- * @param $order
- */
- public function promoters($user_agent){
- //客户本人
- $order_user=Db::name("user")->where("uid",$user_agent["user_id"])->find();
- if ($user_agent["pid"]>0){
- //推广的人的信息
- $spread_identity=Db::name("user")->where("uid",$user_agent["pid"])->field("identity,agent_fee")->find();
- if ($spread_identity["identity"]>0){
- if (($spread_identity["identity"]!=2||$spread_identity["identity"]!=3)&&($order_user["county_agent"]==$user_agent["pid"])){
- $agent_fee=bcdiv($spread_identity["agent_fee"],100);
- $spread_fee=bcmul($user_agent["price"],$agent_fee) ;
- $title="代理费佣金";
- $mark ="获得代理费佣金".$spread_identity["agent_fee"]."%";
- $commission_type="1";
- $this->add_bill($title,$spread_fee,$user_agent["pid"],$mark,$commission_type,$order_user["agent_sn"]);
- }
- //用户本人的县代与当前推广的县代不一致(跨区域推广)
- if ($spread_identity["identity"]==2&&$order_user["county_agent"]!=$user_agent["pid"]&&$order_user["county_agent"]>0){
- //跨辖区用户对应推荐人佣金
- $agent_feezj=bcdiv($spread_identity["agent_fee3"],100);
- $agent_feezj=bcmul($user_agent["price"],$agent_feezj) ;
- $title="代理费佣金";
- $mark ="获得代理费佣金".$spread_identity["agent_fee3"]."%";
- $commission_type="1";
- $this->add_bill($title,$agent_feezj,$user_agent["pid"],$mark,$commission_type,$order_user["agent_sn"]);
- //跨辖区用户对应辖区佣金
- $spread_identity=Db::name("user")->where("uid",$order_user["county_agent"])->field("identity,agent_fee2")->find();
- $agent_fee=bcdiv($spread_identity["agent_fee2"],100);
- $spread_fee=bcmul($user_agent["price"],$agent_fee) ;
- $title="代理费佣金";
- $mark ="其他区域推荐代理费返佣".$spread_identity["agent_fee2"]."%";
- $commission_type="1";
- $this->add_bill($title,$spread_fee,$order_user["county_agent"],$mark,$commission_type,$order_user["agent_sn"]);
- }
- //用户本人的市代与当前推广的市代不一致(跨区域推广)
- if ($spread_identity["identity"]==3&&$order_user["city_agent"]!=$user_agent["pid"]&&$order_user["city_agent"]>0){
- //跨辖区用户对应推荐人佣金
- $agent_feezj=bcdiv($spread_identity["agent_fee3"],100);
- $agent_feezj=bcmul($user_agent["price"],$agent_feezj) ;
- $title="代理费佣金";
- $mark ="获得代理费佣金".$spread_identity["agent_fee3"]."%";
- $commission_type="1";
- $this->add_bill($title,$agent_feezj,$user_agent["pid"],$mark,$commission_type,$order_user["agent_sn"]);
- //跨辖区用户对应辖区佣金
- $spread_identity=Db::name("user")->where("uid",$order_user["county_agent"])->field("identity,agent_fee2")->find();
- $agent_fee=bcdiv($spread_identity["agent_fee2"],100);
- $spread_fee=bcmul($user_agent["price"],$agent_fee) ;
- $title="代理费佣金";
- $mark ="其他区域推荐代理费返佣".$spread_identity["agent_fee2"]."%";
- $commission_type="1";
- $this->add_bill($title,$spread_fee,$order_user["county_agent"],$mark,$commission_type,$order_user["agent_sn"]);
- }
- }
- }
- }
- /**
- * 佣金加入账单
- * @param $title
- * @param $number
- * @param $uid
- * @param $mark
- * @param $commission_type
- * @param $order_sn
- */
- public function add_bill($title,$number,$uid,$mark,$commission_type,$order_sn,$order_id=0){
- // $old_number=Db::name("user")->where("uid",$uid)->value("brokerage_price");
- $data=[
- 'link_id' => $order_id,
- "uid"=>$uid,
- // "pm"=>1,
- "title"=>$title,
- "category"=>"now_money",
- "type"=>"commission",
- "number"=>$number,
- "balance"=>0,
- "mark"=>$mark,
- "create_time"=>time(),
- "status"=>0,
- "commission_type"=>$commission_type,
- "order_sn"=>$order_sn,
- ];
- Db::name("user_bill")->insert($data);
- // Db::name("user")->where("uid",$uid)->inc('brokerage_price', $number) ->update();
- }
- public function merList(string $keyword, $page, $limit)
- {
- $query = $this->dao->searchMerUser($keyword);
- $count = $query->count($this->dao->getPk());
- $list = $query->page($page, $limit)->setOption('field', [])->field('uid,nickname,avatar,user_type,sex')->select();
- return compact('count', 'list');
- }
- /**
- * @param $id
- * @return Form
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeGroupForm($id)
- {
- $isArray = is_array($id);
- if (!$isArray)
- $user = $this->dao->get($id);
- /** @var UserGroupRepository $make */
- $data = app()->make(UserGroupRepository::class)->allOptions();
- return Elm::createForm(Route::buildUrl($isArray ? 'systemUserBatchChangeGroup' : 'systemUserChangeGroup', $isArray ? [] : compact('id'))->build(), [
- Elm::hidden('ids', $isArray ? $id : [$id]),
- Elm::select('group_id', '用户分组', $isArray ? '' : $user->group_id)->options(function () use ($data) {
- $options = [['label' => '不设置', 'value' => '0']];
- foreach ($data as $value => $label) {
- $options[] = compact('value', 'label');
- }
- return $options;
- })
- ])->setTitle('修改用户分组');
- }
- /**
- * @param $id
- * @return Form
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeLabelForm($id)
- {
- $isArray = is_array($id);
- if (!$isArray)
- $user = $this->dao->get($id);
- /** @var UserLabelRepository $make */
- $data = app()->make(UserLabelRepository::class)->allOptions();
- return Elm::createForm(Route::buildUrl($isArray ? 'systemUserBatchChangeLabel' : 'systemUserChangeLabel', $isArray ? [] : compact('id'))->build(), [
- Elm::hidden('ids', $isArray ? $id : [$id]),
- Elm::selectMultiple('label_id', '用户标签', $isArray ? [] : $user->label_id)->options(function () use ($data) {
- $options = [];
- foreach ($data as $value => $label) {
- $value = (string)$value;
- $options[] = compact('value', 'label');
- }
- return $options;
- })
- ])->setTitle('修改用户分组');
- }
- /**
- * @param $id
- * @return Form
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeNowMoneyForm($id)
- {
- return Elm::createForm(Route::buildUrl('systemUserChangeNowMoney', compact('id'))->build(), [
- Elm::radio('type', '修改余额', 1)->options([
- ['label' => '增加', 'value' => 1],
- ['label' => '减少', 'value' => 0],
- ])->required(),
- Elm::number('now_money', '金额')->required()->min(0)
- ])->setTitle('修改用户余额');
- }
- /**
- * @param $id
- * @return Form
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeProForm($id)
- {
- $spreadId = Db::name('user')->where('uid', $id)->value('spread_uid');
- if ($spreadId) {
- $spread_message = Db::name('user')->where('uid', $spreadId)->field('account,nickname')->findOrEmpty();
- } else {
- $spread_message = ['account' => '无推荐人', 'nickname' => '无推荐人'];
- }
- return Elm::createForm(Route::buildUrl('systemUserChangePro', compact('id'))->build(), [
- Elm::input('spread_account_old', '原推荐人')->value($spread_message['account'].'('.$spread_message['nickname'].')')->disabled(true),
- Elm::input('spread_account', '推荐人')->required()->placeholder("请填写推荐人手机号"),
- Elm::textarea('mark', '备注', '')->placeholder('填写备注信息')
- ])->setTitle('修改用户推荐人');
- }
- /**
- * @param $id
- * @return Form
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeProFormLevel($id)
- {
- $levelId = Db::name('user')->where('uid', $id)->value('level_id');
- if ($levelId) {
- $level_message = Db::name('user')->where('uid', $levelId)->field('account,nickname')->findOrEmpty();
- } else {
- $level_message = ['account' => '无节点人', 'nickname' => '无节点人'];
- }
- return Elm::createForm(Route::buildUrl('systemUserChangeLevelPro', compact('id'))->build(), [
- Elm::input('level_account_old', '原节点人')->value($level_message['account'].'('.$level_message['nickname'].')')->disabled(true),
- Elm::input('level_account', '节点人(上级)')->required()->placeholder("请填写节点人(上级)手机号"),
- Elm::textarea('mark', '备注', '')->placeholder('填写备注信息')
- ])->setTitle('修改用户节点人(上级)');
- }
- public function changeProFormGroup($id)
- {
- $userGroup = Db::name('user')->where('uid', $id)->where('is_del', '=', 0)->value('user_group');
- $identityList = Db::name('user_identity')->field('user_group_name label,user_group_id value')->select()->toArray();
- $oldIdentity = [];
- foreach ($identityList as $item) {
- if ($item['value'] == $userGroup) {
- $oldIdentity = $item;
- break;
- }
- }
- return Elm::createForm(Route::buildUrl('systemUserChangeGroupPro', compact('id'))->build(), [
- Elm::select('old_identity_id', '当前用户身份')->options([$oldIdentity])->value($oldIdentity['value'])->disabled(true),
- Elm::select('new_identity_id', '新的用户身份')->options($identityList),
- Elm::textarea('mark', '备注', '')->placeholder('填写备注信息')
- ])->setTitle('修改用户身份');
- }
- /**
- * @param $id
- * @return Form
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeAwardForm($id)
- {
- $user = $this->dao->get($id);
- return Elm::createForm(Route::buildUrl('systemUserChangeAward', compact('id'))->build(), [
- Elm::text('account','账号',$user['account'])->disabled(true),
- Elm::radio('type','类型',1)->options([
- ['label' => 'PV', 'value' => 1],
- ['label' => '积分', 'value' => 2],
- ['label' => '直推佣金', 'value' => 3],
- ['label' => '复购金', 'value' => 4],
- ['label' => '红包', 'value' => 5],
- ['label' => '锁客收益', 'value' => 6],
- ['label' => '推广店铺收益', 'value' => 7],
- ['label' => '贡献值', 'value' => 8],
- ['label' => 'VR', 'value' => 9],
- ['label' => '京豆', 'value' => 10],
- ['label' => '养老金', 'value' => 11],
- ['label' => '股权分红', 'value' => 12],
- ['label' => '联创分红', 'value' => 13],
- ['label' => '合伙人分红', 'value' => 14],
- ['label' => '直推贡献值', 'value' => 15],]),
- Elm::radio('award_type','奖励变更',1)->options([['label' => '增加', 'value' => 1], ['label' => '减少', 'value' => 2]]),
- Elm::number('num', '变动金额')->size('large')->required(),
- Elm::text('admin_id','操作人','管理员')->disabled(true),
- Elm::text('scene','操作场景','后台操作')->disabled(true),
- Elm::textarea('mark','备注')
- ])->setTitle('奖励变更');
- }
- /**
- *
- * @param $uid
- * @param $spread_account
- * @return false|int|void
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function changeAward($id,$type,$award_type,$num,$mark,$admin_id){
- $user = $this->dao->get($id);
- Db::transaction(function () use ($award_type, $user, $type, $num ,$mark,$admin_id) {
- $commission_type = 0;
- switch ($type){
- // PV
- case 1:
- if($award_type == 1){
- // 增加
- $isert_data = [
- 'uid' => $user['uid'],
- 'pv' => $num,
- 'status' => 1,
- 'addtime' => time(),
- 'mark' => empty($mark) ?'管理员调整pv值' : $mark,
- 'settlement_time' => date('Y-m-d H:i:s'),
- ];
- Db::name('user_pv_log')->insert($isert_data);
- Db::name('user')->where('uid',$user['uid'])->inc('pv', $num)->update();
- }else{
- // 减少
- Db::name('user')->where('uid',$user['uid'])->dec('pv', $num)->update();
- }
- break;
- // 积分
- case 2:
- $isert_data = [
- 'uid' => $user['uid'],
- 'reward_socre' => $num,
- 'status' => 1,
- 'mark' => empty($mark) ?'管理员调整积分' : $mark ,
- 'addtime' => time(),
- 'surplus' => $user['score'],
- 'settlement_time' => date('Y-m-d H:i:s'),
- ];
- if($award_type == 1){
- // 增加
- $isert_data['pm'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('score', $num)->update();
- }else{
- // 减少
- $isert_data['pm'] = 2;
- Db::name('user')->where('uid',$user['uid'])->dec('score', $num)->update();
- }
- Db::name('user_sign_score')->insert($isert_data);
- break;
- // 复购金
- case 4:
- $isert_data = [
- 'uid' => $user['uid'],
- 'number' => $num,
- 'status' => 1,
- 'mark' => empty($mark) ?'管理员调整复购金' :$mark ,
- 'addtime' => time(),
- 'surplus' => $user['fugou'],
- 'settlement_time' => date('Y-m-d H:i:s'),
- ];
- if($award_type == 1){
- // 增加
- $isert_data['type'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('fugou', $num)->update();
- }else{
- // 减少
- $isert_data['type'] = 2;
- Db::name('user')->where('uid',$user['uid'])->dec('fugou', $num)->update();
- }
- Db::name('user_sign_fugou')->insert($isert_data);
- break;
- // 红包
- case 5:
- $isert_data = [
- 'uid' => $user['uid'],
- 'number' => $num,
- 'status' => 1,
- 'mark' => empty($mark) ?'管理员调整红包':$mark ,
- 'addtime' => time(),
- 'surplus' => $user['hongbao'],
- 'settlement_time' => date('Y-m-d H:i:s'),
- ];
- if($award_type == 1){
- // 增加
- $isert_data['type'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('hongbao', $num)->update();
- }else{
- // 减少
- $isert_data['type'] = 2;
- Db::name('user')->where('uid',$user['uid'])->dec('hongbao', $num)->update();
- }
- Db::name('user_sign_hongbao')->insert($isert_data);
- break;
- // 贡献值
- case 8:
- $isert_data = [
- 'uid' => $user['uid'],
- 'number' => $num,
- 'status' => 1,
- 'mark' => empty($mark) ?'管理员调整贡献值':$mark ,
- 'addtime' => time(),
- 'surplus' => $user['contribute'],
- 'settlement_time' => date('Y-m-d H:i:s'),
- ];
- if($award_type == 1){
- // 增加
- $isert_data['type'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('contribute', $num)->update();
- }else{
- // 减少
- $isert_data['type'] = 2;
- Db::name('user')->where('uid',$user['uid'])->dec('contribute', $num)->update();
- }
- Db::name('user_sign_gongxian')->insert($isert_data);
- break;
- // vr
- case 9:
- $isert_data = [
- 'uid' => $user['uid'],
- 'number' => $num,
- 'mark' => empty($mark) ?'管理员调整vr':$mark ,
- 'addtime' => time(),
- 'surplus' => $user['vr'],
- 'settlement_time' => date('Y-m-d H:i:s'),
- ];
- if($award_type == 1){
- // 增加
- $isert_data['type'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('vr', $num)->update();
- }else{
- // 减少
- $isert_data['type'] = 2;
- Db::name('user')->where('uid',$user['uid'])->dec('vr', $num)->update();
- }
- Db::name('user_sign_vr')->insert($isert_data);
- break;
- // 京豆
- case 10:
- $isert_data = [
- 'uid' => $user['uid'],
- 'number' => $num,
- 'status' => 1,
- 'mark' => empty($mark) ?'管理员调整京豆':$mark ,
- 'addtime' => time(),
- 'surplus' => $user['jingdou'],
- 'settlement_time' => date('Y-m-d H:i:s'),
- ];
- if($award_type == 1){
- // 增加
- $isert_data['type'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('jingdou', $num)->update();
- }else{
- // 减少
- $isert_data['type'] = 2;
- Db::name('user')->where('uid',$user['uid'])->dec('jingdou', $num)->update();
- }
- Db::name('user_sign_jingdou')->insert($isert_data);
- break;
- // 直推佣金
- case 3:
- $commission_type = 3;
- // 锁客收益
- case 6:
- $commission_type = 7;
- break;
- // 推广店铺收益
- case 7:
- $commission_type = 10;
- break;
- // 养老金
- case 11:
- $commission_type = 5;
- break;
- // 股权分红
- case 12:
- $commission_type = 13;
- break;
- // 联创分红
- case 13:
- $commission_type = 12;
- break;
- // 合伙人分红
- case 14:
- $commission_type = 11;
- break;
- // 直推贡献值
- case 15:
- $isert_data = [
- 'uid' => $user['uid'],
- 'number' => $num,
- 'status' => 1,
- 'mark' => empty($mark) ?'管理员调整直推贡献值':$mark ,
- 'addtime' => time(),
- 'surplus' => $user['contribute'],
- 'settlement_time' => date('Y-m-d H:i:s'),
- ];
- if($award_type == 1){
- // 增加
- $isert_data['type'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('per_contribute', $num)->update();
- }else{
- // 减少
- $isert_data['type'] = 2;
- Db::name('user')->where('uid',$user['uid'])->dec('per_contribute', $num)->update();
- }
- Db::name('user_sign_gongxian')->insert($isert_data);
- break;
- }
- if($commission_type){
- $isert_data = [
- 'uid' => $user['uid'],
- 'number' => $num,
- 'status' => 1,
- 'commission_type' => $commission_type,
- 'mark' => empty($mark) ?'管理员调整收益':$mark ,
- 'create_time' => date('Y-m-d H:i:s'),
- 'take_time' => time()
- ];
- if($commission_type != 5){
- $isert_data['balance'] = $user['brokerage_price'];
- if($award_type == 1){
- // 增加
- $isert_data['pm'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('brokerage_price', $num)->update();
- }else{
- // 减少
- $isert_data['pm'] = 0;
- Db::name('user')->where('uid',$user['uid'])->dec('brokerage_price', $num)->update();
- }
- }else{
- $isert_data['balance'] = $user['annuity'];
- if($award_type == 1){
- // 增加
- $isert_data['pm'] = 1;
- $isert_data['gzc'] = 1;
- Db::name('user')->where('uid',$user['uid'])->inc('annuity', $num)->update();
- }else{
- // 减少
- $isert_data['pm'] = 0;
- Db::name('user')->where('uid',$user['uid'])->dec('annuity', $num)->update();
- }
- }
- Db::name('user_bill')->insert($isert_data);
- }
- if ($commission_type == 5 && $award_type == 1) {
- $cer = Db::name('user')
- ->where('uid', $user['uid'])
- ->field('real_name, phone, card_id')
- ->find();
- $ylj_data_log = [
- 'user_name' => $cer['real_name'],
- "mobile" => $cer['phone'],
- "user_card" => $cer['card_id'],//身份证
- "pension" => $num,//养老金
- "out_trade_no" => '',
- "account_type" => '',
- "order_type" => 0,
- "pay_time" => '',
- "create_time" => date('Y-m-d H:i:s'),
- "update_time" => date('Y-m-d H:i:s'),
- "uid" => $user['uid'],
- "platform_no" => 'IN10' . (int)(microtime(true) * 1000) . mt_rand(10000, 99999),
- "link_id" => ''
- ];
- Db::name('gzc_logs')->insert($ylj_data_log);
- }
- $insert_data = [
- 'uid' => $user['uid'],
- 'type' => $type,
- 'award_type' => $award_type,
- 'num' => $num,
- 'admin_id' => $admin_id,
- 'mark' => empty($mark) ? '管理员操作' : $mark
- ];
- Db::name('change_award_log')->insert($insert_data);
- });
- return true;
- }
- public function changeProForm_yhc($id,$type=0)
- {
- if($type===1){
- return Elm::createForm(Route::buildUrl('systemUserChangePro', compact('id'))->build(), [
- Elm::input('spread_account', '业绩归属人账号')->required()->placeholder("请填写业绩归属人手机号")->info('修改业绩归属人后,用户业绩归属至所填写账号下,但邀请关系及其他邀请相关的奖励不变!'),
- Elm::hidden('type', '1')
- ])->setTitle('修改业绩归属人');
- }
- return Elm::createForm(Route::buildUrl('systemUserChangePro', compact('id'))->build(), [
- Elm::input('spread_account', '推荐人')->required()->placeholder("请填写推荐人手机号")
- ])->setTitle('修改用户推荐人');
- }
- /**
- * @param $id
- * @param $adminId
- * @param $type
- * @param $nowMoney
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changeNowMoney($id, $adminId, $type, $nowMoney)
- {
- $user = $this->dao->get($id);
- Db::transaction(function () use ($id, $adminId, $user, $type, $nowMoney) {
- $balance = $type == 1 ? bcadd($user->now_money, $nowMoney, 2) : bcsub($user->now_money, $nowMoney, 2);
- $user->save(['now_money' => $balance]);
- /** @var UserBillRepository $make */
- $make = app()->make(UserBillRepository::class);
- if ($type == 1) {
- $make->incBill($id, 'now_money', 'sys_inc_money', [
- 'link_id' => $adminId,
- 'status' => 1,
- 'title' => '系统增加余额',
- 'number' => $nowMoney,
- 'mark' => '系统增加了' . floatval($nowMoney) . '余额',
- 'balance' => $balance
- ]);
- } else {
- $make->decBill($id, 'now_money', 'sys_dec_money', [
- 'link_id' => $adminId,
- 'status' => 1,
- 'title' => '系统减少余额',
- 'number' => $nowMoney,
- 'mark' => '系统减少了' . floatval($nowMoney) . '余额',
- 'balance' => $balance
- ]);
- }
- });
- }
- /**
- * @param $password
- * @return false|string|null
- * @author xaboy
- * @day 2020/6/22
- */
- public function encodePassword($password)
- {
- return password_hash($password, PASSWORD_BCRYPT);
- }
- /**
- * @param WechatUser $wechatUser
- * @return BaseDao|array|Model|null
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020-04-28
- */
- public function syncWechatUser(WechatUser $wechatUser, $userType = 'wechat')
- {
- $user = $this->dao->wechatUserIdBytUser($wechatUser->wechat_user_id);
- $request = request();
- if ($user) {
- $user->save([
- 'nickname' => $wechatUser['nickname'] ?: '',
- 'avatar' => $wechatUser['headimgurl'] ?: '',
- 'sex' => $wechatUser['sex'] ?: 0,
- 'last_time' => date('Y-m-d H:i:s'),
- 'last_ip' => $request->ip(),
- ]);
- }
- // else
- // $user = $this->create($userType, [
- // 'account' => 'wx' . $wechatUser->wechat_user_id . time(),
- // 'wechat_user_id' => $wechatUser->wechat_user_id,
- // 'pwd' => $this->encodePassword(123456),
- // 'nickname' => $wechatUser['nickname'] ?: '',
- // 'avatar' => $wechatUser['headimgurl'] ?: '',
- // 'sex' => $wechatUser['sex'] ?: 0,
- // 'spread_uid' => 0,
- // 'is_promoter' => 0,
- // 'last_time' => date('Y-m-d H:i:s'),
- // 'last_ip' => $request->ip()
- // ]);
- return $user;
- }
- /**
- * @param string $type
- * @param array $userInfo
- * @param int $url 推广员的ID
- * @return BaseDao|Model
- * @author xaboy
- * @day 2020-04-28
- */
- public function create(string $type, array $userInfo, $url=0,$spread_uid=null)
- {
- $userInfo['user_type'] = $type;
- Db::startTrans();
- try {
- $user = $this->dao->create($userInfo); //创建用户
- $this -> insterUser($user->uid, $spread_uid);
- //唯品会pid
- // $vip = app()->make(Vip::class);
- // $vip->create_pid($user->uid);
- // //拼多多pid
- // $taoke = app()->make(TaoKe::class);
- // $taoke->generateAd($user->uid);
- // //京东pid(改成京京推推就)
- // $jd = app()->make(Jd::class);
- // $jd->create_pid($user->uid);
- //
- // Queue::push(SendNewPeopleCouponJob::class, $user->uid);
- //赠送积分 注册送30积分
- $this->sign_add($user['uid'], 30,1,'注册送30积分','','', '', 1, '', 1);
- Db::commit();
- return $user;
- } catch (\Exception $e) {
- Log::info($userInfo);
- Db::rollback();
- log::info("注册失败".$e->getFile().':'.$e->getLine().'【'.$e->getMessage().'】');
- throw new AuthException('注册失败');
- }
- }
- public function getUserLevelId($spread_uid){
- if (empty($spread_uid)){
- return false;
- }
- $sql = "select getUserLevelId($spread_uid) as count";
- $getUserLevelId = Db::query($sql);
- $user_level_uids=ltrim($getUserLevelId[0]['count'],'$,');
- return $user_level_uids;
- }
- public function insterUser($uid, $spread_uid){
- /**
- * 查询上级人数 select * from rrx_user_count LIMIT 0,1
- */
- // $spread_uid = Db::name('user') -> where('uid', $uid) -> value('spread_uid');
- // Db::name('log')->insert(['data'=>'公排注册:'.$uid.'======'.$spread_uid]);
- // $userCount = false;
- // if ($spread_uid > 0){
- // //找直推上级网络里面不足5人的排进去
- //
- // $userCount = Db::name('user_count') -> where('level_number >= 0') -> where ('uid', $spread_uid) -> find();
- // if (!$userCount){
- // $userCount = $this -> getCountUId($spread_uid);
- // }
- //
- //
- // }
- // Log::info("userCount:::");
- // Log::info($userCount);
- // Log::info($spread_uid);
- // Db::name('log')->insert(['data'=>'uid:'.$uid.'公排注册:'.json_encode($userCount)]);
- // if (!$userCount){
- // //没有直推上级 大公排
- // $userCount = Db::name('user_count') -> where('level_number >= 0') -> find();
- // //增加一个只查询新账户大公排下的用户
- // // $userCount = Db::name('user_count') -> where('level_number >= 0')->whereIn('uid',$this->getUserLevelId(11112)) -> find();
- // }
- // if ($userCount) {
- // if ($userCount['level_number'] + 1 == systemConfig( 'max_level_number')) { //(33制或者55制)下级最大人数systemConfig( 'max_level_number')
- // Db::name('user_count') -> where('uid',$userCount['uid'])->delete();
- // } else {
- // $level_number = $userCount['level_number'] + 1;
- // Db::name('user_count') -> where('uid',$userCount['uid']) -> update(['level_number'=>$level_number]);
- // }
- // }
- // dd($spread_uid);
- // Db::name('user') -> where('uid',$uid)->update(['level_id'=>$userCount['uid'],'level'=>$this->level()]);
- // Db::name('user_count') -> insert(['uid'=>$uid]);
- }
- public function getCountUId($spread_uid){
- if (empty($spread_uid)){
- return false;
- }
- //查询所有下级是否满足条件
- //查询所有下级uid
- $level_id = Db::name('user') -> where('level_id', $spread_uid) -> field('uid') -> select()->toArray();
- $level_ids = array_column($level_id,'uid');
- $check_ids = Db::name('user_count') -> where('level_number >= 0') -> where ('uid','in', $level_ids) -> find();
- foreach ($level_id as $value){
- //查询下级是否满足条件
- $check = Db::name('user_count') -> where('level_number >= 0') -> where ('uid', $value['uid']) -> find();
- if ($check){
- return $check;
- }else if(empty($check_ids)){
- $id = $this -> getCountUId($value['uid']);
- if ($id){
- return $id;
- }
- }
- }
- return false;
- }
- private function level() {
- $count = Db::name('user')->where('level > 0')->count();
- switch ($count) {
- case 0:
- return 1;
- case 1:
- return 2;
- }
- $number = ($count + 1) - floor($count / 5);
- return ceil(log($number) / log(5)) + 1;
- }
- /**
- * @param User $user
- * @return array
- * @author xaboy
- * @day 2020-04-29
- */
- public function createToken(User $user)
- {
- $service = new JwtTokenService();
- $token = $service->createToken($user->uid, 'user');
- $this->cacheToken($token['token'], $token['out'],$user->uid);
- if($user -> user_number == ''){
- $this -> createUserNumber($user->uid);
- }
- // if($user -> im == 0 && env('im',false)){
- // $im = new Im();
- // $im -> createIm($user -> account,$user -> user_number);
- // }
- return $token;
- }
- /**
- * //TODO 登录成功后
- * @param User $user
- * @author xaboy
- * @day 2020/6/22
- */
- public function loginAfter(User $user)
- {
- $user->last_time = date('Y-m-d H:i:s', time());
- $user->last_ip = request()->ip();
- $user->save();
- }
- /**
- * @param string $token
- * @param int $exp
- * @author xaboy
- * @day 2020-04-29
- */
- public function cacheToken(string $token, int $exp,$uid)
- {
- Cache::set('user_' . $token, time() + $exp, $exp);
- Cache::set('java_' . $token, $uid, $exp);
- }
- /**
- * @param string $token
- * @author xaboy
- * @day 2020-04-29
- */
- public function checkToken(string $token)
- {
- $has = Cache::has('user_' . $token);
- if (!$has)
- throw new AuthException('无效的token');
- $lastTime = Cache::get('user_' . $token);
- if (($lastTime + intval(Config::get('admin.token_valid_exp', 15)) * 60) < time())
- throw new AuthException('token 已过期');
- }
- /**
- * @param string $token
- * @author xaboy
- * @day 2020-04-29
- */
- public function updateToken(string $token)
- {
- Cache::set('user_' . $token, time(), intval(Config::get('admin.token_valid_exp', 15)) * 60);
- }
- /**
- * @param string $token
- * @author xaboy
- * @day 2020-04-29
- */
- public function clearToken(string $token)
- {
- Cache::delete('user_' . $token);
- }
- /**
- * @param string $key
- * @param string $code
- * @author xaboy
- * @day 2020/6/1
- */
- public function checkCode(string $key, string $code)
- {
- $_code = Cache::get('am_captcha' . $key);
- if (!$_code) {
- throw new ValidateException('验证码过期');
- }
- if (strtolower($_code) != strtolower($code)) {
- throw new ValidateException('验证码错误');
- }
- //删除code
- Cache::delete('am_captcha' . $key);
- }
- /**
- * @param string $code
- * @return string
- * @author xaboy
- * @day 2020/6/1
- */
- public function createLoginKey(string $code)
- {
- $key = uniqid(microtime(true), true);
- Cache::set('am_captcha' . $key, $code, Config::get('admin.captcha_exp', 5) * 60);
- return $key;
- }
- //$repository->registr($data['phone'], $data['password'],'APP',"","",$data['spread']);
- public function registr(string $phone, ?string $pwd, $user_type = 'h5',$url="",$nickname="",$external=1,$spread_uid=0)
- {
- $user_res = Db::name('user')->where('phone', $phone)->find();
- if ($user_res && !$user_res['account']) {
- $data = [
- 'account' => $phone,
- ];
- $this->dao->update($user_res['uid'], $data);
- return $this->dao->get($user_res['uid']);
- }
- $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
- $data = [
- 'account' => $phone,
- 'pwd' => $pwd,
- 'nickname' =>$nickname?$nickname:'用户' . substr($phone, 7, 4),
- 'avatar' => 'https://cdn.bjtdba.com/vod/image/2025-01-20/20250120125206881.png',
- 'phone' => $phone,
- 'last_ip' => app('request')->ip(),
- "identity"=>5,
- "external"=>$external,
- "level_id"=>$spread_uid,
- "spread_uid"=>$spread_uid
- ];
- return $this->create($user_type, $data, $url,$spread_uid);
- }
- public function addregistr($data)
- {
- // string $phone, ?string $pwd, $user_type = 'h5',$url,
- $phone=$data['phone'];
- $pwd=empty($data['password'])?time():$data['password'];
- $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
- $data = [
- 'account' => $phone,
- 'pwd' => $pwd,
- 'nickname' => '用户' . substr($phone, 7, 4),
- 'avatar' => 'https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png',
- 'phone' => $phone,
- 'last_ip' => app('request')->ip(),
- 'user_name'=>empty($data['user_name'])?0:$data['user_name'],
- 'birthday'=>empty($data['birthday'])?0:$data['birthday'],
- 'sex'=>empty($data['adr_id'])?0:$data['sex'],
- 'spread_uid'=>$data['spread'],
- 'adr_id'=>empty($data['adr_id'])?0:$data["adr_id"],
- 'identity'=>empty($data['identity'])?0:$data["identity"],
- ];
- return $this->create("APP", $data);
- }
- /**
- * 重置密码
- * @param string $phone
- * @param string|null $pwd
- * @author 似水星辰 [ 2630481389@qq.com ]
- * @created 2020/10/14 23:46
- */
- public function resetPassword(string $phone, ?string $pwd, int $userid)
- {
- $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
- $data = [
- 'account' => $phone,
- 'pwd' => $pwd,
- 'phone' => $phone,
- 'last_ip' => app('request')->ip()
- ];
- return $this->dao->update($userid, $data);
- }
- /*重置手机号*/
- public function resetAccount(string $phone, int $userid, $identity){
- $data = [
- 'account' => $phone,
- 'phone' => $phone,
- 'last_ip' => app('request')->ip()
- ];
- //如果是商家
- if($identity == 4){
- $res = Db::name("merchant_admin")->where(['uid'=>$userid])->update(['account'=>$phone,'phone'=>$phone]);
- if(!$res){
- return false;
- }
- }
- return $this->dao->update($userid, $data);
- }
- public function routineSpreadImage(User $user)
- {
- //小程序
- $name = $user['uid'] . '_' . $user['is_promoter'] . '_user_routine.jpg';
- $attachmentRepository = app()->make(AttachmentRepository::class);
- $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
- $spreadBanner = systemGroupData('spread_banner');
- if (!count($spreadBanner)) return [];
- $siteName = systemConfig('site_name');
- $siteUrl = systemConfig('site_url');
- $uploadType = (int)systemConfig('upload_type') ?: 1;
- //检测远程文件是否存在
- if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
- $imageInfo->delete();
- $imageInfo = null;
- }
- if (!$imageInfo) {
- $routineQrcodeRepository = app()->make(RoutineQrcodeRepository::class);
- $res = $routineQrcodeRepository->getShareCode($user['uid'], 'spread', '',$user['avatar']);
- if (!$res) throw new ValidateException('二维码生成失败');
- $upload = UploadService::create($uploadType);
- $uploadRes = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
- if ($uploadRes === false) {
- throw new ValidateException($upload->getError());
- }
- $imageInfo = $upload->getUploadInfo();
- $imageInfo['image_type'] = $uploadType;
- $imageInfo['dir'] = path_to_url($imageInfo['dir']);
- if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
- $attachmentRepository->create($uploadType, -1, $user->uid, [
- 'attachment_category_id' => 0,
- 'attachment_name' => $imageInfo['name'],
- 'attachment_src' => $imageInfo['dir']
- ]);
- $routineQrcodeRepository->setRoutineQrcodeFind($res['id'], ['status' => 1, 'url_time' => date('Y-m-d H:i:s'), 'qrcode_url' => $imageInfo['dir']]);
- $urlCode = $imageInfo['dir'];
- } else $urlCode = $imageInfo['attachment_src'];
- $siteUrlHttps = set_http_type($siteUrl, request()->isSsl() ? 0 : 1);
- $filelink = [
- 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
- 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
- ];
- if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
- if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
- $resRoutine = true;
- foreach ($spreadBanner as $key => &$item) {
- $posterInfo = '海报生成失败:(';
- $config = array(
- 'image' => array(
- array(
- 'url' => $urlCode, //二维码资源
- 'stream' => 0,
- 'left' => 114,
- 'top' => 790,
- 'right' => 0,
- 'bottom' => 0,
- 'width' => 120,
- 'height' => 120,
- 'opacity' => 100
- )
- ),
- 'text' => array(
- array(
- 'text' => $user['nickname'],
- 'left' => 250,
- 'top' => 840,
- 'fontPath' => $filelink['Bold'], //字体文件
- 'fontSize' => 16, //字号
- 'fontColor' => '40,40,40', //字体颜色
- 'angle' => 0,
- ),
- array(
- 'text' => '邀请您加入' . $siteName,
- 'left' => 250,
- 'top' => 880,
- 'fontPath' => $filelink['Normal'], //字体文件
- 'fontSize' => 16, //字号
- 'fontColor' => '40,40,40', //字体颜色
- 'angle' => 0,
- )
- ),
- 'background' => $item['pic']
- );
- $resRoutine = $resRoutine && $posterInfo = setSharePoster($config, 'routine/spread/poster');
- if (!is_array($posterInfo)) throw new ValidateException($posterInfo);
- $posterInfo['dir'] = path_to_url($posterInfo['dir']);
- if (strpos($posterInfo['dir'], 'http') === false) $posterInfo['dir'] = request()->domain() . $posterInfo['dir'];
- $attachmentRepository->create($uploadType, -1, $user->uid, [
- 'attachment_category_id' => 0,
- 'attachment_name' => $posterInfo['name'],
- 'attachment_src' => $posterInfo['dir']
- ]);
- if ($resRoutine) {
- if ($posterInfo['image_type'] == 1)
- $item['poster'] = rtrim($siteUrlHttps, '/') . $posterInfo['dir'];
- else
- $item['poster'] = set_http_type($posterInfo['dir'], request()->isSsl() ? 0 : 1);
- $item['poster'] = str_replace('\\', '/', $item['poster']);
- }
- }
- return $spreadBanner;
- }
- public function wxSpreadImage(User $user)
- {
- //公众号
- $name = $user['uid'] . '_' . $user['is_promoter'] . '_user_wap.jpg';
- $spreadBanner = systemGroupData('spread_banner');
- if (!count($spreadBanner)) return [];
- $siteName = systemConfig('site_name');
- $attachmentRepository = app()->make(AttachmentRepository::class);
- $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
- $siteUrl = systemConfig('site_url');
- $uploadType = (int)systemConfig('upload_type') ?: 1;
- $resWap = true;
- //检测远程文件是否存在
- if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
- $imageInfo->delete();
- $imageInfo = null;
- }
- if (!$imageInfo) {
- $codeUrl = set_http_type($siteUrl . '/share?spread=' . $user['uid'], request()->isSsl() ? 0 : 1);//二维码链接
- $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name,$user['avatar']);
- if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
- $imageInfo['dir'] = path_to_url($imageInfo['dir']);
- if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
- $attachmentRepository->create(systemConfig('upload_type') ?: 1, -1, $user->uid, [
- 'attachment_category_id' => 0,
- 'attachment_name' => $imageInfo['name'],
- 'attachment_src' => $imageInfo['dir']
- ]);
- $urlCode = $imageInfo['dir'];
- } else $urlCode = $imageInfo['attachment_src'];
- $siteUrl = set_http_type($siteUrl, request()->isSsl() ? 0 : 1);
- $filelink = [
- 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
- 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
- ];
- if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
- if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
- foreach ($spreadBanner as $key => &$item) {
- $posterInfo = '海报生成失败:(';
- $config = array(
- 'image' => array(
- array(
- 'url' => $urlCode, //二维码资源
- 'stream' => 0,
- 'left' => 160,//84
- 'top' => 530,//630
- 'right' => 0,
- 'bottom' => 0,
- 'width' => 280,
- 'height' => 280,
- 'opacity' => 100
- )
- ),
- 'text' => array(
- array(
- 'text' => "NO:".$user['user_number'],
- 'left' => 200,
- 'top' => 850,
- 'fontPath' => $filelink['Bold'], //字体文件
- 'fontSize' => 16, //字号
- 'fontColor' => '0,0,0', //字体颜色
- 'angle' => 0,
- ),
- // array(
- // 'text' => '邀请您加入' . $siteName,
- // 'left' => 290,
- // 'top' => 750,
- // 'fontPath' => $filelink['Normal'], //字体文件
- // 'fontSize' => 16, //字号
- // 'fontColor' => '40,40,40', //字体颜色
- // 'angle' => 0,
- // )
- ),
- 'background' => $item['pic']
- );
- $resWap = $resWap && $posterInfo = setSharePoster($config, 'wap/spread/poster');
- if (!is_array($posterInfo)) throw new ValidateException('海报生成失败');
- $posterInfo['dir'] = path_to_url($posterInfo['dir']);
- if (strpos($posterInfo['dir'], 'http') === false) $posterInfo['dir'] = request()->domain() . $posterInfo['dir'];
- $attachmentRepository->create($uploadType, -1, $user->uid, [
- 'attachment_category_id' => 0,
- 'attachment_name' => $posterInfo['name'],
- 'attachment_src' => $posterInfo['dir']
- ]);
- if ($resWap) {
- if ($posterInfo['image_type'] == 1)
- $item['wap_poster'] = rtrim($siteUrl, '/') . $posterInfo['thumb_path'];
- else
- $item['wap_poster'] = set_http_type($posterInfo['thumb_path'], 1);
- }
- $item['wap_poster'] = str_replace('http://','https://',$item['wap_poster']);
- $item["attachment_src"]= str_replace('http://','https://',$urlCode);
- $item["name"]=$user['phone'];
- }
- return $spreadBanner;
- }
- public function getUsername($uid)
- {
- return User::getDB()->where('uid', $uid)->value('user_name');
- }
- /*获取用户手机号*/
- public function getUserPhone($uid)
- {
- return User::getDB()->where('uid', $uid)->value('account');
- }
- /**
- * @param $uid
- * @param $inc
- * @param string $type
- * @author xaboy
- * @day 2020/6/22
- */
- public function incBrokerage($uid, $inc, $type = '+')
- {
- $weekKey = 'b_top_' . date('Y-m');
- $moneyKey = 'b_top_' . monday();
- //TODO 佣金周榜
- $brokerage = Cache::zscore($weekKey, $uid);
- $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
- Cache::zadd($weekKey, $brokerage, $uid);
- //TODO 佣金月榜
- $brokerage = Cache::zscore($moneyKey, $uid);
- $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
- Cache::zadd($moneyKey, $brokerage, $uid);
- }
- public function brokerageWeekTop($page, $limit)
- {
- $key = 'b_top_' . monday();
- return $this->topList($key, $page, $limit);
- }
- public function brokerageMonthTop($page, $limit)
- {
- $key = 'b_top_' . date('Y-m');
- return $this->topList($key, $page, $limit);
- }
- /**
- * //TODO 绑定上下级关系
- * @param User $user
- * @param int $spreadUid
- * @throws DbException
- * @author xaboy
- * @day 2020/6/22
- */
- public function bindSpread(User $user, int $spreadUid)
- {
- if ($spreadUid && !$user->spread_uid && $user->uid != $spreadUid) {
- Db::transaction(function () use ($spreadUid, $user) {
- $spread_user = $this ->get($spreadUid);
- // //首次邀请赠送899积分
- // if($spread_user['spread_count'] == 0){
- // //首次邀请好友奖励积分
- // $this -> sign_add($spreadUid,systemConfig('first_yq_score'),1,'首次邀请好友奖励积分','','');
- // }
- //邀请好友奖励积分
- // $this->sign_add($spreadUid,systemConfig('invitation'),1,'邀请好友注册奖励积分','','');
- //邀请好友奖励积分
- $this->sign_add($spreadUid, 30,1,'邀请好友注册奖励积分','','', '', 1, '', 1);
- $user->spread_uid = $spreadUid;
- $user->spread_time = date('Y-m-d H:i:s');
- if($spreadUid){
- $user->mer_id = Db::name('user')->where('uid',$spreadUid)->value('mer_id');
- }
- $this->dao->update($spreadUid, [
- 'spread_count' => Db::raw('spread_count +1')
- ]);
- $user->save();
- //TODO 推广人月榜
- Cache::zincrby('s_top_' . date('Y-m'), 1, $spreadUid);
- //TODO 推广人周榜
- Cache::zincrby('s_top_' . monday(), 1, $spreadUid);
- });
- $this->spread_log($user,$spreadUid);
- }
- //绑定上下级关系 加入推广群
- // $this -> hximTg($user -> uid,$spreadUid);
- }
- /**
- * @param $uid int 用户id
- * @param $sid int 上级id
- * @author Tang
- * @created 2021/12/10
- */
- public function hximTg($uid,$sid)
- {
- try {
- $im=new Im();
- $user=Db::name('user')->where('uid',$uid)->find();
- if($user['im']==0){//没有环信账户 创建
- $im->createImUser($user['account'], $user['nickname']);
- $user_account=$user['account'];
- }else{//有环信账户 跳过创建 下一步
- $user_account=$user['account'];
- }
- $userS=Db::name('user')->where('uid',$sid)->find();
- if($userS['im']==0){//上级环信账户 创建
- $im->createImUser($userS['account'], $userS['nickname']);
- $s_account=$userS['account'];
- }else{//有环信账户 跳过创建 下一步
- $s_account=$userS['account'];
- }
- $group_id=Db::name("im_group")->where(['uid'=>$userS['account'],'type'=>'p'])->value('groupid');
- //判断是否有群
- if($group_id){//有则加入
- $im->createGroupUser($group_id,$user_account,$user['uid']);
- }else{
- $group_id=$im->createGroup($s_account,'推广群','t');
- $im->createGroupUser($group_id,$user_account,$user['uid']);
- }
- }catch (\Exception $e) {
- Db::name("log")->insert(array('data'=>'推广群错误'.$e->getMessage()));//日志记录
- }
- }
- //注册时成为推广员身份 记录统计及信息
- public function spread_log($user,$spreadUid){
- if($spreadUid){
- Db::transaction(function () use ($spreadUid, $user) {
- $sp = DB::name("user")->where(['uid'=>$spreadUid])->field("uid,spread_count")->find();
- if($sp){
- //推荐人推荐数量加1
- Db::name("user")->where(['uid'=>$sp['uid']])->update(['spread_count'=>($sp['spread_count']+1)]);
- //保存用户的推荐记录
- $log =[
- 'uid'=> $sp['uid'],
- 'link_id'=>$user->uid,
- 'identity'=>5,
- 'create_time'=>date("Y-m-d H:i:s"),
- ] ;
- Db::name("user_identity_log")->insert($log);
- }
- });
- }
- }
- public function topList($key, $page, $limit)
- {
- $res = Cache::zrevrange($key, ($page - 1) * $limit, $limit, true);
- $ids = array_keys($res);
- $index = array_flip($ids);
- $count = Cache::zcard($key);
- $list = count($ids) ? $this->dao->users($ids, 'uid,avatar,nickname')->toArray() : [];
- foreach ($list as $k => $v) {
- $list[$k]['count'] = $res[$v['uid']] ?? 0;
- }
- $sort = array_column($list, 'count');
- array_multisort($sort, SORT_DESC, $list);
- return compact('count', 'list');
- }
- public function spreadWeekTop($page, $limit)
- {
- $key = 's_top_' . monday();
- return $this->topList($key, $page, $limit);
- }
- public function spreadMonthTop($page, $limit)
- {
- $key = 's_top_' . date('Y-m');
- return $this->topList($key, $page, $limit);
- }
- /**
- * @param $uid
- * @param $nickname
- * @param $sort
- * @param $page
- * @param $limit
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020/6/22
- */
- public function getOneLevelList($uid, $nickname, $sort, $page, $limit)
- {
- $query = $this->search(['spread_uid' => $uid, 'nickname' => $nickname, 'sort' => $sort]);
- $count = $query->count();
- $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
- return compact('list', 'count');
- }
- /**
- * @param $uid
- * @param $nickname
- * @param $sort
- * @param $page
- * @param $limit
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020/6/22
- */
- public function getTwoLevelList($uid, $nickname, $sort, $page, $limit)
- {
- $ids = $this->dao->getSubIds($uid);
- if (count($ids)) {
- $query = $this->search(['spread_uids' => $ids, 'nickname' => $nickname, 'sort' => $sort]);
- $count = $query->count();
- $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
- } else {
- $list = [];
- $count = 0;
- }
- return compact('list', 'count');
- }
- public function getLevelList($uid, array $where, $page, $limit)
- {
- if (!$where['level']) {
- // $ids = $this->dao->getSubIds($uid);
- $ids[] = $uid;
- $where['spread_uids'] = $ids;
- } else if ($where['level'] == 2) {
- $ids = $this->dao->getSubIds($uid);
- if (!count($ids)) return ['list' => [], 'count' => 0];
- $where['spread_uids'] = $ids;
- } else {
- $where['spread_uid'] = $uid;
- }
- $query = $this->search($where);
- $count = $query->count();
- $list = $query->setOption('field', [])->field('User.uid,avatar,nickname,is_promoter,pay_count,pay_price,spread_count,User.create_time')->page($page, $limit)->select();
- return compact('list', 'count','where');
- }
- /**
- * @param $uid
- * @param $page
- * @param $limit
- * @param array $where
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020/6/26
- */
- public function subOrder($uid, $page, $limit, array $where = [])
- {
- if (isset($where['level'])) {
- if (!$where['level']) {
- $ids = $this->dao->getSubIds($uid);
- $subIds = $this->dao->getSubAllIds($ids);
- } else if ($where['level'] == 2) {
- $ids = $this->dao->getSubIds($uid);
- $subIds = $this->dao->getSubAllIds($ids);
- $ids = [];
- } else {
- $ids = $this->dao->getSubIds($uid);
- $subIds = [];
- }
- } else {
- $ids = $this->dao->getSubIds($uid);
- $subIds = $this->dao->getSubAllIds($ids);
- }
- $all = array_merge($ids, $subIds);
- if (!count($all)) return ['count' => 0, 'list' => []];
- $query = app()->make(StoreOrderRepository::class)->usersOrderQuery($where, $all);
- $count = $query->count();
- $list = $query->page($page, $limit)->field('uid,order_sn,pay_time,extension_one,extension_two')->with(['user' => function ($query) {
- $query->field('avatar,nickname,uid');
- }])->select()->toArray();
- foreach ($list as $k => $item) {
- $list[$k]['brokerage'] = in_array($item['uid'], $ids) ? $item['extension_one'] : $item['extension_two'];
- unset($list[$k]['extension_one'], $list[$k]['extension_two']);
- }
- return compact('count', 'list');
- }
- /**
- * @param User $user
- * @return User
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @author xaboy
- * @day 2020/7/2
- */
- public function mainUser(User $user): User
- {
- if (!$user->main_uid || $user->uid == $user->main_uid) return $user;
- $switchUser = $this->dao->get($user->main_uid);
- if (!$switchUser) return $user;
- if ($user->wechat_user_id && !$switchUser->wechat_user_id) {
- $switchUser->wechat_user_id = $user->wechat_user_id;
- $switchUser->save();
- }
- return $switchUser;
- }
- public function switchUser(User $user, $uid)
- {
- if ($user->uid == $uid || !$this->dao->existsWhere(['uid' => $uid, 'phone' => $user->phone]))
- throw new ValidateException('操作失败');
- $this->dao->update($user->uid, ['main_uid' => $uid]);
- $switchUser = $this->dao->get($uid);
- return $switchUser;
- }
- public function returnToken($user, $tokenInfo)
- {
- $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();
- return [
- 'token' => $tokenInfo['token'],
- 'exp' => $tokenInfo['out'],
- 'user' => $user
- ];
- }
- public function switchBrokerage(User $user, $brokerage)
- {
- $user->now_money = bcadd($user->now_money, $brokerage, 2);
- $user->brokerage_price = bcsub($user->brokerage_price, $brokerage, 2);
- Db::transaction(function () use ($brokerage, $user) {
- $user->save();
- app()->make(UserBillRepository::class)->incBill($user->uid, 'now_money', 'brokerage', [
- 'link_id' => 0,
- 'status' => 1,
- 'title' => '佣金转入余额',
- 'number' => $brokerage,
- 'mark' => '成功转入余额' . floatval($brokerage) . '元',
- 'balance' => $user->now_money
- ]);
- app()->make(UserBillRepository::class)->decBill($user->uid, 'brokerage', 'now_money', [
- 'link_id' => 0,
- 'status' => 1,
- 'title' => '佣金转入余额',
- 'number' => $brokerage,
- 'mark' => '成功转入余额' . floatval($brokerage) . '元',
- 'balance' => $user->brokerage_price
- ]);
- });
- }
- /**
- * 签到
- * @param $member_id
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function sub_signin($member_id){
- $member_info = Db::name('user')->where( array('uid' => $member_id) )->find();
- $config =systemConfig([
- 'isopen_signinreward',
- 'signinreward_day1_score',
- 'signinreward_day2_score',
- 'signinreward_day3_score',
- 'signinreward_day4_score',
- 'signinreward_day5_score',
- 'signinreward_day6_score',
- 'signinreward_day7_score',
- ]);
- //是否开启签到奖励
- $isopen_signinreward = empty($config['isopen_signinreward']) ? 0 : $config['isopen_signinreward'];
- if( $isopen_signinreward != 1 )
- {
- return array('code' => 1,'msg' => '签到奖励功能未开启');
- }
- //连续7天签到奖励
- $signinreward_day1_score = empty($config['signinreward_day1_score']) ? 0 : $config['signinreward_day1_score'];
- $signinreward_day2_score = empty($config['signinreward_day2_score']) ? 0 : $config['signinreward_day2_score'];
- $signinreward_day3_score = empty($config['signinreward_day3_score']) ? 0 : $config['signinreward_day3_score'];
- $signinreward_day4_score = empty($config['signinreward_day4_score']) ? 0 : $config['signinreward_day4_score'];
- $signinreward_day5_score = empty($config['signinreward_day5_score']) ? 0 : $config['signinreward_day5_score'];
- $signinreward_day6_score = empty($config['signinreward_day6_score']) ? 0 : $config['signinreward_day6_score'];
- $signinreward_day7_score = empty($config['signinreward_day7_score']) ? 0 : $config['signinreward_day7_score'];
- //准备数据
- $result = array();
- $result['signinreward_day1_score'] = $signinreward_day1_score;
- $result['signinreward_day2_score'] = $signinreward_day2_score;
- $result['signinreward_day3_score'] = $signinreward_day3_score;
- $result['signinreward_day4_score'] = $signinreward_day4_score;
- $result['signinreward_day5_score'] = $signinreward_day5_score;
- $result['signinreward_day6_score'] = $signinreward_day6_score;
- $result['signinreward_day7_score'] = $signinreward_day7_score;
- $today_signintime = time();
- $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->whereDay('signin_time')->find();
- if( !empty($today_signin_info) )
- {
- return array('code' => 1,'msg' => '今天已经签到过了');
- }else{
- //查询昨天是否已经签到了
- $yes_signintime = strtotime( date('Y-m-d'). ' 00:00:00' ) - 86400;
- $yes_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id, 'signin_time' => $yes_signintime ) )->find();
- $has_qian = 1;
- if( !empty($yes_signin_info) )
- {
- $has_qian = $yes_signin_info['continuity_day'] +1;
- $has_qian = $has_qian > 7 ? 7 : $has_qian;
- }
- $get_score = $result["signinreward_day".$has_qian."_score"];
- $ins_data = array();
- $ins_data['member_id'] = $member_id;
- $ins_data['continuity_day'] = $has_qian;
- $ins_data['reward_socre'] = $get_score;
- $ins_data['signin_time'] = $today_signintime;
- $ins_data['addtime'] = time();
- $member_info = Db::name('user')->where( array('uid' => $member_id) )->find();
- $score = $member_info['now_score'];
- Db::name('user_signinreward_record')->insert($ins_data);
- $now_score=$score+$get_score;
- app()->make(UserBillRepository::class)->incBill($member_id, 'now_money', 'recharge', [
- 'link_id' => 1,
- 'status' => 1,
- 'title' => '签到积分',
- 'number' => $get_score,
- 'mark' => '连续签到'.$has_qian.'天赠送',
- 'balance' =>$now_score
- ]);
- Db::name('user')->where( array('uid' => $member_id) )->update(['now_score'=>$now_score]);
- // Db::name('log')->insert(['data'=>Db::name('user')->getLastSql(),'time'=>date('Y-m-d H:i:s',time())]);
- return array('code' =>0, 'now_score' => $score, 'continuity_day' => $has_qian,'reward_socre' => $get_score );
- }
- }
- public function get_signin($member_id,$where=[]){
- if ($where){
- $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time', 'between', [$where['data1'], $where['data2']])->find();
- $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');
- }else{
- $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time',"today")->find();
- $show_day_arr= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time',"month")->column('signin_time');
- }
- $score= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->count('reward_socre');
- $leiji= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->sum('reward_socre');
- foreach ($show_day_arr as &$v){
- $v=date("Y-m-d",$v);
- }
- $result['score'] = $score;
- $result['today_is_signin'] = $today_signin_info?1:0;
- $result['leiji'] = $leiji;
- $result['show_day_arr'] = $show_day_arr;
- return $result;
- }
- public function add_cer($data=[],$member_id)
- {
- $renzeng=Db::name("user_certification")->where("uid",$member_id)->find();
- if ($renzeng){
- $res = Db::name('user_certification')->where("uid",$member_id)->update($data);
- }else{
- $res = Db::name('user_certification')->insert($data);
- }
- if($res){
- return [
- 'user_name' => $data['user_name'],
- 'age' => $this->getAgeByID($data['user_card']),
- 'user_card' => preg_replace('/(\d{6})\d{8}(\d{4})/', '$1****$2', $data['user_card']),
- ];
- }
- else{
- return false;
- }
- }
- public function get_cer($data=[])
- {
- $res = Db::name('user_certification')->where($data)->find();
- //计算年龄
- $res['age'] = $this->getAgeByID($res['user_card']);
- if($res){
- return $res;
- }
- else{
- return false;
- }
- }
- public function getAgeByID($id){
- //过了这年的生日才算多了1周岁
- if(empty($id)) return '';
- $date=strtotime(substr($id,6,8));
- //获得出生年月日的时间戳
- $today=strtotime('today');
- //获得今日的时间戳
- $diff=floor(($today-$date)/86400/365);
- //得到两个日期相差的大体年数
- //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
- $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
- return $age;
- }
- /**
- * @param $data
- *
- */
- public function addagent($user){
- if ($user){
- $data=[
- "identity"=>5,
- "status"=>1,
- "add_time"=>time(),
- "update_time"=>time(),
- "user_id"=>$user->uid,
- "name"=>"推广员",
- "pay_status"=>1,
- "price"=>0,
- "agent_sn"=>time(),
- ];
- Db::name("user_agent")->insert($data);
- }
- }
- /*
- * 申请代理
- @cabbage
- */
- public function agent($data){
- $user = Db::name("user")->where(['uid'=>$data['user_id']])->field("identity,account,uid")->find();
- //判断所申请的区域下是否有代理
- if($data['identity'] == 1){
- if(Db::name("user_street")->where("street_id",$data['street_id'])->value("uid")){
- return ['code'=>400,'msg'=>'该区域下已有代理'];
- }
- }elseif($data['identity'] == 2){
- if(Db::name("user_area")->where("area_id",$data['area_id'])->value("uid")){
- return ['code'=>400,'msg'=>'该区域下已有代理'];
- }
- }elseif($data['identity'] == 3){
- if(Db::name("user_city")->where("city_id",$data['city_id'])->value("uid")){
- return ['code'=>400,'msg'=>'该区域下已有代理'];
- }
- }
- //判断是不是商户
- // if($user['identity']==4){
- // return ['code'=>'400','msg'=>"不符合申请代理的条件"];
- // }
- //判断用户是否是其他代理身份
- // if(in_array($user['identity'],[1,2,3,5])){
- // return ['code'=>'400','msg'=>"用户已是推广身份"];
- // }
- if($user['identity']==$data['identity']){
- return ['code'=>'400','msg'=>"用户已是该身份,无需申请"];
- }
- if($data['spread_account'] == $user['account']){
- return ['code'=>'400','msg'=>"推荐人不能是自己"];
- }
- $real = Db::name("user_certification")->where(["uid"=>$data['user_id'],'status'=>1])->find();
- //判断是否实名认证
- if(!$real){
- return ['code'=>'400','msg'=>"请先实名认证"];
- }
- if($user){
- if($data['identity'] == $user['identity']){
- return ['code'=>'400','msg'=>"已经是该级别代理"];
- }
- if(!in_array($user['identity'],[4,5]) && $data['identity'] < $user['identity']){
- return ['code'=>'400','msg'=>"不能申请低于现在级别的代理"];
- }
- }
- $is_apply= Db::name("user_agent")->where(["user_id"=>$data["user_id"],'status'=>[0,2]])->find();
- if ($is_apply){
- if($is_apply['status'] == 0){
- return ['code'=>'400','msg'=>"您有审核中的代理申清"];
- }
- if($is_apply['status'] == 2) {
- $data['status']= 0;//恢复申请中状态
- $res= Db::name("user_agent")->where("id",$is_apply['id'])->update($data);
- if($res){
- return true;
- }
- }
- }
- $res= Db::name("user_agent")->insert($data);
- if($res){
- return true;
- }
- }
- public function isAgent($uid){
- $res = Db::name("user_agent")
- ->where(["user_id"=>$uid])
- ->whereIn('status',[0,1,2])
- ->whereIn('identity',[1,2,3,6])
- ->order("add_time desc")
- ->find();
- if(!$res){
- return json_encode([]);
- }
- $res['province_name'] = Db::name("user_province")->where(['province_id'=>$res['province_id']])->value("province_name");
- $res['city_name'] = Db::name("user_city")->where(['city_id'=>$res['city_id']])->value("city_name");
- $res['area_name'] = Db::name("user_area")->where(['area_id'=>$res['area_id']])->value("area_name");
- $res['street_name'] = Db::name("user_street")->where(['street_id'=>$res['street_id']])->value("street_name");
- switch ($res['identity']){
- case '1':
- $res['name'] = '镇级服务商';
- break;
- case '2':
- $res['name'] = '县级服务商';
- break;
- case '3':
- $res['name'] = '市级服务商';
- break;
- case '6':
- $res['name'] = '渠道商';
- }
- return $res;
- }
- public function getAgentPayDetail($where=[]){
- $res= Db::name("user_agent")->where($where)->find();
- return $res;
- }
- public function get_agent_info($member_id){
- $user=Db::name("user")->where("uid",$member_id)->find();
- $data=[
- "nickname"=>$user["nickname"],
- "avatar"=>$user["avatar"],
- "is_promoter"=>$user["is_promoter"],
- "identity"=>$user["identity"],
- "brokerage_price"=>set_price_rtrim($user["brokerage_price"]),
- "uid"=>$member_id,
- ];
- $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");
- $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");
- $data["extract"]=(string)Db::name("user_extract")->where(["uid"=>$member_id,"status"=>1])->sum("extract_price");
- return $data;
- }
- /*
- * 全民营销->推广统计
- */
- public function get_extension_info($member_id,$search,$where=[]){
- $data=[];
- $data["count_zong"]=Db::name("user_identity_log")->where(["uid"=>$member_id])->count();
- $data["town"]=Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>1])->whereNotIn("identity","0")->count();
- $data["county"]= Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>2])->whereNotIn("identity","0")->count();
- $data["city"]= Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>3])->whereNotIn("identity","0")->count();
- $data["shop"]=Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>4])->whereNotIn("identity","0")->count();
- $data["tuiguang"]=Db::name("user_identity_log")->where(["uid"=>$member_id])->whereIn('identity','5,0')->count();
- $query =Db::name("user_identity_log")->alias("a")
- ->join('user s',"a.link_id=s.uid")
- ->where(["a.uid"=>$member_id])
- ->field("s.nickname,a.create_time,a.identity,s.phone");
- if(isset($where['identity']) && $where['identity'] != ''){
- $query = $query->where(['a.identity'=>$where['identity']]);
- }
- if(isset($search) && $search !=''){
- $query =$query->whereLike('s.account','%'.$search.'%');
- }
- $list = $query->select();
- $data["list"]=$list;
- return $data;
- }
- public function get_profit_info($member_id,$where){
- // $data["count_yj"]=Db::name("user")->where(["type"=>"commission"])->sum("number");
- // $data["dlfee"]=Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");
- // $data["xiaofee"]=Db::name("user")->where(["type"=>"commission","commission_type"=>2])->sum("number");;
- // $data["county"] =Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");;
- // $data["town"]==Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");;
- $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
- ->field("type,number,status,commission_type,create_time,uid,title,order_sn");
- $order = "create_time desc";
- if($where['date_on'] == 1){
- $order = "create_time desc";
- }elseif($where['date_off'] == 1){
- $order = "create_time asc";
- }
- if(isset($where['commission_type']) && $where['commission_type'] !=''){
- $query = $query->where(['commission_type'=>$where['commission_type']]);
- }else{
- $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
- }
- if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
- $query = $query->whereTime("create_time",$where['order']);
- }
- $list= $query->order($order)->select()->toArray();
- $dangqian_yj=Db::name("user")->where("uid",$member_id)->value("brokerage_price");
- $dlfee=0;
- $xiaofei=0;
- $tuiguang=0;
- $xiaqu=0;
- $weijiesuan=0;
- $qudao=0;
- foreach ($list as &$v){
- // $count_yj=$v["number"]+$count_yj;
- if ($v["status"]==0){
- $v["title"]="【预估】".$v["title"].",单号:".$v["order_sn"];
- $weijiesuan+=$v['number'];
- }elseif($v["status"]==-1){
- $v["title"]="【失效】".$v["title"].",单号:".$v["order_sn"];
- }else{
- if ($v["commission_type"]==1){
- $dlfee+=$v["number"];
- }
- if ($v["commission_type"]==2){
- $xiaofei+=$v["number"];
- }
- if ($v["commission_type"]==3){
- $tuiguang+=$v["number"];
- }
- if ($v["commission_type"]==4){
- $xiaqu+=$v["number"];
- }
- if ($v["commission_type"]==6||$v["commission_type"]==7){
- $tuiguang+=$v["number"];
- }
- if ($v["commission_type"]==9){
- $qudao+=$v["number"];
- }
- if ($v["commission_type"]==10){
- $tuiguang+=$v["number"];
- }
- }
- }
- $data["count_yj"]=round($dangqian_yj,2);//当前佣金
- $data["dlfee"]=round($dlfee,2); //代理非
- $data["xiaofei"]=round($xiaofei,2); //消费佣金
- $data["tuiguang"]= round($tuiguang,2); //推广佣金
- $data["xiaqu"]=round($xiaqu,2); //辖区佣金
- $data["weijiesuan"]=round($weijiesuan,2);//未结束佣金
- $data["qudao"]=round($qudao,2);//渠道
- $data["list"]=$list;
- return $data;
- }
- /*
- * 越攒越多统计
- * */
- public function get_com_all($member_id,$where){
- $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
- ->field("type,number,status,commission_type,create_time,uid,title,order_sn,type_shop");
- $order = "create_time desc";
- if(isset($where['commission_type']) && $where['commission_type'] !=''){
- $query = $query->where(['commission_type'=>$where['commission_type']]);
- }else{
- $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
- }
- if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
- $query = $query->whereTime("create_time",$where['order']);
- }
- $query = $query->where(['status'=>1]);
- $list= $query->order($order)->select()->toArray();
- $dangqian_yj=Db::name("user")->where("uid",$member_id)->value("brokerage_price");
- $dlfee=0;
- $xiaofei=0;
- $tuiguang=0;
- $kuadian=0;
- $xiaqu=0;
- $weijiesuan=0;
- $ptjl=0;
- $qudao=0;
- foreach ($list as &$v){
- // $count_yj=$v["number"]+$count_yj;
- if ($v["commission_type"]==1){
- $dlfee+=$v["number"];
- }
- if ($v["commission_type"]==2){
- $xiaofei+=$v["number"];
- }
- if ($v["commission_type"]==3){
- $tuiguang+=$v["number"];
- }
- if ($v["commission_type"]==4){
- $xiaqu+=$v["number"];
- $v['title'] = '辖区获取佣金';
- }
- if ($v["commission_type"]==7){
- $kuadian+=$v["number"];
- $v['title'] = '跨店获取佣金';
- }
- if ($v["commission_type"]==8){
- $ptjl+=$v["number"];
- $v['title'] = '平台奖励佣金';
- }
- if ($v["commission_type"]==9){
- $qudao+=$v["number"];
- $v['title'] = '渠道商奖励佣金';
- }
- if ($v["commission_type"]==10){
- $tuiguang+=$v["number"];
- $v['title'] = '推荐商户奖励佣金';
- }
- // if ($v['type_shop'] >0){
- // $qudao+=$v['number'];
- // $v['title'] = '第三方订单获取佣金';
- // }
- }
- $data["count_yj"]=round($dangqian_yj,2);//当前佣金
- $data["dlfee"]=round($dlfee,2); //代理非
- $data["xiaofei"]=round($xiaofei,2); //消费佣金
- $data["tuiguang"]= round($tuiguang,2); //推广佣金
- $data["xiaqu"]=round($xiaqu,2); //辖区佣金
- $data["weijiesuan"]=round($weijiesuan,2);//未结束佣金
- $data["kuadian"]=round($kuadian,2); //跨店
- $data["ptjl"]=round($ptjl,2); //平台奖励佣金
- $data["qudao"]=round($qudao,2); //渠道
- return $data;
- }
- /*
- * 越攒越多列表
- * */
- public function get_com_list($member_id,$where){
- $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
- ->field("type,number,status,commission_type,create_time,uid,title,order_sn,type_shop");
- $order = "create_time desc";
- if(isset($where['commission_type']) && $where['commission_type'] !=''){
- $query = $query->where(['commission_type'=>$where['commission_type']]);
- }else{
- $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
- }
- if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
- $query = $query->whereTime("create_time",$where['order']);
- }
- $page = $where['page'] ?? 1;
- $limit = $where['limit'] ?? 10;
- $query = $query->where(['status'=>1]);
- $list= $query->page($page,$limit)->order($order)->select()->toArray();
- $data["list"]=$list;
- return $data;
- }
- /**
- * 获取推广列表
- */
- public function get_tuiguang_list($member_id,$where = []){
- $query = Db::name("user_bill")
- ->alias("ul")
- ->where(["ul.type"=>"commission",'ul.uid'=>$member_id])
- ->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");
- if(isset($where['type']) && in_array($where['type'],[0,1])){
- $query = $query->where(['ul.source'=>$where['type']]);
- }
- if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
- $query = $query->whereTime("create_time",$where['order']);
- }
- $page = $where['page'] ?? 1;
- $limit = $where['limit'] ?? 10;
- $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
- $query = $query ->where("status",'>=',0);
- //不显示红积分的
- $query = $query ->where("is_red_brokerage",'=',0);
- $list= $query->order("create_time desc")->page($page,$limit)->select()->toArray();
- foreach ($list as &$v){
- // $v["create_time"]=date("Y-m-d", $v["create_time"]);
- //0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么
- if($v['type_shop'] == 0){
- if($v['source'] == 0){
- if($v['commission_type'] == 9){
- $this -> getContent('channel_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v);
- }elseif($v['commission_type'] == 10){
- $this -> getContent('merchant_annual_cost_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v);
- }else{
- $this -> getContent('store_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v,$v['create_time']);
- }
- }else{
- $uid=Db::name("store_order")->where("order_sn",$v["order_sn"])->value("uid");
- $v["nickname"]=$this -> getUserNickname($uid);
- $v['content'] = '用户'.$v['nickname'].'到店消费,帮您攒金';
- $v['xiadan'] = $v['create_time'] ?? '';
- $v['jiesuan'] = $v['create_time'];
- }
- }elseif ($v['type_shop'] == '1'){
- $this -> getContent('order_pdd',$v['order_sn'],'拼多多',$v['status'],$v['commission_type'],$v);
- }elseif ($v['type_shop'] == '2'){
- $this -> getContent('order_vip',$v['order_sn'],'唯品会',$v['status'],$v['commission_type'],$v);
- }elseif ($v['type_shop'] == '3'){
- $this -> getContent('order_su',$v['order_sn'],'苏宁易购',$v['status'],$v['commission_type'],$v);
- }
- elseif ($v['type_shop'] == '4'){
- // $uid = Db::name('order_jd')->where("order_sn",$v["order_sn"])->value("uid");
- // $v["nickname"]=$this -> getUserNickname($uid);
- $v["nickname"]='';
- $v['content'] = $v['nickname'].'在网易考拉消费,帮您攒金';
- $v['xiadan'] = '';
- $v['jiesuan'] = '';
- }elseif ($v['type_shop'] == '5'){
- $this -> getContent('order_tb',$v['order_sn'],'淘宝',$v['status'],$v['commission_type'],$v);
- }elseif ($v['type_shop'] == '6'){
- $this -> getContent('order_jd',$v['order_sn'],'京东',$v['status'],$v['commission_type'],$v);
- }elseif ($v['type_shop'] == '7'){
- $this -> getContent('order_tb',$v['order_sn'],'饿了么',$v['status'],$v['commission_type'],$v);
- }
- if($v['commission_type'] == 7){
- $v['mark'] = '【跨店】'.$v['mark'];
- }
- $v['number'] =set_price_rtrim($v['number']);
- }
- return $list;
- }
- public function getUserNickname($uid){
- return Db::name("user")->where("uid", $uid)->value("nickname");
- }
- public function getContent($table,$order_sn,$title,$status,$commission_type,&$v,$create_time=null){
- $yugu = '';
- if($status == 0){
- $yugu = "【预估】";
- if($commission_type == 7){
- $yugu = "【跨店预估】";
- }
- }
- switch ($table){
- case 'store_order':
- $res = Db::name($table)->where("order_sn",$order_sn)->field('uid,create_time,pay_time')->find();
- $v["nickname"]=$this -> getUserNickname($res['uid']);
- $v['content'] = $yugu.$v['nickname'].'在'.$title.'消费,帮您攒金';
- break;
- case 'channel_order':
- $res = Db::name($table)->where("order_no",$order_sn)->field('uid,create_time,pay_time')->find();
- $v["nickname"]=$this -> getUserNickname($res['uid']);
- $v['content'] = $v['nickname'].'成为渠道商,帮您攒金';
- $res['bill_end_time'] = strtotime($res['create_time']);
- break;
- case 'merchant_annual_cost_order':
- $res = Db::name($table)->where("order_no",$order_sn)->field('uid,create_time,pay_time')->find();
- $v["nickname"]=$this -> getUserNickname($res['uid']);
- $v['content'] = $v['nickname'].'成为商户,帮您攒金';
- $res['bill_end_time'] = strtotime($res['create_time']);
- break;
- default:
- $res = Db::name($table)->where("order_sn",$order_sn)->field('uid,create_time,bill_end_time,pay_time')->find();
- $v["nickname"]=$this -> getUserNickname($res['uid']);
- $v['content'] = $yugu.$v['nickname'].'在'.$title.'消费,帮您攒金';
- }
- // $v['xiadan'] = $res['create_time'] ?? $create_time;
- $v['xiadan'] = isset($res['pay_time'])?$res['pay_time']:$create_time;
- $v['jiesuan'] = $v['xiadan'];
- // if (empty($res['bill_end_time']) && empty($res['create_time'])){
- // $v['jiesuan'] = $create_time;
- // }else{
- // $v['jiesuan'] = date('Y-m-d H:i:s',$res['bill_end_time']??strtotime("+10 day", strtotime($res['create_time'])));
- // }
- }
- /**
- * 获取订单数
- */
- public function get_tuiguang_order($member_id){
- $where=["ul.type"=>"commission","ul.status"=>1,'ul.uid'=>$member_id];
- $list=Db::name("user_bill")
- ->alias("ul")
- // ->join("user u","u.uid=ul.uid")
- ->where("commission_type","<>",5)
- ->where($where)
- ->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")
- ->select();
- $num=0;
- $count=0;
- foreach ($list as &$v){
- $num++;
- // $v["create_time"]=date("Y-m-d", $v["create_time"]);
- $uid=Db::name("store_order")->where("order_sn",$v["order_sn"])->value("uid");
- $v["nickname"]=Db::name("user")->where("uid", $uid)->value("nickname");
- $count+=$v["number"];
- }
- return ["num"=>$num,"count"=>round($count,2),"list"=>$list];
- }
- public function get_yanglao($member_id){
- $data = Db::name("user")
- ->where("uid",$member_id)
- ->field("wechat_user_id,card_id,ali_user_id,annuity_frozen,annuity_num,annuity,create_time,birthday,birthday60,card_number,annuity_yiqu,pay_price")
- ->find();
- // $data['annuity'] = 0;
- $certification = Db::name("user_certification")->where("uid",$member_id)->find();
- $data['can_withdraw'] = 0;
- if (!$certification || $certification["status"] !=1 || !$certification["user_card"]){
- $data["birthday60"] = "未实名认证";
- $data['is_certification'] = 0;
- } else {
- // try {
- // $checkAmount = $this->checkAmount($certification);
- // if ($checkAmount['code'] == 0) {
- // $data['annuity'] = $checkAmount['extendData']['amount'];
- // }
- // } catch (\Throwable $e) {
- // Log::info('getyanglaojin' . $e->getMessage());
- // }
- $data['is_certification'] = 1;
- $birth_data = substr($certification["user_card"], 6, 8);
- // $birth = strtotime(substr($certification["user_card"], 6, 8));
- $old_age = $this->getSex($certification["user_card"])?60:55;
- // $age = $this->howOld($birth);
- $age=$this->calculateAge($birth_data);
- if ($age < $old_age) {
- // $yes = $old_age - $age;
- // $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("+" . $yes . " year"));
- }
- if ($age == $old_age) {
- $data['can_withdraw'] = 1;
- // $data["birthday60"] = date("Y-m-d", $birth);
- }
- if ($age > $old_age) {
- $data['can_withdraw'] = 1;
- // $yes = $age - $old_age;
- // $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("-" . $yes . " year"));
- }
- //收益余额
- $data['annuity_num'] = 123;
- $data['annuity_yiqu'] = 123;
- $data["birthday60"] = $this->getFutureBirthday($birth_data,$old_age);
- }
- $order_merchant_price= OrderMerchant::getInstance()->where('paid', 1)
- ->where(function ($query) use ($data) {
- $query->where('pay_user_id', $data['wechat_user_id'])
- ->whereOr('pay_user_id', $data['ali_user_id']);
- })
- ->sum('money');
- //加上线下消费的
- $data['pay_price'] = bcadd($data['pay_price'],$order_merchant_price,2);
- $data["yinghang"] = "中信公证处消费养老金账户";
- // $data["yinghang"]='https://app.bjtdba.com/uploads/def/20201021/8cb66944101287b8ac9c9b9fb1b13a79.png';
- $data["add_up"] = 0.00;
- return $data;
- }
- function calculateAge($birthDate) {
- $today = new \DateTime();
- $diff = $today->diff(new \DateTime($birthDate));
- return $diff->y;
- }
- function getFutureBirthday($birthDate, $years) {
- $date = new \DateTime($birthDate);
- $date->modify("+$years years");
- return $date->format('Y-m-d');
- }
- public function getSex($cid){
- //根据身份证号,自动返回性别
- $sexint = (int)substr($cid,16,1);
- return $sexint % 2 === 0 ? false : true;
- }
- /**
- * 根据时间戳计算年龄
- * @param $birth
- * @return mixed
- */
- public function howOld($birth) {
- list($birthYear, $birthMonth, $birthDay) = explode('-', date('Y-m-d', $birth));
- list($currentYear, $currentMonth, $currentDay) = explode('-', date('Y-m-d'));
- $age = $currentYear - $birthYear - 1;
- if($currentMonth > $birthMonth || $currentMonth == $birthMonth && $currentDay >= $birthDay)
- $age++;
- return $age;
- }
- public function yanglaolog($where,$page=1, $limit=10,$month='',$is_shixiao = 0){
- $where1 = [];
- if(!empty($where)){
- foreach($where as $key => $value){
- $where1['a.'.$key] = $value;
- }
- }
- $query=Db::name("user_bill")
- ->alias('a')
- ->join('Merchant b', 'a.mer_id = b.mer_id','left')
- ->field('a.*,b.mer_name,b.mer_avatar')
- ->where($where1)
- ->when($month!='',function ($q) use ($month){
- $q->whereLike('a.create_time',$month.'%');
- });
- if($is_shixiao == 0){
- $query -> where('a.status','<>','-1');
- }
- $query_sql1 = clone $query;
- $query_sql2 = clone $query;
- $query_sql3 = clone $query;
- $count = $query->count();
- $list = $query->page($page,$limit)->order("a.bill_id desc")->select()
- ->each(function($item){
- if($item['source'] == 0 && $item['type_shop'] == 0){
- $item['product'] = json_decode(Db::name("store_order")
- -> alias('a')
- -> join('store_order_product b','a.order_id = b.order_id','left')
- -> where(["a.order_sn"=>$item['order_sn']])
- -> value('b.cart_info'),true);
- if(empty($item['product'])){
- $item['product']=[
- 'product'=>[
- 'image'=>'https://cdn.bjtdba.com/vod/image/2025-01-21/20250121180855764.png',
- 'store_name'=>'商家年费'
- ]
- ];
- }
- }
- return $item;
- });
- $yugu=$query_sql1->sum('number');
- $yijiesuan=$query_sql1->where('a.status',1)->sum('number');
- $weijiesuan=$yugu-$yijiesuan;
- return compact('count','list','yugu','yijiesuan','weijiesuan');
- }
- /*养老金详情*/
- public function yanglaoDetail($where=[],$field='*'){
- $query=Db::name("user_bill")->where($where)->field($field)->find();
- return $query;
- }
- /*提现记录 type 1佣金 2养老金*/
- public function withdrawal($where){
- $data=Db::name("user_extract")->where($where)->order('extract_id','desc')->select();
- if(!$data->isEmpty()){
- $data=$data->toArray();
- }
- foreach ($data as $k=>&$v){
- if($v['withdrawal_type']==2){
- // $name=Db::name('merchant')->where('mer_id',$v['mer_id'])->value('mer_name');
- $v['title']='佣金提现';
- }else if($v['withdrawal_type']==3){
- if($v['extract_type']==1){
- $tltle='微信';
- $v['title']='提现到'.$tltle;
- }else if($v['extract_type']==3){
- $tltle='银行卡';
- $v['title']='提现到'.$tltle;
- }else if($v['extract_type']==4){
- $v['title']='人工减少佣金';
- }
- }else{
- $v['title']='幸福宝-佣金提现';
- }
- if($v['bank_info']!=''){
- $bank_info=json_decode($v['bank_info'],true);
- }
- $v['extract_price']=set_price_rtrim($v['extract_price']);
- $v['bank_name']=isset($bank_info['bank_name'])?$bank_info['bank_name']:'';
- }
- return $data;
- }
- /*提现记录 type 1佣金 2养老金*/
- public function withdrawal_user($where){
- $data=Db::name("user_extract")->where($where)->where('mer_id is null')->order('extract_id','desc')->select();
- if(!$data->isEmpty()){
- $data=$data->toArray();
- }
- foreach ($data as $k=>&$v){
- if($v['withdrawal_type']==2){
- // $name=Db::name('merchant')->where('mer_id',$v['mer_id'])->value('mer_name');
- $v['title']='佣金提现';
- }else if($v['withdrawal_type']==3){
- if($v['extract_type']==1){
- $tltle='微信';
- $v['title']='提现到'.$tltle;
- }else if($v['extract_type']==3){
- $tltle='银行卡';
- $v['title']='提现到'.$tltle;
- }else if($v['extract_type']==4){
- $v['title']='人工减少佣金';
- }
- }else{
- $v['title']='幸福宝-佣金提现';
- }
- if($v['bank_info']!=''){
- $bank_info=json_decode($v['bank_info'],true);
- $data[$k]['bank_info']=json_decode($v['bank_info'],true);
- }
- $v['extract_price']=set_price_rtrim($v['extract_price']);
- $v['bank_name']=isset($bank_info['bank_name'])?$bank_info['bank_name']:'';
- }
- return $data;
- }
- /*
- * 提现详情
- *@author cabbage
- *@date 2020-10-31
- * */
- public function withdrawalDetail($id,$uid){
- $data= Db::name("user_extract")->where(["uid"=>$uid,'extract_id'=>$id,"type"=>2])->find();
- return $data;
- }
- /*
- * 修改用户推广人id
- *@author cabbage
- *@date 2020-10-31
- * */
- public function update_spread($uid,$spread_account,$mark,$olld_id,$adminId,$spread){
- //被推荐人信息
- $identity=Db::name("user")->where('uid',$uid)->field("identity,spread_uid")->find();
- // $user_identity_log=Db::name("user_identity_log")->where(["link_id"=>$uid])->find();
- if($spread){
- try{
- $data= Db::name("user")->where(["uid"=>$uid])->update(['spread_uid'=>$spread['uid']]);
- Db::name("merchant")->where(["uid"=>$uid])->update(['recommender'=>$spread['uid']]);
- // if ($user_identity_log){
- // Db::name("user_identity_log")->where(["id"=>$user_identity_log["id"]])->update(['uid'=>$spread['uid']]);
- // }else{
- // Db::name("user_identity_log")->insert(['uid'=>$spread['uid'],"identity"=>$identity["identity"],"create_time"=>date("Y-m-d H:i:s"),"link_id"=>$uid]);
- // }
- Db::name("user_spread_change_records")->insert([
- 'operation_id' => $adminId,
- 'uid' => $uid,
- 'old_spread_id' => $olld_id,
- 'new_spread_id' => $spread['uid'],
- 'mark' => $mark
- ]);
- Db::name("user")->where('account',$spread_account)->inc("spread_count",1)->update();
- if ($identity["spread_uid"]){
- Db::name("user")->where('uid',$identity["spread_uid"])->dec("spread_count")->update();
- }
- return $data;
- }catch (Exception $e) {
- Db::rollback();
- }
- }else{
- return false;
- }
- }
- public function update_level_uid($uid, $olld_id, $level_account, $mark,$adminId,$level){
- if($level){
- try{
- Db::name("user_level_change_records")->insert([
- 'operation_id' => $adminId,
- 'uid' => $uid,
- 'old_level_id' => $olld_id,
- 'new_level_id' => $level['uid'],
- 'mark' => $mark ]);
- return Db::name("user")->where(["uid"=>$uid])->update(['level_id'=>$level['uid']]);
- }catch (\Exception $e) {
- return false;
- }
- }else{
- return false;
- }
- }
- public function update_user_group($id, $old_identity_id, $new_identity_id, $adminId, $mark)
- {
- try {
- Db::name("user_identity_change_records")->insert([
- 'operation_id' => $adminId,
- 'uid' => $id,
- 'old_identity_id' => $old_identity_id,
- 'new_identity_id' => $new_identity_id,
- 'mark' => $mark
- ]);
- return Db::name("user")->where("uid", $id)->update(['user_group' => $new_identity_id]);
- } catch (\Exception $e) {
- return false;
- }
- }
- /*获取协议列表*/
- public function getXieYi(){
- $data= Db::name("user_agreement")->where(["status"=>1])->select();
- return $data;
- }
- /*积分记录*/
- public function socreList($uid,$page,$limit){
- $data = Db::name("user_signinreward_record")
- ->where(['member_id'=>$uid])
- ->field("reward_socre,addtime")
- ->page($page,$limit)
- ->order("addtime desc")
- ->select()->toArray();
- foreach ($data as $k => $v) {
- $data[$k]['addtime'] = date("y-m-d H:i:s",$v['addtime']);
- $data[$k]['pm'] = 1 ;
- $data[$k]['mark'] = '签到获得' ;
- }
- $result['list'] = $data;
- $result['count'] = Db::name("user_signinreward_record")->where(['member_id'=>$uid])->count();
- $result['total_socre'] = Db::name("user_signinreward_record")->where(['member_id'=>$uid])->sum("reward_socre");
- $result['is_use'] = 0 ;
- $result['is_pass'] = 0 ;
- return $result;
- }
- /*修改用户信息*/
- public function updateUser($uid,$data,$data2=[]){
- $data = Db::name("user")->where(['uid'=>$uid])->update($data);
- if ($data2){
- $ck= Db::name("user_account")->where(["uid"=>$uid,"type"=>$data2["type"]])->find();
- if ($ck){
- $data= Db::name("user_account")->where(["id"=>$ck["id"]])->update($data2);
- }else{
- $data= Db::name("user_account")->insert($data2);
- }
- }
- return $data;
- }
- /*获取用户信息*/
- public function getUser($uid,$data){
- $user = Db::name("user")->where(['uid' => $uid])->field($data)->find();
- $data = Db::name("user_account")->where(['uid' => $uid])->select()->toArray();
- $types = array_column($data, 'type');
- if (!in_array('1', $types) && $user['wechat_user_id']) {
- $data[] = ['id' => 0, 'avater' => '', 'nickname' => null, 'type' => 1, 'uid' => $uid];
- Db::name("user_account")->insert(['type' => 1, 'uid' => $uid]);
- }
- if (!in_array('2', $types) && $user['ali_user_id']) {
- $data[] = ['id' => 0, 'avater' => '', 'nickname' => null, 'type' => 2, 'uid' => $uid];
- Db::name("user_account")->insert(['type' => 2, 'uid' => $uid]);
- }
- return $data;
- }
- public function getAccount($uid)
- {
- $userAccountList = Db::name("user_account")
- ->where(["uid"=>$uid])
- ->select()
- ->toArray();
- $wxNickname = '';
- $wxAvater = '';
- $alNickname = '';
- $alAvater = '';
- foreach ($userAccountList as $userAccount) {
- if ($userAccount['type'] == 1) {
- $wxNickname = $userAccount['nickname'];
- $wxAvater = $userAccount['avater'];
- } else if ($userAccount['type'] == 2) {
- $alNickname = $userAccount['nickname'];
- $alAvater = $userAccount['avater'];
- }
- }
- $res=Db::name('user_extract_openid')->where('uid',$uid)->value('openid');
- $wechat_user_id = Db::name('user') -> where('uid',$uid) -> value('wechat_user_id');
- if($res && !empty($wechat_user_id)){
- $arr[]=array(
- 'id'=>'1',
- 'type'=>'1',
- 'uid'=>$uid,
- 'nickname'=>$wxNickname,
- 'avater'=>$wxAvater,
- );
- }
- $res = Db::name('user') -> where('uid',$uid) -> value('ali_user_id');
- if($res && $res != '0' && $res != ''){
- $arr[]=array(
- 'id'=>'2',
- 'type'=>'2',
- 'uid'=>$uid,
- 'nickname'=>$alNickname,
- 'avater'=>$alAvater,
- );
- }
- return isset($arr)?$arr:[];
- }
- /**
- * 支付宝授权登录
- * 文档:https://opendocs.alipay.com/open/218/105327
- */
- public function aliSign(){
- $aop = new AopClient;
- $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
- $aop->appId = "2021001197654668";
- $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==';
- $aop->format = "json";
- $aop->charset = "UTF-8";
- $aop->signType = "RSA2";
- $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
- $data = [
- 'apiname'=>'com.alipay.account.auth',
- 'method'=>'alipay.open.auth.sdk.code.get',
- 'app_id'=>'2021001197654668',
- 'app_name'=>'mc',
- 'biz_type'=>'openservice',
- 'pid'=>'2088931546284482', //合作伙伴身份(PID):
- 'product_id'=>'APP_FAST_LOGIN',
- 'scope'=>'kuaijie',
- 'target_id'=>"ALI".time().rand(10000,99999),
- 'auth_type'=>'AUTHACCOUNT',
- 'sign_type'=>'RSA2'
- ];
- $sign = $aop->generateSign($data,"RSA2");
- $paramStr = '';
- foreach ($data as $key => $param) {
- $paramStr .= "{$key}={$param}&";
- }
- $paramStr = $paramStr.'sign='.urlencode($sign);
- return $paramStr;
- }
- /*
- * 支付宝登录验证
- * $userId 支付宝用户唯一id
- * */
- public function aliCheck($userId){
- $user = Db::name("user")->where(['ali_user_id'=>$userId])->find();
- //判断是否是第一次登录
- if($user){
- //成功登录业务逻辑
- if (!$user['account']) {
- return ['code' => 400, 'msg' => '请绑定手机号'];
- } else {
- return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
- }
- }else{
- return ['code' => 400, 'msg' => '请绑定手机号'];
- }
- }
- /*微信信息获取*/
- public function getWechat(){
- $data['appid'] = "wxbf753066ac8686ba";
- $data['appsecret'] = "68943fc124568c4ab4c3f089b7cdf2aa";
- return $data;
- }
- /**
- * 微信登录验证
- * @param $openid
- * @param $nickname
- * @param $headimgurl
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function wechatCheck($openid, $nickname = null, $headimgurl = null): array
- {
- // 1、判断 该openID 是否绑定多个用户
- $userDataList = Db::name("user")->where(['wechat_user_id' => $openid])->select()->toArray();
- $normalUserDataList = [];
- $normalUserData = [];
- if (!empty($userDataList)) {
- $resetWechatUserIdList = [];
- foreach ($userDataList as $userdata) {
- if ($userdata['is_del'] == 1) {
- $resetWechatUserIdList[] = $userdata['uid'];
- } else {
- $normalUserDataList[] = $userdata;
- }
- }
- if (!empty($resetWechatUserIdList)) {
- Db::name("user")->whereIn('uid', $resetWechatUserIdList)->update(["wechat_user_id" => 0]);
- Db::name("user_extract_openid")->whereIn('uid', $resetWechatUserIdList)->delete();
- Db::name("user_account")->whereIn('uid', $resetWechatUserIdList)->delete();
- }
- if (count($normalUserDataList) > 1) {
- return ['code' => 400, 'msg' => '当前账号异常,请联系客服!'];
- } else if (count($normalUserDataList) < 1) {
- return ['code' => 400, 'msg' => '请绑定手机号'];
- } else {
- $normalUserData = array_shift($normalUserDataList);
- }
- } else {
- return ['code' => 400, 'msg' => '请绑定手机号'];
- }
- // 2、更新 user_extract_openid
- $existOpenIdDataList = Db::name('user_extract_openid')->where('openid', $openid)->select()->toArray();
- $normalUserDataListByExtractOpenid = [];
- $normalUserDataByExtractOpenid = [];
- if (!empty($existOpenIdDataList)) {
- $existUidList = array_column($existOpenIdDataList, 'uid');
- // 查询 用户
- $existUserData = Db::name("user")->whereIn("uid", $existUidList)->select()->toArray();
- if (!empty($existUserData)) {
- $resetWechatUserIdList = [];
- $deleteUserExtractOpenidByUidList = [];
- foreach ($existUserData as $userdata) {
- if ($userdata['is_del'] == 1) {
- $resetWechatUserIdList[] = $userdata['uid'];
- } else {
- // if ($userdata['wechat_user_id'] == $openid) {
- $normalUserDataListByExtractOpenid[] = $userdata;
- // } else {
- // $deleteUserExtractOpenidByUidList[] = $userdata['uid'];
- // }
- }
- }
- // 已删除的用户
- if (!empty($resetWechatUserIdList)) {
- Db::name("user")->whereIn('uid', $resetWechatUserIdList)->update(["wechat_user_id" => 0]);
- Db::name("user_extract_openid")->whereIn('uid', $resetWechatUserIdList)->delete();
- Db::name("user_account")->whereIn('uid', $resetWechatUserIdList)->delete();
- }
- // // 用户表绑定的 微信ID 和 微信授权表中的不一致
- // if (!empty($deleteUserExtractOpenidByUidList)) {
- // Db::name("user_extract_openid")->whereIn('uid', $resetWechatUserIdList)->where('openid', $openid)->delete();
- // }
- if (count($normalUserDataListByExtractOpenid) > 1) {
- return ['code' => 400, 'msg' => '当前账号异常,请联系客服!'];
- } else {
- $normalUserDataByExtractOpenid = array_shift($normalUserDataListByExtractOpenid);
- }
- } else {
- Db::name('user_extract_openid')->where('openid', $openid)->delete();
- }
- }
- if (empty($normalUserDataByExtractOpenid)) {
- if (!empty($normalUserData)) {
- Db::name("user_extract_openid")->insert([
- 'uid' => $normalUserData['uid'],
- 'openid' => $openid,
- 'type' => 1
- ]);
- } else {
- return ['code' => 400, 'msg' => '请绑定手机号'];
- }
- } else {
- if ($normalUserDataByExtractOpenid['uid'] != $normalUserData['uid']) {
- return ['code' => 400, 'msg' => '当前账号异常,请联系客服!'];
- }
- }
- $data2 = [];
- if (!is_null($nickname) || !is_null($headimgurl)) {
- $data2 = [
- "type" => 1,
- "uid" => $normalUserData['uid'],
- "nickname" => $nickname ?: '',
- "avater" => $headimgurl ?: '',
- ];
- }
- $this->updateUser(
- $normalUserData['uid'],
- ['wechat_user_id' => $openid],
- $data2
- );
- return ['code' => 200, 'msg' => '登录成功', 'user' => $normalUserData];
- }
- /**
- * 微信登录验证一壶茶
- * @param $openid
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function wechatCheckYhc($openid){
- $enterprise_user = Db::name("enterprise_user")->where(['openid'=>$openid])->find();
- //判断是否是第一次登录,成功登录业务逻辑
- if($enterprise_user && $enterprise_user['uid']!=0){
- $user = Db::name("user")->where(['uid'=>$enterprise_user['uid']])->find();
- return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
- }
- return ['code' => 400, 'msg' => '请绑定手机号'];
- }
- /*微信支付宝绑定*/
- public function thirdBinding(string $phone, ?string $pwd, $user_type = 'APP',$third_user_id='',$type=0,$url, $spread_uid = 0)
- {
- $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
- $user = $this->accountByUser($phone);
- if($user){
- $data = [
- 'last_ip' => app('request')->ip(),
- ];
- }else{
- $data = [
- 'account' => $phone,
- 'pwd' => $pwd,
- 'nickname' => '用户' . substr($phone, 7, 4),
- 'avatar' => $url.'/uploads/logo.jpg',
- 'phone' => $phone,
- 'last_ip' => app('request')->ip(),
- "level_id"=>$spread_uid,
- "spread_uid"=>$spread_uid
- ];
- }
- if($type ==1){
- if(isset($user->wechat_user_id) && $user->wechat_user_id){return true;}//这里可能有问题
- $data['wechat_user_id'] = $third_user_id;
- }elseif($type ==2){
- if(isset($user->ali_user_id) && $user->ali_user_id){return true;}
- // if($user->ali_user_id){return true;}
- $data['ali_user_id'] = $third_user_id;
- }
- if(!$user){
- return $this->create($user_type, $data);
- }else{
- Db::name("user")->where(['account'=>$phone])->update($data);
- return $user;
- }
- }
- public function getTokenByCode($authorization_code,$info=false,$type=123)
- {
- try {
- $aop = new AopClient();
- $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
- if($type=='h5'){
- $aop->appId = '2021001197698727';
- $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=';
- $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
- }else if ($type == 'h5pay'){
- $aop->appId = '2021003191617008';
- $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==';
- $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuUb+0sJSNXjWiG0VJIPzn55+18af/fubYMpRLlreu34ewMgLx1zpCNpB3wrA+dylfWPMAm8PzvKnakByB+VJ/LMNhWHmF8Qkdo4astAikjlI4TMQCK/G384NzrtjHR4DGCDM5CMVt1xw5noF7kNBMYIvgDfhMCYmygdlIjuVdIlVEoQKOsT0RaNMleES0aZvbjvBGkGM0dsetqUExSjid9BF1NAO2ET+J3XMxCtMgCUVmFUvxsCKe6Rapa1/Lk3rzIeG6CRpoabuYfPM9E+3y3f3luSOMXLfH9lOSW1RA8qrF+Ms1RZv8gmzUnbyrPLmmZPmmN/Qs6DGzDVg73fpSwIDAQAB';
- }else{
- $aop->appId = '2021001197654668';
- $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==';
- $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
- }
- $aop->apiVersion = '1.0';
- $aop->signType = 'RSA2';
- $aop->postCharset='UTF-8';
- $aop->format='json';
- $request = new AlipaySystemOauthTokenRequest ();
- $request->setGrantType("authorization_code");
- $request->setCode($authorization_code);
- $result = $aop->execute($request);
- Db::name('log')->insert(['data'=>'支付宝相关信息']);
- if (isset($result->alipay_system_oauth_token_response->user_id)) {
- $return['user_id'] = $result->alipay_system_oauth_token_response->user_id;
- $return['msg'] = $result->alipay_system_oauth_token_response->access_token;
- $access_token=$return['msg'] ;
- } else {
- $return['code'] = $result->error_response->code;
- $return['msg'] = $result->error_response->sub_msg;
- return $return;
- }
- if ($info){
- $request = new AlipayUserInfoShareRequest();
- $result = $aop->execute ( $request ,$access_token);
- $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
- Db::name('log')->insert(['data'=>\GuzzleHttp\json_encode($responseNode)]);
- $resultCode = $result->$responseNode->code;
- Db::name('log')->insert(['data'=>$resultCode]);
- $userData=json_decode(json_encode($result->$responseNode),true);
- if(!empty($resultCode)&&$resultCode == 10000){
- return $userData;
- }
- }
- return $return;
- } catch (\Throwable $w) {
- Db::name('log')->insert(['data'=>json_encode($w->getMessage())]);
- return $w->getMessage();
- }
- }
- /**
- * 使用证书方式,通过 authCode 换取支付宝 AccessToken 和用户信息
- *
- * @param string $authorization_code 从 APP 获取的授权码
- * @param bool $info 是否在获取 Token 后立即获取用户信息 (true: 获取, false: 只获取 Token)
- * @return array 成功时返回包含 token 或用户信息的数组,失败时返回错误信息数组或字符串
- * @throws \Exception
- */
- public function getTokenByCodeWithCert(string $authorization_code, bool $info = false): array
- {
- try {
- // --- 1. 配置证书信息 ---
- // *** 请确保这里的 AppID 和 PrivateKey 是你进行【授权登录】的那个支付宝应用的 ***
- // *** 它可能与你进行【转账】的应用是同一个,也可能是不同的,请仔细核对 ***
- $app_id = "2021003138690179"; // 例如: 20210021XXXXXXXXXX
- $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文件读取 或 直接粘贴(不推荐)
- // *** 证书文件路径 ***
- // 建议使用绝对路径或相对于项目根目录的路径,确保PHP有读取权限
- $app_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/appCertPublicKey_2021003138690179.crt'; // 应用公钥证书路径
- $alipay_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/alipayCertPublicKey_RSA2_2021003138690179.crt'; // 支付宝公钥证书路径
- $alipay_root_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/alipayRootCert_2021003138690179.crt'; // 支付宝根证书路径
- // $app_id = "2021002194632049"; // 例如: 20210021XXXXXXXXXX
- // $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文件读取 或 直接粘贴(不推荐)
- //
- // // *** 证书文件路径 ***
- // // 建议使用绝对路径或相对于项目根目录的路径,确保PHP有读取权限
- // $app_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/appCertPublicKey.crt'; // 应用公钥证书路径
- // $alipay_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/alipayCertPublicKey.crt'; // 支付宝公钥证书路径
- // $alipay_root_cert_path = dirname(__FILE__) . '/../../../../extend/alipay/aop/cert/alipayRootCert.crt'; // 支付宝根证书路径
- $url = "https://openapi.alipay.com/gateway.do"; // 支付宝网关
- // --- 2. 初始化支付宝配置 (使用 AlipayConfig) ---
- $alipayConfig = new AlipayConfig();
- $alipayConfig->setAppId($app_id);
- $alipayConfig->setCharset("utf-8");
- $alipayConfig->setFormat("json");
- $alipayConfig->setSignType("RSA2");
- $alipayConfig->setServerUrl($url);
- $alipayConfig->setPrivateKey($privateKey); // 设置应用私钥
- // *** 设置证书路径 ***
- $alipayConfig->setAppCertPath($app_cert_path);
- $alipayConfig->setAlipayPublicCertPath($alipay_cert_path);
- $alipayConfig->setRootCertPath($alipay_root_cert_path);
- // --- 3. 实例化证书模式客户端 (使用 AopCertClient) ---
- $aop = new AopCertClient($alipayConfig);
- $aop->isCheckAlipayPublicCert = true; // 强烈建议启用支付宝公钥证书校验
- // --- 4. 创建并执行获取 Token 的请求 ---
- $request = new AlipaySystemOauthTokenRequest();
- $request->setGrantType("authorization_code");
- $request->setCode($authorization_code); // 设置从 APP 获取的 authCode
- // 执行请求
- $result = $aop->execute($request); // R 返回的是原始响应字符串,需要解码
- $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; // 结果节点的 key,例如 "alipay_system_oauth_token_response"
- // 解析 JSON 响应
- $resultObj = json_decode($result);
- Db::name('log')->insert(['data' => '支付宝Token获取响应解析: ' . json_encode($resultObj, JSON_UNESCAPED_UNICODE)]);
- // --- 5. 处理 Token 响应 ---
- // 检查是否存在响应节点,并且顶层没有 error_response
- if (isset($resultObj->$responseNode) && !isset($resultObj->error_response)) {
- // 成功获取 Token
- $response = $resultObj->$responseNode; // 获取响应数据对象
- // $return_data = [
- // 'code' => 200,
- // 'msg' => 'Token fetched successfully',
- // 'user_id' => $response->user_id, // 从 $response 获取
- // 'access_token' => $response->access_token, // 从 $response 获取
- // 'refresh_token' => $response->refresh_token,
- // 'expires_in' => $response->expires_in,
- // 're_expires_in' => $response->re_expires_in,
- // // 确保 alipay_user_id 也捕获,如果需要的话 (看你的业务逻辑)
- // // 'alipay_user_id' => $response->alipay_user_id,
- // ];
- $access_token = $response->access_token;
- // --- 6. (可选) 获取用户信息 ---
- if ($info) {
- // ... (获取用户信息的逻辑保持不变,因为它内部的判断可能是正确的) ...
- $userInfoRequest = new AlipayUserInfoShareRequest;
- $userInfoResult = $aop->execute($userInfoRequest, $access_token);
- $userInfoResponseNode = str_replace(".", "_", $userInfoRequest->getApiMethodName()) . "_response";
- $userInfoResultObj = json_decode($userInfoResult);
- Db::name('log')->insert(['data' => '支付宝UserInfo获取响应解析: ' . json_encode($userInfoResultObj, JSON_UNESCAPED_UNICODE)]); // 记录日志
- // !!! 这里判断 UserInfo 响应的逻辑通常是正确的,包含 code == '10000' !!!
- if (isset($userInfoResultObj->$userInfoResponseNode) && isset($userInfoResultObj->$userInfoResponseNode->code) && $userInfoResultObj->$userInfoResponseNode->code == '10000') {
- // 成功获取用户信息
- $userInfoResponse = $userInfoResultObj->$userInfoResponseNode;
- Db::name('log')->insert(['data' => '支付宝用户信息获取成功: ' . json_encode($userInfoResponse, JSON_UNESCAPED_UNICODE)]);
- return [
- 'user_id' => $userInfoResponse->user_id,
- 'nick_name' => $userInfoResponse->nick_name ?? null,
- 'avatar' => $userInfoResponse->avatar ?? null,
- // 其他字段...
- // 'gender' => $userInfoResponse->gender ?? null,
- // 'province' => $userInfoResponse->province ?? null,
- // 'city' => $userInfoResponse->city ?? null,
- ];
- } else {
- // 获取用户信息失败
- $errorMsg = 'Failed to get user info';
- $subMsg = '';
- // 优先从 UserInfo 对应的 ResponseNode 获取错误信息
- if (isset($userInfoResultObj->$userInfoResponseNode) && isset($userInfoResultObj->$userInfoResponseNode->sub_msg)) {
- $errorMsg .= ': ' . $userInfoResultObj->$userInfoResponseNode->sub_msg;
- $subMsg = $userInfoResultObj->$userInfoResponseNode->sub_msg;
- }
- // 否则尝试从 UserInfo 的 error_response 获取
- elseif (isset($userInfoResultObj->error_response) && isset($userInfoResultObj->error_response->sub_msg)) {
- $errorMsg .= ': ' . $userInfoResultObj->error_response->sub_msg;
- $subMsg = $userInfoResultObj->error_response->sub_msg;
- }
- Db::name('log')->insert(['data' => '支付宝用户信息获取失败(Token已成功): ' . $errorMsg . ' | Raw UserInfo: ' . $userInfoResult]);
- return []; // 仍然返回成功的 Token 和用户信息错误标记
- }
- } else {
- // 不需要获取用户信息,直接返回 Token 数据
- Db::name('log')->insert(['data' => '支付宝Token获取成功(无用户信息请求): ' . json_encode($response, JSON_UNESCAPED_UNICODE)]);
- return [];
- }
- } else {
- // 获取 Token 失败
- $errorMsg = 'Failed to exchange token';
- $subMsg = '';
- // 优先检查是否有 error_response
- if (isset($resultObj->error_response)) {
- $errorMsg .= ': ' . ($resultObj->error_response->sub_msg ?? 'Unknown error');
- $subMsg = $resultObj->error_response->sub_msg ?? '';
- }
- // 其次检查 responseNode 中是否有错误信息 (虽然不常见于 Token 接口)
- elseif (isset($resultObj->$responseNode) && isset($resultObj->$responseNode->sub_msg)) {
- $errorMsg .= ': ' . ($resultObj->$responseNode->sub_msg ?? 'Unknown error');
- $subMsg = $resultObj->$responseNode->sub_msg ?? '';
- }
- Db::name('log')->insert(['data' => '支付宝Token获取失败: ' . $errorMsg . ' | Raw Token: ' . $result]);
- return [];
- }
- } catch (\Exception $e) { // 捕获 SDK 或其他异常
- Db::name("log")->insert(['data' => 'Alipay Token/Info Error: '.$e->getFile() . ':' . $e->getLine() . '【' . $e->getMessage() . '】']); //日志记录
- return [];
- }
- }
- // 你可以在 Controller 的其他方法中调用这个函数
- public function handleAlipayCallback($authCode)
- {
- if (!$authCode) {
- return ['status' => 'error', 'message' => 'Auth code is missing'];
- }
- // 调用上面封装的方法,并请求获取用户信息
- $result = $this->getTokenByCodeWithCert($authCode, true); // 第二个参数为 true
- // 根据 $result 处理后续逻辑 (如用户登录注册,返回 token 给 APP 等)
- if ($result['code'] == 200) {
- // 成功处理
- // $alipay_user_id = $result['user_id'];
- // $nick_name = $result['user_info']['nick_name'] ?? 'Unknown';
- // $avatar = $result['user_info']['avatar'] ?? '';
- return ['status' => 'success', 'data' => $result];
- } else {
- // 处理失败
- return ['status' => 'error', 'message' => $result['msg']];
- }
- }
- /**
- * @param $id
- * @return Form
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- * @throws FormBuilderException
- * @author xaboy
- * @day 2020-05-07
- */
- public function changePassForm($id)
- {
- return Elm::createForm(Route::buildUrl('systemUserChangePass', compact('id'))->build(), [
- Elm::input('pass_word', '用户密码')->required()->value("")
- ])->setTitle('修改用户密码');
- }
- public function changePass($uid,$password)
- {
- $pass_word=$this->encodePassword($password);
- $data= Db::name("user")->where(["uid"=>$uid])->update(['pwd'=>$pass_word]);
- if($data){
- return $data;
- }else{
- return false;
- }
- }
- public function wechatGetTokenBycode()
- {
- }
- public function createUserNumber($uid){
- $t = "C";
- $number = '000000000';
- if($uid <= 10){
- $uid = $uid . 'X';
- }
- $strlen = mb_strlen($uid);//id长度
- $newNumber = $t.substr_replace($number,$uid,-$strlen);
- $newNumber = str_replace('4','R',$newNumber);
- Db::name('user') -> where(["uid"=>$uid])->update(['user_number'=>$newNumber]);
- }
- /**
- * @param int $uid 用户ID
- * @param string $score 积分
- * @param int $status 积分状态
- * @param string $mark 备注
- * @param string $has_qian 连续签到天数
- * @param string $today_signintime 签到时间
- * @param int $order_id 订单ID
- * @param int $pm 1-收入。2-支出
- * @param string $order_type
- * @throws DbException
- */
- public function sign_add($uid, $score, $status, $mark, $has_qian = '', $today_signintime = '', $order_id = 0, $pm = 1, $order_type = '',$type='',$settlement_time = '')
- {
- if(!in_array($type,[1,2])){
- // 其他情况都直接返回,因为目前只有365专区购买才可以获得
- return false;
- }
- $ins_data['uid'] = $uid;
- $ins_data['continuity_day'] = $has_qian;
- $ins_data['reward_socre'] = $score;
- // $ins_data['source_uid'] = $uid;
- $ins_data['signin_time'] = $today_signintime;
- $ins_data['addtime'] = time();
- $ins_data['status'] = $status;
- $ins_data['mark'] = $mark;
- $ins_data['source_type'] = $type;
- $ins_data['settlement_time'] = $settlement_time;// 结算时间 真正到了结算时间会结算
- $ins_data['order_id'] = $order_id;
- $ins_data['pm'] = $pm;
- $ins_data['order_type'] = $order_type;
- // $ins_data['surplus'] = 0;
- Db::name('user_sign_score')->insertGetId($ins_data);
- if($pm == 1 && $status == 1){
- Db::name('user')->where('uid',$uid)->inc('score', $score)->update();
- }
- if($pm == 2){
- Db::name('user')->where('uid', $uid)->dec('score', $score)->update();
- }
- }
- public function gold_add($uid,$gold,$mark,$pm=1){
- $ins['uid'] = $uid;
- $ins['gold'] = $gold;
- $ins['mark'] = $mark;
- $ins['time'] = time();
- $ins['pm'] = $pm;
- $id = Db::name('user_gold_log')->insertGetId($ins);
- if($pm == 1){
- Db::name('user_gold')->where('uid',$uid)->inc('now_gold', $gold)->inc('cumulative', $gold)->update();
- }else{
- Db::name('user_gold') -> where('uid',$uid) -> dec('now_gold', $gold)->update();
- }
- $surplus = Db::name('user_gold')->where('uid',$uid)->value('now_gold');
- Db::name('user_gold_log') -> where('id',$id) -> update(['surplus'=>$surplus]);
- }
- function get_level_list(){
- try {
- $tokenInfo = (request()->tokenInfo());
- if(isset($tokenInfo->jti[1]) && $tokenInfo->jti[1]=='admin') {
- $admin_id = request()->adminId();
- $roles_str = Db::name('system_admin')->where('admin_id', $admin_id)->value('roles');
- $phone_count = Db::name('system_role')->whereIn('role_id', $roles_str)->where("phone !=''")->count();
- if ($phone_count) {
- return true;
- }
- }
- }catch (Exception $e) {
- return false;
- }
- return false;
- // $phone_data=Db::name('system_role')->whereIn('role_id',$roles_str)->where("phone !=''")->group("phone")->column('phone');
- // if($phone_data){
- // $uid_data = Db::name('user')->whereIn('phone', $phone_data)->column('uid');
- // if($uid_data){
- // $uids=$this->level_list($uid_data,0);
- // }
- // }
- // }
- // return isset($uids)?$uids:[];
- }
- // function level_list($uid_data,$i){
- // $i++;
- // $uid = Db::name('user')->whereIn('level_id', $uid_data)->column('uid');
- // if($uid && $i<9){
- // $uid_data=array_merge($uid_data,$uid);
- // return $this->level_list($uid_data,$i);
- // }else{
- // return $uid_data;
- // }
- // }
- public function sign_yhc_add($uid,$mer_id,$score,$mark,$order_id=0,$pm=1,$use_uid=0){
- $ins_data['uid'] = $uid;
- $ins_data['mer_id'] = $mer_id;
- $ins_data['mark'] = $mark;
- $ins_data['order_id'] = $order_id;
- $ins_data['pm'] = $pm;
- $ins_data['reward_socre'] = $score;
- $ins_data['use_uid'] = $use_uid;
- try {
- Db::transaction(function () use ($ins_data,$pm,$mer_id,$score,$uid) {
- $id = Db::name('enterprise_user_score')->insertGetId($ins_data);
- if($pm == 2){
- Db::name('enterprise_user') -> where('uid',$uid)-> where('mer_id',$mer_id) -> dec('green_integral',$score)->update();
- }else if ($pm==1){
- Db::name('enterprise_user') -> where('uid',$uid)-> where('mer_id',$mer_id) -> inc('green_integral',$score)->update();
- }
- $green_integral=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('uid',$uid)->value('green_integral');
- if($green_integral<0){
- throw new \Exception('修改失败,用户红积分不足,请刷新后再试');
- }
- });
- }catch (\Exception $e){
- return false;
- }
- return true;
- }
- /**
- * 获取下级所有团队列表
- * @param $uid
- * @return int
- */
- public function getSpreadUidBreak($uid){
- $sql = "select getUserSpreadId($uid) as uids";
- $count = Db::query($sql);
- $count[0]['uids'] = trim($count[0]['uids'],'$,');
- $originalArray = explode(",",$count[0]['uids']);
- $resultArray = array_diff($originalArray, [$uid]);
- return $resultArray;
- }
- /**
- * 设置用户 身份
- * @param $uid
- * @param $identityId
- * @return int|mixed|null
- * @throws DbException
- */
- public function setUserIdentity($uid, $identityId = null)
- {
- if (empty($identityId)) {
- $identityId = $this->getUserIdentity($uid);
- }
- $userData = $this->dao->get($uid)->toArray();
- // 只升级 不降级
- if ($identityId < $userData['user_group']) {
- $identityId = $userData['user_group'];
- }
- $data = ['user_group' => $identityId];
- if (empty($userData['identity_up_time'] ?? null) && $userData['user_group'] == 1 && $identityId > 1) {
- $data['identity_up_time'] = date('Y-m-d H:i:s');
- }
- $this->dao->update($uid, $data);
- return $identityId;
- }
- /**
- * 获取用户 身份
- * @param $uid
- * @return int|mixed
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getUserIdentity($uid)
- {
- // 1、获取所有等级信息
- /** @var UserIdentityRepository $identityRepository */
- $identityRepository = app()->make(UserIdentityRepository::class);
- $identityList = $identityRepository->getIdentityList();
- // 2、获取身份需要的最深等级
- $lowerLevelNumList = array_column($identityList, 'lower_level_num');
- $lowerLevelNumMax = max($lowerLevelNumList);
- $lowerLevelNumMin = min($lowerLevelNumList);
- // 获取需要 递归最深的层数,比如 高级合伙人需要递归10层 普通用户需要递归一层
- $needLower = 0;
- // 0 代表要递归无限极 -1 代表一级也不查
- if($lowerLevelNumMin > 0) {
- $needLower = $lowerLevelNumMax;
- }
- // 最大等级限制
- $maxLvRestrict = 0;
- // 3、获取个人贡献值
- $userData = $this->dao->get($uid)->toArray();
- // 这一步骤是为了 确定用户升级时间,因为后边的团队贡献值,需要查询 用户 升级为业务员后 所产生的团队贡献值
- $determineResult = $this->determineUserUpgradeTime($uid);
- $userData['user_group'] = $determineResult['user_group'];
- $userData['identity_up_time'] = $determineResult['identity_up_time'];
- $startTime = $userData['identity_up_time'];
- $endTime = date('Y-m-d H:i:s');
- // 如果用户身份 为 用户 或者 升级成业务员的时间为空 则无法计算它的团队贡献值
- if ($userData['user_group'] == 1 || empty($startTime)) {
- $maxLvRestrict = 2;
- $needLower = -1;
- }
- // 4、获取下级用户 贡献值
- $userContributionSumMap = $this->getSubordinateContributeByUid($uid, $startTime, $endTime, $needLower);
- // 5、将用户等级由低到高
- usort($identityList, function ($a, $b) {
- return $a['user_group_id'] <=> $b['user_group_id'];
- });
- // 循环记录 如果贡献值 满足了初级合伙人身份 并记录该身份ID,继续下一阶段循环,下一阶段不满足 则该用户身份为初级合伙人
- $identityId = 0;
- foreach ($identityList as $item) {
- $lowerLevelNum = $item['lower_level_num']??0;
- $arriveNumOwn = $userData['contribute'];
- $arriveNumTeam = 0;
- $subordinateContribution = [];
- // 只有 业务员及以上才需要团队贡献值
- if ($item['user_group_id'] > 1) {
- foreach ($userContributionSumMap as $key => $value) {
- $subordinateContribution[$key] = 0;
- if ($lowerLevelNum != 0) {
- foreach ($value as $k => $v) {
- if ($k < $lowerLevelNum) {
- $subordinateContribution[$key] += $v;
- }
- }
- } else {
- $subordinateContribution[$key] = array_sum($value);
- }
- }
- if (!empty($subordinateContribution)) {
- // 大区业绩
- $dqYj = max($subordinateContribution);
- // 总业绩
- $zYj = array_sum($subordinateContribution);
- // 小区团体业绩
- $arriveNumTeam = bcsub($zYj, $dqYj, 2);
- }
- }
- // 从小向大循环,满足则去 下一等级继续验证,不满足 则 返回上次循环记录的值,并结束循环
- if ($item['arrive_num_own'] <= $arriveNumOwn && $item['arrive_num_team'] <= $arriveNumTeam) {
- $identityId = $item['user_group_id'];
- // 用户等级限制,本次获取身份 最大可获取什么身份,比如 用户没有 团队贡献值,他最高只能升到 2 级 即业务员
- if ($identityId == $maxLvRestrict) {
- break;
- }
- } else {
- break;
- }
- }
- if ($identityId < $userData['user_group']) {
- $identityId = $userData['user_group'];
- }
- return $identityId;
- }
- /**
- * 获取该会员的所有下级会员
- * @param array $uidList
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getUidContributeListByLevelIdList(array $uidList)
- {
- return Db::name("user")
- ->whereIn("level_id", $uidList)
- ->field("uid, contribute, level_id")
- ->select()
- ->toArray();
- }
- /**
- * 计算指定用户下属每一层级的总贡献值。
- *
- * @param array $initialUserIds 初始用户ID列表 (视为第0层)。
- * @param int $maxDepth 需要查询的最大深度(相对于初始列表)。
- * 0 表示查询所有层级直到末端。
- * 1 表示只计算第1层(直接下级)的总贡献。
- * N 表示计算到第 N 层(包含第N层)的总贡献。
- * @param int $is_old
- * @param null $startTime
- * @param null $endTime
- * @return array 返回一个数组,键是层级号(从1开始),值是该层级所有用户的贡献值总和。
- * 例如:[ 1 => 600, 2 => 1300 ]
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getContributionSumByLevel(array $initialUserIds, int $maxDepth = 0, $is_old = 0, $startTime = null, $endTime = null): array
- {
- $levelContributions = []; // 结果数组 [level => total_contribution]
- if (empty($initialUserIds)) {
- return $levelContributions;
- }
- $currentLevelIds = $initialUserIds; // 当前层级的用户ID (初始为第0层)
- $currentLevel = 0; // 当前层级号
- // 使用一个集合跟踪所有已处理过的下级用户ID,防止重复计算和循环
- $processedSubordinateIds = [];
- while (!empty($currentLevelIds)) {
- // 计算下一层级的编号
- $nextLevel = $currentLevel + 1;
- // 检查是否达到最大深度限制
- if ($maxDepth > 0 && $nextLevel > $maxDepth) {
- break; // 停止查询更深的层级
- }
- // 批量查询当前层级用户的直接下级
- // 使用 array_chunk 防止 WHERE IN 子句过长 (根据数据库限制调整 chunkSize)
- $chunkSize = 500;
- $subordinatesOfCurrentLevel = [];
- foreach(array_chunk($currentLevelIds, $chunkSize) as $chunk) {
- $subordinatesChunk = Db::name('user')
- ->field('uid') // 只需要下级的uid
- ->whereIn('level_id', $chunk) //level_id 在当前层级用户块中
- ->where('status', 1)
- ->select()
- ->toArray();
- $subordinatesOfCurrentLevel = array_merge($subordinatesOfCurrentLevel, $subordinatesChunk);
- }
- // 如果没有找到任何下级,结束循环
- if (empty($subordinatesOfCurrentLevel)) {
- break;
- }
- // 如果 传入 $startTime 不为空 证明当前在 确定身份的 用户已经是 业务员了
- if (!empty($startTime)) {
- $subordinatesOfCurrentLevelUidList = $this->getUserContributeByUidList(array_column($subordinatesOfCurrentLevel, 'uid'), $startTime, $endTime);
- // // 用户有贡献值记录,我们要根据 用户的身份 从普通消费者 升级 成业务员 的时间来 查询时间范围内产生的贡献值
- // $userSignGongxianList = Db::name('user_sign_gongxian')
- // ->whereIn('uid', array_keys($subordinatesOfCurrentLevelUidList))
- // ->where('addtime', '>=', strtotime($startTime)) // `addtime` int(10) NOT NULL COMMENT '添加时间'
- // ->where('status', 1) // 贡献值状态1-有效 0-失效 -1待确认
- // ->whereNotNull('settlement_time') // `settlement_time` datetime DEFAULT NULL COMMENT '结算时间',
- // ->field('uid, number, type') // 只需要下级的uid和贡献值
- // ->select()
- // ->toArray();
- // foreach ($userSignGongxianList as $value) {
- // if($value['type'] == 1) {
- // $subordinatesOfCurrentLevelUidList[$value['uid']] += $value['number'];
- // } else {
- // $subordinatesOfCurrentLevelUidList[$value['uid']] -= $value['number'];
- // }
- // }
- //
- // if ($is_old == 1) {
- // // 如果是老用户,除了通过贡献值记录表 还要计算 老订单 产生的贡献值
- // $oldUserOfGoodsList = Db::name('old_user_of_goods')
- // ->whereIn('user_id', array_keys($subordinatesOfCurrentLevelUidList))
- // ->where('create_time', '>=', strtotime($startTime)) // `addtime` int(10) NOT NULL COMMENT '添加时间'
- // ->where('status', 1) // '是否完成 0, 未完成 1 已完成',
- // ->field('user_id, money, status, create_time') // 只需要下级的uid和贡献值
- // ->select()
- // ->toArray();
- //
- // foreach ($oldUserOfGoodsList as $storeProductData) {
- // if ($storeProductData['money'] == 1180) {
- // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 700;
- // } else if ($storeProductData['money'] == 10620) {
- // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 6300;
- // } else if ($storeProductData['money'] == 11800) {
- // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 7000;
- // } else if ($storeProductData['money'] == 9440) {
- // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 5600;
- // } else if ($storeProductData['money'] == 2360) {
- // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 1400;
- // } else {
- // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += bcmul($storeProductData['money'], 0.7, 2);
- // }
- // }
- // }
- } else {
- // 如果传入的 $identity_up_time 为空,说明该用户只是一个普通用户(消费者),没有团队业绩
- break;
- }
- $nextLevelTotalContribution = 0;
- $nextLevelIds = []; // 存储下一轮需要查询的用户ID
- // 遍历找到的所有下级
- foreach ($subordinatesOfCurrentLevel as $subordinate) {
- $subordinateId = $subordinate['uid'];
- $subordinateContribution = $subordinatesOfCurrentLevelUidList[$subordinate['uid']] ?? 0; // 安全获取,默认为0
- // 累加下一层级的总贡献值
- // 注意:这里简单累加,如果一个下级同时被当前层多个用户推荐,其贡献会被计算多次
- // 如果要求每个下级只贡献一次(即使有多个上级),需要调整逻辑,
- // 例如在累加前检查 $processedSubordinateIds
- // --- 修改点:确保每个下级贡献只被计算一次 ---
- // if (!isset($processedSubordinateIds[$subordinateId])) { // 如果这个下级还没被处理过
- $nextLevelTotalContribution += (float)$subordinateContribution;
- // }
- // 注释掉上面的检查,因为用户描述似乎是按层级直接累加,不管这个下级是否被上层处理过。
- // 如果A1和A2都属于第1层,他们各自的下级B1和B2都属于第2层,B1和B2的贡献值直接加到第2层的总和里。
- // 如果需要严格按“人”计算,即使一个人出现在多层或被多人推荐也只算一次,则需要解开注释并调整
- // 收集下一轮需要查询的用户ID,同样需要防止重复处理
- if (!isset($processedSubordinateIds[$subordinateId])) {
- $nextLevelIds[] = $subordinateId;
- // 标记这个下级ID已处理过,避免在更深层级中再次将其加入查询队列
- $processedSubordinateIds[$subordinateId] = true;
- }
- }
- // 存储下一层级的总贡献值 (只有当贡献值大于0或你想记录空层级时)
- // 根据例子,我们只记录有贡献的层级,或者至少有用户的层级
- if (!empty($subordinatesOfCurrentLevel)) { // 只要找到了下级就记录该层
- $levelContributions[$nextLevel] = $nextLevelTotalContribution;
- }
- // 准备下一轮迭代
- $currentLevelIds = array_unique($nextLevelIds); // 去重下一层的用户ID
- $currentLevel = $nextLevel; // 更新当前层级
- }
- return $levelContributions;
- }
- /**
- * 获取用户 历史的 个人贡献值记录
- * @param $uidList
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getUserContributeTimeMapByUidList($uidList) {
- $userContributeTimeMap = [];
- $userSignGongxianList = Db::name('user_sign_gongxian')
- ->whereIn('uid', $uidList)
- ->where('status', 1) // 贡献值状态1-有效 0-失效 -1待确认
- ->whereNotNull('settlement_time') // `settlement_time` datetime DEFAULT NULL COMMENT '结算时间',
- ->field('uid, number, type, mark, settlement_time') // 只需要下级的uid和贡献值
- ->select()
- ->toArray();
- foreach ($userSignGongxianList as $value) {
- // 贡献表中 包含多种类型的 贡献值记录,比如 用户消费商家获得赠送贡献值 , 推广获得的贡献值(直推),这些都不能算是 用户的 直接贡献值
- // 只有 用户取消费 比如:购买 ** 商品、扫码消费获得赠送贡献值 等 才算做个人贡献值
- // || strpos($value['mark'], "扫码") !== false
- if (strpos($value['mark'], "购买") !== false || strpos($value['mark'], "会员专区消费商品赠送贡献值") !== false) {
- if($value['type'] == 1) {
- $type = 1;
- } else {
- $type = 2;
- }
- $userContributeTimeMap[$value['uid']][] = [
- 'type' => $type,
- 'contribute' => $value['number'],
- 'settlementTime' => $value['settlement_time']
- ];
- }
- }
- // // 老订单 产生的贡献值 并未在 贡献记录表中
- // $oldUserOfGoodsList = Db::name('old_user_of_goods')
- // ->where('status', 1) // '是否完成 0, 未完成 1 已完成',
- // ->whereIn('user_id', $uidList)
- // ->field('user_id, money, status, create_time') // 只需要下级的uid和贡献值
- // ->select()
- // ->toArray();
- // // 定义一个映射数组,用于存储不同 money 对应的 contribute 值
- // $contributeMapping = [
- // 1180 => 700,
- // 10620 => 6300,
- // 11800 => 7000,
- // 9440 => 5600,
- // 2360 => 1400,
- // ];
- // // 遍历每个 $storeProductData
- // foreach ($oldUserOfGoodsList as $storeProductData) {
- // // 获取 money 的值
- // $money = $storeProductData['money'];
- // // 检查 money 是否在映射中
- // if (isset($contributeMapping[$money])) {
- // // 如果存在,则使用映射的值
- // $contribute = $contributeMapping[$money];
- // } else {
- // // 否则按默认规则计算
- // $contribute = bcmul($money, 0.7, 2);
- // }
- // // 将数据添加到 $userContributeTimeList
- // $userContributeTimeMap[$storeProductData['user_id']][] = [
- // 'type' => 1,
- // 'contribute' => $contribute,
- // 'settlementTime' => date('Y-m-d H:i:s', $storeProductData['create_time'])
- // ];
- // }
- foreach ($userContributeTimeMap as $key => &$subArray) {
- usort($subArray, function ($a, $b) {
- return strtotime($a['settlementTime']) - strtotime($b['settlementTime']);
- });
- }
- return $userContributeTimeMap;
- }
- /**
- * 获取用户升级成业务员的时间
- * @param $uid
- * @return mixed|string
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function determineUserUpgradeTime($uid) {
- $userData = $this->dao->get($uid)->toArray();
- if (empty($userData['identity_up_time'])) {
- $upArriveNumOwn = 0;
- $yeWuYuanId = 0;
- // 1、获取所有等级信息
- /** @var UserIdentityRepository $identityRepository */
- $identityRepository = app()->make(UserIdentityRepository::class);
- $identityList = $identityRepository->getIdentityList();
- foreach ($identityList as $value) {
- if ($value['user_group_name'] == '业务员') {
- $upArriveNumOwn = $value['arrive_num_own'];
- $yeWuYuanId = $value['user_group_id'];
- break;
- }
- }
- // 2、获取用户贡献值 日志记录 对应时间
- $userContributeTimeMap = $this->getUserContributeTimeMapByUidList([$uid]);
- $myIdentityUpTime = '';
- if (!empty($userContributeTimeMap[$uid])) {
- $myArriveNumOwn = 0;
- foreach ($userContributeTimeMap[$uid] as $value) {
- if ($value['type'] == 1) {
- $myArriveNumOwn += $value['contribute'];
- } else {
- $myArriveNumOwn -= $value['contribute'];
- }
- if ($myArriveNumOwn >= $upArriveNumOwn) {
- $myIdentityUpTime = $value['settlementTime'];
- break;
- }
- }
- }
- if (!empty($myIdentityUpTime)) {
- $data['identity_up_time'] = $userData['identity_up_time'] = $myIdentityUpTime;
- // 只升级 不降级
- if ($userData['user_group'] == 1) {
- $userData['user_group'] = $yeWuYuanId;
- }
- $this->dao->update($uid, $data);
- } else {
- if ($userData['is_old'] == 1) {
- $data['identity_up_time'] = $userData['identity_up_time'] = $userData['create_time'];
- $this->dao->update($uid, $data);
- }
- }
- }
- return [
- 'user_group' => $userData['user_group'],
- 'identity_up_time' => $userData['identity_up_time']
- ];
- }
- /**
- * 获取用户列表中 每个人 的 个人贡献值
- * @param array $uidList
- * @param null $startTime
- * @param null $endTime
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getUserContributeByUidList($uidList = [], $startTime = null, $endTime = null)
- {
- $subordinatesOfCurrentLevelUidList = [];
- foreach ($uidList as $uid) {
- $subordinatesOfCurrentLevelUidList[$uid] = 0;
- }
- $userContributeTimeMap = $this->getUserContributeTimeMapByUidList($uidList);
- if (!empty($userContributeTimeMap)) {
- foreach ($userContributeTimeMap as $uid => $contributeInfoList) {
- foreach ($contributeInfoList as $value) {
- // 跳过时间范围外的 贡献值
- if (!empty($startTime) && strtotime($value['settlementTime']) < strtotime($startTime)) {
- continue;
- }
- if (!empty($endTime) && strtotime($value['settlementTime']) > strtotime($endTime)) {
- break;
- }
- if ($value['type'] == 1) {
- $subordinatesOfCurrentLevelUidList[$uid] += $value['contribute'];
- } else {
- $subordinatesOfCurrentLevelUidList[$uid] -= $value['contribute'];
- }
- }
- }
- }
- return $subordinatesOfCurrentLevelUidList;
- }
- /**
- * 根据时间和递归层级 获取部门下 每一层级的 贡献值
- * 假设 老大的 下级是 张三和李四, 董事(最高级身份)需要循环最深的等级是 3 级 得出来的结果↓ 这样是为了计算大小部门
- * $userContributionSumMap[直属下级(部门)张三] =>[0 => 张三个人贡献值, 1 => 张三所有下级用户的个人贡献值, 2 => 张三所有下级用户的下级用户贡献值]
- * $userContributionSumMap[直属下级(部门)李四] =>[0 => 李四个人贡献值, 1 => 李四所有下级用户的个人贡献值, 2 => 李四所有下级用户的下级用户贡献值]
- * @param $uid
- * @param null $startTime
- * @param null $endTime
- * @param int $depth
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getSubordinateContributeByUid($uid, $startTime, $endTime, $depth = 10)
- {
- // 4、获取下级用户 贡献值
- $userContributionSumMap = [];
- if ($depth >= 0 && !empty($startTime)) {
- // 获取用户的直属下级
- $uidContributeList = $this->getUidContributeListByLevelIdList([$uid]);
- $uidContributeUidList = array_column($uidContributeList, 'uid');
- $subordinatesOfCurrentLevelUidList = $this->getUserContributeByUidList($uidContributeUidList, $startTime, $endTime);
- foreach ($uidContributeList as $uidContribute) {
- $goOnDepth = $depth;
- // 获取用户规定时间内 所产生的贡献值 第一级
- $userContributionSumMap[$uidContribute['uid']]['0'] = $subordinatesOfCurrentLevelUidList[$uidContribute['uid']] ?? 0;
- if ($depth == 1) {
- continue;
- } else if ($depth > 1){
- $goOnDepth = $depth - 1;
- }
- // 获取每个下级(部门)的个人贡献值 $goOnDepth = 0 时表示无限递归
- $contributionSumByLevel = $this->getContributionSumByLevel(
- [$uidContribute['uid']],
- $goOnDepth,
- 0,
- $startTime,
- $endTime
- );
- $userContributionSumMap[$uidContribute['uid']] = array_merge($userContributionSumMap[$uidContribute['uid']], $contributionSumByLevel);
- if (!empty($userContributionSumMap[$uidContribute['uid']])) {
- ksort($userContributionSumMap[$uidContribute['uid']]);
- }
- // 假设 老大的 下级是 张三和李四, 董事(最高级身份)需要循环最深的等级是 3 级 得出来的结果↓ 这样是为了计算大小部门
- // $userContributionSumMap[直属下级(部门)张三] =>[0 => 张三个人贡献值, 1 => 张三所有下级用户的个人贡献值, 2 => 张三所有下级用户的下级用户贡献值]
- // $userContributionSumMap[直属下级(部门)李四] =>[0 => 李四个人贡献值, 1 => 李四所有下级用户的个人贡献值, 2 => 李四所有下级用户的下级用户贡献值]
- }
- }
- return $userContributionSumMap;
- }
- /**
- * 获取用户 团队贡献值信息
- * @param $uid
- * @param int $depth // 最深递归层级
- * @param array $betweenTime // 贡献值获取范围
- * @return array
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function getUserContributeInfoByDepth($uid, $depth = 10, $betweenTime = [])
- {
- // 3、获取个人贡献值
- $userData = $this->dao->get($uid)->toArray();
- // 这一步骤是为了 确定用户升级时间,因为后边的团队贡献值,需要查询 用户 升级为业务员后 所产生的团队贡献值
- $determineResult = $this->determineUserUpgradeTime($uid);
- $userData['user_group'] = $determineResult['user_group'];
- $userData['identity_up_time'] = $determineResult['identity_up_time']; // 获得的值 有可能是时间 有可能是 null
- $startTime = $userData['identity_up_time'];
- $endTime = date('Y-m-d H:i:s');
- if (!empty($betweenTime) && !empty($betweenTime['startTime']) && !empty($betweenTime['endTime'])) {
- if(empty($startTime) || strtotime($startTime) < strtotime($betweenTime['startTime'])) {
- $startTime = $betweenTime['startTime'];
- }
- if(strtotime($betweenTime['endTime']) < strtotime($endTime)) {
- $endTime = $betweenTime['endTime'];
- }
- }
- // 如果用户身份是 用户 则
- /**
- * 如果用户身份是 用户,则不计算团队贡献值,因计算团队贡献值 需要升级成业务员后 再进行进行统计
- * 如用户也统计团队贡献值可能会导致: 用户进入系统后,不进行消费,团队贡献值确增长迅速,等某时刻 他只要 进行消费,身份就会快速跃迁,不公平
- * (1)达标贡献值=自己消费产生的贡献值
- * (2)团队达标贡献值= 不计算团队
- */
- if ($userData['user_group'] == 1) {
- $depth = -1;
- }
- // 4、获取下级用户 贡献值
- $userContributionSumMap = $this->getSubordinateContributeByUid($uid, $startTime, $endTime, $depth);
- $subordinateContribution = [];
- foreach ($userContributionSumMap as $key => $value) {
- $subordinateContribution[$key] = array_sum($value);
- }
- $dqYj = 0;
- $arriveNumTeam = 0;
- if (!empty($subordinateContribution)) {
- // 大区业绩
- $dqYj = max($subordinateContribution);
- // 总业绩
- $zYj = array_sum($subordinateContribution);
- // 小区团体业绩
- $arriveNumTeam = bcsub($zYj, $dqYj, 2);
- }
- return [
- 'arriveNumTeam' => $arriveNumTeam, // 小部门贡献值和
- 'contribute' => $userData['contribute'], // 个人贡献值
- 'perContribute' => $userData['per_contribute'], // 直推贡献值
- 'largeContribute' => $dqYj, // 大部门贡献值
- 'subordinate' => $subordinateContribution // 各部门贡献值和
- ];
- }
- public function stockCreateForm()
- {
- $data = Db::name('user')->where(['status' => 1,'is_del' => 0])->field('uid,nickname')->select()->toArray();
- return Elm::createForm(Route::buildUrl('systemUserStockCreate')->build(), [
- Elm::select('user_id', '用户')->options(function () use ($data) {
- foreach ($data as $label) {
- $options[] = ['label' => $label['nickname'],'value' => $label['uid']];
- }
- return $options;
- })->filterable(true),
- Elm::number('pack','份数')->required()
- ])->setTitle('添加股权分红');
- }
- public function stockUpdateForm($id)
- {
- $stock = Db::name('old_user_stock')->where('id',$id)->field('user_id,pack')->find();
- $user = Db::name('user')->where('uid',$stock['user_id'])->field('uid,nickname')->find();
- return Elm::createForm(Route::buildUrl('systemUserStockUpdate',compact('id'))->build(), [
- Elm::input('user_id','用户',$user['nickname'])->disabled(true),
- Elm::number('pack','份数',$stock['pack'])->required()
- ])->setTitle('编辑');
- }
- /**
- * 添加用户操作记录
- * @param $uid
- * @param $model
- * @param $type
- * @param $mark
- * @return void
- */
- public function createUserOperatingRecord($uid, $model, $type, $mark)
- {
- $exists = Db::name('user_operating_record')
- ->where('uid', $uid)
- ->value('id');
- if ($exists) {
- return;
- }
- Db::name('user_operating_record')->insert([
- 'uid' => $uid,
- 'operation_model' => $model,
- 'operation_type' => $type,
- 'mark' => $mark,
- 'operation_time' => date('Y-m-d H:i:s')
- ]);
- }
- /**
- * 保存用户搜索商品关键字
- * @param $uid
- * @param $keyword
- * @param $type
- * @return void
- */
- public function sproductkeywordHistory($uid, $keyword, $type){
- Db::name('third_history')->insert([
- 'uid' => $uid,
- 'keyword' => $keyword,
- 'type' => $type,
- ]);
- }
- /**
- * @param int $uid
- * @return UserEntity
- */
- public function getUserEntityByUid(int $uid): UserEntity
- {
- $entityList = $this->getUserEntityListByUidList([$uid]);
- $entity = array_shift($entityList);
- if ($entity instanceof UserEntity) {
- return $entity;
- } else {
- /** @var UserEntity */
- return UserEntity::newInstance();
- }
- }
- /**
- * 获取用户实体集合 根据 uid集合
- * @param array $uidList
- * @return UserEntity[]
- */
- public function getUserEntityListByUidList(array $uidList): array
- {
- return $this->dao->getUserEntityListByUidList($uidList);
- }
- /**
- * 获取用户实体集合 根据 uid集合
- * @param array $uidList
- * @return UserEntity[]
- */
- public function getUserEntityMapByUidList(array $uidList): array
- {
- $userEntityList = $this->getUserEntityListByUidList($uidList);
- /** @var UserEntity[] $userEntityMapByUid */
- $userEntityMapByUid = array_column($userEntityList, null, 'uid');
- return $userEntityMapByUid;
- }
- /**
- * 更新用户积分 并 写入积分变动记录
- * @param int $uid
- * @param int $type
- * @param float $score
- * @param string $mark
- * @param string $orderType
- * @param string $orderId
- * @return float
- */
- public function updateUserScore(int $uid, int $type, float $score, string $mark = '', string $orderType = '', string $orderId = ''): float
- {
- $userEntity = $this->getUserEntityByUid($uid);
- if (empty($userEntity->getUid())) {
- throw new ValidateException('未查询到用户信息');
- }
- if ($type == UserSignScoreEnum::PM['Expend']['code']) {
- $surplus = bcsub($userEntity->getScore(), $score, 2);
- if ($surplus < 0.00) {
- throw new ValidateException('用户积分不足');
- }
- } else {
- $surplus = bcadd($userEntity->getScore(), $score, 2);
- }
- try {
- $this->dao->update($uid, ['score' => $surplus]);
- /** @var UserSignScoreEntity $userSignScoreEntity */
- $userSignScoreEntity = UserSignScoreEntity::newInstance();
- $userSignScoreEntity->setUid($uid)
- ->setPm($type)
- ->setRewardSocre($score)
- ->setAddtime(time())
- ->setStatus(UserSignScoreEnum::STATUS['Valid']['code'])
- ->setOrderType($orderType)
- ->setOrderId($orderId)
- ->setMark($mark)
- ->setSurplus($surplus);
- /** @var UserSignScoreRepository $userSignScoreRepository */
- $userSignScoreRepository = app()->make(UserSignScoreRepository::class);
- $userSignScoreRepository->create($userSignScoreEntity->toUnderlineArray());
- } catch (DbException $e) {
- throw new ValidateException('更新积分失败');
- }
- return (float)$surplus;
- }
- /**
- * 更新用户Vr 并 写入Vr变动记录
- * @param int $uid
- * @param int $type
- * @param float $vr
- * @param string $mark
- * @param string $orderType
- * @param string $orderId
- * @return float
- */
- public function updateUserVr(int $uid, int $type, float $vr, string $mark = '', string $orderType = '', string $orderId = ''): float
- {
- $userEntity = $this->getUserEntityByUid($uid);
- if (empty($userEntity->getUid())) {
- throw new ValidateException('未查询到用户信息');
- }
- if ($type == UserSignVrEnum::TYPE['Consume']['code']) {
- $surplus = bcsub($userEntity->getVr(), $vr, 2);
- if ($surplus < 0.00) {
- throw new ValidateException('用户VR不足');
- }
- } else {
- $surplus = bcadd($userEntity->getVr(), $vr, 2);
- }
- try {
- $this->dao->update($uid, ['vr' => $surplus]);
- /** @var UserSignVrEntity $userSignVrEntity */
- $userSignVrEntity = UserSignVrEntity::newInstance();
- $userSignVrEntity->setUid($uid)
- ->setType($type)
- ->setNumber($vr)
- ->setAddtime(time())
- ->setOrderType($orderType)
- ->setOrderId($orderId)
- ->setMark($mark)
- ->setSurplus($surplus);
- /** @var UserSignVrRepository $userSignVrRepository */
- $userSignVrRepository = app()->make(UserSignVrRepository::class);
- $userSignVrRepository->create($userSignVrEntity->toUnderlineArray());
- } catch (DbException $e) {
- throw new ValidateException('更新VR失败');
- }
- return (float)$surplus;
- }
- /**
- * 更新用户京豆 并 写入 京豆变动记录
- * @param int $uid
- * @param int $type
- * @param float $jingdou
- * @param string $mark
- * @param string $orderType
- * @param string $orderId
- * @param int $merId
- * @return float
- */
- public function updateUserJingdou(int $uid, int $type, float $jingdou, string $mark = '', string $orderType = '', string $orderId = '', int $merId = 0): float
- {
- $userEntity = $this->getUserEntityByUid($uid);
- if (empty($userEntity->getUid())) {
- throw new ValidateException('未查询到用户信息');
- }
- if ($type == UserSignJingdouEnum::TYPE['Consume']['code']) {
- $surplus = bcsub($userEntity->getJingdou(), $jingdou, 2);
- if ($surplus < 0.00) {
- throw new ValidateException('用户京豆不足');
- }
- } else {
- $surplus = bcadd($userEntity->getJingdou(), $jingdou, 2);
- }
- try {
- $this->dao->update($uid, ['jingdou' => $surplus]);
- /** @var UserSignJingdouEntity $userSignJingdouEntity */
- $userSignJingdouEntity = UserSignJingdouEntity::newInstance();
- $userSignJingdouEntity->setUid($uid)
- ->setType($type)
- ->setStatus(UserSignJingdouEnum::STATUS['Valid']['code'])
- ->setNumber($jingdou)
- ->setAddtime(time())
- ->setOrderType($orderType)
- ->setOrderId($orderId)
- ->setMark($mark)
- ->setSurplus($surplus);
- /** @var UserSignJingdouRepository $userSignJingdouRepository */
- $userSignJingdouRepository = app()->make(UserSignJingdouRepository::class);
- $userSignJingdouRepository->create($userSignJingdouEntity->toUnderlineArray());
- } catch (DbException $e) {
- throw new ValidateException('更新京豆失败');
- }
- return (float)$surplus;
- }
- /**
- * 更新用户复购金 并 写入 复购金变动记录
- * @param int $uid
- * @param int $type
- * @param float $fugou
- * @param string $mark
- * @param string $orderType
- * @param string $orderId
- * @return float
- */
- public function updateUserFugou(int $uid, int $type, float $fugou, string $mark = '', string $orderType = '', string $orderId = ''): float
- {
- $userEntity = $this->getUserEntityByUid($uid);
- if (empty($userEntity->getUid())) {
- throw new ValidateException('未查询到用户信息');
- }
- if ($type == UserSignFugouEnum::TYPE['Consume']['code']) {
- $surplus = bcsub($userEntity->getFugou(), $fugou, 2);
- if ($surplus < 0.00) {
- throw new ValidateException('用户复购金不足');
- }
- } else {
- $surplus = bcadd($userEntity->getFugou(), $fugou, 2);
- }
- try {
- $this->dao->update($uid, ['fugou' => $surplus]);
- /** @var UserSignFugouEntity $userSignFugouEntity */
- $userSignFugouEntity = UserSignFugouEntity::newInstance();
- $userSignFugouEntity->setUid($uid)
- ->setType($type)
- ->setStatus(UserSignFugouEnum::STATUS['Valid']['code'])
- ->setNumber($fugou)
- ->setAddtime(time())
- ->setOrderType($orderType)
- ->setOrderId($orderId)
- ->setMark($mark)
- ->setSurplus($surplus);
- /** @var UserSignFugouRepository $userSignFugouRepository */
- $userSignFugouRepository = app()->make(UserSignFugouRepository::class);
- $userSignFugouRepository->create($userSignFugouEntity->toUnderlineArray());
- } catch (DbException $e) {
- throw new ValidateException('更新京豆失败');
- }
- return (float)$surplus;
- }
- /**
- * 更新用户复购金 并 写入 复购金变动记录
- * @param int $uid
- * @param int $recordId
- * @return float
- */
- public function updateUserBrokeragePriceByRecordId(int $uid, int $recordId): float
- {
- $userEntity = $this->getUserEntityByUid($uid);
- if (empty($userEntity->getUid())) {
- throw new ValidateException('未查询到用户信息');
- }
- /** @var UserBillRepository $userBillRepository */
- $userBillRepository = app()->make(UserBillRepository::class);
- $userBillEntity = $userBillRepository->getUserBillEntityByBillId($recordId);
- if (empty($userBillEntity->getBillId())) {
- throw new ValidateException('未查询到佣金记录信息');
- }
- if ($userBillEntity->getCommissionType() != UserBillEnum::COMMISSION_TYPE['DIRECT_REFERRAL']['code'] && $userBillEntity->getCommissionType() != UserBillEnum::COMMISSION_TYPE['SHARE_EARNINGS']['code']) {
- throw new ValidateException('该记录信息非佣金记录');
- }
- if ($userBillEntity->getStatus() != UserBillEnum::STATUS['PENDING']['code']) {
- throw new ValidateException('该记录信息非待分配状态');
- }
- if ($userBillEntity->getPm() == UserBillEnum::PM['EXPEND']['code']) {
- $surplus = bcsub($userEntity->getBrokeragePrice(), $userBillEntity->getNumber(), 2);
- if ($surplus < 0.00) {
- throw new ValidateException('用户佣金不足');
- }
- } else {
- $surplus = bcadd($userEntity->getBrokeragePrice(), $userBillEntity->getNumber(), 2);
- }
- try {
- $this->dao->update($uid, ['brokerage_price' => $surplus]);
- // 注意 单一
- // $userBillRepository->updateStatusByBillId($userBillEntity->getBillId(), UserBillEnum::STATUS['VALID']['code']);
- } catch (DbException $e) {
- throw new ValidateException('更新京豆失败');
- }
- return (float)$surplus;
- }
- /**
- * 批量更新
- * @param $dataList
- * @return array
- */
- public function batchUpdateUserDataByDataList($dataList): array
- {
- return $this->dao->saveAll($dataList);
- }
- }
|