OrderController.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Requests\CreteTtnRequest;
  4. use App\Http\Requests\ExportScheduleRequest;
  5. use App\Http\Requests\Order\StoreOrderRequest;
  6. use App\Jobs\ExportOneOrderJob;
  7. use App\Jobs\ExportOrdersJob;
  8. use App\Jobs\ExportScheduleJob;
  9. use App\Jobs\GenerateFilesPack;
  10. use App\Jobs\GenerateHandoverPack;
  11. use App\Jobs\GenerateInstallationPack;
  12. use App\Jobs\GenerateTtnPack;
  13. use App\Models\Dictionary\Area;
  14. use App\Models\Dictionary\District;
  15. use App\Models\File;
  16. use App\Models\MafOrder;
  17. use App\Models\ObjectType;
  18. use App\Models\Order;
  19. use App\Models\OrderStatus;
  20. use App\Models\OrderView;
  21. use App\Models\ProductSKU;
  22. use App\Models\Role;
  23. use App\Models\Schedule;
  24. use App\Models\Ttn;
  25. use App\Models\User;
  26. use App\Services\FileService;
  27. use App\Services\NotificationService;
  28. use Illuminate\Http\RedirectResponse;
  29. use Illuminate\Http\Request;
  30. use Illuminate\Support\Facades\DB;
  31. use Illuminate\Support\Str;
  32. use Illuminate\Support\Facades\Storage;
  33. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  34. use Throwable;
  35. use ZipArchive;
  36. class OrderController extends Controller
  37. {
  38. protected array $data = [
  39. 'active' => 'orders',
  40. 'title' => 'Заказы',
  41. 'id' => 'orders',
  42. 'header' => [
  43. 'id' => 'ID',
  44. 'name' => 'Название',
  45. 'user_name' => 'Менеджер',
  46. 'district_name' => 'Округ',
  47. 'area_name' => 'Район',
  48. 'object_address' => 'Адрес объекта',
  49. 'object_type_name' => 'Тип объекта',
  50. 'comment' => 'Комментарий',
  51. 'products_total' => 'Всего МАФ',
  52. 'installation_date' => 'Дата выхода на монтаж',
  53. 'ready_date' => 'Дата готовности площадки',
  54. 'brigadier_name' => 'Бригадир',
  55. 'order_status_name' => 'Статус',
  56. 'tg_group_name' => 'Имя группы в ТГ',
  57. 'tg_group_link' => 'Ссылка на группу в ТГ',
  58. 'products_with_count' => 'МАФы',
  59. 'ready_to_mount' => 'Все МАФы на складе',
  60. ],
  61. 'searchFields' => [
  62. 'name',
  63. 'user_name',
  64. 'district_name',
  65. 'area_name',
  66. 'object_type_name',
  67. 'comment',
  68. 'object_address',
  69. 'installation_date',
  70. 'tg_group_name',
  71. 'tg_group_link',
  72. ],
  73. ];
  74. public function __construct()
  75. {
  76. $this->data['districts'] = District::query()->get()->pluck('name', 'id');
  77. $this->data['areas'] = Area::query()->get()->pluck('name', 'id');
  78. $this->data['objectTypes'] = ObjectType::query()->get()->pluck('name', 'id');
  79. $this->data['orderStatuses'] =OrderStatus::query()->get()->pluck('name', 'id');
  80. $this->data['brigadiers'] = User::query()->where('role', Role::BRIGADIER)->get()->pluck('name', 'id');
  81. $this->data['users'] = User::query()->whereIn('role', [Role::MANAGER, Role::ADMIN])->get()->pluck('name', 'id');
  82. }
  83. /**
  84. * Display a listing of the resource.
  85. */
  86. public function index(Request $request)
  87. {
  88. session(['gp_orders' => $request->all()]);
  89. $nav = $this->startNavigationContext($request);
  90. $model = new OrderView;
  91. // fill filters
  92. $this->createFilters($model, 'user_name', 'district_name', 'area_name', 'object_type_name', 'brigadier_name', 'order_status_name', 'ready_to_mount');
  93. $this->createDateFilters($model, 'installation_date', 'ready_date');
  94. $this->data['ranges'] = [];
  95. $q = $model::query();
  96. $this->acceptFilters($q, $request);
  97. $this->acceptSearch($q, $request);
  98. $this->setSortAndOrderBy($model, $request);
  99. if(hasRole('brigadier')) {
  100. $q->where('brigadier_id', auth()->id())
  101. ->whereIn('order_status_id', Order::visibleStatusIdsForBrigadier());
  102. }
  103. if(hasRole(Role::WAREHOUSE_HEAD)) {
  104. $q->whereNotNull('brigadier_id');
  105. $q->whereNotNull('installation_date');
  106. }
  107. $this->data['filtered_orders_count'] = (clone $q)->count();
  108. $this->data['filtered_products_total'] = (clone $q)->sum('products_total');
  109. $this->applyStableSorting($q);
  110. $this->data['orders'] = $q->paginate($this->data['per_page'])->withQueryString();
  111. foreach ($this->data['orders'] as $order) {
  112. Order::where('id', $order->id)->first()?->recalculateReadyToMount();
  113. }
  114. $this->data['statuses'] = OrderStatus::query()->get()->pluck('name', 'id');
  115. $this->data['nav'] = $nav;
  116. return view('orders.index', $this->data);
  117. }
  118. /**
  119. * Show the form for creating a new resource.
  120. */
  121. public function create(Request $request)
  122. {
  123. $nav = $this->startNavigationContext($request);
  124. $this->data['nav'] = $nav;
  125. $this->data['back_url'] = $this->navigationBackUrl(
  126. $request,
  127. $nav,
  128. route('order.index', session('gp_orders'))
  129. );
  130. return view('orders.edit', $this->data);
  131. }
  132. /**
  133. * Store a newly created resource in storage.
  134. */
  135. public function store(StoreOrderRequest $request, NotificationService $notificationService)
  136. {
  137. $data = $request->validated();
  138. $products = $request->validated('products');
  139. $quantities = $request->validated('quantity');
  140. unset($data['products']);
  141. if(isset($data['id'])) {
  142. $order = Order::query()->where('id', $data['id'])->first();
  143. $status = $order->order_status_id;
  144. $statusErrors = $this->validateMountStatusChange($order, $data['order_status_id'] ?? null);
  145. if ($statusErrors !== []) {
  146. return $this->mountStatusValidationFailed($request, $statusErrors);
  147. }
  148. $order->update($data);
  149. $order->refresh();
  150. if($order->order_status_id != $status) {
  151. $notificationService->notifyOrderStatusChanged($order, auth()->user());
  152. }
  153. } else {
  154. $data['order_status_id'] = Order::STATUS_NEW;
  155. $order = Order::query()->create($data);
  156. $tg_group_name = '/' . $order->district->shortname
  157. . ' ' . $order->object_address
  158. . ' (' . $order->area->name . ')'
  159. . ' - ' . $order->user->name;
  160. $order->update(['tg_group_name' => $tg_group_name]);
  161. $notificationService->notifyOrderCreated($order, auth()->user());
  162. }
  163. // меняем список товаров заказа только если статус новый
  164. if($products && $quantities && ($order->order_status_id == 1)) {
  165. $desiredCounts = [];
  166. foreach ($products as $key => $productId) {
  167. $quantity = (int)($quantities[$key] ?? 0);
  168. if ($quantity < 1) {
  169. continue;
  170. }
  171. if (!isset($desiredCounts[$productId])) {
  172. $desiredCounts[$productId] = 0;
  173. }
  174. $desiredCounts[$productId] += $quantity;
  175. }
  176. $attachedSkus = ProductSKU::query()
  177. ->where('order_id', $order->id)
  178. ->whereNotNull('maf_order_id')
  179. ->with('product:id,article')
  180. ->get();
  181. $attachedByProduct = [];
  182. foreach ($attachedSkus as $sku) {
  183. if (!isset($attachedByProduct[$sku->product_id])) {
  184. $attachedByProduct[$sku->product_id] = 0;
  185. }
  186. $attachedByProduct[$sku->product_id]++;
  187. }
  188. $currentCounts = ProductSKU::query()
  189. ->where('order_id', $order->id)
  190. ->selectRaw('product_id, COUNT(*) as cnt')
  191. ->groupBy('product_id')
  192. ->pluck('cnt', 'product_id')
  193. ->map(fn ($count) => (int)$count)
  194. ->toArray();
  195. $errors = [];
  196. foreach ($attachedByProduct as $productId => $attachedCount) {
  197. $desiredCount = $desiredCounts[$productId] ?? 0;
  198. if ($desiredCount < $attachedCount) {
  199. $article = $attachedSkus->firstWhere('product_id', $productId)?->product?->article ?? ('ID ' . $productId);
  200. $errors[] = "Нельзя удалить привязанные МАФ {$article}: привязано {$attachedCount} шт.";
  201. }
  202. }
  203. // Если есть хотя бы один привязанный МАФ, запрещаем добавлять новые позиции/количество.
  204. if (!empty($attachedByProduct)) {
  205. foreach ($desiredCounts as $productId => $desiredCount) {
  206. $currentCount = $currentCounts[$productId] ?? 0;
  207. if ($desiredCount > $currentCount) {
  208. $errors[] = 'Нельзя добавлять новые позиции МАФ, пока на площадке есть привязанные МАФ.';
  209. break;
  210. }
  211. }
  212. }
  213. if (!empty($errors)) {
  214. return redirect()->back()->withInput()->with(['danger' => $errors]);
  215. }
  216. // Удаляем только непривязанные SKU и пересоздаём их по новому списку.
  217. ProductSKU::query()
  218. ->where('order_id', $order->id)
  219. ->whereNull('maf_order_id')
  220. ->delete();
  221. foreach ($desiredCounts as $productId => $desiredCount) {
  222. $attachedCount = $attachedByProduct[$productId] ?? 0;
  223. $toCreate = $desiredCount - $attachedCount;
  224. for ($i = 0; $i < $toCreate; $i++) {
  225. ProductSKU::query()->create([
  226. 'order_id' => $order->id,
  227. 'product_id' => $productId,
  228. 'status' => 'требуется'
  229. ]);
  230. }
  231. }
  232. }
  233. $order->refresh();
  234. $order->autoChangeStatus();
  235. $nav = $this->resolveNavToken($request);
  236. return redirect()->route('order.show', $this->withNav(['order' => $order], $nav));
  237. }
  238. private function validateMountStatusChange(Order $order, mixed $newStatusId): array
  239. {
  240. if ((int) $newStatusId !== Order::STATUS_IN_MOUNT) {
  241. return [];
  242. }
  243. return $order->getMountStatusErrors();
  244. }
  245. private function mountStatusValidationFailed(Request $request, array $errors)
  246. {
  247. if ($request->expectsJson() || $request->ajax()) {
  248. return response()->json([
  249. 'message' => $errors[0],
  250. 'errors' => $errors,
  251. ], 422);
  252. }
  253. return redirect()->back()->withInput()->with(['danger' => $errors]);
  254. }
  255. /**
  256. * Display the specified resource.
  257. */
  258. public function show(Request $request, int $order)
  259. {
  260. $this->data['order'] = Order::query()
  261. ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
  262. ->with([
  263. 'chatMessages.user',
  264. 'chatMessages.targetUser',
  265. 'chatMessages.notifiedUsers',
  266. 'chatMessages.files',
  267. ])
  268. ->find($order);
  269. if ($request->boolean('sync_year') && $this->data['order']) {
  270. $previousYear = year();
  271. $targetYear = (int)$this->data['order']->year;
  272. if ($previousYear !== $targetYear) {
  273. session(['year' => $targetYear]);
  274. session()->flash('warning', "Год переключен: {$previousYear} → {$targetYear} (по году площадки).");
  275. }
  276. }
  277. if (hasRole('brigadier') && $this->data['order']) {
  278. $canView = (int)$this->data['order']->brigadier_id === (int)auth()->id()
  279. && in_array((int)$this->data['order']->order_status_id, Order::visibleStatusIdsForBrigadier(), true);
  280. if (!$canView) {
  281. abort(403);
  282. }
  283. }
  284. $nav = $this->resolveNavToken($request);
  285. $this->rememberNavigation($request, $nav);
  286. $this->data['nav'] = $nav;
  287. $this->data['back_url'] = $this->navigationBackUrl(
  288. $request,
  289. $nav,
  290. route('order.index', session('gp_orders'))
  291. );
  292. $orderModel = $this->data['order'];
  293. $chatUsers = User::query()->orderBy('name')->get(['id', 'name', 'role']);
  294. $responsibleUserIds = User::query()
  295. ->where('role', Role::ADMIN)
  296. ->pluck('id')
  297. ->map(static fn ($id) => (int) $id)
  298. ->all();
  299. $responsibleUserIds = array_values(array_unique(array_filter(array_merge($responsibleUserIds, [
  300. $orderModel?->user_id ? (int) $orderModel->user_id : null,
  301. $orderModel?->brigadier_id ? (int) $orderModel->brigadier_id : null,
  302. ]))));
  303. $this->data['chatUsers'] = $chatUsers->map(fn ($u) => [
  304. 'id' => $u->id,
  305. 'name' => $u->name,
  306. 'role' => $u->role,
  307. ])->keyBy('id');
  308. $this->data['chatResponsibleUserIds'] = $responsibleUserIds;
  309. $this->data['chatManagerUserId'] = $orderModel?->user_id ? (int) $orderModel->user_id : null;
  310. $this->data['chatBrigadierUserId'] = $orderModel?->brigadier_id ? (int) $orderModel->brigadier_id : null;
  311. return view('orders.show', $this->data);
  312. }
  313. /**
  314. * Show the form for editing the specified resource.
  315. */
  316. public function edit(Request $request, Order $order)
  317. {
  318. $this->data['order'] = $order;
  319. $nav = $this->resolveNavToken($request);
  320. $this->rememberNavigation($request, $nav);
  321. $this->data['nav'] = $nav;
  322. $this->data['back_url'] = $this->navigationBackUrl(
  323. $request,
  324. $nav,
  325. route('order.index', session('gp_orders'))
  326. );
  327. return view('orders.edit', $this->data);
  328. }
  329. /**
  330. * Привязка товаров к заказу
  331. * @param Order $order
  332. * @return RedirectResponse
  333. * @throws Throwable
  334. */
  335. public function getMafToOrder(Order $order)
  336. {
  337. $attached = 0;
  338. $missingByProduct = [];
  339. DB::transaction(function () use ($order, &$attached, &$missingByProduct) {
  340. foreach ($order->products_sku as $productSku) {
  341. // Уже привязан, пропускаем
  342. if ($productSku->maf_order_id) {
  343. continue;
  344. }
  345. $mafOrder = MafOrder::query()
  346. ->where('product_id', $productSku->product_id)
  347. ->where('in_stock', '>', 0)
  348. ->orderBy('created_at')
  349. ->lockForUpdate()
  350. ->first();
  351. if (!$mafOrder) {
  352. $article = $productSku->product?->article ?? ('ID ' . $productSku->product_id);
  353. if (!isset($missingByProduct[$productSku->product_id])) {
  354. $missingByProduct[$productSku->product_id] = ['article' => $article, 'count' => 0];
  355. }
  356. $missingByProduct[$productSku->product_id]['count']++;
  357. continue;
  358. }
  359. $productSku->update(['maf_order_id' => $mafOrder->id, 'status' => 'отгружен']);
  360. $mafOrder->decrement('in_stock');
  361. $attached++;
  362. }
  363. });
  364. $order->autoChangeStatus();
  365. $success = [];
  366. $danger = [];
  367. if ($attached > 0) {
  368. $success[] = "Привязано МАФ: {$attached}.";
  369. }
  370. foreach ($missingByProduct as $missing) {
  371. $danger[] = "Не удалось привязать {$missing['count']} шт. МАФ {$missing['article']}: нет остатка на складе.";
  372. }
  373. if ($attached === 0 && empty($danger)) {
  374. $danger[] = 'Нет МАФ для привязки: все МАФы на площадке уже привязаны.';
  375. }
  376. $flash = [];
  377. if (!empty($success)) {
  378. $flash['success'] = $success;
  379. }
  380. if (!empty($danger)) {
  381. $flash['danger'] = $danger;
  382. }
  383. return redirect()->route('order.show', $order)->with($flash);
  384. }
  385. /**
  386. * @param Order $order
  387. * @return RedirectResponse
  388. */
  389. public function destroy(Order $order)
  390. {
  391. Order::query()->where('id', $order->id)->delete();
  392. ProductSKU::query()->where('order_id', $order->id)->delete();
  393. return redirect()->route('order.index', session('gp_orders'));
  394. }
  395. public function revertMaf(Order $order)
  396. {
  397. $detached = 0;
  398. $notFoundMafOrders = 0;
  399. DB::transaction(function () use ($order, &$detached, &$notFoundMafOrders) {
  400. foreach ($order->products_sku as $maf) {
  401. if (!$maf->maf_order_id) {
  402. continue;
  403. }
  404. $affectedRows = MafOrder::query()
  405. ->where('id', $maf->maf_order_id)
  406. ->lockForUpdate()
  407. ->increment('in_stock');
  408. if (!$affectedRows) {
  409. $notFoundMafOrders++;
  410. continue;
  411. }
  412. $maf->update(['maf_order_id' => null, 'status' => 'требуется']);
  413. $detached++;
  414. }
  415. });
  416. $order->autoChangeStatus();
  417. $success = [];
  418. $danger = [];
  419. if ($detached > 0) {
  420. $success[] = "Отвязано МАФ: {$detached}.";
  421. }
  422. if ($notFoundMafOrders > 0) {
  423. $danger[] = "Не удалось отвязать {$notFoundMafOrders} шт. МАФ: связанный заказ МАФ не найден.";
  424. }
  425. if ($detached === 0 && empty($danger)) {
  426. $danger[] = 'Нет МАФ для отвязки: на площадке нет привязанных МАФ.';
  427. }
  428. $flash = [];
  429. if (!empty($success)) {
  430. $flash['success'] = $success;
  431. }
  432. if (!empty($danger)) {
  433. $flash['danger'] = $danger;
  434. }
  435. return redirect()->route('order.show', $order)->with($flash);
  436. }
  437. public function moveMaf(Request $request)
  438. {
  439. $data = $request->validate([
  440. 'new_order_id' => 'required',
  441. 'ids' => 'required|json',
  442. ]);
  443. $ids = json_decode($data['ids'], true);
  444. $updated = [];
  445. foreach ($ids as $mafId) {
  446. $maf = ProductSKU::query()
  447. ->where('id', $mafId)
  448. ->first();
  449. if($maf) {
  450. $comment = $maf->comment . "\n" . date('Y-m-d H:i') . ' Перенесено с площадки: ' . $maf->order->common_name;
  451. $maf->update(['order_id' => $data['new_order_id'], 'comment' => $comment]);
  452. $updated[] = $maf;
  453. }
  454. }
  455. return response()->json(['success' => true]);
  456. }
  457. public function search(Request $request): array
  458. {
  459. $ret = [];
  460. $s = $request->get('s');
  461. $currentOrderId = $request->integer('current_order_id');
  462. $searchFields = $this->data['searchFields'];
  463. $result = OrderView::query();
  464. if($s) {
  465. $result->where(function ($query) use ($searchFields, $s) {
  466. foreach ($searchFields as $searchField) {
  467. $query->orWhere($searchField, 'LIKE', '%' . $s . '%');
  468. }
  469. });
  470. }
  471. if ($currentOrderId > 0) {
  472. $result->where('id', '!=', $currentOrderId);
  473. }
  474. $result->orderBy('object_address');
  475. foreach ($result->get() as $p) {
  476. $ret[$p->id] = $p->move_maf_name;
  477. }
  478. return $ret;
  479. }
  480. public function uploadPhoto(Request $request, Order $order, FileService $fileService)
  481. {
  482. $data = $request->validate([
  483. 'photo.*' => 'mimes:jpeg,jpg,png,webp',
  484. ]);
  485. try {
  486. $f = [];
  487. foreach ($data['photo'] as $photo) {
  488. $f[] = $fileService->saveUploadedFile('orders/' . $order->id . '/photo', $photo);
  489. }
  490. $order->photos()->syncWithoutDetaching($f);
  491. } catch (Throwable $e) {
  492. report($e);
  493. return redirect()->route('order.show', $order)
  494. ->with(['error' => 'Ошибка загрузки фотографий. Проверьте имя файла и повторите попытку.']);
  495. }
  496. return redirect()->route('order.show', $order)->with(['success' => 'Фотографии успешно загружены!']);
  497. }
  498. public function deletePhoto(Order $order, File $file, FileService $fileService)
  499. {
  500. $order->photos()->detach($file);
  501. Storage::disk('public')->delete($file->path);
  502. $file->delete();
  503. return redirect()->route('order.show', $order);
  504. }
  505. public function deleteAllPhotos(Order $order)
  506. {
  507. $files = $order->photos;
  508. $order->photos()->detach();
  509. foreach ($files as $file) {
  510. Storage::disk('public')->delete($file->path);
  511. $file->delete();
  512. }
  513. return redirect()->route('order.show', $order);
  514. }
  515. public function uploadDocument(Request $request, Order $order, FileService $fileService)
  516. {
  517. $data = $request->validate([
  518. 'document.*' => 'file',
  519. ]);
  520. try {
  521. $f = [];
  522. $i = 0;
  523. foreach ($data['document'] as $document) {
  524. if ($i++ >= 5) break;
  525. $f[] = $fileService->saveUploadedFile('orders/' . $order->id . '/document', $document);
  526. }
  527. $order->documents()->syncWithoutDetaching($f);
  528. } catch (Throwable $e) {
  529. report($e);
  530. return redirect()->route('order.show', $order)
  531. ->with(['error' => 'Ошибка загрузки документов. Проверьте имя файла и повторите попытку.']);
  532. }
  533. return redirect()->route('order.show', $order)->with(['success' => 'Документы успешно загружены!']);
  534. }
  535. public function deleteDocument(Order $order, File $file)
  536. {
  537. $order->documents()->detach($file);
  538. Storage::disk('public')->delete($file->path);
  539. $file->delete();
  540. return redirect()->route('order.show', $order);
  541. }
  542. public function deleteAllDocuments(Order $order)
  543. {
  544. $files = $order->documents;
  545. $order->documents()->detach();
  546. foreach ($files as $file) {
  547. Storage::disk('public')->delete($file->path);
  548. $file->delete();
  549. }
  550. return redirect()->route('order.show', $order);
  551. }
  552. public function uploadStatement(Request $request, Order $order, FileService $fileService)
  553. {
  554. $data = $request->validate([
  555. 'statement.*' => 'file',
  556. ]);
  557. try {
  558. $f = [];
  559. $i = 0;
  560. foreach ($data['statement'] as $statement) {
  561. if ($i++ >= 5) break;
  562. $f[] = $fileService->saveUploadedFile('orders/' . $order->id . '/statement', $statement);
  563. }
  564. $order->statements()->syncWithoutDetaching($f);
  565. } catch (Throwable $e) {
  566. report($e);
  567. return redirect()->route('order.show', $order)
  568. ->with(['error' => 'Ошибка загрузки ведомостей. Проверьте имя файла и повторите попытку.']);
  569. }
  570. return redirect()->route('order.show', $order)->with(['success' => 'Ведомости успешно загружены!']);
  571. }
  572. public function deleteStatement(Order $order, File $file)
  573. {
  574. $order->statements()->detach($file);
  575. Storage::disk('public')->delete($file->path);
  576. $file->delete();
  577. return redirect()->route('order.show', $order);
  578. }
  579. public function deleteAllStatements(Order $order)
  580. {
  581. $files = $order->statements;
  582. $order->statements()->detach();
  583. foreach ($files as $file) {
  584. Storage::disk('public')->delete($file->path);
  585. $file->delete();
  586. }
  587. return redirect()->route('order.show', $order);
  588. }
  589. public function generateInstallationPack(Order $order)
  590. {
  591. $errors = $order->isAllMafConnected();
  592. if($errors) {
  593. return redirect()->route('order.show', $order)->with(['danger' => $errors]);
  594. }
  595. GenerateInstallationPack::dispatch($order, auth()->user()->id);
  596. return redirect()->route('order.show', $order)->with(['success' => 'Задача генерации документов создана!']);
  597. }
  598. public function generateHandoverPack(Order $order)
  599. {
  600. if($errors = $order->canCreateHandover()) {
  601. return redirect()->route('order.show', $order)->with(['danger' => $errors]);
  602. }
  603. GenerateHandoverPack::dispatch($order, auth()->user()->id);
  604. return redirect()->route('order.show', $order)->with(['success' => 'Задача генерации документов создана!']);
  605. }
  606. public function generatePhotosPack(Order $order)
  607. {
  608. GenerateFilesPack::dispatch($order, $order->photos, auth()->user()->id, 'Фото');
  609. return redirect()->back()->with(['success' => 'Задача архивации создана!']);
  610. }
  611. public function createTtn(CreteTtnRequest $request)
  612. {
  613. $ttn = Ttn::query()->create([
  614. 'year' => date('Y'),
  615. 'ttn_number' => Ttn::reserveNextTtnNumber(),
  616. 'ttn_number_suffix' => 'И',
  617. 'order_number' => $request->order_number,
  618. 'order_date' => $request->order_date,
  619. 'departure_date' => $request->departure_date,
  620. 'order_sum' => $request->order_sum,
  621. 'skus' => json_encode($request->skus),
  622. ]);
  623. GenerateTtnPack::dispatch($ttn, auth()->user()->id);
  624. return redirect()->back()->with(['success' => 'Задача формирования ТН создана!']);
  625. }
  626. public function export(Request $request)
  627. {
  628. $request->validate([
  629. 'withFilter' => 'nullable',
  630. 'filters' => 'nullable|array',
  631. 's' => 'nullable|string',
  632. ]);
  633. $orders = Order::query();
  634. if ($request->boolean('withFilter')) {
  635. $filterRequest = new Request(array_filter([
  636. 'filters' => $request->input('filters', []),
  637. 's' => $request->input('s'),
  638. 'sortBy' => $request->input('sortBy'),
  639. 'order' => $request->input('order'),
  640. ], static fn ($value) => $value !== null));
  641. $model = new OrderView;
  642. $this->createFilters($model, 'user_name', 'district_name', 'area_name', 'object_type_name', 'brigadier_name', 'order_status_name', 'ready_to_mount');
  643. $this->createDateFilters($model, 'installation_date', 'ready_date');
  644. $this->data['ranges'] = [];
  645. $q = $model::query();
  646. $this->acceptFilters($q, $filterRequest);
  647. $this->acceptSearch($q, $filterRequest);
  648. $this->setSortAndOrderBy($model, $filterRequest);
  649. if (hasRole('brigadier')) {
  650. $q->where('brigadier_id', auth()->id())
  651. ->whereIn('order_status_id', Order::visibleStatusIdsForBrigadier());
  652. }
  653. if (hasRole(Role::WAREHOUSE_HEAD)) {
  654. $q->whereNotNull('brigadier_id');
  655. $q->whereNotNull('installation_date');
  656. }
  657. $this->applyStableSorting($q);
  658. $orderIds = $q->pluck('id');
  659. $orders = Order::query()
  660. ->whereIn('id', $orderIds)
  661. ->get()
  662. ->sortBy(static fn (Order $order) => $orderIds->search($order->id))
  663. ->values();
  664. } else {
  665. $orders = $orders->get();
  666. }
  667. ExportOrdersJob::dispatch($orders, $request->user()->id);
  668. return redirect()->route('order.index', session('gp_orders'))
  669. ->with(['success' => 'Задача выгрузки создана!']);
  670. }
  671. public function exportOne(Order $order, Request $request)
  672. {
  673. ExportOneOrderJob::dispatch($order, $request->user()->id);
  674. return redirect()->route('order.show', $order->id)
  675. ->with(['success' => 'Задача выгрузки создана!']);
  676. }
  677. public function downloadTechDocs(Order $order): BinaryFileResponse
  678. {
  679. $techDocsPath = public_path('images/tech-docs');
  680. $articles = $order->products_sku
  681. ->pluck('product.article')
  682. ->unique()
  683. ->filter()
  684. ->values();
  685. if ($articles->isEmpty()) {
  686. abort(404, 'Нет МАФов на площадке');
  687. }
  688. $tempFile = tempnam(sys_get_temp_dir(), 'tech_docs_');
  689. if ($tempFile === false) {
  690. abort(500, 'Не удалось создать временный файл архива');
  691. }
  692. $zip = new ZipArchive();
  693. $result = $zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  694. if ($result !== true) {
  695. @unlink($tempFile);
  696. abort(500, 'Не удалось создать архив документации');
  697. }
  698. $filesAdded = 0;
  699. foreach ($articles as $article) {
  700. $articlePath = $techDocsPath . '/' . $article;
  701. if (!is_dir($articlePath)) {
  702. continue;
  703. }
  704. $files = new \RecursiveIteratorIterator(
  705. new \RecursiveDirectoryIterator($articlePath, \RecursiveDirectoryIterator::SKIP_DOTS),
  706. \RecursiveIteratorIterator::LEAVES_ONLY
  707. );
  708. foreach ($files as $file) {
  709. if ($file->isFile()) {
  710. $relativePath = $article . '/' . $file->getFilename();
  711. $zip->addFile($file->getRealPath(), $relativePath);
  712. $filesAdded++;
  713. }
  714. }
  715. }
  716. if (!$filesAdded) {
  717. $zip->addFromString('readme.txt', 'Нет документации для этих МАФ!');
  718. }
  719. $zip->close();
  720. // WebView clients are more reliable with ASCII attachment names.
  721. $archiveName = 'tech_docs_order_' . $order->id . '_' . Str::slug((string)$order->object_address) . '.zip';
  722. $archiveName = trim($archiveName, '._');
  723. if ($archiveName === '.zip' || $archiveName === 'zip' || $archiveName === '') {
  724. $archiveName = 'tech_docs_order_' . $order->id . '.zip';
  725. }
  726. return response()->download($tempFile, $archiveName, [
  727. 'Content-Type' => 'application/zip',
  728. ])->deleteFileAfterSend(true);
  729. }
  730. }