# Design Document

## Overview

This design implements support for Hong Kong companies in the VAT document generation system. The key difference for Hong Kong companies is that they do not require business license (营业执照) and credit report (企业信用报告) documents, as these documents are specific to mainland Chinese companies. The system will detect Hong Kong companies based on the `CompanyCountry` field and skip the generation of these documents while still producing the required authorization documents and ID card translations.

## Architecture

### Detection Flow

```
VATDocumentGenerator.generate()
  ↓
Check CompanyCountry field
  ↓
Normalize country value (香港/HK/Hong Kong → HK)
  ↓
Set isHongKongCompany flag
  ↓
Branch processing based on flag
```

### Document Generation Flow

**For Mainland Chinese Companies (Current Flow):**
1. Authorization documents (Hague/Non-Hague)
2. Credit report original + translation
3. Business license original + translation
4. ID card original + translation

**For Hong Kong Companies (New Flow):**
1. Authorization documents (Hague/Non-Hague)
2. ID card original + translation

## Components and Interfaces

### 1. Hong Kong Company Detection

**Location:** `src/VATDocumentGenerator.php`

**New Method:**
```php
/**
 * Check if the company is a Hong Kong company
 * @param array $dbData Database data containing CompanyCountry field
 * @return bool True if Hong Kong company, false otherwise
 */
private function isHongKongCompany($dbData)
```

**Detection Logic:**
- Extract `CompanyCountry` field from `$dbData`
- Normalize the value to uppercase and trim whitespace
- Check if the value matches:
  - "香港" (Chinese)
  - "HK" (short code)
  - "HONG KONG" (English, case-insensitive)
- Return boolean result

### 2. Modified Methods

#### 2.1 `generate()` Method (Synchronous Phase)

**Current Behavior:**
- Validates credit report file
- Creates async task with credit report path

**New Behavior:**
- Check if Hong Kong company
- If Hong Kong: Skip credit report validation, create async task without credit report path
- If not Hong Kong: Continue with existing flow

**Changes:**
```php
// Add Hong Kong detection
$isHongKongCompany = $this->isHongKongCompany($dbData);

if ($isHongKongCompany) {
    $this->logger->info("检测到香港公司，跳过企业信用报告验证");
    $creditReportPath = null;
} else {
    $creditReportPath = $this->validateCreditReportFile($dbData);
}

// Create async task (with or without credit report path)
$taskId = $this->createAsyncTaskWithCreditReport($id, $creditReportPath, $dbData);
```

#### 2.2 `generateFromCreditReport()` Method (Async Phase)

**Current Behavior:**
- Processes credit report
- Processes business license
- Processes ID card
- Generates all documents
- Merges PDFs

**New Behavior:**
- Check if Hong Kong company
- If Hong Kong:
  - Skip credit report processing
  - Skip business license processing
  - Process ID card only
  - Generate authorization documents and ID card translation only
- If not Hong Kong: Continue with existing flow

**Changes:**
```php
// Add Hong Kong detection
$isHongKongCompany = $this->isHongKongCompany($dbData);

if ($isHongKongCompany) {
    $this->logger->info("检测到香港公司，跳过营业执照和企业信用报告生成");
    $creditReportData = [];
    $businessLicenseData = [];
} else {
    $creditReportData = $this->processCreditReport($dbData, $creditReportFilePath);
    $businessLicenseData = $this->processBusinessLicense($dbData, $creditReportData);
}

// ID card processing continues for all companies
$rawIdCardData = $this->processIdCard($dbData);
```

#### 2.3 `generateWordDocuments()` Method (Hague Flow)

**Current Behavior:**
- Generates 4 authorization documents
- Generates 3 supporting documents (credit report, business license, ID card)

**New Behavior:**
- Accept `$isHongKongCompany` parameter
- If Hong Kong: Skip credit report and business license generation
- Generate only authorization documents and ID card translation

**Changes:**
```php
private function generateWordDocuments($templateData, $dbData, $isHongKongCompany = false)
{
    // ... existing authorization document generation ...
    
    if (!$isHongKongCompany) {
        // Generate supporting documents only for non-Hong Kong companies
        $supportingDocs = $this->generateSupportingDocuments($templateData, $dbData);
        $wordFiles = array_merge($wordFiles, $supportingDocs);
    } else {
        // For Hong Kong companies, only generate ID card translation
        $idCardFile = $this->generateIdCardTranslation($templateData, $requestId);
        if ($idCardFile) {
            $wordFiles['id_card_es'] = $idCardFile;
        }
    }
    
    return $wordFiles;
}
```

#### 2.4 `generateApostilleNotRequiredDocuments()` Method (Non-Hague Flow)

**Current Behavior:**
- Generates apostille not required document
- Generates 3 supporting documents

**New Behavior:**
- Accept `$isHongKongCompany` parameter
- If Hong Kong: Skip credit report and business license generation
- Generate only apostille document and ID card translation

