ProductController.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Requests\StoreProductRequest;
  4. use App\Jobs\Export\ExportCatalog;
  5. use App\Models\File;
  6. use App\Models\Product;
  7. use App\Services\FileService;
  8. use Illuminate\Http\RedirectResponse;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Storage;
  12. use Throwable;
  13. class ProductController extends Controller
  14. {
  15. protected array $data = [
  16. 'active' => 'catalog',
  17. 'title' => 'Каталог',
  18. 'id' => 'products',
  19. 'header' => [
  20. 'image' => 'Картинка',
  21. 'id' => 'ID',
  22. 'article' => 'Артикул',
  23. 'nomenclature_number' => 'Номер номенклатуры',
  24. 'manufacturer' => 'Производитель',
  25. 'unit' => 'Ед. изм.',
  26. 'name_tz' => 'Наименование ТЗ',
  27. 'type_tz' => 'Тип по ТЗ',
  28. 'type' => 'Тип',
  29. 'manufacturer_name' => 'Наименование производителя',
  30. 'sizes' => 'Размеры',
  31. 'product_price_txt' => 'Цена товара',
  32. 'installation_price_txt' => 'Цена установки',
  33. 'total_price_txt' => 'Итоговая цена',
  34. 'note' => 'Примечания',
  35. 'created_at' => 'Дата создания',
  36. 'certificate_id' => 'Сертификат',
  37. 'passport_name' => 'Наименование по паспорту',
  38. 'statement_name' => 'Наименование в ведомости',
  39. 'service_life' => 'Срок службы',
  40. 'certificate_number' => 'Номер сертификата',
  41. 'certificate_date' => 'Дата сертификата',
  42. 'certificate_issuer' => 'Орган сертификации',
  43. 'certificate_type' => 'Вид сертификации',
  44. 'weight' => 'Вес',
  45. 'volume' => 'Объем',
  46. 'places' => 'Мест',
  47. ],
  48. 'searchFields' => [
  49. 'nomenclature_number',
  50. 'article',
  51. 'name_tz',
  52. 'manufacturer_name',
  53. 'note',
  54. ],
  55. ];
  56. public function index(Request $request)
  57. {
  58. session(['gp_products' => $request->query()]);
  59. $nav = $this->resolveNavToken($request);
  60. $this->rememberNavigation($request, $nav);
  61. $model = new Product;
  62. // fill filters
  63. $this->createFilters($model, 'type_tz', 'type', 'certificate_id');
  64. $this->createRangeFilters($model, 'nomenclature_number', 'product_price', 'installation_price', 'total_price');
  65. $this->createDateFilters($model, 'certificate_date', 'created_at');
  66. // create request
  67. $q = $model::query();
  68. $this->acceptFilters($q, $request);
  69. $this->acceptSearch($q, $request);
  70. $this->setSortAndOrderBy($model, $request);
  71. $this->applyStableSorting($q);
  72. $this->data['products'] = $q->paginate($this->data['per_page'])->withQueryString();
  73. $this->data['nav'] = $nav;
  74. return view('catalog.index', $this->data);
  75. }
  76. public function show(Request $request, int $product)
  77. {
  78. $nav = $this->resolveNavToken($request);
  79. $this->rememberNavigation($request, $nav);
  80. $this->data['nav'] = $nav;
  81. $this->data['back_url'] = $this->navigationBackUrl(
  82. $request,
  83. $nav,
  84. route('catalog.index', session('gp_products'))
  85. );
  86. $this->data['product'] = Product::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->find($product);
  87. return view('catalog.edit', $this->data);
  88. }
  89. public function create(Request $request)
  90. {
  91. $nav = $this->resolveNavToken($request);
  92. $this->rememberNavigation($request, $nav);
  93. $this->data['nav'] = $nav;
  94. $this->data['back_url'] = $this->navigationBackUrl(
  95. $request,
  96. $nav,
  97. route('catalog.index', session('gp_products'))
  98. );
  99. $this->data['product'] = null;
  100. return view('catalog.edit', $this->data);
  101. }
  102. public function store(StoreProductRequest $request)
  103. {
  104. Product::create($request->validated());
  105. $nav = $this->resolveNavToken($request);
  106. $backUrl = $this->navigationParentUrl(
  107. $nav,
  108. route('catalog.index', session('gp_products'))
  109. );
  110. return redirect()->to($backUrl);
  111. }
  112. public function update(StoreProductRequest $request, Product $product)
  113. {
  114. $product->update($request->validated());
  115. $nav = $this->resolveNavToken($request);
  116. $backUrl = $this->navigationParentUrl(
  117. $nav,
  118. route('catalog.index', session('gp_products'))
  119. );
  120. return redirect()->to($backUrl);
  121. }
  122. public function delete(Product $product)
  123. {
  124. $product->delete();
  125. return redirect()->route('catalog.index', session('gp_products'));
  126. }
  127. public function export(Request $request)
  128. {
  129. $request->validate([
  130. 'withFilter' => 'nullable',
  131. 'filters' => 'nullable|array',
  132. 's' => 'nullable|string',
  133. ]);
  134. $filters = [];
  135. if ($request->boolean('withFilter')) {
  136. $filters = $request->filters ?? [];
  137. if ($request->filled('s')) {
  138. $filters['s'] = $request->string('s')->toString();
  139. }
  140. }
  141. $filters['year'] = year();
  142. ExportCatalog::dispatch($filters, $request->user()->id);
  143. Log::info('ExportCatalog job created!');
  144. return redirect()->route('catalog.index', session('gp_products'))->with(['success' => 'Задача экспорта успешно создана!']);
  145. }
  146. /**
  147. * ajax
  148. * @param Request $request
  149. * @return array
  150. */
  151. public function search(Request $request): array
  152. {
  153. $s = $request->get('s');
  154. $searchFields = $this->data['searchFields'];
  155. $ret = [];
  156. if($s) {
  157. $result = Product::query()->where(function ($query) use ($searchFields, $s) {
  158. foreach ($searchFields as $searchField) {
  159. $query->orWhere($searchField, 'LIKE', '%' . $s . '%');
  160. }
  161. });
  162. foreach ($result->get() as $p) {
  163. $ret[$p->id] = $p->common_name;
  164. }
  165. }
  166. return $ret;
  167. }
  168. public function uploadCertificate(Request $request, Product $product, FileService $fileService)
  169. {
  170. $data = $request->validate([
  171. 'certificate' => 'file',
  172. ]);
  173. try {
  174. $f = $fileService->saveUploadedFile('products/' . $product->id . '/certificate', $data['certificate']);
  175. $product->update(['certificate_id' => $f->id]);
  176. } catch (Throwable $e) {
  177. report($e);
  178. return $this->redirectToCatalogShow($request, $product)
  179. ->with(['error' => 'Ошибка загрузки сертификата. Проверьте имя файла и повторите попытку.']);
  180. }
  181. return $this->redirectToCatalogShow($request, $product)
  182. ->with(['success' => 'Сертификат успешно загружен!']);
  183. }
  184. public function deleteCertificate(Request $request, Product $product, File $file)
  185. {
  186. $product->update(['certificate_id' => null]);
  187. Storage::disk('public')->delete($file->path);
  188. $file->delete();
  189. return $this->redirectToCatalogShow($request, $product);
  190. }
  191. public function uploadThumbnail(Request $request, Product $product): RedirectResponse
  192. {
  193. $request->validate([
  194. 'thumbnail' => 'required|file|mimes:jpg,jpeg|max:5120',
  195. ]);
  196. $file = $request->file('thumbnail');
  197. $filename = $product->article . '.0000.0000.jpg';
  198. $destinationPath = public_path('images/main');
  199. // Удаляем старый файл если существует
  200. $oldFilePath = $destinationPath . '/' . $filename;
  201. if (file_exists($oldFilePath)) {
  202. unlink($oldFilePath);
  203. }
  204. // Сохраняем новый файл
  205. $file->move($destinationPath, $filename);
  206. return $this->redirectToCatalogShow($request, $product)
  207. ->with('success', 'Миниатюра успешно загружена');
  208. }
  209. private function redirectToCatalogShow(Request $request, Product $product): RedirectResponse
  210. {
  211. $nav = $this->resolveNavToken($request);
  212. return redirect()->route('catalog.show', $this->withNav(['product' => $product], $nav));
  213. }
  214. }