86 lines
2.2 KiB
PHP
86 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace app\admin\service;
|
|
|
|
use app\common\model\User as UserModel;
|
|
|
|
class AccountService
|
|
{
|
|
|
|
/* 查询所有用户 */
|
|
public function getAllUsers()
|
|
{
|
|
$users = UserModel::with('company')->select();
|
|
return $users->map(function ($user) {
|
|
return [
|
|
'id' => $user->id,
|
|
'company' => [
|
|
'id' => $user->company_id,
|
|
'company_name' => $user->company->company_name
|
|
],
|
|
'username' => $user->username,
|
|
'real_name' => $user->real_name,
|
|
'role' => $user->role,
|
|
'status' => $user->status,
|
|
];
|
|
})->toArray();
|
|
}
|
|
|
|
/* 注册账户 */
|
|
public function createAccount($data)
|
|
{
|
|
if (empty($data['real_name'])) {
|
|
$data['real_name'] = $data['username'];
|
|
}
|
|
|
|
# 检查数据库中是否有相同用户名账户
|
|
$exist = UserModel::where('username', $data['username'])->find();
|
|
|
|
if ($exist) {
|
|
throw new \Exception('用户名已存在');
|
|
}
|
|
|
|
$insertData = [
|
|
'company_id' => $data['company_id'] ?? 0,
|
|
'username' => $data['username'],
|
|
'real_name' => $data['real_name'] ?? $data['username'],
|
|
'password' => password_hash('123456', PASSWORD_DEFAULT),
|
|
'role' => $data['role'] ?? 'user',
|
|
'status' => 1,
|
|
];
|
|
|
|
$user = UserModel::create($insertData);
|
|
|
|
/** @var \think\Model $user */
|
|
return $user->visible(['id', 'username', 'real_name', 'role', 'status'])->toArray();
|
|
}
|
|
|
|
/* 更新用户状态 */
|
|
public function updateAccountStatus($id, $status)
|
|
{
|
|
$user = UserModel::find($id);
|
|
if (!$user) {
|
|
throw new \Exception('用户不存在');
|
|
}
|
|
|
|
$user->status = $status;
|
|
$user->save();
|
|
|
|
return $user->visible(['id', 'username', 'real_name', 'role', 'status'])->toArray();
|
|
}
|
|
|
|
|
|
/* 删除用户 */
|
|
public function deleteAccount($id)
|
|
{
|
|
$user = UserModel::find($id);
|
|
if (!$user) {
|
|
throw new \Exception('用户不存在');
|
|
}
|
|
|
|
$user->delete();
|
|
|
|
return ['id' => $id];
|
|
}
|
|
}
|