ProductController.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\Product;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Str;
  6. class ProductController extends Controller
  7. {
  8. public function index(Request $request){
  9. $data['products'] = Product::query()->paginate(20);
  10. $data['series'] = Product::query()->select('series')->distinct()->OrderBy('series')->get();
  11. return view('products.index', $data);
  12. }
  13. public function upload(Request $request){
  14. $xls = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($request->file('file'));
  15. $xls->setReadDataOnly(true);
  16. $sheet = $xls->load($request->file('file'));
  17. // read xls to array
  18. $goods = $sheet->setActiveSheetIndex(0)->toArray();
  19. unset($sheet, $xls);
  20. $series = '';
  21. $i = 1;
  22. $created = 0;
  23. $updated = 0;
  24. $no_image = [];
  25. foreach ($goods as $good){
  26. // check first line and skip it
  27. if($good[0] === '№п/п' && $good['3'] === 'Наименование') continue;
  28. // check the line is name of series
  29. if($good[0] == NULL && $good[1] == NULL && $good[2] == NULL && is_string($good[3])){
  30. $series = $good[3];
  31. continue;
  32. }
  33. $tmp = explode("\n", $good[3]);
  34. if(!isset($tmp[1])){
  35. $good[3] = preg_replace('!\s+!', ' ', $good[3]);
  36. $tmp = explode(' ', $good[3], 2);
  37. }
  38. $data = [
  39. // 'article' => $tmp[0],
  40. 'series' => $series,
  41. 'name' => (isset($tmp[1])) ? $tmp[1] : 'error',
  42. 'name_for_form' => $good[2],
  43. 'product_group' => $good[1],
  44. 'price' => $good[5],
  45. 'characteristics' => $good[4],
  46. 'tech_description' => $good[7],
  47. 'tech_description_short' => $good[8],
  48. 'image_path' => $this->find_image($tmp[0]),
  49. ];
  50. $a= Product::query()->updateOrCreate(['article' => $tmp[0]], $data);
  51. if($a->wasRecentlyCreated) $created++; else $updated++;
  52. //echo $i++ . '. Серия: ' . $series . ', артикул: ' . $tmp[0] . '<br>';
  53. $i++;
  54. if($data['image_path'] == '') $no_image[] = $tmp[0];
  55. }
  56. return view('products.import_result', ['count' => $i, 'updated' => $updated, 'created' => $created, 'no_image' => $no_image]);
  57. }
  58. private $allfiles; // rememer files list
  59. private function find_image($article){
  60. $path_to_files = './' . env('IMAGES_PATH', '---') . '/';
  61. if(!isset($this->allfiles) || empty($this->allfiles)){
  62. $this->allfiles = scandir($path_to_files);
  63. }
  64. foreach ($this->allfiles as $filename){
  65. if((mb_strpos($filename, $article) !== false) || (
  66. mb_strpos(Str::lower($filename), Str::slug($article)) !== false
  67. ))
  68. return $filename;
  69. }
  70. return '';
  71. }
  72. }