UserRepository.php 193 KB

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