UserRepository.php 196 KB

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