UserRepository.php 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820
  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. //赠送积分 注册送30积分
  874. $this->sign_add($user['uid'], 30,1,'注册送30积分','','', '', 1, '', 1);
  875. Db::commit();
  876. return $user;
  877. } catch (\Exception $e) {
  878. Log::info($userInfo);
  879. Db::rollback();
  880. log::info("注册失败".$e->getFile().':'.$e->getLine().'【'.$e->getMessage().'】');
  881. throw new AuthException('注册失败');
  882. }
  883. }
  884. public function getUserLevelId($spread_uid){
  885. if (empty($spread_uid)){
  886. return false;
  887. }
  888. $sql = "select getUserLevelId($spread_uid) as count";
  889. $getUserLevelId = Db::query($sql);
  890. $user_level_uids=ltrim($getUserLevelId[0]['count'],'$,');
  891. return $user_level_uids;
  892. }
  893. public function insterUser($uid, $spread_uid){
  894. /**
  895. * 查询上级人数 select * from rrx_user_count LIMIT 0,1
  896. */
  897. // $spread_uid = Db::name('user') -> where('uid', $uid) -> value('spread_uid');
  898. // Db::name('log')->insert(['data'=>'公排注册:'.$uid.'======'.$spread_uid]);
  899. // $userCount = false;
  900. // if ($spread_uid > 0){
  901. // //找直推上级网络里面不足5人的排进去
  902. //
  903. // $userCount = Db::name('user_count') -> where('level_number >= 0') -> where ('uid', $spread_uid) -> find();
  904. // if (!$userCount){
  905. // $userCount = $this -> getCountUId($spread_uid);
  906. // }
  907. //
  908. //
  909. // }
  910. // Log::info("userCount:::");
  911. // Log::info($userCount);
  912. // Log::info($spread_uid);
  913. // Db::name('log')->insert(['data'=>'uid:'.$uid.'公排注册:'.json_encode($userCount)]);
  914. // if (!$userCount){
  915. // //没有直推上级 大公排
  916. // $userCount = Db::name('user_count') -> where('level_number >= 0') -> find();
  917. // //增加一个只查询新账户大公排下的用户
  918. // // $userCount = Db::name('user_count') -> where('level_number >= 0')->whereIn('uid',$this->getUserLevelId(11112)) -> find();
  919. // }
  920. // if ($userCount) {
  921. // if ($userCount['level_number'] + 1 == systemConfig( 'max_level_number')) { //(33制或者55制)下级最大人数systemConfig( 'max_level_number')
  922. // Db::name('user_count') -> where('uid',$userCount['uid'])->delete();
  923. // } else {
  924. // $level_number = $userCount['level_number'] + 1;
  925. // Db::name('user_count') -> where('uid',$userCount['uid']) -> update(['level_number'=>$level_number]);
  926. // }
  927. // }
  928. // dd($spread_uid);
  929. // Db::name('user') -> where('uid',$uid)->update(['level_id'=>$userCount['uid'],'level'=>$this->level()]);
  930. // Db::name('user_count') -> insert(['uid'=>$uid]);
  931. }
  932. public function getCountUId($spread_uid){
  933. if (empty($spread_uid)){
  934. return false;
  935. }
  936. //查询所有下级是否满足条件
  937. //查询所有下级uid
  938. $level_id = Db::name('user') -> where('level_id', $spread_uid) -> field('uid') -> select()->toArray();
  939. $level_ids = array_column($level_id,'uid');
  940. $check_ids = Db::name('user_count') -> where('level_number >= 0') -> where ('uid','in', $level_ids) -> find();
  941. foreach ($level_id as $value){
  942. //查询下级是否满足条件
  943. $check = Db::name('user_count') -> where('level_number >= 0') -> where ('uid', $value['uid']) -> find();
  944. if ($check){
  945. return $check;
  946. }else if(empty($check_ids)){
  947. $id = $this -> getCountUId($value['uid']);
  948. if ($id){
  949. return $id;
  950. }
  951. }
  952. }
  953. return false;
  954. }
  955. private function level() {
  956. $count = Db::name('user')->where('level > 0')->count();
  957. switch ($count) {
  958. case 0:
  959. return 1;
  960. case 1:
  961. return 2;
  962. }
  963. $number = ($count + 1) - floor($count / 5);
  964. return ceil(log($number) / log(5)) + 1;
  965. }
  966. /**
  967. * @param User $user
  968. * @return array
  969. * @author xaboy
  970. * @day 2020-04-29
  971. */
  972. public function createToken(User $user)
  973. {
  974. $service = new JwtTokenService();
  975. $token = $service->createToken($user->uid, 'user');
  976. $this->cacheToken($token['token'], $token['out'],$user->uid);
  977. if($user -> user_number == ''){
  978. $this -> createUserNumber($user->uid);
  979. }
  980. // if($user -> im == 0 && env('im',false)){
  981. // $im = new Im();
  982. // $im -> createIm($user -> account,$user -> user_number);
  983. // }
  984. return $token;
  985. }
  986. /**
  987. * //TODO 登录成功后
  988. * @param User $user
  989. * @author xaboy
  990. * @day 2020/6/22
  991. */
  992. public function loginAfter(User $user)
  993. {
  994. $user->last_time = date('Y-m-d H:i:s', time());
  995. $user->last_ip = request()->ip();
  996. $user->save();
  997. }
  998. /**
  999. * @param string $token
  1000. * @param int $exp
  1001. * @author xaboy
  1002. * @day 2020-04-29
  1003. */
  1004. public function cacheToken(string $token, int $exp,$uid)
  1005. {
  1006. Cache::set('user_' . $token, time() + $exp, $exp);
  1007. Cache::set('java_' . $token, $uid, $exp);
  1008. }
  1009. /**
  1010. * @param string $token
  1011. * @author xaboy
  1012. * @day 2020-04-29
  1013. */
  1014. public function checkToken(string $token)
  1015. {
  1016. $has = Cache::has('user_' . $token);
  1017. if (!$has)
  1018. throw new AuthException('无效的token');
  1019. $lastTime = Cache::get('user_' . $token);
  1020. if (($lastTime + intval(Config::get('admin.token_valid_exp', 15)) * 60) > time())
  1021. throw new AuthException('token 已过期');
  1022. }
  1023. /**
  1024. * @param string $token
  1025. * @author xaboy
  1026. * @day 2020-04-29
  1027. */
  1028. public function updateToken(string $token)
  1029. {
  1030. Cache::set('user_' . $token, time(), intval(Config::get('admin.token_valid_exp', 15)) * 60);
  1031. }
  1032. /**
  1033. * @param string $token
  1034. * @author xaboy
  1035. * @day 2020-04-29
  1036. */
  1037. public function clearToken(string $token)
  1038. {
  1039. Cache::delete('user_' . $token);
  1040. }
  1041. /**
  1042. * @param string $key
  1043. * @param string $code
  1044. * @author xaboy
  1045. * @day 2020/6/1
  1046. */
  1047. public function checkCode(string $key, string $code)
  1048. {
  1049. $_code = Cache::get('am_captcha' . $key);
  1050. if (!$_code) {
  1051. throw new ValidateException('验证码过期');
  1052. }
  1053. if (strtolower($_code) != strtolower($code)) {
  1054. throw new ValidateException('验证码错误');
  1055. }
  1056. //删除code
  1057. Cache::delete('am_captcha' . $key);
  1058. }
  1059. /**
  1060. * @param string $code
  1061. * @return string
  1062. * @author xaboy
  1063. * @day 2020/6/1
  1064. */
  1065. public function createLoginKey(string $code)
  1066. {
  1067. $key = uniqid(microtime(true), true);
  1068. Cache::set('am_captcha' . $key, $code, Config::get('admin.captcha_exp', 5) * 60);
  1069. return $key;
  1070. }
  1071. //$repository->registr($data['phone'], $data['password'],'APP',"","",$data['spread']);
  1072. public function registr(string $phone, ?string $pwd, $user_type = 'h5',$url="",$nickname="",$external=1,$spread_uid=null)
  1073. {
  1074. $user_res = Db::name('user')->where('phone', $phone)->find();
  1075. if ($user_res && !$user_res['account']) {
  1076. $data = [
  1077. 'account' => $phone,
  1078. ];
  1079. $this->dao->update($user_res['uid'], $data);
  1080. return $this->dao->get($user_res['uid']);
  1081. }
  1082. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1083. $data = [
  1084. 'account' => $phone,
  1085. 'pwd' => $pwd,
  1086. 'nickname' =>$nickname?$nickname:'用户' . substr($phone, 7, 4),
  1087. 'avatar' => 'https://cdn.bjtdba.com/vod/image/2025-01-20/20250120125206881.png',
  1088. 'phone' => $phone,
  1089. 'last_ip' => app('request')->ip(),
  1090. "identity"=>5,
  1091. "external"=>$external,
  1092. "level_id"=>$spread_uid,
  1093. "spread_uid"=>$spread_uid
  1094. ];
  1095. return $this->create($user_type, $data, $url,$spread_uid);
  1096. }
  1097. public function addregistr($data)
  1098. {
  1099. // string $phone, ?string $pwd, $user_type = 'h5',$url,
  1100. $phone=$data['phone'];
  1101. $pwd=empty($data['password'])?time():$data['password'];
  1102. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1103. $data = [
  1104. 'account' => $phone,
  1105. 'pwd' => $pwd,
  1106. 'nickname' => '用户' . substr($phone, 7, 4),
  1107. 'avatar' => 'https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png',
  1108. 'phone' => $phone,
  1109. 'last_ip' => app('request')->ip(),
  1110. 'user_name'=>empty($data['user_name'])?0:$data['user_name'],
  1111. 'birthday'=>empty($data['birthday'])?0:$data['birthday'],
  1112. 'sex'=>empty($data['adr_id'])?0:$data['sex'],
  1113. 'spread_uid'=>$data['spread'],
  1114. 'adr_id'=>empty($data['adr_id'])?0:$data["adr_id"],
  1115. 'identity'=>empty($data['identity'])?0:$data["identity"],
  1116. ];
  1117. return $this->create("APP", $data);
  1118. }
  1119. /**
  1120. * 重置密码
  1121. * @param string $phone
  1122. * @param string|null $pwd
  1123. * @author 似水星辰 [ 2630481389@qq.com ]
  1124. * @created 2020/10/14 23:46
  1125. */
  1126. public function resetPassword(string $phone, ?string $pwd, int $userid)
  1127. {
  1128. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  1129. $data = [
  1130. 'account' => $phone,
  1131. 'pwd' => $pwd,
  1132. 'phone' => $phone,
  1133. 'last_ip' => app('request')->ip()
  1134. ];
  1135. return $this->dao->update($userid, $data);
  1136. }
  1137. /*重置手机号*/
  1138. public function resetAccount(string $phone, int $userid, $identity){
  1139. $data = [
  1140. 'account' => $phone,
  1141. 'phone' => $phone,
  1142. 'last_ip' => app('request')->ip()
  1143. ];
  1144. //如果是商家
  1145. if($identity == 4){
  1146. $res = Db::name("merchant_admin")->where(['uid'=>$userid])->update(['account'=>$phone,'phone'=>$phone]);
  1147. if(!$res){
  1148. return false;
  1149. }
  1150. }
  1151. return $this->dao->update($userid, $data);
  1152. }
  1153. public function routineSpreadImage(User $user)
  1154. {
  1155. //小程序
  1156. $name = $user['uid'] . '_' . $user['is_promoter'] . '_user_routine.jpg';
  1157. $attachmentRepository = app()->make(AttachmentRepository::class);
  1158. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  1159. $spreadBanner = systemGroupData('spread_banner');
  1160. if (!count($spreadBanner)) return [];
  1161. $siteName = systemConfig('site_name');
  1162. $siteUrl = systemConfig('site_url');
  1163. $uploadType = (int)systemConfig('upload_type') ?: 1;
  1164. //检测远程文件是否存在
  1165. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  1166. $imageInfo->delete();
  1167. $imageInfo = null;
  1168. }
  1169. if (!$imageInfo) {
  1170. $routineQrcodeRepository = app()->make(RoutineQrcodeRepository::class);
  1171. $res = $routineQrcodeRepository->getShareCode($user['uid'], 'spread', '',$user['avatar']);
  1172. if (!$res) throw new ValidateException('二维码生成失败');
  1173. $upload = UploadService::create($uploadType);
  1174. $uploadRes = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
  1175. if ($uploadRes === false) {
  1176. throw new ValidateException($upload->getError());
  1177. }
  1178. $imageInfo = $upload->getUploadInfo();
  1179. $imageInfo['image_type'] = $uploadType;
  1180. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  1181. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  1182. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1183. 'attachment_category_id' => 0,
  1184. 'attachment_name' => $imageInfo['name'],
  1185. 'attachment_src' => $imageInfo['dir']
  1186. ]);
  1187. $routineQrcodeRepository->setRoutineQrcodeFind($res['id'], ['status' => 1, 'url_time' => date('Y-m-d H:i:s'), 'qrcode_url' => $imageInfo['dir']]);
  1188. $urlCode = $imageInfo['dir'];
  1189. } else $urlCode = $imageInfo['attachment_src'];
  1190. $siteUrlHttps = set_http_type($siteUrl, request()->isSsl() ? 0 : 1);
  1191. $filelink = [
  1192. 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1193. 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1194. ];
  1195. if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
  1196. if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
  1197. $resRoutine = true;
  1198. foreach ($spreadBanner as $key => &$item) {
  1199. $posterInfo = '海报生成失败:(';
  1200. $config = array(
  1201. 'image' => array(
  1202. array(
  1203. 'url' => $urlCode, //二维码资源
  1204. 'stream' => 0,
  1205. 'left' => 114,
  1206. 'top' => 790,
  1207. 'right' => 0,
  1208. 'bottom' => 0,
  1209. 'width' => 120,
  1210. 'height' => 120,
  1211. 'opacity' => 100
  1212. )
  1213. ),
  1214. 'text' => array(
  1215. array(
  1216. 'text' => $user['nickname'],
  1217. 'left' => 250,
  1218. 'top' => 840,
  1219. 'fontPath' => $filelink['Bold'], //字体文件
  1220. 'fontSize' => 16, //字号
  1221. 'fontColor' => '40,40,40', //字体颜色
  1222. 'angle' => 0,
  1223. ),
  1224. array(
  1225. 'text' => '邀请您加入' . $siteName,
  1226. 'left' => 250,
  1227. 'top' => 880,
  1228. 'fontPath' => $filelink['Normal'], //字体文件
  1229. 'fontSize' => 16, //字号
  1230. 'fontColor' => '40,40,40', //字体颜色
  1231. 'angle' => 0,
  1232. )
  1233. ),
  1234. 'background' => $item['pic']
  1235. );
  1236. $resRoutine = $resRoutine && $posterInfo = setSharePoster($config, 'routine/spread/poster');
  1237. if (!is_array($posterInfo)) throw new ValidateException($posterInfo);
  1238. $posterInfo['dir'] = path_to_url($posterInfo['dir']);
  1239. if (strpos($posterInfo['dir'], 'http') === false) $posterInfo['dir'] = request()->domain() . $posterInfo['dir'];
  1240. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1241. 'attachment_category_id' => 0,
  1242. 'attachment_name' => $posterInfo['name'],
  1243. 'attachment_src' => $posterInfo['dir']
  1244. ]);
  1245. if ($resRoutine) {
  1246. if ($posterInfo['image_type'] == 1)
  1247. $item['poster'] = rtrim($siteUrlHttps, '/') . $posterInfo['dir'];
  1248. else
  1249. $item['poster'] = set_http_type($posterInfo['dir'], request()->isSsl() ? 0 : 1);
  1250. $item['poster'] = str_replace('\\', '/', $item['poster']);
  1251. }
  1252. }
  1253. return $spreadBanner;
  1254. }
  1255. public function wxSpreadImage(User $user)
  1256. {
  1257. //公众号
  1258. $name = $user['uid'] . '_' . $user['is_promoter'] . '_user_wap.jpg';
  1259. $spreadBanner = systemGroupData('spread_banner');
  1260. if (!count($spreadBanner)) return [];
  1261. $siteName = systemConfig('site_name');
  1262. $attachmentRepository = app()->make(AttachmentRepository::class);
  1263. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  1264. $siteUrl = systemConfig('site_url');
  1265. $uploadType = (int)systemConfig('upload_type') ?: 1;
  1266. $resWap = true;
  1267. //检测远程文件是否存在
  1268. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  1269. $imageInfo->delete();
  1270. $imageInfo = null;
  1271. }
  1272. if (!$imageInfo) {
  1273. $codeUrl = set_http_type($siteUrl . '/share?spread=' . $user['uid'], request()->isSsl() ? 0 : 1);//二维码链接
  1274. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name,$user['avatar']);
  1275. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  1276. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  1277. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  1278. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -1, $user->uid, [
  1279. 'attachment_category_id' => 0,
  1280. 'attachment_name' => $imageInfo['name'],
  1281. 'attachment_src' => $imageInfo['dir']
  1282. ]);
  1283. $urlCode = $imageInfo['dir'];
  1284. } else $urlCode = $imageInfo['attachment_src'];
  1285. $siteUrl = set_http_type($siteUrl, request()->isSsl() ? 0 : 1);
  1286. $filelink = [
  1287. 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1288. 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  1289. ];
  1290. if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
  1291. if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
  1292. foreach ($spreadBanner as $key => &$item) {
  1293. $posterInfo = '海报生成失败:(';
  1294. $config = array(
  1295. 'image' => array(
  1296. array(
  1297. 'url' => $urlCode, //二维码资源
  1298. 'stream' => 0,
  1299. 'left' => 160,//84
  1300. 'top' => 530,//630
  1301. 'right' => 0,
  1302. 'bottom' => 0,
  1303. 'width' => 280,
  1304. 'height' => 280,
  1305. 'opacity' => 100
  1306. )
  1307. ),
  1308. 'text' => array(
  1309. array(
  1310. 'text' => "NO:".$user['user_number'],
  1311. 'left' => 200,
  1312. 'top' => 850,
  1313. 'fontPath' => $filelink['Bold'], //字体文件
  1314. 'fontSize' => 16, //字号
  1315. 'fontColor' => '0,0,0', //字体颜色
  1316. 'angle' => 0,
  1317. ),
  1318. // array(
  1319. // 'text' => '邀请您加入' . $siteName,
  1320. // 'left' => 290,
  1321. // 'top' => 750,
  1322. // 'fontPath' => $filelink['Normal'], //字体文件
  1323. // 'fontSize' => 16, //字号
  1324. // 'fontColor' => '40,40,40', //字体颜色
  1325. // 'angle' => 0,
  1326. // )
  1327. ),
  1328. 'background' => $item['pic']
  1329. );
  1330. $resWap = $resWap && $posterInfo = setSharePoster($config, 'wap/spread/poster');
  1331. if (!is_array($posterInfo)) throw new ValidateException('海报生成失败');
  1332. $posterInfo['dir'] = path_to_url($posterInfo['dir']);
  1333. if (strpos($posterInfo['dir'], 'http') === false) $posterInfo['dir'] = request()->domain() . $posterInfo['dir'];
  1334. $attachmentRepository->create($uploadType, -1, $user->uid, [
  1335. 'attachment_category_id' => 0,
  1336. 'attachment_name' => $posterInfo['name'],
  1337. 'attachment_src' => $posterInfo['dir']
  1338. ]);
  1339. if ($resWap) {
  1340. if ($posterInfo['image_type'] == 1)
  1341. $item['wap_poster'] = rtrim($siteUrl, '/') . $posterInfo['thumb_path'];
  1342. else
  1343. $item['wap_poster'] = set_http_type($posterInfo['thumb_path'], 1);
  1344. }
  1345. $item['wap_poster'] = str_replace('http://','https://',$item['wap_poster']);
  1346. $item["attachment_src"]= str_replace('http://','https://',$urlCode);
  1347. $item["name"]=$user['phone'];
  1348. }
  1349. return $spreadBanner;
  1350. }
  1351. public function getUsername($uid)
  1352. {
  1353. return User::getDB()->where('uid', $uid)->value('user_name');
  1354. }
  1355. /*获取用户手机号*/
  1356. public function getUserPhone($uid)
  1357. {
  1358. return User::getDB()->where('uid', $uid)->value('account');
  1359. }
  1360. /**
  1361. * @param $uid
  1362. * @param $inc
  1363. * @param string $type
  1364. * @author xaboy
  1365. * @day 2020/6/22
  1366. */
  1367. public function incBrokerage($uid, $inc, $type = '+')
  1368. {
  1369. $weekKey = 'b_top_' . date('Y-m');
  1370. $moneyKey = 'b_top_' . monday();
  1371. //TODO 佣金周榜
  1372. $brokerage = Cache::zscore($weekKey, $uid);
  1373. $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
  1374. Cache::zadd($weekKey, $brokerage, $uid);
  1375. //TODO 佣金月榜
  1376. $brokerage = Cache::zscore($moneyKey, $uid);
  1377. $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
  1378. Cache::zadd($moneyKey, $brokerage, $uid);
  1379. }
  1380. public function brokerageWeekTop($page, $limit)
  1381. {
  1382. $key = 'b_top_' . monday();
  1383. return $this->topList($key, $page, $limit);
  1384. }
  1385. public function brokerageMonthTop($page, $limit)
  1386. {
  1387. $key = 'b_top_' . date('Y-m');
  1388. return $this->topList($key, $page, $limit);
  1389. }
  1390. /**
  1391. * //TODO 绑定上下级关系
  1392. * @param User $user
  1393. * @param int $spreadUid
  1394. * @throws DbException
  1395. * @author xaboy
  1396. * @day 2020/6/22
  1397. */
  1398. public function bindSpread(User $user, int $spreadUid)
  1399. {
  1400. if ($spreadUid && !$user->spread_uid && $user->uid != $spreadUid) {
  1401. Db::transaction(function () use ($spreadUid, $user) {
  1402. $spread_user = $this ->get($spreadUid);
  1403. // //首次邀请赠送899积分
  1404. // if($spread_user['spread_count'] == 0){
  1405. // //首次邀请好友奖励积分
  1406. // $this -> sign_add($spreadUid,systemConfig('first_yq_score'),1,'首次邀请好友奖励积分','','');
  1407. // }
  1408. //邀请好友奖励积分
  1409. // $this->sign_add($spreadUid,systemConfig('invitation'),1,'邀请好友注册奖励积分','','');
  1410. //邀请好友奖励积分
  1411. $this->sign_add($spreadUid, 30,1,'邀请好友注册奖励积分','','', '', 1, '', 1);
  1412. $user->spread_uid = $spreadUid;
  1413. $user->spread_time = date('Y-m-d H:i:s');
  1414. if($spreadUid){
  1415. $user->mer_id = Db::name('user')->where('uid',$spreadUid)->value('mer_id');
  1416. }
  1417. $this->dao->update($spreadUid, [
  1418. 'spread_count' => Db::raw('spread_count +1')
  1419. ]);
  1420. $user->save();
  1421. //TODO 推广人月榜
  1422. Cache::zincrby('s_top_' . date('Y-m'), 1, $spreadUid);
  1423. //TODO 推广人周榜
  1424. Cache::zincrby('s_top_' . monday(), 1, $spreadUid);
  1425. });
  1426. $this->spread_log($user,$spreadUid);
  1427. }
  1428. //绑定上下级关系 加入推广群
  1429. // $this -> hximTg($user -> uid,$spreadUid);
  1430. }
  1431. /**
  1432. * @param $uid int 用户id
  1433. * @param $sid int 上级id
  1434. * @author Tang
  1435. * @created 2021/12/10
  1436. */
  1437. public function hximTg($uid,$sid)
  1438. {
  1439. try {
  1440. $im=new Im();
  1441. $user=Db::name('user')->where('uid',$uid)->find();
  1442. if($user['im']==0){//没有环信账户 创建
  1443. $im->createImUser($user['account'], $user['nickname']);
  1444. $user_account=$user['account'];
  1445. }else{//有环信账户 跳过创建 下一步
  1446. $user_account=$user['account'];
  1447. }
  1448. $userS=Db::name('user')->where('uid',$sid)->find();
  1449. if($userS['im']==0){//上级环信账户 创建
  1450. $im->createImUser($userS['account'], $userS['nickname']);
  1451. $s_account=$userS['account'];
  1452. }else{//有环信账户 跳过创建 下一步
  1453. $s_account=$userS['account'];
  1454. }
  1455. $group_id=Db::name("im_group")->where(['uid'=>$userS['account'],'type'=>'p'])->value('groupid');
  1456. //判断是否有群
  1457. if($group_id){//有则加入
  1458. $im->createGroupUser($group_id,$user_account,$user['uid']);
  1459. }else{
  1460. $group_id=$im->createGroup($s_account,'推广群','t');
  1461. $im->createGroupUser($group_id,$user_account,$user['uid']);
  1462. }
  1463. }catch (\Exception $e) {
  1464. Db::name("log")->insert(array('data'=>'推广群错误'.$e->getMessage()));//日志记录
  1465. }
  1466. }
  1467. //注册时成为推广员身份 记录统计及信息
  1468. public function spread_log($user,$spreadUid){
  1469. if($spreadUid){
  1470. Db::transaction(function () use ($spreadUid, $user) {
  1471. $sp = DB::name("user")->where(['uid'=>$spreadUid])->field("uid,spread_count")->find();
  1472. if($sp){
  1473. //推荐人推荐数量加1
  1474. Db::name("user")->where(['uid'=>$sp['uid']])->update(['spread_count'=>($sp['spread_count']+1)]);
  1475. //保存用户的推荐记录
  1476. $log =[
  1477. 'uid'=> $sp['uid'],
  1478. 'link_id'=>$user->uid,
  1479. 'identity'=>5,
  1480. 'create_time'=>date("Y-m-d H:i:s"),
  1481. ] ;
  1482. Db::name("user_identity_log")->insert($log);
  1483. }
  1484. });
  1485. }
  1486. }
  1487. public function topList($key, $page, $limit)
  1488. {
  1489. $res = Cache::zrevrange($key, ($page - 1) * $limit, $limit, true);
  1490. $ids = array_keys($res);
  1491. $index = array_flip($ids);
  1492. $count = Cache::zcard($key);
  1493. $list = count($ids) ? $this->dao->users($ids, 'uid,avatar,nickname')->toArray() : [];
  1494. foreach ($list as $k => $v) {
  1495. $list[$k]['count'] = $res[$v['uid']] ?? 0;
  1496. }
  1497. $sort = array_column($list, 'count');
  1498. array_multisort($sort, SORT_DESC, $list);
  1499. return compact('count', 'list');
  1500. }
  1501. public function spreadWeekTop($page, $limit)
  1502. {
  1503. $key = 's_top_' . monday();
  1504. return $this->topList($key, $page, $limit);
  1505. }
  1506. public function spreadMonthTop($page, $limit)
  1507. {
  1508. $key = 's_top_' . date('Y-m');
  1509. return $this->topList($key, $page, $limit);
  1510. }
  1511. /**
  1512. * @param $uid
  1513. * @param $nickname
  1514. * @param $sort
  1515. * @param $page
  1516. * @param $limit
  1517. * @return array
  1518. * @throws DataNotFoundException
  1519. * @throws DbException
  1520. * @throws ModelNotFoundException
  1521. * @author xaboy
  1522. * @day 2020/6/22
  1523. */
  1524. public function getOneLevelList($uid, $nickname, $sort, $page, $limit)
  1525. {
  1526. $query = $this->search(['spread_uid' => $uid, 'nickname' => $nickname, 'sort' => $sort]);
  1527. $count = $query->count();
  1528. $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
  1529. return compact('list', 'count');
  1530. }
  1531. /**
  1532. * @param $uid
  1533. * @param $nickname
  1534. * @param $sort
  1535. * @param $page
  1536. * @param $limit
  1537. * @return array
  1538. * @throws DataNotFoundException
  1539. * @throws DbException
  1540. * @throws ModelNotFoundException
  1541. * @author xaboy
  1542. * @day 2020/6/22
  1543. */
  1544. public function getTwoLevelList($uid, $nickname, $sort, $page, $limit)
  1545. {
  1546. $ids = $this->dao->getSubIds($uid);
  1547. if (count($ids)) {
  1548. $query = $this->search(['spread_uids' => $ids, 'nickname' => $nickname, 'sort' => $sort]);
  1549. $count = $query->count();
  1550. $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
  1551. } else {
  1552. $list = [];
  1553. $count = 0;
  1554. }
  1555. return compact('list', 'count');
  1556. }
  1557. public function getLevelList($uid, array $where, $page, $limit)
  1558. {
  1559. if (!$where['level']) {
  1560. // $ids = $this->dao->getSubIds($uid);
  1561. $ids[] = $uid;
  1562. $where['spread_uids'] = $ids;
  1563. } else if ($where['level'] == 2) {
  1564. $ids = $this->dao->getSubIds($uid);
  1565. if (!count($ids)) return ['list' => [], 'count' => 0];
  1566. $where['spread_uids'] = $ids;
  1567. } else {
  1568. $where['spread_uid'] = $uid;
  1569. }
  1570. $query = $this->search($where);
  1571. $count = $query->count();
  1572. $list = $query->setOption('field', [])->field('User.uid,avatar,nickname,is_promoter,pay_count,pay_price,spread_count,User.create_time')->page($page, $limit)->select();
  1573. return compact('list', 'count','where');
  1574. }
  1575. /**
  1576. * @param $uid
  1577. * @param $page
  1578. * @param $limit
  1579. * @param array $where
  1580. * @return array
  1581. * @throws DataNotFoundException
  1582. * @throws DbException
  1583. * @throws ModelNotFoundException
  1584. * @author xaboy
  1585. * @day 2020/6/26
  1586. */
  1587. public function subOrder($uid, $page, $limit, array $where = [])
  1588. {
  1589. if (isset($where['level'])) {
  1590. if (!$where['level']) {
  1591. $ids = $this->dao->getSubIds($uid);
  1592. $subIds = $this->dao->getSubAllIds($ids);
  1593. } else if ($where['level'] == 2) {
  1594. $ids = $this->dao->getSubIds($uid);
  1595. $subIds = $this->dao->getSubAllIds($ids);
  1596. $ids = [];
  1597. } else {
  1598. $ids = $this->dao->getSubIds($uid);
  1599. $subIds = [];
  1600. }
  1601. } else {
  1602. $ids = $this->dao->getSubIds($uid);
  1603. $subIds = $this->dao->getSubAllIds($ids);
  1604. }
  1605. $all = array_merge($ids, $subIds);
  1606. if (!count($all)) return ['count' => 0, 'list' => []];
  1607. $query = app()->make(StoreOrderRepository::class)->usersOrderQuery($where, $all);
  1608. $count = $query->count();
  1609. $list = $query->page($page, $limit)->field('uid,order_sn,pay_time,extension_one,extension_two')->with(['user' => function ($query) {
  1610. $query->field('avatar,nickname,uid');
  1611. }])->select()->toArray();
  1612. foreach ($list as $k => $item) {
  1613. $list[$k]['brokerage'] = in_array($item['uid'], $ids) ? $item['extension_one'] : $item['extension_two'];
  1614. unset($list[$k]['extension_one'], $list[$k]['extension_two']);
  1615. }
  1616. return compact('count', 'list');
  1617. }
  1618. /**
  1619. * @param User $user
  1620. * @return User
  1621. * @throws DataNotFoundException
  1622. * @throws DbException
  1623. * @throws ModelNotFoundException
  1624. * @author xaboy
  1625. * @day 2020/7/2
  1626. */
  1627. public function mainUser(User $user): User
  1628. {
  1629. if (!$user->main_uid || $user->uid == $user->main_uid) return $user;
  1630. $switchUser = $this->dao->get($user->main_uid);
  1631. if (!$switchUser) return $user;
  1632. if ($user->wechat_user_id && !$switchUser->wechat_user_id) {
  1633. $switchUser->wechat_user_id = $user->wechat_user_id;
  1634. $switchUser->save();
  1635. }
  1636. return $switchUser;
  1637. }
  1638. public function switchUser(User $user, $uid)
  1639. {
  1640. if ($user->uid == $uid || !$this->dao->existsWhere(['uid' => $uid, 'phone' => $user->phone]))
  1641. throw new ValidateException('操作失败');
  1642. $this->dao->update($user->uid, ['main_uid' => $uid]);
  1643. $switchUser = $this->dao->get($uid);
  1644. return $switchUser;
  1645. }
  1646. public function returnToken($user, $tokenInfo)
  1647. {
  1648. $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();
  1649. return [
  1650. 'token' => $tokenInfo['token'],
  1651. 'exp' => $tokenInfo['out'],
  1652. 'user' => $user
  1653. ];
  1654. }
  1655. public function switchBrokerage(User $user, $brokerage)
  1656. {
  1657. $user->now_money = bcadd($user->now_money, $brokerage, 2);
  1658. $user->brokerage_price = bcsub($user->brokerage_price, $brokerage, 2);
  1659. Db::transaction(function () use ($brokerage, $user) {
  1660. $user->save();
  1661. app()->make(UserBillRepository::class)->incBill($user->uid, 'now_money', 'brokerage', [
  1662. 'link_id' => 0,
  1663. 'status' => 1,
  1664. 'title' => '佣金转入余额',
  1665. 'number' => $brokerage,
  1666. 'mark' => '成功转入余额' . floatval($brokerage) . '元',
  1667. 'balance' => $user->now_money
  1668. ]);
  1669. app()->make(UserBillRepository::class)->decBill($user->uid, 'brokerage', 'now_money', [
  1670. 'link_id' => 0,
  1671. 'status' => 1,
  1672. 'title' => '佣金转入余额',
  1673. 'number' => $brokerage,
  1674. 'mark' => '成功转入余额' . floatval($brokerage) . '元',
  1675. 'balance' => $user->brokerage_price
  1676. ]);
  1677. });
  1678. }
  1679. /**
  1680. * 签到
  1681. * @param $member_id
  1682. * @throws DataNotFoundException
  1683. * @throws DbException
  1684. * @throws ModelNotFoundException
  1685. */
  1686. public function sub_signin($member_id){
  1687. $member_info = Db::name('user')->where( array('uid' => $member_id) )->find();
  1688. $config =systemConfig([
  1689. 'isopen_signinreward',
  1690. 'signinreward_day1_score',
  1691. 'signinreward_day2_score',
  1692. 'signinreward_day3_score',
  1693. 'signinreward_day4_score',
  1694. 'signinreward_day5_score',
  1695. 'signinreward_day6_score',
  1696. 'signinreward_day7_score',
  1697. ]);
  1698. //是否开启签到奖励
  1699. $isopen_signinreward = empty($config['isopen_signinreward']) ? 0 : $config['isopen_signinreward'];
  1700. if( $isopen_signinreward != 1 )
  1701. {
  1702. return array('code' => 1,'msg' => '签到奖励功能未开启');
  1703. }
  1704. //连续7天签到奖励
  1705. $signinreward_day1_score = empty($config['signinreward_day1_score']) ? 0 : $config['signinreward_day1_score'];
  1706. $signinreward_day2_score = empty($config['signinreward_day2_score']) ? 0 : $config['signinreward_day2_score'];
  1707. $signinreward_day3_score = empty($config['signinreward_day3_score']) ? 0 : $config['signinreward_day3_score'];
  1708. $signinreward_day4_score = empty($config['signinreward_day4_score']) ? 0 : $config['signinreward_day4_score'];
  1709. $signinreward_day5_score = empty($config['signinreward_day5_score']) ? 0 : $config['signinreward_day5_score'];
  1710. $signinreward_day6_score = empty($config['signinreward_day6_score']) ? 0 : $config['signinreward_day6_score'];
  1711. $signinreward_day7_score = empty($config['signinreward_day7_score']) ? 0 : $config['signinreward_day7_score'];
  1712. //准备数据
  1713. $result = array();
  1714. $result['signinreward_day1_score'] = $signinreward_day1_score;
  1715. $result['signinreward_day2_score'] = $signinreward_day2_score;
  1716. $result['signinreward_day3_score'] = $signinreward_day3_score;
  1717. $result['signinreward_day4_score'] = $signinreward_day4_score;
  1718. $result['signinreward_day5_score'] = $signinreward_day5_score;
  1719. $result['signinreward_day6_score'] = $signinreward_day6_score;
  1720. $result['signinreward_day7_score'] = $signinreward_day7_score;
  1721. $today_signintime = time();
  1722. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->whereDay('signin_time')->find();
  1723. if( !empty($today_signin_info) )
  1724. {
  1725. return array('code' => 1,'msg' => '今天已经签到过了');
  1726. }else{
  1727. //查询昨天是否已经签到了
  1728. $yes_signintime = strtotime( date('Y-m-d'). ' 00:00:00' ) - 86400;
  1729. $yes_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id, 'signin_time' => $yes_signintime ) )->find();
  1730. $has_qian = 1;
  1731. if( !empty($yes_signin_info) )
  1732. {
  1733. $has_qian = $yes_signin_info['continuity_day'] +1;
  1734. $has_qian = $has_qian > 7 ? 7 : $has_qian;
  1735. }
  1736. $get_score = $result["signinreward_day".$has_qian."_score"];
  1737. $ins_data = array();
  1738. $ins_data['member_id'] = $member_id;
  1739. $ins_data['continuity_day'] = $has_qian;
  1740. $ins_data['reward_socre'] = $get_score;
  1741. $ins_data['signin_time'] = $today_signintime;
  1742. $ins_data['addtime'] = time();
  1743. $member_info = Db::name('user')->where( array('uid' => $member_id) )->find();
  1744. $score = $member_info['now_score'];
  1745. Db::name('user_signinreward_record')->insert($ins_data);
  1746. $now_score=$score+$get_score;
  1747. app()->make(UserBillRepository::class)->incBill($member_id, 'now_money', 'recharge', [
  1748. 'link_id' => 1,
  1749. 'status' => 1,
  1750. 'title' => '签到积分',
  1751. 'number' => $get_score,
  1752. 'mark' => '连续签到'.$has_qian.'天赠送',
  1753. 'balance' =>$now_score
  1754. ]);
  1755. Db::name('user')->where( array('uid' => $member_id) )->update(['now_score'=>$now_score]);
  1756. // Db::name('log')->insert(['data'=>Db::name('user')->getLastSql(),'time'=>date('Y-m-d H:i:s',time())]);
  1757. return array('code' =>0, 'now_score' => $score, 'continuity_day' => $has_qian,'reward_socre' => $get_score );
  1758. }
  1759. }
  1760. public function get_signin($member_id,$where=[]){
  1761. if ($where){
  1762. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time', 'between', [$where['data1'], $where['data2']])->find();
  1763. $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');
  1764. }else{
  1765. $today_signin_info = Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time',"today")->find();
  1766. $show_day_arr= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id))->whereTime('signin_time',"month")->column('signin_time');
  1767. }
  1768. $score= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->count('reward_socre');
  1769. $leiji= Db::name('user_signinreward_record')->where( array('member_id' =>$member_id) )->sum('reward_socre');
  1770. foreach ($show_day_arr as &$v){
  1771. $v=date("Y-m-d",$v);
  1772. }
  1773. $result['score'] = $score;
  1774. $result['today_is_signin'] = $today_signin_info?1:0;
  1775. $result['leiji'] = $leiji;
  1776. $result['show_day_arr'] = $show_day_arr;
  1777. return $result;
  1778. }
  1779. public function add_cer($data=[],$member_id)
  1780. {
  1781. $renzeng=Db::name("user_certification")->where("uid",$member_id)->find();
  1782. if ($renzeng){
  1783. $res = Db::name('user_certification')->where("uid",$member_id)->update($data);
  1784. }else{
  1785. $res = Db::name('user_certification')->insert($data);
  1786. }
  1787. if($res){
  1788. return [
  1789. 'user_name' => $data['user_name'],
  1790. 'age' => $this->getAgeByID($data['user_card']),
  1791. 'user_card' => preg_replace('/(\d{6})\d{8}(\d{4})/', '$1****$2', $data['user_card']),
  1792. ];
  1793. }
  1794. else{
  1795. return false;
  1796. }
  1797. }
  1798. public function get_cer($data=[])
  1799. {
  1800. $res = Db::name('user_certification')->where($data)->find();
  1801. //计算年龄
  1802. $res['age'] = $this->getAgeByID($res['user_card']);
  1803. if($res){
  1804. return $res;
  1805. }
  1806. else{
  1807. return false;
  1808. }
  1809. }
  1810. public function getAgeByID($id){
  1811. //过了这年的生日才算多了1周岁
  1812. if(empty($id)) return '';
  1813. $date=strtotime(substr($id,6,8));
  1814. //获得出生年月日的时间戳
  1815. $today=strtotime('today');
  1816. //获得今日的时间戳
  1817. $diff=floor(($today-$date)/86400/365);
  1818. //得到两个日期相差的大体年数
  1819. //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
  1820. $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
  1821. return $age;
  1822. }
  1823. /**
  1824. * @param $data
  1825. *
  1826. */
  1827. public function addagent($user){
  1828. if ($user){
  1829. $data=[
  1830. "identity"=>5,
  1831. "status"=>1,
  1832. "add_time"=>time(),
  1833. "update_time"=>time(),
  1834. "user_id"=>$user->uid,
  1835. "name"=>"推广员",
  1836. "pay_status"=>1,
  1837. "price"=>0,
  1838. "agent_sn"=>time(),
  1839. ];
  1840. Db::name("user_agent")->insert($data);
  1841. }
  1842. }
  1843. /*
  1844. * 申请代理
  1845. @cabbage
  1846. */
  1847. public function agent($data){
  1848. $user = Db::name("user")->where(['uid'=>$data['user_id']])->field("identity,account,uid")->find();
  1849. //判断所申请的区域下是否有代理
  1850. if($data['identity'] == 1){
  1851. if(Db::name("user_street")->where("street_id",$data['street_id'])->value("uid")){
  1852. return ['code'=>400,'msg'=>'该区域下已有代理'];
  1853. }
  1854. }elseif($data['identity'] == 2){
  1855. if(Db::name("user_area")->where("area_id",$data['area_id'])->value("uid")){
  1856. return ['code'=>400,'msg'=>'该区域下已有代理'];
  1857. }
  1858. }elseif($data['identity'] == 3){
  1859. if(Db::name("user_city")->where("city_id",$data['city_id'])->value("uid")){
  1860. return ['code'=>400,'msg'=>'该区域下已有代理'];
  1861. }
  1862. }
  1863. //判断是不是商户
  1864. // if($user['identity']==4){
  1865. // return ['code'=>'400','msg'=>"不符合申请代理的条件"];
  1866. // }
  1867. //判断用户是否是其他代理身份
  1868. // if(in_array($user['identity'],[1,2,3,5])){
  1869. // return ['code'=>'400','msg'=>"用户已是推广身份"];
  1870. // }
  1871. if($user['identity']==$data['identity']){
  1872. return ['code'=>'400','msg'=>"用户已是该身份,无需申请"];
  1873. }
  1874. if($data['spread_account'] == $user['account']){
  1875. return ['code'=>'400','msg'=>"推荐人不能是自己"];
  1876. }
  1877. $real = Db::name("user_certification")->where(["uid"=>$data['user_id'],'status'=>1])->find();
  1878. //判断是否实名认证
  1879. if(!$real){
  1880. return ['code'=>'400','msg'=>"请先实名认证"];
  1881. }
  1882. if($user){
  1883. if($data['identity'] == $user['identity']){
  1884. return ['code'=>'400','msg'=>"已经是该级别代理"];
  1885. }
  1886. if(!in_array($user['identity'],[4,5]) && $data['identity'] < $user['identity']){
  1887. return ['code'=>'400','msg'=>"不能申请低于现在级别的代理"];
  1888. }
  1889. }
  1890. $is_apply= Db::name("user_agent")->where(["user_id"=>$data["user_id"],'status'=>[0,2]])->find();
  1891. if ($is_apply){
  1892. if($is_apply['status'] == 0){
  1893. return ['code'=>'400','msg'=>"您有审核中的代理申清"];
  1894. }
  1895. if($is_apply['status'] == 2) {
  1896. $data['status']= 0;//恢复申请中状态
  1897. $res= Db::name("user_agent")->where("id",$is_apply['id'])->update($data);
  1898. if($res){
  1899. return true;
  1900. }
  1901. }
  1902. }
  1903. $res= Db::name("user_agent")->insert($data);
  1904. if($res){
  1905. return true;
  1906. }
  1907. }
  1908. public function isAgent($uid){
  1909. $res = Db::name("user_agent")
  1910. ->where(["user_id"=>$uid])
  1911. ->whereIn('status',[0,1,2])
  1912. ->whereIn('identity',[1,2,3,6])
  1913. ->order("add_time desc")
  1914. ->find();
  1915. if(!$res){
  1916. return json_encode([]);
  1917. }
  1918. $res['province_name'] = Db::name("user_province")->where(['province_id'=>$res['province_id']])->value("province_name");
  1919. $res['city_name'] = Db::name("user_city")->where(['city_id'=>$res['city_id']])->value("city_name");
  1920. $res['area_name'] = Db::name("user_area")->where(['area_id'=>$res['area_id']])->value("area_name");
  1921. $res['street_name'] = Db::name("user_street")->where(['street_id'=>$res['street_id']])->value("street_name");
  1922. switch ($res['identity']){
  1923. case '1':
  1924. $res['name'] = '镇级服务商';
  1925. break;
  1926. case '2':
  1927. $res['name'] = '县级服务商';
  1928. break;
  1929. case '3':
  1930. $res['name'] = '市级服务商';
  1931. break;
  1932. case '6':
  1933. $res['name'] = '渠道商';
  1934. }
  1935. return $res;
  1936. }
  1937. public function getAgentPayDetail($where=[]){
  1938. $res= Db::name("user_agent")->where($where)->find();
  1939. return $res;
  1940. }
  1941. public function get_agent_info($member_id){
  1942. $user=Db::name("user")->where("uid",$member_id)->find();
  1943. $data=[
  1944. "nickname"=>$user["nickname"],
  1945. "avatar"=>$user["avatar"],
  1946. "is_promoter"=>$user["is_promoter"],
  1947. "identity"=>$user["identity"],
  1948. "brokerage_price"=>set_price_rtrim($user["brokerage_price"]),
  1949. "uid"=>$member_id,
  1950. ];
  1951. $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");
  1952. $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");
  1953. $data["extract"]=(string)Db::name("user_extract")->where(["uid"=>$member_id,"status"=>1])->sum("extract_price");
  1954. return $data;
  1955. }
  1956. /*
  1957. * 全民营销->推广统计
  1958. */
  1959. public function get_extension_info($member_id,$search,$where=[]){
  1960. $data=[];
  1961. $data["count_zong"]=Db::name("user_identity_log")->where(["uid"=>$member_id])->count();
  1962. $data["town"]=Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>1])->whereNotIn("identity","0")->count();
  1963. $data["county"]= Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>2])->whereNotIn("identity","0")->count();
  1964. $data["city"]= Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>3])->whereNotIn("identity","0")->count();
  1965. $data["shop"]=Db::name("user_identity_log")->where(["uid"=>$member_id,'identity'=>4])->whereNotIn("identity","0")->count();
  1966. $data["tuiguang"]=Db::name("user_identity_log")->where(["uid"=>$member_id])->whereIn('identity','5,0')->count();
  1967. $query =Db::name("user_identity_log")->alias("a")
  1968. ->join('user s',"a.link_id=s.uid")
  1969. ->where(["a.uid"=>$member_id])
  1970. ->field("s.nickname,a.create_time,a.identity,s.phone");
  1971. if(isset($where['identity']) && $where['identity'] != ''){
  1972. $query = $query->where(['a.identity'=>$where['identity']]);
  1973. }
  1974. if(isset($search) && $search !=''){
  1975. $query =$query->whereLike('s.account','%'.$search.'%');
  1976. }
  1977. $list = $query->select();
  1978. $data["list"]=$list;
  1979. return $data;
  1980. }
  1981. public function get_profit_info($member_id,$where){
  1982. // $data["count_yj"]=Db::name("user")->where(["type"=>"commission"])->sum("number");
  1983. // $data["dlfee"]=Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");
  1984. // $data["xiaofee"]=Db::name("user")->where(["type"=>"commission","commission_type"=>2])->sum("number");;
  1985. // $data["county"] =Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");;
  1986. // $data["town"]==Db::name("user")->where(["type"=>"commission","commission_type"=>1])->sum("number");;
  1987. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  1988. ->field("type,number,status,commission_type,create_time,uid,title,order_sn");
  1989. $order = "create_time desc";
  1990. if($where['date_on'] == 1){
  1991. $order = "create_time desc";
  1992. }elseif($where['date_off'] == 1){
  1993. $order = "create_time asc";
  1994. }
  1995. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  1996. $query = $query->where(['commission_type'=>$where['commission_type']]);
  1997. }else{
  1998. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  1999. }
  2000. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2001. $query = $query->whereTime("create_time",$where['order']);
  2002. }
  2003. $list= $query->order($order)->select()->toArray();
  2004. $dangqian_yj=Db::name("user")->where("uid",$member_id)->value("brokerage_price");
  2005. $dlfee=0;
  2006. $xiaofei=0;
  2007. $tuiguang=0;
  2008. $xiaqu=0;
  2009. $weijiesuan=0;
  2010. $qudao=0;
  2011. foreach ($list as &$v){
  2012. // $count_yj=$v["number"]+$count_yj;
  2013. if ($v["status"]==0){
  2014. $v["title"]="【预估】".$v["title"].",单号:".$v["order_sn"];
  2015. $weijiesuan+=$v['number'];
  2016. }elseif($v["status"]==-1){
  2017. $v["title"]="【失效】".$v["title"].",单号:".$v["order_sn"];
  2018. }else{
  2019. if ($v["commission_type"]==1){
  2020. $dlfee+=$v["number"];
  2021. }
  2022. if ($v["commission_type"]==2){
  2023. $xiaofei+=$v["number"];
  2024. }
  2025. if ($v["commission_type"]==3){
  2026. $tuiguang+=$v["number"];
  2027. }
  2028. if ($v["commission_type"]==4){
  2029. $xiaqu+=$v["number"];
  2030. }
  2031. if ($v["commission_type"]==6||$v["commission_type"]==7){
  2032. $tuiguang+=$v["number"];
  2033. }
  2034. if ($v["commission_type"]==9){
  2035. $qudao+=$v["number"];
  2036. }
  2037. if ($v["commission_type"]==10){
  2038. $tuiguang+=$v["number"];
  2039. }
  2040. }
  2041. }
  2042. $data["count_yj"]=round($dangqian_yj,2);//当前佣金
  2043. $data["dlfee"]=round($dlfee,2); //代理非
  2044. $data["xiaofei"]=round($xiaofei,2); //消费佣金
  2045. $data["tuiguang"]= round($tuiguang,2); //推广佣金
  2046. $data["xiaqu"]=round($xiaqu,2); //辖区佣金
  2047. $data["weijiesuan"]=round($weijiesuan,2);//未结束佣金
  2048. $data["qudao"]=round($qudao,2);//渠道
  2049. $data["list"]=$list;
  2050. return $data;
  2051. }
  2052. /*
  2053. * 越攒越多统计
  2054. * */
  2055. public function get_com_all($member_id,$where){
  2056. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  2057. ->field("type,number,status,commission_type,create_time,uid,title,order_sn,type_shop");
  2058. $order = "create_time desc";
  2059. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  2060. $query = $query->where(['commission_type'=>$where['commission_type']]);
  2061. }else{
  2062. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2063. }
  2064. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2065. $query = $query->whereTime("create_time",$where['order']);
  2066. }
  2067. $query = $query->where(['status'=>1]);
  2068. $list= $query->order($order)->select()->toArray();
  2069. $dangqian_yj=Db::name("user")->where("uid",$member_id)->value("brokerage_price");
  2070. $dlfee=0;
  2071. $xiaofei=0;
  2072. $tuiguang=0;
  2073. $kuadian=0;
  2074. $xiaqu=0;
  2075. $weijiesuan=0;
  2076. $ptjl=0;
  2077. $qudao=0;
  2078. foreach ($list as &$v){
  2079. // $count_yj=$v["number"]+$count_yj;
  2080. if ($v["commission_type"]==1){
  2081. $dlfee+=$v["number"];
  2082. }
  2083. if ($v["commission_type"]==2){
  2084. $xiaofei+=$v["number"];
  2085. }
  2086. if ($v["commission_type"]==3){
  2087. $tuiguang+=$v["number"];
  2088. }
  2089. if ($v["commission_type"]==4){
  2090. $xiaqu+=$v["number"];
  2091. $v['title'] = '辖区获取佣金';
  2092. }
  2093. if ($v["commission_type"]==7){
  2094. $kuadian+=$v["number"];
  2095. $v['title'] = '跨店获取佣金';
  2096. }
  2097. if ($v["commission_type"]==8){
  2098. $ptjl+=$v["number"];
  2099. $v['title'] = '平台奖励佣金';
  2100. }
  2101. if ($v["commission_type"]==9){
  2102. $qudao+=$v["number"];
  2103. $v['title'] = '渠道商奖励佣金';
  2104. }
  2105. if ($v["commission_type"]==10){
  2106. $tuiguang+=$v["number"];
  2107. $v['title'] = '推荐商户奖励佣金';
  2108. }
  2109. // if ($v['type_shop'] >0){
  2110. // $qudao+=$v['number'];
  2111. // $v['title'] = '第三方订单获取佣金';
  2112. // }
  2113. }
  2114. $data["count_yj"]=round($dangqian_yj,2);//当前佣金
  2115. $data["dlfee"]=round($dlfee,2); //代理非
  2116. $data["xiaofei"]=round($xiaofei,2); //消费佣金
  2117. $data["tuiguang"]= round($tuiguang,2); //推广佣金
  2118. $data["xiaqu"]=round($xiaqu,2); //辖区佣金
  2119. $data["weijiesuan"]=round($weijiesuan,2);//未结束佣金
  2120. $data["kuadian"]=round($kuadian,2); //跨店
  2121. $data["ptjl"]=round($ptjl,2); //平台奖励佣金
  2122. $data["qudao"]=round($qudao,2); //渠道
  2123. return $data;
  2124. }
  2125. /*
  2126. * 越攒越多列表
  2127. * */
  2128. public function get_com_list($member_id,$where){
  2129. $query = Db::name("user_bill")->where(["type"=>"commission",'uid'=>$member_id])
  2130. ->field("type,number,status,commission_type,create_time,uid,title,order_sn,type_shop");
  2131. $order = "create_time desc";
  2132. if(isset($where['commission_type']) && $where['commission_type'] !=''){
  2133. $query = $query->where(['commission_type'=>$where['commission_type']]);
  2134. }else{
  2135. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2136. }
  2137. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2138. $query = $query->whereTime("create_time",$where['order']);
  2139. }
  2140. $page = $where['page'] ?? 1;
  2141. $limit = $where['limit'] ?? 10;
  2142. $query = $query->where(['status'=>1]);
  2143. $list= $query->page($page,$limit)->order($order)->select()->toArray();
  2144. $data["list"]=$list;
  2145. return $data;
  2146. }
  2147. /**
  2148. * 获取推广列表
  2149. */
  2150. public function get_tuiguang_list($member_id,$where = []){
  2151. $query = Db::name("user_bill")
  2152. ->alias("ul")
  2153. ->where(["ul.type"=>"commission",'ul.uid'=>$member_id])
  2154. ->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");
  2155. if(isset($where['type']) && in_array($where['type'],[0,1])){
  2156. $query = $query->where(['ul.source'=>$where['type']]);
  2157. }
  2158. if(isset($where['order']) && in_array($where['order'],["today","yesterday","week","month","year"])){
  2159. $query = $query->whereTime("create_time",$where['order']);
  2160. }
  2161. $page = $where['page'] ?? 1;
  2162. $limit = $where['limit'] ?? 10;
  2163. $query = $query ->whereIn("commission_type",[1,2,3,4,7,8,9,10]);
  2164. $query = $query ->where("status",'>=',0);
  2165. //不显示红积分的
  2166. $query = $query ->where("is_red_brokerage",'=',0);
  2167. $list= $query->order("create_time desc")->page($page,$limit)->select()->toArray();
  2168. foreach ($list as &$v){
  2169. // $v["create_time"]=date("Y-m-d", $v["create_time"]);
  2170. //0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么
  2171. if($v['type_shop'] == 0){
  2172. if($v['source'] == 0){
  2173. if($v['commission_type'] == 9){
  2174. $this -> getContent('channel_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v);
  2175. }elseif($v['commission_type'] == 10){
  2176. $this -> getContent('merchant_annual_cost_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v);
  2177. }else{
  2178. $this -> getContent('store_order',$v['order_sn'],'幸福宝',$v['status'],$v['commission_type'],$v,$v['create_time']);
  2179. }
  2180. }else{
  2181. $uid=Db::name("store_order")->where("order_sn",$v["order_sn"])->value("uid");
  2182. $v["nickname"]=$this -> getUserNickname($uid);
  2183. $v['content'] = '用户'.$v['nickname'].'到店消费,帮您攒金';
  2184. $v['xiadan'] = $v['create_time'] ?? '';
  2185. $v['jiesuan'] = $v['create_time'];
  2186. }
  2187. }elseif ($v['type_shop'] == '1'){
  2188. $this -> getContent('order_pdd',$v['order_sn'],'拼多多',$v['status'],$v['commission_type'],$v);
  2189. }elseif ($v['type_shop'] == '2'){
  2190. $this -> getContent('order_vip',$v['order_sn'],'唯品会',$v['status'],$v['commission_type'],$v);
  2191. }elseif ($v['type_shop'] == '3'){
  2192. $this -> getContent('order_su',$v['order_sn'],'苏宁易购',$v['status'],$v['commission_type'],$v);
  2193. }
  2194. elseif ($v['type_shop'] == '4'){
  2195. // $uid = Db::name('order_jd')->where("order_sn",$v["order_sn"])->value("uid");
  2196. // $v["nickname"]=$this -> getUserNickname($uid);
  2197. $v["nickname"]='';
  2198. $v['content'] = $v['nickname'].'在网易考拉消费,帮您攒金';
  2199. $v['xiadan'] = '';
  2200. $v['jiesuan'] = '';
  2201. }elseif ($v['type_shop'] == '5'){
  2202. $this -> getContent('order_tb',$v['order_sn'],'淘宝',$v['status'],$v['commission_type'],$v);
  2203. }elseif ($v['type_shop'] == '6'){
  2204. $this -> getContent('order_jd',$v['order_sn'],'京东',$v['status'],$v['commission_type'],$v);
  2205. }elseif ($v['type_shop'] == '7'){
  2206. $this -> getContent('order_tb',$v['order_sn'],'饿了么',$v['status'],$v['commission_type'],$v);
  2207. }
  2208. if($v['commission_type'] == 7){
  2209. $v['mark'] = '【跨店】'.$v['mark'];
  2210. }
  2211. $v['number'] =set_price_rtrim($v['number']);
  2212. }
  2213. return $list;
  2214. }
  2215. public function getUserNickname($uid){
  2216. return Db::name("user")->where("uid", $uid)->value("nickname");
  2217. }
  2218. public function getContent($table,$order_sn,$title,$status,$commission_type,&$v,$create_time=null){
  2219. $yugu = '';
  2220. if($status == 0){
  2221. $yugu = "【预估】";
  2222. if($commission_type == 7){
  2223. $yugu = "【跨店预估】";
  2224. }
  2225. }
  2226. switch ($table){
  2227. case 'store_order':
  2228. $res = Db::name($table)->where("order_sn",$order_sn)->field('uid,create_time,pay_time')->find();
  2229. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2230. $v['content'] = $yugu.$v['nickname'].'在'.$title.'消费,帮您攒金';
  2231. break;
  2232. case 'channel_order':
  2233. $res = Db::name($table)->where("order_no",$order_sn)->field('uid,create_time,pay_time')->find();
  2234. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2235. $v['content'] = $v['nickname'].'成为渠道商,帮您攒金';
  2236. $res['bill_end_time'] = strtotime($res['create_time']);
  2237. break;
  2238. case 'merchant_annual_cost_order':
  2239. $res = Db::name($table)->where("order_no",$order_sn)->field('uid,create_time,pay_time')->find();
  2240. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2241. $v['content'] = $v['nickname'].'成为商户,帮您攒金';
  2242. $res['bill_end_time'] = strtotime($res['create_time']);
  2243. break;
  2244. default:
  2245. $res = Db::name($table)->where("order_sn",$order_sn)->field('uid,create_time,bill_end_time,pay_time')->find();
  2246. $v["nickname"]=$this -> getUserNickname($res['uid']);
  2247. $v['content'] = $yugu.$v['nickname'].'在'.$title.'消费,帮您攒金';
  2248. }
  2249. // $v['xiadan'] = $res['create_time'] ?? $create_time;
  2250. $v['xiadan'] = isset($res['pay_time'])?$res['pay_time']:$create_time;
  2251. $v['jiesuan'] = $v['xiadan'];
  2252. // if (empty($res['bill_end_time']) && empty($res['create_time'])){
  2253. // $v['jiesuan'] = $create_time;
  2254. // }else{
  2255. // $v['jiesuan'] = date('Y-m-d H:i:s',$res['bill_end_time']??strtotime("+10 day", strtotime($res['create_time'])));
  2256. // }
  2257. }
  2258. /**
  2259. * 获取订单数
  2260. */
  2261. public function get_tuiguang_order($member_id){
  2262. $where=["ul.type"=>"commission","ul.status"=>1,'ul.uid'=>$member_id];
  2263. $list=Db::name("user_bill")
  2264. ->alias("ul")
  2265. // ->join("user u","u.uid=ul.uid")
  2266. ->where("commission_type","<>",5)
  2267. ->where($where)
  2268. ->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")
  2269. ->select();
  2270. $num=0;
  2271. $count=0;
  2272. foreach ($list as &$v){
  2273. $num++;
  2274. // $v["create_time"]=date("Y-m-d", $v["create_time"]);
  2275. $uid=Db::name("store_order")->where("order_sn",$v["order_sn"])->value("uid");
  2276. $v["nickname"]=Db::name("user")->where("uid", $uid)->value("nickname");
  2277. $count+=$v["number"];
  2278. }
  2279. return ["num"=>$num,"count"=>round($count,2),"list"=>$list];
  2280. }
  2281. public function get_yanglao($member_id){
  2282. $data = Db::name("user")
  2283. ->where("uid",$member_id)
  2284. ->field("wechat_user_id,card_id,ali_user_id,annuity_frozen,annuity_num,annuity,create_time,birthday,birthday60,card_number,annuity_yiqu,pay_price")
  2285. ->find();
  2286. // $data['annuity'] = 0;
  2287. $certification = Db::name("user_certification")->where("uid",$member_id)->find();
  2288. $data['can_withdraw'] = 0;
  2289. if (!$certification || $certification["status"] !=1 || !$certification["user_card"]){
  2290. $data["birthday60"] = "未实名认证";
  2291. $data['is_certification'] = 0;
  2292. } else {
  2293. // try {
  2294. // $checkAmount = $this->checkAmount($certification);
  2295. // if ($checkAmount['code'] == 0) {
  2296. // $data['annuity'] = $checkAmount['extendData']['amount'];
  2297. // }
  2298. // } catch (\Throwable $e) {
  2299. // Log::info('getyanglaojin' . $e->getMessage());
  2300. // }
  2301. $data['is_certification'] = 1;
  2302. $birth_data = substr($certification["user_card"], 6, 8);
  2303. // $birth = strtotime(substr($certification["user_card"], 6, 8));
  2304. $old_age = $this->getSex($certification["user_card"])?60:55;
  2305. // $age = $this->howOld($birth);
  2306. $age=$this->calculateAge($birth_data);
  2307. if ($age < $old_age) {
  2308. // $yes = $old_age - $age;
  2309. // $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("+" . $yes . " year"));
  2310. }
  2311. if ($age == $old_age) {
  2312. $data['can_withdraw'] = 1;
  2313. // $data["birthday60"] = date("Y-m-d", $birth);
  2314. }
  2315. if ($age > $old_age) {
  2316. $data['can_withdraw'] = 1;
  2317. // $yes = $age - $old_age;
  2318. // $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("-" . $yes . " year"));
  2319. }
  2320. //收益余额
  2321. $data['annuity_num'] = 123;
  2322. $data['annuity_yiqu'] = 123;
  2323. $data["birthday60"] = $this->getFutureBirthday($birth_data,$old_age);
  2324. }
  2325. $order_merchant_price= OrderMerchant::getInstance()->where('paid', 1)
  2326. ->where(function ($query) use ($data) {
  2327. $query->where('pay_user_id', $data['wechat_user_id'])
  2328. ->whereOr('pay_user_id', $data['ali_user_id']);
  2329. })
  2330. ->sum('money');
  2331. //加上线下消费的
  2332. $data['pay_price'] = bcadd($data['pay_price'],$order_merchant_price,2);
  2333. $data["yinghang"] = "中信公证处消费养老金账户";
  2334. // $data["yinghang"]='https://app.bjtdba.com/uploads/def/20201021/8cb66944101287b8ac9c9b9fb1b13a79.png';
  2335. $data["add_up"] = 0.00;
  2336. return $data;
  2337. }
  2338. function calculateAge($birthDate) {
  2339. $today = new \DateTime();
  2340. $diff = $today->diff(new \DateTime($birthDate));
  2341. return $diff->y;
  2342. }
  2343. function getFutureBirthday($birthDate, $years) {
  2344. $date = new \DateTime($birthDate);
  2345. $date->modify("+$years years");
  2346. return $date->format('Y-m-d');
  2347. }
  2348. public function getSex($cid){
  2349. //根据身份证号,自动返回性别
  2350. $sexint = (int)substr($cid,16,1);
  2351. return $sexint % 2 === 0 ? false : true;
  2352. }
  2353. /**
  2354. * 根据时间戳计算年龄
  2355. * @param $birth
  2356. * @return mixed
  2357. */
  2358. public function howOld($birth) {
  2359. list($birthYear, $birthMonth, $birthDay) = explode('-', date('Y-m-d', $birth));
  2360. list($currentYear, $currentMonth, $currentDay) = explode('-', date('Y-m-d'));
  2361. $age = $currentYear - $birthYear - 1;
  2362. if($currentMonth > $birthMonth || $currentMonth == $birthMonth && $currentDay >= $birthDay)
  2363. $age++;
  2364. return $age;
  2365. }
  2366. public function yanglaolog($where,$page=1, $limit=10,$month='',$is_shixiao = 0){
  2367. $where1 = [];
  2368. if(!empty($where)){
  2369. foreach($where as $key => $value){
  2370. $where1['a.'.$key] = $value;
  2371. }
  2372. }
  2373. $query=Db::name("user_bill")
  2374. ->alias('a')
  2375. ->join('Merchant b', 'a.mer_id = b.mer_id','left')
  2376. ->field('a.*,b.mer_name,b.mer_avatar')
  2377. ->where($where1)
  2378. ->when($month!='',function ($q) use ($month){
  2379. $q->whereLike('a.create_time',$month.'%');
  2380. });
  2381. if($is_shixiao == 0){
  2382. $query -> where('a.status','<>','-1');
  2383. }
  2384. $query_sql1 = clone $query;
  2385. $query_sql2 = clone $query;
  2386. $query_sql3 = clone $query;
  2387. $count = $query->count();
  2388. $list = $query->page($page,$limit)->order("a.bill_id desc")->select()
  2389. ->each(function($item){
  2390. if($item['source'] == 0 && $item['type_shop'] == 0){
  2391. $item['product'] = json_decode(Db::name("store_order")
  2392. -> alias('a')
  2393. -> join('store_order_product b','a.order_id = b.order_id','left')
  2394. -> where(["a.order_sn"=>$item['order_sn']])
  2395. -> value('b.cart_info'),true);
  2396. if(empty($item['product'])){
  2397. $item['product']=[
  2398. 'product'=>[
  2399. 'image'=>'https://cdn.bjtdba.com/vod/image/2025-01-21/20250121180855764.png',
  2400. 'store_name'=>'商家年费'
  2401. ]
  2402. ];
  2403. }
  2404. }
  2405. return $item;
  2406. });
  2407. $yugu=$query_sql1->sum('number');
  2408. $yijiesuan=$query_sql1->where('a.status',1)->sum('number');
  2409. $weijiesuan=$yugu-$yijiesuan;
  2410. return compact('count','list','yugu','yijiesuan','weijiesuan');
  2411. }
  2412. /*养老金详情*/
  2413. public function yanglaoDetail($where=[],$field='*'){
  2414. $query=Db::name("user_bill")->where($where)->field($field)->find();
  2415. return $query;
  2416. }
  2417. /*提现记录 type 1佣金 2养老金*/
  2418. public function withdrawal($where){
  2419. $data=Db::name("user_extract")->where($where)->order('extract_id','desc')->select();
  2420. if(!$data->isEmpty()){
  2421. $data=$data->toArray();
  2422. }
  2423. foreach ($data as $k=>&$v){
  2424. if($v['withdrawal_type']==2){
  2425. // $name=Db::name('merchant')->where('mer_id',$v['mer_id'])->value('mer_name');
  2426. $v['title']='佣金提现';
  2427. }else if($v['withdrawal_type']==3){
  2428. if($v['extract_type']==1){
  2429. $tltle='微信';
  2430. $v['title']='提现到'.$tltle;
  2431. }else if($v['extract_type']==3){
  2432. $tltle='银行卡';
  2433. $v['title']='提现到'.$tltle;
  2434. }else if($v['extract_type']==4){
  2435. $v['title']='人工减少佣金';
  2436. }
  2437. }else{
  2438. $v['title']='幸福宝-佣金提现';
  2439. }
  2440. if($v['bank_info']!=''){
  2441. $bank_info=json_decode($v['bank_info'],true);
  2442. }
  2443. $v['extract_price']=set_price_rtrim($v['extract_price']);
  2444. $v['bank_name']=isset($bank_info['bank_name'])?$bank_info['bank_name']:'';
  2445. }
  2446. return $data;
  2447. }
  2448. /*提现记录 type 1佣金 2养老金*/
  2449. public function withdrawal_user($where){
  2450. $data=Db::name("user_extract")->where($where)->where('mer_id is null')->order('extract_id','desc')->select();
  2451. if(!$data->isEmpty()){
  2452. $data=$data->toArray();
  2453. }
  2454. foreach ($data as $k=>&$v){
  2455. if($v['withdrawal_type']==2){
  2456. // $name=Db::name('merchant')->where('mer_id',$v['mer_id'])->value('mer_name');
  2457. $v['title']='佣金提现';
  2458. }else if($v['withdrawal_type']==3){
  2459. if($v['extract_type']==1){
  2460. $tltle='微信';
  2461. $v['title']='提现到'.$tltle;
  2462. }else if($v['extract_type']==3){
  2463. $tltle='银行卡';
  2464. $v['title']='提现到'.$tltle;
  2465. }else if($v['extract_type']==4){
  2466. $v['title']='人工减少佣金';
  2467. }
  2468. }else{
  2469. $v['title']='幸福宝-佣金提现';
  2470. }
  2471. if($v['bank_info']!=''){
  2472. $bank_info=json_decode($v['bank_info'],true);
  2473. $data[$k]['bank_info']=json_decode($v['bank_info'],true);
  2474. }
  2475. $v['extract_price']=set_price_rtrim($v['extract_price']);
  2476. $v['bank_name']=isset($bank_info['bank_name'])?$bank_info['bank_name']:'';
  2477. }
  2478. return $data;
  2479. }
  2480. /*
  2481. * 提现详情
  2482. *@author cabbage
  2483. *@date 2020-10-31
  2484. * */
  2485. public function withdrawalDetail($id,$uid){
  2486. $data= Db::name("user_extract")->where(["uid"=>$uid,'extract_id'=>$id,"type"=>2])->find();
  2487. return $data;
  2488. }
  2489. /*
  2490. * 修改用户推广人id
  2491. *@author cabbage
  2492. *@date 2020-10-31
  2493. * */
  2494. public function update_spread($uid,$spread_account){
  2495. //推荐人信息
  2496. $spread = Db::name("user")->where('account',$spread_account)->field("uid")->find();
  2497. //被推荐人信息
  2498. $identity=Db::name("user")->where('uid',$uid)->field("identity,spread_uid")->find();
  2499. $user_identity_log=Db::name("user_identity_log")->where(["link_id"=>$uid])->find();
  2500. if($spread){
  2501. try{
  2502. $data= Db::name("user")->where(["uid"=>$uid])->update(['spread_uid'=>$spread['uid']]);
  2503. Db::name("merchant")->where(["uid"=>$uid])->update(['recommender'=>$spread['uid']]);
  2504. if ($user_identity_log){
  2505. Db::name("user_identity_log")->where(["id"=>$user_identity_log["id"]])->update(['uid'=>$spread['uid']]);
  2506. }else{
  2507. Db::name("user_identity_log")->insert(['uid'=>$spread['uid'],"identity"=>$identity["identity"],"create_time"=>date("Y-m-d H:i:s"),"link_id"=>$uid]);
  2508. }
  2509. Db::name("user")->where('account',$spread_account)->inc("spread_count",1)->update();
  2510. if ($identity["spread_uid"]){
  2511. Db::name("user")->where('uid',$identity["spread_uid"])->dec("spread_count")->update();
  2512. }
  2513. return $data;
  2514. }catch (Exception $e) {
  2515. Db::rollback();
  2516. }
  2517. }else{
  2518. return false;
  2519. }
  2520. }
  2521. /*获取协议列表*/
  2522. public function getXieYi(){
  2523. $data= Db::name("user_agreement")->where(["status"=>1])->select();
  2524. return $data;
  2525. }
  2526. /*积分记录*/
  2527. public function socreList($uid,$page,$limit){
  2528. $data = Db::name("user_signinreward_record")
  2529. ->where(['member_id'=>$uid])
  2530. ->field("reward_socre,addtime")
  2531. ->page($page,$limit)
  2532. ->order("addtime desc")
  2533. ->select()->toArray();
  2534. foreach ($data as $k => $v) {
  2535. $data[$k]['addtime'] = date("y-m-d H:i:s",$v['addtime']);
  2536. $data[$k]['pm'] = 1 ;
  2537. $data[$k]['mark'] = '签到获得' ;
  2538. }
  2539. $result['list'] = $data;
  2540. $result['count'] = Db::name("user_signinreward_record")->where(['member_id'=>$uid])->count();
  2541. $result['total_socre'] = Db::name("user_signinreward_record")->where(['member_id'=>$uid])->sum("reward_socre");
  2542. $result['is_use'] = 0 ;
  2543. $result['is_pass'] = 0 ;
  2544. return $result;
  2545. }
  2546. /*修改用户信息*/
  2547. public function updateUser($uid,$data,$data2=[]){
  2548. $data = Db::name("user")->where(['uid'=>$uid])->update($data);
  2549. if ($data2){
  2550. $ck= Db::name("user_account")->where(["uid"=>$uid,"type"=>$data["type"]])->find();
  2551. if ($ck){
  2552. $data= Db::name("user_account")->where(["id"=>$ck["id"]])->update($data2);
  2553. }else{
  2554. $data= Db::name("user_account")->insert($data2);
  2555. }
  2556. }
  2557. return $data;
  2558. }
  2559. /*获取用户信息*/
  2560. public function getUser($uid,$data){
  2561. $user = Db::name("user")->where(['uid' => $uid])->field($data)->find();
  2562. $data = Db::name("user_account")->where(['uid' => $uid])->select()->toArray();
  2563. $types = array_column($data, 'type');
  2564. if (!in_array('1', $types) && $user['wechat_user_id']) {
  2565. $data[] = ['id' => 0, 'avater' => '', 'nickname' => null, 'type' => 1, 'uid' => $uid];
  2566. Db::name("user_account")->insert(['type' => 1, 'uid' => $uid]);
  2567. }
  2568. if (!in_array('2', $types) && $user['ali_user_id']) {
  2569. $data[] = ['id' => 0, 'avater' => '', 'nickname' => null, 'type' => 2, 'uid' => $uid];
  2570. Db::name("user_account")->insert(['type' => 2, 'uid' => $uid]);
  2571. }
  2572. return $data;
  2573. }
  2574. public function getAccount($uid)
  2575. {
  2576. $res=Db::name('user_extract_openid')->where('uid',$uid)->value('openid');
  2577. if($res){
  2578. $arr[]=array(
  2579. 'id'=>'1',
  2580. 'type'=>'1',
  2581. 'uid'=>$uid,
  2582. 'nickname'=>'',
  2583. 'avater'=>'',
  2584. );
  2585. }
  2586. $res = Db::name('user') -> where('uid',$uid) -> value('ali_user_id');
  2587. if($res && $res != '0' && $res != ''){
  2588. $arr[]=array(
  2589. 'id'=>'2',
  2590. 'type'=>'2',
  2591. 'uid'=>$uid,
  2592. 'nickname'=>'',
  2593. 'avater'=>'',
  2594. );
  2595. }
  2596. return isset($arr)?$arr:[];
  2597. }
  2598. /**
  2599. * 支付宝授权登录
  2600. * 文档:https://opendocs.alipay.com/open/218/105327
  2601. */
  2602. public function aliSign(){
  2603. $aop = new AopClient;
  2604. $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
  2605. $aop->appId = "2021001197654668";
  2606. $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==';
  2607. $aop->format = "json";
  2608. $aop->charset = "UTF-8";
  2609. $aop->signType = "RSA2";
  2610. $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  2611. $data = [
  2612. 'apiname'=>'com.alipay.account.auth',
  2613. 'method'=>'alipay.open.auth.sdk.code.get',
  2614. 'app_id'=>'2021001197654668',
  2615. 'app_name'=>'mc',
  2616. 'biz_type'=>'openservice',
  2617. 'pid'=>'2088931546284482', //合作伙伴身份(PID):
  2618. 'product_id'=>'APP_FAST_LOGIN',
  2619. 'scope'=>'kuaijie',
  2620. 'target_id'=>"ALI".time().rand(10000,99999),
  2621. 'auth_type'=>'AUTHACCOUNT',
  2622. 'sign_type'=>'RSA2'
  2623. ];
  2624. $sign = $aop->generateSign($data,"RSA2");
  2625. $paramStr = '';
  2626. foreach ($data as $key => $param) {
  2627. $paramStr .= "{$key}={$param}&";
  2628. }
  2629. $paramStr = $paramStr.'sign='.urlencode($sign);
  2630. return $paramStr;
  2631. }
  2632. /*
  2633. * 支付宝登录验证
  2634. * $userId 支付宝用户唯一id
  2635. * */
  2636. public function aliCheck($userId){
  2637. $user = Db::name("user")->where(['ali_user_id'=>$userId])->find();
  2638. //判断是否是第一次登录
  2639. if($user){
  2640. //成功登录业务逻辑
  2641. if (!$user['account']) {
  2642. return ['code' => 400, 'msg' => '请绑定手机号'];
  2643. } else {
  2644. return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
  2645. }
  2646. }else{
  2647. return ['code' => 400, 'msg' => '请绑定手机号'];
  2648. }
  2649. }
  2650. /*微信信息获取*/
  2651. public function getWechat(){
  2652. $data['appid'] = "wxbf753066ac8686ba";
  2653. $data['appsecret'] = "68943fc124568c4ab4c3f089b7cdf2aa";
  2654. return $data;
  2655. }
  2656. /*微信登录验证
  2657. $openid 微信openid
  2658. */
  2659. public function wechatCheck($openid){
  2660. $user = Db::name("user")->where(['wechat_user_id'=>$openid])->find();
  2661. //判断是否是第一次登录
  2662. if($user){
  2663. //成功登录业务逻辑
  2664. if (!$user['account']) {
  2665. return ['code' => 400, 'msg' => '请绑定手机号'];
  2666. } else {
  2667. return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
  2668. }
  2669. }else{
  2670. return ['code' => 400, 'msg' => '请绑定手机号'];
  2671. }
  2672. }
  2673. /**
  2674. * 微信登录验证一壶茶
  2675. * @param $openid
  2676. * @return array
  2677. * @throws DataNotFoundException
  2678. * @throws DbException
  2679. * @throws ModelNotFoundException
  2680. */
  2681. public function wechatCheckYhc($openid){
  2682. $enterprise_user = Db::name("enterprise_user")->where(['openid'=>$openid])->find();
  2683. //判断是否是第一次登录,成功登录业务逻辑
  2684. if($enterprise_user && $enterprise_user['uid']!=0){
  2685. $user = Db::name("user")->where(['uid'=>$enterprise_user['uid']])->find();
  2686. return ['code' => 200, 'msg' => '登陆成功', 'user' => $user];
  2687. }
  2688. return ['code' => 400, 'msg' => '请绑定手机号'];
  2689. }
  2690. /*微信支付宝绑定*/
  2691. public function thirdBinding(string $phone, ?string $pwd, $user_type = 'APP',$third_user_id='',$type=0,$url)
  2692. {
  2693. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  2694. $user = $this->accountByUser($phone);
  2695. if($user){
  2696. $data = [
  2697. 'last_ip' => app('request')->ip(),
  2698. ];
  2699. }else{
  2700. $data = [
  2701. 'account' => $phone,
  2702. 'pwd' => $pwd,
  2703. 'nickname' => '用户' . substr($phone, 7, 4),
  2704. 'avatar' => $url.'/uploads/logo.jpg',
  2705. 'phone' => $phone,
  2706. 'last_ip' => app('request')->ip(),
  2707. ];
  2708. }
  2709. if($type ==1){
  2710. if(isset($user->wechat_user_id) && $user->wechat_user_id){return true;}//这里可能有问题
  2711. $data['wechat_user_id'] = $third_user_id;
  2712. }elseif($type ==2){
  2713. if(isset($user->ali_user_id) && $user->ali_user_id){return true;}
  2714. // if($user->ali_user_id){return true;}
  2715. $data['ali_user_id'] = $third_user_id;
  2716. }
  2717. if(!$user){
  2718. return $this->create($user_type, $data);
  2719. }else{
  2720. Db::name("user")->where(['account'=>$phone])->update($data);
  2721. return $user;
  2722. }
  2723. }
  2724. public function getTokenByCode($authorization_code,$info=false,$type=123)
  2725. {
  2726. try {
  2727. $aop = new AopClient();
  2728. $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
  2729. if($type=='h5'){
  2730. $aop->appId = '2021001197698727';
  2731. $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=';
  2732. $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  2733. }else if ($type == 'h5pay'){
  2734. $aop->appId = '2021003191617008';
  2735. $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==';
  2736. $aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuUb+0sJSNXjWiG0VJIPzn55+18af/fubYMpRLlreu34ewMgLx1zpCNpB3wrA+dylfWPMAm8PzvKnakByB+VJ/LMNhWHmF8Qkdo4astAikjlI4TMQCK/G384NzrtjHR4DGCDM5CMVt1xw5noF7kNBMYIvgDfhMCYmygdlIjuVdIlVEoQKOsT0RaNMleES0aZvbjvBGkGM0dsetqUExSjid9BF1NAO2ET+J3XMxCtMgCUVmFUvxsCKe6Rapa1/Lk3rzIeG6CRpoabuYfPM9E+3y3f3luSOMXLfH9lOSW1RA8qrF+Ms1RZv8gmzUnbyrPLmmZPmmN/Qs6DGzDVg73fpSwIDAQAB';
  2737. }else{
  2738. $aop->appId = '2021001197654668';
  2739. $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==';
  2740. $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArHwMZtNYBkK5q2jQ0Ml18H8MhQX9Bpuz/ignvuJC47K7LHY+F6/U/+o/nYeDhqHzUajMAAyM06N3r2qBnWQRjC4JKFMO4i5xIDVycuumzcsWz3LwAkHOFG/S1pGXFWh74zdQDNednhvnNOiTDwjefZRnf5HUqEZK/7tRSaZvzSUIAwHG2zj0C6AYkhg5wr6ZJxgRDjPjqbs6ZMqLT+pITsnCcc6IgIisZbPTdtw1U2FKmQm5n228drI3XKYbE3UVT2y6R0mZNmqmiHDszmYSKOjDrpgtMExWpee8kUFn7J800HIyYtq0nRv1ypdWngUZtkm+szVWOTDGgN4eHQW3FwIDAQAB';
  2741. }
  2742. $aop->apiVersion = '1.0';
  2743. $aop->signType = 'RSA2';
  2744. $aop->postCharset='UTF-8';
  2745. $aop->format='json';
  2746. $request = new AlipaySystemOauthTokenRequest ();
  2747. $request->setGrantType("authorization_code");
  2748. $request->setCode($authorization_code);
  2749. $result = $aop->execute($request);
  2750. Db::name('log')->insert(['data'=>'支付宝相关信息']);
  2751. if (isset($result->alipay_system_oauth_token_response->user_id)) {
  2752. $return['user_id'] = $result->alipay_system_oauth_token_response->user_id;
  2753. $return['msg'] = $result->alipay_system_oauth_token_response->access_token;
  2754. $access_token=$return['msg'] ;
  2755. } else {
  2756. $return['code'] = $result->error_response->code;
  2757. $return['msg'] = $result->error_response->sub_msg;
  2758. return $return;
  2759. }
  2760. if ($info){
  2761. $request = new AlipayUserInfoShareRequest();
  2762. $result = $aop->execute ( $request ,$access_token);
  2763. $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
  2764. Db::name('log')->insert(['data'=>\GuzzleHttp\json_encode($responseNode)]);
  2765. $resultCode = $result->$responseNode->code;
  2766. Db::name('log')->insert(['data'=>$resultCode]);
  2767. $userData=json_decode(json_encode($result->$responseNode),true);
  2768. if(!empty($resultCode)&&$resultCode == 10000){
  2769. return $userData;
  2770. }
  2771. }
  2772. return $return;
  2773. } catch (\Throwable $w) {
  2774. Db::name('log')->insert(['data'=>json_encode($w->getMessage())]);
  2775. return $w->getMessage();
  2776. }
  2777. }
  2778. /**
  2779. * @param $id
  2780. * @return Form
  2781. * @throws DataNotFoundException
  2782. * @throws DbException
  2783. * @throws ModelNotFoundException
  2784. * @throws FormBuilderException
  2785. * @author xaboy
  2786. * @day 2020-05-07
  2787. */
  2788. public function changePassForm($id)
  2789. {
  2790. return Elm::createForm(Route::buildUrl('systemUserChangePass', compact('id'))->build(), [
  2791. Elm::input('pass_word', '用户密码')->required()->value("")
  2792. ])->setTitle('修改用户密码');
  2793. }
  2794. public function changePass($uid,$password)
  2795. {
  2796. $pass_word=$this->encodePassword($password);
  2797. $data= Db::name("user")->where(["uid"=>$uid])->update(['pwd'=>$pass_word]);
  2798. if($data){
  2799. return $data;
  2800. }else{
  2801. return false;
  2802. }
  2803. }
  2804. public function wechatGetTokenBycode()
  2805. {
  2806. }
  2807. public function createUserNumber($uid){
  2808. $t = "C";
  2809. $number = '000000000';
  2810. if($uid <= 10){
  2811. $uid = $uid . 'X';
  2812. }
  2813. $strlen = mb_strlen($uid);//id长度
  2814. $newNumber = $t.substr_replace($number,$uid,-$strlen);
  2815. $newNumber = str_replace('4','R',$newNumber);
  2816. Db::name('user') -> where(["uid"=>$uid])->update(['user_number'=>$newNumber]);
  2817. }
  2818. /**
  2819. * @param int $uid 用户ID
  2820. * @param string $score 积分
  2821. * @param int $status 积分状态
  2822. * @param string $mark 备注
  2823. * @param string $has_qian 连续签到天数
  2824. * @param string $today_signintime 签到时间
  2825. * @param int $order_id 订单ID
  2826. * @param int $pm 1-收入。2-支出
  2827. * @param string $order_type
  2828. * @throws DbException
  2829. */
  2830. public function sign_add($uid, $score, $status, $mark, $has_qian = '', $today_signintime = '', $order_id = 0, $pm = 1, $order_type = '',$type='',$settlement_time = '')
  2831. {
  2832. if(!in_array($type,[1,2])){
  2833. // 其他情况都直接返回,因为目前只有365专区购买才可以获得
  2834. return false;
  2835. }
  2836. $ins_data['uid'] = $uid;
  2837. $ins_data['continuity_day'] = $has_qian;
  2838. $ins_data['reward_socre'] = $score;
  2839. // $ins_data['source_uid'] = $uid;
  2840. $ins_data['signin_time'] = $today_signintime;
  2841. $ins_data['addtime'] = time();
  2842. $ins_data['status'] = $status;
  2843. $ins_data['mark'] = $mark;
  2844. $ins_data['source_type'] = $type;
  2845. $ins_data['settlement_time'] = $settlement_time;// 结算时间 真正到了结算时间会结算
  2846. $ins_data['order_id'] = $order_id;
  2847. $ins_data['pm'] = $pm;
  2848. $ins_data['order_type'] = $order_type;
  2849. // $ins_data['surplus'] = 0;
  2850. Db::name('user_sign_score')->insertGetId($ins_data);
  2851. if($pm == 1 && $status == 1){
  2852. Db::name('user')->where('uid',$uid)->inc('score', $score)->update();
  2853. }
  2854. if($pm == 2){
  2855. Db::name('user')->where('uid', $uid)->dec('score', $score)->update();
  2856. }
  2857. }
  2858. public function gold_add($uid,$gold,$mark,$pm=1){
  2859. $ins['uid'] = $uid;
  2860. $ins['gold'] = $gold;
  2861. $ins['mark'] = $mark;
  2862. $ins['time'] = time();
  2863. $ins['pm'] = $pm;
  2864. $id = Db::name('user_gold_log')->insertGetId($ins);
  2865. if($pm == 1){
  2866. Db::name('user_gold')->where('uid',$uid)->inc('now_gold', $gold)->inc('cumulative', $gold)->update();
  2867. }else{
  2868. Db::name('user_gold') -> where('uid',$uid) -> dec('now_gold', $gold)->update();
  2869. }
  2870. $surplus = Db::name('user_gold')->where('uid',$uid)->value('now_gold');
  2871. Db::name('user_gold_log') -> where('id',$id) -> update(['surplus'=>$surplus]);
  2872. }
  2873. function get_level_list(){
  2874. try {
  2875. $tokenInfo = (request()->tokenInfo());
  2876. if(isset($tokenInfo->jti[1]) && $tokenInfo->jti[1]=='admin') {
  2877. $admin_id = request()->adminId();
  2878. $roles_str = Db::name('system_admin')->where('admin_id', $admin_id)->value('roles');
  2879. $phone_count = Db::name('system_role')->whereIn('role_id', $roles_str)->where("phone !=''")->count();
  2880. if ($phone_count) {
  2881. return true;
  2882. }
  2883. }
  2884. }catch (Exception $e) {
  2885. return false;
  2886. }
  2887. return false;
  2888. // $phone_data=Db::name('system_role')->whereIn('role_id',$roles_str)->where("phone !=''")->group("phone")->column('phone');
  2889. // if($phone_data){
  2890. // $uid_data = Db::name('user')->whereIn('phone', $phone_data)->column('uid');
  2891. // if($uid_data){
  2892. // $uids=$this->level_list($uid_data,0);
  2893. // }
  2894. // }
  2895. // }
  2896. // return isset($uids)?$uids:[];
  2897. }
  2898. // function level_list($uid_data,$i){
  2899. // $i++;
  2900. // $uid = Db::name('user')->whereIn('level_id', $uid_data)->column('uid');
  2901. // if($uid && $i<9){
  2902. // $uid_data=array_merge($uid_data,$uid);
  2903. // return $this->level_list($uid_data,$i);
  2904. // }else{
  2905. // return $uid_data;
  2906. // }
  2907. // }
  2908. public function sign_yhc_add($uid,$mer_id,$score,$mark,$order_id=0,$pm=1,$use_uid=0){
  2909. $ins_data['uid'] = $uid;
  2910. $ins_data['mer_id'] = $mer_id;
  2911. $ins_data['mark'] = $mark;
  2912. $ins_data['order_id'] = $order_id;
  2913. $ins_data['pm'] = $pm;
  2914. $ins_data['reward_socre'] = $score;
  2915. $ins_data['use_uid'] = $use_uid;
  2916. try {
  2917. Db::transaction(function () use ($ins_data,$pm,$mer_id,$score,$uid) {
  2918. $id = Db::name('enterprise_user_score')->insertGetId($ins_data);
  2919. if($pm == 2){
  2920. Db::name('enterprise_user') -> where('uid',$uid)-> where('mer_id',$mer_id) -> dec('green_integral',$score)->update();
  2921. }else if ($pm==1){
  2922. Db::name('enterprise_user') -> where('uid',$uid)-> where('mer_id',$mer_id) -> inc('green_integral',$score)->update();
  2923. }
  2924. $green_integral=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('uid',$uid)->value('green_integral');
  2925. if($green_integral<0){
  2926. throw new \Exception('修改失败,用户红积分不足,请刷新后再试');
  2927. }
  2928. });
  2929. }catch (\Exception $e){
  2930. return false;
  2931. }
  2932. return true;
  2933. }
  2934. /**
  2935. * 获取下级所有团队列表
  2936. * @param $uid
  2937. * @return int
  2938. */
  2939. public function getSpreadUidBreak($uid){
  2940. $sql = "select getUserSpreadId($uid) as uids";
  2941. $count = Db::query($sql);
  2942. $count[0]['uids'] = trim($count[0]['uids'],'$,');
  2943. $originalArray = explode(",",$count[0]['uids']);
  2944. $resultArray = array_diff($originalArray, [$uid]);
  2945. return $resultArray;
  2946. }
  2947. /**
  2948. * 设置用户 身份
  2949. * @param $uid
  2950. * @param $identityId
  2951. * @return int|mixed|null
  2952. * @throws DbException
  2953. */
  2954. public function setUserIdentity($uid, $identityId = null)
  2955. {
  2956. if (empty($identityId)) {
  2957. $identityId = $this->getUserIdentity($uid);
  2958. }
  2959. $userData = $this->dao->get($uid)->toArray();
  2960. $data = ['user_group' => $identityId];
  2961. if (empty($userData['identity_up_time'] ?? null) && $userData['user_group'] == 1 && $identityId > 1) {
  2962. $data['identity_up_time'] = date('Y-m-d H:i:s');
  2963. }
  2964. $this->dao->update($uid, $data);
  2965. return $identityId;
  2966. }
  2967. /**
  2968. * 获取用户 身份
  2969. * @param $uid
  2970. * @return int|mixed
  2971. * @throws DataNotFoundException
  2972. * @throws DbException
  2973. * @throws ModelNotFoundException
  2974. */
  2975. public function getUserIdentity($uid)
  2976. {
  2977. // 1、获取所有等级信息
  2978. /** @var UserIdentityRepository $identityRepository */
  2979. $identityRepository = app()->make(UserIdentityRepository::class);
  2980. $identityList = $identityRepository->getIdentityList();
  2981. // 2、获取身份需要的最深等级
  2982. $lowerLevelNumList = array_column($identityList, 'lower_level_num');
  2983. $lowerLevelNumMax = max($lowerLevelNumList);
  2984. $lowerLevelNumMin = min($lowerLevelNumList);
  2985. // 获取需要 递归最深的层数,比如 高级合伙人需要递归10层 普通用户需要递归一层
  2986. $needLower = 0;
  2987. // 0 代表要递归无限极 -1 代表一级也不查
  2988. if($lowerLevelNumMin > 0) {
  2989. $needLower = $lowerLevelNumMax;
  2990. }
  2991. // 最大等级限制
  2992. $maxLvRestrict = 0;
  2993. // 3、获取个人贡献值
  2994. $userData = $this->dao->get($uid)->toArray();
  2995. // 这一步骤是为了 确定用户升级时间,因为后边的团队贡献值,需要查询 用户 升级为业务员后 所产生的团队贡献值
  2996. $determineResult = $this->determineUserUpgradeTime($uid);
  2997. $userData['user_group'] = $determineResult['user_group'];
  2998. $userData['identity_up_time'] = $determineResult['identity_up_time'];
  2999. $startTime = $userData['identity_up_time'];
  3000. $endTime = date('Y-m-d H:i:s');
  3001. // 如果用户身份 为 用户 或者 升级成业务员的时间为空 则无法计算它的团队贡献值
  3002. if ($userData['user_group'] == 1 || empty($startTime)) {
  3003. $maxLvRestrict = 2;
  3004. $needLower = -1;
  3005. }
  3006. // 4、获取下级用户 贡献值
  3007. $userContributionSumMap = $this->getSubordinateContributeByUid($uid, $startTime, $endTime, $needLower);
  3008. // 5、将用户等级由低到高
  3009. usort($identityList, function ($a, $b) {
  3010. return $a['user_group_id'] <=> $b['user_group_id'];
  3011. });
  3012. // 循环记录 如果贡献值 满足了初级合伙人身份 并记录该身份ID,继续下一阶段循环,下一阶段不满足 则该用户身份为初级合伙人
  3013. $identityId = 0;
  3014. foreach ($identityList as $item) {
  3015. $lowerLevelNum = $item['lower_level_num']??0;
  3016. $arriveNumOwn = $userData['contribute'];
  3017. $arriveNumTeam = 0;
  3018. $subordinateContribution = [];
  3019. // 只有 业务员及以上才需要团队贡献值
  3020. if ($item['user_group_id'] > 1) {
  3021. foreach ($userContributionSumMap as $key => $value) {
  3022. $subordinateContribution[$key] = 0;
  3023. if ($lowerLevelNum != 0) {
  3024. foreach ($value as $k => $v) {
  3025. if ($k < $lowerLevelNum) {
  3026. $subordinateContribution[$key] += $v;
  3027. }
  3028. }
  3029. } else {
  3030. $subordinateContribution[$key] = array_sum($value);
  3031. }
  3032. }
  3033. if (!empty($subordinateContribution)) {
  3034. // 大区业绩
  3035. $dqYj = max($subordinateContribution);
  3036. // 总业绩
  3037. $zYj = array_sum($subordinateContribution);
  3038. // 小区团体业绩
  3039. $arriveNumTeam = bcsub($zYj, $dqYj, 2);
  3040. }
  3041. }
  3042. // 从小向大循环,满足则去 下一等级继续验证,不满足 则 返回上次循环记录的值,并结束循环
  3043. if ($item['arrive_num_own'] <= $arriveNumOwn && $item['arrive_num_team'] <= $arriveNumTeam) {
  3044. $identityId = $item['user_group_id'];
  3045. // 用户等级限制,本次获取身份 最大可获取什么身份,比如 用户没有 团队贡献值,他最高只能升到 2 级 即业务员
  3046. if ($identityId == $maxLvRestrict) {
  3047. break;
  3048. }
  3049. } else {
  3050. break;
  3051. }
  3052. }
  3053. return $identityId;
  3054. }
  3055. /**
  3056. * 获取该会员的所有下级会员
  3057. * @param array $uidList
  3058. * @return array
  3059. * @throws DataNotFoundException
  3060. * @throws DbException
  3061. * @throws ModelNotFoundException
  3062. */
  3063. public function getUidContributeListBySpreadUidList(array $uidList)
  3064. {
  3065. return Db::name("user")
  3066. ->whereIn("spread_uid", $uidList)
  3067. ->field("uid, contribute, spread_uid")
  3068. ->select()
  3069. ->toArray();
  3070. }
  3071. /**
  3072. * 计算指定用户下属每一层级的总贡献值。
  3073. *
  3074. * @param array $initialUserIds 初始用户ID列表 (视为第0层)。
  3075. * @param int $maxDepth 需要查询的最大深度(相对于初始列表)。
  3076. * 0 表示查询所有层级直到末端。
  3077. * 1 表示只计算第1层(直接下级)的总贡献。
  3078. * N 表示计算到第 N 层(包含第N层)的总贡献。
  3079. * @param int $is_old
  3080. * @param null $startTime
  3081. * @param null $endTime
  3082. * @return array 返回一个数组,键是层级号(从1开始),值是该层级所有用户的贡献值总和。
  3083. * 例如:[ 1 => 600, 2 => 1300 ]
  3084. * @throws DataNotFoundException
  3085. * @throws DbException
  3086. * @throws ModelNotFoundException
  3087. */
  3088. public function getContributionSumByLevel(array $initialUserIds, int $maxDepth = 0, $is_old = 0, $startTime = null, $endTime = null): array
  3089. {
  3090. $levelContributions = []; // 结果数组 [level => total_contribution]
  3091. if (empty($initialUserIds)) {
  3092. return $levelContributions;
  3093. }
  3094. $currentLevelIds = $initialUserIds; // 当前层级的用户ID (初始为第0层)
  3095. $currentLevel = 0; // 当前层级号
  3096. // 使用一个集合跟踪所有已处理过的下级用户ID,防止重复计算和循环
  3097. $processedSubordinateIds = [];
  3098. while (!empty($currentLevelIds)) {
  3099. // 计算下一层级的编号
  3100. $nextLevel = $currentLevel + 1;
  3101. // 检查是否达到最大深度限制
  3102. if ($maxDepth > 0 && $nextLevel > $maxDepth) {
  3103. break; // 停止查询更深的层级
  3104. }
  3105. // 批量查询当前层级用户的直接下级
  3106. // 使用 array_chunk 防止 WHERE IN 子句过长 (根据数据库限制调整 chunkSize)
  3107. $chunkSize = 500;
  3108. $subordinatesOfCurrentLevel = [];
  3109. foreach(array_chunk($currentLevelIds, $chunkSize) as $chunk) {
  3110. $subordinatesChunk = Db::name('user')
  3111. ->field('uid') // 只需要下级的uid
  3112. ->whereIn('spread_uid', $chunk) // spread_uid 在当前层级用户块中
  3113. ->where('status', 1)
  3114. ->select()
  3115. ->toArray();
  3116. $subordinatesOfCurrentLevel = array_merge($subordinatesOfCurrentLevel, $subordinatesChunk);
  3117. }
  3118. // 如果没有找到任何下级,结束循环
  3119. if (empty($subordinatesOfCurrentLevel)) {
  3120. break;
  3121. }
  3122. // 如果 传入 $startTime 不为空 证明当前在 确定身份的 用户已经是 业务员了
  3123. if (!empty($startTime)) {
  3124. $subordinatesOfCurrentLevelUidList = $this->getUserContributeByUidList(array_column($subordinatesOfCurrentLevel, 'uid'), $startTime, $endTime);
  3125. // // 用户有贡献值记录,我们要根据 用户的身份 从普通消费者 升级 成业务员 的时间来 查询时间范围内产生的贡献值
  3126. // $userSignGongxianList = Db::name('user_sign_gongxian')
  3127. // ->whereIn('uid', array_keys($subordinatesOfCurrentLevelUidList))
  3128. // ->where('addtime', '>=', strtotime($startTime)) // `addtime` int(10) NOT NULL COMMENT '添加时间'
  3129. // ->where('status', 1) // 贡献值状态1-有效 0-失效 -1待确认
  3130. // ->whereNotNull('settlement_time') // `settlement_time` datetime DEFAULT NULL COMMENT '结算时间',
  3131. // ->field('uid, number, type') // 只需要下级的uid和贡献值
  3132. // ->select()
  3133. // ->toArray();
  3134. // foreach ($userSignGongxianList as $value) {
  3135. // if($value['type'] == 1) {
  3136. // $subordinatesOfCurrentLevelUidList[$value['uid']] += $value['number'];
  3137. // } else {
  3138. // $subordinatesOfCurrentLevelUidList[$value['uid']] -= $value['number'];
  3139. // }
  3140. // }
  3141. //
  3142. // if ($is_old == 1) {
  3143. // // 如果是老用户,除了通过贡献值记录表 还要计算 老订单 产生的贡献值
  3144. // $oldUserOfGoodsList = Db::name('old_user_of_goods')
  3145. // ->whereIn('user_id', array_keys($subordinatesOfCurrentLevelUidList))
  3146. // ->where('create_time', '>=', strtotime($startTime)) // `addtime` int(10) NOT NULL COMMENT '添加时间'
  3147. // ->where('status', 1) // '是否完成 0, 未完成 1 已完成',
  3148. // ->field('user_id, money, status, create_time') // 只需要下级的uid和贡献值
  3149. // ->select()
  3150. // ->toArray();
  3151. //
  3152. // foreach ($oldUserOfGoodsList as $storeProductData) {
  3153. // if ($storeProductData['money'] == 1180) {
  3154. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 700;
  3155. // } else if ($storeProductData['money'] == 10620) {
  3156. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 6300;
  3157. // } else if ($storeProductData['money'] == 11800) {
  3158. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 7000;
  3159. // } else if ($storeProductData['money'] == 9440) {
  3160. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 5600;
  3161. // } else if ($storeProductData['money'] == 2360) {
  3162. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += 1400;
  3163. // } else {
  3164. // $subordinatesOfCurrentLevelUidList[$storeProductData['user_id']] += bcmul($storeProductData['money'], 0.7, 2);
  3165. // }
  3166. // }
  3167. // }
  3168. } else {
  3169. // 如果传入的 $identity_up_time 为空,说明该用户只是一个普通用户(消费者),没有团队业绩
  3170. break;
  3171. }
  3172. $nextLevelTotalContribution = 0;
  3173. $nextLevelIds = []; // 存储下一轮需要查询的用户ID
  3174. // 遍历找到的所有下级
  3175. foreach ($subordinatesOfCurrentLevel as $subordinate) {
  3176. $subordinateId = $subordinate['uid'];
  3177. $subordinateContribution = $subordinatesOfCurrentLevelUidList[$subordinate['uid']] ?? 0; // 安全获取,默认为0
  3178. // 累加下一层级的总贡献值
  3179. // 注意:这里简单累加,如果一个下级同时被当前层多个用户推荐,其贡献会被计算多次
  3180. // 如果要求每个下级只贡献一次(即使有多个上级),需要调整逻辑,
  3181. // 例如在累加前检查 $processedSubordinateIds
  3182. // --- 修改点:确保每个下级贡献只被计算一次 ---
  3183. // if (!isset($processedSubordinateIds[$subordinateId])) { // 如果这个下级还没被处理过
  3184. $nextLevelTotalContribution += (float)$subordinateContribution;
  3185. // }
  3186. // 注释掉上面的检查,因为用户描述似乎是按层级直接累加,不管这个下级是否被上层处理过。
  3187. // 如果A1和A2都属于第1层,他们各自的下级B1和B2都属于第2层,B1和B2的贡献值直接加到第2层的总和里。
  3188. // 如果需要严格按“人”计算,即使一个人出现在多层或被多人推荐也只算一次,则需要解开注释并调整
  3189. // 收集下一轮需要查询的用户ID,同样需要防止重复处理
  3190. if (!isset($processedSubordinateIds[$subordinateId])) {
  3191. $nextLevelIds[] = $subordinateId;
  3192. // 标记这个下级ID已处理过,避免在更深层级中再次将其加入查询队列
  3193. $processedSubordinateIds[$subordinateId] = true;
  3194. }
  3195. }
  3196. // 存储下一层级的总贡献值 (只有当贡献值大于0或你想记录空层级时)
  3197. // 根据例子,我们只记录有贡献的层级,或者至少有用户的层级
  3198. if (!empty($subordinatesOfCurrentLevel)) { // 只要找到了下级就记录该层
  3199. $levelContributions[$nextLevel] = $nextLevelTotalContribution;
  3200. }
  3201. // 准备下一轮迭代
  3202. $currentLevelIds = array_unique($nextLevelIds); // 去重下一层的用户ID
  3203. $currentLevel = $nextLevel; // 更新当前层级
  3204. }
  3205. return $levelContributions;
  3206. }
  3207. /**
  3208. * 获取用户 历史的 个人贡献值记录
  3209. * @param $uidList
  3210. * @return array
  3211. * @throws DataNotFoundException
  3212. * @throws DbException
  3213. * @throws ModelNotFoundException
  3214. */
  3215. public function getUserContributeTimeMapByUidList($uidList) {
  3216. $userContributeTimeMap = [];
  3217. $userSignGongxianList = Db::name('user_sign_gongxian')
  3218. ->whereIn('uid', $uidList)
  3219. ->where('status', 1) // 贡献值状态1-有效 0-失效 -1待确认
  3220. ->whereNotNull('settlement_time') // `settlement_time` datetime DEFAULT NULL COMMENT '结算时间',
  3221. ->field('uid, number, type, mark, settlement_time') // 只需要下级的uid和贡献值
  3222. ->select()
  3223. ->toArray();
  3224. foreach ($userSignGongxianList as $value) {
  3225. // 贡献表中 包含多种类型的 贡献值记录,比如 用户消费商家获得赠送贡献值 , 推广获得的贡献值(直推),这些都不能算是 用户的 直接贡献值
  3226. // 只有 用户取消费 比如:购买 ** 商品、扫码消费获得赠送贡献值 等 才算做个人贡献值
  3227. if (strpos($value['mark'], "购买") !== false || strpos($value['mark'], "扫码") !== false) {
  3228. if($value['type'] == 1) {
  3229. $type = 1;
  3230. } else {
  3231. $type = 2;
  3232. }
  3233. $userContributeTimeMap[$value['uid']][] = [
  3234. 'type' => $type,
  3235. 'contribute' => $value['number'],
  3236. 'settlementTime' => $value['settlement_time']
  3237. ];
  3238. }
  3239. }
  3240. // 老订单 产生的贡献值 并未在 贡献记录表中
  3241. $oldUserOfGoodsList = Db::name('old_user_of_goods')
  3242. ->where('status', 1) // '是否完成 0, 未完成 1 已完成',
  3243. ->whereIn('user_id', $uidList)
  3244. ->field('user_id, money, status, create_time') // 只需要下级的uid和贡献值
  3245. ->select()
  3246. ->toArray();
  3247. // 定义一个映射数组,用于存储不同 money 对应的 contribute 值
  3248. $contributeMapping = [
  3249. 1180 => 700,
  3250. 10620 => 6300,
  3251. 11800 => 7000,
  3252. 9440 => 5600,
  3253. 2360 => 1400,
  3254. ];
  3255. // 遍历每个 $storeProductData
  3256. foreach ($oldUserOfGoodsList as $storeProductData) {
  3257. // 获取 money 的值
  3258. $money = $storeProductData['money'];
  3259. // 检查 money 是否在映射中
  3260. if (isset($contributeMapping[$money])) {
  3261. // 如果存在,则使用映射的值
  3262. $contribute = $contributeMapping[$money];
  3263. } else {
  3264. // 否则按默认规则计算
  3265. $contribute = bcmul($money, 0.7, 2);
  3266. }
  3267. // 将数据添加到 $userContributeTimeList
  3268. $userContributeTimeMap[$storeProductData['user_id']][] = [
  3269. 'type' => 1,
  3270. 'contribute' => $contribute,
  3271. 'settlementTime' => $storeProductData['create_time']
  3272. ];
  3273. }
  3274. foreach ($userContributeTimeMap as $key => &$subArray) {
  3275. usort($subArray, function ($a, $b) {
  3276. return strtotime($a['settlementTime']) - strtotime($b['settlementTime']);
  3277. });
  3278. }
  3279. return $userContributeTimeMap;
  3280. }
  3281. /**
  3282. * 获取用户升级成业务员的时间
  3283. * @param $uid
  3284. * @return mixed|string
  3285. * @throws DataNotFoundException
  3286. * @throws DbException
  3287. * @throws ModelNotFoundException
  3288. */
  3289. public function determineUserUpgradeTime($uid) {
  3290. $userData = $this->dao->get($uid)->toArray();
  3291. if (empty($userData['identity_up_time'])) {
  3292. $upArriveNumOwn = 0;
  3293. $yeWuYuanId = 0;
  3294. // 1、获取所有等级信息
  3295. /** @var UserIdentityRepository $identityRepository */
  3296. $identityRepository = app()->make(UserIdentityRepository::class);
  3297. $identityList = $identityRepository->getIdentityList();
  3298. foreach ($identityList as $value) {
  3299. if ($value['user_group_name'] == '业务员') {
  3300. $upArriveNumOwn = $value['arrive_num_own'];
  3301. $yeWuYuanId = $value['user_group_id'];
  3302. break;
  3303. }
  3304. }
  3305. // 2、获取用户贡献值 日志记录 对应时间
  3306. $userContributeTimeMap = $this->getUserContributeTimeMapByUidList([$uid]);
  3307. if (!empty($userContributeTimeMap[$uid])) {
  3308. $myArriveNumOwn = 0;
  3309. $myIdentityUpTime = '';
  3310. foreach ($userContributeTimeMap[$uid] as $value) {
  3311. if ($value['type'] == 1) {
  3312. $myArriveNumOwn += $value['contribute'];
  3313. } else {
  3314. $myArriveNumOwn -= $value['contribute'];
  3315. }
  3316. if ($myArriveNumOwn >= $upArriveNumOwn) {
  3317. $myIdentityUpTime = $value['settlementTime'];
  3318. break;
  3319. }
  3320. }
  3321. if (!empty($myIdentityUpTime) && !empty($yeWuYuanId)) {
  3322. $userData['identity_up_time'] = $myIdentityUpTime;
  3323. $userData['user_group'] = $yeWuYuanId;
  3324. $this->dao->update($uid, [
  3325. 'identity_up_time' => $userData['identity_up_time'],
  3326. 'user_group' => $yeWuYuanId
  3327. ]);
  3328. }
  3329. }
  3330. }
  3331. return [
  3332. 'user_group' => $userData['user_group'],
  3333. 'identity_up_time' => $userData['identity_up_time']
  3334. ];
  3335. }
  3336. /**
  3337. * 获取用户列表中 每个人 的 个人贡献值
  3338. * @param array $uidList
  3339. * @param null $startTime
  3340. * @param null $endTime
  3341. * @return array
  3342. * @throws DataNotFoundException
  3343. * @throws DbException
  3344. * @throws ModelNotFoundException
  3345. */
  3346. public function getUserContributeByUidList($uidList = [], $startTime = null, $endTime = null)
  3347. {
  3348. $subordinatesOfCurrentLevelUidList = [];
  3349. foreach ($uidList as $uid) {
  3350. $subordinatesOfCurrentLevelUidList[$uid] = 0;
  3351. }
  3352. $userContributeTimeMap = $this->getUserContributeTimeMapByUidList($uidList);
  3353. if (!empty($userContributeTimeMap)) {
  3354. foreach ($userContributeTimeMap as $uid => $contributeInfoList) {
  3355. foreach ($contributeInfoList as $value) {
  3356. // 跳过时间范围外的 贡献值
  3357. if (!empty($startTime) && strtotime($value['settlementTime']) < strtotime($startTime)) {
  3358. continue;
  3359. }
  3360. if (!empty($endTime) && strtotime($value['settlementTime']) > strtotime($endTime)) {
  3361. break;
  3362. }
  3363. if ($value['type'] == 1) {
  3364. $subordinatesOfCurrentLevelUidList[$uid] += $value['contribute'];
  3365. } else {
  3366. $subordinatesOfCurrentLevelUidList[$uid] -= $value['contribute'];
  3367. }
  3368. }
  3369. }
  3370. }
  3371. return $subordinatesOfCurrentLevelUidList;
  3372. }
  3373. /**
  3374. * 根据时间和递归层级 获取部门下 每一层级的 贡献值
  3375. * 假设 老大的 下级是 张三和李四, 董事(最高级身份)需要循环最深的等级是 3 级 得出来的结果↓ 这样是为了计算大小部门
  3376. * $userContributionSumMap[直属下级(部门)张三] =>[0 => 张三个人贡献值, 1 => 张三所有下级用户的个人贡献值, 2 => 张三所有下级用户的下级用户贡献值]
  3377. * $userContributionSumMap[直属下级(部门)李四] =>[0 => 李四个人贡献值, 1 => 李四所有下级用户的个人贡献值, 2 => 李四所有下级用户的下级用户贡献值]
  3378. * @param $uid
  3379. * @param null $startTime
  3380. * @param null $endTime
  3381. * @param int $depth
  3382. * @return array
  3383. * @throws DataNotFoundException
  3384. * @throws DbException
  3385. * @throws ModelNotFoundException
  3386. */
  3387. public function getSubordinateContributeByUid($uid, $startTime, $endTime, $depth = 10)
  3388. {
  3389. // 4、获取下级用户 贡献值
  3390. $userContributionSumMap = [];
  3391. if ($depth >= 0 && !empty($startTime)) {
  3392. // 获取用户的直属下级
  3393. $uidContributeList = $this->getUidContributeListBySpreadUidList([$uid]);
  3394. $uidContributeUidList = array_column($uidContributeList, 'uid');
  3395. $subordinatesOfCurrentLevelUidList = $this->getUserContributeByUidList($uidContributeUidList, $startTime, $endTime);
  3396. foreach ($uidContributeList as $uidContribute) {
  3397. $goOnDepth = $depth;
  3398. // 获取用户规定时间内 所产生的贡献值 第一级
  3399. $userContributionSumMap[$uidContribute['uid']]['0'] = $subordinatesOfCurrentLevelUidList[$uidContribute['uid']] ?? 0;
  3400. if ($depth == 1) {
  3401. continue;
  3402. } else if ($depth > 1){
  3403. $goOnDepth = $depth - 1;
  3404. }
  3405. // 获取每个下级(部门)的个人贡献值 $goOnDepth = 0 时表示无限递归
  3406. $contributionSumByLevel = $this->getContributionSumByLevel(
  3407. [$uidContribute['uid']],
  3408. $goOnDepth,
  3409. 0,
  3410. $startTime,
  3411. $endTime
  3412. );
  3413. $userContributionSumMap[$uidContribute['uid']] = array_merge($userContributionSumMap[$uidContribute['uid']], $contributionSumByLevel);
  3414. if (!empty($userContributionSumMap[$uidContribute['uid']])) {
  3415. ksort($userContributionSumMap[$uidContribute['uid']]);
  3416. }
  3417. // 假设 老大的 下级是 张三和李四, 董事(最高级身份)需要循环最深的等级是 3 级 得出来的结果↓ 这样是为了计算大小部门
  3418. // $userContributionSumMap[直属下级(部门)张三] =>[0 => 张三个人贡献值, 1 => 张三所有下级用户的个人贡献值, 2 => 张三所有下级用户的下级用户贡献值]
  3419. // $userContributionSumMap[直属下级(部门)李四] =>[0 => 李四个人贡献值, 1 => 李四所有下级用户的个人贡献值, 2 => 李四所有下级用户的下级用户贡献值]
  3420. }
  3421. }
  3422. return $userContributionSumMap;
  3423. }
  3424. /**
  3425. * 获取用户 团队贡献值信息
  3426. * @param $uid
  3427. * @param int $depth // 最深递归层级
  3428. * @param array $betweenTime // 贡献值获取范围
  3429. * @return array
  3430. * @throws DataNotFoundException
  3431. * @throws DbException
  3432. * @throws ModelNotFoundException
  3433. */
  3434. public function getUserContributeInfoByDepth($uid, $depth = 10, $betweenTime = [])
  3435. {
  3436. // 3、获取个人贡献值
  3437. $userData = $this->dao->get($uid)->toArray();
  3438. // 这一步骤是为了 确定用户升级时间,因为后边的团队贡献值,需要查询 用户 升级为业务员后 所产生的团队贡献值
  3439. $determineResult = $this->determineUserUpgradeTime($uid);
  3440. $userData['user_group'] = $determineResult['user_group'];
  3441. $userData['identity_up_time'] = $determineResult['identity_up_time']; // 获得的值 有可能是时间 有可能是 null
  3442. $startTime = $userData['identity_up_time'];
  3443. $endTime = date('Y-m-d H:i:s');
  3444. if (!empty($betweenTime) && !empty($betweenTime['startTime']) && !empty($betweenTime['endTime'])) {
  3445. if(empty($startTime) || strtotime($startTime) < strtotime($betweenTime['startTime'])) {
  3446. $startTime = $betweenTime['startTime'];
  3447. }
  3448. if(strtotime($betweenTime['endTime']) < strtotime($endTime)) {
  3449. $endTime = $betweenTime['endTime'];
  3450. }
  3451. }
  3452. // 如果用户身份是 用户 则
  3453. /**
  3454. * 如果用户身份是 用户,则不计算团队贡献值,因计算团队贡献值 需要升级成业务员后 再进行进行统计
  3455. * 如用户也统计团队贡献值可能会导致: 用户进入系统后,不进行消费,团队贡献值确增长迅速,等某时刻 他只要 进行消费,身份就会快速跃迁,不公平
  3456. * (1)达标贡献值=自己消费产生的贡献值
  3457. * (2)团队达标贡献值= 不计算团队
  3458. */
  3459. if ($userData['user_group'] == 1) {
  3460. $depth = -1;
  3461. }
  3462. // 4、获取下级用户 贡献值
  3463. $userContributionSumMap = $this->getSubordinateContributeByUid($uid, $startTime, $endTime, $depth);
  3464. $subordinateContribution = [];
  3465. foreach ($userContributionSumMap as $key => $value) {
  3466. $subordinateContribution[$key] = array_sum($value);
  3467. }
  3468. $dqYj = 0;
  3469. $arriveNumTeam = 0;
  3470. if (!empty($subordinateContribution)) {
  3471. // 大区业绩
  3472. $dqYj = max($subordinateContribution);
  3473. // 总业绩
  3474. $zYj = array_sum($subordinateContribution);
  3475. // 小区团体业绩
  3476. $arriveNumTeam = bcsub($zYj, $dqYj, 2);
  3477. }
  3478. return [
  3479. 'arriveNumTeam' => $arriveNumTeam, // 小部门贡献值和
  3480. 'contribute' => $userData['contribute'], // 个人贡献值
  3481. 'perContribute' => $userData['per_contribute'], // 直推贡献值
  3482. 'largeContribute' => $dqYj, // 大部门贡献值
  3483. 'subordinate' => $subordinateContribution // 各部门贡献值和
  3484. ];
  3485. }
  3486. }