**Changes:**
```php
private function generateApostilleNotRequiredDocuments($templateData, $dbData, $isHongKongCompany = false)
{
    // ... existing apostille document generation ...
    
    if (!$isHongKongCompany) {
        // Generate supporting documents only for non-Hong Kong companies
        $supportingDocs = $this->generateSupportingDocuments($templateData, $dbData);
        $wordFiles = array_merge($wordFiles, $supportingDocs);
    } else {
        // For Hong Kong companies, only generate ID card translation
        $idCardFile = $this->generateIdCardTranslation($templateData, $requestId);
        if ($idCardFile) {
            $wordFiles['id_card_es'] = $idCardFile;
        }
    }
    
    return $wordFiles;
}
```

#### 2.5 `convertAndMergePDF()` Method

**Current Behavior:**
- Converts all Word documents to PDF
- Merges in order: authorization → credit report → business license → ID card

**New Behavior:**
- Accept `$isHongKongCompany` parameter
- If Hong Kong: Skip credit report and business license PDF processing
- Merge only: authorization → ID card

**Changes:**
```php
private function convertAndMergePDF($wordFiles, $dbData, $rawIdCardData, $processType = '海牙', $templateData = null, $isHongKongCompany = false)
{
    // ... existing authorization document conversion ...
    
    if (!$isHongKongCompany) {
        // Process credit report and business license for non-Hong Kong companies
        // ... existing credit report processing ...
        // ... existing business license processing ...
    } else {
        $this->logger->info("香港公司：跳过企业信用报告和营业执照PDF处理");
    }
    
    // ID card processing continues for all companies
    // ... existing ID card processing ...
}
```

### 3. Modified Supporting Methods

#### 3.1 `generateSupportingDocuments()` Method

**Current Behavior:**
- Generates credit report translation
- Generates business license translation
- Generates ID card translation

**New Behavior:**
- Accept `$isHongKongCompany` parameter
- If Hong Kong: Only generate ID card translation
- If not Hong Kong: Generate all three documents

**Changes:**
```php
private function generateSupportingDocuments($templateData, $dbData, $isHongKongCompany = false)
{
    $wordFiles = [];
    
    if (!$isHongKongCompany) {
        // Generate credit report and business license for non-Hong Kong companies
        $creditReportFile = $this->generateCreditReportTranslation($templateData, $requestId);
        if ($creditReportFile) {
            $wordFiles['credit_report_es'] = $creditReportFile;
        }
        
        $businessLicenseFile = $this->generateBusinessLicenseTranslation($templateData, $dbData, $requestId);
        if ($businessLicenseFile) {
            $wordFiles['business_license_es'] = $businessLicenseFile;
        }
        
        $wordFiles['credit_report_original'] = $templateData['credit_report']['original_file_path'] ?? '';
        $wordFiles['business_license_original'] = $templateData['business_license']['original_file_path'] ?? '';
    }
    
    // ID card translation for all companies
    $idCardFile = $this->generateIdCardTranslation($templateData, $requestId);
    if ($idCardFile) {
        $wordFiles['id_card_es'] = $idCardFile;
    }
    
    return $wordFiles;
}
```

#### 3.2 `prepareTemplateData()` Method

**Current Behavior:**
- Prepares data for all document types

**New Behavior:**
- Accept `$isHongKongCompany` parameter
- If Hong Kong: Skip credit report and business license data preparation
- Always prepare authorization and ID card data

**Changes:**
```php
private function prepareTemplateData($dbData, $creditReportData, $businessLicenseData, $idCardData, $isHongKongCompany = false)
{
    $data = [];
    
    if (!$isHongKongCompany) {
        $data['credit_report'] = $creditReportData;
        $data['business_license'] = $businessLicenseData;
    }
    
    // ID card and authorization data for all companies
    $data['id_card'] = $idCardData;
    $data['hague_poa_es'] = $this->prepareHaguePOAData($dbData, $idCardData, 'es');
    $data['hague_poa_en'] = $this->prepareHaguePOAData($dbData, $idCardData, 'en');
    $data['letter_auth_es'] = $this->prepareLetterAuthData($dbData);
    $data['letter_auth_en'] = $this->prepareLetterAuthData($dbData);
    
    return $data;
}
```

## Data Models

### Database Fields Used

**From VATBusinessRecord:**
- `CompanyCountry`: Country name (e.g., "香港", "HK", "Hong Kong", "中国")
- `SpecsName`: Specification name (contains "免海牙" for non-Hague process)
- `BusinessCode`: Business code for identification
- `RegNumber`: Registration number
- Other fields for authorization documents and ID card

**From AsyncTask:**
- `CreditReportFilePath`: Path to credit report file (will be null for Hong Kong companies)

### Hong Kong Company Flag

