task users, set priority at column and task, timer entity

This commit is contained in:
2023-05-23 02:11:44 +03:00
parent c50dc189a7
commit 5da6746cc4
12 changed files with 794 additions and 8 deletions

View File

@ -2,9 +2,11 @@
namespace frontend\modules\api\controllers;
use common\classes\Debug;
use common\models\ProjectColumn;
use frontend\modules\api\models\Project;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
class ProjectColumnController extends ApiController
{
@ -15,6 +17,7 @@ class ProjectColumnController extends ApiController
'get-column' => ['get'],
'get-column-list' => ['get'],
'create-column' => ['post'],
'set-priority' => ['post'],
'update-column' => ['put', 'patch'],
];
}
@ -197,7 +200,7 @@ class ProjectColumnController extends ApiController
$column->load($put, '');
if (!$column->validate()){
if (!$column->validate()) {
throw new BadRequestHttpException(json_encode($column->errors));
}
@ -206,4 +209,71 @@ class ProjectColumnController extends ApiController
return $column;
}
/**
*
* @OA\Post(path="/project-column/set-priority",
* summary="Установить приоритет колонок",
* description="Метод для установления приоритета колонок в проекте",
* security={
* {"bearerAuth": {}}
* },
* tags={"TaskManager"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* required={"project_id", "data"},
* @OA\Property(
* property="project_id",
* type="integer",
* description="Идентификатор проекта",
* ),
* @OA\Property(
* property="data",
* type="string",
* description="Данные для обновления приоритета. Пример: [{"column_id":1,"priority":2},{"column_id":2,"priority":3}]",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает объект проекта",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/Project"),
* ),
* ),
* )
*
* @return array|Project|\yii\db\ActiveRecord
* @throws BadRequestHttpException
*/
public function actionSetPriority()
{
$request = \Yii::$app->request->post();
$data = $request['data'];
$project = Project::findOne($request['project_id']);
if (empty($project)) {
throw new NotFoundHttpException('The project not found');
}
if (!$data = json_decode($data, true)) {
throw new BadRequestHttpException('No valid JSON');
}
foreach ($data as $datum) {
$model = ProjectColumn::findOne($datum['column_id']);
$model->priority = $datum['priority'];
if (!$model->validate()){
throw new BadRequestHttpException($model->errors);
}
$model->save();
}
return $project;
}
}

View File

