ReclamationController.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Requests\CreateReclamationRequest;
  4. use App\Http\Requests\StoreReclamationDetailsRequest;
  5. use App\Http\Requests\StoreReclamationRequest;
  6. use App\Http\Requests\StoreReclamationSparePartsRequest;
  7. use App\Jobs\ExportReclamationsJob;
  8. use App\Jobs\GenerateFilesPack;
  9. use App\Jobs\GenerateReclamationPaymentPack;
  10. use App\Jobs\GenerateReclamationPack;
  11. use App\Models\File;
  12. use App\Models\Order;
  13. use App\Models\Reclamation;
  14. use App\Models\ReclamationDetail;
  15. use App\Models\ReclamationStatus;
  16. use App\Models\ReclamationView;
  17. use App\Models\Role;
  18. use App\Models\User;
  19. use App\Services\FileService;
  20. use App\Services\NotificationService;
  21. use App\Services\SparePartReservationService;
  22. use Illuminate\Http\Request;
  23. use Illuminate\Support\Carbon;
  24. use Illuminate\Support\Facades\Storage;
  25. use Throwable;
  26. class ReclamationController extends Controller
  27. {
  28. protected array $data = [
  29. 'active' => 'reclamations',
  30. 'title' => 'Рекламации',
  31. 'id' => 'reclamations',
  32. 'header' => [
  33. 'id' => 'ID',
  34. 'user_name' => 'Менеджер',
  35. 'status_name' => 'Статус',
  36. 'district_name' => 'Округ',
  37. 'area_name' => 'Район',
  38. 'object_address' => 'Адрес объекта',
  39. 'maf_installation_year' => 'Год установки МАФ',
  40. 'create_date' => 'Дата создания',
  41. 'finish_date' => 'Дата завершения',
  42. 'start_work_date' => 'Дата начала работ',
  43. 'work_days' => 'Срок работ, дней',
  44. 'brigadier_name' => 'Бригадир',
  45. 'reason' => 'Причина',
  46. 'guarantee' => 'Гарантии',
  47. 'whats_done' => 'Что сделано',
  48. 'comment' => 'Комментарий',
  49. ],
  50. 'searchFields' => [
  51. 'reason',
  52. 'guarantee',
  53. 'whats_done',
  54. 'comment',
  55. ],
  56. 'ranges' => [],
  57. ];
  58. public function __construct()
  59. {
  60. $this->data['users'] = User::query()->whereIn('role', [Role::MANAGER, Role::ADMIN])->get()->pluck('name', 'id');
  61. $this->data['statuses'] = ReclamationStatus::query()->get()->pluck('name', 'id');
  62. }
  63. public function index(Request $request)
  64. {
  65. session(['gp_reclamations' => $request->all()]);
  66. $nav = $this->resolveNavToken($request);
  67. $this->rememberNavigation($request, $nav);
  68. $model = new ReclamationView();
  69. // fill filters
  70. $this->createFilters($model, 'user_name', 'status_name');
  71. $this->createDateFilters($model, 'create_date', 'finish_date');
  72. $q = $model::query();
  73. $this->acceptFilters($q, $request);
  74. $this->acceptSearch($q, $request);
  75. $this->setSortAndOrderBy($model, $request);
  76. if (hasRole(Role::BRIGADIER)) {
  77. $q->where('brigadier_id', auth()->id())
  78. ->whereIn('status_id', Reclamation::visibleStatusIdsForBrigadier());
  79. } elseif (hasRole(Role::WAREHOUSE_HEAD)) {
  80. $q->whereNotNull('brigadier_id')
  81. ->whereIn('status_id', Reclamation::visibleStatusIdsForBrigadier());
  82. }
  83. $this->applyStableSorting($q);
  84. $this->data['reclamations'] = $q->paginate($this->data['per_page'])->withQueryString();
  85. $this->data['nav'] = $nav;
  86. return view('reclamations.index', $this->data);
  87. }
  88. public function export(Request $request)
  89. {
  90. $request->validate([
  91. 'withFilter' => 'nullable',
  92. 'filters' => 'nullable|array',
  93. 's' => 'nullable|string',
  94. ]);
  95. $filterRequest = $request->boolean('withFilter')
  96. ? new Request(array_filter([
  97. 'filters' => $request->input('filters', []),
  98. 's' => $request->input('s'),
  99. ], static fn ($value) => $value !== null))
  100. : new Request();
  101. $model = new ReclamationView();
  102. $this->createFilters($model, 'user_name', 'status_name');
  103. $this->createDateFilters($model, 'create_date', 'finish_date');
  104. $q = $model::query();
  105. $this->acceptFilters($q, $filterRequest);
  106. $this->acceptSearch($q, $filterRequest);
  107. $this->setSortAndOrderBy($model, $filterRequest);
  108. $this->applyStableSorting($q);
  109. $reclamationIds = $q->pluck('id')->toArray();
  110. ExportReclamationsJob::dispatch($reclamationIds, $request->user()->id);
  111. return redirect()->route('reclamations.index', session('gp_reclamations'))
  112. ->with(['success' => 'Задача экспорта рекламаций создана!']);
  113. }
  114. public function create(CreateReclamationRequest $request, Order $order, NotificationService $notificationService)
  115. {
  116. $nav = $this->resolveNavToken($request);
  117. $reclamation = Reclamation::query()->create([
  118. 'order_id' => $order->id,
  119. 'user_id' => $request->user()->id,
  120. 'status_id' => Reclamation::STATUS_NEW,
  121. 'create_date' => Carbon::now(),
  122. 'finish_date' => Carbon::now()->addDays(30),
  123. ]);
  124. $skus = $request->validated('skus');
  125. $reclamation->skus()->attach($skus);
  126. $notificationService->notifyReclamationCreated($reclamation->fresh(['order', 'status']), auth()->user());
  127. return redirect()->route('reclamations.show', $this->withNav(['reclamation' => $reclamation], $nav));
  128. }
  129. public function show(Request $request, Reclamation $reclamation)
  130. {
  131. $this->ensureCanViewReclamation($reclamation);
  132. $this->data['brigadiers'] = User::query()->where('role', Role::BRIGADIER)->get()->pluck('name', 'id');
  133. $this->data['reclamation'] = $reclamation->load([
  134. 'order',
  135. 'chatMessages.user',
  136. 'chatMessages.targetUser',
  137. 'chatMessages.notifiedUsers',
  138. 'chatMessages.files',
  139. ]);
  140. $chatUsers = User::query()->orderBy('name')->get(['id', 'name', 'role']);
  141. $responsibleUserIds = User::query()
  142. ->where('role', Role::ADMIN)
  143. ->pluck('id')
  144. ->map(static fn ($id) => (int) $id)
  145. ->all();
  146. $responsibleUserIds = array_values(array_unique(array_filter(array_merge($responsibleUserIds, [
  147. $reclamation->user_id ? (int) $reclamation->user_id : null,
  148. $reclamation->brigadier_id ? (int) $reclamation->brigadier_id : null,
  149. ]))));
  150. $this->data['chatUsers'] = $chatUsers->map(fn ($u) => [
  151. 'id' => $u->id,
  152. 'name' => $u->name,
  153. 'role' => $u->role,
  154. ])->keyBy('id');
  155. $this->data['chatResponsibleUserIds'] = $responsibleUserIds;
  156. $this->data['chatManagerUserId'] = $reclamation->user_id ? (int) $reclamation->user_id : null;
  157. $this->data['chatBrigadierUserId'] = $reclamation->brigadier_id ? (int) $reclamation->brigadier_id : null;
  158. $nav = $this->resolveNavToken($request);
  159. $this->rememberNavigation($request, $nav);
  160. $this->data['nav'] = $nav;
  161. $this->data['back_url'] = $this->navigationBackUrl(
  162. $request,
  163. $nav,
  164. route('reclamations.index', session('gp_reclamations'))
  165. );
  166. return view('reclamations.edit', $this->data);
  167. }
  168. public function update(StoreReclamationRequest $request, Reclamation $reclamation, NotificationService $notificationService)
  169. {
  170. $data = $request->validated();
  171. $oldStatusId = $reclamation->status_id;
  172. $reclamation->update($data);
  173. if ((int) $oldStatusId !== (int) $reclamation->status_id) {
  174. $notificationService->notifyReclamationStatusChanged($reclamation->fresh(['order', 'status']), auth()->user());
  175. }
  176. $nav = $this->resolveNavToken($request);
  177. if ($request->ajax()) {
  178. return response()->noContent();
  179. }
  180. return redirect()->route('reclamations.show', $this->withNav(['reclamation' => $reclamation], $nav));
  181. }
  182. public function updateStatus(Request $request, Reclamation $reclamation, NotificationService $notificationService)
  183. {
  184. if (!hasRole('admin,manager')) {
  185. abort(403);
  186. }
  187. $validated = $request->validate([
  188. 'status_id' => 'required|exists:reclamation_statuses,id',
  189. ]);
  190. $reclamation->update(['status_id' => $validated['status_id']]);
  191. $notificationService->notifyReclamationStatusChanged($reclamation->fresh(['order', 'status']), auth()->user());
  192. return response()->noContent();
  193. }
  194. public function delete(Reclamation $reclamation)
  195. {
  196. $reclamation->delete();
  197. return redirect()->route('reclamations.index');
  198. }
  199. public function uploadPhotoBefore(Request $request, Reclamation $reclamation, FileService $fileService)
  200. {
  201. $this->ensureHasRole([Role::ADMIN, Role::MANAGER]);
  202. $this->ensureCanViewReclamation($reclamation);
  203. $data = $request->validate([
  204. 'photo.*' => 'mimes:jpeg,jpg,png,webp|max:8192',
  205. ]);
  206. try {
  207. $f = [];
  208. foreach ($data['photo'] as $photo) {
  209. $f[] = $fileService->saveUploadedFile('reclamations/' . $reclamation->id . '/photo_before', $photo);
  210. }
  211. $reclamation->photos_before()->syncWithoutDetaching($f);
  212. } catch (Throwable $e) {
  213. report($e);
  214. return $this->redirectToReclamationShow($request, $reclamation)
  215. ->with(['error' => 'Ошибка загрузки фотографий проблемы. Проверьте имя файла и повторите попытку.']);
  216. }
  217. return $this->redirectToReclamationShow($request, $reclamation)
  218. ->with(['success' => 'Фотографии проблемы успешно загружены!']);
  219. }
  220. public function uploadPhotoAfter(Request $request, Reclamation $reclamation, FileService $fileService)
  221. {
  222. $this->ensureCanViewReclamation($reclamation);
  223. $data = $request->validate([
  224. 'photo.*' => 'mimes:jpeg,jpg,png,webp|max:8192',
  225. ]);
  226. try {
  227. $f = [];
  228. foreach ($data['photo'] as $photo) {
  229. $f[] = $fileService->saveUploadedFile('reclamations/' . $reclamation->id . '/photo_after', $photo);
  230. }
  231. $reclamation->photos_after()->syncWithoutDetaching($f);
  232. } catch (Throwable $e) {
  233. report($e);
  234. return $this->redirectToReclamationShow($request, $reclamation)
  235. ->with(['error' => 'Ошибка загрузки фотографий после устранения. Проверьте имя файла и повторите попытку.']);
  236. }
  237. return $this->redirectToReclamationShow($request, $reclamation)
  238. ->with(['success' => 'Фотографии после устранения успешно загружены!']);
  239. }
  240. public function deletePhotoBefore(Request $request, Reclamation $reclamation, File $file, FileService $fileService)
  241. {
  242. $this->ensureHasRole([Role::ADMIN, Role::MANAGER]);
  243. $this->ensureCanViewReclamation($reclamation);
  244. $reclamation->photos_before()->detach($file);
  245. Storage::disk('public')->delete($file->path);
  246. $file->delete();
  247. return $this->redirectToReclamationShow($request, $reclamation);
  248. }
  249. public function deletePhotoAfter(Request $request, Reclamation $reclamation, File $file, FileService $fileService)
  250. {
  251. $this->ensureHasRole([Role::ADMIN, Role::MANAGER]);
  252. $this->ensureCanViewReclamation($reclamation);
  253. $reclamation->photos_after()->detach($file);
  254. Storage::disk('public')->delete($file->path);
  255. $file->delete();
  256. return $this->redirectToReclamationShow($request, $reclamation);
  257. }
  258. public function uploadDocument(Request $request, Reclamation $reclamation, FileService $fileService)
  259. {
  260. $this->ensureHasRole([Role::ADMIN, Role::MANAGER]);
  261. $this->ensureCanViewReclamation($reclamation);
  262. $data = $request->validate([
  263. 'document.*' => 'file',
  264. ]);
  265. try {
  266. $f = [];
  267. $i = 0;
  268. foreach ($data['document'] as $document) {
  269. if ($i++ >= 5) break;
  270. $f[] = $fileService->saveUploadedFile('reclamations/' . $reclamation->id . '/document', $document);
  271. }
  272. $reclamation->documents()->syncWithoutDetaching($f);
  273. } catch (Throwable $e) {
  274. report($e);
  275. return $this->redirectToReclamationShow($request, $reclamation)
  276. ->with(['error' => 'Ошибка загрузки документов рекламации. Проверьте имя файла и повторите попытку.']);
  277. }
  278. return $this->redirectToReclamationShow($request, $reclamation)
  279. ->with(['success' => 'Документы рекламации успешно загружены!']);
  280. }
  281. public function deleteDocument(Request $request, Reclamation $reclamation, File $file)
  282. {
  283. $this->ensureHasRole([Role::ADMIN, Role::MANAGER]);
  284. $this->ensureCanViewReclamation($reclamation);
  285. $reclamation->documents()->detach($file);
  286. Storage::disk('public')->delete($file->path);
  287. $file->delete();
  288. return $this->redirectToReclamationShow($request, $reclamation);
  289. }
  290. public function uploadAct(Request $request, Reclamation $reclamation, FileService $fileService)
  291. {
  292. $this->ensureHasRole([Role::ADMIN, Role::MANAGER, Role::BRIGADIER, Role::WAREHOUSE_HEAD]);
  293. $this->ensureCanViewReclamation($reclamation);
  294. $data = $request->validate([
  295. 'acts.*' => 'file',
  296. ]);
  297. try {
  298. $f = [];
  299. $i = 0;
  300. foreach ($data['acts'] as $document) {
  301. if ($i++ >= 5) break;
  302. $f[] = $fileService->saveUploadedFile('reclamations/' . $reclamation->id . '/act', $document);
  303. }
  304. $reclamation->acts()->syncWithoutDetaching($f);
  305. } catch (Throwable $e) {
  306. report($e);
  307. return $this->redirectToReclamationShow($request, $reclamation)
  308. ->with(['error' => 'Ошибка загрузки актов. Проверьте имя файла и повторите попытку.']);
  309. }
  310. return $this->redirectToReclamationShow($request, $reclamation)
  311. ->with(['success' => 'Акты успешно загружены!']);
  312. }
  313. public function deleteAct(Request $request, Reclamation $reclamation, File $file)
  314. {
  315. $this->ensureHasRole([Role::ADMIN, Role::MANAGER]);
  316. $this->ensureCanViewReclamation($reclamation);
  317. $reclamation->acts()->detach($file);
  318. Storage::disk('public')->delete($file->path);
  319. $file->delete();
  320. return $this->redirectToReclamationShow($request, $reclamation);
  321. }
  322. public function updateDetails(StoreReclamationDetailsRequest $request, Reclamation $reclamation)
  323. {
  324. $names = $request->validated('name');
  325. $quantity = $request->validated('quantity');
  326. $withDocuments = $request->validated('with_documents');
  327. $reservationService = app(SparePartReservationService::class);
  328. foreach ($names as $key => $name) {
  329. if (!$name) continue;
  330. if ((int)$quantity[$key] >= 1) {
  331. // Проверяем, является ли это запчастью
  332. $sparePart = \App\Models\SparePart::where('article', $name)->first();
  333. if ($sparePart) {
  334. // Резервирование вместо прямого списания
  335. $withDocs = isset($withDocuments[$key]) && $withDocuments[$key];
  336. $qty = (int)$quantity[$key];
  337. // Получаем текущее количество в pivot
  338. $currentPivot = $reclamation->spareParts()->find($sparePart->id);
  339. $currentQty = $currentPivot?->pivot->quantity ?? 0;
  340. $diff = $qty - $currentQty;
  341. if ($diff > 0) {
  342. // Нужно зарезервировать дополнительное количество
  343. $result = $reservationService->reserve(
  344. $sparePart->id,
  345. $diff,
  346. $withDocs,
  347. $reclamation->id
  348. );
  349. // Обновляем pivot с учётом результата
  350. $reclamation->spareParts()->syncWithoutDetaching([
  351. $sparePart->id => [
  352. 'quantity' => $qty,
  353. 'with_documents' => $withDocs,
  354. 'status' => $result->isFullyReserved() ? 'reserved' : 'pending',
  355. 'reserved_qty' => $currentQty + $result->reserved,
  356. ]
  357. ]);
  358. } elseif ($diff < 0) {
  359. // Уменьшение — отменяем часть резерва
  360. $reservationService->adjustReservation(
  361. $reclamation->id,
  362. $sparePart->id,
  363. $withDocs,
  364. $qty
  365. );
  366. $reclamation->spareParts()->syncWithoutDetaching([
  367. $sparePart->id => [
  368. 'quantity' => $qty,
  369. 'with_documents' => $withDocs,
  370. 'reserved_qty' => $qty,
  371. ]
  372. ]);
  373. } else {
  374. // Количество не изменилось, возможно изменился with_documents
  375. $reclamation->spareParts()->syncWithoutDetaching([
  376. $sparePart->id => [
  377. 'quantity' => $qty,
  378. 'with_documents' => $withDocs,
  379. ]
  380. ]);
  381. }
  382. } else {
  383. // Обычная деталь
  384. ReclamationDetail::query()->updateOrCreate(
  385. ['reclamation_id' => $reclamation->id, 'name' => $name],
  386. ['quantity' => $quantity[$key]]
  387. );
  388. }
  389. } else {
  390. // Удаление
  391. // Проверяем, является ли это запчастью — отменяем резервы
  392. $sparePartToRemove = \App\Models\SparePart::where('article', $name)->first();
  393. if ($sparePartToRemove) {
  394. // Отменяем все резервы для этой запчасти в рекламации
  395. $reservationService->cancelForReclamation(
  396. $reclamation->id,
  397. $sparePartToRemove->id
  398. );
  399. // Удаляем связь
  400. $reclamation->spareParts()->detach($sparePartToRemove->id);
  401. } else {
  402. // Обычная деталь
  403. ReclamationDetail::query()
  404. ->where('reclamation_id', $reclamation->id)
  405. ->where('name', $name)
  406. ->delete();
  407. }
  408. }
  409. }
  410. return $this->redirectToReclamationShow($request, $reclamation);
  411. }
  412. public function updateSpareParts(StoreReclamationSparePartsRequest $request, Reclamation $reclamation)
  413. {
  414. $rows = $request->validated('rows') ?? [];
  415. $reservationService = app(SparePartReservationService::class);
  416. // Получаем текущие привязки для сравнения
  417. $currentSpareParts = $reclamation->spareParts->keyBy('id');
  418. // Определяем какие запчасти были удалены
  419. $newSparePartIds = collect($rows)->pluck('spare_part_id')->filter()->toArray();
  420. $removedIds = $currentSpareParts->keys()->diff($newSparePartIds);
  421. // Отменяем резервы для удалённых запчастей
  422. foreach ($removedIds as $removedId) {
  423. $current = $currentSpareParts->get($removedId);
  424. if ($current) {
  425. $reservationService->cancelForReclamation(
  426. $reclamation->id,
  427. $removedId,
  428. $current->pivot->with_documents
  429. );
  430. }
  431. }
  432. // Собираем новые привязки
  433. $newSpareParts = [];
  434. foreach ($rows as $row) {
  435. $sparePartId = $row['spare_part_id'] ?? null;
  436. if (empty($sparePartId)) continue;
  437. $quantity = (int)($row['quantity'] ?? 0);
  438. if ($quantity < 1) continue;
  439. $withDocs = !empty($row['with_documents']) && $row['with_documents'] != '0';
  440. // Проверяем, изменилось ли количество
  441. $currentQty = $currentSpareParts->get($sparePartId)?->pivot->quantity ?? 0;
  442. $currentReserved = $currentSpareParts->get($sparePartId)?->pivot->reserved_qty ?? 0;
  443. $diff = $quantity - $currentQty;
  444. $status = 'pending';
  445. $reservedQty = $currentReserved;
  446. if ($diff > 0) {
  447. // Нужно зарезервировать дополнительное количество
  448. $result = $reservationService->reserve(
  449. $sparePartId,
  450. $diff,
  451. $withDocs,
  452. $reclamation->id
  453. );
  454. $reservedQty = $currentReserved + $result->reserved;
  455. $status = $reservedQty >= $quantity ? 'reserved' : 'pending';
  456. } elseif ($diff < 0) {
  457. // Уменьшение — отменяем часть резерва
  458. $reservationService->adjustReservation(
  459. $reclamation->id,
  460. $sparePartId,
  461. $withDocs,
  462. $quantity
  463. );
  464. $reservedQty = $quantity;
  465. $status = 'reserved';
  466. } else {
  467. // Количество не изменилось
  468. $status = $currentReserved >= $quantity ? 'reserved' : 'pending';
  469. }
  470. $newSpareParts[$sparePartId] = [
  471. 'quantity' => $quantity,
  472. 'with_documents' => $withDocs,
  473. 'status' => $status,
  474. 'reserved_qty' => $reservedQty,
  475. ];
  476. }
  477. // Синхронизируем (заменяем все старые привязки новыми)
  478. $reclamation->spareParts()->sync($newSpareParts);
  479. return $this->redirectToReclamationShow($request, $reclamation);
  480. }
  481. public function generateReclamationPack(Request $request, Reclamation $reclamation)
  482. {
  483. GenerateReclamationPack::dispatch($reclamation, auth()->user()->id);
  484. return $this->redirectToReclamationShow($request, $reclamation)
  485. ->with(['success' => 'Задача генерации документов создана!']);
  486. }
  487. public function generateReclamationPaymentPack(Request $request, Reclamation $reclamation)
  488. {
  489. GenerateReclamationPaymentPack::dispatch($reclamation, auth()->user()->id);
  490. return $this->redirectToReclamationShow($request, $reclamation)
  491. ->with(['success' => 'Задача генерации пакета документов на оплату создана!']);
  492. }
  493. public function generatePhotosBeforePack(Request $request, Reclamation $reclamation)
  494. {
  495. GenerateFilesPack::dispatch($reclamation, $reclamation->photos_before, auth()->user()->id, 'Фото проблемы');
  496. return $this->redirectToReclamationShow($request, $reclamation)
  497. ->with(['success' => 'Задача архивации создана!']);
  498. }
  499. public function generatePhotosAfterPack(Request $request, Reclamation $reclamation)
  500. {
  501. GenerateFilesPack::dispatch($reclamation, $reclamation->photos_after, auth()->user()->id, 'Фото после');
  502. return $this->redirectToReclamationShow($request, $reclamation)
  503. ->with(['success' => 'Задача архивации создана!']);
  504. }
  505. private function ensureCanViewReclamation(Reclamation $reclamation): void
  506. {
  507. if (hasRole(Role::BRIGADIER)) {
  508. $canView = (int)$reclamation->brigadier_id === (int)auth()->id()
  509. && in_array((int)$reclamation->status_id, Reclamation::visibleStatusIdsForBrigadier(), true);
  510. if (!$canView) {
  511. abort(403);
  512. }
  513. }
  514. if (hasRole(Role::WAREHOUSE_HEAD)) {
  515. $canView = $reclamation->brigadier_id !== null
  516. && in_array((int)$reclamation->status_id, Reclamation::visibleStatusIdsForBrigadier(), true);
  517. if (!$canView) {
  518. abort(403);
  519. }
  520. }
  521. }
  522. private function ensureHasRole(array $roles): void
  523. {
  524. if (!count(array_intersect($roles, Role::effectiveRoles((string)auth()->user()?->role)))) {
  525. abort(403);
  526. }
  527. }
  528. private function redirectToReclamationShow(Request $request, Reclamation $reclamation)
  529. {
  530. $nav = $this->resolveNavToken($request);
  531. return redirect()->route('reclamations.show', $this->withNav(['reclamation' => $reclamation], $nav));
  532. }
  533. }