# Customer Reconciliation - Export Reconciliable Orders API

## Overview
This document describes the API endpoint for exporting reconciliable orders (orders that need reconciliation) for a specific customer to Excel format.

## API Endpoint

### Export Reconciliable Orders
**Endpoint:** `POST /api/CustomerReconciliationSlip/ExportReconciliableOrders/{customerId}`

**Description:** Xuất Excel danh sách đơn hàng cần đối soát của khách hàng

**Authorization:** Requires `CustomerReconciliationSlip.ExportExcel` or `Founder` role

**Path Parameters:**
- `customerId` (int, required): ID khách hàng

**Request Body:**
```json
{
  "FileName": "DanhSachDonHangCanDoiSoat",
  "IncludeOrderDetails": true,
  "FolderPath": "/exports"
}
```

**Request Model:** `CustomerReconciliationSlipExcelExportModel`

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| FileName | string | No | Tên file Excel (không bao gồm extension). Mặc định: `DanhSachDonHangCanDoiSoat_{customerId}` |
| IncludeOrderDetails | bool | No | Có bao gồm chi tiết đơn hàng không (default: true) |
| FolderPath | string | No | Đường dẫn thư mục lưu file (tùy chọn) |

**Response:** `CustomerReconciliationSlipExcelExportResult`
```json
{
  "Result": 1,
  "Message": "Xuất file Excel thành công",
  "FilePath": "/exports/DanhSachDonHangCanDoiSoat_123.xlsx",
  "FileName": "DanhSachDonHangCanDoiSoat_123.xlsx",
  "FileSize": 102400,
  "TotalRecords": 15,
  "DownloadUrl": "/api/FinanceExcelExport/Download/DanhSachDonHangCanDoiSoat_123.xlsx",
  "ProcessStartTime": "2026-01-09T14:00:00Z",
  "ProcessEndTime": "2026-01-09T14:00:03Z",
  "ProcessingTimeMs": 3000
}
```

**Status Codes:**
- `200 OK`: Export successful
- `400 Bad Request`: Invalid customer ID, no reconciliable orders, or validation errors
- `401 Unauthorized`: User not authenticated
- `403 Forbidden`: User doesn't have required permissions
- `500 Internal Server Error`: System error

---

## Excel File Structure

The exported Excel file follows the same structure as the `ExportExcelDetail` endpoint:

### Sheet Layout

**Row 1: Company Header**
- Columns A-B: Company logo and information (CÔNG TY TNHH LADA EXPRESS, Website, Hotline)
- Columns D-E: Title "DANH SÁCH ĐƠN HÀNG CẦN ĐỐI SOÁT" (centered, bold, 16pt)

**Row 4-5: Customer Information**
- Row 4: Mã khách hàng (Customer Code)
- Row 5: Tên khách hàng (Customer Name)

**Row 7: Table Title**
- "DANH SÁCH ĐƠN HÀNG" (centered, bold, 14pt)

**Row 8: Table Header** (Red background, white text)
- Column A: Mã đơn hàng (Order Code)
- Column B: Địa chỉ gửi (Sender Address - Name, Phone, Address)
- Column C: Địa chỉ nhận (Receiver Address - Name, Phone, Address)
- Column D: Sản phẩm (Products - Quantity, Name, Weight)
- Column E: Tài chính (Financial - COD, Fee, Net Amount)

**Row 9+: Order Data**
- Each row contains one order with wrapped text
- Financial column shows:
  - Thu hộ: {AppliedCodAmount}
  - Cước phí: {AppliedFeeAmount}
  - Thực nhận: {NetAmount}

### Formatting
- Row height: Header (95), Title (40), Table Header (30), Data rows (60)
- Column widths: A (15), B (35), C (35), D (30), E (25)
- All cells have borders (thin style)
- Text wrapping enabled for multi-line content
- Numbers formatted with thousand separators

---

## Business Logic

### Reconciliable Orders Criteria
Orders are considered "reconciliable" if they meet the criteria defined in the stored procedure `sp_GetReconciliableOrdersByCustomer`. This typically includes:
- Orders that have been delivered
- COD has been collected
- Orders not yet included in any non-rejected reconciliation slip

