File: //home/armgroup/libs/app/Imports/ProductPricesImport.php
<?php
namespace App\Imports;
use App\Models\Product;
use App\Models\AttributeValue;
use App\Models\Image;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
use PhpOffice\PhpSpreadsheet\Shared\Date;
HeadingRowFormatter::default('none');
class ProductPricesImport implements
SkipsEmptyRows,
ToCollection,
WithHeadingRow,
WithValidation,
WithChunkReading
{
public function collection(Collection $rows)
{
foreach ($rows as $row) {
try {
$data = $this->mapRow($row);
if (empty($data['excel_name'])) {
continue;
}
$product = Product::where('name', 'like', "%{$data['excel_name']}%")->first();
if (!$product) {
continue;
}
if (empty($data['special'])) {
continue;
}
// try {
// $organizations = [
// [
// 'special_started_at' => Date::excelToDateTimeObject($row['تاریخ شروع']),
// 'special_ended_at' => Date::excelToDateTimeObject($row['تاریخ پایان']),
// ]
// ];
// dd($organizations);
// } catch (\Throwable $e) {
// dd($e->getMessage(), $e->getLine(), $e->getFile());
// }
$organizations = [
[
'product_id' => $product->id,
'organization_id' => $data['organization_id'],
'special' => $data['special'],
'special_started_at' => Date::excelToDateTimeObject($row['تاریخ شروع']),
'special_ended_at' => Date::excelToDateTimeObject($row['تاریخ پایان']),
]
];
foreach ($organizations as $item => $value) {
\DB::table('organization_product')->insert($value);
}
} catch (\Throwable $e) {
Log::error('attribute Import Error', [
'message' => $e->getMessage(),
'row' => $row->toArray(),
]);
}
}
}
private function mapRow($row): array
{
return [
'excel_name' =>$row['نام محصول'] ?? '',
'organization_id' => $row['سازمان'] ?? '',
'special' => $row['قیمت'] ?? '',
'special_started_at' => $row['تاریخ شروع'] ?? '',
'special_ended_at' => $row['تاریخ پایان'] ?? '',
];
}
// private function clean($value)
// {
// return trim(str_replace("\u{00A0}", ' ', $value));
// }
public function rules(): array
{
return [
'نام محصول' => ['required'],
'سازمان' => ['nullable'],
'قیمت' => ['required'],
'تاریخ شروع' => ['nullable'],
'تاریخ پایان' => ['nullable'],
];
}
public function chunkSize(): int
{
return 2000;
}
}