@ -4,9 +4,13 @@ namespace frontend\modules\api\controllers;
use common\classes\Debug;
use common\models\ProjectTask;
use common\models\ProjectTaskUser;
use common\models\User;
use common\services\TaskService;
use frontend\modules\api\models\ProjectColumn;
use Yii;
use yii\base\InvalidConfigException;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
@ -20,6 +24,8 @@ class TaskController extends ApiController
'get-user-tasks' => ['get'],
'create-task' => ['post'],
'update-task' => ['put', 'patch'],
'add-user-to-task' => ['post'],
'del-user' => ['delete'],
];
}
@ -92,7 +98,7 @@ class TaskController extends ApiController
public function actionCreateTask(): ProjectTask
{
$request = Yii::$app->getRequest()->getBodyParams();
if(!isset($request['user_id']) or $request['user_id'] == null){
if (!isset($request['user_id']) or $request['user_id'] == null) {
$request['user_id'] = Yii::$app->user->id;
}
@ -325,4 +331,203 @@ class TaskController extends ApiController
return $modelTask;
}
/**
*
* @OA\Post(path="/task/add-user-to-task",
* summary="Добавить пользователя в задачу",
* description="Метод для добавления пользователя в задачу",
* security={
* {"bearerAuth": {}}
* },
* tags={"TaskManager"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* required={"user_id", "task_id"},
* @OA\Property(
* property="user_id",
* type="integer",
* description="Идентификатор пользователя",
* ),
* @OA\Property(
* property="task_id",
* type="integer",
* description="Идентификатор задачи",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает объект связи задачи и пользователя",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/ProjectTaskUser"),
* ),
* ),
* )
*
* @return ProjectTaskUser
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
*/
public function actionAddUserToTask(): ProjectTaskUser
{
$request = \Yii::$app->request->post();
$user = User::findOne($request['user_id']);
if (!$user) {
throw new NotFoundHttpException('User not found');
}
if (empty ($request['task_id']) or !TaskService::taskExists($request['task_id'])) {
throw new NotFoundHttpException('The task does not exist');
}
if (ProjectTaskUser::find()->where(['user_id' => $request['user_id'], 'task_id' => $request['task_id']])->exists()) {
throw new ServerErrorHttpException('The user has already been added');
}
$model = new ProjectTaskUser();
$model->load($request, '');
if (!$model->validate()) {
throw new ServerErrorHttpException($model->errors);
}
$model->save();
return $model;
}
/**
*
* @OA\Delete(path="/task/del-user",
* summary="Удаление пользователя из задачи",
* description="Метод для Удаления пользователя из задачи",
* security={
* {"bearerAuth": {}}
* },
* tags={"TaskManager"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* required={"task_id", "user_id"},
* @OA\Property(
* property="task_id",
* type="integer",
* description="Идентификатор задачи",
* ),
* @OA\Property(
* property="user_id",
* type="integer",
* description="Идентификатор пользователя",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает объект задачи",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/ProjectTask"),
* ),
* ),
* )
*
* @return ProjectTask|null
* @throws InvalidConfigException
* @throws NotFoundHttpException
*/
public function actionDelUser(): ?ProjectTask
{
$request = Yii::$app->request->getBodyParams();
$user = User::findOne($request['user_id']);
if (!$user) {
throw new NotFoundHttpException('User not found');
}
if (empty ($request['task_id']) or !TaskService::taskExists($request['task_id'])) {
throw new NotFoundHttpException('The task does not exist');
}
ProjectTaskUser::deleteAll(['task_id' => $request['task_id'], 'user_id' => $request['user_id']]);
return TaskService::getTask($request['task_id']);
}
/**
*
* @OA\Post(path="/task/set-priority",
* summary="Установить приоритет задач",
* description="Метод для установления приоритета задач в колонке",
* security={
* {"bearerAuth": {}}
* },
* tags={"TaskManager"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* required={"column_id", "data"},
* @OA\Property(
* property="column_id",
* type="integer",
* description="Идентификатор проекта",
* ),
* @OA\Property(
* property="data",
* type="string",
* description="Данные для обновления приоритета. Пример: [{"task_id":3,"priority":2},{"task_id":4,"priority":3}]",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает объект колонки",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/ProjectColumn"),
* ),
* ),
* )
*
* @return ProjectColumn
* @throws BadRequestHttpException
* @throws NotFoundHttpException
*/
public function actionSetPriority(): ProjectColumn
{
$request = \Yii::$app->request->post();
$data = $request['data'];
if (!$data = json_decode($data, true)) {
throw new BadRequestHttpException('No valid JSON');
}
$column = ProjectColumn::findOne($request['column_id']);
if (empty($column)) {
throw new NotFoundHttpException('The column not found');
}
foreach ($data as $datum) {
$model = ProjectTask::findOne($datum['task_id']);
$model->priority = $datum['priority'];
if (!$model->validate()){
throw new BadRequestHttpException($model->errors);
}
$model->save();
}
return $column;
}
}

View File

