ChampionshipsController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Age_group;
  4. use App\Championship;
  5. use App\Competence;
  6. use App\Criterion;
  7. use App\Http\Controllers\UserController;
  8. use App\Module;
  9. use App\Month;
  10. use App\Result;
  11. use App\User;
  12. use App\Member;
  13. use Validator;
  14. use Illuminate\Http\Request;
  15. class ChampionshipsController extends Controller
  16. {
  17. private $champ_id = NULL;
  18. /**
  19. * Метод для получения списка всех чемпионатов
  20. * @param Request $request
  21. * @return \Illuminate\Http\JsonResponse
  22. */
  23. public function all(Request $request)
  24. {
  25. /*
  26. * Делаем выборку чемпионатов
  27. */
  28. $championships = Championship::all();
  29. /*
  30. * Если чемпионаты не найдены, то ответ - 404
  31. */
  32. if (count($championships) === 0) {
  33. return response()
  34. ->json(["status" => false, "message" => "Rows not found"])
  35. ->setStatusCode(404, "Rows not found");
  36. }
  37. /*
  38. * Пустой массив для хранения списка чемпионатов
  39. */
  40. $championshipsList = [];
  41. /*
  42. * Перебираем список всех найденых чемпионатов
  43. */
  44. foreach ($championships as $championship) {
  45. /*
  46. * Упаковываем чемпионаты
  47. */
  48. $championshipsList[] = [
  49. "id" => $championship->id, //Идентификатор чемпионата
  50. "title" => $championship->title, //Название чемпионата
  51. "from" => $championship->from_date, //День старта чемпионата
  52. "to" => $championship->to_date, //День окончания чемпионата
  53. "month" => $championship->month()->first()->title, //Месяц
  54. "year" => $championship->year, //Год
  55. "group" => $championship->group, //Возрастная группа
  56. "status" => $championship->status, //Стутус данного чемпионата
  57. //Эксперт (организатор) чемпиоаната
  58. "expert" => [
  59. "id" => $championship->expert()->first()->id,
  60. "name" => $championship->expert()->first()->name,
  61. "position" => $championship->expert()->first()->position
  62. ],
  63. "competence" => $championship->competence()->first()->title, //Название компетенции
  64. "location" => $championship->location
  65. ];
  66. }
  67. /*
  68. * Возвращаем
  69. */
  70. return response()
  71. ->json($championshipsList)
  72. ->setStatusCode(200, "Championships List");
  73. }
  74. public function allByToken(Request $request)
  75. {
  76. /*
  77. * Загружаем пользователя, который выполняет действие
  78. */
  79. $expert = UserController::getUserByToken($request->bearerToken());
  80. /*
  81. * Если пользователь не имеет статус 1 (главный эксперт), возвращаем ошибку 403
  82. */
  83. if ($expert->position !== 1)
  84. return response()->json(["status" => false, "message" => "Permission denied"])->setStatusCode(403, 'Permission denied');
  85. /*
  86. * Делаем выборку чемпионатов
  87. */
  88. $championships = Championship::where('competence', $request->competence)
  89. ->where('year', $request->year)
  90. ->where('expert', $expert->id)
  91. ->get();
  92. /*
  93. * Если чемпионаты не найдены, то ответ - 404
  94. */
  95. if (count($championships) === 0) {
  96. return response()
  97. ->json(["status" => false, "message" => "Rows not found"])
  98. ->setStatusCode(404, "Rows not found");
  99. }
  100. /*
  101. * Пустой массив для хранения списка чемпионатов
  102. */
  103. $championshipsList = [];
  104. /*
  105. * Перебираем список всех найденых чемпионатов
  106. */
  107. foreach ($championships as $championship) {
  108. /*
  109. * Упаковываем чемпионаты
  110. */
  111. $championshipsList[] = [
  112. "id" => $championship->id, //Идентификатор чемпионата
  113. "title" => $championship->title, //Название чемпионата
  114. "from" => $championship->from_date, //День старта чемпионата
  115. "to" => $championship->to_date, //День окончания чемпионата
  116. "month" => $championship->month()->first()->title, //Месяц
  117. "year" => $championship->year, //Год
  118. "group" => $championship->group, //Возрастная группа
  119. "status" => $championship->status, //Стутус данного чемпионата
  120. //Эксперт (организатор) чемпиоаната
  121. "expert" => [
  122. "id" => $championship->expert()->first()->id,
  123. "name" => $championship->expert()->first()->name,
  124. "position" => $championship->expert()->first()->position
  125. ],
  126. "competence" => $championship->competence()->first()->title, //Название компетенции
  127. "location" => $championship->location
  128. ];
  129. }
  130. /*
  131. * Возвращаем
  132. */
  133. return response()
  134. ->json($championshipsList)
  135. ->setStatusCode(200, "Championships List");
  136. }
  137. /**
  138. * Метод для получения информации о чемпионате
  139. * @param $id
  140. * @return \Illuminate\Http\JsonResponse
  141. */
  142. public function one($id)
  143. {
  144. $this->champ_id = $id;
  145. /*
  146. * Ищем чемпионат по ID
  147. */
  148. $championship = Championship::find($this->champ_id);
  149. /*
  150. * Проверяем наличие чемпионата. Если его нет, возвращаем ошибку 404
  151. */
  152. if (!$championship)
  153. return response()
  154. ->json(["status" => false, "message" => "Championship not found"])
  155. ->setStatusCode(404, "Championship not found");
  156. $championshipRes = [
  157. "id" => $championship->id, //Идентификатор чемпионата
  158. "title" => $championship->title, //Название чемпионата
  159. "from" => $championship->from_date, //День старта чемпионата
  160. "to" => $championship->to_date, //День окончания чемпионата
  161. "month" => $championship->month()->first()->title, //Месяц
  162. "month_id" => $championship->month()->first()->id, //Месяц ID
  163. "year" => $championship->year, //Год
  164. "group" => $championship->group, //Возрастная группа
  165. "status" => $championship->status, //Стутус данного чемпионата
  166. "city" => $championship->city, //Стутус данного чемпионата
  167. "location" => $championship->location, //Место проведения чемпионата
  168. "competence" => $championship->competence()->first()->title, //Название компетенции
  169. "experts" => $championship->experts,
  170. "members" => $this->getResults(),
  171. "modules" => $championship->modules
  172. ];
  173. return response()
  174. ->json($championshipRes);
  175. }
  176. /**
  177. * Метод для получения результатов по идентификатору чемпионата
  178. * @return array
  179. */
  180. private function getResults() {
  181. $i = 0;
  182. /*
  183. * Список участников с результатами
  184. */
  185. $membersResults = [];
  186. $members = Member::where('championship', $this->champ_id)->get();
  187. /*
  188. * Загрузка всех модулей чемпионата
  189. */
  190. $modules = Module::where('championship', $this->champ_id)->get();
  191. /*
  192. * Перебираем всех участников и подсчитываем
  193. * баллы
  194. */
  195. foreach ($members as $member) {
  196. /*
  197. * Массив для хранения результатов
  198. * каждого модуля для участника
  199. */
  200. $modulesResults = [];
  201. /*
  202. * Переменная для подсчета общего кол-ва
  203. * очков участника
  204. */
  205. $allScore = 0;
  206. /*
  207. * Перебираем все модули
  208. */
  209. foreach ($modules as $module) {
  210. /*
  211. * Загружаем все критерии модуля
  212. */
  213. $criteria = Result::where('module_id', $module->id)
  214. ->where('member_id', $member->id)
  215. ->get();
  216. /*
  217. * Перемнная для хранения очков набранных
  218. * в данном модуле
  219. */
  220. $modulePoints = 0;
  221. /*
  222. * Перебираем критерии и складываем баллы
  223. */
  224. foreach ($criteria as $criterion) {
  225. /*
  226. * Складываем баллы в переменную $modulePoints
  227. */
  228. $modulePoints = $modulePoints + $criterion->points * 1;
  229. }
  230. /*
  231. * Складываем баллы в переменную с общим кол-вом
  232. * очков за все модули
  233. */
  234. $allScore = $allScore + $modulePoints;
  235. /*
  236. * Добавляем результаты и название модуля в массив $modulesResults
  237. */
  238. $modulesResults[] = [
  239. "title" => $module->title,
  240. "points" => round($modulePoints, 2)
  241. ];
  242. }
  243. /*
  244. * Добавляем пользователя в массив с результати
  245. * участников
  246. */
  247. $membersResults['member_' . $i] = [
  248. "member_id" => $member->id,
  249. "name" => $member->name,
  250. "university" => $member->university,
  251. "modules" => $modulesResults,
  252. "all_score" => round($allScore, 2)
  253. ];
  254. $i = $i + 1;
  255. }
  256. /*
  257. * Сортируем массив по ключу all_score (от лучшего результата к худшему)
  258. */
  259. $membersResults = collect($membersResults)
  260. ->sortBy('all_score')
  261. ->reverse()
  262. ->toArray();
  263. /*
  264. * Возвращаем массив с результатами
  265. */
  266. return $membersResults;
  267. }
  268. /**
  269. * Создание нового чемпионата
  270. * @param Request $request
  271. * @return \Illuminate\Http\JsonResponse
  272. */
  273. public function create(Request $request)
  274. {
  275. /*
  276. * Загружаем пользователя, который выполняет действие
  277. */
  278. $expert = UserController::getUserByToken($request->bearerToken());
  279. /*
  280. * Если пользователь не имеет статус 1 (главный эксперт), возвращаем ошибку 403
  281. */
  282. if ($expert->position !== 1)
  283. return response()->json(["status" => false, "message" => "Permission denied"])->setStatusCode(403, 'Permission denied');
  284. /*
  285. * Валидация полей
  286. */
  287. $nowYear = date('Y'); //Текущая дата
  288. $validator = Validator::make(
  289. $request->all(),
  290. [
  291. "title" => ['required'],
  292. "date_before" => ['required', 'numeric', 'max:31'],
  293. "date_after" => ['required', 'numeric', 'max:31'],
  294. "month" => ['required', 'numeric', 'max:12'],
  295. "year" => ['required', 'numeric', "max:$nowYear"],
  296. "location" => ['required'],
  297. "city" => ['required', 'numeric', 'max:3'],
  298. "competence" => ['required', 'numeric', 'max:200'],
  299. "age_group" => ['required', 'numeric', 'max:3']
  300. ]
  301. );
  302. /*
  303. * Проверяем результаты валидации
  304. */
  305. if ($validator->fails())
  306. return response()->json(["status" => false, "errors" => $validator->messages()])->setStatusCode(400, "Error fields");
  307. /*
  308. * Создаем экземпляр чемпионата и добавляем в базу данных
  309. */
  310. $champ = new Championship();
  311. $champ->fill([
  312. "title" => $request->title,
  313. "from_date" => $request->date_before,
  314. "to_date" => $request->date_after,
  315. "month" => $request->month,
  316. "year" => $request->year,
  317. "city" => $request->city,
  318. "group" => $request->age_group,
  319. "expert" => $expert->id,
  320. "competence" => $request->competence,
  321. "location" => $request->location,
  322. "status" => 1
  323. ]);
  324. $champ->save();
  325. /*
  326. * Успешный ответ
  327. */
  328. return response()->json(['status' => true, "message" => "Championship successfully registered"], 201);
  329. }
  330. public function update(Request $request, $id)
  331. {
  332. /*
  333. * Загружаем пользователя, который выполняет действие
  334. */
  335. $expert = UserController::getUserByToken($request->bearerToken());
  336. /*
  337. * Если пользователь не имеет статус 1 (главный эксперт), возвращаем ошибку 403
  338. */
  339. if ($expert->position !== 1)
  340. return response()->json(["status" => false, "message" => "Permission denied"])->setStatusCode(403, 'Permission denied');
  341. $champ = Championship::find($id);
  342. if (!$champ)
  343. return response()->json(["status" => false, "message" => "Championship not found"])->setStatusCode(404, 'Permission denied');
  344. if ($expert->position !== $champ->expert)
  345. return response()->json(["status" => false, "message" => "Permission denied"])->setStatusCode(403, 'Permission denied');
  346. /*
  347. * Валидация полей
  348. */
  349. $nowYear = date('Y'); //Текущий год
  350. $validator = Validator::make(
  351. $request->all(),
  352. [
  353. "title" => ['required'],
  354. "date_before" => ['required', 'numeric', 'max:31'],
  355. "date_after" => ['required', 'numeric', 'max:31'],
  356. "month" => ['required', 'numeric', 'max:12'],
  357. "year" => ['required', 'numeric', "max:$nowYear"],
  358. "location" => ['required'],
  359. "city" => ['required', 'numeric', 'max:3'],
  360. "age_group" => ['required', 'numeric', 'max:3'],
  361. "status" => ['required', 'numeric', 'max:3']
  362. ]
  363. );
  364. /*
  365. * Проверяем результаты валидации
  366. */
  367. if ($validator->fails())
  368. return response()->json(["status" => false, "errors" => $validator->messages()])->setStatusCode(400, "Error fields");
  369. $champ->title = $request->title;
  370. $champ->from_date = $request->date_before;
  371. $champ->to_date = $request->date_after;
  372. $champ->month = $request->month;
  373. $champ->year = $request->year;
  374. $champ->group = $request->age_group;
  375. $champ->status = $request->status;
  376. $champ->location = $request->location;
  377. $champ->city = $request->city;
  378. $champ->save();
  379. return response()->json(['status' => true, "message" => "Championship successfully updated"], 202);
  380. }
  381. public function addMember(Request $request, $id)
  382. {
  383. /*
  384. * Загружаем пользователя, который выполняет действие
  385. */
  386. $expert = UserController::getUserByToken($request->bearerToken());
  387. /*
  388. * Если пользователь не имеет статус 1 (главный эксперт), возвращаем ошибку 403
  389. */
  390. if ($expert->position !== 1)
  391. return response()->json(["status" => false, "message" => "Permission denied"])->setStatusCode(403, 'Permission denied');
  392. $champ = Championship::find($id);
  393. if (!$champ)
  394. return response()->json(["status" => false, "message" => "Championship not found"])->setStatusCode(404, 'Championship not found');
  395. if ($expert->position !== $champ->expert)
  396. return response()->json(["status" => false, "message" => "Permission denied"])->setStatusCode(403, 'Permission denied');
  397. $validator = Validator::make(
  398. $request->all(),
  399. [
  400. "name" => ['required'],
  401. "university" => ['required'],
  402. ]
  403. );
  404. /*
  405. * Проверяем результаты валидации
  406. */
  407. if ($validator->fails())
  408. return response()->json(["status" => false, "errors" => $validator->messages()])->setStatusCode(400, "Error fields");
  409. $member = new Member();
  410. $member->name = $request->name;
  411. $member->university = $request->university;
  412. $member->championship = $id;
  413. $member->save();
  414. return response()->json(['status' => true, "message" => "Member is added"], 201);
  415. }
  416. public function removeMember(Request $request, $champ_id, $member_id)
  417. {
  418. /*
  419. * Загружаем пользователя, который выполняет действие
  420. */
  421. $expert = UserController::getUserByToken($request->bearerToken());
  422. /*
  423. * Если пользователь не имеет статус 1 (главный эксперт), возвращаем ошибку 403
  424. */
  425. if ($expert->position !== 1)
  426. return response()
  427. ->json(["status" => false, "message" => "Permission denied"])
  428. ->setStatusCode(403, 'Permission denied');
  429. $champ = Championship::find($champ_id);
  430. if (!$champ)
  431. return response()
  432. ->json(["status" => false, "message" => "Championship not found"])
  433. ->setStatusCode(404, 'Championship not found');
  434. if ($expert->position !== $champ->expert)
  435. return response()
  436. ->json(["status" => false, "message" => "Permission denied"])
  437. ->setStatusCode(403, 'Permission denied');
  438. $member = Member::find($member_id);
  439. if (!$member)
  440. return response()
  441. ->json(["status" => false, "message" => "Member not found"])
  442. ->setStatusCode(404, 'Member not found');
  443. if ($member->championship != $champ->id)
  444. return response()
  445. ->json(["status" => false, "message" => "Member not found"])
  446. ->setStatusCode(404, 'Member not found');
  447. $member->delete();
  448. return response()
  449. ->json(["status" => false, "message" => "Member is deleted"])
  450. ->setStatusCode(200, 'Member is deleted');
  451. }
  452. public function updateMember(Request $request, $champ_id, $member_id)
  453. {
  454. /*
  455. * Загружаем пользователя, который выполняет действие
  456. */
  457. $expert = UserController::getUserByToken($request->bearerToken());
  458. /*
  459. * Если пользователь не имеет статус 1 (главный эксперт), возвращаем ошибку 403
  460. */
  461. if ($expert->position !== 1)
  462. return response()
  463. ->json(["status" => false, "message" => "Permission denied"])
  464. ->setStatusCode(403, 'Permission denied');
  465. $champ = Championship::find($champ_id);
  466. if (!$champ)
  467. return response()
  468. ->json(["status" => false, "message" => "Championship not found"])
  469. ->setStatusCode(404, 'Championship not found');
  470. if ($expert->position !== $champ->expert)
  471. return response()
  472. ->json(["status" => false, "message" => "Permission denied"])
  473. ->setStatusCode(403, 'Permission denied');
  474. $member = Member::find($member_id);
  475. if (!$member)
  476. return response()
  477. ->json(["status" => false, "message" => "Member not found"])
  478. ->setStatusCode(404, 'Member not found');
  479. if ($member->championship != $champ->id)
  480. return response()
  481. ->json(["status" => false, "message" => "Member not found"])
  482. ->setStatusCode(404, 'Member not found');
  483. $validator = Validator::make(
  484. $request->all(),
  485. [
  486. "name" => ['required'],
  487. "university" => ['required'],
  488. ]
  489. );
  490. /*
  491. * Проверяем результаты валидации
  492. */
  493. if ($validator->fails())
  494. return response()->json(["status" => false, "errors" => $validator->messages()])->setStatusCode(400, "Error fields");
  495. $member->name = $request->name;
  496. $member->university = $request->university;
  497. $member->save();
  498. return response()
  499. ->json(["status" => false, "message" => "Member is updated"])
  500. ->setStatusCode(202, 'Member is updated');
  501. }
  502. }