feat: 接入 DeepSeek,新增 AI 分类建议、自然语言查询与智能记账
- 后端新增 AI 模块:DeepSeek 客户端、用户级配置表 t_ai_config、用量记录表 t_ai_usage - 批量设置支持 AI 推荐分类与标签,并可一键应用 - 交易列表支持自然语言查询,解析为筛选条件确认后应用 - 支持自然语言记账,解析后预填新增表单 - 新增 AI 设置页:启用开关、API Key、接口地址、模型、连通性测试与用量统计 - 交易列表重排:AI 查询区、已激活筛选标签、备注与查询历史缓存 - 账单导入默认分类下拉补充分类图标 - 顶部用户入口改为下拉菜单(AI 设置 / 退出登录)
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
// AI 智能建议相关 API 接口:配置读写、连通性测试、建议生成与应用
|
||||
import request from './request'
|
||||
|
||||
/** AI 配置数据结构(API Key 已脱敏) */
|
||||
export interface AiConfig {
|
||||
enabled: boolean
|
||||
apiKey: string | null
|
||||
hasApiKey: boolean
|
||||
baseUrl: string
|
||||
model: string
|
||||
}
|
||||
|
||||
/** 单条 AI 建议 */
|
||||
export interface AiSuggestion {
|
||||
transactionId: number
|
||||
categoryId: number | null
|
||||
categoryName: string | null
|
||||
tagIds: number[]
|
||||
tagNames: string[]
|
||||
reason: string
|
||||
}
|
||||
|
||||
/** 获取当前用户的 AI 配置 */
|
||||
export function getAiConfig() {
|
||||
return request.get('/ai/config')
|
||||
}
|
||||
|
||||
/** 保存 AI 配置,apiKey 留空表示不修改原值 */
|
||||
export function saveAiConfig(data: { enabled: boolean; apiKey?: string; baseUrl?: string; model?: string }) {
|
||||
return request.put('/ai/config', data)
|
||||
}
|
||||
|
||||
/** 测试 DeepSeek 连通性(耗时较长,单独放宽超时) */
|
||||
export function testAiConfig() {
|
||||
return request.post('/ai/config/test', {}, { timeout: 60000 })
|
||||
}
|
||||
|
||||
/** 生成分类与标签建议(调用大模型,超时放宽) */
|
||||
export function suggestByAi(ids: number[]) {
|
||||
return request.post('/ai/suggest', { ids }, { timeout: 120000 })
|
||||
}
|
||||
|
||||
/** 一键应用建议:覆盖分类并追加标签 */
|
||||
export function applyAiSuggestions(suggestions: { transactionId: number; categoryId: number | null; tagIds: number[] }[]) {
|
||||
return request.post('/ai/apply', { suggestions })
|
||||
}
|
||||
|
||||
/** 自然语言查询解析结果 */
|
||||
export interface AiQueryResult {
|
||||
summary: string
|
||||
types: string[]
|
||||
categoryIds: number[]
|
||||
categoryNames: string[]
|
||||
uncategorized: boolean
|
||||
paymentMethods: string[]
|
||||
startTime: string | null
|
||||
endTime: string | null
|
||||
includeInStats: boolean | null
|
||||
minAmount: number | null
|
||||
maxAmount: number | null
|
||||
remark: string | null
|
||||
tagIds: number[]
|
||||
tagNames: string[]
|
||||
unmatched: string[]
|
||||
}
|
||||
|
||||
/** 将自然语言查询解析为筛选条件 */
|
||||
export function queryByAi(query: string) {
|
||||
return request.post('/ai/query', { query }, { timeout: 120000 })
|
||||
}
|
||||
|
||||
/** 自然语言记账解析结果 */
|
||||
export interface AiRecordResult {
|
||||
summary: string
|
||||
type: string
|
||||
amount: number | null
|
||||
categoryId: number | null
|
||||
categoryName: string | null
|
||||
paymentMethod: string | null
|
||||
transactionTime: string | null
|
||||
remark: string | null
|
||||
includeInStats: boolean | null
|
||||
tagIds: number[]
|
||||
tagNames: string[]
|
||||
unmatched: string[]
|
||||
}
|
||||
|
||||
/** 将自然语言记账内容解析为交易记录 */
|
||||
export function parseRecordByAi(text: string) {
|
||||
return request.post('/ai/record', { text }, { timeout: 120000 })
|
||||
}
|
||||
|
||||
/** AI 使用累计汇总 */
|
||||
export interface AiUsageSummary {
|
||||
totalCalls: number
|
||||
successCalls: number
|
||||
failedCalls: number
|
||||
promptTokens: number
|
||||
completionTokens: number
|
||||
totalTokens: number
|
||||
cachedTokens: number
|
||||
}
|
||||
|
||||
/** 单条 AI 使用明细 */
|
||||
export interface AiUsageItem {
|
||||
id: number
|
||||
type: string
|
||||
model: string
|
||||
transactionCount: number
|
||||
promptTokens: number
|
||||
completionTokens: number
|
||||
totalTokens: number
|
||||
cachedTokens: number
|
||||
success: boolean
|
||||
errorMessage: string | null
|
||||
durationMs: number | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/** AI 使用情况(累计汇总 + 最近明细) */
|
||||
export interface AiUsageResult {
|
||||
summary: AiUsageSummary
|
||||
recent: AiUsageItem[]
|
||||
}
|
||||
|
||||
/** 获取 AI 使用情况 */
|
||||
export function getAiUsage(limit = 20) {
|
||||
return request.get('/ai/usage', { params: { limit } })
|
||||
}
|
||||
@@ -81,6 +81,7 @@ export default {
|
||||
transactions: { zh: '收支记录', en: 'Transactions' },
|
||||
categories: { zh: '分类管理', en: 'Categories' },
|
||||
tags: { zh: '标签管理', en: 'Tags' },
|
||||
aiSettings: { zh: 'AI 设置', en: 'AI Settings' },
|
||||
user: { zh: '用户', en: 'User' },
|
||||
logout: { zh: '退出', en: 'Sign Out' },
|
||||
},
|
||||
@@ -141,6 +142,9 @@ export default {
|
||||
amountRange: { zh: '金额区间', en: 'Amount Range' },
|
||||
search: { zh: '查询', en: 'Search' },
|
||||
reset: { zh: '重置', en: 'Reset' },
|
||||
activeFilters: { zh: '已激活:', en: 'Active:' },
|
||||
clearAll: { zh: '清空全部', en: 'Clear all' },
|
||||
exampleLabel: { zh: '示例', en: 'Examples' },
|
||||
summary: { zh: '总计 {total} 条 · 第 {page} / {pages} 页 · 每页 {size} 条', en: 'Total {total} · Page {page} / {pages} · {size} per page' },
|
||||
pageExpense: { zh: '本页支出', en: 'Page Expense' },
|
||||
pageIncome: { zh: '本页收入', en: 'Page Income' },
|
||||
@@ -193,6 +197,7 @@ export default {
|
||||
amountPlaceholder: { zh: '请输入金额', en: 'Enter amount' },
|
||||
paymentPlaceholder: { zh: '选择支付方式', en: 'Select payment method' },
|
||||
remarkPlaceholder: { zh: '可选备注说明', en: 'Optional remark' },
|
||||
remarkHistoryClear: { zh: '清空历史', en: 'Clear history' },
|
||||
tagPlaceholder: { zh: '选择标签', en: 'Select tags' },
|
||||
noRawData: { zh: '该记录没有原始账单数据', en: 'This record has no raw bill data' },
|
||||
remarkHiddenSuccess: { zh: '已隐藏备注', en: 'Remark hidden' },
|
||||
@@ -299,4 +304,104 @@ export default {
|
||||
loadCategoriesFailed: { zh: '加载分类失败', en: 'Failed to load categories' },
|
||||
loadTagsFailed: { zh: '加载标签失败', en: 'Failed to load tags' },
|
||||
},
|
||||
|
||||
// AI 智能建议
|
||||
ai: {
|
||||
title: { zh: 'AI 智能建议', en: 'AI Suggestions' },
|
||||
intro: { zh: '配置 DeepSeek 后,可在收支记录页的「一键设置」中让 AI 根据记录内容推荐分类与标签。', en: 'After configuring DeepSeek, you can let AI recommend categories and tags for records in the "Batch Set" dialog on the Transactions page.' },
|
||||
configTitle: { zh: '模型配置', en: 'Model Configuration' },
|
||||
enabledOn: { zh: '已启用', en: 'Enabled' },
|
||||
enabledOff: { zh: '未启用', en: 'Disabled' },
|
||||
enabled: { zh: '启用 AI 建议', en: 'Enable AI suggestions' },
|
||||
enabledHint: { zh: '关闭后不会发起任何 AI 请求', en: 'No AI requests are sent when disabled' },
|
||||
apiKey: { zh: 'API Key', en: 'API Key' },
|
||||
apiKeyPlaceholder: { zh: '请输入 DeepSeek API Key', en: 'Enter your DeepSeek API Key' },
|
||||
apiKeyKeep: { zh: '已配置,留空表示不修改', en: 'Configured; leave blank to keep unchanged' },
|
||||
baseUrl: { zh: '接口地址', en: 'Base URL' },
|
||||
model: { zh: '模型', en: 'Model' },
|
||||
save: { zh: '保存', en: 'Save' },
|
||||
test: { zh: '测试连接', en: 'Test connection' },
|
||||
saveSuccess: { zh: '保存成功', en: 'Saved successfully' },
|
||||
loadFailed: { zh: '加载 AI 配置失败', en: 'Failed to load AI config' },
|
||||
testSuccess: { zh: '连接成功', en: 'Connection succeeded' },
|
||||
testFailed: { zh: '连接失败', en: 'Connection failed' },
|
||||
suggestButton: { zh: 'AI 智能建议', en: 'AI suggestions' },
|
||||
suggestTitle: { zh: 'AI 分类与标签建议', en: 'AI category & tag suggestions' },
|
||||
suggesting: { zh: '正在分析,请稍候…', en: 'Analyzing, please wait…' },
|
||||
suggestFailed: { zh: 'AI 建议生成失败', en: 'Failed to generate AI suggestions' },
|
||||
noSuggestion: { zh: 'AI 未返回有效建议', en: 'AI returned no valid suggestions' },
|
||||
applyAll: { zh: '全部应用({count})', en: 'Apply all ({count})' },
|
||||
applySuccess: { zh: '已应用 {count} 条建议', en: 'Applied {count} suggestions' },
|
||||
applyFailed: { zh: '应用建议失败', en: 'Failed to apply suggestions' },
|
||||
applyHint: { zh: '将覆盖分类并追加标签,确认后立即写入', en: 'Categories will be overwritten and tags appended; changes are written immediately.' },
|
||||
needConfig: { zh: 'AI 未启用,请先在「AI 设置」中配置', en: 'AI is not enabled. Please configure it in AI Settings first.' },
|
||||
query: {
|
||||
placeholder: { zh: '用自然语言查询,如:上个月餐饮花了多少', en: 'Ask in natural language, e.g. dining expenses last month' },
|
||||
examples: { zh: '上个月餐饮|超过500的支出|待报销的支出|微信支付', en: 'Dining last month|Expenses over 500|Pending reimbursement|Paid by WeChat' },
|
||||
button: { zh: 'AI 查询', en: 'AI Query' },
|
||||
emptyInput: { zh: '请输入查询内容', en: 'Please enter a query' },
|
||||
clearHistory: { zh: '清空历史', en: 'Clear history' },
|
||||
failed: { zh: 'AI 查询解析失败', en: 'Failed to parse the query' },
|
||||
resultTitle: { zh: 'AI 解析结果', en: 'AI Query Result' },
|
||||
apply: { zh: '应用筛选', en: 'Apply filters' },
|
||||
applied: { zh: '已应用 AI 查询筛选条件', en: 'AI query filters applied' },
|
||||
noCondition: { zh: '未识别到可用的筛选条件,请换一种说法', en: 'No usable filter conditions recognized, please rephrase' },
|
||||
type: { zh: '类型', en: 'Type' },
|
||||
category: { zh: '分类', en: 'Category' },
|
||||
tag: { zh: '标签', en: 'Tag' },
|
||||
payment: { zh: '支付方式', en: 'Payment' },
|
||||
dateRange: { zh: '时间范围', en: 'Date range' },
|
||||
amountRange: { zh: '金额范围', en: 'Amount range' },
|
||||
remark: { zh: '备注', en: 'Remark' },
|
||||
includeInStats: { zh: '计入统计', en: 'In stats' },
|
||||
includeYes: { zh: '计入', en: 'Included' },
|
||||
includeNo: { zh: '不计入', en: 'Excluded' },
|
||||
unmatched: { zh: '未识别', en: 'Unmatched' },
|
||||
},
|
||||
record: {
|
||||
button: { zh: '智能记账', en: 'Smart Entry' },
|
||||
title: { zh: 'AI 智能记账', en: 'AI Smart Entry' },
|
||||
hint: { zh: '用一句话描述这笔收支,AI 会帮你填好表单,确认后再保存。', en: 'Describe the transaction in one sentence; AI fills the form for you to confirm.' },
|
||||
placeholder: { zh: '例如:昨天中午吃饭 35 支付宝', en: 'e.g. Lunch yesterday 35 Alipay' },
|
||||
parse: { zh: '解析', en: 'Parse' },
|
||||
emptyInput: { zh: '请输入记账内容', en: 'Please enter the transaction description' },
|
||||
failed: { zh: 'AI 记账解析失败', en: 'Failed to parse the transaction' },
|
||||
},
|
||||
column: {
|
||||
record: { zh: '记录', en: 'Record' },
|
||||
category: { zh: '建议分类', en: 'Suggested category' },
|
||||
tags: { zh: '建议标签', en: 'Suggested tags' },
|
||||
reason: { zh: '理由', en: 'Reason' },
|
||||
},
|
||||
usage: {
|
||||
title: { zh: '使用情况', en: 'Usage' },
|
||||
recentTitle: { zh: '最近调用记录', en: 'Recent calls' },
|
||||
refresh: { zh: '刷新', en: 'Refresh' },
|
||||
totalCalls: { zh: '调用次数', en: 'Calls' },
|
||||
successCalls: { zh: '成功', en: 'Succeeded' },
|
||||
failedCalls: { zh: '失败', en: 'Failed' },
|
||||
promptTokens: { zh: '输入 Token', en: 'Prompt tokens' },
|
||||
completionTokens: { zh: '输出 Token', en: 'Completion tokens' },
|
||||
totalTokens: { zh: '总 Token', en: 'Total tokens' },
|
||||
cachedTokens: { zh: '缓存命中', en: 'Cached tokens' },
|
||||
success: { zh: '成功', en: 'Success' },
|
||||
failed: { zh: '失败', en: 'Failed' },
|
||||
loadFailed: { zh: '加载使用情况失败', en: 'Failed to load usage' },
|
||||
empty: { zh: '暂无调用记录', en: 'No usage records yet' },
|
||||
type: {
|
||||
suggest: { zh: '生成建议', en: 'Suggest' },
|
||||
test: { zh: '测试连接', en: 'Test' },
|
||||
},
|
||||
column: {
|
||||
time: { zh: '时间', en: 'Time' },
|
||||
type: { zh: '类型', en: 'Type' },
|
||||
count: { zh: '分析条数', en: 'Records' },
|
||||
promptTokens: { zh: '输入', en: 'Prompt' },
|
||||
completionTokens: { zh: '输出', en: 'Completion' },
|
||||
totalTokens: { zh: '总计', en: 'Total' },
|
||||
duration: { zh: '耗时', en: 'Duration' },
|
||||
status: { zh: '状态', en: 'Status' },
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -41,6 +41,11 @@ const router = createRouter({
|
||||
name: 'Tags',
|
||||
component: () => import('../views/TagManage.vue'), // 标签管理
|
||||
},
|
||||
{
|
||||
path: 'ai-settings',
|
||||
name: 'AiSettings',
|
||||
component: () => import('../views/AiSettings.vue'), // AI 设置
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
<script setup lang="ts">
|
||||
// AI 设置页:配置 DeepSeek 的启用开关、API Key、基础地址与模型,并展示 AI 使用情况
|
||||
import { ref, onMounted, computed, h } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import {
|
||||
useMessage, NCard, NForm, NFormItem, NInput, NSwitch, NButton, NSpace, NAlert, NText,
|
||||
NStatistic, NDataTable, NTag, NGrid, NGridItem, NIcon, NEmpty,
|
||||
} from 'naive-ui'
|
||||
import type { DataTableColumns } from 'naive-ui'
|
||||
import {
|
||||
PulseOutline, CheckmarkCircleOutline, CloseCircleOutline, StatsChartOutline,
|
||||
CloudUploadOutline, CloudDownloadOutline, FlashOutline, TimeOutline,
|
||||
SettingsOutline, KeyOutline, LinkOutline, CubeOutline, SaveOutline,
|
||||
} from '@vicons/ionicons5'
|
||||
import { getAiConfig, saveAiConfig, testAiConfig, getAiUsage } from '../api/ai'
|
||||
import type { AiUsageResult } from '../api/ai'
|
||||
|
||||
const message = useMessage() // 消息提示
|
||||
const { t } = useI18n() // 国际化
|
||||
|
||||
const saving = ref(false) // 保存状态
|
||||
const testing = ref(false) // 测试连接状态
|
||||
const hasApiKey = ref(false) // 是否已配置过 API Key
|
||||
const usage = ref<AiUsageResult | null>(null) // AI 使用情况
|
||||
const usageLoading = ref(false) // 使用情况加载状态
|
||||
|
||||
// 表单数据
|
||||
const form = ref({ enabled: false, apiKey: '', baseUrl: 'https://api.deepseek.com', model: 'deepseek-chat' })
|
||||
|
||||
/** 加载当前用户的 AI 配置 */
|
||||
async function loadConfig() {
|
||||
try {
|
||||
const res: any = await getAiConfig()
|
||||
const data = res.data
|
||||
form.value = {
|
||||
enabled: !!data.enabled,
|
||||
apiKey: '',
|
||||
baseUrl: data.baseUrl || 'https://api.deepseek.com',
|
||||
model: data.model || 'deepseek-chat',
|
||||
}
|
||||
hasApiKey.value = !!data.hasApiKey
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('ai.loadFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
/** 加载 AI 使用情况(累计汇总 + 最近明细) */
|
||||
async function loadUsage() {
|
||||
usageLoading.value = true
|
||||
try {
|
||||
const res: any = await getAiUsage()
|
||||
usage.value = res.data
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('ai.usage.loadFailed'))
|
||||
} finally {
|
||||
usageLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 提交表单数据,apiKey 为空时不覆盖已保存的 Key */
|
||||
function buildPayload() {
|
||||
return {
|
||||
enabled: form.value.enabled,
|
||||
apiKey: form.value.apiKey || undefined,
|
||||
baseUrl: form.value.baseUrl,
|
||||
model: form.value.model,
|
||||
}
|
||||
}
|
||||
|
||||
/** 保存配置 */
|
||||
async function handleSave() {
|
||||
saving.value = true
|
||||
try {
|
||||
await saveAiConfig(buildPayload())
|
||||
message.success(t('ai.saveSuccess'))
|
||||
await loadConfig()
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('common.operationFailed'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 测试连接:先保存当前表单,再向 DeepSeek 发起测试请求 */
|
||||
async function handleTest() {
|
||||
testing.value = true
|
||||
try {
|
||||
await saveAiConfig(buildPayload())
|
||||
await testAiConfig()
|
||||
message.success(t('ai.testSuccess'))
|
||||
await loadConfig()
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('ai.testFailed'))
|
||||
} finally {
|
||||
testing.value = false
|
||||
// 测试连接也会产生使用记录,刷新使用情况
|
||||
await loadUsage()
|
||||
}
|
||||
}
|
||||
|
||||
/** 数字千分位格式化 */
|
||||
function formatNumber(value: number | null | undefined) {
|
||||
return value == null ? '0' : Number(value).toLocaleString()
|
||||
}
|
||||
|
||||
/** 使用概览卡片配置 */
|
||||
const overviewStats = computed(() => [
|
||||
{ key: 'calls', label: t('ai.usage.totalCalls'), value: usage.value?.summary.totalCalls ?? 0, icon: PulseOutline, color: '#2080f0' },
|
||||
{ key: 'success', label: t('ai.usage.successCalls'), value: usage.value?.summary.successCalls ?? 0, icon: CheckmarkCircleOutline, color: '#18a058' },
|
||||
{ key: 'failed', label: t('ai.usage.failedCalls'), value: usage.value?.summary.failedCalls ?? 0, icon: CloseCircleOutline, color: '#d03050' },
|
||||
{ key: 'total', label: t('ai.usage.totalTokens'), value: usage.value?.summary.totalTokens ?? 0, icon: StatsChartOutline, color: '#7c3aed' },
|
||||
])
|
||||
|
||||
/** Token 明细卡片配置 */
|
||||
const tokenStats = computed(() => [
|
||||
{ key: 'prompt', label: t('ai.usage.promptTokens'), value: usage.value?.summary.promptTokens ?? 0, icon: CloudUploadOutline, color: '#2080f0' },
|
||||
{ key: 'completion', label: t('ai.usage.completionTokens'), value: usage.value?.summary.completionTokens ?? 0, icon: CloudDownloadOutline, color: '#f0a020' },
|
||||
{ key: 'cached', label: t('ai.usage.cachedTokens'), value: usage.value?.summary.cachedTokens ?? 0, icon: FlashOutline, color: '#18a058' },
|
||||
])
|
||||
|
||||
/** 使用明细表格列定义(随语言切换响应式更新) */
|
||||
const usageColumns = computed<DataTableColumns<any>>(() => [
|
||||
{
|
||||
title: t('ai.usage.column.time'), key: 'createdAt', width: 160,
|
||||
render: (row) => {
|
||||
if (!row.createdAt) return '-'
|
||||
const [date, time] = String(row.createdAt).replace('T', ' ').split(' ')
|
||||
return h('div', { class: 'cell-time' }, [
|
||||
h('div', null, date),
|
||||
h('div', { class: 'cell-time-sub' }, (time || '').substring(0, 8)),
|
||||
])
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('ai.usage.column.type'), key: 'type', width: 120,
|
||||
render: (row) => h(NTag, { type: row.type === 'SUGGEST' ? 'info' : 'default', size: 'small', bordered: false },
|
||||
{ default: () => t(`ai.usage.type.${String(row.type).toLowerCase()}`) }),
|
||||
},
|
||||
{
|
||||
title: t('ai.usage.column.count'), key: 'transactionCount', width: 100, align: 'right', titleAlign: 'right',
|
||||
render: (row) => formatNumber(row.transactionCount),
|
||||
},
|
||||
{
|
||||
title: t('ai.usage.column.promptTokens'), key: 'promptTokens', width: 100, align: 'right', titleAlign: 'right',
|
||||
render: (row) => h('span', { class: 'cell-num' }, formatNumber(row.promptTokens)),
|
||||
},
|
||||
{
|
||||
title: t('ai.usage.column.completionTokens'), key: 'completionTokens', width: 100, align: 'right', titleAlign: 'right',
|
||||
render: (row) => h('span', { class: 'cell-num' }, formatNumber(row.completionTokens)),
|
||||
},
|
||||
{
|
||||
title: t('ai.usage.column.totalTokens'), key: 'totalTokens', width: 100, align: 'right', titleAlign: 'right',
|
||||
render: (row) => h('span', { class: 'cell-num cell-total' }, formatNumber(row.totalTokens)),
|
||||
},
|
||||
{
|
||||
title: t('ai.usage.column.duration'), key: 'durationMs', width: 100, align: 'right', titleAlign: 'right',
|
||||
render: (row) => (row.durationMs != null ? `${formatNumber(row.durationMs)} ms` : '-'),
|
||||
},
|
||||
{
|
||||
title: t('ai.usage.column.status'), key: 'success', width: 110, align: 'center', titleAlign: 'center',
|
||||
render: (row) => (row.success
|
||||
? h(NTag, { type: 'success', size: 'small', bordered: false }, { default: () => t('ai.usage.success') })
|
||||
: h('span', { title: row.errorMessage || '' },
|
||||
h(NTag, { type: 'error', size: 'small', bordered: false }, { default: () => t('ai.usage.failed') }))),
|
||||
},
|
||||
])
|
||||
|
||||
// 页面挂载时加载配置与使用情况
|
||||
onMounted(() => {
|
||||
loadConfig()
|
||||
loadUsage()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h2 style="margin: 0 0 16px;">{{ t('ai.title') }}</h2>
|
||||
|
||||
<!-- 模型配置 -->
|
||||
<NCard :bordered="false" class="config-card">
|
||||
<template #header>
|
||||
<NSpace align="center" :size="8">
|
||||
<NIcon :component="SettingsOutline" />
|
||||
<span>{{ t('ai.configTitle') }}</span>
|
||||
</NSpace>
|
||||
</template>
|
||||
<template #header-extra>
|
||||
<NTag :type="form.enabled ? 'success' : 'default'" size="small" :bordered="false">
|
||||
{{ form.enabled ? t('ai.enabledOn') : t('ai.enabledOff') }}
|
||||
</NTag>
|
||||
</template>
|
||||
|
||||
<NAlert type="info" :show-icon="true" style="margin-bottom: 20px;">
|
||||
{{ t('ai.intro') }}
|
||||
</NAlert>
|
||||
|
||||
<NForm label-placement="left" label-width="130">
|
||||
<NFormItem :label="t('ai.enabled')">
|
||||
<div class="switch-row">
|
||||
<NSwitch v-model:value="form.enabled" />
|
||||
<NText depth="3" style="font-size: 12px;">{{ t('ai.enabledHint') }}</NText>
|
||||
</div>
|
||||
</NFormItem>
|
||||
<NFormItem :label="t('ai.apiKey')">
|
||||
<NInput
|
||||
v-model:value="form.apiKey"
|
||||
type="password"
|
||||
show-password-on="click"
|
||||
:placeholder="hasApiKey ? t('ai.apiKeyKeep') : t('ai.apiKeyPlaceholder')"
|
||||
>
|
||||
<template #prefix>
|
||||
<NIcon :component="KeyOutline" />
|
||||
</template>
|
||||
</NInput>
|
||||
</NFormItem>
|
||||
<NFormItem :label="t('ai.baseUrl')">
|
||||
<NInput v-model:value="form.baseUrl" placeholder="https://api.deepseek.com">
|
||||
<template #prefix>
|
||||
<NIcon :component="LinkOutline" />
|
||||
</template>
|
||||
</NInput>
|
||||
</NFormItem>
|
||||
<NFormItem :label="t('ai.model')">
|
||||
<NInput v-model:value="form.model" placeholder="deepseek-chat">
|
||||
<template #prefix>
|
||||
<NIcon :component="CubeOutline" />
|
||||
</template>
|
||||
</NInput>
|
||||
</NFormItem>
|
||||
<NFormItem>
|
||||
<NSpace>
|
||||
<NButton type="primary" :loading="saving" @click="handleSave">
|
||||
<template #icon>
|
||||
<NIcon :component="SaveOutline" />
|
||||
</template>
|
||||
{{ t('ai.save') }}
|
||||
</NButton>
|
||||
<NButton :loading="testing" :disabled="!form.enabled" @click="handleTest">
|
||||
<template #icon>
|
||||
<NIcon :component="FlashOutline" />
|
||||
</template>
|
||||
{{ t('ai.test') }}
|
||||
</NButton>
|
||||
</NSpace>
|
||||
</NFormItem>
|
||||
</NForm>
|
||||
</NCard>
|
||||
|
||||
<!-- 使用情况:累计汇总 + 最近调用明细 -->
|
||||
<NCard :bordered="false" class="usage-card">
|
||||
<template #header>
|
||||
<NSpace justify="space-between" align="center" style="width: 100%;">
|
||||
<NSpace align="center" :size="8">
|
||||
<NIcon :component="StatsChartOutline" />
|
||||
<span>{{ t('ai.usage.title') }}</span>
|
||||
</NSpace>
|
||||
<NButton size="small" :loading="usageLoading" @click="loadUsage">
|
||||
<template #icon>
|
||||
<NIcon :component="TimeOutline" />
|
||||
</template>
|
||||
{{ t('ai.usage.refresh') }}
|
||||
</NButton>
|
||||
</NSpace>
|
||||
</template>
|
||||
|
||||
<!-- 调用概览 -->
|
||||
<NGrid cols="2 m:4" :x-gap="12" :y-gap="12">
|
||||
<NGridItem v-for="item in overviewStats" :key="item.key">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon" :style="{ background: item.color + '1a', color: item.color }">
|
||||
<NIcon size="20"><component :is="item.icon" /></NIcon>
|
||||
</div>
|
||||
<NStatistic
|
||||
:label="item.label"
|
||||
:value="formatNumber(item.value)"
|
||||
:value-style="{ color: item.color, fontSize: '20px', fontWeight: 600 }"
|
||||
/>
|
||||
</div>
|
||||
</NGridItem>
|
||||
</NGrid>
|
||||
|
||||
<!-- Token 明细 -->
|
||||
<NGrid cols="1 s:3" :x-gap="12" :y-gap="12" style="margin-top: 12px;">
|
||||
<NGridItem v-for="item in tokenStats" :key="item.key">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon" :style="{ background: item.color + '1a', color: item.color }">
|
||||
<NIcon size="20"><component :is="item.icon" /></NIcon>
|
||||
</div>
|
||||
<NStatistic
|
||||
:label="item.label"
|
||||
:value="formatNumber(item.value)"
|
||||
:value-style="{ color: item.color, fontSize: '20px', fontWeight: 600 }"
|
||||
/>
|
||||
</div>
|
||||
</NGridItem>
|
||||
</NGrid>
|
||||
|
||||
<!-- 最近调用明细 -->
|
||||
<div class="table-title">{{ t('ai.usage.recentTitle') }}</div>
|
||||
<NDataTable
|
||||
:columns="usageColumns"
|
||||
:data="usage?.recent ?? []"
|
||||
:loading="usageLoading"
|
||||
size="small"
|
||||
:bordered="false"
|
||||
:striped="true"
|
||||
class="usage-table"
|
||||
>
|
||||
<template #empty>
|
||||
<NEmpty :description="t('ai.usage.empty')" />
|
||||
</template>
|
||||
</NDataTable>
|
||||
</NCard>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.config-card {
|
||||
max-width: 720px;
|
||||
}
|
||||
.usage-card {
|
||||
max-width: 960px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.switch-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.table-title {
|
||||
margin: 22px 0 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: #666;
|
||||
}
|
||||
.stat-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 10px;
|
||||
background: rgba(0, 0, 0, 0.02);
|
||||
transition: background 0.2s ease;
|
||||
}
|
||||
.stat-card:hover {
|
||||
background: rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
.stat-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border-radius: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.cell-time {
|
||||
line-height: 1.35;
|
||||
}
|
||||
.cell-time-sub {
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
}
|
||||
.cell-num {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.cell-total {
|
||||
font-weight: 600;
|
||||
}
|
||||
/* 表头与行视觉优化 */
|
||||
.usage-table :deep(.n-data-table-th) {
|
||||
background-color: rgba(0, 0, 0, 0.025);
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
}
|
||||
.usage-table :deep(.n-data-table-td) {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
</style>
|
||||
@@ -104,8 +104,8 @@ function resetFilters() {
|
||||
}
|
||||
|
||||
// 默认分类
|
||||
const expenseCategories = ref<{ label: string; value: number }[]>([])
|
||||
const incomeCategories = ref<{ label: string; value: number }[]>([])
|
||||
const expenseCategories = ref<{ label: string; value: number; icon: string }[]>([])
|
||||
const incomeCategories = ref<{ label: string; value: number; icon: string }[]>([])
|
||||
const expenseCategoryId = ref<number | null>(null)
|
||||
const incomeCategoryId = ref<number | null>(null)
|
||||
|
||||
@@ -225,13 +225,21 @@ const columns = computed<DataTableColumns<ParsedBillRow>>(() => [
|
||||
async function loadCategories() {
|
||||
try {
|
||||
const [expenseRes, incomeRes]: any = await Promise.all([getCategoryList('EXPENSE'), getCategoryList('INCOME')])
|
||||
expenseCategories.value = (expenseRes.data || []).map((c: any) => ({ label: c.name, value: c.id }))
|
||||
incomeCategories.value = (incomeRes.data || []).map((c: any) => ({ label: c.name, value: c.id }))
|
||||
expenseCategories.value = (expenseRes.data || []).map((c: any) => ({ label: c.name, value: c.id, icon: c.icon || '' }))
|
||||
incomeCategories.value = (incomeRes.data || []).map((c: any) => ({ label: c.name, value: c.id, icon: c.icon || '' }))
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('import.loadCategoriesFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
/** 分类下拉项渲染:图标 + 名称 */
|
||||
function renderCategoryLabel(option: any) {
|
||||
return h('span', null, [
|
||||
option.icon ? h('span', { style: { marginRight: '6px' } }, option.icon) : null,
|
||||
option.label,
|
||||
])
|
||||
}
|
||||
|
||||
/** 加载标签选项 */
|
||||
async function loadTags() {
|
||||
try {
|
||||
@@ -435,6 +443,7 @@ watch(
|
||||
<NSelect
|
||||
v-model:value="expenseCategoryId"
|
||||
:options="expenseCategories"
|
||||
:render-label="renderCategoryLabel"
|
||||
filterable
|
||||
clearable
|
||||
:placeholder="t('import.notSetCategory')"
|
||||
@@ -444,6 +453,7 @@ watch(
|
||||
<NSelect
|
||||
v-model:value="incomeCategoryId"
|
||||
:options="incomeCategories"
|
||||
:render-label="renderCategoryLabel"
|
||||
filterable
|
||||
clearable
|
||||
:placeholder="t('import.notSetCategory')"
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
import { h, computed } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { NLayout, NLayoutSider, NLayoutContent, NLayoutHeader, NMenu, NButton, NSpace, NIcon } from 'naive-ui'
|
||||
import { NLayout, NLayoutSider, NLayoutContent, NLayoutHeader, NMenu, NSpace, NIcon, NDropdown } from 'naive-ui'
|
||||
import type { MenuOption } from 'naive-ui'
|
||||
import { BarChartOutline, ListOutline, FolderOpenOutline, PricetagsOutline, LogOutOutline } from '@vicons/ionicons5'
|
||||
import { BarChartOutline, ListOutline, FolderOpenOutline, PricetagsOutline, SparklesOutline, LogOutOutline, ChevronDownOutline } from '@vicons/ionicons5'
|
||||
import { useUserStore } from '../store/user'
|
||||
import LocaleSwitch from '../components/LocaleSwitch.vue'
|
||||
|
||||
@@ -43,6 +43,21 @@ function handleMenuUpdate(key: string) {
|
||||
router.push(`/${key}`)
|
||||
}
|
||||
|
||||
// 顶部用户下拉菜单配置项(随语言切换响应式更新)
|
||||
const userMenuOptions = computed(() => [
|
||||
{ label: t('layout.aiSettings'), key: 'ai-settings', icon: renderIcon(SparklesOutline) },
|
||||
{ label: t('layout.logout'), key: 'logout', icon: renderIcon(LogOutOutline) },
|
||||
])
|
||||
|
||||
/** 用户下拉菜单选择事件:跳转 AI 设置或退出登录 */
|
||||
function handleUserMenuSelect(key: string) {
|
||||
if (key === 'ai-settings') {
|
||||
router.push('/ai-settings')
|
||||
} else if (key === 'logout') {
|
||||
handleLogout()
|
||||
}
|
||||
}
|
||||
|
||||
/** 退出登录:清空用户状态并跳转到登录页 */
|
||||
function handleLogout() {
|
||||
userStore.logout()
|
||||
@@ -70,17 +85,16 @@ function handleLogout() {
|
||||
/>
|
||||
</NLayoutSider>
|
||||
<NLayout>
|
||||
<!-- 顶部栏:显示用户名和退出按钮 -->
|
||||
<NLayoutHeader bordered style="padding: 12px 24px; display: flex; justify-content: space-between; align-items: center;">
|
||||
<span style="font-size: 16px; font-weight: 500;">{{ userStore.nickname || t('layout.user') }}</span>
|
||||
<NSpace align="center">
|
||||
<!-- 顶部栏:用户下拉菜单与语言切换 -->
|
||||
<NLayoutHeader bordered style="padding: 12px 24px; display: flex; justify-content: flex-end; align-items: center;">
|
||||
<NSpace align="center" :size="16">
|
||||
<LocaleSwitch />
|
||||
<NButton quaternary size="small" @click="handleLogout">
|
||||
<template #icon>
|
||||
<NIcon :component="LogOutOutline" />
|
||||
</template>
|
||||
{{ t('layout.logout') }}
|
||||
</NButton>
|
||||
<NDropdown :options="userMenuOptions" @select="handleUserMenuSelect">
|
||||
<span style="font-size: 16px; font-weight: 500; cursor: pointer; display: inline-flex; align-items: center;">
|
||||
{{ userStore.nickname || t('layout.user') }}
|
||||
<NIcon :component="ChevronDownOutline" size="16" style="margin-left: 4px;" />
|
||||
</span>
|
||||
</NDropdown>
|
||||
</NSpace>
|
||||
</NLayoutHeader>
|
||||
<!-- 子路由内容渲染区域 -->
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
// 收支记录管理组件:展示交易记录列表(分页),支持新增、编辑、删除、多条件筛选
|
||||
import { ref, onMounted, computed, h, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useMessage, useDialog, NButton, NSpace, NDataTable, NTag, NModal, NForm, NFormItem, NInput, NInputNumber, NSelect, NDatePicker, NPagination, NCard, NSwitch, NIcon, NPopover } from 'naive-ui'
|
||||
import { EyeOutline, EyeOffOutline } from '@vicons/ionicons5'
|
||||
import type { DataTableColumns } from 'naive-ui'
|
||||
import { useMessage, useDialog, NButton, NSpace, NDataTable, NTag, NModal, NForm, NFormItem, NInput, NInputNumber, NSelect, NDatePicker, NPagination, NCard, NSwitch, NIcon, NPopover, NAutoComplete, NAlert, NDescriptions, NDescriptionsItem, NDivider, NDropdown } from 'naive-ui'
|
||||
import { EyeOutline, EyeOffOutline, CloseCircleOutline, SparklesOutline, BulbOutline } from '@vicons/ionicons5'
|
||||
import type { DataTableColumns, AutoCompleteOption } from 'naive-ui'
|
||||
import { getTransactionPage, createTransaction, updateTransaction, deleteTransaction, exportTransaction, toggleTransactionStats, toggleRemarkHidden, batchUpdateCategory, batchTags } from '../api/transaction'
|
||||
import { getAiConfig, suggestByAi, applyAiSuggestions, queryByAi, parseRecordByAi } from '../api/ai'
|
||||
import type { AiSuggestion, AiQueryResult, AiRecordResult } from '../api/ai'
|
||||
import { getCategoryList } from '../api/category'
|
||||
import { getTagList } from '../api/tag'
|
||||
import BillImportModal from './BillImportModal.vue'
|
||||
@@ -78,6 +80,24 @@ const loading = ref(false) // 列表加载状态
|
||||
const showModal = ref(false) // 新增/编辑弹窗显示状态
|
||||
const showImportModal = ref(false) // 账单导入弹窗显示状态
|
||||
const showBatchModal = ref(false) // 批量设置分类弹窗显示状态
|
||||
const showAiModal = ref(false) // AI 建议弹窗显示状态
|
||||
const aiEnabled = ref(false) // AI 建议是否启用
|
||||
const aiLoading = ref(false) // AI 建议生成状态
|
||||
const aiApplying = ref(false) // AI 建议应用状态
|
||||
const aiSuggestions = ref<AiSuggestion[]>([]) // AI 建议列表
|
||||
const aiQueryText = ref('') // AI 自然语言查询输入
|
||||
const aiQuerying = ref(false) // AI 查询解析状态
|
||||
const showAiQueryModal = ref(false) // AI 查询结果弹窗显示状态
|
||||
const aiQueryResult = ref<AiQueryResult | null>(null) // AI 查询解析结果
|
||||
// AI 查询历史存储键与上限
|
||||
const AI_QUERY_HISTORY_KEY = 'finance.transaction.aiQueryHistory'
|
||||
const AI_QUERY_HISTORY_MAX = 10
|
||||
// 下拉中“清空历史”选项的哨兵值
|
||||
const CLEAR_AI_QUERY_HISTORY = '__clear_ai_query_history__'
|
||||
const aiQueryHistory = ref<string[]>([]) // AI 查询历史(最近使用,最新在前)
|
||||
const showAiRecordModal = ref(false) // AI 记账弹窗显示状态
|
||||
const aiRecordText = ref('') // AI 记账输入
|
||||
const aiRecording = ref(false) // AI 记账解析状态
|
||||
const showRawModal = ref(false) // 原始账单数据弹窗显示状态
|
||||
const rawDataText = ref('') // 格式化后的原始账单数据文本
|
||||
const batchExpenseCategoryId = ref<number | null>(null) // 批量设置的支出分类
|
||||
@@ -131,6 +151,12 @@ const filterPaymentMethod = ref<string[]>([]) // 支付方式筛选(多选)
|
||||
const filterDateRange = ref<[number, number] | null>(null) // 日期范围筛选(起止时间戳)
|
||||
const filterIncludeInStats = ref<string | null>(null) // 计入统计筛选:null-全部,'true'-计入,'false'-不计入
|
||||
const filterRemark = ref('') // 备注关键字搜索
|
||||
// 备注关键词历史存储键与上限
|
||||
const REMARK_HISTORY_KEY = 'finance.transaction.remarkHistory'
|
||||
const REMARK_HISTORY_MAX = 10
|
||||
// 下拉中“清空历史”选项的哨兵值
|
||||
const CLEAR_REMARK_HISTORY = '__clear_remark_history__'
|
||||
const remarkHistory = ref<string[]>([]) // 备注关键词历史(最近输入,最新在前)
|
||||
const filterMinAmount = ref<number | null>(null) // 最小金额筛选
|
||||
const filterMaxAmount = ref<number | null>(null) // 最大金额筛选
|
||||
const filterTag = ref<number[]>([]) // 标签筛选(多选)
|
||||
@@ -232,6 +258,103 @@ watch(
|
||||
{ deep: true },
|
||||
)
|
||||
|
||||
/** 从 localStorage 读取备注关键词历史,忽略损坏数据 */
|
||||
function loadRemarkHistory() {
|
||||
try {
|
||||
const raw = localStorage.getItem(REMARK_HISTORY_KEY)
|
||||
const parsed = raw ? JSON.parse(raw) : []
|
||||
remarkHistory.value = Array.isArray(parsed)
|
||||
? parsed.filter((item) => typeof item === 'string' && item.trim()).slice(0, REMARK_HISTORY_MAX)
|
||||
: []
|
||||
} catch (e) {
|
||||
remarkHistory.value = []
|
||||
}
|
||||
}
|
||||
|
||||
/** 记录一次备注关键词:去重(忽略大小写)、最新在前、上限 10 条 */
|
||||
function recordRemarkKeyword() {
|
||||
const value = filterRemark.value.trim()
|
||||
if (!value) return
|
||||
const rest = remarkHistory.value.filter((item) => item.toLowerCase() !== value.toLowerCase())
|
||||
remarkHistory.value = [value, ...rest].slice(0, REMARK_HISTORY_MAX)
|
||||
try {
|
||||
localStorage.setItem(REMARK_HISTORY_KEY, JSON.stringify(remarkHistory.value))
|
||||
} catch (e) {
|
||||
// 忽略写入失败
|
||||
}
|
||||
}
|
||||
|
||||
/** 清空备注关键词历史 */
|
||||
function clearRemarkHistory() {
|
||||
remarkHistory.value = []
|
||||
try {
|
||||
localStorage.removeItem(REMARK_HISTORY_KEY)
|
||||
} catch (e) {
|
||||
// 忽略删除失败
|
||||
}
|
||||
}
|
||||
|
||||
// 备注历史下拉选项:按当前输入过滤历史项(忽略大小写),历史非空时末尾追加“清空历史”
|
||||
const remarkOptions = computed<AutoCompleteOption[]>(() => {
|
||||
const keyword = filterRemark.value.trim().toLowerCase()
|
||||
const options: AutoCompleteOption[] = remarkHistory.value
|
||||
.filter((item) => item.toLowerCase().includes(keyword))
|
||||
.map((item) => ({ label: item, value: item }))
|
||||
if (remarkHistory.value.length > 0) {
|
||||
options.push({ label: CLEAR_REMARK_HISTORY, value: CLEAR_REMARK_HISTORY })
|
||||
}
|
||||
return options
|
||||
})
|
||||
|
||||
/** 输入同步:清空项执行清空,其余写入输入框(NAutoComplete 回调传入的是选项 label) */
|
||||
function handleRemarkInput(value: string | null) {
|
||||
if (value === CLEAR_REMARK_HISTORY) {
|
||||
clearRemarkHistory()
|
||||
return
|
||||
}
|
||||
filterRemark.value = value || ''
|
||||
}
|
||||
|
||||
/** 选中历史项:填入并立即搜索 */
|
||||
function handleRemarkSelect(value: string) {
|
||||
if (value === CLEAR_REMARK_HISTORY) {
|
||||
clearRemarkHistory()
|
||||
return
|
||||
}
|
||||
filterRemark.value = value
|
||||
handleSearch()
|
||||
}
|
||||
|
||||
/** 失焦时记录当前备注关键词 */
|
||||
function handleRemarkBlur() {
|
||||
recordRemarkKeyword()
|
||||
}
|
||||
|
||||
/** 回车时记录关键词并搜索(阻止 NAutoComplete 内部选中建议项,保持原回车搜索语义) */
|
||||
function handleRemarkKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter') {
|
||||
e.stopPropagation()
|
||||
recordRemarkKeyword()
|
||||
handleSearch()
|
||||
}
|
||||
}
|
||||
|
||||
/** 聚焦即展示历史下拉(NAutoComplete 默认仅在输入非空时展示) */
|
||||
function showRemarkMenu() {
|
||||
return true
|
||||
}
|
||||
|
||||
/** 渲染下拉选项,清空项使用弱化样式与图标 */
|
||||
function renderRemarkLabel(option: AutoCompleteOption) {
|
||||
if (String(option.value) === CLEAR_REMARK_HISTORY) {
|
||||
return h('span', { style: { display: 'flex', alignItems: 'center', gap: '4px', color: '#999' } }, [
|
||||
h(NIcon, { size: 16 }, { default: () => h(CloseCircleOutline) }),
|
||||
t('transaction.remarkHistoryClear'),
|
||||
])
|
||||
}
|
||||
return option.label as string
|
||||
}
|
||||
|
||||
/** 将时间戳格式化为 ISO 格式的日期时间字符串(YYYY-MM-DDTHH:mm:ss) */
|
||||
function formatTimestamp(ts: number, isEnd = false): string {
|
||||
const d = new Date(ts)
|
||||
@@ -593,6 +716,396 @@ async function handleToggleStats(row: TransactionItem, value: boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 加载 AI 启用状态,用于控制批量设置中的入口显示 */
|
||||
async function loadAiConfig() {
|
||||
try {
|
||||
const res: any = await getAiConfig()
|
||||
aiEnabled.value = !!res.data.enabled
|
||||
} catch (e) {
|
||||
// 静默处理,AI 入口保持隐藏
|
||||
aiEnabled.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 请求 AI 建议:对当前表格展示的记录生成分类与标签建议 */
|
||||
async function handleAiSuggest() {
|
||||
if (transactions.value.length === 0) {
|
||||
message.warning(t('transaction.noRecordsToSet'))
|
||||
return
|
||||
}
|
||||
aiLoading.value = true
|
||||
try {
|
||||
const ids = transactions.value.map((t) => t.id)
|
||||
const res: any = await suggestByAi(ids)
|
||||
aiSuggestions.value = res.data || []
|
||||
if (aiSuggestions.value.length === 0) {
|
||||
message.warning(t('ai.noSuggestion'))
|
||||
return
|
||||
}
|
||||
showBatchModal.value = false
|
||||
showAiModal.value = true
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('ai.suggestFailed'))
|
||||
} finally {
|
||||
aiLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 一键应用全部 AI 建议:覆盖分类并追加标签 */
|
||||
async function handleAiApply() {
|
||||
if (aiSuggestions.value.length === 0) {
|
||||
return
|
||||
}
|
||||
aiApplying.value = true
|
||||
try {
|
||||
const payload = aiSuggestions.value.map((s) => ({
|
||||
transactionId: s.transactionId,
|
||||
categoryId: s.categoryId,
|
||||
tagIds: s.tagIds || [],
|
||||
}))
|
||||
const res: any = await applyAiSuggestions(payload)
|
||||
message.success(t('ai.applySuccess', { count: res.data }))
|
||||
showAiModal.value = false
|
||||
await fetchData()
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('ai.applyFailed'))
|
||||
} finally {
|
||||
aiApplying.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开 AI 记账弹窗 */
|
||||
function handleAiRecordOpen() {
|
||||
if (!aiEnabled.value) {
|
||||
message.warning(t('ai.needConfig'))
|
||||
return
|
||||
}
|
||||
aiRecordText.value = ''
|
||||
showAiRecordModal.value = true
|
||||
}
|
||||
|
||||
/** 解析自然语言记账并预填新增表单 */
|
||||
async function handleAiRecordParse() {
|
||||
const text = aiRecordText.value.trim()
|
||||
if (!text) {
|
||||
message.warning(t('ai.record.emptyInput'))
|
||||
return
|
||||
}
|
||||
aiRecording.value = true
|
||||
try {
|
||||
const res: any = await parseRecordByAi(text)
|
||||
const r: AiRecordResult = res.data
|
||||
editingId.value = null
|
||||
form.value = {
|
||||
categoryId: r.categoryId ?? null,
|
||||
type: r.type || 'EXPENSE',
|
||||
amount: r.amount ?? null,
|
||||
paymentMethod: r.paymentMethod || '',
|
||||
remark: r.remark || '',
|
||||
transactionTime: r.transactionTime ? new Date(r.transactionTime).getTime() : Date.now(),
|
||||
includeInStats: r.includeInStats ?? true,
|
||||
tagIds: r.tagIds || [],
|
||||
}
|
||||
showAiRecordModal.value = false
|
||||
showModal.value = true
|
||||
if (r.summary) {
|
||||
message.info(r.summary)
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('ai.record.failed'))
|
||||
} finally {
|
||||
aiRecording.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 请求 AI 解析自然语言查询 */
|
||||
async function handleAiQuery() {
|
||||
if (!aiEnabled.value) {
|
||||
message.warning(t('ai.needConfig'))
|
||||
return
|
||||
}
|
||||
const text = aiQueryText.value.trim()
|
||||
if (!text) {
|
||||
message.warning(t('ai.query.emptyInput'))
|
||||
return
|
||||
}
|
||||
recordAiQueryHistory()
|
||||
aiQuerying.value = true
|
||||
try {
|
||||
const res: any = await queryByAi(text)
|
||||
aiQueryResult.value = res.data
|
||||
showAiQueryModal.value = true
|
||||
} catch (e: any) {
|
||||
message.error(e.message || t('ai.query.failed'))
|
||||
} finally {
|
||||
aiQuerying.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 将 AI 解析结果应用到筛选条件并查询 */
|
||||
function applyAiQuery() {
|
||||
const r = aiQueryResult.value
|
||||
if (!r) return
|
||||
filterType.value = r.types || []
|
||||
const categoryIds = [...(r.categoryIds || [])]
|
||||
if (r.uncategorized) categoryIds.push(0)
|
||||
filterCategory.value = categoryIds
|
||||
filterPaymentMethod.value = r.paymentMethods || []
|
||||
filterDateRange.value = r.startTime && r.endTime
|
||||
? [new Date(r.startTime).getTime(), new Date(r.endTime).getTime()]
|
||||
: null
|
||||
filterIncludeInStats.value = r.includeInStats == null ? null : (r.includeInStats ? 'true' : 'false')
|
||||
filterMinAmount.value = r.minAmount ?? null
|
||||
filterMaxAmount.value = r.maxAmount ?? null
|
||||
filterRemark.value = r.remark || ''
|
||||
filterTag.value = r.tagIds || []
|
||||
showAiQueryModal.value = false
|
||||
handleSearch()
|
||||
message.success(t('ai.query.applied'))
|
||||
}
|
||||
|
||||
/** 解析结果是否为空(无任何可用筛选条件) */
|
||||
const aiQueryEmpty = computed(() => {
|
||||
const r = aiQueryResult.value
|
||||
if (!r) return true
|
||||
return (r.types?.length ?? 0) === 0
|
||||
&& (r.categoryIds?.length ?? 0) === 0
|
||||
&& !r.uncategorized
|
||||
&& (r.tagIds?.length ?? 0) === 0
|
||||
&& (r.paymentMethods?.length ?? 0) === 0
|
||||
&& !r.startTime
|
||||
&& r.minAmount == null
|
||||
&& r.maxAmount == null
|
||||
&& !r.remark
|
||||
&& r.includeInStats == null
|
||||
})
|
||||
|
||||
/** 格式化解析结果中的时间用于展示 */
|
||||
function formatAiDate(value: string | null | undefined) {
|
||||
return value ? value.replace('T', ' ').substring(0, 16) : ''
|
||||
}
|
||||
|
||||
/** AI 查询示例(从 i18n 拆分为数组) */
|
||||
const queryExamples = computed(() => t('ai.query.examples').split('|'))
|
||||
|
||||
/** AI 查询示例下拉选项 */
|
||||
const exampleOptions = computed(() => queryExamples.value.map((example) => ({ label: example, key: example })))
|
||||
|
||||
/** 选择示例后填入输入框 */
|
||||
function handleExampleSelect(key: string) {
|
||||
aiQueryText.value = key
|
||||
}
|
||||
|
||||
/** 从 localStorage 读取 AI 查询历史,忽略损坏数据 */
|
||||
function loadAiQueryHistory() {
|
||||
try {
|
||||
const raw = localStorage.getItem(AI_QUERY_HISTORY_KEY)
|
||||
const parsed = raw ? JSON.parse(raw) : []
|
||||
aiQueryHistory.value = Array.isArray(parsed)
|
||||
? parsed.filter((item) => typeof item === 'string' && item.trim()).slice(0, AI_QUERY_HISTORY_MAX)
|
||||
: []
|
||||
} catch (e) {
|
||||
aiQueryHistory.value = []
|
||||
}
|
||||
}
|
||||
|
||||
/** 记录一次 AI 查询文本:去重(忽略大小写)、最新在前、上限 10 条 */
|
||||
function recordAiQueryHistory() {
|
||||
const value = aiQueryText.value.trim()
|
||||
if (!value) return
|
||||
const rest = aiQueryHistory.value.filter((item) => item.toLowerCase() !== value.toLowerCase())
|
||||
aiQueryHistory.value = [value, ...rest].slice(0, AI_QUERY_HISTORY_MAX)
|
||||
try {
|
||||
localStorage.setItem(AI_QUERY_HISTORY_KEY, JSON.stringify(aiQueryHistory.value))
|
||||
} catch (e) {
|
||||
// 忽略写入失败
|
||||
}
|
||||
}
|
||||
|
||||
/** 清空 AI 查询历史 */
|
||||
function clearAiQueryHistory() {
|
||||
aiQueryHistory.value = []
|
||||
try {
|
||||
localStorage.removeItem(AI_QUERY_HISTORY_KEY)
|
||||
} catch (e) {
|
||||
// 忽略删除失败
|
||||
}
|
||||
}
|
||||
|
||||
// AI 查询历史下拉选项:按当前输入过滤历史项(忽略大小写),历史非空时末尾追加“清空历史”
|
||||
const aiQueryOptions = computed<AutoCompleteOption[]>(() => {
|
||||
const keyword = aiQueryText.value.trim().toLowerCase()
|
||||
const options: AutoCompleteOption[] = aiQueryHistory.value
|
||||
.filter((item) => item.toLowerCase().includes(keyword))
|
||||
.map((item) => ({ label: item, value: item }))
|
||||
if (aiQueryHistory.value.length > 0) {
|
||||
options.push({ label: CLEAR_AI_QUERY_HISTORY, value: CLEAR_AI_QUERY_HISTORY })
|
||||
}
|
||||
return options
|
||||
})
|
||||
|
||||
/** 输入同步:清空项执行清空,其余写入输入框(NAutoComplete 回调传入的是选项 label) */
|
||||
function handleAiQueryInput(value: string | null) {
|
||||
if (value === CLEAR_AI_QUERY_HISTORY) {
|
||||
clearAiQueryHistory()
|
||||
return
|
||||
}
|
||||
aiQueryText.value = value || ''
|
||||
}
|
||||
|
||||
/** 选中历史项:填入并立即发起查询 */
|
||||
function handleAiQuerySelect(value: string) {
|
||||
if (value === CLEAR_AI_QUERY_HISTORY) {
|
||||
clearAiQueryHistory()
|
||||
return
|
||||
}
|
||||
aiQueryText.value = value
|
||||
handleAiQuery()
|
||||
}
|
||||
|
||||
/** 回车时发起查询(阻止 NAutoComplete 内部选中建议项) */
|
||||
function handleAiQueryKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter') {
|
||||
e.stopPropagation()
|
||||
handleAiQuery()
|
||||
}
|
||||
}
|
||||
|
||||
/** 聚焦即展示历史下拉 */
|
||||
function showAiQueryMenu() {
|
||||
return true
|
||||
}
|
||||
|
||||
/** 渲染下拉选项,清空项使用弱化样式与图标 */
|
||||
function renderAiQueryLabel(option: AutoCompleteOption) {
|
||||
if (String(option.value) === CLEAR_AI_QUERY_HISTORY) {
|
||||
return h('span', { style: { display: 'flex', alignItems: 'center', gap: '4px', color: '#999' } }, [
|
||||
h(NIcon, { size: 16 }, { default: () => h(CloseCircleOutline) }),
|
||||
t('ai.query.clearHistory'),
|
||||
])
|
||||
}
|
||||
return option.label as string
|
||||
}
|
||||
|
||||
/** 将时间戳格式化为 yyyy-MM-dd */
|
||||
function formatDateLabel(ts: number) {
|
||||
const d = new Date(ts)
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
}
|
||||
|
||||
/** 已激活的筛选条件标签(可单独移除) */
|
||||
const activeFilterTags = computed(() => {
|
||||
const tags: { key: string; label: string; clear: () => void }[] = []
|
||||
|
||||
filterType.value.forEach((v) => {
|
||||
tags.push({
|
||||
key: `type:${v}`,
|
||||
label: v === 'INCOME' ? t('common.types.income') : t('common.types.expense'),
|
||||
clear: () => { filterType.value = filterType.value.filter((x) => x !== v) },
|
||||
})
|
||||
})
|
||||
|
||||
filterCategory.value.forEach((id) => {
|
||||
const name = id === 0
|
||||
? t('transaction.uncategorized')
|
||||
: categories.value.find((c) => c.value === id)?.label || String(id)
|
||||
tags.push({
|
||||
key: `category:${id}`,
|
||||
label: name,
|
||||
clear: () => { filterCategory.value = filterCategory.value.filter((x) => x !== id) },
|
||||
})
|
||||
})
|
||||
|
||||
if (filterDateRange.value) {
|
||||
tags.push({
|
||||
key: 'date',
|
||||
label: `${formatDateLabel(filterDateRange.value[0])} ~ ${formatDateLabel(filterDateRange.value[1])}`,
|
||||
clear: () => { filterDateRange.value = null },
|
||||
})
|
||||
}
|
||||
|
||||
if (filterRemark.value.trim()) {
|
||||
tags.push({
|
||||
key: 'remark',
|
||||
label: `${t('transaction.column.remark')}: ${filterRemark.value.trim()}`,
|
||||
clear: () => { filterRemark.value = '' },
|
||||
})
|
||||
}
|
||||
|
||||
filterPaymentMethod.value.forEach((v) => {
|
||||
tags.push({
|
||||
key: `payment:${v}`,
|
||||
label: getPaymentLabel(v),
|
||||
clear: () => { filterPaymentMethod.value = filterPaymentMethod.value.filter((x) => x !== v) },
|
||||
})
|
||||
})
|
||||
|
||||
filterTag.value.forEach((id) => {
|
||||
const name = allTags.value.find((tag) => tag.id === id)?.name || String(id)
|
||||
tags.push({
|
||||
key: `tag:${id}`,
|
||||
label: name,
|
||||
clear: () => { filterTag.value = filterTag.value.filter((x) => x !== id) },
|
||||
})
|
||||
})
|
||||
|
||||
if (filterIncludeInStats.value !== null) {
|
||||
tags.push({
|
||||
key: 'includeInStats',
|
||||
label: filterIncludeInStats.value === 'true' ? t('transaction.includeFilter.yes') : t('transaction.includeFilter.no'),
|
||||
clear: () => { filterIncludeInStats.value = null },
|
||||
})
|
||||
}
|
||||
|
||||
if (filterMinAmount.value != null || filterMaxAmount.value != null) {
|
||||
tags.push({
|
||||
key: 'amount',
|
||||
label: `${t('transaction.amountRange')}: ${filterMinAmount.value ?? 0} ~ ${filterMaxAmount.value ?? '∞'}`,
|
||||
clear: () => { filterMinAmount.value = null; filterMaxAmount.value = null },
|
||||
})
|
||||
}
|
||||
|
||||
return tags
|
||||
})
|
||||
|
||||
/** 移除单个筛选条件后自动重查 */
|
||||
function applyTagClear(tag: { clear: () => void }) {
|
||||
tag.clear()
|
||||
handleSearch()
|
||||
}
|
||||
|
||||
/** AI 建议行:合并交易记录信息用于展示 */
|
||||
const aiRows = computed(() =>
|
||||
aiSuggestions.value.map((s) => ({
|
||||
...s,
|
||||
transaction: transactions.value.find((t) => t.id === s.transactionId) || null,
|
||||
})),
|
||||
)
|
||||
|
||||
/** AI 建议表格列定义(随语言切换响应式更新) */
|
||||
const aiColumns = computed<DataTableColumns<any>>(() => [
|
||||
{
|
||||
title: t('ai.column.record'), key: 'record', minWidth: 200,
|
||||
render: (row) => {
|
||||
const tx = row.transaction
|
||||
if (!tx) return `#${row.transactionId}`
|
||||
const time = tx.transactionTime?.replace('T', ' ').substring(0, 16) || '-'
|
||||
const sign = tx.type === 'INCOME' ? '+' : '-'
|
||||
return h('div', null, [
|
||||
h('div', null, `${time} ${sign}${tx.amount.toFixed(2)}`),
|
||||
h('div', { style: { color: '#999', fontSize: '12px' } }, tx.remark || '-'),
|
||||
])
|
||||
},
|
||||
},
|
||||
{ title: t('ai.column.category'), key: 'category', width: 130, render: (row) => row.categoryName || '-' },
|
||||
{
|
||||
title: t('ai.column.tags'), key: 'tags', minWidth: 150,
|
||||
render: (row) => (row.tagNames && row.tagNames.length > 0 ? row.tagNames.join('、') : '-'),
|
||||
},
|
||||
{ title: t('ai.column.reason'), key: 'reason', minWidth: 180, ellipsis: { tooltip: true } },
|
||||
])
|
||||
|
||||
/** 打开批量设置分类弹窗 */
|
||||
function handleBatchOpen() {
|
||||
if (transactions.value.length === 0) {
|
||||
@@ -678,6 +1191,9 @@ async function handleExport() {
|
||||
// 组件挂载时加载分类和交易记录
|
||||
onMounted(() => {
|
||||
loadFilterPrefs()
|
||||
loadRemarkHistory()
|
||||
loadAiQueryHistory()
|
||||
loadAiConfig()
|
||||
fetchCategories()
|
||||
fetchTags()
|
||||
fetchData()
|
||||
@@ -686,22 +1202,63 @@ onMounted(() => {
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<!-- 顶部:标题和新增按钮 -->
|
||||
<NSpace justify="space-between" style="margin-bottom: 16px;">
|
||||
<!-- 顶部:标题和操作按钮 -->
|
||||
<NSpace justify="space-between" align="center" style="margin-bottom: 16px;" :wrap="true">
|
||||
<h2 style="margin: 0;">{{ t('transaction.title') }}</h2>
|
||||
<NSpace align="center">
|
||||
<NSpace align="center" :wrap="true">
|
||||
<span style="color: #999; font-size: 13px;">{{ t('transaction.sortLabel') }}</span>
|
||||
<NSelect v-model:value="sortValue" :options="sortOptions" style="width: 170px;" />
|
||||
<NDivider vertical style="margin: 0 4px;" />
|
||||
<NButton @click="handleBatchOpen">{{ t('transaction.batchSet') }}</NButton>
|
||||
<NButton @click="showImportModal = true">{{ t('transaction.importBill') }}</NButton>
|
||||
<NButton @click="handleExport">{{ t('transaction.exportExcel') }}</NButton>
|
||||
<NButton v-if="aiEnabled" @click="handleAiRecordOpen">
|
||||
<template #icon>
|
||||
<NIcon :component="SparklesOutline" />
|
||||
</template>
|
||||
{{ t('ai.record.button') }}
|
||||
</NButton>
|
||||
<NButton type="primary" @click="handleAdd">{{ t('transaction.addRecord') }}</NButton>
|
||||
</NSpace>
|
||||
</NSpace>
|
||||
|
||||
<!-- 筛选条件区域:常用条件常驻,其余收进「更多筛选」 -->
|
||||
<!-- 查询与筛选 -->
|
||||
<NCard :bordered="false" style="margin-bottom: 16px;">
|
||||
<NSpace align="center" :wrap="true" :size="[12, 12]">
|
||||
<!-- AI 智能查询(仅启用时显示) -->
|
||||
<template v-if="aiEnabled">
|
||||
<NSpace align="center" :wrap="true" :size="[12, 8]">
|
||||
<NAutoComplete
|
||||
:value="aiQueryText"
|
||||
:options="aiQueryOptions"
|
||||
:get-show="showAiQueryMenu"
|
||||
:render-label="renderAiQueryLabel"
|
||||
:input-props="{ onKeydown: handleAiQueryKeydown }"
|
||||
clearable
|
||||
:placeholder="t('ai.query.placeholder')"
|
||||
style="width: 360px;"
|
||||
@update:value="handleAiQueryInput"
|
||||
@select="handleAiQuerySelect"
|
||||
>
|
||||
<template #prefix>
|
||||
<NIcon :component="SparklesOutline" />
|
||||
</template>
|
||||
</NAutoComplete>
|
||||
<NButton type="primary" :loading="aiQuerying" @click="handleAiQuery">{{ t('ai.query.button') }}</NButton>
|
||||
<NDropdown trigger="click" :options="exampleOptions" @select="handleExampleSelect">
|
||||
<NButton text type="primary" size="small">
|
||||
<template #icon>
|
||||
<NIcon :component="BulbOutline" />
|
||||
</template>
|
||||
{{ t('transaction.exampleLabel') }}
|
||||
</NButton>
|
||||
</NDropdown>
|
||||
</NSpace>
|
||||
|
||||
<NDivider style="margin: 12px 0;" />
|
||||
</template>
|
||||
|
||||
<!-- 常用筛选条件 -->
|
||||
<NSpace align="center" :wrap="true" :size="[12, 8]">
|
||||
<NSelect
|
||||
v-model:value="filterType"
|
||||
:options="typeOptions"
|
||||
@@ -729,12 +1286,18 @@ onMounted(() => {
|
||||
clearable
|
||||
style="width: 260px;"
|
||||
/>
|
||||
<NInput
|
||||
v-model:value="filterRemark"
|
||||
<NAutoComplete
|
||||
:value="filterRemark"
|
||||
:options="remarkOptions"
|
||||
:get-show="showRemarkMenu"
|
||||
:render-label="renderRemarkLabel"
|
||||
:input-props="{ onKeydown: handleRemarkKeydown }"
|
||||
clearable
|
||||
:placeholder="t('transaction.column.remark')"
|
||||
style="width: 180px;"
|
||||
@keyup.enter="handleSearch"
|
||||
@update:value="handleRemarkInput"
|
||||
@select="handleRemarkSelect"
|
||||
@blur="handleRemarkBlur"
|
||||
/>
|
||||
<NPopover v-model:show="showMoreFilter" trigger="click" placement="bottom-start">
|
||||
<template #trigger>
|
||||
@@ -811,6 +1374,23 @@ onMounted(() => {
|
||||
<NButton type="primary" @click="handleSearch">{{ t('transaction.search') }}</NButton>
|
||||
<NButton @click="handleReset">{{ t('transaction.reset') }}</NButton>
|
||||
</NSpace>
|
||||
|
||||
<!-- 已激活的筛选条件 -->
|
||||
<div v-if="activeFilterTags.length > 0" class="active-filters">
|
||||
<NSpace align="center" :wrap="true" :size="[8, 8]">
|
||||
<span style="color: #999; font-size: 12px;">{{ t('transaction.activeFilters') }}</span>
|
||||
<NTag
|
||||
v-for="tag in activeFilterTags"
|
||||
:key="tag.key"
|
||||
size="small"
|
||||
closable
|
||||
@close="applyTagClear(tag)"
|
||||
>
|
||||
{{ tag.label }}
|
||||
</NTag>
|
||||
<NButton text size="tiny" type="primary" @click="handleReset">{{ t('transaction.clearAll') }}</NButton>
|
||||
</NSpace>
|
||||
</div>
|
||||
</NCard>
|
||||
|
||||
<!-- 表格信息栏(右上角) -->
|
||||
@@ -897,6 +1477,9 @@ onMounted(() => {
|
||||
{{ t('transaction.batchScopeHint', { count: transactions.length }) }}
|
||||
</span>
|
||||
</NFormItem>
|
||||
<NFormItem v-if="aiEnabled" :label="t('ai.suggestButton')">
|
||||
<NButton :loading="aiLoading" @click="handleAiSuggest">{{ t('ai.suggestButton') }}</NButton>
|
||||
</NFormItem>
|
||||
<NFormItem :label="t('transaction.expenseCategory')">
|
||||
<NSelect
|
||||
v-model:value="batchExpenseCategoryId"
|
||||
@@ -929,6 +1512,99 @@ onMounted(() => {
|
||||
<NButton type="primary" block :loading="batching" @click="handleBatchSubmit">{{ t('common.confirm') }}</NButton>
|
||||
</NForm>
|
||||
</NModal>
|
||||
|
||||
<!-- AI 建议弹窗(一键应用分类与标签建议) -->
|
||||
<NModal v-model:show="showAiModal" preset="card" :title="t('ai.suggestTitle')" style="width: 860px; max-width: 92vw;">
|
||||
<NSpace vertical :size="12">
|
||||
<NAlert type="warning" :show-icon="true">{{ t('ai.applyHint') }}</NAlert>
|
||||
<NDataTable
|
||||
:columns="aiColumns"
|
||||
:data="aiRows"
|
||||
:max-height="420"
|
||||
:row-key="(row) => row.transactionId"
|
||||
size="small"
|
||||
:bordered="false"
|
||||
/>
|
||||
<NSpace justify="end">
|
||||
<NButton @click="showAiModal = false">{{ t('common.cancel') }}</NButton>
|
||||
<NButton type="primary" :loading="aiApplying" :disabled="aiRows.length === 0" @click="handleAiApply">
|
||||
{{ t('ai.applyAll', { count: aiRows.length }) }}
|
||||
</NButton>
|
||||
</NSpace>
|
||||
</NSpace>
|
||||
</NModal>
|
||||
|
||||
<!-- AI 自然语言查询解析结果弹窗 -->
|
||||
<NModal v-model:show="showAiQueryModal" preset="card" :title="t('ai.query.resultTitle')" style="width: 560px; max-width: 92vw;">
|
||||
<NSpace vertical :size="12">
|
||||
<NAlert v-if="aiQueryResult?.summary" type="info" :show-icon="true">{{ aiQueryResult.summary }}</NAlert>
|
||||
<NText v-if="aiQueryEmpty" depth="3">{{ t('ai.query.noCondition') }}</NText>
|
||||
<NDescriptions v-else :column="1" label-placement="left" bordered size="small">
|
||||
<NDescriptionsItem v-if="aiQueryResult?.types?.length" :label="t('ai.query.type')">
|
||||
<NSpace :size="6">
|
||||
<NTag v-for="tp in aiQueryResult.types" :key="tp" size="small" :type="tp === 'INCOME' ? 'success' : 'error'">
|
||||
{{ tp === 'INCOME' ? t('common.types.income') : t('common.types.expense') }}
|
||||
</NTag>
|
||||
</NSpace>
|
||||
</NDescriptionsItem>
|
||||
<NDescriptionsItem v-if="aiQueryResult?.categoryNames?.length || aiQueryResult?.uncategorized" :label="t('ai.query.category')">
|
||||
<NSpace :size="6">
|
||||
<NTag v-for="c in aiQueryResult?.categoryNames || []" :key="c" size="small">{{ c }}</NTag>
|
||||
<NTag v-if="aiQueryResult?.uncategorized" size="small">{{ t('transaction.uncategorized') }}</NTag>
|
||||
</NSpace>
|
||||
</NDescriptionsItem>
|
||||
<NDescriptionsItem v-if="aiQueryResult?.tagNames?.length" :label="t('ai.query.tag')">
|
||||
<NSpace :size="6">
|
||||
<NTag v-for="tg in aiQueryResult.tagNames" :key="tg" size="small">{{ tg }}</NTag>
|
||||
</NSpace>
|
||||
</NDescriptionsItem>
|
||||
<NDescriptionsItem v-if="aiQueryResult?.paymentMethods?.length" :label="t('ai.query.payment')">
|
||||
<NSpace :size="6">
|
||||
<NTag v-for="pm in aiQueryResult.paymentMethods" :key="pm" size="small">{{ getPaymentLabel(pm) }}</NTag>
|
||||
</NSpace>
|
||||
</NDescriptionsItem>
|
||||
<NDescriptionsItem v-if="aiQueryResult?.startTime && aiQueryResult?.endTime" :label="t('ai.query.dateRange')">
|
||||
{{ formatAiDate(aiQueryResult.startTime) }} ~ {{ formatAiDate(aiQueryResult.endTime) }}
|
||||
</NDescriptionsItem>
|
||||
<NDescriptionsItem
|
||||
v-if="aiQueryResult && (aiQueryResult.minAmount != null || aiQueryResult.maxAmount != null)"
|
||||
:label="t('ai.query.amountRange')"
|
||||
>
|
||||
{{ aiQueryResult.minAmount ?? 0 }} ~ {{ aiQueryResult.maxAmount ?? '∞' }}
|
||||
</NDescriptionsItem>
|
||||
<NDescriptionsItem v-if="aiQueryResult?.remark" :label="t('ai.query.remark')">{{ aiQueryResult.remark }}</NDescriptionsItem>
|
||||
<NDescriptionsItem v-if="aiQueryResult && aiQueryResult.includeInStats != null" :label="t('ai.query.includeInStats')">
|
||||
{{ aiQueryResult.includeInStats ? t('ai.query.includeYes') : t('ai.query.includeNo') }}
|
||||
</NDescriptionsItem>
|
||||
<NDescriptionsItem v-if="aiQueryResult?.unmatched?.length" :label="t('ai.query.unmatched')">
|
||||
<NSpace :size="6">
|
||||
<NTag v-for="u in aiQueryResult.unmatched" :key="u" size="small" type="warning">{{ u }}</NTag>
|
||||
</NSpace>
|
||||
</NDescriptionsItem>
|
||||
</NDescriptions>
|
||||
<NSpace justify="end">
|
||||
<NButton @click="showAiQueryModal = false">{{ t('common.cancel') }}</NButton>
|
||||
<NButton type="primary" :disabled="aiQueryEmpty" @click="applyAiQuery">{{ t('ai.query.apply') }}</NButton>
|
||||
</NSpace>
|
||||
</NSpace>
|
||||
</NModal>
|
||||
|
||||
<!-- AI 智能记账弹窗 -->
|
||||
<NModal v-model:show="showAiRecordModal" preset="card" :title="t('ai.record.title')" style="width: 520px; max-width: 92vw;">
|
||||
<NSpace vertical :size="12">
|
||||
<NAlert type="info" :show-icon="true">{{ t('ai.record.hint') }}</NAlert>
|
||||
<NInput
|
||||
v-model:value="aiRecordText"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 3, maxRows: 6 }"
|
||||
:placeholder="t('ai.record.placeholder')"
|
||||
/>
|
||||
<NSpace justify="end">
|
||||
<NButton @click="showAiRecordModal = false">{{ t('common.cancel') }}</NButton>
|
||||
<NButton type="primary" :loading="aiRecording" @click="handleAiRecordParse">{{ t('ai.record.parse') }}</NButton>
|
||||
</NSpace>
|
||||
</NSpace>
|
||||
</NModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -949,4 +1625,9 @@ onMounted(() => {
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
}
|
||||
.active-filters {
|
||||
margin-top: 12px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user