where('sync_status', 0) ->where('channel', $channelId) ->get(); if ($leads->isEmpty()) { return 0; } $now = time(); $count = 0; Db::transaction(function () use ($leads, $enterUserId, $channelId, $now, &$count) { $insert = []; $ids = []; foreach ($leads as $lead) { $leadArr = (array)$lead; $insert[] = $this->mapLeadToInquiry($leadArr, $now, $enterUserId, $channelId); $ids[] = $leadArr['id']; } if ($insert) { Db::table('inquiry_log')->insert($insert); Db::table('fb_leads') ->whereIn('id', $ids) ->update([ 'sync_status' => 1, 'updated_at' => $now, ]); $count = count($insert); } }); return $count; } /** * 映射一条 fb_leads -> inquiry_log */ protected function mapLeadToInquiry(array $lead, int $now, int $enterUserId, int $channelId): array { $email = (string)($lead['email'] ?? ''); $tel = (string)($lead['phone'] ?? ''); $wa = $tel; $countryId = PhoneCountryHelper::detectCountryId($tel ?: $wa); return [ 'order_no' => $this->orderNum(), 'enter_user_id' => $enterUserId, 'recipient' => 0, 'quality' => 2, 'channel' => $channelId, // 👈 inquiry_log 里同样用这个渠道ID 'email' => $email, 'tel' => $tel, 'whatsapp' => $wa, 'country' => $countryId ?: 0, 'contacts' => (string)($lead['full_name'] ?? ''), 'content' => $this->buildContentHtml($lead), 'status' => 0, 'r_time' => 0, 't_time' => 0, 'sync_crm' => 0, 'created_at' => $now, 'updated_at' => $now, ]; } protected function orderNum(): string { return 'SN' . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT); } /** * 富文本内容拼装 —— 基于你之前的版本 */ protected function buildContentHtml(array $lead): string { $e = function ($v) { return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }; $lines = []; if (!empty($lead['car_model'])) { $lines[] = '
意向车型:' . $e($lead['car_model']) . '
'; } if (!empty($lead['car_quantity']) || !empty($lead['car_quantity_text'])) { $qty = $lead['car_quantity'] ?? $lead['car_quantity_text'] ?? ''; $lines[] = '意向数量:' . $e($qty) . '
'; } if (!empty($lead['favorite_color'])) { $lines[] = '意向颜色:' . $e($lead['favorite_color']) . '
'; } if (!empty($lead['usage_type'])) { $lines[] = '用途:' . $e($lead['usage_type']) . '
'; } if (!empty($lead['seat_preference'])) { $lines[] = '座位数偏好:' . $e($lead['seat_preference']) . '
'; } $lines[] = '广告与表单信息:
'; $lines[] = '平台:' . $e($lead['platform'] ?? '') . '
'; $lines[] = 'Campaign:' . $e($lead['campaign_name'] ?? '') . ' (#' . $e($lead['campaign_id'] ?? '') . ')
'; $lines[] = 'Adset:' . $e($lead['adset_name'] ?? '') . ' (#' . $e($lead['adset_id'] ?? '') . ')
'; $lines[] = 'Ad:' . $e($lead['ad_name'] ?? '') . ' (#' . $e($lead['ad_id'] ?? '') . ')
'; $lines[] = 'Form:' . $e($lead['form_name'] ?? '') . ' (#' . $e($lead['form_id'] ?? '') . ')
'; $lines[] = 'Meta 信息:
'; $lines[] = 'Lead ID:' . $e($lead['fb_lead_id'] ?? '') . '
'; $lines[] = 'FB 创建时间原始值:' . $e($lead['fb_created_time'] ?? '') . '
'; if (!empty($lead['inbox_url'])) { $url = $e($lead['inbox_url']); $lines[] = 'Inbox 链接:' . $url . '
'; } return implode("\n", $lines); } }