UserRepository.php 177 KB

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