From 1bcc7834c251e90dfae3176c40d821cdbf0780ed Mon Sep 17 00:00:00 2001 From: Kavalar Date: Thu, 1 Feb 2024 00:57:42 +0300 Subject: [PATCH] reports fix --- common/models/Reports.php | 17 +- common/models/ReportsTask.php | 18 +- console/controllers/SqlController.php | 20 +- ...48_add_user_id_column_at_reports_table.php | 45 ++ ..._reports_user_card_id_at_reports_table.php | 28 ++ .../api/controllers/ReportsController.php | 433 +++++++++--------- .../modules/api/models/ReportSearchForm.php | 13 +- frontend/modules/api/models/Reports.php | 14 + 8 files changed, 355 insertions(+), 233 deletions(-) create mode 100644 console/migrations/m240131_080048_add_user_id_column_at_reports_table.php create mode 100644 console/migrations/m240131_132201_drop_fk_reports_user_card_id_at_reports_table.php diff --git a/common/models/Reports.php b/common/models/Reports.php index 1fc3b47..49612ae 100755 --- a/common/models/Reports.php +++ b/common/models/Reports.php @@ -14,6 +14,7 @@ use Yii; * @property string $difficulties * @property string $tomorrow * @property int $user_card_id + * @property int $user_id * @property int $project_id * @property int $company_id * @property int $status @@ -38,11 +39,12 @@ class Reports extends \yii\db\ActiveRecord public function rules() { return [ - [['user_card_id', 'status', 'company_id', 'project_id'], 'integer'], + [['user_card_id', 'user_id', 'status', 'company_id', 'project_id'], 'integer'], [['_task'], 'checkIsArray'], - [['user_card_id', 'created_at'], 'required'], + [['created_at'], 'required'], [['today', 'difficulties', 'tomorrow', 'created_at'], 'string', 'max' => 255], [['user_card_id'], 'exist', 'skipOnError' => true, 'targetClass' => UserCard::class, 'targetAttribute' => ['user_card_id' => 'id']], + [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::class, 'targetAttribute' => ['user_id' => 'id']], [['project_id'], 'exist', 'skipOnEmpty' => true, 'targetClass' => Project::class, 'targetAttribute' => ['project_id' => 'id']], [['company_id'], 'exist', 'skipOnEmpty' => true, 'targetClass' => Company::class, 'targetAttribute' => ['company_id' => 'id']], ]; @@ -59,7 +61,8 @@ class Reports extends \yii\db\ActiveRecord 'today' => 'Что было сделано сегодня?', 'difficulties' => 'Какие сложности возникли?', 'tomorrow' => 'Что планируется сделать завтра?', - 'user_card_id' => 'Пользователь', + 'user_card_id' => 'Профиль пользователя', + 'user_id' => 'Пользователь', 'status' => 'Статус', 'project_id' => 'ID проекта', 'company_id' => 'ID компании' @@ -95,6 +98,14 @@ class Reports extends \yii\db\ActiveRecord return $this->hasOne(UserCard::className(), ['id' => 'user_card_id']); } + /** + * @return \yii\db\ActiveQuery + */ + private function getUser(): \yii\db\ActiveQuery + { + return $this->hasOne(User::class, ['id' => 'user_id']); + } + public function getTask() { return $this->hasMany(ReportsTask::class, ['report_id' => 'id']); diff --git a/common/models/ReportsTask.php b/common/models/ReportsTask.php index b86fcf0..b4c0194 100755 --- a/common/models/ReportsTask.php +++ b/common/models/ReportsTask.php @@ -19,14 +19,14 @@ use Yii; */ class ReportsTask extends \yii\db\ActiveRecord { - const SCENARIO_WITHOUT_REPORT_ID = 'withoutReportID'; - - public function scenarios() - { - $scenarios = parent::scenarios(); - $scenarios[self::SCENARIO_WITHOUT_REPORT_ID] = self::attributes(); - return $scenarios; - } +// const SCENARIO_WITHOUT_REPORT_ID = 'withoutReportID'; +// +// public function scenarios() +// { +// $scenarios = parent::scenarios(); +// $scenarios[self::SCENARIO_WITHOUT_REPORT_ID] = self::attributes(); +// return $scenarios; +// } /** * {@inheritdoc} @@ -42,7 +42,7 @@ class ReportsTask extends \yii\db\ActiveRecord public function rules() { return [ - [['report_id'], 'required', 'on' => self::SCENARIO_DEFAULT], + //[['report_id'], 'required', 'on' => self::SCENARIO_DEFAULT], [['report_id', 'created_at', 'status', 'minutes_spent'], 'integer'], [['hours_spent'], 'number'], ['minutes_spent', 'compare', 'compareValue' => 60, 'operator' => '<'], diff --git a/console/controllers/SqlController.php b/console/controllers/SqlController.php index 4727c5f..2273546 100755 --- a/console/controllers/SqlController.php +++ b/console/controllers/SqlController.php @@ -4,6 +4,7 @@ namespace console\controllers; +use common\models\Reports; use common\models\UserCard; use Yii; use yii\console\Controller; @@ -21,11 +22,10 @@ class SqlController extends Controller { $model = UserCard::find()->all(); foreach ($model as $item) { - if(!$item->photo){ - if($item->gender === 1){ + if (!$item->photo) { + if ($item->gender === 1) { $item->photo = '/profileava/f' . random_int(1, 6) . '.png'; - } - else { + } else { $item->photo = '/profileava/m' . random_int(1, 10) . '.png'; } $item->save(); @@ -38,4 +38,16 @@ class SqlController extends Controller { echo UserCard::generateUserForUserCard() . "\n"; } + + public function actionAddUserIdToReports() + { + $reports = Reports::find()->all(); + foreach ($reports as $report) { + $report->user_id = $report->userCard->id_user; + $report->save(); + echo "user $report->user_id changed\n"; + } + + echo "script completed successfully\n"; + } } \ No newline at end of file diff --git a/console/migrations/m240131_080048_add_user_id_column_at_reports_table.php b/console/migrations/m240131_080048_add_user_id_column_at_reports_table.php new file mode 100644 index 0000000..3781c30 --- /dev/null +++ b/console/migrations/m240131_080048_add_user_id_column_at_reports_table.php @@ -0,0 +1,45 @@ +addColumn(self::TABLE_NAME, self::COLUMN_NAME, $this->integer(11)->after("status")); + $this->addForeignKey('fk_reports_user', self::TABLE_NAME, self::COLUMN_NAME, 'user', 'id'); + } + + /** + * {@inheritdoc} + */ + public function safeDown() + { + $this->dropForeignKey('fk_reports_user', self::TABLE_NAME); + $this->dropColumn(self::TABLE_NAME, self::COLUMN_NAME); + } + + /* + // Use up()/down() to run migration code without a transaction. + public function up() + { + + } + + public function down() + { + echo "m240131_080048_add_user_id_column_at_reports_table cannot be reverted.\n"; + + return false; + } + */ +} diff --git a/console/migrations/m240131_132201_drop_fk_reports_user_card_id_at_reports_table.php b/console/migrations/m240131_132201_drop_fk_reports_user_card_id_at_reports_table.php new file mode 100644 index 0000000..5ede190 --- /dev/null +++ b/console/migrations/m240131_132201_drop_fk_reports_user_card_id_at_reports_table.php @@ -0,0 +1,28 @@ +dropForeignKey("fk-reports-user_card_id", "reports"); + $this->dropIndex("idx-reports-user_card_id", "reports"); + $this->alterColumn("reports", "user_card_id", $this->integer(11)); + $this->alterColumn("reports", "status", $this->integer(1)->defaultValue(1)); + } + + /** + * {@inheritdoc} + */ + public function safeDown() + { + + } +} diff --git a/frontend/modules/api/controllers/ReportsController.php b/frontend/modules/api/controllers/ReportsController.php index 3167efd..524afea 100755 --- a/frontend/modules/api/controllers/ReportsController.php +++ b/frontend/modules/api/controllers/ReportsController.php @@ -2,6 +2,7 @@ namespace frontend\modules\api\controllers; +use common\classes\Debug; use common\models\Reports; use common\models\ReportsTask; use common\models\UserCard; @@ -14,39 +15,48 @@ use yii\web\NotFoundHttpException; class ReportsController extends ApiController { + public function verbs(): array + { + return [ + 'index' => ['get'], + 'attach' => ['post'], + 'delete' => ['delete'], + 'update' => ['put', 'patch'], + ]; + } + /** - * @OA\Get(path="/user-response/index", + * @OA\Get(path="/reports/index", * summary="Поиск отчётов по промежутку дат", * description="Осуществляет поиск отчётов пользователя по промежутку дат", * security={ * {"bearerAuth": {}} * }, * tags={"Reports"}, - * @OA\RequestBody( - * @OA\MediaType( - * mediaType="application/x-www-form-urlencoded", - * @OA\Schema( - * required={"user_card_id"}, - * @OA\Property( - * property="user_card_id", - * type="integer", - * description="Идентификатор карты(профиля) пользователя", - * nullable=false, - * ), - * @OA\Property( - * property="fromDate", - * type="DateTime", - * description="Дата начала поиска", - * nullable=false, - * ), - * @OA\Property( - * property="toDate", - * type="DateTime", - * description="Дата конца периода поиска", - * nullable=false, - * ), - * ), - * ), + * @OA\Parameter( + * name="user_id", + * description="Идентификатор пользователя", + * in="query", + * required=true, + * @OA\Schema( + * type="integer", + * ) + * ), + * @OA\Parameter( + * name="fromDate", + * description="Дата начала поиска", + * in="query", + * @OA\Schema( + * type="DateTime", + * ) + * ), + * @OA\Parameter( + * name="toDate", + * description="Дата конца периода поиска", + * in="query", + * @OA\Schema( + * type="DateTime", + * ) * ), * * @OA\Response( @@ -61,10 +71,9 @@ class ReportsController extends ApiController * * ) * - * @param $user_card_id * @return array */ - public function actionIndex($user_card_id): array + public function actionIndex(): array { $reportsModel = new ReportSearchForm(); @@ -82,32 +91,30 @@ class ReportsController extends ApiController } /** - * @OA\Get(path="/user-response/find-by-date", + * @OA\Get(path="/reports/find-by-date", * summary="Поиск отчётов по дате", * description="Осуществляет поиск отчётов пользователя по дате", * security={ * {"bearerAuth": {}} * }, * tags={"Reports"}, - * @OA\RequestBody( - * @OA\MediaType( - * mediaType="application/x-www-form-urlencoded", - * @OA\Schema( - * required={"user_card_id"}, - * @OA\Property( - * property="user_card_id", - * type="integer", - * description="Идентификатор карты(профиля) пользователя", - * nullable=false, - * ), - * @OA\Property( - * property="date", - * type="DateTime", - * description="Дата поиска", - * nullable=false, - * ), - * ), - * ), + * @OA\Parameter( + * name="user_id", + * description="Идентификатор пользователя", + * in="query", + * required=true, + * @OA\Schema( + * type="integer", + * ) + * ), + * @OA\Parameter( + * name="date", + * description="Дата поиска", + * in="query", + * required=true, + * @OA\Schema( + * type="DateTime", + * ) * ), * * @OA\Response( @@ -131,7 +138,7 @@ class ReportsController extends ApiController $reportsModel = new ReportSearchForm(); $params = Yii::$app->request->get(); - if(!isset($params['user_card_id']) or !isset($params['date'])){ + if(!isset($params['user_id']) or !isset($params['date'])){ throw new NotFoundHttpException('Required parameter are missing!'); } @@ -157,96 +164,75 @@ class ReportsController extends ApiController * {"bearerAuth": {}} * }, * tags={"Reports"}, - * @OA\Parameter( - * name="difficulties", - * in="query", - * required=false, - * description="Описание сложностей возникших при выполнении задач", - * @OA\Schema( - * type="string", - * ) - * ), - * @OA\Parameter( - * name="tomorrow", - * in="query", - * required=false, - * description="Описание планов на завтра", - * @OA\Schema( - * type="string", - * ) - * ), - * @OA\Parameter( - * name="created_at", - * in="query", - * required=false, - * description="Дата создания", - * @OA\Schema( - * type="string", - * ) - * ), - * @OA\Parameter( - * name="status", - * in="query", - * required=false, - * description="Статус", - * @OA\Schema( - * type="integer", - * ) - * ), - * @OA\Parameter( - * name="user_card_id", - * in="query", - * required=false, - * description="ID карты(профиля) пользователя", - * @OA\Schema( - * type="integer", - * ) - * ), - * @OA\Parameter( - * name="project_id", - * in="query", - * required=false, - * description="ID проекта", - * @OA\Schema( - * type="integer", - * ) - * ), - * @OA\Parameter( - * name="company_id", - * in="query", - * required=false, - * description="ID компании", - * @OA\Schema( - * type="integer", - * ) - * ), - * @OA\Parameter( - * name="tasks[]", - * in="query", - * required=false, - * description="Масив задач. ", - * @OA\Schema( - * type="array", - * @OA\Items( - * type="object", - * @OA\Property( - * property="task", - * description="Название задачи", - * type="string", - * ), - * @OA\Property( - * property="hours_spent", - * description="Затраченное количество часов", - * type="string", - * ), - * @OA\Property( - * property="minutes_spent", - * description="Затраченное количество минут", - * type="string", - * ) - * ) - * ) + * + * @OA\RequestBody( + * @OA\MediaType( + * mediaType="multipart/form-data", + * @OA\Schema( + * required={"tasks"}, + * @OA\Property( + * property="user_id", + * type="integer", + * description="Идентификатор пользователя", + * ), + * @OA\Property( + * property="created_at", + * type="Date", + * description="Идентификатор пользователя", + * ), + * @OA\Property( + * property="difficulties", + * type="string", + * description="Описание сложностей возникших при выполнении задач", + * ), + * @OA\Property( + * property="tomorrow", + * type="string", + * description="Описание планов на завтра", + * ), + * @OA\Property( + * property="Статус", + * type="integer", + * description="Статус", + * ), + * @OA\Property( + * property="project_id", + * type="integer", + * description="Идентификатор проекта", + * ), + * @OA\Property( + * property="company_id", + * type="integer", + * description="Идентификатор компании", + * ), + * @OA\Property( + * property="tasks[]", + * type="array", + * description="Массив выполненых задач", + * @OA\Items( + * type="object", + * @OA\Property( + * property="task", + * description="Название задачи", + * type="string", + * ), + * @OA\Property( + * property="hours_spent", + * description="Затраченное количество часов", + * type="string", + * ), + * @OA\Property( + * property="minutes_spent", + * description="Затраченное количество минут", + * type="string", + * ) + * ) + * + * ), + * ), + * ), * ), + * * @OA\Response( * response=200, * description="Возвращает объект Запроса", @@ -267,11 +253,12 @@ class ReportsController extends ApiController throw new BadRequestHttpException('Нет параметра tasks'); } - if(!isset($params['user_card_id'])){ - $userCard = UserCard::find()->where(['id_user' => Yii::$app->user->id])->one(); - if($userCard){ - $params['user_card_id'] = $userCard->id; - } + if(!isset($params['user_id'])){ + $params['user_id'] = Yii::$app->user->id; + } + + if (!isset($params['created_at'])){ + $params['created_at'] = date("Y-m-d"); } $reportsModel = new Reports(); @@ -283,7 +270,7 @@ class ReportsController extends ApiController $tasks = $params['tasks']; foreach ($tasks as $task) { $reportsTask = new ReportsTask(); - $reportsTask->attributes = $task; + $reportsTask->load($task, ''); $reportsTask->report_id = $reportsModel->id; $reportsTask->created_at = $reportsTask->created_at ?? strtotime($reportsModel->created_at); $reportsTask->status = $reportsTask->status ?? 1; @@ -298,26 +285,21 @@ class ReportsController extends ApiController /** - * @OA\Get(path="/user-response/delete", + * @OA\Delete (path="/reports/delete", * summary="Удаление отчёта", * description="Осуществляет удаление отчёта", * security={ * {"bearerAuth": {}} * }, * tags={"Reports"}, - * @OA\RequestBody( - * @OA\MediaType( - * mediaType="application/x-www-form-urlencoded", - * @OA\Schema( - * required={"id"}, - * @OA\Property( - * property="id", - * type="integer", - * description="Идентификатор отчётая", - * nullable=false, - * ), - * ), - * ), + * @OA\Parameter( + * name="id", + * description="Идентификатор отчета", + * in="query", + * required=true, + * @OA\Schema( + * type="integer", + * ) * ), * * @OA\Response( @@ -331,10 +313,8 @@ class ReportsController extends ApiController * @throws \Throwable * @throws \yii\db\StaleObjectException */ - public function actionDelete() + public function actionDelete($id): bool { - $id = Yii::$app->request->get('id'); - $report = Reports::findOne($id); if(null === $report) { @@ -349,7 +329,7 @@ class ReportsController extends ApiController } /** - * @OA\Get(path="/reports/update", + * @OA\Put (path="/reports/update", * summary="Обновление отчёта", * description="Метод для Обновления отчёта", * security={ @@ -365,50 +345,61 @@ class ReportsController extends ApiController * type="integer", * ) * ), - * @OA\Parameter( - * name="created_at", - * in="query", - * required=false, - * description="Дата создания (yyyy-mm-dd)", - * @OA\Schema( - * type="DateTime", - * ) - * ), - * @OA\Parameter( - * name="today", - * in="query", - * required=false, - * description="Сделанное сегодня", - * @OA\Schema( - * type="string", - * ) - * ), - * @OA\Parameter( - * name="difficulties", - * in="query", - * required=false, - * description="Описание сложностей возникших при выполнении задач", - * @OA\Schema( - * type="string", - * ) - * ), - * @OA\Parameter( - * name="tomorrow", - * in="query", - * required=false, - * description="Описание планов на завтра", - * @OA\Schema( - * type="string", - * ) - * ), - * @OA\Parameter( - * name="status", - * in="query", - * required=false, - * description="Статус", - * @OA\Schema( - * type="integer", - * ) + * @OA\RequestBody( + * @OA\MediaType( + * mediaType="application/x-www-form-urlencoded", + * @OA\Schema( + * required={}, + * @OA\Property( + * property="created_at", + * type="DateTime", + * description="Дата создания (yyyy-mm-dd)", + * ), + * @OA\Property( + * property="today", + * type="string", + * description="Сделанное сегодня", + * ), + * @OA\Property( + * property="difficulties", + * type="string", + * description="Описание сложностей возникших при выполнении задач", + * ), + * @OA\Property( + * property="tomorrow", + * type="string", + * description="Описание планов на завтра", + * ), + * @OA\Property( + * property="status", + * type="integer", + * description="Статус", + * ), + * @OA\Property( + * property="tasks[]", + * type="array", + * description="Массив выполненых задач", + * @OA\Items( + * type="object", + * @OA\Property( + * property="task", + * description="Название задачи", + * type="string", + * ), + * @OA\Property( + * property="hours_spent", + * description="Затраченное количество часов", + * type="string", + * ), + * @OA\Property( + * property="minutes_spent", + * description="Затраченное количество минут", + * type="string", + * ), + * ), + * ), + * ), + * ), * ), * @OA\Response( * response=200, @@ -418,26 +409,30 @@ class ReportsController extends ApiController * @OA\Schema(ref="#/components/schemas/ReportsResponseCreateExample"), * ), * ), - * ) + * ), * * @return array * @throws BadRequestHttpException * @throws NotFoundHttpException */ - public function actionUpdate(): array + public function actionUpdate($id): array { - $params = Yii::$app->request->get(); + $params = Yii::$app->getRequest()->getBodyParams(); + $reportsModel = Reports::findone($id); - $reportsModel = Reports::findone($params['id']); if(!isset($reportsModel)) { throw new NotFoundHttpException('report not found'); } - if(isset($params['user_card_id'])) { + if (!isset($params['tasks'])){ + throw new BadRequestHttpException('Нет параметра tasks'); + } + + if(isset($params['user_id'])) { throw new \RuntimeException('constraint by user_card_id'); } - $reportsModel->attributes = $params; + $reportsModel->load($params, ''); if(!$reportsModel->validate()){ throw new BadRequestHttpException(json_encode($reportsModel->errors)); @@ -445,6 +440,20 @@ class ReportsController extends ApiController $reportsModel->save(); + ReportsTask::deleteAll(['report_id' => $reportsModel->id]); + foreach ($params['tasks'] as $task) { + $reportsTask = new ReportsTask(); + $reportsTask->load($task, ''); + $reportsTask->report_id = $reportsModel->id; + $reportsTask->created_at = $reportsTask->created_at ?? strtotime($reportsModel->created_at); + $reportsTask->status = $reportsTask->status ?? 1; + + if(!$reportsTask->validate() ){ + throw new BadRequestHttpException(json_encode($reportsTask->errors)); + } + $reportsTask->save(); + } + return $reportsModel->toArray(); } diff --git a/frontend/modules/api/models/ReportSearchForm.php b/frontend/modules/api/models/ReportSearchForm.php index f595aab..001c8ef 100755 --- a/frontend/modules/api/models/ReportSearchForm.php +++ b/frontend/modules/api/models/ReportSearchForm.php @@ -3,6 +3,7 @@ namespace frontend\modules\api\models; +use common\classes\Debug; use common\models\Reports; use yii\base\Model; @@ -10,6 +11,7 @@ use yii\base\Model; class ReportSearchForm extends Model { public $user_card_id; + public $user_id; public $limit; public $offset; /** @var string */ @@ -22,6 +24,7 @@ class ReportSearchForm extends Model $this->limit = 10; $this->offset = 0; $this->user_card_id = null; + $this->user_id = null; $this->toDate = date('Y-m-d'); $this->fromDate = date('Y-m-d'); @@ -36,7 +39,7 @@ class ReportSearchForm extends Model [['byDate'], 'safe'], [['fromDate', 'toDate', 'date'], 'string'], // [['fromDate', 'toDate', 'date'], 'date', 'format' => 'php:Y-m-d'], - [[ 'user_card_id'], 'integer', 'min' => 0], + [[ 'user_card_id', 'user_id'], 'integer', 'min' => 0], ]; } @@ -48,8 +51,8 @@ class ReportSearchForm extends Model $queryBuilder->andWhere(['between', 'reports.created_at', $this->fromDate, $this->toDate]); } - if (isset($this->user_card_id)) { - $queryBuilder->andWhere(['reports.user_card_id' => $this->user_card_id]); + if (isset($this->user_id)) { + $queryBuilder->andWhere(['reports.user_id' => $this->user_id]); } $queryBuilder->limit($this->limit) @@ -61,7 +64,7 @@ class ReportSearchForm extends Model public function findByDate() { return Reports::find()->with('task') - ->where(['reports.user_card_id' => $this->user_card_id]) + ->where(['reports.user_id' => $this->user_id]) ->andWhere(['reports.created_at' => $this->date]) ->asArray()->all(); } @@ -69,7 +72,7 @@ class ReportSearchForm extends Model public function reportsByDate() { return Reports::find()->with('task') - ->where(['reports.user_card_id' => $this->user_card_id]) + ->where(['reports.user_id' => $this->user_id]) ->andWhere(['between', 'reports.created_at', $this->fromDate, $this->toDate]) ->asArray()->all(); } diff --git a/frontend/modules/api/models/Reports.php b/frontend/modules/api/models/Reports.php index 5628fda..e749a8d 100644 --- a/frontend/modules/api/models/Reports.php +++ b/frontend/modules/api/models/Reports.php @@ -35,6 +35,12 @@ namespace frontend\modules\api\models; * description="ID карты(профиля) пользователя" * ), * @OA\Property( + * property="user_id", + * type="integer", + * example=23, + * description="ID пользователя" + * ), + * @OA\Property( * property="project_id", * type="integer", * example=1, @@ -75,6 +81,10 @@ namespace frontend\modules\api\models; * type="integer", * ), * @OA\Property( + * property="user_id", + * type="integer", + * ), + * @OA\Property( * property="project_id", * type="integer", * ), @@ -111,6 +121,10 @@ namespace frontend\modules\api\models; * type="integer", * ), * @OA\Property( + * property="user_id", + * type="integer", + * ), + * @OA\Property( * property="project_id", * type="integer", * ),