ReclamationController.php 27 KB

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