UserRepository.php 178 KB

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