UserRepository.php 217 KB

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