123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565 |
- <?php
- namespace app\controllers;
- use Yii;
- use yii\db\Query;
- use yii\web\BadRequestHttpException;
- use yii\web\Response;
- use app\models\entity\Accounts;
- use app\models\entity\Tasks;
- use app\models\entity\Tasktypes;
- use app\models\entity\ar\TargetObject;
- use app\models\entity\ar\Scenario;
- use app\models\entity\ar\Stage;
- use app\models\entity\ar\Media;
- class ArealityController extends MainController
- {
- const ADMIN_ONLY_ERROR = 'Функция доступна только администраторам';
- const SAVE_ERROR = 'Ошибка сохранения';
- const OBJECT_NOT_FOUND = 'Объект не найден';
- const INVALID_JSON = 'Неверный формат JSON';
- /** @var Accounts */
- private $user;
- private $response = ['login' => '', 'response' => [], 'error' => []];
- /**
- * @param $action
- * @return bool
- * @throws \yii\web\HttpException
- */
- public function beforeAction($action)
- {
- parent::beforeAction($action);
- $key = Yii::$app->request->headers->get('uuid-key');
- $this->checkAuth($key);
- Yii::$app->response->format = Response::FORMAT_JSON;
- $login = Yii::$app->request->post('login');
- $password = Yii::$app->request->post('password');
- $this->response['login'] = $login;
- $this->user = $this->getAccount($login, $password);
- return true;
- }
- /**
- * Получение данных
- *
- * @return array
- */
- public function actionGetardata()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- //objects
- /** @var TargetObject $object */
- foreach(TargetObject::findAll(['status' => 1]) as $object) {
- $this->response['response']['objects'][] = $object->asArray();
- }
- //scenarios
- $scenarios = [];
- foreach (Scenario::find()->all() as $scenario) {
- $scenarioArr = $scenario->asArray();
- $stages = [];
- /** @var Scenario $scenario */
- foreach ($scenario->stages as $stage) {
- $stages[] = $stage->asArray(true);
- }
- $scenarioArr['stages'] = $stages;
- $scenarios[] = $scenarioArr;
- }
- $this->response['response']['scenarios'] = $scenarios;
- //all_types
- $typesArr = Tasktypes::find()
- ->select(['id', 'name', 'scenario_id'])
- ->where(['company' => $this->user->company])
- ->all()
- ;
- $this->response['response']['all_types'] = $typesArr;
- return $this->response;
- }
- /**
- * Добавление объекта.
- *
- * @return array
- */
- public function actionAddobject()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- $object = new TargetObject();
- $object->fillFromArray($params);
- if ($object->save()) {
- $this->response['response'] = $object->id;
- } else {
- $this->response['error'] = self::SAVE_ERROR;
- }
- return $this->response;
- }
- /**
- * Редактирование объекта.
- *
- * @return array
- */
- public function actionEditobject()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- $this->update($params, TargetObject::class);
- return $this->response;
- }
- /**
- * Удаление объекта.
- *
- * @throws \Throwable
- * @return array
- */
- public function actionRemoveobject()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $objectId = (int)Yii::$app->request->post('id');
- //Ищем все задачи с присланным objectId
- $tasks = Tasks::find()->where(['object_id' => $objectId])->all();
- //Обнуляем все эти objectId
- foreach ($tasks as $task) {
- $task->object_id = null;
- $task->save();
- }
- //Делаем объект не активным
- $object = TargetObject::findOne($objectId);
- if (!$object) {
- $this->response['error'] = 'Объект не найден';
- } else {
- $object->status = 0;
- $object->save();
- $this->response['response'] = 'Объект удалён';
- }
- return $this->response;
- }
- /**
- * Добавление этапа.
- *
- * @return array
- */
- public function actionAddstage()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- $stage = new Stage();
- $stage->fillFromArray($params);
- if ($stage->save()) {
- $this->response['response'] = $stage->id;
- } else {
- $this->response['error'] = self::SAVE_ERROR;
- }
- return $this->response;
- }
- /**
- * Редактирование этапа.
- *
- * @return array
- */
- public function actionEditstage()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- $this->update($params, Stage::class);
- return $this->response;
- }
- /**
- * Удаление этапа.
- *
- * @throws \Throwable
- * @return array
- */
- public function actionRemovestage()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $stageId = (int)Yii::$app->request->post('id');
- $stage = Stage::findOne($stageId);
- if ($stage) {
- $stage->delete();
- $this->response['response'] = 'Этап удалён';
- } else {
- $this->response['error'] = 'Этап не найден';
- }
- return $this->response;
- }
- /**
- * Добавление сценария.
- *
- * @return array
- */
- public function actionAddscenario()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- $scenario = new Scenario();
- $scenario->fillFromArray($params);
- if ($scenario->save()) {
- $this->response['response'] = $scenario->id;
- } else {
- $this->response['error'] = self::SAVE_ERROR;
- }
- return $this->response;
- }
- /**
- * Редактирование сценария.
- *
- * @return array
- */
- public function actionEditscenario()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- $this->update($params, Scenario::class);
- return $this->response;
- }
- /**
- * Удаление сценария.
- *
- * @throws \Throwable
- * @return array
- */
- public function actionRemovescenario()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $scenarioId = (int)Yii::$app->request->post('id');
- $scenario = Scenario::findOne($scenarioId);
- if ($scenario) {
- $scenario->delete();
- $this->response['response'] = 'Сценарий удалён';
- } else {
- $this->response['error'] = 'Сценарий не найден';
- }
- return $this->response;
- }
- /**
- * Добавление медиа.
- *
- * @return array
- */
- public function actionAddmedia()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- if ($params) {
- $media = new Media();
- $media->fillFromArray($params);
- if ($media->save()) {
- $this->response['response'] = $media->id;
- } else {
- $this->response['error'] = self::SAVE_ERROR;
- }
- } else {
- $this->response['error'] = self::INVALID_JSON;
- }
- return $this->response;
- }
- /**
- * Редактирование медиа.
- *
- * @return array
- */
- public function actionEditmedia()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- $this->update($params, Media::class);
- return $this->response;
- }
- /**
- * Удаление медиа.
- *
- * @throws \Throwable
- * @return array
- */
- public function actionRemovemedia()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $mediaId = (int)Yii::$app->request->post('id');
- $media = Media::findOne($mediaId);
- if ($media) {
- $media->delete();
- $this->response['response'] = 'Медиаданные удалёны';
- } else {
- $this->response['error'] = 'Медиаданные не найдены';
- }
- return $this->response;
- }
- /**
- * Получение списка команд\задач, относящихся к компании пользователя и имеющие принадлежность к сценарию
- *
- * @return array
- */
- public function actionCommands()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- //Запросы 30 секунд выполняется.
- // $tasks = Tasks::find()->all();
- //
- // /** @var Tasks $task */
- // foreach ($tasks as $task) {
- // $companyId = $task->accounts->company_id;
- // $scenarioId = $task->tasktypes->scenario_id;
- // if ($companyId == $this->user->company && $scenarioId) {
- // $this->response['response'][] = [
- // 'command_id' => $task->id,
- // 'name_command' => $task->tasktypes->name,
- // 'scenario_id' => $task->tasktypes->scenario_id,
- // ];
- // }
- // }
- //
- // return $this->response;
- $query = new Query();
- $query->select('tt.id as command_id, ttt.name as name_command, tt.scenario_id')
- ->from(Accounts::tableName() . ' ta')
- ->leftJoin(Tasks::tableName() . ' tt', 'ta.id = tt.assignees_arr')
- ->innerJoin(Tasktypes::tableName() . ' ttt', 'ttt.id = tt.type')
- ->where(['ta.company' => $this->user->company])
- ->andWhere(['>', 'tt.scenario_id', 0])
- ;
- $this->response['response'] = $query->all();
- return $this->response;
- }
- /**
- * Присваивает задаче сценарий
- *
- * @return array
- * @throws BadRequestHttpException
- */
- public function actionSetscenario()
- {
- if (!$this->user->isAdmin()) {
- $this->response['error'] = self::ADMIN_ONLY_ERROR;
- return $this->response;
- }
- $params = json_decode(Yii::$app->request->post('params'), true);
- $taskTypeIds = $params['tasktypes'];
- $scenarioId = (int)$params['id_scenario'];
- if (!($params && $taskTypeIds && $scenarioId)) {
- throw new BadRequestHttpException('', 400);
- }
- $taskTypes = Tasktypes::findAll(['scenario_id' => $scenarioId]);
- foreach ($taskTypes as $type) {
- $type->scenario_id = null;
- $type->save();
- }
- $taskTypes = Tasktypes::findAll($taskTypeIds);
- foreach ($taskTypes as $taskType) {
- $taskType->scenario_id = $scenarioId;
- $taskType->save();
- $this->response['response']['tasktypes'][] = $taskType->id;
- }
- return $this->response;
- }
- public function getAccount($login, $password)
- {
- return Accounts::findOne(['login' => $login, 'password' => md5($password)]);
- }
- /**
- * Получение команд\задач, по их ID
- *
- * @return array
- */
- public function actionCommand()
- {
- $id = Yii::$app->request->post('id');
- $task = Tasks::findOne($id);
- if ($task) {
- $result = [];
- $result['command_id'] = $task->id;
- $result['name_command'] = $task->tasktypes->name;
- $result['scenario_id'] = $task->tasktypes->scenario_id ?? 0;
- if ($scenario = Scenario::findOne($result['scenario_id'])) {
- $result['name'] = $scenario->name;
- $result['stages'] = [];
- foreach ($scenario->stages as $stage) {
- $stageArr = $stage->asArray(true);
- if ($stage->object) {
- $stageArr['object']['id'] = $stage->object->id;
- $stageArr['object']['object_name'] = $stage->object->name;
- $stageArr['object']['name_display'] = $stage->object->name_display;
- $stageArr['object']['target_name_xml'] = $stage->object->target_name_xml;
- $stageArr['object']['type'] = $stage->object->type;
- }
- $result['stages'][] = $stageArr;
- }
- }
- $this->response['response'] = $result;
- } else {
- $this->response['error'] = self::OBJECT_NOT_FOUND;
- }
- return $this->response;
- }
- /**
- * Обновляет один из объектов (TargetObject, Scenario, Stage, Media). Если объект не существует
- * заполняет $this->response['error']. В случае успеха записывает в $this->response['response'] id объекта.
- * Ксасс указанный в $type содлжен содержать метод fillFromArray($params)
- *
- * @param array $params
- * @param string $type
- * @return bool
- */
- private function update($params, $type = '')
- {
- switch ($type) {
- case TargetObject::class:
- $object = TargetObject::findOne($params['id']);
- break;
- case Scenario::class:
- $object = Scenario::findOne($params['id']);
- break;
- case Stage::class:
- $object = Stage::findOne($params['id']);
- break;
- default:
- $object = Media::findOne($params['id']);
- break;
- }
- if (!$object) {
- $this->response['error'] = self::OBJECT_NOT_FOUND;
- return false;
- }
- $object->fillFromArray($params);
- if ($object->save()) {
- $this->response['response'] = $object->id;
- } else {
- $this->response['error'] = self::SAVE_ERROR;
- }
- return true;
- }
- }
|