OrderController.php 35 KB

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