ProductController.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Helpers\DateHelper;
  4. use App\Jobs\Export\ExportCatalog;
  5. use App\Jobs\Import\ImportCatalog;
  6. use App\Models\Product;
  7. use Illuminate\Http\RedirectResponse;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\Storage;
  11. use Illuminate\Support\Str;
  12. class ProductController extends Controller
  13. {
  14. protected array $data = [
  15. 'active' => 'catalog',
  16. 'title' => 'Каталог',
  17. 'id' => 'products',
  18. 'header' => [
  19. 'id' => 'ID',
  20. 'year' => 'Год',
  21. 'nomenclature_number' => 'Номер номенклатуры',
  22. 'article' => 'Артикул',
  23. 'manufacturer' => 'Производитель',
  24. 'name_tz' => 'Наименование ТЗ',
  25. 'type_tz' => 'Тип по ТЗ',
  26. 'type' => 'Тип',
  27. 'manufacturer_name' => 'Наименование производителя',
  28. 'sizes' => 'Размеры',
  29. 'price_status' => 'Статус цены',
  30. 'product_price_txt' => 'Цена товара',
  31. 'installation_price_txt' => 'Цена установки',
  32. 'service_price_txt' => 'Цена обслуживания',
  33. 'total_price_txt' => 'Итоговая цена',
  34. 'note' => 'Примечания',
  35. 'created_at' => 'Дата создания',
  36. ]
  37. ];
  38. public function index(Request $request)
  39. {
  40. $filters = [
  41. 'type_tz' => [
  42. 'title' => 'Тип по ТЗ',
  43. 'values' => Product::getFilters('type_tz')
  44. ],
  45. 'type' => [
  46. 'title' => 'Тип',
  47. 'values' => Product::getFilters('type')
  48. ],
  49. ];
  50. $ranges = [
  51. 'product_price' => [
  52. 'title' => 'Цена товара',
  53. 'min' => Product::query()->min('product_price') / 100,
  54. 'max' => Product::query()->max('product_price') / 100,
  55. ],
  56. 'installation_price' => [
  57. 'title' => 'Цена установки',
  58. 'min' => Product::query()->min('installation_price') / 100,
  59. 'max' => Product::query()->max('installation_price') / 100,
  60. ],
  61. 'service_price' => [
  62. 'title' => 'Цена обслуживания',
  63. 'min' => Product::query()->min('service_price') / 100,
  64. 'max' => Product::query()->max('service_price') / 100,
  65. ],
  66. 'total_price' => [
  67. 'title' => 'Итоговая цена',
  68. 'min' => Product::query()->min('total_price') / 100,
  69. 'max' => Product::query()->max('total_price') / 100,
  70. ],
  71. ];
  72. $dates = [
  73. 'created_at' => [
  74. 'title' => 'Дата создания',
  75. 'min' => DateHelper::getDateForDB(Product::query()->min('created_at') ?? ''),
  76. 'max' => DateHelper::getDateForDB(Product::query()->max('created_at') ?? ''),
  77. ]
  78. ];
  79. $this->data['searchFields'] = [
  80. 'nomenclature_number',
  81. 'article',
  82. 'name_tz',
  83. 'manufacturer_name',
  84. 'note',
  85. ];
  86. // fill filters
  87. $this->data['filters'] = $filters;
  88. $this->data['dates'] = $dates;
  89. $this->data['ranges'] = $ranges;
  90. // create request
  91. $q = Product::query();
  92. // accept filters
  93. if(!empty($request->filters) && is_array($request->filters)) {
  94. foreach ($request->filters as $filterName => $filterValue) {
  95. if(!$filterValue) continue;
  96. if(Str::contains($filterName, 'price')) {
  97. $filterValue = $filterValue * 100;
  98. }
  99. if(Str::endsWith($filterName, '_from')) {
  100. if(is_string($filterValue) && DateHelper::isDate($filterValue)) {
  101. $filterValue .= ' 00:00:00';
  102. }
  103. $q->where(Str::replace('_from', '', $filterName), '>=', $filterValue);
  104. } elseif(Str::endsWith($filterName, '_to')) {
  105. if(is_string($filterValue) && DateHelper::isDate($filterValue)) {
  106. $filterValue .= ' 23:59:59';
  107. }
  108. $q->where(Str::replace('_to', '', $filterName), '<=', $filterValue);
  109. } else {
  110. $q->where($filterName, '=', $filterValue);
  111. }
  112. }
  113. }
  114. // accept search
  115. if(!empty($request->s)) {
  116. $s = $request->s;
  117. $searchFields = $this->data['searchFields'];
  118. $q->where(function ($query) use ($searchFields, $s) {
  119. foreach ($searchFields as $searchField) {
  120. $query->orWhere($searchField, 'LIKE', '%' . $s . '%');
  121. }
  122. });
  123. }
  124. // ------- setup sort and order --------------------------------------------------------------------------------
  125. $this->data['sortBy'] = (!empty($request->sortBy))
  126. ? Str::replace('_txt', '', $request->sortBy) // remove '_txt' fields modifier
  127. : Product::DEFAULT_SORT_BY;
  128. // check for sortBy is valid field
  129. $p = new Product();
  130. if(!in_array($this->data['sortBy'], array_merge(['id', 'created_at'], $p->getFillable()))) {
  131. $this->data['sortBy'] = Product::DEFAULT_SORT_BY;
  132. }
  133. // set order
  134. $this->data['orderBy'] = (!empty($request->order)) ? 'desc' : 'asc';
  135. $q->orderBy($this->data['sortBy'], $this->data['orderBy']);
  136. // $q->dumpRawSql();
  137. $this->data['products'] = $q->paginate()->withQueryString();
  138. return view('catalog.index', $this->data);
  139. }
  140. public function show()
  141. {
  142. }
  143. /**
  144. * @param Request $request
  145. * @return RedirectResponse
  146. */
  147. public function import(Request $request)
  148. {
  149. // validate data
  150. $request->validate([
  151. 'year' => 'required|integer|min:2000|max:' . (int)date('Y', strtotime('next year')),
  152. 'import_file' => 'file',
  153. ]);
  154. // load and save file
  155. $path = Str::random(2) . '/' . Str::uuid() . '.' .$request->file('import_file')->getClientOriginalExtension();
  156. Storage::disk('upload')->put($path, $request->file('import_file')->getContent());
  157. // dispatch job
  158. ImportCatalog::dispatch($path, $request->year, $request->user()->id);
  159. Log::info('ImportCatalog job created!');
  160. return redirect()->route('catalog.index')->with(['success' => 'Задача импорта успешно создана!']);
  161. }
  162. public function export(Request $request)
  163. {
  164. $request->validate([
  165. 'withFilter' => 'nullable',
  166. 'filters' => 'nullable|array',
  167. ]);
  168. // load and save file
  169. $filters = ($request->withFilter) ? $request->filters ?? [] : [];
  170. // dispatch job
  171. ExportCatalog::dispatch($filters , $request->user()->id);
  172. Log::info('ImportCatalog job created!');
  173. return redirect()->route('catalog.index')->with(['success' => 'Задача экспорта успешно создана!']);
  174. }
  175. }