feat: [商品管理] 優化商品匯入邏輯,支援 13 碼條碼自動生成、Upsert 更新機制與 Excel 說明工作表
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Has been skipped
Koori-ERP-Deploy-System / deploy-production (push) Successful in 1m7s

This commit is contained in:
2026-02-06 09:26:50 +08:00
parent e1aa452b3c
commit 906b094c18
7 changed files with 187 additions and 44 deletions

View File

@@ -57,21 +57,25 @@ class ProductImport implements ToModel, WithHeadingRow, WithValidation, WithMapp
$baseUnitId = $this->units[$row['基本單位']] ?? null;
$largeUnitId = isset($row['大單位']) ? ($this->units[$row['大單位']] ?? null) : null;
// 若必要關聯找不到,理論上 Validation 會攔截,但此處做防禦性編程
if (!$categoryId || !$baseUnitId) {
return null;
}
// 處理商品代號:若為空則自動生成
$code = $row['商品代號'] ?? null;
if (empty($code)) {
$code = $this->generateRandomCode();
$barcode = $row['條碼'] ?? null;
// Upsert 邏輯:優先以條碼查找,次之以商品代號查找
$product = null;
if (!empty($barcode)) {
$product = Product::where('barcode', $barcode)->first();
}
return new Product([
'code' => $code,
'barcode' => $row['條碼'],
if (!$product && !empty($code)) {
$product = Product::where('code', $code)->first();
}
$data = [
'name' => $row['商品名稱'],
'category_id' => $categoryId,
'brand' => $row['品牌'] ?? null,
@@ -84,7 +88,26 @@ class ProductImport implements ToModel, WithHeadingRow, WithValidation, WithMapp
'price' => $row['售價'] ?? null,
'member_price' => $row['會員價'] ?? null,
'wholesale_price' => $row['批發價'] ?? null,
]);
];
if ($product) {
// 更新現有商品
$product->update($data);
return null; // 返回 null 以避免 Maatwebsite/Excel 嘗試再次 insert
}
// 建立新商品:處理代碼與條碼自動生成
if (empty($code)) {
$code = $this->generateRandomCode();
}
if (empty($barcode)) {
$barcode = $this->generateRandomBarcode();
}
$data['code'] = $code;
$data['barcode'] = $barcode;
return new Product($data);
}
/**
@@ -105,11 +128,28 @@ class ProductImport implements ToModel, WithHeadingRow, WithValidation, WithMapp
return $code;
}
/**
* 生成隨機 13 碼條碼 (純數字)
*/
private function generateRandomBarcode(): string
{
$barcode = '';
do {
$barcode = '';
for ($i = 0; $i < 13; $i++) {
$barcode .= rand(0, 9);
}
} while (Product::where('barcode', $barcode)->exists());
return $barcode;
}
public function rules(): array
{
return [
'商品代號' => ['nullable', 'string', 'min:2', 'max:8', 'unique:products,code'],
'條碼' => ['required', 'string', 'unique:products,barcode'],
'商品代號' => ['nullable', 'string', 'min:2', 'max:8'],
'條碼' => ['nullable', 'string'],
'商品名稱' => ['required', 'string'],
'類別名稱' => ['required', function($attribute, $value, $fail) {
if (!isset($this->categories[$value])) {