优化代码
All checks were successful
Docker Build & Deploy / Build Docker Image (push) Successful in 23s
Docker Build & Deploy / Deploy to Production (push) Successful in 6s
Docker Build & Deploy / Cleanup Dangling Images (push) Successful in 1s

This commit is contained in:
孙诚
2026-01-04 16:43:32 +08:00
parent ab22325ca7
commit 557d44aed8
11 changed files with 200 additions and 460 deletions

View File

@@ -36,11 +36,7 @@ public class AuthController : ControllerBase
if (string.IsNullOrEmpty(request.Password) || request.Password != _authSettings.Password) if (string.IsNullOrEmpty(request.Password) || request.Password != _authSettings.Password)
{ {
_logger.LogWarning("登录失败: 密码错误"); _logger.LogWarning("登录失败: 密码错误");
return new BaseResponse<LoginResponse> return "密码错误".Fail<LoginResponse>();
{
Success = false,
Message = "密码错误"
};
} }
// 生成JWT Token // 生成JWT Token
@@ -49,15 +45,11 @@ public class AuthController : ControllerBase
_logger.LogInformation("用户登录成功"); _logger.LogInformation("用户登录成功");
return new BaseResponse<LoginResponse> return new LoginResponse
{ {
Success = true, Token = token,
Data = new LoginResponse ExpiresAt = expiresAt
{ }.Ok();
Token = token,
ExpiresAt = expiresAt
}
};
} }
private string GenerateJwtToken() private string GenerateJwtToken()

View File

@@ -17,7 +17,7 @@ public class BillImportController(
/// <param name="type">账单类型Alipay | WeChat</param> /// <param name="type">账单类型Alipay | WeChat</param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
public async Task<BaseResponse<object>> UploadFile( public async Task<BaseResponse> UploadFile(
[FromForm] IFormFile file, [FromForm] IFormFile file,
[FromForm] string type [FromForm] string type
) )
@@ -27,12 +27,12 @@ public class BillImportController(
// 验证参数 // 验证参数
if (file.Length == 0) if (file.Length == 0)
{ {
return BaseResponse<object>.Fail("请选择要上传的文件"); return "请选择要上传的文件".Fail();
} }
if (string.IsNullOrWhiteSpace(type) || (type != "Alipay" && type != "WeChat")) if (string.IsNullOrWhiteSpace(type) || (type != "Alipay" && type != "WeChat"))
{ {
return BaseResponse<object>.Fail("账单类型参数错误,必须是 Alipay 或 WeChat"); return "账单类型参数错误,必须是 Alipay 或 WeChat".Fail();
} }
// 验证文件类型 // 验证文件类型
@@ -40,14 +40,14 @@ public class BillImportController(
var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant(); var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (!allowedExtensions.Contains(fileExtension)) if (!allowedExtensions.Contains(fileExtension))
{ {
return BaseResponse<object>.Fail("只支持 CSV 或 Excel 文件格式"); return "只支持 CSV 或 Excel 文件格式".Fail();
} }
// 验证文件大小10MB限制 // 验证文件大小10MB限制
const long maxFileSize = 10 * 1024 * 1024; const long maxFileSize = 10 * 1024 * 1024;
if (file.Length > maxFileSize) if (file.Length > maxFileSize)
{ {
return BaseResponse<object>.Fail("文件大小不能超过 10MB"); return "文件大小不能超过 10MB".Fail();
} }
// 生成唯一文件名 // 生成唯一文件名
@@ -69,16 +69,12 @@ public class BillImportController(
} }
} }
return new BaseResponse<object> return message.Ok();
{
Success = ok,
Message = message
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "文件上传失败,类型: {Type}", type); logger.LogError(ex, "文件上传失败,类型: {Type}", type);
return BaseResponse<object>.Fail($"文件上传失败: {ex.Message}"); return $"文件上传失败: {ex.Message}".Fail();
} }
} }
} }

View File

@@ -1,5 +1,54 @@
namespace WebApi.Controllers.Dto; namespace WebApi.Controllers.Dto;
public static class BaseResponseExtensions
{
public static BaseResponse<T> Ok<T>(this T response)
{
return new BaseResponse<T>
{
Success = true,
Data = response
};
}
public static BaseResponse<T> Ok<T>(this T response, string message)
{
return new BaseResponse<T>
{
Success = true,
Data = response,
Message = message
};
}
public static BaseResponse Ok(this string message)
{
return new BaseResponse
{
Success = true,
Message = message
};
}
public static BaseResponse<T> Fail<T>(this string message)
{
return new BaseResponse<T>
{
Success = false,
Message = message
};
}
public static BaseResponse Fail(this string message)
{
return new BaseResponse
{
Success = false,
Message = message
};
}
}
public class BaseResponse public class BaseResponse
{ {
/// <summary> /// <summary>
@@ -28,6 +77,15 @@ public class BaseResponse
Success = true Success = true
}; };
} }
public static BaseResponse Done(string message)
{
return new BaseResponse
{
Success = true,
Message = message
};
}
} }
public class BaseResponse<T> : BaseResponse public class BaseResponse<T> : BaseResponse

View File

