UserRepository.php 217 KB

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