海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.7 KiB

  1. <?php
  2. namespace App\Jobs;
  3. use App\Imports\ProductImport;
  4. use Exception;
  5. use Illuminate\Bus\Queueable;
  6. use Illuminate\Contracts\Queue\ShouldBeUnique;
  7. use Illuminate\Contracts\Queue\ShouldQueue;
  8. use Illuminate\Foundation\Bus\Dispatchable;
  9. use Illuminate\Queue\InteractsWithQueue;
  10. use Illuminate\Queue\SerializesModels;
  11. use Illuminate\Support\Facades\Storage;
  12. use Maatwebsite\Excel\Facades\Excel;
  13. use ZipArchive;
  14. class ImportProductFromExcel implements ShouldQueue
  15. {
  16. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  17. private int $supplier_id;
  18. private string $zip_file;
  19. /**
  20. * Create a new job instance.
  21. *
  22. * @return void
  23. */
  24. public function __construct(int $supplier_id, string $zip_file)
  25. {
  26. $this->supplier_id = $supplier_id;
  27. $this->zip_file = $zip_file;
  28. }
  29. /**
  30. * Execute the job.
  31. *
  32. * @return void
  33. * @throws Exception
  34. */
  35. public function handle()
  36. {
  37. if (!$this->supplier_id) {
  38. throw new Exception('未指定要导入的供应商');
  39. } else if (!$this->zip_file) {
  40. throw new Exception('未指定要导入的zip文件');
  41. }
  42. $extract_dir = "excel/extract/{$this->supplier_id}/";
  43. Storage::deleteDirectory($extract_dir);
  44. Storage::makeDirectory($extract_dir);
  45. $extract_path = Storage::path($extract_dir . basename($this->zip_file, '.zip'));
  46. $zip = new ZipArchive;
  47. if ($zip->open($this->zip_file) === TRUE && $zip->extractTo($extract_path)) {
  48. $zip->close();
  49. } else {
  50. throw new Exception("解压文件 {$this->zip_file} 失败!");
  51. }
  52. # 解压后删除压缩文件
  53. unlink($this->zip_file);
  54. Excel::import(new ProductImport($this->supplier_id, $extract_path), $extract_path . '/产品.xlsx');
  55. }
  56. }