sms = $sms; $this->userService = new UserService(); $this->activityService = new ActivityService(); $this->momentCon = new MomentService($sms); Carbon::setLocale('zh'); } //通用发短信任务 public function sentMessage($mobile, $message) { $this->sms->sentMessage($mobile, $message); } //支付回调 public function checkMarkOrder() { // $trade_nos = PayOrder::where('is_hooked', 0)->pluck('trade_no'); $trade_nos = DB::table('pay_orders')->where('is_hooked')->pluck('trade_no'); foreach ($trade_nos as $trade_no) { $url = config('app.url') . '/api/mark/order/pay/' . $trade_no; Http::http($url, [], "GET"); } return 'ok'; } public function checkFailTransfer() { $histories = ReferreAwardHistory::where('is_hooked', -1)->get(); foreach ($histories as $history) { $trade_no = $history->trade_no; $openid = Wechat::where('user_id', $history->user_id)->value('openid'); if ($history->type === 'register') {//注册 $amount = 1 * 100; $desc = '推荐注册用户奖励(福恋小程序)'; } elseif ($history->type === 'approve') { $amount = 2 * 100; $desc = '推荐认证用户奖励(福恋小程序)'; } $result = \WechatService::userTransfer($trade_no, $openid, $amount, $desc); if ($result) { $history->is_hooked = 0; $history->save(); } else { } } return; } /** * 发送用户报告统计数据给商家 */ public function sendUserReportStatisticToMerchant() { $time = date('H') . ':00:00'; $merchant_configs = MerchantReport::where('notification_type', '!=', 0)->where('notification_time', $time) ->get(); foreach ($merchant_configs as $key => $val) { $openid = MerchantAccount::where('id', $val->m_id)->value('openid'); if (!$openid) { continue; } $order_count = TouristOrder::where('type', $val->type)->where('type_id', $val->type_id)->whereIn('pay_status', [1, 4]) ->count(); $order_ids = TouristOrder::where('type', $val->type)->where('type_id', $val->type_id)->whereIn('pay_status', [1, 4]) ->pluck('id')->toArray(); if ($val->notification_type == 1) { $add_time = Carbon::today()->toDateString(); $report_count = ReportAnswer::whereIn('m_order_id', $order_ids)->where('created_at', '>=', $add_time . ' 00:00:00') ->where('created_at', '>=', $add_time . ' 23:59:59')->count(); } elseif ($val->notification_type == 2) { $add_time = Carbon::today()->addDays(-1)->toDateString(); $report_count = ReportAnswer::whereIn('m_order_id', $order_ids)->where('created_at', '>=', $add_time . ' 00:00:00') ->where('created_at', '>=', $add_time . ' 23:59:59')->count(); } $activity = CommunityActivity::where('id', $val->type_id)->first(); $a = round($report_count / $order_count * 100, 2) . '%'; $tesk_name = ReportQuestion::where('type_id', $val->type_id)->where('type', $val->type)->value('title'); if (!$tesk_name) { continue; } $merchant = MerchantAccount::find($val->m_id); $param['openid'] = $openid; $param['first'] = $merchant->share_title . '您好'; $param['keyword1'] = $activity->title . ' ' . $add_time; $param['keyword2'] = $tesk_name; $param['keyword3'] = '共' . $a . ' (' . $report_count . '/' . $order_count . ') 人完成'; $param['remark'] = '请在后台查看详情'; \WechatService::reportStatisticNotice($param); } } //转账回调 public function checkReferreTransfer() { $histories = ReferreAwardHistory::where('is_hooked', 0)->get(); foreach ($histories as $history) { $result = \WechatService::transferred($history->trade_no); if ($result) { $history->is_hooked = 1; $history->save(); } else { $history->is_hooked = -1; $history->save(); } } return; } //清除没有支付的订单 public function checkUnpaidOrder() { try { $trade_nos = DB::table('pay_orders')->where('pay_status', 'UNPAID')->where('is_hooked', 0)->where('cash', '>', 0)->pluck('trade_no'); foreach ($trade_nos as $trade_no) { $pay_order = PayOrder::where('trade_no', $trade_no)->first(); if (empty($pay_order)) { continue; } $order = Order::where('trade_no', $trade_no)->first(); $now_time = date('Y-m-d H:i:s'); $order_time = $pay_order->created_at->toDateTimeString(); $compare_result = $this->compareTime($now_time, $order_time); if ($compare_result) { if ($order->pay_type == 'wechat') { $url = config('app.url') . '/api/app/callback/orders/' . $trade_no; $data = []; } else { continue; } $result = Http::post($url, $data); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function checkIOSUnpaidOrder() { try { $end_time = date('Y-m-d H:i:s'); $start_time = date('Y-m-d H:i:s', strtotime('-30 minute')); $orders = Order::with('payorder')->whereBetween('created_at', [$start_time, $end_time])->where('pay_type', 'ios')->where('pay_status', "UNPAID")->orderBy('id', 'desc')->get(); foreach ($orders as $order) { $url = config('app.url') . '/api/ios/orders/notify'; $data = [ 'trade_no' => $order->trade_no, 'apple_receipt' => $order->payorder->receipt ]; $result = Http::http($url, $data, 'POST'); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function compareTime($time1, $time2) { $str_time1 = strtotime($time1); $str_time2 = strtotime($time2) + 30 * 24 * 3600; if ($str_time1 >= $str_time2) {//已過期 return false; } else { return true; } } /** * 检测退款订单 * @return [type] [description] */ public function chechRefundOrder() { try { //活动退款 $refund_orders = RefundOrder::where('type', '<>', 'approve')->where('is_hook', 0)->get(); foreach ($refund_orders as $order) { if ($order->refund_fee == 0) { RefundOrder::where('id', $order->id)->update(['is_hook' => 1]); } else { $result = \WechatService::orderRefunded($order->refund_trade_no); if ($result) { RefundOrder::where('id', $order->id)->update(['is_hook' => 1]); } } } //认证退费转账 $refund_orders = RefundOrder::where('type', 'approve')->where('is_hook', 0)->get(); foreach ($refund_orders as $order) { $result = \WechatService::transferred($order->refund_trade_no); if ($result) { $order->is_hook = 1; $order->save(); } } return; } catch (\Exception $e) { $this->getError($e); return false; } } //检测form_id是否失效 public function checkFormId() { try { $end_time = date('Y-m-d H:i:s', strtotime('-7 day')); $form_id_arr = DB::table('form_ids')->where('created_at', '<=', $end_time)->delete(); return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 添加好友 */ public function addFriend() { try { $openids = DB::table('wechats')->whereNotNull('user_id')->whereNotNull('deleted_at')->pluck('openid'); $users = DB::table('users')->whereIn('from_openid', $openids)->whereNotNull('from_openid')->where('from_openid', '<>', '')->whereNull('deleted_at') ->get(); foreach ($users as $user) { $user_id = $user->id; $send_user_id = DB::table('wechats')->where('openid', $user->from_openid)->value('user_id'); if ($send_user_id) { $link = Linking::where(function ($sql) use ($user_id, $send_user_id) { $sql->where('user_id', $user_id)->where('user_linking_id', $send_user_id); })->orWhere(function ($sql) use ($user_id, $send_user_id) { $sql->where('user_id', $send_user_id)->where('user_linking_id', $user_id); })->first(); if (empty($link)) { DB::table('linkings')->insert([ 'user_id' => $user_id, 'user_linking_id' => $send_user_id, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]); } } } return true; } catch (Exception $e) { $this->getError($e); return false; } } public function userMatchingRate() { $now_time = time(); $start_time = date('Y-m-d', strtotime('-1 day')); $user_ids = ProfileCourtship::where('updated_at', '>', $start_time)->whereNull('deleted_at')->pluck('user_id'); $other_users = User::with('profileCourtship')->whereHas('profileCourtship', function ($sql) { $sql->where('user_id', '>', 1); })->where('type', 'single')->where('sex', '>', 0)->orderBy('id', 'desc')->select('id', 'name', 'sex', 'type', 'created_at')->get()->toArray(); $single_men = []; $single_women = []; foreach ($other_users as $other_user) { if ($other_user['sex'] == 1) { $single_men[] = $other_user; } elseif ($other_user['sex'] == 2) { $single_women[] = $other_user; } } // foreach ($users as $user) { // if ($user->sex == 1) { // foreach ($single_women as $single_woman) { // $this->matchingRate($user, $single_woman); // } // }elseif ($user->sex == 2){ // foreach ($single_men as $single_man) { // $this->matchingRate($user, $single_man); // } // } // } return; } public function recommendNoticeNum() { //不接收的用户 $not_recommend_user_ids = [62617]; try { $user_list = []; $user_subscribe_list = []; User::fullinkUser()->where('type', 'single')->where('hidden_profile', 'NONE')->whereNotIn('id', $not_recommend_user_ids)->whereHas('recommendLinks')->chunk(100, function ($users) use (&$user_list, &$user_subscribe_list) { //获取未推荐的用户 foreach ($users as $user) { $link = RecommendLinkingNew::where('id_users_left', $user->id)->where('is_recommend', 1)->orderBy('score', 'desc')->orderBy('id', 'desc')->whereHas('otherUser', function ($sql) use ($user) { $sql->where('hidden_profile', 'NONE')->where('type', 'single')->photo() ->whereDoesntHave('recommendOtherSingles', function ($query) use ($user) { $query->where('user_id', $user->id); }); })->first(); if (empty($link)) continue; $user_list[] = $user->id; if ($user->is_subscribe == 1) { $user_subscribe_list[] = $user->id; } } }); $total_count = count($user_list); $subscribe_count = count($user_subscribe_list); $res = json_encode(['total_count' => $total_count, 'subscribe_count' => $subscribe_count]); Redis::set('recommend_num_' . date("Y-m-d"), $res); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function recommendSingleNotice() { //不接收的用户 $not_recommend_user_ids = [62617, 102978, 113649, 125766]; try { set_time_limit(0); $recommend_data = []; $user_list = []; User::recommend()->chunk(100, function ($users) use (&$recommend_data, &$user_list, $not_recommend_user_ids) { //获取未推荐的用户 foreach ($users as $user) { if (in_array($user->id, $not_recommend_user_ids)) continue; //已推荐用户 $other_user_ids = RecommendSingleHistory::where('user_id', $user->id)->pluck('other_user_id')->toArray(); //黑名单用户 $black_user_ids = LinkingBlacklist::where('user_id', $user->id)->pluck("other_user_id")->toArray(); $black_other_user_ids = LinkingBlacklist::where('other_user_id', $user->id)->pluck("user_id")->toArray(); $other_user_ids = array_merge($other_user_ids, User::FULLLINKIDS, $black_user_ids, $black_other_user_ids); $link = RecommendLinkingNew::with('otherUser', 'recommendLogs')->where('id_users_left', $user->id)->whereNotIn('id_users_right', $other_user_ids)->where('is_recommend', 1)->orderBy('score', 'desc')->orderBy('id', 'desc')->whereHas('otherUser', function ($sql) { $sql->where('hidden_profile', 'NONE')->where('type', 'single')->photo(); })->first(); if (empty($link)) { continue; } $user_list[] = $user->id; //发送推送模板消息 $result = $this->sendOfficialRecommend($user, $link->otherUser); if (!$result) { //发送小程序模板 $result = $this->sendMiniRecommend($user, $link->otherUser); } //推送通知 // $result = $this->momentCon->sendAttachMsg($link->otherUser->id, $type='recommend_user', $content='为你推荐匹配度高的用户['.$link->otherUser->nickname.']', $link->otherUser->id, $user->id, $user->app_avatar); if ($result) {//发送成功记录 $data['user_id'] = $user->id; $data['other_user_id'] = $link->otherUser->id; $data['created_at'] = date('Y-m-d H:i:s'); $data['updated_at'] = date('Y-m-d H:i:s'); $recommend_data[] = $data; } } return $recommend_data; }); $redis = Redis::connection('big_data'); $cronRecommendUserList = $redis->keys('cronRecommendUserList:*'); if (!empty($cronRecommendUserList)) { $redis->del($cronRecommendUserList); } $cronRecommendUserListKey = 'cronRecommendUserList:' . date('Y-m-d H:i:s'); $redis->set($cronRecommendUserListKey, json_encode(['data' => $user_list])); if (count($recommend_data)) { RecommendSingleHistory::insert($recommend_data); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 同步更新关注公众号 * @return [type] [description] */ public function syncIsSubscribe() { try { set_time_limit(0); User::linkData()->chunk(1000, function ($users) { foreach ($users as $user) { $result = $user->hasSubscribeOfficial(); } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function sendOfficialRecommend($user, $target_user) { if ($user->wechat) { $official_openid = Viewer::where('user_id', $user->id)->value('openid'); if (empty($official_openid)) { $official_openid = $user->wechat->official_openid; } if (empty($official_openid)) { \Log::info('没有公众号openid'); return false; } //是否关注公众号 $result = $user->is_subscribe; if ($result) { $param['user_id'] = $target_user->id; $param['user_name'] = $target_user->nickname; $param['openid'] = $official_openid; $param['channel'] = 'recommend'; $param['title'] = "今日推荐的嘉宾更新啦"; $param['host'] = '福恋'; $param['user_info'] = $this->checkUserInfo($user, $target_user); if (empty($param['user_info']) || empty($param['host']) || empty($param['user_name'])) { return false; } $param['remark'] = "快去和TA打个招呼吧!"; $result = \WechatService::agRecommendNotcie($param); } else { return false; } return true; } return false; } public function checkUserInfo($user, $target_user) { $info = '发现了一位'; //身高 $target_profile = $target_user->profileCourtship; if ($target_user->sex == 1) { $info = $info . '小哥哥不错'; if ($target_profile->stature >= ' 175') { $info = $info . ',身高' . $target_profile->stature; } } elseif ($target_user->sex == 2) { $info = $info . "小姐姐不错"; if ($target_profile->stature >= ' 175') { $info = $info . ',身高' . $target_profile->stature; } } else { return false; } //学历 $degree_arr = ['大专', '本科', '硕士', '博士']; if (in_array($target_profile->degree, $degree_arr)) { $info = $info . ',' . $target_profile->degree . '学历'; } //同城 $user_profile = $user->profileCourtship; if ($user_profile->city == $target_profile->city) { $info = $info . ',和你同城'; } elseif ($user_profile->resident_city == $target_profile->resident_city) {//老乡 $info = $info . ',和你是老乡'; } $info = $info . ',说不定是你喜欢的哦~'; return $info; } public function sendMiniRecommend($user, $target_user) { if (!empty($user->wechat) && !empty($user->wechat->openid)) { $param['openid'] = $user->wechat->openid; $param['time'] = date('Y-m-d H:i:s'); $param['message'] = "小恋为你推荐合适的Ta"; $param['user_id'] = $target_user->id; $param['name'] = $target_user->nickname; $param['channel'] = 'recommend'; $form_id = $this->formId($param['openid']); if (!empty($form_id)) { $form_id->status = 1; $form_id->save(); $param['form_id'] = $form_id->form_id; \WechatService::recommendSingleNotice($param); return true; } } return false; } public function newUserMatchingRate() { set_time_limit(0); $user = User::with('profileCourtship')->whereHas('profileCourtship', function ($sql) { $sql->where('user_id', '>', 1); })->where('type', 'single')->where('sex', '>', 0)->where('hidden_profile', '<>', 'ALLSEX')->select('id', 'name', 'sex', 'type', 'hidden_profile', 'created_at')->orderBy('id', 'desc')->first(); if (empty($user)) { return; } $single_men = []; $single_women = []; $other_users = User::with('profileCourtship')->whereHas('profileCourtship', function ($sql) { $sql->where('user_id', '>', 1); })->where('type', 'single')->where('sex', '>', 0)->where('sex', '<>', $user->sex)->select('id', 'name', 'sex', 'type', 'hidden_profile', 'created_at')->orderBy('id', 'desc')->get()->toArray(); //删除已有的 MatchingRate::where(['user_id' => $user->id])->delete(); $new_data = []; foreach ($other_users as $other_user) { $data = $this->matchingRate($user, $other_user, $type = 'new'); $new_data[] = $data; } $collect = collect($new_data); $collects = $collect->chunk(10); foreach ($collects as $collect) { MatchingRate::insert($collect->toArray()); } $user->save(); return; } /** * 匹配度 */ public function matchingRate($user, $other_user, $type = null) { $other_user = (object) $other_user; $user_profile = $user->profileCourtship; $other_user_profile = (object) $other_user->profile_courtship; $weight = 0; if (empty($user)) { return; } if (empty($other_user)) { return; } if (empty($user_profile)) { return; } if (is_object($other_user_profile) && empty($other_user_profile)) { return; } if (is_array($other_user_profile) && count($other_user_profile) == 0) { return; } if ($user->type != 'single' || $other_user->type != 'single') { return; } //如果单身匹配到介绍人删除 if ($user->type == 'single' && $other_user->type == 'marriage') { DB::table('matching_rates')->where(['user_id' => $user->id, 'other_user_id' => $other_user->id])->delete(); return; } //同性排除 if ($user->sex == $other_user->sex) { return; } //是否同信仰 if (!empty($user_profile->belief) && !empty($other_user_profile->belief) && $user_profile->belief == $other_user_profile->belief) { $belief = 10; $weight += 10; } else { $belief = -100; $weight += -100; } //居住地是否同省 if (!empty($user_profile->province) && !empty($other_user_profile->province) && $user_profile->province == $other_user_profile->province) { $residence_province = 1; $weight += 1; } else { $residence_province = 0; } if ($user_profile->province == $other_user_profile->province && $user_profile->city == $other_user_profile->city) { $residence_city = 2; $weight += 2; } else { $residence_city = 0; } if (!empty($user_profile->resident_province) && !empty($other_user_profile->resident_province) && $user_profile->resident_province == $other_user_profile->resident_province) { $grow_province = 1; $weight += 1; } else { $grow_province = 0; } if ($user_profile->resident_province == $other_user_profile->resident_province && $user_profile->resident_city == $other_user_profile->resident_city) { $grow_city = 1; $weight += 1; } else { $grow_city = 0; } $now_time = date('Y-m-d H:i:s'); $end_time = $other_user->created_at; $time = $this->getTime($now_time, $end_time); if ($time['day'] < 3) { $new_member = 3; $weight += 3; } else { $new_member = 0; } $photo_count = DB::table('profile_photos')->where('user_id', $other_user->id)->count(); if ($photo_count) { $photos = 1; $weight += 1; } else { $photos = 0; } // if ($other_user->identification_photos && count(json_decode($other_user->identification_photos, true))) { // $identification_photos = 2; // $weight +=2; // }else{ $identification_photos = 0; // } // if ($other_user->graduate_photos && count(json_decode($other_user->graduate_photos, true))) { // $graduate_photos = 1; // $weight +=1; // }else{ $graduate_photos = 0; // } // if ($other_user->other_photos && count(json_decode($other_user->other_photos, true))) { // $other_photos = 1; // $weight +=1; // }else{ $other_photos = 0; // } $user_birthday = $user_profile->birthday; $other_user_birthday = $other_user_profile->birthday; $age = -999.99; $age_diff = 999; if (!empty($user_birthday) && !empty($other_user_birthday)) { $user_age = $this->getAge($user_birthday); $other_user_age = $this->getAge($other_user_birthday); $age_diff = $user_age - $other_user_age; if ($user->sex == 1) {//你是男生 if ($user_age - $other_user_age >= 10 && $user_age - $other_user_age < 20) {//男生大女生十至二十岁之间 $age = -5; } if ($user_age - $other_user_age >= 20) {//男生大二十岁 $age = -20; } if ($user_age - $other_user_age >= 5 && $user_age - $other_user_age < 10) {//男生大女生五岁至十岁之间 $age = -3; } if ($user_age - $other_user_age < 5 && $user_age - $other_user_age >= -3) {//男生大女生0-5 或者 女生大男生 0-3 $age = 3; } if ($other_user_age - $user_age > 3 && $other_user_age - $user_age < 10) {//女生大男生 3-10 $age = -10; } if ($other_user_age - $user_age >= 10) {//女生大男生 10 $age = -20; } } if ($user->sex == 2) {//你是女生 if ($user_age - $other_user_age >= 10) {//女生大男生 10 $age = -20; } if ($user_age - $other_user_age >= 5 && $user_age - $other_user_age < 10) {//女生大男生 5-10 $age = -10; } if ($user_age - $other_user_age < 5 && $user_age - $other_user_age > 3) { //女生大男生 3-5 $age = -5; } if ($user_age - $other_user_age <= 3 && $user_age - $other_user_age >= -5) { //女生大男生 -3-5 $age = 3; } if ($other_user_age - $user_age >= 5 && $other_user_age - $user_age < 10) {//男生大女生 5-10 $age = -3; } if ($other_user_age - $user_age >= 10 && $other_user_age - $user_age < 20) {//男生大女生 10-20 $age = -5; } if ($other_user_age - $user_age >= 20) {//男生大女生 20 $age = -20; } } if (empty($age)) { // if ($user_age > $other_user_age) { // $age = 4 - ($user_age - $other_user_age)/5; // }else{ // $age = 4 - ($other_user_age - $user_age)/5; // } // if ($age >= 1000 || $age <= -1000) { // $age = -999.99; // } $age = -999.99; } $weight += $age; } if ($type == 'new') { $data = [ 'user_id' => $user->id, 'other_user_id' => $other_user->id, 'new_member' => $new_member, 'age' => $age, 'age_diff' => $age_diff, 'belief' => $belief, 'residence_province' => $residence_province, 'residence_city' => $residence_city, 'grow_province' => $grow_province, 'grow_city' => $grow_city, 'photos' => $photos, 'identification_photos' => $identification_photos, 'graduate_photos' => $graduate_photos, 'other_photos' => $other_photos, 'weight' => $weight, ]; return $data; } $rate = MatchingRate::where(['user_id' => $user->id, 'other_user_id' => $other_user->id])->first(); // $rate = DB::table('matching_rates')->where(['user_id'=> $user->id, 'other_user_id'=>$other_user->id])->first(); if (empty($rate)) { try { $array = [ 'user_id' => $user->id, 'other_user_id' => $other_user->id, 'new_member' => $new_member, 'age' => $age, 'age_diff' => $age_diff, 'belief' => $belief, 'residence_province' => $residence_province, 'residence_city' => $residence_city, 'grow_province' => $grow_province, 'grow_city' => $grow_city, 'photos' => $photos, 'identification_photos' => $identification_photos, 'graduate_photos' => $graduate_photos, 'other_photos' => $other_photos, 'weight' => $weight, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; DB::transaction(function () use ($array) { $rate = DB::table('matching_rates')->insert($array); }); } catch (Exception $e) { $this->sentMessage('15872844805', $e->getMessage()); return; } } else { $rate->new_member = $new_member; $rate->age = $age; $rate->age_diff = $age_diff; $rate->belief = $belief; $rate->residence_province = $residence_province; $rate->residence_city = $residence_city; $rate->grow_province = $grow_province; $rate->grow_city = $grow_city; $rate->photos = $photos; $rate->identification_photos = $identification_photos; $rate->graduate_photos = $graduate_photos; $rate->other_photos = $other_photos; $rate->weight = $weight; $rate->save(); } return $age; } /** * 檢查三天新用戶 * @return [type] [description] */ public function newDayUser() { try { $users = User::where('type', 'single')->where('is_new', 1)->get(); foreach ($users as $user) { $now_time = date('Y-m-d H:i:s', time()); $end_time = $user->created_at; $time = $this->getTime($now_time, $end_time); if ($time['day'] > 3) { $user->is_new = 0; $user->save(); ProfileCourtship::where('user_id', $user->id)->update(['updated_at' => $now_time]); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 获取年龄 * @param string $birthday 生日 * @return integer 年龄 */ public function getAge($birthday) { $age = strtotime($birthday); if ($age === false) { return null; } list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age)); $now = strtotime("now"); list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now)); $age = $y2 - $y1; if ((int) ($m2 . $d2) < (int) ($m1 . $d1)) $age -= 1; return $age; } /** * 时间差 */ public function getTime($begin_time, $end_time) { $begin_time = strtotime($begin_time); $end_time = strtotime($end_time); if ($begin_time < $end_time) { $starttime = $begin_time; $endtime = $end_time; } else { $starttime = $end_time; $endtime = $begin_time; } $timediff = $endtime - $starttime; $days = intval($timediff / 86400); $remain = $timediff % 86400; $hours = intval($remain / 3600); $remain = $remain % 3600; $mins = intval($remain / 60); $secs = $remain % 60; $res = array("day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs); return $res; } /** * 留言通知 */ public function chatMessageNotice() { //未读信息接收人 $other_user_ids = ChatMessage::where('status', 0)->distinct('other_user_id')->pluck('other_user_id'); foreach ($other_user_ids as $other_user_id) { //未读信息发送人 $user_ids = ChatMessage::where('status', 0)->where('other_user_id', $other_user_id)->distinct('user_id')->pluck("user_id"); //未读接收人openid $param['openid'] = Wechat::where('user_id', $other_user_id)->value('openid'); if (!count($user_ids)) { continue; } if (count($user_ids) == 1) { $messages = ChatMessage::where('status', 0)->where('other_user_id', $other_user_id)->where('user_id', $user_ids[0])->get()->toArray(); if (!count($messages)) { continue; } if (count($messages) == 1) { $message = $messages[0]['content']; } else { $message = '1位好友的' . count($messages) . '条新留言,待您点击详情回复!'; } $name = User::where('id', $user_ids[0])->value('name'); $param['name'] = $name; $param['created_at'] = $messages[0]['created_at']; $param['message'] = $message; } else { $message_count = ChatMessage::where('status', 0)->where('other_user_id', $other_user_id)->whereIn('user_id', $user_ids)->count(); $param['message'] = count($user_ids) . '位好友的' . $message_count . '条新留言,待您进入小程序回复!'; $name = User::where('id', $user_ids[0])->value('name'); $param['name'] = $name . '等' . count($user_ids) . '位好友'; $param['created_at'] = ChatMessage::whereIn('user_id', $user_ids)->where('other_user_id', $other_user_id)->where('status', 0)->value('created_at')->toDateTimeString(); } $form_id = $this->formId($param['openid']); if (!empty($form_id)) { $form_id->status = 1; $form_id->save(); $param['form_id'] = $form_id->form_id; \WechatService::chatMessageNotice($param); } continue; } return; } /** * 获取对应的formid */ public function formId($openid) { $now_time = time(); $end_time = $now_time - 7 * 24 * 60 * 60; $time = date('Y-m-d H:i:s', $end_time); $form_id = FormId::where('openid', $openid)->where('status', 0)->where('form_id', '<>', 'the formId is a mock one')->where('created_at', '>', $time)->orderBy('id', 'asc')->first(); return $form_id; } /** * 添加圆图 */ public function addUserCircleAvatar() { try { $users = User::whereNull('circle_avatar')->where(function ($sql) { $sql->whereNotNull('app_avatar')->orWhereNotNull('photo')->orWhereHas('wechat', function ($query) { $query->where(function ($sql1) { $sql1->whereNotNull('avatar')->where('avatar', '<>', ''); })->orWhere(function ($sql2) { $sql2->whereNotNull('avatar2')->where('avatar2', '<>', ''); }); }); })->orderBy('id', 'desc')->limit(50)->get(); foreach ($users as $user) { $pic = ''; if ($user->photo) { $pic = $this->circleImage($user->photo, $user->id, 'ufutx'); } elseif ($user->app_avatar) { $pic = $this->circleImage($user->app_avatar, $user->id, 'ufutx'); } elseif ($user->wechat && $user->wechat->avatar2) { $pic = $this->circleImage($user->wechat->avatar2, $user->id, 'ufutx'); // $audit_wechat_avatar = true; } elseif ($user->wechat && $user->wechat->avatar) { $pic = $this->circleImage($user->wechat->avatar, $user->id, 'wechat'); // $audit_wechat_avatar = true; } if (!empty($pic)) { // User::where('id', $user->id)->update(['circle_avatar'=>$pic]); $data = ['circle_avatar' => $pic]; //微信登录获取的头像做个审核 // if (isset($audit_wechat_avatar)) { // $data['photo'] = $pic; // $data['is_photo_audited'] = 0; // } User::where('id', $user->id)->update($data); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 圆图 * @param string $imgpath 图片路径 * @param int $user_id 用户id * @return string 生成图片路径 */ public function circleImage($imgpath = null, $user_id = null, $type = 'wechat') { $filesize = @getimagesize($imgpath); if ($type == 'wechat' && !strstr($imgpath, 'images.ufutx.com')) { $new_imgpath = $this->changeWechatAvatar($imgpath, 132); } else { $new_imgpath = $imgpath; } $new_filesize = @getimagesize($new_imgpath); switch ($new_filesize['mime']) { case 'image/jpg': $src_img = imagecreatefromjpeg($new_imgpath); break; case 'image/jpeg': $src_img = imagecreatefromjpeg($new_imgpath); break; case 'image/png': $src_img = imagecreatefrompng($new_imgpath); break; case 'image/gif': $src_img = imagecreatefromgif($new_imgpath); break; } if (empty($src_img)) { return; } $wh = @getimagesize($new_imgpath); $w = $wh[0]; $h = $wh[1]; $w = min($w, $h); $h = $w; $img = imagecreatetruecolor($w, $h); //这一句一定要有 imagesavealpha($img, true); //拾取一个完全透明的颜色,最后一个参数127为全透明 $bg = imagecolorallocatealpha($img, 255, 255, 255, 127); imagefill($img, 0, 0, $bg); $r = $w / 2; //圆半径 $y_x = $r; //圆心X坐标 $y_y = $r; //圆心Y坐标 for ($x = 0; $x < $w; $x++) { for ($y = 0; $y < $h; $y++) { $rgbColor = imagecolorat($src_img, $x, $y); if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) { imagesetpixel($img, $x, $y, $rgbColor); } } } $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.png'; $file_path = storage_path('circleImg/' . $filename); imagepng($img, $file_path); $pic = ''; if (file_exists($file_path)) { $pic = $this->uploadFile($file_path); try { unlink($file_path); } catch (Exception $e) { $this->getError($e); } } return $pic; } public function changeWechatAvatar($imgpath = null, $size = 0) { $imageArr = explode('/', $imgpath); $imageArr[count($imageArr) - 1] = $size; $imgpath = implode('/', $imageArr); return $imgpath; } //文件地址上传 public function uploadFile($file) { $ossClient = UploadController::getOssClient(); //生成file $object = date('Y') . date('m') . "/" . date('d') . "/" . basename($file); $url = 'https://' . config('alioss.picture_domain') . '/' . $object; try { // $result = $ossClient->putObject(config('alioss.buckets.picture'), $object, $file); $result = $ossClient->uploadFile(config('alioss.buckets.picture'), $object, $file); } catch (\OSS\Core\OssException $e) { // return $this->failure('oss_put_failure', $e->getMessage()); } return $url; } /** * 检测临时会员(24小时) * @return [type] [description] */ public function checkTempMember() { try { $temp_members = TempMember::where('status', 0)->get(); foreach ($temp_members as $temp_member) { $time = time(); $temp_time = $temp_member->created_at->toDateTimeString(); $temp_time = strtotime($temp_time); //相差五分钟 $diff_time = $time - $temp_time; $param['openid'] = Wechat::where('user_id', $temp_member->user_id)->value('openid'); $user = User::where('id', $temp_member->user_id)->first(); if (empty($user)) { TempMember::where('id', $temp_member->id)->update(['status' => 1]); continue; } // dd($diff_time); if ($time - 24 * 3600 >= $temp_time) {//一天后 TempMember::where('id', $temp_member->id)->update(['status' => 1]); User::where('id', $temp_member->user_id)->update(['temp_member' => 0, 'hidden' => 0]); //到期提醒 $param['rank_name'] = '临时会员'; $param['time'] = date('Y-m-d H:i:s', $time); $param['message'] = '您的24小时临时会员体验已经到期,如果需要继续享用会员服务,请您进入小程序购买会员,感谢您的体验!'; $form_id = $this->formId($param['openid']); if (!empty($form_id)) { $form_id->status = 1; $form_id->save(); $param['form_id'] = $form_id->form_id; \WechatService::VIPEndNotice($param); } } elseif ($diff_time >= 5 * 60 && $diff_time < 6 * 60) {//注册后五分钟 if ($user->is_approved) { continue; } $param['rank_name'] = '尊享VIP'; $param['name'] = $user->name; $param['end_time'] = date("Y-m-d H:i:s", $temp_time + 24 * 3600); $form_id = $this->formId($param['openid']); if (!empty($form_id)) { $form_id->status = 1; $form_id->save(); $param['form_id'] = $form_id->form_id; \WechatService::VIPStartNotice($param); } else { //短信通知 $message = '祝贺您成功注册了福恋小程序,已赠送一天尊享VIP体验!'; $this->sms->sentMessage($user->mobile, $message); } } elseif ($diff_time >= 23 * 3600 && $diff_time < 23 * 3600 + 60) {//注册小時 if ($user->is_approved) { continue; } $param['rank_name'] = '尊享VIP'; $param['message'] = '您的尊享VIP体验即将到期,请尽快体验!'; $param['time'] = date("Y-m-d H:i:s", $temp_time + 24 * 3600); $form_id = $this->formId($param['openid']); if (!empty($form_id)) { $form_id->status = 1; $form_id->save(); $param['form_id'] = $form_id->form_id; \WechatService::VIPEndNotice($param); } else { //短信通知 $message = '您的尊享VIP体验将于' . date("Y-m-d H:i:s", $temp_time + 24 * 3600) . '到期,请尽快体验!'; $this->sms->sentMessage($user->mobile, $message); } } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 老用户发消息 * @return [type] [description] */ public function tempMemberNotice() { $content = "您有一个礼包待领取"; $user_ids = User::where('rank_id', 0)->where('temp_member', 0)->where('type', 'single')->pluck('id'); foreach ($user_ids as $user_id) { $count = TempMember::where('user_id', $user_id)->count(); if ($count) { continue; } $notice_count = Notice::where('user_id', $user_id)->where('content', $content)->count(); if ($notice_count) { continue; } Notice::create([ 'user_id' => $user_id, 'send_user_id' => 1, 'type' => 'temp', 'content' => $content, ]); $mobile = User::where('id', $user_id)->value('mobile'); $message = '福恋为您提供了24小时免费会员体验,进入小程序查看详情'; $this->sentMessage($mobile, $message); } return; } public function myQrcode() { try { User::whereNull("my_qrcode")->whereHas('wechat', function ($sql) { $sql->whereNotNull('openid'); })->chunk(100, function ($users) { $app = EasyWechat::miniProgram(); $optional = [ 'page' => 'pages/tabBar/welcome', 'width' => 260, 'is_hyaline' => true, 'auto_color' => true, ]; foreach ($users as $user) { $response = $app->app_code->getUnlimit('from_user_id=' . $user->id, $optional); $qrcode_path = storage_path('qrcode'); $file_name = time() . 'home_qrcode.png'; // 保存小程序码到文件 if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) { $filename = $response->saveAs($qrcode_path, $file_name); } $qrcode_path = storage_path() . "/qrcode/" . $file_name; if (file_exists($qrcode_path)) { $qrcode = $this->uploadFile($qrcode_path); unlink($qrcode_path); User::where('id', $user->id)->update(['my_qrcode' => $qrcode]); } break; } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function userShareQrcode() { $single_path = "pages/home/information"; $marriage_path = "pages/home/informationV2"; User::whereDoesntHave("userDetailQrcode")->chunk(100, function ($users) use ($single_path, $marriage_path) { foreach ($users as $user) { $path = $user->type == "single" ? $single_path : $marriage_path; $scene = "id={$user->id}&from_user_id={$user->id}"; $qrcode = QrcodeRectService::getUnlimitQrcode($path, $scene); $param = ['path' => $path, 'scene' => $scene]; $user->userDetailQrcode()->create(['qrcode_path' => $qrcode, 'type' => 4, 'param' => json_encode($param)]); } }); } public function myShare() { $time = time(); $users = User::whereNull('my_share')->whereHas('wechat', function ($sql) { $sql->whereNotNull('avatar2'); })->with('wechat')->get(); foreach ($users as $user) { // $wechat = Wechat::where('user_id', $user->id)->first(); // if (empty($user->wechat)) { // continue; // } $avatar = $user->circle_avatar ?: $user->wechat->avatar2; $name = $user->name; $openid = $user->wechat->openid; if (empty($user->my_qrcode)) { $app = EasyWechat::miniProgram(); $data = []; $data['is_hyaline'] = true; $response = $app->app_code->get('/pages/tabBar/welcome?from_openid=' . $openid, $data); $path = $time . 'home_qrcode.png'; // $filename = $response->saveAs(storage_path('qrcode'), $path); if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) { try { $filename = $response->saveAs(storage_path('qrcode'), $path); } catch (Exception $e) { continue; } } $qrcode_path = storage_path() . "/qrcode/" . $time . "home_qrcode.png"; if (file_exists($qrcode_path)) { $qrcode = $this->uploadFile($qrcode_path); try { unlink($qrcode_path); } catch (Exception $e) { return $this->failure($e->getMessage()); exit(); } $user->my_qrcode = $qrcode; } $image2 = $user->my_qrcode; } else { $image2 = $user->my_qrcode; } //http://images.ufutx.com/201808/17/dd7540992e1e124a0947aa2422bf711c.jpeg // $image1 = "http://images.ufutx.com/201808/17/dd7540992e1e124a0947aa2422bf711c.jpeg"; $image1 = "https://images.ufutx.com/201909/02/56f3f8255dc326ebd4b4a7f39b0ae76f.jpeg"; $new_image = $this->imageAddImage($image1, $image2, 297, 297, 218, 156, 'bottom-left'); if ($avatar) { $new_image = $this->imageAddImage($new_image, $avatar, 163, 163, 300, 60, 'top-left'); } $new_image = $this->textAddImage($new_image, 'Hi,我是' . $name, 30, 375, 243, '#001100', 'center'); if ($user->type == 'single') { $slogan = '我在福恋,找对象!'; } else { $slogan = '我在福恋为你找对象!'; } $new_image = $this->textAddImage($new_image, $slogan, 42, 375, 309, '#d92553', 'center'); $file_path = storage_path("/qrcode/" . $time . "invite_qrcode.png"); $new_image->save($file_path); $qrcode = ''; if (file_exists($file_path)) { $pic = $this->uploadFile($file_path); try { unlink($file_path); } catch (Exception $e) { // return $this->failure($e->getMessage()); // exit(); } } $user->my_share = $pic; $user->save(); } return; } public function myShareQrcodeRect() { \DB::beginTransaction(); try { $users = User::whereNotNull('circle_avatar')->where('circle_avatar', '<>', '')->where(function ($sql) { $sql->where('my_share_rect', '')->orWhereNull('my_share_rect'); })->limit(100)->get(); foreach ($users as $user) { //二维码 $my_qrcode_rect = \App\Facades\QrcodeRectService::getQrCodeRect($user); //画图 $my_share_rect = \App\Facades\QrcodeRectService::makeMyShareRect($user, $my_qrcode_rect); //更新 User::where('id', $user->id)->update(['my_qrcode_rect' => $my_qrcode_rect, 'my_share_rect' => $my_share_rect]); } \DB::commit(); } catch (\Exception $e) { \DB::rollBack(); $this->getError($e); // $this->sms->sentMessage('15872844805', 'cron生成分享图片报错'); } } /** * 图片添加图片 * @param string $image1 第一张图片 * @param string $image2 第二张图片 * @param int $image2_w 图片宽度 * @param int $image2_h 图片高度 * @param integer $offset_x 文字X轴偏移 * @param integer $offset_y 文字Y轴偏移 * @param string $offset * @return image 新图片 */ public function imageAddImage($image1, $image2, $image2_w, $image2_h, $offset_x = 0, $offset_y = 0, $offset = 'top-left') { Image::configure(['driver' => 'gd']); $image = Image::make($image1); $image_v2 = Image::make($image2)->resize($image2_w, $image2_h); $image_width = $image->width(); $image_height = $image->height(); $image_copy = $image->insert($image_v2, $offset, $offset_x, $offset_y); return $image_copy; } /** * 图片添加文字 * @param string $image 图片 * @param string $text 文字 * @param int $text_size 文字尺寸 * @param int $offset_x 文字X轴偏移 * @param int $offset_y 文字Y轴偏移 * @param string $color 文字颜色 * @param string $align 文字位置 * @param string $valign * @return image 新图片 */ public function textAddImage($image, $text, $text_size, $offset_x, $offset_y, $color = '#000000', $align = 'center', $valign = 'top') { Image::configure(['driver' => 'gd']); $image = Image::make($image); $image->text($text, $offset_x, $offset_y, function ($font) use ($text_size, $color, $align, $valign) { $font->file(storage_path() . '/font/a.ttc'); $font->size($text_size); $font->color($color); $font->align($align); $font->valign($valign); }); return $image; } /** * 微信头像上传到服务器 * @return [type] [description] */ public function wechatAvatarUpdate() { try { $wechats = Wechat::whereNotNull('avatar')->where(function ($sql) { $sql->whereNull('avatar2')->orWhere('avatar2', ''); })->where('avatar', '<>', 'null')->where('avatar', '<>', '')->limit(10)->orderBy('id', 'desc')->get(); foreach ($wechats as $wechat) { //上传头像 if (!empty($wechat->avatar)) { if (!strstr($wechat->avatar, 'images.ufutx.com') && !strstr($wechat->avatar, 'local-pictures.oss-cn-shenzhen.aliyuncs.com')) { $avatar = $this->changeWechatAvatar($wechat->avatar, 0); } else { $avatar = $wechat->avatar; } if (empty($avatar)) { continue; } //尺寸是否不符; $size_fail = false; $img = Image::make($avatar); $width = $img->width(); $height = $img->height(); if ($width < 250 || $height < 250) { $img = $img->resize(250, 250); } else { $size_fail = true; } $file_path = storage_path("qrcode/" . time() . "wechat_avatar.png"); $result = $img->save($file_path); $pic = $this->uploadFile($file_path); try { if (file_exists($file_path)) { unlink($file_path); } else { \Log::info($file_path . '文件不存在'); } } catch (Exception $e) { $this->getError($e); return false; } Wechat::where('id', $wechat->id)->where('avatar', $wechat->avatar)->update(['avatar2' => $pic]); //检查头像是否合格 // if($wechat->user_id > 0){ // $result = $this->userService->faceDelectBaiDu($pic); // if (!empty($result->result) && empty($result->error_code) && empty($size_fail)) { // User::where('id', $wechat->user_id)->update(['photo'=>$pic, 'is_photo_audited'=>1]); // } // } } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 檢查會員期限 * @return [type] [description] */ public function checkRankDeadline() { try { //过期的&没有到期时间 User::where("rank_id", ">", 0)->chunk(100, function ($users) { foreach ($users as $user) { $h = RankHistory::where('user_id', $user->id)->whereNotNull('deadline')->where('deadline', '>', date('Y-m-d H:i:s'))->orderBy('deadline', 'asc')->first(); if ($h) { User::where('id', $user->id)->update(['rank_id' => $h->rank_id]); } else { User::where('id', $user->id)->update(['rank_id' => 0]); } RankHistory::where('deadline', '<=', date('Y-m-d H:i:s'))->delete(); } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 检查邀请人是否注册 * @return [type] [description] */ public function checkInviteHistory() { $invite_openids = InviteHistory::/*where('is_approved', 1)->*/ where('status', 0)->distinct('invite_openid')->pluck('invite_openid'); foreach ($invite_openids as $invite_openid) { //邀请认证人数 $count = InviteHistory::where('invite_openid', $invite_openid)/*->where('is_approved', 1)*/ ->where('status', 0)->count(); if ($count >= 2) { //邀请人的user_id $wechat = Wechat::where('openid', $invite_openid)->first(); if (empty($wechat) || empty($wechat->user_id)) {//数据错误 // InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->update(['status'=>1]); continue; } $user_id = $wechat->user_id; $user = User::find($user_id); if (empty($user)) { continue; } if ($user->type == 'marriage') {//介绍人 continue; } if ($user->mobile == "13710178377" || $user->mobile == '18898888797' || $user->mobile == "13178822477") { continue; } //最近一次的会员记录 $rank_history = RankHistory::withTrashed()->where('user_id', $user_id)->where('rank_id', $user->rank_id)->whereNotNull('deadline')->first(); if (empty($rank_history)) {//普通市级会员 RankHistory::create([ 'user_id' => $user_id, 'rank_id' => 1, 'deadline' => date('Y-m-d H:i:s', strtotime('+1 month')), ]); //标记邀请用户 InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->limit(2)->orderBy('id', 'asc')->update(['status' => 1]); //更新等級 User::where('id', $user_id)->update(['rank_id' => 1]); //TODO 通知 $message = "由于您成功邀请两位注册会员,您的市级会员权限已成功开通一个月"; $this->sentMessage($user->mobile, $message); continue; } else { if ($rank_history->rank_id == 1) {//市级会员 if (empty($rank_history->deleted_at)) {//未过期 //更新期限 $rank_history->deadline = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($rank_history->deadline))); $rank_history->save(); //TODO 通知 $message = "由于您成功邀请两位注册成员,您的市级会员权限已成功续航一个月"; $this->sentMessage($user->mobile, $message); } else {//已过期 //创建新的会员期限 RankHistory::create([ 'user_id' => $user_id, 'rank_id' => 1, 'deadline' => date('Y-m-d H:i:s', strtotime('+1 month')), ]); //更新等級 User::where('id', $user_id)->update(['rank_id' => 1]); //TODO 通知 $message = "由于您成功邀请两位注册成员,您的市级会员权限已成功开通一个月"; $this->sentMessage($user->mobile, $message); } //标记邀请用户 InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->limit(2)->orderBy('id', 'asc')->update(['status' => 1]); continue; } elseif ($rank_history->rank_id == 2) { if (empty($rank_history->deleted_at)) {//未过期 if ($count >= 3) { $rank_history->deadline = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($rank_history->deadline))); $rank_history->save(); //标记邀请用户 InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->limit(3)->orderBy('id', 'asc')->update(['status' => 1]); //更新等級 User::where('id', $user_id)->update(['rank_id' => 2]); //TODO 通知 $message = "由于您成功邀请三位注册成员,您的黄金会员成功续航一个月"; $this->sentMessage($user->mobile, $message); continue; } } else {//已过期 $time = time(); $end_time = strtotime($rank_history->deadline) + (7 * 24 * 3600); if ($time >= $end_time) {//七天以後 if ($count >= 2) { RankHistory::create([ 'user_id' => $user_id, 'rank_id' => 1, 'deadline' => date('Y-m-d H:i:s', strtotime('+1 month')), ]); //标记邀请用户 InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->limit(2)->orderBy('id', 'asc')->update(['status' => 1]); //更新等級 User::where('id', $user_id)->update(['rank_id' => 1]); //TODO 通知 $message = "由于您成功邀请两位注册成员,您的市级会员权限已成功开通一个月"; $this->sentMessage($user->mobile, $message); continue; } } else {//七天以内 if ($count >= 3) { $rank_history->deadline = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($rank_history->deadline))); $rank_history->deleted_at = null; $rank_history->save(); //标记邀请用户 InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->limit(3)->orderBy('id', 'asc')->update(['status' => 1]); //更新等級 User::where('id', $user_id)->update(['rank_id' => 2]); //TODO 通知 $message = "由于您在会员到期后七天内成功邀请三位注册会员,您的黄金会员成功续航一个月"; $this->sentMessage($user->mobile, $message); continue; } } } } elseif ($rank_history->rank_id == 3) { if (empty($rank_history->deleted_at)) {//未过期 if ($count >= 5) { $rank_history->deadline = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($rank_history->deadline))); $rank_history->save(); //标记邀请用户 InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->limit(5)->orderBy('id', 'asc')->update(['status' => 1]); //更新等級 User::where('id', $user_id)->update(['rank_id' => 3]); //TODO 通知 $message = "由于您成功邀请五位注册会员,您的钻石会员成功续航一个月"; $this->sentMessage($user->mobile, $message); continue; } } else {//已过期 $time = time(); $end_time = strtotime($rank_history->deadline) + (7 * 24 * 3600); if ($time >= $end_time) {//七天以後 if ($count >= 2) { RankHistory::create([ 'user_id' => $user_id, 'rank_id' => 1, 'deadline' => date('Y-m-d H:i:s', strtotime('+1 month')), ]); //标记邀请用户 InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->limit(2)->orderBy('id', 'asc')->update(['status' => 1]); //更新等級 User::where('id', $user_id)->update(['rank_id' => 1]); //TODO 通知 $message = "由于您成功邀请两位注册会员,您的市级会员权限已成功开通一个月"; $this->sentMessage($user->mobile, $message); continue; } } else {//七天以内 if ($count >= 5) { $rank_history->deadline = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($rank_history->deadline))); $rank_history->deleted_at = null; $rank_history->save(); //标记邀请用户 InviteHistory::where('invite_openid', $invite_openid)->where('status', 0)->limit(5)->orderBy('id', 'asc')->update(['status' => 1]); //更新等級 User::where('id', $user_id)->update(['rank_id' => 3]); //TODO 通知 $message = "由于您在会员到期后七天内成功邀请五位注册会员,您的钻石会员成功续航一个月"; $this->sentMessage($user->mobile, $message); continue; } } } } } } } return; } /** * 检查活动二维码 * @return [type] [description] */ public function checkActivityQrcode() { try { $activities = Activity::whereNull('qrcode')->get(); foreach ($activities as $activity) { $app = EasyWechat::miniProgram(); $data = []; $data['is_hyaline'] = true; $response = $app->app_code->get('/pages/party/detail?party_id=' . $activity->id, $data); $time = time(); $path = $time . 'activity_qrocde.png'; $filename = $response->saveAs(storage_path('qrcode'), $path); $qrcode_path = storage_path("/qrcode/" . $time . "activity_qrocde.png"); if (file_exists($qrcode_path)) { $qrcode = $this->uploadFile($qrcode_path); $activity->qrcode = $qrcode; $activity->save(); try { unlink($qrcode_path); } catch (Exception $e) { return $this->failure($e->getMessage()); } } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 签到二维码 */ public function checkActivitySignInQrcode() { try { $activities = Activity::whereNull('sign_in_qrcode')->where('can_repeat_sign', 0)->get();//只能单次报名且二维码为null 自动生成码 foreach ($activities as $activity) { //可多次报名 后台手动生成码 $app = \WechatService::app(); $data = []; $data['is_hyaline'] = true; $response = $app->app_code->get('pages/party/signSuccess?party_id=' . $activity->id, $data); $time = time() . 'rand' . mt_rand(1000, 9999); $path = $time . 'sign_in_qrcode.png'; $filename = $response->saveAs(storage_path('qrcode'), $path); $qrcode_path = storage_path("qrcode/" . $time . "sign_in_qrcode.png"); if (file_exists($qrcode_path)) { $qrcode = $this->uploadFile($qrcode_path); $activity->sign_in_qrcode = $qrcode; $activity->save(); try { unlink($qrcode_path); } catch (Exception $e) { return $this->failure($e->getMessage()); } } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 投票二维码 */ public function checkActivityVoteQrcode() { try { $activities = Activity::whereNull('vote_qrcode')->get(); foreach ($activities as $activity) { $app = \WechatService::app(); $data = []; $data['is_hyaline'] = true; $response = $app->app_code->get('pages/party/luckMember?party_id=' . $activity->id, $data); $time = time() . 'rand' . mt_rand(1000, 9999); $path = $time . 'vote_qrcode.png'; $filename = $response->saveAs(storage_path('qrcode'), $path); $qrcode_path = storage_path("qrcode/" . $time . "vote_qrcode.png"); if (file_exists($qrcode_path)) { $qrcode = $this->uploadFile($qrcode_path); $activity->vote_qrcode = $qrcode; $activity->save(); try { unlink($qrcode_path); } catch (Exception $e) { return $this->failure($e->getMessage()); } } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 心仪投票二维码 */ public function checkActivitySexVoteQrcode() { try { $activities = Activity::whereNull('vote_set_qrcode')->get(); foreach ($activities as $activity) { $app = \WechatService::app(); $data = []; $data['is_hyaline'] = true; $response = $app->app_code->get('pages/party/votePage?party_id=' . $activity->id, $data); $time = time() . 'rand' . mt_rand(1000, 9999); $path = $time . 'sex_vote_qrcode.png'; $filename = $response->saveAs(storage_path('qrcode'), $path); $qrcode_path = storage_path("qrcode/" . $time . "sex_vote_qrcode.png"); if (file_exists($qrcode_path)) { $qrcode = $this->uploadFile($qrcode_path); $activity->vote_set_qrcode = $qrcode; $activity->save(); try { unlink($qrcode_path); } catch (Exception $e) { return $this->failure($e->getMessage()); } } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 检车活动过期 * @return [type] [description] */ public function checkActivityDeadline() { try { $time = date('Y-m-d H:i:s'); $activities = Activity::where('is_deadline', 0)->where('end_time', '<=', $time)->get(); foreach ($activities as $activity) { Activity::where('id', $activity->id)->update(['is_deadline' => 1, 'is_hidden' => 2]);//截止报名并归为已下架 //取消置顶 $this->activityService->cancelActivityTop($activity->id); } $activities = Activity::where('is_deadline', 1)->where('end_time', '>', $time)->get(); foreach ($activities as $activity) { Activity::where('id', $activity->id)->update(['is_deadline' => 0, 'is_cancel' => 0, 'is_hidden' => 0]); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 给用户黄金会员 * @return [type] [description] */ public function giveUserRank() { // $temp_user_ids = DB::table('temp_rank_histories')->where('rank_id', 2)->where('type', 'new_year')->pluck('user_id'); // $users = User::where('rank_id', '<=', 2)->where('is_approved', 1)->where('type', 'single')->whereNotIn('id', $temp_user_ids)->where('created_at', '<', '2019-1-1')->get(); // foreach ($users as $user) { // if ($user->rank_id > 2) { // continue; // } // $wechat = Wechat::where('user_id', $user->id)->first(); // if (empty($wechat)) { // continue; // } // $user->rank_id = 2; // $user->save(); // $h = RankHistory::where('user_id', $user->id)->where('rank_id', 2)->whereNotNull('deadline')->first(); // $temp_rank_history = DB::table('temp_rank_histories')->where('user_id', $user->id)->where('rank_id', 2)->where('type', 'new_year')->first(); // if (!empty($temp_rank_history)) { // continue; // }else{ // DB::table('temp_rank_histories')->insert([ // 'user_id'=>$user->id, // 'rank_id'=>2, // 'type'=>'new_year', // ]); // if (empty($h)) { // $h = RankHistory::create([ // 'user_id'=>$user->id, // 'rank_id'=>2, // 'deadline'=>date('y-m-d H:i:s', strtotime('+1 month')), // ]); // }else{ // $h->deadline = date('Y-m-d H:i:s', strtotime('+1 month', strtotime($h->deadline))); // $h->save(); // } // $message = $user->name.'用户你好, 福恋免费赠送30天黄金VIP使用权限,有效期至'.$h->deadline.', 感谢你对福恋平台实名认证的支持!'; // $this->sms->sentMessage($user->mobile, $message); // } // } return; } public function fellowingCardShare() { try { $cards = Card::whereNull('qrcode')->get(); foreach ($cards as $card) { $user = User::findOrFail($card->user_id); $app = EasyWechat::miniProgram(); $optional = [ 'page' => 'pages/users/groupMember', 'width' => 260, 'is_hyaline' => true, 'auto_color' => true, ]; $response = $app->app_code->getUnlimit('id=' . $card->id . '&from_user_id=' . $user->id, $optional); $qrcode_path = storage_path('qrcode'); $file_name = time() . $card->id . 'fellow_card_qrcode.png'; // 保存小程序码到文件 if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) { $response->saveAs($qrcode_path, $file_name); } $qrcode_path = storage_path() . "/qrcode/" . $file_name; if (file_exists($qrcode_path)) { $qrcode = $this->uploadFile($qrcode_path); $card->qrcode = $qrcode; $card->save(); unlink($qrcode_path); } else { Log::info($qrcode_path . '文件不存在'); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 审核成员 * 头像和信息 * @return [type] [description] */ public function audit() { $users = User::where('is_audited', 0)->where(function ($sql) { $sql->whereNull('photo')->orWhere('photo', ''); })->whereBetween('id', [5262, 6262])->orderBy('id', 'desc')->get(); foreach ($users as $user) { //是否完成资料 $avatar = Wechat::where('user_id', $user->id)->value('avatar2'); if (empty($avatar)) { continue; } // $result = $this->userService->faceDelectBaiDu($avatar); // if (empty($result->result)) { // continue; // } $user->photo = $avatar; $user->save(); } return; } //预约通知 public function reservations() { //获取预约的用户 $result = UserReservation::select('id', 'user_id', 'type_id')->where('status', 0)->where('type', 'reservations')->get(); foreach ($result as $key => $value) { $live = live::where('id', $value->type_id)->first(); if (!$live) break; //活动前三十分钟 $time = Date('Y-m-d H:i:s', time() + 1800); if ($live->start_time < $time && $live->end_time > now()) { //获取用户手机号 $mobile = user::where('id', $value->user_id)->value('mobile'); $message = '您预约的《' . $live->title . '》即将开播~赶紧过来围观吧~'; Messenger::sendSMS($mobile, $message); UserReservation::where('id', $value->id)->update(['status' => 1]); } } } public function noticeActivityUsers() { try { $weeks = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; $activities = Activity::with('activityMember')->where('is_deadline', 0)->where('is_cancel', 0)->orderBy('start_time', 'asc')->get(); foreach ($activities as $activity) { $now_time = date('Y-m-d'); $start_time = date('Y-m-d', strtotime($activity->start_time)); if ($now_time == $start_time) { foreach ($activity->activityMember as $member) { $m = Message::create([ 'phone' => $member->mobile, 'message' => '', 'confirmed' => 1, 'code' => '活动', 'ip' => request() ? request()->ip() : '127.0.0.1', ]); $message_url = \CommonUtilsService::clickUrl(env('APP_URL') . '/mobile/#/activityDetail/' . $activity->id, $m->id); $url = \CommonUtilsService::shortUrl($message_url); $message = '您报名的“' . $activity->theme . '”活动已获主办方确认,请于' . $activity->start_time . ' (' . $weeks[date('w', strtotime($activity->start_time))] . ')准时签到入场,详情请访问:' . $url['url'] . '。【福恋】'; $m->message = $message; $m->save(); Messenger::sendSMS($member->mobile, $message); // $url = env('APP_URL').'/mobile/#/activityDetail/'.$activity->id; // $url = \CommonUtilsService::shortUrl($url); // $message = '您报名的“'.$activity->theme.'”活动已获主办方确认,请于'.$activity->start_time.' ('.$weeks[date('w',strtotime($activity->start_time))].')准时签到入场,详情请访问:'.$url['url'].'。【福恋】'; // $this->sentMessage($member->mobile, $message); } } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 平台提现回调 * @return [type] [description] */ public function checkPaasWithdraw() { try { //三十天内的 $start_time = date('Y-m-d H:i:s', strtotime('-30 day')); $withdraws = PaasWithdraw::where('is_hooked', 0)->where('created_at', '>', $start_time)->get(); foreach ($withdraws as $withdraw) { $result = \WechatService::officialTransferred($withdraw->trade_no); if ($result) { $withdraw->is_hooked = 1; $withdraw->save(); } } return false; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 修改介绍人地址 * @return [type] [description] */ public function updateMarrageAddress() { $marriages = User::where('type', 'marriage')->with('profileMarriage') ->whereHas('profileMarriage', function ($sql) { $sql->whereNull('province'); })->chunk(10, function ($users) { foreach ($users as $user) { $user->getAddress(); } }); return 'ok'; } public function addedBonuses() { try { $this_monday = strtotime('-1 monday', time()); //上周一 $last_monday = $this_monday - 7 * 24 * 3600; $start_time = date('Y-m-d', $last_monday); $end_time = date('Y-m-d', $this_monday); $user_ids = AddedBonus::where('created_at', '>', $start_time)->where('created_at', '<', $end_time)->distinct('user_id')->pluck('user_id'); $data = []; foreach ($user_ids as $user_id) { $bonus_obj = Bonus::where('user_id', $user_id)->where('start_time', $start_time)->where('end_time', $end_time)->first(); if (empty($bonus_obj)) { //上周邀请 $bonuses = AddedBonus::where('user_id', $user_id)->where('created_at', '>', $start_time)->where('created_at', '<', $end_time)->get(); $first_week_count = $bonuses->where('amount', 7)->count(); $other_week_count = $bonuses->where('amount', 0)->count(); //人数 $bonus_count = $bonuses->count(); $award = 0; if ($bonus_count >= 30 && $bonus_count < 100) { //多少个是第一周的 $award = $first_week_count * 7 + $other_week_count * 5; } elseif ($bonus_count >= 100 && $bonus_count < 200) { $award = $bonus_count * 7; } elseif ($bonus_count >= 200) { $award = $bonus_count * 10; } elseif ($first_week_count) { $award = $first_week_count * 7; } $new_data = []; $new_data['user_id'] = $user_id; $new_data['first_week_count'] = $first_week_count; $new_data['other_week_count'] = $other_week_count; $new_data['bonus_count'] = $bonus_count; $new_data['award'] = $award; $new_data['start_time'] = $start_time; $new_data['end_time'] = $end_time; $new_data['created_at'] = date('Y-m-d H:i:s'); $new_data['updated_at'] = date('Y-m-d H:i:s'); $data[] = $new_data; } continue; } if (count($data)) { Bonus::insert($data); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 检查转账订单 * @return [type] [description] */ public function checkTransferOrder() { try { $orders = TransferOrder::where('is_hooked', 0)->chunk(100, function ($orders) { foreach ($orders as $order) { $result = \WechatService::transferred($order->trade_no); if ($result) { $order->is_hooked = 1; $order->save(); } } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 定时更新红包状态 * @return [type] [description] */ public function reportRedPacket() { //10分钟有多于10个红包报告 $not_enough_alarm = Redis::get('NotenoughAlarm'); $start = date('Y-m-d H:i:s', strtotime('-10 minutes')); $orders = RedPacketOrder::where('created_at', '>', $start)->groupBy('err_code')->select('err_code', DB::raw('count(*) as count'), DB::raw('sum(amount) as amount'))->get(); $message = '预警助脱单红包报告:' . ($not_enough_alarm ? '配额关' : '配额开') . ' '; $alarm_count = 0; foreach ($orders as $order) { $message .= $order->err_code . ':' . $order->count . '个,¥' . $order->amount . ' '; $alarm_count += $order->count; } if ($alarm_count > 10) { $this->adminNotice($message); } //30分钟报告一次 $redpacket_report_count = Redis::get('redpacket_report_count'); if ($redpacket_report_count % 3 == 0) { $start = date('Y-m-d H:i:s', strtotime('-30 minutes')); $orders = RedPacketOrder::where('created_at', '>', $start)->groupBy('err_code')->select('err_code', DB::raw('count(*) as count'), DB::raw('sum(amount) as amount'))->get(); $message = '定时助脱单红包报告:' . ($not_enough_alarm ? '配额关' : '配额开') . ' '; foreach ($orders as $order) { $message .= $order->err_code . ':' . $order->count . '个,¥' . $order->amount . ' '; } $sources = RedPacketOrder::where('created_at', '>', $start)->groupBy('source')->select('source', DB::raw('count(*) as count'), DB::raw('sum(amount) as amount'))->get(); $message .= '渠道统计: '; foreach ($sources as $order) { $message .= $order->source . ':' . $order->count . '个,¥' . $order->amount . ' '; } $this->adminNotice($message); } $redpacket_report_count++; Redis::set('redpacket_report_count', $redpacket_report_count); } /** * 检查红包是否超过限额并自动关闭与开启 */ public function checkRedPacketQuota() { try { $start = date('Y-m-d'); $red_quota = Redis::get('red_quota'); $red_quota = $red_quota ? $red_quota : 2000; $amount = RedPacketOrder::where('created_at', '>', $start)->where(function ($query) { $query->whereNull('err_code') ->orWhere('err_code', '=', 'SUCCESS'); })->sum('amount'); $not_enough_alarm = Redis::get('NotenoughAlarm'); var_dump([$amount, $not_enough_alarm]); if ($amount > $red_quota && !$not_enough_alarm) { Redis::set('NotenoughAlarm', count(RedPacketOrder::groupBy(DB::raw('left(created_at,10)'))->pluck('id'))); $this->adminNotice('无渠道红包日发放量已经超过' . $red_quota . ', 系统关闭红包'); } $amount_unpaid = RedPacketOrder::where('created_at', '>', $start)->where('err_code', 'NOTENOUGH')->sum('amount'); if ($not_enough_alarm && ($amount < $red_quota) && $amount_unpaid == 0) { Redis::set('NotenoughAlarm', 0); $this->adminNotice('当日红包流量已经重置,重新开启无渠道发红包功能'); } return false; } catch (\Exception $e) { $this->getError($e); return false; } } /** * '无渠道红包日发放量已经超过2000, 系统关闭红包' */ public function adminNotice($message) { $app = app('wechat.official_account'); $text = new Text($message); $openId = 'okaDW0y9vmK5P1URU40PrYWjL2SA'; $result = $app->customer_service->message($text)->to($openId)->send(); } /** * 检查红包重复红包 * @return [type] [description] */ public function checkRedRepeat() { $orders = RedPacketOrder::whereIn('type', ['MP', 'SHAREMP'])->where('is_hooked', 0)->skip(0)->take(500)->get(); $i = 0; $data = []; foreach ($orders as $order) { $data[$i++] = $this->trimRedOrder($order); } return $data; } /** * 内部函数:去除重复领取的红包 */ public function trimRedOrder($order) { if ($order->type == 'SHAREMP') { $reds_paid = RedPacketOrder::where('official_openid', $order->official_openid)->where('from_official_openid', $order->from_official_openid); $reds_init = RedPacketOrder::where('official_openid', $order->official_openid)->where('from_official_openid', $order->from_official_openid); $reds_updated = RedPacketOrder::where('official_openid', $order->official_openid)->where('from_official_openid', $order->from_official_openid); } else if ($order->type == 'MP') { $reds_paid = RedPacketOrder::where('official_openid', $order->official_openid)->where('type', 'MP'); $reds_init = RedPacketOrder::where('official_openid', $order->official_openid)->where('type', 'MP'); $reds_updated = RedPacketOrder::where('official_openid', $order->official_openid)->where('type', 'MP'); } else if ($order->type == 'FRUIT') { $reds_paid = RedPacketOrder::where('official_openid', $order->official_openid)->where('type', 'FRUIT'); $reds_init = RedPacketOrder::where('official_openid', $order->official_openid)->where('type', 'FRUIT'); $reds_updated = RedPacketOrder::where('official_openid', $order->official_openid)->where('type', 'FRUIT'); } else { return 'unexpectType:' . $order->type; } $paid_count = $reds_paid->where('is_hooked', 1)->count(); $count = $reds_init->where('is_hooked', 0)->count(); //already fetch redpacket if ($paid_count > 0) { $reds_updated->where('is_hooked', 0)->update(['is_hooked' => 2, 'err_code' => 'REPEATED', 'return_msg' => '重复红包' . $order->type]); } else if ($count > 0) { if ($count > 1) { $ids = $reds_updated->where('is_hooked', 0) ->where('id', '<>', $order->id)->pluck('id'); RedPacketOrder::whereIn('id', $ids)->update(['is_hooked' => 2, 'err_code' => 'REPEATED', 'return_msg' => '重复未处理红包' . $order->type]); } /**todo: transfer to user redpacket and set is_hooked */ } //是重复红包 if ($paid_count > 0) { return false; } else { //检查IP黑名单 if ($order->ip) { $is_black = BlackIp::where('ip', $order->ip)->count(); if ($is_black) { RedPacketOrder::where('id', $order->id)->update(['is_hooked' => 2, 'err_code' => 'BLACKIP', 'return_msg' => '抢红包黑名单']); return false; } } return $order->type . ':' . 'Paid:' . $paid_count . ',initRed:' . $count; } } /** * 检查红包订单是否成功 * @return [type] [description] */ public function checkRedPacketOrder() { /* type: * * MP: 关注公众号红包 * SHAREMP: 分享关注公众号红包 * */ $ids = []; RedPacketOrder::whereIn('type', ['FRUIT', 'MP', 'SHAREMP'])->where('trigged', 0)->where('is_hooked', 0) ->take(1800)->chunk(100, $ids = function ($orders) { foreach ($orders as $order) { $result = \WechatService::checkNormalRedPack($order->trade_no); if ($result->status) { $order->is_hooked = 1; $order->err_code = $result->result['result_code']; $order->return_msg = $result->result['desc']; } else { //订单处理上锁 $order_lock = Redis::get('rp_order_lock_' . $order->id); if ($order_lock) { //已锁订单 continue; } else { //锁定去处理 Redis::setex('rp_order_lock_' . $order->id, 10, 1); } try { $res = $this->trimRedOrder($order); if (empty($res)) { //存在重复红包,不处理! continue; } if (!\WechatService::officialIsSubscribed($order->official_openid)) { $order->return_msg = '无效红包:未关注公众号'; $order->err_code = 'NOSUB'; $order->is_hooked = 2; $order->save(); continue; } $order->err_code = $result->result['err_code']; $order->return_msg = $result->result['return_msg']; if (in_array($order->err_code, ['NOT_FOUND', 'NOTENOUGH'])) { $send_name = $order->send_name ? $order->send_name : '福恋助脱单红包'; $res = \WechatService::officialUserTransfer( $order->trade_no, $order->official_openid, $order->amount * 100, $send_name ); if ($res['return_code'] == 'SUCCESS') { if ($res['result_code'] == 'SUCCESS') { $order->is_hooked = 1; $order->err_code = $res['result_code']; $order->return_msg = $order->send_name; } else { $order->err_code = $res['err_code']; $order->return_msg = $res['err_code_des']; if ($order->err_code == 'SYSTEMERROR') { $order->is_hooked = 0; sleep(5); } else if ($order->err_code == 'NOTENOUGH') { Redis::set('NotenoughAlarm', count(RedPacketOrder::groupBy(DB::raw('left(created_at,10)'))->pluck('id'))); $app = app('wechat.official_account'); $text = new Text('微信支付余额不足!请及时充值'); $openId = 'okaDW0y9vmK5P1URU40PrYWjL2SA'; $result = $app->customer_service->message($text)->to($openId)->send(); } else { $order->is_hooked = 2; } } } } //订单处理解锁 Redis::setex('rp_order_lock_' . $order->id, 6, 0); } catch (Exception $e) { //订单处理解锁 Redis::setex('rp_order_lock_' . $order->id, 6, 0); } } $order->save(); } }); return $ids; } /** * 图片信息 */ public function photoInfo() { try { return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function checkArena() { //当前时间 $time = date('Y-m-d H:i:s'); $arenas = Arena::whereIn('status', [0, 1, 2])->get(); foreach ($arenas as $arena) { //当前时间在开始时间与结束时间之间,状态变成1 if ($arena->start_time <= $time && $arena->end_time > $time) { $arena->status = 1; } elseif ($arena->end_time <= $time) {//当前时间大于结束时间,状态变成2 $arena->status = 2; } else { $arena->status = 0; } $arena->save(); } } public function updateGoldData() { try { $profiles = SingleProfile::whereNull('user_id')->limit(100)->get(); foreach ($profiles as $profile) { //判断是否注册过 $user = User::withTrashed()->where('mobile', $profile->mobile)->first(); if (empty($user)) { $user = new User(); $user->name = $profile->name; $user->mobile = $profile->mobile; $user->belief = $profile->belief; $user->sex = $profile->sex == '男' ? 1 : 2; $user->email = $profile->mobile . '@ufutx.com'; $from_user_id = is_numeric($profile->from_user_id) ? $profile->from_user_id : 0; $user->from_user_id = $from_user_id; $user->password = bcrypt($profile->mobile); $user->type = 'single'; $user->from_platform = "community_ag"; $user->save(); $profile_courtship = new ProfileCourtship(); $profile_courtship->user_id = $user->id; $profile_courtship->province = $profile->province; $profile_courtship->city = $profile->city; $profile_courtship->dist = $profile->dist; $profile_courtship->resident_province = $profile->resident_province; $profile_courtship->resident_city = $profile->resident_city; $profile_courtship->resident_dist = $profile->resident_dist; $profile_courtship->age = $profile->age; $profile_courtship->birthday = $profile->birthday; $profile_courtship->stature = $profile->stature; $profile_courtship->sex = $user->sex; $profile_courtship->state = $profile->state; $profile_courtship->degree = $profile->degree == "大学本科" ? '本科' : $profile->degree; $profile_courtship->belief = $profile->belief; $profile_courtship->post = $profile->post; $profile_courtship->save(); $profile->user_id = $user->id; $profile->save(); $wechat = new Wechat(); $wechat->user_id = $user->id; $wechat->type = 'single'; $wechat->official_openid = $profile->openid; $wechat->nickname = $profile->wechat_nickname; $wechat->gender = $profile->wechat_sex == '男' ? 1 : 2; $wechat->country = $profile->wechat_country; $address_arr = explode(' ', $profile->wechat_address); $wechat->province = count($address_arr) == 2 ? $address_arr[0] : null; $wechat->city = count($address_arr) == 2 ? $address_arr[1] : null; $wechat->avatar = $profile->avatar; $wechat->save(); //添加登录记录 // Dynamic::create(['user_id'=>$user->id, 'content'=>'金数据注册']); } else { $profile->user_id = $user->id; $profile->save(); //修改单身资料 $data['belief'] = $profile->belief; $data['sex'] = $profile->sex == '男' ? 1 : 2; $data['province'] = $profile->province; $data['city'] = $profile->city; $data['dist'] = $profile->dist; $data['resident_province'] = $profile->resident_province; $data['resident_city'] = $profile->resident_city; $data['resident_dist'] = $profile->resident_dist; $data['birthday'] = $profile->birthday; $data['stature'] = $profile->stature; $data['state'] = $profile->state; $data['degree'] = $profile->degree == "大学本科" ? '本科' : $profile->degree; $data['post'] = $profile->post; $profile_courtship = ProfileCourtship::where('user_id', $user->id)->first(); if (empty($profile_courtship)) { $data['user_id'] = $user->id; ProfileCourtship::where('user_id', $user->id)->insert($data); } else { $profile_courtship->update($data); } $user->belief = $data['belief']; $user->sex = $data['sex']; $user->save(); $wechat = Wechat::where('user_id', $user->id)->first(); \Log::info('updateGoldData'); if ($wechat && empty($wechat->official_openid)) { $wechat->official_openid = $profile->openid; $wechat->save(); } } #TODO发送推荐模板消息 //获取需要推荐的用户 $sex = $user->sex == 1 ? 2 : 1; $min_birthday = $profile->lover_min_birthday; $max_birthday = $profile->lover_max_birthday; $state = $profile->lover_state; $belief = $profile->belief; $target_user = $this->getGoldRecommendProfile($user, $sex, $min_birthday, $max_birthday, $state, $belief); if ($target_user && $profile->openid) { //发送推荐模板消息 $param['user_id'] = $target_user->id; $param['user_name'] = $target_user->name; $param['openid'] = $profile->openid; $param['recive_user_id'] = $profile->user_id; // \WechatService::agRecommendNotcie($param); //检测是否关注公众号 SendAGRecommend::dispatch($param)->delay(now()->addMinutes(5))->onQueue('love'); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 获取为Ta推荐的用户 */ public function getGoldRecommendProfile($user, $sex, $min_birthday, $max_birthday, $state, $belief) { //已推荐过的用户 $other_user_ids = $user->hasRecommended(); $user = User::whereHas('profileCourtship', function ($sql) use ($min_birthday, $max_birthday, $state) { $sql = $sql->where('birthday', '>=', $max_birthday)->where('birthday', '<=', $min_birthday)->where('hidden_profile', '<>', 'ALLSEX'); if ($state == '从未结婚') { $sql = $sql->where('state', $state); } })->whereNotIn('id', $other_user_ids)->where('is_approved', 1)->where('sex', $sex)->where('type', 'single')->where('belief', $belief)->first(); return $user; } /** * 更新年龄 */ public function updateProfileAge() { $profiles = ProfileCourtship::whereNotNull('birthday')->whereNull('age')->limit(100)->get(); foreach ($profiles as $profile) { $age = $this->getAge($profile->birthday); $profile->age = $age; $profile->save(); } } /** * 获取心灵密友问题答案 */ public function getSoulAnswers() { if (config('app.env') == 'local') { $url = "https://testsearch.soulbuddy.cn/fl/get_question_list"; } else { $url = 'https://api.soulbuddy.cn/fl/get_question_list'; } //最后一次获取到的答案时间 $last_answer = SoulAnswer::whereNull('user_id')->orderBy('id', 'desc')->first(); if (empty($last_answer)) { $start_time = ""; } else { $start_time = strtotime($last_answer->updated_at->toDateTimeString()); } $clientID = 36; $secret = '35da4e6e7664e010'; $end_time = time(); $sign = "clientID=" . $clientID . "&end_time=" . $end_time . "&start_time=" . $start_time . $secret; $sign = strtoupper(md5($sign)); $data = [ 'clientID' => $clientID, 'start_time' => $start_time, 'end_time' => $end_time, 'sign' => $sign ]; //请求数据 $result = Http::http($url, $data, 'POST'); return json_decode($result, true); } /** * 保存心灵密友答案 */ public function saveSoulAnswers() { //获取答案 $result = $this->getSoulAnswers(); if ($result['code'] && $result['data']) {//请求成功 $answers = $result['data']; $answers_data = []; foreach ($answers as $answer) { $data = []; $talent_info = $answer['talent_info']; $data['question_id'] = $answer['question_id']; $data['created_at'] = date('Y-m-d H:i:s', $answer['create_time']); $data['answer'] = $answer['answer_text']; $data['answer_url'] = $answer['answer_url']; $data['is_text'] = $answer['is_text']; $data['talent_name'] = $talent_info['true_name']; $data['talent_id'] = $talent_info['u_id']; $data['talent_link'] = $answer['talent_link']; $data['talent_title'] = $talent_info['user_title']; $data['talent_logo'] = $talent_info['logo']; $data['type'] = 'TALENT'; $data['updated_at'] = date('Y-m-d H:i:s'); $answers_data[] = $data; } SoulAnswer::insert($answers_data); } } /** * 更新个人信息完成分数 */ public function updateUserInfoScore() { try { User::where('is_update_score', 0)->limit(1000)->orderBy('id', 'desc')->chunk(100, function ($users) { foreach ($users as $user) { $userService = new UserService; $profile = $user->profileCourtship; $result = $userService->profileIntegrity($profile, $user); $score = $result['count']; User::where('id', $user->id)->update(['info_complete_score' => $score, 'is_update_score' => 1]); } return; }); } catch (\Exception $e) { $this->getError($e); return; } } /** * 每日更新用户资料 * @return [type] [description] */ public function dailyUpdateUserInfoScore() { set_time_limit(0); try { $start_time = date('Y-m-d', strtotime("-1 day")); $end_time = date('Y-m-d'); User::whereBetween('updated_at', [$start_time, $end_time])->chunk(1000, function ($users) { foreach ($users as $user) { $userService = new UserService; $profile = $user->profileCourtship; $result = $userService->profileIntegrity($profile, $user); $score = $result['count']; User::where('id', $user->id)->update(['info_complete_score' => $score, 'is_update_score' => 1]); } }); return; } catch (\Exception $e) { $this->getError($e); return; } return; } public function calculateInfoCompleteScore($user) { $sum = 0; if ($user->profileCourtship) { //个人信息 $profile = $user->profileCourtship; //年龄1分 if ($profile->birthday) { $sum += 1; } //身高1分 if ($profile->stature) { $sum += 1; } //体重1分 if ($profile->weight) { $sum += 1; } //婚姻1分 if ($profile->state) { $sum += 1; } //出生地1分 if ($profile->province && $profile->city) { $sum += 1; } //户口1分 if ($profile->resident_type) { $sum += 1; } //成长环境1分 if ($profile->habitat) { $sum += 1; } //公司1分 if ($profile->conpany) { $sum += 1; } //公司性质1分 if ($profile->work_sort) { $sum += 1; } //公司职位1分 if ($profile->post) { $sum += 1; } //信仰1分 if ($profile->belief) { $sum += 1; } //居住地1分 if ($profile->province && $profile->city) { $sum += 1; } } //行业1分 if ($user->industry && $user->industry_sub) { $sum += 1; } //实名认证10分 if ($user->is_approved) { $sum += 10; } //实人认证10分 if ($user->is_real_approved) { $sum += 5; } return $sum; } public function isSubscribe() { try { User::chunk(100, function ($users) { foreach ($users as $user) { $user->is_subscribe = $user->hasSubscribeOfficial(); $user->save(); } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function addRedBlackIp() { try { DB::table('black_ips')->distinct()->get(['ip']); $blackIps = BlackIp::whereNull('count')->pluck('ip')->toarray(); $redBlackIps = RedPacketOrder::select(DB::raw('count(id) as count'), 'ip')->whereIn('ip', $blackIps)->groupBy('ip')->havingRaw('count > ?', [5])->get(); foreach ($redBlackIps as $item) { BlackIp::where('ip', $item->ip)->update(['count' => $item->count]); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 最终的红包分配 */ public function testcreateParticipantPacket() { if (date('Y-m-d') != '2020-01-14') { return; } // 完成九个果子的用户数 $count = Participant::where('fruit_num', '>=', 9)->count(); // $count = 84795; //单次最多红包数 $single_count = 10000; //分次数插入数据库 $num = (int) ceil($count / $single_count); $total_red_packet = number_format($count * 0.3, 2, '.', ''); //单次获取的金额 $array = [ 'count' => $count, 'total_packet' => $total_red_packet, ]; CreateNewYearPacket::dispatch($array)->onQueue('love'); } public function participantPacket($min_fruit_num, $max_fruit_num, $money, $min_money, $max_money) { $count = Participant::where('fruit_num', '>=', $min_fruit_num); if ($max_fruit_num) { $count = $count->where('fruit_num', '<', $max_fruit_num); } $count = $count->count(); $total_money = 1700;//$count * $money; if (empty($total_money)) { return; } $packet_data = [ 'min' => $min_money, 'max' => $max_money, 'num' => $count, 'total' => $total_money, ]; //生成红包 CreateParticipantPacket::dispatch($packet_data)->onQueue('love'); return compact('count', 'total_money'); } public function participantPacketV2($min_fruit_num, $max_fruit_num, $money, $min_money, $max_money, $fruit_histoies) { $fruit_histoies = $fruit_histoies->where('num', '>=', $min_fruit_num); if ($max_fruit_num) { $fruit_histoies = $fruit_histoies->where('num', '<', $max_fruit_num); } $count = $fruit_histoies->count(); if ($min_fruit_num == 12) { $total_money = 1110; } elseif ($min_fruit_num == 20) { $total_money = 900; } elseif ($min_fruit_num == 50) { $total_money = 1500; } // $total_money = 1700;//$count * $money; if (empty($total_money)) { return; } $packet_data = [ 'min' => $min_money, 'max' => $max_money, 'num' => $count, 'total' => $total_money, ]; //生成红包 CreateParticipantPacket::dispatch($packet_data)->onQueue('love'); return compact('count', 'total_money'); } /** * 2月份的红包 * 二月份领取9个及以上的(删除) * 上一次没有领取红包的 */ public function createParticipantPacketV2() { //没领过红包的 // $packet_participant_ids = ParticipantRedPacket::distinct('participant_id')->pluck('participant_id')->toArray(); // $zero_count = 0; // $success_packet_participant_ids = Participant::where('fruit_num', '>=',9)->pluck('id'); // foreach ($success_packet_participant_ids as $participant_id) { // if(!in_array('participant_id', $packet_participant_ids)){ // $zero_count++; // } // } //二月份领取9个及以上的 $participant_ids = FruitHistory::where('created_at', '>', '2020-02-01')->distinct('participant_id')->pluck('participant_id'); $fruit_histoies = \DB::table('fruit_histories')->select(\DB::raw('count(*) as num, participant_id, created_at')) ->where('created_at', '>', '2020-02-01') ->groupBy('participant_id') ->orderBy('num', 'desc') ->get(); $fourth_stage = $this->participantPacketV2(50, 0, 26, Participant::FOURTH_MIN_MONEY, Participant::FOURTH_MAX_MONEY, $fruit_histoies); $third_stage = $this->participantPacketV2(20, 50, 20, Participant::THIRD_MIN_MONEY, Participant::THIRD_MAX_MONEY, $fruit_histoies); $second_stage = $this->participantPacketV2(12, 20, 10, Participant::SECOND_MIN_MONEY, Participant::SECOND_MAX_MONEY, $fruit_histoies); $first_count = $fruit_histoies->where('num', '>=', 9)->where('num', '<', 12)->count(); $total_count = $fourth_stage['count'] + $second_stage['count'] + $third_stage['count'] + $first_count; $total_money = $this->totalRedPacket($total_count); $first_money = 1500; $first_packet_data = [ 'min' => Participant::FIRST_MIN_MONEY, 'max' => Participant::FIRST_MAX_MONEY, 'num' => $first_count, 'total' => $first_money, ]; //生成红包 CreateParticipantPacket::dispatch($first_packet_data)->onQueue('love'); } public function createParticipantPacket() { if (date('Y-m-d') != '2020-01-25') { return; } $total_count = Participant::where('fruit_num', '>=', 9)->count(); $fourth_stage = $this->participantPacket(50, 0, 8, Participant::FOURTH_MIN_MONEY, Participant::FOURTH_MAX_MONEY); $third_stage = $this->participantPacket(20, 50, 5, Participant::THIRD_MIN_MONEY, Participant::THIRD_MAX_MONEY); $second_stage = $this->participantPacket(12, 20, 2, Participant::SECOND_MIN_MONEY, Participant::SECOND_MAX_MONEY); $first_count = Participant::where('fruit_num', '>=', 9)->where('fruit_num', '<', 12)->count(); // //红包总金额 $total_count = $fourth_stage['count'] + $second_stage['count'] + $third_stage['count'] + $first_count; $total_money = $this->totalRedPacket($total_count); $first_money = 1500;//$total_money - $fourth_stage['total_money'] - $second_stage['total_money'] - $third_stage['total_money']; // echo "total_money". $total_money; // echo "total_count". $total_count; // echo 'first_money:'.$first_money; // echo 'first_count:'.$first_count; // echo 'second_money:'.$second_stage['total_money']; // echo 'second_count:'.$second_stage['count']; // echo 'third_money:'.$third_stage['total_money']; // echo 'third_count:'.$third_stage['count']; // echo 'fourth_money:'.$fourth_stage['total_money']; // echo 'fourth_count:'.$fourth_stage['count']; $first_packet_data = [ 'min' => Participant::FIRST_MIN_MONEY, 'max' => Participant::FIRST_MAX_MONEY, 'num' => $first_count, 'total' => $first_money, ]; //生成红包 CreateParticipantPacket::dispatch($first_packet_data)->onQueue('love'); } /** * 总红包金额 */ public function totalRedPacket($count) { $total_red_packet = 0; if ($count < 1000) { $total_red_packet = $count * 3.5; } elseif ($count >= 1000 && $count < 5000) { $total_red_packet = $count * 3; } elseif ($count >= 5000 && $count < 10000) { $total_red_packet = $count * 2; } elseif ($count >= 10000 && $count < 1000000) { $total_red_packet = $count; } else { $total_red_packet = 1000000; } return $total_red_packet; } /** * 2020年1月15 08:00:00通知用户 */ public function participantPacketStartNotice() { if (date('Y-m-d') != '2020-01-15') { return; } $wechat_users = Wechat::whereNotNull('official_openid')->select('official_openid', 'nickname')->get('official_openid'); foreach ($wechat_users as $wechat_user) { $text = $this->getServiceNewsText($wechat_user['nickname']); $array = [ 'official_openid' => $wechat_user['official_openid'], 'text' => $text, ]; SendServiceNews::dispatch($array)->onQueue('love'); } } public function getServiceNewsText($nickname) { $nickname = $nickname ? $nickname : '你好'; $url = env('APP_URL') . '/red/packet/activity/wechat/auth'; $text = $nickname . ',恭喜您被抽中体验新年抢百万红包活动!,立即体验GO!'; return $text; } public function updatePhotoSize(Request $request) { $users = User::whereNotNull('photo')->chunk(100, function ($users) { foreach ($users as $user) { $img = Image::make($user->photo)->resize(250, 250); $file_path = storage_path("qrcode/" . time() . "wechat_avatar.png"); $img->save($file_path); $pic = $this->uploadFile($file_path); try { if (is_file($file_path)) { unlink($file_path); } } catch (Exception $e) { // return $this->failure($e->getMessage()); } $user->photo_backup = $pic; $user->save(); } }); } public function syncFaceScore() { $users = \DB::table('users')->whereNotNull('photo')->where('face_score', 0) ->rightJoin('image_infos', 'users.photo', '=', 'image_infos.url') ->limit(100) ->get(); foreach ($users as $user) { Log::info('syncFaceScore user_id: ' . $user->user_id); $user->face_score = $user->beauty; User::where('photo', $user->photo)->update(['face_score' => $user->beauty]); } } // public function faceScore() // { // User::where("face_score", 0)->whereNotNUll('photo')->where('is_photo_audited ', 1)->where('type', 'single')->where('hidden_profile', 'NONE') // ->where('negative_score', '<>', 200) // ->chunk(100, function ($users) { // foreach ($users as $user) // { // //人脸识别 // $user_service = new UserService(); // $result = $user_service->faceDelectBaiDu($user->photo); // if (empty($result->result)) { // Log::info("【faceScore】用户id ".$user->id.'图片人脸识别失败'); // continue; // } // $face_list = $result->result->face_list; // $face_socre = $face_list[0]->beauty; // User::where('id', $user->id)->update(['face_score'=>$face_socre]); // //创建百度图片信息 // $user_service->addImageInfo($user, $user->photo, $face_list[0]); // $res = $user_service->checkPhotoResult($result, $user->id); // if (empty($res)) throw new \Exception("图片分析失败", 1); // if (is_array($res) && $res['code']) { // //增加错误头像记录 // ErrorPhoto::firstOrCreate(['user_id'=>$user->id, 'photo'=>$user->photo, 'error_msg'=>$res['msg']]); // if ($res['msg'] == "pic not has face") return $this->failure('图片上传失败,可能未获取到人脸,请换一张照片'); // if ($res['msg'] == "image download fail") return $this->failure('图片解析失败,请重新上传'); // continue; // } // } // }); // } public function syncLiveViews() { $lives = Live::where('start_time', '<', date('Y-m-d H:i:s'))->where('url', '!=', '')->get(); foreach ($lives as $live) { try { if (empty($live->url) || strstr($live->url, 'ls')) continue; $contents = file_get_contents($live->url); $views = mb_substr($contents, mb_strpos($contents, '') + 70, '10'); $views = mb_substr($views, 0, mb_strpos($views, '人')); Live::where('id', $live->id)->update(['times' => $views]); } catch (\Exception $e) { $this->getError($e); } } } // public function delRepeat(){ //// $arr = ViewerShare::select('viewer_id', 'sharer_id')->groupBy('viewer_id', 'sharer_id')->get(); //// foreach ($arr as $item){ //// $is_set = ViewerShare::where('viewer_id', $item->viewer_id)->where('sharer_id', $item->sharer_id)->where('type', 1)->count(); //// if($is_set == 0){ //// $count = ViewerShare::where('viewer_id', $item->viewer_id)->where('sharer_id', $item->sharer_id)->where('type', 2)->count(); //// ViewerShare::where('viewer_id', $item->viewer_id)->where('sharer_id', $item->sharer_id)->where('type', 2)->where('is_show', 1)->orderBy('created_at', 'desc')->limit(1)->update(['is_show'=>0]); //// } //// //// } //// } /// /** * 同步IM用户 * @return [type] [description] */ public function synIMUser() { try { // $count = User::whereDoesntHave('IMUser')->count(); // if (empty($count)) { // return true; // } $users = User::whereDoesntHave('IMUser')->orderBy('id', 'desc')->limit(10)->get(); foreach ($users as $user) { $user->createIMUser(); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 同步社群到IM * @return [type] [description] */ public function syncIMGroup() { try { $communities = Community::where('tid', '')->orWhereNull('tid')->orWhere('tid', 0)->limit(100)->get(); foreach ($communities as $community) { $tid = $community->createIMGroup(); if ($tid) { Community::where('id', $community->id)->update(['tid' => $tid]); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 同步社群成员到网易群 * @return [type] [description] */ public function syncIMCommunityMember() { try { // throw new \Exception("Error Processing Request", 1); $members = CommunityMember::with('community', 'user')->whereHas('community', function ($sql) { $sql->where('is_hided', 0)->whereNotNull('tid')->where('tid', '<>', 0); })->where('is_sync_im', 0)->limit(100)->get(); foreach ($members as $member) { $community = $member->community; $user = $member->user; if (empty($community) || empty($user)) { $member->delete(); continue; } //同步 $result = $community->addIntoIMGroup([$member->user_id]); } return true; } catch (\Exception $e) { $this->getError($e, false); return false; } } public function syncIMCommunityChat() { } /** * 检查主播是否在直播间 * @return [type] [description] */ public function checkInteractLiveMaker() { try { $lives = InteractLive::where('in_live', 1)->paginate(); foreach ($lives as $live) { //检查主播是否在房间 $result = $live->chatroomLineMembers([$live->user_id]); if (empty($result[0]['onlineStat'])) {//主播不在直播间 $live_service = new LiveService(); $live_service->closeLive($live); //发送关闭直播间自定义消息 $attach = json_encode([InteractLive::CHATMSGTYPE['main_leave'], 'data' => '主播离开']); $result = $live->chatroomSendMsg($live->user_id, $msgType = 10, $attach); if (empty($result)) throw new \Exception("直播间id:" . $live->id . "发送自定义消息失败", 1); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 检测直播间成员在线 * @return [type] [description] */ public function checkInteractLiveMembers() { try { InteractLive::where('in_live', 1)->chunk(10, function ($lives) { foreach ($lives as $live) { $user_ids = $live->memberLogs()->where('in_live', 1)->limit(200)->pluck('user_id')->toArray(); if (!count($user_ids)) continue; $members = $live->chatroomLineMembers($user_ids); if (!count($members)) { $live->memberLogs()->whereIn('user_id', $user_ids)->update(['in_live' => 0]); } else { $data = []; foreach ($members as $member) { if ($member['onlineStat']) { $data[] = $member['accid']; } } $live->memberLogs()->whereNotIn('user_id', $data)->update(['in_live' => 0]); } } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function checkActivitie() { try { \Log::info('checkActivitie begin'); $user_ids = User::where('is_approved', 1)->where('is_real_approved', 0)->where('type', 'single')->where('belief', '基督教')->orderBy('liveness', 'desc')->pluck('id')->toArray(); $activity_user_ids = ActivityUser::pluck('user_id'); $insert_arr = []; $new_arr = []; foreach ($user_ids as $user_id) { // if(!in_array($user_id, $activity_user_ids)) { $new_arr['user_id'] = $user_id; $new_arr['type'] = 6; $new_arr['created_at'] = date('Y-m-d H:i:s'); $new_arr['updated_at'] = date('Y-m-d H:i:s'); $insert_arr[] = $new_arr; // } } ActivityUser::insert($insert_arr); return true; } catch (\Exception $e) { $this->getError($e, false); return false; } } public function updateLiveClickNum() { InteractLive::where('in_live', 1)->chunk(100, function ($lives) { foreach ($lives as $live) { $click_num_key = $live->clickNumKey(); $click_num = Cache::get($click_num_key, 0); InteractLive::where('id', $live->id)->update(['click_num' => $click_num]); } }); return true; } public function checkMobile() { try { \Log::info('checkMobile begin'); $mobile_arr = User::pluck('mobile')->toArray(); $insert_arr = []; $new_arr = []; foreach ($mobile_arr as $mobile) { if (strlen($mobile) == 11) { $result = $this->getResult($mobile); if (!empty($result)) { $new_result = json_decode($result); if ($new_result->code == 200000) { $new_arr['mobile'] = $mobile; $new_arr['status'] = $new_result->data[0]->status; $new_arr['result'] = $result; $new_arr['created_at'] = date("Y-m-d H:i:s"); $new_arr['updated_at'] = date("Y-m-d H:i:s"); $insert_arr[] = $new_arr; } } } } CheckMobileModel::insert($insert_arr); \Log::info('checkMobile end'); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function getResult($mobile) { $host = "http://ali.market.alicloudapi.com"; $path = "/open/unn/batch-ucheck"; $method = "POST"; $appcode = config("aliyun.appcode"); $headers = array(); array_push($headers, "Authorization:APPCODE " . $appcode); $querys = "mobiles=" . $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); } $result = curl_exec($curl); return $result; } public function createdMakerOnlineLog() { $yestoday_start_time = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'))); $yestoday_end_time = date('Y-m-d H:i:s', mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1); $logs = InteractLiveLog::whereNotNull('end_time')->whereBetween('created_at', [$yestoday_start_time, $yestoday_end_time])->groupBy('mk_user_id')->get(); $insert_arr = []; foreach ($logs as $log) { $new_arr = []; $new_arr['user_id'] = $log->mk_user_id; $all_hours = InteractLiveLog::selectRaw('sum(round((UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(created_at))/3600, 2)) AS hours')->where('mk_user_id', $log->mk_user_id)->whereNotNull('end_time')->whereBetween('created_at', [$yestoday_start_time, $yestoday_end_time])->value('hours'); $single_hours = InteractLiveLog::selectRaw('sum(round((UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(first_start_time))/3600, 2)) AS hours')->where('mk_user_id', $log->mk_user_id)->whereNotNull('first_start_time')->whereNotNull('end_time') ->where(function ($query) { $query->where(function ($query) { $query->whereNotNull('male_user_id')->WhereNull('female_user_id'); }) ->orWhere(function ($query) { $query->whereNull('male_user_id')->WhereNotNull('female_user_id'); }); })->whereBetween('created_at', [$yestoday_start_time, $yestoday_end_time])->value('hours'); // $double_single_hours = InteractLiveLog::selectRaw('sum(round((UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time))/3600, 2)) AS hours')->where('mk_user_id', $log->mk_user_id)->whereNotNull('first_start_time')->whereNotNull('start_time')->whereNotNull('end_time')->whereNoTNull('male_user_id')->WhereNotNull('female_user_id')->whereBetween('created_at', [$yestoday_start_time, $yestoday_end_time])->value('hours'); // $single_hours = bcadd($single_hours, $double_single_hours, 2); $double_hours = InteractLiveLog::selectRaw('sum(round((UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time))/3600, 2)) AS hours')->where('mk_user_id', $log->mk_user_id)->whereNotNull('start_time')->whereNotNull('end_time')->whereNoTNull('male_user_id')->WhereNotNull('female_user_id')->whereBetween('created_at', [$yestoday_start_time, $yestoday_end_time])->value('hours'); $nobody_hours = bcsub(bcsub($all_hours, $single_hours, 2), $double_hours, 2); $new_arr['all_hours'] = $all_hours; $new_arr['single_hours'] = $single_hours; $new_arr['double_hours'] = $double_hours; $new_arr['nobody_hours'] = $nobody_hours; $new_arr['start_time'] = $yestoday_start_time; $new_arr['end_time'] = $yestoday_end_time; $new_arr['created_at'] = date('Y-m-d H:i:s'); $new_arr['updated_at'] = date('Y-m-d H:i:s'); if ($all_hours > 0) { $insert_arr[] = $new_arr; } } MakerScoreLog::insert($insert_arr); return true; } public function changeCoin() { try { \DB::beginTransaction(); $logs = CoinLog::where('type', 'RECSYSTEM')->whereBetween('created_at', ['2020-11-11 10:42:35', '2020-11-11 10:42:37'])->where('is_hooked', 1)->whereNotIn('user_id', [4869, 4585, 2356]); $logs = $logs->get(); foreach ($logs as $log) { $coin = Coin::where('user_id', $log->user_id)->first(); $coin->decrement('remain_amount', $log->coin); $coin->increment('amount_from_other', $log->coin); } $history = CoinLog::where('type', 'RECSYSTEM')->whereBetween('created_at', ['2020-11-11 10:42:35', '2020-11-11 10:42:37'])->where('is_hooked', 1)->whereNotIn('user_id', [4869, 4585, 2356])->update(['is_hooked' => 0]); \DB::commit(); return true; } catch (\Exception $e) { \DB::rollBack(); $this->getError($e); return false; } } /** * 同步直播数 * @return [type] [description] */ public function syncLiveNum() { try { \App\Jobs\SendIMBroadcastMsg::dispatch()->onQueue('love'); } catch (\Exception $e) { $this->getError($e); return false; } } /** * 未完善资料的每天模板提醒 * @return [type] [description] */ public function noProfileNotice() { try { //获取已关注公众号用户 User::with('profileCourtship', 'wechat', 'viewer')->where('is_subscribe', 1)->where('type', 'single')->where('hidden_profile', 'NONE')->noFiveProfile()->chunk(100, function ($users) { //是否完善五项资料 foreach ($users as $user) { $openid = $user->wechat ? $user->wechat->official_openid : null; if (empty($openid)) { $openid = $user->viewer ? $user->viewer->openid : null; } if ($openid) { $param["touser"] = $openid; $param['template_id'] = config('wechat.tpls.no_profile_notice'); $param['url'] = env('APP_URL') . '/h5'; $param['miniprogram'] = [ 'appid' => config('wechat.mini_program.app_id'), 'pagepath' => 'pages/tabBar/welcome?from_platform=RDINFO_1229', ]; $param['data'] = [ "first" => '你脱单了吗?今日已为您生成推荐,快去看看吧', 'keyword1' => $user->nickname ?: ($user->name ?: $user->mobile), 'keyword2' => $user->created_at->toDateTimeString(), 'remark' => '点击进入,还可以参与签到,分享。赢福币,领VIP!' ]; SendTemplateMsg::dispatch($param)->onQueue('template_message'); } } }); } catch (\Exception $e) { $this->getError($e); return false; } } /** * 关注公众号未注册模板消息提醒 * @return [type] [description] */ public function noRegisterNotice() { try { //获取最后一次的openid $key = 'last_no_register_openid'; $no_register_openid = null; //获取所有的openid $app = \WechatService::officialApp(); $result = $app->user->list(Cache::get($key, null)); if (empty($result['count'])) return true; $openid_arr = $result['data']['openid']; //获取前三千个用户openid $sub_openid_arr = array_slice($openid_arr, 0, 3500); //获取最后一位 $last_openid = $sub_openid_arr[count($sub_openid_arr) - 1]; //记录最后一个openid $result = Cache::put($key, $last_openid, 2 * 24 * 60); foreach ($sub_openid_arr as $sub_openid) { //是否注册小程序 $wechat = Wechat::where('official_openid', $sub_openid)->first(); if ($wechat && $wechat->user_id) continue; $viewer = Viewer::where('openid', $sub_openid)->first(); if ($viewer && $viewer->user_id) continue; $user = $app->user->get($sub_openid); //发送模板消息 $param["touser"] = $sub_openid; $param['template_id'] = config('wechat.tpls.no_profile_notice'); $param['url'] = env('APP_URL') . '/h5'; $param['miniprogram'] = [ 'appid' => config('wechat.mini_program.app_id'), 'pagepath' => 'pages/tabBar/welcome?from_platform=RDINFO_1229', ]; $param['data'] = [ "first" => '你脱单了吗?今日已为您生成推荐,快去看看吧', 'keyword1' => $user['nickname'], 'keyword2' => date('Y-m-d H:i:s', $user['subscribe_time']), 'remark' => '点击进入,还可以参与签到,分享。赢福币,领VIP!' ]; SendTemplateMsg::dispatch($param)->onQueue('template_message'); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 签到订阅通知提醒 * @return [type] [description] */ public function signInNotice() { try { //以前有签到今日没签到用户ID $user_ids = $this->unsignUserIds(); if (empty(count($user_ids))) return true; User::whereIn('id', $user_ids)->whereHas('wechat')->where('hidden_profile', 'NONE')->chunk(100, function ($users) { foreach ($users as $user) { // SendSubTemplateMsg::dispatch('sign_in', $user)->onQueue('love'); SendSubTemplateMsg::dispatch('sign_in_v2', $user)->onQueue('template_message'); } }); return true; } catch (\user_ids $e) { $this->getError($e); return false; } } public function unsignUserIds() { //以前签到的用户id $sign_user_ids = SignLog::where('type', 'NEWYEAR')->where('sign_date', '<', date('Y-m-d'))->distinct('user_id')->pluck('user_id')->toArray(); //今天签到的用户id $day_sign_user_ids = SignLog::where('type', 'NEWYEAR')->where('sign_date', '>=', date('Y-m-d'))->distinct('user_id')->pluck('user_id')->toArray(); $arr = []; foreach ($sign_user_ids as $user_id) { foreach ($day_sign_user_ids as $day_user_id) { if ($user_id == $day_user_id) { $arr[] = $user_id; } } } $user_ids = array_diff($sign_user_ids, $arr); //已经签到七天用户id $complete_user_ids = SignLog::where('type', 'NEWYEAR')->groupBy('user_id')->select(\DB::raw('count(*) as num'), 'user_id')->get()->where('num', 7)->pluck('user_id')->toArray(); $user_ids = array_diff($user_ids, $complete_user_ids); return $user_ids; } /** * 每日匹配通知 * @return [type] [description] */ public function matchNotice() { try { $not_recommend_ids = [113649]; User::where('type', 'single')->whereNotIn('id', $not_recommend_ids)->where('hidden_profile', 'NONE')->fullinkUser()->chunk(100, function ($users) { foreach ($users as $user) { $target_user_ids = RecommendUser::where('user_id', $user->id)->where('start_time', '>=', date('Y-m-d') . ' 12:00:00') /*->inRandomOrder()*/ ->orderBy('other_user_id', 'asc')->limit(2) ->get(); if (sizeof($target_user_ids) < 2) { continue; } $target_user_id = []; foreach ($target_user_ids as $key => $val) { $target_user_id[] = $val->other_user_id; } $user_nick_mames = User::whereIn('id', $target_user_id)->pluck('nickname'); $nick_mame = ''; foreach ($user_nick_mames as $key => $val) { if (mb_strlen($val) > 5) { $val = mb_substr($val, 0, 4) . '...'; } if (empty($nick_mame)) { $nick_mame = $val . '、'; } else { $nick_mame = $nick_mame . $val; } } $targe_user = $nick_mame . '等'; SendSubTemplateMsg::dispatch('match', $user, $targe_user)->onQueue('template_message'); $target_user_id = []; $targe_user = ''; } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 每日访问记录 * @return [type] [description] */ public function visitNotice() { try { $start_time = date('Y-m-d', strtotime('-1 day')); $end_time = date('Y-m-d 23:59::59', strtotime('-1 day')); //昨天被查看的用户 UserPreviewHistory::with('user')->whereBetween('created_at', [$start_time, $end_time])->distinct('user_id')->chunk(100, function ($logs) { foreach ($logs as $log) { if (empty($log->user) || $log->user->hidden_profile != "NONE" || $log->user->type != 'single') { continue; } SendSubTemplateMsg::dispatch('visit_log', $log->user)->onQueue('template_message'); } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function changeSignDays() { $beginYesterday = date("Y-m-d 00:00:00", strtotime("-1 day")); $endYesterday = date("Y-m-d 00:00:00"); $endToday = date("Y-m-d 23:59:59"); //昨日签到用户 $yesterday_signuser = SignLog::whereBetween('sign_date', [$beginYesterday, $endYesterday])->pluck('user_id')->toArray(); //签到三十天用户 $month_sign = UserSign::where('sign_days', 30)->pluck('user_id')->toArray(); //今日签到用户 $today_signuser = SignLog::whereBetween('sign_date', [$endYesterday, $endToday])->pluck('user_id')->toArray(); //连续签到用户 $sign_user = UserSign::where('sign_days', '>', 0)->pluck('user_id')->toArray(); foreach ($sign_user as $val) { //昨日是否签到 if (!in_array($val, $yesterday_signuser)) { //今日也没签到 if (!in_array($val, $today_signuser)) { UserSign::where('user_id', $val)->update(['sign_days' => 0]); } } } //签到三十天用户归零 foreach ($month_sign as $value) { //今日没签到 if (!in_array($value, $today_signuser)) { UserSign::where('user_id', $val)->update(['sign_days' => 0]); } } } /** * 检测在线直播 */ public function checkTeamLives() { try { TeamLive::where('in_live', 1)->chunk(100, function ($lives) { foreach ($lives as $live) { //判断主播是否在直播间内 $im = new IMService(); $result = $im->chatroomLineMembers($live->chat_room_id, [$live->user_id]); if (empty($result) || $result['code'] != 200) { throw new \Exception("批量获取在线用户失败", 1); } $user_info = $result['desc']['data'][0]; // \Log::info($user_info); if (empty($user_info['onlineStat'])) { //修改直播状态 $live->in_live = 0; $live->save(); //修改直播记录 $log = $live->liveLogs()->whereNull('end_time')->orderBy('id', 'desc')->first(); if ($log) { $log->end_time = date('Y-m-d H:i:s'); $click_num_key = $live->clickNumKey(); $log->click_num = Cache::get($click_num_key, 0); $log->save(); } //修改群扩展状态 $team = Team::find($live->team_id); if (empty($team)) throw new \Exception("群聊直播错误", 1); //修改群扩展信息 if ($team->custom) { $old_custom = $team->custom; $old_custom->in_live = 0; $old_custom->anchor_id = $live->user_id; } else { $old_custom['in_live'] = 0; $old_custom['anchor_id'] = $live->user_id; } $data['custom'] = json_encode($old_custom); $data['tid'] = $live->team_id; $data['owner'] = $team->owner; $im_service = new IMService(env('IM_APP_KEY'), env("IM_APP_SECRET")); $url = "https://api.netease.im/nimserver/team/update.action"; $result = $im_service->postDataCurl($url, $data); $team->custom = $data['custom']; $team->save(); } } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function updateUserActiveProperties($param = null) { try { $redis = Cache::getRedis(); switch ($param) { case 'liveness': //获取所有keys $key_name = '_cache:' . User::RDLIVENESSKEY; $keys = $redis->keys($key_name . "*"); $user_ids = []; $values = []; foreach ($keys as $key) { $user_id = explode('_', $key)[4]; $user_ids[] = $user_id; $value = $redis->get($key); $values['r_' . $user_id] = $value; //删除缓存 $redis->del($key); } $users = User::whereIn("id", $user_ids)->get(); foreach ($users as $user) { $value = $values['r_' . $user->id]; if ($user->liveness < $value) { User::where('id', $user->id)->update(['liveness' => $value]); } } break; case 'visit': $key_name = '_cache:' . User::RDLASTTIMEKEY; $keys = $redis->keys($key_name . "*"); $user_ids = []; $values = []; foreach ($keys as $key) { $user_id = explode('_', $key)[5]; $user_ids[] = $user_id; $value = $redis->get($key); $value = explode('"', $value)[1]; $values['r_' . $user_id] = $value; //删除缓存 $redis->del($key); } $users = User::whereIn("id", $user_ids)->get(); foreach ($users as $user) { $value = $values['r_' . $user->id]; User::where('id', $user->id)->update(['last_visit' => $value]); } break; default: break; } return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function recommendActivity() { try { $activity_id = 435; $users = User::with('wechat')->where([/*'type'=>'single',*/ 'hidden_profile' => 'NONE', 'is_subscribe' => 1])->whereHas('profileCourtship', function ($sql) { $sql->where("city", '深圳市'); })->get(); foreach ($users as $user) { if (empty($user->wechat) || empty($user->wechat->official_openid)) continue; $param['touser'] = $user->wechat->official_openid; // dd($param['touser']); $param['activity_id'] = $activity_id; $url = ''; $path = 'pages/party/detail?party_id=' . $param['activity_id']; $param['template_id'] = config('wechat.tpls.activity_rec'); $param['url'] = $url; $param['miniprogram'] = [ 'appid' => config('wechat.mini_program.app_id'), 'pagepath' => $path, ]; $param['data'] = [ 'first' => '为你准备了一个精彩的【线下活动】。', 'keyword1' => $user->nickname, 'keyword2' => date('Y-m-d H:i:s'), 'remark' => '请点击进入查看详情,期待您的参与!', ]; // dd($param); \App\Jobs\SendTemplateMsg::dispatch($param)->onQueue('template_message'); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } //检查同步群聊成员 public function syncTeamMembers() { $teams = Team::get(); foreach ($teams as $team) { $im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET')); $result = $im_service->queryDetailGroup($team->id); if ($result['code'] == 200) { $wangyi_members = array_column($result['tinfo']['members'], 'accid'); $wangyi_owner = array_column($result['tinfo']['owner'], 'accid'); $wangyi_admins = array_column($result['tinfo']['admins'], 'accid'); $wangyi_members = array_merge($wangyi_members, $wangyi_admins, $wangyi_owner); $wangyi_members[] = $team->owner; $local_members = UserTeam::where('team_id', $team->id)->pluck('user_id')->toArray(); $delete_members = array_diff($local_members, $wangyi_members); $insert_members = array_diff($wangyi_members, $local_members); $insert = []; foreach ($insert_members as $user_id) { $new_arr = [ 'user_id' => $user_id, 'team_id' => $team->id, 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s"), ]; $insert[] = $new_arr; } if (!empty($delete_members)) { foreach ($delete_members as $delete_member) { UserTeam::where('user_id', $delete_member)->where('team_id', $team->id)->delete(); } } if (!empty($insert)) { UserTeam::insert($insert); } } } return false; } /** * 同步真人认证正面照到服务器 * @return [type] [description] */ public function syncLivePerson() { try { Liveperson::whereNull('love_avatar')->whereNoTNull('avatar')->chunk(100, function ($logs) { foreach ($logs as $log) { Image::configure(['driver' => 'gd']); $time = uniqid(); $image = Image::make($log->avatar); $file_path = storage_path("/qrcode/" . $time . "person.png"); $image->save($file_path); $pic = null; if (file_exists($file_path)) { $pic = $this->uploadFile($file_path); try { unlink($file_path); } catch (\Exception $e) { $this->getError($e); } } Liveperson::where("id", $log->id)->update(['love_avatar' => $pic]); } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function faceMatch() { try { $user_service = new UserService(); $data = []; Liveperson::with('user:id,photo')->where('status', 1)->whereHas('user', function ($sql) { $sql->whereNoTNull("photo")->where('is_photo_audited', 1); })->whereDoesntHave('faceMatch')->chunk(100, function ($logs) use ($user_service, &$data) { foreach ($logs as $log) { $image1 = $log->avatar; $image2 = $log->user->photo; $result = $user_service->faceMatch($image1, $image2); if (empty($result)) continue; if (empty($result) || !empty($result->error_msg)) { if ($log->user->id == 97761 || $log->user->id == 100729) continue; // User::where('id', $log->user->id)->update(['is_photo_audited'=>0]); continue; } $arr['user_id'] = $log->user->id; $arr['first_image'] = $image1; $arr['last_image'] = $image2; $arr['first_token'] = ($result->face_list)[0]->face_token; $arr['last_token'] = ($result->face_list)[1]->face_token; $arr['score'] = $result->score; $arr['created_at'] = $arr['updated_at'] = date('Y-m-d H:i:s'); $data[] = $arr; } }); if (count($data)) { FaceMatch::insert($data); } return true; } catch (\Exception $e) { $this->getError($e); return false; } } //好友消息未读短信通知 public function chatRemind() { if (config('app.env') == 'production') { $short_url = \CommonUtilsService::shortUrl(env('APP_URL') . '/h5/#/jump?type=message'); //已发送过短信的用户id $chat_messages = ChatMessage::whereHas('otherUser', function ($sql) { $sql->where('id', '>', 0)->where('hidden_profile', '<>', 'ALLSEX'); }) ->where('other_user_id', '<>', 1)->where('status', 0)->where('has_remain', 0)->where('type', 'chat')->get(); $update_messages = []; $remind_users = []; foreach ($chat_messages as $chat_message) { $key = 'remind_user_id_' . $chat_message->other_user_id; $has_send = Redis::get($key); if (!$has_send) { $remind_users[] = $chat_message->other_user_id; Redis::setex($key, 7 * 24 * 3600, $chat_message->other_user_id); } $update_messages[] = $chat_message->id; } if (!empty($update_messages)) { ChatMessage::whereIn('id', $update_messages)->update(['has_remain' => 1, 'status' => 1]); } //获取手机号 if ($remind_users) { $mobiles = User::whereIn('id', $remind_users)->pluck('mobile')->toArray(); $array = [ 'mobile' => $mobiles, 'message' => "【福恋】你有一条用户私聊消息未读,可点击 " . $short_url['url'] . " 查看消息内容并回复ta", ]; SendSmsBatch::dispatch($array)->onQueue('love'); } return true; } } public function syncSex() { try { $users = \DB::table('users as u') ->join('profile_courtships as c', function ($join) { $join->on('u.id', '=', 'c.user_id') ->on('c.sex', '!=', 'u.sex'); }) ->select('c.user_id', 'u.id', 'u.sex as u_sex', 'c.sex as c_sex') ->get(); foreach ($users as $user) { if ($user->u_sex) { \DB::table('profile_courtships')->where("user_id", $user->user_id)->update(['sex' => $user->u_sex]); } else { \DB::table('users')->where("id", $user->user_id)->update(['sex' => $user->c_sex]); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function syncBelief() { try { $users = \DB::table('users as u') ->join('profile_courtships as c', function ($join) { $join->on('u.id', '=', 'c.user_id') ->on('c.belief', '!=', 'u.belief'); }) ->select('c.user_id', 'u.id', 'u.belief as u_belief', 'c.belief as c_belief') ->get(); foreach ($users as $user) { if ($user->c_belief) { \DB::table('users')->where("id", $user->user_id)->update(['belief' => $user->c_belief]); } else { \DB::table('profile_courtships')->where("user_id", $user->user_id)->update(['belief' => $user->u_belief]); } } return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function syncCardIdSex() { try { User::whereNotNull("card_num")->where('is_approved', 1)->chunk(100, function ($users) { foreach ($users as $user) { if (strlen($user->card_num) != 18) continue; $sex = \CommonUtilsService::getSexByCard($user->card_num); User::where('id', $user->id)->update(['sex' => $sex]); if ($user->type == 'single') { ProfileCourtship::where('user_id', $user->id)->update(['sex' => $sex]); } else { ProfileCourtship::where('user_id', $user->id)->update(['sex' => $sex]); ProfileMarriage::where('user_id', $user->id)->update(['sex' => $sex]); } if ($user->sex != $sex) SignActitityMember::dispatch($user->id)->onQueue('love'); } }); } catch (\Exception $e) { $this->getError($e); return false; } } public function dailySyncCardIdSexBirthday() { try { User::whereNotNull("card_num")->where('is_approved', 1)->chunk(100, function ($users) { foreach ($users as $user) { $sex = \CommonUtilsService::getSexByCard($user->card_num); if (empty($sex)) continue; $result = \CommonUtilsService::checkCardBirhday($user->card_num); if ($result['error'] == 2) { $arr['birthday'] = $result['tdate']; } $arr['sex'] = $sex; if ($user->sex != $sex) User::where('id', $user->id)->update(['sex' => $sex]); if ($user->type == 'single') { ProfileCourtship::where('user_id', $user->id)->update($arr); } else { ProfileCourtship::where('user_id', $user->id)->update($arr); ProfileMarriage::where('user_id', $user->id)->update($arr); } } }); } catch (\Exception $e) { $this->getError($e); return false; } } /** * 检查收益冻结(包括服务商和用户) */ public function checkEarningFrozen() { try { MEarning::where('status', 'freezing')->orderBy('id', 'desc')->chunk(100, function ($earnings) { try { \DB::beginTransaction(); foreach ($earnings as $earning) { //当前时间 $now_time = time(); //冻结时间 $earning_time = strtotime($earning->earning_time); if ($now_time > $earning_time) {//解冻 //修改收益状态和冻结时间 $earning->status = "finished"; $earning->earning_time = date('Y-m-d H:i:s', $now_time); $earning->save(); //修改收益账号 if ($earning->m_user_id) { //用户账号 $account = MEarningAccount::firstOrCreate(['m_user_id' => $earning->m_user_id, 'm_id' => $earning->m_id]); $account->decrement('frozen_earning', $earning->value); $account->increment('balance', $earning->value); } else { //服务商账号 $account = MEarningAccount::firstOrCreate(['m_user_id' => 0, 'm_id' => $earning->m_id]); $account->decrement('frozen_earning', $earning->value); $account->increment('balance', $earning->value); } } } \DB::commit(); } catch (\Excepation $e) { \DB::rollback(); $this->getError($e); } }); } catch (\Exception $e) { $this->getError($e); return false; } } /** * 检查福恋收益冻结 */ public function checkLoveEarningFrozen() { try { Earning::where('status', 'freezing')->orderBy('id', 'desc')->chunk(100, function ($earnings) { try { \DB::beginTransaction(); foreach ($earnings as $earning) { //当前时间 $now_time = time(); //冻结时间 $earning_time = strtotime($earning->earning_time); if ($now_time > $earning_time) {//解冻 //修改收益状态和冻结时间 $earning->status = "finished"; $earning->earning_time = date('Y-m-d H:i:s', $now_time); $earning->save(); //修改收益账号 if ($earning->m_user_id) { //用户账号 $account = EarningAccount::firstOrCreate(['user_id' => $earning->user_id]); $account->decrement('frozen_earning', $earning->value); $account->increment('balance', $earning->value); } else { //服务商账号 $account = EarningAccount::firstOrCreate(['user_id' => $earning->user_id]); $account->decrement('frozen_earning', $earning->value); $account->increment('balance', $earning->value); } } } \DB::commit(); } catch (\Excepation $e) { \DB::rollback(); $this->getError($e); } }); } catch (\Exception $e) { $this->getError($e); return false; } } /** * 同步服务商咨询 */ public function syncMerchatInformations() { AnchorArticle::whereDoesntHave('information')->whereNotNull('m_id')->chunk(100, function ($articles) { foreach ($articles as $article) { $info = new MerchantInformation(); $info->merchant_id = $article->m_id; $info->title = $article->title; $info->content = $article->content; $info->pic = $article->cover; $info->created_at = $article->publish_at; $info->updated_at = $article->publish_at; $info->save(); $article->information_id = $info->id; $article->save(); } }); } /** * 最近七天已支付订单 没有生成收益 * */ public function checkEarningOrder() { try { $start_time = date('Y-m-d H:i:s', strtotime('-10 day')); TouristOrder::whereDoesntHave('mEarning')->where('pay_type', 'wechat') ->where('type', 'not like', '%reward%')->where('type', '<>', 'transfer') ->where('price', '>', 0)->where('pay_type', '<>', 'free') ->where('channel', '<>', 6)->where('pay_status', 4)->whereNotNull('merchant_id') ->where('created_at', '>=', $start_time)->chunk(100, function ($orders) { foreach ($orders as $order) { Log::info('checkEarningOrder earning:order:ids ' . $order->id); $redis = Redis::connection('big_data'); $redis->lpush('earning:order:ids', $order->id); } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } public function checkLoveEarningOrder() { try { $start_time = date('Y-m-d H:i:s', strtotime('-7 day')); Order::whereDoesntHave('earning')->where('type', 'rank')->where('price', '>', 0)->where('pay_type', '<>', 'free')->where('pay_status', 'PAID')->where('created_at', '>=', $start_time)->chunk(100, function ($orders) { foreach ($orders as $order) { $redis = Redis::connection('big_data'); $redis->lpush('love:earning:order:ids', $order->id); SendEarningMessage::dispatch($order->id)->onQueue('love')->delay(now()->addMinutes(1)); } }); return true; } catch (\Exception $e) { $this->getError($e); return false; } } /** * 同步用户活跃度 */ public function syncDynamic() { try { $start_time = date('Y-m-d H:i:s', strtotime('-1 month')); $users = Dynamic::where('created_at', '>', $start_time)->groupby('user_id')->select('user_id', DB::raw('count(*) as month_dynamic'))->chunk(100, function ($users) { foreach ($users as $user) { ProfileCourtship::where('id', $user->user_id)->update(['month_dynamic' => $user->month_dynamic]); } }); } catch (\Exception $e) { $this->getError($e); return false; } } // 商家生成月报告通知 public function generateMonthAnalyse() { try { $standardTime = date('Y-m-1'); $monthStart = date("Y-m-1 00:00:00"); $lastMonthStart = date('Y-m-1 00:00:00', strtotime("-1 month", strtotime($standardTime))); $lastMonthEnd = date('Y-m-d H:i:s', strtotime("-1 sec", strtotime($monthStart))); $mch_ids = MerchantAccount::pluck('id'); $title = date('Y年m月', strtotime($lastMonthStart)) . '数据报告'; $arr = []; foreach ($mch_ids as $value) { $visit_count = AccessRecord::where('account_id', $value)->where('updated_at', '>=', $lastMonthStart)->where('updated_at', '<=', $lastMonthEnd)->count(); $add_count = AccessRecord::where('account_id', $value)->where('created_at', '>=', $lastMonthStart)->where('created_at', '<=', $lastMonthEnd)->count(); $order_count = TouristOrder::where('merchant_id', $value)->whereIn('pay_status', [1, 4])->where('created_at', '>=', $lastMonthStart)->where('created_at', '<=', $lastMonthEnd)->count(); $profit = MEarning::where('m_id', $value)->where('m_user_id', 0)->where('status', 'finished')->where('created_at', '>=', $lastMonthStart)->where('created_at', '<=', $lastMonthEnd)->sum('value'); $content = "上月累计访问用户数" . $visit_count . ",其中新用户数" . $add_count . ",总订单数为" . $order_count . ",共产生" . $profit . "元收益"; $insert = [ 'm_id' => $value, 'm_user_id' => 0, 'type' => 'analyse', 'type_id' => 0, 'content' => json_encode(['title' => $title, 'content' => $content], true), 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; $arr[] = $insert; } SaasNotice::insert($arr); } catch (\Exception $e) { $this->getError($e); return false; } } /** * 每天访客(异性单身)通知 */ public function visitorNotice() { try { //每天有新访客的用户 DB::table('user_previews')->where('created_at', '>=', date('Y-m-d'))->where('status', 0)->groupby('user_id')->select('user_id')->orderBy('user_id', 'asc')->chunk(100, function ($pre_arr) { foreach ($pre_arr as $pre) { $user = User::where('id', $pre->user_id)->where('hidden_profile', 'NONE')->select('id', 'mobile', 'type', 'sex')->first(); if ($user && $user->type == 'single') { //异性单身 $count = UserPreview::with('previewUser')->whereHas('previewUser', function ($sql) use ($user) { $sql->where('type', 'single')->where('sex', '>', 0)->where('sex', '<>', $user->sex); })->where('user_id', $user->id)->where('created_at', '>=', date('Y-m-d'))->where('status', 0)->count(); if ($count) { $message = '有' . $count . '个人偷偷看了你哦,魅力在线的你,快来看看有没同频的人,点击 ufutx.cn/s/Ap5'; SendEasySms::dispatch(['mobile' => $user->mobile, 'message' => $message])->onQueue('love'); } } } }); } catch (\Exception $e) { $this->getError($e); return false; } } /** * 订单状态修改(结算) */ public function setOrderSettlement() { try { TouristOrder::where('pay_status', 1)->chunk(100, function ($orders) { foreach ($orders as $order) { if ($order->type == 'transfer' || $order->type == 'reward_info' || $order->pay_type == "partner" || $order->price == 0 || $order->channel == 6) { $order->update(['pay_status' => 4]); continue; } $order->origin_type = $order->type; //收益规则 if ($order->type == 'community') { $order->type = ($order->activity) ? 'activity' : 'service'; } //订单是否是服务市场订单 $is_market_service = MerchantService::where('merchant_id', $order->merchant_id)->where('type', $order->origin_type)->where('type_id', $order->type_id)->where('service_type', 1)->first() ? 1 : 0; if ($is_market_service) { $merchant_id = MarketService::where('type', $order->origin_type)->where('type_id', $order->type_id)->value('merchant_id'); } else { $merchant_id = $order->merchant_id; } $earning_rule = MerchantInfo::where('m_id', $order->merchant_id)->value('earning_rule') ?: 'system'; if ($earning_rule == 'system') { $rule = MEarningRules::where('m_id', $merchant_id)->where('name', $order->type)->where('type_id', $order->type_id)->first(); if (empty($rule)) { $rule = MEarningRules::where('m_id', $merchant_id)->where('name', $order->type)->where('type_id', 0)->first(); } } elseif ($earning_rule == 'grade') { $rule = $this->earningAgentRule($order); } $rule_date = $rule && $rule->ratio ? $rule->forzen_time : 0; $rule_time = $rule_date * 24 * 3600; Log::info("setOrderSettlement 订单id:$order->id"); if ($order->type == "activity") { //是否到了活动结束时间 $end_time = $order->activity->end_time; Log::info("setOrderSettlement 订单id:$order->id end_time: " . (date("Y-m-d H:i:s", strtotime($end_time) + $rule_time))); if (time() < strtotime($end_time) + $rule_time) continue; } else { Log::info("setOrderSettlement 订单id:$order->id end_time: " . (date("Y-m-d H:i:s", strtotime($order->created_at) + $rule_time))); if (time() < strtotime($order->created_at) + $rule_time) continue; } //修改订单状态 TouristOrder::where('id', $order->id)->update(['pay_status' => 4]); //加入队列计算收益 Log::info("setOrderSettlement earning:order:ids " . $order->id); $redis = Redis::connection('big_data'); $redis->lpush('earning:order:ids', $order->id); } }); } catch (\Exception $e) { $this->getError($e); } } public function earningAgentRule($order) { $last_user = MerchantUser::where('openid', $order->from_openid)->whereNotNull('openid')->first(); if (empty($last_user)) return null; //用户等级比例 $grade_user = MEarningGradeUser::with('grade')->where('m_id', $order->merchant_id)->where('user_id', $last_user->id)->first(); if ($grade_user && $grade_user->grade) { $grade = $grade_user->grade; } else { $price = TouristOrder::where('merchant_id', $order->merchant_id)->where("from_openid", $last_user->openid)->whereIn('pay_status', [1, 4])->where('id', '<', $order->id)->sum('price'); $grade = MEarningGrade::where('m_id', $order->merchant_id)->where('amount', '<=', $price)->orderBy('amount', 'desc')->first(); } //更新等级 // $this->updateEarningAgent($order, $last_user); return $grade; } /** * 检查收益通知 */ public function checkEarningNotice() { try { while (true) { $redis = Redis::connection('big_data'); $order_id = $redis->rpop('earning:notice:order:ids'); if (empty($order_id)) break; $order = TouristOrder::find($order_id); if (empty($order)) continue; $m_user_ids = MEarning::where('m_order_id', $order->id)->where('m_user_id', '!=', 0)->where('value', '>', 0)->distinct('m_user_id')->pluck('m_user_id'); foreach ($m_user_ids as $m_user_id) { $user = MerchantUser::where('id', $m_user_id)->first(); if (empty($user) || empty($user->mpUser)) continue; $user_service = new UserService(); $mp_user = $user->mpUser; \Log::info("收益通知用户id: " . $mp_user->id); //系统通知 $path_url = 'https://love.ufutx.com/h5/#/guidePage'; $count = Notice::where('user_id', $mp_user->id)->where('type_id', $order->id)->where('path_url', $path_url)->count(); if ($count) continue; $user_service->sendNotice($mp_user->id, 1, 'system', '您有一笔分享收益', null, $order->id, $path_url, 2); //公众号通知 if ($mp_user->wechat && $mp_user->wechat->official_openid) { $name = $order->name; if (empty($name)) { $name = MerchantUser::where('id', $order->account_id)->value('nickname'); } $mobile = $order->mobile; if (empty($mobile) || $mobile == '未获取') { $mobile = MerchantUser::where('id', $order->account_id)->value('mobile'); } $first = '您推荐的用户【' . $name; if ($mobile) { $first = $first . ',' . substr_replace($mobile, '****', 3, 4); } $first = $first . '】而产生的订单收益已到账'; //收益金额 $amount = MEarning::where('m_user_id', $m_user_id)->where('m_order_id', $order->id)->sum('value'); $data['touser'] = $mp_user->wechat->official_openid; $data['template_id'] = config('wechat.tpls.earning_notice'); $data['url'] = env('APP_URL') . '/auth/saas/earning/account'; $data['data'] = [ 'first' => $first, 'keyword1' => '¥' . $amount, 'keyword2' => date('Y-m-d H:i:s'), 'remark' => '点击查看详情,现在去提现', ]; SendTemplateMsg::dispatch($data)->onQueue('template_message'); } } } } catch (\Exception $e) { $this->getError($e); } } /** * 检查推荐是否购买 */ public function checkRecommendIsBuy() { try { PortraitRecord::where('recommend_type', 'user')->where('pay_status', 0)->where('channel', '<>', 3)->chunk(100, function ($records) { foreach ($records as $record) { $type = $record->match_type; if ($type == 'service' || $type == 'activity') $type = 'community'; if ($record->channel == 0 || $record->channel == 1) { $official_openid = Wechat::where('user_id', $record->user_id)->value('official_openid'); if (!$official_openid) { $official_openid = Viewer::where('user_id', $record->user_id)->value('openid'); } $from_official_openid = Wechat::where('user_id', $record->recommend_user_id)->value('official_openid'); if (!$from_official_openid) { $from_official_openid = Viewer::where('user_id', $record->recommend_user_id)->value('openid'); } $orders = TouristOrder::where('open_id', $official_openid)->where('from_openid', $from_official_openid)->where('type', $type)->where('type_id', $record->match_type_id)->get(); } else {//小程序 $mp_openid = Wechat::where('user_id', $record->user_id)->value('openid'); $from_mp_openid = Wechat::where('user_id', $record->recommend_user_id)->value('openid'); $orders = TouristOrder::where('open_id', $mp_openid)->where('from_openid', $from_mp_openid)->where('type', $type)->where('type_id', $record->match_type_id)->get(); } foreach ($orders as $order) { if ($order->pay_status == 0 || $order->pay_status == 3) continue; if ($order->pay_status == 1 || $order->pay_status == 4) $record->update(['pay_status' => 1]); } } }); } catch (\Exception $e) { $this->getError($e); } } //根据福恋用户id 匹配saas用户id public function matchMerchantUser($user_id) { $m_user = MerchantUser::where('user_id', $user_id)->first(); if ($m_user) { return $m_user->id; } $openid = Wechat::where('user_id', $user_id)->value('official_openid'); if ($openid) { $m_user = MerchantUser::where('openid', $openid)->first(); if ($m_user) { return $m_user->id; } } $openid = Viewer::where('user_id', $user_id)->value('openid'); if ($openid) { $m_user = MerchantUser::where('openid', $openid)->first(); if ($m_user) { return $m_user->id; } } $user = User::find($user_id); $m_user = MerchantUser::where('uuid', $user->uuid)->first(); if ($m_user) { return $m_user->id; } $unionid = Wechat::where('user_id', $user_id)->value('unionid'); if ($unionid) { $m_user = MerchantUser::where('unionid', $unionid)->first(); if ($m_user) { return $m_user->id; } } return 0; } //根据saas用户id 匹配福恋用户id public function matchFulinkUser($m_user_id) { $m_user = MerchantUser::where('id', $m_user_id)->first(); if ($m_user && $m_user->user_id) { return $m_user->user_id; } $wechat_user_id = Wechat::where('official_openid', $m_user->openid)->value('user_id'); if ($wechat_user_id) { return $wechat_user_id; } $wechat_user_id = Wechat::where('unionid', $m_user->unionid)->value('user_id'); if ($wechat_user_id) { return $wechat_user_id; } $viewer_user_id = Viewer::where('openid', $m_user_id)->value('user_id'); if ($viewer_user_id) { return $viewer_user_id; } $wechat_user_id = Wechat::where('unionid', $m_user->unionid)->value('user_id'); if ($wechat_user_id) { return $wechat_user_id; } $user_id = User::where('mobile', $m_user->mobile)->value('id'); if ($user_id) { return $user_id; } return 0; } /** * 同步saas用户和福恋用户的用户画像 */ public function synUserPortrait() { try { \Log::info('同步saas用户和福恋用户的用户画像'); $logs = Portrait::where('user_id', '<>', 0)->where('m_user_id', 0)->select('id', 'user_id', 'm_user_id', 'created_at', 'updated_at')->get(); foreach ($logs as $key => $log) { $m_user_id = $this->matchMerchantUser($log->user_id); if ($m_user_id == 0) continue; $log->update(['m_user_id' => $m_user_id]); } $histories = Portrait::where('user_id', 0)->where('m_user_id', '<>', 0)->select('id', 'user_id', 'm_user_id', 'created_at', 'updated_at')->get(); foreach ($histories as $key => $history) { $user_id = $this->matchFulinkUser($history->m_user_id); if ($user_id == 0) continue; $history->update(['user_id' => $user_id]); } } catch (\Exception $e) { $this->getError($e); } } public function syncServicesPv() { try { //测评 MerchantEvaluate::chunk(100, function ($items) { foreach ($items as $value) { $pv = Redis::zscore('evaluate', $value->test_item_id); if ($pv) { MerchantEvaluate::where('id', $value->id)->update(['pv' => $pv]); } } }); //咨询 Consultation::chunk(100, function ($items) { foreach ($items as $value) { $pv = Redis::zscore('consulation', $value->id); if ($pv) { Consultation::where('id', $value->id)->update(['pv' => $pv]); } } }); //课程 Course::chunk(100, function ($items) { foreach ($items as $value) { $pv = Redis::zscore('coursepv', $value->id); if ($pv) { Course::where('id', $value->id)->update(['pv' => $pv]); } } }); //店铺 MerchantShop::chunk(100, function ($items) { foreach ($items as $value) { $pv = Redis::zscore('shop', $value->id); if ($pv) { MerchantShop::where('id', $value->id)->update(['pv' => $pv]); } } }); //资讯 MerchantInformation::chunk(100, function ($items) { foreach ($items as $value) { $pv = Redis::zscore('information', $value->id); if ($pv) { MerchantInformation::where('id', $value->id)->update(['pv' => $pv]); } } }); //视频 AnchorVideo::chunk(100, function ($items) { foreach ($items as $value) { $pv = Redis::zscore('short_videopv', $value->id); if ($pv) { AnchorVideo::where('id', $value->id)->update(['pv' => $pv]); } } }); //测试 QATest::chunk(100, function ($items) { foreach ($items as $value) { $pv = Redis::zscore('testpv', $value->id); if ($pv) { QATest::where('id', $value->id)->update(['pv' => $pv]); } } }); } catch (\Exception $e) { $this->getError($e); } } public function getRefundTradeNo() { $dateline = time(); $mix_1 = rand(100, 999); $mix_2 = rand(10, 99); return 'r' . $dateline . $mix_1 . $mix_2; } //检测拼团失败 退款并通知 public function checkGroupRefund() { try { $time = date('Y-m-d H:i:s'); //已支付 但是没有拼团成功的拼单 记录 $histories = CollageGroupHistories::with('tOrder')->whereHas('tOrder', function ($sql) { $sql->whereIn('pay_status', [1, 4]); })->where('status', 0)->where('deadline', '<', $time)->get(); foreach ($histories as $key => $history) { $group = CollageGroup::find($history->group_id)->first(); if ($group->type == 'community') { $activity = CommunityActivity::find($group->type_id); if ($activity->class == 'one' && $activity->start_time > $time) // 活动已开始 不退款 continue; } DB::beginTransaction(); if ($history->tOrder->pay_status == 4) { //检测该笔订单是否生成收益记录 $log = MEarning::where('m_order_id', $history->tOrder->id)->first(); if ($log) { $earning = MEarningAccount::where('m_id', $history->tOrder->merchant_id)->where('m_user_id', 0)->first(); //已产生收益 余额充足(扣除余额) if ($earning && $earning->balance >= $history->tOrder->price && $earning->total_value >= $history->tOrder->price) { $earning->decrement('balance', $history->tOrder->price); $earning->decrement('total_value', $history->tOrder->price); } else { $merchant_name = Anchor::where('m_id', $history->tOrder->merchant_id)->value('name'); $message = '用户拼团失败,商家:' . $merchant_name . '余额不足以发起退款'; $this->sentMessage(18171893605, $message); break; } } } $refund_trade_no = $this->getRefundTradeNo(); $array = ['refund_desc' => '拼团订单失败,原路退款']; $result = \WechatService::orderRefund($history->tOrder->trade_no, $refund_trade_no, $history->tOrder->price, $history->tOrder->price, $array); $refund = MRefundOrder::create([ 'm_id' => $history->tOrder->merchant_id, 'm_user_id' => $history->tOrder->account_id, 'type' => $history->tOrder->type, 'trade_no' => $history->tOrder->trade_no, 'refund_trade_no' => $refund_trade_no, 'total_fee' => $history->tOrder->price, 'refund_fee' => $history->tOrder->price, 'is_hook' => 0, 'remark' => '拼团订单失败,原路退款', ]); if (is_array($result) && $result['status'] === true) {//退款成功 $history->tOrder->update(['pay_status' => 3]); $history->update(['status' => 2]); $refund->update(['is_hook' => 1]); $type = $this->getOrderType($history->tOrder); \CommonUtilsService::groupRefundNotice($history->tOrder, $history->tOrder->price, $type); } DB::commit(); } } catch (\Exception $e) { DB::rollBack(); $this->getError($e); } } public function getOrderType($order) { switch ($order->type) { case 'consult': $result = '咨询'; break; case 'shop': $result = '商品'; break; case 'community': $class = CommunityActivity::where('id', $order->type_id)->value('class'); $result = $class == 'many' ? '服务' : '活动'; break; case 'course': $result = '课程'; break; case 'evaluate': $result = '测评'; break; default: $result = '系统'; break; } return $result; } public function sendOrderSurvey() { try { while (true) { $order_id = Redis::rpop('survey:order:ids'); if (empty($order_id)) break; $order = TouristOrder::find($order_id); if (empty($order)) continue; $activity = CommunityActivity::where('id', $order->type_id)->first(); $class = $activity->class; $type = ($class == 'one') ? 'activity' : 'service'; $log = Questionnaire::where('type', $type)->where('type_id', $order->type_id)->first(); if (empty($log)) continue; $jump_url = urlencode(env('APP_URL') . '/pu/#/questionnaireV2/' . $log->id); $share_url = env('APP_URL') . '/api/official/live/wechat/FamilyAuth?merchant_id=' . $order->account_id . '&url=' . $jump_url; //模板通知 if ($order->channel == 0 || $order->channel == 1) { $openid = $order->open_id; } else { $openid = Wechat::where('openid', $order->openid)->value('official_openid'); } if ($openid) { $data['touser'] = $openid; $data['template_id'] = config('wechat.tpls.survey_notice'); $data['url'] = $share_url; $data['data'] = [ 'first' => '您好,问卷调查已经接收成功', 'keyword1' => '关于' . $activity->title . '问卷调查', 'keyword2' => date('Y-m-d H:i:s'), 'keyword3' => date('Y-m-d H:i:s', strtotime('+ 7 days')), 'remark' => '点击查看问卷调查内容', ]; SendTemplateMsg::dispatch($data)->onQueue('love'); } } } catch (\Exception $e) { $this->getError($e); } } public function operateNotice() { try { //今天需要跟进的角色 $today_role_ids = ServiceOrderOperation::whereHas('reminds', function ($sql) { $sql->where('remind_date', date('Y-m-d')); })->whereDoesntHave('remarks', function ($sql) { $sql->where('remind_date', date('Y-m-d')); })->where('status', 0)->pluck('order_role_id')->toArray(); //今天需要跟进的管理员 $admin_ids1 = ServiceRoleAdmin::whereIn('order_role_id', $today_role_ids)->distinct('admin_id')->pluck('admin_id')->toArray(); //明天需要跟进的角色 $tomorrow_role_ids = ServiceOrderOperation::whereHas('reminds', function ($sql) { $sql->where('remind_date', date('Y-m-d', strtotime('+1 day'))); })->whereDoesntHave('remarks', function ($sql) { $sql->where('remind_date', date('Y-m-d', strtotime('+1 day'))); })->where('status', 0)->pluck('order_role_id')->toArray(); $admin_ids2 = ServiceRoleAdmin::whereIn('order_role_id', $tomorrow_role_ids)->distinct('admin_id')->pluck('admin_id')->toArray(); $admin_ids = array_unique(array_merge($admin_ids1, $admin_ids2)); foreach ($admin_ids as $admin_id) { $today_operate_count = ServiceOrderOperation::whereHas('reminds', function ($sql) { $sql->where('remind_date', date('Y-m-d')); })->whereDoesntHave('remarks', function ($sql) { $sql->where('remind_date', date('Y-m-d')); })->whereHas('role.admins', function ($sql) use ($admin_id) { $sql->where('admin_id', $admin_id); })->where('status', 0)->count(); $tomorrow_operate_count = ServiceOrderOperation::whereHas('reminds', function ($sql) { $sql->where('remind_date', date('Y-m-d', strtotime('+1 day'))); })->whereDoesntHave('remarks', function ($sql) { $sql->where('remind_date', date('Y-m-d', strtotime('+1 day'))); })->whereHas('role.admins', function ($sql) use ($admin_id) { $sql->where('admin_id', $admin_id); })->where('status', 0)->count(); if (!$today_operate_count && !$tomorrow_operate_count) continue; if ($today_operate_count) { $title = "今日需要完成" . $today_operate_count . '条职责'; } if ($tomorrow_operate_count) { $other_title = '明日需要完成' . $tomorrow_operate_count . '条职责'; $title = $today_operate_count ? $title . ',' . $other_title : $other_title; } //模板消息提醒 $openid = null; if ($admin_id) { $openid = MerchantMembers::where('admin_id', $admin_id)->whereNotNull("notice_openid")->value('notice_openid'); } if ($openid) { $data['touser'] = $openid; $data['template_id'] = config('wechat.tpls.role_operate_notice'); $data['url'] = ''; $data['data'] = [ 'first' => '您好,服务流程职责提醒', 'keyword1' => '服务流程跟进', 'keyword2' => $title, 'remark' => '请进入服务商后台管理查看详情', ]; SendTemplateMsg::dispatch($data)->onQueue('love'); } } } catch (\Exception $e) { $this->getError($e); } } public function storeAdminNoticeUrl() { try { MerchantMembers::whereNull('notice_bind_url')->chunk(100, function ($members) { foreach ($members as $member) { $url = config('app.url') . '/bind/merchants/' . $member->mch_id . '/admins/' . $member->admin_id . '/notice/openid'; $qrcode = $this->getUrlqrcode($url); MerchantMembers::where('id', $member->id)->update(['notice_bind_url' => $qrcode]); } }); MerchantAccount::whereNull('notice_bind_url')->chunk(100, function ($accounts) { foreach ($accounts as $account) { $url = config('app.url') . '/bind/merchants/' . $account->id . '/admins/0/notice/openid'; $qrcode = $this->getUrlqrcode($url); MerchantAccount::where('id', $account->id)->update(['notice_bind_url' => $qrcode]); } }); } catch (\Exception $e) { $this->getError($e); } } public function getUrlqrcode($url, $size = 300) { $name = mb_substr($url, stripos($url, 'community')); $name = str_replace('/', '-', $name); $name = base64_encode($name); $path = storage_path("qrcode/$name.png"); QrCode::format('png')->margin(1)->size($size)->generate($url, $path); $pic = $this->uploadFile($path); try { unlink($path); } catch (\Exception $e) { $this->getError($e); } return $pic; } //即将到截止时间拼团订单(截止前半小时) 自动成团 public function autoFinishGroup() { $histories = CollageGroupHistories::with('tOrder')->whereHas('tOrder', function ($sql) { $sql->whereIn('pay_status', [1, 4]); }) ->where('is_initiator', 1)->where('status', 0) ->select('id', 'group_id', 'm_order_id', 'deadline') ->get(); $auto_ids = [];//需要自动成团的id foreach ($histories as $key => $history) { $deadline1 = strtotime($history->deadline);//截止时间时间戳 $deadline2 = strtotime(date('Y-m-d H:i:s'));//当前时间时间戳 if ($deadline1 - $deadline2 < 1800) { $auto_ids[] = $history->id; } } if (empty($auto_ids)) return; foreach ($auto_ids as $key => $value) { try { DB::beginTransaction(); $history = CollageGroupHistories::where('id', $value)->first(); $group = CollageGroup::where('id', $history->group_id)->first(); $count = CollageGroupBatch::where('batch', $history->id)->get()->count();//当前几人 $need_count = $group->require_num - $count;//需要几人 $insert = []; for ($i = 0; $i < $need_count; $i++) { $insert_sub = [ 'history_id' => 0,//0为虚拟用户 'batch' => $history->id, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; $insert[] = $insert_sub; } //插入虚拟用户 if (!empty($insert)) CollageGroupBatch::insert($insert); //拼团成功 $history_ids = CollageGroupBatch::where('batch', $history->id)->where('history_id', '<>', 0)->pluck('history_id'); CollageGroupHistories::whereIn('id', $history_ids)->update(['status' => 1]); switch ($group->type) { case 'course': $order = TouristOrder::find($history->m_order_id); UserCourses::where('course_id', $group->type_id)->where('trade_no', $order->trade_no) ->where('merchant_user_id', $history->m_user_id)->update(['status' => 1]); break; } DB::commit(); } catch (\Exception $e) { DB::rollBack(); $this->getError($e); return; } //本次拼团成功(给所有拼团人员发) $m_order_ids = CollageGroupHistories::whereIn('id', $history_ids)->pluck('m_order_id')->toArray(); $notice_users = TouristOrder::whereIn('id', $m_order_ids)->whereIn('pay_status', [1, 4])->get(); foreach ($notice_users as $notice_user) { if ($group->type == 'course') { switch ($notice_user->channel) { case "福恋小程序": $param = $this->getMpGroupParams($notice_user, $group, $history->deadline, 1); \WechatService::sendJoinGroupNotice($param); break; case "商家": $jump_url = urlencode(env('APP_URL') . '/pu/#/courseDetail/' . $group->type_id); $url = env('APP_URL') . '/api/official/live/wechat/FamilyAuth?merchant_id=' . $notice_user->merchant_id . '&anchor_openid=&url=' . $jump_url; $first = "您的课程拼团订单已成功拼团!"; $param = [ 'touser' => $order->open_id, 'template_id' => config('wechat.tpls.buy_success_notice'), 'url' => $url, 'data' => [ 'first' => $first, 'keyword1' => $order->desc, 'keyword2' => $order->trade_no, 'keyword3' => "¥" . $order->price, 'keyword4' => $order->created_at->toDateTimeString(), 'remark' => '点击详情可查看课程', ] ]; //通知用户 SendTemplateMsg::dispatch($param)->onQueue("love"); break; } } } } } public function getMpGroupParams($order, $group, $deadline, $status = 0) { $history_id = CollageGroupHistories::where('m_order_id', $order->id)->value('id'); $param['openid'] = $order->open_id; $param['order_id'] = $order->id; $param['title'] = mb_substr($order->desc, 0, 8) . '..'; $param['price'] = $order->price . '元'; $param['num'] = $group->require_num . '人'; $param['deadline'] = $deadline; //发送给团员的温馨提示 $param['team_desc'] = '您已成功参与拼团,具体拼团成败请留意通知'; //发送给团张的温馨提示 $param['lead_desc'] = '本团有效期为' . $group->expire_in . '小时 赶紧邀请好友来拼团吧'; $param['desc'] = '恭喜你,本次拼团已成功'; $param['status'] = $status; $param['history_id'] = $history_id; return $param; } public function getSaasGroupParams($order, $group, $deadline, $status = 0) { $history_id = CollageGroupHistories::where('m_order_id', $order->id)->value('id'); $param['openid'] = $order->open_id; $param['order_id'] = $order->id; $param['title'] = mb_substr($order->desc, 0, 8) . '..'; $param['price'] = $order->price . '元'; $param['num'] = $group->require_num . '人'; $param['deadline'] = $deadline; //发送给团员的温馨提示 $param['team_desc'] = '您已成功参与拼团,具体拼团成败请留意通知'; //发送给团张的温馨提示 $param['lead_desc'] = '本团有效期为' . $group->expire_in . '小时 赶紧邀请好友来拼团吧'; $param['desc'] = '恭喜你,本次拼团已成功'; $param['status'] = $status; $param['history_id'] = $history_id; return $param; } public function startMessageNotice() { try { $start_time = date('Y-m-d H:i', strtotime('-10 minute')); $other_user_ids = ChatMessage::where('status', 0)->where('created_at', '>', $start_time)->distinct('other_user_id')->pluck('other_user_id'); foreach ($other_user_ids as $other_user_id) { $other_user = User::find($other_user_id); if (empty($other_user)) continue; $users = ChatMessage::with('user')->where('other_user_id', $other_user_id)->where('status', 0)->where('created_at', '>', $start_time)->groupBy('user_id')->limit(3)->get(); $name = ''; if (isset($users[0]['user']['nickname'])) { $name = $name . $users[0]['user']['nickname']; } if (isset($users[1]['user']['nickname'])) { $name = $name . ', ' . $users[1]['user']['nickname']; } if (isset($users[2]['user']['nickname'])) { $name = $name . '等'; } $data['touser'] = $other_user->wechat ? $other_user->wechat->official_openid : null; $data['template_id'] = config('wechat.tpls.start_message_notice'); // $data['template_id'] = '5ax0Q1o71701F1efuMBvdR5FfQNebuQyv0j11p-iPgw'; $data['url'] = ''; $data['miniprogram'] = [ 'appid' => config('wechat.mini_program.app_id'), 'pagepath' => '/pages/tabBar/news' ]; // $ta = $user->sex == 1?'他':"她"; $data['data'] = [ 'first' => 'Hi, Ta在找你!', 'keyword1' => date('Y-m-d H:i:s'), 'keyword2' => $name, 'remark' => '本通知可在福恋小程序 我的-设置 中关闭。', ]; SendTemplateMsg::dispatch($data)->onQueue('start_message'); } } catch (\Exception $e) { $this->getError($e); } } public function homeRecommendUser() { try { $links = DB::table('recommend_linking_news as rln')->groupBy('id_users_left')->selectRaw('id_users_left as user_id, count(*) as count'); DB::table('users as u')->joinSub($links, 'ufutx_l', function ($join) { $join->on('l.user_id', '=', 'u.id'); }) ->where('l.count', '>', 1) ->where(['u.type' => 'single', 'u.hidden_profile' => 'NONE']) ->where("u.id", 58859) ->select('l.*', 'u.nickname', 'u.id', 'u.sex')->orderBy('u.id', 'desc')->chunk(100, function ($users) { foreach ($users as $user) { $start_time = date('Y-m-d 12:00:00'); $end_time = date('Y-m-d 12:00:00', strtotime('+1 day')); $now_time = date('Y-m-d H:i:s'); //是否查看最新的 $is_preview = RecommendUser::where("user_id", $user->id)->orderBy('start_time', 'desc')->value('is_preview'); if (empty($is_preview)) { //更新时间 RecommendUser::where("user_id", $user->id)->where('is_preview', 0)->update(['start_time' => $start_time, 'end_time' => $end_time]); continue; } //拉黑用户 $black_ids = (new LinkingBlacklist())->getBlackIds($user->id); $links = $this->maxScoreRecommendUsers($user, $black_ids); $black_ids = array_merge($black_ids, User::FULLLINKIDS); if (count($links) == 0) { // RecommendUser::where("user_id", $user->id)->delete(); // $links = $this->maxScoreRecommendUsers($user,$black_ids); // if (count($links) < 7) { // $recommend_users = DB::table('users as u')->rightJoin('area_users as au', 'au.user_id', '=', 'u.id') // ->leftJoin('profile_courtships as pc', 'pc.user_id', 'u.id') // ->whereNotIn('au.user_id',$black_ids) // ->where('au.area_id', 43)->where('au.is_audited', 1)->where("u.sex", '<>', $user->sex)->where('hidden_profile', 'NONE')->orderBy('au.created_at', 'desc')->select('u.id','u.photo', 'u.nickname','u.rank_id','u.is_approved', 'is_real_approved', 'pc.city','pc.birthday', 'pc.stature','u.industry', 'u.industry_sub', 'pc.interest_hobby' , 'pc.degree')->limit(7)->get(); $start_birthday = date('Y-m-d', strtotime($user->profileCourtship->birthday) - 5 * 365 * 24 * 60 * 60); $end_birthday = date('Y-m-d', strtotime($user->profileCourtship->birthday) + 5 * 365 * 24 * 60 * 60); $recommend_user_ids = RecommendUser::where("user_id", $user->id)->pluck('other_user_id')->toArray(); $recommend_users = DB::table('users as u') ->leftJoin('profile_courtships as pc', 'pc.user_id', '=', 'u.id') // ->leftJoin("recommend_linking_news as rl", 'rl.id_users_right', '=','u.id') // ->leftJoin('recommend_users as ru', 'ru.other_user_id','=', 'u.id') ->where("u.sex", '<>', $user->sex) ->whereNotNull('u.photo') ->where('u.is_approved', 1) ->where('u.hidden_profile', 'NONE') ->where("u.is_approved", 1) ->whereNotIn('u.id', $black_ids) ->where('u.type', 'single') ->where("u.belief", $user->belief) ->where("pc.state", ["从未结婚", "未婚"]) ->where('pc.negative_score', '<>', 200) // ->where('rl.id_users_left', $user->id) ->whereNotIn('u.id', $recommend_user_ids) ->where("pc.birthday", '>', $start_birthday) ->where('pc.birthday', '<', $end_birthday) ->select('u.id', 'u.photo', 'u.nickname', 'u.rank_id', 'u.is_approved', 'u.is_real_approved', 'pc.city', 'pc.birthday', 'pc.stature', 'u.industry', 'u.industry_sub', 'pc.interest_hobby', 'pc.introduction', 'pc.degree') ->limit(7)->get(); $data = []; foreach ($recommend_users as $recommend_user) { $data[] = ['user_id' => $user->id, 'other_user_id' => $recommend_user->id, 'start_time' => $start_time, 'end_time' => $end_time, 'is_preview' => 0, 'created_at' => $now_time, 'updated_at' => $now_time]; } RecommendUser::insert($data); } // } } }); } catch (\Exception $e) { $this->getError($e); } } public function maxScoreRecommendUsers($user, $black_ids) { $start_time = date('Y-m-d 12:00:00'); $end_time = date('Y-m-d 12:00:00', strtotime('+1 day')); $now_time = date('Y-m-d H:i:s'); $links = DB::table('recommend_linking_news as rln')->whereNotExists(function ($sql) use ($user) { $sql->select(DB::raw(1))->from('recommend_users as ru')->whereRaw('ufutx_ru.other_user_id = ufutx_rln.id_users_right ')->where('ru.user_id', $user->id); }) ->leftJoin('users as u', 'u.id', '=', 'rln.id_users_right') ->where('u.hidden_profile', 'NONE') ->where('u.type', 'single') ->whereNotNull('u.photo') ->where('id_users_left', $user->id)->whereNotIn('id_users_right', $black_ids)->orderBy('rln.score', 'desc')->limit(7)->get(); if (count($links) == 7) { $data = []; foreach ($links as $link) { $data[] = ['user_id' => $link->id_users_left, 'other_user_id' => $link->id_users_right, 'is_preview' => 0, 'start_time' => $start_time, 'end_time' => $end_time, 'created_at' => $now_time, 'updated_at' => $now_time]; } RecommendUser::insert($data); } return $links; } //自动分区推荐 public function areaUserBySetting() { //获取所有要自动跑的分区 try { $result = ClassAreaSetting::where('status', 1)->get(); $full_user_ids = StaffUser::pluck("user_id")->toArray(); $black_user_ids = SystemBlacklist::pluck('user_id')->toArray(); foreach ($result as $key => $value) { $has_in_ids = AreaUser::where('area_id', $value->class_id)->where('is_show', 1)->where('is_audited', 1)->pluck('user_id')->toArray(); //屏蔽人员id $has_in_ids = array_unique(array_merge($full_user_ids, $black_user_ids, $has_in_ids)); $users = DB::table('users as u') ->leftJoin('profile_courtships as pc', 'u.id', '=', 'pc.user_id')->whereNotNull('pc.user_id') ->select('u.id', 'u.nickname', 'u.photo', 'u.rank_id', 'u.belief', 'u.is_real_approved', 'u.hidden_profile', 'pc.user_id', 'pc.province', 'pc.city', 'pc.birthday', 'pc.degree', 'pc.introduction', 'pc.ideal_mate', 'pc.stature', DB::raw('char_length(introduction) as introduction_words'), DB::raw('char_length(ideal_mate) as ideal_mate_words')); if ($value->min_birth && $value->max_birth) { $users = $users->whereBetween('birthday', [$value->min_birth, $value->max_birth]); } if ($value->is_vip) { $op = $value->is_vip == 1 ? '>' : '='; $users = $users->where('u.rank_id', $op, 0); } if ($value->is_real_approved) { $op = $value->is_real_approved == 1 ? '=' : '<>'; $users = $users->where('u.is_real_approved', $op, 1); } if ($value->belief) { $belief = $value->belief == 1 ? '基督教' : '佛教'; $users = $users->where('u.belief', $belief); } if ($value->introduction_num) { $users = $users->whereRaw('char_length(introduction) >= ' . $value->introduction_num); } if ($value->ideal_mate_num) { $users = $users->whereRaw('char_length(ideal_mate) >= ' . $value->ideal_mate_num); } if ($value->province) { $users = $users->where('pc.province', $value->province); } if ($value->city) { $users = $users->where('pc.city', $value->city); } if ($value->min_degree || $value->max_degree) { if ($value->min_degree && !in_array($value->min_degree, [1, 2, 3, 4])) throw new \Exception('自动化专区,学历参数有误:' . $value->min_degree); if ($value->max_degree && !in_array($value->max_degree, [1, 2, 3, 4])) throw new \Exception('自动化专区,学历参数有误:' . $value->max_degree); $result = $this->degreeSort($value->min_degree, $value->max_degree); $users = $users->whereIn('pc.degree', $result); } if ($value->state) { $users = $users->where('u.type', '=', $value->state); } if ($value->min_stature) { $users = $users->where('pc.stature', '>=', $value->min_stature); } if ($value->max_stature) { $users = $users->where('pc.stature', '<=', $value->max_stature); } if ($value->photo_num) { $photo_user_ids = ProfilePhoto::selectRaw('count(id) as photo_count,user_id')->groupBy('user_id')->having('photo_count', '>=', $value->photo_num)->pluck('user_id')->toArray(); $users = $users->whereIn('u.id', $photo_user_ids); } if ($value->last_visit) { $time = date("Y-m-d", strtotime("-" . ($value->last_visit) . " month")); $users = $users->where("u.last_visit", ">", $time); } $users = $users->where('is_photo_audited', 1)->where('u.hidden_profile', 'NONE')->where('u.negative_score', '<', 200)->whereNotNull('u.photo')->whereNull('u.deleted_at')->whereNotIn('u.id', $has_in_ids)->orderBy('u.id', 'desc')->chunk(100, function ($users) use ($value) { DB::beginTransaction(); // 该用户是否在此专区 //1在 变成通过 2.不在 加入分区 $insert = []; foreach ($users as $key => $user) { $exist = AreaUser::where('area_id', $value->class_id)->where('user_id', $user->id)->first(); if ($exist) { $exist->update(['is_show' => 1, 'is_audited' => 1, 'is_apply' => 2]); continue; } $insert_sub = ['user_id' => $user->id, 'area_id' => $value->class_id, 'is_show' => 1, 'is_audited' => 1, 'is_apply' => 2, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'),]; $insert[] = $insert_sub; } if (!empty($insert)) AreaUser::insert($insert); DB::commit(); }); } } catch (\Exception $e) { DB::rollBack(); $this->getError($e); } } public function degreeSort($min_degree = null, $max_degree = null) { $degree_arr = ['专科', '本科', '硕士', '博士']; $need_arr = []; if (empty($min_degree) && empty($max_degree)) { return $need_arr; } elseif (empty($min_degree) && !empty($max_degree)) { foreach ($degree_arr as $key => $value) { $need_arr[] = $value; if ($max_degree == $key + 1) return $need_arr; } } elseif (!empty($min_degree) && empty($max_degree)) { foreach ($degree_arr as $key => $value) { $need_arr[] = $value; if ($min_degree == $key + 1) return $need_arr; } } elseif (!empty($min_degree) && !empty($max_degree) && $min_degree != $max_degree) { foreach ($degree_arr as $key => $value) {//23 12 if ($min_degree > ($key + 1)) continue; $need_arr[] = $value; if ($max_degree == $key + 1) return $need_arr; } } else {//最低学历最高学历相等 $need_arr[] = $degree_arr[$min_degree - 1]; return $need_arr; } } // 不符合专区设置条件自动踢出 public function checkAreaUsers() { try { $full_user_ids = StaffUser::pluck("user_id")->toArray(); $black_user_ids = SystemBlacklist::pluck('user_id')->toArray(); $out_user_ids = array_merge($full_user_ids, $black_user_ids); $settings = ClassAreaSetting::where('status', 1)->get(); foreach ($settings as $key => $value) { $del_user_id = [];//不符合条件的用户id $area_users = AreaUser::where('area_id', $value->class_id)->where('is_audited', 1)->get(); foreach ($area_users as $key => $area_user) { if (empty($area_user->user)) { $del_user_id[] = $area_user->user_id; continue; } if (in_array($area_user->user_id, $out_user_ids)) { $del_user_id[] = $area_user->user_id; continue; } if (empty($area_user->user->profileCourtship)) { $del_user_id[] = $area_user->user_id; continue; } $user = $area_user->user; if ($user->is_photo_audited != 1) {//头像没认证移除 $del_user_id[] = $area_user->user_id; continue; } $profile = $area_user->user->profileCourtship; if ($value->min_birth && $value->max_birth) {//出生 $time = strtotime($profile->birthday); $time1 = strtotime($value->min_birth); $time2 = strtotime($value->max_birth); if ($time < $time1 || $time > $time2) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->is_vip && $value->is_vip == 1) {//会员 if ($user->rank_id == 0) { $del_user_id[] = $area_user->user_id; continue; } } elseif ($value->is_vip && $value->is_vip == 2) { if ($user->rank_id > 0) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->is_real_approved && $value->is_real_approved == 1) {//真人认证 if ($user->is_real_approved != 1) { $del_user_id[] = $area_user->user_id; continue; } } elseif ($value->is_real_approved && $value->is_real_approved == 2) { if ($user->is_real_approved == 1) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->belief && $value->belief == 1) {//信仰 if ($user->belief != '基督教') { $del_user_id[] = $area_user->user_id; continue; } } elseif ($value->belief && $value->belief == 2) { if ($user->belief != '佛教') { $del_user_id[] = $area_user->user_id; continue; } } if ($value->min_degree || $value->max_degree) { $degree_arr = $this->degreeSort($value->min_degree, $value->max_degree); if (!in_array($profile->degree, $degree_arr)) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->min_stature) { if ($profile->stature < $value->min_stature) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->max_stature) { if ($profile->stature > $value->max_stature) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->province) { if ($profile->province != $value->province) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->city) { if ($profile->city != $value->city) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->state) { if ($user->type != $value->state) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->introduction_num) { if (mb_strlen($profile->introduction) < $value->introduction_num) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->ideal_mate_num) { if (mb_strlen($profile->ideal_mate) < $value->ideal_mate_num) { $del_user_id[] = $area_user->user_id; continue; } } if ($value->photo_num) {//生活照 $photo_num = $user->profilePhoto()->count(); if ($photo_num < $value->photo_num) { $del_user_id[] = $area_user->user_id; continue; } } } DB::beginTransaction(); AreaUser::where('area_id', $value->class_id)->whereIn('user_id', $del_user_id)->delete(); DB::commit(); } } catch (\Exception $e) { DB::rollBack(); $this->getError($e); } } public function initUserScore() { try { set_time_limit(0); $users = DB::table('users as u') ->leftJoin('recommend_linking_news as n', 'u.id', '=', 'n.id_users_left') ->leftJoin('profile_courtships as c', 'u.id', '=', 'c.user_id') ->leftJoin('system_blacklists as b', 'u.id', '=', 'b.user_id') ->whereNull('n.id')->whereNull('b.id') ->where('u.type', 'single')->where('u.hidden_profile', 'NONE')->whereNotNull('c.sex') ->whereNotNull('c.belief')->whereNotNull('c.province')->whereNotNull('c.city')->where('c.birthday', '<', '2004-01-01') ->select('u.id') ->orderBy('id', 'desc') ->chunk(100, function ($users) { foreach ($users as $user) { $redis = Redis::connection('big_data'); $redis->lpush('ai:update:ids', $user->id); } }); // foreach ($users as $user) // { // $redis = Redis::connection('big_data'); // $redis->lpush('ai:update:ids', $user->id); // } } catch (\Exception $e) { $this->getError($e); return false; } } public function http_get_data($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_URL, $url); ob_start(); curl_exec($ch); $return_content = ob_get_contents(); ob_end_clean(); $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $return_content; } //检测用户微信头像 public function checkUserPhoto() { $path = date('Y') . date('m') . "/" . date('d'); require_once base_path('vendor/aliyuncs/oss-sdk-php') . '/autoload.php'; try { $ossClient = new \OSS\OssClient(config('alioss.id'), config('alioss.secret'), config('alioss.host')); } catch (\OSS\Core\OssException $e) { return $this->failure('oss_connect_failure', $e->getMessage()); } //photo字段是微信头像用户 $users = User::where('photo', 'like', "%thirdwx%")->select('id', 'photo')->get(); foreach ($users as $key => $user) { $rand = \CommonUtilsService::getTradeNO(); $object = $path . "/" . $rand . ".jpg"; $file_url = 'https://' . config('alioss.picture_domain') . '/' . $object; $return_content = $this->http_get_data($user->photo); $filename = storage_path("qrcode/" . time() . $rand . '.png'); $fp = @fopen($filename, "a"); //将文件绑定到流 fwrite($fp, $return_content); //写入文件 $ossClient->uploadFile(config('alioss.buckets.picture'), $object, $filename); fclose($fp); unlink($filename); $user->update(['photo' => $file_url]); } return $this->success('ok'); } public function errorMsg() { try { $i = 100; while ($i) { $message = Redis::rpop('error_message'); if (empty($message)) break; SendMail::dispatch($message)->onQueue('error_email'); $i--; } } catch (\Exception $e) { $this->getError($e); } } public function appointment_sendMessage() { $start_time = Carbon::now()->addMinute(30)->format('H:i'); $end_time = Carbon::now()->addHour(1)->format('H:i'); $start_date = Carbon::now()->format('Y-m-d'); $saas_appointment_ids = SaasUserAppointment::with('merchant', 'merchant_user') ->where('appointment_date', $start_date) ->where('start_time', '=', $start_time) ->where('end_time', "=", $end_time) ->get(); foreach ($saas_appointment_ids as $key => $val) { if ($val->mobile) { $message = '您在今天' . $val->start_time . '-' . $val->end_time . '预约了' . $val->merchant->share_title . '商家,请及时与对方沟通'; Message::create([ 'phone' => $val->mobile, 'message' => $message, 'confirmed' => 1, 'ip' => request() ? request()->ip() : '127.0.0.1', ]); Messengers::sendSMS($val->mobile, $message); } if (!empty($val->merchant->mobile)) { $message = '用户' . $val->merchant_user->nickname . '今天' . $val->start_time . '-' . $val->end_time . '预约了您,请空闲出您的时间'; Message::create([ 'phone' => $val->merchant->mobile, 'message' => $message, 'confirmed' => 1, 'ip' => request() ? request()->ip() : '127.0.0.1', ]); Messengers::sendSMS($val->merchant->mobile, $message); } } } public function send_sms_message() { try { $start = true; while ($start) { $message = Redis::rpop('send_sms_message'); if (!empty($message)) { $message_array = json_decode($message, true); SendSmsBatch::dispatch($message_array)->onQueue('love'); } else { $start = false; } } } catch (\Exception $e) { $this->getError($e); } } public function checkCrmComment() { try { $date = date('Y-m-d H:i:s'); CrmUserLog::where('commented_at', '<', $date)->whereNotNull('commented_at')->whereNull('f_commented_at')->chunk(100, function ($logs) { foreach ($logs as $log) { CrmUser::where('user_id', $log->user_id)->update(['step' => 'sale', 'status' => 0, 'grade' => null, 'graded_at' => null]); CrmUserLog::where("id", $log->id)->forceDelete(); } }); } catch (\Exception $e) { $this->getError($e); } } public function CrmDataStat() { try { $this->crmRoleStat('c_service'); $this->crmRoleStat('t_service'); } catch (\Exception $e) { $this->getError($e); } } public function crmRoleStat($type) { try { $comment_type = ($type == 'c_service') ? 'crm' : "crm_t"; $role_type = ($type == 'c_service') ? '客服' : "销售"; $start_date = date('Y-m-d', strtotime('-1 day')); $end_date = date('Y-m-d'); CrmRole::withCount([ 'userLogs' => function ($sql) { $sql->where('status', 1); }, 'comments' => function ($sql) use ($start_date, $end_date, $comment_type) { $sql->where('type', $comment_type)->whereBetween('created_at', [$start_date, $end_date]); } ])->with('wechat')->where('type', $type)->chunk(100, function ($roles) use ($start_date, $end_date, $comment_type, $role_type) { foreach ($roles as $role) { $comment_user_count = ClientComment::where('maker_user_id', $role->user_id)->where('type', $comment_type)->whereBetween('created_at', [$start_date, $end_date])->groupBy('user_id')->count(); $openid = $role->wechat ? $role->wechat->official_openid : null; if ($openid) { $data['touser'] = $openid; $data['template_id'] = config('wechat.tpls.crm_role_data'); $data['url'] = 'https://love.ufutx.com/admin_pro/#/login'; $data['data'] = [ 'first' => '您好,以下是昨天的工作进度提醒:', 'keyword1' => $role_type, 'keyword2' => ' 昨天一共沟通过用户' . $comment_user_count . '位、填写备注' . $role->comments_count . '条,当前在服务的用户' . $role->user_logs_count . '位', 'remark' => '详情请进入后台系统查看', ]; SendTemplateMsg::dispatch($data)->onQueue('template_message'); } } }); } catch (\Exception $e) { $this->getError($e); } } public function checkReportFile() { try { ini_set('memory_limit', -1); $file = ReportFile::whereNull('url')->orWhere('url', '')->first(); if (empty($file)) return; SendMail::dispatch('有活动报告未生成成功 file_id:' . $file->id, 'hankin_h@126.com', 'message')->onQueue('error_email'); $order = TouristOrder::where('id', $file->order_id)->where('account_id', $file->user_id)->first(); // ReportExport::dispatch($order)->onQueue('report.export'); \App\Exports\ReportExport::export($order); } catch (\Exception $e) { $this->getError($e); } } public function checkTencentFaceIdRes() { TencentFaceidLog::where('is_real_approved', 0)->whereNotNull('eid_token')->chunk(100, function ($logs) { foreach ($logs as $log) { \Log::info('faceid.' . $log->id); $res = CommonUtilsService::tencentFaceidRes($log->eid_token); if (isset($res->Text) && isset($res->Text->ErrCode) && $res->Text->ErrCode == 0) { try { DB::beginTransaction(); TencentFaceidLog::where('id', $log->id)->update(['is_real_approved' => 1]); $sex = CommonUtilsService::getSexByCard($log->card_num); MerchantUser::where('openid', $log->openid)->update(['sex' => $sex]); DB::commit(); } catch (\Exception $e) { $this->getError($e); } } else { TencentFaceidLog::where('id', $log->id)->update(['eid_token' => null]); } } }); } public function checkUserDetailQrcode() { $city_arr = ["北京", "北京市"]; User::whereDoesntHave('userDetailQrcode')->whereHas("profileCourtship", function ($sql) use ($city_arr) { $sql->whereIn('city', $city_arr); })->chunk(100, function ($users) { foreach ($users as $user) { $qrcode_path = QrcodeRectService::getViewerMiniQrcode($user->id); if (empty($qrcode_path)) continue; // dd($qrcode_path); $param = ['page' => 'pages/home/information?id=' . $user->id, 'from_user_id' => $user->id]; $param = json_encode($param); $data = [ 'user_id' => $user->id, 'qrcode_path' => $qrcode_path, 'type' => 4, 'param' => $param, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; $user->my_qrcode = $qrcode_path; DB::table('user_share_qrcode')->insert($data); } }); } public function checkNoticeMsgStatus() { NoticeMessage::withCount('notices')->where('status', 0)->where('timing', "<", time())->chunk(100, function ($messages) { foreach ($messages as $message) { if ($message->notices_count) { NoticeMessage::where('id', $message->id)->update(['status' => 1]); } } }); } public function checkTestQrcode() { QATest::whereDoesntHave('qrcode', function ($sql) { $sql->where('type', 'test'); })->chunk(100, function ($tests) { foreach ($tests as $test) { MakeQrcode::dispatch('test', $test->id, $test->merchant_id)->onQueue('love'); } }); } public function transferOrderLinkmen() { TouristOrder::where('type', 'community')->whereIn('pay_status', [1, 4])->whereNull("linkmen_bk")->where('created_at', '>', '20230501')->chunk(100, function ($orders) { foreach ($orders as $order) { $linkmen = json_decode($order->linkmen); TouristOrder::where('id', $order->id)->update(['linkmen_bk' => json_encode($linkmen, JSON_UNESCAPED_UNICODE)]); } }); } /** * 检测一分钟前更新的账户是否存在异常 */ public function checkMEarningAccount() { $date = date('Y-m-d H:i', strtotime('-1 minute')); MEarningAccount::where('updated_at', ">=", $date)->chunk(100, function ($accounts) { foreach ($accounts as $account) { Log::info("检测账号id:{$account->id}"); CheckMEarningAccount::dispatch($account)->onQueue('love'); } }); } /** * 福恋小程序群聊未读通知 */ public function groupChatUnreadNotice() { $datetime = date('Y-m-d H:i:s', strtotime('-30 minute')); $where = [ ['created_at', '>=', $datetime] ]; $team_ids = MsgHistory::where($where)->groupBy('team_id')->pluck('team_id'); foreach ($team_ids as $team_id) { $cache_key = ApiRedisKey::getGroupChatUnreadKey($team_id); $user_ids = Redis::sMembers($cache_key); if (!$user_ids) { continue; } Redis::del($cache_key); foreach ($user_ids as $user_id) { GroupChatUnreadNotice::dispatch($team_id, $user_id)->onQueue('start_message'); } } } /** * 关闭资料用户移除群聊 */ public function clearCloseUserByGroupChat() { $ids = User::where('hidden_profile', 'ALLSEX')->limit(20)->pluck('id'); $im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET')); $where = [ ['type', '!=', 1], ]; $data = UserTeam::whereIn('user_id', $ids)->where($where)->limit(20)->get(); foreach ($data as $item) { $result = $im_service->leaveTeam($item->team_id, $item->user_id); if ($result['code'] == 200 || $result['code'] == 414) { UserTeam::where('user_id', $item->user_id)->where('team_id', $item->team_id)->delete(); } } } /** * 提醒saas咨询用户 */ public function remindConsult() { $start_date = date('Y-m-d H:i:s'); $end_date = date('Y-m-d H:i:s', strtotime('+30 minutes')); $data = ConsultationRecords::where('pay_status', 1) ->where('status', '<>', 2) ->whereNull('comment') ->whereRaw("LEFT(reservation_time,16) between '{$start_date}' and '{$end_date}'") ->get(); foreach ($data as $order) { $cache_key = sprintf("saas:remind:consult:%s", $order->id); $check = Redis::get($cache_key); //已经提醒过 if ($check) { continue; } $merchant_user = MerchantUser::find($order->merchant_user_id); if (!$merchant_user) { continue; } $consult = Consultation::find($order->consulation_id); if (!$consult) { continue; } //公众号 $consult_account = ConsultAccount::find($consult->consult_account_id); $content = "【{$consult->title}】咨询即将开始,请准时参加哦!"; $url = env('APP_URL') . "/pu/#/consultationIn?id={$order->consulation_id}&orderId={$order->id}&merchant_id={$order->merchant_id}&time={$order->duration}&mobile={$consult_account->mobile}"; \CommonUtilsService::consultCustomNotice( $merchant_user->openid, $url, $order->name, $order->reservation_time, $content ); //短信 if ($order->phone) { $content = "亲爱的用户,【{$consult->title}】{$order->reservation_time}咨询即将开始,请准时参加哦!"; Message::create([ 'phone' => $order->phone, 'message' => $content, 'confirmed' => 1, 'ip' => request() ? request()->ip() : '127.0.0.1', ]); Messengers::sendSMS($order->phone, $content); } Redis::setex($cache_key, 60 * 60, 1); } } /** * 提醒saas咨询超过预约结束时间的邀请评价 */ public function remindConsultEndComment() { $start_datetime = "2023-09-15 00:00";//过滤之前没处理的 $end_datetime = date('Y-m-d H:i'); $data = ConsultationRecords::where('pay_status', 1) ->where('status', '<>', 2) ->whereNull('comment') ->whereRaw("DATE_ADD(CONCAT(LEFT(reservation_time,11),RIGHT(reservation_time,5)),INTERVAL duration MINUTE) between '{$start_datetime}' and '{$end_datetime}'") ->get(); foreach ($data as $order) { $cache_key = sprintf("saas:remind:consult_end_comment:%s", $order->id); $check = Redis::get($cache_key); //已经提醒过 if ($check) { continue; } $merchant_user = MerchantUser::find($order->merchant_user_id); if (!$merchant_user) { continue; } $consult = Consultation::find($order->consulation_id); if (!$consult) { continue; } //公众号 $content = "感谢您的咨询,别忘记给我们留下宝贵的评价哦!如另约时间,请忽略本通知。"; $url = env('APP_URL') . "/pu/#/evaluation?id={$order->consulation_id}&orderId={$order->id}&merchant_id={$order->merchant_id}"; \CommonUtilsService::consultCustomNotice( $merchant_user->openid, $url, $order->name, $order->reservation_time, $content ); //短信 if ($order->phone) { $content = "亲爱的用户,【{$consult->title}】感谢您的咨询,别忘记给我们留下宝贵的评价哦!如另约时间,请忽略本通知。"; Message::create([ 'phone' => $order->phone, 'message' => $content, 'confirmed' => 1, 'ip' => request() ? request()->ip() : '127.0.0.1', ]); Messengers::sendSMS($order->phone, $content); } //修改为结束订单 ConsultationRecords::where('id', $order->id)->update(['status' => 2]); Redis::setex($cache_key, 60 * 60 * 24, 1); } } /** * 移除专区/置顶推荐不是单身的用户 */ public function clearAreasUserNotIsSingle() { $areas_ids = ClassArea::where('is_show', 1)->pluck('id')->toArray(); $areas_user_ids = AreaUser::whereIn('area_id', $areas_ids) ->where('is_audited', 1) ->groupBy('user_id') ->pluck('user_id') ->toArray(); $clear_user_ids = User::whereIn('id', $areas_user_ids)->where('type', '<>', 'single')->pluck('id')->toArray(); if (!$clear_user_ids) { return; } AreaUser::whereIn('area_id', $areas_ids) ->whereIn('user_id', $clear_user_ids) ->where('is_audited', 1) ->delete(); } /** * 同步云信用户资料 */ public function syncYunxinUser() { $cache_key = 'temp_cron_sync_yunxin_user_last_id'; $last_id = Redis::get($cache_key); $limit = request()->input('limit', 100); $where = []; if ($last_id) { $where[] = ['id', '>', $last_id]; } $users = User::query()->where($where)->orderBy('id', 'asc')->limit($limit)->get(); $im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET')); $last_user = $users->toArray()[count($users) - 1] ?? null; foreach ($users as $user) { $data = [ 'accid' => $user->id, 'name' => $user->nickname, 'icon' => $user->photo, 'gender' => $user->sex ]; try { $im_service->updateUinfoV2($data); } catch (\Exception $e) { continue; } } if ($last_user) { Redis::set($cache_key, $last_user['id']); } } public function inviteUserCountNotice() { $start_time = date('Y-m-d 00:00:00', strtotime('-1 day')); $end_time = date('Y-m-d 23:59:59', strtotime('-1 day')); $users = User::query() ->selectRaw('from_user_id,count(*) as count,GROUP_CONCAT(nickname SEPARATOR "、") as nicknames') ->whereBetween('created_at', [$start_time, $end_time]) ->whereNotNull('from_user_id') ->groupBy('from_user_id') ->get() ->toArray(); foreach ($users as &$item) { $wechat = Wechat::query()->where('user_id', $item['from_user_id'])->first(); if (!$wechat->official_openid) { continue; } $data['touser'] = $wechat->official_openid; $data['template_id'] = config('wechat.tpls.invite_register_notice'); $data['url'] = ''; $data['miniprogram'] = [ 'appid' => config('wechat.mini_program.app_id'), 'pagepath' => '/pages/users/myShare' ]; $data['data'] = [ 'thing6' => mb_strimwidth($item['nicknames'], 0, 20, '...', 'utf-8'), 'thing5' => "您昨天邀请了{$item['count']}位福恋小程序新用户注册!", 'time3' => date('Y年m月d日', strtotime('-1 day')), ]; SendTemplateMsg::dispatch($data)->onQueue('template_message'); } } }