ReclamationController.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. 'productionOrder',
  143. 'productionOrderItems.catalogItem.imageFile',
  144. 'reclamationType',
  145. 'chatMessages.user',
  146. 'chatMessages.targetUser',
  147. 'chatMessages.notifiedUsers',
  148. 'chatMessages.files',
  149. ]);
  150. $chatUsers = User::query()->orderBy('name')->get(['id', 'name', 'role']);
  151. $responsibleUserIds = User::query()
  152. ->withPermission('reclamations.scope.admin')
  153. ->pluck('id')
  154. ->map(static fn ($id) => (int) $id)
  155. ->all();
  156. $responsibleUserIds = array_values(array_unique(array_filter(array_merge($responsibleUserIds, [
  157. $reclamation->user_id ? (int) $reclamation->user_id : null,
  158. $reclamation->brigadier_id ? (int) $reclamation->brigadier_id : null,
  159. ]))));
  160. $this->data['chatUsers'] = $chatUsers->map(fn ($u) => [
  161. 'id' => $u->id,
  162. 'name' => $u->name,
  163. 'role' => $u->role,
  164. ])->keyBy('id');
  165. $this->data['chatResponsibleUserIds'] = $responsibleUserIds;
  166. $this->data['chatManagerUserId'] = $reclamation->user_id ? (int) $reclamation->user_id : null;
  167. $this->data['chatBrigadierUserId'] = $reclamation->brigadier_id ? (int) $reclamation->brigadier_id : null;
  168. $nav = $this->resolveNavToken($request);
  169. $this->rememberNavigation($request, $nav);
  170. $this->data['nav'] = $nav;
  171. $this->data['back_url'] = $this->navigationBackUrl(
  172. $request,
  173. $nav,
  174. route('reclamations.index', session('gp_reclamations'))
  175. );
  176. return view('reclamations.edit', $this->data);
  177. }
  178. public function update(StoreReclamationRequest $request, Reclamation $reclamation, NotificationService $notificationService)
  179. {
  180. $data = $request->validated();
  181. $oldStatusId = $reclamation->status_id;
  182. $reclamation->update($data);
  183. if ((int) $oldStatusId !== (int) $reclamation->status_id) {
  184. $notificationService->notifyReclamationStatusChanged(
  185. $reclamation->fresh(['order', 'productionOrder', 'status']),
  186. auth()->user(),
  187. );
  188. }
  189. $nav = $this->resolveNavToken($request);
  190. if ($request->ajax()) {
  191. return response()->noContent();
  192. }
  193. return redirect()->route('reclamations.show', $this->withNav(['reclamation' => $reclamation], $nav));
  194. }
  195. public function updateStatus(Request $request, Reclamation $reclamation, NotificationService $notificationService)
  196. {
  197. $this->ensureHasPermission('reclamations.status.update');
  198. $validated = $request->validate([
  199. 'status_id' => 'required|exists:reclamation_statuses,id',
  200. ]);
  201. $reclamation->update(['status_id' => $validated['status_id']]);
  202. $notificationService->notifyReclamationStatusChanged(
  203. $reclamation->fresh(['order', 'productionOrder', 'status']),
  204. auth()->user(),
  205. );
  206. return response()->noContent();
  207. }
  208. public function delete(Reclamation $reclamation)
  209. {
  210. $reclamation->delete();
  211. return redirect()->route('reclamations.index');
  212. }
  213. public function uploadPhotoBefore(Request $request, Reclamation $reclamation, FileService $fileService)
  214. {
  215. $this->ensureHasPermission('reclamations.photos.upload');
  216. $this->ensureCanViewReclamation($reclamation);
  217. $data = $request->validate([
  218. 'photo.*' => 'mimes:jpeg,jpg,png,webp|max:8192',
  219. ]);
  220. try {
  221. $f = [];
  222. foreach ($data['photo'] as $photo) {
  223. $f[] = $fileService->saveUploadedFile('reclamations/' . $reclamation->id . '/photo_before', $photo);
  224. }
  225. $reclamation->photos_before()->syncWithoutDetaching($f);
  226. } catch (Throwable $e) {
  227. report($e);
  228. return $this->redirectToReclamationShow($request, $reclamation)
  229. ->with(['error' => 'Ошибка загрузки фотографий проблемы. Проверьте имя файла и повторите попытку.']);
  230. }
  231. return $this->redirectToReclamationShow($request, $reclamation)
  232. ->with(['success' => 'Фотографии проблемы успешно загружены!']);
  233. }
  234. public function uploadPhotoAfter(Request $request, Reclamation $reclamation, FileService $fileService)
  235. {
  236. $this->ensureCanViewReclamation($reclamation);
  237. $data = $request->validate([
  238. 'photo.*' => 'mimes:jpeg,jpg,png,webp|max:8192',
  239. ]);
  240. try {
  241. $f = [];
  242. foreach ($data['photo'] as $photo) {
  243. $f[] = $fileService->saveUploadedFile('reclamations/' . $reclamation->id . '/photo_after', $photo);
  244. }
  245. $reclamation->photos_after()->syncWithoutDetaching($f);
  246. } catch (Throwable $e) {
  247. report($e);
  248. return $this->redirectToReclamationShow($request, $reclamation)
  249. ->with(['error' => 'Ошибка загрузки фотографий после устранения. Проверьте имя файла и повторите попытку.']);
  250. }
  251. return $this->redirectToReclamationShow($request, $reclamation)
  252. ->with(['success' => 'Фотографии после устранения успешно загружены!']);
  253. }
  254. public function deletePhotoBefore(Request $request, Reclamation $reclamation, File $file, FileService $fileService)
  255. {
  256. $this->ensureHasPermission('reclamations.photos.delete');
  257. $this->ensureCanViewReclamation($reclamation);
  258. $reclamation->photos_before()->detach($file);
  259. $fileService->deleteFileWithThumbnail($file);
  260. $file->delete();
  261. return $this->redirectToReclamationShow($request, $reclamation);
  262. }
  263. public function deletePhotoAfter(Request $request, Reclamation $reclamation, File $file, FileService $fileService)
  264. {
  265. $this->ensureHasPermission('reclamations.photos.delete');
  266. $this->ensureCanViewReclamation($reclamation);
  267. $reclamation->photos_after()->detach($file);
  268. $fileService->deleteFileWithThumbnail($file);
  269. $file->delete();
  270. return $this->redirectToReclamationShow($request, $reclamation);
  271. }
  272. public function uploadDocument(Request $request, Reclamation $reclamation, FileService $fileService)
  273. {
  274. $this->ensureHasPermission('reclamations.documents.upload');
  275. $this->ensureCanViewReclamation($reclamation);
  276. $data = $request->validate([
  277. 'document.*' => 'file',
  278. ]);
  279. try {
  280. $f = [];
  281. $i = 0;
  282. foreach ($data['document'] as $document) {
  283. if ($i++ >= 5) break;
  284. $f[] = $fileService->saveUploadedFile('reclamations/' . $reclamation->id . '/document', $document);
  285. }
  286. $reclamation->documents()->syncWithoutDetaching($f);
  287. } catch (Throwable $e) {
  288. report($e);
  289. return $this->redirectToReclamationShow($request, $reclamation)
  290. ->with(['error' => 'Ошибка загрузки документов рекламации. Проверьте имя файла и повторите попытку.']);
  291. }
  292. return $this->redirectToReclamationShow($request, $reclamation)
  293. ->with(['success' => 'Документы рекламации успешно загружены!']);
  294. }
  295. public function deleteDocument(Request $request, Reclamation $reclamation, File $file)
  296. {
  297. $this->ensureHasPermission('reclamations.documents.delete');
  298. $this->ensureCanViewReclamation($reclamation);
  299. $reclamation->documents()->detach($file);
  300. Storage::disk('public')->delete($file->path);
  301. $file->delete();
  302. return $this->redirectToReclamationShow($request, $reclamation);
  303. }
  304. public function uploadAct(Request $request, Reclamation $reclamation, FileService $fileService)
  305. {
  306. $this->ensureHasPermission('reclamations.act.upload');
  307. $this->ensureCanViewReclamation($reclamation);
  308. $data = $request->validate([
  309. 'acts.*' => 'file',
  310. ]);
  311. try {
  312. $f = [];
  313. $i = 0;
  314. foreach ($data['acts'] as $document) {
  315. if ($i++ >= 5) break;
  316. $f[] = $fileService->saveUploadedFile('reclamations/' . $reclamation->id . '/act', $document);
  317. }
  318. $reclamation->acts()->syncWithoutDetaching($f);
  319. } catch (Throwable $e) {
  320. report($e);
  321. return $this->redirectToReclamationShow($request, $reclamation)
  322. ->with(['error' => 'Ошибка загрузки актов. Проверьте имя файла и повторите попытку.']);
  323. }
  324. return $this->redirectToReclamationShow($request, $reclamation)
  325. ->with(['success' => 'Акты успешно загружены!']);
  326. }
  327. public function deleteAct(Request $request, Reclamation $reclamation, File $file)
  328. {
  329. $this->ensureHasPermission('reclamations.act.delete');
  330. $this->ensureCanViewReclamation($reclamation);
  331. $reclamation->acts()->detach($file);
  332. Storage::disk('public')->delete($file->path);
  333. $file->delete();
  334. return $this->redirectToReclamationShow($request, $reclamation);
  335. }
  336. public function updateDetails(StoreReclamationDetailsRequest $request, Reclamation $reclamation)
  337. {
  338. $names = $request->validated('name');
  339. $quantity = $request->validated('quantity');
  340. $withDocuments = $request->validated('with_documents');
  341. $reservationService = app(SparePartReservationService::class);
  342. foreach ($names as $key => $name) {
  343. if (!$name) continue;
  344. if ((int)$quantity[$key] >= 1) {
  345. // Проверяем, является ли это запчастью
  346. $sparePart = \App\Models\SparePart::where('article', $name)->first();
  347. if ($sparePart) {
  348. // Резервирование вместо прямого списания
  349. $withDocs = isset($withDocuments[$key]) && $withDocuments[$key];
  350. $qty = (int)$quantity[$key];
  351. // Получаем текущее количество в pivot
  352. $currentPivot = $reclamation->spareParts()->find($sparePart->id);
  353. $currentQty = $currentPivot?->pivot->quantity ?? 0;
  354. $diff = $qty - $currentQty;
  355. if ($diff > 0) {
  356. // Нужно зарезервировать дополнительное количество
  357. $result = $reservationService->reserve(
  358. $sparePart->id,
  359. $diff,
  360. $withDocs,
  361. $reclamation->id
  362. );
  363. // Обновляем pivot с учётом результата
  364. $reclamation->spareParts()->syncWithoutDetaching([
  365. $sparePart->id => [
  366. 'quantity' => $qty,
  367. 'with_documents' => $withDocs,
  368. 'status' => $result->isFullyReserved() ? 'reserved' : 'pending',
  369. 'reserved_qty' => $currentQty + $result->reserved,
  370. ]
  371. ]);
  372. } elseif ($diff < 0) {
  373. // Уменьшение — отменяем часть резерва
  374. $reservationService->adjustReservation(
  375. $reclamation->id,
  376. $sparePart->id,
  377. $withDocs,
  378. $qty
  379. );
  380. $reclamation->spareParts()->syncWithoutDetaching([
  381. $sparePart->id => [
  382. 'quantity' => $qty,
  383. 'with_documents' => $withDocs,
  384. 'reserved_qty' => $qty,
  385. ]
  386. ]);
  387. } else {
  388. // Количество не изменилось, возможно изменился with_documents
  389. $reclamation->spareParts()->syncWithoutDetaching([
  390. $sparePart->id => [
  391. 'quantity' => $qty,
  392. 'with_documents' => $withDocs,
  393. ]
  394. ]);
  395. }
  396. } else {
  397. // Обычная деталь
  398. ReclamationDetail::query()->updateOrCreate(
  399. ['reclamation_id' => $reclamation->id, 'name' => $name],
  400. ['quantity' => $quantity[$key]]
  401. );
  402. }
  403. } else {
  404. // Удаление
  405. // Проверяем, является ли это запчастью — отменяем резервы
  406. $sparePartToRemove = \App\Models\SparePart::where('article', $name)->first();
  407. if ($sparePartToRemove) {
  408. // Отменяем все резервы для этой запчасти в рекламации
  409. $reservationService->cancelForReclamation(
  410. $reclamation->id,
  411. $sparePartToRemove->id
  412. );
  413. // Удаляем связь
  414. $reclamation->spareParts()->detach($sparePartToRemove->id);
  415. } else {
  416. // Обычная деталь
  417. ReclamationDetail::query()
  418. ->where('reclamation_id', $reclamation->id)
  419. ->where('name', $name)
  420. ->delete();
  421. }
  422. }
  423. }
  424. return $this->redirectToReclamationShow($request, $reclamation);
  425. }
  426. public function updateSpareParts(StoreReclamationSparePartsRequest $request, Reclamation $reclamation)
  427. {
  428. $rows = $request->validated('rows') ?? [];
  429. $reservationService = app(SparePartReservationService::class);
  430. // Получаем текущие привязки для сравнения
  431. $currentSpareParts = $reclamation->spareParts->keyBy('id');
  432. // Определяем какие запчасти были удалены
  433. $newSparePartIds = collect($rows)->pluck('spare_part_id')->filter()->toArray();
  434. $removedIds = $currentSpareParts->keys()->diff($newSparePartIds);
  435. // Отменяем резервы для удалённых запчастей
  436. foreach ($removedIds as $removedId) {
  437. $current = $currentSpareParts->get($removedId);
  438. if ($current) {
  439. $reservationService->cancelForReclamation(
  440. $reclamation->id,
  441. $removedId,
  442. $current->pivot->with_documents
  443. );
  444. }
  445. }
  446. // Собираем новые привязки
  447. $newSpareParts = [];
  448. foreach ($rows as $row) {
  449. $sparePartId = $row['spare_part_id'] ?? null;
  450. if (empty($sparePartId)) continue;
  451. $quantity = (int)($row['quantity'] ?? 0);
  452. if ($quantity < 1) continue;
  453. $withDocs = !empty($row['with_documents']) && $row['with_documents'] != '0';
  454. // Проверяем, изменилось ли количество
  455. $currentQty = $currentSpareParts->get($sparePartId)?->pivot->quantity ?? 0;
  456. $currentReserved = $currentSpareParts->get($sparePartId)?->pivot->reserved_qty ?? 0;
  457. $diff = $quantity - $currentQty;
  458. $status = 'pending';
  459. $reservedQty = $currentReserved;
  460. if ($diff > 0) {
  461. // Нужно зарезервировать дополнительное количество
  462. $result = $reservationService->reserve(
  463. $sparePartId,
  464. $diff,
  465. $withDocs,
  466. $reclamation->id
  467. );
  468. $reservedQty = $currentReserved + $result->reserved;
  469. $status = $reservedQty >= $quantity ? 'reserved' : 'pending';
  470. } elseif ($diff < 0) {
  471. // Уменьшение — отменяем часть резерва
  472. $reservationService->adjustReservation(
  473. $reclamation->id,
  474. $sparePartId,
  475. $withDocs,
  476. $quantity
  477. );
  478. $reservedQty = $quantity;
  479. $status = 'reserved';
  480. } else {
  481. // Количество не изменилось
  482. $status = $currentReserved >= $quantity ? 'reserved' : 'pending';
  483. }
  484. $newSpareParts[$sparePartId] = [
  485. 'quantity' => $quantity,
  486. 'with_documents' => $withDocs,
  487. 'status' => $status,
  488. 'reserved_qty' => $reservedQty,
  489. ];
  490. }
  491. // Синхронизируем (заменяем все старые привязки новыми)
  492. $reclamation->spareParts()->sync($newSpareParts);
  493. return $this->redirectToReclamationShow($request, $reclamation);
  494. }
  495. public function generateReclamationPack(Request $request, Reclamation $reclamation)
  496. {
  497. abort_unless($reclamation->isDkr(), 403);
  498. GenerateReclamationPack::dispatch($reclamation, auth()->user()->id);
  499. return $this->redirectToReclamationShow($request, $reclamation)
  500. ->with(['success' => 'Задача генерации документов создана!']);
  501. }
  502. public function generateReclamationPaymentPack(Request $request, Reclamation $reclamation)
  503. {
  504. $this->ensureCanViewReclamation($reclamation);
  505. abort_unless($reclamation->isDkr(), 403);
  506. GenerateReclamationPaymentPack::dispatch($reclamation, auth()->user()->id);
  507. return $this->redirectToReclamationShow($request, $reclamation)
  508. ->with(['success' => 'Задача генерации пакета документов на оплату создана!']);
  509. }
  510. public function generatePhotosBeforePack(Request $request, Reclamation $reclamation)
  511. {
  512. GenerateFilesPack::dispatch($reclamation, $reclamation->photos_before, auth()->user()->id, 'Фото проблемы');
  513. return $this->redirectToReclamationShow($request, $reclamation)
  514. ->with(['success' => 'Задача архивации создана!']);
  515. }
  516. public function generatePhotosAfterPack(Request $request, Reclamation $reclamation)
  517. {
  518. GenerateFilesPack::dispatch($reclamation, $reclamation->photos_after, auth()->user()->id, 'Фото после');
  519. return $this->redirectToReclamationShow($request, $reclamation)
  520. ->with(['success' => 'Задача архивации создана!']);
  521. }
  522. private function ensureCanViewReclamation(Reclamation $reclamation): void
  523. {
  524. if (!$this->canViewReclamationByVisibilityScope($reclamation, auth()->user())) {
  525. abort(403);
  526. }
  527. }
  528. private function applyReclamationVisibilityScope($query, ?User $user): void
  529. {
  530. $scope = $user?->visibilityScope('reclamations');
  531. match ($scope) {
  532. 'admin', 'manager' => null,
  533. 'brigadier' => $query
  534. ->where('brigadier_id', $user->id)
  535. ->whereIn('status_id', Reclamation::visibleStatusIdsForBrigadier()),
  536. 'warehouse_head' => $query
  537. ->whereNotNull('brigadier_id')
  538. ->whereIn('status_id', Reclamation::visibleStatusIdsForBrigadier()),
  539. default => $query->whereRaw('1 = 0'),
  540. };
  541. }
  542. private function applyReclamationTypeTab(Builder $query, Request $request): string
  543. {
  544. $tab = $request->input('tab') === ReclamationType::CODE_DKR
  545. ? ReclamationType::CODE_DKR
  546. : 'all';
  547. if ($tab === ReclamationType::CODE_DKR) {
  548. $query->where('reclamation_type_code', ReclamationType::CODE_DKR);
  549. }
  550. return $tab;
  551. }
  552. private function canViewReclamationByVisibilityScope(Reclamation $reclamation, ?User $user): bool
  553. {
  554. return match ($user?->visibilityScope('reclamations')) {
  555. 'admin', 'manager' => true,
  556. 'brigadier' => (int)$reclamation->brigadier_id === (int)$user->id
  557. && in_array((int)$reclamation->status_id, Reclamation::visibleStatusIdsForBrigadier(), true),
  558. 'warehouse_head' => $reclamation->brigadier_id !== null
  559. && in_array((int)$reclamation->status_id, Reclamation::visibleStatusIdsForBrigadier(), true),
  560. default => false,
  561. };
  562. }
  563. private function ensureHasPermission(string $permission): void
  564. {
  565. abort_unless(auth()->user()?->hasPermission($permission), 403);
  566. }
  567. private function redirectToReclamationShow(Request $request, Reclamation $reclamation)
  568. {
  569. $nav = $this->resolveNavToken($request);
  570. return redirect()->route('reclamations.show', $this->withNav(['reclamation' => $reclamation], $nav));
  571. }
  572. }