### Permission Check
- **Founder**: Can export for any customer
- **Accountant**: Can export for any customer (with `CustomerReconciliationSlip.View` role)
- **Manager/Sale**: Can only export for customers they manage

The permission check is performed by the `GetReconciliableOrdersAsync` method in `CustomerReconciliationSlipService`.

---

## Usage Examples

### Example 1: Export reconciliable orders for a customer
```bash
POST /api/CustomerReconciliationSlip/ExportReconciliableOrders/123
Content-Type: application/json
Authorization: Bearer {token}

{
  "FileName": "DonHangCanDoiSoat_KH123",
  "IncludeOrderDetails": true
}
```

### Example 2: Export with default filename
```bash
POST /api/CustomerReconciliationSlip/ExportReconciliableOrders/456
Content-Type: application/json
Authorization: Bearer {token}

{
  "IncludeOrderDetails": true
}
```
This will generate filename: `DanhSachDonHangCanDoiSoat_456.xlsx`

---

## Error Handling

### Common Error Scenarios

1. **Invalid Customer ID**
   ```json
   {
     "Result": 2,
     "Message": "ID khách hàng không hợp lệ"
   }
   ```

2. **No Reconciliable Orders**
   ```json
   {
     "Result": 2,
     "Message": "Không có đơn hàng nào cần đối soát"
   }
   ```

3. **Customer Not Found**
   ```json
   {
     "Result": 2,
     "Message": "Không tìm thấy khách hàng"
   }
   ```

4. **Permission Denied**
   ```json
   {
     "Result": 2,
     "Message": "Bạn không có quyền truy cập dữ liệu khách hàng này"
   }
   ```

---

## Security Considerations

1. **Authorization**: Only users with `CustomerReconciliationSlip.ExportExcel` or `Founder` role can export
2. **Data Access**: Users can only export orders for customers they have permission to view
   - Founders and Accountants: All customers
   - Managers/Sales: Only their assigned customers
3. **File Storage**: Exported files are stored in the `reconciliable-orders` subfolder
4. **Cleanup**: Consider implementing automatic cleanup of old exported files

---

## Performance Considerations

1. **Database Query**: The `GetReconciliableOrdersAsync` method uses a stored procedure for optimal performance
2. **Large Datasets**: For customers with many reconciliable orders, the export may take several seconds
3. **Async Processing**: The entire export pipeline uses async/await for non-blocking operations
4. **Memory Usage**: Excel generation is done in-memory; consider streaming for very large exports

---

## Related APIs
- [Customer Reconciliation Slip API](./API_CustomerReconciliationSlip.md)
- [Customer Reconciliation Slip Excel Export API](./API_CustomerReconciliationSlipExcelExport.md)
- [Get Reconciliable Orders API](./API_CustomerReconciliationSlip.md#get-reconciliable-orders)

---

## Implementation Notes

### Service Dependencies
- `ICustomerReconciliationSlipService`: To fetch reconciliable orders
- `IRepository<Customer>`: To fetch customer information
- `IExcelFileService`: To save the generated Excel file

### Excel Generation
The Excel file is generated using EPPlus library with the following helper methods:
- `CreateReconciliableOrdersExcelPackageAsync`: Main method to create the Excel package
- `AddCompanyHeader`: Adds company logo and header (reused from existing code)
- `AddReconciliableOrdersInfo`: Adds customer information
- `AddReconciliableOrdersTable`: Adds the orders table with data
- `FormatReconciliableOrdersWorksheet`: Applies formatting to the worksheet

### Data Limitations
Note that the `CustomerReconciliationSlipDetailItem` DTO does not include:
- Sender address information (Column B will be empty)
- Product/package information (Column D will be empty)

If this information is needed, consider:
1. Enhancing the `sp_GetReconciliableOrdersByCustomer` stored procedure to include this data
2. Updating the `CustomerReconciliationSlipDetailItem` DTO to include these fields
3. Modifying the `GetReconciliableOrdersAsync` method to populate these fields
