添加智能分类功能,支持获取未分类账单数量和列表;实现AI分类逻辑;更新相关API和前端视图
All checks were successful
Docker Build & Deploy / Build Docker Image (push) Successful in 20s
Docker Build & Deploy / Deploy to Production (push) Successful in 8s

This commit is contained in:
孙诚
2025-12-25 15:40:50 +08:00
parent a9dfcdaa5c
commit bbcb630401
9 changed files with 714 additions and 3 deletions

View File

@@ -100,3 +100,63 @@ export const getTransactionsByDate = (date) => {
// 注意分类相关的API已迁移到 transactionCategory.js
// 请使用 getCategoryTree 等新接口
/**
* 获取未分类的账单数量
* @returns {Promise<{success: boolean, data: number}>}
*/
export const getUnclassifiedCount = () => {
return request({
url: '/TransactionRecord/GetUnclassifiedCount',
method: 'get'
})
}
/**
* 获取未分类的账单列表
* @param {number} pageSize - 每页数量默认10条
* @returns {Promise<{success: boolean, data: Array}>}
*/
export const getUnclassified = (pageSize = 10) => {
return request({
url: '/TransactionRecord/GetUnclassified',
method: 'get',
params: { pageSize }
})
}
/**
* 智能分类 - 使用AI对账单进行分类EventSource流式响应
* @param {number} pageSize - 每次分类的账单数量
* @returns {EventSource} 返回EventSource对象用于接收流式数据
*/
export const smartClassify = (pageSize = 10) => {
const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000'
const token = localStorage.getItem('token')
const url = `${baseURL}/api/TransactionRecord/SmartClassify`
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ pageSize })
})
}
/**
* 批量更新账单分类
* @param {Array} items - 要更新的账单分类数据数组
* @param {number} items[].id - 账单ID
* @param {string} items[].classify - 一级分类
* @param {string} items[].subClassify - 子分类
* @returns {Promise<{success: boolean, message: string}>}
*/
export const batchUpdateClassify = (items) => {
return request({
url: '/TransactionRecord/BatchUpdateClassify',
method: 'post',
data: items
})
}

View File

@@ -34,6 +34,12 @@ const router = createRouter({
component: () => import('../views/CalendarView.vue'),
meta: { requiresAuth: true },
},
{
path: '/smart-classification',
name: 'smart-classification',
component: () => import('../views/SmartClassification.vue'),
meta: { requiresAuth: true },
}
],
})

View File

@@ -16,7 +16,7 @@
<p>账单处理</p>
</div>
<van-cell-group inset>
<van-cell title="智能分类" is-link />
<van-cell title="智能分类" is-link @click="handleSmartClassification" />
</van-cell-group>
<div class="detail-header">
@@ -101,6 +101,10 @@ const handleFileChange = async (event) => {
}
}
const handleSmartClassification = () => {
router.push({ name: 'smart-classification' })
}
/**
* 处理退出登录
*/

View File

