UserRepository.php 200 KB

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