UserRepository.php 135 KB

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