ProductController.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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->startNavigationContext($request);
  60. $model = new Product;
  61. // fill filters
  62. $this->createFilters($model, 'type_tz', 'type', 'certificate_id');
  63. $this->createRangeFilters($model, 'nomenclature_number', 'product_price', 'installation_price', 'total_price');
  64. $this->createDateFilters($model, 'certificate_date', 'created_at');
  65. // create request
  66. $q = $model::query();
  67. $this->acceptFilters($q, $request);
  68. $this->acceptSearch($q, $request);
  69. $this->setSortAndOrderBy($model, $request);
  70. $this->applyStableSorting($q);
  71. $this->data['products'] = $q->paginate($this->data['per_page'])->withQueryString();
  72. $this->data['nav'] = $nav;
  73. return view('catalog.index', $this->data);
  74. }
  75. public function show(Request $request, int $product)
  76. {
  77. $nav = $this->resolveNavToken($request);
  78. $this->rememberNavigation($request, $nav);
  79. $this->data['nav'] = $nav;
  80. $this->data['back_url'] = $this->navigationBackUrl(
  81. $request,
  82. $nav,
  83. route('catalog.index', session('gp_products'))
  84. );
  85. $this->data['product'] = Product::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->find($product);
  86. return view('catalog.edit', $this->data);
  87. }
  88. public function create(Request $request)
  89. {
  90. $nav = $this->resolveNavToken($request);
  91. $this->rememberNavigation($request, $nav);
  92. $this->data['nav'] = $nav;
  93. $this->data['back_url'] = $this->navigationBackUrl(
  94. $request,
  95. $nav,
  96. route('catalog.index', session('gp_products'))
  97. );
  98. $this->data['product'] = null;
  99. return view('catalog.edit', $this->data);
  100. }
  101. public function store(StoreProductRequest $request)
  102. {
  103. Product::create($request->validated());
  104. $nav = $this->resolveNavToken($request);
  105. $backUrl = $this->navigationParentUrl(
  106. $nav,
  107. route('catalog.index', session('gp_products'))
  108. );
  109. return redirect()->to($backUrl);
  110. }
  111. public function update(StoreProductRequest $request, Product $product)
  112. {
  113. $product->update($request->validated());
  114. $nav = $this->resolveNavToken($request);
  115. $backUrl = $this->navigationParentUrl(
  116. $nav,
  117. route('catalog.index', session('gp_products'))
  118. );
  119. return redirect()->to($backUrl);
  120. }
  121. public function delete(Product $product)
  122. {
  123. $product->delete();
  124. return redirect()->route('catalog.index', session('gp_products'));
  125. }
  126. public function export(Request $request)
  127. {
  128. $request->validate([
  129. 'withFilter' => 'nullable',
  130. 'filters' => 'nullable|array',
  131. 's' => 'nullable|string',
  132. ]);
  133. $filters = [];
  134. if ($request->boolean('withFilter')) {
  135. $filters = $request->filters ?? [];
  136. if ($request->filled('s')) {
  137. $filters['s'] = $request->string('s')->toString();
  138. }
  139. }
  140. $filters['year'] = year();
  141. ExportCatalog::dispatch($filters, $request->user()->id);
  142. Log::info('ExportCatalog job created!');
  143. return redirect()->route('catalog.index', session('gp_products'))->with(['success' => 'Задача экспорта успешно создана!']);
  144. }
  145. /**
  146. * ajax
  147. * @param Request $request
  148. * @return array
  149. */
  150. public function search(Request $request): array
  151. {
  152. $s = $request->get('s');
  153. $searchFields = $this->data['searchFields'];
  154. $ret = [];
  155. if($s) {
  156. $result = Product::query()->where(function ($query) use ($searchFields, $s) {
  157. foreach ($searchFields as $searchField) {
  158. $query->orWhere($searchField, 'LIKE', '%' . $s . '%');
  159. }
  160. });
  161. foreach ($result->get() as $p) {
  162. $ret[$p->id] = $p->common_name;
  163. }
  164. }
  165. return $ret;
  166. }
  167. public function uploadCertificate(Request $request, Product $product, FileService $fileService)
  168. {
  169. $data = $request->validate([
  170. 'certificate' => 'file',
  171. ]);
  172. try {
  173. $f = $fileService->saveUploadedFile('products/' . $product->id . '/certificate', $data['certificate']);
  174. $product->update(['certificate_id' => $f->id]);
  175. } catch (Throwable $e) {
  176. report($e);
  177. return $this->redirectToCatalogShow($request, $product)
  178. ->with(['error' => 'Ошибка загрузки сертификата. Проверьте имя файла и повторите попытку.']);
  179. }
  180. return $this->redirectToCatalogShow($request, $product)
  181. ->with(['success' => 'Сертификат успешно загружен!']);
  182. }
  183. public function deleteCertificate(Request $request, Product $product, File $file)
  184. {
  185. $product->update(['certificate_id' => null]);
  186. Storage::disk('public')->delete($file->path);
  187. $file->delete();
  188. return $this->redirectToCatalogShow($request, $product);
  189. }
  190. public function uploadThumbnail(Request $request, Product $product): RedirectResponse
  191. {
  192. $request->validate([
  193. 'thumbnail' => 'required|file|mimes:jpg,jpeg|max:5120',
  194. ]);
  195. $file = $request->file('thumbnail');
  196. $filename = $product->article . '.0000.0000.jpg';
  197. $destinationPath = public_path('images/main');
  198. // Удаляем старый файл если существует
  199. $oldFilePath = $destinationPath . '/' . $filename;
  200. if (file_exists($oldFilePath)) {
  201. unlink($oldFilePath);
  202. }
  203. // Сохраняем новый файл
  204. $file->move($destinationPath, $filename);
  205. return $this->redirectToCatalogShow($request, $product)
  206. ->with('success', 'Миниатюра успешно загружена');
  207. }
  208. private function redirectToCatalogShow(Request $request, Product $product): RedirectResponse
  209. {
  210. $nav = $this->resolveNavToken($request);
  211. return redirect()->route('catalog.show', $this->withNav(['product' => $product], $nav));
  212. }
  213. }