UserRepository.php 178 KB

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