UserRepository.php 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227
  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. public function changeProForm_yhc($id,$type=0)
  749. {
  750. if($type===1){
  751. return Elm::createForm(Route::buildUrl('systemUserChangePro', compact('id'))->build(), [
  752. Elm::input('spread_account', '业绩归属人账号')->required()->placeholder("请填写业绩归属人手机号")->info('修改业绩归属人后,用户业绩归属至所填写账号下,但邀请关系及其他邀请相关的奖励不变!'),
  753. Elm::hidden('type', '1')
  754. ])->setTitle('修改业绩归属人');
  755. }
  756. return Elm::createForm(Route::buildUrl('systemUserChangePro', compact('id'))->build(), [
  757. Elm::input('spread_account', '推荐人')->required()->placeholder("请填写推荐人手机号")
  758. ])->setTitle('修改用户推荐人');
  759. }
  760. /**
  761. * @param $id
  762. * @param $adminId
  763. * @param $type
  764. * @param $nowMoney
  765. * @throws DataNotFoundException
  766. * @throws DbException
  767. * @throws ModelNotFoundException
  768. * @author xaboy
  769. * @day 2020-05-07
  770. */
  771. public function changeNowMoney($id, $adminId, $type, $nowMoney)
  772. {
  773. $user = $this->dao->get($id);
  774. Db::transaction(function () use ($id, $adminId, $user, $type, $nowMoney) {
  775. $balance = $type == 1 ? bcadd($user->now_money, $nowMoney, 2) : bcsub($user->now_money, $nowMoney, 2);
  776. $user->save(['now_money' => $balance]);
  777. /** @var UserBillRepository $make */
  778. $make = app()->make(UserBillRepository::class);
  779. if ($type == 1) {
  780. $make->incBill($id, 'now_money', 'sys_inc_money', [
  781. 'link_id' => $adminId,
  782. 'status' => 1,
  783. 'title' => '系统增加余额',
  784. 'number' => $nowMoney,
  785. 'mark' => '系统增加了' . floatval($nowMoney) . '余额',
  786. 'balance' => $balance
  787. ]);
  788. } else {
  789. $make->decBill($id, 'now_money', 'sys_dec_money', [
  790. 'link_id' => $adminId,
  791. 'status' => 1,
  792. 'title' => '系统减少余额',
  793. 'number' => $nowMoney,
  794. 'mark' => '系统减少了' . floatval($nowMoney) . '余额',
  795. 'balance' => $balance
  796. ]);
  797. }
  798. });
  799. }
  800. /**
  801. * @param $password
  802. * @return false|string|null
  803. * @author xaboy
  804. * @day 2020/6/22
  805. */
  806. public function encodePassword($password)
  807. {
  808. return password_hash($password, PASSWORD_BCRYPT);
  809. }
  810. /**
  811. * @param WechatUser $wechatUser
  812. * @return BaseDao|array|Model|null
  813. * @throws DataNotFoundException
  814. * @throws DbException
  815. * @throws ModelNotFoundException
  816. * @author xaboy
  817. * @day 2020-04-28
  818. */
  819. public function syncWechatUser(WechatUser $wechatUser, $userType = 'wechat')
  820. {
  821. $user = $this->dao->wechatUserIdBytUser($wechatUser->wechat_user_id);
  822. $request = request();
  823. if ($user) {
  824. $user->save([
  825. 'nickname' => $wechatUser['nickname'] ?: '',
  826. 'avatar' => $wechatUser['headimgurl'] ?: '',
  827. 'sex' => $wechatUser['sex'] ?: 0,
  828. 'last_time' => date('Y-m-d H:i:s'),
  829. 'last_ip' => $request->ip(),
  830. ]);
  831. }
  832. // else
  833. // $user = $this->create($userType, [
  834. // 'account' => 'wx' . $wechatUser->wechat_user_id . time(),
  835. // 'wechat_user_id' => $wechatUser->wechat_user_id,
  836. // 'pwd' => $this->encodePassword(123456),
  837. // 'nickname' => $wechatUser['nickname'] ?: '',
  838. // 'avatar' => $wechatUser['headimgurl'] ?: '',
  839. // 'sex' => $wechatUser['sex'] ?: 0,
  840. // 'spread_uid' => 0,
  841. // 'is_promoter' => 0,
  842. // 'last_time' => date('Y-m-d H:i:s'),
  843. // 'last_ip' => $request->ip()
  844. // ]);
  845. return $user;
  846. }
  847. /**
  848. * @param string $type
  849. * @param array $userInfo
  850. * @param int $url 推广员的ID
  851. * @return BaseDao|Model
  852. * @author xaboy
  853. * @day 2020-04-28
  854. */
  855. public function create(string $type, array $userInfo, $url=0,$spread_uid=null)
  856. {
  857. $userInfo['user_type'] = $type;
  858. Db::startTrans();
  859. try {
  860. $user = $this->dao->create($userInfo); //创建用户
  861. $this -> insterUser($user->uid, $spread_uid);
  862. //唯品会pid
  863. // $vip = app()->make(Vip::class);
  864. // $vip->create_pid($user->uid);
  865. // //拼多多pid
  866. // $taoke = app()->make(TaoKe::class);
  867. // $taoke->generateAd($user->uid);
  868. // //京东pid(改成京京推推就)
  869. // $jd = app()->make(Jd::class);
  870. // $jd->create_pid($user->uid);
  871. //
  872. // Queue::push(SendNewPeopleCouponJob::class, $user->uid);
  873. //赠送积分 注册送10积分
  874. // $this->sign_add($user['uid'], 10,1,'注册送10积分','','');
  875. Db::commit();
  876. return $user;
  877. } catch (\Exception $e) {
  878. Log::info($userInfo);
  879. Db::rollback();
  880. log::info("注册失败".$e->getFile().':'.$e->getLine().'【'.$e->getMessage().'】');
  881. throw new AuthException('注册失败');
  882. }
  883. }
  884. public function getUserLevelId($spread_uid){
  885. if (empty($spread_uid)){
  886. return false;
  887. }
  888. $sql = "select getUserLevelId($spread_uid) as count";
  889. $getUserLevelId = Db::query($sql);
  890. $user_level_uids=ltrim($getUserLevelId[0]['count'],'$,');
  891. return $user_level_uids;
  892. }
  893. public function insterUser($uid, $spread_uid){
  894. /**
  895. * 查询上级人数 select * from rrx_user_count LIMIT 0,1
  896. */
  897. // $spread_uid = Db::name('user') -> where('uid', $uid) -> value('spread_uid');
  898. // Db::name('log')->insert(['data'=>'公排注册:'.$uid.'======'.$spread_uid]);
  899. // $userCount = false;
  900. // if ($spread_uid > 0){
  901. // //找直推上级网络里面不足5人的排进去
  902. //
  903. // $userCount = Db::name('user_count') -> where('level_number >= 0') -> where ('uid', $spread_uid) -> find();
  904. // if (!$userCount){
  905. // $userCount = $this -> getCountUId($spread_uid);
  906. // }
  907. //
  908. //
  909. // }
  910. // Log::info("userCount:::");
  911. // Log::info($userCount);
  912. // Log::info($spread_uid);
  913. // Db::name('log')->insert(['data'=>'uid:'.$uid.'公排注册:'.json_encode($userCount)]);
  914. // if (!$userCount){
  915. // //没有直推上级 大公排
  916. // $userCount = Db::name('user_count') -> where('level_number >= 0') -> find();
  917. // //增加一个只查询新账户大公排下的用户
  918. // // $userCount = Db::name('user_count') -> where('level_number >= 0')->whereIn('uid',$this->getUserLevelId(11112)) -> find();
  919. // }
  920. // if ($userCount) {
  921. // if ($userCount['level_number'] + 1 == systemConfig( 'max_level_number')) { //(33制或者55制)下级最大人数systemConfig( 'max_level_number')
  922. // Db::name('user_count') -> where('uid',$userCount['uid'])->delete();
  923. // } else {
  924. // $level_number = $userCount['level_number'] + 1;
  925. // Db::name('user_count') -> where('uid',$userCount['uid']) -> update(['level_number'=>$level_number]);
  926. // }
  927. // }
  928. // dd($spread_uid);
  929. // Db::name('user') -> where('uid',$uid)->update(['level_id'=>$userCount['uid'],'level'=>$this->level()]);
  930. // Db::name('user_count') -> insert(['uid'=>$uid]);
  931. }
  932. public function getCountUId($spread_uid){
  933. if (empty($spread_uid)){
  934. return false;
  935. }
  936. //查询所有下级是否满足条件
  937. //查询所有下级uid
  938. $level_id = Db::name('user') -> where('level_id', $spread_uid) -> field('uid') -> select()->toArray();
  939. $level_ids = array_column($level_id,'uid');
  940. $check_ids = Db::name('user_count') -> where('level_number >= 0') -> where ('uid','in', $level_ids) -> find();
  941. foreach ($level_id as $value){
  942. //查询下级是否满足条件
  943. $check = Db::name('user_count') -> where('level_number >= 0') -> where ('uid', $value['uid']) -> find();
  944. if ($check){
  945. return $check;
  946. }else if(empty($check_ids)){
  947. $id = $this -> getCountUId($value['uid']);
  948. if ($id){
  949. return $id;
  950. }
  951. }
  952. }
  953. return false;
  954. }
  955. private function level() {
  956. $count = Db::name('user')->where('level > 0')->count();
  957. switch ($count) {
  958. case 0:
  959. return 1;
  960. case 1:
  961. return 2;
  962. }
  963. $number = ($count + 1) - floor($count / 5);
  964. return ceil(log($number) / log(5)) + 1;
  965. }
  966. /**
  967. * @param User $user
  968. * @return array
  969. * @author xaboy
  970. * @day 2020-04-29
  971. */
  972. public function createToken(User $user)
  973. {
  974. $service = new JwtTokenService();
  975. $token = $service->createToken($user->uid, 'user');
  976. $this->cacheToken($token['token'], $token['out'],$user->uid);
  977. if($user -> user_number == ''){
  978. $this -> createUserNumber($user->uid);
  979. }
  980. // if($user -> im == 0 && env('im',false)){
  981. // $im = new Im();
  982. // $im -> createIm($user -> account,$user -> user_number);
  983. // }
  984. return $token;
  985. }
  986. /**
  987. * //TODO 登录成功后
  988. * @param User $user
  989. * @author xaboy
  990. * @day 2020/6/22
  991. */
  992. public function loginAfter(User $user)
  993. {
  994. $user->last_time = date('Y-m-d H:i:s', time());
  995. $user->last_ip = request()->ip();
  996. $user->save();
  997. }
  998. /**
  999. * @param string $token
  1000. * @param int $exp
  1001. * @author xaboy
  1002. * @day 2020-04-29
  1003. */
  1004. public function cacheToken(string $token, int $exp,$uid)
  1005. {
  1006. Cache::set('user_' . $token, time() + $exp, $exp);
  1007. Cache::set('java_' . $token, $uid, $exp);
  1008. }
  1009. /**
  1010. * @param string $token
  1011. * @author xaboy
  1012. * @day 2020-04-29
  1013. */
  1014. public function checkToken(string $token)
  1015. {
  1016. $has = Cache::has('user_' . $token);
  1017. if (!$has)
  1018. throw new AuthException('无效的token');
  1019. $lastTime = Cache::get('user_' . $token);
  1020. if (($lastTime + intval(Config::get('admin.token_valid_exp', 15)) * 60) > time())
  1021. throw new AuthException('token 已过期');
  1022. }
  1023. /**
  1024. * @param string $token
  1025. * @author xaboy
  1026. * @day 2020-04-29
  1027. */
  1028. public function updateToken(string $token)
  1029. {
  1030. Cache::set('user_' . $token, time(), intval(Config::get('admin.token_valid_exp', 15)) * 60);
  1031. }
  1032. /**
  1033. * @param string $token
  1034. * @author xaboy
  1035. * @day 2020-04-29
  1036. */
  1037. public function clearToken(string $token)
  1038. {
  1039. Cache::delete('user_' . $token);
  1040. }
  1041. /**
  1042. * @param string $key
  1043. * @param string $code
  1044. * @author xaboy
  1045. * @day 2020/6/1
  1046. */
  1047. public function checkCode(string $key, string $code)
  1048. {
  1049. $_code = Cache::get('am_captcha' . $key);
  1050. if (!$_code) {
  1051. throw new ValidateException('验证码过期');
  1052. }
  1053. if (strtolower($_code) != strtolower($code)) {
  1054. throw new ValidateException('验证码错误');
  1055. }
  1056. //删除code
  1057. Cache::delete('am_captcha' . $key);
  1058. }
  1059. /**
  1060. * @param string $code
  1061. * @return string
  1062. * @author xaboy
  1063. * @day 2020/6/1
  1064. */
  1065. public function createLoginKey(string $code)
  1066. {
  1067. $key = uniqid(microtime(true), true);
  1068. Cache::set('am_captcha' . $key, $code, Config::get('admin.captcha_exp', 5) * 60);
  1069. return $key;
  1070. }
  1071. //$repository->registr($data['phone'], $data['password'],'APP',"","",$data['spread']);
  1072. public function registr(string $phone, ?string $pwd, $user_type = 'h5',$url="",$nickname="",$external=1,$spread_uid=null)
  1073. {
  1074. $user_res = Db::name('user')->where('phone', $phone)->find();
  1075. if ($user_res && !$user_res['account']) {
  1076. $data = [
  1077. 'account' => $phone,
  1078. ];
  1079. $this->dao->update($user_res['uid'], $data);
  1080. return $this->dao->get($user_res['uid']);
  1081. }
  1082. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1083. $data = [
  1084. 'account' => $phone,
  1085. 'pwd' => $pwd,
  1086. 'nickname' =>$nickname?$nickname:'用户' . substr($phone, 7, 4),
  1087. 'avatar' => 'https://cdn.bjtdba.com/vod/image/2025-01-20/20250120125206881.png',
  1088. 'phone' => $phone,
  1089. 'last_ip' => app('request')->ip(),
  1090. "identity"=>5,
  1091. "external"=>$external,
  1092. "level_id"=>$spread_uid,
  1093. "spread_uid"=>$spread_uid
  1094. ];
  1095. return $this->create($user_type, $data, $url,$spread_uid);
  1096. }
  1097. public function addregistr($data)
  1098. {
  1099. // string $phone, ?string $pwd, $user_type = 'h5',$url,
  1100. $phone=$data['phone'];
  1101. $pwd=empty($data['password'])?time():$data['password'];
  1102. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1103. $data = [
  1104. 'account' => $phone,
  1105. 'pwd' => $pwd,
  1106. 'nickname' => '用户' . substr($phone, 7, 4),
  1107. 'avatar' => 'https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png',
  1108. 'phone' => $phone,
  1109. 'last_ip' => app('request')->ip(),
  1110. 'user_name'=>empty($data['user_name'])?0:$data['user_name'],
  1111. 'birthday'=>empty($data['birthday'])?0:$data['birthday'],
  1112. 'sex'=>empty($data['adr_id'])?0:$data['sex'],
  1113. 'spread_uid'=>$data['spread'],
  1114. 'adr_id'=>empty($data['adr_id'])?0:$data["adr_id"],
  1115. 'identity'=>empty($data['identity'])?0:$data["identity"],
  1116. ];
  1117. return $this->create("APP", $data);
  1118. }
  1119. /**
  1120. * 重置密码
  1121. * @param string $phone
  1122. * @param string|null $pwd
  1123. * @author 似水星辰 [ 2630481389@qq.com ]
  1124. * @created 2020/10/14 23:46
  1125. */
  1126. public function resetPassword(string $phone, ?string $pwd, int $userid)
  1127. {
  1128. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1129. $data = [
  1130. 'account' => $phone,
  1131. 'pwd' => $pwd,
  1132. 'phone' => $phone,
  1133. 'last_ip' => app('request')->ip()
  1134. ];
  1135. return $this->dao->update($userid, $data);
  1136. }
  1137. /*重置手机号*/
  1138. public function resetAccount(string $phone, int $userid, $identity){
  1139. $data = [
  1140. 'account' => $phone,
  1141. 'phone' => $phone,
  1142. 'last_ip' => app('request')->ip()
  1143. ];
  1144. //如果是商家
  1145. if($identity == 4){
  1146. $res = Db::name("merchant_admin")->where(['uid'=>$userid])->update(['account'=>$phone,'phone'=>$phone]);
  1147. if(!$res){
  1148. return false;
  1149. }
  1150. }
  1151. return $this->dao->update($userid, $data);
  1152. }
  1153. public function routineSpreadImage(User $user)
  1154. {
  1155. //小程序
  1156. $name = $user['uid'] . '_' . $user['is_promoter'] . '_user_routine.jpg';
  1157. $attachmentRepository = app()->make(AttachmentRepository::class);
  1158. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  1159. $spreadBanner = systemGroupData('spread_banner');
  1160. if (!count($spreadBanner)) return [];
  1161. $siteName = systemConfig('site_name');
  1162. $siteUrl = systemConfig('site_url');
  1163. $uploadType = (int)systemConfig('upload_type') ?: 1;
  1164. //检测远程文件是否存在
  1165. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  1166. $imageInfo->delete();
  1167. $imageInfo = null;
  1168. }
  1169. if (!$imageInfo) {
  1170. $routineQrcodeRepository = app()->make(RoutineQrcodeRepository::class);
  1171. $res = $routineQrcodeRepository->getShareCode($user['uid'], 'spread', '',$user['avatar']);
  1172. if (!$res) throw new ValidateException('二维码生成失败');
  1173. $upload = UploadService::create($uploadType);
  1174. $uploadRes = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
  1175. if ($uploadRes === false) {
  1176. throw new ValidateException($upload->getError());
  1177. }
  1178. $imageInfo = $upload->getUploadInfo();
  1179. $imageInfo['image_type'] = $uploadType;
  1180. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  1181. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  1182. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1183. 'attachment_category_id' => 0,
  1184. 'attachment_name' => $imageInfo['name'],
  1185. 'attachment_src' => $imageInfo['dir']
  1186. ]);
  1187. $routineQrcodeRepository->setRoutineQrcodeFind($res['id'], ['status' => 1, 'url_time' => date('Y-m-d H:i:s'), 'qrcode_url' => $imageInfo['dir']]);
  1188. $urlCode = $imageInfo['dir'];
  1189. } else $urlCode = $imageInfo['attachment_src'];
  1190. $siteUrlHttps = set_http_type($siteUrl, request()->isSsl() ? 0 : 1);
  1191. $filelink = [
  1192. 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1193. 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1194. ];
  1195. if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
  1196. if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
  1197. $resRoutine = true;
  1198. foreach ($spreadBanner as $key => &$item) {
  1199. $posterInfo = '海报生成失败:(';
  1200. $config = array(
  1201. 'image' => array(
  1202. array(
  1203. 'url' => $urlCode, //二维码资源
  1204. 'stream' => 0,
  1205. 'left' => 114,
  1206. 'top' => 790,
  1207. 'right' => 0,
  1208. 'bottom' => 0,
  1209. 'width' => 120,
  1210. 'height' => 120,
  1211. 'opacity' => 100
  1212. )
  1213. ),
  1214. 'text' => array(
  1215. array(
  1216. 'text' => $user['nickname'],
  1217. 'left' => 250,
  1218. 'top' => 840,
  1219. 'fontPath' => $filelink['Bold'], //字体文件
  1220. 'fontSize' => 16, //字号
  1221. 'fontColor' => '40,40,40', //字体颜色
  1222. 'angle' => 0,
  1223. ),
  1224. array(
  1225. 'text' => '邀请您加入' . $siteName,
  1226. 'left' => 250,
  1227. 'top' => 880,
  1228. 'fontPath' => $filelink['Normal'], //字体文件
  1229. 'fontSize' => 16, //字号
  1230. 'fontColor' => '40,40,40', //字体颜色
  1231. 'angle' => 0,
  1232. )
  1233. ),
  1234. 'background' => $item['pic']
  1235. );
  1236. $resRoutine = $resRoutine && $posterInfo = setSharePoster($config, 'routine/spread/poster');
  1237. if (!is_array($posterInfo)) throw new ValidateException($posterInfo);
  1238. $posterInfo['dir'] = path_to_url($posterInfo['dir']);
  1239. if (strpos($posterInfo['dir'], 'http') === false) $posterInfo['dir'] = request()->domain() . $posterInfo['dir'];
  1240. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1241. 'attachment_category_id' => 0,
  1242. 'attachment_name' => $posterInfo['name'],
  1243. 'attachment_src' => $posterInfo['dir']
  1244. ]);
  1245. if ($resRoutine) {
  1246. if ($posterInfo['image_type'] == 1)
  1247. $item['poster'] = rtrim($siteUrlHttps, '/') . $posterInfo['dir'];
  1248. else
  1249. $item['poster'] = set_http_type($posterInfo['dir'], request()->isSsl() ? 0 : 1);
  1250. $item['poster'] = str_replace('\\', '/', $item['poster']);
  1251. }
  1252. }
  1253. return $spreadBanner;
  1254. }
  1255. public function wxSpreadImage(User $user)
  1256. {
  1257. //公众号
  1258. $name = $user['uid'] . '_' . $user['is_promoter'] . '_user_wap.jpg';
  1259. $spreadBanner = systemGroupData('spread_banner');
  1260. if (!count($spreadBanner)) return [];
  1261. $siteName = systemConfig('site_name');
  1262. $attachmentRepository = app()->make(AttachmentRepository::class);
  1263. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  1264. $siteUrl = systemConfig('site_url');
  1265. $uploadType = (int)systemConfig('upload_type') ?: 1;
  1266. $resWap = true;
  1267. //检测远程文件是否存在
  1268. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  1269. $imageInfo->delete();
  1270. $imageInfo = null;
  1271. }
  1272. if (!$imageInfo) {
  1273. $codeUrl = set_http_type($siteUrl . '/share?spread=' . $user['uid'], request()->isSsl() ? 0 : 1);//二维码链接
  1274. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name,$user['avatar']);
  1275. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  1276. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  1277. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  1278. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -1, $user->uid, [
  1279. 'attachment_category_id' => 0,
  1280. 'attachment_name' => $imageInfo['name'],
  1281. 'attachment_src' => $imageInfo['dir']
  1282. ]);
  1283. $urlCode = $imageInfo['dir'];
  1284. } else $urlCode = $imageInfo['attachment_src'];
  1285. $siteUrl = set_http_type($siteUrl, request()->isSsl() ? 0 : 1);
  1286. $filelink = [
  1287. 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1288. 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1289. ];
  1290. if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
  1291. if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
  1292. foreach ($spreadBanner as $key => &$item) {
  1293. $posterInfo = '海报生成失败:(';
  1294. $config = array(
  1295. 'image' => array(
  1296. array(
  1297. 'url' => $urlCode, //二维码资源
  1298. 'stream' => 0,
  1299. 'left' => 160,//84
  1300. 'top' => 530,//630
  1301. 'right' => 0,
  1302. 'bottom' => 0,
  1303. 'width' => 280,
  1304. 'height' => 280,
  1305. 'opacity' => 100
  1306. )
  1307. ),
  1308. 'text' => array(
  1309. array(
  1310. 'text' => "NO:".$user['user_number'],
  1311. 'left' => 200,
  1312. 'top' => 850,
  1313. 'fontPath' => $filelink['Bold'], //字体文件
  1314. 'fontSize' => 16, //字号
  1315. 'fontColor' => '0,0,0', //字体颜色
  1316. 'angle' => 0,
  1317. ),
  1318. // array(
  1319. // 'text' => '邀请您加入' . $siteName,
  1320. // 'left' => 290,
  1321. // 'top' => 750,
  1322. // 'fontPath' => $filelink['Normal'], //字体文件
  1323. // 'fontSize' => 16, //字号
  1324. // 'fontColor' => '40,40,40', //字体颜色
  1325. // 'angle' => 0,
  1326. // )
  1327. ),
  1328. 'background' => $item['pic']
  1329. );
  1330. $resWap = $resWap && $posterInfo = setSharePoster($config, 'wap/spread/poster');
  1331. if (!is_array($posterInfo)) throw new ValidateException('海报生成失败');
  1332. $posterInfo['dir'] = path_to_url($posterInfo['dir']);
  1333. if (strpos($posterInfo['dir'], 'http') === false) $posterInfo['dir'] = request()->domain() . $posterInfo['dir'];
  1334. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1335. 'attachment_category_id' => 0,
  1336. 'attachment_name' => $posterInfo['name'],
  1337. 'attachment_src' => $posterInfo['dir']
  1338. ]);
  1339. if ($resWap) {
  1340. if ($posterInfo['image_type'] == 1)
  1341. $item['wap_poster'] = rtrim($siteUrl, '/') . $posterInfo['thumb_path'];
  1342. else
  1343. $item['wap_poster'] = set_http_type($posterInfo['thumb_path'], 1);
  1344. }
  1345. $item['wap_poster'] = str_replace('http://','https://',$item['wap_poster']);
  1346. $item["attachment_src"]= str_replace('http://','https://',$urlCode);
  1347. $item["name"]=$user['phone'];
  1348. }
  1349. return $spreadBanner;
  1350. }
  1351. public function getUsername($uid)
  1352. {
  1353. return User::getDB()->where('uid', $uid)->value('user_name');
  1354. }
  1355. /*获取用户手机号*/
  1356. public function getUserPhone($uid)
  1357. {
  1358. return User::getDB()->where('uid', $uid)->value('account');
  1359. }
  1360. /**
  1361. * @param $uid
  1362. * @param $inc
  1363. * @param string $type
  1364. * @author xaboy
  1365. * @day 2020/6/22
  1366. */
  1367. public function incBrokerage($uid, $inc, $type = '+')
  1368. {
  1369. $weekKey = 'b_top_' . date('Y-m');
  1370. $moneyKey = 'b_top_' . monday();
  1371. //TODO 佣金周榜
  1372. $brokerage = Cache::zscore($weekKey, $uid);
  1373. $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
  1374. Cache::zadd($weekKey, $brokerage, $uid);
  1375. //TODO 佣金月榜
  1376. $brokerage = Cache::zscore($moneyKey, $uid);
  1377. $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
  1378. Cache::zadd($moneyKey, $brokerage, $uid);
  1379. }
  1380. public function brokerageWeekTop($page, $limit)
  1381. {
  1382. $key = 'b_top_' . monday();
  1383. return $this->topList($key, $page, $limit);
  1384. }
  1385. public function brokerageMonthTop($page, $limit)
  1386. {
  1387. $key = 'b_top_' . date('Y-m');
  1388. return $this->topList($key, $page, $limit);
  1389. }
  1390. /**
  1391. * //TODO 绑定上下级关系
  1392. * @param User $user
  1393. * @param int $spreadUid
  1394. * @throws DbException
  1395. * @author xaboy
  1396. * @day 2020/6/22
  1397. */
  1398. public function bindSpread(User $user, int $spreadUid)
  1399. {
  1400. if ($spreadUid && !$user->spread_uid && $user->uid != $spreadUid) {
  1401. Db::transaction(function () use ($spreadUid, $user) {
  1402. $spread_user = $this ->get($spreadUid);
  1403. // //首次邀请赠送899积分
  1404. // if($spread_user['spread_count'] == 0){
  1405. // //首次邀请好友奖励积分
  1406. // $this -> sign_add($spreadUid,systemConfig('first_yq_score'),1,'首次邀请好友奖励积分','','');
  1407. // }
  1408. // //邀请好友奖励积分
  1409. // $this -> sign_add($spreadUid,systemConfig('invitation'),1,'邀请好友注册奖励积分','','');
  1410. $user->spread_uid = $spreadUid;
  1411. $user->spread_time = date('Y-m-d H:i:s');
  1412. if($spreadUid){
  1413. $user->mer_id = Db::name('user')->where('uid',$spreadUid)->value('mer_id');
  1414. }
  1415. $this->dao->update($spreadUid, [
  1416. 'spread_count' => Db::raw('spread_count +1')
  1417. ]);
  1418. $user->save();
  1419. //TODO 推广人月榜
  1420. Cache::zincrby('s_top_' . date('Y-m'), 1, $spreadUid);
  1421. //TODO 推广人周榜
  1422. Cache::zincrby('s_top_' . monday(), 1, $spreadUid);
  1423. });
  1424. $this->spread_log($user,$spreadUid);
  1425. }
  1426. //绑定上下级关系 加入推广群
  1427. // $this -> hximTg($user -> uid,$spreadUid);
  1428. }
  1429. /**
  1430. * @param $uid int 用户id
  1431. * @param $sid int 上级id
  1432. * @author Tang
  1433. * @created 2021/12/10
  1434. */
  1435. public function hximTg($uid,$sid)
  1436. {
  1437. try {
  1438. $im=new Im();
  1439. $user=Db::name('user')->where('uid',$uid)->find();
  1440. if($user['im']==0){//没有环信账户 创建
  1441. $im->createImUser($user['account'], $user['nickname']);
  1442. $user_account=$user['account'];
  1443. }else{//有环信账户 跳过创建 下一步
  1444. $user_account=$user['account'];
  1445. }
  1446. $userS=Db::name('user')->where('uid',$sid)->find();
  1447. if($userS['im']==0){//上级环信账户 创建
  1448. $im->createImUser($userS['account'], $userS['nickname']);
  1449. $s_account=$userS['account'];
  1450. }else{//有环信账户 跳过创建 下一步
  1451. $s_account=$userS['account'];
  1452. }
  1453. $group_id=Db::name("im_group")->where(['uid'=>$userS['account'],'type'=>'p'])->value('groupid');
  1454. //判断是否有群
  1455. if($group_id){//有则加入
  1456. $im->createGroupUser($group_id,$user_account,$user['uid']);
  1457. }else{
  1458. $group_id=$im->createGroup($s_account,'推广群','t');
  1459. $im->createGroupUser($group_id,$user_account,$user['uid']);
  1460. }
  1461. }catch (\Exception $e) {
  1462. Db::name("log")->insert(array('data'=>'推广群错误'.$e->getMessage()));//日志记录
  1463. }
  1464. }
  1465. //注册时成为推广员身份 记录统计及信息
  1466. public function spread_log($user,$spreadUid){
  1467. if($spreadUid){
  1468. Db::transaction(function () use ($spreadUid, $user) {
  1469. $sp = DB::name("user")->where(['uid'=>$spreadUid])->field("uid,spread_count")->find();
  1470. if($sp){
  1471. //推荐人推荐数量加1
  1472. Db::name("user")->where(['uid'=>$sp['uid']])->update(['spread_count'=>($sp['spread_count']+1)]);
  1473. //保存用户的推荐记录
  1474. $log =[
  1475. 'uid'=> $sp['uid'],
  1476. 'link_id'=>$user->uid,
  1477. 'identity'=>5,
  1478. 'create_time'=>date("Y-m-d H:i:s"),
  1479. ] ;
  1480. Db::name("user_identity_log")->insert($log);
  1481. }
  1482. });
  1483. }
  1484. }
  1485. public function topList($key, $page, $limit)
  1486. {
  1487. $res = Cache::zrevrange($key, ($page - 1) * $limit, $limit, true);
  1488. $ids = array_keys($res);
  1489. $index = array_flip($ids);
  1490. $count = Cache::zcard($key);
  1491. $list = count($ids) ? $this->dao->users($ids, 'uid,avatar,nickname')->toArray() : [];
  1492. foreach ($list as $k => $v) {
  1493. $list[$k]['count'] = $res[$v['uid']] ?? 0;
  1494. }
  1495. $sort = array_column($list, 'count');
  1496. array_multisort($sort, SORT_DESC, $list);
  1497. return compact('count', 'list');
  1498. }
  1499. public function spreadWeekTop($page, $limit)
  1500. {
  1501. $key = 's_top_' . monday();
  1502. return $this->topList($key, $page, $limit);
  1503. }
  1504. public function spreadMonthTop($page, $limit)
  1505. {
  1506. $key = 's_top_' . date('Y-m');
  1507. return $this->topList($key, $page, $limit);
  1508. }
  1509. /**
  1510. * @param $uid
  1511. * @param $nickname
  1512. * @param $sort
  1513. * @param $page
  1514. * @param $limit
  1515. * @return array
  1516. * @throws DataNotFoundException
  1517. * @throws DbException
  1518. * @throws ModelNotFoundException
  1519. * @author xaboy
  1520. * @day 2020/6/22
  1521. */
  1522. public function getOneLevelList($uid, $nickname, $sort, $page, $limit)
  1523. {
  1524. $query = $this->search(['spread_uid' => $uid, 'nickname' => $nickname, 'sort' => $sort]);
  1525. $count = $query->count();
  1526. $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
  1527. return compact('list', 'count');
  1528. }
  1529. /**
  1530. * @param $uid
  1531. * @param $nickname
  1532. * @param $sort
  1533. * @param $page
  1534. * @param $limit
  1535. * @return array
  1536. * @throws DataNotFoundException
  1537. * @throws DbException
  1538. * @throws ModelNotFoundException
  1539. * @author xaboy
  1540. * @day 2020/6/22
  1541. */
  1542. public function getTwoLevelList($uid, $nickname, $sort, $page, $limit)
  1543. {
  1544. $ids = $this->dao->getSubIds($uid);
  1545. if (count($ids)) {
  1546. $query = $this->search(['spread_uids' => $ids, 'nickname' => $nickname, 'sort' => $sort]);
  1547. $count = $query->count();
  1548. $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
  1549. } else {
  1550. $list = [];
  1551. $count = 0;
  1552. }
  1553. return compact('list', 'count');
  1554. }
  1555. public function getLevelList($uid, array $where, $page, $limit)
  1556. {
  1557. if (!$where['level']) {
  1558. // $ids = $this->dao->getSubIds($uid);
  1559. $ids[] = $uid;
  1560. $where['spread_uids'] = $ids;
  1561. } else if ($where['level'] == 2) {
  1562. $ids = $this->dao->getSubIds($uid);
  1563. if (!count($ids)) return ['list' => [], 'count' => 0];
  1564. $where['spread_uids'] = $ids;
  1565. } else {
  1566. $where['spread_uid'] = $uid;
  1567. }
  1568. $query = $this->search($where);
  1569. $count = $query->count();
  1570. $list = $query->setOption('field', [])->field('User.uid,avatar,nickname,is_promoter,pay_count,pay_price,spread_count,User.create_time')->page($page, $limit)->select();
  1571. return compact('list', 'count','where');
  1572. }
  1573. /**
  1574. * @param $uid
  1575. * @param $page
  1576. * @param $limit
  1577. * @param array $where
  1578. * @return array
  1579. * @throws DataNotFoundException
  1580. * @throws DbException
  1581. * @throws ModelNotFoundException
  1582. * @author xaboy
  1583. * @day 2020/6/26
  1584. */
  1585. public function subOrder($uid, $page, $limit, array $where = [])
  1586. {
  1587. if (isset($where['level'])) {
  1588. if (!$where['level']) {
  1589. $ids = $this->dao->getSubIds($uid);
  1590. $subIds = $this->dao->getSubAllIds($ids);
  1591. } else if ($where['level'] == 2) {
  1592. $ids = $this->dao->getSubIds($uid);
  1593. $subIds = $this->dao->getSubAllIds($ids);
  1594. $ids = [];
  1595. } else {
  1596. $ids = $this->dao->getSubIds($uid);
  1597. $subIds = [];
  1598. }
  1599. } else {
  1600. $ids = $this->dao->getSubIds($uid);
  1601. $subIds = $this->dao->getSubAllIds($ids);
  1602. }
  1603. $all = array_merge($ids, $subIds);
  1604. if (!count($all)) return ['count' => 0, 'list' => []];
  1605. $query = app()->make(StoreOrderRepository::class)->usersOrderQuery($where, $all);
  1606. $count = $query->count();
  1607. $list = $query->page($page, $limit)->field('uid,order_sn,pay_time,extension_one,extension_two')->with(['user' => function ($query) {
  1608. $query->field('avatar,nickname,uid');
  1609. }])->select()->toArray();
  1610. foreach ($list as $k => $item) {
  1611. $list[$k]['brokerage'] = in_array($item['uid'], $ids) ? $item['extension_one'] : $item['extension_two'];
  1612. unset($list[$k]['extension_one'], $list[$k]['extension_two']);
  1613. }
  1614. return compact('count', 'list');
  1615. }
  1616. /**
  1617. * @param User $user
  1618. * @return User
  1619. * @throws DataNotFoundException
  1620. * @throws DbException
  1621. * @throws ModelNotFoundException
  1622. * @author xaboy
  1623. * @day 2020/7/2
  1624. */
  1625. public function mainUser(User $user): User
  1626. {
  1627. if (!$user->main_uid || $user->uid == $user->main_uid) return $user;
  1628. $switchUser = $this->dao->get($user->main_uid);
  1629. if (!$switchUser) return $user;
  1630. if ($user->wechat_user_id && !$switchUser->wechat_user_id) {
  1631. $switchUser->wechat_user_id = $user->wechat_user_id;
  1632. $switchUser->save();
  1633. }
  1634. return $switchUser;
  1635. }
  1636. public function switchUser(User $user, $uid)
  1637. {
  1638. if ($user->uid == $uid || !$this->dao->existsWhere(['uid' => $uid, 'phone' => $user->phone]))
  1639. throw new ValidateException('操作失败');
  1640. $this->dao->update($user->uid, ['main_uid' => $uid]);
  1641. $switchUser = $this->dao->get($uid);
  1642. return $switchUser;
  1643. }
  1644. public function returnToken($user, $tokenInfo)
  1645. {
  1646. $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();
  1647. return [
  1648. 'token' => $tokenInfo['token'],
  1649. 'exp' => $tokenInfo['out'],
  1650. 'user' => $user
  1651. ];
  1652. }
  1653. public function switchBrokerage(User $user, $brokerage)
  1654. {
  1655. $user->now_money = bcadd($user->now_money, $brokerage, 2);
  1656. $user->brokerage_price = bcsub($user->brokerage_price, $brokerage, 2);
  1657. Db::transaction(function () use ($brokerage, $user) {
  1658. $user->save();
  1659. app()->make(UserBillRepository::class)->incBill($user->uid, 'now_money', 'brokerage', [
  1660. 'link_id' => 0,
  1661. 'status' => 1,
  1662. 'title' => '佣金转入余额',
  1663. 'number' => $brokerage,
  1664. 'mark' => '成功转入余额' . floatval($brokerage) . '元',
  1665. 'balance' => $user->now_money
  1666. ]);
  1667. app()->make(UserBillRepository::class)->decBill($user->uid, 'brokerage', 'now_money', [
  1668. 'link_id' => 0,
  1669. 'status' => 1,
  1670. 'title' => '佣金转入余额',
  1671. 'number' => $brokerage,
  1672. 'mark' => '成功转入余额' . floatval($brokerage) . '元',
  1673. 'balance' => $user->brokerage_price
  1674. ]);
  1675. });
  1676. }
  1677. /**
  1678. * 签到
  1679. * @param $member_id
  1680. * @throws DataNotFoundException
  1681. * @throws DbException
  1682. * @throws ModelNotFoundException
  1683. */
  1684. public function sub_signin($member_id){
  1685. $member_info = Db::name('user')->where( array('uid' => $member_id) )->find();
  1686. $config =systemConfig([
  1687. 'isopen_signinreward',
  1688. 'signinreward_day1_score',
  1689. 'signinreward_day2_score',
  1690. 'signinreward_day3_score',
  1691. 'signinreward_day4_score',
  1692. 'signinreward_day5_score',
  1693. 'signinreward_day6_score',
  1694. 'signinreward_day7_score',
  1695. ]);
  1696. //是否开启签到奖励
  1697. $isopen_signinreward = empty($config['isopen_signinreward']) ? 0 : $config['isopen_signinreward'];
  1698. if( $isopen_signinreward != 1 )
  1699. {
  1700. return array('code' => 1,'msg' => '签到奖励功能未开启');
  1701. }
  1702. //连续7天签到奖励
  1703. $signinreward_day1_score = empty($config['signinreward_day1_score']) ? 0 : $config['signinreward_day1_score'];
  1704. $signinreward_day2_score = empty($config['signinreward_day2_score']) ? 0 : $config['signinreward_day2_score'];
  1705. $signinreward_day3_score = empty($config['signinreward_day3_score']) ? 0 : $config['signinreward_day3_score'];
  1706. $signinreward_day4_score = empty($config['signinreward_day4_score']) ? 0 : $config['signinreward_day4_score'];
  1707. $signinreward_day5_score = empty($config['signinreward_day5_score']) ? 0 : $config['signinreward_day5_score'];
  1708. $signinreward_day6_score = empty($config['signinreward_day6_score']) ? 0 : $config['signinreward_day6_score'];
  1709. $signinreward_day7_score = empty($config['signinreward_day7_score']) ? 0 : $config['signinreward_day7_score'];
  1710. //准备数据
  1711. $result = array();
  1712. $result['signinreward_day1_score'] = $signinreward_day1_score;
  1713. $result['signinreward_day2_score'] = $signinreward_day2_score;
  1714. $result['signinreward_day3_score'] = $signinreward_day3_score;
  1715. $result['signinreward_day4_score'] = $signinreward_day4_score;
  1716. $result['signinreward_day5_score'] = $signinreward_day5_score;
  1717. $result['signinreward_day6_score'] = $signinreward_day6_score;
  1718. $result['signinreward_day7_score'] = $signinreward_day7_score;
  1719. $today_signintime = time();
  1720. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->whereDay('signin_time')->find();
  1721. if( !empty($today_signin_info) )
  1722. {
  1723. return array('code' => 1,'msg' => '今天已经签到过了');
  1724. }else{
  1725. //查询昨天是否已经签到了
  1726. $yes_signintime = strtotime( date('Y-m-d'). ' 00:00:00' ) - 86400;
  1727. $yes_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id, 'signin_time' => $yes_signintime ) )->find();
  1728. $has_qian = 1;
  1729. if( !empty($yes_signin_info) )
  1730. {
  1731. $has_qian = $yes_signin_info['continuity_day'] +1;
  1732. $has_qian = $has_qian > 7 ? 7 : $has_qian;
  1733. }
  1734. $get_score = $result["signinreward_day".$has_qian."_score"];
  1735. $ins_data = array();
  1736. $ins_data['member_id'] = $member_id;
  1737. $ins_data['continuity_day'] = $has_qian;
  1738. $ins_data['reward_socre'] = $get_score;
  1739. $ins_data['signin_time'] = $today_signintime;
  1740. $ins_data['addtime'] = time();
  1741. $member_info = Db::name('user')->where( array('uid' => $member_id) )->find();
  1742. $score = $member_info['now_score'];
  1743. Db::name('user_signinreward_record')->insert($ins_data);
  1744. $now_score=$score+$get_score;
  1745. app()->make(UserBillRepository::class)->incBill($member_id, 'now_money', 'recharge', [
  1746. 'link_id' => 1,
  1747. 'status' => 1,
  1748. 'title' => '签到积分',
  1749. 'number' => $get_score,
  1750. 'mark' => '连续签到'.$has_qian.'天赠送',
  1751. 'balance' =>$now_score
  1752. ]);
  1753. Db::name('user')->where( array('uid' => $member_id) )->update(['now_score'=>$now_score]);
  1754. // Db::name('log')->insert(['data'=>Db::name('user')->getLastSql(),'time'=>date('Y-m-d H:i:s',time())]);
  1755. return array('code' =>0, 'now_score' => $score, 'continuity_day' => $has_qian,'reward_socre' => $get_score );
  1756. }
  1757. }
  1758. public function get_signin($member_id,$where=[]){
  1759. if ($where){
  1760. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time', 'between', [$where['data1'], $where['data2']])->find();
  1761. $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');
  1762. }else{
  1763. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time',"today")->find();
  1764. $show_day_arr= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time',"month")->column('signin_time');
  1765. }
  1766. $score= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->count('reward_socre');
  1767. $leiji= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->sum('reward_socre');
  1768. foreach ($show_day_arr as &$v){
  1769. $v=date("Y-m-d",$v);
  1770. }
  1771. $result['score'] = $score;
  1772. $result['today_is_signin'] = $today_signin_info?1:0;
  1773. $result['leiji'] = $leiji;
  1774. $result['show_day_arr'] = $show_day_arr;
  1775. return $result;
  1776. }
  1777. public function add_cer($data=[],$member_id)
  1778. {
  1779. $renzeng=Db::name("user_certification")->where("uid",$member_id)->find();
  1780. if ($renzeng){
  1781. $res = Db::name('user_certification')->where("uid",$member_id)->update($data);
  1782. }else{
  1783. $res = Db::name('user_certification')->insert($data);
  1784. }
  1785. if($res){
  1786. return [
  1787. 'user_name' => $data['user_name'],
  1788. 'age' => $this->getAgeByID($data['user_card']),
  1789. 'user_card' => preg_replace('/(\d{6})\d{8}(\d{4})/', '$1****$2', $data['user_card']),
  1790. ];
  1791. }
  1792. else{
  1793. return false;
  1794. }
  1795. }
  1796. public function get_cer($data=[])
  1797. {
  1798. $res = Db::name('user_certification')->where($data)->find();
  1799. //计算年龄
  1800. $res['age'] = $this->getAgeByID($res['user_card']);
  1801. if($res){
  1802. return $res;
  1803. }
  1804. else{
  1805. return false;
  1806. }
  1807. }
  1808. public function getAgeByID($id){
  1809. //过了这年的生日才算多了1周岁
  1810. if(empty($id)) return '';
  1811. $date=strtotime(substr($id,6,8));
  1812. //获得出生年月日的时间戳
  1813. $today=strtotime('today');
  1814. //获得今日的时间戳
  1815. $diff=floor(($today-$date)/86400/365);
  1816. //得到两个日期相差的大体年数
  1817. //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
  1818. $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
  1819. return $age;
  1820. }
  1821. /**
  1822. * @param $data
  1823. *
  1824. */
  1825. public function addagent($user){
  1826. if ($user){
  1827. $data=[
  1828. "identity"=>5,
  1829. "status"=>1,
  1830. "add_time"=>time(),
  1831. "update_time"=>time(),
  1832. "user_id"=>$user->uid,
  1833. "name"=>"推广员",
  1834. "pay_status"=>1,
  1835. "price"=>0,
  1836. "agent_sn"=>time(),
  1837. ];
  1838. Db::name("user_agent")->insert($data);
  1839. }
  1840. }
  1841. /*
  1842. * 申请代理
  1843. @cabbage
  1844. */
  1845. public function agent($data){
  1846. $user = Db::name("user")->where(['uid'=>$data['user_id']])->field("identity,account,uid")->find();
  1847. //判断所申请的区域下是否有代理
  1848. if($data['identity'] == 1){
  1849. if(Db::name("user_street")->where("street_id",$data['street_id'])->value("uid")){
  1850. return ['code'=>400,'msg'=>'该区域下已有代理'];
  1851. }
  1852. }elseif($data['identity'] == 2){
  1853. if(Db::name("user_area")->where("area_id",$data['area_id'])->value("uid")){
  1854. return ['code'=>400,'msg'=>'该区域下已有代理'];
  1855. }
  1856. }elseif($data['identity'] == 3){
  1857. if(Db::name("user_city")->where("city_id",$data['city_id'])->value("uid")){
  1858. return ['code'=>400,'msg'=>'该区域下已有代理'];
  1859. }
  1860. }
  1861. //判断是不是商户
  1862. // if($user['identity']==4){
  1863. // return ['code'=>'400','msg'=>"不符合申请代理的条件"];
  1864. // }
  1865. //判断用户是否是其他代理身份
  1866. // if(in_array($user['identity'],[1,2,3,5])){
  1867. // return ['code'=>'400','msg'=>"用户已是推广身份"];
  1868. // }
  1869. if($user['identity']==$data['identity']){
  1870. return ['code'=>'400','msg'=>"用户已是该身份,无需申请"];
  1871. }
  1872. if($data['spread_account'] == $user['account']){
  1873. return ['code'=>'400','msg'=>"推荐人不能是自己"];
  1874. }
  1875. $real = Db::name("user_certification")->where(["uid"=>$data['user_id'],'status'=>1])->find();
  1876. //判断是否实名认证
  1877. if(!$real){
  1878. return ['code'=>'400','msg'=>"请先实名认证"];
  1879. }
  1880. if($user){
  1881. if($data['identity'] == $user['identity']){
  1882. return ['code'=>'400','msg'=>"已经是该级别代理"];
  1883. }
  1884. if(!in_array($user['identity'],[4,5]) && $data['identity'] < $user['identity']){
  1885. return ['code'=>'400','msg'=>"不能申请低于现在级别的代理"];
  1886. }
  1887. }
  1888. $is_apply= Db::name("user_agent")->where(["user_id"=>$data["user_id"],'status'=>[0,2]])->find();
  1889. if ($is_apply){
  1890. if($is_apply['status'] == 0){
  1891. return ['code'=>'400','msg'=>"您有审核中的代理申清"];
  1892. }
  1893. if($is_apply['status'] == 2) {
  1894. $data['status']= 0;//恢复申请中状态
  1895. $res= Db::name("user_agent")->where("id",$is_apply['id'])->update($data);
  1896. if($res){
  1897. return true;
  1898. }
  1899. }
  1900. }
  1901. $res= Db::name("user_agent")->insert($data);
  1902. if($res){
  1903. return true;
  1904. }
  1905. }
  1906. public function isAgent($uid){
  1907. $res = Db::name("user_agent")
  1908. ->where(["user_id"=>$uid])
  1909. ->whereIn('status',[0,1,2])
  1910. ->whereIn('identity',[1,2,3,6])
  1911. ->order("add_time desc")
  1912. ->find();
  1913. if(!$res){
  1914. return json_encode([]);
  1915. }
  1916. $res['province_name'] = Db::name("user_province")->where(['province_id'=>$res['province_id']])->value("province_name");
  1917. $res['city_name'] = Db::name("user_city")->where(['city_id'=>$res['city_id']])->value("city_name");
  1918. $res['area_name'] = Db::name("user_area")->where(['area_id'=>$res['area_id']])->value("area_name");
  1919. $res['street_name'] = Db::name("user_street")->where(['street_id'=>$res['street_id']])->value("street_name");
  1920. switch ($res['identity']){
  1921. case '1':
  1922. $res['name'] = '镇级服务商';
  1923. break;
  1924. case '2':
  1925. $res['name'] = '县级服务商';
  1926. break;
  1927. case '3':
  1928. $res['name'] = '市级服务商';
  1929. break;
  1930. case '6':
  1931. $res['name'] = '渠道商';
  1932. }
  1933. return $res;
  1934. }
  1935. public function getAgentPayDetail($where=[]){
  1936. $res= Db::name("user_agent")->where($where)->find();
  1937. return $res;
  1938. }
  1939. public function get_agent_info($member_id){
  1940. $user=Db::name("user")->where("uid",$member_id)->find();
  1941. $data=[
  1942. "nickname"=>$user["nickname"],
  1943. "avatar"=>$user["avatar"],
  1944. "is_promoter"=>$user["is_promoter"],
  1945. "identity"=>$user["identity"],
  1946. "brokerage_price"=>set_price_rtrim($user["brokerage_price"]),
  1947. "uid"=>$member_id,
  1948. ];
  1949. $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");
  1950. $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");
  1951. $data["extract"]=(string)Db::name("user_extract")->where(["uid"=>$member_id,"status"=>1])->sum("extract_price");
  1952. return $data;
  1953. }
  1954. /*
  1955. * 全民营销->推广统计
  1956. */
  1957. public function get_extension_info($member_id,$search,$where=[]){
  1958. $data=[];
  1959. $data["count_zong"]=Db::name("user_identity_log")->where(["uid"=>$member_id])->count();
  1960. $data["town"]=Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>1])->whereNotIn("identity","0")->count();
  1961. $data["county"]= Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>2])->whereNotIn("identity","0")->count();
  1962. $data["city"]= Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>3])->whereNotIn("identity","0")->count();
  1963. $data["shop"]=Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>4])->whereNotIn("identity","0")->count();
  1964. $data["tuiguang"]=Db::name("user_identity_log")->where(["uid"=>$member_id])->whereIn('identity','5,0')->count();
  1965. $query =Db::name("user_identity_log")->alias("a")
  1966. ->join('user s',"a.link_id=s.uid")
  1967. ->where(["a.uid"=>$member_id])
  1968. ->field("s.nickname,a.create_time,a.identity,s.phone");
  1969. if(isset($where['identity']) && $where['identity'] != ''){
  1970. $query = $query->where(['a.identity'=>$where['identity']]);
  1971. }
  1972. if(isset($search) && $search !=''){
  1973. $query =$query->whereLike('s.account','%'.$search.'%');
  1974. }
  1975. $list = $query->select();
  1976. $data["list"]=$list;
  1977. return $data;
  1978. }
  1979. public function get_profit_info($member_id,$where){
  1980. // $data["count_yj"]=Db::name("user")->where(["type"=>"commission"])->sum("number");
  1981. // $data["dlfee"]=Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");
  1982. // $data["xiaofee"]=Db::name("user")->where(["type"=>"commission","commission_type"=>2])->sum("number");;
  1983. // $data["county"] =Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");;
  1984. // $data["town"]==Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");;
  1985. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  1986. ->field("type,number,status,commission_type,create_time,uid,title,order_sn");
  1987. $order = "create_time desc";
  1988. if($where['date_on'] == 1){
  1989. $order = "create_time desc";
  1990. }elseif($where['date_off'] == 1){
  1991. $order = "create_time asc";
  1992. }
  1993. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  1994. $query = $query->where(['commission_type'=>$where['commission_type']]);
  1995. }else{
  1996. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  1997. }
  1998. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  1999. $query = $query->whereTime("create_time",$where['order']);
  2000. }
  2001. $list= $query->order($order)->select()->toArray();
  2002. $dangqian_yj=Db::name("user")->where("uid",$member_id)->value("brokerage_price");
  2003. $dlfee=0;
  2004. $xiaofei=0;
  2005. $tuiguang=0;
  2006. $xiaqu=0;
  2007. $weijiesuan=0;
  2008. $qudao=0;
  2009. foreach ($list as &$v){
  2010. // $count_yj=$v["number"]+$count_yj;
  2011. if ($v["status"]==0){
  2012. $v["title"]="【预估】".$v["title"].",单号:".$v["order_sn"];
  2013. $weijiesuan+=$v['number'];
  2014. }elseif($v["status"]==-1){
  2015. $v["title"]="【失效】".$v["title"].",单号:".$v["order_sn"];
  2016. }else{
  2017. if ($v["commission_type"]==1){
  2018. $dlfee+=$v["number"];
  2019. }
  2020. if ($v["commission_type"]==2){
  2021. $xiaofei+=$v["number"];
  2022. }
  2023. if ($v["commission_type"]==3){
  2024. $tuiguang+=$v["number"];
  2025. }
  2026. if ($v["commission_type"]==4){
  2027. $xiaqu+=$v["number"];
  2028. }
  2029. if ($v["commission_type"]==6||$v["commission_type"]==7){
  2030. $tuiguang+=$v["number"];
  2031. }
  2032. if ($v["commission_type"]==9){
  2033. $qudao+=$v["number"];
  2034. }
  2035. if ($v["commission_type"]==10){
  2036. $tuiguang+=$v["number"];
  2037. }
  2038. }
  2039. }
  2040. $data["count_yj"]=round($dangqian_yj,2);//当前佣金
  2041. $data["dlfee"]=round($dlfee,2); //代理非
  2042. $data["xiaofei"]=round($xiaofei,2); //消费佣金
  2043. $data["tuiguang"]= round($tuiguang,2); //推广佣金
  2044. $data["xiaqu"]=round($xiaqu,2); //辖区佣金
  2045. $data["weijiesuan"]=round($weijiesuan,2);//未结束佣金
  2046. $data["qudao"]=round($qudao,2);//渠道
  2047. $data["list"]=$list;
  2048. return $data;
  2049. }
  2050. /*
  2051. * 越攒越多统计
  2052. * */
  2053. public function get_com_all($member_id,$where){
  2054. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  2055. ->field("type,number,status,commission_type,create_time,uid,title,order_sn,type_shop");
  2056. $order = "create_time desc";
  2057. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  2058. $query = $query->where(['commission_type'=>$where['commission_type']]);
  2059. }else{
  2060. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2061. }
  2062. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2063. $query = $query->whereTime("create_time",$where['order']);
  2064. }
  2065. $query = $query->where(['status'=>1]);
  2066. $list= $query->order($order)->select()->toArray();
  2067. $dangqian_yj=Db::name("user")->where("uid",$member_id)->value("brokerage_price");
  2068. $dlfee=0;
  2069. $xiaofei=0;
  2070. $tuiguang=0;
  2071. $kuadian=0;
  2072. $xiaqu=0;
  2073. $weijiesuan=0;
  2074. $ptjl=0;
  2075. $qudao=0;
  2076. foreach ($list as &$v){
  2077. // $count_yj=$v["number"]+$count_yj;
  2078. if ($v["commission_type"]==1){
  2079. $dlfee+=$v["number"];
  2080. }
  2081. if ($v["commission_type"]==2){
  2082. $xiaofei+=$v["number"];
  2083. }
  2084. if ($v["commission_type"]==3){
  2085. $tuiguang+=$v["number"];
  2086. }
  2087. if ($v["commission_type"]==4){
  2088. $xiaqu+=$v["number"];
  2089. $v['title'] = '辖区获取佣金';
  2090. }
  2091. if ($v["commission_type"]==7){
  2092. $kuadian+=$v["number"];
  2093. $v['title'] = '跨店获取佣金';
  2094. }
  2095. if ($v["commission_type"]==8){
  2096. $ptjl+=$v["number"];
  2097. $v['title'] = '平台奖励佣金';
  2098. }
  2099. if ($v["commission_type"]==9){
  2100. $qudao+=$v["number"];
  2101. $v['title'] = '渠道商奖励佣金';
  2102. }
  2103. if ($v["commission_type"]==10){
  2104. $tuiguang+=$v["number"];
  2105. $v['title'] = '推荐商户奖励佣金';
  2106. }
  2107. // if ($v['type_shop'] >0){
  2108. // $qudao+=$v['number'];
  2109. // $v['title'] = '第三方订单获取佣金';
  2110. // }
  2111. }
  2112. $data["count_yj"]=round($dangqian_yj,2);//当前佣金
  2113. $data["dlfee"]=round($dlfee,2); //代理非
  2114. $data["xiaofei"]=round($xiaofei,2); //消费佣金
  2115. $data["tuiguang"]= round($tuiguang,2); //推广佣金
  2116. $data["xiaqu"]=round($xiaqu,2); //辖区佣金
  2117. $data["weijiesuan"]=round($weijiesuan,2);//未结束佣金
  2118. $data["kuadian"]=round($kuadian,2); //跨店
  2119. $data["ptjl"]=round($ptjl,2); //平台奖励佣金
  2120. $data["qudao"]=round($qudao,2); //渠道
  2121. return $data;
  2122. }
  2123. /*
  2124. * 越攒越多列表
  2125. * */
  2126. public function get_com_list($member_id,$where){
  2127. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  2128. ->field("type,number,status,commission_type,create_time,uid,title,order_sn,type_shop");
  2129. $order = "create_time desc";
  2130. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  2131. $query = $query->where(['commission_type'=>$where['commission_type']]);
  2132. }else{
  2133. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2134. }
  2135. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2136. $query = $query->whereTime("create_time",$where['order']);
  2137. }
  2138. $page = $where['page'] ?? 1;
  2139. $limit = $where['limit'] ?? 10;
  2140. $query = $query->where(['status'=>1]);
  2141. $list= $query->page($page,$limit)->order($order)->select()->toArray();
  2142. $data["list"]=$list;
  2143. return $data;
  2144. }
  2145. /**
  2146. * 获取推广列表
  2147. */
  2148. public function get_tuiguang_list($member_id,$where = []){
  2149. $query = Db::name("user_bill")
  2150. ->alias("ul")
  2151. ->where(["ul.type"=>"commission",'ul.uid'=>$member_id])
  2152. ->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");
  2153. if(isset($where['type']) && in_array($where['type'],[0,1])){
  2154. $query = $query->where(['ul.source'=>$where['type']]);
  2155. }
  2156. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2157. $query = $query->whereTime("create_time",$where['order']);
  2158. }
  2159. $page = $where['page'] ?? 1;
  2160. $limit = $where['limit'] ?? 10;
  2161. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2162. $query = $query ->where("status",'>=',0);
  2163. //不显示红积分的
  2164. $query = $query ->where("is_red_brokerage",'=',0);
  2165. $list= $query->order("create_time desc")->page($page,$limit)->select()->toArray();
  2166. foreach ($list as &$v){
  2167. // $v["create_time"]=date("Y-m-d", $v["create_time"]);
  2168. //0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么
  2169. if($v['type_shop'] == 0){
  2170. if($v['source'] == 0){
  2171. if($v['commission_type'] == 9){
  2172. $this -> getContent('channel_order',$v['order_sn'],'储蓄保',$v['status'],$v['commission_type'],$v);
  2173. }elseif($v['commission_type'] == 10){
  2174. $this -> getContent('merchant_annual_cost_order',$v['order_sn'],'储蓄保',$v['status'],$v['commission_type'],$v);
  2175. }else{
  2176. $this -> getContent('store_order',$v['order_sn'],'储蓄保',$v['status'],$v['commission_type'],$v,$v['create_time']);
  2177. }
  2178. }else{
  2179. $uid=Db::name("store_order")->where("order_sn",$v["order_sn"])->value("uid");
  2180. $v["nickname"]=$this -> getUserNickname($uid);
  2181. $v['content'] = '用户'.$v['nickname'].'到店消费,帮您攒金';
  2182. $v['xiadan'] = $v['create_time'] ?? '';
  2183. $v['jiesuan'] = $v['create_time'];
  2184. }
  2185. }elseif ($v['type_shop'] == '1'){
  2186. $this -> getContent('order_pdd',$v['order_sn'],'拼多多',$v['status'],$v['commission_type'],$v);
  2187. }elseif ($v['type_shop'] == '2'){
  2188. $this -> getContent('order_vip',$v['order_sn'],'唯品会',$v['status'],$v['commission_type'],$v);
  2189. }elseif ($v['type_shop'] == '3'){
  2190. $this -> getContent('order_su',$v['order_sn'],'苏宁易购',$v['status'],$v['commission_type'],$v);
  2191. }
  2192. elseif ($v['type_shop'] == '4'){
  2193. // $uid = Db::name('order_jd')->where("order_sn",$v["order_sn"])->value("uid");
  2194. // $v["nickname"]=$this -> getUserNickname($uid);
  2195. $v["nickname"]='';
  2196. $v['content'] = $v['nickname'].'在网易考拉消费,帮您攒金';
  2197. $v['xiadan'] = '';
  2198. $v['jiesuan'] = '';
  2199. }elseif ($v['type_shop'] == '5'){
  2200. $this -> getContent('order_tb',$v['order_sn'],'淘宝',$v['status'],$v['commission_type'],$v);
  2201. }elseif ($v['type_shop'] == '6'){
  2202. $this -> getContent('order_jd',$v['order_sn'],'京东',$v['status'],$v['commission_type'],$v);
  2203. }elseif ($v['type_shop'] == '7'){
  2204. $this -> getContent('order_tb',$v['order_sn'],'饿了么',$v['status'],$v['commission_type'],$v);
  2205. }
  2206. if($v['commission_type'] == 7){
  2207. $v['mark'] = '【跨店】'.$v['mark'];
  2208. }
  2209. $v['number'] =set_price_rtrim($v['number']);
  2210. }
  2211. return $list;
  2212. }
  2213. public function getUserNickname($uid){
  2214. return Db::name("user")->where("uid", $uid)->value("nickname");
  2215. }
  2216. public function getContent($table,$order_sn,$title,$status,$commission_type,&$v,$create_time=null){
  2217. $yugu = '';
  2218. if($status == 0){
  2219. $yugu = "【预估】";
  2220. if($commission_type == 7){
  2221. $yugu = "【跨店预估】";
  2222. }
  2223. }
  2224. switch ($table){
  2225. case 'store_order':
  2226. $res = Db::name($table)->where("order_sn",$order_sn)->field('uid,create_time,pay_time')->find();
  2227. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2228. $v['content'] = $yugu.$v['nickname'].'在'.$title.'消费,帮您攒金';
  2229. break;
  2230. case 'channel_order':
  2231. $res = Db::name($table)->where("order_no",$order_sn)->field('uid,create_time,pay_time')->find();
  2232. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2233. $v['content'] = $v['nickname'].'成为渠道商,帮您攒金';
  2234. $res['bill_end_time'] = strtotime($res['create_time']);
  2235. break;
  2236. case 'merchant_annual_cost_order':
  2237. $res = Db::name($table)->where("order_no",$order_sn)->field('uid,create_time,pay_time')->find();
  2238. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2239. $v['content'] = $v['nickname'].'成为商户,帮您攒金';
  2240. $res['bill_end_time'] = strtotime($res['create_time']);
  2241. break;
  2242. default:
  2243. $res = Db::name($table)->where("order_sn",$order_sn)->field('uid,create_time,bill_end_time,pay_time')->find();
  2244. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2245. $v['content'] = $yugu.$v['nickname'].'在'.$title.'消费,帮您攒金';
  2246. }
  2247. // $v['xiadan'] = $res['create_time'] ?? $create_time;
  2248. $v['xiadan'] = isset($res['pay_time'])?$res['pay_time']:$create_time;
  2249. $v['jiesuan'] = $v['xiadan'];
  2250. // if (empty($res['bill_end_time']) && empty($res['create_time'])){
  2251. // $v['jiesuan'] = $create_time;
  2252. // }else{
  2253. // $v['jiesuan'] = date('Y-m-d H:i:s',$res['bill_end_time']??strtotime("+10 day", strtotime($res['create_time'])));
  2254. // }
  2255. }
  2256. /**
  2257. * 获取订单数
  2258. */
  2259. public function get_tuiguang_order($member_id){
  2260. $where=["ul.type"=>"commission","ul.status"=>1,'ul.uid'=>$member_id];
  2261. $list=Db::name("user_bill")
  2262. ->alias("ul")
  2263. // ->join("user u","u.uid=ul.uid")
  2264. ->where("commission_type","<>",5)
  2265. ->where($where)
  2266. ->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")
  2267. ->select();
  2268. $num=0;
  2269. $count=0;
  2270. foreach ($list as &$v){
  2271. $num++;
  2272. // $v["create_time"]=date("Y-m-d", $v["create_time"]);
  2273. $uid=Db::name("store_order")->where("order_sn",$v["order_sn"])->value("uid");
  2274. $v["nickname"]=Db::name("user")->where("uid", $uid)->value("nickname");
  2275. $count+=$v["number"];
  2276. }
  2277. return ["num"=>$num,"count"=>round($count,2),"list"=>$list];
  2278. }
  2279. public function get_yanglao($member_id){
  2280. $data = Db::name("user")
  2281. ->where("uid",$member_id)
  2282. ->field("wechat_user_id,card_id,ali_user_id,annuity_frozen,annuity_num,annuity,create_time,birthday,birthday60,card_number,annuity_yiqu,pay_price")
  2283. ->find();
  2284. // $data['annuity'] = 0;
  2285. $certification = Db::name("user_certification")->where("uid",$member_id)->find();
  2286. $data['can_withdraw'] = 0;
  2287. if (!$certification || $certification["status"] !=1 || !$certification["user_card"]){
  2288. $data["birthday60"] = "未实名认证";
  2289. $data['is_certification'] = 0;
  2290. } else {
  2291. // try {
  2292. // $checkAmount = $this->checkAmount($certification);
  2293. // if ($checkAmount['code'] == 0) {
  2294. // $data['annuity'] = $checkAmount['extendData']['amount'];
  2295. // }
  2296. // } catch (\Throwable $e) {
  2297. // Log::info('getyanglaojin' . $e->getMessage());
  2298. // }
  2299. $data['is_certification'] = 1;
  2300. $birth_data = substr($certification["user_card"], 6, 8);
  2301. // $birth = strtotime(substr($certification["user_card"], 6, 8));
  2302. $old_age = $this->getSex($certification["user_card"])?60:55;
  2303. // $age = $this->howOld($birth);
  2304. $age=$this->calculateAge($birth_data);
  2305. if ($age < $old_age) {
  2306. // $yes = $old_age - $age;
  2307. // $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("+" . $yes . " year"));
  2308. }
  2309. if ($age == $old_age) {
  2310. $data['can_withdraw'] = 1;
  2311. // $data["birthday60"] = date("Y-m-d", $birth);
  2312. }
  2313. if ($age > $old_age) {
  2314. $data['can_withdraw'] = 1;
  2315. // $yes = $age - $old_age;
  2316. // $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("-" . $yes . " year"));
  2317. }
  2318. //收益余额
  2319. $data['annuity_num'] = 123;
  2320. $data['annuity_yiqu'] = 123;
  2321. $data["birthday60"] = $this->getFutureBirthday($birth_data,$old_age);
  2322. }
  2323. $order_merchant_price= OrderMerchant::getInstance()->where('paid', 1)
  2324. ->where(function ($query) use ($data) {
  2325. $query->where('pay_user_id', $data['wechat_user_id'])
  2326. ->whereOr('pay_user_id', $data['ali_user_id']);
  2327. })
  2328. ->sum('money');
  2329. //加上线下消费的
  2330. $data['pay_price'] = bcadd($data['pay_price'],$order_merchant_price,2);
  2331. $data["yinghang"] = "中信公证处消费养老金账户";
  2332. // $data["yinghang"]='https://app.bjtdba.com/uploads/def/20201021/8cb66944101287b8ac9c9b9fb1b13a79.png';
  2333. $data["add_up"] = 0.00;
  2334. return $data;
  2335. }
  2336. function calculateAge($birthDate) {
  2337. $today = new \DateTime();
  2338. $diff = $today->diff(new \DateTime($birthDate));
  2339. return $diff->y;
  2340. }
  2341. function getFutureBirthday($birthDate, $years) {
  2342. $date = new \DateTime($birthDate);
  2343. $date->modify("+$years years");
  2344. return $date->format('Y-m-d');
  2345. }
  2346. public function getSex($cid){
  2347. //根据身份证号,自动返回性别
  2348. $sexint = (int)substr($cid,16,1);
  2349. return $sexint % 2 === 0 ? false : true;
  2350. }
  2351. /**
  2352. * 根据时间戳计算年龄
  2353. * @param $birth
  2354. * @return mixed
  2355. */
  2356. public function howOld($birth) {
  2357. list($birthYear, $birthMonth, $birthDay) = explode('-', date('Y-m-d', $birth));
  2358. list($currentYear, $currentMonth, $currentDay) = explode('-', date('Y-m-d'));
  2359. $age = $currentYear - $birthYear - 1;
  2360. if($currentMonth > $birthMonth || $currentMonth == $birthMonth && $currentDay >= $birthDay)
  2361. $age++;
  2362. return $age;
  2363. }
  2364. public function yanglaolog($where,$page=1, $limit=10,$month=''){
  2365. $where1 = [];
  2366. if(!empty($where)){
  2367. foreach($where as $key => $value){
  2368. $where1['a.'.$key] = $value;
  2369. }
  2370. }
  2371. $query=Db::name("user_bill")
  2372. ->alias('a')
  2373. ->join('Merchant b', 'a.mer_id = b.mer_id','left')
  2374. ->field('a.*,b.mer_name,b.mer_avatar')
  2375. ->where($where1)
  2376. ->when($month!='',function ($q) use ($month){
  2377. $q->whereLike('a.create_time',$month.'%');
  2378. });
  2379. $query -> where('a.status','<>','-1');
  2380. $query_sql1 = clone $query;
  2381. $query_sql2 = clone $query;
  2382. $query_sql3 = clone $query;
  2383. $count = $query->count();
  2384. $list = $query->page($page,$limit)->order("a.bill_id desc")->select()
  2385. ->each(function($item){
  2386. if($item['source'] == 0 && $item['type_shop'] == 0){
  2387. $item['product'] = json_decode(Db::name("store_order")
  2388. -> alias('a')
  2389. -> join('store_order_product b','a.order_id = b.order_id','left')
  2390. -> where(["a.order_sn"=>$item['order_sn']])
  2391. -> value('b.cart_info'),true);
  2392. if(empty($item['product'])){
  2393. $item['product']=[
  2394. 'product'=>[
  2395. 'image'=>'http://app.bjtdba.com/uploads/def/20210326/e91a34629fefb65170071c2d45a623ac.jpg',
  2396. 'store_name'=>'商家年费'
  2397. ]
  2398. ];
  2399. }
  2400. }
  2401. return $item;
  2402. });
  2403. $yugu=$query_sql1->sum('number');
  2404. $yijiesuan=$query_sql1->where('a.status',1)->sum('number');
  2405. $weijiesuan=$yugu-$yijiesuan;
  2406. return compact('count','list','yugu','yijiesuan','weijiesuan');
  2407. }
  2408. /*养老金详情*/
  2409. public function yanglaoDetail($where=[],$field='*'){
  2410. $query=Db::name("user_bill")->where($where)->field($field)->find();
  2411. return $query;
  2412. }
  2413. /*提现记录 type 1佣金 2养老金*/
  2414. public function withdrawal($where){
  2415. $data=Db::name("user_extract")->where($where)->order('extract_id','desc')->select();
  2416. if(!$data->isEmpty()){
  2417. $data=$data->toArray();
  2418. }
  2419. foreach ($data as $k=>&$v){
  2420. if($v['withdrawal_type']==2){
  2421. // $name=Db::name('merchant')->where('mer_id',$v['mer_id'])->value('mer_name');
  2422. $v['title']='佣金提现';
  2423. }else if($v['withdrawal_type']==3){
  2424. if($v['extract_type']==1){
  2425. $tltle='微信';
  2426. $v['title']='提现到'.$tltle;
  2427. }else if($v['extract_type']==3){
  2428. $tltle='银行卡';
  2429. $v['title']='提现到'.$tltle;
  2430. }else if($v['extract_type']==4){
  2431. $v['title']='人工减少佣金';
  2432. }
  2433. }else{
  2434. $v['title']='储蓄保-佣金提现';
  2435. }
  2436. if($v['bank_info']!=''){
  2437. $bank_info=json_decode($v['bank_info'],true);
  2438. }
  2439. $v['extract_price']=set_price_rtrim($v['extract_price']);
  2440. $v['bank_name']=isset($bank_info['bank_name'])?$bank_info['bank_name']:'';
  2441. }
  2442. return $data;
  2443. }
  2444. /*提现记录 type 1佣金 2养老金*/
  2445. public function withdrawal_user($where){
  2446. $data=Db::name("user_extract")->where($where)->where('mer_id is null')->order('extract_id','desc')->select();
  2447. if(!$data->isEmpty()){
  2448. $data=$data->toArray();
  2449. }
  2450. foreach ($data as $k=>&$v){
  2451. if($v['withdrawal_type']==2){
  2452. // $name=Db::name('merchant')->where('mer_id',$v['mer_id'])->value('mer_name');
  2453. $v['title']='佣金提现';
  2454. }else if($v['withdrawal_type']==3){
  2455. if($v['extract_type']==1){
  2456. $tltle='微信';
  2457. $v['title']='提现到'.$tltle;
  2458. }else if($v['extract_type']==3){
  2459. $tltle='银行卡';
  2460. $v['title']='提现到'.$tltle;
  2461. }else if($v['extract_type']==4){
  2462. $v['title']='人工减少佣金';
  2463. }
  2464. }else{
  2465. $v['title']='储蓄保-佣金提现';
  2466. }
  2467. if($v['bank_info']!=''){
  2468. $bank_info=json_decode($v['bank_info'],true);
  2469. }
  2470. $v['extract_price']=set_price_rtrim($v['extract_price']);
  2471. $v['bank_name']=isset($bank_info['bank_name'])?$bank_info['bank_name']:'';
  2472. }
  2473. return $data;
  2474. }
  2475. /*
  2476. * 提现详情
  2477. *@author cabbage
  2478. *@date 2020-10-31
  2479. * */
  2480. public function withdrawalDetail($id,$uid){
  2481. $data= Db::name("user_extract")->where(["uid"=>$uid,'extract_id'=>$id,"type"=>2])->find();
  2482. return $data;
  2483. }
  2484. /*
  2485. * 修改用户推广人id
  2486. *@author cabbage
  2487. *@date 2020-10-31
  2488. * */
  2489. public function update_spread($uid,$spread_account){
  2490. //推荐人信息
  2491. $spread = Db::name("user")->where('account',$spread_account)->field("uid")->find();
  2492. //被推荐人信息
  2493. $identity=Db::name("user")->where('uid',$uid)->field("identity,spread_uid")->find();
  2494. $user_identity_log=Db::name("user_identity_log")->where(["link_id"=>$uid])->find();
  2495. if($spread){
  2496. try{
  2497. $data= Db::name("user")->where(["uid"=>$uid])->update(['spread_uid'=>$spread['uid']]);
  2498. Db::name("merchant")->where(["uid"=>$uid])->update(['recommender'=>$spread['uid']]);
  2499. if ($user_identity_log){
  2500. Db::name("user_identity_log")->where(["id"=>$user_identity_log["id"]])->update(['uid'=>$spread['uid']]);
  2501. }else{
  2502. Db::name("user_identity_log")->insert(['uid'=>$spread['uid'],"identity"=>$identity["identity"],"create_time"=>date("Y-m-d H:i:s"),"link_id"=>$uid]);
  2503. }
  2504. Db::name("user")->where('account',$spread_account)->inc("spread_count",1)->update();
  2505. if ($identity["spread_uid"]){
  2506. Db::name("user")->where('uid',$identity["spread_uid"])->dec("spread_count")->update();
  2507. }
  2508. return $data;
  2509. }catch (Exception $e) {
  2510. Db::rollback();
  2511. }
  2512. }else{
  2513. return false;
  2514. }
  2515. }
  2516. /*获取协议列表*/
  2517. public function getXieYi(){
  2518. $data= Db::name("user_agreement")->where(["status"=>1])->select();
  2519. return $data;
  2520. }
  2521. /*积分记录*/
  2522. public function socreList($uid,$page,$limit){
  2523. $data = Db::name("user_signinreward_record")
  2524. ->where(['member_id'=>$uid])
  2525. ->field("reward_socre,addtime")
  2526. ->page($page,$limit)
  2527. ->order("addtime desc")
  2528. ->select()->toArray();
  2529. foreach ($data as $k => $v) {
  2530. $data[$k]['addtime'] = date("y-m-d H:i:s",$v['addtime']);
  2531. $data[$k]['pm'] = 1 ;
  2532. $data[$k]['mark'] = '签到获得' ;
  2533. }
  2534. $result['list'] = $data;
  2535. $result['count'] = Db::name("user_signinreward_record")->where(['member_id'=>$uid])->count();
  2536. $result['total_socre'] = Db::name("user_signinreward_record")->where(['member_id'=>$uid])->sum("reward_socre");
  2537. $result['is_use'] = 0 ;
  2538. $result['is_pass'] = 0 ;
  2539. return $result;
  2540. }
  2541. /*修改用户信息*/
  2542. public function updateUser($uid,$data,$data2=[]){
  2543. $data = Db::name("user")->where(['uid'=>$uid])->update($data);
  2544. if ($data2){
  2545. $ck= Db::name("user_account")->where(["uid"=>$uid,"type"=>$data["type"]])->find();
  2546. if ($ck){
  2547. $data= Db::name("user_account")->where(["id"=>$ck["id"]])->update($data2);
  2548. }else{
  2549. $data= Db::name("user_account")->insert($data2);
  2550. }
  2551. }
  2552. return $data;
  2553. }
  2554. /*获取用户信息*/
  2555. public function getUser($uid,$data){
  2556. $user = Db::name("user")->where(['uid' => $uid])->field($data)->find();
  2557. $data = Db::name("user_account")->where(['uid' => $uid])->select()->toArray();
  2558. $types = array_column($data, 'type');
  2559. if (!in_array('1', $types) && $user['wechat_user_id']) {
  2560. $data[] = ['id' => 0, 'avater' => '', 'nickname' => null, 'type' => 1, 'uid' => $uid];
  2561. Db::name("user_account")->insert(['type' => 1, 'uid' => $uid]);
  2562. }
  2563. if (!in_array('2', $types) && $user['ali_user_id']) {
  2564. $data[] = ['id' => 0, 'avater' => '', 'nickname' => null, 'type' => 2, 'uid' => $uid];
  2565. Db::name("user_account")->insert(['type' => 2, 'uid' => $uid]);
  2566. }
  2567. return $data;
  2568. }
  2569. public function getAccount($uid)
  2570. {
  2571. $res=Db::name('user_extract_openid')->where('uid',$uid)->value('openid');
  2572. if($res){
  2573. $arr[]=array(
  2574. 'id'=>'1',
  2575. 'type'=>'1',
  2576. 'uid'=>$uid,
  2577. 'nickname'=>'',
  2578. 'avater'=>'',
  2579. );
  2580. }
  2581. $res = Db::name('user') -> where('uid',$uid) -> value('ali_user_id');
  2582. if($res && $res != '0' && $res != ''){
  2583. $arr[]=array(
  2584. 'id'=>'2',
  2585. 'type'=>'2',
  2586. 'uid'=>$uid,
  2587. 'nickname'=>'',
  2588. 'avater'=>'',
  2589. );
  2590. }
  2591. return isset($arr)?$arr:[];
  2592. }
  2593. /**
  2594. * 支付宝授权登录
  2595. * 文档:https://opendocs.alipay.com/open/218/105327
  2596. */
  2597. public function aliSign(){
  2598. $aop = new AopClient;
  2599. $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
  2600. $aop->appId = "2021001197654668";
  2601. $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==';
  2602. $aop->format = "json";
  2603. $aop->charset = "UTF-8";
  2604. $aop->signType = "RSA2";
  2605. $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  2606. $data = [
  2607. 'apiname'=>'com.alipay.account.auth',
  2608. 'method'=>'alipay.open.auth.sdk.code.get',
  2609. 'app_id'=>'2021001197654668',
  2610. 'app_name'=>'mc',
  2611. 'biz_type'=>'openservice',
  2612. 'pid'=>'2088931546284482', //合作伙伴身份(PID):
  2613. 'product_id'=>'APP_FAST_LOGIN',
  2614. 'scope'=>'kuaijie',
  2615. 'target_id'=>"ALI".time().rand(10000,99999),
  2616. 'auth_type'=>'AUTHACCOUNT',
  2617. 'sign_type'=>'RSA2'
  2618. ];
  2619. $sign = $aop->generateSign($data,"RSA2");
  2620. $paramStr = '';
  2621. foreach ($data as $key => $param) {
  2622. $paramStr .= "{$key}={$param}&";
  2623. }
  2624. $paramStr = $paramStr.'sign='.urlencode($sign);
  2625. return $paramStr;
  2626. }
  2627. /*
  2628. * 支付宝登录验证
  2629. * $userId 支付宝用户唯一id
  2630. * */
  2631. public function aliCheck($userId){
  2632. $user = Db::name("user")->where(['ali_user_id'=>$userId])->find();
  2633. //判断是否是第一次登录
  2634. if($user){
  2635. //成功登录业务逻辑
  2636. if (!$user['account']) {
  2637. return ['code' => 400, 'msg' => '请绑定手机号'];
  2638. } else {
  2639. return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
  2640. }
  2641. }else{
  2642. return ['code' => 400, 'msg' => '请绑定手机号'];
  2643. }
  2644. }
  2645. /*微信信息获取*/
  2646. public function getWechat(){
  2647. $data['appid'] = "wxbf753066ac8686ba";
  2648. $data['appsecret'] = "68943fc124568c4ab4c3f089b7cdf2aa";
  2649. return $data;
  2650. }
  2651. /*微信登录验证
  2652. $openid 微信openid
  2653. */
  2654. public function wechatCheck($openid){
  2655. $user = Db::name("user")->where(['wechat_user_id'=>$openid])->find();
  2656. //判断是否是第一次登录
  2657. if($user){
  2658. //成功登录业务逻辑
  2659. if (!$user['account']) {
  2660. return ['code' => 400, 'msg' => '请绑定手机号'];
  2661. } else {
  2662. return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
  2663. }
  2664. }else{
  2665. return ['code' => 400, 'msg' => '请绑定手机号'];
  2666. }
  2667. }
  2668. /**
  2669. * 微信登录验证一壶茶
  2670. * @param $openid
  2671. * @return array
  2672. * @throws DataNotFoundException
  2673. * @throws DbException
  2674. * @throws ModelNotFoundException
  2675. */
  2676. public function wechatCheckYhc($openid){
  2677. $enterprise_user = Db::name("enterprise_user")->where(['openid'=>$openid])->find();
  2678. //判断是否是第一次登录,成功登录业务逻辑
  2679. if($enterprise_user && $enterprise_user['uid']!=0){
  2680. $user = Db::name("user")->where(['uid'=>$enterprise_user['uid']])->find();
  2681. return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
  2682. }
  2683. return ['code' => 400, 'msg' => '请绑定手机号'];
  2684. }
  2685. /*微信支付宝绑定*/
  2686. public function thirdBinding(string $phone, ?string $pwd, $user_type = 'APP',$third_user_id='',$type=0,$url)
  2687. {
  2688. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  2689. $user = $this->accountByUser($phone);
  2690. if($user){
  2691. $data = [
  2692. 'last_ip' => app('request')->ip(),
  2693. ];
  2694. }else{
  2695. $data = [
  2696. 'account' => $phone,
  2697. 'pwd' => $pwd,
  2698. 'nickname' => '用户' . substr($phone, 7, 4),
  2699. 'avatar' => $url.'/uploads/logo.jpg',
  2700. 'phone' => $phone,
  2701. 'last_ip' => app('request')->ip(),
  2702. ];
  2703. }
  2704. if($type ==1){
  2705. if(isset($user->wechat_user_id) && $user->wechat_user_id){return true;}//这里可能有问题
  2706. $data['wechat_user_id'] = $third_user_id;
  2707. }elseif($type ==2){
  2708. if(isset($user->ali_user_id) && $user->ali_user_id){return true;}
  2709. // if($user->ali_user_id){return true;}
  2710. $data['ali_user_id'] = $third_user_id;
  2711. }
  2712. if(!$user){
  2713. return $this->create($user_type, $data);
  2714. }else{
  2715. Db::name("user")->where(['account'=>$phone])->update($data);
  2716. return $user;
  2717. }
  2718. }
  2719. public function getTokenByCode($authorization_code,$info=false,$type=123)
  2720. {
  2721. try {
  2722. $aop = new AopClient();
  2723. $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
  2724. if($type=='h5'){
  2725. $aop->appId = '2021001197698727';
  2726. $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=';
  2727. $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  2728. }else if ($type == 'h5pay'){
  2729. $aop->appId = '2021003191617008';
  2730. $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==';
  2731. $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuUb+0sJSNXjWiG0VJIPzn55+18af/fubYMpRLlreu34ewMgLx1zpCNpB3wrA+dylfWPMAm8PzvKnakByB+VJ/LMNhWHmF8Qkdo4astAikjlI4TMQCK/G384NzrtjHR4DGCDM5CMVt1xw5noF7kNBMYIvgDfhMCYmygdlIjuVdIlVEoQKOsT0RaNMleES0aZvbjvBGkGM0dsetqUExSjid9BF1NAO2ET+J3XMxCtMgCUVmFUvxsCKe6Rapa1/Lk3rzIeG6CRpoabuYfPM9E+3y3f3luSOMXLfH9lOSW1RA8qrF+Ms1RZv8gmzUnbyrPLmmZPmmN/Qs6DGzDVg73fpSwIDAQAB';
  2732. }else{
  2733. $aop->appId = '2021001197654668';
  2734. $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==';
  2735. $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  2736. }
  2737. $aop->apiVersion = '1.0';
  2738. $aop->signType = 'RSA2';
  2739. $aop->postCharset='UTF-8';
  2740. $aop->format='json';
  2741. $request = new AlipaySystemOauthTokenRequest ();
  2742. $request->setGrantType("authorization_code");
  2743. $request->setCode($authorization_code);
  2744. $result = $aop->execute($request);
  2745. if (isset($result->alipay_system_oauth_token_response->user_id)) {
  2746. $return['user_id'] = $result->alipay_system_oauth_token_response->user_id;
  2747. $return['msg'] = $result->alipay_system_oauth_token_response->access_token;
  2748. $access_token=$return['msg'] ;
  2749. } else {
  2750. $return['code'] = $result->error_response->code;
  2751. $return['msg'] = $result->error_response->sub_msg;
  2752. return $return;
  2753. }
  2754. if ($info){
  2755. $request = new AlipayUserInfoShareRequest();
  2756. $result = $aop->execute ( $request ,$access_token);
  2757. $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
  2758. Db::name('log')->insert(['data'=>\GuzzleHttp\json_encode($responseNode)]);
  2759. $resultCode = $result->$responseNode->code;
  2760. Db::name('log')->insert(['data'=>$resultCode]);
  2761. $userData=json_decode(json_encode($result->$responseNode),true);
  2762. if(!empty($resultCode)&&$resultCode == 10000){
  2763. return $userData;
  2764. }
  2765. }
  2766. return $return;
  2767. } catch (\Throwable $w) {
  2768. Db::name('log')->insert(['data'=>json_encode($w->getMessage())]);
  2769. return $w->getMessage();
  2770. }
  2771. }
  2772. /**
  2773. * @param $id
  2774. * @return Form
  2775. * @throws DataNotFoundException
  2776. * @throws DbException
  2777. * @throws ModelNotFoundException
  2778. * @throws FormBuilderException
  2779. * @author xaboy
  2780. * @day 2020-05-07
  2781. */
  2782. public function changePassForm($id)
  2783. {
  2784. return Elm::createForm(Route::buildUrl('systemUserChangePass', compact('id'))->build(), [
  2785. Elm::input('pass_word', '用户密码')->required()->value("")
  2786. ])->setTitle('修改用户密码');
  2787. }
  2788. public function changePass($uid,$password)
  2789. {
  2790. $pass_word=$this->encodePassword($password);
  2791. $data= Db::name("user")->where(["uid"=>$uid])->update(['pwd'=>$pass_word]);
  2792. if($data){
  2793. return $data;
  2794. }else{
  2795. return false;
  2796. }
  2797. }
  2798. public function wechatGetTokenBycode()
  2799. {
  2800. }
  2801. public function createUserNumber($uid){
  2802. $t = "C";
  2803. $number = '000000000';
  2804. if($uid <= 10){
  2805. $uid = $uid . 'X';
  2806. }
  2807. $strlen = mb_strlen($uid);//id长度
  2808. $newNumber = $t.substr_replace($number,$uid,-$strlen);
  2809. $newNumber = str_replace('4','R',$newNumber);
  2810. Db::name('user') -> where(["uid"=>$uid])->update(['user_number'=>$newNumber]);
  2811. }
  2812. /**
  2813. * @param int $uid 用户ID
  2814. * @param string $score 积分
  2815. * @param int $status 积分状态
  2816. * @param string $mark 备注
  2817. * @param string $has_qian 连续签到天数
  2818. * @param string $today_signintime 签到时间
  2819. * @param int $order_id 订单ID
  2820. * @param int $pm 1-收入。2-支出
  2821. * @param string $order_type
  2822. * @throws DbException
  2823. */
  2824. public function sign_add($uid, $score, $status, $mark, $has_qian = '', $today_signintime = '', $order_id = 0, $pm = 1, $order_type = '',$type='',$settlement_time = '')
  2825. {
  2826. if(!in_array($type,[1,2])){
  2827. // 其他情况都直接返回,因为目前只有365专区购买才可以获得
  2828. return false;
  2829. }
  2830. $ins_data['uid'] = $uid;
  2831. $ins_data['continuity_day'] = $has_qian;
  2832. $ins_data['reward_socre'] = $score;
  2833. $ins_data['source_uid'] = $uid;
  2834. $ins_data['signin_time'] = $today_signintime;
  2835. $ins_data['addtime'] = time();
  2836. $ins_data['status'] = $status;
  2837. $ins_data['mark'] = $mark;
  2838. $ins_data['source_type'] = $type;
  2839. $ins_data['settlement_time'] = $settlement_time;// 结算时间 真正到了结算时间会结算
  2840. $ins_data['order_id'] = $order_id;
  2841. $ins_data['pm'] = $pm;
  2842. $ins_data['order_type'] = $order_type;
  2843. $ins_data['surplus'] = 0;
  2844. Db::name('user_sign_score')->insertGetId($ins_data);
  2845. if($pm == 1 && $status == 1){
  2846. Db::name('user')->where('uid',$uid)->inc('score', $score)->update();
  2847. }
  2848. if($pm == 2){
  2849. Db::name('user')->where('uid', $uid)->dec('score', $score)->update();
  2850. }
  2851. }
  2852. public function gold_add($uid,$gold,$mark,$pm=1){
  2853. $ins['uid'] = $uid;
  2854. $ins['gold'] = $gold;
  2855. $ins['mark'] = $mark;
  2856. $ins['time'] = time();
  2857. $ins['pm'] = $pm;
  2858. $id = Db::name('user_gold_log')->insertGetId($ins);
  2859. if($pm == 1){
  2860. Db::name('user_gold')->where('uid',$uid)->inc('now_gold', $gold)->inc('cumulative', $gold)->update();
  2861. }else{
  2862. Db::name('user_gold') -> where('uid',$uid) -> dec('now_gold', $gold)->update();
  2863. }
  2864. $surplus = Db::name('user_gold')->where('uid',$uid)->value('now_gold');
  2865. Db::name('user_gold_log') -> where('id',$id) -> update(['surplus'=>$surplus]);
  2866. }
  2867. function get_level_list(){
  2868. try {
  2869. $tokenInfo = (request()->tokenInfo());
  2870. if(isset($tokenInfo->jti[1]) && $tokenInfo->jti[1]=='admin') {
  2871. $admin_id = request()->adminId();
  2872. $roles_str = Db::name('system_admin')->where('admin_id', $admin_id)->value('roles');
  2873. $phone_count = Db::name('system_role')->whereIn('role_id', $roles_str)->where("phone !=''")->count();
  2874. if ($phone_count) {
  2875. return true;
  2876. }
  2877. }
  2878. }catch (Exception $e) {
  2879. return false;
  2880. }
  2881. return false;
  2882. // $phone_data=Db::name('system_role')->whereIn('role_id',$roles_str)->where("phone !=''")->group("phone")->column('phone');
  2883. // if($phone_data){
  2884. // $uid_data = Db::name('user')->whereIn('phone', $phone_data)->column('uid');
  2885. // if($uid_data){
  2886. // $uids=$this->level_list($uid_data,0);
  2887. // }
  2888. // }
  2889. // }
  2890. // return isset($uids)?$uids:[];
  2891. }
  2892. // function level_list($uid_data,$i){
  2893. // $i++;
  2894. // $uid = Db::name('user')->whereIn('level_id', $uid_data)->column('uid');
  2895. // if($uid && $i<9){
  2896. // $uid_data=array_merge($uid_data,$uid);
  2897. // return $this->level_list($uid_data,$i);
  2898. // }else{
  2899. // return $uid_data;
  2900. // }
  2901. // }
  2902. public function sign_yhc_add($uid,$mer_id,$score,$mark,$order_id=0,$pm=1,$use_uid=0){
  2903. $ins_data['uid'] = $uid;
  2904. $ins_data['mer_id'] = $mer_id;
  2905. $ins_data['mark'] = $mark;
  2906. $ins_data['order_id'] = $order_id;
  2907. $ins_data['pm'] = $pm;
  2908. $ins_data['reward_socre'] = $score;
  2909. $ins_data['use_uid'] = $use_uid;
  2910. try {
  2911. Db::transaction(function () use ($ins_data,$pm,$mer_id,$score,$uid) {
  2912. $id = Db::name('enterprise_user_score')->insertGetId($ins_data);
  2913. if($pm == 2){
  2914. Db::name('enterprise_user') -> where('uid',$uid)-> where('mer_id',$mer_id) -> dec('green_integral',$score)->update();
  2915. }else if ($pm==1){
  2916. Db::name('enterprise_user') -> where('uid',$uid)-> where('mer_id',$mer_id) -> inc('green_integral',$score)->update();
  2917. }
  2918. $green_integral=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('uid',$uid)->value('green_integral');
  2919. if($green_integral<0){
  2920. throw new \Exception('修改失败,用户红积分不足,请刷新后再试');
  2921. }
  2922. });
  2923. }catch (\Exception $e){
  2924. return false;
  2925. }
  2926. return true;
  2927. }
  2928. /**
  2929. * 获取下级所有团队列表
  2930. * @param $uid
  2931. * @return int
  2932. */
  2933. public function getSpreadUidBreak($uid){
  2934. $sql = "select getUserSpreadId($uid) as uids";
  2935. $count = Db::query($sql);
  2936. $count[0]['uids'] = trim($count[0]['uids'],'$,');
  2937. $originalArray = explode(",",$count[0]['uids']);
  2938. $resultArray = array_diff($originalArray, [$uid]);
  2939. return $resultArray;
  2940. }
  2941. }