p2 project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1003 lines
44 KiB

<?php
namespace app\admin\service;
use app\admin\controller\Admin;
use app\admin\validate\AdminValidate;
use app\home\service\BaseHomeService;
use app\model\AdminLogModel;
use app\model\AdminModel;
use app\model\AuthRoleModel;
use app\model\GroupLeaderWithUserModel;
use app\model\PurchaseVipLogModel;
use app\model\PurchaseVipModel;
use app\model\SellerWithUserModel;
use app\model\TranslatorCustomerModel;
use app\model\UserAccessLogModel;
use app\model\UserChatGroupModel;
use app\model\UserChatLinkModel;
use app\model\UserModel;
use think\facade\Cache;
use think\exception\ValidateException;
use app\utility\UnqId;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;
use function Sodium\compare;
use think\facade\Request;
class AdminService extends AdminBaseService
{
// 根据角色获取账号列表
public function getUsersByRole($param)
{
try {
if (!isset($param['role_name'])) {
return $this->toData('400', '缺少参数');
}
$role = AuthRoleModel::where(['name'=>$param['role_name']])->find();
if (empty($role)) {
return $this->toData('500', '没有目标角色信息');
}
// 根据角色查询账号列表
$users = AdminModel::where(['role_id'=>$role->id])->select()->toArray();
return $this->toData('0', 'ok', $users);
} catch (\Exception $e) {
return $this->toData('500', '系统错误', [$e->getMessage(), $e->getTrace()]);
}
}
public function addUser($param): array
{
try {
// 参数校验
validate(AdminValidate::class)->scene('addUser')->check($param);
// 查找用户是否存在
$username = $param['user_name'];
$user = AdminModel::getByUserName($username);
if (!empty($user)) {
return $this->toData('200100', '该用户已存在', []);
}
$param['password'] = (new UnqId())->encryptPassword($param['password'], env('ENCRYPT.ADMINSALT'));
$param['invite_code'] = (new BaseHomeService())->getUniqInviteCode();
$resAdmin = AdminModel::create($param);
if (!$resAdmin) {
return $this->toData('1', '添加失败');
}
// 检测一下是否注册过聊天账号,没有的话就注册一下聊天账号
$isRegChat = UserChatLinkModel::where(['user_id'=>$resAdmin->id, 'user_type'=>UserChatLinkModel::USER_CHAT_LINK_USER_TYPE_ADMIN])->find();
if (empty($isRegChat)) {
$chatData = [
'Username' => $resAdmin->id."_".$resAdmin->user_name, //用account.id + account.user_name 拼接作为聊天账号注册的Username
'Password' => '123456',
'Nickname' => $resAdmin->user_name,
'Avatar' => env('USER.DEFAULT_HEAD_IMG_PATH'),
];
$chatUrl = env('CHAT_SERVER.BASE_URL') . '/api/user/register';
$regChat = (new \app\utility\RequestChatServer())->ReqChatServer($chatUrl, $chatData);
if (!isset($regChat['data']['uuid'])) {
return $this->toData('0', '注册聊天账号失败.', ['chat_response' => $regChat]);
}
UserChatLinkModel::create([
'user_id' => $resAdmin->id,
'user_type' => 2,
'chat_uuid' => $regChat['data']['uuid'],
'chat_name' => $regChat['data']['username']
]);
}
// 检测一下是否创建过聊天群组,没有的话创建一个
$chatGroup = UserChatGroupModel::where(['user_id'=>$resAdmin->id,'remark'=>UserChatGroupModel::USER_CHAT_GROUP_REMARK_ADMIN_INIT])->find();
if (empty($chatGroup)) {
$groupName = 'ivs-group'.$resAdmin->id;
$chatGroupData = [
'Name' => $groupName,
];
$chatGroupUrl = env('CHAT_SERVER.BASE_URL') . '/api/group/'.$regChat['data']['uuid'];
$chatGroupRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatGroupUrl, $chatGroupData);
if (!isset($chatGroupRes['data']['group_uuid'])) {
return $this->toData('100400', '创建聊天群组失败');
}
UserChatGroupModel::create([
'user_id' => $resAdmin->id,
'user_chat_uuid' => $regChat['data']['uuid'],
'group_name' => $groupName,
'group_uuid' => $chatGroupRes['data']['group_uuid'],
'remark' => UserChatGroupModel::USER_CHAT_GROUP_REMARK_ADMIN_INIT,
]);
}
return $this->toData('0', '添加成功');
} catch (ValidateException $validateException) {
$message = $validateException->getError();
return $this->toData('100400', $message);
} catch (\Exception $exception) {
return $this->toData('100500', '系统繁忙.', [$exception->getMessage()]);
}
}
/**
* 获取用户列表
* @return array
*/
public function getUserList($param)
{
try {
$adminModel = new AdminModel();
//查询条件
if (isset($param['user_name']) && !empty($param['user_name'])) {
$adminModel = $adminModel->where('user_name', $param['user_name']);
}
if (isset($param['nick_name']) && !empty($param['nick_name'])) {
$adminModel = $adminModel->where('nick_name', $param['nick_name']);
}
// 总数
$total = $adminModel->count();
$list = $adminModel->withoutField('password,token')->order('id', 'asc')->page($param['page'], $param['limit'])->select()->toArray();
$roleIds = array_column($list, "role_id");
$roleList = AuthRoleModel::where('id', 'in', $roleIds)->field('id,name')->select()->toArray();
$host = Request::host();
$host = str_replace('api.', '', $host);
if (!empty($list)) {
for ($i = 0; $i < count($list); $i++) {
$index = array_search($list[$i]['role_id'], array_column($roleList, 'id'));
if ($index !== false) {
$list[$i]['role_name'] = $roleList[$index]['name'];
}
$list[$i]['url'] = $host . '/register/index?=agent_code='.$list[$i]['invite_code'];
}
}
return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $list]);
} catch (\Exception $exception) {
return $this->toData('100500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
/**
* @desc 获取用户信息
* @param $userId
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function getUserInfo($userId)
{
try {
if (empty($userId) || $userId <= 0) {
return $this->toData('100403', 'Please log in first', []);
}
$info = AdminModel::find($userId);
if (empty($info)) {
return $this->toData('100400', 'The user does not exist.', []);
}
$infoArr = $info->toArray();
// 获取用户的聊天账号信息
$chatInfo = UserChatLinkModel::where(['user_id'=>$userId, 'user_type'=>UserChatLinkModel::USER_CHAT_LINK_USER_TYPE_ADMIN])->find();
$chat_uuid = 0;
if (!empty($chatInfo)) {
$chat_uuid = $chatInfo->chat_uuid;
}
$infoArr['chat_uuid'] = $chat_uuid;
// 返回数据
return $this->toData('0', 'Modification successful.', $infoArr);
} catch (\Exception $exception) {
return $this->toData('100500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
/**
* @desc 设置用户信息
* @param $userId
* @param $param
* @return array
*/
public function updateInfo($userId, $param): array
{
try {
// 主键
if (empty($userId) || $userId <= 0) {
return $this->toData('200403', 'Please log in first.', []);
}
// 参数校验
validate(AdminValidate::class)->scene('updateInfo')->check($param);
// 查找用户信息
$user = AdminModel::find($userId);
if (empty($user)) {
return $this->toData('200403', 'Please log in first.', []);
}
$user['nick_name'] = $param['nick_name'];
$user['email'] = $param['email'];
$user['mobile'] = isset($param['mobile']) ? $param['mobile'] : null;
$user['desc'] = isset($param['desc']) ? $param['mobile'] : null;
$user->save();
// 返回
return $this->toData('0', 'Modification successful.', []);
} catch (ValidateException $validateException) {
$message = $validateException->getError();
return $this->toData('200400', $message);
} catch (\Exception $exception) {
return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
}
}
/**
* 编辑账号信息
* @param $accountId
* @param $param
* @return array
*/
public function updateAccount($accountId, $param): array
{
try {
// 主键
if (empty($accountId) || $accountId <= 0) {
return $this->toData('200404', 'accountId lose.', []);
}
// 参数校验
validate(AdminValidate::class)->scene('updateAccount')->check($param);
// 查找用户信息
$user = AdminModel::find($accountId);
if (empty($user)) {
return $this->toData('200403', '不存在该用户.', []);
}
if (isset($param['password'])) {
$user['password'] = (new UnqId())->encryptPassword($param['password'], env('ENCRYPT.ADMINSALT'));
}
$user['role_id'] = $param['role_id'];
$user['user_name'] = $param['user_name'];
$user['nick_name'] = $param['nick_name'];
$user['email'] = $param['email'] ?? null;
$user['remark'] = $param['remark'] ?? null;
$user['parent_id'] = $param['parent_id'] ?? 0;
$user->save();
// 返回
return $this->toData('0', 'Modification successful.', []);
} catch (ValidateException $validateException) {
$message = $validateException->getError();
return $this->toData('200400', $message);
} catch (\Exception $exception) {
return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
}
}
public function updateAccountStauts($accountId, $param): array
{
try {
// 主键
if (empty($accountId) || $accountId <= 0) {
return $this->toData('200404', 'accountId lose.', []);
}
// 参数校验
validate(AdminValidate::class)->scene('updateAccountStatus')->check($param);
// 查找用户信息
$user = AdminModel::find($accountId);
if (empty($user)) {
return $this->toData('200403', 'Please log in first.', []);
}
$user['status'] = $param['status'];
$user->save();
// 返回
return $this->toData('0', 'Modification successful.', []);
} catch (ValidateException $validateException) {
$message = $validateException->getError();
return $this->toData('200400', $message);
} catch (\Exception $exception) {
return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
}
}
public function updatePassword($userId, $param): array
{
try {
// 主键
if (empty($userId) || $userId <= 0) {
return $this->toData('200403', 'Please log in first.', []);
}
// 参数校验
validate(AdminValidate::class)->scene('updatePassword')->check($param);
// 查找用户信息
$user = AdminModel::find($userId);
if (empty($user)) {
return $this->toData('200403', 'Please log in first.', []);
}
//检查原始密码
$flag = (new UnqId())->checkPassword($param['old_password'], $user['password'], env('ENCRYPT.ADMINSALT'));
if (!$flag) {
return $this->toData('200401', '原始密码错误', []);
}
//设置新密码
$newPassword = (new UnqId())->encryptPassword($param['new_password'], env('ENCRYPT.ADMINSALT'));
$user['password'] = $newPassword;
$user->save();
// 返回
return $this->toData('0', 'Modification successful.', []);
} catch (ValidateException $validateException) {
$message = $validateException->getError();
return $this->toData('200400', $message);
} catch (\Exception $exception) {
return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
}
}
public function del($id): array
{
try {
$adminModel = AdminModel::find($id);
$adminModel->delete();
// 返回
return $this->toData('0', 'Modification successful.', []);
} catch (ValidateException $validateException) {
$message = $validateException->getError();
return $this->toData('200400', $message);
} catch (\Exception $exception) {
return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
}
}
/**
* 查询用户权限代码
* @param $id
* @return array
*/
public function getPermCode($id): array
{
try {
$adminModel = AdminModel::find($id);
//根据角色查询权限代码
$roleModel = AuthRoleModel::find($adminModel->role_id);
$rules = $roleModel->rules;
if ($rules) {
$rules = explode(",", $rules);
//字符串转换为数字类型
// $rules=array_map(function ($value){
// return (int)$value;
// },$rules);
}
// 返回
return $this->toData('0', 'Modification successful.', $rules);
} catch (ValidateException $validateException) {
$message = $validateException->getError();
return $this->toData('200400', $message);
} catch (\Exception $exception) {
return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
}
}
/**
* @desc 退出登陆
* @param $userId
* @return array
*/
public function logout($userId)
{
try {
// 获取用户
$user = AdminModel::find($userId);
if (empty($user)) {
return $this->toData('200300', '用户不存在', []);
}
$user->token = "";
$user->save();
return $this->toData('0', 'Modification successful.');
} catch (\Exception $exception) {
return $this->toData('200500', 'The system is busy.', [$exception->getMessage()]);
}
}
public function logList($param)
{
try {
$adminLogModel = new AdminLogModel();
//查询条件
if (!empty($param['create_date'])) {
$adminLogModel = $adminLogModel->where('create_date', $param['create_date']);
}
// 总数
$total = $adminLogModel->count();
$list = $adminLogModel->order('id', 'desc')->page($param['page'], $param['limit'])->select()->toArray();
$accountIds = array_column($list, "admin_id");
$accountList = AdminModel::where('id', 'in', $accountIds)->column('user_name', 'id');
// $menuList = AuthRuleModel::column('title', 'path');
if (!empty($list)) {
foreach ($list as &$v) {
$v['admin_name'] = $accountList[$v['admin_id']] ?? '-';
$v['path_text'] = '用户上分';
}
}
return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $list]);
} catch (\Exception $exception) {
return $this->toData('100500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
public function inviteCode()
{
try {
$user = AdminModel::select();
foreach ($user as $v){
$inviteCode = (new BaseHomeService())->getUniqInviteCode();
AdminModel::where('id',$v->id)->update(['invite_code'=>$inviteCode]);
}
} catch (\Exception $exception) {
return $this->toData('500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
// 获取翻译员列表
public function getTranslatorList($param)
{
try {
if (empty($param['page']) || empty($param['limit'])) {
return $this->toData('400', '缺少分页参数');
}
// 查询角色表中翻译角色的id
$role = AuthRoleModel::where(['name'=>'翻译'])->find();
if (empty($role)) {
return $this->toData('400', '系统不存在翻译角色,请先创建');
}
// 查询属于翻译角色的所有账号
$where = ['role_id'=>$role->id];
if (!empty($param['user_name'])) {
$list = AdminModel::where($where)->whereLike('user_name', '%'.$param['user_name'].'%')->order('id', 'desc')->paginate([
'list_rows' => $param['limit'],
'page' => $param['page'],
]);
} else {
$list = AdminModel::where($where)->order('id', 'desc')->paginate([
'list_rows' => $param['limit'],
'page' => $param['page'],
]);
}
return $this->toData('0', 'SUCCESS', [
'list' => $list->items(), // 当前页的数据
'page' => $list->currentPage(), // 当前页码
'total' => $list->total(), // 总记录数
'last_page' => $list->lastPage(), // 最后一页页码
]);
} catch (\Exception $exception) {
return $this->toData('500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
// 翻译员添加客服聊天好友
public function translatorAddCustomer($param)
{
try {
if (empty($param['translator_id'])) {
return $this->toData('400', '缺少翻译员参数');
}
if (empty($param['customer_id_list']) || !is_array($param['customer_id_list'])) {
return $this->toData('400', '缺少客服参数');
}
// 翻译员的聊天账号信息
$translatorChatInfo = UserChatLinkModel::where(['user_id'=>$param['translator_id'], 'user_type'=>UserChatLinkModel::USER_CHAT_LINK_USER_TYPE_ADMIN])->find();
if (empty($translatorChatInfo)) {
return $this->toData('500', '翻译员的聊条账号信息错误');
}
// 翻译员创建的聊天群组信息
$chatGroup = UserChatGroupModel::where(['user_id'=>$param['translator_id'], 'remark'=>UserChatGroupModel::USER_CHAT_GROUP_REMARK_ADMIN_INIT])->find();
if (empty($chatGroup)) {
return $this->toData('500', 'The chat group is error.');
}
foreach ($param['customer_id_list'] as $customerId) {
// 记录好友关系
$translatorCustomer = TranslatorCustomerModel::where(['translator_id'=>$param['translator_id'], 'customer_id'=>$customerId])->find();
if (empty($translatorCustomer)) {
TranslatorCustomerModel::create(['translator_id'=>$param['translator_id'], 'customer_id'=>$customerId]);
}
//查询客服的聊天账号uuid
$customerChatInfo = UserChatLinkModel::where(['user_id'=>$customerId, 'user_type'=>UserChatLinkModel::USER_CHAT_LINK_USER_TYPE_ADMIN])->find();
if (empty($customerChatInfo)) {
return $this->toData('500', '客服的聊天账号信息错误');
}
$chatFriendsData = [
'UserUuid' => $translatorChatInfo->chat_uuid,
'CustomerUuid' => $customerChatInfo->chat_uuid,
];
$chatFriendsUrl = env('CHAT_SERVER.BASE_URL') . '/api/eachOtherFriends';
$chatFriendsRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatFriendsUrl, $chatFriendsData);
Log::info("翻译员添加客服好友结果:". json_encode($chatFriendsRes));
// 将客服添加到翻译员的聊天群组中
$joinChatGroupUrl = env('CHAT_SERVER.BASE_URL') . '/api/group/join/'.$customerChatInfo->chat_uuid.'/'.$chatGroup->group_uuid;
$joinChatGroupRes = (new \app\utility\RequestChatServer())->ReqChatServer($joinChatGroupUrl, []);
Log::info("翻译员添加客服到聊天群组结果:". json_encode($joinChatGroupRes));
}
return $this->toData('0', 'SUCCESS', []);
} catch (\Exception $exception) {
return $this->toData('500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
// 翻译员以绑定的客服列表
public function translatorBindCustomerList($param)
{
try {
if (empty($param['translator_id'])) {
return $this->toData('400', '缺少参数');
}
if (empty($param['page']) || empty($param['limit'])) {
return $this->toData('400', '缺少分页参数');
}
$list = TranslatorCustomerModel::where(['translator_id'=>$param['translator_id']])->order('id', 'desc')->paginate([
'list_rows' => $param['limit'],
'page' => $param['page'],
]);
return $this->toData('0', 'SUCCESS', [
'list' => $list->items(), // 当前页的数据
'page' => $list->currentPage(), // 当前页码
'total' => $list->total(), // 总记录数
'last_page' => $list->lastPage(), // 最后一页页码
]);
} catch (\Exception $exception) {
return $this->toData('500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
// 组长与用户添加chat好友
public function groupLeaderWithUser($param)
{
try {
if (empty($param['group_leader_id']) || empty($param['user_id'])) {
return $this->toData('400', '缺少参数');
}
$relation = GroupLeaderWithUserModel::where(['user_id'=>$param['user_id']])->find();
if (empty($relation)) {
$res = GroupLeaderWithUserModel::create([
'user_id' => $param['user_id'],
'group_leader_id' => $param['group_leader_id']
]);
if (empty($res->id)) {
return $this->toData('0', '操作失败');
}
}
$adminUserChat = UserChatLinkModel::where(['user_id'=>$param['group_leader_id'], 'user_type'=>UserChatLinkModel::USER_CHAT_LINK_USER_TYPE_ADMIN])->find();
if (empty($adminUserChat)) {
return $this->toData('400', '管理端账号缺少chat信息');
}
$frontUserChat = UserChatLinkModel::where(['user_id'=>$param['user_id'], 'user_type'=>UserChatLinkModel::USER_CHAT_LINK_USER_TYPE_PC])->find();
if (empty($frontUserChat)) {
return $this->toData('400', '用户账号缺少chat信息');
}
$chatFriendsData = [
'UserUuid' => $frontUserChat->chat_uuid,
'CustomerUuid' => $adminUserChat->chat_uuid,
];
$chatFriendsUrl = env('CHAT_SERVER.BASE_URL') . '/api/eachOtherFriends';
$chatFriendsRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatFriendsUrl, $chatFriendsData);
return $this->toData('0', 'ok', $chatFriendsRes);
} catch (\Exception $e) {
return $this->toData('500', '系统错误', [$e->getMessage(), $e->getTrace()]);
}
}
// 电销与用户添加chat好友
public function sellerWithUser($param)
{
try {
if (empty($param['seller_id']) || empty($param['user_id'])) {
return $this->toData('400', '缺少参数');
}
$relation = SellerWithUserModel::where(['user_id'=>$param['user_id']])->find();
if (empty($relation)) {
$res = SellerWithUserModel::create([
'user_id' => $param['user_id'],
'seller_id' => $param['seller_id']
]);
if (empty($res->id)) {
return $this->toData('0', '操作失败');
}
}
$adminUserChat = UserChatLinkModel::where(['user_id'=>$param['seller_id'], 'user_type'=>UserChatLinkModel::USER_CHAT_LINK_USER_TYPE_ADMIN])->find();
if (empty($adminUserChat)) {
return $this->toData('400', '管理端账号缺少chat信息');
}
$frontUserChat = UserChatLinkModel::where(['user_id'=>$param['user_id'], 'user_type'=>UserChatLinkModel::USER_CHAT_LINK_USER_TYPE_PC])->find();
if (empty($frontUserChat)) {
return $this->toData('400', '用户账号缺少chat信息');
}
$chatFriendsData = [
'UserUuid' => $frontUserChat->chat_uuid,
'CustomerUuid' => $adminUserChat->chat_uuid,
];
$chatFriendsUrl = env('CHAT_SERVER.BASE_URL') . '/api/eachOtherFriends';
$chatFriendsRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatFriendsUrl, $chatFriendsData);
return $this->toData('0', 'ok', $chatFriendsRes);
} catch (\Exception $e) {
return $this->toData('500', '系统错误', [$e->getMessage(), $e->getTrace()]);
}
}
// 用户访问页面的记录
public function getUserAccessLog($adminId, $param)
{
try {
if (empty($param['page']) || empty($param['limit'])) {
return $this->toData('400', '缺少分页参数');
}
// 获取账号信息
$account = AdminModel::where('id', $adminId)->find();
if (empty($account)) {
return $this->toData('400', '当前账号数据为空');
}
// 获取账号角色信息
$role = AuthRoleModel::where(['id'=>$account->role_id])->find();
if (empty($role)) {
return $this->toData('400', '当前账号分配的角色数据为空');
}
// 根据账号角色限制数据查看范围, 超级管理员可以查看所有用户数据,代理可以查看自己所属用户的数据,总监、组长以此类推
$whereUser = [];
switch ($role->name) {
case AuthRoleModel::NAME_ADMIN: // 超级管理员可以查看所有数据
if (!empty($param['user_id'])) {
$whereUser[] = ['user_id', '=', $param['user_id']];
}
break;
case AuthRoleModel::NAME_AGENT: // 代理 - 查看代理下可以查看的用户
$userIds = UserModel::where('agent_id', $adminId)->column('user_id');
if (!empty($param['user_id']) && in_array($param['user_id'], $userIds)) {
$whereUser[] = ['user_id', '=', $param['user_id']];
} else {
$whereUser[] = ['user_id', 'in', $userIds];
}
break;
case AuthRoleModel::NAME_DIRECTOR: // 总监 - 查询总监下可以查看的用户
$userIds = [];
$teamHeaders = AdminModel::where('parent_id', $adminId)->column('id'); // 组长账号
if (!empty($teamHeaders)) {
$customer = AdminModel::whereIn('parent_id', $teamHeaders)->column('id'); // 客服账号
if (!empty($customer)) {
$userIds = UserModel::whereIn('customer_id', $customer)->column('user_id');
}
}
if (!empty($param['user_id']) && in_array($param['user_id'], $userIds)) {
$whereUser[] = ['user_id', '=', $param['user_id']];
} else {
$whereUser[] = ['user_id', 'in', $userIds];
}
break;
case AuthRoleModel::NAME_TEAM_HEADER: // 组长 - 查看组长下可以查看的用户
$userIds = [];
$customer = AdminModel::where('parent_id', $adminId)->column('id');
if (!empty($customer)) {
$userIds = UserModel::whereIn('customer_id', $customer)->column('user_id');
}
if (!empty($param['user_id']) && in_array($param['user_id'], $userIds)) {
$whereUser[] = ['user_id', '=', $param['user_id']];
} else {
$whereUser[] = ['user_id', 'in', $userIds];
}
break;
case AuthRoleModel::NAME_CUSTOMER: // 客服 - 查看客服下的用户
$userIds = UserModel::where(['customer_id' => $adminId])->column('user_id');
if (!empty($param['user_id']) && in_array($param['user_id'], $userIds)) {
$whereUser[] = ['user_id', '=', $param['user_id']];
} else {
$whereUser[] = ['user_id', 'in', $userIds];
}
break;
default:
return $this->toData('500', '普通角色没有关联用户账号,不能查看用户数');
}
$where = [];
if (!empty($param['module'])) {
$where['module'] = $param['module'];
}
$list = UserAccessLogModel::where($where)->where($whereUser)->order('id', 'desc')->paginate([
'list_rows' => $param['limit'],
'page' => $param['page'],
]);
return $this->toData('0', 'SUCCESS', [
'list' => $list->items(),
'page' => $list->currentPage(),
'total' => $list->total(),
'last_page' => $list->lastPage(),
]);
} catch (\Exception $exception) {
return $this->toData('500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
public function getAdminOperationLog($adminId, $param)
{
try {
if (empty($param['page']) || empty($param['limit'])) {
return $this->toData('400', '缺少分页参数');
}
// 获取账号信息
$account = AdminModel::where('id', $adminId)->find();
if (empty($account)) {
return $this->toData('400', '当前账号数据为空');
}
// 获取账号角色信息
$role = AuthRoleModel::where(['id'=>$account->role_id])->find();
if (empty($role)) {
return $this->toData('400', '当前账号分配的角色数据为空');
}
// 根据账号角色限制数据查看范围
$where = [];
switch ($role->name) {
case AuthRoleModel::NAME_ADMIN: // 超级管理员可以查看所有数据
if (!empty($param['admin_id'])) {
$where[] = ['admin_id', '=', $param['admin_id']];
}
break;
case AuthRoleModel::NAME_AGENT: // 代理 - 查看自己以及下属账号的操作数据
$ids = [$adminId];
$directors = AdminModel::where('parent_id', $adminId)->column('id');
if (!empty($directors)){
$ids = array_merge($ids, $directors);
$teamHeader = AdminModel::where('parent_id', 'in', $directors)->column('id');
if (!empty($teamHeader)) {
$ids = array_merge($ids, $teamHeader);
$customer = AdminModel::where('parent_id','in', $teamHeader)->column('id');
if (!empty($customer)) {
$ids = array_merge($ids, $customer);
}
}
}
if (!empty($param['admin_id']) && in_array($param['admin_id'], $ids)) {
$where[] = ['admin_id', '=', $param['admin_id']];
} else {
$where[] = ['admin_id', 'in', $ids];
}
break;
case AuthRoleModel::NAME_DIRECTOR: // 总监 - 查看自己以及下属账号的操作数据
$ids = [$adminId];
$teamHeader = AdminModel::where('parent_id', $adminId)->column('id');
if (!empty($teamHeader)){
$ids = array_merge($ids, $teamHeader);
$customer = AdminModel::where('parent_id','in', $teamHeader)->column('id');
if (!empty($customer)) {
$ids = array_merge($ids, $customer);
}
}
if (!empty($param['admin_id']) && in_array($param['admin_id'], $ids)) {
$where[] = ['admin_id', '=',$param['admin_id']];
} else {
$where[] = ['admin_id', 'in', $ids];
}
break;
case AuthRoleModel::NAME_TEAM_HEADER: // 组长 - 查看自己以及下属账号的操作数据
$ids = [$adminId];
$customer = AdminModel::where('parent_id', $adminId)->column('id');
if (!empty($customer)) {
$ids = array_merge($ids, $customer);
}
if (!empty($param['admin_id']) && in_array($param['admin_id'], $ids)) {
$where[] = ['admin_id', '=', $param['admin_id']];
} else {
$where[] = ['admin_id', 'in', $ids];
}
break;
case AuthRoleModel::NAME_CUSTOMER: // 客服 - 查看自己操作数据
$where[] = ['admin_id', '=', $adminId];
break;
default:
$where[] = ['admin_id', '=', $adminId]; // 其它角色 - 查看自己的操作数
}
$list = AdminLogModel::where($where)->order('id', 'desc')->paginate([
'list_rows' => $param['limit'],
'page' => $param['page'],
]);
return $this->toData('0', 'SUCCESS', [
'list' => $list->items(),
'page' => $list->currentPage(),
'total' => $list->total(),
'last_page' => $list->lastPage(),
]);
} catch (\Exception $exception) {
return $this->toData('500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
}
}
// 赠送会员
public function giveVip($param)
{
try {
if (empty($param['user_id'])) {
return $this->toData('400', '请指定用户ID');
}
if (empty($param['days']) || $param['days'] <= 0 ) {
return $this->toData('400', '赠送时间错误');
}
$userId = $param['user_id'];
$giveDay = $param['days'];
$info = UserModel::getFieldsByUserId('trade_password,lever_status,gender,last_name,first_name,real_status,country_id,user_no,nick_name,email,phone_number,country_code,agent_id,is_real,head_img_id,invite_code,is_test_user', $param['user_id']);
if (empty($info)) {
return $this->toData('500', 'The user does not exist.');
}
// 记录赠送vip信息
Db::transaction(function () use ($userId, $giveDay) {
// 查询用户是否开通过vip,更新用户vip到期时间
$vipLog = PurchaseVipModel::where(['user_id'=>$userId])->find();
$expireTimestamp = strtotime("+$giveDay day");
$expireTime = date("Y-m-d H:i:s", $expireTimestamp);
if (!empty($vipLog)) {
if (empty($vipLog->expire)) {
return $this->toData('100400', ' The vip expire error ');
}
if ($vipLog->expire >= date("Y-m-d H:i:s")) {
$expireTimestamp = strtotime("+$giveDay day", strtotime($vipLog->expire));
$expireTime = date("Y-m-d H:i:s", $expireTimestamp);
}
$vipLog->expire = $expireTime;
$vipLog->save();
} else {
PurchaseVipModel::create([
'user_id' => $userId,
'expire' => $expireTime
]);
}
// 添加用户购买VIP的日志
PurchaseVipLogModel::create([
'user_id' => $userId,
'amount' => 0,
'stock_id' => "USD",
'expire' => $expireTime,
'day' => $giveDay,
]);
});
return $this->toData('0', 'successful');
} catch (\Exception $e) {
return $this->toData('500', 'The system is busy.', [$e->getMessage(), $e->getTrace()]);
}
}
// 单次发送邮件或短信
public function sendEmailOrSms($param)
{
try {
if (empty($param['user_id']) || empty($param['type']) || empty($param['content'])) {
return $this->toData('400', '参数错误');
}
if (!in_array($param['type'], [1,2])) {
return $this->toData('400', '参数错误');
}
$user = UserModel::where(['user_id'=>$param['user_id']])->find();
if (empty($user)) {
return $this->toData('500', '用户不存在');
}
// 发送邮件
if ($param['type'] == 1) {
if (empty($param['title'])) {
return $this->toData('400', '参数错误');
}
if (empty($user->email)) {
return $this->toData('500', '用户邮箱为空');
}
$emailTemplate['email'] = $user->email;
$title = trim($param['title']);
$content = trim($param['content']);
$phpEmail = new \app\utility\SendEmail();
$bool = $phpEmail->sendEmail($emailTemplate['email'], $title, $content);
if (!$bool) {
return $this->toData('500', '邮件发送失败');
}
}
// 发送短信
if ($param['type'] == 2) {
if (empty($user->phone_number)) {
return $this->toData('500', '用户手机号为空');
}
$accessKey = env('SMS.ACCESS_KEY_ID');
$secret = env('SMS.ACCESS_KEY_SECRET');
if (empty($accessKey) || empty($secret)) {
return $this->toData('500', '短信账号配置错误');
}
$to = $user->phone_number;
$content = trim($param['content']);
$from = 'Bourse';
$bool = (new \app\utility\SendSms())->sendMessageToGlobe($to, $content, $from, $accessKey, $secret);
if (!$bool) {
return $this->toData('500', '短信发送失败');
}
}
return $this->toData('0', 'success');
} catch (\Exception $e) {
return $this->toData('500', 'The system is busy.', [$e->getMessage(), $e->getTrace()]);
}
}
// 批量发送短信或邮件
public function batchSendEmailOrSms($param)
{
try {
// type: 1-短信,2-邮件
if (!in_array($param['type'], [1,2])) {
return $this->toData('400', '发送类型不在支持范围内');
}
// content: 发送的消息内容
if (empty($param['content'])) {
return $this->toData('400', '消息内容不能为空');
}
// user_ids: 要发送的用户ID, 数组格式
if (empty($param['user_ids']) || !is_array($param['user_ids'])) {
return $this->toData('400', '用户ID错误');
}
switch ($param['type']) {
case 1: // 发送短信
$userList = UserModel::where('user_id', 'in', $param['user_ids'])->column('phone_number,country_code', 'user_id');
if (empty($userList)) {
return $this->toData('500', '用户列表为空');
}
// 循环将每个用户发送短信任务加入到队列
foreach ($userList as $v) {
if (empty($v)) {
continue;
}
$jobName = 'app\admin\job\SendSmsFromBackend';
Queue::push($jobName, [
'mobile' => $v['country_code'].$v['phone_number'],
'message' => $param['content'],
], 'sendSmsFromBackend');
}
break;
case 2: // 发送邮件
if (empty($param['title'])) {
return $this->toData('400', '邮件标题不能为空');
}
$userList = UserModel::where('user_id', 'in', $param['user_ids'])->column('email');
if (empty($userList)) {
return $this->toData('500', '用户列表为空');
}
// 循环将每个用户发送邮件任务加入到队列
foreach ($userList as $email) {
if (empty($email)) {
continue;
}
$jobName = 'app\admin\job\SendEmailFromBackend';
Queue::push($jobName, [
'email' => $email,
'title' => $param['title'],
'content' => $param['content'],
], 'sendEmailFromBackend');
}
break;
default:
return $this->toData('500', '操作类型错误', []);
}
return $this->toData('0', 'ok');
} catch (\Exception $e) {
return $this->toData('500', 'The system is busy', [$e->getMessage(), $e->getTrace()]);
}
}
}