123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822 |
- <?php
- /**
- * Created by PhpStorm.
- * User: shensong
- * Date: 2022/3/25
- * Time: 10:20
- */
- namespace App\Service;
- use App\Log;
- use App\Models\AccountLicenseRenewalJob;
- use App\Models\AccountLicenseRenewalJobRecord;
- use App\Models\AdqUser;
- use App\Models\AuthorizeCorp;
- use App\Models\CustomerDetails;
- use App\Models\DjDepartment;
- use App\Models\DjUser;
- use App\Models\OfficialAccount;
- use App\Models\OfficialWebUserActionSetId;
- use App\Models\Report\CustomerServiceData;
- use App\Models\Report\DjCustomerConversationReport;
- use App\Models\System\AdminManageCorp;
- use App\Models\System\Users;
- use App\Models\TencentAdConf;
- use App\RedisModel;
- use App\Support\EmailQueue;
- use App\Support\qyApi\QyCommon;
- class DjUserService
- {
- /**
- * 根据企业id查询内部员工列表
- * @param $corpid string 企业id
- * @param $userName string 客服名称
- * @return array
- */
- public static function userList($corpid, $userName, $status=null)
- {
- // 查询部门列表
- $departmentList = DjDepartment::query()
- ->selectRaw('department_id, name as department_name')
- ->where('enable', 1)
- ->where('corpid', $corpid)
- ->get()
- ->keyBy('department_id')
- ->toArray();
- $userList = DjUser::query()
- ->select(['user_id', 'name', 'open_user_id', 'avatar', 'department', 'status', 'is_active', 'expire_time'])
- ->where('corpid', $corpid)
- ->where('enable', 1)
- ->where('name', 'like', '%' . $userName . '%')
- ->where(function($query) use($status){
- if($status) $query->where('status', 1);
- })
- ->get()
- ->toArray();
- $departmentData = [];
- $userData = [];
- $total = 0;
- foreach ($userList as &$user) {
- $user['active_desc'] = '';
- if(!$user['is_active']) {
- $user['active_time'] = $user['expire_time'] = null;
- $user['active_desc'] = '未激活';
- } else {
- if($user['expire_time']) {
- $expireTimestamp = strtotime($user['expire_time']);
- if($expireTimestamp <= time()) {
- $user['active_desc'] = '未激活';
- } else {
- if($expireTimestamp - time() <= 86400 * 15) {
- $user['active_desc'] = '即将过期';
- }
- }
- }
- }
- $departmentIdList = explode(',', $user['department']);
- foreach ($departmentIdList as $departmentId) {
- if (!isset($departmentData[$departmentId])) {
- $departmentData[$departmentId] = isset($departmentList[$departmentId]) ? $departmentList[$departmentId] : [];
- }
- $user['department_list'][] = isset($departmentList[$departmentId]['department_name']) ? $departmentList[$departmentId]['department_name'] : '';
- $departmentData[$departmentId]['user_list'][] = $user;
- if (!in_array($user['user_id'], $userData)) {
- $userData[] = $user['user_id'];
- $total += 1;
- }
- }
- }
- return ['list' => array_values($departmentData), 'count' => $total];
- }
- /**
- * 成员管理列表
- * @param $corpid string 企业id
- * @param $userName string 客服名称
- * @param $departmentList array 部门列表
- * @param $page int 页码
- * @param $pageSize int 每页数据条数
- * @param $isActive
- * @param $appId
- * @param $accountId
- * @param $operatorId
- * @param $expireDays
- * @return array
- */
- public static function users($corpid, $userName, $userIds, $departmentList, $page, $pageSize, $isActive, $appId
- , $accountId, $operatorId, $expireDays)
- {
- if($userIds) {
- $userIds = explode(',', $userIds);
- }
- $users = [];
- if(!empty($appId) || !empty($accountId) || !empty($operatorId)) {
- $userResult = AdqUser::search([
- 'corpid' => $corpid,
- 'app_id' => $appId,
- 'account_id' => $accountId,
- 'operator_id' => $operatorId
- ]);
- $users = $userResult->pluck('user_id')->toArray();
- $users = array_filter($users);
- }
- $expireTime = null;
- if ($expireDays) {
- if(empty($isActive)) $isActive = 1;
- $expireTime = date('Y-m-d 00:00:00', strtotime('+' . $expireDays . ' days'));
- }
- list($userList, $userCount) = DjUser::getUserList($corpid, $userName, $userIds, $departmentList, $page, $pageSize
- , $isActive, $appId, $accountId, $operatorId, $users, $expireTime);
- // 查询部门列表
- $departmentList = DjDepartment::query()
- ->selectRaw('department_id, name as department_name')
- ->where('enable', 1)
- ->where('corpid', $corpid)
- ->get()
- ->keyBy('department_id')
- ->toArray();
- // 查询客服id列表
- $userIdList = array_column($userList, 'user_id');
- // 查询客服对应客户数
- $userCustomerCountList = CustomerDetails::suffix($corpid)
- ->selectRaw('user_id, count(1) as count')
- // ->whereIn('loss_status', [0, 1, 2])
- ->where('loss_status', 1)
- ->where('can_receive', 1)
- ->where('enable', 1)
- ->where('corpid', $corpid)
- ->whereIn('user_id', $userIdList)
- ->groupBy('user_id')
- ->get()
- ->keyBy('user_id')
- ->toArray();
- # 批量查询客服绑定的adq投放账号,公众号以及运营人员 投放人员
- $adqUserList = AdqUser::getUserList($corpid, $userIdList);
- $adqUserList = $adqUserList->keyBy('user_id')->toArray();
- # 提取客服绑定的公众号名称
- $appIdList = array_column($adqUserList, 'app_id');
- $appIdList = array_filter($appIdList);
- $appList = OfficialAccount::getAppInfoList($appIdList);
- # 提取客服绑定的运营人员名称
- $operatorIdList = array_column($adqUserList, 'operator_id');
- $operatorIdList = array_filter($operatorIdList);
- $operatorList = Users::getUserInfoList($operatorIdList);
- # 批量查询昨日新增客户数
- $yesterday = date('Y-m-d', strtotime('-1 days'));
- $reportList = DjCustomerConversationReport::query()
- ->whereIn('user_id', $userIdList)
- ->where('corpid', $corpid)
- ->where('date', $yesterday)
- ->select(['new_contact_cnt', 'loss_contact_cnt', 'user_id'])
- ->get();
- $yesterdayLoss = $yesterdayAdd = $customerCount = 0;
- foreach ($userList as $key => $value) {
- # 客服对应客户数
- $count = isset($userCustomerCountList[$value['user_id']]['count']) ? $userCustomerCountList[$value['user_id']]['count'] : 0;
- $userList[$key]['customer_number'] = $count;
- $userReport = $reportList->where('user_id', $value['user_id'])->first();
- $userList[$key]['new_contact_cnt'] = $userReport->new_contact_cnt ?? 0;
- $userList[$key]['loss_contact_cnt'] = $userReport->loss_contact_cnt ?? 0;
- $yesterdayLoss += $userList[$key]['loss_contact_cnt'];
- $yesterdayAdd += $userList[$key]['new_contact_cnt'];
- $customerCount += $count;
- # 客服对应部门
- $department = explode(',', $value['department']);
- $userList[$key]['department'] = $department;
- $departmentNameList = [];
- foreach($department as $item) {
- $departmentNameList[] = isset($departmentList[$item]['department_name']) ? $departmentList[$item]['department_name'] : '';
- }
- $userList[$key]['department_list'] = $departmentNameList;
- # 客服对应adq数据源
- $adqUserInfo = isset($adqUserList[$value['user_id']]) ? $adqUserList[$value['user_id']] : null;
- $userList[$key]['account_id'] = $adqUserInfo['account_id'] ?? null;
- $userList[$key]['order_type'] = empty($adqUserInfo['account_id']) ? 1 : 2;
- $userList[$key]['operator_id'] = $adqUserInfo['operator_id'] ?? null;
- $userList[$key]['app_id'] = $adqUserInfo['app_id'] ?? null;
- $userList[$key]['app_name'] = $appList[$userList[$key]['app_id']] ?? null;
- $userList[$key]['operator_name']=$operatorList[$userList[$key]['operator_id']] ?? null;
- # 激活状态描述
- $userList[$key]['active_desc'] = '';
- if(!$value['is_active']) {
- $userList[$key]['active_time'] = $userList[$key]['expire_time'] = null;
- $user['active_desc'] = '未激活';
- } else {
- if($value['expire_time']) {
- $expireTimestamp = strtotime($value['expire_time']);
- if($expireTimestamp <= time()) {
- $userList[$key]['active_desc'] = '未激活';
- } else {
- if($expireTimestamp - time() <= 86400 * 15) {
- $userList[$key]['active_desc'] = '即将过期';
- }
- }
- }
- }
- }
- return [$userList, $userCount, $yesterdayAdd, $yesterdayLoss, $customerCount];
- }
- /*
- * 成员详情
- * @param $corpid
- * @param $user_id
- */
- public static function user_info($corpid,$user_id){
- $ret = [];
- #成员基本信息
- $ret['user_info'] = DjUser::query()
- ->select(['user_id', 'name', 'open_user_id', 'avatar', 'department', 'status'])
- ->where('corpid', $corpid)
- ->where("user_id",$user_id)
- ->where('enable', 1)
- ->first();
- if(empty($ret['user_info'])) {
- return [];
- } else {
- $ret['user_info'] = $ret['user_info']->toArray();
- }
- #成员部门信息
- $ret['user_info']['department'] = DjDepartment::query()
- ->where('enable', 1)
- ->where('corpid', $corpid)
- ->whereIn("department_id",explode(',',$ret['user_info']['department']))
- ->pluck("name")
- ->toArray();
- # 客户总数
- $ret['customer']['total'] = CustomerDetails::suffix($corpid)
- ->whereIn('loss_status', [0, 1, 2])
- ->where('corpid', $corpid)
- ->where('user_id', $user_id)
- ->count();
- # 今日新增
- $ret['customer']['today'] = CustomerDetails::suffix($corpid)
- ->where('corpid', $corpid)
- ->where('user_id', $user_id)
- ->whereBetween("createtime",[strtotime(date("Y-m-d")),strtotime(date("Y-m-d 23:59:59"))])
- ->count();
- # 昨日新增
- $ret['customer']['yesterday'] = CustomerDetails::suffix($corpid)
- ->where('corpid', $corpid)
- ->where('user_id', $user_id)
- ->whereBetween("createtime",[strtotime(date("Y-m-d", strtotime("-1 days"))),strtotime(date("Y-m-d 23:59:59", strtotime("-1 days")))])
- ->count();
- # 总流失
- $ret['customer']['loss_total'] = CustomerDetails::suffix($corpid)
- ->where('loss_status', 0)
- ->where('corpid', $corpid)
- ->where('user_id', $user_id)
- ->count();
- # 今日流失
- $ret['customer']['today_loss'] = CustomerDetails::suffix($corpid)
- ->where('loss_status', 0)
- ->where('corpid', $corpid)
- ->where('user_id', $user_id)
- ->whereBetween("loss_time",[date("Y-m-d"),date("Y-m-d 23:59:59")])
- ->count();
- # 昨日流失
- $ret['customer']['yesterday_loss'] = CustomerDetails::suffix($corpid)
- ->where('loss_status', 0)
- ->where('corpid', $corpid)
- ->where('user_id', $user_id)
- ->whereBetween("loss_time",[date("Y-m-d", strtotime("-1 days")),date("Y-m-d 23:59:59", strtotime("-1 days"))])
- ->count();
- return $ret;
- }
- /*
- * 会话统计列表
- * @param $corpid
- * @param $user_id
- * @param $begin_date
- * @param $end_date
- */
- public static function conversation_report($corpid, $user_id, $begin_date, $end_date){
- $query = DjCustomerConversationReport::query()->where("corpid",$corpid)
- ->where("user_id",$user_id)
- ->whereBetween("date",[$begin_date,$end_date]);
- $list = $query->select(['date', 'chat_cnt', 'message_cnt', 'reply_percentage', 'avg_reply_time', 'new_contact_cnt', 'loss_contact_cnt'])
- ->orderBy("date","asc")
- ->get()->toArray();
- return $list;
- }
- /*
- * 会话统计列表
- * @param $corpid
- * @param $user_id
- * @param $begin_date
- * @param $end_date
- */
- public static function conversation_report_total($corpid, $user_id, $begin_date, $end_date){
- $query = DjCustomerConversationReport::query()->where("corpid",$corpid)
- ->where("user_id",$user_id)
- ->whereBetween("date",[$begin_date,$end_date]);
- /**汇总**/
- $total = $query->selectRaw("sum(chat_cnt) as chat_cnt")
- ->selectRaw("sum(message_cnt) as message_cnt")
- ->selectRaw("round(avg(reply_percentage),2) as reply_percentage")
- ->selectRaw("round(avg(avg_reply_time),2) as avg_reply_time")
- ->first();
- $total->chat_cnt = $total->chat_cnt===null ? 0:$total->chat_cnt;
- $total->message_cnt = $total->message_cnt===null ? 0:$total->message_cnt;
- $total->reply_percentage = $total->reply_percentage===null ? '0%':$total->reply_percentage."%";
- $total->avg_reply_time = $total->avg_reply_time===null ? 0:$total->avg_reply_time;
- return $total;
- }
- public static function departments($corpid)
- {
- // 查询部门列表
- $departmentList = DjDepartment::query()
- ->selectRaw('department_id, name as department_name, parent_id')
- ->where('enable', 1)
- ->where('corpid', $corpid)
- ->get()
- ->toArray();
- return $departmentList;
- }
- public static function bindUserAdqAccountId($corpid, $userId, $accountId, $sysGroupId, $appId, $operatorId)
- {
- $requestData = [
- 'corpid' => $corpid,
- 'user_id' => $userId,
- 'account_id' => $accountId,
- 'sys_group_id' => $sysGroupId,
- 'app_id' => $appId,
- 'operator_id' => $operatorId,
- ];
- try{
- $web_user_action_set_id = null;
- if(!empty($accountId)) {
- // 判断数据源ID是否已经授权到系统当中
- $adqInfo = OfficialWebUserActionSetId::query()
- ->where('account_id', $accountId)
- ->where('sys_group_id', $sysGroupId)
- ->first();
- if(empty($adqInfo)) {
- Log::logError('DjUserService.bindUserAdqAccountId', [
- 'params' => $requestData,
- 'err_msg' => 'adq投放账号ID查询失败,确认填写是否正确',
- ], 'interface');
- return ['adq投放账号ID查询失败,确认填写是否正确', 4900 ];
- }
- if(empty($adqInfo->web_user_action_set_id)) {
- Log::logError('DjUserService.bindUserAdqAccountId', [
- 'params' => $requestData,
- 'err_msg' => 'adq投放账号尚未绑定web数据源',
- ], 'interface');
- return ['adq投放账号尚未绑定web数据源', 4901];
- }
- $web_user_action_set_id = $adqInfo->web_user_action_set_id;
- }
- # 验证当公众号不为空时,投放账号以及运营人员也不能为空
- if(!empty($appId)) {
- if(empty($accountId)) {
- return ['公众号绑定adq投放账号必填', 4902];
- }
- if(empty($operatorId)) {
- return ['公众号绑定运营人员必填', 4903];
- }
- // # 验证一个公众号是否只绑定了一个运营人员
- // $operatorIdList = AdqUser::getOperateUidList($appId);
- // $newOperatorIdList = array_unique(array_merge([$operatorId], $operatorIdList));
- // if(count($newOperatorIdList) > 1) {
- // return ['一个公众号只可以绑定同一个运营人员', 4904];
- // }
- }
- // 查询数据是否已经在数据表中
- $row = AdqUser::query()
- ->where('corpid', $corpid)
- ->where('user_id', $userId)
- ->first();
- $enableUserIdList = Users::getCorpUserList($sysGroupId);
- $enableUserIdList[] = $row->operator_id ?? 0;
- if(!in_array($operatorId, $enableUserIdList)){
- return ['运营人员不合法', 5254];
- }
- if($row) {
- $res = AdqUser::query()
- ->where('corpid', $corpid)
- ->where('user_id', $userId)
- ->update([
- 'user_action_set_id' => $web_user_action_set_id,
- 'account_id' => $accountId,
- 'app_id' => $appId,
- 'operator_id' => $operatorId,
- 'update_time' => date('Y-m-d H:i:s')
- ]);
- } else {
- $userInfo = DjUser::query()
- ->where('corpid', $corpid)
- ->where('user_id', $userId)
- ->first();
- $res = AdqUser::query()
- ->insert([
- 'corpid' => $corpid,
- 'user_id' => $userId,
- 'user_action_set_id' => $web_user_action_set_id,
- 'account_id' => $accountId,
- 'app_id' => $appId,
- 'operator_id' => $operatorId,
- 'update_time' => date('Y-m-d H:i:s'),
- 'user_name' => $userInfo->name ?? null,
- ]);
- }
- if($res) {
- return ['成功', 0];
- } else {
- Log::logError('DjUserService.bindUserAdqAccountId', [
- 'params' => $requestData,
- 'err_msg' => '绑定客服数据源失败',
- ], 'interface');
- return ['失败', 400];
- }
- } catch (\Exception $exception) {
- Log::logError('DjUserService.bindUserAdqAccountId', [
- 'params' => $requestData,
- 'err_msg' => '绑定客服数据源程序异常',
- 'file' => $exception->getFile(),
- 'line' => $exception->getLine(),
- 'message' => $exception->getMessage(),
- 'trace' => $exception->getTraceAsString()
- ], 'interface');
- EmailQueue::rPush('绑定客服数据源程序异常', json_encode([
- 'params' => $requestData,
- 'err_msg' => '绑定客服数据源程序异常',
- 'file' => $exception->getFile(),
- 'line' => $exception->getLine(),
- 'message' => $exception->getMessage(),
- 'trace' => $exception->getTraceAsString()
- ], 256), ['song.shen@kuxuan-inc.com'], '猎羽');
- return ['失败', 400];
- }
- }
- public static function updateUserStatus($corpid, $userId, $status, &$errcode)
- {
- $customerServiceData = CustomerServiceData::query()->where('corpid', $corpid)
- ->where('user_id', $userId)->where('enable', 1)->first();
- if(empty($customerServiceData)) {
- $errcode = 1102;
- return false;
- }
- if($customerServiceData->status == $status) {
- return true;
- }
- $res = CustomerServiceData::query()->where('id', $customerServiceData->id)->update([
- 'status' => $status
- ]);
- if(!$res) {
- $errcode = 500;
- return false;
- }
- return true;
- }
- public static function nearExpiredUserList($corpid) {
- }
- # 创建客服许可续期任务
- public static function createRenewalJob($sysGroupId, $adminId, $title, $type, $accountList)
- {
- # 验证公司以及客服是否可用
- $corpIdList = AdminManageCorp::where('sys_user_id', $sysGroupId)
- ->where('is_delete', 0)->pluck('corpid')
- ->all();
- if (empty($corpIdList)) return ['没有可以操作的企微', 2704];
- $corpList = AuthorizeCorp::query()
- ->whereIn('id', $corpIdList)
- ->where('enable', 1)
- ->pluck('corpid')
- ->all();
- $userList = DjUser::query()
- ->select(['user_id', 'corpid', 'name', 'avatar', 'is_active', 'expire_time'])
- ->whereIn('corpid', $corpList)
- ->where('enable', 1)
- ->where('status', 1)
- ->where('active_code', '>', '')
- ->get();
- foreach($accountList as $accountInfo) {
- if(!isset($accountInfo['corpid']) || !isset($accountInfo['user_list'])) {
- return ['企微客服信息数据格式不合法, 请联系管理员', 2706];
- }
- if(!in_array($accountInfo['corpid'], $corpList)) {
- return ['企微列表超出操作范围', 2705];
- }
- foreach($accountInfo['user_list'] as $userId) {
- $userInfo = $userList->where('corpid', $accountInfo['corpid'])->where('user_id', $userId)->first();
- if(empty($userInfo)) {
- return ['所选择客服列表中存在不可续期客服', 2707];
- }
- }
- }
- \DB::beginTransaction();
- # 记录数据
- $ruleId = AccountLicenseRenewalJob::saveData($sysGroupId, $adminId, $accountList, $type, $title);
- if(empty($ruleId)) {
- \DB::rollBack();
- return ['程序1异常,请联系管理员', 500];
- }
- # 将信息写入Redis中处理
- $res = RedisModel::lPush(AccountLicenseRenewalJob::ACCOUNT_LICENSE_RENEWAL_JOB_LIST, $ruleId);
- if(!$res) {
- \DB::rollBack();
- return ['程序2异常,请联系管理员', 500];
- }
- \DB::commit();
- return ['添加成功', 0];
- }
- # 客服许可续期任务列表
- public static function renewalJobList($sysGroupId, $title, $status, $page, $pageSize, &$errno) {
- try{
- $jobModel = AccountLicenseRenewalJob::jobList($sysGroupId, $title, $status);
- $offset = ($page - 1) * $pageSize;
- $count = $jobModel->count();
- $list = $jobModel->orderBy('id', 'desc')->offset($offset)->limit($pageSize)->get();
- # 统计发送信息
- $ruleIds = $list->pluck('rule_id');
- $sendStatData = AccountLicenseRenewalJobRecord::query()->selectRaw("rule_id, count(1) as count")
- ->whereIn('rule_id', $ruleIds)->groupBy(['rule_id'])->get();
- $errStatData = AccountLicenseRenewalJobRecord::query()->select(['errcode', 'rule_id', 'user_id', 'corpid'])
- ->whereIn('rule_id', $ruleIds)->where('errcode', '!=', 0)->get();
- $senderIdList = [];
- foreach ($errStatData as $item) {
- $senderIdList[] = '("'.$item['corpid'].'","'.$item['user_id'].'")';
- }
- if(!empty($senderIdList)) {
- $senderInfoList = DjUser::query()->whereRaw('(corpid, user_id) in ('. implode(',', $senderIdList).')')
- ->where('enable', 1)->get();
- } else {
- $senderInfoList = DjUser::query()->where('enable', 1)->get();
- }
- $corpInfoList = AuthorizeCorp::query()->get();
- $errcodeConf = config('qyWechat.errcode');
- //数据格式化(异常状态码, 续期客服个数)
- foreach($list as $datum) {
- # 统计发送情况
- $sendStatInfo = $sendStatData->where('rule_id', $datum->rule_id)->first();
- $datum->user_num = $sendStatInfo->count ?? 0;
- if(0 == $datum->user_num) {
- # 记录表中客服数为空时从客服列表字段中解析客服个数
- $datum->user_num = self::getUserNum(json_decode($datum->account_list, 1));
- }
- # 查询失败信息
- $errList = $errStatData->where('rule_id', $datum->rule_id)->all();
- $err_msg_list = [];
- if(!empty($errList)){
- foreach ($errList as $item) {// 无可发送的客户
- $err_msg = $errcodeConf[$item['errcode']] ?? null;
- if(60111 == $item['errcode']) {//UserID不存在
- // 当出现此种错误时,将客服名称一并拼接起来展示
- $senderName = $senderInfoList->where('corpid', $item['corpid'])
- ->where('user_id', $item['user_id'])->first();
- $senderName = $senderName->name ?? '';
- $corpName = $corpInfoList->where('corpid', $item['corpid'])->first();
- $corpName = $corpName->corp_name ?? '';
- $err_msg = $corpName.$senderName.$err_msg;
- }
- $err_msg = $datum->status != 4 ? '部分失败由于'.$err_msg : $err_msg;
- if(!empty($err_msg) && !in_array($err_msg, $err_msg_list)) {
- $err_msg_list[] = $err_msg;
- }
- }
- }
- $datum->err_msg = $err_msg_list;
- unset($datum->account_list);
- }
- } catch (\Exception $e) {
- Log::logError('获取客服许可迁移列表过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- ], 'renewalJobList');
- $errno = 5237;
- return [[], 0];
- }
- return [$list, $count];
- }
- public static function getUserNum($accountList) {
- $number = 0;
- foreach($accountList as $item) {
- $number += count($item['user_list']);
- }
- return $number;
- }
- # 客服许可续期任务详情
- public static function renewalJobDetail($ruleId, &$errno) {
- try{
- $selectColumn = 'id as rule_id, title, status, account_list, create_time';
- $detail = AccountLicenseRenewalJob::getRuleInfoById($ruleId, $selectColumn);
- if(empty($detail)) return [];
- # 查询详情列表
- $list = AccountLicenseRenewalJobRecord::getRecordList($ruleId);
- if($list->isNotEmpty()) {
- # 提取企微信息
- $corpIdList = array_unique(array_column($list->toArray(), 'corpid'));
- $corpInfoList = AuthorizeCorp::query()->whereIn('corpid', $corpIdList)->get();
- $senderInfoList = DjUser::query()->whereIn('corpid', $corpIdList)
- ->where('enable', 1)->get();
- $errcodeConf = config('qyWechat.errcode');
- foreach($list as $item) {
- $corpInfo = $corpInfoList->where('corpid', $item->corpid)->first();
- $item->corp_name = $corpInfo->corp_name ?? '';
- $senderInfo = $senderInfoList->where('corpid', $item->corpid)->where('user_id', $item->user_id)->first();
- $item->user_name = $senderInfo->name ?? '';
- $errmsg = '';
- if($item->errcode > 0) $errmsg = $errcodeConf[$item->errcode] ?? null;
- $item->errmsg = $errmsg;
- }
- } else {
- $accountList = json_decode($detail->account_list, 1);
- $list = [];
- # 提取企微信息
- $corpIdList = array_unique(array_column($accountList, 'corpid'));
- $corpInfoList = AuthorizeCorp::query()->whereIn('corpid', $corpIdList)->get();
- $senderInfoList = DjUser::query()->whereIn('corpid', $corpIdList)
- ->where('enable', 1)->get();
- foreach($accountList as $item) {
- foreach ($item['user_list'] as $userId) {
- $value = [
- "corpid" => $item['corpid'],
- "user_id"=> $userId,
- "status" => -1 == $detail->status ? 2 : 0,
- "errcode"=> 0,
- "errmsg" => "",
- ];
- $corpInfo = $corpInfoList->where('corpid', $item['corpid'])->first();
- $value['corp_name'] = $corpInfo->corp_name ?? '';
- $senderInfo = $senderInfoList->where('corpid', $item['corpid'])->where('user_id', $userId)->first();
- $value['user_name'] = $senderInfo->name ?? '';
- $list[] = $value;
- }
- }
- }
- unset($detail->account_list);
- $detail->list = $list;
- } catch (\Exception $e) {
- Log::logError('群发详情获取过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'rule_id' => $ruleId
- ], 'ruleDetail');
- $errno = 5238;
- return [];
- }
- return $detail;
- }
- # 取消客服许可续期任务(只可取消未支付且未失效的订单)
- public static function cancelRenewalJob($ruleId, &$errno) {
- // 查询当前任务状态,如果为未执行,则直接修改任务状态为已取消,不在处理
- $selectColumn = 'status';
- \DB::begintransaction();
- $ruleInfo = AccountLicenseRenewalJob::getRuleInfoById($ruleId, $selectColumn);
- if($ruleInfo->status == AccountLicenseRenewalJob::NON_EXECUTION_JOB_STATUS) {
- $res = AccountLicenseRenewalJob::updateRuleStatus($ruleId, AccountLicenseRenewalJob::CANCELLED_JOB_STATUS);
- if($res) {
- \DB::commit();
- } else {
- \DB::rollBack();
- $errno = 500;
- }
- return [];
- }
- # 找到可以取消的订单id列表
- $orderList = AccountLicenseRenewalJobRecord::getUnPaidOrderIdList($ruleId);
- if($orderList->isEmpty()) {
- $errno = 5239;
- return '客服许可续期任务暂无可以取消的订单';
- }
- $resArr = [];
- $errcodeConf = config('qyWechat.errcode');
- $corpInfoList = AuthorizeCorp::query()->get();
- foreach ($orderList as $item) {
- $res = QyCommon::cancelOrder($item->corpid, $item->order_id);
- if(0 != $res['errcode']) {
- $corpInfo = $corpInfoList->where('corpid', $item->corpid)->first();
- $corpName = $corpInfo->corp_name ?? null;
- $err_msg = $errcodeConf[$res['errcode']] ?? null;
- $resArr[] = [
- 'corpid' => $item->corpid,
- 'corp_name' => $corpName,
- 'errcode' => $res['errcode'],
- 'errmsg' => $err_msg
- ];
- } else {
- AccountLicenseRenewalJobRecord::query()->where('corpid', $item->corpid)
- ->where('order_id', $item->order_id)->update(['status' => 2]);
- }
- }
- // 如果订单已经全部取消支付,则将任务状态变更为已取消
- $totalCount = AccountLicenseRenewalJobRecord::getRecordCount($ruleId, null);
- $cancelCount = AccountLicenseRenewalJobRecord::getRecordCount($ruleId, AccountLicenseRenewalJobRecord::CANCELLED_STATUS);
- if($totalCount > 0) {
- if($totalCount == $cancelCount) {
- AccountLicenseRenewalJob::updateRuleStatus($ruleId, AccountLicenseRenewalJob::CANCELLED_JOB_STATUS);
- }
- }
- if(!empty($resArr)) {
- $errno=2708;
- return $resArr;
- } else {
- return [];
- }
- }
- }
|