123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664 |
- <?php
- namespace App\Service;
- use App\Log;
- use App\Models\AuthorizeCorp;
- use App\Models\CorpUserScaleWarningConf;
- use App\Models\DjUser;
- use App\Models\System\AdminManageCorp;
- use App\Models\System\Users;
- use App\Models\WarnGroup;
- use App\Models\WarnGroupDjuser;
- use App\Models\WarnGroupUser;
- use App\Models\WarnRule;
- use App\Models\WarnRuleConf;
- use App\Models\WarnUser;
- use App\RedisModel;
- use Illuminate\Support\Facades\Auth;
- class WarnService
- {
- public static function groupList($sysGroupId, $keyword, $page, $pageSize, $isSelect = 0)
- {
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- $query = WarnGroup::query()
- ->select(['id', 'name', 'enable'])
- ->where('sys_group_id', $sysGroupId)
- ->where(function ($query) use ($keyword) {
- if (!empty($keyword)) $query->where('name', 'like', '%'.$keyword.'%');
- });
- $total = $query->count();
- if ($total == 0) return [[], 0];
- if(1 == $isSelect){
- $groupList = $query->where('enable', 1)
- ->orderByDesc('created_at')
- ->get();
- } else {
- $groupList = $query
- ->orderByDesc('created_at')
- ->offset(($page - 1) * $pageSize)
- ->limit($pageSize)
- ->get();
- $groupIds = $groupList->pluck('id')->all();
- // 获取预警人员
- $groupUserArr = WarnGroupUser::getUserList($groupIds);
- // 获取客服信息
- $groupDjuserArr = WarnGroupDjuser::getDjserList($groupIds);
- foreach ($groupList as $groupInfo) {
- $groupInfo->user_list = $groupUserArr[$groupInfo->id] ?? [];
- $groupInfo->djuser_list = $groupDjuserArr[$groupInfo->id] ?? [];
- }
- }
- return [$groupList, $total];
- }
- public static function groupOperate($sysGroupId, $groupName, $userList, $djuserList, $groupId = null)
- {
- // 检测预警组名称
- if (empty($groupName)) return [false, 3201];
- // 检测预警用户是否是json
- $userArr = json_decode($userList, true);
- if (!is_array($userArr)) return [false, 3202];
- // 检测预警用户数据
- $userArr = array_unique($userArr);
- $traUserCount = count($userArr);
- $hasUserCount = WarnUser::query()
- ->whereIn('id', $userArr)
- ->where('enable', 1)
- ->count();
- if ($traUserCount != $hasUserCount) return [false, 3202];
- // 检测客服信息是否是json
- $djuserArr = json_decode($djuserList, true);
- if (!is_array($djuserArr)) return [false, 3202];
- $djuserStrArr = array_unique(array_map(function ($djuser) {
- return "('{$djuser['user_id']}', '{$djuser['corpid']}')";
- }, $djuserArr));
- // 检测客服数据
- $djusersWhereStr = implode(',', $djuserStrArr);
- $traDjuserCount = count($djuserStrArr);
- if($traDjuserCount > 0){
- $hasDjuserCount = DjUser::query()
- ->whereRaw("(user_id, corpid) IN ({$djusersWhereStr})")
- ->where('enable', 1)
- ->count();
- } else {
- $hasDjuserCount = 0;
- }
- if ($traDjuserCount != $hasDjuserCount) return [false, 3202];
- // 检测预警组名称是否存在
- $isExist = WarnGroup::query()
- ->where('sys_group_id', $sysGroupId)
- ->where('name', $groupName)
- ->where(function ($query) use ($groupId) {
- if (!is_null($groupId)) $query->where('id', '!=', $groupId);
- })
- ->where('enable', 1)
- ->exists();
- if ($isExist) return [false, 3204];
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- // 库存储
- \DB::begintransaction();
- try {
- if (is_null($groupId)) {
- // 插入
- $res = WarnGroup::query()->create([
- 'sys_group_id' => $sysGroupId,
- 'name' => $groupName,
- 'user_list' => implode(',', $userArr),
- 'dj_user_list' => json_encode($djuserArr, 256),
- ]);
- $groupId = $res->id;
- } else {
- // 更新
- // 检测数据是否存在
- $userGroupInfo = WarnGroup::query()
- ->where('sys_group_id', $sysGroupId)
- ->where('id', $groupId)
- ->first();
- if (empty($userGroupInfo)) {
- \DB::rollBack();
- return [[], 3205];
- }
- $userGroupInfo->update([
- 'name' => $groupName,
- 'user_list' => implode(',', $userArr),
- 'dj_user_list' => json_encode($djuserArr, 256),
- ]);
- }
- // 操作预警用户
- WarnGroupUser::groupUserOperate($groupId, $userArr);
- // 操作客服
- WarnGroupDjuser::groupDjuserOperate($groupId, $djuserArr);
- \DB::commit();
- return [true, 0];
- } catch (\Throwable $e) {
- Log::logError(
- '预警用户组操作有误~'.$e->getMessage().PHP_EOL.$e->getTraceAsString(),
- [
- 'sysGroupId' => $sysGroupId,
- 'groupName' => $groupName,
- 'userList' => $userList,
- 'groupId' => $groupId
- ],
- 'WarnService'
- );
- \DB::rollBack();
- return [false, 3106];
- }
- }
- public static function groupDetail($sysGroupId, $groupId)
- {
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- // 检测数据是否存在
- $userGroupInfo = WarnGroup::query()
- ->select(['id', 'name', 'enable'])
- ->where('sys_group_id', $sysGroupId)
- ->where('id', $groupId)
- ->first();
- if (empty($userGroupInfo)) return [[], 3205];
- // 获取预警人员
- $groupUserArr = WarnGroupUser::getUserList($groupId);
- $userGroupInfo->user_list = $groupUserArr[$groupId] ?? [];
- // 获取客服信息
- $groupDjuserArr = WarnGroupDjuser::getDjserList($groupId);
- $userGroupInfo->djuser_list = $groupDjuserArr[$groupId] ?? [];
- return [$userGroupInfo, 0];
- }
- public static function groupEableOp($sysGroupId, $groupId, $enable)
- {
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- // 检测数据是否存在
- $userGroupInfo = WarnGroup::query()
- ->where('sys_group_id', $sysGroupId)
- ->where('id', $groupId)
- ->first();
- if (empty($userGroupInfo)) return [[], 3205];
- try {
- $userGroupInfo->update(['enable' => $enable]);
- return [true, 0];
- } catch (\Throwable $e) {
- Log::logError(
- '预警用户组操作有误~'.$e->getMessage().PHP_EOL.$e->getTraceAsString(),
- [
- 'sysGroupId' => $sysGroupId,
- 'groupId' => $groupId,
- 'enable' => $enable
- ],
- 'WarnService'
- );
- return [false, 3106];
- }
- }
- public static function ruleConfList($sysGroupId)
- {
- // 规则列表
- $ruleList = WarnRule::query()
- ->select(['rule_id', 'rule', 'defval'])
- ->orderBy('id', 'ASC')
- ->get();
- if ($ruleList->isEmpty()) return [];
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- // 规则配置列表
- $ruleConfList = WarnRuleConf::query()
- ->where('sys_group_id', $sysGroupId)
- ->whereIn('rule_id', $ruleList->pluck('rule_id'))
- ->pluck('setval', 'rule_id');
- foreach ($ruleList as $rule) {
- $rule->setval = $ruleConfList->get($rule->rule_id) ?? $rule->defval;
- unset($rule->defval);
- }
- return $ruleList;
- }
- public static function ruleConfOperate($sysGroupId, $ruleId, $setVal)
- {
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- try {
- WarnRuleConf::query()
- ->updateOrCreate([
- 'sys_group_id' => $sysGroupId,
- 'rule_id' => $ruleId,
- ], [
- 'setval' => $setVal
- ]);
- return [true, 0];
- } catch (\Throwable $e) {
- Log::logError(
- '预警配置操作异常~ '.$e->getMessage().PHP_EOL.$e->getTraceAsString(),
- [
- 'sysGroupId' => $sysGroupId,
- 'ruleId' => $ruleId,
- 'setVal' => $setVal,
- ],
- 'WarnService'
- );
- return [false, 3106];
- }
- }
- public static function userList($sysGroupId, $keyword, $page, $pageSize)
- {
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- $query = WarnUser::query()
- ->select(['id', 'name', 'phone'])
- ->where('sys_group_id', $sysGroupId)
- ->where(function ($query) use ($keyword) {
- if (!empty($keyword)) $query->where('name', 'like', '%'.$keyword.'%');
- })
- ->where('enable', 1);
- $total = $query->count();
- if ($total == 0) return [[], 0];
- $userList = $query
- ->orderByDesc('created_at')
- ->offset(($page - 1) * $pageSize)
- ->limit($pageSize)
- ->get();
- return [$userList, $total];
- }
- public static function userOperate($sysGroupId, $name, $phone, $enable, $userId)
- {
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- // 检测手机号是否合法
- $isMob="/^1[3456789]{1}\d{9}$/";
- if(!preg_match($isMob, $phone)) return [false, 3203];
- // 检测预警人员手机号码是否存在
- $isExist = WarnUser::query()
- ->where('sys_group_id', $sysGroupId)
- ->where('phone', $phone)
- ->where(function ($query) use ($userId) {
- if (!empty($userId)) $query->where('id', '!=', $userId);
- })
- ->where('enable', 1)
- ->exists();
- if ($isExist) return [false, 3207];
- $hasPhone = $phone;
- if (!empty($userId)) {
- $userInfo = WarnUser::query()->find($userId);
- if (empty($userInfo)) return [false, 3208];
- $hasPhone = $userInfo->phone;
- }
- try {
- WarnUser::query()->updateOrCreate([
- 'sys_group_id' => $sysGroupId,
- 'phone' => $hasPhone
- ], [
- 'name' => $name,
- 'phone' => $phone,
- 'enable' => $enable
- ]);
- if(!empty($userId) && 0 == $enable) {
- # 禁用 查询预警组中所有使用该预警人的记录,然后在记录中删除该预警人
- $groupList = WarnGroup::query()->whereRaw('find_in_set('.$userId.', `user_list`)')->get();
- if($groupList->isNotEmpty()){
- foreach($groupList as $groupInfo) {
- $userList = explode(',', $groupInfo->user_list);
- $key = array_search($userId, $userList);
- unset($userList[$key]);
- $newUserList = implode(',', $userList);
- WarnGroup::query()->where('id', $groupInfo->id)->update(['user_list' => $newUserList]);
- }
- }
- WarnGroupUser::query()->where('user_id', $userId)->where('enable', 1)->update(['enable' => 0]);
- }
- return [true, 0];
- } catch (\Throwable $e) {
- Log::logError(
- '预警人员操作异常~ '.$e->getMessage().PHP_EOL.$e->getTraceAsString(),
- [
- 'sysGroupId' => $sysGroupId,
- 'ruleId' => $name,
- 'setVal' => $phone,
- 'enable' => $enable,
- 'userId' => $userId
- ],
- 'WarnService'
- );
- return [false, 3106];
- }
- }
- public static function djuserList($sysGroupId, $isActive)
- {
- // 获取系统分组id
- self::getSysGroupId($sysGroupId);
- $corpIdList = AdminManageCorp::query()
- ->where('sys_user_id', $sysGroupId)
- ->where('is_delete', 0)
- ->pluck('corpid')
- ->all();
- if (empty($corpIdList)) return [];
- $corpList = AuthorizeCorp::query()
- ->select(['id', 'corpid', 'corp_name'])
- ->whereIn('id', $corpIdList)
- ->where('enable', 1)
- ->get()
- ->keyBy('id')
- ->toArray();
- $userList = DjUser::query()
- ->select(['user_id', 'corpid', 'name', 'avatar', 'is_active', 'expire_time'])
- ->whereIn('corpid', array_column($corpList, 'corpid'))
- ->where('enable', 1)
- ->where('status', 1)
- ->where(function($query) use ($isActive) {
- if($isActive) $query->where('active_code', '>', '');
- })
- ->get()
- ->toArray();
- $corpUserList = [];
- 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'] = '即将过期';
- }
- }
- }
- }
- $corpUserList[$user['corpid']][] = $user;
- }
- $djuserList = [];
- foreach ($corpIdList as $corpId) {
- $corpInfo = $corpList[$corpId] ?? [];
- if (empty($corpInfo)) continue;
- $corpInfo['user_list'] = $corpUserList[$corpInfo['corpid']] ?? [];
- $djuserList[] = $corpInfo;
- }
- return $djuserList;
- }
- private static function getSysGroupId(&$sysGroupId)
- {
- $userInfo = Users::query()->find(Auth::id());
- if (!$userInfo->is_system_admin) $sysGroupId = $userInfo->group_admin_id;
- }
- public static function setCorpUserScaleWarnConf($sysGroupId, $adminId, $confList, $isSystemAdmin) {
- # 对规则配置数据项进行校验
- $thresholdList = CorpUserScaleWarningConf::THRESHOLD_LIST;
- $relationCorpIdList = AdminManageCorp::query()
- ->where("sys_user_id",$sysGroupId)
- ->where("is_delete",0)
- ->pluck("corpid")->toArray();
- $relationCorpList = AuthorizeCorp::query()->select('corpid')
- ->whereIn('id', $relationCorpIdList)
- ->where('enable', 1)->get();
- $confList = json_decode($confList, 1);
- foreach($confList as $confInfo) {
- if(!isset($confInfo['threshold']) || !isset($confInfo['corp_list']) || !in_array($confInfo['threshold'], $thresholdList)) {
- return ['规则配置数据项有误1', 3209];
- }
- # 系统管理员调过企微操作权限验证
- if($isSystemAdmin != Users::SYSTEM_ADMIN && !empty($confInfo['corp_list'])) {
- $corpList = $relationCorpList->whereIn('corpid', array_column($confInfo['corp_list'], 'corpid'))->all();
- $corpList = !empty($corpList) ? array_column($corpList, 'corpid') : [];
- if(count($corpList) < count($confInfo['corp_list'])) {
- return ['规则配置数据项有误2', 3209];
- }
- }
- }
- $updateTime = date('Y-m-d H:i:s');
- if($isSystemAdmin == Users::SYSTEM_ADMIN) {
- $sysGroupId = $adminId;
- }
- \DB::begintransaction();
- # 将配置数据拆分处理
- foreach($confList as $confInfo) {
- CorpUserScaleWarningConf::query()->where('sys_group_id', $sysGroupId)
- ->where('warning_threshold', $confInfo['threshold'])->where('enable', 1)
- ->update(['enable' => 0]);
- if(!empty($confInfo['corp_list'])) {
- $corpIdList = array_column($confInfo['corp_list'], 'corpid');
- foreach($corpIdList as $corpid) {
- $res = CorpUserScaleWarningConf::query()->updateOrCreate([
- 'sys_group_id' => $sysGroupId,
- 'corpid' => $corpid,
- 'warning_threshold' => $confInfo['threshold'],
- ],[
- 'enable' => 1,
- 'update_time' => $updateTime,
- ]);
- if(!$res) {
- \DB::rollBack();
- return ['更新数据异常,请联系管理员', 500];
- }
- }
- }
- }
- \DB::commit();
- return ['保存成功', 0];
- }
- public static function getCorpUserScaleWarnConf($sysGroupId, $adminId, $isSystemAdmin) {
- if($isSystemAdmin == Users::SYSTEM_ADMIN) {
- $sysGroupId = $adminId;
- }
- $query = CorpUserScaleWarningConf::query()->where('sys_group_id', $sysGroupId)
- ->where('enable', 1);
- if($isSystemAdmin != Users::SYSTEM_ADMIN) {
- $relationCorpIdList = AdminManageCorp::query()
- ->where("sys_user_id",$sysGroupId)
- ->where("is_delete",0)
- ->pluck("corpid")->toArray();
- $relationCorpList = AuthorizeCorp::query()->select('corpid')
- ->whereIn('id', $relationCorpIdList)
- ->where('enable', 1)->get();
- $corpIdList = $relationCorpList->isNotEmpty() ? array_column($relationCorpList->toArray(), 'corpid') : [];
- $query = $query->whereIn('corpid', $corpIdList);
- }
- # 查询所有有效数据
- $data = $query->get();
- $corpDataList = null;
- if($data->isNotEmpty()) {
- # 提取企微ID列表
- $corpIdList = array_column($data->toArray(), 'corpid');
- # 企微id去重
- $uniqueCorpIdList = array_unique($corpIdList);
- # 批量查询企微信息
- $corpDataList = AuthorizeCorp::getAllCorpList($uniqueCorpIdList);
- }
- $corpIdList = array_unique(array_column($data->toArray(), 'corpid'));
- $corpUserScaleList = CorpService::getMultipleCorpUserScaleFromRds($corpIdList);
- $result = [];
- foreach (CorpUserScaleWarningConf::THRESHOLD_LIST as $threshold) {
- $rows = $data->where('warning_threshold', $threshold)->all();
- $corpList = !empty($rows) ? array_column($rows, 'corpid') : [];
- # 获取企微用户规模
- $corpData = array_map(function($corpid) use ($corpDataList, $threshold, $corpUserScaleList) {
- $userScale = $corpUserScaleList[$corpid] ?? 0;
- $corpInfo = $corpDataList->where('corpid', $corpid)->first();
- $corpName = !empty($corpInfo) ? $corpInfo->corp_name : '';
- $rate = round($userScale / $threshold, 2);
- if($rate < 0.8) {
- $type = '1';
- } else if ($rate < 1) {
- $type = '2';
- } else {
- $type = '3';
- }
- return ['corpid' => $corpid, 'corp_name' => $corpName, 'user_scale' => $userScale, 'type' => $type];
- }, $corpList);
- array_multisort(array_column($corpData, 'user_scale'), SORT_DESC, $corpData);
- $result[] = [
- 'threshold' => $threshold,
- 'corp_list' => $corpData
- ];
- }
- return $result;
- }
- public static function setCorpUserScaleWarnConfNew($sysGroupId, $adminId, $isSystemAdmin, $threshold, $corpIdList) {
- $relationCorpIdList = AdminManageCorp::query()
- ->where("sys_user_id",$sysGroupId)
- ->where("is_delete",0)
- ->pluck("corpid")->toArray();
- $relationCorpList = AuthorizeCorp::query()->select('corpid')
- ->whereIn('id', $relationCorpIdList)
- ->where('enable', 1)->get();
- # 过滤空数据
- $corpIdList = array_filter($corpIdList);
- # 系统管理员调过企微操作权限验证
- if($isSystemAdmin != Users::SYSTEM_ADMIN && !empty($corpIdList)) {
- $corpList = $relationCorpList->whereIn('corpid', $corpIdList)->all();
- $corpList = !empty($corpList) ? array_column($corpList, 'corpid') : [];
- if(count($corpList) < count($corpList)) {
- return ['规则配置数据项有误2', 3209];
- }
- }
- $updateTime = date('Y-m-d H:i:s');
- if($isSystemAdmin == Users::SYSTEM_ADMIN) {
- $sysGroupId = $adminId;
- }
- \DB::begintransaction();
- CorpUserScaleWarningConf::query()->where('sys_group_id', $sysGroupId)
- ->where('warning_threshold', $threshold)->where('enable', 1)
- ->update(['enable' => 0]);
- if(!empty($corpIdList)) {
- foreach($corpIdList as $corpid) {
- $res = CorpUserScaleWarningConf::query()->updateOrCreate([
- 'sys_group_id' => $sysGroupId,
- 'corpid' => $corpid,
- 'warning_threshold' => $threshold,
- ],[
- 'enable' => 1,
- 'update_time' => $updateTime,
- ]);
- if(!$res) {
- \DB::rollBack();
- return ['更新数据异常,请联系管理员', 500];
- }
- }
- }
- \DB::commit();
- return ['保存成功', 0];
- }
- public static function getNoticeDataList($corpid, $userId, $noticeList, $noticeType) {
- # 获取企微名称
- $corp = AuthorizeCorp::query()->where('corpid', $corpid)->where('enable', 1)->value('corp_name');
- # 获取客服名称
- $userName = DjUser::query()->where('corpid', $corpid)->where('user_id', $userId)->where('enable', 1)->value('name');
- # 获取需要接收预警通知的用户信息
- $noticeList = explode(',', $noticeList);
- if($noticeType == 1) { // 预警人
- $noticeUserList = WarnUser::query()->whereIn('id', $noticeList)->where('enable', 1)->get();
- $noticeCorpUserList = [];
- } elseif ($noticeType == 2) { // 预警组
- $noticeGroupInfo = WarnGroup::query()->whereIn('id', $noticeList)->where('enable', 1)->first();
- $noticeUserIdList = $noticeGroupInfo->user_list;
- $noticeUserIdList = explode(',', $noticeUserIdList);
- $noticeUserList = WarnUser::query()->whereIn('id', $noticeUserIdList)->where('enable', 1)->get();
- $noticeCorpUserList = json_decode($noticeGroupInfo->dj_user_list, true);
- }
- return ['corp' => $corp, 'userName' => $userName, 'noticeUserList' => $noticeUserList, 'noticeCorpUserList' => $noticeCorpUserList];
- }
- }
|