2023-04-21 20:11:24 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Imports;
|
|
|
|
|
|
|
|
|
|
use App\Models\CombinationGood;
|
|
|
|
|
use App\Models\GoodsSku;
|
|
|
|
|
use App\Utils\ArrayUtils;
|
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
|
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
|
|
|
|
|
use Maatwebsite\Excel\Concerns\ToArray;
|
|
|
|
|
use Maatwebsite\Excel\Concerns\WithStartRow;
|
|
|
|
|
|
|
|
|
|
class CombinationGoodsImport implements ToArray, SkipsEmptyRows, WithStartRow
|
|
|
|
|
{
|
|
|
|
|
public function startRow(): int
|
|
|
|
|
{
|
|
|
|
|
return 2;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function array(array $array)
|
|
|
|
|
{
|
|
|
|
|
$main = [];
|
|
|
|
|
foreach ($array as &$row) {
|
|
|
|
|
$row = array_map(function ($value) {
|
|
|
|
|
return trim($value);
|
|
|
|
|
}, $row);
|
|
|
|
|
if (empty($row[0]) || empty($row[1])) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
// 组合商品
|
|
|
|
|
if (empty($row[2]) && empty($row[3])) {
|
|
|
|
|
$main[$row[1]] = [
|
|
|
|
|
'title' => $row[0],
|
|
|
|
|
'external_sku_id' => $row[1],
|
|
|
|
|
'item' => []
|
|
|
|
|
];
|
|
|
|
|
} else {
|
|
|
|
|
$main[$row[1]]['item'][] = [
|
|
|
|
|
'item_code' => $row[2],
|
|
|
|
|
'item_num' => $row[3],
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
foreach ($main as $info) {
|
|
|
|
|
if (empty($info['item'])) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
DB::beginTransaction();
|
|
|
|
|
try {
|
|
|
|
|
$itemCodes = array_column($info['item'], 'item_code');
|
|
|
|
|
$skus = GoodsSku::query()
|
|
|
|
|
->whereIn('external_sku_id', $itemCodes)
|
|
|
|
|
->get(['id', 'external_sku_id', 'stock'])
|
|
|
|
|
->toArray();
|
|
|
|
|
$skus = ArrayUtils::index($skus, 'external_sku_id');
|
2023-04-28 10:42:26 +08:00
|
|
|
$stock = [];
|
2023-04-21 20:11:24 +08:00
|
|
|
foreach ($info['item'] as $item) {
|
2023-04-28 10:42:26 +08:00
|
|
|
$stock[] = (int)($skus[$item['item_code']]['stock'] / $item['item_num']);
|
2023-04-21 20:11:24 +08:00
|
|
|
}
|
2023-04-28 10:42:26 +08:00
|
|
|
$stock = min($stock);
|
2023-04-25 18:27:07 +08:00
|
|
|
$status = $stock ? (5 < $stock ? 1 : 2) : 0;
|
2023-04-22 15:56:53 +08:00
|
|
|
$sku = GoodsSku::query()->updateOrCreate(
|
2023-04-21 20:11:24 +08:00
|
|
|
['external_sku_id' => $info['external_sku_id'], 'is_combination' => 1],
|
2023-04-25 18:27:07 +08:00
|
|
|
['title' => $info['title'], 'goods_id' => 0, 'sku_code' => $info['external_sku_id'], 'stock' => $stock, 'status' => $status]
|
2023-04-21 20:11:24 +08:00
|
|
|
);
|
|
|
|
|
CombinationGood::query()
|
|
|
|
|
->where('goods_sku_id', $sku->id)
|
|
|
|
|
->delete();
|
|
|
|
|
foreach ($info['item'] as $item) {
|
|
|
|
|
CombinationGood::query()->create(['goods_sku_id' => $sku->id, 'item_id' => $skus[$item['item_code']]['id'], 'item_num' => $item['item_num']]);
|
|
|
|
|
}
|
|
|
|
|
DB::commit();
|
|
|
|
|
} catch (\Exception $exception) {
|
|
|
|
|
DB::rollBack();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|