功能添加
All checks were successful
Docker Build & Deploy / Build Docker Image (push) Successful in 20s
Docker Build & Deploy / Deploy to Production (push) Successful in 5s

This commit is contained in:
孙诚
2025-12-26 15:21:31 +08:00
parent 7dfb6a5902
commit cb11d80d1f
26 changed files with 2208 additions and 841 deletions

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"vue3snippets.enable-compile-vue-file-on-did-save-code": false
}

View File

@@ -1,4 +1,6 @@
namespace Entity;
using System.Security.Cryptography;
namespace Entity;
/// <summary>
/// 邮件消息实体
@@ -29,4 +31,14 @@ public class EmailMessage : BaseEntity
/// 邮件接收时间
/// </summary>
public DateTime ReceivedDate { get; set; }
public string Md5 { get; set; } = string.Empty;
public string ComputeBodyHash()
{
using var md5 = MD5.Create();
var inputBytes = System.Text.Encoding.UTF8.GetBytes(Body + HtmlBody);
var hashBytes = md5.ComputeHash(inputBytes);
return Convert.ToHexString(hashBytes);
}
}

View File

@@ -1,7 +1,7 @@
namespace Entity;
/// <summary>
/// 交易分类(层级结构:类型 -> 分类 -> 子分类)
/// 交易分类
/// </summary>
public class TransactionCategory : BaseEntity
{
@@ -10,38 +10,8 @@ public class TransactionCategory : BaseEntity
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 父分类ID0表示顶级分类
/// </summary>
public long ParentId { get; set; }
/// <summary>
/// 交易类型(支出/收入)
/// </summary>
public TransactionType Type { get; set; }
/// <summary>
/// 层级1=类型级, 2=分类级, 3=子分类级)
/// </summary>
public int Level { get; set; }
/// <summary>
/// 排序号
/// </summary>
public int SortOrder { get; set; }
/// <summary>
/// 图标(可选)
/// </summary>
public string? Icon { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; } = true;
/// <summary>
/// 备注
/// </summary>
public string? Remark { get; set; }
}

View File

@@ -50,11 +50,6 @@ public class TransactionRecord : BaseEntity
/// </summary>
public string Classify { get; set; } = string.Empty;
/// <summary>
/// 交易子分类
/// </summary>
public string SubClassify { get; set; } = string.Empty;
/// <summary>
/// 导入编号
/// </summary>

View File

@@ -2,11 +2,7 @@
public interface IEmailMessageRepository : IBaseRepository<EmailMessage>
{
Task<EmailMessage?> ExistsAsync(
string from,
string subject,
DateTime receivedDate,
string body);
Task<EmailMessage?> ExistsAsync(string md5);
/// <summary>
/// 分页获取邮件列表(游标分页)
@@ -25,14 +21,10 @@ public interface IEmailMessageRepository : IBaseRepository<EmailMessage>
public class EmailMessageRepository(IFreeSql freeSql) : BaseRepository<EmailMessage>(freeSql), IEmailMessageRepository
{
public async Task<EmailMessage?> ExistsAsync(
string from,
string subject,
DateTime receivedDate,
string body)
public async Task<EmailMessage?> ExistsAsync(string md5)
{
return await FreeSql.Select<EmailMessage>()
.Where(m => m.From == from && m.Subject == subject && m.ReceivedDate == receivedDate && m.Body == body)
.Where(e => e.Md5 == md5)
.FirstAsync();
}

View File

@@ -6,24 +6,14 @@
public interface ITransactionCategoryRepository : IBaseRepository<TransactionCategory>
{
/// <summary>
/// 根据类型获取所有顶级分类Level=2即类型下的分类
/// 根据类型获取所有分类
/// </summary>
Task<List<TransactionCategory>> GetTopLevelCategoriesByTypeAsync(TransactionType type);
Task<List<TransactionCategory>> GetCategoriesByTypeAsync(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);
Task<TransactionCategory?> GetByNameAndTypeAsync(string name, TransactionType type);
/// <summary>
/// 检查分类是否被使用
@@ -37,101 +27,23 @@ public interface ITransactionCategoryRepository : IBaseRepository<TransactionCat
public class TransactionCategoryRepository(IFreeSql freeSql) : BaseRepository<TransactionCategory>(freeSql), ITransactionCategoryRepository
{
/// <summary>
/// 根据类型获取所有顶级分类Level=2
/// 根据类型获取所有分类
/// </summary>
public async Task<List<TransactionCategory>> GetTopLevelCategoriesByTypeAsync(TransactionType type)
public async Task<List<TransactionCategory>> GetCategoriesByTypeAsync(TransactionType type)
{
return await FreeSql.Select<TransactionCategory>()
.Where(c => c.Type == type && c.Level == 2 && c.IsEnabled)
.OrderBy(c => c.SortOrder)
.Where(c => c.Type == type)
.OrderBy(c => c.Name)
.ToListAsync();
}
/// <summary>
/// 根据父分类ID获取子分类
/// 根据名称和类型查找分类
/// </summary>
public async Task<List<TransactionCategory>> GetChildCategoriesAsync(long parentId)
public async Task<TransactionCategory?> GetByNameAndTypeAsync(string name, TransactionType type)
{
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)
.Where(c => c.Name == name && c.Type == type)
.FirstAsync();
}
@@ -140,35 +52,13 @@ public class TransactionCategoryRepository(IFreeSql freeSql) : BaseRepository<Tr
/// </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
};
var count = await FreeSql.Select<TransactionRecord>()
.Where(r => r.Classify == category.Name && r.Type == category.Type)
.CountAsync();
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

@@ -26,11 +26,6 @@ public interface ITransactionRecordRepository : IBaseRepository<TransactionRecor
/// </summary>
Task<List<string>> GetDistinctClassifyAsync();
/// <summary>
/// 获取所有不同的交易子分类
/// </summary>
Task<List<string>> GetDistinctSubClassifyAsync();
/// <summary>
/// 获取指定月份每天的消费统计
/// </summary>
@@ -73,6 +68,30 @@ public interface ITransactionRecordRepository : IBaseRepository<TransactionRecor
/// <param name="pageSize">每页数量</param>
/// <returns>未分类账单列表</returns>
Task<List<TransactionRecord>> GetUnclassifiedAsync(int pageSize = 10);
/// <summary>
/// 获取按交易摘要(Reason)分组的统计信息(支持分页)
/// </summary>
/// <param name="pageIndex">页码从1开始</param>
/// <param name="pageSize">每页数量</param>
/// <returns>分组统计列表和总数</returns>
Task<(List<ReasonGroupDto> list, int total)> GetReasonGroupsAsync(int pageIndex = 1, int pageSize = 20);
/// <summary>
/// 按摘要批量更新交易记录的分类
/// </summary>
/// <param name="reason">交易摘要</param>
/// <param name="type">交易类型</param>
/// <param name="classify">分类名称</param>
/// <returns>更新的记录数量</returns>
Task<int> BatchUpdateByReasonAsync(string reason, TransactionType type, string classify);
/// <summary>
/// 根据关键词查询交易记录模糊匹配Reason字段
/// </summary>
/// <param name="keyword">关键词</param>
/// <returns>匹配的交易记录列表</returns>
Task<List<TransactionRecord>> QueryBySqlAsync(string sql);
}
public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<TransactionRecord>(freeSql), ITransactionRecordRepository
@@ -100,7 +119,6 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
{
query = query.Where(t => t.Reason.Contains(searchKeyword) ||
t.Classify.Contains(searchKeyword) ||
t.SubClassify.Contains(searchKeyword) ||
t.Card.Contains(searchKeyword) ||
t.ImportFrom.Contains(searchKeyword));
}
@@ -135,14 +153,6 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
.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);
@@ -209,4 +219,93 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
.Page(1, pageSize)
.ToListAsync();
}
public async Task<(List<ReasonGroupDto> list, int total)> GetReasonGroupsAsync(int pageIndex = 1, int pageSize = 20)
{
// 先按照Reason分组统计每个Reason的数量
var groups = await FreeSql.Select<TransactionRecord>()
.Where(t => !string.IsNullOrEmpty(t.Reason))
.Where(t => string.IsNullOrEmpty(t.Classify)) // 只统计未分类的
.GroupBy(t => t.Reason)
.ToListAsync(g => new
{
Reason = g.Key,
Count = g.Count()
});
// 按数量降序排序
var sortedGroups = groups.OrderByDescending(g => g.Count).ToList();
var total = sortedGroups.Count;
// 分页
var pagedGroups = sortedGroups
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToList();
// 为每个分组获取示例记录
var result = new List<ReasonGroupDto>();
foreach (var group in pagedGroups)
{
var sample = await FreeSql.Select<TransactionRecord>()
.Where(t => t.Reason == group.Reason)
.FirstAsync();
if (sample != null)
{
result.Add(new ReasonGroupDto
{
Reason = group.Reason,
Count = (int)group.Count,
SampleType = sample.Type,
SampleClassify = sample.Classify ?? string.Empty
});
}
}
return (result, total);
}
public async Task<int> BatchUpdateByReasonAsync(string reason, TransactionType type, string classify)
{
return await FreeSql.Update<TransactionRecord>()
.Set(t => t.Type, type)
.Set(t => t.Classify, classify)
.Where(t => t.Reason == reason)
.ExecuteAffrowsAsync();
}
public async Task<List<TransactionRecord>> QueryBySqlAsync(string sql)
{
return await FreeSql.Select<TransactionRecord>()
.Where(sql)
.OrderByDescending(t => t.OccurredAt)
.ToListAsync();
}
}
/// <summary>
/// 按Reason分组统计DTO
/// </summary>
public class ReasonGroupDto
{
/// <summary>
/// 交易摘要
/// </summary>
public string Reason { get; set; } = string.Empty;
/// <summary>
/// 该摘要的记录数量
/// </summary>
public int Count { get; set; }
/// <summary>
/// 示例交易类型(该分组中第一条记录的类型)
/// </summary>
public TransactionType SampleType { get; set; }
/// <summary>
/// 示例分类(该分组中第一条记录的分类)
/// </summary>
public string SampleClassify { get; set; } = string.Empty;
}

View File

