UserRepository.php 213 KB

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