UserRepository.php 171 KB

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