OrderController.php 34 KB

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