@@ -61,23 +61,19 @@ public class EmailMessageController(
var email = await emailRepository.GetByIdAsync(id); var email = await emailRepository.GetByIdAsync(id);
if (email == null) if (email == null)
{ {
return BaseResponse<EmailMessageDto>.Fail("邮件不存在"); return "邮件不存在".Fail<EmailMessageDto>();
} }
// 获取账单数量 // 获取账单数量
var transactionCount = await transactionRepository.GetCountByEmailIdAsync(id); var transactionCount = await transactionRepository.GetCountByEmailIdAsync(id);
var emailDto = EmailMessageDto.FromEntity(email, transactionCount); var emailDto = EmailMessageDto.FromEntity(email, transactionCount);
return new BaseResponse<EmailMessageDto> return emailDto.Ok();
{
Success = true,
Data = emailDto
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取邮件详情失败邮件ID: {EmailId}", id); logger.LogError(ex, "获取邮件详情失败邮件ID: {EmailId}", id);
return BaseResponse<EmailMessageDto>.Fail($"获取邮件详情失败: {ex.Message}"); return $"获取邮件详情失败: {ex.Message}".Fail<EmailMessageDto>();
} }
} }
@@ -88,20 +84,17 @@ public class EmailMessageController(
var success = await emailRepository.DeleteAsync(id); var success = await emailRepository.DeleteAsync(id);
if (success) if (success)
{ {
return new BaseResponse return BaseResponse.Done();
{
Success = true
};
} }
else else
{ {
return BaseResponse.Fail("删除邮件失败,邮件不存在"); return "删除邮件失败,邮件不存在".Fail();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "删除邮件失败邮件ID: {EmailId}", id); logger.LogError(ex, "删除邮件失败邮件ID: {EmailId}", id);
return BaseResponse.Fail($"删除邮件失败: {ex.Message}"); return $"删除邮件失败: {ex.Message}".Fail();
} }
} }
@@ -116,26 +109,23 @@ public class EmailMessageController(
var email = await emailRepository.GetByIdAsync(id); var email = await emailRepository.GetByIdAsync(id);
if (email == null) if (email == null)
{ {
return BaseResponse.Fail("邮件不存在"); return "邮件不存在".Fail();
} }
var success = await emailHandleService.RefreshTransactionRecordsAsync(id); var success = await emailHandleService.RefreshTransactionRecordsAsync(id);
if (success) if (success)
{ {
return new BaseResponse return BaseResponse.Done();
{
Success = true
};
} }
else else
{ {
return BaseResponse.Fail("重新分析失败"); return "重新分析失败".Fail();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "重新分析邮件失败邮件ID: {EmailId}", id); logger.LogError(ex, "重新分析邮件失败邮件ID: {EmailId}", id);
return BaseResponse.Fail($"重新分析失败: {ex.Message}"); return $"重新分析失败: {ex.Message}".Fail();
} }
} }
@@ -148,16 +138,12 @@ public class EmailMessageController(
try try
{ {
await emailBackgroundService.SyncEmailsAsync(); await emailBackgroundService.SyncEmailsAsync();
return new BaseResponse return "邮件同步成功".Ok();
{
Success = true,
Message = "同步成功"
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "同步邮件失败"); logger.LogError(ex, "同步邮件失败");
return BaseResponse.Fail($"同步邮件失败: {ex.Message}"); return $"同步邮件失败: {ex.Message}".Fail();
} }
} }
} }

View File

@@ -1,174 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Quartz;
namespace WebApi.Controllers;
/// <summary>
/// 定时任务管理控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class JobController(
ISchedulerFactory schedulerFactory,
ILogger<JobController> logger) : ControllerBase
{
/// <summary>
/// 手动触发邮件同步任务
/// </summary>
[HttpPost("sync-email")]
[Authorize]
public async Task<IActionResult> TriggerEmailSync()
{
try
{
var scheduler = await schedulerFactory.GetScheduler();
var jobKey = new JobKey("EmailSyncJob");
// 立即触发任务
await scheduler.TriggerJob(jobKey);
logger.LogInformation("手动触发邮件同步任务成功");
return Ok(new { message = "邮件同步任务已触发" });
}
catch (Exception ex)
{
logger.LogError(ex, "触发邮件同步任务失败");
return StatusCode(500, new { message = "触发任务失败", error = ex.Message });
}
}
/// <summary>
/// 手动触发周期性账单任务
/// </summary>
[HttpPost("periodic-bill")]
[Authorize]
public async Task<IActionResult> TriggerPeriodicBill()
{
try
{
var scheduler = await schedulerFactory.GetScheduler();
var jobKey = new JobKey("PeriodicBillJob");
// 立即触发任务
await scheduler.TriggerJob(jobKey);
logger.LogInformation("手动触发周期性账单任务成功");
return Ok(new { message = "周期性账单任务已触发" });
}
catch (Exception ex)
{
logger.LogError(ex, "触发周期性账单任务失败");
return StatusCode(500, new { message = "触发任务失败", error = ex.Message });
}
}
/// <summary>
/// 获取所有任务的状态
/// </summary>
[HttpGet("status")]
[Authorize]
public async Task<IActionResult> GetJobStatus()
{
try
{
var scheduler = await schedulerFactory.GetScheduler();
var jobGroups = await scheduler.GetJobGroupNames();
var jobStatuses = new List<object>();
foreach (var group in jobGroups)
{
var jobKeys = await scheduler.GetJobKeys(Quartz.Impl.Matchers.GroupMatcher<JobKey>.GroupEquals(group));
foreach (var jobKey in jobKeys)
{
var triggers = await scheduler.GetTriggersOfJob(jobKey);
var jobDetail = await scheduler.GetJobDetail(jobKey);
foreach (var trigger in triggers)
{
var triggerState = await scheduler.GetTriggerState(trigger.Key);
var nextFireTime = trigger.GetNextFireTimeUtc();
var previousFireTime = trigger.GetPreviousFireTimeUtc();
jobStatuses.Add(new
{
jobName = jobKey.Name,
jobGroup = jobKey.Group,
triggerName = trigger.Key.Name,
triggerState = triggerState.ToString(),
nextFireTime = nextFireTime?.LocalDateTime,
previousFireTime = previousFireTime?.LocalDateTime,
description = trigger.Description,
jobType = jobDetail?.JobType.Name
});
}
}
}
return Ok(jobStatuses);
}
catch (Exception ex)
{
logger.LogError(ex, "获取任务状态失败");
return StatusCode(500, new { message = "获取任务状态失败", error = ex.Message });
}
}
/// <summary>
/// 暂停指定任务
/// </summary>
[HttpPost("pause/{jobName}")]
[Authorize]
public async Task<IActionResult> PauseJob(string jobName)
{
try
{
var scheduler = await schedulerFactory.GetScheduler();
var jobKey = new JobKey(jobName);
if (!await scheduler.CheckExists(jobKey))
{
return NotFound(new { message = $"任务 {jobName} 不存在" });
}
await scheduler.PauseJob(jobKey);
logger.LogInformation("任务 {JobName} 已暂停", jobName);
return Ok(new { message = $"任务 {jobName} 已暂停" });
}
catch (Exception ex)
{
logger.LogError(ex, "暂停任务 {JobName} 失败", jobName);
return StatusCode(500, new { message = "暂停任务失败", error = ex.Message });
}
}
/// <summary>
/// 恢复指定任务
/// </summary>
[HttpPost("resume/{jobName}")]
[Authorize]
public async Task<IActionResult> ResumeJob(string jobName)
{
try
{
var scheduler = await schedulerFactory.GetScheduler();
var jobKey = new JobKey(jobName);
if (!await scheduler.CheckExists(jobKey))
{
return NotFound(new { message = $"任务 {jobName} 不存在" });
}
await scheduler.ResumeJob(jobKey);
logger.LogInformation("任务 {JobName} 已恢复", jobName);
return Ok(new { message = $"任务 {jobName} 已恢复" });
}
catch (Exception ex)
{
logger.LogError(ex, "恢复任务 {JobName} 失败", jobName);
return StatusCode(500, new { message = "恢复任务失败", error = ex.Message });
}
}
}

