海南旅游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.
 
 
 

96 lines
2.8 KiB

<?php
namespace App\Jobs;
use App\Exports\ProductExport;
use App\Exports\ProductSpecExport;
use App\Models\Product;
use App\Models\ProductExportLog;
use App\Models\ProductSpec;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ZipArchive;
/**
* 导出全部产品
*/
class ExportProductToExcel implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private int $supplier_id;
private string|array|null $_export_;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(int $supplier_id, string|array $_export_ = null)
{
$this->supplier_id = $supplier_id;
$this->_export_ = $_export_;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$export_dir = "supplier/export/{$this->supplier_id}/" . date('Y-m') . '/';
$product_file = $export_dir . '产品.xlsx';
Storage::disk('public')->deleteDirectory($export_dir);
if (!Excel::store(new ProductExport($this->supplier_id, $this->_export_, $export_dir), $product_file, 'public')) {
return;
}
# 导出规格
$ids = $this->_export_ == 'all' ?
Product::where('supplier_id', $this->supplier_id)->get('id')->pluck('id') :
Product::whereIn('id', $this->_export_)->where('supplier_id', $this->supplier_id)->get('id')->pluck('id');
foreach ($ids as $id) {
if (ProductSpec::where([['product_id', '=', $id], ['date', '>=', date('Y-m-d')]])->exists()) {
Excel::store(new ProductSpecExport($id), $export_dir . "产品规格{$id}.xlsx", 'public');
}
}
# 生成zip文件
$zip = new ZipArchive();
$zip_file = substr(rtrim($export_dir, '/'), 0, strrpos(rtrim($export_dir, '/'), '/')) . '/export_' . date('Y-m-d_H-i-s') . '.zip';
if ($zip->open(Storage::disk('public')->path($zip_file),ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(Storage::disk('public')->path($export_dir)),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen(Storage::disk('public')->path($export_dir)));
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
}
Storage::disk('public')->deleteDirectory($export_dir);
# 生成导出记录
ProductExportLog::create([
'supplier_id' => $this->supplier_id,
'filename' => $zip_file,
]);
}
}