大量的代码格式化
Some checks failed
Docker Build & Deploy / Build Docker Image (push) Failing after 1m10s
Docker Build & Deploy / Deploy to Production (push) Has been skipped
Docker Build & Deploy / Cleanup Dangling Images (push) Successful in 1s
Docker Build & Deploy / WeChat Notification (push) Successful in 1s

This commit is contained in:
孙诚
2026-01-16 11:15:44 +08:00
parent 9069e3dbcf
commit 319f8f7d7b
54 changed files with 2973 additions and 2200 deletions

View File

@@ -58,7 +58,7 @@ public interface ITransactionRecordRepository : IBaseRepository<TransactionRecor
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns>每天的消费笔数和金额详情</returns>
Task<Dictionary<string, (int count, decimal expense, decimal income)>> GetDailyStatisticsAsync(int year, int month);
Task<Dictionary<string, (int count, decimal expense, decimal income, decimal saving)>> GetDailyStatisticsAsync(int year, int month, string? savingClassify = null);
/// <summary>
/// 获取指定日期范围内的每日统计
@@ -66,7 +66,7 @@ public interface ITransactionRecordRepository : IBaseRepository<TransactionRecor
/// <param name="startDate">开始日期</param>
/// <param name="endDate">结束日期</param>
/// <returns>每天的消费笔数和金额详情</returns>
Task<Dictionary<string, (int count, decimal expense, decimal income)>> GetDailyStatisticsByRangeAsync(DateTime startDate, DateTime endDate);
Task<Dictionary<string, (int count, decimal expense, decimal income, decimal saving)>> GetDailyStatisticsByRangeAsync(DateTime startDate, DateTime endDate, string? savingClassify = null);
/// <summary>
/// 获取指定日期范围内的交易记录
@@ -345,15 +345,15 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
.ToListAsync(t => t.Classify);
}
public async Task<Dictionary<string, (int count, decimal expense, decimal income)>> GetDailyStatisticsAsync(int year, int month)
public async Task<Dictionary<string, (int count, decimal expense, decimal income, decimal saving)>> GetDailyStatisticsAsync(int year, int month, string? savingClassify = null)
{
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1);
return await GetDailyStatisticsByRangeAsync(startDate, endDate);
return await GetDailyStatisticsByRangeAsync(startDate, endDate, savingClassify);
}
public async Task<Dictionary<string, (int count, decimal expense, decimal income)>> GetDailyStatisticsByRangeAsync(DateTime startDate, DateTime endDate)
public async Task<Dictionary<string, (int count, decimal expense, decimal income, decimal saving)>> GetDailyStatisticsByRangeAsync(DateTime startDate, DateTime endDate, string? savingClassify = null)
{
var records = await FreeSql.Select<TransactionRecord>()
.Where(t => t.OccurredAt >= startDate && t.OccurredAt < endDate)
@@ -368,7 +368,14 @@ public class TransactionRecordRepository(IFreeSql freeSql) : BaseRepository<Tran
// 分别统计收入和支出
var income = g.Where(t => t.Type == TransactionType.Income).Sum(t => Math.Abs(t.Amount));
var expense = g.Where(t => t.Type == TransactionType.Expense).Sum(t => Math.Abs(t.Amount));
return (count: g.Count(), expense: expense, income: income);
var saving = 0m;
if(!string.IsNullOrEmpty(savingClassify))
{
saving = g.Where(t => savingClassify.Split(',').Contains(t.Classify)).Sum(t => Math.Abs(t.Amount));
}
return (count: g.Count(), expense, income, saving);
}
);

View File

@@ -2,5 +2,6 @@
"$schema": "https://json.schemastore.org/prettierrc",
"semi": false,
"singleQuote": true,
"printWidth": 100
"printWidth": 100,
"trailingComma": "none"
}

View File

@@ -1,52 +1,82 @@
import js from '@eslint/js'
import js from '@eslint/js'
import globals from 'globals'
import pluginVue from 'eslint-plugin-vue'
import skipFormatting from '@vue/eslint-config-prettier/skip-formatting'
export default [
{
ignores: ['**/dist/**', '**/dist-ssr/**', '**/coverage/**', '**/node_modules/**', '.nuxt/**'],
ignores: ['**/dist/**', '**/dist-ssr/**', '**/coverage/**', '**/node_modules/**', '.nuxt/**']
},
// Load Vue recommended rules first (sets up parser etc.)
...pluginVue.configs['flat/recommended'],
// General Configuration for all JS/Vue files
{
files: ['**/*.{js,mjs,jsx}'],
files: ['**/*.{js,mjs,jsx,vue}'],
languageOptions: {
globals: {
...globals.browser,
},
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
...globals.browser
},
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {
// Import standard JS recommended rules
...js.configs.recommended.rules,
'indent': ['error', 2],
// --- Logic & Best Practices ---
'no-unused-vars': ['warn', {
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_'
}],
'no-undef': 'error',
'no-console': ['warn', { allow: ['warn', 'error', 'info'] }],
'no-debugger': 'warn',
'eqeqeq': ['error', 'always', { null: 'ignore' }],
'curly': ['error', 'all'],
'prefer-const': 'warn',
'no-var': 'error',
// --- Formatting & Style (User requested warnings) ---
'indent': ['error', 2, { SwitchCase: 1 }],
'quotes': ['error', 'single', { avoidEscape: true }],
'semi': ['error', 'never'],
'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'comma-dangle': ['error', 'never'],
'no-trailing-spaces': 'error',
'no-multiple-empty-lines': ['error', { max: 1 }],
'space-before-function-paren': ['error', 'always'],
},
'object-curly-spacing': ['error', 'always'],
'array-bracket-spacing': ['error', 'never']
}
},
...pluginVue.configs['flat/recommended'],
// Vue Specific Overrides
{
files: ['**/*.vue'],
rules: {
'vue/multi-word-component-names': 'off',
'vue/no-v-html': 'warn',
// Turn off standard indent for Vue files to avoid conflicts with vue/html-indent
// or script indentation issues. Vue plugin handles this better.
'indent': 'off',
},
// Ensure Vue's own indentation rules are active (they are in 'recommended' but let's be explicit if needed)
'vue/html-indent': ['error', 2],
'vue/script-indent': ['error', 2, {
baseIndent: 0,
switchCase: 1,
ignores: []
}]
}
},
skipFormatting,
// Service Worker specific globals
{
files: ['**/service-worker.js', '**/src/registerServiceWorker.js'],
languageOptions: {
globals: {
...globals.serviceworker,
...globals.browser,
},
},
},
...globals.serviceworker
}
}
}
]

View File