@@ -195,7 +195,7 @@ public class EmailBackgroundService(
message.Subject,
message.Date.DateTime,
message.TextBody ?? message.HtmlBody ?? string.Empty
))
) || (DateTime.Now - message.Date.DateTime > TimeSpan.FromDays(3)))
{
#if DEBUG
logger.LogDebug("DEBUG 模式下,跳过标记已读步骤");

View File

@@ -29,24 +29,24 @@ public class EmailHandleService(
string body
)
{
var emailMessage = await SaveEmailAsync(from, subject, date, body);
if (emailMessage == null)
{
throw new InvalidOperationException("邮件保存失败,无法继续处理");
}
var filterForm = emailSettings.Value.FilterFromAddresses;
if (filterForm.Length == 0)
{
logger.LogWarning("未配置邮件过滤条件,跳过账单处理");
return true;
return false;
}
if (!filterForm.Any(f => from.Contains(f)))
{
logger.LogInformation("邮件不符合发件人过滤条件,跳过账单处理");
return true;
return false;
}
var emailMessage = await SaveEmailAsync(from, subject, date, body);
if (emailMessage == null)
{
throw new InvalidOperationException("邮件保存失败,无法继续处理");
}
var parsed = await ParseEmailBodyAsync(
@@ -161,7 +161,6 @@ public class EmailHandleService(
{
From = from,
Subject = subject,
ReceivedDate = date,
};
@@ -177,13 +176,15 @@ public class EmailHandleService(
try
{
var existsEmail = await emailRepo.ExistsAsync(from, subject, date, body);
var emailMd5 = emailEntity.ComputeBodyHash();
var existsEmail = await emailRepo.ExistsAsync(emailMd5);
if (existsEmail != null)
{
logger.LogInformation("检测到重复邮件,跳过入库:{From} | {Subject} | {Date}", from, subject, date);
return existsEmail;
}
emailEntity.Md5 = emailMd5;
var ok = await emailRepo.AddAsync(emailEntity);
if (ok)
{

View File

@@ -3,16 +3,19 @@
<div class="app-root">
<RouterView />
<van-tabbar v-model="active" v-show="showTabbar">
<van-tabbar-item icon="notes-o" to="/calendar">
<van-tabbar-item icon="notes" to="/calendar">
日历
</van-tabbar-item>
<van-tabbar-item icon="balance-list-o" to="/" @click="handleTabClick('/')">
<van-tabbar-item icon="chart-trending-o" to="/statistics">
统计
</van-tabbar-item>
<van-tabbar-item icon="balance-list" to="/" @click="handleTabClick('/')">
账单
</van-tabbar-item>
<van-tabbar-item icon="records-o" to="/email" @click="handleTabClick('/email')">
<van-tabbar-item icon="records" to="/email" @click="handleTabClick('/email')">
邮件
</van-tabbar-item>
<van-tabbar-item icon="setting-o" to="/setting">
<van-tabbar-item icon="setting" to="/setting">
设置
</van-tabbar-item>
</van-tabbar>
@@ -53,7 +56,8 @@ const showTabbar = computed(() => {
return route.path === '/' ||
route.path === '/calendar' ||
route.path === '/email' ||
route.path === '/setting'
route.path === '/setting' ||
route.path === '/statistics'
})
const active = ref(0)

View File

@@ -1,44 +1,18 @@
import request from './request'
/**
* 获取分类(支持按类型筛选)
* 获取分类列表(支持按类型筛选)
* @param {string|null} type - 交易类型(Expense=0/Income=1)null表示获取全部
* @returns {Promise<{success: boolean, data: Array}>}
*/
export const getCategoryTree = (type = null) => {
export const getCategoryList = (type = null) => {
return request({
url: '/TransactionCategory/GetTree',
url: '/TransactionCategory/GetList',
method: 'get',
params: type !== null ? { type } : {}
})
}
/**
* 获取顶级分类列表(按类型)
* @param {number} type - 交易类型(Expense=0/Income=1)
* @returns {Promise<{success: boolean, data: Array}>}
*/
export const getTopLevelCategories = (type) => {
return request({
url: '/TransactionCategory/GetTopLevel',
method: 'get',
params: { type }
})
}
/**
* 获取子分类列表
* @param {number} parentId - 父分类ID
* @returns {Promise<{success: boolean, data: Array}>}
*/
export const getChildCategories = (parentId) => {
return request({
url: '/TransactionCategory/GetChildren',
method: 'get',
params: { parentId }
})
}
/**
* 根据ID获取分类详情
* @param {number} id - 分类ID
@@ -53,7 +27,7 @@ export const getCategoryById = (id) => {
/**
* 创建分类
* @param {object} data - 分类数据
* @param {object} data - 分类数据 { name, type }
* @returns {Promise<{success: boolean, data: number}>} 返回新创建的分类ID
*/
export const createCategory = (data) => {
@@ -66,7 +40,7 @@ export const createCategory = (data) => {
/**
* 更新分类
* @param {object} data - 分类数据
* @param {object} data - 分类数据 { id, name }
* @returns {Promise<{success: boolean}>}
*/
export const updateCategory = (data) => {
@@ -92,7 +66,7 @@ export const deleteCategory = (id) => {
/**
* 批量创建分类(用于初始化)
* @param {Array} dataList - 分类数据数组
* @param {Array} dataList - 分类数据数组 [{ name, type }, ...]
* @returns {Promise<{success: boolean, data: number}>} 返回创建的数量
*/
export const batchCreateCategories = (dataList) => {

View File

@@ -41,7 +41,6 @@ export const getTransactionDetail = (id) => {
* @param {number} data.balance - 交易后余额
* @param {number} data.type - 交易类型 (0:支出, 1:收入, 2:不计入收支)
* @param {string} data.classify - 交易分类
* @param {string} data.subClassify - 交易子分类
* @returns {Promise<{success: boolean}>}
*/
export const createTransaction = (data) => {
@@ -60,7 +59,6 @@ export const createTransaction = (data) => {
* @param {number} data.balance - 交易后余额
* @param {number} data.type - 交易类型 (0:支出, 1:收入, 2:不计入收支)
* @param {string} data.classify - 交易分类
* @param {string} data.subClassify - 交易子分类
* @returns {Promise<{success: boolean}>}
*/
export const updateTransaction = (data) => {
@@ -99,7 +97,7 @@ export const getTransactionsByDate = (date) => {
// 注意分类相关的API已迁移到 transactionCategory.js
// 请使用 getCategoryTree 等新接口
// 请使用 getCategoryList 等新接口
/**
* 获取未分类的账单数量
@@ -127,13 +125,13 @@ export const getUnclassified = (pageSize = 10) => {
/**
* 智能分类 - 使用AI对账单进行分类EventSource流式响应
* @param {number} pageSize - 每次分类的账单数量
* @returns {EventSource} 返回EventSource对象用于接收流式数据
* @param {Array<number>} transactionIds - 分类的账单ID列表
* @returns {Promise<Response>} 返回响应对象用于接收流式数据
*/
export const smartClassify = (pageSize = 10) => {
const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000'
export const smartClassify = (transactionIds = []) => {
const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5071/api'
const token = localStorage.getItem('token')
const url = `${baseURL}/api/TransactionRecord/SmartClassify`
const url = `${baseURL}/TransactionRecord/SmartClassify`
return fetch(url, {
method: 'POST',
@@ -141,7 +139,7 @@ export const smartClassify = (pageSize = 10) => {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ pageSize })
body: JSON.stringify({ transactionIds })
})
}
@@ -149,8 +147,7 @@ export const smartClassify = (pageSize = 10) => {
* 批量更新账单分类
* @param {Array} items - 要更新的账单分类数据数组
* @param {number} items[].id - 账单ID
* @param {string} items[].classify - 一级分类
* @param {string} items[].subClassify - 子分类
* @param {string} items[].classify - 分类
* @returns {Promise<{success: boolean, message: string}>}
*/
export const batchUpdateClassify = (items) => {
@@ -160,3 +157,46 @@ export const batchUpdateClassify = (items) => {
data: items
})
}
/**
* 获取按交易摘要分组的统计信息(支持分页)
* @param {number} pageIndex - 页码从1开始
* @param {number} pageSize - 每页数量默认20
* @returns {Promise<{success: boolean, data: Array, total: number}>}
*/
export const getReasonGroups = (pageIndex = 1, pageSize = 20) => {
return request({
url: '/TransactionRecord/GetReasonGroups',
method: 'get',
params: { pageIndex, pageSize }
})
}
/**
* 按摘要批量更新分类
* @param {Object} data - 批量更新数据
* @param {string} data.reason - 交易摘要
* @param {number} data.type - 交易类型 (0:支出, 1:收入, 2:不计入收支)
* @param {string} data.classify - 分类名称
* @returns {Promise<{success: boolean, data: number, message: string}>}
*/
export const batchUpdateByReason = (data) => {
return request({
url: '/TransactionRecord/BatchUpdateByReason',
method: 'post',
data
})
}
/**
* NLP分析 - 根据用户自然语言输入查询交易记录并预设分类
* @param {string} userInput - 用户的自然语言输入
* @returns {Promise<{success: boolean, data: Object}>}
*/
export const nlpAnalysis = (userInput) => {
return request({
url: '/TransactionRecord/NlpAnalysis',
method: 'post',
data: { userInput }
})
}

View File

@@ -57,24 +57,43 @@
@click="showTypePicker = true"
:rules="[{ required: true, message: '请选择交易类型' }]"
/>
<van-field
v-model="editForm.classify"
is-link
readonly
name="classify"
label="交易分类"
placeholder="请选择或输入交易分类"
@click="openClassifyPicker"
/>
<van-field
v-model="editForm.subClassify"
is-link
readonly
name="subClassify"
label="交易子分类"
placeholder="请选择或输入交易子分类"
@click="showSubClassifyPicker = true"
/>
<van-field name="classify" label="交易分类">
<template #input>
<span v-if="!editForm.classify" style="color: #c8c9cc;">请选择交易分类</span>
<span v-else>{{ editForm.classify }}</span>
</template>
</van-field>
<!-- 分类按钮网格 -->
<div class="classify-buttons">
<van-button
v-for="item in classifyColumns"
:key="item.id"
:type="editForm.classify === item.text ? 'primary' : 'default'"
size="small"
class="classify-btn"
@click="selectClassify(item.text)"
>
{{ item.text }}
</van-button>
<van-button
type="success"
size="small"
class="classify-btn"
@click="showAddClassify = true"
>
+ 新增
</van-button>
<van-button
v-if="editForm.classify"
type="warning"
size="small"
class="classify-btn"
@click="clearClassify"
>
清空
</van-button>
</div>
</van-cell-group>
<div style="margin: 16px;">
@@ -96,42 +115,6 @@
/>
</van-popup>
<!-- 交易分类选择器 -->
<van-popup v-model:show="showClassifyPicker" position="bottom" round>
<van-picker
ref="classifyPickerRef"
:columns="classifyColumns"
@confirm="onClassifyConfirm"
@cancel="showClassifyPicker = false"
>
<template #toolbar>
<div class="picker-toolbar">
<van-button class="toolbar-cancel" size="small" @click="clearClassify">清空</van-button>
<van-button class="toolbar-add" size="small" type="primary" @click="showAddClassify = true">新增</van-button>
<van-button class="toolbar-confirm" size="small" type="primary" @click="confirmClassify">确认</van-button>
</div>
</template>
</van-picker>
</van-popup>
<!-- 交易子分类选择器 -->
<van-popup v-model:show="showSubClassifyPicker" position="bottom" round>
<van-picker
ref="subClassifyPickerRef"
:columns="subClassifyColumns"
@confirm="onSubClassifyConfirm"
@cancel="showSubClassifyPicker = false"
>
<template #toolbar>
<div class="picker-toolbar">
<van-button class="toolbar-cancel" size="small" @click="clearSubClassify">清空</van-button>
<van-button class="toolbar-add" size="small" type="primary" @click="showAddSubClassify = true">新增</van-button>
<van-button class="toolbar-confirm" size="small" type="primary" @click="confirmSubClassify">确认</van-button>
</div>
</template>
</van-picker>
</van-popup>
<!-- 新增分类对话框 -->
<van-dialog
v-model:show="showAddClassify"
@@ -141,23 +124,13 @@
>
<van-field v-model="newClassify" placeholder="请输入新的交易分类" />
</van-dialog>
<!-- 新增子分类对话框 -->
<van-dialog
v-model:show="showAddSubClassify"
title="新增交易子分类"
show-cancel-button
@confirm="addNewSubClassify"
>
<van-field v-model="newSubClassify" placeholder="请输入新的交易子分类" />
</van-dialog>
</template>
<script setup>
import { ref, reactive, watch, defineProps, defineEmits } from 'vue'
import { showToast } from 'vant'
import { updateTransaction } from '@/api/transactionRecord'
import { getCategoryTree, createCategory } from '@/api/transactionCategory'
import { getCategoryList, createCategory } from '@/api/transactionCategory'
const props = defineProps({
show: {
@@ -184,16 +157,9 @@ const typeColumns = [
// 分类相关
const classifyColumns = ref([])
const subClassifyColumns = ref([])
const showTypePicker = ref(false)
const showClassifyPicker = ref(false)
const showSubClassifyPicker = ref(false)
const showAddClassify = ref(false)
const showAddSubClassify = ref(false)
const newClassify = ref('')
const newSubClassify = ref('')
const classifyPickerRef = ref(null)
const subClassifyPickerRef = ref(null)
// 编辑表单
const editForm = reactive({
@@ -203,8 +169,7 @@ const editForm = reactive({
balance: '',
type: 0,
typeText: '',
classify: '',
subClassify: ''
classify: ''
})
// 监听props变化
@@ -222,7 +187,6 @@ watch(() => props.transaction, (newVal) => {
editForm.type = newVal.type
editForm.typeText = getTypeName(newVal.type)
editForm.classify = newVal.classify || ''
editForm.subClassify = newVal.subClassify || ''
// 根据交易类型加载分类
loadClassifyList(newVal.type)
@@ -235,9 +199,8 @@ watch(visible, (newVal) => {
// 监听交易类型变化,重新加载分类
watch(() => editForm.type, (newVal) => {
// 清空已选的分类和子分类
// 清空已选的分类
editForm.classify = ''
editForm.subClassify = ''
// 重新加载对应类型的分类列表
loadClassifyList(newVal)
})
@@ -246,17 +209,15 @@ const handleVisibleChange = (newVal) => {
emit('update:show', newVal)
}
// 加载分类列表(从分类树中提取)
// 加载分类列表
const loadClassifyList = async (type = null) => {
try {
const response = await getCategoryTree(type)
const response = await getCategoryList(type)
if (response.success) {
// 从树形结构中提取分类名称Level 2
classifyColumns.value = (response.data || []).map(item => ({
text: item.name,
value: item.name,
id: item.id,
children: item.children || []
id: item.id
}))
}
} catch (error) {
@@ -264,25 +225,6 @@ const loadClassifyList = async (type = null) => {
}
}
// 加载子分类列表(根据选中的分类)
const loadSubClassifyList = async (classifyName) => {
try {
// 从已加载的分类树中查找对应的子分类
const classifyItem = classifyColumns.value.find(item => item.value === classifyName)
if (classifyItem && classifyItem.children) {
subClassifyColumns.value = classifyItem.children.map(child => ({
text: child.name,
value: child.name,
id: child.id
}))
} else {
subClassifyColumns.value = []
}
} catch (error) {
console.error('加载子分类列表出错:', error)
}
}
// 提交编辑
const onSubmit = async () => {
try {
@@ -294,8 +236,7 @@ const onSubmit = async () => {
amount: parseFloat(editForm.amount),
balance: parseFloat(editForm.balance),
type: editForm.type,
classify: editForm.classify,
subClassify: editForm.subClassify
classify: editForm.classify
}
const response = await updateTransaction(data)
@@ -316,11 +257,9 @@ const onSubmit = async () => {
}
}
// 打开分类选择器
const openClassifyPicker = async () => {
// 先根据当前交易类型加载分类
await loadClassifyList(editForm.type)
showClassifyPicker.value = true
// 选择分类
const selectClassify = (classify) => {
editForm.classify = classify
}
// 交易类型选择确认
@@ -330,24 +269,6 @@ const onTypeConfirm = ({ selectedValues, selectedOptions }) => {
showTypePicker.value = false
}
// 交易分类选择确认
const onClassifyConfirm = async ({ selectedOptions }) => {
if (selectedOptions && selectedOptions[0]) {
editForm.classify = selectedOptions[0].text
// 加载对应的子分类
await loadSubClassifyList(selectedOptions[0].value)
}
showClassifyPicker.value = false
}
// 交易子分类选择确认
const onSubClassifyConfirm = ({ selectedOptions }) => {
if (selectedOptions && selectedOptions[0]) {
editForm.subClassify = selectedOptions[0].text
}
showSubClassifyPicker.value = false
}
// 新增分类
const addNewClassify = async () => {
if (!newClassify.value.trim()) {
@@ -361,10 +282,7 @@ const addNewClassify = async () => {
// 调用API创建分类
const response = await createCategory({
name: categoryName,
parentId: 0,
type: editForm.type,
level: 2,
sortOrder: 0
type: editForm.type
})
if (response.success) {
@@ -381,95 +299,15 @@ const addNewClassify = async () => {
} finally {
newClassify.value = ''
showAddClassify.value = false
showClassifyPicker.value = false
}
}
// 新增子分类
const addNewSubClassify = async () => {
if (!newSubClassify.value.trim()) {
showToast('请输入子分类名称')
return
}
if (!editForm.classify) {
showToast('请先选择分类')
return
}
try {
const subCategoryName = newSubClassify.value.trim()
// 找到父分类的ID
const parentCategory = classifyColumns.value.find(c => c.value === editForm.classify)
if (!parentCategory || !parentCategory.id) {
showToast('未找到父分类信息')
return
}
// 调用API创建子分类
const response = await createCategory({
name: subCategoryName,
parentId: parentCategory.id,
type: editForm.type,
level: 3,
sortOrder: 0
})
if (response.success) {
showToast('子分类创建成功')
// 重新加载子分类列表
await loadSubClassifyList(editForm.classify)
editForm.subClassify = subCategoryName
} else {
showToast(response.message || '创建子分类失败')
}
} catch (error) {
console.error('创建子分类出错:', error)
showToast('创建子分类失败')
} finally {
newSubClassify.value = ''
showAddSubClassify.value = false
showSubClassifyPicker.value = false
}
}
// 清空分类
const clearClassify = () => {
editForm.classify = ''
showClassifyPicker.value = false
showToast('已清空分类')
}
// 清空子分类
const clearSubClassify = () => {
editForm.subClassify = ''
showSubClassifyPicker.value = false
showToast('已清空子分类')
}
// 确认分类(从 picker 中获取选中值)
const confirmClassify = () => {
if (classifyPickerRef.value) {
const selectedValues = classifyPickerRef.value.getSelectedOptions()
if (selectedValues && selectedValues[0]) {
editForm.classify = selectedValues[0].text
}
}
showClassifyPicker.value = false
}
// 确认子分类(从 picker 中获取选中值)
const confirmSubClassify = () => {
if (subClassifyPickerRef.value) {
const selectedValues = subClassifyPickerRef.value.getSelectedOptions()
if (selectedValues && selectedValues[0]) {
editForm.subClassify = selectedValues[0].text
}
}
showSubClassifyPicker.value = false
}
// 获取交易类型名称
const getTypeName = (type) => {
const typeMap = {
@@ -503,19 +341,16 @@ const formatDate = (dateString) => {
margin: 10px 0;
}
.picker-toolbar {
.classify-buttons {
display: flex;
width: 100%;
align-items: center;
padding: 5px 10px;
border-bottom: 1px solid #ebedf0;
flex-wrap: wrap;
gap: 8px;
padding: 12px 16px;
}
.toolbar-cancel {
margin-right: auto;
}
.toolbar-confirm {
margin-left: auto;
.classify-btn {
flex: 0 0 auto;
min-width: 70px;
border-radius: 16px;
}
</style>

View File

@@ -11,47 +11,74 @@
v-for="transaction in transactions"
:key="transaction.id"
>
<div
class="transaction-card"
@click="handleClick(transaction)"
>
<div class="card-left">
<div class="transaction-title">
<span class="reason">{{ transaction.reason || '(无摘要)' }}</span>
<div class="transaction-row">
<van-checkbox
v-if="showCheckbox"
:model-value="isSelected(transaction.id)"
@update:model-value="toggleSelection(transaction)"
class="checkbox-col"
/>
<div
class="transaction-card"
@click="handleClick(transaction)"
>
<div class="card-left">
<div class="transaction-title">
<span class="reason">{{ transaction.reason || '(无摘要)' }}</span>
</div>
<div class="transaction-info">
<div>交易时间: {{ formatDate(transaction.occurredAt) }}</div>
<div>
<span v-if="transaction.classify">
分类: {{ transaction.classify }}
</span>
<span v-if="transaction.upsetedClassify && transaction.upsetedClassify !== transaction.classify" style="color: #ff976a">
{{ transaction.upsetedClassify }}
</span>
</div>
<div v-if="transaction.card">
卡号: {{ transaction.card }}
</div>
<div v-if="transaction.importFrom">
来源: {{ transaction.importFrom }}
</div>
</div>
</div>
<div class="card-middle">
<van-tag
:type="getTypeTagType(transaction.type)"
size="medium"
>
{{ getTypeName(transaction.type) }}
</van-tag>
<template
v-if="Number.isFinite(transaction.upsetedType) && transaction.upsetedType !== transaction.type"
>
<van-tag
:type="getTypeTagType(transaction.upsetedType)"
size="medium"
>
{{ getTypeName(transaction.upsetedType) }}
</van-tag>
</template>
</div>
<div class="transaction-info">
<div>交易时间: {{ formatDate(transaction.occurredAt) }}</div>
<div v-if="transaction.classify">分类: {{ transaction.classify }}
<span v-if="transaction.subClassify">/ {{ transaction.subClassify }}</span>
</div>
<div v-if="transaction.card">
卡号: {{ transaction.card }}
</div>
<div v-if="transaction.importFrom">
来源: {{ transaction.importFrom }}
<div class="card-right">
<div class="transaction-amount">
<div :class="['amount', getAmountClass(transaction.type)]">
{{ formatAmount(transaction.amount, transaction.type) }}
</div>
<div class="balance" v-if="transaction.balance && transaction.balance > 0">
余额: {{ formatMoney(transaction.balance) }}
</div>
<div class="balance" v-if="transaction.refundAmount && transaction.refundAmount > 0">
退款: {{ formatMoney(transaction.refundAmount) }}
</div>
</div>
<van-icon name="arrow" size="16" color="#c8c9cc" />
</div>
</div>
<div class="card-right">
<div class="transaction-amount">
<div :class="['amount', getAmountClass(transaction.type)]">
{{ formatAmount(transaction.amount, transaction.type) }}
</div>
<div class="balance" v-if="transaction.balance && transaction.balance > 0">
余额: {{ formatMoney(transaction.balance) }}
</div>
<div class="balance" v-if="transaction.refundAmount && transaction.refundAmount > 0">
退款: {{ formatMoney(transaction.refundAmount) }}
</div>
</div>
<van-icon name="arrow" size="16" color="#c8c9cc" />
</div>
</div>
<template #right v-if="showDelete">
<van-button
@@ -76,7 +103,7 @@
<script setup>
import { defineEmits } from 'vue'
defineProps({
const props = defineProps({
transactions: {
type: Array,
default: () => []
@@ -92,10 +119,18 @@ defineProps({
showDelete: {
type: Boolean,
default: true
},
showCheckbox: {
type: Boolean,
default: false
},
selectedIds: {
type: Set,
default: () => new Set()
}
})
const emit = defineEmits(['load', 'click', 'delete'])
const emit = defineEmits(['load', 'click', 'delete', 'update:selectedIds'])
const onLoad = () => {
emit('load')
@@ -109,6 +144,20 @@ const handleDeleteClick = (transaction) => {
emit('delete', transaction)
}
const isSelected = (id) => {
return props.selectedIds.has(id)
}
const toggleSelection = (transaction) => {
const newSelectedIds = new Set(props.selectedIds)
if (newSelectedIds.has(transaction.id)) {
newSelectedIds.delete(transaction.id)
} else {
newSelectedIds.add(transaction.id)
}
emit('update:selectedIds', newSelectedIds)
}
// 获取交易类型名称
const getTypeName = (type) => {
const typeMap = {
@@ -168,6 +217,18 @@ const formatDate = (dateString) => {
width: 100%;
}
.transaction-row {
display: flex;
align-items: center;
width: 100%;
overflow: hidden;
}
.checkbox-col {
padding: 12px 8px;
flex-shrink: 0;
}
.transaction-card {
display: flex;
justify-content: space-between;
@@ -175,12 +236,27 @@ const formatDate = (dateString) => {
padding: 12px 16px;
cursor: pointer;
transition: background-color 0.3s;
flex: 1;
min-width: 0;
overflow: hidden;
position: relative;
}
.card-left {
flex: 1;
min-width: 0;
padding-right: 12px;
overflow: hidden;
}
.card-middle {
position: absolute;
top: 12px;
right: 20px;
display: flex;
align-items: center;
gap: 8px;
z-index: 1;
}
.card-right {
@@ -191,14 +267,13 @@ const formatDate = (dateString) => {
}
.transaction-title {
display: flex;
align-items: center;
font-weight: bold;
margin-bottom: 8px;
gap: 8px;
overflow: hidden;
}
.reason {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -212,6 +287,14 @@ const formatDate = (dateString) => {
line-height: 1.6;
}
.original-info {
color: #ff976a;
font-style: italic;
display: flex;
align-items: center;
gap: 4px;
}
.transaction-amount {
text-align: right;
display: flex;
@@ -235,10 +318,6 @@ const formatDate = (dateString) => {
color: #07c160;
}
.amount.neutral {
color: #646566;
}
.balance {
font-size: 12px;
color: #969799;

View File

@@ -37,7 +37,25 @@ const router = createRouter({
{
path: '/smart-classification',
name: 'smart-classification',
component: () => import('../views/SmartClassification.vue'),
component: () => import('../views/ClassificationSmart.vue'),
meta: { requiresAuth: true },
},
{
path: '/classification-edit',
name: 'classification-edit',
component: () => import('../views/ClassificationEdit.vue'),
meta: { requiresAuth: true },
},
{
path: '/classification-batch',
name: 'classification-batch',
component: () => import('../views/ClassificationBatch.vue'),
meta: { requiresAuth: true },
},
{
path: '/classification-nlp',
name: 'classification-nlp',
component: () => import('../views/ClassificationNLP.vue'),
meta: { requiresAuth: true },
}
],

View File

@@ -1,190 +1,211 @@
<template>
<div class="calendar-container">
<van-calendar title="日历"
:poppable="false"
:show-confirm="false"
:formatter="formatterCalendar"
<van-calendar
title="日历"
:poppable="false"
:show-confirm="false"
:formatter="formatterCalendar"
:min-date="minDate"
:max-date="maxDate"
@month-show="onMonthShow"
@select="onDateSelect" />
:max-date="maxDate"
@month-show="onMonthShow"
@select="onDateSelect"
/>
<!-- 日期交易列表弹出层 -->
<van-popup v-model:show="listVisible" position="bottom" :style="{ height: '85%' }" round closeable>
<van-popup
v-model:show="listVisible"
position="bottom"
:style="{ height: '85%' }"
round
closeable
>
<div class="date-transactions">
<div class="popup-header">
<h3>{{ selectedDateText }}</h3>
<p v-if="dateTransactions.length"> {{ dateTransactions.length }} 笔交易</p>
</div>
<TransactionList :transactions="dateTransactions" :loading="listLoading" :finished="true" :show-delete="false"
@click="viewDetail" />
<TransactionList
:transactions="dateTransactions"
:loading="listLoading"
:finished="true"
:show-delete="false"
@click="viewDetail"
/>
</div>
</van-popup>
<!-- 交易详情组件 -->
<TransactionDetail v-model:show="detailVisible" :transaction="currentTransaction" @save="onDetailSave" />
<TransactionDetail
v-model:show="detailVisible"
:transaction="currentTransaction"
@save="onDetailSave"
/>
</div>
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { showToast } from 'vant'
import request from '@/api/request'
import { getTransactionDetail, getTransactionsByDate } from '@/api/transactionRecord'
import TransactionList from '@/components/TransactionList.vue'
import TransactionDetail from '@/components/TransactionDetail.vue'
import { ref, onMounted, nextTick } from "vue";
import { showToast } from "vant";
import request from "@/api/request";
import { getTransactionDetail, getTransactionsByDate } from "@/api/transactionRecord";
import TransactionList from "@/components/TransactionList.vue";
import TransactionDetail from "@/components/TransactionDetail.vue";
const dailyStatistics = ref({})
const listVisible = ref(false)
const detailVisible = ref(false)
const dateTransactions = ref([])
const currentTransaction = ref(null)
const listLoading = ref(false)
const selectedDate = ref(null)
const selectedDateText = ref('')
const dailyStatistics = ref({});
const listVisible = ref(false);
const detailVisible = ref(false);
const dateTransactions = ref([]);
const currentTransaction = ref(null);
const listLoading = ref(false);
const selectedDate = ref(null);
const selectedDateText = ref("");
// 设置日历可选范围例如过去2年到未来1年
const minDate = new Date(new Date().getFullYear() - 2, 0, 1) // 2年前的1月1日
const maxDate = new Date(new Date().getFullYear() + 1, 11, 31) // 明年12月31日
const minDate = new Date(new Date().getFullYear() - 2, 0, 1); // 2年前的1月1日
const maxDate = new Date(new Date().getFullYear() + 1, 11, 31); // 明年12月31日
onMounted(async () => {
await nextTick()
await nextTick();
setTimeout(() => {
// 计算页面高度滚动3/4高度以显示更多日期
const height = document.querySelector('.calendar-container').clientHeight * 0.45
document
.querySelector('.van-calendar__body')
.scrollBy({
top: -height,
behavior: 'smooth'
})
const height = document.querySelector(".calendar-container").clientHeight * 0.45;
document.querySelector(".van-calendar__body").scrollBy({
top: -height,
behavior: "smooth",
});
}, 300);
})
});
// 获取日历统计数据
const fetchDailyStatistics = async (year, month) => {
try {
const response = await request.get('/TransactionRecord/GetDailyStatistics', {
params: { year, month }
})
const response = await request.get("/TransactionRecord/GetDailyStatistics", {
params: { year, month },
});
if (response.success && response.data) {
// 将数组转换为对象key为日期
const statsMap = {}
response.data.forEach(item => {
const statsMap = {};
response.data.forEach((item) => {
statsMap[item.date] = {
count: item.count,
amount: item.amount
}
})
amount: item.amount,
};
});
dailyStatistics.value = {
...dailyStatistics.value,
...statsMap
}
...statsMap,
};
}
} catch (error) {
console.error('获取日历统计数据失败:', error)
console.error("获取日历统计数据失败:", error);
}
}
};
// 获取指定日期的交易列表
const fetchDateTransactions = async (date) => {
try {
listLoading.value = true
const dateStr = date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-')
listLoading.value = true;
const dateStr = date
.toLocaleString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" })
.replace(/\//g, "-");
const response = await getTransactionsByDate(dateStr)
const response = await getTransactionsByDate(dateStr);
if (response.success && response.data) {
dateTransactions.value = response.data
// 根据金额从大到小排序
dateTransactions.value = response
.data
.sort((a, b) => b.amount - a.amount);
} else {
dateTransactions.value = []
showToast(response.message || '获取交易列表失败')
dateTransactions.value = [];
showToast(response.message || "获取交易列表失败");
}
} catch (error) {
console.error('获取日期交易列表失败:', error)
dateTransactions.value = []
showToast('获取交易列表失败')
console.error("获取日期交易列表失败:", error);
dateTransactions.value = [];
showToast("获取交易列表失败");
} finally {
listLoading.value = false
listLoading.value = false;
}
}
};
// 当月份显示时触发
const onMonthShow = ({ date }) => {
const year = date.getFullYear()
const month = date.getMonth() + 1
fetchDailyStatistics(year, month)
}
const year = date.getFullYear();
const month = date.getMonth() + 1;
fetchDailyStatistics(year, month);
};
// 日期选择事件
const onDateSelect = (date) => {
selectedDate.value = date
selectedDateText.value = formatSelectedDate(date)
fetchDateTransactions(date)
listVisible.value = true
}
selectedDate.value = date;
selectedDateText.value = formatSelectedDate(date);
fetchDateTransactions(date);
listVisible.value = true;
};
// 格式化选中的日期
const formatSelectedDate = (date) => {
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long'
})
}
return date.toLocaleDateString("zh-CN", {
year: "numeric",
month: "long",
day: "numeric",
weekday: "long",
});
};
// 查看详情
const viewDetail = async (transaction) => {
try {
const response = await getTransactionDetail(transaction.id)
const response = await getTransactionDetail(transaction.id);
if (response.success) {
currentTransaction.value = response.data
detailVisible.value = true
currentTransaction.value = response.data;
detailVisible.value = true;
} else {
showToast(response.message || '获取详情失败')
showToast(response.message || "获取详情失败");
}
} catch (error) {
console.error('获取详情出错:', error)
showToast('获取详情失败')
console.error("获取详情出错:", error);
showToast("获取详情失败");
}
}
};
// 详情保存后的回调
const onDetailSave = () => {
// 重新加载当前日期的交易列表
if (selectedDate.value) {
fetchDateTransactions(selectedDate.value)
fetchDateTransactions(selectedDate.value);
}
// 重新加载当前月份的统计数据
const now = selectedDate.value || new Date()
fetchDailyStatistics(now.getFullYear(), now.getMonth() + 1)
}
const now = selectedDate.value || new Date();
fetchDailyStatistics(now.getFullYear(), now.getMonth() + 1);
};
const formatterCalendar = (day) => {
const dayCopy = { ...day };
if (dayCopy.date.toDateString() === new Date().toDateString()) {
dayCopy.text = '今天';
dayCopy.text = "今天";
}
// 格式化日期为 yyyy-MM-dd
const dateKey = dayCopy.date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-');
const stats = dailyStatistics.value[dateKey]
const dateKey = dayCopy.date
.toLocaleString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" })
.replace(/\//g, "-");
const stats = dailyStatistics.value[dateKey];
if (stats) {
dayCopy.topInfo = `${stats.count}` // 展示消费笔数
dayCopy.bottomInfo = `${stats.amount.toFixed(1)}` // 展示消费金额
dayCopy.topInfo = `${stats.count}`; // 展示消费笔数
dayCopy.bottomInfo = `${stats.amount.toFixed(1)}`; // 展示消费金额
}
return dayCopy;
};
// 初始加载当前月份数据
const now = new Date()
fetchDailyStatistics(now.getFullYear(), now.getMonth() + 1)
const now = new Date();
fetchDailyStatistics(now.getFullYear(), now.getMonth() + 1);
</script>
<style scoped>
@@ -238,4 +259,4 @@ fetchDailyStatistics(now.getFullYear(), now.getMonth() + 1)
font-size: 14px;
color: #969799;
}
</style>
</style>

View File

@@ -0,0 +1,515 @@
<template>
<div style="padding-bottom: calc(60px + env(safe-area-inset-bottom, 0px));">
<van-nav-bar
title="批量分类"
left-text="返回"
left-arrow
@click-left="handleBack"
placeholder
/>
<!-- 未分类账单统计 -->
<div class="unclassified-stat">
<span>未分类账单数: {{ unclassifiedCount }}</span>
</div>
<!-- 分组列表 -->
<div>
<van-empty v-if="reasonGroups.length === 0 && !listLoading && finished" description="暂无数据" />
<van-list
v-model:loading="listLoading"
v-model:error="error"
:finished="finished"
finished-text="没有更多了"
error-text="请求失败点击重新加载"
@load="onLoad"
>
<van-cell-group inset>
<van-cell
v-for="group in reasonGroups"
:key="group.reason"
clickable
@click="handleSelectGroup(group)"
>
<template #title>
<div class="group-title">
{{ group.reason }}
</div>
</template>
<template #label>
<div class="group-info">
<van-tag
:type="getTypeColor(group.sampleType)"
size="medium"
style="margin-right: 8px;"
>
{{ getTypeName(group.sampleType) }}
</van-tag>
<van-tag
v-if="group.sampleClassify"
type="primary"
size="medium"
style="margin-right: 8px;"
>
{{ group.sampleClassify }}
</van-tag>
<span class="count-text">{{ group.count }} 条记录</span>
</div>
</template>
<template #right-icon>
<van-icon name="arrow" />
</template>
</van-cell>
</van-cell-group>
</van-list>
</div>
<!-- 批量设置对话框 -->
<van-dialog
v-model:show="showSettingDialog"
title="批量设置分类"
:show-cancel-button="true"
@confirm="handleConfirmUpdate"
@cancel="resetForm"
>
<van-form ref="formRef" class="setting-form">
<van-cell-group inset>
<!-- 显示选中的摘要 -->
<van-field
:model-value="selectedGroup?.reason"
label="交易摘要"
readonly
input-align="left"
/>
<!-- 显示记录数量 -->
<van-field
:model-value="`${selectedGroup?.count || 0} `"
label="记录数量"
readonly
input-align="left"
/>
<!-- 交易类型选择 -->
<van-field
v-model="form.typeName"
is-link
readonly
name="type"
label="交易类型"
placeholder="请选择交易类型"
@click="showTypePicker = true"
:rules="[{ required: true, message: '请选择交易类型' }]"
/>
<!-- 分类选择 -->
<van-field name="classify" label="分类">
<template #input>
<span v-if="!form.classify" style="opacity: 0.4;">请选择分类</span>
<span v-else>{{ form.classify }}</span>
</template>
</van-field>
<!-- 分类按钮网格 -->
<div class="classify-buttons">
<van-button
v-for="item in classifyOptions"
:key="item.id"
:type="form.classify === item.text ? 'primary' : 'default'"
size="small"
class="classify-btn"
@click="selectClassify(item.text)"
>
{{ item.text }}
</van-button>
<van-button
type="success"
size="small"
class="classify-btn"
@click="showAddClassify = true"
>
+ 新增
</van-button>
<van-button
v-if="form.classify"
type="warning"
size="small"
class="classify-btn"
@click="clearClassify"
>
清空
</van-button>
</div>
</van-cell-group>
</van-form>
</van-dialog>
<!-- 交易类型选择器 -->
<van-popup v-model:show="showTypePicker" position="bottom" round>
<van-picker
show-toolbar
:columns="typeOptions"
@confirm="handleConfirmType"
@cancel="showTypePicker = false"
/>
</van-popup>
<!-- 新增分类对话框 -->
<van-dialog
v-model:show="showAddClassify"
title="新增交易分类"
show-cancel-button
@confirm="addNewClassify"
>
<van-field v-model="newClassify" placeholder="请输入新的交易分类" />
</van-dialog>
</div>
</template>
<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
showSuccessToast,
showToast,
showLoadingToast,
closeToast,
showConfirmDialog
} from 'vant'
import { getReasonGroups, batchUpdateByReason, getUnclassifiedCount } from '@/api/transactionRecord'
import { getCategoryList, createCategory } from '@/api/transactionCategory'
const router = useRouter()
// 交易类型选项
const typeOptions = [
{ text: '支出', value: 0 },
{ text: '收入', value: 1 },
{ text: '不计收支', value: 2 }
]
// 数据状态
const listLoading = ref(false)
const error = ref(false)
const finished = ref(false)
const reasonGroups = ref([])
const categories = ref([])
const pageIndex = ref(1)
const pageSize = 20
const unclassifiedCount = ref(0)
const total = ref(0)
// 对话框状态
const showSettingDialog = ref(false)
const showTypePicker = ref(false)
const showAddClassify = ref(false)
// 表单状态
const formRef = ref(null)
const selectedGroup = ref(null)
const newClassify = ref('')
const form = ref({
type: null,
typeName: '',
classify: ''
})
// 根据选中的类型过滤分类选项
const classifyOptions = computed(() => {
if (form.value.type === null) return []
return categories.value
.filter(c => c.type === form.value.type)
.map(c => ({ text: c.name, value: c.name, id: c.id }))
})
// 监听交易类型变化,重新加载分类
watch(() => form.value.type, (newVal) => {
// 清空已选的分类
form.value.classify = ''
// 重新加载对应类型的分类列表
loadCategories(newVal)
})
// 获取类型名称
const getTypeName = (type) => {
const typeMap = {
0: '支出',
1: '收入',
2: '不计收支'
}
return typeMap[type] || '未知'
}
// 获取类型对应的标签颜色
const getTypeColor = (type) => {
const colorMap = {
0: 'danger', // 支出 - 红色
1: 'success', // 收入 - 绿色
2: 'default' // 不计收支 - 灰色
}
return colorMap[type] || 'default'
}
// 获取分组数据
const loadReasonGroups = async () => {
try {
const res = await getReasonGroups(pageIndex.value, pageSize)
if (res.success) {
const newData = res.data || []
reasonGroups.value = [...reasonGroups.value, ...newData]
total.value = res.total || 0
// 判断是否还有更多数据
if (reasonGroups.value.length >= total.value) {
finished.value = true
}
// 加载成功后,页码+1为下次加载做准备
pageIndex.value++
error.value = false
} else {
error.value = true
showToast(res.message || '获取分组数据失败')
}
} catch (err) {
console.error('获取分组数据失败:', err)
error.value = true
showToast('获取分组数据失败')
}
}
// 获取未分类账单统计
const loadUnclassifiedCount = async () => {
try {
const res = await getUnclassifiedCount()
if (res.success) {
unclassifiedCount.value = res.data || 0
}
} catch (error) {
console.error('获取未分类账单数量失败:', error)
}
}
// 加载更多
const onLoad = async () => {
await loadReasonGroups()
// 首次加载时获取统计信息
if (pageIndex.value === 2) {
await loadUnclassifiedCount()
}
listLoading.value = false
}
// 获取所有分类
const loadCategories = async (type = null) => {
try {
const res = await getCategoryList(type)
if (res.success) {
categories.value = res.data || []
}
} catch (error) {
console.error('获取分类列表失败:', error)
}
}
// 选择分组
const handleSelectGroup = (group) => {
selectedGroup.value = group
form.value = {
type: group.sampleType,
typeName: getTypeName(group.sampleType),
classify: group.sampleClassify
}
// 加载对应类型的分类列表
loadCategories(group.sampleType)
showSettingDialog.value = true
}
// 选择分类
const selectClassify = (classify) => {
form.value.classify = classify
}
// 确认选择交易类型
const handleConfirmType = ({ selectedOptions }) => {
form.value.type = selectedOptions[0].value
form.value.typeName = selectedOptions[0].text
showTypePicker.value = false
}
// 新增分类
const addNewClassify = async () => {
if (!newClassify.value.trim()) {
showToast('请输入分类名称')
return
}
if (form.value.type === null) {
showToast('请先选择交易类型')
return
}
try {
const categoryName = newClassify.value.trim()
// 调用API创建分类
const response = await createCategory({
name: categoryName,
type: form.value.type
})
if (response.success) {
showToast('分类创建成功')
// 重新加载分类列表
await loadCategories(form.value.type)
form.value.classify = categoryName
} else {
showToast(response.message || '创建分类失败')
}
} catch (error) {
console.error('创建分类出错:', error)
showToast('创建分类失败')
} finally {
newClassify.value = ''
showAddClassify.value = false
}
}
// 清空分类
const clearClassify = () => {
form.value.classify = ''
showToast('已清空分类')
}
// 确认批量更新
const handleConfirmUpdate = async () => {
try {
// 表单验证
await formRef.value?.validate()
// 二次确认
await showConfirmDialog({
title: '确认批量设置',
message: `确定要将「${selectedGroup.value.reason}」的 ${selectedGroup.value.count} 条记录设置为「${form.value.typeName} - ${form.value.classify}」吗?`
})
showLoadingToast({
message: '更新中...',
forbidClick: true,
duration: 0
})
const res = await batchUpdateByReason({
reason: selectedGroup.value.reason,
type: form.value.type,
classify: form.value.classify
})
closeToast()
if (res.success) {
showSuccessToast(res.message || `成功更新 ${res.data} 条记录`)
showSettingDialog.value = false
resetForm()
// 重新加载数据
reasonGroups.value = []
pageIndex.value = 1
finished.value = false
listLoading.value = true
await loadReasonGroups()
await loadUnclassifiedCount()
listLoading.value = false
} else {
showToast(res.message || '批量更新失败')
}
} catch (error) {
closeToast()
if (error !== 'cancel') {
console.error('批量更新失败:', error)
showToast(error.message || '批量更新失败')
}
}
}
// 重置表单
const resetForm = () => {
selectedGroup.value = null
form.value = {
type: null,
typeName: '',
classify: ''
}
formRef.value?.resetValidation()
}
// 返回上一页
const handleBack = () => {
router.back()
}
// 页面加载
onMounted(() => {
// onLoad 会自动触发首次加载
})
</script>
<style scoped>
.loading-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 200px;
}
.group-title {
font-size: 15px;
font-weight: 500;
margin-bottom: 4px;
}
.group-info {
align-items: center;
margin-top: 4px;
}
.count-text {
font-size: 13px;
opacity: 0.6;
}
.unclassified-stat {
padding-left: 16px;
padding-top: 12px;
font-size: 14px;
font-weight: 500;
opacity: 0.83px;
opacity: 0.6;
}
.setting-form {
padding: 16px 0;
}
.classify-buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 12px 16px;
max-height: 300px;
overflow-y: auto;
}
.classify-btn {
flex: 0 0 auto;
min-width: 70px;
border-radius: 16px;
}
:deep(.van-cell-group--inset) {
margin: 16px;
}
</style>

View File

@@ -0,0 +1,338 @@
<template>
<div
style="padding-bottom: calc(60px + env(safe-area-inset-bottom, 0px));"
>
<van-nav-bar
:title="navTitle"
left-text="返回"
left-arrow
@click-left="handleBack"
placeholder
/>
<!-- 第一层选择交易类型 -->
<div v-if="currentLevel === 0" class="level-container">
<van-cell-group inset>
<van-cell
v-for="type in typeOptions"
:key="type.value"
:title="type.label"
is-link
@click="handleSelectType(type.value)"
/>
</van-cell-group>
</div>
<!-- 第二层分类列表 -->
<div v-else class="level-container">
<!-- 面包屑导航 -->
<div class="breadcrumb">
<van-tag
type="primary"
closeable
@close="handleBackToRoot"
style="margin-left: 16px;"
>
{{ currentTypeName }}
</van-tag>
</div>
<!-- 分类列表 -->
<van-empty v-if="categories.length === 0" description="暂无分类" />
<van-cell-group v-else inset>
<van-swipe-cell v-for="category in categories" :key="category.id">
<van-cell :title="category.name" />
<template #right>
<van-button
square
type="danger"
text="删除"
@click="handleDelete(category)"
/>
</template>
</van-swipe-cell>
</van-cell-group>
<!-- 新增分类按钮 -->
<div class="add-button-container">
<van-button
type="primary"
size="large"
block
@click="handleAddCategory"
>
新增分类
</van-button>
</div>
</div>
<!-- 新增分类对话框 -->
<van-dialog
v-model:show="showAddDialog"
title="新增分类"
@confirm="handleConfirmAdd"
@cancel="resetAddForm"
>
<van-form ref="addFormRef">
<van-field
v-model="addForm.name"
name="name"
label="分类名称"
placeholder="请输入分类名称"
:rules="[{ required: true, message: '请输入分类名称' }]"
/>
</van-form>
</van-dialog>
<!-- 删除确认对话框 -->
<van-dialog
v-model:show="showDeleteConfirm"
title="删除分类"
message="删除后无法恢复,确定要删除吗?"
@confirm="handleConfirmDelete"
/>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
showSuccessToast,
showToast,
showLoadingToast,
closeToast
} from 'vant'
import {
getCategoryList,
createCategory,
deleteCategory
} from '@/api/transactionCategory'
const router = useRouter()
// 交易类型选项
const typeOptions = [
{ value: 0, label: '支出' },
{ value: 1, label: '收入' },
{ value: 2, label: '不计收支' }
]
// 层级状态
const currentLevel = ref(0) // 0=类型选择, 1=分类管理
const currentType = ref(null) // 当前选中的交易类型
const currentTypeName = computed(() => {
const type = typeOptions.find(t => t.value === currentType.value)
return type ? type.label : ''
})
// 分类数据
const categories = ref([])
// 编辑对话框
const showAddDialog = ref(false)
const addFormRef = ref(null)
const addForm = ref({
name: ''
})
// 删除确认
const showDeleteConfirm = ref(false)
const deleteTarget = ref(null)
// 计算导航栏标题
const navTitle = computed(() => {
if (currentLevel.value === 0) {
return '编辑分类'
}
return currentTypeName.value
})
/**
* 选择交易类型,进入分类管理
*/
const handleSelectType = async (type) => {
currentType.value = type
currentLevel.value = 1
await loadCategories()
}
/**
* 加载分类列表
*/
const loadCategories = async () => {
try {
showLoadingToast({
message: '加载中...',
forbidClick: true,
duration: 0
})
const { success, data } = await getCategoryList(currentType.value)
if (success) {
categories.value = data || []
} else {
showToast('加载分类失败')
}
} catch (error) {
console.error('加载分类错误:', error)
showToast('加载分类失败: ' + (error.message || '未知错误'))
} finally {
closeToast()
}
}
/**
* 返回上一级
*/
const handleBack = () => {
if (currentLevel.value === 1) {
currentLevel.value = 0
currentType.value = null
categories.value = []
} else {
router.back()
}
}
/**
* 返回到根目录(类型选择)
*/
const handleBackToRoot = () => {
currentLevel.value = 0
currentType.value = null
categories.value = []
}
/**
* 新增分类
*/
const handleAddCategory = () => {
addForm.value = {
name: ''
}
showAddDialog.value = true
}
/**
* 确认新增
*/
const handleConfirmAdd = async () => {
try {
// 表单验证
await addFormRef.value?.validate()
showLoadingToast({
message: '创建中...',
forbidClick: true,
duration: 0
})
const { success, message } = await createCategory({
name: addForm.value.name,
type: currentType.value
})
if (success) {
showSuccessToast('创建成功')
showAddDialog.value = false
resetAddForm()
await loadCategories()
} else {
showToast(message || '创建失败')
}
} catch (error) {
console.error('创建失败:', error)
showToast('创建失败: ' + (error.message || '未知错误'))
} finally {
closeToast()
}
}
/**
* 删除分类
*/
const handleDelete = async (category) => {
deleteTarget.value = category
showDeleteConfirm.value = true
}
/**
* 确认删除
*/
const handleConfirmDelete = async () => {
if (!deleteTarget.value) return
try {
showLoadingToast({
message: '删除中...',
forbidClick: true,
duration: 0
})
const { success, message } = await deleteCategory(deleteTarget.value.id)
if (success) {
showSuccessToast('删除成功')
showDeleteConfirm.value = false
deleteTarget.value = null
await loadCategories()
} else {
showToast(message || '删除失败')
}
} catch (error) {
console.error('删除失败:', error)
showToast('删除失败: ' + (error.message || '未知错误'))
} finally {
closeToast()
}
}
/**
* 重置新增表单
*/
const resetAddForm = () => {
addForm.value = {
name: ''
}
}
onMounted(() => {
// 初始化时显示类型选择
currentLevel.value = 0
})
</script>
<style scoped>
.level-container {
padding-top: 16px;
min-height: calc(100vh - 50px);
}
.breadcrumb {
margin-bottom: 16px;
padding: 8px 0;
}
.breadcrumb .van-tag {
cursor: pointer;
}
/* 新增按钮 */
.add-button-container {
position: fixed;
bottom: calc(60px + env(safe-area-inset-bottom, 0px));
left: 16px;
right: 16px;
z-index: 10;
}
/* 深色模式 */
@media (prefers-color-scheme: dark) {
.level-container {
background: #1a1a1a;
}
}
</style>

View File

@@ -0,0 +1,371 @@
<template>
<div class="classification-nlp">
<van-nav-bar
title="智能分类助手"
left-text="返回"
left-arrow
@click-left="onClickLeft"
/>
<div class="container">
<!-- 输入区域 -->
<div class="input-section">
<van-cell-group inset>
<van-field
v-model="userInput"
rows="3"
autosize
type="textarea"
maxlength="200"
placeholder="用自然语言描述您的需求AI将帮您找到相关交易并自动设置分类。例如我想要将苏州城慧的支出都改为地铁通勤消费"
show-word-limit
/>
</van-cell-group>
<div class="action-buttons">
<van-button
type="primary"
block
round
:loading="analyzing"
@click="handleAnalyze"
>
分析查询
</van-button>
</div>
</div>
<!-- 分析结果展示 -->
<div v-if="analysisResult" class="result-section">
<van-cell-group inset>
<van-cell title="查询关键词" :value="analysisResult.searchKeyword" />
<van-cell title="AI建议类型" :value="getTypeName(analysisResult.targetType)" />
<van-cell title="AI建议分类" :value="analysisResult.targetClassify" />
<van-cell
title="找到记录"
:value="`${analysisResult.records.length} 条`"
is-link
@click="showRecordsList = true"
/>
</van-cell-group>
</div>
</div>
<!-- 交易详情弹窗 -->
<TransactionDetail
v-model:show="showDetail"
:transaction="currentTransaction"
@save="handleDetailSave"
/>
<!-- 记录列表弹窗 -->
<van-popup
v-model:show="showRecordsList"
position="bottom"
:style="{ height: '80%' }"
round
>
<div class="records-popup">
<div class="popup-header">
<h3>交易记录列表</h3>
<van-icon name="cross" @click="showRecordsList = false" />
</div>
<!-- 批量操作按钮 -->
<div class="batch-actions">
<van-button
plain
type="primary"
size="small"
@click="selectAll"
>
全选
</van-button>
<van-button
plain
type="default"
size="small"
@click="selectNone"
>
全不选
</van-button>
<van-button
type="success"
size="small"
:loading="submitting"
:disabled="selectedIds.size === 0"
@click="handleSubmit"
>
提交分类 ({{ selectedIds.size }})
</van-button>
</div>
<!-- 交易记录列表 -->
<div class="records-list">
<TransactionList
:transactions="displayRecords"
:loading="false"
:finished="true"
:show-checkbox="true"
:selected-ids="selectedIds"
@update:selected-ids="updateSelectedIds"
@click="handleRecordClick"
:show-delete="false"
/>
</div>
</div>
</van-popup>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { nlpAnalysis, batchUpdateClassify } from '@/api/transactionRecord'
import TransactionList from '@/components/TransactionList.vue'
import TransactionDetail from '@/components/TransactionDetail.vue'
const router = useRouter()
const userInput = ref('')
const analyzing = ref(false)
const submitting = ref(false)
const analysisResult = ref(null)
const selectedIds = ref(new Set())
const showDetail = ref(false)
const currentTransaction = ref(null)
const showRecordsList = ref(false) // 控制记录列表弹窗
// 返回按钮
const onClickLeft = () => {
router.back()
}
// 将带目标分类的记录转换为普通交易记录格式供列表显示
const displayRecords = computed(() => {
if (!analysisResult.value) return []
return analysisResult.value.records.map(r => ({
id: r.id,
reason: r.reason,
amount: r.amount,
balance: r.balance,
card: r.card,
occurredAt: r.occurredAt,
createTime: r.createTime,
importFrom: r.importFrom,
refundAmount: r.refundAmount,
// 显示目标类型和分类
type: r.targetType,
classify: r.targetClassify,
upsetedClassify: r.upsetedClassify,
upsetedType: r.upsetedType
}))
})
// 获取交易类型名称
const getTypeName = (type) => {
const typeMap = {
0: '支出',
1: '收入',
2: '不计入收支'
}
return typeMap[type] || '未知'
}
// 分析用户输入
const handleAnalyze = async () => {
if (!userInput.value.trim()) {
showToast('请输入查询条件')
return
}
try {
analyzing.value = true
const response = await nlpAnalysis(userInput.value)
if (response.success) {
analysisResult.value = response.data
// 默认全选
const allIds = new Set(response.data.records.map(r => r.id))
selectedIds.value = allIds
showToast(`找到 ${response.data.records.length} 条记录`)
} else {
showToast(response.message || '分析失败')
}
} catch (error) {
console.error('分析失败:', error)
showToast('分析失败,请重试')
} finally {
analyzing.value = false
}
}
// 全选
const selectAll = () => {
if (!analysisResult.value) return
const allIds = new Set(analysisResult.value.records.map(r => r.id))
selectedIds.value = allIds
}
// 全不选
const selectNone = () => {
selectedIds.value = new Set()
}
// 更新选中状态
const updateSelectedIds = (newSelectedIds) => {
selectedIds.value = newSelectedIds
}
// 点击记录查看详情
const handleRecordClick = (transaction) => {
// 从原始记录中获取完整信息
const record = analysisResult.value?.records.find(r => r.id === transaction.id)
if (record) {
currentTransaction.value = {
id: record.id,
reason: record.reason,
amount: record.amount,
balance: record.balance,
card: record.card,
occurredAt: record.occurredAt,
createTime: record.createTime,
importFrom: record.importFrom,
refundAmount: record.refundAmount,
// 用户可以在详情中修改类型和分类
type: record.targetType,
classify: record.targetClassify
}
showDetail.value = true
}
}
// 详情保存后
const handleDetailSave = () => {
// 详情中的修改已经保存到服务器
// 这里可以选择重新分析或者只更新本地显示
showToast('修改已保存')
}
// 提交分类
const handleSubmit = async () => {
if (selectedIds.value.size === 0) {
showToast('请至少选择一条记录')
return
}
try {
await showConfirmDialog({
title: '确认提交',
message: `确定要为选中的 ${selectedIds.value.size} 条记录设置分类吗?`
})
} catch {
return
}
try {
submitting.value = true
// 构建批量更新数据使用AI修改后的结果
const items = analysisResult.value.records
.filter(r => selectedIds.value.has(r.id))
.map(r => ({
id: r.id,
classify: r.upsetedClassify,
type: r.upsetedType
}))
const response = await batchUpdateClassify(items)
if (response.success) {
showToast('分类设置成功')
// 清空结果,让用户进行新的查询
analysisResult.value = null
selectedIds.value = new Set()
userInput.value = ''
} else {
showToast(response.message || '设置失败')
}
} catch (error) {
console.error('提交失败:', error)
showToast('提交失败,请重试')
} finally {
submitting.value = false
}
}
</script>
<style scoped>
.classification-nlp {
min-height: 100vh;
background-color: var(--van-background, #f7f8fa);
padding-bottom: calc(60px + env(safe-area-inset-bottom, 0px));
}
.container {
padding: 0;
}
.input-section {
padding: 12px 0;
}
.action-buttons {
padding: 12px 16px;
}
.result-section {
padding-top: 8px;
}
.van-notice-bar {
margin: 12px 16px;
}
.batch-actions {
display: flex;
gap: 8px;
padding: 12px 16px;
background-color: var(--van-background-2, #fff);
margin-bottom: 8px;
}
.batch-actions > button:last-child {
margin-left: auto;
}
.records-list {
padding-bottom: 20px;
overflow-y: auto;
flex: 1;
}
.records-popup {
display: flex;
flex-direction: column;
height: 100%;
background-color: var(--van-background, #f7f8fa);
}
.popup-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px;
background-color: var(--van-background-2, #fff);
}
.popup-header h3 {
margin: 0;
font-size: 16px;
font-weight: 500;
}
.popup-header .van-icon {
font-size: 20px;
cursor: pointer;
}
</style>

View File

@@ -7,7 +7,7 @@
@click-left="onClickLeft"
/>
<div class="container" style="padding-top: 46px;">
<div class="container" style="padding-top: 5px;">
<!-- 统计信息 -->
<div class="stats-info">
<span class="stats-label">未分类账单</span>
@@ -18,9 +18,11 @@
<TransactionList
:transactions="records"
:loading="false"
:finished="true"
:show-delete="false"
:show-checkbox="true"
:selected-ids="selectedIds"
@click="viewDetail"
@update:selected-ids="selectedIds = $event"
/>
</div>
@@ -36,11 +38,11 @@
<van-button
type="primary"
:loading="classifying"
:disabled="records.length === 0"
:disabled="selectedIds.size === 0"
@click="startClassify"
class="action-btn"
>
{{ classifying ? '分类中...' : '开始智能分类' }}
{{ classifying ? '分类中...' : `开始分类 (${selectedIds.size}/${records.length})` }}
</van-button>
<van-button
@@ -72,10 +74,12 @@ import TransactionDetail from '@/components/TransactionDetail.vue'
const router = useRouter()
const unclassifiedCount = ref(0)
const records = ref([])
const selectedIds = ref(new Set()) // ID
const classifying = ref(false)
const hasChanges = ref(false)
const detailVisible = ref(false)
const currentTransaction = ref(null)
const classifyBuffer = ref('') // SSE
const onClickLeft = () => {
if (hasChanges.value) {
@@ -104,7 +108,7 @@ const loadUnclassifiedCount = async () => {
//
const loadUnclassified = async () => {
const toast = showLoadingToast({
showLoadingToast({
message: '加载中...',
forbidClick: true,
duration: 0
@@ -114,6 +118,8 @@ const loadUnclassified = async () => {
const res = await getUnclassified(10)
if (res.success) {
records.value = res.data
//
selectedIds.value = new Set(res.data.map(r => r.id))
} else {
showToast(res.message || '加载失败')
}
@@ -127,15 +133,24 @@ const loadUnclassified = async () => {
//
const startClassify = async () => {
if (records.value.length === 0) {
showToast('没有需要分类的账单')
const idsToClassify = Array.from(selectedIds.value)
if (idsToClassify.length === 0) {
showToast('请先选择要分类的账单')
return
}
const toast = showLoadingToast({
message: '智能分类中...',
forbidClick: true,
duration: 0
})
classifying.value = true
classifyBuffer.value = '' //
try {
const response = await smartClassify(10)
const response = await smartClassify(idsToClassify)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
@@ -173,49 +188,83 @@ const startClassify = async () => {
showToast(`分类失败: ${error.message}`)
} finally {
classifying.value = false
classifyBuffer.value = ''
closeToast()
}
}
// SSE
const handleSSEEvent = (eventType, data) => {
if (eventType === 'data') {
// JSON
try {
// JSON
if (!window.classifyBuffer) {
window.classifyBuffer = ''
}
window.classifyBuffer += data
// AIJSON
classifyBuffer.value += data
// JSON
const jsonMatches = window.classifyBuffer.match(/\{[^}]+\}/g)
if (jsonMatches) {
for (const jsonStr of jsonMatches) {
// JSON
// 使 { }
let startIndex = 0
while (startIndex < classifyBuffer.value.length) {
const openBrace = classifyBuffer.value.indexOf('{', startIndex)
if (openBrace === -1) {
// {
classifyBuffer.value = ''
break
}
//
let braceCount = 0
let closeBrace = -1
for (let i = openBrace; i < classifyBuffer.value.length; i++) {
if (classifyBuffer.value[i] === '{') braceCount++
else if (classifyBuffer.value[i] === '}') {
braceCount--
if (braceCount === 0) {
closeBrace = i
break
}
}
}
if (closeBrace !== -1) {
// JSON
const jsonStr = classifyBuffer.value.substring(openBrace, closeBrace + 1)
try {
const result = JSON.parse(jsonStr)
if (result.id) {
const record = records.value.find(r => r.id === result.id)
if (record) {
record.classify = result.classify || ''
record.subClassify = result.subClassify || ''
// AItypetype
if (result.type !== undefined && result.type !== null) {
record.type = result.type
}
hasChanges.value = true
}
// JSON
window.classifyBuffer = window.classifyBuffer.replace(jsonStr, '')
}
} catch (e) {
// JSON
console.error('JSON解析失败:', e)
}
//
classifyBuffer.value = classifyBuffer.value.substring(closeBrace + 1)
startIndex = 0 // JSON
} else {
// JSON
break
}
}
} catch (error) {
console.error('解析分类结果失败', error)
}
} else if (eventType === 'start') {
showToast(data)
} else if (eventType === 'end') {
window.classifyBuffer = ''
classifyBuffer.value = ''
showToast('分类完成')
} else if (eventType === 'error') {
window.classifyBuffer = ''
classifyBuffer.value = ''
showToast(data)
}
}
@@ -227,7 +276,7 @@ const saveClassifications = async () => {
.map(r => ({
id: r.id,
classify: r.classify,
subClassify: r.subClassify
type: r.type
}))
if (itemsToUpdate.length === 0) {

View File

@@ -415,8 +415,6 @@ onMounted(() => {
</script>
<style scoped>
@import '@/styles/common.css';
.email-info {
display: flex;
flex-direction: column;

View File

@@ -16,15 +16,11 @@
<p>分类处理</p>
</div>
<van-cell-group inset>
<van-cell title="编辑分类" is-link @click="handleEditClassification" />
</van-cell-group>
<van-cell-group inset>
<van-cell title="分类管理" is-link @click="handleEditClassification" />
<van-cell title="批量分类" is-link @click="handleBatchClassification" />
</van-cell-group>
<van-cell-group inset>
<van-cell title="智能分类" is-link @click="handleSmartClassification" />
<van-cell title="自然语言分类" is-link @click="handleNaturalLanguageClassification" />
</van-cell-group>
<div class="detail-header">
<p>账户</p>
</div>
@@ -107,10 +103,22 @@ const handleFileChange = async (event) => {
}
}
const handleEditClassification = () => {
router.push({ name: 'classification-edit' })
}
const handleBatchClassification = () => {
router.push({ name: 'classification-batch' })
}
const handleSmartClassification = () => {
router.push({ name: 'smart-classification' })
}
const handleNaturalLanguageClassification = () => {
router.push({ name: 'classification-nlp' })
}
/**
* 处理退出登录
*/

View File

@@ -100,15 +100,6 @@
placeholder="请选择或输入交易分类"
@click="showAddClassifyPicker = true"
/>
<van-field
v-model="addForm.subClassify"
is-link
readonly
name="subClassify"
label="交易子分类"
placeholder="请选择或输入交易子分类"
@click="showAddSubClassifyPicker = true"
/>
</van-cell-group>
<div style="margin: 16px;">
@@ -160,29 +151,21 @@
</van-picker>
</van-popup>
<!-- 新增交易 - 交易子分类选择器 -->
<van-popup v-model:show="showAddSubClassifyPicker" position="bottom" round>
<van-picker
ref="addSubClassifyPickerRef"
:columns="subClassifyColumns"
@confirm="onAddSubClassifyConfirm"
@cancel="showAddSubClassifyPicker = false"
>
<template #toolbar>
<div class="picker-toolbar">
<van-button class="toolbar-cancel" size="small" @click="clearAddSubClassify">清空</van-button>
<van-button class="toolbar-add" size="small" type="primary" @click="showAddSubClassify = true">新增</van-button>
<van-button class="toolbar-confirm" size="small" type="primary" @click="confirmAddSubClassify">确认</van-button>
</div>
</template>
</van-picker>
</van-popup>
<!-- 新增分类对话框 -->
<van-dialog
v-model:show="showAddClassify"
title="新增交易分类"
show-cancel-button
@confirm="addNewClassify"
>
<van-field v-model="newClassify" placeholder="请输入新的交易分类" />
</van-dialog>
<!-- 底部浮动搜索框 -->
<div class="floating-search">
<van-search
v-model="searchKeyword"
placeholder="搜索交易摘要、来源、卡号、分类或子分类"
placeholder="搜索交易摘要、来源、卡号、分类"
@update:model-value="onSearchChange"
@clear="onSearchClear"
shape="round"
@@ -200,7 +183,7 @@ import {
createTransaction,
deleteTransaction
} from '@/api/transactionRecord'
import { getCategoryTree } from '@/api/transactionCategory'
import { getCategoryList, createCategory } from '@/api/transactionCategory'
import TransactionList from '@/components/TransactionList.vue'
import TransactionDetail from '@/components/TransactionDetail.vue'
@@ -225,9 +208,9 @@ const showDateTimePicker = ref(false)
const dateTimeValue = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()])
const showAddTypePicker = ref(false)
const showAddClassifyPicker = ref(false)
const showAddSubClassifyPicker = ref(false)
const addClassifyPickerRef = ref(null)
const addSubClassifyPickerRef = ref(null)
const showAddClassify = ref(false)
const newClassify = ref('')
// 交易类型
const typeColumns = [
@@ -238,7 +221,6 @@ const typeColumns = [
// 分类相关
const classifyColumns = ref([])
const subClassifyColumns = ref([])
// 新增表单
const addForm = reactive({
@@ -247,21 +229,18 @@ const addForm = reactive({
amount: '',
type: 0,
typeText: '',
classify: '',
subClassify: ''
classify: ''
})
// 加载分类列表(从分类树中提取)
// 加载分类列表
const loadClassifyList = async (type = null) => {
try {
const response = await getCategoryTree(type)
const response = await getCategoryList(type)
if (response.success) {
// 从树形结构中提取分类名称Level 2
classifyColumns.value = (response.data || []).map(item => ({
text: item.name,
value: item.name,
id: item.id,
children: item.children || []
id: item.id
}))
}
} catch (error) {
@@ -269,25 +248,6 @@ const loadClassifyList = async (type = null) => {
}
}
// 加载子分类列表(根据选中的分类)
const loadSubClassifyList = async (classifyName) => {
try {
// 从已加载的分类树中查找对应的子分类
const classifyItem = classifyColumns.value.find(item => item.value === classifyName)
if (classifyItem && classifyItem.children) {
subClassifyColumns.value = classifyItem.children.map(child => ({
text: child.name,
value: child.name,
id: child.id
}))
} else {
subClassifyColumns.value = []
}
} catch (error) {
console.error('加载子分类列表出错:', error)
}
}
// 加载数据
const loadData = async (isRefresh = false) => {
if (isRefresh) {
@@ -441,7 +401,6 @@ const openAddDialog = () => {
addForm.type = 0
addForm.typeText = ''
addForm.classify = ''
addForm.subClassify = ''
// 设置默认日期时间为当前时间
const now = new Date()
@@ -477,23 +436,13 @@ const onAddTypeConfirm = ({ selectedValues, selectedOptions }) => {
}
// 新增交易 - 交易分类选择确认
const onAddClassifyConfirm = async ({ selectedOptions }) => {
const onAddClassifyConfirm = ({ selectedOptions }) => {
if (selectedOptions && selectedOptions[0]) {
addForm.classify = selectedOptions[0].text
// 加载对应的子分类
await loadSubClassifyList(selectedOptions[0].value)
}
showAddClassifyPicker.value = false
}
// 新增交易 - 交易子分类选择确认
const onAddSubClassifyConfirm = ({ selectedOptions }) => {
if (selectedOptions && selectedOptions[0]) {
addForm.subClassify = selectedOptions[0].text
}
showAddSubClassifyPicker.value = false
}
// 新增交易 - 清空分类
const clearAddClassify = () => {
addForm.classify = ''
@@ -501,13 +450,6 @@ const clearAddClassify = () => {
showToast('已清空分类')
}
// 新增交易 - 清空子分类
const clearAddSubClassify = () => {
addForm.subClassify = ''
showAddSubClassifyPicker.value = false
showToast('已清空子分类')
}
// 新增交易 - 确认分类(从 picker 中获取选中值)
const confirmAddClassify = () => {
if (addClassifyPickerRef.value) {
@@ -519,15 +461,33 @@ const confirmAddClassify = () => {
showAddClassifyPicker.value = false
}
// 新增交易 - 确认子分类(从 picker 中获取选中值)
const confirmAddSubClassify = () => {
if (addSubClassifyPickerRef.value) {
const selectedValues = addSubClassifyPickerRef.value.getSelectedOptions()
if (selectedValues && selectedValues[0]) {
addForm.subClassify = selectedValues[0].text
}
// 新增分类
const addNewClassify = async () => {
if (!newClassify.value.trim()) {
showToast('请输入分类名称')
return
}
try {
const response = await createCategory({
name: newClassify.value.trim(),
type: addForm.type
})
if (response.success) {
showToast('新增分类成功')
newClassify.value = ''
// 重新加载分类列表
await loadClassifyList(addForm.type)
// 设置为新增的分类
addForm.classify = response.data.name
} else {
showToast(response.message || '新增分类失败')
}
} catch (error) {
console.error('新增分类失败:', error)
showToast('新增分类失败')
}
showAddSubClassifyPicker.value = false
}
// 提交新增交易
@@ -540,8 +500,7 @@ const onAddSubmit = async () => {
reason: addForm.reason,
amount: parseFloat(addForm.amount),
type: addForm.type,
classify: addForm.classify || null,
subClassify: addForm.subClassify || null
classify: addForm.classify || null
}
const response = await createTransaction(data)

View File

@@ -8,36 +8,23 @@ public class TransactionCategoryController(
) : ControllerBase
{
/// <summary>
/// 获取分类(支持按类型筛选)
/// 获取分类列表(支持按类型筛选)
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<TransactionCategoryTreeDto>>> GetTreeAsync([FromQuery] TransactionType? type = null)
public async Task<BaseResponse<List<TransactionCategory>>> GetListAsync([FromQuery] TransactionType? type = null)
{
try
{
var tree = await categoryRepository.GetCategoryTreeAsync(type);
return new BaseResponse<List<TransactionCategoryTreeDto>>
List<TransactionCategory> categories;
if (type.HasValue)
{
Success = true,
Data = tree
};
}
catch (Exception ex)
{
logger.LogError(ex, "获取分类树失败");
return BaseResponse<List<TransactionCategoryTreeDto>>.Fail($"获取分类树失败: {ex.Message}");
}
}
/// <summary>
/// 获取顶级分类列表(按类型)
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<TransactionCategory>>> GetTopLevelAsync([FromQuery] TransactionType type)
{
try
{
var categories = await categoryRepository.GetTopLevelCategoriesByTypeAsync(type);
categories = await categoryRepository.GetCategoriesByTypeAsync(type.Value);
}
else
{
categories = (await categoryRepository.GetAllAsync()).ToList();
}
return new BaseResponse<List<TransactionCategory>>
{
Success = true,
@@ -46,30 +33,8 @@ public class TransactionCategoryController(
}
catch (Exception ex)
{
logger.LogError(ex, "获取顶级分类失败, Type: {Type}", type);
return BaseResponse<List<TransactionCategory>>.Fail($"获取顶级分类失败: {ex.Message}");
}
}
/// <summary>
/// 获取子分类列表
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<TransactionCategory>>> GetChildrenAsync([FromQuery] long parentId)
{
try
{
var categories = await categoryRepository.GetChildCategoriesAsync(parentId);
return new BaseResponse<List<TransactionCategory>>
{
Success = true,
Data = categories
};
}
catch (Exception ex)
{
logger.LogError(ex, "获取子分类失败, ParentId: {ParentId}", parentId);
return BaseResponse<List<TransactionCategory>>.Fail($"获取子分类失败: {ex.Message}");
logger.LogError(ex, "获取分类列表失败");
return BaseResponse<List<TransactionCategory>>.Fail($"获取分类列表失败: {ex.Message}");
}
}
@@ -109,21 +74,16 @@ public class TransactionCategoryController(
try
{
// 检查同名分类
var existing = await categoryRepository.GetByNameAndParentAsync(dto.Name, dto.ParentId, dto.Type);
var existing = await categoryRepository.GetByNameAndTypeAsync(dto.Name, dto.Type);
if (existing != null)
{
return BaseResponse<long>.Fail("同级已存在相同名称的分类");
return BaseResponse<long>.Fail("已存在相同名称的分类");
}
var category = new TransactionCategory
{
Name = dto.Name,
ParentId = dto.ParentId,
Type = dto.Type,
Level = dto.Level,
SortOrder = dto.SortOrder,
Icon = dto.Icon,
Remark = dto.Remark
Type = dto.Type
};
var result = await categoryRepository.AddAsync(category);
@@ -164,18 +124,14 @@ public class TransactionCategoryController(
// 如果修改了名称,检查同名
if (category.Name != dto.Name)
{
var existing = await categoryRepository.GetByNameAndParentAsync(dto.Name, category.ParentId, category.Type);
var existing = await categoryRepository.GetByNameAndTypeAsync(dto.Name, category.Type);
if (existing != null && existing.Id != dto.Id)
{
return BaseResponse.Fail("同级已存在相同名称的分类");
return BaseResponse.Fail("已存在相同名称的分类");
}
}
category.Name = dto.Name;
category.SortOrder = dto.SortOrder;
category.Icon = dto.Icon;
category.IsEnabled = dto.IsEnabled;
category.Remark = dto.Remark;
category.UpdateTime = DateTime.Now;
var success = await categoryRepository.UpdateAsync(category);
@@ -203,13 +159,6 @@ public class TransactionCategoryController(
{
try
{
// 检查是否有子分类
var children = await categoryRepository.GetChildCategoriesAsync(id);
if (children.Any())
{
return BaseResponse.Fail("该分类下存在子分类,无法删除");
}
// 检查是否被使用
var inUse = await categoryRepository.IsCategoryInUseAsync(id);
if (inUse)
@@ -245,12 +194,7 @@ public class TransactionCategoryController(
var categories = dtoList.Select(dto => new TransactionCategory
{
Name = dto.Name,
ParentId = dto.ParentId,
Type = dto.Type,
Level = dto.Level,
SortOrder = dto.SortOrder,
Icon = dto.Icon,
Remark = dto.Remark
Type = dto.Type
}).ToList();
var result = await categoryRepository.AddRangeAsync(categories);
@@ -280,12 +224,7 @@ public class TransactionCategoryController(
/// </summary>
public record CreateCategoryDto(
string Name,
long ParentId,
TransactionType Type,
int Level,
int SortOrder = 0,
string? Icon = null,
string? Remark = null
TransactionType Type
);
/// <summary>
@@ -293,9 +232,5 @@ public record CreateCategoryDto(
/// </summary>
public record UpdateCategoryDto(
long Id,
string Name,
int SortOrder,
string? Icon,
bool IsEnabled,
string? Remark
string Name
);

View File

@@ -110,7 +110,6 @@ public class TransactionRecordController(
Amount = dto.Amount,
Type = dto.Type,
Classify = dto.Classify ?? string.Empty,
SubClassify = dto.SubClassify ?? string.Empty,
ImportFrom = "手动录入",
EmailMessageId = 0 // 手动录入的记录EmailMessageId 设为 0
};
@@ -155,7 +154,6 @@ public class TransactionRecordController(
transaction.Balance = dto.Balance;
transaction.Type = dto.Type;
transaction.Classify = dto.Classify ?? string.Empty;
transaction.SubClassify = dto.SubClassify ?? string.Empty;
var success = await transactionRepository.UpdateAsync(transaction);
if (success)
@@ -322,46 +320,65 @@ public class TransactionRecordController(
try
{
// 获取要分类的账单
var records = await transactionRepository.GetUnclassifiedAsync(request.PageSize);
// 验证账单ID列表
if (request.TransactionIds == null || request.TransactionIds.Count == 0)
{
await WriteEventAsync("error", "请提供要分类的账单ID");
return;
}
// 获取指定ID的账单
var records = new List<Entity.TransactionRecord>();
foreach (var id in request.TransactionIds)
{
var record = await transactionRepository.GetByIdAsync(id);
if (record != null && record.Classify == string.Empty)
{
records.Add(record);
}
}
if (records.Count == 0)
{
await WriteEventAsync("error", "没有需要分类的账单");
await WriteEventAsync("error", "找不到指定的账单");
return;
}
// 获取所有分类
var categories = await categoryRepository.GetAllAsync();
// 构建分类信息
var categoryInfo = string.Join("\n", categories
.Select(c =>
var categoryInfo = new StringBuilder();
foreach (var type in new[] { 0, 1, 2 })
{
var typeName = GetTypeName((TransactionType)type);
categoryInfo.AppendLine($"{typeName}: ");
var categoriesOfType = categories.Where(c => (int)c.Type == type).ToList();
foreach (var category in categoriesOfType)
{
var children = categories.Where(x => x.ParentId == c.Id).ToList();
var childrenStr = children.Count > 0
? $",子分类:{string.Join("", children.Select(x => x.Name))}"
: "";
return $"- {c.Name} ({(c.Type == TransactionType.Expense ? "" : "")}){childrenStr}";
}));
categoryInfo.AppendLine($"- {category.Name}");
}
}
// 构建账单信息
var billsInfo = string.Join("\n", records.Select((r, i) =>
var billsInfo = string.Join("\n", records.Select((r, i) =>
$"{i + 1}. ID={r.Id}, 摘要={r.Reason}, 金额={r.Amount}, 类型={GetTypeName(r.Type)}"));
var systemPrompt = $@"你是一个专业的账单分类助手。请根据提供的账单信息和分类列表,为每个账单选择最合适的分类。
var systemPrompt = $$"""
你是一个专业的账单分类助手。请根据提供的账单信息和分类列表,为每个账单选择最合适的分类。
可用的分类列表:
{categoryInfo}
可用的分类列表:
{{categoryInfo}}
分类规则:
1. 根据账单的摘要和金额,选择最匹配的一级分类
2. 如果有合适的子分类,也要指定子分类
3. 如果无法确定分类,可以选择""其他""
分类规则:
1. 根据账单的摘要和金额,选择最匹配的分类
2. 如果无法确定分类,可以选择""其他""
请对每个账单进行分类,每次输出一个账单的分类结果,格式如下:
{{""id"": 账单ID, ""classify"": ""一级分类"", ""subClassify"": ""子分类""}}
请对每个账单进行分类,每次输出一个账单的分类结果,格式如下:
{"id": 账单ID, "type": 0:支出/1:收入/2:不计入收支(Type为Number枚举值) ,"classify": 分类名称}
只输出JSON不要有其他文字说明。";
JSON
""";
var userPrompt = $@"请为以下账单进行分类:
@@ -403,7 +420,11 @@ public class TransactionRecordController(
if (record != null)
{
record.Classify = item.Classify ?? string.Empty;
record.SubClassify = item.SubClassify ?? string.Empty;
// 如果提供了Type也更新Type
if (item.Type.HasValue)
{
record.Type = item.Type.Value;
}
var success = await transactionRepository.UpdateAsync(record);
if (success)
successCount++;
@@ -429,6 +450,183 @@ public class TransactionRecordController(
}
}
/// <summary>
/// 获取按交易摘要分组的统计信息(支持分页)
/// </summary>
[HttpGet]
public async Task<PagedResponse<Repository.ReasonGroupDto>> GetReasonGroupsAsync(
[FromQuery] int pageIndex = 1,
[FromQuery] int pageSize = 20)
{
try
{
var (list, total) = await transactionRepository.GetReasonGroupsAsync(pageIndex, pageSize);
return new PagedResponse<Repository.ReasonGroupDto>
{
Success = true,
Data = list.ToArray(),
Total = total
};
}
catch (Exception ex)
{
logger.LogError(ex, "获取交易摘要分组失败");
return PagedResponse<Repository.ReasonGroupDto>.Fail($"获取交易摘要分组失败: {ex.Message}");
}
}
/// <summary>
/// 按摘要批量更新分类
/// </summary>
[HttpPost]
public async Task<BaseResponse<int>> BatchUpdateByReasonAsync([FromBody] BatchUpdateByReasonDto dto)
{
try
{
var count = await transactionRepository.BatchUpdateByReasonAsync(dto.Reason, dto.Type, dto.Classify);
return new BaseResponse<int>
{
Success = true,
Data = count,
Message = $"成功更新 {count} 条记录"
};
}
catch (Exception ex)
{
logger.LogError(ex, "按摘要批量更新分类失败,摘要: {Reason}", dto.Reason);
return BaseResponse<int>.Fail($"按摘要批量更新分类失败: {ex.Message}");
}
}
/// <summary>
/// 自然语言分析 - 根据用户输入的自然语言查询交易记录并预设分类
/// </summary>
[HttpPost]
public async Task<BaseResponse<NlpAnalysisResult>> NlpAnalysisAsync([FromBody] NlpAnalysisRequest request)
{
try
{
if (string.IsNullOrWhiteSpace(request.UserInput))
{
return BaseResponse<NlpAnalysisResult>.Fail("请输入查询条件");
}
// 获取所有分类
var categories = await categoryRepository.GetAllAsync();
var categoryInfo = new StringBuilder();
foreach (var type in new[] { 0, 1, 2 })
{
var typeName = GetTypeName((TransactionType)type);
categoryInfo.AppendLine($"{typeName}: ");
var categoriesOfType = categories.Where(c => (int)c.Type == type).ToList();
foreach (var category in categoriesOfType)
{
categoryInfo.AppendLine($"- {category.Name}");
}
}
var systemPrompt = $$"""
你是一个专业的交易记录查询助手。用户会用自然语言描述他想要查询和分类的交易记录。
可用的分类列表:
{{categoryInfo}}
你需要分析用户的需求,提取以下信息:
1. 查询SQL, 根据用户的描述生成SQL Where 子句用于查询交易记录。例如Reason LIKE '%关键词%'
Table Schema:
TransactionRecord (
Id LONG,
Reason STRING,
Amount DECIMAL,
RefundAmount DECIMAL,
Balance DECIMAL,
OccurredAt DATETIME,
EmailMessageId LONG,
Type INT,
Classify STRING,
ImportNo STRING,
ImportFrom STRING
)
2. 目标交易类型0:支出, 1:收入, 2:不计入收支)
3. 目标分类名称(必须从上面的分类列表中选择)
请以JSON格式输出格式如下
{
"sql": "SQL",
"targetType": ,
"targetClassify": "分类名称"
}
JSON
""";
var userPrompt = $"用户输入:{request.UserInput}";
// 调用AI分析
var aiResponse = await openAiService.ChatAsync(systemPrompt, userPrompt);
logger.LogInformation("NLP分析AI返回结果: {Response}", aiResponse);
if (string.IsNullOrWhiteSpace(aiResponse))
{
return BaseResponse<NlpAnalysisResult>.Fail("AI分析失败请检查AI配置");
}
// 解析AI返回的JSON
NlpAnalysisInfo? analysisInfo;
try
{
analysisInfo = JsonSerializer.Deserialize<NlpAnalysisInfo>(aiResponse);
if (analysisInfo == null)
{
return BaseResponse<NlpAnalysisResult>.Fail("AI返回格式错误");
}
}
catch (Exception ex)
{
logger.LogError(ex, "解析AI返回结果失败返回内容: {Response}", aiResponse);
return BaseResponse<NlpAnalysisResult>.Fail($"AI返回格式错误: {ex.Message}");
}
// 根据关键词查询交易记录
var allRecords = await transactionRepository.QueryBySqlAsync(analysisInfo.Sql);
logger.LogInformation("NLP分析查询到 {Count} 条记录SQL: {Sql}", allRecords.Count, analysisInfo.Sql);
// 为每条记录预设分类
var recordsWithClassify = allRecords.Select(r => new TransactionRecordWithClassify
{
Id = r.Id,
Reason = r.Reason ?? string.Empty,
Amount = r.Amount,
Balance = r.Balance,
Card = r.Card ?? string.Empty,
OccurredAt = r.OccurredAt,
CreateTime = r.CreateTime,
ImportFrom = r.ImportFrom ?? string.Empty,
RefundAmount = r.RefundAmount,
UpsetedType = analysisInfo.TargetType,
UpsetedClassify = analysisInfo.TargetClassify,
TargetType = r.Type,
TargetClassify = r.Classify ?? string.Empty
}).ToList();
return new BaseResponse<NlpAnalysisResult>
{
Success = true,
Data = new NlpAnalysisResult
{
Records = recordsWithClassify,
TargetType = analysisInfo.TargetType,
TargetClassify = analysisInfo.TargetClassify,
SearchKeyword = analysisInfo.Sql
}
};
}
catch (Exception ex)
{
logger.LogError(ex, "NLP分析失败用户输入: {Input}", request.UserInput);
return BaseResponse<NlpAnalysisResult>.Fail($"NLP分析失败: {ex.Message}");
}
}
private async Task WriteEventAsync(string eventType, string data)
{
var message = $"event: {eventType}\ndata: {data}\n\n";
@@ -458,8 +656,7 @@ public record CreateTransactionDto(
string? Reason,
decimal Amount,
TransactionType Type,
string? Classify,
string? SubClassify
string? Classify
);
/// <summary>
@@ -471,8 +668,7 @@ public record UpdateTransactionDto(
decimal Amount,
decimal Balance,
TransactionType Type,
string? Classify,
string? SubClassify
string? Classify
);
/// <summary>
@@ -488,7 +684,7 @@ public record DailyStatisticsDto(
/// 智能分类请求DTO
/// </summary>
public record SmartClassifyRequest(
int PageSize = 10
List<long>? TransactionIds = null
);
/// <summary>
@@ -497,5 +693,67 @@ public record SmartClassifyRequest(
public record BatchUpdateClassifyItem(
long Id,
string? Classify,
string? SubClassify
);
TransactionType? Type = null
);
/// <summary>
/// 按摘要批量更新DTO
/// </summary>
public record BatchUpdateByReasonDto(
string Reason,
TransactionType Type,
string Classify
);
/// <summary>
/// NLP分析请求DTO
/// </summary>
public record NlpAnalysisRequest(
string UserInput
);
/// <summary>
/// NLP分析结果DTO
/// </summary>
public record NlpAnalysisResult
{
public List<TransactionRecordWithClassify> Records { get; set; } = new();
public TransactionType TargetType { get; set; }
public string TargetClassify { get; set; } = string.Empty;
public string SearchKeyword { get; set; } = string.Empty;
}
/// <summary>
/// 带分类信息的交易记录DTO
/// </summary>
public record TransactionRecordWithClassify
{
public long Id { get; set; }
public string Reason { get; set; } = string.Empty;
public decimal Amount { get; set; }
public decimal Balance { get; set; }
public string Card { get; set; } = string.Empty;
public DateTime OccurredAt { get; set; }
public DateTime CreateTime { get; set; }
public string ImportFrom { get; set; } = string.Empty;
public decimal RefundAmount { get; set; }
public TransactionType UpsetedType { get; set; }
public string UpsetedClassify { get; set; } = string.Empty;
public TransactionType TargetType { get; set; }
public string TargetClassify { get; set; } = string.Empty;
}
/// <summary>
/// AI分析信息DTO内部使用
/// </summary>
public record NlpAnalysisInfo
{
[JsonPropertyName("sql")]
public string Sql { get; set; } = string.Empty;
[JsonPropertyName("targetType")]
public TransactionType TargetType { get; set; }
[JsonPropertyName("targetClassify")]
public string TargetClassify { get; set; } = string.Empty;
}

View File

@@ -3,4 +3,7 @@ global using Common;
global using Microsoft.AspNetCore.Mvc;
global using WebApi.Controllers.Dto;
global using Repository;
global using Entity;
global using Entity;
global using System.Text.Json;
global using System.Text;
global using System.Text.Json.Serialization;