UserRepository.php 175 KB

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