ProjectManagerController.php 2.37 KB
<?php

namespace App\Http\Container\AdminSection\Controllers\Audition;

use App\Enums\UserScopeEnum;
use App\Helpers\OperationLog;
use App\Http\Container\AdminSection\Requests\Audition\ProjectManagerRequest;
use App\Models\Pivots\UserProjectPivot;
use App\Models\Project;
use App\Models\User;
use App\Support\Controller;
use DB;
use Hikoon\LaravelApi\Facades\Response;
use Hikoon\LaravelApi\Support\ApiCode;

class ProjectManagerController extends Controller
{
    /**
     * @param \App\Http\Container\AdminSection\Requests\Audition\ProjectManagerRequest $request
     * @return \Hikoon\LaravelApi\Facades\Response
     */
    public function store(ProjectManagerRequest $request): Response
    {
        $attribute   = $request->validated();
        $user        = User::query()->find($attribute['user_id'], ['id', 'nick_name']);
        $projectName = Project::query()->whereKey($attribute['project_id'])->value('name');
        if (!$user) {
            return $this->fail(ApiCode::VALIDATION_ERROR, '用户不存在');
        }
        if ($user->getAttribute('scope') === UserScopeEnum::SYSTEM) {
            return $this->fail(ApiCode::VALIDATION_ERROR, '该用户为系统管理员');
        }

        User::query()->whereKey($attribute['user_id'])->update(['scope' => UserScopeEnum::PROJECT]);
        $projectManager = UserProjectPivot::query()->updateOrCreate($attribute);
        OperationLog::admin()->subject($projectManager)->createAction()->content('《%s》新增管理员:%s', $projectName, $user->getAttribute('nick_name'));
        return $this->success(ApiCode::CREATE_SUCCESS);
    }


    public function destroy(UserProjectPivot $projectManager): Response
    {

        DB::transaction(static function () use ($projectManager) {
            $nickName    = $projectManager->user()->value('nick_name');
            $projectName = $projectManager->project()->value('name');
            $userId      = $projectManager->getAttribute('user_id');
            $projectManager->delete();

            if (UserProjectPivot::query()->where('user_id', $userId)->doesntExist()) {
                User::query()->whereKey($userId)->update(['scope' => UserScopeEnum::UNSET]);
            }

            OperationLog::admin()->subject($projectManager)->deleteAction()->content('《%s》移除管理员:%s', $projectName, $nickName);
        });

        return $this->success(ApiCode::DELETE_SUCCESS);
    }
}