first commot
All checks were successful
Docker Build & Deploy / Build Docker Image (push) Successful in 8s
Docker Build & Deploy / Deploy to Production (push) Successful in 7s

This commit is contained in:
孙诚
2025-12-25 11:20:56 +08:00
commit 4526cc6396
104 changed files with 11070 additions and 0 deletions

View File

@@ -0,0 +1,142 @@
namespace Repository;
/// <summary>
/// 仓储基础接口
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
public interface IBaseRepository<T> where T : BaseEntity
{
/// <summary>
/// 获取所有数据
/// </summary>
Task<IEnumerable<T>> GetAllAsync();
/// <summary>
/// 根据ID获取单条数据
/// </summary>
Task<T?> GetByIdAsync(long id);
/// <summary>
/// 添加数据
/// </summary>
Task<bool> AddAsync(T entity);
/// <summary>
/// 添加数据
/// </summary>
Task<bool> AddRangeAsync(IEnumerable<T> entities);
/// <summary>
/// 更新数据
/// </summary>
Task<bool> UpdateAsync(T entity);
/// <summary>
/// 批量更新数据
/// </summary>
Task<bool> UpdateRangeAsync(IEnumerable<T> entities);
/// <summary>
/// 删除数据
/// </summary>
Task<bool> DeleteAsync(long id);
}
/// <summary>
/// 仓储基类实现 - 基于 FreeSql
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
public abstract class BaseRepository<T>(IFreeSql freeSql) : IBaseRepository<T> where T : BaseEntity
{
protected readonly IFreeSql FreeSql = freeSql ?? throw new ArgumentNullException(nameof(freeSql));
public virtual async Task<IEnumerable<T>> GetAllAsync()
{
try
{
return await FreeSql.Select<T>().ToListAsync();
}
catch
{
return [];
}
}
public virtual async Task<T?> GetByIdAsync(long id)
{
try
{
// FreeSql 会根据配置自动识别主键
return await FreeSql.Select<T>().Where(x => x.Id == id).FirstAsync();
}
catch
{
return null;
}
}
public virtual async Task<bool> AddAsync(T entity)
{
try
{
var result = await FreeSql.Insert(entity).ExecuteAffrowsAsync();
return result == 1;
}
catch
{
return false;
}
}
public async Task<bool> AddRangeAsync(IEnumerable<T> entities)
{
var result = await FreeSql.Insert(entities).ExecuteAffrowsAsync();
return result == entities.Count();
}
public virtual async Task<bool> UpdateAsync(T entity)
{
try
{
var affrows = await FreeSql.Update<T>()
.SetSource(entity)
.ExecuteAffrowsAsync();
return affrows > 0;
}
catch (Exception ex)
{
Console.WriteLine($"Update failed: {ex.Message}");
return false;
}
}
public virtual async Task<bool> UpdateRangeAsync(IEnumerable<T> entities)
{
try
{
var affrows = await FreeSql.Update<T>()
.SetSource(entities)
.ExecuteAffrowsAsync();
return affrows == entities.Count();
}
catch (Exception ex)
{
Console.WriteLine($"UpdateRange failed: {ex.Message}");
return false;
}
}
public virtual async Task<bool> DeleteAsync(long id)
{
try
{
var affrows = await FreeSql.Delete<T>().Where(x => x.Id == id).ExecuteAffrowsAsync();
return affrows > 0;
}
catch
{
return false;
}
}
}

View File