View File

@@ -22,13 +22,7 @@ public class LogController(ILogger<LogController> logger) : ControllerBase
var logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "logs"); var logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "logs");
if (!Directory.Exists(logDirectory)) if (!Directory.Exists(logDirectory))
{ {
return new PagedResponse<LogEntry> return PagedResponse<LogEntry>.Fail("日志目录不存在");
{
Success = true,
Data = [],
Total = 0,
Message = "日志目录不存在"
};
} }
// 确定要读取的日志文件 // 确定要读取的日志文件
@@ -47,17 +41,11 @@ public class LogController(ILogger<LogController> logger) : ControllerBase
// 检查文件是否存在 // 检查文件是否存在
if (!System.IO.File.Exists(logFilePath)) if (!System.IO.File.Exists(logFilePath))
{ {
return new PagedResponse<LogEntry> return PagedResponse<LogEntry>.Done([], 0);
{
Success = true,
Data = [],
Total = 0,
Message = "日志文件不存在"
};
} }
// 流式读取日志(边读边过滤,满足条件后停止) // 流式读取日志(边读边过滤,满足条件后停止)
var (logEntries, total) = await ReadLogsStreamAsync( var (logEntries, total) = await ReadLogsAsync(
logFilePath, logFilePath,
pageIndex, pageIndex,
pageSize, pageSize,
@@ -66,24 +54,12 @@ public class LogController(ILogger<LogController> logger) : ControllerBase
var pagedData = logEntries; var pagedData = logEntries;
return new PagedResponse<LogEntry> return PagedResponse<LogEntry>.Done(pagedData.ToArray(), total);
{
Success = true,
Data = pagedData.ToArray(),
Total = total,
Message = "获取日志成功"
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取日志失败"); logger.LogError(ex, "获取日志失败");
return new PagedResponse<LogEntry> return PagedResponse<LogEntry>.Fail($"获取日志失败: {ex.Message}");
{
Success = false,
Data = [],
Total = 0,
Message = $"获取日志失败: {ex.Message}"
};
} }
} }
@@ -91,14 +67,14 @@ public class LogController(ILogger<LogController> logger) : ControllerBase
/// 获取可用的日志日期列表 /// 获取可用的日志日期列表
/// </summary> /// </summary>
[HttpGet] [HttpGet]
public IActionResult GetAvailableDates() public BaseResponse<string[]> GetAvailableDates()
{ {
try try
{ {
var logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "logs"); var logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "logs");
if (!Directory.Exists(logDirectory)) if (!Directory.Exists(logDirectory))
{ {
return Ok(new { success = true, data = new List<string>() }); return ((string[])[]).Ok();
} }
var logFiles = Directory.GetFiles(logDirectory, "log-*.txt"); var logFiles = Directory.GetFiles(logDirectory, "log-*.txt");
@@ -108,12 +84,12 @@ public class LogController(ILogger<LogController> logger) : ControllerBase
.OrderByDescending(d => d) .OrderByDescending(d => d)
.ToList(); .ToList();
return Ok(new { success = true, data = dates }); return dates.ToArray().Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取日志日期列表失败"); logger.LogError(ex, "获取日志日期列表失败");
return Ok(new { success = false, message = $"获取日志日期列表失败: {ex.Message}" }); return $"获取日志日期列表失败: {ex.Message}".Fail<string[]>();
} }
} }
@@ -206,19 +182,17 @@ public class LogController(ILogger<LogController> logger) : ControllerBase
} }
/// <summary> /// <summary>
/// 流式读取日志(真正的流式:只读取需要的数据,满足后立即停止) /// 读取日志
/// </summary> /// </summary>
private async Task<(List<LogEntry> entries, int total)> ReadLogsStreamAsync( private async Task<(List<LogEntry> entries, int total)> ReadLogsAsync(
string path, string path,
int pageIndex, int pageIndex,
int pageSize, int pageSize,
string? searchKeyword, string? searchKeyword,
string? logLevel) string? logLevel)
{ {
// 简化:一次性读取所有行,合并多行日志,过滤并在内存中分页
var allLines = await ReadAllLinesAsync(path); var allLines = await ReadAllLinesAsync(path);
// 合并多行日志为独立条目
var merged = MergeMultiLineLog(allLines); var merged = MergeMultiLineLog(allLines);
var parsed = new List<LogEntry>(); var parsed = new List<LogEntry>();
@@ -231,7 +205,6 @@ public class LogController(ILogger<LogController> logger) : ControllerBase
} }
} }
// 倒序(最新在前)
parsed.Reverse(); parsed.Reverse();
var total = parsed.Count; var total = parsed.Count;

View File

