存客宝应用接口初始化

This commit is contained in:
Ghost
2026-01-05 10:25:32 +08:00
parent fa37227954
commit 02797ba50a
414 changed files with 85530 additions and 75 deletions

View File

@@ -0,0 +1,32 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Cookie设置
// +----------------------------------------------------------------------
return [
// cookie 名称前缀
'prefix' => '',
// cookie 保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/',
// cookie 有效域名
'domain' => '',
// cookie 启用安全传输
'secure' => false,
// httponly设置
'httponly' => '',
// 是否使用 setcookie
'setcookie' => true,
// 跨站需要
'SameSite' => 'None',
];

View File

@@ -0,0 +1,52 @@
<?php
use think\facade\Route;
// 超级管理员认证相关路由(不需要鉴权)
Route::post('auth/login', 'app\superadmin\controller\auth\AuthLoginController@index');
// 需要登录认证的路由组
Route::group('', function () {
// 仪表盘概述
Route::group('dashboard', function () {
Route::get('base', 'app\superadmin\controller\dashboard\GetBasestatisticsController@index');
});
// 菜单管理相关路由
Route::group('menu', function () {
Route::get('tree', 'app\superadmin\controller\Menu\GetMenuTreeController@index');
Route::get('toplevel', 'app\superadmin\controller\Menu\GetTopLevelForPermissionController@index');
});
// 管理员相关路由
Route::group('administrator', function () {
Route::get('list', 'app\superadmin\controller\administrator\GetAdministratorListController@index');
Route::get('detail/:id', 'app\superadmin\controller\administrator\GetAdministratorDetailController@index');
Route::post('update', 'app\superadmin\controller\administrator\UpdateAdministratorController@index');
Route::post('add', 'app\superadmin\controller\administrator\AddAdministratorController@index');
Route::post('delete', 'app\superadmin\controller\administrator\DeleteAdministratorController@index');
});
// 客户池管理路由
Route::group('trafficPool', function () {
Route::get('list', 'app\superadmin\controller\traffic\GetPoolListController@index');
Route::get('detail', 'app\superadmin\controller\traffic\GetPoolDetailController@index');
});
// 设备管理吗
Route::group('devices', function () {
Route::get('add-results', 'app\superadmin\controller\devices\GetAddResultedDevicesController@index');
});
// 公司路由
Route::group('company', function () {
Route::post('add', 'app\superadmin\controller\company\CreateCompanyController@index');
Route::post('update', 'app\superadmin\controller\company\UpdateCompanyController@index');
Route::post('delete', 'app\superadmin\controller\company\DeleteCompanyController@index');
Route::get('list', 'app\superadmin\controller\company\GetCompanyListController@index');
Route::get('detail/:id', 'app\superadmin\controller\company\GetCompanyDetailForUpdateController@index');
Route::get('profile/:id', 'app\superadmin\controller\company\GetCompanyDetailForProfileController@index');
Route::get('devices', 'app\superadmin\controller\company\GetCompanyDevicesForProfileController@index');
Route::get('subusers', 'app\superadmin\controller\company\GetCompanySubusersForProfileController@index');
});
})->middleware(['app\superadmin\middleware\AdminAuth']);

View File

@@ -0,0 +1,46 @@
<?php
namespace app\superadmin\controller;
use think\Controller;
/**
* 设备管理控制器
*/
class BaseController extends Controller
{
/**
* 管理员信息
*
* @var object
*/
protected $admin;
/**
* 初始化
*/
protected function initialize()
{
parent::initialize();
date_default_timezone_set('Asia/Shanghai');
}
/**
* 获取管理员信息
*
* @param string $column
* @return mixed
* @throws \Exception
*/
protected function getAdminInfo(string $column = '')
{
$admin = $this->request->adminInfo;
if (!$admin) {
throw new \Exception('未授权访问,缺少有效的身份凭证', 401);
}
return $column ? $admin[$column] : $admin;
}
}

View File

