2025-12-25 11:20:56 +08:00
|
|
|
|
namespace WebApi.Controllers;
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 账单导入控制器
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
[ApiController]
|
|
|
|
|
|
[Route("api/[controller]/[action]")]
|
|
|
|
|
|
public class BillImportController(
|
|
|
|
|
|
ILogger<BillImportController> logger,
|
|
|
|
|
|
IImportService importService
|
|
|
|
|
|
) : ControllerBase
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 上传账单文件
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="file">账单文件</param>
|
|
|
|
|
|
/// <param name="type">账单类型(Alipay | WeChat)</param>
|
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
|
[HttpPost]
|
2026-01-04 16:43:32 +08:00
|
|
|
|
public async Task<BaseResponse> UploadFile(
|
2025-12-25 11:20:56 +08:00
|
|
|
|
[FromForm] IFormFile file,
|
|
|
|
|
|
[FromForm] string type
|
|
|
|
|
|
)
|
|
|
|
|
|
{
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
// 验证参数
|
|
|
|
|
|
if (file.Length == 0)
|
|
|
|
|
|
{
|
2026-01-04 16:43:32 +08:00
|
|
|
|
return "请选择要上传的文件".Fail();
|
2025-12-25 11:20:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrWhiteSpace(type) || (type != "Alipay" && type != "WeChat"))
|
|
|
|
|
|
{
|
2026-01-04 16:43:32 +08:00
|
|
|
|
return "账单类型参数错误,必须是 Alipay 或 WeChat".Fail();
|
2025-12-25 11:20:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 验证文件类型
|
|
|
|
|
|
var allowedExtensions = new[] { ".csv", ".xlsx", ".xls" };
|
|
|
|
|
|
var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
|
|
|
|
|
|
if (!allowedExtensions.Contains(fileExtension))
|
|
|
|
|
|
{
|
2026-01-04 16:43:32 +08:00
|
|
|
|
return "只支持 CSV 或 Excel 文件格式".Fail();
|
2025-12-25 11:20:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 验证文件大小(10MB限制)
|
|
|
|
|
|
const long maxFileSize = 10 * 1024 * 1024;
|
|
|
|
|
|
if (file.Length > maxFileSize)
|
|
|
|
|
|
{
|
2026-01-04 16:43:32 +08:00
|
|
|
|
return "文件大小不能超过 10MB".Fail();
|
2025-12-25 11:20:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 生成唯一文件名
|
|
|
|
|
|
var fileName = $"{type}_{DateTime.Now:yyyyMMddHHmmss}_{Guid.NewGuid():N}{fileExtension}";
|
|
|
|
|
|
|
|
|
|
|
|
// 保存文件
|
|
|
|
|
|
var ok = false;
|
|
|
|
|
|
var message = string.Empty;
|
|
|
|
|
|
await using (var stream = new MemoryStream())
|
|
|
|
|
|
{
|
|
|
|
|
|
await file.CopyToAsync(stream);
|
|
|
|
|
|
if (type == "Alipay")
|
|
|
|
|
|
{
|
|
|
|
|
|
(ok, message) = await importService.ImportAlipayAsync(stream, fileExtension);
|
|
|
|
|
|
}
|
|
|
|
|
|
else if (type == "WeChat")
|
|
|
|
|
|
{
|
|
|
|
|
|
(ok, message) = await importService.ImportWeChatAsync(stream, fileExtension);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-04 16:43:32 +08:00
|
|
|
|
return message.Ok();
|
2025-12-25 11:20:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
|
{
|
|
|
|
|
|
logger.LogError(ex, "文件上传失败,类型: {Type}", type);
|
2026-01-04 16:43:32 +08:00
|
|
|
|
return $"文件上传失败: {ex.Message}".Fail();
|
2025-12-25 11:20:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|