@@ -0,0 +1,64 @@
namespace Repository;
public interface IEmailMessageRepository : IBaseRepository<EmailMessage>
{
Task<EmailMessage?> ExistsAsync(
string from,
string subject,
DateTime receivedDate,
string body);
/// <summary>
/// 分页获取邮件列表(游标分页)
/// </summary>
/// <param name="lastReceivedDate">上一页最后一条记录的接收时间</param>
/// <param name="lastId">上一页最后一条记录的ID</param>
/// <param name="pageSize">每页数量</param>
/// <returns>邮件列表、最后接收时间和最后ID</returns>
Task<(List<EmailMessage> list, DateTime? lastReceivedDate, long lastId)> GetPagedListAsync(DateTime? lastReceivedDate, long? lastId, int pageSize = 20);
/// <summary>
/// 获取总数
/// </summary>
Task<long> GetTotalCountAsync();
}
public class EmailMessageRepository(IFreeSql freeSql) : BaseRepository<EmailMessage>(freeSql), IEmailMessageRepository
{
public async Task<EmailMessage?> ExistsAsync(
string from,
string subject,
DateTime receivedDate,
string body)
{
return await FreeSql.Select<EmailMessage>()
.Where(m => m.From == from && m.Subject == subject && m.ReceivedDate == receivedDate && m.Body == body)
.FirstAsync();
}
public async Task<(List<EmailMessage> list, DateTime? lastReceivedDate, long lastId)> GetPagedListAsync(DateTime? lastReceivedDate, long? lastId, int pageSize = 20)
{
var query = FreeSql.Select<EmailMessage>();
// 如果提供了游标,则获取小于游标位置的记录
if (lastReceivedDate.HasValue && lastId.HasValue)
{
query = query.Where(e => e.ReceivedDate < lastReceivedDate.Value ||
(e.ReceivedDate == lastReceivedDate.Value && e.Id < lastId.Value));
}
var list = await query
.OrderByDescending(e => e.ReceivedDate)
.OrderByDescending(e => e.Id)
.Page(1, pageSize)
.ToListAsync();
var lastRecord = list.Count > 0 ? list.Last() : null;
return (list, lastRecord?.ReceivedDate, lastRecord?.Id ?? 0);
}
public async Task<long> GetTotalCountAsync()
{
return await FreeSql.Select<EmailMessage>().CountAsync();
}
}

View File

@@ -0,0 +1,5 @@
global using Entity;
global using FreeSql;
global using System.Linq;

View File

@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj" />
<ProjectReference Include="..\Entity\Entity.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FreeSql.Provider.Sqlite" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,174 @@
namespace Repository;
/// <summary>
/// 交易分类仓储接口
/// </summary>
public interface ITransactionCategoryRepository : IBaseRepository<TransactionCategory>
{
/// <summary>
/// 根据类型获取所有顶级分类Level=2即类型下的分类
/// </summary>
Task<List<TransactionCategory>> GetTopLevelCategoriesByTypeAsync(TransactionType type);
/// <summary>
/// 根据父分类ID获取子分类
/// </summary>
Task<List<TransactionCategory>> GetChildCategoriesAsync(long parentId);
/// <summary>
/// 获取完整的分类树(按类型)
/// </summary>
Task<List<TransactionCategoryTreeDto>> GetCategoryTreeAsync(TransactionType? type = null);
/// <summary>
/// 根据名称和父ID查找分类防止重复
/// </summary>
Task<TransactionCategory?> GetByNameAndParentAsync(string name, long parentId, TransactionType type);
/// <summary>
/// 检查分类是否被使用
/// </summary>
Task<bool> IsCategoryInUseAsync(long categoryId);
}
/// <summary>
/// 交易分类仓储实现
/// </summary>
public class TransactionCategoryRepository(IFreeSql freeSql) : BaseRepository<TransactionCategory>(freeSql), ITransactionCategoryRepository
{
/// <summary>
/// 根据类型获取所有顶级分类Level=2
/// </summary>
public async Task<List<TransactionCategory>> GetTopLevelCategoriesByTypeAsync(TransactionType type)
{
return await FreeSql.Select<TransactionCategory>()
.Where(c => c.Type == type && c.Level == 2 && c.IsEnabled)
.OrderBy(c => c.SortOrder)
.OrderBy(c => c.Name)
.ToListAsync();
}
/// <summary>
/// 根据父分类ID获取子分类
/// </summary>
public async Task<List<TransactionCategory>> GetChildCategoriesAsync(long parentId)
{
return await FreeSql.Select<TransactionCategory>()
.Where(c => c.ParentId == parentId && c.IsEnabled)
.OrderBy(c => c.SortOrder)
.OrderBy(c => c.Name)
.ToListAsync();
}
/// <summary>
/// 获取完整的分类树
/// </summary>
public async Task<List<TransactionCategoryTreeDto>> GetCategoryTreeAsync(TransactionType? type = null)
{
var query = FreeSql.Select<TransactionCategory>()
.Where(c => c.IsEnabled);
if (type.HasValue)
{
query = query.Where(c => c.Type == type.Value);
}
var allCategories = await query
.OrderBy(c => c.Type)
.OrderBy(c => c.SortOrder)
.OrderBy(c => c.Name)
.ToListAsync();
// 构建树形结构Level 2为根节点即各个分类
var result = new List<TransactionCategoryTreeDto>();
var level2Categories = allCategories.Where(c => c.Level == 2).ToList();
foreach (var category in level2Categories)
{
var treeNode = new TransactionCategoryTreeDto
{
Id = category.Id,
Name = category.Name,
Type = category.Type,
Level = category.Level,
Icon = category.Icon,
Children = BuildChildrenTree(category.Id, allCategories)
};
result.Add(treeNode);
}
return result;
}
/// <summary>
/// 递归构建子分类树
/// </summary>
private List<TransactionCategoryTreeDto> BuildChildrenTree(long parentId, List<TransactionCategory> allCategories)
{
var children = allCategories.Where(c => c.ParentId == parentId).ToList();
var result = new List<TransactionCategoryTreeDto>();
foreach (var child in children)
{
var treeNode = new TransactionCategoryTreeDto
{
Id = child.Id,
Name = child.Name,
Type = child.Type,
Level = child.Level,
Icon = child.Icon,
Children = BuildChildrenTree(child.Id, allCategories)
};
result.Add(treeNode);
}
return result;
}
/// <summary>
/// 根据名称和父ID查找分类
/// </summary>
public async Task<TransactionCategory?> GetByNameAndParentAsync(string name, long parentId, TransactionType type)
{
return await FreeSql.Select<TransactionCategory>()
.Where(c => c.Name == name && c.ParentId == parentId && c.Type == type)
.FirstAsync();
}
/// <summary>
/// 检查分类是否被使用
/// </summary>
public async Task<bool> IsCategoryInUseAsync(long categoryId)
{
// 检查是否有交易记录使用此分类
var category = await GetByIdAsync(categoryId);
if (category == null) return false;
// 根据层级检查不同的字段
var count = category.Level switch
{
2 => await FreeSql.Select<TransactionRecord>()
.Where(r => r.Classify == category.Name && r.Type == category.Type)
.CountAsync(),
3 => await FreeSql.Select<TransactionRecord>()
.Where(r => r.SubClassify == category.Name && r.Type == category.Type)
.CountAsync(),
_ => 0
};
return count > 0;
}
}
/// <summary>
/// 分类树DTO
/// </summary>
public class TransactionCategoryTreeDto
{
public long Id { get; set; }
public string Name { get; set; } = string.Empty;
public TransactionType Type { get; set; }
public int Level { get; set; }
public string? Icon { get; set; }
public List<TransactionCategoryTreeDto> Children { get; set; } = new();
}

