# Customer Reconciliation Slip Excel Export API

## Overview
This document describes the Excel export functionality for Customer Reconciliation Slips, which allows exporting both list and detail views of reconciliation slips to Excel format.

## API Endpoints

### 1. Export Excel List
**Endpoint:** `POST /api/CustomerReconciliationSlip/ExportExcel`

**Description:** Xuất Excel danh sách phiếu đối soát khách hàng

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

**Request Body:**
```json
{
  "FileName": "DanhSachPhieuDoiSoat",
  "CustomerReconciliationSlipIds": [1, 2, 3],
  "FromDate": "2024-01-01T00:00:00Z",
  "ToDate": "2024-12-31T23:59:59Z",
  "CustomerId": 123,
  "Status": 2,
  "Type": 1,
  "IncludeOrderDetails": true,
  "IncludeApprovalInfo": true,
  "IncludeNotes": true,
  "FolderPath": "/exports"
}
```

**Request Model:** `CustomerReconciliationSlipExcelExportModel`

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| FileName | string | No | Tên file Excel (không bao gồm extension) |
| CustomerReconciliationSlipIds | List<int> | No | Danh sách ID phiếu đối soát cần xuất |
| FromDate | DateTime? | No | Ngày bắt đầu (để filter) |
| ToDate | DateTime? | No | Ngày kết thúc (để filter) |
| CustomerId | int? | No | ID khách hàng (để filter) |
| Status | int? | No | Trạng thái phiếu đối soát (để filter) |
| Type | int? | No | Loại phiếu đối soát (để filter) |
| IncludeOrderDetails | bool | No | Có bao gồm chi tiết đơn hàng không (default: true) |
| IncludeApprovalInfo | bool | No | Có bao gồm thông tin duyệt/hoàn thành không (default: true) |
| IncludeNotes | bool | No | Có bao gồm ghi chú 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 Excel thành công",
  "FilePath": "/exports/DanhSachPhieuDoiSoatKhachHang.xlsx",
  "FileName": "DanhSachPhieuDoiSoatKhachHang.xlsx",
  "FileSize": 102400,
  "TotalRecords": 25,
  "DownloadUrl": "https://example.com/downloads/DanhSachPhieuDoiSoatKhachHang.xlsx",
  "ProcessStartTime": "2024-12-09T10:00:00Z",
  "ProcessEndTime": "2024-12-09T10:00:05Z",
  "ProcessingTimeMs": 5000,
  "ProcessInfo": {
    "DatabaseQueryTimeMs": 1500,
    "DataConversionTimeMs": 1000,
    "ExcelGenerationTimeMs": 2000,
    "FileSaveTimeMs": 500,
    "TotalProcessingTimeMs": 5000
  }
}
```

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

---

### 2. Export Excel Detail
**Endpoint:** `POST /api/CustomerReconciliationSlip/ExportExcelDetail/{slipId}`

**Description:** Xuất Excel chi tiết phiếu đối soát khách hàng

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

**Path Parameters:**
- `slipId` (int, required): ID phiếu đối soát

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

**Request Model:** `CustomerReconciliationSlipExcelExportModel` (same as above, but CustomerReconciliationSlipIds and filter fields are ignored)

**Response:** `CustomerReconciliationSlipExcelExportResult` (same structure as above)

**Status Codes:**
- `200 OK`: Export successful
- `400 Bad Request`: Invalid slip ID or validation errors
- `401 Unauthorized`: User not authenticated
- `403 Forbidden`: User doesn't have required permissions
- `404 Not Found`: Slip not found
- `500 Internal Server Error`: System error

---

## Data Models

### CustomerReconciliationSlipExcelExportModel
```csharp
public class CustomerReconciliationSlipExcelExportModel : BaseModel<int>
{
    public string? FileName { get; set; }
    public List<int>? CustomerReconciliationSlipIds { get; set; }
    public DateTime? FromDate { get; set; }
    public DateTime? ToDate { get; set; }
    public int? CustomerId { get; set; }
    public int? Status { get; set; }
    public int? Type { get; set; }
    public bool IncludeOrderDetails { get; set; } = true;
    public bool IncludeApprovalInfo { get; set; } = true;
    public bool IncludeNotes { get; set; } = true;
    public string? FolderPath { get; set; }
}
```

### CustomerReconciliationSlipExcelExportResult
```csharp
public class CustomerReconciliationSlipExcelExportResult : BaseResult
{
    public string? FilePath { get; set; }
    public string? FileName { get; set; }
    public long FileSize { get; set; }
    public int TotalRecords { get; set; }
    public string? DownloadUrl { get; set; }
    public DateTimeOffset ProcessStartTime { get; set; }
    public DateTimeOffset ProcessEndTime { get; set; }
    public long ProcessingTimeMs { get; }
    public CustomerReconciliationSlipExcelProcessInfo ProcessInfo { get; set; }
}

