erp-backend/app/Services/SkuMatchService.php
2026-04-01 17:07:04 +08:00

73 lines
2.5 KiB
PHP

<?php
namespace App\Services;
use App\Models\Order;
use App\Models\Platform;
use App\Models\MatchLog;
use App\Models\UnmatchedLog;
use Illuminate\Support\Facades\DB;
class SkuMatchService
{
public function matchOrderItems($orderId)
{
$order = Order::with('items')->findOrFail($orderId);
$allMatched = true;
DB::transaction(function () use ($order, &$allMatched) {
foreach ($order->items as $item) {
// 通过平台SKU编码查找平台商品
$platformSku = Platform::where('sku_code', $item->platform_sku)->first();
if ($platformSku) {
// 查找当前生效的绑定
$activeBinding = $platformSku->activeBinding;
if ($activeBinding) {
$item->erp_sku_id = $activeBinding->erp_sku_id;
$item->match_status = 1;
$item->save();
MatchLog::create([
'order_item_id' => $item->id,
'platform_sku' => $item->platform_sku,
'erp_sku_id' => $activeBinding->erp_sku_id,
'match_type' => 'auto'
]);
} else {
$allMatched = false;
$item->match_status = 0;
$item->save();
UnmatchedLog::create([
'order_item_id' => $item->id,
'platform_sku' => $item->platform_sku,
'reason' => 'no_active_binding'
]);
}
} else {
$allMatched = false;
$item->match_status = 0;
$item->save();
UnmatchedLog::create([
'order_item_id' => $item->id,
'platform_sku' => $item->platform_sku,
'reason' => 'platform_sku_not_found'
]);
}
}
$order->match_status = $allMatched ? 1 : 0;
$order->match_time = now();
$order->save();
});
return [
'order_id' => $orderId,
'all_matched' => $allMatched,
'matched_count' => $order->items()->where('match_status', 1)->count(),
'total_count' => $order->items()->count()
];
}
}