@@ -0,0 +1,179 @@
<?php
namespace app\superadmin\controller\Menu;
use app\common\model\Administrator as AdministratorModel;
use app\common\model\Menu as MenuModel;
use app\common\model\AdministratorPermissions as AdministratorPermissionsModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
use think\facade\Cache;
/**
* 菜单控制器
*/
class GetMenuTreeController extends BaseController
{
/**
* 组织成树状结构
*
* @param array $menus
* @param int $parentId
* @return array
*/
private function buildMenuTree(array $menus, int $parentId = 0): array
{
$tree = [];
foreach ($menus as $menu) {
if ($menu['parentId'] == $parentId) {
$children = $this->buildMenuTree($menus, $menu['id']);
if (!empty($children)) {
$menu['children'] = $children;
}
$tree[] = $menu;
}
}
return $tree;
}
/**
* 获取管理员权限
*
* @return array
*/
protected function getPermissions(): array
{
$record = AdministratorPermissionsModel::where('adminId', $this->getAdminInfo('id'))->find();
if (!$record || empty($record->permissions)) {
return [];
}
$permissions = $record->permissions ? json_decode($record->permissions, true) : [];
if (isset($permissions['ids']) && !empty($permissions['ids'])) {
return is_string($permissions['ids']) ? explode(',', $permissions['ids']) : $permissions['ids'];
}
return [];
}
/**
* 获取所有菜单,并组织成树状结构
*
* @return array
*/
protected function getMenuTree(): array
{
// 获取所有菜单
$allMenus = MenuModel::where('status', MenuModel::STATUS_ACTIVE)->order('sort', 'asc')->select()->toArray();
// 组织成树状结构
return $allMenus ? $this->buildMenuTree($allMenus) : [];
}
/**
* 获取所有一级菜单(用户拥有权限的)
*
* @param array $permissionIds
* @return array
*/
protected function getTopMenusInPermissionIds(array $permissionIds): array
{
$where = [
'parentId' => MenuModel::TOP_LEVEL,
'status' => MenuModel::STATUS_ACTIVE,
];
return MenuModel::where($where)->whereIn('id', $permissionIds)->order('sort', 'asc')->select()->toArray();
}
/**
* 获取所有子菜单.
*
* @param array $topMenuIds
* @return array
*/
protected function getAllChildrenInPermissionIds(array $topMenuIds): array
{
return MenuModel::where('status', MenuModel::STATUS_ACTIVE)->whereIn('parentId', $topMenuIds)->order('sort', 'asc')->select()->toArray();
}
/**
* 获取用户菜单
*
* @param array $permissionIds
* @return array
*/
protected function getUserMenus(array $permissionIds): array
{
$topMenus = $this->getTopMenusInPermissionIds($permissionIds);
// 菜单ID集合用于获取子菜单
$childMenus = $this->getAllChildrenInPermissionIds(
array_column($topMenus, 'id')
);
return $this->_makeMenuTree($topMenus, $childMenus);
}
/**
* 构建菜单树.
*
* @param array $topMenus
* @param array $childMenus
* @return array
*/
protected function _makeMenuTree(array $topMenus, array $childMenus): array
{
// 将子菜单按照父ID进行分组
$childMenusGroup = [];
foreach ($childMenus as $menu) {
$childMenusGroup[$menu['parentId']][] = $menu;
}
foreach ($topMenus as $topMenu) {
if (isset($childMenusGroup[$topMenu['id']])) {
$topMenu['children'] = $childMenusGroup[$topMenu['id']];
}
$menuTree[] = $topMenu;
}
return $menuTree ?? [];
}
/**
* 根据权限ID获取相应的菜单树
*
* @param array $permissionIds 权限ID数组
* @return array
*/
protected function getMenuTreeByPermissions(array $permissionIds): array
{
// 如果没有权限,返回空数组
return $permissionIds ? $this->getUserMenus($permissionIds) : [];
}
/**
* 获取菜单列表(树状结构)
* @return \think\response\Json
*/
public function index()
{
if ($this->getAdminInfo('id') == AdministratorModel::MASTER_ID) {
$menuTree = $this->getMenuTree();
} else {
$menuTree = $this->getMenuTreeByPermissions(
$this->getPermissions()
);
}
return ResponseHelper::success($menuTree);
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace app\superadmin\controller\Menu;
use app\common\model\Menu as MenuModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
/**
* 菜单控制器
*/
class GetTopLevelForPermissionController extends BaseController
{
/**
* 获取所有启用的一级菜单
*
* @return \think\response\Json
*/
protected function getTopLevelMenus(): array
{
$where = [
'parentId' => MenuModel::TOP_LEVEL,
'status' => MenuModel::STATUS_NORMAL
];
return MenuModel::where($where)->field('id, title')->order('sort', 'asc')->select()->toArray();
}
/**
* 获取一级菜单(供权限设置使用)
*
* @return \think\response\Json
*/
public function index()
{
$menus = $this->getTopLevelMenus();
return ResponseHelper::success($menus);
}
}

View File

@@ -0,0 +1,150 @@
<?php
namespace app\superadmin\controller\administrator;
use app\common\model\Administrator as AdministratorModel;
use app\common\model\AdministratorPermissions as AdministratorPermissionsModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
use think\Controller;
use think\Db;
use think\Validate;
/**
* 管理员控制器
*/
class AddAdministratorController extends BaseController
{
/**
* 检查账号是否已存在
*
* @param string $account
* @return void
* @throws \Exception
*/
protected function chekAdminIsExist(string $account)
{
$exists = AdministratorModel::where('account', $account)->count() > 0;
if ($exists) {
throw new \Exception('账号已存在', 400);
}
}
/**
* 数据验证
*
* @param array $params
* @return $this
* @throws \Exception
*/
protected function dataValidate(array $params): self
{
$validate = Validate::make([
'account' => 'require|regex:^[a-zA-Z0-9]+$|/\S+/',
'username' => 'require|/\S+/',
'password' => 'require|/\S+/',
'permissionIds' => 'require|array',
], [
'account.require' => '账号不能为空',
'account.regex' => '账号只能用数字或者字母或者数字字母组合',
'username.require' => '用户名不能为空',
'password.require' => '密码不能为空',
'permissionIds.require' => '请至少分配一种权限',
]);
if (!$validate->check($params)) {
throw new \Exception($validate->getError(), 400);
}
return $this;
}
/**
* 判断是否有权限修改
*
* @return $this
*/
protected function checkPermission(): self
{
if ($this->getAdminInfo('id') != AdministratorModel::MASTER_ID) {
throw new \Exception('您没有权限添加管理员', 403);
}
return $this;
}
/**
* 保存管理员权限
*
* @param int $adminId 管理员ID
* @param array $permissionIds 权限ID数组
* @return bool
*/
protected function savePermissions(int $adminId, array $permissionIds)
{
$record = AdministratorPermissionsModel::where('adminId', $adminId)->find();
$permissionData = [
'ids' => is_array($permissionIds) ? implode(',', $permissionIds) : $permissionIds
];
if ($record) {
return $record->save([
'permissions' => json_encode($permissionData),
]);
} else {
return AdministratorPermissionsModel::create([
'adminId' => $adminId,
'permissions' => json_encode($permissionData),
]);
}
}
/**
* 添加管理员信息
*
* @param array $params
* @return AdministratorModel
* @throws \Exception
*/
protected function addAdministrator(array $params): AdministratorModel
{
$result = AdministratorModel::create(array_merge($params, ['password' => md5($params['password'])]));
if (!$result) {
throw new \Exception('添加管理员失败', 401);
}
return $result;
}
/**
* 添加管理员
*
* @return \think\response\Json
*/
public function index()
{
try {
$params = $this->request->only(['account', 'username', 'password', 'permissionIds']);
$this->dataValidate($params);
$this->checkPermission()->chekAdminIsExist($params['account']);
Db::startTrans();
$admin = $this->addAdministrator($params);
// 保存权限
if (!empty($params['permissionIds'])) {
$this->savePermissions($admin->id, $params['permissionIds']);
}
Db::commit();
return ResponseHelper::success();
} catch (\Exception $e) {
Db::rollback();
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace app\superadmin\controller\administrator;
use app\superadmin\controller\BaseController;
use app\common\model\Administrator as AdministratorModel;
use app\common\model\AdministratorPermissions as AdministratorPermissionsModel;
use library\ResponseHelper;
use think\Controller;
use think\Db;
use think\Validate;
/**
* 管理员控制器
*/
class DeleteAdministratorController extends BaseController
{
/**
* 删除管理员
*
* @param int $adminId
* @return void
* @throws \Exception
*/
protected function deleteAdmin(int $adminId): void
{
$admin = AdministratorModel::where('id', $adminId)->find();
if (!$admin) {
throw new \Exception('管理员不存在', 404);
}
if (!$admin->delete()) {
throw new \Exception('管理员删除失败', 400);
}
}
/**
* 删除管理员权限
*
* @param int $adminId
* @return void
* @throws \Exception
*/
protected function deletePermission(int $adminId): void
{
$permission = AdministratorPermissionsModel::where('adminId', $adminId)->find();
if (!$permission->delete()) {
throw new \Exception('管理员权限移除失败', 400);
}
}
/**
* 删除账号的限制条件
*
* @param int $adminId
* @return void
* @throws \Exception
*/
protected function canNotDeleteSelf(int $adminId)
{
// 不能删除自己的账号
if ($this->getAdminInfo('id') == $adminId) {
throw new \Exception('不能删除自己的账号', 403);
}
// 只有超级管理员(ID为1)可以删除管理员
if ($this->getAdminInfo('id') != AdministratorModel::MASTER_ID) {
throw new \Exception('您没有权限删除管理员', 403);
}
// 不能删除超级管理员账号
if ($adminId == AdministratorModel::MASTER_ID) {
throw new \Exception('不能删除超级管理员账号', 403);
}
}
/**
* 数据验证
*
* @param array $params
* @return $this
* @throws \Exception
*/
protected function dataValidate(array $params): self
{
$validate = Validate::make([
'id' => 'require|regex:/^[1-9]\d*$/',
], [
'id.regex' => '非法请求',
'id.require' => '非法请求',
]);
if (!$validate->check($params)) {
throw new \Exception($validate->getError(), 400);
}
return $this;
}
/**
* 删除管理员
*
* @return \think\response\Json
*/
public function index()
{
try {
$params = $this->request->only('id');
$adminId = $params['id'];
$this->dataValidate($params)->canNotDeleteSelf($adminId);
Db::startTrans();
$this->deleteAdmin($adminId);
$this->deletePermission($adminId);
Db::commit();
return ResponseHelper::success();
} catch (\Exception $e) {
Db::rollback();
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,108 @@
<?php
namespace app\superadmin\controller\administrator;
use app\common\model\Administrator as AdministratorModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
use think\Db;
/**
* 管理员控制器
*/
class GetAdministratorDetailController extends BaseController
{
/**
* 查询管理员信息,关联权限表
*
* @param int $adminId
* @return AdministratorModel
* @throws \Exception
*/
protected function getAdministrator(int $adminId): AdministratorModel
{
$admin = AdministratorModel::alias('a')
->field([
'a.id', 'a.account', 'a.username', 'a.status', 'a.authId', 'a.createTime createdAt', 'a.lastLoginTime lastLogin',
'p.permissions'
])
->leftJoin('administrator_permissions p', 'a.id = p.adminId')
->where('a.id', $adminId)
->find();
if (!$admin) {
throw new \Exception('管理员不存在', 404);
}
return $admin;
}
/**
* 解析权限数据
*
* @param string|null $permission
* @return array
*/
protected function parsePermissions(?string $permission): array
{
$permissionIds = [];
if (!empty($permission)) {
$permissions = json_decode($permission, true);
$permissions = is_array($permissions) ? $permissions : json_decode($permissions, true);
if (isset($permissions['ids'])) {
$permissionIds = is_string($permissions['ids']) ? explode(',', $permissions['ids']) : $permissions['ids'];
$permissionIds = array_map('intval', $permissionIds);
}
}
return $permissionIds;
}
/**
* 根据权限ID获取角色名称
*
* @param int $authId
* @return string
*/
protected function getRoleName($authId): string
{
switch ($authId) {
case 1:
return '超级管理员';
case 2:
return '项目管理员';
case 3:
return '客户管理员';
default:
return '普通管理员';
}
}
/**
* 获取详细信息
*
* @param int $id 管理员ID
* @return \think\response\Json
*/
public function index($id)
{
try {
$admin = $this->getAdministrator($id);
$roleName = $this->getRoleName($admin->authId);
$permissionIds = $this->parsePermissions($admin->permissions);
return ResponseHelper::success(
array_merge($admin->toArray(), [
'roleName' => $roleName,
'permissions' => $permissionIds,
'lastLogin' => $admin->lastLogin ? date('Y-m-d H:i', $admin->lastLogin) : '从未登录',
'createdAt' => date('Y-m-d H:i', $admin->createdAt),
])
);
} catch (\Exception $e) {
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,175 @@
<?php
namespace app\superadmin\controller\administrator;
use app\common\model\Administrator as AdministratorModel;
use app\common\model\AdministratorPermissions as AdministratorPermissionsModel;
use app\common\model\Menu as MenuModel;
use library\ResponseHelper;
use think\Controller;
/**
* 管理员控制器
*/
class GetAdministratorListController extends Controller
{
/**
* 构建查询条件
*
* @param array $params
* @return array
*/
protected function makeWhere(array $params = []): array
{
$where = [];
// 如果有搜索关键词
if (!empty($keyword = $this->request->param('keyword/s', ''))) {
$where[] = ['account|username', 'like', "%{$keyword}%"];
}
return array_merge($params, $where);
}
/**
* 获取管理员列表
*
* @param array $where 查询条件
* @return \think\Paginator 分页对象
*/
protected function getAdministratorList(array $where): \think\Paginator
{
$query = AdministratorModel::alias('a')
->field([
'a.id', 'a.account', 'a.username', 'a.status', 'a.authId', 'a.createTime createdAt', 'a.lastLoginTime', 'a.lastLoginIp'
]);
foreach ($where as $key => $value) {
if (is_numeric($key) && is_array($value) && isset($value[0]) && $value[0] === 'exp') {
$query->whereExp('', $value[1]);
continue;
}
$query->where($key, $value);
}
return $query->paginate($this->request->param('limit/d', 10), false, ['page' => $this->request->param('page/d', 1)]);
}
/**
* 根据权限ID获取角色名称
*
* @param int $authId 权限ID
* @return string
*/
protected function getRoleName($authId): string
{
switch ($authId) {
case 1:
return '超级管理员';
case 2:
return '项目管理员';
case 3:
return '客户管理员';
default:
return '普通管理员';
}
}
/**
* 获取管理员权限
*
* @param int $adminId
* @return array
*/
protected function _getPermissions(int $adminId): array
{
$record = AdministratorPermissionsModel::where('adminId', $adminId)->find();
if (!$record || empty($record->permissions)) {
return [];
}
$permissions = $record->permissions ? json_decode($record->permissions, true) : [];
if (isset($permissions['ids']) && !empty($permissions['ids'])) {
return is_string($permissions['ids']) ? explode(',', $permissions['ids']) : $permissions['ids'];
}
return [];
}
/**
* 通过菜单的id获取菜单的名字
*
* @param array $ids
* @return array
*/
protected function getMenusNameByIds(array $ids): array
{
return MenuModel::whereIn('id', $ids)->column('title');
}
/**
* 根据权限ID获取权限列表
*
* @param int $authId 权限ID
* @return array
*/
protected function getPermissions(int $authId): array
{
$ids = $this->_getPermissions($authId);
if ($ids) {
return $this->getMenusNameByIds($ids);
}
return [];
}
/**
* 构建返回数据
*
* @param \think\Paginator $list
* @return array
*/
protected function makeReturnedResult(\think\Paginator $list): array
{
$result = [];
foreach ($list->items() as $item) {
$section = [
'id' => $item->id,
'account' => $item->account,
'username' => $item->username,
'status' => $item->status,
'createdAt' => date('Y-m-d H:i:s', $item->createdAt),
'lastLogin' => !empty($item->lastLoginTime) ? date('Y-m-d H:i:s', $item->lastLoginTime) : '从未登录',
'role' => $this->getRoleName($item->authId),
'permissions' => $this->getPermissions($item->id),
];
array_push($result, $section);
}
return $result;
}
/**
* 获取管理员列表
*
* @return \think\response\Json
*/
public function index()
{
$where = $this->makeWhere();
$result = $this->getAdministratorList($where);
return ResponseHelper::success(
[
'list' => $this->makeReturnedResult($result),
'total' => $result->total(),
]
);
}
}

View File

@@ -0,0 +1,154 @@
<?php
namespace app\superadmin\controller\administrator;
use app\common\model\Administrator as AdministratorModel;
use app\common\model\AdministratorPermissions as AdministratorPermissionsModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
use think\Db;
use think\Validate;
/**
* 管理员控制器
*/
class UpdateAdministratorController extends BaseController
{
/**
* 更新管理员信息
*
* @param array $params
* @return void
* @throws \Exception
*/
protected function udpateAdministrator(array $params): void
{
$admin = AdministratorModel::find($params['id']);
if (!$admin) {
throw new \Exception('管理员不存在', 404);
}
if (!empty($params['password'])) {
$params['password'] = md5($params['password']);
}
if (!$admin->save($params)) {
throw new \Exception('记录更新失败', 402);
}
}
/**
* 数据验证
*
* @param array $params
* @return $this
* @throws \Exception
*/
protected function dataValidate(array $params): self
{
$validate = Validate::make([
'id' => 'require|regex:/^[1-9]\d*$/',
'account' => 'require|regex:^[a-zA-Z0-9]+$|/\S+/',
'username' => 'require|/\S+/',
'password' => '/\S+/',
'permissionIds' => 'array',
], [
'id.require' => '缺少必要参数',
'account.require' => '账号不能为空',
'account.regex' => '账号只能用数字或者字母或者数字字母组合',
'username.require' => '用户名不能为空',
'permissionIds.array' => '请至少分配一种权限',
]);
if (!$validate->check($params)) {
throw new \Exception($validate->getError(), 400);
}
return $this;
}
/**
* 判断是否有权限修改
*
* @param int $adminId
* @param array $params
* @return $this
*/
protected function checkPermission(int $adminId, array $params): self
{
$currentAdminId = $this->getAdminInfo('id');
if ($currentAdminId != AdministratorModel::MASTER_ID && $currentAdminId != $adminId) {
throw new \Exception('您没有权限修改其他管理员', 403);
}
if ($params['id'] != AdministratorModel::MASTER_ID && empty($params['permissionIds'])) {
throw new \Exception('请至少分配一种权限', 403);
}
return $this;
}
/**
* 保存管理员权限
*
* @param int $adminId
* @param array $permissionIds
* @return bool
*/
protected function savePermissions(int $adminId, array $permissionIds)
{
$record = AdministratorPermissionsModel::where('adminId', $adminId)->find();
$permissionData = [
'ids' => is_array($permissionIds) ? implode(',', $permissionIds) : $permissionIds
];
if ($record) {
return $record->save([
'permissions' => json_encode($permissionData),
]);
} else {
return AdministratorPermissionsModel::create([
'adminId' => $adminId,
'permissions' => json_encode($permissionData),
]);
}
}
/**
* 更新管理员信息
*
* @return \think\response\Json
*/
public function index()
{
try {
$params = $this->request->only(['id', 'account', 'username', 'password', 'permissionIds']);
// 被修改的管理员id
$adminId = $params['id'] ?? 0;
$this->dataValidate($params)->checkPermission($adminId, $params);
Db::startTrans();
$this->udpateAdministrator($params);
// 如果当前是超级管理员(ID为1),并且修改的不是自己,则更新权限
if ($this->getAdminInfo('id') == AdministratorModel::MASTER_ID
&& $this->getAdminInfo('id') != $adminId
&& !empty($params['permissionIds'])
) {
$this->savePermissions($adminId, $params['permissionIds']);
}
Db::commit();
return ResponseHelper::success();
} catch (\Exception $e) {
Db::rollback();
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,166 @@
<?php
namespace app\superadmin\controller\auth;
use app\common\model\Administrator as AdministratorModel;
use app\superadmin\controller\administrator\DeleteAdministratorController;
use library\ResponseHelper;
use think\Controller;
use think\Validate;
use think\facade\Cookie;
class AuthLoginController extends Controller
{
/**
* 创建登录令牌
* @param DeleteAdministratorController $admin
* @return string
*/
protected function createToken(AdministratorModel $admin): string
{
return md5($admin->id . '|' . $admin->account . 'cunkebao_admin_secret');
}
/**
* 数据验证
*
* @param array $params
* @return $this
* @throws \Exception
*/
protected function dataValidate(array $params): self
{
$validate = Validate::make([
'account' => 'require|/\S+/',
'password' => 'require|/\S+/',
]);
if (!$validate->check($params)) {
throw new \Exception($validate->getError(), 400);
}
return $this;
}
/**
* 获取管理员信息
*
* @param array $params
* @return object|AdministratorModel
* @throws \Exception
*/
protected function getAdministrator(array $params): AdministratorModel
{
extract($params);
$admin = AdministratorModel::where(['account' => $account])->find();
if (!$admin ||
$admin->password !== $password ||
$admin->deleteTime
) {
throw new \Exception('账号不存在或密码错误', 404);
}
if (!$admin->status) {
throw new \Exception('账号已禁用', 404);
}
return $admin;
}
/**
* 更新登录信息
*
* @param AdministratorModel $admin
* @return $this
*/
protected function saveLoginInfo(AdministratorModel $admin): self
{
$admin->lastLoginTime = time();
$admin->lastLoginIp = $this->request->ip();
if (!$admin->save()) {
throw new \Exception('拒绝登录', 403);
}
return $this;
}
/**
* 设置登录Cookie有效期24小时
*
* @param AdministratorModel $admin
* @return void
*/
protected function setCookie(AdministratorModel $admin): void
{
// 获取当前环境
$env = app()->env->get('APP_ENV', 'production');
// 获取请求的域名
$origin = $this->request->header('origin');
$domain = '';
if ($origin) {
// 解析域名
$parsedUrl = parse_url($origin);
if (isset($parsedUrl['host'])) {
// 如果是测试环境,使用完整的域名
if ($env === 'testing') {
$domain = $parsedUrl['host'];
} else {
// 生产环境使用顶级域名
$parts = explode('.', $parsedUrl['host']);
if (count($parts) > 1) {
$domain = '.' . $parts[count($parts) - 2] . '.' . $parts[count($parts) - 1];
}
}
}
}
// 设置cookie选项
$options = [
'expire' => 86400,
'path' => '/',
'httponly' => true,
'samesite' => 'None', // 允许跨域
'secure' => true // 仅 HTTPS 下有效
];
// 如果有域名,添加到选项
if ($domain) {
$options['domain'] = $domain;
}
// 设置cookies
Cookie::set('admin_id', $admin->id, $options);
Cookie::set('admin_token', $this->createToken($admin), $options);
}
/**
* 管理员登录
*
* @return \think\response\Json
*/
public function index()
{
try {
$params = $this->request->only(['account', 'password']);
$admin = $this->dataValidate($params)->getAdministrator($params);
$this->saveLoginInfo($admin)->setCookie($admin);
return ResponseHelper::success(
[
'id' => $admin->id,
'name' => $admin->username,
'account' => $admin->account,
'token' => Cookie::get('admin_token')
]
);
} catch (\Exception $e) {
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,288 @@
<?php
namespace app\superadmin\controller\company;
use app\api\controller\DeviceController;
use app\common\model\Company as CompanyModel;
use app\common\model\User as UsersModel;
use app\superadmin\controller\BaseController;
use Eison\Utils\Helper\ArrHelper;
use Exception;
use library\ResponseHelper;
use library\s2\CurlHandle;
use think\Db;
use think\facade\Env;
use think\response\Json;
use think\Validate;
/**
* 公司控制器
*/
class CreateCompanyController extends BaseController
{
/**
* S2 创建用户。
*
* @param array $params
* @return mixed|null
* @throws Exception
*/
protected function s2CreateUser(array $params): ?array
{
$params = ArrHelper::getValue('account=userName,password,username=realName,username=nickname,companyId=departmentId', $params);
// 创建账号
$response = CurlHandle::getInstant()
->setBaseUrl(Env::get('rpc.API_BASE_URL'))
->setMethod('post')
->send('/v1/api/account/create', $params);
$result = json_decode($response, true);
if ($result['code'] != 200) {
throw new Exception($result['msg'], 210 . $result['code']);
}
return $result['data'] ?: null;
}
/**
* S2 创建部门并返回id
*
* @param array $params
* @return array
*/
protected function s2CreateDepartmentAndUser(array $params): ?array
{
$params = ArrHelper::getValue('name=departmentName,memo=departmentMemo,account=accountName,password=accountPassword,username=accountRealName,username=accountNickname,accountMemo', $params);
// 创建公司部门
$response = CurlHandle::getInstant()
->setBaseUrl(Env::get('rpc.API_BASE_URL'))
->setMethod('post')
->send('/v1/api/account/createNewAccount', $params);
$result = json_decode($response, true);
if ($result['code'] != 200) {
throw new Exception($result['msg'], 210 . $result['code']);
}
return $result['data'] ?: null;
}
/**
* 数据验证
*
* @param array $params
* @return $this
* @throws Exception
*/
protected function dataValidate(array $params): self
{
$validate = Validate::make([
'name' => 'require|max:50|/\S+/',
'account' => 'require|regex:^[a-zA-Z0-9]+$|max:20|/\S+/',
'username' => 'require|max:20|/\S+/',
'phone' => 'require|regex:/^1[3-9]\d{9}$/',
'status' => 'require|in:0,1',
'password' => 'require|/\S+/',
'memo' => '/\S+/',
], [
'name.require' => '请输入项目名称',
'account.require' => '请输入账号',
'account.max' => '账号长度受限',
'account.regex' => '账号只能用数字或者字母或者数字字母组合',
'username.require' => '请输入用户昵称',
'phone.require' => '请输入手机号',
'phone.regex' => '手机号格式错误',
'status.require' => '缺少重要参数',
'status.in' => '非法参数',
'password.require' => '请输入密码',
]);
if (!$validate->check($params)) {
throw new Exception($validate->getError(), 400);
}
return $this;
}
/**
* 设备创建分组
*
* @param array $params
* @return void
* @throws Exception
*/
protected function s2CreateDeviceGroup(array $params): void
{
$respon = (new DeviceController())->createGroup($params, true);
$respon = json_decode($respon, true);
if ($respon['code'] != 200) {
throw new Exception('设备分组添加错误', 210 . $respon['code']);
}
}
/**
* S2 部分
*
* @param array $params
* @return array
* @throws Exception
*/
protected function creatS2About(array $params): array
{
$department = $this->s2CreateDepartmentAndUser($params);
if (!$department || !isset($department['id']) || !isset($department['departmentId'])) {
throw new Exception('S2返参异常', 210402);
}
// 设备创建分组
$this->s2CreateDeviceGroup(['groupName' => $params['name']]);
return array_merge($params, [
'companyId' => $department['departmentId'],
's2_accountId' => $department['id'],
]);
}
/**
* 存客宝创建项目
*
* @param array $params
* @return void
* @throws Exception
*/
protected function ckbCreateCompany(array $params): void
{
$params = ArrHelper::getValue('companyId=id,companyId,name,memo,status', $params);
$result = CompanyModel::create($params);
if (!$result) {
throw new Exception('创建公司记录失败', 402);
}
}
/**
* 创建功能账号,不可登录,也非管理员,用户也不可见.
*
* @param array $params
* @return void
* @throws Exception
*/
protected function createFuncUsers(array $params): void
{
$seedCols = [
['account' => $params['account'] . '_01', 'username' => $params['username'] . '_子账号01', 'status' => UsersModel::ADMIN_STP, 'isAdmin' => UsersModel::ADMIN_OTP, 'typeId' => UsersModel::MASTER_USER],
['account' => $params['account'] . '_02', 'username' => $params['username'] . '_子账号02', 'status' => UsersModel::ADMIN_STP, 'isAdmin' => UsersModel::ADMIN_OTP, 'typeId' => UsersModel::MASTER_USER],
['account' => $params['account'] . '_03', 'username' => $params['username'] . '_子账号03', 'status' => UsersModel::ADMIN_STP, 'isAdmin' => UsersModel::ADMIN_OTP, 'typeId' => UsersModel::MASTER_USER],
['account' => $params['account'] . '_offline', 'username' => $params['username'] . '_处理离线专用', 'status' => UsersModel::STATUS_STOP, 'isAdmin' => UsersModel::ADMIN_OTP, 'typeId' => UsersModel::NOT_USER],
['account' => $params['account'] . '_delete', 'username' => $params['username'] . '_处理删除专用', 'status' => UsersModel::STATUS_STOP, 'isAdmin' => UsersModel::ADMIN_OTP, 'typeId' => UsersModel::NOT_USER],
];
foreach ($seedCols as $seeds) {
$this->s2CreateUser(array_merge($params, ArrHelper::getValue('account,username', $seeds)));
$this->ckbCreateUser(array_merge($params, $seeds));
}
}
/**
* 存客宝创建账号
*
* @param array $params
* @return void
* @throws Exception
*/
protected function ckbCreateUser(array $params): void
{
$params = ArrHelper::getValue('username,account,password,companyId,s2_accountId,status,phone,isAdmin,typeId', $params);
$params = array_merge($params, [
'passwordLocal' => localEncrypt($params['password']),
'passwordMd5' => md5($params['password']),
]);
if (!UsersModel::create($params)) {
throw new Exception('创建用户记录失败', 402);
}
}
/**
* @param array $params
* @return void
* @throws Exception
*/
protected function createCkbAbout(array $params)
{
// 1. 存客宝创建项目
$this->ckbCreateCompany($params);
// 2. 存客宝创建操盘手总账号
$this->ckbCreateUser(array_merge($params, [
'isAdmin' => UsersModel::ADMIN_STP, // 主要账号默认1
'typeId' => UsersModel::MASTER_USER, // 类型:运营后台/操盘手传1、 门店传2
]));
}
/**
* 检查项目名称是否已存在
*
* @param array $where
* @return void
* @throws Exception
*/
protected function checkCompanyNameOrAccountOrPhoneExists(array $where): void
{
extract($where);
// 项目名称尽量不重名
$exists = CompanyModel::where(compact('name'))->count() > 0;
if ($exists) {
throw new Exception('项目名称已存在', 403);
}
// 账号不重名
$exists = UsersModel::where(compact('account'))->count() > 0;
if ($exists) {
throw new Exception('用户账号已存在', 403);
}
// 手机号不重名
$exists = UsersModel::where(compact('phone'))->count() > 0;
if ($exists) {
throw new Exception('手机号已存在', 403);
}
}
/**
* 创建新项目
*
* @return Json
*/
public function index()
{
try {
$params = $this->request->only(['name', 'status', 'username', 'account', 'password', 'phone', 'memo']);
$params = $this->dataValidate($params)->creatS2About($params);
Db::startTrans();
$this->checkCompanyNameOrAccountOrPhoneExists(ArrHelper::getValue('name,account,phone', $params));
$this->createCkbAbout($params);
// 创建功能账号,不可登录,也非管理员,用户也不可见
$this->createFuncUsers($params);
Db::commit();
return ResponseHelper::success();
} catch (Exception $e) {
Db::rollback();
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace app\superadmin\controller\company;
use app\common\model\Company as CompanyModel;
use app\common\model\User as UserModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
use think\Db;
use think\Validate;
/**
* 公司控制器
*/
class DeleteCompanyController extends BaseController
{
/**
* 数据验证
*
* @param array $params
* @return $this
* @throws \Exception
*/
protected function dataValidate(array $params): self
{
$validate = Validate::make([
'id' => 'require|regex:/^[1-9]\d*$/',
], [
'id.regex' => '非法请求',
'id.require' => '非法请求',
]);
if (!$validate->check($params)) {
throw new \Exception($validate->getError(), 400);
}
return $this;
}
/**
* 删除项目
*
* @param int $id
* @throws \Exception
*/
protected function deleteCompany(int $id): void
{
$company = CompanyModel::where('id', $id)->find();
if (!$company) {
throw new \Exception('项目不存在', 404);
}
if (!$company->delete()) {
throw new \Exception('项目删除失败', 400);
}
}
/**
* 删除用户
*
* @param int $companId
* @throws \Exception
*/
protected function deleteUsers(int $companId): void
{
$users = UserModel::where('companyId', $companId)->select();
foreach ($users as $user) {
if (!$user->delete()) {
throw new \Exception($user->username . ' 用户删除失败', 400);
}
}
}
/**
* 删除存客宝数据
*
* @param int $companId
* @return self
* @throws \Exception
*/
protected function delteCkbAbout(int $companId): self
{
// 1. 删除项目
$this->deleteCompany($companId);
// 2. 删除用户
$this->deleteUsers($companId);
return $this;
}
/**
* 删除 s2 数据
*
* @return void
*/
protected function deleteS2About()
{
}
/**
* 删除项目
*
* @return \think\response\Json
*/
public function index()
{
try {
$params = $this->request->only('id');
$companId = $params['id'];
Db::startTrans();
$this->dataValidate($params)->delteCkbAbout($companId)->deleteS2About($companId);
Db::commit();
return ResponseHelper::success();
} catch (\Exception $e) {
Db::rollback();
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,114 @@
<?php
namespace app\superadmin\controller\company;
use app\common\model\Company as CompanyModel;
use app\common\model\Device as DeviceModel;
use app\common\model\DeviceWechatLogin as DeviceWechatLoginModel;
use app\common\model\User as UserModel;
use app\common\model\WechatFriendShip as WechatFriendModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
/**
* 公司控制器
*/
class GetCompanyDetailForProfileController extends BaseController
{
/**
* 获取登录设备的所有微信
*
* @param int $companyId
* @return array
*/
protected function getDeveiceWechats(int $companyId): array
{
$wechatIds = DeviceWechatLoginModel::where('companyId', $companyId)->column('wechatId');
return array_unique($wechatIds);
}
/**
* 统计微信好友数量
*
* @param int $companyId
* @return int
*/
protected function getFriendCountByCompanyId(int $companyId): int
{
$wechatIds = $this->getDeveiceWechats($companyId);
return WechatFriendModel::whereIn('ownerWechatId', $wechatIds)->count();
}
/**
* 根据 CompanyId 获取设备数量
*
* @param int $companyId
* @return int
*/
protected function getDeviceCountByCompanyId(int $companyId): int
{
return DeviceModel::where('companyId', $companyId)->count();
}
/**
* 根据 CompanyId 获取子账号数量
*
* @param int $companyId
* @return int
*/
protected function getUsersCountByCompanyId(int $companyId): int
{
$where = array_merge(compact('companyId'), array('isAdmin' => UserModel::ADMIN_OTP));
return UserModel::where($where)->count();
}
/**
* 获取项目详情
*
* @param int $id
* @return CompanyModel
* @throws \Exception
*/
protected function getCompanyDetail(int $id): array
{
$detail = CompanyModel::alias('c')
->field([
'c.id', 'c.name', 'c.memo', 'c.companyId', 'c.createTime',
'u.account', 'u.phone'
])
->leftJoin('users u', 'c.companyId = u.companyId and u.isAdmin = ' . UserModel::ADMIN_STP)
->find($id);
if (!$detail) {
throw new \Exception('项目不存在', 404);
}
return $detail->toArray();
}
/**
* 获取项目详情
*
* @param int $id
* @return \think\response\Json
*/
public function index($id)
{
try {
$data = $this->getCompanyDetail($id);
$userCount = $this->getUsersCountByCompanyId($id);
$deviceCount = $this->getDeviceCountByCompanyId($id);
$friendCount = $this->getFriendCountByCompanyId($id);
return ResponseHelper::success(
array_merge($data, compact('deviceCount', 'friendCount', 'userCount'))
);
} catch (\Exception $e) {
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace app\superadmin\controller\company;
use app\common\model\Company as CompanyModel;
use app\common\model\Device as DeviceModel;
use app\common\model\User as UserModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
/**
* 公司控制器
*/
class GetCompanyDetailForUpdateController extends BaseController
{
/**
* 根据 CompanyId 获取设备列表
*
* @param int $companyId
* @return array
*/
protected function getDevicesByCompanyId(int $companyId): array
{
return DeviceModel::alias('d')
->field([
'd.id', 'd.memo', 'd.model', 'd.brand', 'd.phone', 'd.imei', 'd.createTime', 'd.alive',
])
->where('companyId', $companyId)
->select()
->toArray() ?: [];
}
/**
* 获取项目详情
*
* @param int $id
* @return CompanyModel
* @throws \Exception
*/
protected function getCompanyDetail(int $id): array
{
$detail = CompanyModel::alias('c')
->field([
'c.id', 'c.name', 'c.status', 'c.memo', 'c.companyId',
'u.account', 'u.username', 'u.phone', 'u.s2_accountId'
])
->leftJoin('users u', 'c.companyId = u.companyId and u.isAdmin = ' . UserModel::ADMIN_STP)
->find($id);
if (!$detail) {
throw new \Exception('项目不存在', 404);
}
return $detail->toArray();
}
/**
* 获取项目详情
*
* @param int $id
* @return \think\response\Json
*/
public function index($id)
{
try {
$data = $this->getCompanyDetail($id);
$devices = $this->getDevicesByCompanyId($data['companyId']);
return ResponseHelper::success(
array_merge($data, compact('devices'))
);
} catch (\Exception $e) {
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,105 @@
<?php
namespace app\superadmin\controller\company;
use app\common\model\Device as DeviceModel;
use app\common\model\DeviceWechatLogin as DeviceWechatLoginModel;
use app\common\model\WechatFriendShip as WechatFriendShipModel;
use Eison\Utils\Helper\ArrHelper;
use library\ResponseHelper;
use think\Controller;
/**
* 设备管理控制器
*/
class GetCompanyDevicesForProfileController extends Controller
{
/**
* 获取项目下的所有设备
*
* @return array
*/
protected function getDevicesWithCompanyId(): array
{
$companyId = $this->request->param('companyId/d', 0);
$devices = DeviceModel::alias('d')
->field([
'd.id', 'd.memo', 'd.imei', 'd.phone', 'd.model', 'd.brand', 'd.alive', 'd.id deviceId'
])
->where(compact('companyId'))
->select()
->toArray();
if (empty($devices)) {
throw new \Exception('暂无设备', 200);
}
return $devices;
}
/**
* 查询设备与微信的关联关系.
*
* @return array
*/
protected function getDeviceWechatRelationsByDeviceIds(array $deviceIds): array
{
// 获取设备最新登录记录的id
$latestLogs = DeviceWechatLoginModel::getDevicesLatestLogin($deviceIds);
// 获取最新登录记录id
$latestIds = array_column($latestLogs, 'lastedId');
return DeviceWechatLoginModel::alias('d')
->field([
'd.deviceId', 'd.wechatId', 'd.alive wAlive'
])
->whereIn('id', $latestIds)
->select()
->toArray();
}
/**
* 获取设备的微信好友统计
*
* @param array $ownerWechatId
* @return void
*/
protected function getWechatFriendsCount(array $deviceIds): array
{
// 查询设备与微信的关联关系
$relations = $this->getDeviceWechatRelationsByDeviceIds($deviceIds);
// 统计微信好友数量
$friendCounts = WechatFriendShipModel::alias('f')
->field([
'f.ownerWechatId wechatId', 'count(*) friendCount'
])
->whereIn('ownerWechatId', array_column($relations, 'wechatId'))
->group('ownerWechatId')
->select()
->toArray();
return ArrHelper::leftJoin($relations, $friendCounts, 'wechatId');
}
/**
* 获取公司关联的设备列表
*
* @return \think\response\Json
*/
public function index()
{
try {
$devices = $this->getDevicesWithCompanyId();
$friendCount = $this->getWechatFriendsCount(array_column($devices, 'id'));
$result = ArrHelper::leftJoin($devices, $friendCount, 'deviceId');
return ResponseHelper::success($result);
} catch (\Exception $e) {
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace app\superadmin\controller\company;
use app\common\model\Company as CompanyModel;
use app\common\model\Device as DeviceModel;
use app\common\model\User as usersModel;
use app\superadmin\controller\BaseController;
use Eison\Utils\Helper\ArrHelper;
use library\ResponseHelper;
/**
* 公司控制器
*/
class GetCompanyListController extends BaseController
{
/**
* 构建查询条件
*
* @param array $params
* @return array
*/
protected function makeWhere(array $params = []): array
{
$where = [];
// 如果有搜索关键词
if (!empty($keyword = $this->request->param('keyword/s', ''))) {
$where[] = ['name', 'like', "%{$keyword}%"];
}
return array_merge($params, $where);
}
/**
* 获取设备统计
*
* @return array
*/
protected function getDevices()
{
$devices = DeviceModel::field('companyId, count(id) as numCount')->group('companyId')->select();
$devices = $devices ? $devices->toArray() : array();
return ArrHelper::columnTokey('companyId', $devices);
}
/**
* 获取项目列表
*
* @param array $where 查询条件
* @param int $page 页码
* @param int $limit 每页数量
* @return \think\Paginator 分页对象
*/
protected function getCompanyList(array $where): \think\Paginator
{
$query = CompanyModel::alias('c')
->field([
'c.id', 'c.name', 'c.status', 'c.companyId', 'c.memo', 'c.createTime'
]);
foreach ($where as $key => $value) {
if (is_numeric($key) && is_array($value) && isset($value[0]) && $value[0] === 'exp') {
$query->whereExp('', $value[1]);
continue;
}
$query->where($key, $value);
}
return $query->order('id', 'desc')
->paginate($this->request->param('limit/d', 10), false, ['page' => $this->request->param('page/d', 1)]);
}
/**
* 统计项目下的用户数量
*
* @param int $companyId
* @return int
*/
protected function countUserInCompany(int $companyId): int
{
return UsersModel::where('companyId', $companyId)->count('id');
}
/**
* 构建返回数据
*
* @param \think\Paginator $Companylist
* @return array
*/
protected function makeReturnedResult(\think\Paginator $Companylist): array
{
$result = [];
$devices = $this->getDevices();
foreach ($Companylist->items() as $item) {
$item->userCount = $this->countUserInCompany($item->companyId);
$item->deviceCount = $devices[$item->companyId]['numCount'] ?? 0;
array_push($result, $item->toArray());
}
return $result;
}
/**
* 获取项目列表
*
* @return \think\response\Json
*/
public function index()
{
$where = $this->makeWhere();
$result = $this->getCompanyList($where);
return ResponseHelper::success(
[
'list' => $this->makeReturnedResult($result),
'total' => $result->total(),
]
);
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace app\superadmin\controller\company;
use app\common\model\User as UserModel;
use library\ResponseHelper;
use think\Controller;
/**
* 设备管理控制器
*/
class GetCompanySubusersForProfileController extends Controller
{
/**
* 获取项目下的所有子账号
*
* @return CompanyModel
* @throws \Exception
*/
protected function getSubusers(): array
{
$where = [
'companyId' => $this->request->param('companyId/d', 0),
'isAdmin' => UserModel::ADMIN_OTP
];
return UserModel::alias('u')
->field([
'u.id', 'u.account', 'u.phone', 'u.username', 'u.avatar', 'u.status', 'u.createTime', 'u.typeId'
])
->where($where)
->select()
->toArray();
}
/**
* 获取公司关联的设备列表
*
* @return \think\response\Json
*/
public function index()
{
$users = $this->getSubusers();
foreach ($users as &$user) {
$user['createTime'] = date('Y-m-d H:i:s', $user['createTime']);
}
return ResponseHelper::success($users);
}
}

View File

@@ -0,0 +1,228 @@
<?php
namespace app\superadmin\controller\company;
use app\common\model\Company as CompanyModel;
use app\common\model\User as UsersModel;
use app\superadmin\controller\BaseController;
use Eison\Utils\Helper\ArrHelper;
use library\ResponseHelper;
use think\Db;
use think\Validate;
/**
* 公司控制器
*/
class UpdateCompanyController extends BaseController
{
/**
* 通过id获取项目详情
*
* @return CompanyModel
* @throws \Exception
*/
protected function getCompanyDetailById(): CompanyModel
{
$company = CompanyModel::find(
$this->request->post('id/d', 0)
);
if (!$company) {
throw new \Exception('项目不存在', 404);
}
// 外部使用
$this->companyId = $company->id;
return $company;
}
/**
* 通过账号获取用户信息
*
* @return UsersModel
* @throws \Exception
*/
protected function getUserDetailByCompanyId(): ?UsersModel
{
$where = [
'isAdmin' => UsersModel::MASTER_USER, // 必须保证 isAdmin 有且只有一个
'companyId' => $this->companyId,
];
$user = UsersModel::where($where)->find();
if (!$user) {
throw new \Exception('用户不存在', 404);
}
return $user;
}
/**
* 更新项目信息
*
* @param array $params
* @return void
* @throws \Exception
*/
protected function updateCompany(array $params): void
{
$params = ArrHelper::getValue('name,status,memo', $params);
$params = ArrHelper::rmValue($params);
$company = $this->getCompanyDetailById();
if (!$company->save($params)) {
throw new \Exception('项目更新失败', 403);
}
}
/**
* 更新账号信息
*
* @param array $params
* @return void
*/
protected function updateUserAccount(array $params): void
{
$params = ArrHelper::getValue('username,account,password,phone,status', $params);
$params = ArrHelper::rmValue($params);
if (isset($params['password'])) {
$params['passwordMd5'] = md5($params['password']);
$params['passwordLocal'] = localEncrypt($params['password']);
}
$user = $this->getUserDetailByCompanyId();
if (!$user->save($params)) {
throw new \Exception('用户账号更新失败', 403);
}
}
/**
* 更新存客宝端数据
*
* @param array $params
* @return self
* @throws \Exception
*/
protected function updateCkbAbout(array $params): self
{
// 1. 更新项目信息
$this->updateCompany($params);
// 2. 更新账号信息
$this->updateUserAccount($params);
return $this;
}
/**
* 更新触客宝端数据
*
* @param array $params
* @return self
* @throws \Exception
*/
protected function updateS2About(array $params): self
{
// 1. 更新项目信息
$this->updateCompany($params);
// 2. 更新账号信息
$this->updateUserAccount($params);
return $this;
}
/**
* 检查项目名称是否已存在(排除自身)
*
* @param array $where
* @return void
* @throws \Exception
*/
protected function checkCompanyNameOrAccountOrPhoneExists(array $where): void
{
extract($where);
// 项目名称尽量不重名
$exists = CompanyModel::where(compact('name'))->where('id', '<>', $id)->count() > 0;
if ($exists) {
throw new \Exception('项目名称已存在', 403);
}
// TODO数据迁移时存客宝主账号先查询出id通过id查询出S2的最新信息然后更新。
$exists = UsersModel::where(compact('account'))->where('companyId', '<>', $id)->count() > 0;
if ($exists) {
throw new \Exception('用户账号已存在', 403);
}
// 手机号不重复
$exists = UsersModel::where(compact('phone'))->where('companyId', '<>', $id)->count() > 0;
if ($exists) {
throw new \Exception('手机号已存在', 403);
}
}
/**
* 数据验证
*
* @param array $params
* @return $this
* @throws \Exception
*/
protected function dataValidate(array $params): self
{
$validate = Validate::make([
'id' => 'require',
'name' => 'require|max:50|/\S+/',
'username' => 'require|max:20|/\S+/',
'account' => 'require|regex:^[a-zA-Z0-9]+$|max:20|/\S+/',
'phone' => 'require|regex:/^1[3-9]\d{9}$/',
'status' => 'require|in:0,1'
], [
'id.require' => '非法请求',
'name.require' => '请输入项目名称',
'username.require' => '请输入用户昵称',
'account.require' => '请输入账号',
'account.regex' => '账号只能用数字或者字母或者数字字母组合',
'account.max' => '账号长度受限',
'phone.require' => '请输入手机号',
'phone.regex' => '手机号格式错误',
'status.require' => '缺少重要参数',
'status.in' => '非法参数',
]);
if (!$validate->check($params)) {
throw new \Exception($validate->getError(), 400);
}
return $this;
}
/**
* 更新项目信息
*
* @return \think\response\Json
*/
public function index()
{
try {
$params = $this->request->only(['id', 'name', 'status', 'username', 'account', 'password', 'phone', 'memo']);
// 数据验证
$this->dataValidate($params);
$this->checkCompanyNameOrAccountOrPhoneExists(ArrHelper::getValue('id,name,account,phone', $params));
Db::startTrans();
$this->updateCkbAbout($params)->updateS2About($params);
Db::commit();
return ResponseHelper::success();
} catch (\Exception $e) {
Db::rollback();
return ResponseHelper::error($e->getMessage(), $e->getCode());
}
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace app\superadmin\controller\dashboard;
use app\common\model\Administrator as AdministratorModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Device as DeviceModel;
use library\ResponseHelper;
use think\Controller;
/**
* 仪表盘控制器
*/
class GetBasestatisticsController extends Controller
{
/**
* 项目总数
*
* @return CompanyModel
*/
protected function getCompanyCount(): int
{
return CompanyModel::count('*');
}
/**
* 管理员数量
*
* @return int
*/
protected function getAdminCount(): int
{
return AdministratorModel::count('*');
}
/**
* 设备总数
*
* @return int
*/
protected function getDeviceCount(): int
{
return DeviceModel::count('*');
}
/**
* 获取基础统计信息
*
* @return \think\response\Json
*/
public function index()
{
return ResponseHelper::success(
[
'companyCount' => $this->getCompanyCount(),
'adminCount' => $this->getAdminCount(),
'customerCount' => $this->getDeviceCount(),
]
);
}
}

View File

@@ -0,0 +1,149 @@
<?php
namespace app\superadmin\controller\devices;
use app\api\controller\DeviceController as ApiDeviceController;
use app\common\model\Device as DeviceModel;
use app\common\model\User as UserModel;
use library\ResponseHelper;
use think\Controller;
use think\Db;
/**
* 设备控制器
*/
class GetAddResultedDevicesController extends Controller
{
/**
* 通过账号id 获取项目id。
*
* @param int $accountId
* @return int
*/
protected function getCompanyIdByAccountId(int $accountId): int
{
return UserModel::where('s2_accountId', $accountId)->value('companyId');
}
/**
* 获取项目下的所有设备。
*
* @param int $companyId
* @return array
*/
protected function getAllDevicesIdWithInCompany(int $companyId): array
{
return DeviceModel::where('companyId', $companyId)->column('id') ?: [0];
}
/**
* 执行数据迁移。
*
* @param int $accountId
* @return void
*/
protected function migrateData(int $accountId): void
{
$companyId = $this->getCompanyIdByAccountId($accountId);
$deviceIds = $this->getAllDevicesIdWithInCompany($companyId) ?: [0];
// 从 s2_device 导入数据。
$this->getNewDeviceFromS2_device($deviceIds, $companyId);
}
/**
* 获取当前设备数量
*
* @param int $accountId
* @return int
*/
protected function getCkbDeviceCount(int $accountId): int
{
return DeviceModel::where(
[
'companyId' => $this->getCompanyIdByAccountId($accountId)
]
)
->count('*');
}
/**
* 从 s2_device 导入数据。
*
* @param array $ids
* @param int $companyId
* @return void
*/
protected function getNewDeviceFromS2_device(array $ids, int $companyId): void
{
$ids = implode(',', $ids);
$sql = "INSERT INTO ck_device(`id`, `imei`, `model`, phone, operatingSystem, memo, alive, brand, rooted, xPosed, softwareVersion, extra, createTime, updateTime, deleteTime, companyId)
SELECT
d.id, d.imei, d.model, d.phone, d.operatingSystem, d.memo, d.alive, d.brand, d.rooted, d.xPosed, d.softwareVersion, d.extra, d.createTime, d.lastUpdateTime, d.deleteTime, a.departmentId AS companyId
FROM s2_device d
JOIN s2_company_account a ON d.currentAccountId = a.id
WHERE isDeleted = 0 AND deletedAndStop = 0 AND d.id NOT IN ({$ids}) AND a.departmentId = {$companyId}
ON DUPLICATE KEY UPDATE
imei = VALUES(imei),
model = VALUES(model),
phone = VALUES(phone),
operatingSystem = VALUES(operatingSystem),
memo = VALUES(memo),
alive = VALUES(alive),
brand = VALUES(brand),
rooted = VALUES(rooted),
xPosed = VALUES(xPosed),
softwareVersion = VALUES(softwareVersion),
extra = VALUES(extra),
updateTime = VALUES(updateTime),
deleteTime = VALUES(deleteTime),
companyId = VALUES(companyId)";
Db::query($sql);
}
/**
* 获取添加的关联设备结果。
*
* @param int $accountId
* @return bool
*/
protected function getAddResulted(int $accountId): bool
{
$result = (new ApiDeviceController())->getlist(
[
'accountId' => $accountId,
'pageIndex' => 0,
'pageSize' => 100
],
true
);
$result = json_decode($result, true);
$result = $result['data']['results'][0] ?? false;
return $result ? (
count($result) > $this->getCkbDeviceCount($accountId)
) : false;
}
/**
* 获取基础统计信息
*
* @return \think\response\Json
*/
public function index()
{
$accountId = $this->request->param('accountId/d');
$isAdded = $this->getAddResulted($accountId);
$isAdded && $this->migrateData($accountId);
return ResponseHelper::success(
[
'added' => $isAdded
]
);
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace app\superadmin\controller\traffic;
use app\common\model\Company as CompanyModel;
use app\common\model\TrafficPool as TrafficPoolModel;
use app\common\model\TrafficSource as TrafficSourceModel;
use app\common\model\WechatAccount as WechatAccountModel;
use app\common\model\WechatTag as WechatTagModel;
use think\Controller;
use think\facade\Request;
/**
* 客户池控制器
*/
class GetPoolDetailController extends Controller
{
/**
* 获取客户详情
* @return \think\response\Json
*/
public function index()
{
// 获取参数
$id = Request::param('id/d');
if (!$id) {
return json(['code' => 400, 'msg' => '参数错误']);
}
try {
// 查询流量来源信息
$sourceInfo = TrafficSourceModel::alias('ts')
->join('company c', 'ts.companyId = c.companyId', 'LEFT')
->field([
'ts.fromd as source',
'ts.createTime as addTime',
'c.name as projectName',
'ts.identifier'
])
->where('ts.id', $id)
->find();
if (!$sourceInfo) {
return json(['code' => 404, 'msg' => '记录不存在']);
}
// 查询客户池信息
$poolInfo = TrafficPoolModel::where('identifier', $sourceInfo['identifier'])
->field('wechatId')
->find();
$result = [
'source' => $sourceInfo['source'],
'addTime' => $sourceInfo['addTime'] ? date('Y-m-d H:i:s', $sourceInfo['addTime']) : null,
'projectName' => $sourceInfo['projectName']
];
// 如果存在微信ID查询微信账号信息
if ($poolInfo && $poolInfo['wechatId']) {
// 查询微信账号信息
$wechatInfo = WechatAccountModel::where('wechatId', $poolInfo['wechatId'])
->field('avatar,nickname,region,gender')
->find();
if ($wechatInfo) {
$result = array_merge($result, [
'avatar' => $wechatInfo['avatar'],
'nickname' => $wechatInfo['nickname'],
'region' => $wechatInfo['region'],
'gender' => $this->formatGender($wechatInfo['gender'])
]);
// 查询标签信息
$tagInfo = WechatTagModel::where('wechatId', $poolInfo['wechatId'])
->field('tags')
->find();
if ($tagInfo) {
$result['tags'] = is_string($tagInfo['tags']) ?
json_decode($tagInfo['tags'], true) :
$tagInfo['tags'];
} else {
$result['tags'] = [];
}
}
} else {
$result = array_merge($result, [
'avatar' => '',
'nickname' => '未知',
'region' => '未知',
'gender' => $this->formatGender(0),
'tags' => []
]);
}
return json([
'code' => 200,
'msg' => '获取成功',
'data' => $result
]);
} catch (\Exception $e) {
return json([
'code' => 500,
'msg' => '系统错误:' . $e->getMessage()
]);
}
}
/**
* 格式化性别显示
* @param int $gender
* @return string
*/
protected function formatGender($gender)
{
switch ($gender) {
case 1:
return '男';
case 2:
return '女';
default:
return '保密';
}
}
}

View File

@@ -0,0 +1,113 @@
<?php
namespace app\superadmin\controller\traffic;
use app\common\model\TrafficPool as TrafficPoolModel;
use app\superadmin\controller\BaseController;
use library\ResponseHelper;
use think\facade\Request;
/**
* 客户池控制器
*/
class GetPoolListController extends BaseController
{
/**
* 格式化性别显示
*
* @param int $gender
* @return string
*/
protected function formatGender(?int $gender): string
{
switch ($gender) {
case 1:
return '男';
case 2:
return '女';
default:
return '保密';
}
}
/**
* 处理标签显示
*
* @param string|null $tags
* @return array
*/
protected function handlTags(?string $tags): array
{
return is_string($tags) ? json_decode($tags, true) : [];
}
/**
* 格式化时间
*
* @param string|null $date
* @return string|null
*/
protected function formatDate(?string $date): ?string
{
return $date ? date('Y-m-d H:i:s', $date) : null;
}
/**
* 构建返回数据
*
* @param \think\Paginator $list
* @return \think\Paginator
*/
protected function makeReturnedValue(\think\Paginator $list): \think\Paginator
{
$list->each(function ($item) {
$item->gender = $this->formatGender($item->gender);
$item->addTime = $this->formatDate($item->addTime);
$item->tags = $this->handlTags($item->tags);
});
return $list;
}
/**
* 构建查询.
*
* @return TrafficPoolModel|\think\Paginator
*/
protected function gePoolList(): \think\Paginator
{
$query = TrafficPoolModel::alias('tp')
->field([
'tp.wechatId',
'ts.id', 'ts.createTime as addTime', 'ts.fromd as source',
'c.name as projectName',
'wa.avatar', 'wa.gender', 'wa.nickname', 'wa.region',
'wt.tags'
])
->join('traffic_source ts', 'tp.identifier = ts.identifier', 'RIGHT')
->join('company c', 'ts.companyId = c.companyId', 'LEFT')
->join('wechat_account wa', 'tp.wechatId = wa.wechatId', 'LEFT')
->join('wechat_tag wt', 'wa.wechatId = wt.wechatId', 'LEFT');
return $query->paginate($this->request->param('limit/d', 10), false, ['page' => $this->request->param('page/d', 1)]);
}
/**
* 获取客户池列表
*
* @return \think\response\Json
*/
public function index()
{
$list = $this->gePoolList();
return ResponseHelper::success(
[
'list' => $this->makeReturnedValue($list)->items(),
'total' => $list->total(),
'page' => $list->currentPage(),
'limit' => $list->listRows()
]
);
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace app\superadmin\middleware;
use app\common\model\Administrator;
/**
* 超级管理员后台登录认证中间件
*/
class AdminAuth
{
/**
* 处理请求
* @param \think\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, \Closure $next)
{
// 对OPTIONS请求直接放行由跨域中间件处理
if ($request->method(true) == 'OPTIONS') {
return $next($request);
}
// 获取Cookie中的管理员信息
$adminId = cookie('admin_id');
$adminToken = cookie('admin_token');
// 如果没有登录信息返回401未授权
if (empty($adminId) || empty($adminToken)) {
return json([
'code' => 401,
'msg' => '请先登录',
'data' => null
]);
}
// 获取管理员信息
$admin = Administrator::where([
['id', '=', $adminId],
['status', '=', 1]
])->find();
// 如果管理员不存在返回401未授权
if (!$admin) {
return json([
'code' => 401,
'msg' => '管理员账号不存在或已被禁用',
'data' => null
]);
}
// 验证Token是否有效
$expectedToken = $this->createToken($admin);
if ($adminToken !== $expectedToken) {
return json([
'code' => 401,
'msg' => '登录已过期,请重新登录',
'data' => null
]);
}
// 将管理员信息绑定到请求对象,方便后续控制器使用
$request->adminInfo = $admin;
// 继续执行后续操作
return $next($request);
}
/**
* 创建登录令牌
*
* @param Administrator $admin
* @return string
*/
private function createToken($admin)
{
$data = $admin->id . '|' . $admin->account;
return md5($data . 'cunkebao_admin_secret');
}
}