View File

@@ -0,0 +1,183 @@
namespace Repository;
public interface ITransactionRecordRepository : IBaseRepository<TransactionRecord>
{
Task<TransactionRecord?> ExistsByEmailMessageIdAsync(long emailMessageId, DateTime occurredAt);
Task<TransactionRecord?> ExistsByImportNoAsync(string importNo, string importFrom);
/// <summary>
/// 分页获取交易记录列表(游标分页)
/// </summary>
/// <param name="lastOccurredAt">上一页最后一条记录的发生时间</param>
/// <param name="lastId">上一页最后一条记录的ID</param>
/// <param name="pageSize">每页数量</param>
/// <param name="searchKeyword">搜索关键词(搜索交易摘要和分类)</param>
/// <returns>交易记录列表、最后发生时间和最后ID</returns>
Task<(List<TransactionRecord> list, DateTime? lastOccurredAt, long lastId)> GetPagedListAsync(DateTime? lastOccurredAt, long? lastId, int pageSize = 20, string? searchKeyword = null);
/// <summary>
/// 获取总数
/// </summary>
Task<long> GetTotalCountAsync();
/// <summary>
/// 获取所有不同的交易分类
/// </summary>
Task<List<string>> GetDistinctClassifyAsync();
/// <summary>
/// 获取所有不同的交易子分类
/// </summary>
Task<List<string>> GetDistinctSubClassifyAsync();
/// <summary>
/// 获取指定月份每天的消费统计
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns>每天的消费笔数和金额</returns>
Task<Dictionary<string, (int count, decimal amount)>> GetDailyStatisticsAsync(int year, int month);
/// <summary>
/// 获取指定日期范围内的交易记录
/// </summary>
/// <param name="startDate">开始日期</param>
/// <param name="endDate">结束日期</param>
/// <returns>交易记录列表</returns>
Task<List<TransactionRecord>> GetByDateRangeAsync(DateTime startDate, DateTime endDate);
/// <summary>
/// 获取指定邮件的交易记录数量
/// </summary>
/// <param name="emailMessageId">邮件ID</param>
/// <returns>交易记录数量</returns>
Task<int> GetCountByEmailIdAsync(long emailMessageId);
/// <summary>
/// 获取指定邮件的交易记录列表
/// </summary>
/// <param name="emailMessageId">邮件ID</param>
/// <returns>交易记录列表</returns>
Task<List<TransactionRecord>> GetByEmailIdAsync(long emailMessageId);
}
public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<TransactionRecord>(freeSql), ITransactionRecordRepository
{
public async Task<TransactionRecord?> ExistsByEmailMessageIdAsync(long emailMessageId, DateTime occurredAt)
{
return await FreeSql.Select<TransactionRecord>()
.Where(t => t.EmailMessageId == emailMessageId && t.OccurredAt == occurredAt)
.FirstAsync();
}
public async Task<TransactionRecord?> ExistsByImportNoAsync(string importNo, string importFrom)
{
return await FreeSql.Select<TransactionRecord>()
.Where(t => t.ImportNo == importNo && t.ImportFrom == importFrom)
.FirstAsync();
}
public async Task<(List<TransactionRecord> list, DateTime? lastOccurredAt, long lastId)> GetPagedListAsync(DateTime? lastOccurredAt, long? lastId, int pageSize = 20, string? searchKeyword = null)
{
var query = FreeSql.Select<TransactionRecord>();
// 如果提供了搜索关键词,则添加搜索条件
if (!string.IsNullOrWhiteSpace(searchKeyword))
{
query = query.Where(t => t.Reason.Contains(searchKeyword) ||
t.Classify.Contains(searchKeyword) ||
t.SubClassify.Contains(searchKeyword) ||
t.Card.Contains(searchKeyword) ||
t.ImportFrom.Contains(searchKeyword));
}
// 如果提供了游标,则获取小于游标位置的记录
if (lastOccurredAt.HasValue && lastId.HasValue)
{
query = query.Where(t => t.OccurredAt < lastOccurredAt.Value ||
(t.OccurredAt == lastOccurredAt.Value && t.Id < lastId.Value));
}
var list = await query
.OrderByDescending(t => t.OccurredAt)
.OrderByDescending(t => t.Id)
.Page(1, pageSize)
.ToListAsync();
var lastRecord = list.Count > 0 ? list.Last() : null;
return (list, lastRecord?.OccurredAt, lastRecord?.Id ?? 0);
}
public async Task<long> GetTotalCountAsync()
{
return await FreeSql.Select<TransactionRecord>().CountAsync();
}
public async Task<List<string>> GetDistinctClassifyAsync()
{
return await FreeSql.Select<TransactionRecord>()
.Where(t => !string.IsNullOrEmpty(t.Classify))
.Distinct()
.ToListAsync(t => t.Classify);
}
public async Task<List<string>> GetDistinctSubClassifyAsync()
{
return await FreeSql.Select<TransactionRecord>()
.Where(t => !string.IsNullOrEmpty(t.SubClassify))
.Distinct()
.ToListAsync(t => t.SubClassify);
}
public async Task<Dictionary<string, (int count, decimal amount)>> GetDailyStatisticsAsync(int year, int month)
{
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1);
var records = await FreeSql.Select<TransactionRecord>()
.Where(t => t.OccurredAt >= startDate && t.OccurredAt < endDate)
.Where(t => t.Type == TransactionType.Expense || t.Type == TransactionType.Income) // 统计消费和收入
.ToListAsync();
var statistics = records
.GroupBy(t => t.OccurredAt.ToString("yyyy-MM-dd"))
.ToDictionary(
g => g.Key,
g =>
{
// 分别统计收入和支出
var income = g.Where(t => t.Type == TransactionType.Income).Sum(t => t.Amount);
var expense = g.Where(t => t.Type == TransactionType.Expense).Sum(t => t.Amount);
// 净额 = 收入 - 支出(消费大于收入时为负数)
var netAmount = income - expense;
return (count: g.Count(), amount: netAmount);
}
);
return statistics;
}
public async Task<List<TransactionRecord>> GetByDateRangeAsync(DateTime startDate, DateTime endDate)
{
return await FreeSql.Select<TransactionRecord>()
.Where(t => t.OccurredAt >= startDate && t.OccurredAt <= endDate)
.OrderBy(t => t.OccurredAt)
.ToListAsync();
}
public async Task<int> GetCountByEmailIdAsync(long emailMessageId)
{
return (int)await FreeSql.Select<TransactionRecord>()
.Where(t => t.EmailMessageId == emailMessageId)
.CountAsync();
}
public async Task<List<TransactionRecord>> GetByEmailIdAsync(long emailMessageId)
{
return await FreeSql.Select<TransactionRecord>()
.Where(t => t.EmailMessageId == emailMessageId)
.OrderBy(t => t.OccurredAt)
.ToListAsync();
}
}