@@ -34,12 +34,12 @@ public class MessageRecordController(IMessageRecordService messageService, ILogg
try try
{ {
var count = await messageService.GetUnreadCountAsync(); var count = await messageService.GetUnreadCountAsync();
return BaseResponse<long>.Done(count); return count.Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取未读消息数量失败"); logger.LogError(ex, "获取未读消息数量失败");
return BaseResponse<long>.Fail($"获取未读消息数量失败: {ex.Message}"); return $"获取未读消息数量失败: {ex.Message}".Fail<long>();
} }
} }
@@ -52,12 +52,12 @@ public class MessageRecordController(IMessageRecordService messageService, ILogg
try try
{ {
var result = await messageService.MarkAsReadAsync(id); var result = await messageService.MarkAsReadAsync(id);
return BaseResponse<bool>.Done(result); return result.Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "标记消息已读失败ID: {Id}", id); logger.LogError(ex, "标记消息已读失败ID: {Id}", id);
return BaseResponse<bool>.Fail($"标记消息已读失败: {ex.Message}"); return $"标记消息已读失败: {ex.Message}".Fail<bool>();
} }
} }
@@ -70,12 +70,12 @@ public class MessageRecordController(IMessageRecordService messageService, ILogg
try try
{ {
var result = await messageService.MarkAllAsReadAsync(); var result = await messageService.MarkAllAsReadAsync();
return BaseResponse<bool>.Done(result); return result.Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "全部标记已读失败"); logger.LogError(ex, "全部标记已读失败");
return BaseResponse<bool>.Fail($"全部标记已读失败: {ex.Message}"); return $"全部标记已读失败: {ex.Message}".Fail<bool>();
} }
} }
@@ -88,12 +88,12 @@ public class MessageRecordController(IMessageRecordService messageService, ILogg
try try
{ {
var result = await messageService.DeleteAsync(id); var result = await messageService.DeleteAsync(id);
return BaseResponse<bool>.Done(result); return result.Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "删除消息失败ID: {Id}", id); logger.LogError(ex, "删除消息失败ID: {Id}", id);
return BaseResponse<bool>.Fail($"删除消息失败: {ex.Message}"); return $"删除消息失败: {ex.Message}".Fail<bool>();
} }
} }
@@ -106,12 +106,12 @@ public class MessageRecordController(IMessageRecordService messageService, ILogg
try try
{ {
var result = await messageService.AddAsync(message); var result = await messageService.AddAsync(message);
return BaseResponse<bool>.Done(result); return result.Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "新增消息失败"); logger.LogError(ex, "新增消息失败");
return BaseResponse<bool>.Fail($"新增消息失败: {ex.Message}"); return $"新增消息失败: {ex.Message}".Fail<bool>();
} }
} }
} }

View File

@@ -10,11 +10,11 @@ public class NotificationController(INotificationService notificationService) :
try try
{ {
var key = await notificationService.GetVapidPublicKeyAsync(); var key = await notificationService.GetVapidPublicKeyAsync();
return BaseResponse<string>.Done(key); return key.Ok<string>();
} }
catch (Exception ex) catch (Exception ex)
{ {
return BaseResponse<string>.Fail(ex.Message); return ex.Message.Fail<string>();
} }
} }
@@ -27,7 +27,7 @@ public class NotificationController(INotificationService notificationService) :
} }
catch (Exception ex) catch (Exception ex)
{ {
return BaseResponse.Fail(ex.Message); return ex.Message.Fail();
} }
} }
@@ -40,7 +40,7 @@ public class NotificationController(INotificationService notificationService) :
} }
catch (Exception ex) catch (Exception ex)
{ {
return BaseResponse.Fail(ex.Message); return ex.Message.Fail();
} }
} }
} }

View File