The `isHongKongCompany` boolean flag will be passed through the processing pipeline:

```
generate() → generateFromCreditReport() → generateWordDocuments() / generateApostilleNotRequiredDocuments() → convertAndMergePDF()
```

## Error Handling

### Validation

1. **Missing CompanyCountry Field:**
   - If `CompanyCountry` is null or empty, assume not Hong Kong company
   - Log warning: "CompanyCountry字段为空，假定为非香港公司"

2. **Invalid Country Value:**
   - If country value doesn't match known patterns, assume not Hong Kong company
   - Continue with normal processing

### Processing Errors

1. **Hong Kong Company with Credit Report:**
   - If Hong Kong company but credit report path exists, log warning and skip processing
   - Do not throw error

2. **Hong Kong Company Missing ID Card:**
   - Throw error as ID card is required for all companies
   - Error message: "身份证文件缺失，无法生成文档"

## Testing Strategy

### Unit Tests (Optional)

1. **Test `isHongKongCompany()` Method:**
   - Test with "香港" → returns true
   - Test with "HK" → returns true
   - Test with "Hong Kong" → returns true
   - Test with "hong kong" (lowercase) → returns true
   - Test with "中国" → returns false
   - Test with null → returns false
   - Test with empty string → returns false

2. **Test Document Generation:**
   - Mock Hong Kong company data
   - Verify credit report processing is skipped
   - Verify business license processing is skipped
   - Verify ID card processing continues
   - Verify authorization documents are generated

### Integration Tests (Optional)

1. **End-to-End Hong Kong Company Flow:**
   - Create test VAT record with CompanyCountry = "HK"
   - Run generate() method
   - Verify async task created without credit report path
   - Run generateFromCreditReport() with null credit report path
   - Verify final PDF contains only authorization + ID card documents

2. **End-to-End Mainland Company Flow:**
   - Create test VAT record with CompanyCountry = "中国"
   - Run complete flow
   - Verify all documents are generated

### Manual Testing

1. **Test with Real Hong Kong Company Data:**
   - Use actual Hong Kong company record from database
   - Verify correct documents are generated
   - Verify PDF structure and content

2. **Test with Real Mainland Company Data:**
   - Use actual mainland company record
   - Verify no regression in existing functionality

## Logging Strategy

### Log Levels

- **INFO:** Detection results, processing steps
- **WARNING:** Missing fields, skipped processing
- **ERROR:** Critical failures
- **SUCCESS:** Successful completion of major steps

### Log Messages

1. **Detection:**
   - "检测公司国家: {CompanyCountry}"
   - "检测到香港公司，跳过营业执照和企业信用报告生成"
   - "非香港公司，继续正常流程"

2. **Synchronous Phase:**
   - "香港公司：跳过企业信用报告验证"
   - "创建异步任务（香港公司，无企业信用报告）"

3. **Async Phase:**
   - "香港公司：跳过企业信用报告处理"
   - "香港公司：跳过营业执照处理"
   - "香港公司：继续身份证处理"

4. **Document Generation:**
   - "香港公司：仅生成授权书和身份证翻译件"
   - "香港公司：跳过企业信用报告翻译件生成"
   - "香港公司：跳过营业执照翻译件生成"

5. **PDF Merge:**
   - "香港公司：PDF合并文件列表: [authorization_docs, id_card_docs]"
   - "香港公司：跳过企业信用报告和营业执照PDF处理"

## Performance Considerations

### Time Savings for Hong Kong Companies

**Skipped Operations:**
1. Credit report file download and validation (~2-5 seconds)
2. Credit report OCR processing (~3-10 seconds)
3. Business license file download (~1-3 seconds)
4. Business license OCR processing (~2-5 seconds)
5. Credit report translation generation (~5-10 seconds)
6. Business license translation generation (~5-10 seconds)
7. PDF conversion for 4 documents (~4-8 seconds)

**Estimated Time Savings:** 22-51 seconds per Hong Kong company

### Resource Savings

- Reduced API calls to OCR services
- Reduced translation API calls
- Reduced file storage (no credit report/business license files)
- Reduced PDF processing load

## Backward Compatibility

### Existing Functionality

- All existing mainland company processing remains unchanged
- No changes to database schema
- No changes to API interfaces
- No changes to template files

### Migration

- No migration required
- Feature is automatically enabled based on CompanyCountry field
- Existing records will continue to work as before

## Future Enhancements

1. **Support for Other Regions:**
   - Extend detection logic to support other regions (Macau, Taiwan, etc.)
   - Create region-specific document generation rules

2. **Configurable Document Requirements:**
   - Move document requirements to configuration file
   - Allow per-country customization of required documents

3. **Document Type Registry:**
   - Create a registry of document types and their applicability by country
   - Implement dynamic document generation based on registry

4. **Validation Rules:**
   - Add country-specific validation rules
   - Validate required fields based on company country