@@ -0,0 +1,335 @@
<template>
<div class="smart-classification">
<van-nav-bar
title="智能分类"
left-text="返回"
left-arrow
style="position: fixed; top: 0; left: 0; right: 0; z-index: 100;"
@click-left="onClickLeft"
/>
<div class="container" style="padding-top: 46px;">
<!-- 统计信息 -->
<div class="stats-info">
<span class="stats-label">未分类账单</span>
<span class="stats-value">{{ records.length }} / {{ unclassifiedCount }}</span>
</div>
<!-- 账单列表 -->
<TransactionList
:transactions="records"
:loading="false"
:finished="true"
:show-delete="false"
@click="viewDetail"
/>
</div>
<!-- 详情/编辑弹出层 -->
<TransactionDetail
v-model:show="detailVisible"
:transaction="currentTransaction"
@save="onDetailSave"
/>
<!-- 底部操作按钮 -->
<div class="action-bar">
<van-button
type="primary"
:loading="classifying"
:disabled="records.length === 0"
@click="startClassify"
class="action-btn"
>
{{ classifying ? '分类中...' : '开始智能分类' }}
</van-button>
<van-button
type="success"
:disabled="!hasChanges || classifying"
@click="saveClassifications"
class="action-btn"
>
保存分类
</van-button>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast, showConfirmDialog } from 'vant'
import {
getUnclassifiedCount,
getUnclassified,
smartClassify,
batchUpdateClassify,
getTransactionDetail
} from '@/api/transactionRecord'
import TransactionList from '@/components/TransactionList.vue'
import TransactionDetail from '@/components/TransactionDetail.vue'
const router = useRouter()
const unclassifiedCount = ref(0)
const records = ref([])
const classifying = ref(false)
const hasChanges = ref(false)
const detailVisible = ref(false)
const currentTransaction = ref(null)
const onClickLeft = () => {
if (hasChanges.value) {
showConfirmDialog({
title: '提示',
message: '有未保存的分类结果,确定要离开吗?',
}).then(() => {
router.back()
}).catch(() => {})
} else {
router.back()
}
}
// 加载未分类账单数量
const loadUnclassifiedCount = async () => {
try {
const res = await getUnclassifiedCount()
if (res.success) {
unclassifiedCount.value = res.data
}
} catch (error) {
console.error('获取未分类数量失败', error)
}
}
// 加载未分类账单列表
const loadUnclassified = async () => {
const toast = showLoadingToast({
message: '加载中...',
forbidClick: true,
duration: 0
})
try {
const res = await getUnclassified(10)
if (res.success) {
records.value = res.data
} else {
showToast(res.message || '加载失败')
}
} catch (error) {
console.error('加载账单失败', error)
showToast('加载失败')
} finally {
closeToast()
}
}
// 开始智能分类
const startClassify = async () => {
if (records.value.length === 0) {
showToast('没有需要分类的账单')
return
}
classifying.value = true
try {
const response = await smartClassify(10)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (!line.trim()) continue
const eventMatch = line.match(/^event: (.+)$/m)
const dataMatch = line.match(/^data: (.+)$/m)
if (eventMatch && dataMatch) {
const eventType = eventMatch[1]
const data = dataMatch[1]
handleSSEEvent(eventType, data)
}
}
}
} catch (error) {
console.error('智能分类失败', error)
showToast(`分类失败: ${error.message}`)
} finally {
classifying.value = false
}
}
// 处理SSE事件
const handleSSEEvent = (eventType, data) => {
if (eventType === 'data') {
// 尝试解析JSON数据并更新对应账单的分类
try {
// 累积JSON片段
if (!window.classifyBuffer) {
window.classifyBuffer = ''
}
window.classifyBuffer += data
// 尝试提取完整的JSON对象
const jsonMatches = window.classifyBuffer.match(/\{[^}]+\}/g)
if (jsonMatches) {
for (const jsonStr of jsonMatches) {
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 || ''
hasChanges.value = true
}
// 移除已处理的JSON
window.classifyBuffer = window.classifyBuffer.replace(jsonStr, '')
}
} catch (e) {
// 不是完整的JSON继续累积
}
}
}
} catch (error) {
console.error('解析分类结果失败', error)
}
} else if (eventType === 'end') {
window.classifyBuffer = ''
showToast('分类完成')
} else if (eventType === 'error') {
window.classifyBuffer = ''
showToast(data)
}
}
// 保存分类
const saveClassifications = async () => {
const itemsToUpdate = records.value
.filter(r => r.classify)
.map(r => ({
id: r.id,
classify: r.classify,
subClassify: r.subClassify
}))
if (itemsToUpdate.length === 0) {
showToast('没有需要保存的分类')
return
}
const toast = showLoadingToast({
message: '保存中...',
forbidClick: true,
duration: 0
})
try {
const res = await batchUpdateClassify(itemsToUpdate)
if (res.success) {
showToast('保存成功')
hasChanges.value = false
// 重新加载数据
await loadUnclassifiedCount()
await loadUnclassified()
} else {
showToast(res.message || '保存失败')
}
} catch (error) {
console.error('保存失败', error)
showToast('保存失败')
} finally {
closeToast()
}
}
// 查看详情
const viewDetail = async (transaction) => {
try {
const response = await getTransactionDetail(transaction.id)
if (response.success) {
currentTransaction.value = response.data
detailVisible.value = true
} else {
showToast(response.message || '获取详情失败')
}
} catch (error) {
console.error('获取详情出错:', error)
showToast('获取详情失败')
}
}
// 详情保存后的回调
const onDetailSave = async () => {
// 重新加载数据
await loadUnclassifiedCount()
await loadUnclassified()
}
onMounted(() => {
loadUnclassifiedCount()
loadUnclassified()
})
</script>
<style scoped>
.smart-classification {
min-height: 100vh;
padding-bottom: 60px;
}
/* 统计信息 */
.stats-info {
padding: 12px 16px;
font-size: 14px;
color: #969799;
}
.stats-value {
font-weight: 500;
}
/* 底部操作栏 */
.action-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
gap: 12px;
padding: 12px;
background-color: var(--van-background-2, #fff);
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
z-index: 100;
}
@media (prefers-color-scheme: dark) {
.action-bar {
background-color: var(--van-background-2, #2c2c2c);
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.3);
}
}
.action-btn {
flex: 1;
height: 44px;
}
</style>