@@ -26,16 +26,12 @@ public class TransactionCategoryController(
categories = (await categoryRepository.GetAllAsync()).ToList(); categories = (await categoryRepository.GetAllAsync()).ToList();
} }
return new BaseResponse<List<TransactionCategory>> return categories.Ok();
{
Success = true,
Data = categories
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取分类列表失败"); logger.LogError(ex, "获取分类列表失败");
return BaseResponse<List<TransactionCategory>>.Fail($"获取分类列表失败: {ex.Message}"); return $"获取分类列表失败: {ex.Message}".Fail<List<TransactionCategory>>();
} }
} }
@@ -50,19 +46,15 @@ public class TransactionCategoryController(
var category = await categoryRepository.GetByIdAsync(id); var category = await categoryRepository.GetByIdAsync(id);
if (category == null) if (category == null)
{ {
return BaseResponse<TransactionCategory>.Fail("分类不存在"); return "分类不存在".Fail<TransactionCategory>();
} }
return new BaseResponse<TransactionCategory> return category.Ok();
{
Success = true,
Data = category
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取分类详情失败, Id: {Id}", id); logger.LogError(ex, "获取分类详情失败, Id: {Id}", id);
return BaseResponse<TransactionCategory>.Fail($"获取分类详情失败: {ex.Message}"); return $"获取分类详情失败: {ex.Message}".Fail<TransactionCategory>();
} }
} }
@@ -78,7 +70,7 @@ public class TransactionCategoryController(
var existing = await categoryRepository.GetByNameAndTypeAsync(dto.Name, dto.Type); var existing = await categoryRepository.GetByNameAndTypeAsync(dto.Name, dto.Type);
if (existing != null) if (existing != null)
{ {
return BaseResponse<long>.Fail("已存在相同名称的分类"); return "已存在相同名称的分类".Fail<long>();
} }
var category = new TransactionCategory var category = new TransactionCategory
@@ -90,21 +82,17 @@ public class TransactionCategoryController(
var result = await categoryRepository.AddAsync(category); var result = await categoryRepository.AddAsync(category);
if (result) if (result)
{ {
return new BaseResponse<long> return category.Id.Ok();
{
Success = true,
Data = category.Id
};
} }
else else
{ {
return BaseResponse<long>.Fail("创建分类失败"); return "创建分类失败".Fail<long>();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "创建分类失败, Dto: {@Dto}", dto); logger.LogError(ex, "创建分类失败, Dto: {@Dto}", dto);
return BaseResponse<long>.Fail($"创建分类失败: {ex.Message}"); return $"创建分类失败: {ex.Message}".Fail<long>();
} }
} }
@@ -119,7 +107,7 @@ public class TransactionCategoryController(
var category = await categoryRepository.GetByIdAsync(dto.Id); var category = await categoryRepository.GetByIdAsync(dto.Id);
if (category == null) if (category == null)
{ {
return BaseResponse.Fail("分类不存在"); return "分类不存在".Fail();
} }
// 如果修改了名称,检查同名 // 如果修改了名称,检查同名
@@ -128,7 +116,7 @@ public class TransactionCategoryController(
var existing = await categoryRepository.GetByNameAndTypeAsync(dto.Name, category.Type); var existing = await categoryRepository.GetByNameAndTypeAsync(dto.Name, category.Type);
if (existing != null && existing.Id != dto.Id) if (existing != null && existing.Id != dto.Id)
{ {
return BaseResponse.Fail("已存在相同名称的分类"); return "已存在相同名称的分类".Fail();
} }
// 同步更新交易记录中的分类名称 // 同步更新交易记录中的分类名称
@@ -141,17 +129,17 @@ public class TransactionCategoryController(
var success = await categoryRepository.UpdateAsync(category); var success = await categoryRepository.UpdateAsync(category);
if (success) if (success)
{ {
return new BaseResponse { Success = true }; return "更新分类成功".Ok();
} }
else else
{ {
return BaseResponse.Fail("更新分类失败"); return "更新分类失败".Fail();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "更新分类失败, Dto: {@Dto}", dto); logger.LogError(ex, "更新分类失败, Dto: {@Dto}", dto);
return BaseResponse.Fail($"更新分类失败: {ex.Message}"); return $"更新分类失败: {ex.Message}".Fail();
} }
} }
@@ -167,23 +155,23 @@ public class TransactionCategoryController(
var inUse = await categoryRepository.IsCategoryInUseAsync(id); var inUse = await categoryRepository.IsCategoryInUseAsync(id);
if (inUse) if (inUse)
{ {
return BaseResponse.Fail("该分类已被使用,无法删除"); return "该分类已被使用,无法删除".Fail();
} }
var success = await categoryRepository.DeleteAsync(id); var success = await categoryRepository.DeleteAsync(id);
if (success) if (success)
{ {
return new BaseResponse { Success = true }; return BaseResponse.Done();
} }
else else
{ {
return BaseResponse.Fail("删除分类失败,分类不存在"); return "删除分类失败,分类不存在".Fail();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "删除分类失败, Id: {Id}", id); logger.LogError(ex, "删除分类失败, Id: {Id}", id);
return BaseResponse.Fail($"删除分类失败: {ex.Message}"); return $"删除分类失败: {ex.Message}".Fail();
} }
} }
@@ -204,21 +192,17 @@ public class TransactionCategoryController(
var result = await categoryRepository.AddRangeAsync(categories); var result = await categoryRepository.AddRangeAsync(categories);
if (result) if (result)
{ {
return new BaseResponse<int> return categories.Count.Ok();
{
Success = true,
Data = categories.Count
};
} }
else else
{ {
return BaseResponse<int>.Fail("批量创建分类失败"); return "批量创建分类失败".Fail<int>();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "批量创建分类失败, Count: {Count}", dtoList.Count); logger.LogError(ex, "批量创建分类失败, Count: {Count}", dtoList.Count);
return BaseResponse<int>.Fail($"批量创建分类失败: {ex.Message}"); return $"批量创建分类失败: {ex.Message}".Fail<int>();
} }
} }
} }

View File

