UserRepository.php 170 KB

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