OrderController.php 32 KB

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