ArealityController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. <?php
  2. namespace app\controllers;
  3. use Yii;
  4. use yii\db\Query;
  5. use yii\web\BadRequestHttpException;
  6. use yii\web\Response;
  7. use app\models\entity\Accounts;
  8. use app\models\entity\Tasks;
  9. use app\models\entity\Tasktypes;
  10. use app\models\entity\ar\TargetObject;
  11. use app\models\entity\ar\Scenario;
  12. use app\models\entity\ar\Stage;
  13. use app\models\entity\ar\Media;
  14. class ArealityController extends MainController
  15. {
  16. const ADMIN_ONLY_ERROR = 'Функция доступна только администраторам';
  17. const SAVE_ERROR = 'Ошибка сохранения';
  18. const OBJECT_NOT_FOUND = 'Объект не найден';
  19. const INVALID_JSON = 'Неверный формат JSON';
  20. /** @var Accounts */
  21. private $user;
  22. private $response = ['login' => '', 'response' => [], 'error' => []];
  23. /**
  24. * @param $action
  25. * @return bool
  26. * @throws \yii\web\HttpException
  27. */
  28. public function beforeAction($action)
  29. {
  30. parent::beforeAction($action);
  31. $key = Yii::$app->request->headers->get('uuid-key');
  32. $this->checkAuth($key);
  33. Yii::$app->response->format = Response::FORMAT_JSON;
  34. $login = Yii::$app->request->post('login');
  35. $password = Yii::$app->request->post('password');
  36. $this->response['login'] = $login;
  37. $this->user = $this->getAccount($login, $password);
  38. return true;
  39. }
  40. /**
  41. * Получение данных
  42. *
  43. * @return array
  44. */
  45. public function actionGetardata()
  46. {
  47. if (!$this->user->isAdmin()) {
  48. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  49. return $this->response;
  50. }
  51. //objects
  52. /** @var TargetObject $object */
  53. foreach(TargetObject::findAll(['status' => 1]) as $object) {
  54. $this->response['response']['objects'][] = $object->asArray();
  55. }
  56. //scenarios
  57. $scenarios = [];
  58. foreach (Scenario::find()->all() as $scenario) {
  59. $scenarioArr = $scenario->asArray();
  60. $stages = [];
  61. /** @var Scenario $scenario */
  62. foreach ($scenario->stages as $stage) {
  63. $stages[] = $stage->asArray(true);
  64. }
  65. $scenarioArr['stages'] = $stages;
  66. $scenarios[] = $scenarioArr;
  67. }
  68. $this->response['response']['scenarios'] = $scenarios;
  69. //all_types
  70. $typesArr = Tasktypes::find()
  71. ->select(['id', 'name', 'scenario_id'])
  72. ->where(['company' => $this->user->company])
  73. ->all()
  74. ;
  75. $this->response['response']['all_types'] = $typesArr;
  76. return $this->response;
  77. }
  78. /**
  79. * Добавление объекта.
  80. *
  81. * @return array
  82. */
  83. public function actionAddobject()
  84. {
  85. if (!$this->user->isAdmin()) {
  86. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  87. return $this->response;
  88. }
  89. $params = json_decode(Yii::$app->request->post('params'), true);
  90. $object = new TargetObject();
  91. $object->fillFromArray($params);
  92. if ($object->save()) {
  93. $this->response['response'] = $object->id;
  94. } else {
  95. $this->response['error'] = self::SAVE_ERROR;
  96. }
  97. return $this->response;
  98. }
  99. /**
  100. * Редактирование объекта.
  101. *
  102. * @return array
  103. */
  104. public function actionEditobject()
  105. {
  106. if (!$this->user->isAdmin()) {
  107. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  108. return $this->response;
  109. }
  110. $params = json_decode(Yii::$app->request->post('params'), true);
  111. $this->update($params, TargetObject::class);
  112. return $this->response;
  113. }
  114. /**
  115. * Удаление объекта.
  116. *
  117. * @throws \Throwable
  118. * @return array
  119. */
  120. public function actionRemoveobject()
  121. {
  122. if (!$this->user->isAdmin()) {
  123. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  124. return $this->response;
  125. }
  126. $objectId = (int)Yii::$app->request->post('id');
  127. //Ищем все задачи с присланным objectId
  128. $tasks = Tasks::find()->where(['object_id' => $objectId])->all();
  129. //Обнуляем все эти objectId
  130. foreach ($tasks as $task) {
  131. $task->object_id = null;
  132. $task->save();
  133. }
  134. //Делаем объект не активным
  135. $object = TargetObject::findOne($objectId);
  136. if (!$object) {
  137. $this->response['error'] = 'Объект не найден';
  138. } else {
  139. $object->status = 0;
  140. $object->save();
  141. $this->response['response'] = 'Объект удалён';
  142. }
  143. return $this->response;
  144. }
  145. /**
  146. * Добавление этапа.
  147. *
  148. * @return array
  149. */
  150. public function actionAddstage()
  151. {
  152. if (!$this->user->isAdmin()) {
  153. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  154. return $this->response;
  155. }
  156. $params = json_decode(Yii::$app->request->post('params'), true);
  157. $stage = new Stage();
  158. $stage->fillFromArray($params);
  159. if ($stage->save()) {
  160. $this->response['response'] = $stage->id;
  161. } else {
  162. $this->response['error'] = self::SAVE_ERROR;
  163. }
  164. return $this->response;
  165. }
  166. /**
  167. * Редактирование этапа.
  168. *
  169. * @return array
  170. */
  171. public function actionEditstage()
  172. {
  173. if (!$this->user->isAdmin()) {
  174. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  175. return $this->response;
  176. }
  177. $params = json_decode(Yii::$app->request->post('params'), true);
  178. $this->update($params, Stage::class);
  179. return $this->response;
  180. }
  181. /**
  182. * Удаление этапа.
  183. *
  184. * @throws \Throwable
  185. * @return array
  186. */
  187. public function actionRemovestage()
  188. {
  189. if (!$this->user->isAdmin()) {
  190. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  191. return $this->response;
  192. }
  193. $stageId = (int)Yii::$app->request->post('id');
  194. $stage = Stage::findOne($stageId);
  195. if ($stage) {
  196. $stage->delete();
  197. $this->response['response'] = 'Этап удалён';
  198. } else {
  199. $this->response['error'] = 'Этап не найден';
  200. }
  201. return $this->response;
  202. }
  203. /**
  204. * Добавление сценария.
  205. *
  206. * @return array
  207. */
  208. public function actionAddscenario()
  209. {
  210. if (!$this->user->isAdmin()) {
  211. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  212. return $this->response;
  213. }
  214. $params = json_decode(Yii::$app->request->post('params'), true);
  215. $scenario = new Scenario();
  216. $scenario->fillFromArray($params);
  217. if ($scenario->save()) {
  218. $this->response['response'] = $scenario->id;
  219. } else {
  220. $this->response['error'] = self::SAVE_ERROR;
  221. }
  222. return $this->response;
  223. }
  224. /**
  225. * Редактирование сценария.
  226. *
  227. * @return array
  228. */
  229. public function actionEditscenario()
  230. {
  231. if (!$this->user->isAdmin()) {
  232. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  233. return $this->response;
  234. }
  235. $params = json_decode(Yii::$app->request->post('params'), true);
  236. $this->update($params, Scenario::class);
  237. return $this->response;
  238. }
  239. /**
  240. * Удаление сценария.
  241. *
  242. * @throws \Throwable
  243. * @return array
  244. */
  245. public function actionRemovescenario()
  246. {
  247. if (!$this->user->isAdmin()) {
  248. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  249. return $this->response;
  250. }
  251. $scenarioId = (int)Yii::$app->request->post('id');
  252. $scenario = Scenario::findOne($scenarioId);
  253. if ($scenario) {
  254. $scenario->delete();
  255. $this->response['response'] = 'Сценарий удалён';
  256. } else {
  257. $this->response['error'] = 'Сценарий не найден';
  258. }
  259. return $this->response;
  260. }
  261. /**
  262. * Добавление медиа.
  263. *
  264. * @return array
  265. */
  266. public function actionAddmedia()
  267. {
  268. if (!$this->user->isAdmin()) {
  269. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  270. return $this->response;
  271. }
  272. $params = json_decode(Yii::$app->request->post('params'), true);
  273. if ($params) {
  274. $media = new Media();
  275. $media->fillFromArray($params);
  276. if ($media->save()) {
  277. $this->response['response'] = $media->id;
  278. } else {
  279. $this->response['error'] = self::SAVE_ERROR;
  280. }
  281. } else {
  282. $this->response['error'] = self::INVALID_JSON;
  283. }
  284. return $this->response;
  285. }
  286. /**
  287. * Редактирование медиа.
  288. *
  289. * @return array
  290. */
  291. public function actionEditmedia()
  292. {
  293. if (!$this->user->isAdmin()) {
  294. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  295. return $this->response;
  296. }
  297. $params = json_decode(Yii::$app->request->post('params'), true);
  298. $this->update($params, Media::class);
  299. return $this->response;
  300. }
  301. /**
  302. * Удаление медиа.
  303. *
  304. * @throws \Throwable
  305. * @return array
  306. */
  307. public function actionRemovemedia()
  308. {
  309. if (!$this->user->isAdmin()) {
  310. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  311. return $this->response;
  312. }
  313. $mediaId = (int)Yii::$app->request->post('id');
  314. $media = Media::findOne($mediaId);
  315. if ($media) {
  316. $media->delete();
  317. $this->response['response'] = 'Медиаданные удалёны';
  318. } else {
  319. $this->response['error'] = 'Медиаданные не найдены';
  320. }
  321. return $this->response;
  322. }
  323. /**
  324. * Получение списка команд\задач, относящихся к компании пользователя и имеющие принадлежность к сценарию
  325. *
  326. * @return array
  327. */
  328. public function actionCommands()
  329. {
  330. if (!$this->user->isAdmin()) {
  331. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  332. return $this->response;
  333. }
  334. //Запросы 30 секунд выполняется.
  335. // $tasks = Tasks::find()->all();
  336. //
  337. // /** @var Tasks $task */
  338. // foreach ($tasks as $task) {
  339. // $companyId = $task->accounts->company_id;
  340. // $scenarioId = $task->tasktypes->scenario_id;
  341. // if ($companyId == $this->user->company && $scenarioId) {
  342. // $this->response['response'][] = [
  343. // 'command_id' => $task->id,
  344. // 'name_command' => $task->tasktypes->name,
  345. // 'scenario_id' => $task->tasktypes->scenario_id,
  346. // ];
  347. // }
  348. // }
  349. //
  350. // return $this->response;
  351. $query = new Query();
  352. $query->select('tt.id as command_id, ttt.name as name_command, tt.scenario_id')
  353. ->from(Accounts::tableName() . ' ta')
  354. ->leftJoin(Tasks::tableName() . ' tt', 'ta.id = tt.assignees_arr')
  355. ->innerJoin(Tasktypes::tableName() . ' ttt', 'ttt.id = tt.type')
  356. ->where(['ta.company' => $this->user->company])
  357. ->andWhere(['>', 'tt.scenario_id', 0])
  358. ;
  359. $this->response['response'] = $query->all();
  360. return $this->response;
  361. }
  362. /**
  363. * Присваивает задаче сценарий
  364. *
  365. * @return array
  366. * @throws BadRequestHttpException
  367. */
  368. public function actionSetscenario()
  369. {
  370. if (!$this->user->isAdmin()) {
  371. $this->response['error'] = self::ADMIN_ONLY_ERROR;
  372. return $this->response;
  373. }
  374. $params = json_decode(Yii::$app->request->post('params'), true);
  375. $taskTypeIds = $params['tasktypes'];
  376. $scenarioId = (int)$params['id_scenario'];
  377. if (!($params && $taskTypeIds && $scenarioId)) {
  378. throw new BadRequestHttpException('', 400);
  379. }
  380. $taskTypes = Tasktypes::findAll(['scenario_id' => $scenarioId]);
  381. foreach ($taskTypes as $type) {
  382. $type->scenario_id = null;
  383. $type->save();
  384. }
  385. $taskTypes = Tasktypes::findAll($taskTypeIds);
  386. foreach ($taskTypes as $taskType) {
  387. $taskType->scenario_id = $scenarioId;
  388. $taskType->save();
  389. $this->response['response']['tasktypes'][] = $taskType->id;
  390. }
  391. return $this->response;
  392. }
  393. public function getAccount($login, $password)
  394. {
  395. return Accounts::findOne(['login' => $login, 'password' => md5($password)]);
  396. }
  397. /**
  398. * Получение команд\задач, по их ID
  399. *
  400. * @return array
  401. */
  402. public function actionCommand()
  403. {
  404. $id = Yii::$app->request->post('id');
  405. $task = Tasks::findOne($id);
  406. if ($task) {
  407. $result = [];
  408. $result['command_id'] = $task->id;
  409. $result['name_command'] = $task->tasktypes->name;
  410. $result['scenario_id'] = $task->tasktypes->scenario_id ?? 0;
  411. if ($scenario = Scenario::findOne($result['scenario_id'])) {
  412. $result['name'] = $scenario->name;
  413. $result['stages'] = [];
  414. foreach ($scenario->stages as $stage) {
  415. $stageArr = $stage->asArray(true);
  416. if ($stage->object) {
  417. $stageArr['object']['id'] = $stage->object->id;
  418. $stageArr['object']['object_name'] = $stage->object->name;
  419. $stageArr['object']['name_display'] = $stage->object->name_display;
  420. $stageArr['object']['target_name_xml'] = $stage->object->target_name_xml;
  421. $stageArr['object']['type'] = $stage->object->type;
  422. }
  423. $result['stages'][] = $stageArr;
  424. }
  425. }
  426. $this->response['response'] = $result;
  427. } else {
  428. $this->response['error'] = self::OBJECT_NOT_FOUND;
  429. }
  430. return $this->response;
  431. }
  432. /**
  433. * Обновляет один из объектов (TargetObject, Scenario, Stage, Media). Если объект не существует
  434. * заполняет $this->response['error']. В случае успеха записывает в $this->response['response'] id объекта.
  435. * Ксасс указанный в $type содлжен содержать метод fillFromArray($params)
  436. *
  437. * @param array $params
  438. * @param string $type
  439. * @return bool
  440. */
  441. private function update($params, $type = '')
  442. {
  443. switch ($type) {
  444. case TargetObject::class:
  445. $object = TargetObject::findOne($params['id']);
  446. break;
  447. case Scenario::class:
  448. $object = Scenario::findOne($params['id']);
  449. break;
  450. case Stage::class:
  451. $object = Stage::findOne($params['id']);
  452. break;
  453. default:
  454. $object = Media::findOne($params['id']);
  455. break;
  456. }
  457. if (!$object) {
  458. $this->response['error'] = self::OBJECT_NOT_FOUND;
  459. return false;
  460. }
  461. $object->fillFromArray($params);
  462. if ($object->save()) {
  463. $this->response['response'] = $object->id;
  464. } else {
  465. $this->response['error'] = self::SAVE_ERROR;
  466. }
  467. return true;
  468. }
  469. }