@ -0,0 +1,237 @@
<?php
namespace frontend\modules\api\controllers;
use common\classes\Debug;
use frontend\modules\api\models\Timer;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
class TimerController extends ApiController
{
public function verbs(): array
{
return [
'create' => ['post'],
'update' => ['put'],
'get-by-entity' => ['get'],
];
}
/**
*
* @OA\Post(path="/timer/create",
* summary="Добавить таймер",
* description="Метод для создания таймера",
* security={
* {"bearerAuth": {}}
* },
* tags={"Timer"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* required={"entity_type", "entity_id", "created_at"},
* @OA\Property(
* property="entity_type",
* type="integer",
* description="Тип сущности",
* ),
* @OA\Property(
* property="entity_id",
* type="integer",
* description="Идентификатор сущности",
* ),
* @OA\Property(
* property="created_at",
* type="datetime",
* description="Время запуска. Формат (Год-месяц-день Час:минута:секунда). Пример: 2023-05-22 21:36:55",
* example="2023-05-22 21:36:55",
* ),
* @OA\Property(
* property="status",
* type="integer",
* description="Статус комментария",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает объект комментария",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/Timer"),
* ),
* ),
* )
*
* @return Timer
* @throws BadRequestHttpException
*/
public function actionCreate(): Timer
{
$request = \Yii::$app->request->post();
$user_id = \Yii::$app->user->id;
if (!$user_id) {
throw new BadRequestHttpException('User not found');
}
$request = array_diff($request, [null, '']);
//Закрываем предыдущие таймеры
$oldTimers = Timer::find()->where(['entity_id' => $request['entity_id'], 'entity_type' => $request['entity_type']])->all();
if ($oldTimers){
foreach ($oldTimers as $oldTimer){
if ($oldTimer->stopped_at == null){
$oldTimer->stopped_at = date("Y-m-d H:i:s");
$oldTimer->save();
}
}
}
$model = new Timer();
$model->load($request, '');
$model->user_id = $user_id;
$model->created_at = date("Y-m-d H:i:s");
if (!$model->validate()) {
throw new BadRequestHttpException(json_encode($model->errors));
}
$model->save();
return $model;
}
/**
*
* @OA\Put(path="/timer/update",
* summary="Редактировать таймер",
* description="Метод для редактирования таймера",
* security={
* {"bearerAuth": {}}
* },
* tags={"Timer"},
*
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* required={"timer_id"},
* @OA\Property(
* property="timer_id",
* type="integer",
* description="Идентификатор таймера",
* ),
* @OA\Property(
* property="stopped_at",
* type="datetime",
* description="Время завершения работы таймера",
* ),
* @OA\Property(
* property="status",
* type="integer",
* description="статус",
* ),
* ),
* ),
* ),
* @OA\Response(
* response=200,
* description="Возвращает объект Таймера",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/Timer"),
* ),
* ),
* )
*
* @return Timer
* @throws BadRequestHttpException
* @throws \yii\base\InvalidConfigException
*/
public function actionUpdate(): Timer
{
$user_id = \Yii::$app->user->id;
if (!$user_id) {
throw new BadRequestHttpException(json_encode(['User not found']));
}
$timer_id = \Yii::$app->request->getBodyParam('timer_id');
$model = Timer::findOne($timer_id);
if (!$model) {
throw new BadRequestHttpException(json_encode(['Timer not found']));
}
$put = array_diff(\Yii::$app->request->getBodyParams(), [null, '']);
$model->load($put, '');
if(!$model->validate()){
throw new BadRequestHttpException($model->errors);
}
$model->save();
return $model;
}
/**
*
* @OA\Get(path="/timer/get-by-entity",
* summary="Получить таймер по идентификатору сущности",
* description="Метод для получения таймера по идентификатору сущности.",
* security={
* {"bearerAuth": {}}
* },
* tags={"Timer"},
* @OA\Parameter(
* name="entity_id",
* in="query",
* required=true,
* @OA\Schema(
* type="integer",
* default=null
* )
* ),
*
* @OA\Parameter(
* name="entity_type",
* in="query",
* required=true,
* @OA\Schema(
* type="integer",
* default=null
* )
* ),
*
* @OA\Response(
* response=200,
* description="Возвращает массив объектов Таймера",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/TimerExample"),
* ),
* ),
* )
*
* @param int $entity_type
* @param int $entity_id
* @return array
* @throws NotFoundHttpException
*/
public function actionGetByEntity(int $entity_type, int $entity_id): array
{
$model = Timer::find()->where(['entity_type' => $entity_type, 'entity_id' => $entity_id, 'status' => Timer::STATUS_ACTIVE])->all();
if (!$model) {
throw new NotFoundHttpException('The timer not found');
}
return $model;
}
}