@@ -53,19 +53,15 @@ public class TransactionPeriodicController(
var periodic = await periodicRepository.GetByIdAsync(id); var periodic = await periodicRepository.GetByIdAsync(id);
if (periodic == null) if (periodic == null)
{ {
return BaseResponse<TransactionPeriodic>.Fail("周期性账单不存在"); return "周期性账单不存在".Fail<TransactionPeriodic>();
} }
return new BaseResponse<TransactionPeriodic> return periodic.Ok();
{
Success = true,
Data = periodic
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取周期性账单详情失败ID: {Id}", id); logger.LogError(ex, "获取周期性账单详情失败ID: {Id}", id);
return BaseResponse<TransactionPeriodic>.Fail($"获取详情失败: {ex.Message}"); return $"获取详情失败: {ex.Message}".Fail<TransactionPeriodic>();
} }
} }
@@ -94,20 +90,15 @@ public class TransactionPeriodicController(
var success = await periodicRepository.AddAsync(periodic); var success = await periodicRepository.AddAsync(periodic);
if (!success) if (!success)
{ {
return BaseResponse<TransactionPeriodic>.Fail("创建周期性账单失败"); return "创建周期性账单失败".Fail<TransactionPeriodic>();
} }
return new BaseResponse<TransactionPeriodic> return periodic.Ok("创建成功");
{
Success = true,
Data = periodic,
Message = "创建成功"
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "创建周期性账单失败"); logger.LogError(ex, "创建周期性账单失败");
return BaseResponse<TransactionPeriodic>.Fail($"创建失败: {ex.Message}"); return $"创建失败: {ex.Message}".Fail<TransactionPeriodic>();
} }
} }
@@ -115,14 +106,14 @@ public class TransactionPeriodicController(
/// 更新周期性账单 /// 更新周期性账单
/// </summary> /// </summary>
[HttpPost] [HttpPost]
public async Task<BaseResponse<object>> UpdateAsync([FromBody] UpdatePeriodicRequest request) public async Task<BaseResponse> UpdateAsync([FromBody] UpdatePeriodicRequest request)
{ {
try try
{ {
var periodic = await periodicRepository.GetByIdAsync(request.Id); var periodic = await periodicRepository.GetByIdAsync(request.Id);
if (periodic == null) if (periodic == null)
{ {
return BaseResponse<object>.Fail("周期性账单不存在"); return "周期性账单不存在".Fail();
} }
periodic.PeriodicType = request.PeriodicType; periodic.PeriodicType = request.PeriodicType;
@@ -140,19 +131,15 @@ public class TransactionPeriodicController(
var success = await periodicRepository.UpdateAsync(periodic); var success = await periodicRepository.UpdateAsync(periodic);
if (!success) if (!success)
{ {
return BaseResponse<object>.Fail("更新周期性账单失败"); return "更新周期性账单失败".Fail();
} }
return new BaseResponse<object> return "更新成功".Ok();
{
Success = true,
Message = "更新成功"
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "更新周期性账单失败ID: {Id}", request.Id); logger.LogError(ex, "更新周期性账单失败ID: {Id}", request.Id);
return BaseResponse<object>.Fail($"更新失败: {ex.Message}"); return $"更新失败: {ex.Message}".Fail();
} }
} }
@@ -160,26 +147,22 @@ public class TransactionPeriodicController(
/// 删除周期性账单 /// 删除周期性账单
/// </summary> /// </summary>
[HttpPost] [HttpPost]
public async Task<BaseResponse<object>> DeleteByIdAsync([FromQuery] long id) public async Task<BaseResponse> DeleteByIdAsync([FromQuery] long id)
{ {
try try
{ {
var success = await periodicRepository.DeleteAsync(id); var success = await periodicRepository.DeleteAsync(id);
if (!success) if (!success)
{ {
return BaseResponse<object>.Fail("删除周期性账单失败"); return "删除周期性账单失败".Fail();
} }
return new BaseResponse<object> return "删除成功".Ok();
{
Success = true,
Message = "删除成功"
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "删除周期性账单失败ID: {Id}", id); logger.LogError(ex, "删除周期性账单失败ID: {Id}", id);
return BaseResponse<object>.Fail($"删除失败: {ex.Message}"); return $"删除失败: {ex.Message}".Fail();
} }
} }
@@ -187,14 +170,14 @@ public class TransactionPeriodicController(
/// 启用/禁用周期性账单 /// 启用/禁用周期性账单
/// </summary> /// </summary>
[HttpPost] [HttpPost]
public async Task<BaseResponse<object>> ToggleEnabledAsync([FromQuery] long id, [FromQuery] bool enabled) public async Task<BaseResponse> ToggleEnabledAsync([FromQuery] long id, [FromQuery] bool enabled)
{ {
try try
{ {
var periodic = await periodicRepository.GetByIdAsync(id); var periodic = await periodicRepository.GetByIdAsync(id);
if (periodic == null) if (periodic == null)
{ {
return BaseResponse<object>.Fail("周期性账单不存在"); return "周期性账单不存在".Fail();
} }
periodic.IsEnabled = enabled; periodic.IsEnabled = enabled;
@@ -203,19 +186,15 @@ public class TransactionPeriodicController(
var success = await periodicRepository.UpdateAsync(periodic); var success = await periodicRepository.UpdateAsync(periodic);
if (!success) if (!success)
{ {
return BaseResponse<object>.Fail("操作失败"); return "操作失败".Fail();
} }
return new BaseResponse<object> return (enabled ? "已启用" : "已禁用").Ok();
{
Success = true,
Message = enabled ? "已启用" : "已禁用"
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "启用/禁用周期性账单失败ID: {Id}", id); logger.LogError(ex, "启用/禁用周期性账单失败ID: {Id}", id);
return BaseResponse<object>.Fail($"操作失败: {ex.Message}"); return $"操作失败: {ex.Message}".Fail();
} }
} }
} }

View File

@@ -72,19 +72,15 @@ public class TransactionRecordController(
var transaction = await transactionRepository.GetByIdAsync(id); var transaction = await transactionRepository.GetByIdAsync(id);
if (transaction == null) if (transaction == null)
{ {
return BaseResponse<TransactionRecord>.Fail("交易记录不存在"); return "交易记录不存在".Fail<TransactionRecord>();
} }
return new BaseResponse<TransactionRecord> return transaction.Ok();
{
Success = true,
Data = transaction
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取交易记录详情失败交易ID: {TransactionId}", id); logger.LogError(ex, "获取交易记录详情失败交易ID: {TransactionId}", id);
return BaseResponse<TransactionRecord>.Fail($"获取交易记录详情失败: {ex.Message}"); return $"获取交易记录详情失败: {ex.Message}".Fail<TransactionRecord>();
} }
} }
@@ -97,16 +93,12 @@ public class TransactionRecordController(
try try
{ {
var transactions = await transactionRepository.GetByEmailIdAsync(emailId); var transactions = await transactionRepository.GetByEmailIdAsync(emailId);
return new BaseResponse<List<TransactionRecord>> return transactions.Ok();
{
Success = true,
Data = transactions
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取邮件交易记录失败邮件ID: {EmailId}", emailId); logger.LogError(ex, "获取邮件交易记录失败邮件ID: {EmailId}", emailId);
return BaseResponse<List<TransactionRecord>>.Fail($"获取邮件交易记录失败: {ex.Message}"); return $"获取邮件交易记录失败: {ex.Message}".Fail<List<TransactionRecord>>();
} }
} }
@@ -121,7 +113,7 @@ public class TransactionRecordController(
// 解析日期字符串 // 解析日期字符串
if (!DateTime.TryParse(dto.OccurredAt, out var occurredAt)) if (!DateTime.TryParse(dto.OccurredAt, out var occurredAt))
{ {
return BaseResponse.Fail("交易时间格式不正确"); return "交易时间格式不正确".Fail();
} }
var transaction = new TransactionRecord var transaction = new TransactionRecord
@@ -140,20 +132,17 @@ public class TransactionRecordController(
var result = await transactionRepository.AddAsync(transaction); var result = await transactionRepository.AddAsync(transaction);
if (result) if (result)
{ {
return new BaseResponse return BaseResponse.Done();
{
Success = true
};
} }
else else
{ {
return BaseResponse.Fail("创建交易记录失败"); return "创建交易记录失败".Fail();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "创建交易记录失败,交易信息: {@TransactionDto}", dto); logger.LogError(ex, "创建交易记录失败,交易信息: {@TransactionDto}", dto);
return BaseResponse.Fail($"创建交易记录失败: {ex.Message}"); return $"创建交易记录失败: {ex.Message}".Fail();
} }
} }
@@ -168,7 +157,7 @@ public class TransactionRecordController(
var transaction = await transactionRepository.GetByIdAsync(dto.Id); var transaction = await transactionRepository.GetByIdAsync(dto.Id);
if (transaction == null) if (transaction == null)
{ {
return BaseResponse.Fail("交易记录不存在"); return "交易记录不存在".Fail();
} }
// 更新可编辑字段 // 更新可编辑字段
@@ -181,20 +170,17 @@ public class TransactionRecordController(
var success = await transactionRepository.UpdateAsync(transaction); var success = await transactionRepository.UpdateAsync(transaction);
if (success) if (success)
{ {
return new BaseResponse return BaseResponse.Done();
{
Success = true
};
} }
else else
{ {
return BaseResponse.Fail("更新交易记录失败"); return "更新交易记录失败".Fail();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "更新交易记录失败交易ID: {TransactionId}, 交易信息: {@TransactionDto}", dto.Id, dto); logger.LogError(ex, "更新交易记录失败交易ID: {TransactionId}, 交易信息: {@TransactionDto}", dto.Id, dto);
return BaseResponse.Fail($"更新交易记录失败: {ex.Message}"); return $"更新交易记录失败: {ex.Message}".Fail();
} }
} }
@@ -209,20 +195,17 @@ public class TransactionRecordController(
var success = await transactionRepository.DeleteAsync(id); var success = await transactionRepository.DeleteAsync(id);
if (success) if (success)
{ {
return new BaseResponse return BaseResponse.Done();
{
Success = true
};
} }
else else
{ {
return BaseResponse.Fail("删除交易记录失败,记录不存在"); return "删除交易记录失败,记录不存在".Fail();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "删除交易记录失败交易ID: {TransactionId}", id); logger.LogError(ex, "删除交易记录失败交易ID: {TransactionId}", id);
return BaseResponse.Fail($"删除交易记录失败: {ex.Message}"); return $"删除交易记录失败: {ex.Message}".Fail();
} }
} }
@@ -240,16 +223,12 @@ public class TransactionRecordController(
var statistics = await transactionRepository.GetDailyStatisticsAsync(year, month); var statistics = await transactionRepository.GetDailyStatisticsAsync(year, month);
var result = statistics.Select(s => new DailyStatisticsDto(s.Key, s.Value.count, s.Value.amount)).ToList(); var result = statistics.Select(s => new DailyStatisticsDto(s.Key, s.Value.count, s.Value.amount)).ToList();
return new BaseResponse<List<DailyStatisticsDto>> return result.Ok();
{
Success = true,
Data = result
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取日历统计数据失败,年份: {Year}, 月份: {Month}", year, month); logger.LogError(ex, "获取日历统计数据失败,年份: {Year}, 月份: {Month}", year, month);
return BaseResponse<List<DailyStatisticsDto>>.Fail($"获取日历统计数据失败: {ex.Message}"); return $"获取日历统计数据失败: {ex.Message}".Fail<List<DailyStatisticsDto>>();
} }
} }
@@ -265,16 +244,12 @@ public class TransactionRecordController(
try try
{ {
var statistics = await transactionRepository.GetMonthlyStatisticsAsync(year, month); var statistics = await transactionRepository.GetMonthlyStatisticsAsync(year, month);
return new BaseResponse<MonthlyStatistics> return statistics.Ok();
{
Success = true,
Data = statistics
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取月度统计数据失败,年份: {Year}, 月份: {Month}", year, month); logger.LogError(ex, "获取月度统计数据失败,年份: {Year}, 月份: {Month}", year, month);
return BaseResponse<MonthlyStatistics>.Fail($"获取月度统计数据失败: {ex.Message}"); return $"获取月度统计数据失败: {ex.Message}".Fail<MonthlyStatistics>();
} }
} }
@@ -291,16 +266,12 @@ public class TransactionRecordController(
try try
{ {
var statistics = await transactionRepository.GetCategoryStatisticsAsync(year, month, type); var statistics = await transactionRepository.GetCategoryStatisticsAsync(year, month, type);
return new BaseResponse<List<CategoryStatistics>> return statistics.Ok();
{
Success = true,
Data = statistics
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取分类统计数据失败,年份: {Year}, 月份: {Month}, 类型: {Type}", year, month, type); logger.LogError(ex, "获取分类统计数据失败,年份: {Year}, 月份: {Month}, 类型: {Type}", year, month, type);
return BaseResponse<List<CategoryStatistics>>.Fail($"获取分类统计数据失败: {ex.Message}"); return $"获取分类统计数据失败: {ex.Message}".Fail<List<CategoryStatistics>>();
} }
} }
@@ -317,16 +288,12 @@ public class TransactionRecordController(
try try
{ {
var statistics = await transactionRepository.GetTrendStatisticsAsync(startYear, startMonth, monthCount); var statistics = await transactionRepository.GetTrendStatisticsAsync(startYear, startMonth, monthCount);
return new BaseResponse<List<TrendStatistics>> return statistics.Ok();
{
Success = true,
Data = statistics
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取趋势统计数据失败,开始年份: {Year}, 开始月份: {Month}, 月份数: {Count}", startYear, startMonth, monthCount); logger.LogError(ex, "获取趋势统计数据失败,开始年份: {Year}, 开始月份: {Month}, 月份数: {Count}", startYear, startMonth, monthCount);
return BaseResponse<List<TrendStatistics>>.Fail($"获取趋势统计数据失败: {ex.Message}"); return $"获取趋势统计数据失败: {ex.Message}".Fail<List<TrendStatistics>>();
} }
} }
@@ -361,7 +328,7 @@ public class TransactionRecordController(
{ {
if (!DateTime.TryParse(date, out var targetDate)) if (!DateTime.TryParse(date, out var targetDate))
{ {
return BaseResponse<List<TransactionRecord>>.Fail("日期格式不正确"); return "日期格式不正确".Fail<List<TransactionRecord>>();
} }
// 获取当天的开始和结束时间 // 获取当天的开始和结束时间
@@ -370,16 +337,12 @@ public class TransactionRecordController(
var records = await transactionRepository.GetByDateRangeAsync(startDate, endDate); var records = await transactionRepository.GetByDateRangeAsync(startDate, endDate);
return new BaseResponse<List<TransactionRecord>> return records.Ok();
{
Success = true,
Data = records
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取指定日期的交易记录失败,日期: {Date}", date); logger.LogError(ex, "获取指定日期的交易记录失败,日期: {Date}", date);
return BaseResponse<List<TransactionRecord>>.Fail($"获取指定日期的交易记录失败: {ex.Message}"); return $"获取指定日期的交易记录失败: {ex.Message}".Fail<List<TransactionRecord>>();
} }
} }
@@ -392,16 +355,12 @@ public class TransactionRecordController(
try try
{ {
var count = await transactionRepository.GetUnclassifiedCountAsync(); var count = await transactionRepository.GetUnclassifiedCountAsync();
return new BaseResponse<int> return count.Ok();
{
Success = true,
Data = count
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取未分类账单数量失败"); logger.LogError(ex, "获取未分类账单数量失败");
return BaseResponse<int>.Fail($"获取未分类账单数量失败: {ex.Message}"); return $"获取未分类账单数量失败: {ex.Message}".Fail<int>();
} }
} }
@@ -414,16 +373,12 @@ public class TransactionRecordController(
try try
{ {
var records = await transactionRepository.GetUnclassifiedAsync(pageSize); var records = await transactionRepository.GetUnclassifiedAsync(pageSize);
return new BaseResponse<List<TransactionRecord>> return records.Ok();
{
Success = true,
Data = records
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取未分类账单列表失败"); logger.LogError(ex, "获取未分类账单列表失败");
return BaseResponse<List<TransactionRecord>>.Fail($"获取未分类账单列表失败: {ex.Message}"); return $"获取未分类账单列表失败: {ex.Message}".Fail<List<TransactionRecord>>();
} }
} }
@@ -487,16 +442,12 @@ public class TransactionRecordController(
} }
} }
return new BaseResponse return $"批量更新完成,成功 {successCount} 条,失败 {failCount} 条".Ok();
{
Success = true,
Message = $"批量更新完成,成功 {successCount} 条,失败 {failCount} 条"
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "批量更新分类失败"); logger.LogError(ex, "批量更新分类失败");
return BaseResponse.Fail($"批量更新分类失败: {ex.Message}"); return $"批量更新分类失败: {ex.Message}".Fail();
} }
} }
@@ -534,17 +485,12 @@ public class TransactionRecordController(
try try
{ {
var count = await transactionRepository.BatchUpdateByReasonAsync(dto.Reason, dto.Type, dto.Classify); var count = await transactionRepository.BatchUpdateByReasonAsync(dto.Reason, dto.Type, dto.Classify);
return new BaseResponse<int> return count.Ok($"成功更新 {count} 条记录");
{
Success = true,
Data = count,
Message = $"成功更新 {count} 条记录"
};
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "按摘要批量更新分类失败,摘要: {Reason}", dto.Reason); logger.LogError(ex, "按摘要批量更新分类失败,摘要: {Reason}", dto.Reason);
return BaseResponse<int>.Fail($"按摘要批量更新分类失败: {ex.Message}"); return $"按摘要批量更新分类失败: {ex.Message}".Fail<int>();
} }
} }
@@ -556,7 +502,7 @@ public class TransactionRecordController(
{ {
if (string.IsNullOrEmpty(request.Text)) if (string.IsNullOrEmpty(request.Text))
{ {
return BaseResponse<TransactionParseResult>.Fail("请求参数缺失text"); return "请求参数缺失text".Fail<TransactionParseResult>();
} }
try try
@@ -565,15 +511,15 @@ public class TransactionRecordController(
if (result == null) if (result == null)
{ {
return BaseResponse<TransactionParseResult>.Fail("AI解析失败"); return "AI解析失败".Fail<TransactionParseResult>();
} }
return BaseResponse<TransactionParseResult>.Done(result); return result.Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "一句话录账解析失败,文本: {Text}", request.Text); logger.LogError(ex, "一句话录账解析失败,文本: {Text}", request.Text);
return BaseResponse<TransactionParseResult>.Fail("AI解析失败: " + ex.Message); return ("AI解析失败: " + ex.Message).Fail<TransactionParseResult>();
} }
} }
@@ -588,17 +534,17 @@ public class TransactionRecordController(
var current = await transactionRepository.GetByIdAsync(id); var current = await transactionRepository.GetByIdAsync(id);
if (current == null) if (current == null)
{ {
return BaseResponse<TransactionRecord[]>.Done([]); return ((TransactionRecord[])[]).Ok();
} }
var list = await transactionRepository.GetCandidatesForOffsetAsync(id, current.Amount, current.Type); var list = await transactionRepository.GetCandidatesForOffsetAsync(id, current.Amount, current.Type);
return BaseResponse<TransactionRecord[]>.Done(list.ToArray()); return list.ToArray().Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "获取抵账候选列表失败交易ID: {TransactionId}", id); logger.LogError(ex, "获取抵账候选列表失败交易ID: {TransactionId}", id);
return BaseResponse<TransactionRecord[]>.Fail($"获取抵账候选列表失败: {ex.Message}"); return $"获取抵账候选列表失败: {ex.Message}".Fail<TransactionRecord[]>();
} }
} }