cafeg/app/Imports/PromoImport.php
2025-08-07 14:06:02 +08:00

116 lines
4.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Imports;
use App\Models\Promocode;
use Illuminate\Support\Collection;
use Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use function Illuminate\Log\log;
class PromoImport implements ToCollection
{
protected $from;
public function __construct($from = 'cafeg')
{
$this->from = $from;
}
public function collection(Collection $rows)
{
if ($this->from == 'cafeg') {
foreach ($rows as $row) {
$data = $row->toArray();
if ($data[3] != '提货码') { // 跳過標題行
$code = $data[3];
$promo = Promocode::where('code', $code)
->where('from', 'cafeg')
->first();
if ($promo) {
// 如果已存在,且 give_to 不為 null就更新
if ($promo->give_to !== null) {
$promo->update([
'discount' => 100,
'type' => 'percent',
'usage_limit' => 1,
'valid_from' => date('Y-m-d'),
'valid_to' => date('Y-m-d', strtotime('+1 day')),
'is_active' => 1,
'from' => 'cafeg',
]);
Log::info("已更新:{$code}");
} else {
Log::info("跳過give_to 為 null{$code}");
}
} else {
// 不存在就新增
Promocode::create([
'code' => $code,
'discount' => 100,
'type' => 'percent',
'usage_limit' => 1,
'valid_from' => date('Y-m-d'),
'valid_to' => date('Y-m-d', strtotime('+1 day')),
'is_active' => 1,
'from' => 'cafeg',
]);
Log::info("已新增:{$code}");
}
}
}
}
if ($this->from == 'teamaster') {
Log::info('import-from: teamaster');
Log::info('row', );
foreach ($rows->toArray() as $row) {
$code = $row[0];
$promo = Promocode::where('code', $code)
->where('from', 'teamaster')
->first();
if ($promo) {
// 如果已存在,且 give_to 不為 null就更新
if ($promo->give_to != null) {
$promo->update([
'discount' => 70,
'type' => 'amount',
'usage_limit' => 1,
'valid_from' => date('Y-m-d'),
'valid_to' => date('Y-m-d', strtotime('+7 day')),
'is_active' => 1,
'from' => 'teamaster',
]);
Log::info("已更新:{$code}");
} else {
Log::info("跳過give_to 為 null{$code}");
}
} else {
Log::info("新增代碼:{$code}");
// 不存在就新增
Promocode::create([
'code' => $code,
'discount' => 70,
'type' => 'amount',
'usage_limit' => 1,
'valid_from' => date('Y-m-d'),
'valid_to' => date('Y-m-d', strtotime('+7 day')),
'is_active' => 1,
'from' => 'teamaster',
]);
Log::info("已新增:{$code}");
}
}
}
}
}