ProductController.php 7.4 KB

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