@@ -1,4 +1,4 @@
{
{
"name": "email-bill",
"version": "1.0.0",
"private": true,
@@ -11,7 +11,7 @@
"build": "vite build",
"preview": "vite preview",
"lint": "eslint . --fix --cache",
"format": "prettier --write --experimental-cli src/"
"format": "prettier --write src/"
},
"dependencies": {
"axios": "^1.13.2",

View File

@@ -1,56 +1,56 @@
const VERSION = '1.0.0'; // Build Time: 2026-01-07 15:59:36
const CACHE_NAME = `emailbill-${VERSION}`;
const VERSION = '1.0.0' // Build Time: 2026-01-07 15:59:36
const CACHE_NAME = `emailbill-${VERSION}`
const urlsToCache = [
'/',
'/index.html',
'/favicon.ico',
'/manifest.json'
];
]
// 安装 Service Worker
self.addEventListener('install', (event) => {
console.log('[Service Worker] 安装中...');
console.log('[Service Worker] 安装中...')
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => {
console.log('[Service Worker] 缓存文件');
return cache.addAll(urlsToCache);
console.log('[Service Worker] 缓存文件')
return cache.addAll(urlsToCache)
})
);
});
)
})
// 监听跳过等待消息
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
self.skipWaiting()
}
});
})
// 激活 Service Worker
self.addEventListener('activate', (event) => {
console.log('[Service Worker] 激活中...');
console.log('[Service Worker] 激活中...')
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
console.log('[Service Worker] 删除旧缓存:', cacheName);
return caches.delete(cacheName);
console.log('[Service Worker] 删除旧缓存:', cacheName)
return caches.delete(cacheName)
}
})
);
)
}).then(() => self.clients.claim())
);
});
)
})
// 拦截请求
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
const { request } = event
const url = new URL(request.url)
// 跳过跨域请求
if (url.origin !== location.origin) {
return;
return
}
// API请求使用网络优先策略
@@ -60,19 +60,19 @@ self.addEventListener('fetch', (event) => {
.then((response) => {
// 只针对成功的GET请求进行缓存
if (request.method === 'GET' && response.status === 200) {
const responseClone = response.clone();
const responseClone = response.clone()
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, responseClone);
});
cache.put(request, responseClone)
})
}
return response;
return response
})
.catch(() => {
// 网络失败时尝试从缓存获取
return caches.match(request);
return caches.match(request)
})
);
return;
)
return
}
// 页面请求使用网络优先策略,确保能获取到最新的 index.html
@@ -80,17 +80,17 @@ self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(request)
.then((response) => {
const responseClone = response.clone();
const responseClone = response.clone()
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, responseClone);
});
return response;
cache.put(request, responseClone)
})
return response
})
.catch(() => {
return caches.match('/index.html') || caches.match(request);
return caches.match('/index.html') || caches.match(request)
})
);
return;
)
return
}
// 其他静态资源使用缓存优先策略
@@ -98,50 +98,50 @@ self.addEventListener('fetch', (event) => {
caches.match(request)
.then((response) => {
if (response) {
return response;
return response
}
return fetch(request).then((response) => {
// 检查是否是有效响应
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
return response
}
const responseClone = response.clone();
const responseClone = response.clone()
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, responseClone);
});
cache.put(request, responseClone)
})
return response;
});
return response
})
})
.catch(() => {
// 返回离线页面或默认内容
if (request.destination === 'document') {
return caches.match('/index.html');
return caches.match('/index.html')
}
})
);
});
)
})
// 后台同步
self.addEventListener('sync', (event) => {
console.log('[Service Worker] 后台同步:', event.tag);
console.log('[Service Worker] 后台同步:', event.tag)
if (event.tag === 'sync-data') {
event.waitUntil(syncData());
event.waitUntil(syncData())
}
});
})
// 推送通知
self.addEventListener('push', (event) => {
console.log('[Service Worker] 收到推送消息');
let data = { title: '账单管理', body: '您有新的消息', url: '/', icon: '/icons/icon-192x192.png' };
console.log('[Service Worker] 收到推送消息')
let data = { title: '账单管理', body: '您有新的消息', url: '/', icon: '/icons/icon-192x192.png' }
if (event.data) {
try {
const json = event.data.json();
data = { ...data, ...json };
const json = event.data.json()
data = { ...data, ...json }
} catch {
data.body = event.data.text();
data.body = event.data.text()
}
}
@@ -153,41 +153,41 @@ self.addEventListener('push', (event) => {
tag: 'emailbill-notification',
requireInteraction: false,
data: { url: data.url }
};
}
event.waitUntil(
self.registration.showNotification(data.title, options)
);
});
)
})
// 通知点击
self.addEventListener('notificationclick', (event) => {
console.log('[Service Worker] 通知被点击');
event.notification.close();
const urlToOpen = event.notification.data?.url || '/';
console.log('[Service Worker] 通知被点击')
event.notification.close()
const urlToOpen = event.notification.data?.url || '/'
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
// 如果已经打开了该 URL则聚焦
for (let i = 0; i < windowClients.length; i++) {
const client = windowClients[i];
const client = windowClients[i]
if (client.url === urlToOpen && 'focus' in client) {
return client.focus();
return client.focus()
}
}
// 否则打开新窗口
if (clients.openWindow) {
return clients.openWindow(urlToOpen);
return clients.openWindow(urlToOpen)
}
})
);
});
)
})
// 数据同步函数
async function syncData() {
async function syncData () {
try {
// 这里添加需要同步的逻辑
console.log('[Service Worker] 执行数据同步');
console.log('[Service Worker] 执行数据同步')
} catch (error) {
console.error('[Service Worker] 同步失败:', error);
console.error('[Service Worker] 同步失败:', error)
}
}

View File

@@ -3,10 +3,13 @@
<div class="app-root">
<RouterView />
<van-tabbar v-show="showTabbar" v-model="active">
<van-tabbar-item name="ccalendar" icon="notes" to="/calendar">
日历
</van-tabbar-item>
<van-tabbar-item name="statistics" icon="chart-trending-o" to="/" @click="handleTabClick('/statistics')">
<van-tabbar-item name="ccalendar" icon="notes" to="/calendar"> 日历 </van-tabbar-item>
<van-tabbar-item
name="statistics"
icon="chart-trending-o"
to="/"
@click="handleTabClick('/statistics')"
>
统计
</van-tabbar-item>
<van-tabbar-item
@@ -18,14 +21,17 @@
>
账单
</van-tabbar-item>
<van-tabbar-item name="budget" icon="bill-o" to="/budget" @click="handleTabClick('/budget')">
<van-tabbar-item
name="budget"
icon="bill-o"
to="/budget"
@click="handleTabClick('/budget')"
>
预算
</van-tabbar-item>
<van-tabbar-item name="setting" icon="setting" to="/setting">
设置
</van-tabbar-item>
<van-tabbar-item name="setting" icon="setting" to="/setting"> 设置 </van-tabbar-item>
</van-tabbar>
<GlobalAddBill v-if="isShowAddBill" @success="handleAddTransactionSuccess"/>
<GlobalAddBill v-if="isShowAddBill" @success="handleAddTransactionSuccess" />
<div v-if="needRefresh" class="update-toast" @click="updateServiceWorker">
<van-icon name="upgrade" class="update-icon" />
@@ -85,12 +91,14 @@ onUnmounted(() => {
const route = useRoute()
// 根据路由判断是否显示Tabbar
const showTabbar = computed(() => {
return route.path === '/' ||
return (
route.path === '/' ||
route.path === '/calendar' ||
route.path === '/message' ||
route.path === '/setting' ||
route.path === '/balance' ||
route.path === '/budget'
)
})
const active = ref('')
@@ -116,11 +124,14 @@ setInterval(() => {
}, 60 * 1000) // 每60秒更新一次未读消息数
// 监听路由变化调整
watch(() => route.path, (newPath) => {
setActive(newPath)
watch(
() => route.path,
(newPath) => {
setActive(newPath)
messageStore.updateUnreadCount()
})
messageStore.updateUnreadCount()
}
)
const setActive = (path) => {
active.value = (() => {
@@ -142,9 +153,7 @@ const setActive = (path) => {
}
const isShowAddBill = computed(() => {
return route.path === '/'
|| route.path === '/balance'
|| route.path === '/message'
return route.path === '/' || route.path === '/balance' || route.path === '/message'
})
onUnmounted(() => {
@@ -165,7 +174,6 @@ const handleAddTransactionSuccess = () => {
const event = new Event('transactions-changed')
window.dispatchEvent(event)
}
</script>
<style scoped>

View File

@@ -26,45 +26,47 @@ export const uploadBillFile = (file, type) => {
Authorization: `Bearer ${useAuthStore().token || ''}`
},
timeout: 60000 // 文件上传增加超时时间
}).then(response => {
const { data } = response
})
.then((response) => {
const { data } = response
if (data.success === false) {
showToast(data.message || '上传失败')
return Promise.reject(new Error(data.message || '上传失败'))
}
return data
}).catch(error => {
console.error('上传错误:', error)
if (error.response) {
const { status, data } = error.response
let message = '上传失败'
switch (status) {
case 400:
message = data?.message || '请求参数错误'
break
case 401:
message = '未授权,请先登录'
break
case 403:
message = '没有权限'
break
case 413:
message = '文件过大'
break
case 500:
message = '服务器错误'
break
if (data.success === false) {
showToast(data.message || '上传失败')
return Promise.reject(new Error(data.message || '上传失败'))
}
showToast(message)
return Promise.reject(new Error(message))
}
return data
})
.catch((error) => {
console.error('上传错误:', error)
showToast('网络错误,请检查网络连接')
return Promise.reject(error)
})
if (error.response) {
const { status, data } = error.response
let message = '上传失败'
switch (status) {
case 400:
message = data?.message || '请求参数错误'
break
case 401:
message = '未授权,请先登录'
break
case 403:
message = '没有权限'
break
case 413:
message = '文件过大'
break
case 500:
message = '服务器错误'
break
}
showToast(message)
return Promise.reject(new Error(message))
}
showToast('网络错误,请检查网络连接')
return Promise.reject(error)
})
}

View File

@@ -37,7 +37,7 @@ export const getEmailDetail = (id) => {
*/
export const deleteEmail = (id) => {
return request({
url: `/EmailMessage/DeleteById`,
url: '/EmailMessage/DeleteById',
method: 'post',
params: { id }
})
@@ -50,7 +50,7 @@ export const deleteEmail = (id) => {
*/
export const refreshTransactionRecords = (id) => {
return request({
url: `/EmailMessage/RefreshTransactionRecords`,
url: '/EmailMessage/RefreshTransactionRecords',
method: 'post',
params: { id }
})
@@ -62,7 +62,7 @@ export const refreshTransactionRecords = (id) => {
*/
export const syncEmails = () => {
return request({
url: `/EmailMessage/SyncEmails`,
url: '/EmailMessage/SyncEmails',
method: 'post'
})
}

View File

@@ -1,13 +1,13 @@
import request from '@/api/request'
export function getJobs() {
export function getJobs () {
return request({
url: '/Job/GetJobs',
method: 'get'
})
}
export function executeJob(jobName) {
export function executeJob (jobName) {
return request({
url: '/Job/Execute',
method: 'post',
@@ -15,7 +15,7 @@ export function executeJob(jobName) {
})
}
export function pauseJob(jobName) {
export function pauseJob (jobName) {
return request({
url: '/Job/Pause',
method: 'post',
@@ -23,7 +23,7 @@ export function pauseJob(jobName) {
})
}
export function resumeJob(jobName) {
export function resumeJob (jobName) {
return request({
url: '/Job/Resume',
method: 'post',

View File

@@ -14,7 +14,7 @@ const request = axios.create({
// 请求拦截器
request.interceptors.request.use(
config => {
(config) => {
// 添加 token 认证信息
const authStore = useAuthStore()
if (authStore.token) {
@@ -22,7 +22,7 @@ request.interceptors.request.use(
}
return config
},
error => {
(error) => {
console.error('请求错误:', error)
return Promise.reject(error)
}
@@ -30,7 +30,7 @@ request.interceptors.request.use(
// 响应拦截器
request.interceptors.response.use(
response => {
(response) => {
const { data } = response
// 统一处理业务错误
@@ -41,7 +41,7 @@ request.interceptors.response.use(
return data
},
error => {
(error) => {
console.error('响应错误:', error)
// 统一处理 HTTP 错误
@@ -58,7 +58,10 @@ request.interceptors.response.use(
// 清除登录状态并跳转到登录页
const authStore = useAuthStore()
authStore.logout()
router.push({ name: 'login', query: { redirect: router.currentRoute.value.fullPath } })
router.push({
name: 'login',
query: { redirect: router.currentRoute.value.fullPath }
})
break
}
case 403:

View File

@@ -79,7 +79,7 @@ export const updatePeriodic = (data) => {
*/
export const deletePeriodic = (id) => {
return request({
url: `/TransactionPeriodic/DeleteById`,
url: '/TransactionPeriodic/DeleteById',
method: 'post',
params: { id }
})

View File

@@ -99,7 +99,7 @@ export const updateTransaction = (data) => {
*/
export const deleteTransaction = (id) => {
return request({
url: `/TransactionRecord/DeleteById`,
url: '/TransactionRecord/DeleteById',
method: 'post',
params: { id }
})
@@ -118,7 +118,6 @@ export const getTransactionsByDate = (date) => {
})
}
// 注意分类相关的API已迁移到 transactionCategory.js
// 请使用 getCategoryList 等新接口
@@ -160,7 +159,7 @@ export const smartClassify = (transactionIds = []) => {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ transactionIds })
})

View File

@@ -1,7 +1,8 @@
@import './base.css';
/* 禁用页面弹性缩放和橡皮筋效果 */
html, body {
html,
body {
overscroll-behavior: none;
overscroll-behavior-y: none;
-webkit-overflow-scrolling: touch;
@@ -57,7 +58,9 @@ a,
}
}
html, body, #app {
html,
body,
#app {
margin: 0;
padding: 0;
height: 100%;

View File

@@ -5,7 +5,10 @@
show-cancel-button
@confirm="handleConfirm"
>
<van-field v-model="classifyName" placeholder="请输入新的交易分类" />
<van-field
v-model="classifyName"
placeholder="请输入新的交易分类"
/>
</van-dialog>
</template>

View File

@@ -6,8 +6,12 @@
<van-field label="时间">
<template #input>
<div style="display: flex; gap: 16px">
<div @click="showDatePicker = true">{{ form.date }}</div>
<div @click="showTimePicker = true">{{ form.time }}</div>
<div @click="showDatePicker = true">
{{ form.date }}
</div>
<div @click="showTimePicker = true">
{{ form.time }}
</div>
</div>
</template>
</van-field>
@@ -37,9 +41,9 @@
<van-field name="type" label="类型">
<template #input>
<van-radio-group v-model="form.type" direction="horizontal" @change="handleTypeChange">
<van-radio :name="0">支出</van-radio>
<van-radio :name="1">收入</van-radio>
<van-radio :name="2">不计</van-radio>
<van-radio :name="0"> 支出 </van-radio>
<van-radio :name="1"> 收入 </van-radio>
<van-radio :name="2"> 不计 </van-radio>
</van-radio-group>
</template>
</van-field>
@@ -47,23 +51,20 @@
<!-- 分类 -->
<van-field name="category" label="分类">
<template #input>
<span v-if="!categoryName" style="color: var(--van-text-color-3);">请选择分类</span>
<span v-if="!categoryName" style="color: var(--van-text-color-3)">请选择分类</span>
<span v-else>{{ categoryName }}</span>
</template>
</van-field>
<!-- 分类选择组件 -->
<ClassifySelector
v-model="categoryName"
:type="form.type"
/>
<ClassifySelector v-model="categoryName" :type="form.type" />
</van-cell-group>
<div class="actions">
<van-button round block type="primary" native-type="submit" :loading="loading">
{{ submitText }}
</van-button>
<slot name="actions"></slot>
<slot name="actions" />
</div>
</van-form>
@@ -146,9 +147,15 @@ const initForm = async () => {
currentTime.value = form.value.time.split(':')
}
if (amount !== undefined) form.value.amount = amount
if (reason !== undefined) form.value.note = reason
if (type !== undefined) form.value.type = type
if (amount !== undefined) {
form.value.amount = amount
}
if (reason !== undefined) {
form.value.note = reason
}
if (type !== undefined) {
form.value.type = type
}
// 如果有传入分类名称,尝试设置
if (classify) {
@@ -166,9 +173,13 @@ onMounted(() => {
})
// 监听 initialData 变化 (例如重新解析后)
watch(() => props.initialData, () => {
initForm()
}, { deep: true })
watch(
() => props.initialData,
() => {
initForm()
},
{ deep: true }
)
const handleTypeChange = (newType) => {
if (!isSyncing.value) {

View File

@@ -1,10 +1,6 @@
<template>
<div class="manual-bill-add">
<BillForm
ref="billFormRef"
:loading="saving"
@submit="handleSave"
/>
<BillForm ref="billFormRef" :loading="saving" @submit="handleSave" />
</div>
</template>

View File

@@ -1,6 +1,6 @@
<template>
<div>
<div v-if="!parseResult" class="input-section" style="margin: 12px 12px 0 16px;">
<div v-if="!parseResult" class="input-section" style="margin: 12px 12px 0 16px">
<van-field
v-model="text"
type="textarea"
@@ -31,13 +31,7 @@
@submit="handleSave"
>
<template #actions>
<van-button
plain
round
block
class="mt-2"
@click="parseResult = null"
>
<van-button plain round block class="mt-2" @click="parseResult = null">
重新输入
</van-button>
</template>
@@ -60,14 +54,16 @@ const saving = ref(false)
const parseResult = ref(null)
const handleParse = async () => {
if (!text.value.trim()) return
if (!text.value.trim()) {
return
}
parsing.value = true
parseResult.value = null
try {
const res = await parseOneLine(text.value)
if(!res.success){
if (!res.success) {
throw new Error(res.message || '解析失败')
}

View File

@@ -9,14 +9,16 @@
<div class="budget-info">
<slot name="tag">
<van-tag
:type="budget.type === BudgetPeriodType.Year ? 'warning' : 'primary'"
:type="budget.type === BudgetPeriodType.Year ? 'warning' : 'primary'"
plain
class="status-tag"
>
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
</van-tag>
</slot>
<h3 class="card-title">{{ budget.name }}</h3>
<h3 class="card-title">
{{ budget.name }}
</h3>
<span v-if="budget.selectedCategories?.length" class="card-subtitle">
({{ budget.selectedCategories.join('') }})
</span>
@@ -29,9 +31,11 @@
<span class="compact-label">实际/目标</span>
<span class="compact-value">
<slot name="collapsed-amount">
{{ budget.current !== undefined && budget.limit !== undefined
? `¥${budget.current?.toFixed(0) || 0} / ¥${budget.limit?.toFixed(0) || 0}`
: '--' }}
{{
budget.current !== undefined && budget.limit !== undefined
? `¥${budget.current?.toFixed(0) || 0} / ¥${budget.limit?.toFixed(0) || 0}`
: '--'
}}
</slot>
</span>
</div>
@@ -45,18 +49,20 @@
<!-- 展开状态 -->
<div v-else class="budget-inner-card">
<div class="card-header" style="margin-bottom: 0;">
<div class="card-header" style="margin-bottom: 0">
<div class="budget-info">
<slot name="tag">
<van-tag
:type="budget.type === BudgetPeriodType.Year ? 'warning' : 'primary'"
:type="budget.type === BudgetPeriodType.Year ? 'warning' : 'primary'"
plain
class="status-tag"
>
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
</van-tag>
</slot>
<h3 class="card-title" style="max-width: 120px;">{{ budget.name }}</h3>
<h3 class="card-title" style="max-width: 120px">
{{ budget.name }}
</h3>
</div>
<div class="header-actions">
<slot name="actions">
@@ -76,12 +82,7 @@
@click.stop="handleQueryBills"
/>
<template v-if="budget.category !== 2">
<van-button
icon="edit"
size="small"
plain
@click.stop="$emit('click', budget)"
/>
<van-button icon="edit" size="small" plain @click.stop="$emit('click', budget)" />
</template>
</slot>
</div>
@@ -101,12 +102,14 @@
</van-tag>
</div>
<div class="amount-info">
<slot name="amount-info"></slot>
<slot name="amount-info" />
</div>
<div class="progress-section">
<slot name="progress-info">
<span class="period-type">{{ periodLabel }}{{ budget.category === 0 ? '使用' : '达成' }}</span>
<span class="period-type"
>{{ periodLabel }}{{ budget.category === 0 ? '使用' : '达成' }}</span
>
<van-progress
:percentage="Math.min(percentage, 100)"
stroke-width="8"
@@ -129,23 +132,19 @@
<van-collapse-transition>
<div v-if="budget.description && showDescription" class="budget-description">
<div class="description-content rich-html-content" v-html="budget.description"></div>
<div class="description-content rich-html-content" v-html="budget.description" />
</div>
</van-collapse-transition>
</div>
<div class="card-footer">
<slot name="footer"></slot>
<slot name="footer" />
</div>
</div>
</div>
<!-- 关联账单列表弹窗 -->
<PopupContainer
v-model="showBillListModal"
title="关联账单列表"
height="75%"
>
<PopupContainer v-model="showBillListModal" title="关联账单列表" height="75%">
<TransactionList
:transactions="billList"
:loading="billLoading"
@@ -166,15 +165,13 @@
<div class="collapsed-header">
<div class="budget-info">
<slot name="tag">
<van-tag
type="success"
plain
class="status-tag"
>
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
<van-tag type="success" plain class="status-tag">
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
</van-tag>
</slot>
<h3 class="card-title">{{ budget.name }}</h3>
<h3 class="card-title">
{{ budget.name }}
</h3>
<span v-if="budget.selectedCategories?.length" class="card-subtitle">
({{ budget.selectedCategories.join('') }})
</span>
@@ -187,9 +184,7 @@
<span class="compact-label">实际</span>
<span class="compact-value">
<slot name="collapsed-amount">
{{ budget.current !== undefined
? `¥${budget.current?.toFixed(0) || 0}`
: '--' }}
{{ budget.current !== undefined ? `¥${budget.current?.toFixed(0) || 0}` : '--' }}
</slot>
</span>
</div>
@@ -198,18 +193,16 @@
<!-- 展开状态 -->
<div v-else class="budget-inner-card">
<div class="card-header" style="margin-bottom: 0;">
<div class="card-header" style="margin-bottom: 0">
<div class="budget-info">
<slot name="tag">
<van-tag
type="success"
plain
class="status-tag"
>
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
<van-tag type="success" plain class="status-tag">
{{ budget.type === BudgetPeriodType.Year ? '年度' : '月度' }}
</van-tag>
</slot>
<h3 class="card-title" style="max-width: 120px;">{{ budget.name }}</h3>
<h3 class="card-title" style="max-width: 120px">
{{ budget.name }}
</h3>
</div>
<div class="header-actions">
<slot name="actions">
@@ -229,12 +222,7 @@
@click.stop="handleQueryBills"
/>
<template v-if="budget.category !== 2">
<van-button
icon="edit"
size="small"
plain
@click.stop="$emit('click', budget)"
/>
<van-button icon="edit" size="small" plain @click.stop="$emit('click', budget)" />
</template>
</slot>
</div>
@@ -257,22 +245,24 @@
<div class="no-limit-amount-info">
<div class="amount-item">
<span>
<span class="label">实际</span>
<span class="value" style="margin-left: 12px;">¥{{ budget.current?.toFixed(0) || 0 }}</span>
<span class="label">实际</span>
<span class="value" style="margin-left: 12px"
>¥{{ budget.current?.toFixed(0) || 0 }}</span
>
</span>
</div>
</div>
<div class="no-limit-notice">
<span>
<van-icon name="info-o" style="margin-right: 4px;" />
<van-icon name="info-o" style="margin-right: 4px" />
不记额预算 - 直接计入存款明细
</span>
</div>
<van-collapse-transition>
<div v-if="budget.description && showDescription" class="budget-description">
<div class="description-content rich-html-content" v-html="budget.description"></div>
<div class="description-content rich-html-content" v-html="budget.description" />
</div>
</van-collapse-transition>
</div>
@@ -280,11 +270,7 @@
</div>
<!-- 关联账单列表弹窗 -->
<PopupContainer
v-model="showBillListModal"
title="关联账单列表"
height="75%"
>
<PopupContainer v-model="showBillListModal" title="关联账单列表" height="75%">
<TransactionList
:transactions="billList"
:loading="billLoading"
@@ -362,12 +348,11 @@ const handleQueryBills = async () => {
sortByAmount: true
})
if(response.success) {
if (response.success) {
billList.value = response.data || []
} else {
billList.value = []
}
} catch (error) {
console.error('查询账单列表失败:', error)
billList.value = []
@@ -377,18 +362,26 @@ const handleQueryBills = async () => {
}
const percentage = computed(() => {
if (!props.budget.limit) return 0
if (!props.budget.limit) {
return 0
}
return Math.round((props.budget.current / props.budget.limit) * 100)
})
const timePercentage = computed(() => {
if (!props.budget.periodStart || !props.budget.periodEnd) return 0
if (!props.budget.periodStart || !props.budget.periodEnd) {
return 0
}
const start = new Date(props.budget.periodStart).getTime()
const end = new Date(props.budget.periodEnd).getTime()
const now = new Date().getTime()
if (now <= start) return 0
if (now >= end) return 100
if (now <= start) {
return 0
}
if (now >= end) {
return 100
}
return Math.round(((now - start) / (end - start)) * 100)
})

View File

@@ -1,7 +1,11 @@
<template>
<PopupContainer
v-model="visible"
:title="isEdit ? `编辑${getCategoryName(form.category)}预算` : `新增${getCategoryName(form.category)}预算`"
:title="
isEdit
? `编辑${getCategoryName(form.category)}预算`
: `新增${getCategoryName(form.category)}预算`
"
height="75%"
>
<div class="add-budget-form">
@@ -17,7 +21,9 @@
<!-- 新增不记额预算复选框 -->
<van-field label="不记额预算">
<template #input>
<van-checkbox v-model="form.noLimit" @update:model-value="onNoLimitChange">不记额预算仅限年度</van-checkbox>
<van-checkbox v-model="form.noLimit" @update:model-value="onNoLimitChange">
不记额预算仅限年度
</van-checkbox>
</template>
</van-field>
<van-field name="type" label="统计周期">
@@ -27,8 +33,8 @@
direction="horizontal"
:disabled="isEdit || form.noLimit"
>
<van-radio :name="BudgetPeriodType.Month"></van-radio>
<van-radio :name="BudgetPeriodType.Year"></van-radio>
<van-radio :name="BudgetPeriodType.Month"> </van-radio>
<van-radio :name="BudgetPeriodType.Year"> </van-radio>
</van-radio-group>
</template>
</van-field>
@@ -48,7 +54,12 @@
</van-field>
<van-field label="相关分类">
<template #input>
<div v-if="form.selectedCategories.length === 0" style="color: var(--van-text-color-3);">可多选分类</div>
<div
v-if="form.selectedCategories.length === 0"
style="color: var(--van-text-color-3)"
>
可多选分类
</div>
<div v-else class="selected-categories">
<span class="ellipsis-text">
{{ form.selectedCategories.join('、') }}
@@ -67,7 +78,7 @@
</van-form>
</div>
<template #footer>
<van-button block round type="primary" @click="onSubmit">保存预算</van-button>
<van-button block round type="primary" @click="onSubmit"> 保存预算 </van-button>
</template>
</PopupContainer>
</template>
@@ -92,15 +103,11 @@ const form = reactive({
category: BudgetCategory.Expense,
limit: '',
selectedCategories: [],
noLimit: false // 新增字段
noLimit: false // 新增字段
})
const open = ({
data,
isEditFlag,
category
}) => {
if(category === undefined) {
const open = ({ data, isEditFlag, category }) => {
if (category === undefined) {
showToast('缺少必要参数category')
return
}
@@ -114,7 +121,7 @@ const open = ({
category: category,
limit: data.limit,
selectedCategories: data.selectedCategories ? [...data.selectedCategories] : [],
noLimit: data.noLimit || false // 新增
noLimit: data.noLimit || false // 新增
})
} else {
Object.assign(form, {
@@ -124,7 +131,7 @@ const open = ({
category: category,
limit: '',
selectedCategories: [],
noLimit: false // 新增
noLimit: false // 新增
})
}
visible.value = true
@@ -135,16 +142,20 @@ defineExpose({
})
const budgetType = computed(() => {
return form.category === BudgetCategory.Expense ? 0 : (form.category === BudgetCategory.Income ? 1 : 2)
return form.category === BudgetCategory.Expense
? 0
: form.category === BudgetCategory.Income
? 1
: 2
})
const onSubmit = async () => {
try {
const data = {
...form,
limit: form.noLimit ? 0 : parseFloat(form.limit), // 不记额时金额为0
limit: form.noLimit ? 0 : parseFloat(form.limit), // 不记额时金额为0
selectedCategories: form.selectedCategories,
noLimit: form.noLimit // 新增
noLimit: form.noLimit // 新增
}
const res = form.id ? await updateBudget(data) : await createBudget(data)
@@ -160,7 +171,7 @@ const onSubmit = async () => {
}
const getCategoryName = (category) => {
switch(category) {
switch (category) {
case BudgetCategory.Expense:
return '支出'
case BudgetCategory.Income:

View File

@@ -1,7 +1,11 @@
<template>
<div class="summary-container">
<transition :name="transitionName" mode="out-in">
<div v-if="stats && (stats.month || stats.year)" :key="dateKey" class="summary-card common-card">
<div
v-if="stats && (stats.month || stats.year)"
:key="dateKey"
class="summary-card common-card"
>
<!-- 左切换按钮 -->
<div class="nav-arrow left" @click.stop="changeMonth(-1)">
<van-icon name="arrow-left" />
@@ -20,7 +24,7 @@
<span class="amount">¥{{ formatMoney(stats[key]?.limit || 0) }}</span>
</div>
</div>
<div v-if="config.showDivider" class="divider"></div>
<div v-if="config.showDivider" class="divider" />
</template>
</div>
@@ -71,8 +75,7 @@ const dateKey = computed(() => props.date.getFullYear() + '-' + props.date.getMo
const isCurrentMonth = computed(() => {
const now = new Date()
return props.date.getFullYear() === now.getFullYear() &&
props.date.getMonth() === now.getMonth()
return props.date.getFullYear() === now.getFullYear() && props.date.getMonth() === now.getMonth()
})
const periodConfigs = computed(() => ({
@@ -94,7 +97,10 @@ const changeMonth = (delta) => {
}
const formatMoney = (val) => {
return parseFloat(val || 0).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })
return parseFloat(val || 0).toLocaleString(undefined, {
minimumFractionDigits: 0,
maximumFractionDigits: 0
})
}
</script>

View File

@@ -1,9 +1,5 @@
<template>
<PopupContainer
v-model="visible"
title="设置存款分类"
height="60%"
>
<PopupContainer v-model="visible" title="设置存款分类" height="60%">
<div class="savings-config-content">
<div class="config-header">
<p class="subtitle">这些分类的统计值将计入存款</p>
@@ -22,7 +18,7 @@
</div>
<template #footer>
<van-button block round type="primary" @click="onSubmit">保存配置</van-button>
<van-button block round type="primary" @click="onSubmit"> 保存配置 </van-button>
</template>
</PopupContainer>
</template>
@@ -52,7 +48,7 @@ const fetchConfig = async () => {
try {
const res = await getConfig('SavingsCategories')
if (res.success && res.data) {
selectedCategories.value = res.data.split(',').filter(x => x)
selectedCategories.value = res.data.split(',').filter((x) => x)
} else {
selectedCategories.value = []
}

View File

@@ -98,17 +98,21 @@ const innerOptions = ref([])
const addClassifyDialogRef = ref()
const displayOptions = computed(() => {
if (props.options) return props.options
if (props.options) {
return props.options
}
return innerOptions.value
})
const fetchOptions = async () => {
if (props.options) return
if (props.options) {
return
}
try {
const response = await getCategoryList(props.type)
if (response.success) {
innerOptions.value = (response.data || []).map(item => ({
innerOptions.value = (response.data || []).map((item) => ({
text: item.name,
value: item.name,
id: item.id
@@ -152,9 +156,12 @@ const handleAddConfirm = async (categoryName) => {
}
}
watch(() => props.type, () => {
fetchOptions()
})
watch(
() => props.type,
() => {
fetchOptions()
}
)
onMounted(() => {
fetchOptions()
@@ -175,8 +182,10 @@ const isSelected = (item) => {
// 是否全部选中
const isAllSelected = computed(() => {
if (!props.multiple || displayOptions.value.length === 0) return false
return displayOptions.value.every(item => props.modelValue.includes(item.text))
if (!props.multiple || displayOptions.value.length === 0) {
return false
}
return displayOptions.value.every((item) => props.modelValue.includes(item.text))
})
// 是否有任何选中
@@ -208,13 +217,15 @@ const toggleItem = (item) => {
// 切换全选
const toggleAll = () => {
if (!props.multiple) return
if (!props.multiple) {
return
}
if (isAllSelected.value) {
emit('update:modelValue', [])
emit('change', [])
} else {
const allValues = displayOptions.value.map(item => item.text)
const allValues = displayOptions.value.map((item) => item.text)
emit('update:modelValue', allValues)
emit('change', allValues)
}

View File

@@ -42,16 +42,14 @@
</div>
<div class="heatmap-footer">
<div v-if="totalCount > 0" class="summary-text">
过去一年共 {{ totalCount }} 笔交易
</div>
<div v-if="totalCount > 0" class="summary-text">过去一年共 {{ totalCount }} 笔交易</div>
<div class="legend">
<span></span>
<div class="legend-item level-0"></div>
<div class="legend-item level-1"></div>
<div class="legend-item level-2"></div>
<div class="legend-item level-3"></div>
<div class="legend-item level-4"></div>
<div class="legend-item level-0" />
<div class="legend-item level-1" />
<div class="legend-item level-2" />
<div class="legend-item level-3" />
<div class="legend-item level-4" />
<span></span>
</div>
</div>
@@ -59,84 +57,84 @@
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { getDailyStatisticsRange } from '@/api/statistics';
import { ref, onMounted, nextTick } from 'vue'
import { getDailyStatisticsRange } from '@/api/statistics'
const stats = ref({});
const weeks = ref([]);
const monthLabels = ref([]);
const totalCount = ref(0);
const scrollContainer = ref(null);
const thresholds = ref([2, 4, 7]); // Default thresholds
const stats = ref({})
const weeks = ref([])
const monthLabels = ref([])
const totalCount = ref(0)
const scrollContainer = ref(null)
const thresholds = ref([2, 4, 7]) // Default thresholds
const CELL_SIZE = 15;
const CELL_GAP = 3;
const WEEK_WIDTH = CELL_SIZE + CELL_GAP;
const CELL_SIZE = 15
const CELL_GAP = 3
const WEEK_WIDTH = CELL_SIZE + CELL_GAP
const formatDate = (d) => {
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
const fetchData = async () => {
const endDate = new Date();
const startDate = new Date();
startDate.setFullYear(endDate.getFullYear() - 1);
const endDate = new Date()
const startDate = new Date()
startDate.setFullYear(endDate.getFullYear() - 1)
try {
const res = await getDailyStatisticsRange({
startDate: formatDate(startDate),
endDate: formatDate(endDate)
});
})
if (res.success) {
const map = {};
let count = 0;
res.data.forEach(item => {
map[item.date] = item;
count += item.count;
});
stats.value = map;
totalCount.value = count;
const map = {}
let count = 0
res.data.forEach((item) => {
map[item.date] = item
count += item.count
})
stats.value = map
totalCount.value = count
// Calculate thresholds based on last 15 days average
const today = new Date();
let last15DaysSum = 0;
for(let i = 0; i < 15; i++) {
const d = new Date(today);
d.setDate(d.getDate() - i);
const dateStr = formatDate(d);
last15DaysSum += (map[dateStr]?.count || 0);
const today = new Date()
let last15DaysSum = 0
for (let i = 0; i < 15; i++) {
const d = new Date(today)
d.setDate(d.getDate() - i)
const dateStr = formatDate(d)
last15DaysSum += map[dateStr]?.count || 0
}
const avg = last15DaysSum / 15;
console.log("avg", avg)
const avg = last15DaysSum / 15
console.log('avg', avg)
// Step size calculation: ensure at least 1, roughly avg/2 to create spread
// Level 1: 1 ~ step
// Level 2: step+1 ~ step*2
// Level 3: step*2+1 ~ step*3
// Level 4: > step*3
const step = Math.max(Math.ceil(avg / 2), 1);
thresholds.value = [step, step * 2, step * 3];
const step = Math.max(Math.ceil(avg / 2), 1)
thresholds.value = [step, step * 2, step * 3]
generateHeatmapData(startDate, endDate);
generateHeatmapData(startDate, endDate)
}
} catch (e) {
console.error("Failed to fetch heatmap data", e);
console.error('Failed to fetch heatmap data', e)
}
};
}
const generateHeatmapData = (startDate, endDate) => {
const data = [];
const current = new Date(startDate);
const data = []
const current = new Date(startDate)
const allDays = [];
const allDays = []
// Adjust start date to be Monday to align weeks
// 0 = Sunday, 1 = Monday
const startDay = current.getDay();
const startDay = current.getDay()
// If startDay is 0 (Sunday), we need to go back 6 days to Monday
// If startDay is 1 (Monday), we are good
// If startDay is 2 (Tuesday), we need to go back 1 day
@@ -145,113 +143,123 @@ const generateHeatmapData = (startDate, endDate) => {
// Sunday (0) -> 6 days back
// Tuesday (2) -> 1 day back
const daysToSubtract = (startDay + 6) % 7;
const daysToSubtract = (startDay + 6) % 7
// We don't necessarily need to subtract from startDate for data fetching,
// but for grid alignment we want the first column to start on Monday.
const alignStart = new Date(startDate);
const alignStart = new Date(startDate)
// alignStart.setDate(alignStart.getDate() - daysToSubtract);
const tempDate = new Date(alignStart);
const tempDate = new Date(alignStart)
while (tempDate <= endDate) {
const dateStr = formatDate(tempDate);
const dateStr = formatDate(tempDate)
allDays.push({
date: dateStr,
count: stats.value[dateStr]?.count || 0,
obj: new Date(tempDate)
});
tempDate.setDate(tempDate.getDate() + 1);
})
tempDate.setDate(tempDate.getDate() + 1)
}
// Now group into weeks
const resultWeeks = [];
let currentWeek = [];
const resultWeeks = []
let currentWeek = []
// Pad first week if start date is not Monday
// allDays[0] is startDate
const firstDayObj = new Date(allDays[0].date);
const firstDay = firstDayObj.getDay(); // 0-6 (Sun-Sat)
const firstDayObj = new Date(allDays[0].date)
const firstDay = firstDayObj.getDay() // 0-6 (Sun-Sat)
// We want Monday (1) to be index 0
// Mon(1)->0, Tue(2)->1, ..., Sun(0)->6
const padCount = (firstDay + 6) % 7;
const padCount = (firstDay + 6) % 7
for (let i = 0; i < padCount; i++) {
currentWeek.push(null);
currentWeek.push(null)
}
allDays.forEach(day => {
currentWeek.push(day);
allDays.forEach((day) => {
currentWeek.push(day)
if (currentWeek.length === 7) {
resultWeeks.push(currentWeek);
currentWeek = [];
resultWeeks.push(currentWeek)
currentWeek = []
}
});
})
// Push last partial week
if (currentWeek.length > 0) {
while (currentWeek.length < 7) {
currentWeek.push(null);
currentWeek.push(null)
}
resultWeeks.push(currentWeek);
resultWeeks.push(currentWeek)
}
weeks.value = resultWeeks;
weeks.value = resultWeeks
// Generate Month Labels
const labels = [];
let lastMonth = -1;
const labels = []
let lastMonth = -1
resultWeeks.forEach((week, index) => {
// Check the first valid day in the week
const day = week.find(d => d !== null);
const day = week.find((d) => d !== null)
if (day) {
const d = new Date(day.date);
const month = d.getMonth();
const d = new Date(day.date)
const month = d.getMonth()
if (month !== lastMonth) {
labels.push({
text: d.toLocaleString('zh-CN', { month: 'short' }),
left: index * WEEK_WIDTH
});
lastMonth = month;
})
lastMonth = month
}
}
});
})
monthLabels.value = labels;
monthLabels.value = labels
// Scroll to end
nextTick(() => {
if (scrollContainer.value) {
scrollContainer.value.scrollLeft = scrollContainer.value.scrollWidth;
scrollContainer.value.scrollLeft = scrollContainer.value.scrollWidth
}
});
};
})
}
const getLevelClass = (day) => {
if (!day) return 'invisible';
const count = day.count;
if (count === 0) return 'level-0';
if (count <= thresholds.value[0]) return 'level-1';
if (count <= thresholds.value[1]) return 'level-2';
if (count <= thresholds.value[2]) return 'level-3';
return 'level-4';
};
if (!day) {
return 'invisible'
}
const count = day.count
if (count === 0) {
return 'level-0'
}
if (count <= thresholds.value[0]) {
return 'level-1'
}
if (count <= thresholds.value[1]) {
return 'level-2'
}
if (count <= thresholds.value[2]) {
return 'level-3'
}
return 'level-4'
}
const onCellClick = (day) => {
if (day) {
// Emit event or show toast
// console.log(day);
}
};
}
defineExpose({
refresh: fetchData
});
})
onMounted(() => {
fetchData();
});
fetchData()
})
</script>
<style scoped>
@@ -260,7 +268,7 @@ onMounted(() => {
border-radius: 8px;
padding: 12px;
color: var(--van-text-color);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
margin: 0 10px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border: 1px solid var(--van-border-color);
@@ -357,7 +365,9 @@ onMounted(() => {
*/
margin-top: 21px;
}
.weekday-label:first-child { margin-top: 18px; }
.weekday-label:first-child {
margin-top: 18px;
}
.heatmap-grid {
display: flex;
@@ -382,12 +392,22 @@ onMounted(() => {
background-color: transparent;
}
.level-0 { background-color: var(--van-gray-2); }
.level-0 {
background-color: var(--van-gray-2);
}
/* Default (Light Mode) - Light to Deep Green */
.level-1 { background-color: #9be9a8; }
.level-2 { background-color: #40c463; }
.level-3 { background-color: #30a14e; }
.level-4 { background-color: #216e39; }
.level-1 {
background-color: #9be9a8;
}
.level-2 {
background-color: #40c463;
}
.level-3 {
background-color: #30a14e;
}
.level-4 {
background-color: #216e39;
}
/* Dark Mode - Dark to Light/Bright Green (GitHub Dark Mode Style) */
/* The user requested "From Light to Deep" (浅至深) which usually means standard heatmap logic (darker = more).
@@ -417,10 +437,18 @@ onMounted(() => {
This goes from Dark Green -> Bright Green.
*/
@media (prefers-color-scheme: dark) {
.level-1 { background-color: #9be9a8; }
.level-2 { background-color: #40c463; }
.level-3 { background-color: #30a14e; }
.level-4 { background-color: #216e39; }
.level-1 {
background-color: #9be9a8;
}
.level-2 {
background-color: #40c463;
}
.level-3 {
background-color: #30a14e;
}
.level-4 {
background-color: #216e39;
}
}
.heatmap-footer {

View File

@@ -6,11 +6,7 @@
</div>
<!-- Add Bill Modal -->
<PopupContainer
v-model="showAddBill"
title="记一笔"
height="75%"
>
<PopupContainer v-model="showAddBill" title="记一笔" height="75%">
<van-tabs v-model:active="activeTab" shrink>
<van-tab title="一句话录账" name="one">
<OneLineBillAdd :key="componentKey" @success="handleSuccess" />

View File

@@ -13,10 +13,12 @@
<div class="popup-header-fixed">
<!-- 标题行 (无子标题且有操作时使用 Grid 布局) -->
<div class="header-title-row" :class="{ 'has-actions': !subtitle && hasActions }">
<h3 class="popup-title">{{ title }}</h3>
<h3 class="popup-title">
{{ title }}
</h3>
<!-- 无子标题时操作按钮与标题同行 -->
<div v-if="!subtitle && hasActions" class="header-actions-inline">
<slot name="header-actions"></slot>
<slot name="header-actions" />
</div>
</div>
@@ -24,18 +26,18 @@
<div v-if="subtitle" class="header-stats">
<span class="stats-text" v-html="subtitle" />
<!-- 额外操作插槽 -->
<slot v-if="hasActions" name="header-actions"></slot>
<slot v-if="hasActions" name="header-actions" />
</div>
</div>
<!-- 内容区域可滚动 -->
<div class="popup-scroll-content">
<slot></slot>
<slot />
</div>
<!-- 底部页脚固定不可滚动 -->
<div v-if="slots.footer" class="popup-footer-fixed">
<slot name="footer"></slot>
<slot name="footer" />
</div>
</div>
</van-popup>
@@ -47,24 +49,24 @@ import { computed, useSlots } from 'vue'
const props = defineProps({
modelValue: {
type: Boolean,
required: true,
required: true
},
title: {
type: String,
default: '',
default: ''
},
subtitle: {
type: String,
default: '',
default: ''
},
height: {
type: String,
default: '80%',
default: '80%'
},
closeable: {
type: Boolean,
default: true,
},
default: true
}
})
const emit = defineEmits(['update:modelValue'])
@@ -74,7 +76,7 @@ const slots = useSlots()
// 双向绑定
const visible = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value),
set: (value) => emit('update:modelValue', value)
})
// 判断是否有操作按钮

View File

@@ -1,8 +1,14 @@
<template>
<div class="reason-group-list-v2">
<van-empty v-if="groups.length === 0 && !loading" description="暂无数据" />
<van-empty
v-if="groups.length === 0 && !loading"
description="暂无数据"
/>
<van-cell-group v-else inset>
<van-cell-group
v-else
inset
>
<van-cell
v-for="group in groups"
:key="group.reason"
@@ -27,7 +33,7 @@
<van-tag
:type="getTypeColor(group.sampleType)"
size="medium"
style="margin-right: 8px;"
style="margin-right: 8px"
>
{{ getTypeName(group.sampleType) }}
</van-tag>
@@ -35,12 +41,15 @@
v-if="group.sampleClassify"
type="primary"
size="medium"
style="margin-right: 8px;"
style="margin-right: 8px"
>
{{ group.sampleClassify }}
</van-tag>
<span class="count-text">{{ group.count }} </span>
<span v-if="group.totalAmount" class="amount-text">
<span
v-if="group.totalAmount"
class="amount-text"
>
¥{{ Math.abs(group.totalAmount).toFixed(2) }}
</span>
</div>
@@ -92,7 +101,10 @@
title="批量设置分类"
height="60%"
>
<van-form ref="batchFormRef" class="setting-form">
<van-form
ref="batchFormRef"
class="setting-form"
>
<van-cell-group inset>
<!-- 显示选中的摘要 -->
<van-field
@@ -111,20 +123,38 @@
/>
<!-- 交易类型 -->
<van-field name="type" label="交易类型">
<van-field
name="type"
label="交易类型"
>
<template #input>
<van-radio-group v-model="batchForm.type" direction="horizontal">
<van-radio :name="0">支出</van-radio>
<van-radio :name="1">收入</van-radio>
<van-radio :name="2">不计</van-radio>
<van-radio-group
v-model="batchForm.type"
direction="horizontal"
>
<van-radio :name="0">
支出
</van-radio>
<van-radio :name="1">
收入
</van-radio>
<van-radio :name="2">
不计
</van-radio>
</van-radio-group>
</template>
</van-field>
<!-- 分类选择 -->
<van-field name="classify" label="分类">
<van-field
name="classify"
label="分类"
>
<template #input>
<span v-if="!batchForm.classify" style="opacity: 0.4;">请选择分类</span>
<span
v-if="!batchForm.classify"
style="opacity: 0.4"
>请选择分类</span>
<span v-else>{{ batchForm.classify }}</span>
</template>
</van-field>
@@ -152,13 +182,7 @@
<script setup>
import { ref, computed, watch, onBeforeUnmount } from 'vue'
import {
showToast,
showSuccessToast,
showLoadingToast,
closeToast,
showConfirmDialog
} from 'vant'
import { showToast, showSuccessToast, showLoadingToast, closeToast, showConfirmDialog } from 'vant'
import { getReasonGroups, batchUpdateByReason, getTransactionList } from '@/api/transactionRecord'
import ClassifySelector from './ClassifySelector.vue'
import TransactionList from './TransactionList.vue'
@@ -212,9 +236,12 @@ const batchForm = ref({
})
// 监听交易类型变化,重新加载分类
watch(() => batchForm.value.type, (newVal) => {
batchForm.value.classify = ''
})
watch(
() => batchForm.value.type,
(newVal) => {
batchForm.value.classify = ''
}
)
// 获取类型名称
const getTypeName = (type) => {
@@ -256,7 +283,9 @@ const handleGroupClick = async (group) => {
// 加载分组的交易记录
const loadGroupTransactions = async () => {
if (transactionFinished.value || !selectedGroup.value) return
if (transactionFinished.value || !selectedGroup.value) {
return
}
transactionLoading.value = true
try {
@@ -354,19 +383,17 @@ const handleConfirmBatchUpdate = async () => {
emit('data-changed')
try {
window.dispatchEvent(
new CustomEvent(
'transactions-changed',
{
detail: {
reason: batchGroup.value.reason
}
})
)
} catch(e) {
new CustomEvent('transactions-changed', {
detail: {
reason: batchGroup.value.reason
}
})
)
} catch (e) {
console.error('触发全局 transactions-changed 事件失败:', e)
}
// 关闭弹窗
showTransactionList.value = false
}
// 关闭弹窗
showTransactionList.value = false
} else {
showToast(res.message || '批量更新失败')
}
@@ -398,18 +425,18 @@ const handleTransactionClick = (transaction) => {
// 处理分组中的删除事件
const handleGroupTransactionDelete = async (transactionId) => {
groupTransactions.value = groupTransactions.value.filter(t => t.id !== transactionId)
groupTransactions.value = groupTransactions.value.filter((t) => t.id !== transactionId)
groupTransactionsTotal.value = Math.max(0, (groupTransactionsTotal.value || 0) - 1)
if(groupTransactions.value.length === 0 && !transactionFinished.value) {
if (groupTransactions.value.length === 0 && !transactionFinished.value) {
// 如果当前页数据为空且未加载完,则尝试加载下一页
await loadGroupTransactions()
}
if(groupTransactions.value.length === 0){
if (groupTransactions.value.length === 0) {
// 如果删除后当前分组没有交易了,关闭弹窗
showTransactionList.value = false
groups.value = groups.value.filter(g => g.reason !== selectedGroup.value.reason)
groups.value = groups.value.filter((g) => g.reason !== selectedGroup.value.reason)
selectedGroup.value = null
total.value--
}
@@ -433,10 +460,12 @@ const onGlobalTransactionDeleted = () => {
}
}
window.addEventListener && window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.addEventListener &&
window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.removeEventListener &&
window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
})
// 当有交易新增/修改/批量更新时的刷新监听
@@ -451,10 +480,12 @@ const onGlobalTransactionsChanged = () => {
}
}
window.addEventListener && window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
window.addEventListener &&
window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
window.removeEventListener &&
window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
})
// 处理账单保存后的回调
@@ -471,7 +502,9 @@ const handleTransactionSaved = async () => {
* 加载数据(支持分页)
*/
const loadData = async () => {
if (finished.value) return
if (finished.value) {
return
}
loading.value = true
try {
@@ -522,7 +555,7 @@ const refresh = async () => {
*/
const getList = (onlySelected = false) => {
if (onlySelected && props.selectable) {
return groups.value.filter(g => selectedReasons.value.has(g.reason))
return groups.value.filter((g) => selectedReasons.value.has(g.reason))
}
return [...groups.value]
}
@@ -564,7 +597,7 @@ const clearSelection = () => {
* 全选
*/
const selectAll = () => {
selectedReasons.value = new Set(groups.value.map(g => g.reason))
selectedReasons.value = new Set(groups.value.map((g) => g.reason))
}
// 暴露方法给父组件

View File

@@ -11,7 +11,7 @@
>
<template v-if="!loading && !saving">
<van-icon :name="buttonIcon" />
<span style="margin-left: 4px;">{{ buttonText }}</span>
<span style="margin-left: 4px">{{ buttonText }}</span>
</template>
</van-button>
</template>
@@ -52,28 +52,42 @@ const hasClassifiedResults = computed(() => {
// 按钮类型
const buttonType = computed(() => {
if (saving.value) return 'warning'
if (loading.value) return 'primary'
if (hasClassifiedResults.value) return 'success'
if (saving.value) {
return 'warning'
}
if (loading.value) {
return 'primary'
}
if (hasClassifiedResults.value) {
return 'success'
}
return 'primary'
})
// 按钮图标
const buttonIcon = computed(() => {
if (hasClassifiedResults.value) return 'success'
if (hasClassifiedResults.value) {
return 'success'
}
return 'fire'
})
// 按钮文字(非加载状态)
const buttonText = computed(() => {
if (hasClassifiedResults.value) return '保存分类'
if (hasClassifiedResults.value) {
return '保存分类'
}
return '智能分类'
})
// 加载中文字
const loadingText = computed(() => {
if (saving.value) return '保存中...'
if (loading.value) return '分类中...'
if (saving.value) {
return '保存中...'
}
if (loading.value) {
return '分类中...'
}
return ''
})
@@ -92,7 +106,9 @@ const handleClick = () => {
* 保存分类结果
*/
const handleSaveClassify = async () => {
if (saving.value || loading.value) return
if (saving.value || loading.value) {
return
}
try {
saving.value = true
@@ -104,7 +120,7 @@ const handleSaveClassify = async () => {
})
// 准备批量更新数据
const items = classifiedResults.value.map(item => ({
const items = classifiedResults.value.map((item) => ({
id: item.id,
classify: item.classify,
type: item.type
@@ -161,7 +177,7 @@ const handleSmartClassify = async () => {
return
}
if(lockClassifiedResults.value) {
if (lockClassifiedResults.value) {
showToast('当前有分类任务正在进行,请稍后再试')
loading.value = false
return
@@ -200,7 +216,7 @@ const handleSmartClassify = async () => {
// 分批处理
for (let i = 0; i < allTransactions.length; i += batchSize) {
const batch = allTransactions.slice(i, i + batchSize)
const transactionIds = batch.map(t => t.id)
const transactionIds = batch.map((t) => t.id)
const currentBatch = Math.floor(i / batchSize) + 1
const totalBatches = Math.ceil(allTransactions.length / batchSize)
@@ -229,7 +245,9 @@ const handleSmartClassify = async () => {
while (true) {
const { done, value } = await reader.read()
if (done) break
if (done) {
break
}
buffer += decoder.decode(value, { stream: true })
@@ -238,7 +256,9 @@ const handleSmartClassify = async () => {
buffer = events.pop() || '' // 保留最后一个不完整的部分
for (const eventBlock of events) {
if (!eventBlock.trim()) continue
if (!eventBlock.trim()) {
continue
}
try {
const lines = eventBlock.split('\n')
@@ -276,7 +296,7 @@ const handleSmartClassify = async () => {
})
// 实时更新交易记录的分类信息
const index = props.transactions.findIndex(t => t.id === data.id)
const index = props.transactions.findIndex((t) => t.id === data.id)
if (index !== -1) {
const transaction = props.transactions[index]
transaction.upsetedClassify = data.Classify
@@ -344,14 +364,14 @@ const handleSmartClassify = async () => {
const removeClassifiedTransaction = (transactionId) => {
// 从已分类结果中移除指定ID的项
classifiedResults.value = classifiedResults.value.filter(item => item.id !== transactionId)
classifiedResults.value = classifiedResults.value.filter((item) => item.id !== transactionId)
}
/**
* 重置组件状态
*/
const reset = () => {
if(lockClassifiedResults.value) {
if (lockClassifiedResults.value) {
showToast('当前有分类任务正在进行,无法重置')
return
}
@@ -365,8 +385,7 @@ const reset = () => {
defineExpose({
reset,
removeClassifiedTransaction
});
})
</script>
<style scoped>

View File

@@ -1,118 +1,119 @@
<template>
<PopupContainer
v-model="visible"
title="交易详情"
height="75%"
:closeable="false"
>
<PopupContainer v-model="visible" title="交易详情" height="75%" :closeable="false">
<template #header-actions>
<van-button size="small" type="primary" plain @click="handleOffsetClick">抵账</van-button>
<van-button size="small" type="primary" plain @click="handleOffsetClick"> 抵账 </van-button>
</template>
<van-form style="margin-top: 12px;">
<van-cell-group inset>
<van-cell title="记录时间" :value="formatDate(transaction.createTime)" />
</van-cell-group>
<van-form style="margin-top: 12px">
<van-cell-group inset>
<van-cell title="记录时间" :value="formatDate(transaction.createTime)" />
</van-cell-group>
<van-cell-group inset title="交易明细">
<van-field
v-model="occurredAtLabel"
name="occurredAt"
label="交易时间"
readonly
is-link
placeholder="请选择交易时间"
:rules="[{ required: true, message: '请选择交易时间' }]"
@click="showDatePicker = true"
/>
<van-field
v-model="editForm.reason"
name="reason"
label="交易摘要"
placeholder="请输入交易摘要"
type="textarea"
rows="2"
autosize
maxlength="200"
show-word-limit
/>
<van-field
v-model="editForm.amount"
name="amount"
label="交易金额"
placeholder="请输入交易金额"
type="number"
:rules="[{ required: true, message: '请输入交易金额' }]"
/>
<van-field
v-model="editForm.balance"
name="balance"
label="交易后余额"
placeholder="请输入交易后余额"
type="number"
:rules="[{ required: true, message: '请输入交易后余额' }]"
/>
<van-cell-group inset title="交易明细">
<van-field
v-model="occurredAtLabel"
name="occurredAt"
label="交易时间"
readonly
is-link
placeholder="请选择交易时间"
:rules="[{ required: true, message: '请选择交易时间' }]"
@click="showDatePicker = true"
/>
<van-field
v-model="editForm.reason"
name="reason"
label="交易摘要"
placeholder="请输入交易摘要"
type="textarea"
rows="2"
autosize
maxlength="200"
show-word-limit
/>
<van-field
v-model="editForm.amount"
name="amount"
label="交易金额"
placeholder="请输入交易金额"
type="number"
:rules="[{ required: true, message: '请输入交易金额' }]"
/>
<van-field
v-model="editForm.balance"
name="balance"
label="交易后余额"
placeholder="请输入交易后余额"
type="number"
:rules="[{ required: true, message: '请输入交易后余额' }]"
/>
<van-field name="type" label="交易类型">
<template #input>
<van-radio-group v-model="editForm.type" direction="horizontal" @change="handleTypeChange">
<van-radio :name="0">支出</van-radio>
<van-radio :name="1">收入</van-radio>
<van-radio :name="2">不计</van-radio>
</van-radio-group>
</template>
</van-field>
<van-field name="type" label="交易类型">
<template #input>
<van-radio-group
v-model="editForm.type"
direction="horizontal"
@change="handleTypeChange"
>
<van-radio :name="0"> 支出 </van-radio>
<van-radio :name="1"> 收入 </van-radio>
<van-radio :name="2"> 不计 </van-radio>
</van-radio-group>
</template>
</van-field>
<van-field name="classify" label="交易分类">
<template #input>
<div style="flex: 1;">
<div
v-if="transaction && transaction.unconfirmedClassify && transaction.unconfirmedClassify !== editForm.classify"
class="suggestion-tip"
@click="applySuggestion"
>
<van-icon name="bulb-o" class="suggestion-icon" />
<span class="suggestion-text">
建议: {{ transaction.unconfirmedClassify }}
<span v-if="transaction.unconfirmedType !== null && transaction.unconfirmedType !== undefined && transaction.unconfirmedType !== editForm.type">
({{ getTypeName(transaction.unconfirmedType) }})
</span>
<van-field name="classify" label="交易分类">
<template #input>
<div style="flex: 1">
<div
v-if="
transaction &&
transaction.unconfirmedClassify &&
transaction.unconfirmedClassify !== editForm.classify
"
class="suggestion-tip"
@click="applySuggestion"
>
<van-icon name="bulb-o" class="suggestion-icon" />
<span class="suggestion-text">
建议: {{ transaction.unconfirmedClassify }}
<span
v-if="
transaction.unconfirmedType !== null &&
transaction.unconfirmedType !== undefined &&
transaction.unconfirmedType !== editForm.type
"
>
({{ getTypeName(transaction.unconfirmedType) }})
</span>
<div class="suggestion-apply">应用</div>
</div>
<span v-else-if="!editForm.classify" style="color: var(--van-gray-5);">请选择交易分类</span>
<span v-else>{{ editForm.classify }}</span>
</span>
<div class="suggestion-apply">应用</div>
</div>
</template>
</van-field>
<span v-else-if="!editForm.classify" style="color: var(--van-gray-5)"
>请选择交易分类</span
>
<span v-else>{{ editForm.classify }}</span>
</div>
</template>
</van-field>
<ClassifySelector
v-model="editForm.classify"
:type="editForm.type"
@change="handleClassifyChange"
/>
</van-cell-group>
<ClassifySelector
v-model="editForm.classify"
:type="editForm.type"
@change="handleClassifyChange"
/>
</van-cell-group>
</van-form>
<template #footer>
<van-button
round
block
type="primary"
:loading="submitting"
@click="onSubmit"
>
<van-button round block type="primary" :loading="submitting" @click="onSubmit">
保存修改
</van-button>
</template>
</PopupContainer>
<!-- 抵账候选列表弹窗 -->
<PopupContainer
v-model="showOffsetPopup"
title="选择抵账交易"
height="75%"
>
<PopupContainer v-model="showOffsetPopup" title="选择抵账交易" height="75%">
<van-list>
<van-cell
v-for="item in offsetCandidates"
@@ -154,7 +155,11 @@ import { showToast, showConfirmDialog } from 'vant'
import dayjs from 'dayjs'
import PopupContainer from '@/components/PopupContainer.vue'
import ClassifySelector from '@/components/ClassifySelector.vue'
import { updateTransaction, getCandidatesForOffset, offsetTransactions } from '@/api/transactionRecord'
import {
updateTransaction,
getCandidatesForOffset,
offsetTransactions
} from '@/api/transactionRecord'
const props = defineProps({
show: {
@@ -196,35 +201,41 @@ const occurredAtLabel = computed(() => {
})
// 监听props变化
watch(() => props.show, (newVal) => {
visible.value = newVal
})
watch(() => props.transaction, (newVal) => {
if (newVal) {
isSyncing.value = true
// 填充编辑表单
editForm.id = newVal.id
editForm.reason = newVal.reason || ''
editForm.amount = String(newVal.amount)
editForm.balance = String(newVal.balance)
editForm.type = newVal.type
editForm.classify = newVal.classify || ''
// 初始化日期时间
if (newVal.occurredAt) {
editForm.occurredAt = newVal.occurredAt
const dt = dayjs(newVal.occurredAt)
currentDate.value = dt.format('YYYY-MM-DD').split('-')
currentTime.value = dt.format('HH:mm').split(':')
}
// 在下一个 tick 结束同步状态,确保 van-radio-group 的 @change 已触发完毕
nextTick(() => {
isSyncing.value = false
})
watch(
() => props.show,
(newVal) => {
visible.value = newVal
}
})
)
watch(
() => props.transaction,
(newVal) => {
if (newVal) {
isSyncing.value = true
// 填充编辑表单
editForm.id = newVal.id
editForm.reason = newVal.reason || ''
editForm.amount = String(newVal.amount)
editForm.balance = String(newVal.balance)
editForm.type = newVal.type
editForm.classify = newVal.classify || ''
// 初始化日期时间
if (newVal.occurredAt) {
editForm.occurredAt = newVal.occurredAt
const dt = dayjs(newVal.occurredAt)
currentDate.value = dt.format('YYYY-MM-DD').split('-')
currentTime.value = dt.format('HH:mm').split(':')
}
// 在下一个 tick 结束同步状态,确保 van-radio-group 的 @change 已触发完毕
nextTick(() => {
isSyncing.value = false
})
}
}
)
watch(visible, (newVal) => {
emit('update:show', newVal)
@@ -258,7 +269,10 @@ const onConfirmTime = ({ selectedValues }) => {
const applySuggestion = () => {
if (props.transaction.unconfirmedClassify) {
editForm.classify = props.transaction.unconfirmedClassify
if (props.transaction.unconfirmedType !== null && props.transaction.unconfirmedType !== undefined) {
if (
props.transaction.unconfirmedType !== null &&
props.transaction.unconfirmedType !== undefined
) {
editForm.type = props.transaction.unconfirmedType
}
}
@@ -314,7 +328,9 @@ const handleClassifyChange = () => {
// 清空分类
const formatDate = (dateString) => {
if (!dateString) return ''
if (!dateString) {
return ''
}
const date = new Date(dateString)
return date.toLocaleString('zh-CN', {
year: 'numeric',
@@ -347,7 +363,7 @@ const handleOffsetClick = async () => {
const handleCandidateSelect = (candidate) => {
showConfirmDialog({
title: '确认抵账',
message: `确认将当前交易与 "${candidate.reason}" (${candidate.amount}) 互相抵消吗?\n抵消后两笔交易将被删除`,
message: `确认将当前交易与 "${candidate.reason}" (${candidate.amount}) 互相抵消吗\n抵消后两笔交易将被删除`
})
.then(async () => {
try {
@@ -367,7 +383,7 @@ const handleCandidateSelect = (candidate) => {
})
.catch(() => {
// on cancel
});
})
}
</script>

View File

@@ -1,11 +1,6 @@
<template>
<div class="transaction-list-container transaction-list">
<van-list
:loading="loading"
:finished="finished"
finished-text="没有更多了"
@load="onLoad"
>
<van-list :loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
<van-cell-group v-if="transactions && transactions.length" inset style="margin-top: 10px">
<van-swipe-cell
v-for="transaction in transactions"
@@ -19,10 +14,7 @@
class="checkbox-col"
@update:model-value="toggleSelection(transaction)"
/>
<div
class="transaction-card"
@click="handleClick(transaction)"
>
<div class="transaction-card" @click="handleClick(transaction)">
<div class="card-left">
<div class="transaction-title">
<span class="reason">{{ transaction.reason || '(无摘要)' }}</span>
@@ -30,34 +22,32 @@
<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: var(--van-warning-color)">
<span v-if="transaction.classify"> 分类: {{ transaction.classify }} </span>
<span
v-if="
transaction.upsetedClassify &&
transaction.upsetedClassify !== transaction.classify
"
style="color: var(--van-warning-color)"
>
→ {{ transaction.upsetedClassify }}
</span>
</div>
<div v-if="transaction.importFrom">
来源: {{ transaction.importFrom }}
</div>
<div v-if="transaction.importFrom">来源: {{ transaction.importFrom }}</div>
</div>
</div>
<div class="card-middle">
<van-tag
:type="getTypeTagType(transaction.type)"
size="medium"
>
<van-tag :type="getTypeTagType(transaction.type)" size="medium">
{{ getTypeName(transaction.type) }}
</van-tag>
<template
v-if="Number.isFinite(transaction.upsetedType) && transaction.upsetedType !== transaction.type"
v-if="
Number.isFinite(transaction.upsetedType) &&
transaction.upsetedType !== transaction.type
"
>
<van-tag
:type="getTypeTagType(transaction.upsetedType)"
size="medium"
>
<van-tag :type="getTypeTagType(transaction.upsetedType)" size="medium">
{{ getTypeName(transaction.upsetedType) }}
</van-tag>
</template>
@@ -70,7 +60,10 @@
<div v-if="transaction.balance && transaction.balance > 0" class="balance">
余额: {{ formatMoney(transaction.balance) }}
</div>
<div v-if="transaction.refundAmount && transaction.refundAmount > 0" class="balance">
<div
v-if="transaction.refundAmount && transaction.refundAmount > 0"
class="balance"
>
退款: {{ formatMoney(transaction.refundAmount) }}
</div>
</div>
@@ -212,16 +205,24 @@ const getTypeTagType = (type) => {
// 获取金额样式类
const getAmountClass = (type) => {
if (type === 0) return 'expense'
if (type === 1) return 'income'
if (type === 0) {
return 'expense'
}
if (type === 1) {
return 'income'
}
return 'neutral'
}
// 格式化金额(带符号)
const formatAmount = (amount, type) => {
const formatted = formatMoney(amount)
if (type === 0) return `- ${formatted}`
if (type === 1) return `+ ${formatted}`
if (type === 0) {
return `- ${formatted}`
}
if (type === 1) {
return `+ ${formatted}`
}
return formatted
}
@@ -232,7 +233,9 @@ const formatMoney = (amount) => {
// 格式化日期
const formatDate = (dateString) => {
if (!dateString) return ''
if (!dateString) {
return ''
}
const date = new Date(dateString)
return date.toLocaleString('zh-CN', {
year: 'numeric',

View File

@@ -8,7 +8,7 @@ import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import vant from 'vant'
import { ConfigProvider } from 'vant';
import { ConfigProvider } from 'vant'
import 'vant/lib/index.css'
// 注册 Service Worker
@@ -19,7 +19,7 @@ const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(vant)
app.use(ConfigProvider);
app.use(ConfigProvider)
app.mount('#app')

View File

@@ -1,65 +1,68 @@
import { ref } from 'vue';
import { ref } from 'vue'
export const needRefresh = ref(false);
let swRegistration = null;
export const needRefresh = ref(false)
let swRegistration = null
export async function updateServiceWorker() {
if (swRegistration && swRegistration.waiting) {
await swRegistration.waiting.postMessage({ type: 'SKIP_WAITING' });
await swRegistration.waiting.postMessage({ type: 'SKIP_WAITING' })
}
}
export function register() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
const swUrl = `/service-worker.js`;
const swUrl = '/service-worker.js'
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
swRegistration = registration;
console.log('[SW] Service Worker 注册成功:', registration.scope);
swRegistration = registration
console.log('[SW] Service Worker 注册成功:', registration.scope)
// 如果已经有等待中的更新
if (registration.waiting) {
console.log('[SW] 发现未处理的新版本');
needRefresh.value = true;
console.log('[SW] 发现未处理的新版本')
needRefresh.value = true
}
// 检查更新
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
console.log('[SW] 发现新版本');
const newWorker = registration.installing
console.log('[SW] 发现新版本')
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// 新的 Service Worker 已安装,提示用户刷新
console.log('[SW] 新版本可用,请刷新页面');
needRefresh.value = true;
console.log('[SW] 新版本可用,请刷新页面')
needRefresh.value = true
} else {
// 首次安装
console.log('[SW] 内容已缓存,可离线使用');
console.log('[SW] 内容已缓存,可离线使用')
}
}
});
});
})
})
// 定期检查更新
setInterval(() => {
registration.update();
}, 60 * 60 * 1000); // 每小时检查一次
setInterval(
() => {
registration.update()
},
60 * 60 * 1000
) // 每小时检查一次
})
.catch((error) => {
console.error('[SW] Service Worker 注册失败:', error);
});
console.error('[SW] Service Worker 注册失败:', error)
})
// 监听 Service Worker 控制器变化
navigator.serviceWorker.addEventListener('controllerchange', () => {
console.log('[SW] 控制器已更改,页面将刷新');
window.location.reload();
});
});
console.log('[SW] 控制器已更改,页面将刷新')
window.location.reload()
})
})
}
}
@@ -67,35 +70,37 @@ export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
registration.unregister()
})
.catch((error) => {
console.error(error.message);
});
console.error(error.message)
})
}
}
// 请求通知权限
export function requestNotificationPermission() {
if ('Notification' in window && 'serviceWorker' in navigator) {
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('[SW] 通知权限已授予');
console.log('[SW] 通知权限已授予')
}
});
})
}
}
// 后台同步
export function registerBackgroundSync(tag = 'sync-data') {
if ('serviceWorker' in navigator && 'SyncManager' in window) {
navigator.serviceWorker.ready.then((registration) => {
return registration.sync.register(tag);
}).then(() => {
console.log('[SW] 后台同步已注册:', tag);
}).catch((err) => {
console.error('[SW] 后台同步注册失败:', err);
});
navigator.serviceWorker.ready
.then((registration) => {
return registration.sync.register(tag)
})
.then(() => {
console.log('[SW] 后台同步注册:', tag)
})
.catch((err) => {
console.error('[SW] 后台同步注册失败:', err)
})
}
}

View File

@@ -8,106 +8,106 @@ const router = createRouter({
path: '/login',
name: 'login',
component: () => import('../views/LoginView.vue'),
meta: { requiresAuth: false },
meta: { requiresAuth: false }
},
{
path: '/balance',
name: 'balance',
component: () => import('../views/BalanceView.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/email',
name: 'email',
component: () => import('../views/EmailRecord.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/setting',
name: 'setting',
component: () => import('../views/SettingView.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/calendar',
name: 'calendar',
component: () => import('../views/CalendarView.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/smart-classification',
name: 'smart-classification',
component: () => import('../views/ClassificationSmart.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/classification-edit',
name: 'classification-edit',
component: () => import('../views/ClassificationEdit.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/classification-batch',
name: 'classification-batch',
component: () => import('../views/ClassificationBatch.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/classification-nlp',
name: 'classification-nlp',
component: () => import('../views/ClassificationNLP.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/',
name: 'statistics',
component: () => import('../views/StatisticsView.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/bill-analysis',
name: 'bill-analysis',
component: () => import('../views/BillAnalysisView.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/message',
name: 'message',
redirect: { path: '/balance', query: { tab: 'message' } },
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/periodic-record',
name: 'periodic-record',
component: () => import('../views/PeriodicRecord.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/log',
name: 'log',
component: () => import('../views/LogView.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/budget',
name: 'budget',
component: () => import('../views/BudgetView.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
path: '/scheduled-tasks',
name: 'scheduled-tasks',
component: () => import('../views/ScheduledTasksView.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
},
{
// 待确认的分类项
path: '/unconfirmed-classification',
name: 'unconfirmed-classification',
component: () => import('../views/UnconfirmedClassification.vue'),
meta: { requiresAuth: true },
meta: { requiresAuth: true }
}
],
]
})
// 路由守卫
@@ -127,4 +127,3 @@ router.beforeEach((to, from, next) => {
})
export default router

View File

@@ -7,7 +7,9 @@ export const useAuthStore = defineStore('auth', () => {
const expiresAt = ref(localStorage.getItem('expiresAt') || '')
const isAuthenticated = computed(() => {
if (!token.value || !expiresAt.value) return false
if (!token.value || !expiresAt.value) {
return false
}
// 检查token是否过期
return new Date(expiresAt.value) > new Date()
})
@@ -44,6 +46,6 @@ export const useAuthStore = defineStore('auth', () => {
expiresAt,
isAuthenticated,
login,
logout,
logout
}
})

View File

@@ -1,6 +1,5 @@
<template>
<div class="page-container-flex">
<!-- 顶部导航栏 -->
<van-nav-bar title="账单" placeholder>
<template #right>
@@ -14,45 +13,48 @@
立即同步
</van-button>
<van-icon
v-if="tabActive === 'message'"
name="passed"
size="20"
@click="messageViewRef?.handleMarkAllRead()"
v-if="tabActive === 'message'"
name="passed"
size="20"
@click="messageViewRef?.handleMarkAllRead()"
/>
</template>
</van-nav-bar>
<van-tabs v-model:active="tabActive" type="card" style="margin: 12px 0 2px 0;">
<van-tabs v-model:active="tabActive" type="card" style="margin: 12px 0 2px 0">
<van-tab title="账单" name="balance" />
<van-tab title="邮件" name="email" />
<van-tab title="消息" name="message" />
</van-tabs>
<TransactionsRecord v-if="tabActive === 'balance'" ref="transactionsRecordRef"/>
<TransactionsRecord v-if="tabActive === 'balance'" ref="transactionsRecordRef" />
<EmailRecord v-else-if="tabActive === 'email'" ref="emailRecordRef" />
<MessageView v-else-if="tabActive === 'message'" ref="messageViewRef" :is-component="true" />
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import TransactionsRecord from './TransactionsRecord.vue';
import EmailRecord from './EmailRecord.vue';
import MessageView from './MessageView.vue';
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import TransactionsRecord from './TransactionsRecord.vue'
import EmailRecord from './EmailRecord.vue'
import MessageView from './MessageView.vue'
const route = useRoute();
const tabActive = ref(route.query.tab || 'balance');
const route = useRoute()
const tabActive = ref(route.query.tab || 'balance')
// 监听路由参数变化,用于从 tabbar 点击时切换 tab
watch(() => route.query.tab, (newTab) => {
if (newTab) {
tabActive.value = newTab;
watch(
() => route.query.tab,
(newTab) => {
if (newTab) {
tabActive.value = newTab
}
}
});
)
const transactionsRecordRef = ref(null);
const emailRecordRef = ref(null);
const messageViewRef = ref(null);
const transactionsRecordRef = ref(null)
const emailRecordRef = ref(null)
const messageViewRef = ref(null)
</script>
<style scoped>

View File

@@ -1,6 +1,6 @@
<!-- eslint-disable vue/no-v-html -->
<template>
<div class="page-container-flex">
<div class="page-container-flex">
<!-- 顶部导航栏 -->
<van-nav-bar
title="智能分析"
@@ -12,7 +12,7 @@
<van-icon
name="setting-o"
size="20"
style="cursor: pointer; padding-right: 12px;"
style="cursor: pointer; padding-right: 12px"
@click="onClickPrompt"
/>
</template>
@@ -33,7 +33,9 @@
/>
<div class="quick-questions">
<div class="quick-title">快捷问题</div>
<div class="quick-title">
快捷问题
</div>
<van-tag
v-for="(q, index) in quickQuestions"
:key="index"
@@ -61,7 +63,10 @@
</div>
<!-- 结果区域 -->
<div v-if="showResult" class="result-section">
<div
v-if="showResult"
class="result-section"
>
<div class="result-header">
<h3>分析结果</h3>
<van-icon
@@ -72,12 +77,18 @@
/>
</div>
<div ref="resultContainer" class="result-content rich-html-content">
<div v-html="resultHtml"></div>
<van-loading v-if="analyzing" class="result-loading">
<div
ref="resultContainer"
class="result-content rich-html-content"
>
<div v-html="resultHtml" />
<van-loading
v-if="analyzing"
class="result-loading"
>
AI正在分析中...
</van-loading>
<div ref="scrollAnchor"></div>
<div ref="scrollAnchor" />
</div>
</div>
</div>
@@ -210,7 +221,7 @@ const startAnalysis = async () => {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
userInput: userInput.value
@@ -227,7 +238,9 @@ const startAnalysis = async () => {
while (true) {
const { done, value } = await reader.read()
if (done) break
if (done) {
break
}
const chunk = decoder.decode(value, { stream: true })
const lines = chunk.split('\n')
@@ -254,7 +267,6 @@ const startAnalysis = async () => {
}
}
}
} catch (error) {
console.error('分析失败:', error)
showToast('分析失败,请重试')

View File

@@ -1,12 +1,15 @@
<!-- eslint-disable vue/no-v-html -->
<template>
<div class="page-container-flex">
<van-nav-bar title="预算管理" placeholder>
<van-nav-bar
title="预算管理"
placeholder
>
<template #right>
<van-icon
v-if="activeTab !== BudgetCategory.Savings
&& uncoveredCategories.length > 0
&& !isArchive"
v-if="
activeTab !== BudgetCategory.Savings && uncoveredCategories.length > 0 && !isArchive
"
name="warning-o"
size="20"
color="var(--van-danger-color)"
@@ -39,8 +42,16 @@
</template>
</van-nav-bar>
<van-tabs v-model:active="activeTab" type="card" class="budget-tabs" style="margin: 12px 4px;">
<van-tab title="支出" :name="BudgetCategory.Expense">
<van-tabs
v-model:active="activeTab"
type="card"
class="budget-tabs"
style="margin: 12px 4px"
>
<van-tab
title="支出"
:name="BudgetCategory.Expense"
>
<BudgetSummary
v-if="activeTab !== BudgetCategory.Savings"
v-model:date="selectedDate"
@@ -48,50 +59,86 @@
:title="activeTabTitle"
:get-value-class="getValueClass"
/>
<van-pull-refresh v-model="isRefreshing" class="scroll-content" @refresh="onRefresh">
<van-pull-refresh
v-model="isRefreshing"
class="scroll-content"
@refresh="onRefresh"
>
<div class="budget-list">
<template v-if="expenseBudgets?.length > 0">
<van-swipe-cell v-for="budget in expenseBudgets" :key="budget.id">
<van-swipe-cell
v-for="budget in expenseBudgets"
:key="budget.id"
>
<BudgetCard
:budget="budget"
:progress-color="getProgressColor(budget)"
:percent-class="{ 'warning': (budget.current / budget.limit) > 0.8 }"
:percent-class="{
warning: budget.current / budget.limit > 0.8
}"
:period-label="getPeriodLabel(budget.type)"
@click="budgetEditRef.open({
data: budget,
isEditFlag: true,
category: budget.category
})"
@click="
budgetEditRef.open({
data: budget,
isEditFlag: true,
category: budget.category
})
"
>
<template #amount-info>
<div class="info-item">
<div class="label">已支出</div>
<div class="value expense">¥{{ formatMoney(budget.current) }}</div>
<div class="label">
已支出
</div>
<div class="value expense">
¥{{ formatMoney(budget.current) }}
</div>
</div>
<div class="info-item">
<div class="label">预算</div>
<div class="value">¥{{ formatMoney(budget.limit) }}</div>
<div class="label">
预算
</div>
<div class="value">
¥{{ formatMoney(budget.limit) }}
</div>
</div>
<div class="info-item">
<div class="label">余额</div>
<div class="value" :class="budget.limit - budget.current >= 0 ? 'income' : 'expense'">
<div class="label">
余额
</div>
<div
class="value"
:class="budget.limit - budget.current >= 0 ? 'income' : 'expense'"
>
¥{{ formatMoney(budget.limit - budget.current) }}
</div>
</div>
</template>
</BudgetCard>
<template #right>
<van-button square text="删除" type="danger" class="delete-button" @click="handleDelete(budget)" />
<van-button
square
text="删除"
type="danger"
class="delete-button"
@click="handleDelete(budget)"
/>
</template>
</van-swipe-cell>
</template>
<van-empty v-else description="暂无支出预算" />
<van-empty
v-else
description="暂无支出预算"
/>
</div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))" />
</van-pull-refresh>
</van-tab>
<van-tab title="收入" :name="BudgetCategory.Income">
<van-tab
title="收入"
:name="BudgetCategory.Income"
>
<BudgetSummary
v-if="activeTab !== BudgetCategory.Savings"
v-model:date="selectedDate"
@@ -99,51 +146,92 @@
:title="activeTabTitle"
:get-value-class="getValueClass"
/>
<van-pull-refresh v-model="isRefreshing" class="scroll-content" @refresh="onRefresh">
<van-pull-refresh
v-model="isRefreshing"
class="scroll-content"
@refresh="onRefresh"
>
<div class="budget-list">
<template v-if="incomeBudgets?.length > 0">
<van-swipe-cell v-for="budget in incomeBudgets" :key="budget.id">
<van-swipe-cell
v-for="budget in incomeBudgets"
:key="budget.id"
>
<BudgetCard
:budget="budget"
:progress-color="getProgressColor(budget)"
:percent-class="{ 'income': (budget.current / budget.limit) >= 1 }"
:percent-class="{
income: budget.current / budget.limit >= 1
}"
:period-label="getPeriodLabel(budget.type)"
@click="budgetEditRef.open({
data: budget,
isEditFlag: true,
category: budget.category
})"
@click="
budgetEditRef.open({
data: budget,
isEditFlag: true,
category: budget.category
})
"
>
<template #amount-info>
<div class="info-item">
<div class="label">已收入</div>
<div class="value income">¥{{ formatMoney(budget.current) }}</div>
<div class="label">
已收入
</div>
<div class="value income">
¥{{ formatMoney(budget.current) }}
</div>
</div>
<div class="info-item">
<div class="label">目标</div>
<div class="value">¥{{ formatMoney(budget.limit) }}</div>
<div class="label">
目标
</div>
<div class="value">
¥{{ formatMoney(budget.limit) }}
</div>
</div>
<div class="info-item">
<div class="label">差额</div>
<div class="value" :class="budget.current >= budget.limit ? 'income' : 'expense'">
<div class="label">
差额
</div>
<div
class="value"
:class="budget.current >= budget.limit ? 'income' : 'expense'"
>
¥{{ formatMoney(Math.abs(budget.limit - budget.current)) }}
</div>
</div>
</template>
</BudgetCard>
<template #right>
<van-button square text="删除" type="danger" class="delete-button" @click="handleDelete(budget)" />
<van-button
square
text="删除"
type="danger"
class="delete-button"
@click="handleDelete(budget)"
/>
</template>
</van-swipe-cell>
</template>
<van-empty v-else description="暂无收入预算" />
<van-empty
v-else
description="暂无收入预算"
/>
</div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))" />
</van-pull-refresh>
</van-tab>
<van-tab title="存款" :name="BudgetCategory.Savings">
<van-pull-refresh v-model="isRefreshing" class="scroll-content" style="padding-top:4px" @refresh="onRefresh">
<van-tab
title="存款"
:name="BudgetCategory.Savings"
>
<van-pull-refresh
v-model="isRefreshing"
class="scroll-content"
style="padding-top: 4px"
@refresh="onRefresh"
>
<div class="budget-list">
<template v-if="savingsBudgets?.length > 0">
<BudgetCard
@@ -151,21 +239,31 @@
:key="budget.id"
:budget="budget"
:progress-color="getProgressColor(budget)"
:percent-class="{ 'income': (budget.current / budget.limit) >= 1 }"
:percent-class="{ income: budget.current / budget.limit >= 1 }"
:period-label="getPeriodLabel(budget.type)"
style="margin: 0 12px 12px;"
style="margin: 0 12px 12px"
>
<template #amount-info>
<div class="info-item">
<div class="label">已存</div>
<div class="value income">¥{{ formatMoney(budget.current) }}</div>
<div class="label">
已存
</div>
<div class="value income">
¥{{ formatMoney(budget.current) }}
</div>
</div>
<div class="info-item">
<div class="label">目标</div>
<div class="value">¥{{ formatMoney(budget.limit) }}</div>
<div class="label">
目标
</div>
<div class="value">
¥{{ formatMoney(budget.limit) }}
</div>
</div>
<div class="info-item">
<div class="label">还差</div>
<div class="label">
还差
</div>
<div class="value expense">
¥{{ formatMoney(Math.max(0, budget.limit - budget.current)) }}
</div>
@@ -180,8 +278,7 @@
plain
type="primary"
@click.stop="handleSavingsNav(budget, -1)"
>
</van-button>
/>
<span class="current-date-label">
{{ getSavingsDateLabel(budget) }}
</span>
@@ -193,15 +290,17 @@
icon-position="right"
:disabled="disabledSavingsNextNav(budget)"
@click.stop="handleSavingsNav(budget, 1)"
>
</van-button>
/>
</div>
</template>
</BudgetCard>
</template>
<van-empty v-else description="暂无存款计划" />
<van-empty
v-else
description="暂无存款计划"
/>
</div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))" />
</van-pull-refresh>
</van-tab>
</van-tabs>
@@ -222,13 +321,24 @@
height="60%"
>
<div class="uncovered-list">
<div v-for="item in uncoveredCategories" :key="item.category" class="uncovered-item">
<div
v-for="item in uncoveredCategories"
:key="item.category"
class="uncovered-item"
>
<div class="item-left">
<div class="category-name">{{ item.category }}</div>
<div class="transaction-count">{{ item.transactionCount }} 笔记录</div>
<div class="category-name">
{{ item.category }}
</div>
<div class="transaction-count">
{{ item.transactionCount }} 笔记录
</div>
</div>
<div class="item-right">
<div class="item-amount" :class="activeTab === BudgetCategory.Expense ? 'expense' : 'income'">
<div
class="item-amount"
:class="activeTab === BudgetCategory.Expense ? 'expense' : 'income'"
>
¥{{ formatMoney(item.totalAmount) }}
</div>
</div>
@@ -236,7 +346,12 @@
</div>
<template #footer>
<van-button block round type="primary" @click="showUncoveredDetails = false">
<van-button
block
round
type="primary"
@click="showUncoveredDetails = false"
>
我知道了
</van-button>
</template>
@@ -248,10 +363,13 @@
:subtitle="`${selectedDate.getFullYear()}年${selectedDate.getMonth() + 1}月`"
height="70%"
>
<div style="padding: 16px;">
<div style="padding: 16px">
<div
class="rich-html-content"
v-html="archiveSummary || '<p style=\'text-align:center;color:var(--van-text-color-3)\'>暂无总结</p>'"
v-html="
archiveSummary ||
'<p style=\'text-align:center;color:var(--van-text-color-3)\'>暂无总结</p>'
"
/>
</div>
</PopupContainer>
@@ -261,7 +379,14 @@
<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { getBudgetList, deleteBudget, getCategoryStats, getUncoveredCategories, getArchiveSummary, updateArchiveSummary, getSavingsBudget } from '@/api/budget'
import {
getBudgetList,
deleteBudget,
getCategoryStats,
getUncoveredCategories,
getArchiveSummary,
getSavingsBudget
} from '@/api/budget'
import { BudgetPeriodType, BudgetCategory } from '@/constants/enums'
import BudgetCard from '@/components/Budget/BudgetCard.vue'
import BudgetSummary from '@/components/Budget/BudgetSummary.vue'
@@ -279,7 +404,6 @@ const uncoveredCategories = ref([])
const showSummaryPopup = ref(false)
const archiveSummary = ref('')
const isSavingSummary = ref(false)
const expenseBudgets = ref([])
const incomeBudgets = ref([])
@@ -290,14 +414,19 @@ const overallStats = ref({
})
const activeTabTitle = computed(() => {
if (activeTab.value === BudgetCategory.Expense) return '使用'
if (activeTab.value === BudgetCategory.Expense) {
return '使用'
}
return '达成'
})
const isArchive = computed(() => {
const now = new Date()
return selectedDate.value.getFullYear() < now.getFullYear() ||
(selectedDate.value.getFullYear() === now.getFullYear() && selectedDate.value.getMonth() < now.getMonth())
return (
selectedDate.value.getFullYear() < now.getFullYear() ||
(selectedDate.value.getFullYear() === now.getFullYear() &&
selectedDate.value.getMonth() < now.getMonth())
)
})
watch(activeTab, async () => {
@@ -305,23 +434,29 @@ watch(activeTab, async () => {
})
watch(selectedDate, async () => {
await Promise.all([
fetchBudgetList(),
fetchCategoryStats(),
fetchUncoveredCategories()
])
await Promise.all([fetchBudgetList(), fetchCategoryStats(), fetchUncoveredCategories()])
})
const getValueClass = (rate) => {
const numRate = parseFloat(rate)
if (numRate === 0) return ''
if (numRate === 0) {
return ''
}
if (activeTab.value === BudgetCategory.Expense) {
if (numRate >= 100) return 'expense'
if (numRate >= 80) return 'warning'
if (numRate >= 100) {
return 'expense'
}
if (numRate >= 80) {
return 'warning'
}
return 'income'
} else {
if (numRate >= 100) return 'income'
if (numRate >= 80) return 'warning'
if (numRate >= 100) {
return 'income'
}
if (numRate >= 80) {
return 'warning'
}
return 'expense'
}
}
@@ -331,9 +466,9 @@ const fetchBudgetList = async () => {
const res = await getBudgetList(selectedDate.value.toISOString())
if (res.success) {
const data = res.data || []
expenseBudgets.value = data.filter(b => b.category === BudgetCategory.Expense)
incomeBudgets.value = data.filter(b => b.category === BudgetCategory.Income)
savingsBudgets.value = data.filter(b => b.category === BudgetCategory.Savings)
expenseBudgets.value = data.filter((b) => b.category === BudgetCategory.Expense)
incomeBudgets.value = data.filter((b) => b.category === BudgetCategory.Income)
savingsBudgets.value = data.filter((b) => b.category === BudgetCategory.Savings)
}
} catch (err) {
console.error('加载预算列表失败', err)
@@ -393,18 +528,17 @@ const fetchUncoveredCategories = async () => {
onMounted(async () => {
try {
await Promise.all([
fetchBudgetList(),
fetchCategoryStats(),
fetchUncoveredCategories()
])
await Promise.all([fetchBudgetList(), fetchCategoryStats(), fetchUncoveredCategories()])
} catch (err) {
console.error('获取初始化数据失败', err)
}
})
const formatMoney = (val) => {
return parseFloat(val || 0).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })
return parseFloat(val || 0).toLocaleString(undefined, {
minimumFractionDigits: 0,
maximumFractionDigits: 0
})
}
const getPeriodLabel = (type) => {
@@ -427,7 +561,9 @@ const getPeriodLabel = (type) => {
}
const getProgressColor = (budget) => {
if (!budget.limit || budget.limit === 0) return 'var(--van-primary-color)'
if (!budget.limit || budget.limit === 0) {
return 'var(--van-primary-color)'
}
const ratio = Math.min(Math.max(budget.current / budget.limit, 0), 1)
@@ -467,10 +603,10 @@ const getProgressColor = (budget) => {
// 支出: 这是一个"安全 -> 警示 -> 危险"的过程
// 使用 蓝绿色 -> 黄色 -> 橙红色的渐变,更加自然且具有高级感
stops = [
{ p: 0, c: { r: 64, g: 169, b: 255 } }, // 0% 清新的蓝色 (Safe/Fresh)
{ p: 0.4, c: { r: 54, g: 207, b: 201 } }, // 40% 青色过渡
{ p: 0.7, c: { r: 250, g: 173, b: 20 } }, // 70% 温暖的黄色 (Warning)
{ p: 1, c: { r: 255, g: 77, b: 79 } } // 100% 柔和的红色 (Danger)
{ p: 0, c: { r: 64, g: 169, b: 255 } }, // 0% 清新的蓝色 (Safe/Fresh)
{ p: 0.4, c: { r: 54, g: 207, b: 201 } }, // 40% 青色过渡
{ p: 0.7, c: { r: 250, g: 173, b: 20 } }, // 70% 温暖的黄色 (Warning)
{ p: 1, c: { r: 255, g: 77, b: 79 } } // 100% 柔和的红色 (Danger)
]
} else {
// 收入/存款: 这是一个"开始 -> 积累 -> 达成"的过程
@@ -484,11 +620,11 @@ const getProgressColor = (budget) => {
// 如果用户喜欢"红->蓝"的逻辑,可以尝试这种"红->白->蓝"的冷暖过渡:
stops = [
{ p: 0, c: { r: 245, g: 34, b: 45 } }, // 深红
{ p: 0, c: { r: 245, g: 34, b: 45 } }, // 深红
{ p: 0.45, c: { r: 255, g: 204, b: 204 } }, // 浅红
{ p: 0.5, c: { r: 240, g: 242, b: 245 } }, // 中性灰白
{ p: 0.5, c: { r: 240, g: 242, b: 245 } }, // 中性灰白
{ p: 0.55, c: { r: 186, g: 231, b: 255 } }, // 浅蓝
{ p: 1, c: { r: 24, g: 144, b: 255 } } // 深蓝
{ p: 1, c: { r: 24, g: 144, b: 255 } } // 深蓝
]
}
@@ -531,7 +667,9 @@ const handleDelete = async (budget) => {
}
const getSavingsDateLabel = (budget) => {
if (!budget.periodStart) return ''
if (!budget.periodStart) {
return ''
}
const date = new Date(budget.periodStart)
if (budget.type === BudgetPeriodType.Year) {
return `${date.getFullYear()}`
@@ -541,7 +679,9 @@ const getSavingsDateLabel = (budget) => {
}
const handleSavingsNav = async (budget, offset) => {
if (!budget.periodStart) return
if (!budget.periodStart) {
return
}
const date = new Date(budget.periodStart)
let year = date.getFullYear()
@@ -564,7 +704,7 @@ const handleSavingsNav = async (budget, offset) => {
const res = await getSavingsBudget(year, month, budget.type)
if (res.success && res.data) {
// 找到并更新对应的 budget 对象
const index = savingsBudgets.value.findIndex(b => b.id === budget.id)
const index = savingsBudgets.value.findIndex((b) => b.id === budget.id)
if (index !== -1) {
savingsBudgets.value[index] = res.data
}
@@ -578,7 +718,9 @@ const handleSavingsNav = async (budget, offset) => {
}
const disabledSavingsNextNav = (budget) => {
if (!budget.periodStart) return true
if (!budget.periodStart) {
return true
}
const date = new Date(budget.periodStart)
const now = new Date()
if (budget.type === BudgetPeriodType.Year) {
@@ -693,7 +835,9 @@ const disabledSavingsNextNav = (budget) => {
.item-amount {
font-size: 18px;
font-weight: 600;
font-family: DIN Alternate, system-ui;
font-family:
DIN Alternate,
system-ui;
}
/* 设置页面容器背景色 */

View File

@@ -14,7 +14,7 @@
<ContributionHeatmap ref="heatmapRef" />
<!-- 底部安全距离 -->
<div style="height: calc(60px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(60px + env(safe-area-inset-bottom, 0px))" />
<!-- 日期交易列表弹出层 -->
<PopupContainer
@@ -50,221 +50,227 @@
</template>
<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount } 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 SmartClassifyButton from "@/components/SmartClassifyButton.vue";
import PopupContainer from "@/components/PopupContainer.vue";
import ContributionHeatmap from "@/components/ContributionHeatmap.vue";
import { ref, onMounted, nextTick, onBeforeUnmount } 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 SmartClassifyButton from '@/components/SmartClassifyButton.vue'
import PopupContainer from '@/components/PopupContainer.vue'
import ContributionHeatmap from '@/components/ContributionHeatmap.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 heatmapRef = ref(null);
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 heatmapRef = ref(null)
// 设置日历可选范围例如过去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.43;
document.querySelector(".van-calendar__body").scrollBy({
const height = document.querySelector('.calendar-container').clientHeight * 0.43
document.querySelector('.van-calendar__body').scrollBy({
top: -height,
behavior: "smooth",
});
}, 300);
});
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 = {};
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 smartClassifyButtonRef = ref(null);
const smartClassifyButtonRef = ref(null)
// 获取指定日期的交易列表
const fetchDateTransactions = async (date) => {
try {
listLoading.value = true;
listLoading.value = true
const dateStr = date
.toLocaleString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" })
.replace(/\//g, "-");
.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
.sort((a, b) => b.amount - a.amount);
dateTransactions.value = response.data.sort((a, b) => b.amount - a.amount)
// 重置智能分类按钮
smartClassifyButtonRef.value?.reset()
} 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 getBalance = (transactions) => {
let balance = 0;
transactions.forEach(tx => {
if(tx.type === 1) {
balance += tx.amount;
} else if(tx.type === 0) {
balance -= tx.amount;
let balance = 0
transactions.forEach((tx) => {
if (tx.type === 1) {
balance += tx.amount
} else if (tx.type === 0) {
balance -= tx.amount
}
});
})
if(balance >= 0) {
return `结余收入 ${balance.toFixed(1)}`;
if (balance >= 0) {
return `结余收入 ${balance.toFixed(1)}`
} else {
return `结余支出 ${(-balance).toFixed(1)}`;
return `结余支出 ${(-balance).toFixed(1)}`
}
};
}
// 当月份显示时触发
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 = async (saveData) => {
var item = dateTransactions.value.find(tx => tx.id === saveData.id);
if(!item) return
const item = dateTransactions.value.find((tx) => tx.id === saveData.id)
if (!item) {
return
}
// 如果分类发生了变化 移除智能分类的内容,防止被智能分类覆盖
if(item.classify !== saveData.classify) {
if (item.classify !== saveData.classify) {
// 通知智能分类按钮组件移除指定项
smartClassifyButtonRef.value?.removeClassifiedTransaction(saveData.id)
item.upsetedClassify = ''
}
// 更新当前日期交易列表中的数据
Object.assign(item, saveData);
Object.assign(item, saveData)
// 重新加载当前月份的统计数据
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 handleDateTransactionDelete = async (transactionId) => {
dateTransactions.value = dateTransactions.value.filter(t => t.id !== transactionId)
dateTransactions.value = dateTransactions.value.filter((t) => t.id !== transactionId)
// 刷新当前日期以及当月的统计数据
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 onSmartClassifySave = async () => {
// 保存完成后重新加载数据
if (selectedDate.value) {
await fetchDateTransactions(selectedDate.value);
await 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 };
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];
.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 || 0).toFixed(1)}` // 展示消费金额
}
return dayCopy;
};
return dayCopy
}
// 初始加载当前月份数据
const now = new Date();
fetchDailyStatistics(now.getFullYear(), now.getMonth() + 1);
const now = new Date()
fetchDailyStatistics(now.getFullYear(), now.getMonth() + 1)
// 全局删除事件监听,确保日历页面数据一致
const onGlobalTransactionDeleted = () => {
@@ -276,10 +282,12 @@ const onGlobalTransactionDeleted = () => {
heatmapRef.value?.refresh()
}
window.addEventListener && window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.addEventListener &&
window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.removeEventListener &&
window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
})
// 当有交易被新增/修改/批量更新时刷新
@@ -292,15 +300,17 @@ const onGlobalTransactionsChanged = () => {
heatmapRef.value?.refresh()
}
window.addEventListener && window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
window.addEventListener &&
window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
window.removeEventListener &&
window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
})
</script>
<style scoped>
.van-calendar{
.van-calendar {
background: transparent !important;
}
@@ -340,5 +350,4 @@ onBeforeUnmount(() => {
:deep(.heatmap-card) {
flex-shrink: 0; /* Prevent heatmap from shrinking */
}
</style>

View File

@@ -9,113 +9,94 @@
/>
<div class="scroll-content">
<!-- 第一层选择交易类型 -->
<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
style="margin-left: 16px;"
@close="handleBackToRoot"
>
{{ currentTypeName }}
</van-tag>
<!-- 第一层选择交易类型 -->
<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>
<!-- 分类列表 -->
<van-empty v-if="categories.length === 0" description="暂无分类" />
<!-- 第二层分类列表 -->
<div v-else class="level-container">
<!-- 面包屑导航 -->
<div class="breadcrumb">
<van-tag type="primary" closeable style="margin-left: 16px" @close="handleBackToRoot">
{{ currentTypeName }}
</van-tag>
</div>
<van-cell-group v-else inset>
<van-swipe-cell v-for="category in categories" :key="category.id">
<van-cell
:title="category.name"
is-link
@click="handleEdit(category)"
/>
<template #right>
<van-button
square
type="danger"
text="删除"
@click="handleDelete(category)"
/>
</template>
</van-swipe-cell>
</van-cell-group>
</div>
<!-- 分类列表 -->
<van-empty v-if="categories.length === 0" description="暂无分类" />
<!-- 底部安全距离 -->
<div style="height: calc(55px + env(safe-area-inset-bottom, 0px))"></div>
<van-cell-group v-else inset>
<van-swipe-cell v-for="category in categories" :key="category.id">
<van-cell :title="category.name" is-link @click="handleEdit(category)" />
<template #right>
<van-button square type="danger" text="删除" @click="handleDelete(category)" />
</template>
</van-swipe-cell>
</van-cell-group>
</div>
<div class="bottom-button">
<!-- 新增分类按钮 -->
<van-button
type="primary"
size="large"
icon="plus"
@click="handleAddCategory"
<!-- 底部安全距离 -->
<div style="height: calc(55px + env(safe-area-inset-bottom, 0px))" />
<div class="bottom-button">
<!-- 新增分类按钮 -->
<van-button type="primary" size="large" icon="plus" @click="handleAddCategory">
新增分类
</van-button>
</div>
<!-- 新增分类对话框 -->
<van-dialog
v-model:show="showAddDialog"
title="新增分类"
@confirm="handleConfirmAdd"
@cancel="resetAddForm"
>
新增分类
</van-button>
</div>
<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="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="showEditDialog"
title="编辑分类"
show-cancel-button
@confirm="handleConfirmEdit"
>
<van-form ref="editFormRef">
<van-field
v-model="editForm.name"
name="name"
label="分类名称"
placeholder="请输入分类名称"
:rules="[{ required: true, message: '请输入分类名称' }]"
/>
</van-form>
</van-dialog>
<!-- 编辑分类对话框 -->
<van-dialog
v-model:show="showEditDialog"
title="编辑分类"
show-cancel-button
@confirm="handleConfirmEdit"
>
<van-form ref="editFormRef">
<van-field
v-model="editForm.name"
name="name"
label="分类名称"
placeholder="请输入分类名称"
:rules="[{ required: true, message: '请输入分类名称' }]"
/>
</van-form>
</van-dialog>
<!-- 删除确认对话框 -->
<van-dialog
v-model:show="showDeleteConfirm"
title="删除分类"
message="删除后无法恢复,确定要删除吗?"
@confirm="handleConfirmDelete"
/>
<!-- 删除确认对话框 -->
<van-dialog
v-model:show="showDeleteConfirm"
title="删除分类"
message="删除后无法恢复,确定要删除吗?"
@confirm="handleConfirmDelete"
/>
</div>
</div>
</template>
@@ -123,12 +104,7 @@
<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
showSuccessToast,
showToast,
showLoadingToast,
closeToast
} from 'vant'
import { showSuccessToast, showToast, showLoadingToast, closeToast } from 'vant'
import {
getCategoryList,
createCategory,
@@ -149,7 +125,7 @@ const typeOptions = [
const currentLevel = ref(0) // 0=类型选择, 1=分类管理
const currentType = ref(null) // 当前选中的交易类型
const currentTypeName = computed(() => {
const type = typeOptions.find(t => t.value === currentType.value)
const type = typeOptions.find((t) => t.value === currentType.value)
return type ? type.label : ''
})
@@ -340,7 +316,9 @@ const handleDelete = async (category) => {
* 确认删除
*/
const handleConfirmDelete = async () => {
if (!deleteTarget.value) return
if (!deleteTarget.value) {
return
}
try {
showLoadingToast({
@@ -382,7 +360,6 @@ onMounted(() => {
})
</script>
<style scoped>
.level-container {
min-height: calc(100vh - 50px);

View File

@@ -1,11 +1,6 @@
<template>
<div class="page-container-flex classification-nlp">
<van-nav-bar
title="自然语言分类"
left-text="返回"
left-arrow
@click-left="onClickLeft"
/>
<van-nav-bar title="自然语言分类" left-text="返回" left-arrow @click-left="onClickLeft" />
<div class="scroll-content">
<!-- 输入区域 -->
@@ -23,13 +18,7 @@
</van-cell-group>
<div class="action-buttons">
<van-button
type="primary"
block
round
:loading="analyzing"
@click="handleAnalyze"
>
<van-button type="primary" block round :loading="analyzing" @click="handleAnalyze">
分析查询
</van-button>
</div>
@@ -59,30 +48,12 @@
/>
<!-- 记录列表弹窗 -->
<PopupContainer
v-model="showRecordsList"
title="交易记录列表"
height="75%"
>
<div style="background: var(--van-background);">
<PopupContainer v-model="showRecordsList" title="交易记录列表" height="75%">
<div style="background: var(--van-background)">
<!-- 批量操作按钮 -->
<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 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"
@@ -138,9 +109,11 @@ const onClickLeft = () => {
// 将带目标分类的记录转换为普通交易记录格式供列表显示
const displayRecords = computed(() => {
if (!analysisResult.value) return []
if (!analysisResult.value) {
return []
}
return analysisResult.value.records.map(r => ({
return analysisResult.value.records.map((r) => ({
id: r.id,
reason: r.reason,
amount: r.amount,
@@ -183,7 +156,7 @@ const handleAnalyze = async () => {
analysisResult.value = response.data
// 默认全选
const allIds = new Set(response.data.records.map(r => r.id))
const allIds = new Set(response.data.records.map((r) => r.id))
selectedIds.value = allIds
showToast(`找到 ${response.data.records.length} 条记录`)
@@ -200,8 +173,10 @@ const handleAnalyze = async () => {
// 全选
const selectAll = () => {
if (!analysisResult.value) return
const allIds = new Set(analysisResult.value.records.map(r => r.id))
if (!analysisResult.value) {
return
}
const allIds = new Set(analysisResult.value.records.map((r) => r.id))
selectedIds.value = allIds
}
@@ -218,7 +193,7 @@ const updateSelectedIds = (newSelectedIds) => {
// 点击记录查看详情
const handleRecordClick = (transaction) => {
// 从原始记录中获取完整信息
const record = analysisResult.value?.records.find(r => r.id === transaction.id)
const record = analysisResult.value?.records.find((r) => r.id === transaction.id)
if (record) {
currentTransaction.value = {
id: record.id,
@@ -266,8 +241,8 @@ const handleSubmit = async () => {
// 构建批量更新数据使用AI修改后的结果
const items = analysisResult.value.records
.filter(r => selectedIds.value.has(r.id))
.map(r => ({
.filter((r) => selectedIds.value.has(r.id))
.map((r) => ({
id: r.id,
classify: r.upsetedClassify,
type: r.upsetedType

View File

@@ -1,13 +1,8 @@
<template>
<div class="page-container-flex smart-classification">
<van-nav-bar
title="智能分类"
left-text="返回"
left-arrow
@click-left="onClickLeft"
/>
<van-nav-bar title="智能分类" left-text="返回" left-arrow @click-left="onClickLeft" />
<div class="scroll-content" style="padding-top: 5px;">
<div class="scroll-content" style="padding-top: 5px">
<!-- 统计信息 -->
<div class="stats-info">
<span class="stats-label">未分类账单 </span>
@@ -23,7 +18,7 @@
/>
<!-- 底部安全距离 -->
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))" />
</div>
<!-- 底部操作按钮 -->
@@ -56,11 +51,7 @@
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast, showConfirmDialog } from 'vant'
import {
getUnclassifiedCount,
smartClassify,
batchUpdateClassify
} from '@/api/transactionRecord'
import { getUnclassifiedCount, smartClassify, batchUpdateClassify } from '@/api/transactionRecord'
import ReasonGroupList from '@/components/ReasonGroupList.vue'
const router = useRouter()
@@ -74,7 +65,9 @@ const suppressDataChanged = ref(false)
// 计算已选中的数量
const selectedCount = computed(() => {
if (!groupListRef.value) return 0
if (!groupListRef.value) {
return 0
}
return groupListRef.value.getSelectedReasons().size
})
@@ -114,10 +107,12 @@ const onClickLeft = () => {
if (hasChanges.value) {
showConfirmDialog({
title: '提示',
message: '有未保存的分类结果,确定要离开吗?',
}).then(() => {
router.back()
}).catch(() => {})
message: '有未保存的分类结果,确定要离开吗?'
})
.then(() => {
router.back()
})
.catch(() => {})
} else {
router.back()
}
@@ -125,7 +120,9 @@ const onClickLeft = () => {
// 开始智能分类
const startClassify = async () => {
if (!groupListRef.value) return
if (!groupListRef.value) {
return
}
// 获取所有选中分组
const selectedGroups = groupListRef.value.getList(true)
@@ -167,14 +164,18 @@ const startClassify = async () => {
while (true) {
const { done, value } = await reader.read()
if (done) break
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
if (!line.trim()) {
continue
}
const eventMatch = line.match(/^event: (.+)$/m)
const dataMatch = line.match(/^data: (.+)$/m)
@@ -215,8 +216,9 @@ const handleSSEEvent = (eventType, data, classifyResults) => {
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] === '}') {
if (classifyBuffer.value[i] === '{') {
braceCount++
} else if (classifyBuffer.value[i] === '}') {
braceCount--
if (braceCount === 0) {
closeBrace = i
@@ -283,7 +285,9 @@ const handleSSEEvent = (eventType, data, classifyResults) => {
// 保存分类
const saveClassifications = async () => {
if (!groupListRef.value) return
if (!groupListRef.value) {
return
}
// 收集所有已分类的账单
const groups = groupListRef.value.getList()

View File

@@ -2,9 +2,16 @@
<template>
<div class="page-container-flex">
<!-- 下拉刷新区域 -->
<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<van-pull-refresh
v-model="refreshing"
@refresh="onRefresh"
>
<!-- 加载提示 -->
<van-loading v-if="loading && !(emailList && emailList.length)" vertical style="padding: 50px 0">
<van-loading
v-if="loading && !(emailList && emailList.length)"
vertical
style="padding: 50px 0"
>
加载中...
</van-loading>
<!-- 邮件列表 -->
@@ -14,7 +21,11 @@
finished-text="没有更多了"
@load="onLoad"
>
<van-cell-group v-if="emailList && emailList.length" inset style="margin-top: 10px">
<van-cell-group
v-if="emailList && emailList.length"
inset
style="margin-top: 10px"
>
<van-swipe-cell
v-for="email in emailList"
:key="email.id"
@@ -27,11 +38,15 @@
>
<template #value>
<div class="email-info">
<div class="email-date">{{ formatDate(email.receivedDate) }}</div>
<div v-if="email.transactionCount > 0" class="bill-count">
<span style="font-size: 12px;">已解析{{ email.transactionCount }}条账单</span>
<div class="email-date">
{{ formatDate(email.receivedDate) }}
</div>
<div
v-if="email.transactionCount > 0"
class="bill-count"
>
<span style="font-size: 12px">已解析{{ email.transactionCount }}条账单</span>
</div>
</div>
</template>
</van-cell>
@@ -54,13 +69,13 @@
</van-list>
<!-- 底部安全距离 -->
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))" />
</van-pull-refresh>
<!-- 详情弹出层 -->
<PopupContainer
v-model="detailVisible"
:title="currentEmail ? (currentEmail.Subject || currentEmail.subject || '(无主题)') : ''"
:title="currentEmail ? currentEmail.Subject || currentEmail.subject || '(无主题)' : ''"
height="75%"
>
<template #header-actions>
@@ -75,10 +90,22 @@
</template>
<div v-if="currentEmail">
<van-cell-group inset style="margin-top: 12px;">
<van-cell title="发件人" :value="currentEmail.From || currentEmail.from || '未知'" />
<van-cell title="接收时间" :value="formatDate(currentEmail.ReceivedDate || currentEmail.receivedDate)" />
<van-cell title="记录时间" :value="formatDate(currentEmail.CreateTime || currentEmail.createTime)" />
<van-cell-group
inset
style="margin-top: 12px"
>
<van-cell
title="发件人"
:value="currentEmail.From || currentEmail.from || '未知'"
/>
<van-cell
title="接收时间"
:value="formatDate(currentEmail.ReceivedDate || currentEmail.receivedDate)"
/>
<van-cell
title="记录时间"
:value="formatDate(currentEmail.CreateTime || currentEmail.createTime)"
/>
<van-cell
v-if="(currentEmail.TransactionCount || currentEmail.transactionCount || 0) > 0"
title="已解析账单数"
@@ -88,21 +115,26 @@
/>
</van-cell-group>
<div class="email-content">
<h4 style="margin-left: 10px;">邮件内容</h4>
<h4 style="margin-left: 10px">
邮件内容
</h4>
<div
v-if="currentEmail.htmlBody"
class="content-body html-content"
v-html="currentEmail.htmlBody"
></div>
/>
<div
v-else-if="currentEmail.body"
class="content-body"
>
{{ currentEmail.body }}
</div>
<div v-else class="content-body empty-content">
<div
v-else
class="content-body empty-content"
>
暂无邮件内容
<div style="font-size: 12px; margin-top: 8px; color: var(--van-gray-6);">
<div style="font-size: 12px; margin-top: 8px; color: var(--van-gray-6)">
Debug: {{ Object.keys(currentEmail).join(', ') }}
</div>
</div>
@@ -139,7 +171,14 @@
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { getEmailList, getEmailDetail, deleteEmail, refreshTransactionRecords, syncEmails, getEmailTransactions } from '@/api/emailRecord'
import {
getEmailList,
getEmailDetail,
deleteEmail,
refreshTransactionRecords,
syncEmails,
getEmailTransactions
} from '@/api/emailRecord'
import { getTransactionDetail } from '@/api/transactionRecord'
import TransactionList from '@/components/TransactionList.vue'
import TransactionDetail from '@/components/TransactionDetail.vue'
@@ -163,7 +202,9 @@ const currentTransaction = ref(null)
// 加载数据
const loadData = async (isRefresh = false) => {
if (loading.value) return // 防止重复加载
if (loading.value) {
return
} // 防止重复加载
if (isRefresh) {
pageIndex.value = 1
@@ -246,7 +287,7 @@ const handleDelete = async (email) => {
try {
await showConfirmDialog({
title: '提示',
message: '确定要删除这封邮件吗?',
message: '确定要删除这封邮件吗?'
})
const response = await deleteEmail(email.id)
@@ -266,12 +307,14 @@ const handleDelete = async (email) => {
// 重新分析
const handleRefreshAnalysis = async () => {
if (!currentEmail.value) return
if (!currentEmail.value) {
return
}
try {
await showConfirmDialog({
title: '提示',
message: '确定要重新分析该邮件并刷新交易记录吗?',
message: '确定要重新分析该邮件并刷新交易记录吗?'
})
refreshingAnalysis.value = true
@@ -316,7 +359,9 @@ const handleSync = async () => {
// 查看关联的账单列表
const viewTransactions = async () => {
if (!currentEmail.value) return
if (!currentEmail.value) {
return
}
try {
const emailId = currentEmail.value.id
@@ -340,18 +385,22 @@ const onGlobalTransactionDeleted = (e) => {
// 如果交易列表弹窗打开,尝试重新加载邮箱的交易列表
if (transactionListVisible.value && currentEmail.value) {
const emailId = currentEmail.value.id || currentEmail.value.Id
getEmailTransactions(emailId).then(response => {
if (response.success) {
transactionList.value = response.data || []
}
}).catch(() => {})
getEmailTransactions(emailId)
.then((response) => {
if (response.success) {
transactionList.value = response.data || []
}
})
.catch(() => {})
}
}
window.addEventListener && window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.addEventListener &&
window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.removeEventListener &&
window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
})
// 监听新增/修改/批量更新事件,刷新弹窗内交易或邮件列表
@@ -359,21 +408,25 @@ const onGlobalTransactionsChanged = (e) => {
console.log('收到全局交易变更事件:', e)
if (transactionListVisible.value && currentEmail.value) {
const emailId = currentEmail.value.id || currentEmail.value.Id
getEmailTransactions(emailId).then(response => {
if (response.success) {
transactionList.value = response.data || []
}
}).catch(() => {})
getEmailTransactions(emailId)
.then((response) => {
if (response.success) {
transactionList.value = response.data || []
}
})
.catch(() => {})
} else {
// 也刷新邮件列表以保持统计一致
loadData(true)
}
}
window.addEventListener && window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
window.addEventListener &&
window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
window.removeEventListener &&
window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
})
// 处理点击账单
@@ -394,7 +447,7 @@ const handleTransactionClick = async (transaction) => {
const handleTransactionDelete = (transactionId) => {
// 从当前的交易列表中移除该交易
transactionList.value = transactionList.value.filter(t => t.id !== transactionId)
transactionList.value = transactionList.value.filter((t) => t.id !== transactionId)
// 刷新邮件列表
loadData(true)
@@ -402,16 +455,15 @@ const handleTransactionDelete = (transactionId) => {
// 刷新当前邮件详情
if (currentEmail.value) {
const emailId = currentEmail.value.id
getEmailDetail(emailId).then(response => {
getEmailDetail(emailId).then((response) => {
if (response.success) {
currentEmail.value = response.data
}
})
}
try {
window.dispatchEvent(
new CustomEvent('transaction-deleted', { detail: transactionId }))
} catch(e) {
window.dispatchEvent(new CustomEvent('transaction-deleted', { detail: transactionId }))
} catch (e) {
console.error(e)
}
}
@@ -428,21 +480,22 @@ const handleTransactionSave = async () => {
}
try {
window.dispatchEvent(
new CustomEvent(
'transactions-changed',
{
detail: {
emailId: currentEmail.value?.id
}
}))
} catch(e) {
new CustomEvent('transactions-changed', {
detail: {
emailId: currentEmail.value?.id
}
})
)
} catch (e) {
console.error(e)
}
}
// 格式化日期
const formatDate = (dateString) => {
if (!dateString) return ''
if (!dateString) {
return ''
}
const date = new Date(dateString)
return date.toLocaleString('zh-CN', {
year: 'numeric',
@@ -454,8 +507,6 @@ const formatDate = (dateString) => {
})
}
onMounted(() => {
loadData(true)
})
@@ -467,7 +518,6 @@ defineExpose({
</script>
<style scoped>
:deep(.van-pull-refresh) {
flex: 1;
overflow-y: auto;

View File

@@ -20,16 +20,31 @@
<div class="filter-row">
<van-dropdown-menu>
<van-dropdown-item v-model="selectedLevel" :options="levelOptions" @change="handleSearch" />
<van-dropdown-item v-model="selectedDate" :options="dateOptions" @change="handleSearch" />
<van-dropdown-item
v-model="selectedLevel"
:options="levelOptions"
@change="handleSearch"
/>
<van-dropdown-item
v-model="selectedDate"
:options="dateOptions"
@change="handleSearch"
/>
</van-dropdown-menu>
</div>
</div>
<!-- 下拉刷新区域 -->
<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<van-pull-refresh
v-model="refreshing"
@refresh="onRefresh"
>
<!-- 加载提示 -->
<van-loading v-if="loading && !logList.length" vertical style="padding: 50px 0">
<van-loading
v-if="loading && !logList.length"
vertical
style="padding: 50px 0"
>
加载中...
</van-loading>
@@ -51,7 +66,9 @@
<span class="log-level">{{ log.level }}</span>
<span class="log-time">{{ formatTime(log.timestamp) }}</span>
</div>
<div class="log-message">{{ log.message }}</div>
<div class="log-message">
{{ log.message }}
</div>
</div>
<!-- 空状态 -->
@@ -63,7 +80,7 @@
</van-list>
<!-- 底部安全距离 -->
<div style="height: 20px"></div>
<div style="height: 20px" />
</van-pull-refresh>
</div>
</div>
@@ -106,9 +123,7 @@ const levelOptions = ref([
])
// 日期选项
const dateOptions = ref([
{ text: '全部日期', value: '' }
])
const dateOptions = ref([{ text: '全部日期', value: '' }])
/**
* 返回上一页
@@ -122,12 +137,12 @@ const handleBack = () => {
*/
const getLevelClass = (level) => {
const levelMap = {
'ERR': 'level-error',
'FTL': 'level-fatal',
'WRN': 'level-warning',
'INF': 'level-info',
'DBG': 'level-debug',
'VRB': 'level-verbose'
ERR: 'level-error',
FTL: 'level-fatal',
WRN: 'level-warning',
INF: 'level-info',
DBG: 'level-debug',
VRB: 'level-verbose'
}
return levelMap[level] || 'level-default'
}
@@ -145,7 +160,9 @@ const formatTime = (timestamp) => {
* 加载日志数据
*/
const loadLogs = async (reset = false) => {
if (fetching.value) return
if (fetching.value) {
return
}
fetching.value = true
@@ -223,7 +240,9 @@ const onRefresh = async () => {
* 加载更多
*/
const onLoad = async () => {
if (finished.value || fetching.value) return
if (finished.value || fetching.value) {
return
}
// 如果是第一次加载
if (pageIndex.value === 1 && logList.value.length === 0) {
@@ -257,14 +276,11 @@ const loadAvailableDates = async () => {
try {
const response = await getAvailableDates()
if (response.success && response.data) {
const dates = response.data.map(date => ({
const dates = response.data.map((date) => ({
text: formatDate(date),
value: date
}))
dateOptions.value = [
{ text: '全部日期', value: '' },
...dates
]
dateOptions.value = [{ text: '全部日期', value: '' }, ...dates]
}
} catch (error) {
console.error('加载日期列表失败:', error)

View File

@@ -1,18 +1,34 @@
<!-- eslint-disable vue/no-v-html -->
<template>
<div class="page-container-flex">
<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<van-pull-refresh
v-model="refreshing"
@refresh="onRefresh"
>
<van-list
v-model:loading="loading"
:finished="finished"
finished-text="没有更多了"
@load="onLoad"
>
<van-cell-group v-if="list.length" inset style="margin-top: 10px">
<van-swipe-cell v-for="item in list" :key="item.id">
<div class="message-card" @click="viewDetail(item)">
<van-cell-group
v-if="list.length"
inset
style="margin-top: 10px"
>
<van-swipe-cell
v-for="item in list"
:key="item.id"
>
<div
class="message-card"
@click="viewDetail(item)"
>
<div class="card-left">
<div class="message-title" :class="{ 'unread': !item.isRead }">
<div
class="message-title"
:class="{ unread: !item.isRead }"
>
{{ item.title }}
</div>
<div class="message-content">
@@ -23,16 +39,34 @@
</div>
</div>
<div class="card-right">
<van-tag v-if="!item.isRead" type="danger">未读</van-tag>
<van-icon name="arrow" size="16" class="arrow-icon" />
<van-tag
v-if="!item.isRead"
type="danger"
>
未读
</van-tag>
<van-icon
name="arrow"
size="16"
class="arrow-icon"
/>
</div>
</div>
<template #right>
<van-button square text="删除" type="danger" class="delete-button" @click="handleDelete(item)" />
<van-button
square
text="删除"
type="danger"
class="delete-button"
@click="handleDelete(item)"
/>
</template>
</van-swipe-cell>
</van-cell-group>
<van-empty v-else-if="!loading" description="暂无消息" />
<van-empty
v-else-if="!loading"
description="暂无消息"
/>
</van-list>
</van-pull-refresh>
@@ -47,13 +81,23 @@
v-if="currentMessage.messageType === 2"
class="detail-content rich-html-content"
v-html="currentMessage.content"
/>
<div
v-else
class="detail-content"
>
</div>
<div v-else class="detail-content">
{{ currentMessage.content }}
</div>
<template v-if="currentMessage.url && currentMessage.messageType === 1" #footer>
<van-button type="primary" block round @click="handleUrlJump(currentMessage.url)">
<template
v-if="currentMessage.url && currentMessage.messageType === 1"
#footer
>
<van-button
type="primary"
block
round
@click="handleUrlJump(currentMessage.url)"
>
查看详情
</van-button>
</template>
@@ -62,164 +106,166 @@
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { getMessageList, markAsRead, deleteMessage, markAllAsRead } from '@/api/message';
import { useMessageStore } from '@/stores/message';
import PopupContainer from '@/components/PopupContainer.vue';
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { getMessageList, markAsRead, deleteMessage, markAllAsRead } from '@/api/message'
import { useMessageStore } from '@/stores/message'
import PopupContainer from '@/components/PopupContainer.vue'
const messageStore = useMessageStore();
const router = useRouter();
const list = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const pageIndex = ref(1);
const pageSize = ref(20);
const messageStore = useMessageStore()
const router = useRouter()
const list = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const pageIndex = ref(1)
const pageSize = ref(20)
const detailVisible = ref(false);
const currentMessage = ref({});
const detailVisible = ref(false)
const currentMessage = ref({})
const onLoad = async () => {
if (refreshing.value) {
list.value = [];
pageIndex.value = 1;
refreshing.value = false;
list.value = []
pageIndex.value = 1
refreshing.value = false
}
try {
const res = await getMessageList({
pageIndex: pageIndex.value,
pageSize: pageSize.value
});
})
if (res.success) {
// 格式化时间
const data = res.data.map(item => ({
const data = res.data.map((item) => ({
...item,
createTime: new Date(item.createTime).toLocaleString()
}));
}))
if (pageIndex.value === 1) {
list.value = data;
list.value = data
} else {
list.value = [...list.value, ...data];
list.value = [...list.value, ...data]
}
// 判断是否加载完成
if (list.value.length >= res.total || data.length < pageSize.value) {
finished.value = true;
finished.value = true
} else {
pageIndex.value++;
pageIndex.value++
}
} else {
showToast(res.message || '加载失败');
finished.value = true;
showToast(res.message || '加载失败')
finished.value = true
}
} catch (error) {
console.error(error);
showToast('加载失败');
finished.value = true;
console.error(error)
showToast('加载失败')
finished.value = true
} finally {
loading.value = false;
loading.value = false
}
};
}
const onRefresh = () => {
finished.value = false;
loading.value = true;
onLoad();
};
finished.value = false
loading.value = true
onLoad()
}
const viewDetail = async (item) => {
if (!item.isRead) {
try {
await markAsRead(item.id);
item.isRead = true;
messageStore.updateUnreadCount();
await markAsRead(item.id)
item.isRead = true
messageStore.updateUnreadCount()
} catch (error) {
console.error('标记已读失败', error);
console.error('标记已读失败', error)
}
}
currentMessage.value = item;
detailVisible.value = true;
};
currentMessage.value = item
detailVisible.value = true
}
const handleUrlJump = (targetUrl) => {
if (!targetUrl) return;
if (!targetUrl) {
return
}
if (targetUrl.startsWith('http')) {
window.open(targetUrl, '_blank');
window.open(targetUrl, '_blank')
} else if (targetUrl.startsWith('/')) {
router.push(targetUrl);
detailVisible.value = false;
router.push(targetUrl)
detailVisible.value = false
} else {
showToast('无效的URL');
showToast('无效的URL')
}
};
}
const handleDelete = (item) => {
showDialog({
title: '提示',
message: '确定要删除这条消息吗?',
showCancelButton: true,
showCancelButton: true
}).then(async (action) => {
if (action === 'confirm') {
try {
const res = await deleteMessage(item.id);
const res = await deleteMessage(item.id)
if (res.success) {
showToast('删除成功');
const wasUnread = !item.isRead;
list.value = list.value.filter(i => i.id !== item.id);
showToast('删除成功')
const wasUnread = !item.isRead
list.value = list.value.filter((i) => i.id !== item.id)
if (wasUnread) {
messageStore.updateUnreadCount();
messageStore.updateUnreadCount()
}
} else {
showToast(res.message || '删除失败');
showToast(res.message || '删除失败')
}
} catch (error) {
console.error('删除消息失败', error);
showToast('删除失败');
console.error('删除消息失败', error)
showToast('删除失败')
}
}
});
};
})
}
const handleMarkAllRead = () => {
showDialog({
title: '提示',
message: '确定要将所有消息标记为已读吗?',
showCancelButton: true,
showCancelButton: true
}).then(async (action) => {
if (action === 'confirm') {
try {
const res = await markAllAsRead();
const res = await markAllAsRead()
if (res.success) {
showToast('操作成功');
showToast('操作成功')
// 刷新列表
onRefresh();
onRefresh()
// 更新未读计数
messageStore.updateUnreadCount();
messageStore.updateUnreadCount()
} else {
showToast(res.message || '操作失败');
showToast(res.message || '操作失败')
}
} catch (error) {
console.error('标记所有已读失败', error);
showToast('操作失败');
console.error('标记所有已读失败', error)
showToast('操作失败')
}
}
});
};
})
}
onMounted(() => {
// onLoad 会由 van-list 自动触发
});
})
defineExpose({
handleMarkAllRead
});
})
</script>
<style scoped>
@@ -257,7 +303,7 @@ defineExpose({
white-space: nowrap;
}
.message-content{
.message-content {
font-size: 14px;
color: var(--van-text-color-2);
margin-bottom: 6px;

View File

@@ -36,7 +36,10 @@
</template>
</van-cell>
<van-cell title="分类" :value="item.classify || '未分类'" />
<van-cell title="下次执行时间" :value="formatDateTime(item.nextExecuteTime) || '未设置'" />
<van-cell
title="下次执行时间"
:value="formatDateTime(item.nextExecuteTime) || '未设置'"
/>
<van-cell title="状态">
<template #value>
<van-switch
@@ -69,18 +72,12 @@
</van-list>
<!-- 底部安全距离 -->
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))" />
</van-pull-refresh>
<!-- 底部新增按钮 -->
<div class="bottom-button">
<van-button
type="primary"
size="large"
round
icon="plus"
@click="openAddDialog"
>
<van-button type="primary" size="large" round icon="plus" @click="openAddDialog">
新增周期账单
</van-button>
</div>
@@ -93,111 +90,104 @@
>
<van-form>
<van-cell-group inset title="周期设置">
<van-field
v-model="form.periodicTypeText"
is-link
readonly
name="periodicType"
label="周期"
placeholder="请选择周期类型"
:rules="[{ required: true, message: '请选择周期类型' }]"
@click="showPeriodicTypePicker = true"
/>
<van-field
v-model="form.periodicTypeText"
is-link
readonly
name="periodicType"
label="周期"
placeholder="请选择周期类型"
:rules="[{ required: true, message: '请选择周期类型' }]"
@click="showPeriodicTypePicker = true"
/>
<!-- 每周配置 -->
<van-field
v-if="form.periodicType === 1"
v-model="form.weekdaysText"
is-link
readonly
name="weekdays"
label="星期"
placeholder="请选择星期几"
:rules="[{ required: true, message: '请选择星期几' }]"
@click="showWeekdaysPicker = true"
/>
<!-- 每周配置 -->
<van-field
v-if="form.periodicType === 1"
v-model="form.weekdaysText"
is-link
readonly
name="weekdays"
label="星期"
placeholder="请选择星期几"
:rules="[{ required: true, message: '请选择星期几' }]"
@click="showWeekdaysPicker = true"
/>
<!-- 每月配置 -->
<van-field
v-if="form.periodicType === 2"
v-model="form.monthDaysText"
is-link
readonly
name="monthDays"
label="日期"
placeholder="请选择每月的日期"
:rules="[{ required: true, message: '请选择日期' }]"
@click="showMonthDaysPicker = true"
/>
<!-- 每月配置 -->
<van-field
v-if="form.periodicType === 2"
v-model="form.monthDaysText"
is-link
readonly
name="monthDays"
label="日期"
placeholder="请选择每月的日期"
:rules="[{ required: true, message: '请选择日期' }]"
@click="showMonthDaysPicker = true"
/>
<!-- 每季度配置 -->
<van-field
v-if="form.periodicType === 3"
v-model="form.quarterDay"
name="quarterDay"
label="季度第几天"
placeholder="请输入季度开始后第几天"
type="number"
:rules="[{ required: true, message: '请输入季度开始后第几天' }]"
/>
<!-- 每季度配置 -->
<van-field
v-if="form.periodicType === 3"
v-model="form.quarterDay"
name="quarterDay"
label="季度第几天"
placeholder="请输入季度开始后第几天"
type="number"
:rules="[{ required: true, message: '请输入季度开始后第几天' }]"
/>
<!-- 每年配置 -->
<van-field
v-if="form.periodicType === 4"
v-model="form.yearDay"
name="yearDay"
label="年第几天"
placeholder="请输入年开始后第几天"
type="number"
:rules="[{ required: true, message: '请输入年开始后第几天' }]"
/>
<!-- 每年配置 -->
<van-field
v-if="form.periodicType === 4"
v-model="form.yearDay"
name="yearDay"
label="年第几天"
placeholder="请输入年开始后第几天"
type="number"
:rules="[{ required: true, message: '请输入年开始后第几天' }]"
/>
</van-cell-group>
<van-cell-group inset title="基本信息">
<van-field
v-model="form.reason"
name="reason"
label="摘要"
placeholder="请输入交易摘要"
type="textarea"
rows="2"
autosize
maxlength="200"
show-word-limit
/>
<van-field
v-model="form.amount"
name="amount"
label="金额"
placeholder="请输入金额"
type="number"
:rules="[{ required: true, message: '请输入金额' }]"
/>
<van-field
v-model="form.type"
name="type"
label="类型"
>
<template #input>
<van-radio-group v-model="form.type" direction="horizontal">
<van-radio :name="0">支出</van-radio>
<van-radio :name="1">收入</van-radio>
<van-radio :name="2">不计</van-radio>
</van-radio-group>
</template>
</van-field>
<van-field name="classify" label="分类">
<template #input>
<span v-if="!form.classify" style="color: var(--van-gray-5);">请选择交易分类</span>
<span v-else>{{ form.classify }}</span>
</template>
</van-field>
<van-field
v-model="form.reason"
name="reason"
label="摘要"
placeholder="请输入交易摘要"
type="textarea"
rows="2"
autosize
maxlength="200"
show-word-limit
/>
<van-field
v-model="form.amount"
name="amount"
label="金额"
placeholder="请输入金额"
type="number"
:rules="[{ required: true, message: '请输入金额' }]"
/>
<van-field v-model="form.type" name="type" label="类型">
<template #input>
<van-radio-group v-model="form.type" direction="horizontal">
<van-radio :name="0"> 支出 </van-radio>
<van-radio :name="1"> 收入 </van-radio>
<van-radio :name="2"> 不计 </van-radio>
</van-radio-group>
</template>
</van-field>
<van-field name="classify" label="分类">
<template #input>
<span v-if="!form.classify" style="color: var(--van-gray-5)">请选择交易分类</span>
<span v-else>{{ form.classify }}</span>
</template>
</van-field>
<!-- 分类选择组件 -->
<ClassifySelector
v-model="form.classify"
:type="form.type"
/>
<!-- 分类选择组件 -->
<ClassifySelector v-model="form.classify" :type="form.type" />
</van-cell-group>
</van-form>
<template #footer>
@@ -392,22 +382,24 @@ const getPeriodicTypeText = (item) => {
if (item.periodicConfig) {
switch (item.periodicType) {
case 1: // 每周
{
const weekdays = item.periodicConfig.split(',').map(
d => {
const dayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
return dayMap[parseInt(d)] || ''
}).join('、')
text += ` (${weekdays})`
break
}
case 2: // 每月
{
const days = item.periodicConfig.split(',').join('、')
text += ` (${days}日)`
break
}
case 1: {
// 每周
const weekdays = item.periodicConfig
.split(',')
.map((d) => {
const dayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
return dayMap[parseInt(d)] || ''
})
.join('、')
text += ` (${weekdays})`
break
}
case 2: {
// 每月
const days = item.periodicConfig.split(',').join('、')
text += ` (${days}日)`
break
}
case 3: // 每季度
text += ` (第${item.periodicConfig}天)`
break
@@ -436,20 +428,22 @@ const editPeriodic = (item) => {
form.type = item.type
form.classify = item.classify
form.periodicType = item.periodicType
form.periodicTypeText = periodicTypeColumns.find(t => t.value === item.periodicType)?.text || ''
form.periodicTypeText = periodicTypeColumns.find((t) => t.value === item.periodicType)?.text || ''
// 解析周期配置
if (item.periodicConfig) {
switch (item.periodicType) {
case 1: // 每周
form.weekdays = item.periodicConfig.split(',').map(d => parseInt(d))
form.weekdaysText = form.weekdays.map(d => {
return weekdaysColumns.find(w => w.value === d)?.text || ''
}).join('、')
form.weekdays = item.periodicConfig.split(',').map((d) => parseInt(d))
form.weekdaysText = form.weekdays
.map((d) => {
return weekdaysColumns.find((w) => w.value === d)?.text || ''
})
.join('、')
break
case 2: // 每月
form.monthDays = item.periodicConfig.split(',').map(d => parseInt(d))
form.monthDaysText = form.monthDays.map(d => `${d}`).join('、')
form.monthDays = item.periodicConfig.split(',').map((d) => parseInt(d))
form.monthDaysText = form.monthDays.map((d) => `${d}`).join('、')
break
case 3: // 每季度
form.quarterDay = item.periodicConfig
@@ -468,7 +462,7 @@ const deletePeriodic = async (item) => {
try {
await showConfirmDialog({
title: '提示',
message: '确定要删除这条周期性账单吗?',
message: '确定要删除这条周期性账单吗?'
})
const response = await deletePeriodicApi(item.id)
@@ -493,7 +487,7 @@ const toggleEnabled = async (id, enabled) => {
if (response.success) {
showToast(enabled ? '已启用' : '已禁用')
// 更新本地数据
const item = periodicList.value.find(p => p.id === id)
const item = periodicList.value.find((p) => p.id === id)
if (item) {
item.isEnabled = enabled
}
@@ -510,7 +504,9 @@ const toggleEnabled = async (id, enabled) => {
}
const formatDateTime = (date) => {
if (!date) return ''
if (!date) {
return ''
}
return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}
@@ -557,7 +553,6 @@ const onMonthDaysConfirm = ({ selectedValues, selectedOptions }) => {
form.monthDaysText = selectedOptions[0].text
showMonthDaysPicker.value = false
}
</script>
<style scoped>
@@ -599,5 +594,4 @@ const onMonthDaysConfirm = ({ selectedValues, selectedOptions }) => {
:deep(.van-nav-bar) {
background: transparent !important;
}
</style>

View File

@@ -1,19 +1,40 @@
<template>
<div class="page-container-flex">
<van-nav-bar title="定时任务" left-arrow placeholder @click-left="onClickLeft" />
<van-nav-bar
title="定时任务"
left-arrow
placeholder
@click-left="onClickLeft"
/>
<div class="scroll-content">
<van-pull-refresh v-model="loading" @refresh="fetchTasks">
<div v-for="task in tasks" :key="task.name" class="task-card">
<van-pull-refresh
v-model="loading"
@refresh="fetchTasks"
>
<div
v-for="task in tasks"
:key="task.name"
class="task-card"
>
<van-cell-group inset>
<van-cell :title="task.jobDescription" :label="task.triggerDescription || task.name">
<van-cell
:title="task.jobDescription"
:label="task.triggerDescription || task.name"
>
<template #value>
<van-tag :type="task.status === 'Paused' ? 'warning' : 'success'">
{{ task.status === 'Paused' ? '已暂停' : '已启动' }}
</van-tag>
</template>
</van-cell>
<van-cell title="任务标识" :value="task.name" />
<van-cell title="下次执行" :value="task.nextRunTime || '无'" />
<van-cell
title="任务标识"
:value="task.name"
/>
<van-cell
title="下次执行"
:value="task.nextRunTime || '无'"
/>
<div class="card-footer">
<van-row gutter="10">
<van-col span="12">
@@ -55,10 +76,13 @@
</div>
</van-pull-refresh>
<van-empty v-if="tasks.length === 0 && !loading" description="无定时任务" />
<van-empty
v-if="tasks.length === 0 && !loading"
description="无定时任务"
/>
<!-- 底部安全距离 -->
<div style="height: calc(20px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(20px + env(safe-area-inset-bottom, 0px))" />
</div>
</div>
</template>
@@ -102,7 +126,7 @@ const handleExecute = async (task) => {
try {
await showConfirmDialog({
title: '确认执行',
message: `确定要立即执行"${task.jobDescription}"吗?`,
message: `确定要立即执行"${task.jobDescription}"吗?`
})
showLoadingToast({
@@ -132,7 +156,7 @@ const handlePause = async (task) => {
try {
await showConfirmDialog({
title: '确认暂停',
message: `确定要暂停"${task.jobDescription}"吗?`,
message: `确定要暂停"${task.jobDescription}"吗?`
})
const { success, message } = await pauseJob(task.name)

View File

@@ -1,59 +1,137 @@
<template>
<div class="page-container-flex">
<van-nav-bar title="设置" placeholder/>
<van-nav-bar
title="设置"
placeholder
/>
<div class="scroll-content">
<div class="detail-header" style="padding-bottom: 5px;">
<div
class="detail-header"
style="padding-bottom: 5px"
>
<p>账单</p>
</div>
<van-cell-group inset>
<van-cell title="从支付宝导入" is-link @click="handleImportClick('Alipay')" />
<van-cell title="从微信导入" is-link @click="handleImportClick('WeChat')" />
<van-cell title="周期记录" is-link @click="handlePeriodicRecord" />
<van-cell
title="从支付宝导入"
is-link
@click="handleImportClick('Alipay')"
/>
<van-cell
title="从微信导入"
is-link
@click="handleImportClick('WeChat')"
/>
<van-cell
title="周期记录"
is-link
@click="handlePeriodicRecord"
/>
</van-cell-group>
<!-- 隐藏的文件选择器 -->
<input ref="fileInputRef" type="file" accept=".csv,.xlsx,.xls" style="display: none" @change="handleFileChange" />
<input
ref="fileInputRef"
type="file"
accept=".csv,.xlsx,.xls"
style="display: none"
@change="handleFileChange"
>
<div class="detail-header" style="padding-bottom: 5px;">
<div
class="detail-header"
style="padding-bottom: 5px"
>
<p>分类</p>
</div>
<van-cell-group inset>
<van-cell title="待确认分类" is-link @click="handleUnconfirmedClassification" />
<van-cell title="编辑分类" is-link @click="handleEditClassification" />
<van-cell title="批量分类" is-link @click="handleBatchClassification" />
<van-cell title="智能分类" is-link @click="handleSmartClassification" />
<van-cell
title="待确认分类"
is-link
@click="handleUnconfirmedClassification"
/>
<van-cell
title="编辑分类"
is-link
@click="handleEditClassification"
/>
<van-cell
title="批量分类"
is-link
@click="handleBatchClassification"
/>
<van-cell
title="智能分类"
is-link
@click="handleSmartClassification"
/>
<!-- <van-cell title="自然语言分类" is-link @click="handleNaturalLanguageClassification" /> -->
</van-cell-group>
<div class="detail-header" style="padding-bottom: 5px;">
<div
class="detail-header"
style="padding-bottom: 5px"
>
<p>通知</p>
</div>
<van-cell-group inset>
<van-cell title="开启消息通知">
<template #right-icon>
<van-switch v-model="notificationEnabled" size="24" :loading="notificationLoading" @change="handleNotificationToggle" />
<van-switch
v-model="notificationEnabled"
size="24"
:loading="notificationLoading"
@change="handleNotificationToggle"
/>
</template>
</van-cell>
<van-cell v-if="notificationEnabled" title="测试通知" is-link @click="handleTestNotification" />
<van-cell
v-if="notificationEnabled"
title="测试通知"
is-link
@click="handleTestNotification"
/>
</van-cell-group>
<div class="detail-header" style="padding-bottom: 5px;">
<div
class="detail-header"
style="padding-bottom: 5px"
>
<p>开发者</p>
</div>
<van-cell-group inset>
<van-cell title="查看日志" is-link @click="handleLogView" />
<van-cell title="清除缓存" is-link @click="handleReloadFromNetwork" />
<van-cell title="定时任务" is-link @click="handleScheduledTasks" />
<van-cell
title="查看日志"
is-link
@click="handleLogView"
/>
<van-cell
title="清除缓存"
is-link
@click="handleReloadFromNetwork"
/>
<van-cell
title="定时任务"
is-link
@click="handleScheduledTasks"
/>
</van-cell-group>
<div class="detail-header" style="padding-bottom: 5px;">
<div
class="detail-header"
style="padding-bottom: 5px"
>
<p>账户</p>
</div>
<van-cell-group inset>
<van-cell title="退出登录" is-link @click="handleLogout" />
<van-cell
title="退出登录"
is-link
@click="handleLogout"
/>
</van-cell-group>
<!-- 底部安全距离 -->
<div style="height: calc(80px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(80px + env(safe-area-inset-bottom, 0px))" />
</div>
</div>
</template>
@@ -82,15 +160,15 @@ onMounted(async () => {
}
})
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
function urlBase64ToUint8Array (base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')
const rawData = window.atob(base64)
const outputArray = new Uint8Array(rawData.length)
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray;
return outputArray
}
const handleNotificationToggle = async (checked) => {
@@ -113,7 +191,7 @@ const handleNotificationToggle = async (checked) => {
return
}
let { success, data, message } = await getVapidPublicKey()
const { success, data, message } = await getVapidPublicKey()
if (!success) {
throw new Error(message || '获取 VAPID 公钥失败')
@@ -184,7 +262,11 @@ const handleFileChange = async (event) => {
}
// 验证文件类型
const validTypes = ['text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
const validTypes = [
'text/csv',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
]
if (!validTypes.includes(file.type)) {
showToast('请选择 CSV 或 Excel 文件')
return
@@ -218,8 +300,7 @@ const handleFileChange = async (event) => {
} catch (error) {
console.error('上传失败:', error)
showToast('上传失败: ' + (error.message || '未知错误'))
}
finally {
} finally {
closeToast()
// 清空文件输入,允许重复选择同一文件
event.target.value = ''
@@ -249,7 +330,7 @@ const handleLogout = async () => {
try {
await showConfirmDialog({
title: '提示',
message: '确定要退出登录吗?',
message: '确定要退出登录吗?'
})
authStore.logout()
@@ -276,7 +357,7 @@ const handleReloadFromNetwork = async () => {
try {
await showConfirmDialog({
title: '提示',
message: '确定要刷新网络吗?此操作不可撤销。',
message: '确定要刷新网络吗?此操作不可撤销。'
})
// PWA程序强制页面更新到最新版本
@@ -300,7 +381,6 @@ const handleReloadFromNetwork = async () => {
const handleScheduledTasks = () => {
router.push({ name: 'scheduled-tasks' })
}
</script>
<style scoped>

View File

@@ -1,48 +1,101 @@
<template>
<div class="page-container-flex">
<!-- 顶部导航栏 -->
<van-nav-bar title="账单统计" placeholder>
<van-nav-bar
title="账单统计"
placeholder
>
<template #right>
<van-icon name="chat-o" size="20" @click="goToAnalysis" />
<van-icon
name="chat-o"
size="20"
@click="goToAnalysis"
/>
</template>
</van-nav-bar>
<!-- 下拉刷新 -->
<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<van-pull-refresh
v-model="refreshing"
@refresh="onRefresh"
>
<!-- 初始加载中 -->
<van-loading v-if="loading && firstLoading" vertical style="padding: 100px 0">
<van-loading
v-if="loading && firstLoading"
vertical
style="padding: 100px 0"
>
加载统计数据中...
</van-loading>
<!-- 固定概览部分置顶不滚动 -->
<div v-if="!firstLoading" class="overview-fixed-wrapper">
<transition :name="transitionName" mode="out-in">
<div
v-if="!firstLoading"
class="overview-fixed-wrapper"
>
<transition
:name="transitionName"
mode="out-in"
>
<div :key="dateKey">
<!-- 月度概览卡片 -->
<div class="overview-card">
<!-- 左切换按钮 -->
<div class="nav-arrow left" @click.stop="changeMonth(-1)">
<div
class="nav-arrow left"
@click.stop="changeMonth(-1)"
>
<van-icon name="arrow-left" />
</div>
<div class="overview-item clickable" @click="goToTypeOverviewBills(0)">
<div class="label">总支出</div>
<div class="value expense">¥{{ formatMoney(monthlyData.totalExpense) }}</div>
<div class="sub-text">{{ monthlyData.expenseCount }}</div>
</div>
<div class="divider"></div>
<div class="overview-item clickable" @click="goToTypeOverviewBills(1)">
<div class="label">总收入</div>
<div class="value income">¥{{ formatMoney(monthlyData.totalIncome) }}</div>
<div class="sub-text">{{ monthlyData.incomeCount }}</div>
</div>
<div class="divider"></div>
<div class="overview-item clickable" @click="goToTypeOverviewBills(null)">
<div class="label">结余</div>
<div class="value" :class="monthlyData.balance >= 0 ? 'income' : 'expense'">
{{ monthlyData.balance >= 0 ? '' : '-' }}¥{{ formatMoney(Math.abs(monthlyData.balance)) }}
<div
class="overview-item clickable"
@click="goToTypeOverviewBills(0)"
>
<div class="label">
总支出
</div>
<div class="value expense">
¥{{ formatMoney(monthlyData.totalExpense) }}
</div>
<div class="sub-text">
{{ monthlyData.expenseCount }}
</div>
</div>
<div class="divider" />
<div
class="overview-item clickable"
@click="goToTypeOverviewBills(1)"
>
<div class="label">
总收入
</div>
<div class="value income">
¥{{ formatMoney(monthlyData.totalIncome) }}
</div>
<div class="sub-text">
{{ monthlyData.incomeCount }}
</div>
</div>
<div class="divider" />
<div
class="overview-item clickable"
@click="goToTypeOverviewBills(null)"
>
<div class="label">
结余
</div>
<div
class="value"
:class="monthlyData.balance >= 0 ? 'income' : 'expense'"
>
{{ monthlyData.balance >= 0 ? '' : '-' }}¥{{
formatMoney(Math.abs(monthlyData.balance))
}}
</div>
<div class="sub-text">
{{ monthlyData.totalCount }}笔交易
</div>
<div class="sub-text">{{ monthlyData.totalCount }}笔交易</div>
</div>
<!-- 右切换按钮 -->
@@ -56,7 +109,10 @@
</div>
<!-- 月份日期标识 -->
<div class="date-tag" @click="showMonthPicker = true">
<div
class="date-tag"
@click="showMonthPicker = true"
>
{{ dateTagLabel }}
<van-icon name="arrow-down" />
</div>
@@ -66,69 +122,121 @@
</div>
<!-- 统计内容可滚动部分 -->
<div v-if="!firstLoading" class="statistics-content">
<transition :name="transitionName" mode="out-in">
<div
v-if="!firstLoading"
class="statistics-content"
>
<transition
:name="transitionName"
mode="out-in"
>
<div :key="dateKey">
<!-- 趋势统计 -->
<div class="common-card">
<div
class="common-card"
style="padding-bottom: 5px"
>
<div class="card-header">
<h3 class="card-title">每日收支趋势</h3>
<h3 class="card-title">
收支趋势
</h3>
</div>
<div class="trend-chart" style="height: 240px; padding: 10px 0;">
<div ref="chartRef" style="width: 100%; height: 100%;"></div>
<div
class="trend-chart"
style="height: 240px; padding: 10px 0"
>
<div
ref="chartRef"
style="width: 100%; height: 100%"
/>
</div>
</div>
<!-- 分类统计 -->
<div class="common-card">
<div class="card-header">
<h3 class="card-title">支出分类统计</h3>
<van-tag type="primary" size="medium">{{ expenseCategoriesView.length }}</van-tag>
<h3 class="card-title">
支出分类
</h3>
<van-tag
type="primary"
size="medium"
>
{{ expenseCategoriesView.length }}
</van-tag>
</div>
<!-- 环形图区域 -->
<div v-if="expenseCategoriesView.length > 0" class="chart-container">
<div class="ring-chart">
<div ref="pieChartRef" style="width: 100%; height: 100%;"></div>
</div>
</div>
<!-- 分类列表 -->
<div v-if="expenseCategoriesSimpView.length > 0" class="category-list">
<div
v-for="(category) in expenseCategoriesSimpView"
:key="category.isOther ? 'other' : category.classify"
class="category-item clickable"
@click="category.isOther ? (showAllExpense = true) : goToCategoryBills(category.classify, 0)"
>
<div class="category-info">
<div class="category-color" :style="{ backgroundColor: category.color }"></div>
<div class="category-name-with-count">
<span class="category-name">{{ category.classify || '未分类' }}</span>
<span class="category-count">{{ category.count }}</span>
<!-- 环形图区域 -->
<div
v-if="expenseCategoriesView.length > 0"
class="chart-container"
>
<div class="ring-chart">
<div
ref="pieChartRef"
style="width: 100%; height: 100%"
/>
</div>
</div>
<div class="category-stats">
<div class="category-amount">¥{{ formatMoney(category.amount) }}</div>
<div class="category-percent">{{ category.percent }}%</div>
<!-- 分类列表 -->
<div
v-if="expenseCategoriesSimpView.length > 0"
class="category-list"
>
<div
v-for="category in expenseCategoriesSimpView"
:key="category.isOther ? 'other' : category.classify"
class="category-item clickable"
@click="
category.isOther
? (showAllExpense = true)
: goToCategoryBills(category.classify, 0)
"
>
<div class="category-info">
<div
class="category-color"
:style="{ backgroundColor: category.color }"
/>
<div class="category-name-with-count">
<span class="category-name">{{ category.classify || '未分类' }}</span>
<span class="category-count">{{ category.count }}</span>
</div>
</div>
<div class="category-stats">
<div class="category-amount">
¥{{ formatMoney(category.amount) }}
</div>
<div class="category-percent">
{{ category.percent }}%
</div>
</div>
<van-icon
:name="category.isOther ? 'arrow-down' : 'arrow'"
class="category-arrow"
/>
</div>
</div>
<van-icon :name="category.isOther ? 'arrow-down' : 'arrow'" class="category-arrow" />
<van-empty
v-else
description="本月暂无支出记录"
image="search"
/>
</div>
</div>
<van-empty
v-else
description="本月暂无支出记录"
image="search"
/>
</div>
<!-- 收入分类统计 -->
<div v-if="incomeCategoriesView.length > 0" class="common-card">
<div
v-if="incomeCategoriesView.length > 0"
class="common-card"
>
<div class="card-header">
<h3 class="card-title">收入分类统计</h3>
<van-tag type="success" size="medium">{{ incomeCategoriesView.length }}</van-tag>
<h3 class="card-title">
收入分类统计
</h3>
<van-tag
type="success"
size="medium"
>
{{ incomeCategoriesView.length }}
</van-tag>
</div>
<div class="category-list">
@@ -136,29 +244,49 @@
v-for="category in incomeCategoriesView"
:key="category.isOther ? 'other' : category.classify"
class="category-item clickable"
@click="category.isOther ? (showAllIncome = true) : goToCategoryBills(category.classify, 1)"
@click="
category.isOther
? (showAllIncome = true)
: goToCategoryBills(category.classify, 1)
"
>
<div class="category-info">
<div class="category-color income-color"></div>
<div class="category-color income-color" />
<div class="category-name-with-count">
<span class="category-name">{{ category.classify || '未分类' }}</span>
<span class="category-count">{{ category.count }}</span>
</div>
</div>
<div class="category-stats">
<div class="category-amount income-text">¥{{ formatMoney(category.amount) }}</div>
<div class="category-percent">{{ category.percent }}%</div>
<div class="category-amount income-text">
¥{{ formatMoney(category.amount) }}
</div>
<div class="category-percent">
{{ category.percent }}%
</div>
</div>
<van-icon :name="category.isOther ? 'arrow-down' : 'arrow'" class="category-arrow" />
<van-icon
:name="category.isOther ? 'arrow-down' : 'arrow'"
class="category-arrow"
/>
</div>
</div>
</div>
<!-- 不计收支分类统计 -->
<div v-if="noneCategoriesView.length > 0" class="common-card">
<div
v-if="noneCategoriesView.length > 0"
class="common-card"
>
<div class="card-header">
<h3 class="card-title">不计收支分类统计</h3>
<van-tag type="info" size="medium">{{ noneCategoriesView.length }}</van-tag>
<h3 class="card-title">
不计收支分类统计
</h3>
<van-tag
type="info"
size="medium"
>
{{ noneCategoriesView.length }}
</van-tag>
</div>
<div class="category-list">
@@ -166,59 +294,91 @@
v-for="category in noneCategoriesView"
:key="category.isOther ? 'other' : category.classify"
class="category-item clickable"
@click="category.isOther ? (showAllNone = true) : goToCategoryBills(category.classify, 2)"
@click="
category.isOther
? (showAllNone = true)
: goToCategoryBills(category.classify, 2)
"
>
<div class="category-info">
<div class="category-color none-color"></div>
<div class="category-color none-color" />
<div class="category-name-with-count">
<span class="category-name">{{ category.classify || '未分类' }}</span>
<span class="category-count">{{ category.count }}</span>
</div>
</div>
<div class="category-stats">
<div class="category-amount none-text">¥{{ formatMoney(category.amount) }}</div>
<div class="category-percent">{{ category.percent }}%</div>
<div class="category-amount none-text">
¥{{ formatMoney(category.amount) }}
</div>
<div class="category-percent">
{{ category.percent }}%
</div>
</div>
<van-icon :name="category.isOther ? 'arrow-down' : 'arrow'" class="category-arrow" />
<van-icon
:name="category.isOther ? 'arrow-down' : 'arrow'"
class="category-arrow"
/>
</div>
</div>
</div>
<!-- 其他统计 -->
<div class="common-card">
<div class="card-header">
<h3 class="card-title">其他统计</h3>
<h3 class="card-title">
其他统计
</h3>
</div>
<div class="other-stats">
<div class="stat-item">
<div class="stat-label">日均支出</div>
<div class="stat-value">¥{{ formatMoney(dailyAverage.expense) }}</div>
<div class="stat-label">
日均支出
</div>
<div class="stat-value">
¥{{ formatMoney(dailyAverage.expense) }}
</div>
</div>
<div class="stat-item">
<div class="stat-label">日均收入</div>
<div class="stat-value income-text">¥{{ formatMoney(dailyAverage.income) }}</div>
<div class="stat-label">
日均收入
</div>
<div class="stat-value income-text">
¥{{ formatMoney(dailyAverage.income) }}
</div>
</div>
<div class="stat-item">
<div class="stat-label">最大单笔支出</div>
<div class="stat-value">¥{{ formatMoney(monthlyData.maxExpense) }}</div>
<div class="stat-label">
最大单笔支出
</div>
<div class="stat-value">
¥{{ formatMoney(monthlyData.maxExpense) }}
</div>
</div>
<div class="stat-item">
<div class="stat-label">最大单笔收入</div>
<div class="stat-value income-text">¥{{ formatMoney(monthlyData.maxIncome) }}</div>
<div class="stat-label">
最大单笔收入
</div>
<div class="stat-value income-text">
¥{{ formatMoney(monthlyData.maxIncome) }}
</div>
</div>
</div>
</div>
<!-- 底部安全距离 -->
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))" />
</div>
</transition>
</div>
</van-pull-refresh>
<!-- 月份选择器 -->
<van-popup v-model:show="showMonthPicker" position="bottom" round teleport="body">
<van-popup
v-model:show="showMonthPicker"
position="bottom"
round
teleport="body"
>
<van-date-picker
v-model="selectedDate"
title="选择月份"
@@ -270,7 +430,7 @@
</template>
<script setup>
import { ref, computed, onMounted, onActivated, nextTick } from 'vue'
import { ref, computed, onMounted, onActivated, nextTick, watch } from 'vue'
import { onBeforeUnmount } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
@@ -294,7 +454,10 @@ const showAllIncome = ref(false)
const showAllNone = ref(false)
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth() + 1)
const selectedDate = ref([new Date().getFullYear().toString(), (new Date().getMonth() + 1).toString().padStart(2, '0')])
const selectedDate = ref([
new Date().getFullYear().toString(),
(new Date().getMonth() + 1).toString().padStart(2, '0')
])
const transitionName = ref('slide-right')
const dateKey = computed(() => `${currentYear.value}-${currentMonth.value}`)
@@ -309,7 +472,7 @@ const selectedCategoryTitle = ref('')
const selectedClassify = ref('')
const selectedType = ref(null)
const billPageIndex = ref(1)
let billPageSize = 20
const billPageSize = 20
// 详情编辑相关
const detailVisible = ref(false)
@@ -335,7 +498,9 @@ const noneCategories = ref([])
const expenseCategoriesSimpView = computed(() => {
const list = expenseCategoriesView.value
if (showAllExpense.value || list.length <= 7) return list
if (showAllExpense.value || list.length <= 7) {
return list
}
const top = list.slice(0, 6)
const rest = list.slice(6)
@@ -352,7 +517,7 @@ const expenseCategoriesSimpView = computed(() => {
const expenseCategoriesView = computed(() => {
const list = [...expenseCategories.value]
const unclassifiedIndex = list.findIndex(c => !c.classify)
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
@@ -363,13 +528,15 @@ const expenseCategoriesView = computed(() => {
const incomeCategoriesView = computed(() => {
const list = [...incomeCategories.value]
const unclassifiedIndex = list.findIndex(c => !c.classify)
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
if (showAllIncome.value || list.length <= 7) return list
if (showAllIncome.value || list.length <= 7) {
return list
}
const top = list.slice(0, 6)
const rest = list.slice(6)
@@ -385,13 +552,15 @@ const incomeCategoriesView = computed(() => {
const noneCategoriesView = computed(() => {
const list = [...noneCategories.value]
const unclassifiedIndex = list.findIndex(c => !c.classify)
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
if (showAllNone.value || list.length <= 7) return list
if (showAllNone.value || list.length <= 7) {
return list
}
const top = list.slice(0, 6)
const rest = list.slice(6)
@@ -406,7 +575,6 @@ const noneCategoriesView = computed(() => {
})
// 趋势数据
const trendData = ref([])
const dailyData = ref([])
const chartRef = ref(null)
const pieChartRef = ref(null)
@@ -419,28 +587,23 @@ const maxDate = new Date()
// 颜色配置
const colors = [
'#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8',
'#F7DC6F', '#BB8FCE', '#85C1E2', '#F8B88B', '#AAB7B8',
'#FF8ED4', '#67E6DC', '#FFAB73', '#C9B1FF', '#7BDFF2'
'#FF6B6B',
'#4ECDC4',
'#45B7D1',
'#FFA07A',
'#98D8C8',
'#F7DC6F',
'#BB8FCE',
'#85C1E2',
'#F8B88B',
'#AAB7B8',
'#FF8ED4',
'#67E6DC',
'#FFAB73',
'#C9B1FF',
'#7BDFF2'
]
// 计算环形图数据
const circumference = computed(() => 2 * Math.PI * 70)
const chartSegments = computed(() => {
let offset = 0
return expenseCategoriesView.value.map((category) => {
const percent = category.percent / 100
const length = circumference.value * percent
const segment = {
color: category.color,
length,
offset
}
offset += length
return segment
})
})
// 日均统计
const dailyAverage = computed(() => {
const daysInMonth = new Date(currentYear.value, currentMonth.value, 0).getDate()
@@ -475,7 +638,7 @@ const dateTagLabel = computed(() => {
}
if (currentYear.value === lastYear && currentMonth.value === lastMonth) {
return `上月`
return '上月'
}
return `${currentYear.value}${currentMonth.value}`
@@ -488,8 +651,12 @@ const isUnclassified = computed(() => {
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) return '0'
return Number(value).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 切换月份
@@ -530,7 +697,10 @@ const onMonthConfirm = ({ selectedValues }) => {
const newMonth = parseInt(selectedValues[1])
// 判断方向以应用动画
if (newYear > currentYear.value || (newYear === currentYear.value && newMonth > currentMonth.value)) {
if (
newYear > currentYear.value ||
(newYear === currentYear.value && newMonth > currentMonth.value)
) {
transitionName.value = 'slide-left'
} else {
transitionName.value = 'slide-right'
@@ -561,11 +731,7 @@ const fetchStatistics = async (showLoading = true) => {
}
try {
await Promise.all([
fetchMonthlyData(),
fetchCategoryData(),
fetchDailyData()
])
await Promise.all([fetchMonthlyData(), fetchCategoryData(), fetchDailyData()])
} catch (error) {
console.error('获取统计数据失败:', error)
showToast('获取统计数据失败')
@@ -625,7 +791,7 @@ const fetchCategoryData = async () => {
})
if (incomeResponse.success && incomeResponse.data) {
incomeCategories.value = incomeResponse.data.map(item => ({
incomeCategories.value = incomeResponse.data.map((item) => ({
classify: item.classify,
amount: item.amount,
count: item.count,
@@ -641,7 +807,7 @@ const fetchCategoryData = async () => {
})
if (noneResponse.success && noneResponse.data) {
noneCategories.value = noneResponse.data.map(item => ({
noneCategories.value = noneResponse.data.map((item) => ({
classify: item.classify,
amount: item.amount,
count: item.count,
@@ -678,7 +844,33 @@ const fetchDailyData = async () => {
}
const renderChart = (data) => {
if (!chartRef.value) return
if (!chartRef.value) {
return
}
// 尝试获取DOM上的现有实例
const existingInstance = echarts.getInstanceByDom(chartRef.value)
// 如果当前保存的实例与DOM不一致或者DOM上已经有实例但我们没保存引用
if (chartInstance && chartInstance !== existingInstance) {
// 这种情况很少见,但为了保险,销毁旧的引用
if (!chartInstance.isDisposed()) {
chartInstance.dispose()
}
chartInstance = null
}
// 如果DOM变了transition导致的旧的chartInstance绑定的DOM已经不在了
// 这时 chartInstance.getDom() !== chartRef.value
if (chartInstance && chartInstance.getDom() !== chartRef.value) {
chartInstance.dispose()
chartInstance = null
}
// 如果DOM上已经有实例可能由其他途径创建复用它
if (!chartInstance && existingInstance) {
chartInstance = existingInstance
}
if (!chartInstance) {
chartInstance = echarts.init(chartRef.value)
@@ -700,7 +892,7 @@ const renderChart = (data) => {
// 创建日期映射
const dataMap = new Map()
data.forEach(item => {
data.forEach((item) => {
const day = new Date(item.date).getDate()
dataMap.set(day, item)
})
@@ -720,7 +912,7 @@ const renderChart = (data) => {
}
}
const dates = fullData.map(item => {
const dates = fullData.map((item) => {
const date = new Date(item.date)
return `${date.getDate()}`
})
@@ -730,30 +922,42 @@ const renderChart = (data) => {
let accumulatedIncome = 0
let accumulatedBalance = 0
const expenses = fullData.map(item => {
const expenses = fullData.map((item) => {
accumulatedExpense += item.expense
return accumulatedExpense
})
const incomes = fullData.map(item => {
const incomes = fullData.map((item) => {
accumulatedIncome += item.income
return accumulatedIncome
})
const balances = fullData.map(item => {
const balances = fullData.map((item) => {
accumulatedBalance += item.balance
return accumulatedBalance
})
// 计算最大绝对值用于动态设置Y轴间隔
const allValues = [...expenses, ...incomes, ...balances]
const maxValue = Math.max(...allValues.map(Math.abs), 1000)
// 动态计算间隔目标是大约5-8个刻度
// 比如最大值是 11k间隔可以是 2k (11/2 = 5.5)
// 最大值是 3k间隔可以是 0.5k 或 1k
let interval = 1000
if (maxValue > 8000) {
interval = Math.ceil(maxValue / 6 / 1000) * 1000
}
const option = {
tooltip: {
trigger: 'axis',
formatter: function (params) {
let result = params[0].name + '<br/>';
params.forEach(param => {
result += param.marker + param.seriesName + ': ' + formatMoney(param.value) + '<br/>';
});
return result;
let result = params[0].name + '<br/>'
params.forEach((param) => {
result += param.marker + param.seriesName + ': ' + formatMoney(param.value) + '<br/>'
})
return result
}
},
legend: {
@@ -766,8 +970,8 @@ const renderChart = (data) => {
grid: {
left: '3%',
right: '4%',
bottom: '10%',
top: '10%',
bottom: '15%',
top: '5%',
containLabel: true
},
xAxis: {
@@ -780,11 +984,11 @@ const renderChart = (data) => {
},
yAxis: {
type: 'value',
interval: 1000, // 固定间隔1k
splitNumber: 5,
axisLabel: {
color: '#999', // 适配深色模式
formatter: (value) => {
return (value / 1000) + 'k'
return value / 1000 + 'k'
}
},
splitLine: {
@@ -829,8 +1033,31 @@ const renderChart = (data) => {
}
const renderPieChart = () => {
if (!pieChartRef.value) return
if (expenseCategoriesView.value.length === 0) return
if (!pieChartRef.value) {
return
}
if (expenseCategoriesView.value.length === 0) {
return
}
// 尝试获取DOM上的现有实例
const existingInstance = echarts.getInstanceByDom(pieChartRef.value)
if (pieChartInstance && pieChartInstance !== existingInstance) {
if (!pieChartInstance.isDisposed()) {
pieChartInstance.dispose()
}
pieChartInstance = null
}
if (pieChartInstance && pieChartInstance.getDom() !== pieChartRef.value) {
pieChartInstance.dispose()
pieChartInstance = null
}
if (!pieChartInstance && existingInstance) {
pieChartInstance = existingInstance
}
if (!pieChartInstance) {
pieChartInstance = echarts.init(pieChartRef.value)
@@ -963,7 +1190,9 @@ const smartClassifyButtonRef = ref(null)
const transactionListRef = ref(null)
// 加载分类账单数据
const loadCategoryBills = async (customIndex = null, customSize = null) => {
if (billListLoading.value || billListFinished.value) return
if (billListLoading.value || billListFinished.value) {
return
}
billListLoading.value = true
try {
@@ -1026,7 +1255,7 @@ const viewBillDetail = async (transaction) => {
}
const handleCategoryBillsDelete = (deletedId) => {
categoryBills.value = categoryBills.value.filter(t => t.id !== deletedId)
categoryBills.value = categoryBills.value.filter((t) => t.id !== deletedId)
categoryBillsTotal.value--
// 被删除后刷新统计数据和账单列表
@@ -1039,13 +1268,15 @@ const onBillSave = async (updatedTransaction) => {
await fetchStatistics()
// 只刷新列表中指定的账单项
const item = categoryBills.value.find(t => t.id === updatedTransaction.id)
if(!item) return
const item = categoryBills.value.find((t) => t.id === updatedTransaction.id)
if (!item) {
return
}
// 如果分类发生了变化
if(item.classify !== updatedTransaction.classify) {
if (item.classify !== updatedTransaction.classify) {
// 从列表中移除该项
categoryBills.value = categoryBills.value.filter(t => t.id !== updatedTransaction.id)
categoryBills.value = categoryBills.value.filter((t) => t.id !== updatedTransaction.id)
categoryBillsTotal.value--
// 通知智能分类按钮组件移除指定项
smartClassifyButtonRef.value?.removeClassifiedTransaction(updatedTransaction.id)
@@ -1075,8 +1306,12 @@ const onSmartClassifySave = async () => {
// 刷新统计数据
await fetchStatistics()
try {
window.dispatchEvent(new CustomEvent('transactions-changed', { detail: { reason: selectedClassify.value, type: selectedType.value } }))
} catch(e) {
window.dispatchEvent(
new CustomEvent('transactions-changed', {
detail: { reason: selectedClassify.value, type: selectedType.value }
})
)
} catch (e) {
console.error('触发 transactions-changed 事件失败:', e)
}
@@ -1086,13 +1321,13 @@ const onSmartClassifySave = async () => {
const handleNotifiedTransactionId = async (transactionId) => {
console.log('收到已处理交易ID通知:', transactionId)
// 滚动到指定的交易项
const index = categoryBills.value.findIndex(item => String(item.id) === String(transactionId))
const index = categoryBills.value.findIndex((item) => String(item.id) === String(transactionId))
if (index !== -1) {
// 等待 DOM 更新
await nextTick()
// 允许一丁点延迟让浏览器响应渲染
await new Promise(resolve => setTimeout(resolve, 0))
await new Promise((resolve) => setTimeout(resolve, 0))
const listElement = transactionListRef.value?.$el
if (listElement) {
@@ -1116,6 +1351,28 @@ const handleResize = () => {
pieChartInstance && pieChartInstance.resize()
}
// 监听DOM引用变化确保在月份切换DOM重建后重新渲染图表
watch(chartRef, (newVal) => {
// 无论有没有数据只要DOM变了就尝试渲染
// 如果没有数据renderChart 内部也应该处理(或者我们可以传空数据)
if (newVal) {
setTimeout(() => {
// 传入当前 dailyData即使是空的renderChart 应该能处理
renderChart(dailyData.value || [])
chartInstance && chartInstance.resize()
}, 50)
}
})
watch(pieChartRef, (newVal) => {
if (newVal) {
setTimeout(() => {
renderPieChart()
pieChartInstance && pieChartInstance.resize()
}, 50)
}
})
// 页面激活时刷新数据(从其他页面返回时)
onActivated(() => {
fetchStatistics()
@@ -1127,10 +1384,12 @@ const onGlobalTransactionDeleted = () => {
fetchStatistics()
}
window.addEventListener && window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.addEventListener &&
window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.removeEventListener &&
window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.removeEventListener('resize', handleResize)
chartInstance && chartInstance.dispose()
pieChartInstance && pieChartInstance.dispose()
@@ -1140,15 +1399,17 @@ const onGlobalTransactionsChanged = () => {
fetchStatistics()
}
window.addEventListener && window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
window.addEventListener &&
window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
window.removeEventListener &&
window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
})
</script>
<style scoped>
.page-container-flex{
.page-container-flex {
background: transparent !important;
}
@@ -1598,5 +1859,4 @@ onBeforeUnmount(() => {
:deep(.van-nav-bar) {
background: transparent !important;
}
</style>

View File

@@ -14,7 +14,11 @@
<!-- 下拉刷新区域 -->
<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<!-- 加载提示 -->
<van-loading v-if="loading && !(transactionList && transactionList.length)" vertical style="padding: 50px 0">
<van-loading
v-if="loading && !(transactionList && transactionList.length)"
vertical
style="padding: 50px 0"
>
加载中...
</van-loading>
@@ -26,14 +30,16 @@
:show-delete="true"
@load="onLoad"
@click="viewDetail"
@delete="(id) => {
// 从当前的交易列表中移除该交易
transactionList.value = transactionList.value.filter(t => t.id !== id)
}"
@delete="
(id) => {
// 从当前的交易列表中移除该交易
transactionList.value = transactionList.value.filter((t) => t.id !== id)
}
"
/>
<!-- 底部安全距离 -->
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))"></div>
<div style="height: calc(50px + env(safe-area-inset-bottom, 0px))" />
</van-pull-refresh>
<!-- 详情/编辑弹出层 -->
@@ -48,10 +54,7 @@
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { showToast } from 'vant'
import {
getTransactionList,
getTransactionDetail
} from '@/api/transactionRecord'
import { getTransactionList, getTransactionDetail } from '@/api/transactionRecord'
import TransactionList from '@/components/TransactionList.vue'
import TransactionDetail from '@/components/TransactionDetail.vue'
@@ -69,8 +72,6 @@ const currentTransaction = ref(null)
const searchKeyword = ref('')
let searchTimer = null
// 加载数据
const loadData = async (isRefresh = false) => {
if (isRefresh) {
@@ -194,10 +195,12 @@ const onGlobalTransactionDeleted = () => {
loadData(true)
}
window.addEventListener && window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.addEventListener &&
window.addEventListener('transaction-deleted', onGlobalTransactionDeleted)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
window.removeEventListener &&
window.removeEventListener('transaction-deleted', onGlobalTransactionDeleted)
})
// 外部新增/修改/批量更新时的刷新监听
@@ -208,18 +211,16 @@ const onGlobalTransactionsChanged = () => {
loadData(true)
}
window.addEventListener && window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
window.addEventListener &&
window.addEventListener('transactions-changed', onGlobalTransactionsChanged)
onBeforeUnmount(() => {
window.removeEventListener && window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
window.removeEventListener &&
window.removeEventListener('transactions-changed', onGlobalTransactionsChanged)
})
</script>
<style scoped>
:deep(.van-pull-refresh) {
flex: 1;
overflow-y: auto;
@@ -231,7 +232,6 @@ onBeforeUnmount(() => {
padding: 4px 12px;
z-index: 100;
margin-top: 10px;
}
.top-search-bar :deep(.van-search) {
@@ -239,8 +239,6 @@ onBeforeUnmount(() => {
background: transparent;
}
/* 设置页面容器背景色 */
:deep(.van-nav-bar) {
background: transparent !important;

View File

@@ -20,8 +20,13 @@
</van-nav-bar>
<div class="scroll-content">
<div v-if="loading && transactions.length === 0" class="loading-container">
<van-loading vertical>加载中...</van-loading>
<div
v-if="loading && transactions.length === 0"
class="loading-container"
>
<van-loading vertical>
加载中...
</van-loading>
</div>
<TransactionList
@@ -92,7 +97,7 @@ const handleConfirmSelected = async () => {
// 转换数据格式以适配 TransactionList 组件
const displayTransactions = computed(() => {
return transactions.value.map(t => ({
return transactions.value.map((t) => ({
...t,
upsetedClassify: t.unconfirmedClassify,
upsetedType: t.unconfirmedType
@@ -104,13 +109,12 @@ const loadData = async () => {
try {
const response = await getUnconfirmedTransactionList()
if (response && response.success) {
transactions.value = (response.data || [])
.map(t => ({
...t,
upsetedClassify: t.unconfirmedClassify,
upsetedType: t.unconfirmedType
}))
selectedIds.value = new Set(response.data.map(t => t.id))
transactions.value = (response.data || []).map((t) => ({
...t,
upsetedClassify: t.unconfirmedClassify,
upsetedType: t.unconfirmedType
}))
selectedIds.value = new Set(response.data.map((t) => t.id))
}
} catch (error) {
console.error('获取待确认列表失败:', error)
@@ -125,7 +129,7 @@ const handleTransactionClick = (transaction) => {
}
const handleTransactionDeleted = (id) => {
transactions.value = transactions.value.filter(t => t.id !== id)
transactions.value = transactions.value.filter((t) => t.id !== id)
}
const updateSelectedIds = (ids) => {

View File

@@ -14,7 +14,7 @@ export default defineConfig({
{
name: 'update-sw-version',
apply: 'build',
closeBundle() {
closeBundle () {
const swPath = resolve(fileURLToPath(new URL('.', import.meta.url)), 'dist/service-worker.js')
if (existsSync(swPath)) {
let content = readFileSync(swPath, 'utf8')
@@ -29,7 +29,7 @@ export default defineConfig({
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
}
},
build: {
// 确保 Service Worker 和 manifest 被正确复制

View File

@@ -1,4 +1,4 @@
namespace WebApi.Controllers;
namespace WebApi.Controllers;
using System.Text.Json;
using System.Text.Json.Nodes;
@@ -9,7 +9,8 @@ using Repository;
public class TransactionRecordController(
ITransactionRecordRepository transactionRepository,
ISmartHandleService smartHandleService,
ILogger<TransactionRecordController> logger
ILogger<TransactionRecordController> logger,
IConfigService configService
) : ControllerBase
{
/// <summary>
@@ -272,13 +273,16 @@ public class TransactionRecordController(
{
try
{
var statistics = await transactionRepository.GetDailyStatisticsAsync(year, month);
// 获取存款分类
var savingClassify = await configService.GetConfigByKeyAsync<string>("SavingsCategories");
var statistics = await transactionRepository.GetDailyStatisticsAsync(year, month, savingClassify);
var result = statistics.Select(s => new DailyStatisticsDto(
s.Key,
s.Value.count,
s.Value.expense,
s.Value.income,
s.Value.income - s.Value.expense // Balance = Income - Expense
s.Value.saving
)).ToList();
return result.Ok();
@@ -305,7 +309,13 @@ public class TransactionRecordController(
var effectiveEndDate = endDate.Date.AddDays(1);
var effectiveStartDate = startDate.Date;
var statistics = await transactionRepository.GetDailyStatisticsByRangeAsync(effectiveStartDate, effectiveEndDate);
// 获取存款分类
var savingClassify = await configService.GetConfigByKeyAsync<string>("SavingsCategories");
var statistics = await transactionRepository.GetDailyStatisticsByRangeAsync(
effectiveStartDate,
effectiveEndDate,
savingClassify);
var result = statistics.Select(s => new DailyStatisticsDto(
s.Key,
s.Value.count,
@@ -725,17 +735,6 @@ public class TransactionRecordController(
await Response.WriteAsync(message);
await Response.Body.FlushAsync();
}
private static string GetTypeName(TransactionType type)
{
return type switch
{
TransactionType.Expense => "支出",
TransactionType.Income => "收入",
TransactionType.None => "不计入收支",
_ => "未知"
};
}
}
/// <summary>