ReclamationController.php 26 KB

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