public class CustomerReconciliationSlipExcelProcessInfo
{
    public long DatabaseQueryTimeMs { get; set; }
    public long DataConversionTimeMs { get; set; }
    public long ExcelGenerationTimeMs { get; set; }
    public long FileSaveTimeMs { get; set; }
    public long TotalProcessingTimeMs { get; }
}
```

---

## Validation Rules

The model includes built-in validation:

1. **Date Range**: FromDate must not be greater than ToDate
2. **Slip IDs**: All IDs in CustomerReconciliationSlipIds must be positive integers
3. **File Name**: Must not contain invalid file name characters

---

## Slip Types and Statuses

### Slip Types (CustomerReconciliationSlipType)
- `1` - Receivable (Phiếu thanh toán - công ty chuyển tiền cho khách)
- `2` - Payable (Phiếu thu tiền - khách chuyển tiền cho công ty)

### Slip Statuses (CustomerReconciliationSlipStatus)
- `1` - Draft (Nháp)
- `2` - PendingApproval (Chờ duyệt)
- `3` - Approved (Đã duyệt)
- `4` - Completed (Hoàn thành)
- `8` - Rejected (Từ chối)

---

## Implementation Notes

### Current Status
The Excel export endpoints are currently **scaffolded** and return placeholder responses. The actual Excel generation logic needs to be implemented in a service layer.

### TODO
1. Create `ICustomerReconciliationSlipExcelService` interface
2. Implement `CustomerReconciliationSlipExcelService` with actual Excel generation logic
3. Inject the service into the controller
4. Implement the following methods:
   - `ExportCustomerReconciliationSlipsAsync(model)` - for list export
   - `ExportCustomerReconciliationSlipDetailAsync(slipId, model)` - for detail export

### Recommended Excel Structure

#### For List Export:
**Sheet 1: Summary**
- Slip Code
- Customer Name
- Customer Phone
- Type (Receivable/Payable)
- Status
- Total COD Amount
- Total Fee Amount
- Final Amount
- Order Count
- Created By
- Created Time
- Approved By
- Approved Time
- Completed By
- Completed Time

**Sheet 2: Order Details** (if IncludeOrderDetails = true)
- Slip Code
- Order Code
- Partner Code
- COD Amount
- Fee Amount
- Net Amount
- Delivered Date
- COD Collected Date
- Order Status
- Physical Status

#### For Detail Export:
**Sheet 1: Slip Information**
- All slip details including customer info, financial summary, approval info, etc.

**Sheet 2: Order Details**
- All orders in the slip with full details

**Sheet 3: Action Logs** (if IncludeNotes = true)
- Action history with timestamps, actors, and notes

---

## Usage Examples

### Example 1: Export all slips for a specific customer
```bash
POST /api/CustomerReconciliationSlip/ExportExcel
Content-Type: application/json
Authorization: Bearer {token}

{
  "CustomerId": 123,
  "IncludeOrderDetails": true,
  "IncludeApprovalInfo": true,
  "IncludeNotes": true
}
```

### Example 2: Export specific slips by IDs
```bash
POST /api/CustomerReconciliationSlip/ExportExcel
Content-Type: application/json
Authorization: Bearer {token}

{
  "CustomerReconciliationSlipIds": [1, 2, 3, 4, 5],
  "FileName": "PhieuDoiSoatThang12",
  "IncludeOrderDetails": true
}
```

### Example 3: Export single slip detail
```bash
POST /api/CustomerReconciliationSlip/ExportExcelDetail/123
Content-Type: application/json
Authorization: Bearer {token}

{
  "FileName": "ChiTietPhieu_CR-241209-A1B2",
  "IncludeOrderDetails": true,
  "IncludeApprovalInfo": true,
  "IncludeNotes": true
}
```

---

## Security Considerations

1. **Authorization**: Only users with `CustomerReconciliationSlip.ExportExcel` or `Founder` role can export
2. **Data Access**: Users should only be able to export slips they have permission to view
3. **File Storage**: Exported files should be stored securely with appropriate access controls
4. **Cleanup**: Implement automatic cleanup of old exported files to prevent disk space issues
5. **Rate Limiting**: Consider implementing rate limiting to prevent abuse

---

## Performance Considerations

1. **Large Datasets**: For large exports, consider implementing:
   - Background job processing
   - Progress tracking
   - Email notification when export is complete
2. **Caching**: Cache frequently exported data to improve performance
3. **Pagination**: For very large datasets, consider splitting into multiple files
4. **Async Processing**: Use async/await throughout the export pipeline

---

## Related Documentation
- [Customer Reconciliation Slip API](./API_CustomerReconciliationSlip.md)
- [Reconciliation Excel Export](./ReconciliationExcelExport.md)
- [Transfer Payment Bill Excel Export](./TransferPaymentBillExcelExport.md)
