love_php/app/Models/User.php
2026-04-02 09:20:51 +08:00

2295 lines
73 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Models;
use App\Models\App\MsgHistory;
use App\Models\App\Team;
use App\Models\CloseProfileHistory;
use App\Models\App\Vote;
use App\Models\Live\ActivityUser;
use App\Models\Live\Article;
use App\Models\Live\ArticleComment;
use App\Traits\CanPreview;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Laravel\Passport\HasApiTokens;
use Actuallymab\LaravelComment\CanComment;
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Rememberable\Rememberable;
use Overtrue\LaravelFollow\Traits\CanLike;
use Overtrue\LaravelFollow\Traits\CanFavorite;
use App\Models\PositionHistory;
use App\Models\WrongInfoHistories;
use App\Utils\Http;
use App\Models\Rank;
use App\Models\Wechat;
use App\Models\ClientComment;
use App\Models\BannedHistory;
use App\Models\RecommendSingleHistory;
use App\Models\SingleProfile;
use App\Services\UserService;
use App\Models\Live\Viewer;
use App\Models\Live\ActivityUserRemark;
use App\Models\LinkingRequest;
use App\Services\IMService;
use App\Http\Response\ResponseJson;
use App\Models\Live\Asset;
use App\Models\Live\AssetLog;
use App\Models\ChatMessage;
use App\Models\Server\MerchantUser;
use Illuminate\Support\Facades\Cache;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
use CanComment;
use CanFollow, CanBeFollowed, CanLike, CanFavorite, CanPreview;
use SoftDeletes;
use Rememberable;
use ResponseJson;
//福恋客服手机号
public const SERVERMOBILE = ['15311111111'];
// 默认头像
public const DefaultAvatar = "https://images.ufutx.com/202108/06/e1b03db630b24fd818d1aa9967ce3fb1.png";
// 福恋logo
public const systemLogo = "https://image.fulllinkai.com/202111/08/bce088cd4b0ddf22b0f25df88671c29a.jpeg";
public const LOVEID = 1;
//福恋客服手机号alpha
public const SERVERMOBILEALPHA = ['13682473215'];
//福恋员工用户
public const FULLLINKIDS = [1, 625, 898, 61850, 42343, 48594, 49091, 49819, 647, 58701, 60889, 43020, 60744, 81685, 85172, 76429, 82400, 59078, 85037, 8163, 75247,79675, 86159, 94076, 3480, 8771, 49408, 52958, 58290, 61848, 70533, 70535, 70537, 70538, 74993, 86029, 93259, 97623, 97733,13170,6318, 161, 69938];
// public const FULLLINKIDS = StaffUser::pluck("user_id");
//福恋商户id
public const FULINKMERCHANTIDS = [1,5,10,590,40,7,276,59,327,22,411,32,443,69,596,522,714,525,894,491,305,991,709];
//APP完善资料
public const APPCOMPLETEINFO ='birthday,state,province,city,resident_province,resident_city,stature,weight,introduction,ideal_mate,interest_label,income';
public const APPMARRIAGEINFO = 'sex,birthday,slogan,belief';
//APP注册资料
public const BASEPROFILEINFO = ['birthday'];
public const BASEUSERINFO = ['sex', 'belief','nickname'];
//APP其他基本资料
public const OTHERPROFILEINFO = ['stature', 'weight', 'resident_province', 'resident_city', 'province', 'city', 'introduction'];
public const OTHERUSERINFO = ['industry', 'industry_sub', 'belief', 'photo'];
//小程序其他基本资料
public const MPOTHERPROFILEINFO = ['stature', 'weight', 'resident_province', 'resident_city', 'introduction'];
public const MPOTHERUSERINFO = ['industry', /*'industry_sub', 'belief',*/ 'photo'];
//小程序七项基本资料资料
public const MPBASEPROFILEINFO = ['birthday', 'province', 'city', 'state'];
public const MPBASEUSERINFO = ['nickname', 'sex', 'belief', 'photo', 'mobile'];
//recommend_user 推荐用户, friend 好友请求follow 关注好友remind_profile_photo 提醒上传生活照, moment 动态
public const ATTACHMSGTYPE = ['recommend_user', 'friend', 'follow', 'remind_profile_photo', 'moment'];
public const RECOMMENDINFO = ['photo', 'is_photo_audited','name', 'card_num', /*'is_approved',*/ 'is_real_approved'];
//小程序任务资料
public const TASKUSERINFO = ['nickname', 'sex', 'industry', 'belief', 'industry_sub'];
public const TASKPROFILEINFO = ['stature', 'weight', 'province', 'city', 'birthday', 'state', 'degree', 'graduate_school', 'resident_province', 'resident_city'];
//可以获得福币的资料
public const COINUSER = ['nickname', 'sex', 'industry', 'industry_sub', 'belief'];
public const COINPROFILE = ['stature', 'weight', 'province', 'city', 'birthday', 'state', 'degree', 'graduate_school', 'resident_province', 'resident_city', 'income', 'wechat_id'];
//小程序所有资料
public const MPALLUSER = ['photo', 'nickname', 'sex', 'mobile', 'industry', 'industry_sub', 'belief'];
public const MPALLPROFILE = ['stature', 'weight', 'province', 'city', 'birthday', 'state', 'resident_province', 'resident_city', 'income', 'introduction','ideal_mate', 'interest_hobby'];
//缓存用户信息key
public const RDUSERKEY = 'rd_user_';
//缓存用户活跃度key
public const RDLIVENESSKEY = 'rd_liveness_user_';
//缓存用户最近访问时间key
public const RDLASTTIMEKEY = 'rd_last_time_user_';
//缓存用户访问量
public const RDPREVIEWKEY = 'rd_preview_user_';
//缓存用户属性
public const RDUSERPROPERTY = ['fans_count', 'follow_count', 'friend_count', 'age', 'is_super_rank', 'preview_count', 'rank_deadline'];
//缓存用户地理位置
public const RDUSERPTKEY = 'rd_user_pt_';
//love_gpt 小恋
public const LOVE_GPT_USER_ID = 1;
public const LOVE_GPT_USER_ID_TEST = 130430;
//小天使id
public const CHERUB_ID = 69938;
public const CHERUB_ID_TEST = 130430;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'mobile', 'email', 'password', 'is_admin', 'rank_id', 'is_photo_audited', 'photo', 'avatar','circle_avatar', 'negative_score', 'nickname', 'from_openid', 'from_platform','from_activity_id', 'sex', 'belief', 'type', 'scene', 'from_user_id', 'approve_time','identification_photos','device_idfa','device_imei','my_qrcode'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token', 'card_num',
];
protected $home_location;
protected $post_location;
protected $appends = ['avatar'];
/*
* wechat info
*/
public function wechat()
{
return $this->hasOne(Wechat::class);
}
public function wrongInfo()
{
return $this->hasMany(WrongInfoHistories::class);
}
public function blackList()
{
return $this->hasMany(Blacklist::class);
}
public function linkBlackList()
{
return $this->hasMany(LinkingBlacklist::class);
}
public function recommendWechat()
{
return $this->hasONe(Wechat::class, 'openid', 'from_openid');
}
public function profileCourtship()
{
return $this->hasOne(ProfileCourtship::class);
}
public function sass_profileCourtship()
{
return $this->hasOne(ProfileCourtship::class)->select('sex','city','province','age','birthday','belief','state','stature','weight','resident_province','resident_city','income','degree','ideal_mate','introduction','interest_hobby','mate_conditon');
}
public function profileMarriage()
{
return $this->hasOne(ProfileMarriage::class);
}
public function userDetailQrcode()
{
return $this->hasOne(UserShareQrcode::class, 'user_id', 'id')->where('type', 4);
}
public function linkings()
{
return $this->hasMany(Linking::class);
}
public function bannedHistory()
{
return $this->hasMany(BannedHistory::class);
}
public function otherLinkings()
{
return $this->hasMany(Linking::class, 'user_linking_id');
}
public function asset()
{
return $this->hasOne(Live\Asset::class);
}
public function rank()
{
return $this->belongsTo('App\Models\Rank', 'rank_id', 'id');
}
public function goodMatch()
{
return $this->hasOne(GoodMatch::class, 'user_id', 'id');
}
public function matchmakerClient()
{
return $this->hasOne(MatchmakerClient::class, 'client_user_id', 'id');
}
public function isAdmin() {
return $this->is_admin;
}
public function profilePhoto()
{
return $this->hasMany(ProfilePhoto::class);
}
//被访问
public function userPreviewHistory()
{
return $this->hasMany(UserPreviewHistory::class, 'user_id');
}
public function rankHistories()
{
return $this->hasMany(RankHistory::class);
}
public function rankHistoriesV2()
{
return $this->hasMany(RankHistory::class);
}
public function homeRecommend()
{
return $this->hasOne(HomeRecommend::class);
}
public function userPreview()
{
return $this->hasMany(UserPreview::class);
}
public function positionHistory()
{
return $this->hasMany(PositionHistory::class);
}
public function referre()
{
return $this->hasOne(Referre::class);
}
public function addedBonus()
{
return $this->hasMany(AddedBonus::class);
}
public function bonus()
{
return $this->hasMany(Bonus::class);
}
public function clientComments()
{
return $this->hasMany(ClientComment::class)->orderBy('id', 'desc');
}
public function clientComment()
{
return $this->hasMany(ClientComment::class)->orderBy('created_at','desc');
}
public function orderRemarks()
{
return $this->hasMany(OrderRemarks::class);
}
public function community()
{
return $this->hasMany(community::class);
}
public function fromWechat()
{
return $this->hasOne(Wechat::class, 'openid', 'from_openid');
}
public function singleProfile()
{
return $this->hasOne(SingleProfile::class, 'user_id', 'id');
}
public function activityMember()
{
return $this->hasMany(ActivityMember::class);
}
public function orders()
{
return $this->hasMany(Order::class);
}
public function activityShareHistories()
{
return $this->hasMany(ActivityShareHistory::class);
}
//社群搜索记录
public function keywordHistories()
{
return $this->hasMany(KeywordHistory::class);
}
//网易云账号
public function IMUser()
{
return $this->hasOne(WangYiYunUser::class);
}
public function communityStar(){
return $this->hasOne(CommunityStar::class, 'user_id');
}
public function userInfo(){
return $this->hasOne(UserInfo::class,'user_id','id');
}
public function interactLive()
{
return $this->hasOne(InteractLive::class, 'user_id');
}
//直播卡
public function interactLiveCards()
{
return $this->hasMany(InteractLiveCard::class, 'user_id', 'id');
}
//福币
public function coin()
{
return $this->hasOne(Coin::class);
}
//福币记录
public function coinLogs()
{
return $this->hasMany(CoinLog::class);
}
public function interactLiveGiftLogs()
{
return $this->hasMany(InteractLiveGiftLog::class);
}
public function moments()
{
return $this->hasMany(Moment::class);
}
public function systemBlacklist()
{
return $this->hasOne(SystemBlacklist::class, 'user_id', 'id');
}
// public function comment(){
// return $this->hasMany(ArticleComment::class, 'user_id');
// }
public function feedbacker(){
return $this->hasMany(ArticleComment::class, 'feedback_id');
}
public function coinWithdrawLogs()
{
return $this->hasMany(CoinWithdrawLog::class);
}
public function feedback()
{
return $this->hasMany(FeedbackHistory::class,'user_id','id')->select('user_id','content');
}
public function feedbackv2()
{
return $this->hasMany(FeedbackHistory::class,'user_id','id')->select('user_id','content');
}
public function signLogs()
{
return $this->hasMany(SignLog::class);
}
//社群分类
public function groupAdmin(){
return $this->hasMany(CommunityGroupAdmin::class);
}
public function inviteLogs()
{
return $this->hasMany(InviteHistory::class, 'invite_user_id', 'id');
}
public function flashRoseLogs()
{
return $this->hasMany(FlashRoseLog::class);
}
public function flashRose()
{
return $this->hasOne(FlashRose::class);
}
public function userRemark()
{
return $this->hasMany(ActivityUserRemark::class,'user_id');
}
public function shareImgLogs()
{
return $this->hasMany(ShareImgLog::class);
}
public function viewer()
{
return $this->hasOne(Viewer::class);
}
public function areaUser(){
return $this->hasMany(AreaUser::class,'user_id','id');
}
//群聊
public function team()
{
return $this->belongsToMany(Team::class, 'user_team')
->orderBy('user_team.created_at', 'desc')
->withTimestamps()
->withPivot('mute');
}
//群主
public function owner()
{
return $this->hasOne(Team::class, 'owner');
}
//网易云信聊天记录
public function msgHistory()
{
return $this->hasOne(MsgHistory::class, 'owner');
}
public function closeProfile(){
return $this->hasOne(CloseProfileHistory::class);
}
public function operatorUser(){
return $this->hasOne(CloseProfileHistory::class,'operator','id');
}
/**
* 每日推荐
* @return [type] [description]
*/
public function recommendUsers()
{
return $this->hasMany(RecommendUser::class);
}
public function merchantUser()
{
return $this->hasOne(MerchantUser::class);
}
public function crmRole()
{
return $this->hasOne(CrmRole::class, 'user_id', 'id');
}
public function crmAdmin()
{
return $this->hasOne(CrmRole::class, 'user_id', 'id')->where('type', 'admin');
}
public function crmCService()
{
return $this->hasOne(CrmRole::class, 'user_id', 'id')->where('type', 'c_service');
}
public function crmTService()
{
return $this->hasOne(CrmRole::class, 'user_id', 'id')->where('type', 't_service');
}
public function crmUser()
{
return $this->hasOne(CrmUser::class, 'user_id', 'id');
}
public function crmUserLogs()
{
return $this->hasMany(CrmUserLog::class, 'user_id', 'id');
}
//是否好友
public function isFriend($user)
{
$id = $this->id;
$user_id = $user->id;
$count = Linking::where(function($sql) use($id, $user_id){
$sql->where(['user_id'=>$user_id, 'user_linking_id'=>$id]);
})->orWhere(function($sql) use($id, $user_id){
$sql->where(['user_id'=>$id, 'user_linking_id'=>$user_id]);
})->count();
return $count?true:false;
}
/**
* 当前会员等级
* @return [type] [description]
*/
public function currentRank()
{
$rank_id = $this->rank_id;
$history_rank = $this->rankHistories()->orderBy('rank_id', 'desc')->first();
if ($history_rank && $rank_id != $history_rank->rank_id) {
$this->update(['rank_id'=>$history_rank->rank_id]);
}elseif (empty($history_rank)) {
$this->update(['rank_id'=>0]);
}
return $history_rank;
}
public function rankName()
{
$history = $this->currentRank();
if (empty($history)) {
return $rank_name = '普通会员';
}
$rank_name = Rank::where('id', $history->rank_id)->value('name');
return $rank_name;
}
//添加访问记录
public function addUserPreview($user_id)
{
if ($this->id == $user_id || empty($this->mobile) || empty($this->photo)) {
return;
}
$preview = UserPreview::where(['user_id'=>$user_id, 'preview_user_id'=>$this->id])->first();
if (empty($preview)) {
$preview = UserPreview::create(['user_id'=>$user_id, 'preview_user_id'=>$this->id]);
}
//是否是隐身访问
if ($this->getAttributes()['hidden']) {
UserPreviewHistory::create(['user_id'=>$user_id, 'preview_user_id'=>$this->id, 'is_hidden'=>1]);
$preview->preview_time = date('Y-m-d H:i:s');
$preview->status = 1;
$preview->save();
}else{
UserPreviewHistory::create(['user_id'=>$user_id, 'preview_user_id'=>$this->id, 'is_hidden'=>0]);
$is_update = empty($preview->preview_time)?1:0;
$preview->preview_time = date('Y-m-d H:i:s');
$preview->status = 0;
$preview->save();
$content = '用户【'.$this->nickname.'】最近访问了你';
$this->sendIMAttachMsg($this->id, $user_id, 'preview', $content);
if ($is_update) {
$user = User::find($user_id);
if (empty($user)) return ;
$user->updateCacheUser('preview_count');
}
}
//缓存点击量
$rd_key = (self::RDPREVIEWKEY).$user_id;
if (Cache::has($rd_key)) {
Cache::increment($rd_key, 1);
}else{
$user = User::find($user_id);
$user->cachePreview();
}
return;
}
public function sendIMAttachMsg($sender, $receiver, $type, $content)
{
//发送自定义
$attach = [
'id'=>1,
'timestamp;'=>time(),
'sender'=>$sender,
'receiver'=>$receiver,
'type'=>$type,
'content'=>$content,
'needBadge'=>true,
];
$im_service = new IMService(env('IM_APP_KEY'), env("IM_APP_SECRET"));
$result = $im_service->sendAttachMsg($sender,0,$receiver,json_encode($attach));
return true;
}
//用户头像
public function userAvatar($user_id=null)
{
if (!empty($user_id)) {
$user = $this->where('id', $user_id)->first();
if(!$user)return '';
}else{
$user = $this;
//处理下面is_photo_audited拿不到数据做判断的情况
if (!isset($user->is_photo_audited) || !isset($user->photo) || !isset($user->sex)){
$user = (new $this)->where('id',$this->id ?? 0)->first() ?: $this;
}
}
if ($user->photo) {
$avatar = strstr($user->photo,'?x-oss-process=style/scale1')?$user->photo:$user->photo.'?x-oss-process=style/scale1';
} elseif ($user->app_avatar) {
$avatar = strstr($user->app_avatar,'?x-oss-process=style/scale1')?$user->app_avatar:$user->app_avatar.'?x-oss-process=style/scale1';
} /*elseif ($user->circle_avatar) {
$avatar = $user->circle_avatar;
}*/ elseif (empty($user->photo) && empty($user->app_avatar)) {
if ($user->sex == 1) {
// $avatar = 'http://images.ufutx.com/201811/12/0e8b72aae6fa640d9e73ed312edeebf3.png';
$avatar = "https://image.fulllinkai.com/202203/09/39cb4692a41a0a26efa4832e5e0bed91.png";
}elseif ($user->sex == 2) {
// $avatar = 'http://images.ufutx.com/201811/12/dddd79aa2c2fc6a6f35e641f6b8fb8f5.png';
$avatar = "https://image.fulllinkai.com/202203/09/b934cf1de643cc3716390eba2cb31085.png";
}else{
$avatar = 'https://image.fulllinkai.com/202203/09/cc1c73eb1a4941fef25a15cd1ff2f9df.png';
}
}
//审核中
if ($user->is_photo_audited == 0 && $user->photo){
if ($user->sex == 1) {
$avatar = "https://image.fulllinkai.com/202203/09/39cb4692a41a0a26efa4832e5e0bed91.png";
} elseif ($user->sex == 2) {
$avatar = "https://image.fulllinkai.com/202203/09/b934cf1de643cc3716390eba2cb31085.png";
} else {
$avatar = 'https://image.fulllinkai.com/202203/09/cc1c73eb1a4941fef25a15cd1ff2f9df.png';
}
}
return $avatar;
}
// avatar修改器
public function getAvatarAttribute()
{
return $this->userAvatar();
}
public function getphotoAttribute($value)
{
if ($this->is_photo_audited == -1) {
// return 'https://image.fulllinkai.com/202207/04/1fa9a906b956efa26852fb685a845fff.png';
//不通过 根据性别展示默认头像
if ($this->sex == 1) {
$value = "https://image.fulllinkai.com/202203/09/39cb4692a41a0a26efa4832e5e0bed91.png";
} elseif ($this->sex == 2) {
$value = "https://image.fulllinkai.com/202203/09/b934cf1de643cc3716390eba2cb31085.png";
} else {
$value = 'https://image.fulllinkai.com/202203/09/cc1c73eb1a4941fef25a15cd1ff2f9df.png';
}
}
return $value;
}
/**
* 是否是游客 1:是0
*/
public function getIsVisitorAttribute()
{
return ($this->mobile && $this->photo)?0:1;
}
/**
* 修改介绍人地址
* @return [type] [description]
*/
public function getAddress()
{
$location_longitude = $this->location_longitude;
$location_latitude = $this->location_latitude;
$result = $this->positionGetAddress($location_longitude, $location_latitude);
if (empty($result)) {
$result = $this->homeLocation();
$this->home_location = $result;
}else{
$this->post_location = $result;
}
if (!empty($result)) {
$this->ProfileMarriage()->update($result);
}
}
/**
* 坐标转地址
* @return
*/
public function positionGetAddress($location_longitude, $location_latitude)
{
//1.经纬度转地址
if (empty($location_longitude) || empty($location_latitude)) {
return false;
}
$localtion = $location_latitude.','.$location_longitude;
$url = "https://apis.map.qq.com/ws/geocoder/v1/?location=".$localtion.'&key=P43BZ-QSDCP-BMHDP-V3BTR-3EL45-KOFJL';
$result = json_decode(Http::http($url, [], 'GET'), true);
if ($result['status'] == 0) {
$address_component = $result['result']['address_component'];
if (count($address_component) && isset($address_component['province']) && isset($address_component['city'])) {
$result = [
'province'=>$address_component['province'],
'city'=>$address_component['city']
];
return $result;
}
return false;
}else{
return false;
}
return false;
}
/**
* 手机号归属地
* @return [type] [description]
*/
public function homeLocation($mobile=null)
{
if (empty($mobile)) {
$mobile = $this->mobile;
}
$host = "http://showphone.market.alicloudapi.com";
$path = "/6-1";
$method = "GET";
$appcode = "ad41385e76184cffab0a5dc7654f8db2";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$querys = "num=".$mobile;
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
if (1 == strpos("$".$host, "https://"))
{
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
$re = json_decode(curl_exec($curl), true);
if (isset($re['showapi_res_body'])) {
$body = $re['showapi_res_body'];
if (isset($body['prov']) && isset($body['city'])) {
$result['province'] = $body['prov'];
$result['city'] = $body['city'];
return $result;
}else{
return false;
}
}
return false;
}
public function getValidFormId()
{
$seven_day_age = date('Y-m-d H:i:s', strtotime('-7 day'));
$form = $this->formIds()->where('status', 0)->where('created_at', '>', $seven_day_age)->orderBy('id', 'asc')->first();
return $form;
}
/**
* 推荐人名称
*/
public function FromUsername()
{
$from_user_id = 0;
if ($this->from_openid) {
$from_user_id = Wechat::where('openid', $this->from_openid)->value('user_id');
}elseif ($this->from_user_id) {
$from_user_id = $this->from_user_id;
}elseif ($this->from_official_openid) {
$from_user_id = Wechat::where('openid', $this->from_official_openid)->value('user_id');
}
$from_user_name = null; //from_user_id = 13003
if ($from_user_id) {
$from_user_name = $this->where('id', $from_user_id)->value('name');
}
return $from_user_name;
}
public function FromUsernames()
{
$from_user_id = $this->from_user_id;
$from_user_name = null;
// dd(1);
if ($from_user_id) {
$from_user_name = $this->where('id', $from_user_id)->value('name');
}
return $from_user_name;
}
/**
* 是否是自己邀请注册的
* @param [type] $other_user [description]
* @return boolean [description]
*/
public function isInvited($other_user)
{
$user_id = $this->id;
$openid = $this->wechat->openid;
$official_openid = $this->wechat->official_openid;
if ($user_id == $other_user->id) {
return true;
}
$is_user_id = false;
$is_openid = false;
$is_official_openid = false;
if ($user_id == $other_user->from_user_id) {
$is_user_id = true;
}
if ($openid == $other_user->from_openid && $openid) {
$is_openid = true;
}
if ($official_openid == $other_user->from_official_openid && $official_openid) {
$is_official_openid = true;
}
if ($is_user_id || $is_openid || $is_official_openid) {
return true;
}
return false;
}
/**
* 是否被禁言
*/
public function isBanned($type)
{
if (empty($type)) {
return false;
}
$time = date('Y-m-d H:i:s');
$history = BannedHistory::where('user_id', $this->id)->where('type', $type)->where('end_time', '>=', $time)->first();
return $history;
}
/**
* 单身是否填写七项基本资料
*/
public function isCompletedHomeProfile()
{
if ($this->type == 'single') {
$profile = $this->profileCourtship;
if ($profile->province && $profile->city && $profile->sex && $profile->state && $profile->belief && $profile->max_age && $profile->min_age && $profile->birthday) {
return true;
}
return false;
}
}
/**
* 共同好友列表
*/
public function mutualFriends($request, $other_user)
{
//我的好友id
$my_friend_ids = $this->userFriendIds($this);
//Ta的好友id
$other_user_friend_ids = $this->userFriendIds($other_user);
//公共好友id
$mutual_friend_ids = array_intersect($my_friend_ids, $other_user_friend_ids);
$users = User::whereIn('id', $mutual_friend_ids)->with('profileCourtship', 'profileMarriage');
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$users = $users->where(function($sql) use($keyword){
$sql->where('name', 'like', '%'.$keyword.'%')
->orWhere('mobile', 'like', '%'.$keyword.'%');
});
}
$users = $users->paginate();
foreach ($users as $user) {
if ($user->type == 'single') {
$user->age = \CommonUtilsService::getAge($user->profileCourtship->birthday);
$user->stature = $user->profileCourtship->stature;
$user->city = $user->profileCourtship->city;
}else{
$user->age = \CommonUtilsService::getAge($user->profileMarriage->birthday);
$user->stature = '';
$user->city = $user->profileMarriage->city;
}
}
return $users;
}
public function userFriendIds($user)
{
//我的好友id
$ids = Linking::where('user_id', $user->id)->pluck('user_linking_id')->toArray();
$other_ids = Linking::where('user_linking_id', $user->id)->pluck('user_id')->toArray();
$my_friend_ids = array_merge($ids, $other_ids);
return $my_friend_ids;
}
public function hasRecommended()
{
$other_user_ids = RecommendSingleHistory::where('user_id', $this->id)->pluck('other_user_id')->toArray();
return $other_user_ids;
}
public function recommendSingles()
{
return $this->hasMany(RecommendSingleHistory::class, 'user_id', 'id');
}
public function recommendOtherSingles()
{
return $this->hasMany(RecommendSingleHistory::class, 'other_user_id', 'id');
}
public function recommendLinks()
{
return $this->hasMany(RecommendLinkingNew::class, 'id_users_left', 'id');
}
/**
* 是否关注福恋智能公众号
*/
public function hasSubscribeOfficial()
{
try {
$is_subscribe = 0;
$viewer = null;
$app = \WechatService::officialApp('new');
$official_openid = SingleProfile::where('user_id', $this->id)->value('openid');
if (empty($official_openid)) {
$viewer = Viewer::where('mobile', $this->mobile)->first();
}else{
$wechat_user = $app->user->get($official_openid);
if (array_key_exists('errmsg', $wechat_user)) {
$viewer = Viewer::where('mobile', $this->mobile)->first();
}else{
$result = !empty($wechat_user)&&count($wechat_user)&&isset($wechat_user['subscribe']);
$is_subscribe = $result?$wechat_user['subscribe']:0;
if ($is_subscribe != $this->is_subscribe) {
$this->is_subscribe = $is_subscribe;
$this->save();
}
return $is_subscribe;
}
}
if ($viewer) {
$official_openid = $viewer->openid;
$wechat_user = $app->user->get($official_openid);
if (array_key_exists('errmsg', $wechat_user)) {
return $is_subscribe;
}else{
$result = !empty($wechat_user)&&count($wechat_user)&&isset($wechat_user['subscribe']);
$is_subscribe = $result?$wechat_user['subscribe']:0;
}
}
if ($is_subscribe != $this->is_subscribe) {
$this->is_subscribe = $is_subscribe;
$this->save();
}
// \Log::info('userid'. $this->id. '-subscribe: '.$is_subscribe);
return $is_subscribe;
} catch (\Exception $e) {
$this->getError($e);
return 0;
}
}
public function isSubscribe($openid)
{
$is_subscribe = 0;
$app = \WechatService::officialApp('new');
$wechat_user = $app->user->get($openid);
if (array_key_exists('errmsg', $wechat_user)) {
throw new \Exception("获取用户微信信息失败");
}else{
$result = !empty($wechat_user)&&count($wechat_user)&&isset($wechat_user['subscribe']);
$is_subscribe = $result?$wechat_user['subscribe']:0;
}
return $is_subscribe?1:0;
}
static public function hasSubscribeOfficialWithOpenid($official_openid)
{
$app = \WechatService::officialApp();
$wechat_user = $app->user->get($official_openid);
$result = !empty($wechat_user)&&count($wechat_user)&&isset($wechat_user['subscribe']);
$is_subscribe = $result?$wechat_user['subscribe']:0;
return $is_subscribe;
}
/**
* 是否是临时会员
*/
public function isTempMember($user_id=0)
{
$user_id = $user_id?:$this->id;
$member = TempMember::where('user_id', $user_id)->where('status', 0)->first();
return $member?true:false;
}
/**
* 获取临时会员
* @return [type] [description]
*/
public function getTempRank()
{
$result = TempMember::where('user_id', $this->id)->first();
if ($result) {
return ['code'=>1, 'msg'=>'已领取过'];
}
TempMember::create([
'user_id'=>$this->id,
'status'=>0
]);
$this->temp_member = 1;
$this->save();
return true;
}
/**
* 是否是超级会员
*/
public function isSuperRank($user_id=0)
{
$now = date('Y-m-d H:i:s');
$user = $user_id?User::find($user_id):$this;
$rank = RankHistory::where('rank_id', $user->rank_id)->where('user_id', $user->id)->where('deadline','>', $now)->first();
$temp_rank = $this->isTempMember($user->id);
return $rank||$temp_rank?1:0;
}
/**
* 增减分享会员
*/
public function addSuperRank($day=0, $month=0, $type=null,$other_type=null)
{
try {
//修改会员等级
if ($this->rank_id != 9) {//超级会员
$this->rank_id = 9;
$this->save();
}
//增加会员记录
$history = RankHistory::where(['user_id'=>$this->id, 'rank_id'=>9])->orderBy('deadline','desc')->first();
if (empty($history)) {
$history = RankHistory::create(['user_id'=>$this->id, 'rank_id'=>9, 'type'=>$type,'other_type'=>$other_type]);
}
if ($history->deadline) {
if ($month) {
if ($type) {
RankHistory::create([
'user_id'=>$this->id,
'rank_id'=>9,
'deadline'=> date('Y-m-d H:i:s', strtotime('+'.$month.' month', strtotime($history->deadline))),
'type'=>$type,
'other_type'=>$other_type
]);
}else{
$history->deadline = date('Y-m-d H:i:s', strtotime('+'.$month.' month', strtotime($history->deadline)));
}
}
if ($day) {
if ($type) {
RankHistory::create([
'user_id'=>$this->id,
'rank_id'=>9,
'deadline'=> date('Y-m-d H:i:s', strtotime('+'.$day.' day', strtotime($history->deadline))),
'type'=>$type,
'other_type'=>$other_type
]);
}else{
$history->deadline = date('Y-m-d H:i:s', strtotime('+'.$day.' day', strtotime($history->deadline)));
}
}
}else{
if ($month) {
$history->deadline = date('Y-m-d H:i:s', strtotime('+'.$month.' month'));
}
if ($day) {
$history->deadline = date('Y-m-d H:i:s', strtotime('+'.$day.' day'));
}
$history->type = $type;
}
$history->save();
$this->updateCacheUser('is_super_rank');
$this->updateCacheUser('rank_deadline');
return true;
} catch (\Exception $e) {
return false;
}
}
/**
* 获取开通分类,会员记录的数量
*/
public function getSuperCount($user_id,$type,$other_type = null){
$deadline = date('Y-m-d H:i:s');
$rankHistory = RankHistory::where('deadline','>=',$deadline)
->where('user_id',$user_id)
->where('type',$type);
// dump($other_type);
if($other_type){
$rankHistory->where('other_type',$other_type);
}
return $rankHistory->count();
}
/**
* 是否可以兑换会员
*/
public function canGetSuperRank()
{
if (empty($this->wechat)) {
return 0;
}
$count = InviteHistory::where('invite_openid', $this->wechat->openid)->where('status', 0)->count();
return $count?1:0;
}
/**
* 是否可以领取24小时超级会员
*/
public function canGetDailySuperRank()
{
//判断资料是否完全
$user_service = new UserService();
$result = $user_service->profileIntegrity($this->profileCourtship, $this);
if ($result['total_count'] != $result['count']) {
return '领取失败,资料未完善';
}
//是否领取过
$count = TempMember::where('user_id', $this->id)->count();
if ($count) {
return '领取失败,已领取过临时会员';
}
//是否头像认证
if ($this->is_photo_audited != 1) {
return "领取失败,头像未通过认证";
}
//是否真人认证
if ($this->is_real_approved != 1) {
return '领取失败,未通过真人认证';
}
return false;
}
/**
* 获取直播id
* @return [type] [description]
*/
public function getViewerId()
{
try {
$unionid = $this->wechat?$this->wechat->unionid:null;
$mobile = $this->mobile;
$viewer_id = Viewer::where('user_id', $this->id)->value('id');
if (empty($viewer_id)) {
if (empty($unionid)) {
$viewer_id = Viewer::where('mobile', $mobile)->value('id');
}else{
$viewer_id = Viewer::where('unionid', $unionid)->value('id');
if (empty($viewer_id)) {
$viewer_id = Viewer::where('mobile', $mobile)->value('id');
}
}
}
return $viewer_id;
} catch (\Exception $e) {
\Log::error('获取直播用户失败');
return null;
}
}
/**
* 用户钱包
*/
public function userAsset()
{
try {
$asset = $this->asset;
if ($asset) return $asset;
$viewer_id = $this->getViewerId();
if (empty($viewer_id)) return null;
$asset = Asset::where('viewer_id', $viewer_id)->first();
if (empty($asset)) return null;
$asset->user_id = $this->id;
$asset->save();
if ($asset->viewer_id) {
AssetLog::where('viewer_id', $asset->viewer_id)->whereNull('user_id')->update(['user_id'=>$this->id]);
}
return $asset;
} catch (\Exception $e) {
$this->getError($e);
return null;
}
}
//访问器
public function getCircleAvatarAttribute($value)
{
if ($value) {
return $value;
}elseif ($this->sex == 1) {
return 'https://image.fulllinkai.com/202203/09/39cb4692a41a0a26efa4832e5e0bed91.png';
}elseif ($this->sex == 2) {
return 'https://image.fulllinkai.com/202203/09/b934cf1de643cc3716390eba2cb31085.png';
}else {
return 'https://image.fulllinkai.com/202203/09/cc1c73eb1a4941fef25a15cd1ff2f9df.png';
}
}
public function getNicknameAttribute($value)
{
if(!$value){
return "";
}else{
return $value;
}
}
//添加好友权限
public function addFriendPermission()
{
$start_time = date('Y-m-d');
$end_time = date('Y-m-d H:i:s');
//当天申请加好友次数
$friend_request_count = LinkingRequest::where('user_linking_id', $this->id)->whereBetween('created_at', [$start_time, $end_time])->count();
if ($friend_request_count > 7) {
return false;
}
return true;
}
public function createIMUser()
{
$im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET'));
$wyyUser = $this->IMUser;
$accid = config('app.env') == 'production'?$this->id:'alpha_'.$this->id;
// //创建网易云账号
$result = $im_service->createUserId($accid,$this->nickname,$props='{}',$this->app_avatar);
//\Log::info('创建网易云账号');
//\Log::info($result);
if ($result['code'] == 200) {
$wyyUser = $this->IMUser()->create([
'accid'=>$accid,
'name'=>$this->nickname,
'photo'=>$this->app_avatar,
'mobile'=>$this->mobile,
'gender'=>$this->sex?:0,
'token'=>$result['info']['token'],
]);
}elseif ($result['code'] == 414 && $result['desc'] == 'already register') {
if (empty($this->IMUser)) {
$result = $im_service->getUinfos([$accid]);
if ($result['code'] == 200) {
$info = $result['uinfos'][0];
$accid = '';
$name = '';
$gender = '';
if(array_key_exists("accid",$info)){
$accid = $info['accid'];
}
if(array_key_exists("name",$info)){
$name = $info['name'];
}
if(array_key_exists("gender",$info)){
$gender = $info['gender'];
}
$wyyUser = new WangYiYunUser();
$wyyUser->user_id = $accid;
$wyyUser->accid = $this->id;
$wyyUser->name = $name;
$wyyUser->gender = $gender;
$wyyUser->save();
}
}
}
return $wyyUser;
}
/**
* 添加网易好友
* @param [type] $user [description]
* @param [type] $otherUser [description]
*/
public function addIMFriend($otherUser, $msg='')
{
try {
$user = $this;
if ($user->id == $otherUser->id) {
return false;
}
$im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET'));
$accid = $user->id;
$faccid = $otherUser->id;
//创建im账号
if (empty($user->IMUser)) {
$user->createIMUser();
}
if (empty($otherUser->IMUser)) {
$otherUser->createIMUser();
}
$result = $im_service->addFriend($accid,$faccid,$type='1',$msg);
if ($result['code'] != 200) {
throw new \Exception("添加网易好友失败".json_encode($result), 1);
}
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 删除IM好友
* @param [type] $user 被删除的好友信息
* @return [type] [description]
*/
public function deleteIMFriend($user)
{
try {
$im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET'));
$accid = $this->id;
$faccid = $user->id;
//创建im账号
if (empty($this->IMUser)) {
$this->createIMUser();
}
if (empty($user->IMUser)) {
$user->createIMUser();
}
$result = $im_service->deleteFriend($accid,$faccid);
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 是否已经设置密码
* @return boolean [description]
*/
public function hasPassword()
{
$password = User::where('id', $this->id)->value("password");
return $password?1:0;
}
/**
* 好友数
* @return [type] [description]
*/
public function friendCount()
{
$user_ids = $this->userFriendIds($this);
$friend_count = User::whereIn('id', $user_ids)
->where('id', '!=', $this->id);
// if ($this->type =='single') {
// $friend_count = $friend_count->where('type', 'single');
// }else{
// $friend_count = $friend_count->where('type', '<>', 'single');
// }
$friend_count = $friend_count->count();
return $friend_count?:0;
}
//用户出生日期同步身份证
public function cardBirthdayToProfile($channel='')
{
//拿到身份证的出生日期
$result = \CommonUtilsService::checkCardBirhday($this->card_num);
if ($result['error'] != 2) {
return false;
}
$birthday = $result['tdate'];
if ($channel == 'app') {
$this->profileCourtship->birthday = $birthday;
$this->profileCourtship->save();
}else{
if ($this->type == 'single') {
if ($this->profileCourtship) {
$this->profileCourtship->birthday = $birthday;
$this->profileCourtship->save();
}
}else{
if ($this->profileMarriage) {
$this->profileMarriage->birthday = $birthday;
$this->profileMarriage->save();
}
}
}
return true;
}
public function isCompletedProfile($type)
{
try {
$result = 1;
switch ($type) {
case 'app_register_info':
$profile_info = self::BASEPROFILEINFO;
$user_info = self::BASEUSERINFO;
break;
case "mp_other_info":
$profile_info = self::MPOTHERPROFILEINFO;
$user_info = self::MPOTHERUSERINFO;
// if (empty($this->profilePhoto()->count())) return 0;
break;
case 'app_other_info':
$profile_info = self::OTHERPROFILEINFO;
$user_info = self::OTHERUSERINFO;
//是否有生活照
if (empty($this->profilePhoto()->count())) return 0;
break;
default:
# code...
break;
}
foreach ($profile_info as $info) {
if (empty($this->profileCourtship->$info)) {
$result = 0;
break;
}
}
unset($this->profileCourtship);
if (empty($result)) return $result;
foreach ($user_info as $info) {
if (empty($this->$info)) {
$result = 0;
break;
}
}
return $result;
} catch (\Exception $e) {
$this->getError($e);
return 0;
}
}
/**
* 检查创建直播间权限
* 1.红娘
* 2.未创建过直播间
* @return [type] [description]
*/
public function checkStoreLive()
{
try {
//判断是否是红娘
if (empty($this->live_match_maker)) return false;
return true;
} catch (\Exception $e) {//报错
$this->getError($e);
return false;
}
}
/**
* 检查申请相亲权限
* @param integer $live_id [当前直播间]
* @param integer $card_live_id [卡限制直播间]
* @return [type] [description]
*/
public function checkInteractApply($live_id, $card_live_id=0)
{
try {
$result = $this->isBanBylives($live_id);
if (is_array($result)) return $result;
// $result = $this->hasInteractLiveCard($card_live_id);
// if (is_array($result)) return $result;
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 是否有相亲卡
* @param [type] $card_live_id [description]
* @return boolean [description]
*/
public function hasInteractLiveCard($card_live_id)
{
$now_time = date('Y-m-d H:i:s');
//是否有直播卡
$card = InteractLiveCard::where('user_id', $this->id)->where(function($sql) use($card_live_id){
$sql->where('live_id', $card_live_id)->orWhere('live_id', 0);
})->where(function($sql) use($now_time){
$sql->where('end_time', '<', $now_time)->orWhereNull('end_time');
})->first();
if (empty($card)) return ['code'=>1, 'msg'=>'没有互动直播卡'];
return true;
}
/**
* 是否有足够的福币
* @return boolean [description]
*/
public function hasEnoughCoin($live)
{
try {
$coin_info = $this->coinInfo();
if ($this->sex == 1 && $coin_info->remain_amount < 10 * $live->male_fee) {
return ['code'=>1, 'msg'=>'福币金额不足以该直播间连麦,请先充值'];
}
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 是否被禁止
* @param [type] $live_id [description]
* @return boolean [description]
*/
public function isBanBylives($live_id)
{
//是否被禁止
$now_time = date('Y-m-d H:i:s');
$log = InteractLiveBanLog::where('user_id', $this->id)->where('live_id', $live_id)->where('start_time', '<', $now_time)->where('end_time', '>', $now_time)->orderBy('end_time', 'desc')->first();
if ($log) return ['code'=>1, 'msg'=>'已被禁止申请该直播间至'.$log->end_time];
return false;
}
/**
* 福币信息
* @return [type] [description]
*/
public function coinInfo()
{
try {
$coin_info = $this->coin;
if (empty($coin_info)) {
$coin_info = new Coin;
$coin_info->user_id = $this->id;
$coin_info->remain_amount = 0;
$coin_info->used_amount = 0;
$coin_info->amount_from_other = 0;
$coin_info->save();
}
return $coin_info;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
//可提现福币
public function user_coin($user_id)
{
//获取用户总福币
$total_coin = CoinLog::where('user_id',$user_id)
->where('type','RECSYSTEM')
->where(function ($query){
$query->where('remark', 'like','%邀请好友%')
->orWhere('remark', 'like','%城市群主服务%')
->orWhere('remark', 'like','%奖励%')
->orWhere('remark', 'like','%刘勇芳%')
->orWhere('remark', 'like','%钉钉%');
})->sum('coin');
//已提现
$cash = CoinWithdrawLog::where('user_id',$user_id)->where(function ($query){
$query->where('remark', 'like','%邀请好友%');
})->wherein('status',[0,1])->wherein('is_hooked',[0,1])->sum('value');
//获取活动获得的总福币
$remarkcan_remain_amount = $total_coin - $cash??0;
return $remarkcan_remain_amount;
}
/**
* 修改福币信息
* @param [type] $type 类型
* @param [type] $value 金额
* @param [type] $coin_type 福币类型 cash表示可提现other表示不可提现
* @return [type] [description]
*/
public function updateCoinInfo($type, $value, $coin_type='cash')
{
try {
$coin_info = $this->coinInfo();
if (empty($coin_info)) throw new \Exception("没有福币信息", 1);
$total_coin = $coin_info->remain_amount + $coin_info->amount_from_other;
if ($type == 'add') {
if ($coin_type == 'cash') {
$coin_info->increment('remain_amount', $value);
}else{
$coin_info->increment('amount_from_other', $value);
}
}elseif ($type == 'sub') {
if ($total_coin < $value) {
throw new \Exception("剩余福币不足", 1);
}
if ($coin_info->amount_from_other >= $value) {
$coin_info->decrement('amount_from_other', $value);
}else{
$sub_remain_amount = $value - $coin_info->amount_from_other;
$coin_info->decrement('amount_from_other', $coin_info->amount_from_other);
$coin_info->decrement('remain_amount', $sub_remain_amount);
}
$coin_info->increment('used_amount', $value);
}
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 增加福币记录
* @param [type] $type [description]
* @param [type] $type_id [description]
* @param [type] $value [description]
*/
public function addCoinLog($type, $type_id, $value, $remark='')
{
try {
$log = $this->coinLogs()->create([
'type'=>$type,
'coin'=>$value,
'type_id'=>$type_id,
'is_hooked'=>1,
'remark'=>$remark,
]);
return $log;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
public function addInteractLiveGift($send_user_id, $gift_id, $num, $total_coin)
{
$log = $this->interactLiveGiftLogs()->create([
'send_user_id'=>$send_user_id,
'gift_id'=>$gift_id,
'num'=>$num,
'total_coin'=>$total_coin
]);
return $log;
}
public function dynamic(){
return $this->hasMany(Dynamic::class);
}
public function dynamics()
{
$instance = new Dynamic();
$instance->setSuffix($this->id % 10);
$foreignKey = $this->getForeignKey();
$localKey = $this->getKeyName();
return new HasMany($instance->newQuery(), $this, $foreignKey, $localKey);
}
public function activityUser(){
return $this->hasMany(ActivityUser::class);
}
public function activityFollowUser(){
return $this->hasMany(ActivityUser::class, 'follow_user_id');
}
public function article(){
return $this->hasMany(Article::class);
}
public function role()
{
return $this->belongsToMany(Rbac\Role::class, 'admin_role_users', 'user_id', 'role_id');
}
public function admin()
{
return $this->hasMany(Admin::class);
}
public function unlikeMomentLogs()
{
return $this->hasMany(UnlikeMomentLog::class);
}
public function commentLive($live)
{
try {
InteractLiveComment::create([
'user_id'=>$this->id,
'live_id'=>$live->id,
'num'=>$live->num,
'label'=>json_encode(request()->input('label',[]), JSON_UNESCAPED_UNICODE),
'option'=>request()->input('option'),
'content'=>request()->input('content')
]);
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
public function chatMessageCountWithUser($user_id)
{
$system_type = ['remind','greet','notice'];
$count = ChatMessage::where('user_id', $this->id)->where('other_user_id', $user_id)->wherenotin('system_type',$system_type)->count();
return $count;
}
public function isIMFriend($user_id)
{
try {
$im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET'));
$arr = $im_service->getFriend($this->id, time(), strtotime(auth()->user()->created_at->toDateTimeString()));
$result = 0;
if ($arr['code'] == 200) {
$friends = $arr['friends'];
foreach ($friends as $friend) {
if ($friend['faccid'] == $user_id) {
$result = 1;
break;
}
}
}
return $result;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
// public function getIsPhotoAuditedAttribute($value)
// {
// $is_photo_audited = 0;
// if (empty($this->photo)) {
// $is_photo_audited = -1;
// }elseif ($this->photo && empty($value)) {
// $is_photo_audited = 0;
// }elseif ($this->photo && $value) {
// $is_photo_audited = 1;
// }
// return $is_photo_audited;
// }
public function getIsEducateApprovedAttribute($value)
{
$status = $this->approveLog()->where('type', 'educate')->orderBy('updated_at', 'desc')->value('status');
if ($status == 0 && is_numeric($status)) {//审核中
$value = 2;
}elseif ($status == 0 && !is_numeric($status)) {//无状态
$value = 3;
}elseif ($status == 1) {//通过
$value = 1;
}elseif ($status == -1) {//拒绝
$value = 0;
}
return $value;
}
public function getIsRealApprovedAttribute($value)
{
$log = $this->approveLog()->where('type', 'body')->orderBy('updated_at', 'desc')->first();
// $value = 0;
if ($log) {
$status = $log->status;
if (empty($status) && is_numeric($status)) {//0 审核中
$value = $log->ways?2:0;
}elseif (empty($status) && !is_numeric($status) && $value== 0) {//未提交审核
$value = 0;
}elseif (empty($status) && !is_numeric($status) && $value== 1) {//未提交审核
$value = 0;
}elseif ($status == 1 && $value ==1) {//通过
$value = 1;
}elseif ($status == -1) {//拒绝
$value = -1;
}
}else {
$value = 0;
}
return $value;
}
public function getIsApprovedAttribute($value)
{
$status = $this->approveLog()->where('type', 'name')->orderBy('updated_at', 'desc')->value('status');
if ($value == 1) {//认证成功
$value = 1;
}elseif ($value == 0 && $status == 0 && is_numeric($status)) {//认证中
$value = 2;
}elseif ($value == 0 && $status == -1) {//认证失败
$value = -1;
}elseif ($value == 0 && !is_numeric($status)) {//未提供认证
$value = 0;
}
return $value;
}
public function approveLog()
{
return $this->hasMany(ApproveHistory::class);
}
public function bodyApproveLog()
{
return $this->hasOne(ApproveHistory::class, 'user_id', 'id')->where('type', 'body');
}
public function updateApproveInfo($type, $status,$from_m_id=null,$extend=null)
{
try {
$user_service = new UserService();
//创建认证记录
$log = $this->approveLog()->firstOrCreate([
'type'=>$type,
]);
$log->from_user_id = $user_service->getFromParam('from_user_id');
$log->from_platform = $user_service->getFromParam('from_platform');
$log->from_m_id = $from_m_id;
$log->status = $status;
$log->extend = $extend ? json_encode($extend) : null;
$log->save();
//修改认证信息
switch ($type) {
case 'name':
$this->is_approved = $status;
break;
case 'body':
$this->is_real_approved = $status;
$this->card_num = request()->input('card_num');
$this->name = request()->input('name');
//修改生日记录
$this->cardBirthdayToProfile('app');
break;
case 'educate':
$this->is_educate_approved = $status;
break;
}
$this->save();
return $log;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 升级学历
* @param $extend
* @return void
*/
public function upgradeEducation($extend)
{
$user_service = new UserService();
//创建认证记录
$log = $this->approveLog()->firstOrCreate([
'type'=> 'educate',
]);
$log->from_user_id = $user_service->getFromParam('from_user_id');
$log->from_platform = $user_service->getFromParam('from_platform');
$log->from_m_id = null;
$log->status = 0;
$log->extend = $extend ? json_encode($extend) : null;
$log->save();
}
public function dislikeLogs()
{
return $this->hasMany(UserDislikeLog::class);
}
/**
* 资料修改记录
* @param [type] $old_data [description]
* @param [type] $new_data [description]
*/
public function addProfileChangeLog($old_data, $new_data)
{
if (count($old_data)) {
ProfileChangeHistory::create([
'user_id'=>$this->id,
'owner_user_id'=>$this->id,
'new_content'=>json_encode($new_data),
'old_content'=>json_encode($old_data)
]);
}
}
public function userFriendQuestion()
{
return $this->hasOne(UserFriendQuestion::class);
}
public function friendQuestions()
{
return $this->hasOne(FriendQuestion::class);
}
public function friendQuestion()
{
try {
$userFriendQuestion = $this->userFriendQuestion()->first();
$content = $userFriendQuestion?$userFriendQuestion->question->title:'';
return $content;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
public function scopePhoto($query)
{
return $query->whereNotNull('photo')->where('is_photo_audited', '<>', -1);
}
/**
* 获取排序
* @return [type] [description]
*/
public function giftIcons()
{
$logs = $this->interactLiveGiftLogs()->groupBy('gift_id')->selectRaw('sum(total_coin) as sum, user_id, gift_id')->orderBy('sum', 'desc')->with('gift')->limit(5)->get();
$icons = [];
foreach ($logs as $log) {
$icons[] = $log->gift->icon;
}
return $icons;
}
public function scopeRecommend($query)
{
return $query->fullinkUser()->where('type', 'single')->where('is_subscribe', 1)->where('hidden_profile', 'NONE');
}
public function scopeSingle($query)
{
return $query->where('type', 'single')->NotHidden();
}
public function scopeApprove($query)
{
return $query->where('is_approved', 1)->NotHidden();
}
public function scopePay($query)
{
return $query->where(function($sql) {
$sql->whereHas('orders', function($query){
$query->where('pay_status', 'PAID')->where('price', '>', 0);
});
});
}
public function scopeLinkData($query)
{
return $query->where('link_data', 1);
}
public function scopeFullinkUser($query)
{
return $query->whereNotIn('id', self::FULLLINKIDS);
}
public function isMessenger()
{
$is_messenger = 0;
$viewer_id = $this->getViewerId();
if ($viewer_id) {
$viewer = Viewer::with('messenger')->where('id', $viewer_id)->first();
if ($viewer && $viewer->messenger && $viewer->messenger->is_audit) {
$is_messenger = 1;
}
}
return $is_messenger;
}
public function totalCoin()
{
try {
$coin_obj = Coin::where('user_id', $this->id)->first();
if (empty($coin_obj)) return 0;
return $coin_obj->remain_amount + $coin_obj->amount_from_other;
} catch (\Exception $e) {
$this->getError($e);
return 0;
}
}
public function scopeNoFiveProfile($query)
{
return $query->where(function($sql){
$sql->whereNull('nickname')
->orWhereNull('sex')
->orWhere('sex', 0)
->orWhereNull('belief')
->orWhereHas('profileCourtship', function($sql){
$sql->whereNull('birthday')
->orWhereNull('province')
->orWhereNull('city');
});
});
}
public function withdrawer()
{
return $this->hasOne(CoinWithdrawer::class);
}
public function anchors()
{
return $this->hasMany(TeamLiveAnchor::class);
}
public function isAnchor($team_id)
{
$result = $this->anchors()->where('team_id', $team_id)->exists();
return $result?1:0;
}
public static function cacheUserKey($user_id)
{
return self::RDUSERKEY.$user_id;
}
public function cacheUserProperty($property)
{
switch ($property) {
case 'fans_count':
$result = $this->followers()->where('hidden_profile', '<>', 'ALLSEX')->count()?:0;
break;
case 'follow_count':
$result = $this->followings()->where('hidden_profile', '<>', 'ALLSEX')->count()?:0;
break;
case 'friend_count':
$user_id = $this->id;
$result = Linking::whereHas('user', function($sql){
})->whereHas('userLink', function($sql){
})->where(function($sql) use($user_id){
$sql->where('user_id',$user_id)->orWhere('user_linking_id', $user_id);
})->count();
break;
case 'age':
$profile = $this->profileCourtship;
$result = $profile? \CommonUtilsService::getAge($profile->birthday):0;
break;
case 'is_super_rank':
$result = $this->isSuperRank();
break;
case "preview_count":
// $result = $this->userPreview()->whereNotNull('preview_time')->whereHas('previewUser',function ($query){
// $query->where('hidden_profile', '<>', 'ALLSEX');
// })->count()?:0;
// if ($this->id == 58859) {
$result = UserPreviewHistory::whereHas('previewUser', function($sql) {
if ($this->type == 'single') {
$sql->where('sex', '<>', $this->sex)->where('type', 'single')->where('hidden_profile', '<>', 'ALLSEX');
}
})->where('user_id', $this->id)->where('is_hidden', 0)->groupBy('preview_user_id')
->get()->toArray();
$result = count($result)?:0;
// }
break;
case "rank_deadline":
$result = RankHistory::where('user_id', $this->id)->whereNotNull('deadline')->orderBy('deadline', 'desc')->value('deadline');
break;
default:
$result = $this->$property;
break;
}
return $result;
}
//缓存用户信息
public function cacheUser()
{
try {
$rd_user_key = self::cacheUserKey($this->id);
$property_arr = User::RDUSERPROPERTY;
if ($this->type == 'single') {
$this->profileCourtship;
}else{
$this->profileCourtship;
$this->profileMarriage;
}
foreach ($property_arr as $property) {
$result = $this->cacheUserProperty($property);
$this->$property = $result;
}
$result = Cache::put($rd_user_key, $this, now()->addMinutes(15));
return $result;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 修改缓存属性
* @return [type] [description]
*/
public function updateCacheUser($property)
{
try {
$rd_user_key = self::cacheUserKey($this->id);
if (Cache::has($rd_user_key)) {
$result = $this->cacheUserProperty($property);
$rd_user = Cache::get($rd_user_key);
$rd_user->$property = $result;
$result = Cache::put($rd_user_key, $rd_user, now()->addMinutes(15));
}else{
$result = $this->cacheUser();
}
return $result;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
public static function cachePreviewKey($user_id)
{
return self::RDPREVIEWKEY.$user_id;
}
public static function cachePtKey($user_id)
{
return self::RDUSERPTKEY.$user_id;
}
//缓存访问量信息
public function cachePreview()
{
try {
$rd_key = self::cachePreviewKey($this->id);
$count = $this->userPreviewHistory()->count()?:0;
$result = Cache::put($rd_key, $count, now()->addHours(24));
return $result;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 新增访问量
*/
public function addCachePreview()
{
$rd_key = self::cachePreviewKey($this->id);
Cache::increment($rd_key, 1);
return Cache::get($rd_key);
}
/**
* 用户点击量
*/
public function previewCacheCount()
{
try {
$rd_key = (self::RDPREVIEWKEY).$this->id;
if (Cache::has($rd_key)) {
$count = Cache::get($rd_key);
}else{
$count = $this->userPreviewHistory()->count()?:0;
Cache::put($rd_key, $count, now()->addHours(24));
}
return $count;
} catch (\Exception $e) {
$this->getError($e);
return 0;
}
}
//好友列表(成为好友顺序排序)
public function friends(){
return $this->belongsToMany(User::class, 'linkings', 'user_id', 'user_linking_id')
->orderBy('linkings.created_at', 'desc')
->withPivot('user_id','user_linking_id', 'created_at', 'id');
}
public function scopeType($query, $type)
{
return $query->where('type', $type);
}
public function scopeNotHidden($query)
{
return $query->where('hidden_profile', 'NONE');
}
//是否付费vip
public function cashVip(){
$order = Order::where('user_id',$this->id)->where('pay_status','PAID')->whereIn('type',['rank','single_service'])->first();
return $order ? 1 : 0;
}
/**
* 是否是测试号码
* @return bool
*/
public function getMobileAttribute($value)
{
$result = substr($value, 0, 4);
return ($result == 'love')?null:$value;
}
//超级管理员
public function superRole()
{
$role = $this->role()->where('name', '超级管理员')->first();
return $role;
}
public function portrait()
{
return $this->hasOne(Portrait::class, 'user_id', 'id');
}
public function completePortrait()
{
$portrait = $this->portrait;
if (empty($portrait)) return false;
$array = ['economic_requirement', 'work_requirement', 'body_requirement', 'child_requirement', 'area_requirement','belief_requirement','family_requirement',
'age_requirement', 'interest_label', 'marry_in', 'economic_situation_work', 'economic_situation_job', 'economic_situation_salary', 'economic_situation_house',
'character', 'raw_family', 'family_members', 'state'
];
foreach ($array as $val)
{
if (empty($portrait->$val)) return false;
}
return true;
}
public function earningUser()
{
return $this->hasOne(EarningUser::class, 'user_id', 'id');
}
public function exchangeLogs()
{
return $this->hasMany(CoinExchange::class);
}
//被投诉关联
public function complains()
{
return $this->hasMany(ComplaintHistory::class, 'complaint_id', 'id');
}
}