# 电话号码验证修复说明

> 注：该清洗逻辑现位于 `src/Services/VatRecordTransform.php::cleanPhone()`，source 流程（DataSyncService）与 API 流程（ApiDataSyncService）共用，本文档描述的历史修复行为不变。

## 修复的问题

### 1. 电话号码空格处理
**问题**: 源数据中的电话号码可能包含空格，如 `86 17781686790`
**修复**: 在清理电话号码时，先去掉所有空格，再提取数字

```php
// 修复前
$cleanPhone = preg_replace('/[^\d]/', '', $phone);

// 修复后
$phoneWithoutSpaces = str_replace(' ', '', $phone);
$cleanPhone = preg_replace('/[^\d]/', '', $phoneWithoutSpaces);
```

### 2. 法人国家字段验证
**问题**: 没有在电话号码格式化前验证法人国家字段是否为空
**修复**: 在处理电话号码前，先验证法人国家字段不能为空

```php
// 验证法人国家字段不能为空
if (empty($record->LegalPersonCountry)) {
    $this->logger->error("VATBusinessRecord.ID: {$record->ID} - Legal person country is required but empty");
    $this->handleValidationFailure($record, 'Legal person country field cannot be empty');
    return ['success' => false, 'recordId' => $record->ID, 'message' => 'Legal person country field cannot be empty'];
}
```

### 3. 错误消息更新
**问题**: 验证失败时错误消息没有正确更新到VATBusinessRecord表的PushTaxBureauErrorMsg字段
**修复**: 
- 修改 `handleValidationFailure` 方法支持自定义错误消息
- 确保 `updateSourceRecordStatus` 方法正确更新错误消息字段

```php
private function handleValidationFailure(VatBusinessRecord $record, ?string $customErrorMessage = null): void
{
    $errorMessage = $customErrorMessage ?? $this->validator->getErrorMessage();
    $this->updateSourceRecordStatus($record->ID, -1, $errorMessage);
    $this->logger->warning("VATBusinessRecord.ID: {$record->ID} - Validation failed: {$errorMessage}");
}
```

## 国家验证确认

### 不区分大小写比较
CountryService 已经实现了不区分大小写的国家名比较：

```php
// 3. 尝试作为英文名匹配（不区分大小写）
$lowerInput = strtolower($input);
foreach ($this->countryByEnglish as $englishName => $value) {
    if (strtolower($englishName) === $lowerInput) {
        return $englishName;
    }
}
```

### 返回值确认
CountryService 返回的是 Country 表中的 `CountryName_en` 字段值：

```sql
SELECT CountryName, CountryTwoCode, CountryName_en, GlobalRoaming 
FROM Country 
WHERE CountryName_en IS NOT NULL AND CountryName_en != ''
```

## 支持的输入格式

### 国家输入
- 二字码: `GB`, `gb`, `UK`, `uk`
- 中文名: `英国`
- 英文名: `United Kingdom`, `united kingdom`, `UNITED KINGDOM`

### 电话号码输入
- 带空格: `86 17781686790`
- 多个空格: `86  17781686790`
- 带符号: `86-17781686790`, `+86 177 8168 6790`
- 带括号: `86(177)81686790`

## 错误处理流程

1. **法人国家为空**: 
   - 错误消息: "Legal person country field cannot be empty"
   - 状态: PushTaxBureauStatus = -1

2. **国家区号未找到**:
   - 错误消息: "Phone number formatting failed: [phone], country: [country]"
   - 状态: PushTaxBureauStatus = -1

3. **电话号码无效**:
   - 错误消息: "Phone number formatting failed: [phone], country: [country]"
   - 状态: PushTaxBureauStatus = -1

## 测试

运行测试脚本验证修复：
```bash
php test/test_phone_validation.php
```

## 数据库更新

状态与错误信息更新在源库 **`VATRegInfo`** 表（`updateSourceRecordStatus()` 方法）：
- `VATRegInfo.PushTaxBureauStatus` = -1
- `VATRegInfo.PushTaxBureauErrorMsg` = 具体错误消息