This commit is contained in:
SunCheng
2026-02-09 19:25:51 +08:00
parent 63aaaf39c5
commit 3e18283e52
38 changed files with 6188 additions and 5342 deletions

View File

@@ -1,12 +1,13 @@
---
name: bug-fix
description: Bug诊断与修复技能 - 强调交互式确认和影响分析
tags:
metadata:
tags:
- bug-fix
- debugging
- troubleshooting
- interactive
version: 1.0.1
version: 1.0.1
---
# Bug修复技能

View File

@@ -1,12 +1,13 @@
---
name: code-refactoring
description: 代码重构技能 - 强调保持功能不变的前提下优化代码结构,充分理解需求和交互式确认
tags:
metadata:
tags:
- refactoring
- code-quality
- clean-code
- interactive
version: 1.0.0
version: 1.0.0
---
# 代码重构技能

Binary file not shown.

After

Width:  |  Height:  |  Size: 642 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 447 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -10,6 +10,11 @@ public interface ITransactionStatisticsService
Task<List<CategoryStatistics>> GetCategoryStatisticsAsync(int year, int month, TransactionType type);
/// <summary>
/// 按日期范围获取分类统计数据
/// </summary>
Task<List<CategoryStatistics>> GetCategoryStatisticsByDateRangeAsync(DateTime startDate, DateTime endDate, TransactionType type);
Task<List<TrendStatistics>> GetTrendStatisticsAsync(int startYear, int startMonth, int monthCount);
Task<(List<ReasonGroupDto> list, int total)> GetReasonGroupsAsync(int pageIndex = 1, int pageSize = 20);
@@ -145,6 +150,40 @@ public class TransactionStatisticsService(
return categoryGroups;
}
/// <summary>
/// 按日期范围获取分类统计数据
/// </summary>
public async Task<List<CategoryStatistics>> GetCategoryStatisticsByDateRangeAsync(DateTime startDate, DateTime endDate, TransactionType type)
{
var records = await transactionRepository.QueryAsync(
startDate: startDate,
endDate: endDate,
type: type,
pageSize: int.MaxValue);
var categoryGroups = records
.GroupBy(t => t.Classify)
.Select(g => new CategoryStatistics
{
Classify = g.Key,
Amount = g.Sum(t => Math.Abs(t.Amount)),
Count = g.Count()
})
.OrderByDescending(c => c.Amount)
.ToList();
var total = categoryGroups.Sum(c => c.Amount);
if (total > 0)
{
foreach (var category in categoryGroups)
{
category.Percent = Math.Round((category.Amount / total) * 100, 1);
}
}
return categoryGroups;
}
public async Task<List<TrendStatistics>> GetTrendStatisticsAsync(int startYear, int startMonth, int monthCount)
{
var trends = new List<TrendStatistics>();

View File

@@ -94,6 +94,7 @@ const cachedViews = ref([
'CalendarV2', // 日历V2页面
'CalendarView', // 日历V1页面
'StatisticsView', // 统计页面
'StatisticsV2View', // 统计V2页面
'BalanceView', // 账单页面
'BudgetView' // 预算页面
])

View File

@@ -20,7 +20,7 @@ import request from './request'
*/
export const getMonthlyStatistics = (params) => {
return request({
url: '/TransactionRecord/GetMonthlyStatistics',
url: '/TransactionStatistics/GetMonthlyStatistics',
method: 'get',
params
})
@@ -41,7 +41,28 @@ export const getMonthlyStatistics = (params) => {
*/
export const getCategoryStatistics = (params) => {
return request({
url: '/TransactionRecord/GetCategoryStatistics',
url: '/TransactionStatistics/GetCategoryStatistics',
method: 'get',
params
})
}
/**
* 按日期范围获取分类统计数据
* @param {Object} params - 查询参数
* @param {string} params.startDate - 开始日期 (格式: YYYY-MM-DD)
* @param {string} params.endDate - 结束日期 (格式: YYYY-MM-DD)
* @param {number} params.type - 交易类型 (0:支出, 1:收入, 2:不计入收支)
* @returns {Promise<{success: boolean, data: Array}>}
* @returns {Array} data - 分类统计列表
* @returns {string} data[].classify - 分类名称
* @returns {number} data[].amount - 金额
* @returns {number} data[].percent - 百分比
* @returns {number} data[].count - 交易笔数
*/
export const getCategoryStatisticsByDateRange = (params) => {
return request({
url: '/TransactionStatistics/GetCategoryStatisticsByDateRange',
method: 'get',
params
})
@@ -62,7 +83,7 @@ export const getCategoryStatistics = (params) => {
*/
export const getTrendStatistics = (params) => {
return request({
url: '/TransactionRecord/GetTrendStatistics',
url: '/TransactionStatistics/GetTrendStatistics',
method: 'get',
params
})
@@ -81,7 +102,7 @@ export const getTrendStatistics = (params) => {
*/
export const getDailyStatistics = (params) => {
return request({
url: '/TransactionRecord/GetDailyStatistics',
url: '/TransactionStatistics/GetDailyStatistics',
method: 'get',
params
})
@@ -99,7 +120,47 @@ export const getDailyStatistics = (params) => {
*/
export const getBalanceStatistics = (params) => {
return request({
url: '/TransactionRecord/GetBalanceStatistics',
url: '/TransactionStatistics/GetBalanceStatistics',
method: 'get',
params
})
}
/**
* 获取指定周范围的每天的消费统计
* @param {Object} params - 查询参数
* @param {string} params.startDate - 开始日期 (yyyy-MM-dd)
* @param {string} params.endDate - 结束日期 (yyyy-MM-dd)
* @returns {Promise<{success: boolean, data: Array}>}
* @returns {Array} data - 每日统计列表
* @returns {string} data[].date - 日期
* @returns {number} data[].count - 交易笔数
* @returns {number} data[].amount - 交易金额
*/
export const getWeeklyStatistics = (params) => {
return request({
url: '/TransactionStatistics/GetWeeklyStatistics',
method: 'get',
params
})
}
/**
* 获取指定日期范围的统计汇总数据
* @param {Object} params - 查询参数
* @param {string} params.startDate - 开始日期 (yyyy-MM-dd)
* @param {string} params.endDate - 结束日期 (yyyy-MM-dd)
* @returns {Promise<{success: boolean, data: Object}>}
* @returns {Object} data.totalExpense - 总支出
* @returns {Object} data.totalIncome - 总收入
* @returns {Object} data.balance - 结余
* @returns {Object} data.expenseCount - 支出笔数
* @returns {Object} data.incomeCount - 收入笔数
* @returns {Object} data.totalCount - 总笔数
*/
export const getRangeStatistics = (params) => {
return request({
url: '/TransactionStatistics/GetRangeStatistics',
method: 'get',
params
})

View File

@@ -189,7 +189,7 @@ export const batchUpdateClassify = (items) => {
*/
export const getReasonGroups = (pageIndex = 1, pageSize = 20) => {
return request({
url: '/TransactionRecord/GetReasonGroups',
url: '/TransactionStatistics/GetReasonGroups',
method: 'get',
params: { pageIndex, pageSize }
})

View File

@@ -0,0 +1,504 @@
<template>
<van-popup
v-model:show="visible"
position="bottom"
:style="{ height: '80%' }"
round
closeable
>
<div class="popup-wrapper">
<!-- 头部 -->
<div class="popup-header">
<h2 class="popup-title">
{{ title }}
</h2>
<div
v-if="total > 0"
class="popup-subtitle"
>
{{ total }} 笔交易
</div>
</div>
<!-- 交易列表 -->
<div class="transactions">
<!-- 加载状态 -->
<van-loading
v-if="loading && transactions.length === 0"
class="txn-loading"
size="24px"
vertical
>
加载中...
</van-loading>
<!-- 空状态 -->
<div
v-else-if="transactions.length === 0"
class="txn-empty"
>
<div class="empty-icon">
<van-icon
name="balance-list-o"
size="48"
/>
</div>
<div class="empty-text">
暂无交易记录
</div>
</div>
<!-- 交易列表 -->
<div
v-else
class="txn-list"
>
<div
v-for="txn in transactions"
:key="txn.id"
class="txn-card"
@click="onTransactionClick(txn)"
>
<div
class="txn-icon"
:style="{ backgroundColor: txn.iconBg }"
>
<van-icon
:name="txn.icon"
:color="txn.iconColor"
/>
</div>
<div class="txn-content">
<div class="txn-name">
{{ txn.reason }}
</div>
<div class="txn-footer">
<div class="txn-time">
{{ formatDateTime(txn.occurredAt) }}
</div>
<span
v-if="txn.classify"
class="txn-classify-tag"
:class="txn.type === 1 ? 'tag-income' : 'tag-expense'"
>
{{ txn.classify }}
</span>
</div>
</div>
<div class="txn-amount">
{{ formatAmount(txn.amount, txn.type) }}
</div>
</div>
<!-- 加载更多 -->
<div
v-if="!finished"
class="load-more"
>
<van-loading
v-if="loading"
size="20px"
>
加载中...
</van-loading>
<van-button
v-else
type="primary"
size="small"
@click="loadMore"
>
加载更多
</van-button>
</div>
<!-- 已加载全部 -->
<div
v-else
class="finished-text"
>
已加载全部
</div>
</div>
</div>
</div>
</van-popup>
<!-- 交易详情弹窗 -->
<TransactionDetailSheet
v-model:show="showDetail"
:transaction="currentTransaction"
@save="handleSave"
@delete="handleDelete"
/>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { showToast } from 'vant'
import TransactionDetailSheet from '@/components/Transaction/TransactionDetailSheet.vue'
import { getTransactionList } from '@/api/transactionRecord'
const props = defineProps({
modelValue: {
type: Boolean,
default: false
},
classify: {
type: String,
default: ''
},
type: {
type: Number,
default: 0
},
year: {
type: Number,
required: true
},
month: {
type: Number,
required: true
}
})
const emit = defineEmits(['update:modelValue', 'refresh'])
// 双向绑定
const visible = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value)
})
// 标题
const title = computed(() => {
const classifyText = props.classify || '未分类'
const typeText = props.type === 0 ? '支出' : props.type === 1 ? '收入' : '不计收支'
return `${classifyText} - ${typeText}`
})
// 数据状态
const transactions = ref([])
const loading = ref(false)
const finished = ref(false)
const pageIndex = ref(1)
const pageSize = 20
const total = ref(0)
// 详情弹窗
const showDetail = ref(false)
const currentTransaction = ref(null)
// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
const date = new Date(dateTimeStr)
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${month}-${day} ${hours}:${minutes}`
}
// 格式化金额
const formatAmount = (amount, type) => {
const sign = type === 1 ? '+' : '-'
return `${sign}${amount.toFixed(2)}`
}
// 根据分类获取图标
const getIconByClassify = (classify) => {
const iconMap = {
'餐饮': 'food',
'购物': 'shopping',
'交通': 'logistics',
'娱乐': 'play-circle',
'医疗': 'medic',
'工资': 'gold-coin',
'红包': 'gift'
}
return iconMap[classify] || 'bill'
}
// 根据类型获取颜色
const getColorByType = (type) => {
return type === 1 ? '#22C55E' : '#FF6B6B'
}
// 加载数据
const loadData = async (isRefresh = false) => {
if (loading.value || finished.value) {
return
}
if (isRefresh) {
pageIndex.value = 1
transactions.value = []
finished.value = false
}
loading.value = true
try {
const params = {
pageIndex: pageIndex.value,
pageSize: pageSize,
type: props.type,
year: props.year,
month: props.month || 0,
sortByAmount: true
}
if (props.classify) {
params.classify = props.classify
}
const response = await getTransactionList(params)
if (response.success) {
const newList = response.data || []
// 转换数据格式,添加显示所需的字段
const formattedList = newList.map(txn => ({
...txn,
icon: getIconByClassify(txn.classify),
iconColor: getColorByType(txn.type),
iconBg: '#FFFFFF'
}))
transactions.value = [...transactions.value, ...formattedList]
total.value = response.total
if (newList.length === 0 || newList.length < pageSize) {
finished.value = true
} else {
pageIndex.value++
}
} else {
showToast(response.message || '加载账单失败')
finished.value = true
}
} catch (error) {
console.error('加载分类账单失败:', error)
showToast('加载账单失败')
finished.value = true
} finally {
loading.value = false
}
}
// 加载更多
const loadMore = () => {
loadData(false)
}
// 点击交易
const onTransactionClick = (txn) => {
currentTransaction.value = txn
showDetail.value = true
}
// 保存交易
const handleSave = () => {
showDetail.value = false
// 重新加载数据
loadData(true)
// 通知父组件刷新
emit('refresh')
}
// 删除交易
const handleDelete = (id) => {
showDetail.value = false
// 从列表中移除
transactions.value = transactions.value.filter(t => t.id !== id)
total.value--
// 通知父组件刷新
emit('refresh')
}
// 监听弹窗打开
watch(visible, (newValue) => {
if (newValue) {
loadData(true)
} else {
// 关闭时重置状态
transactions.value = []
pageIndex.value = 1
finished.value = false
total.value = 0
}
})
</script>
<style scoped>
@import '@/assets/theme.css';
.popup-wrapper {
height: 100%;
display: flex;
flex-direction: column;
background-color: var(--bg-primary);
}
.popup-header {
flex-shrink: 0;
padding: var(--spacing-2xl);
padding-bottom: var(--spacing-lg);
border-bottom: 1px solid var(--border-color);
}
.popup-title {
font-family: var(--font-display);
font-size: var(--font-xl);
font-weight: var(--font-bold);
color: var(--text-primary);
margin: 0;
text-align: center;
}
.popup-subtitle {
margin-top: var(--spacing-sm);
font-size: var(--font-md);
font-weight: var(--font-medium);
color: var(--text-secondary);
text-align: center;
}
.transactions {
flex: 1;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
padding: var(--spacing-lg);
}
.txn-loading {
padding: var(--spacing-3xl);
text-align: center;
}
.txn-list {
display: flex;
flex-direction: column;
gap: var(--spacing-lg);
}
.txn-card {
display: flex;
align-items: center;
gap: 14px;
padding: var(--spacing-xl);
background-color: var(--bg-secondary);
border-radius: var(--radius-md);
cursor: pointer;
transition: opacity 0.2s;
}
.txn-card:active {
opacity: 0.7;
}
.txn-icon {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: var(--radius-full);
flex-shrink: 0;
}
.txn-content {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
flex: 1;
min-width: 0;
}
.txn-name {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.txn-footer {
display: flex;
align-items: center;
gap: var(--spacing-sm);
}
.txn-time {
font-size: var(--font-md);
font-weight: var(--font-medium);
color: var(--text-tertiary);
}
.txn-classify-tag {
padding: 2px 8px;
font-size: var(--font-xs);
font-weight: var(--font-medium);
border-radius: var(--radius-full);
flex-shrink: 0;
}
.txn-classify-tag.tag-income {
background-color: rgba(34, 197, 94, 0.15);
color: var(--accent-success);
}
.txn-classify-tag.tag-expense {
background-color: rgba(59, 130, 246, 0.15);
color: #3B82F6;
}
.txn-amount {
font-size: var(--font-lg);
font-weight: var(--font-bold);
color: var(--text-primary);
flex-shrink: 0;
margin-left: var(--spacing-md);
}
.load-more {
display: flex;
justify-content: center;
padding: var(--spacing-xl) 0;
}
.finished-text {
text-align: center;
padding: var(--spacing-xl) 0;
font-size: var(--font-md);
color: var(--text-tertiary);
}
/* 空状态 */
.txn-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 300px;
padding: var(--spacing-4xl) var(--spacing-2xl);
gap: var(--spacing-md);
}
.empty-icon {
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
border-radius: var(--radius-full);
background: linear-gradient(135deg, var(--bg-tertiary) 0%, var(--bg-secondary) 100%);
color: var(--text-tertiary);
margin-bottom: var(--spacing-sm);
}
.empty-text {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-secondary);
}
</style>

View File

@@ -0,0 +1,183 @@
<template>
<header class="calendar-header">
<!-- 左箭头 -->
<button
class="nav-btn"
aria-label="上一个周期"
@click="emit('prev')"
>
<van-icon name="arrow-left" />
</button>
<!-- 标题内容可点击跳转 -->
<div
class="header-content"
@click="emit('jump')"
>
<h1 class="header-title">
{{ formattedTitle }}
</h1>
</div>
<!-- 右箭头 -->
<button
class="nav-btn"
aria-label="下一个周期"
@click="emit('next')"
>
<van-icon name="arrow" />
</button>
<!-- 通知按钮 -->
<button
v-if="showNotification"
class="notif-btn"
aria-label="通知"
@click="emit('notification')"
>
<van-icon name="bell" />
</button>
</header>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
type: {
type: String,
required: true,
validator: (value) => ['week', 'month', 'year'].includes(value)
},
currentDate: {
type: Date,
required: true
},
showNotification: {
type: Boolean,
default: true
}
})
const emit = defineEmits(['prev', 'next', 'jump', 'notification'])
/**
* 计算 ISO 8601 标准的周数
* @param date 目标日期
* @returns 周数 (1-53)
*/
const getISOWeek = (date) => {
const target = new Date(date.valueOf())
const dayNr = (date.getDay() + 6) % 7 // 周一为0周日为6
target.setDate(target.getDate() - dayNr + 3) // 本周四
const firstThursday = new Date(target.getFullYear(), 0, 4) // 该年第一个周四
const weekDiff = Math.floor((target.valueOf() - firstThursday.valueOf()) / 86400000)
return 1 + Math.floor(weekDiff / 7)
}
/**
* 计算 ISO 8601 标准的年份(用于周数)
* 注意:年末/年初的周可能属于相邻年份
*/
const getISOYear = (date) => {
const target = new Date(date.valueOf())
const dayNr = (date.getDay() + 6) % 7
target.setDate(target.getDate() - dayNr + 3) // 本周四
return target.getFullYear()
}
// 格式化标题
const formattedTitle = computed(() => {
const date = props.currentDate
const year = date.getFullYear()
const month = date.getMonth() + 1
switch (props.type) {
case 'week': {
const isoYear = getISOYear(date)
const weekNum = getISOWeek(date)
return `${isoYear}年第${weekNum}`
}
case 'month':
return `${year}${month}`
case 'year':
return `${year}`
default:
return ''
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
/* ========== 头部 ========== */
.calendar-header {
display: flex;
align-items: center;
justify-content: flex-start;
padding: 8px 24px;
gap: 8px;
background: transparent !important;
position: relative;
z-index: 1;
}
.header-content {
display: flex;
flex-direction: column;
gap: 4px;
cursor: pointer;
user-select: none;
-webkit-tap-highlight-color: transparent;
}
.header-title {
font-family: var(--font-primary);
font-size: var(--font-2xl);
font-weight: var(--font-medium);
color: var(--text-primary);
margin: 0;
transition: opacity 0.2s;
}
.header-content:active .header-title {
opacity: 0.6;
}
.notif-btn {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: var(--radius-full);
background-color: var(--bg-button);
border: none;
cursor: pointer;
transition: opacity 0.2s;
margin-left: auto;
}
.notif-btn:active {
opacity: 0.7;
}
.nav-btn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 18px;
background-color: transparent;
border: none;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.2s;
}
.nav-btn:active {
background-color: var(--bg-tertiary);
}
</style>

View File

@@ -0,0 +1,313 @@
<template>
<div class="glass-nav-container">
<!-- 渐变淡化效果 -->
<div class="gradient-fade">
<!-- 药丸形导航栏 -->
<div class="nav-pill">
<div
v-for="(item, index) in navItems"
:key="item.name"
class="nav-item"
:class="{ 'nav-item-active': activeTab === item.name }"
@click="handleTabClick(item, index)"
>
<van-icon
:name="item.icon"
size="24"
:color="getIconColor(activeTab === item.name)"
/>
<span
class="nav-label"
:class="{ 'nav-label-active': activeTab === item.name }"
>
{{ item.label }}
</span>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const props = defineProps({
modelValue: {
type: String,
default: 'statistics'
},
items: {
type: Array,
default () {
return [
{ name: 'calendar', label: '日历', icon: 'notes', path: '/calendar' },
{ name: 'statistics', label: '统计', icon: 'chart-trending-o', path: '/' },
{ name: 'balance', label: '账单', icon: 'balance-list', path: '/balance' },
{ name: 'budget', label: '预算', icon: 'bill-o', path: '/budget' },
{ name: 'setting', label: '设置', icon: 'setting', path: '/setting' }
]
}
}
})
const emit = defineEmits(['update:modelValue', 'tab-click'])
const router = useRouter()
const route = useRoute()
// 使用计算属性来获取导航项,优先使用传入的 props
const navItems = computed(() => props.items)
// 响应式的活动标签状态
const activeTab = ref(props.modelValue)
// 检测当前主题(暗色或亮色)
const isDarkMode = ref(false)
const updateTheme = () => {
isDarkMode.value = window.matchMedia('(prefers-color-scheme: dark)').matches
}
// 根据主题和激活状态计算图标颜色
const getIconColor = (isActive) => {
if (isActive) {
// 激活状态:暗色模式用浅色,亮色模式用深色
return isDarkMode.value ? '#FAFAF9' : '#1A1A1A'
} else {
// 非激活状态:暗色模式用灰色,亮色模式用浅灰色
return isDarkMode.value ? '#6B6B6F' : '#9CA3AF'
}
}
// 根据当前路由路径匹配对应的导航项
const getActiveTabFromRoute = (currentPath) => {
// 规范化路径: 去掉 -v2 后缀以支持版本切换
const normalizedPath = currentPath.replace(/-v2$/, '')
const matchedItem = navItems.value.find(item => {
if (!item.path) {return false}
// 完全匹配
if (item.path === currentPath || item.path === normalizedPath) {
return true
}
// 首页特殊处理: '/' 应该匹配 '/' 和 '/statistics*'
if (item.path === '/' && (currentPath === '/' || normalizedPath === '/statistics')) {
return true
}
return false
})
return matchedItem?.name || props.modelValue
}
// 更新激活状态的通用方法
const updateActiveTab = (newTab) => {
if (newTab && newTab !== activeTab.value) {
activeTab.value = newTab
emit('update:modelValue', newTab)
}
}
// 监听外部 modelValue 的变化
watch(() => props.modelValue, (newValue) => {
updateActiveTab(newValue)
}, { immediate: true })
// 监听路由变化,自动同步底部导航高亮状态
watch(() => route.path, (newPath) => {
const matchedTab = getActiveTabFromRoute(newPath)
updateActiveTab(matchedTab)
}, { immediate: true })
const handleTabClick = (item, index) => {
activeTab.value = item.name
emit('update:modelValue', item.name)
emit('tab-click', item, index)
// 如果有路径定义,则进行路由跳转
if (item.path) {
router.push(item.path).catch(err => {
// 忽略相同路由导航错误
if (err.name !== 'NavigationDuplicated') {
console.warn('Navigation error:', err)
}
})
}
}
// 组件挂载时确保状态正确
onMounted(() => {
const matchedTab = getActiveTabFromRoute(route.path)
updateActiveTab(matchedTab)
// 初始化主题检测
updateTheme()
// 监听系统主题变化
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
mediaQuery.addEventListener('change', updateTheme)
// 组件卸载时清理监听器
const cleanup = () => {
mediaQuery.removeEventListener('change', updateTheme)
}
// Vue 3 中可以直接在 onMounted 中返回清理函数
return cleanup
})
</script>
<style scoped lang="scss">
.glass-nav-container {
position: fixed;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 95px;
z-index: 1000;
pointer-events: none;
}
/* 亮色模式渐变(默认) */
.gradient-fade {
width: 100%;
height: 100%;
background: linear-gradient(180deg, rgba(246, 247, 248, 0) 0%, rgba(246, 247, 248, 1) 50%);
padding: 12px 21px 21px 21px;
pointer-events: none;
display: flex;
align-items: flex-end;
}
/* 亮色模式导航栏(默认) - 增强透明和毛玻璃效果 */
.nav-pill {
width: 100%;
height: 62px;
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(40px) saturate(180%);
-webkit-backdrop-filter: blur(40px) saturate(180%);
border: 1px solid rgba(229, 231, 235, 0.6);
border-radius: 31px;
padding: 4px;
display: flex;
align-items: center;
justify-content: space-around;
box-shadow: 0 -4px 24px rgba(0, 0, 0, 0.08), 0 0 0 0.5px rgba(255, 255, 255, 0.5) inset;
pointer-events: auto;
}
.nav-item {
width: 56px;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
cursor: pointer;
transition: all 0.2s ease;
border-radius: 27px;
&:active {
transform: scale(0.95);
}
}
/* 亮色模式文字颜色(默认) */
.nav-label {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 10px;
font-weight: 500;
color: #9CA3AF;
transition: all 0.2s ease;
line-height: 1.2;
}
.nav-label-active {
font-weight: 600;
color: #1A1A1A;
}
/* 适配安全区域 */
@supports (padding-bottom: env(safe-area-inset-bottom)) {
.gradient-fade {
padding-bottom: calc(21px + env(safe-area-inset-bottom));
}
}
/* 响应式适配 */
@media (max-width: 375px) {
.gradient-fade {
padding-left: 16px;
padding-right: 16px;
}
.nav-item {
width: 52px;
}
}
/* 深色模式适配 - 增强透明和毛玻璃效果 */
@media (prefers-color-scheme: dark) {
.gradient-fade {
background: linear-gradient(180deg, rgba(11, 11, 14, 0) 0%, rgba(11, 11, 14, 1) 50%);
}
.nav-pill {
background: rgba(26, 26, 30, 0.75);
backdrop-filter: blur(40px) saturate(180%);
-webkit-backdrop-filter: blur(40px) saturate(180%);
border-color: rgba(42, 42, 46, 0.6);
box-shadow: 0 -4px 24px rgba(0, 0, 0, 0.25), 0 0 0 0.5px rgba(255, 255, 255, 0.1) inset;
}
.nav-label {
color: #6B6B6F;
}
.nav-label-active {
color: #FAFAF9;
}
}
/* iOS 样式优化 */
.nav-pill {
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
}
/* 毛玻璃效果增强 - 根据浏览器支持调整透明度 */
@supports (backdrop-filter: blur(40px)) {
.nav-pill {
background: rgba(255, 255, 255, 0.6);
}
@media (prefers-color-scheme: dark) {
.nav-pill {
background: rgba(26, 26, 30, 0.65);
}
}
}
@supports not (backdrop-filter: blur(40px)) {
/* 浏览器不支持毛玻璃效果时,增加不透明度以确保可读性 */
.nav-pill {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
@media (prefers-color-scheme: dark) {
.nav-pill {
background: rgba(26, 26, 30, 0.95);
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
}
}
</style>

View File

@@ -0,0 +1,345 @@
<template>
<div
class="modern-empty"
:class="[`theme-${theme}`, `size-${size}`]"
>
<div class="empty-content">
<!-- 图标容器 -->
<div
class="icon-container"
:class="{ 'with-animation': animation }"
>
<div class="icon-bg" />
<div class="icon-wrapper">
<!-- 自定义图标插槽 -->
<slot name="icon">
<svg
class="empty-icon"
viewBox="0 0 64 64"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<component :is="iconPath" />
</svg>
</slot>
</div>
</div>
<!-- 文字内容 -->
<div class="text-content">
<h3
v-if="title"
class="empty-title"
>
{{ title }}
</h3>
<p
v-if="description"
class="empty-description"
>
{{ description }}
</p>
</div>
<!-- 操作按钮 -->
<div
v-if="$slots.action || actionText"
class="empty-action"
>
<slot name="action">
<van-button
v-if="actionText"
type="primary"
round
size="small"
@click="$emit('action-click')"
>
{{ actionText }}
</van-button>
</slot>
</div>
</div>
</div>
</template>
<script setup>
import { computed, h } from 'vue'
const props = defineProps({
// 空状态类型search, data, inbox, calendar, finance, chart
type: {
type: String,
default: 'search'
},
// 主题色blue, green, orange, purple, gray
theme: {
type: String,
default: 'blue'
},
// 标题
title: {
type: String,
default: ''
},
// 描述文字
description: {
type: String,
default: '暂无数据'
},
// 是否显示动画
animation: {
type: Boolean,
default: true
},
// 操作按钮文字
actionText: {
type: String,
default: ''
},
// 尺寸small, medium, large
size: {
type: String,
default: 'medium'
}
})
defineEmits(['action-click'])
// 根据类型选择SVG图标路径
const iconPath = computed(() => {
const icons = {
search: () => h('g', [
h('circle', { cx: '26', cy: '26', r: '18', stroke: 'currentColor', 'stroke-width': '3', fill: 'none' }),
h('path', { d: 'M40 40L54 54', stroke: 'currentColor', 'stroke-width': '3', 'stroke-linecap': 'round' })
]),
data: () => h('g', [
h('path', { d: 'M8 48L22 32L36 40L56 16', stroke: 'currentColor', 'stroke-width': '3', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', fill: 'none' }),
h('circle', { cx: '8', cy: '48', r: '3', fill: 'currentColor' }),
h('circle', { cx: '22', cy: '32', r: '3', fill: 'currentColor' }),
h('circle', { cx: '36', cy: '40', r: '3', fill: 'currentColor' }),
h('circle', { cx: '56', cy: '16', r: '3', fill: 'currentColor' })
]),
inbox: () => h('g', [
h('path', { d: 'M8 16L32 4L56 16V52C56 54.2 54.2 56 52 56H12C9.8 56 8 54.2 8 52V16Z', stroke: 'currentColor', 'stroke-width': '3', fill: 'none' }),
h('path', { d: 'M8 32H20L24 40H40L44 32H56', stroke: 'currentColor', 'stroke-width': '3', fill: 'none' })
]),
calendar: () => h('g', [
h('rect', { x: '8', y: '12', width: '48', height: '44', rx: '4', stroke: 'currentColor', 'stroke-width': '3', fill: 'none' }),
h('path', { d: 'M8 24H56', stroke: 'currentColor', 'stroke-width': '3' }),
h('path', { d: 'M20 8V16', stroke: 'currentColor', 'stroke-width': '3', 'stroke-linecap': 'round' }),
h('path', { d: 'M44 8V16', stroke: 'currentColor', 'stroke-width': '3', 'stroke-linecap': 'round' })
]),
finance: () => h('g', [
h('circle', { cx: '32', cy: '32', r: '24', stroke: 'currentColor', 'stroke-width': '3', fill: 'none' }),
h('path', { d: 'M32 16V48', stroke: 'currentColor', 'stroke-width': '3' }),
h('path', { d: 'M24 22H36C38.2 22 40 23.8 40 26C40 28.2 38.2 30 36 30H28C25.8 30 24 31.8 24 34C24 36.2 25.8 38 28 38H40', stroke: 'currentColor', 'stroke-width': '3', fill: 'none' })
]),
chart: () => h('g', [
h('rect', { x: '12', y: '36', width: '8', height: '20', rx: '2', fill: 'currentColor' }),
h('rect', { x: '28', y: '24', width: '8', height: '32', rx: '2', fill: 'currentColor' }),
h('rect', { x: '44', y: '12', width: '8', height: '44', rx: '2', fill: 'currentColor' })
])
}
return icons[props.type] || icons.search
})
</script>
<style scoped lang="scss">
.modern-empty {
width: 100%;
padding: 40px 20px;
display: flex;
justify-content: center;
align-items: center;
.empty-content {
display: flex;
flex-direction: column;
align-items: center;
max-width: 300px;
}
// 图标容器
.icon-container {
position: relative;
width: 120px;
height: 120px;
margin-bottom: 24px;
&.with-animation {
.icon-bg {
animation: pulse 2s ease-in-out infinite;
}
.icon-wrapper {
animation: float 3s ease-in-out infinite;
}
}
.icon-bg {
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
opacity: 0.1;
}
.icon-wrapper {
position: absolute;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
.empty-icon {
width: 56px;
height: 56px;
opacity: 0.6;
}
}
}
// 文字内容
.text-content {
text-align: center;
margin-bottom: 20px;
.empty-title {
font-size: 18px;
font-weight: 600;
color: var(--van-text-color);
margin: 0 0 8px;
line-height: 1.4;
}
.empty-description {
font-size: 14px;
color: var(--van-text-color-2);
margin: 0;
line-height: 1.6;
}
}
// 操作按钮
.empty-action {
margin-top: 4px;
}
// 主题色
&.theme-blue {
.icon-bg {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.empty-icon {
color: #667eea;
}
}
&.theme-green {
.icon-bg {
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}
.empty-icon {
color: #11998e;
}
}
&.theme-orange {
.icon-bg {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.empty-icon {
color: #f5576c;
}
}
&.theme-purple {
.icon-bg {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}
.empty-icon {
color: #4facfe;
}
}
&.theme-gray {
.icon-bg {
background: linear-gradient(135deg, #bdc3c7 0%, #2c3e50 100%);
}
.empty-icon {
color: #95a5a6;
}
}
}
// 动画
@keyframes pulse {
0%, 100% {
transform: scale(1);
opacity: 0.1;
}
50% {
transform: scale(1.05);
opacity: 0.15;
}
}
@keyframes float {
0%, 100% {
transform: translateY(0px);
}
50% {
transform: translateY(-10px);
}
}
// 尺寸变体
.modern-empty.size-small {
padding: 24px 16px;
.icon-container {
width: 80px;
height: 80px;
margin-bottom: 16px;
.empty-icon {
width: 40px;
height: 40px;
}
}
.text-content {
.empty-title {
font-size: 16px;
}
.empty-description {
font-size: 13px;
}
}
}
.modern-empty.size-large {
padding: 60px 20px;
.icon-container {
width: 160px;
height: 160px;
margin-bottom: 32px;
.empty-icon {
width: 72px;
height: 72px;
}
}
.text-content {
.empty-title {
font-size: 20px;
}
.empty-description {
font-size: 15px;
}
}
}
</style>

View File

@@ -0,0 +1,90 @@
<template>
<div class="tabs-wrapper">
<div class="segmented-control">
<div
class="tab-item"
:class="{ active: activeTab === 'week' }"
@click="$emit('change', 'week')"
>
<span class="tab-text"></span>
</div>
<div
class="tab-item"
:class="{ active: activeTab === 'month' }"
@click="$emit('change', 'month')"
>
<span class="tab-text"></span>
</div>
<div
class="tab-item"
:class="{ active: activeTab === 'year' }"
@click="$emit('change', 'year')"
>
<span class="tab-text"></span>
</div>
</div>
</div>
</template>
<script setup>
defineProps({
activeTab: {
type: String,
required: true,
validator: (value) => ['week', 'month', 'year'].includes(value)
}
})
defineEmits(['change'])
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
.tabs-wrapper {
padding: var(--spacing-sm) var(--spacing-xl);
.segmented-control {
display: flex;
background: transparent;
border-radius: var(--radius-md);
padding: 0;
gap: var(--spacing-sm);
height: 40px;
.tab-item {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-md);
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
background: rgba(128, 128, 128, 0.15);
&.active {
background: rgba(128, 128, 128, 0.3);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
.tab-text {
color: var(--text-primary);
font-weight: var(--font-bold);
}
}
&:not(.active):hover {
background: rgba(128, 128, 128, 0.2);
}
.tab-text {
font-family: var(--font-primary);
font-size: var(--font-md);
font-weight: var(--font-medium);
color: var(--text-secondary);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
user-select: none;
}
}
}
}
</style>

View File

@@ -68,7 +68,13 @@ const router = createRouter({
{
path: '/',
name: 'statistics',
component: () => import('../views/StatisticsView.vue'),
component: () => import('../views/statisticsV1/Index.vue'),
meta: { requiresAuth: true }
},
{
path: '/statistics-v2',
name: 'statistics-v2',
component: () => import('../views/statisticsV2/Index.vue'),
meta: { requiresAuth: true }
},
{

44
Web/src/utils/format.js Normal file
View File

@@ -0,0 +1,44 @@
/**
* 格式化金额
* @param {number} value 金额数值
* @returns {string} 格式化后的金额字符串
*/
export const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
/**
* 格式化日期
* @param {Date|string} date 日期
* @param {string} format 格式化模板
* @returns {string} 格式化后的日期字符串
*/
export const formatDate = (date, format = 'YYYY-MM-DD') => {
const d = new Date(date)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
}
/**
* 格式化百分比
* @param {number} value 数值
* @param {number} decimals 小数位数
* @returns {string} 格式化后的百分比字符串
*/
export const formatPercent = (value, decimals = 1) => {
if (!value && value !== 0) {
return '0%'
}
return `${Number(value).toFixed(decimals)}%`
}

View File

@@ -55,6 +55,12 @@
ref="messageViewRef"
:is-component="true"
/>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeNavTab"
@tab-click="handleNavTabClick"
/>
</div>
</template>
@@ -64,8 +70,17 @@ import { useRoute } from 'vue-router'
import TransactionsRecord from './TransactionsRecord.vue'
import EmailRecord from './EmailRecord.vue'
import MessageView from './MessageView.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
const route = useRoute()
// 底部导航栏
const activeNavTab = ref('balance')
const handleNavTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
const tabActive = ref(route.query.tab || 'balance')
// 监听路由参数变化,用于从 tabbar 点击时切换 tab

View File

@@ -497,6 +497,12 @@
@cancel="showDatePicker = false"
/>
</van-popup>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="navActiveTab"
@tab-click="handleNavTabClick"
/>
</div>
</template>
@@ -518,6 +524,14 @@ import BudgetEditPopup from '@/components/Budget/BudgetEditPopup.vue'
import SavingsConfigPopup from '@/components/Budget/SavingsConfigPopup.vue'
import BudgetChartAnalysis from '@/components/Budget/BudgetChartAnalysis.vue'
import PopupContainer from '@/components/PopupContainer.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
// 底部导航栏
const navActiveTab = ref('budget')
const handleNavTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
const activeTab = ref(BudgetCategory.Expense)
const selectedDate = ref(new Date())

View File

@@ -44,6 +44,12 @@
:transaction="currentTransaction"
@save="onDetailSave"
/>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
</div>
</template>
@@ -56,6 +62,14 @@ 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 GlassBottomNav from '@/components/GlassBottomNav.vue'
// 底部导航栏
const activeTab = ref('calendar')
const handleTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
const dailyStatistics = ref({})
const listVisible = ref(false)

View File

@@ -139,6 +139,12 @@
<!-- 底部安全距离 -->
<div style="height: calc(80px + env(safe-area-inset-bottom, 0px))" />
</div>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
</div>
</template>
@@ -151,10 +157,19 @@ import { useAuthStore } from '@/stores/auth'
import { useVersionStore } from '@/stores/version'
import { getVapidPublicKey, subscribe, testNotification } from '@/api/notification'
import { updateServiceWorker } from '@/registerServiceWorker'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
const router = useRouter()
const authStore = useAuthStore()
const versionStore = useVersionStore()
// 底部导航栏
const activeTab = ref('setting')
const handleTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
const fileInputRef = ref(null)
const currentType = ref('')
const notificationEnabled = ref(false)

View File

@@ -1,34 +1,14 @@
<template>
<div class="page-container-flex calendar-v2-wrapper">
<!-- 头部固定 -->
<header class="calendar-header">
<button
class="month-nav-btn"
aria-label="上一月"
@click="changeMonth(-1)"
>
<van-icon name="arrow-left" />
</button>
<div class="header-content">
<h1 class="header-title">
{{ currentMonth }}
</h1>
</div>
<button
class="month-nav-btn"
aria-label="下一月"
@click="changeMonth(1)"
>
<van-icon name="arrow" />
</button>
<button
class="notif-btn"
aria-label="通知"
@click="onNotificationClick"
>
<van-icon name="bell" />
</button>
</header>
<CalendarHeader
type="month"
:current-date="currentDate"
@prev="changeMonth(-1)"
@next="changeMonth(1)"
@jump="onDateJump"
@notification="onNotificationClick"
/>
<!-- 可滚动内容区域 -->
<div class="calendar-scroll-content">
@@ -73,17 +53,42 @@
@save="handleTransactionSave"
@delete="handleTransactionDelete"
/>
<!-- 日期选择器弹窗 -->
<van-popup
v-model:show="showDatePicker"
position="bottom"
round
>
<van-date-picker
v-model="pickerDate"
title="选择年月"
:min-date="new Date(2020, 0, 1)"
:max-date="new Date()"
:columns-type="['year', 'month']"
@confirm="onDatePickerConfirm"
@cancel="onDatePickerCancel"
/>
</van-popup>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import CalendarHeader from '@/components/DateSelectHeader.vue'
import CalendarModule from './modules/Calendar.vue'
import StatsModule from './modules/Stats.vue'
import TransactionListModule from './modules/TransactionList.vue'
import TransactionDetailSheet from '@/components/Transaction/TransactionDetailSheet.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
import { getTransactionDetail } from '@/api/transactionRecord'
// 定义组件名称keep-alive 需要通过 name 识别)
@@ -94,6 +99,13 @@ defineOptions({
// 路由
const router = useRouter()
// 底部导航栏
const activeTab = ref('calendar')
const handleTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
// 下拉刷新状态
const refreshing = ref(false)
@@ -105,12 +117,9 @@ const selectedDate = ref(new Date())
const slideDirection = ref('slide-left')
const calendarKey = ref(0)
// 当前月份格式化(中文)
const currentMonth = computed(() => {
const year = currentDate.value.getFullYear()
const month = currentDate.value.getMonth() + 1
return `${year}${month}`
})
// 日期选择器相关
const showDatePicker = ref(false)
const pickerDate = ref(new Date())
// 格式化日期为 key (yyyy-MM-dd)
const formatDateKey = (date) => {
@@ -181,6 +190,38 @@ const onNotificationClick = () => {
router.push('/message')
}
// 点击日期标题,打开日期选择器
const onDateJump = () => {
pickerDate.value = new Date(currentDate.value)
showDatePicker.value = true
}
// 确认日期选择
const onDatePickerConfirm = ({ selectedValues }) => {
const [year, month] = selectedValues
const newDate = new Date(year, month - 1, 1)
// 检查是否超过当前月
const today = new Date()
if (newDate.getFullYear() > today.getFullYear() ||
(newDate.getFullYear() === today.getFullYear() && newDate.getMonth() > today.getMonth())) {
showToast('不能选择未来的月份')
showDatePicker.value = false
return
}
// 更新日期
currentDate.value = newDate
selectedDate.value = newDate
calendarKey.value += 1
showDatePicker.value = false
}
// 取消日期选择
const onDatePickerCancel = () => {
showDatePicker.value = false
}
// 点击 Smart 按钮 - 跳转到智能分类页面
const onSmartClick = () => {
router.push({
@@ -346,68 +387,6 @@ onBeforeUnmount(() => {
background-color: var(--bg-primary);
}
/* ========== 头部 ========== */
.calendar-header {
display: flex;
align-items: center;
justify-content: flex-start;
padding: 8px 24px;
gap: 8px;
background: transparent !important;
position: relative;
z-index: 1;
}
.header-content {
display: flex;
flex-direction: column;
gap: 4px;
}
.header-title {
font-family: var(--font-primary);
font-size: var(--font-2xl);
font-weight: var(--font-medium);
color: var(--text-primary);
margin: 0;
}
.notif-btn {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: var(--radius-full);
background-color: var(--bg-button);
border: none;
cursor: pointer;
transition: opacity 0.2s;
margin-left: auto;
}
.notif-btn:active {
opacity: 0.7;
}
.month-nav-btn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 18px;
background-color: transparent;
border: none;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.2s;
}
.month-nav-btn:active {
background-color: var(--bg-tertiary);
}
/* 底部安全距离 */
.bottom-spacer {
height: calc(60px + env(safe-area-inset-bottom, 0px));

View File

@@ -14,11 +14,19 @@
</div>
</template>
<template #right>
<div class="nav-right-buttons">
<van-icon
name="upgrade"
size="18"
style="margin-right: 12px;"
@click="goToStatisticsV2"
/>
<van-icon
name="chat-o"
size="20"
@click="goToAnalysis"
/>
</div>
</template>
</van-nav-bar>
@@ -310,6 +318,12 @@
:transaction="currentTransaction"
@save="onBillSave"
/>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
</div>
</template>
@@ -325,10 +339,18 @@ 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 GlassBottomNav from '@/components/GlassBottomNav.vue'
import { getCssVar } from '@/utils/theme'
const router = useRouter()
//
const activeTab = ref('statistics')
const handleTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
//
}
//
const loading = ref(true)
const firstLoading = ref(true)
@@ -1063,6 +1085,11 @@ const goToAnalysis = () => {
router.push('/bill-analysis')
}
// V2
const goToStatisticsV2 = () => {
router.push('/statistics-v2')
}
//
const goToCategoryBills = (classify, type) => {
selectedClassify.value = classify || '未分类' // TODO
@@ -1338,6 +1365,12 @@ watch(dateSelectionMode, (newMode) => {
color: var(--van-text-color);
}
/* 导航栏右侧按钮组 */
.nav-right-buttons {
display: flex;
align-items: center;
}
/* 余额卡片 */
.balance-amount {
text-align: center;

View File

@@ -0,0 +1,407 @@
<template>
<!-- 支出分类统计 -->
<div
class="common-card"
style="padding-bottom: 10px;"
>
<div class="card-header">
<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 class="category-list">
<div
v-for="category in expenseCategoriesSimpView"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', 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="arrow"
class="category-arrow"
/>
</div>
<!-- 展开/收起按钮 -->
<div
v-if="expenseCategoriesView.length > 1"
class="expand-toggle"
@click="showAllExpense = !showAllExpense"
>
<van-icon :name="showAllExpense ? 'arrow-up' : 'arrow-down'" />
</div>
</div>
<ModernEmpty
v-if="!expenseCategoriesView || !expenseCategoriesView.length"
type="chart"
theme="blue"
title="暂无支出"
description="本期还没有支出记录"
size="small"
/>
</div>
</template>
<script setup>
import { ref, computed, onBeforeUnmount, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { getCssVar } from '@/utils/theme'
import ModernEmpty from '@/components/ModernEmpty.vue'
const props = defineProps({
categories: {
type: Array,
default: () => []
},
totalExpense: {
type: Number,
default: 0
},
colors: {
type: Array,
default: () => []
}
})
defineEmits(['category-click'])
const pieChartRef = ref(null)
let pieChartInstance = null
const showAllExpense = ref(false)
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 计算属性
const expenseCategoriesView = computed(() => {
const list = [...props.categories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
const expenseCategoriesSimpView = computed(() => {
const list = expenseCategoriesView.value
if (showAllExpense.value) {
return list
}
// 只展示未分类
const unclassified = list.filter((c) => c.classify === '未分类' || !c.classify)
if (unclassified.length > 0) {
return [...unclassified]
}
return []
})
// 渲染饼图
const renderPieChart = () => {
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)
}
// 使用 Top N + Other 的数据逻辑,确保图表不会太拥挤
const list = [...expenseCategoriesView.value]
let chartData = []
// 按照金额排序
list.sort((a, b) => b.amount - a.amount)
const MAX_SLICES = 8 // 最大显示扇区数,其余合并为"其他"
if (list.length > MAX_SLICES) {
const topList = list.slice(0, MAX_SLICES - 1)
const otherList = list.slice(MAX_SLICES - 1)
const otherAmount = otherList.reduce((sum, item) => sum + item.amount, 0)
chartData = topList.map((item, index) => ({
value: item.amount,
name: item.classify || '未分类',
itemStyle: { color: props.colors[index % props.colors.length] }
}))
chartData.push({
value: otherAmount,
name: '其他',
itemStyle: { color: getCssVar('--van-gray-6') } // 使用灰色表示其他
})
} else {
chartData = list.map((item, index) => ({
value: item.amount,
name: item.classify || '未分类',
itemStyle: { color: props.colors[index % props.colors.length] }
}))
}
const option = {
title: {
text: '¥' + formatMoney(props.totalExpense),
subtext: '总支出',
left: 'center',
top: 'center',
textStyle: {
color: getCssVar('--chart-text-muted'), // 适配深色模式
fontSize: 20,
fontWeight: 'bold'
},
subtextStyle: {
color: getCssVar('--chart-text-muted'),
fontSize: 13
}
},
tooltip: {
trigger: 'item',
formatter: (params) => {
return `${params.name}: ¥${formatMoney(params.value)} (${params.percent.toFixed(1)}%)`
}
},
series: [
{
name: '支出分类',
type: 'pie',
radius: ['50%', '80%'],
avoidLabelOverlap: true,
minAngle: 5, // 最小扇区角度,防止扇区太小看不见
itemStyle: {
borderRadius: 5,
borderColor: getCssVar('--van-background-2'),
borderWidth: 2
},
label: {
show: false
},
labelLine: {
show: false
},
data: chartData
}
]
}
pieChartInstance.setOption(option)
}
// 监听数据变化重新渲染图表
watch(() => [props.categories, props.totalExpense, props.colors], () => {
nextTick(() => {
renderPieChart()
})
}, { deep: true, immediate: true })
// 组件销毁时清理图表实例
onBeforeUnmount(() => {
if (pieChartInstance && !pieChartInstance.isDisposed()) {
pieChartInstance.dispose()
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
/* 环形图 */
.chart-container {
padding: 0;
}
.ring-chart {
position: relative;
width: 100%;
height: 200px;
margin: 0 auto;
}
/* 分类列表 */
.category-list {
padding: 0;
}
.category-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--van-border-color);
transition: background-color 0.2s;
gap: 12px;
}
.category-item:last-child {
border-bottom: none;
}
.category-item.clickable {
cursor: pointer;
}
.category-item.clickable:active {
background-color: var(--van-background);
}
.category-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 0;
}
.category-name-with-count {
display: flex;
align-items: center;
gap: 8px;
}
.category-color {
width: 12px;
height: 12px;
border-radius: 50%;
}
.category-name {
font-size: 14px;
color: var(--van-text-color);
}
.category-count {
font-size: 12px;
color: var(--van-text-color-3);
}
.category-stats {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.category-arrow {
margin-left: 8px;
color: var(--van-text-color-3);
font-size: 16px;
flex-shrink: 0;
}
.expand-toggle {
display: flex;
justify-content: center;
align-items: center;
padding-top: 0;
color: var(--van-text-color-3);
font-size: 20px;
cursor: pointer;
}
.expand-toggle:active {
opacity: 0.7;
}
.category-amount {
font-size: 15px;
font-weight: 600;
color: var(--van-text-color);
}
.category-percent {
font-size: 12px;
color: var(--van-text-color-3);
background: var(--van-background);
padding: 2px 8px;
border-radius: 10px;
}
</style>

View File

@@ -0,0 +1,272 @@
<template>
<!-- 收支和不计收支并列显示 -->
<div class="side-by-side-cards">
<!-- 收入分类统计 -->
<div class="common-card half-card">
<div class="card-header">
<h3 class="card-title">
收入
<span
class="income-text"
style="font-size: 13px; margin-left: 4px"
>
¥{{ formatMoney(totalIncome) }}
</span>
</h3>
<van-tag
type="success"
size="medium"
>
{{ incomeCategories.length }}
</van-tag>
</div>
<div
v-if="incomeCategories.length > 0"
class="category-list"
>
<div
v-for="category in incomeCategories"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 1)"
>
<div class="category-info">
<div class="category-color income-color" />
<span class="category-name text-ellipsis">{{ category.classify || '未分类' }}</span>
</div>
<div class="category-amount income-text">
¥{{ formatMoney(category.amount) }}
</div>
</div>
</div>
<ModernEmpty
v-else
type="finance"
theme="green"
title="暂无收入"
description="本期还没有收入记录"
size="small"
/>
</div>
<!-- 不计收支分类统计 -->
<div class="common-card half-card">
<div class="card-header">
<h3 class="card-title">
不计收支
</h3>
<van-tag
type="warning"
size="medium"
>
{{ noneCategories.length }}
</van-tag>
</div>
<div
v-if="noneCategories.length > 0"
class="category-list"
>
<div
v-for="category in noneCategories"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 2)"
>
<div class="category-info">
<div class="category-color none-color" />
<span class="category-name text-ellipsis">{{ category.classify || '未分类' }}</span>
</div>
<div class="category-amount none-text">
¥{{ formatMoney(category.amount) }}
</div>
</div>
</div>
<ModernEmpty
v-else
type="inbox"
theme="gray"
title="暂无数据"
description="本期没有不计收支记录"
size="small"
/>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
import ModernEmpty from '@/components/ModernEmpty.vue'
const props = defineProps({
incomeCategories: {
type: Array,
default: () => []
},
noneCategories: {
type: Array,
default: () => []
},
totalIncome: {
type: Number,
default: 0
}
})
defineEmits(['category-click'])
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 处理未分类排序
const incomeCategories = computed(() => {
const list = [...props.incomeCategories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
const noneCategories = computed(() => {
const list = [...props.noneCategories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
/* 并列显示卡片 */
.side-by-side-cards {
display: flex;
gap: 12px;
margin: 0 12px 16px;
}
.side-by-side-cards .common-card {
margin: 0;
flex: 1;
min-width: 0; /* 允许内部元素缩小 */
padding: 12px;
}
.card-header {
margin-bottom: 0;
}
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 13px;
}
/* 分类列表 */
.category-list {
padding: 0;
}
.category-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--van-border-color);
transition: background-color 0.2s;
gap: 12px;
}
.category-item:last-child {
border-bottom: none;
}
.category-item.clickable {
cursor: pointer;
}
.category-item.clickable:active {
background-color: var(--van-background);
}
.category-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 0;
}
.category-color {
width: 12px;
height: 12px;
border-radius: 50%;
}
.category-name {
font-size: 14px;
color: var(--van-text-color);
}
.category-amount {
font-size: 15px;
font-weight: 600;
color: var(--van-text-color);
flex-shrink: 0;
}
.income-color {
background-color: var(--van-success-color);
}
.income-text {
color: var(--van-success-color);
}
/* 不计收支颜色 */
.none-color {
background-color: var(--van-gray-6);
}
.none-text {
color: var(--van-gray-6);
}
</style>

View File

@@ -0,0 +1,766 @@
<template>
<van-config-provider :theme="theme">
<div class="page-container-flex statistics-v2-wrapper">
<!-- 头部年月选择器 -->
<CalendarHeader
:type="currentPeriod"
:current-date="currentDate"
:show-notification="true"
@prev="handlePrevPeriod"
@next="handleNextPeriod"
@jump="showDatePicker = true"
@notification="goToStatisticsV1"
/>
<div>
<!-- 时间段选择器 -->
<TimePeriodTabs
:active-tab="currentPeriod"
@change="handlePeriodChange"
/>
</div>
<!-- 可滚动内容区域 -->
<div class="statistics-scroll-content">
<!-- 下拉刷新 -->
<van-pull-refresh
v-model="refreshing"
@refresh="onRefresh"
>
<!-- 加载状态 -->
<van-loading
v-if="loading"
vertical
style="padding: 100px 0"
>
加载统计数据中...
</van-loading>
<!-- 错误状态 -->
<div
v-else-if="hasError"
class="error-state"
>
<van-empty
image="error"
:description="errorMessage || '加载数据时出现错误'"
>
<van-button
type="primary"
size="small"
@click="retryLoad"
>
重试
</van-button>
</van-empty>
</div>
<!-- 统计内容 -->
<div
v-else
class="statistics-content"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<!-- 收支结余和趋势卡片合并 -->
<MonthlyExpenseCard
:amount="monthlyStats.totalExpense"
:income="monthlyStats.totalIncome"
:balance="monthlyStats.balance"
:trend-data="trendStats"
:period="currentPeriod"
:current-date="currentDate"
/>
<!-- 支出分类卡片 -->
<ExpenseCategoryCard
:categories="expenseCategories"
:total-expense="monthlyStats.totalExpense"
:colors="categoryColors"
@category-click="goToCategoryBills"
/>
<!-- 收入和不计收支分类卡片 -->
<IncomeNoneCategoryCard
:income-categories="incomeCategories"
:none-categories="noneCategories"
:total-income="monthlyStats.totalIncome"
@category-click="goToCategoryBills"
/>
</div>
</van-pull-refresh>
</div>
<!-- 日期选择器 -->
<van-popup
v-model:show="showDatePicker"
position="bottom"
:style="{ height: '50%' }"
>
<van-date-picker
v-model="selectedDate"
:type="datePickerType"
:min-date="minDate"
:max-date="maxDate"
@confirm="onDateConfirm"
@cancel="showDatePicker = false"
/>
</van-popup>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
<!-- 分类账单弹窗 -->
<CategoryBillPopup
v-model="billPopupVisible"
:classify="selectedClassify"
:type="selectedType"
:year="currentDate.getFullYear()"
:month="currentPeriod === 'year' ? 0 : currentDate.getMonth() + 1"
@refresh="loadStatistics"
/>
</div>
</van-config-provider>
</template>
<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import CalendarHeader from '@/components/DateSelectHeader.vue'
import TimePeriodTabs from '@/components/TimePeriodTabs.vue'
import MonthlyExpenseCard from './modules/MonthlyExpenseCard.vue'
import ExpenseCategoryCard from './modules/ExpenseCategoryCard.vue'
import IncomeNoneCategoryCard from './modules/IncomeNoneCategoryCard.vue'
import CategoryBillPopup from '@/components/CategoryBillPopup.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
import { getMonthlyStatistics, getCategoryStatistics, getCategoryStatisticsByDateRange, getDailyStatistics, getTrendStatistics, getWeeklyStatistics, getRangeStatistics } from '@/api/statistics'
import { useMessageStore } from '@/stores/message'
import { getCssVar } from '@/utils/theme'
// 为组件缓存设置名称
defineOptions({
name: 'StatisticsV2View'
})
const router = useRouter()
const messageStore = useMessageStore()
// 主题
const theme = computed(() => messageStore.isDarkMode ? 'dark' : 'light')
// 底部导航栏
const activeTab = ref('statistics')
const handleTabClick = (_item, _index) => {
// 导航逻辑已在组件内部处理
}
// 状态管理
const loading = ref(false)
const refreshing = ref(false)
const showDatePicker = ref(false)
const errorMessage = ref('')
const hasError = ref(false)
// 分类账单弹窗状态
const billPopupVisible = ref(false)
const selectedClassify = ref('')
const selectedType = ref(0)
// 触摸滑动相关状态
const touchStartX = ref(0)
const touchStartY = ref(0)
const touchEndX = ref(0)
const touchEndY = ref(0)
// 时间段选择
const currentPeriod = ref('month')
const currentDate = ref(new Date())
const selectedDate = ref([])
const minDate = new Date(2020, 0, 1)
const maxDate = new Date()
// 统计数据
const monthlyStats = ref({
totalExpense: 0,
totalIncome: 0,
balance: 0,
expenseCount: 0,
incomeCount: 0
})
const trendStats = ref([])
const expenseCategories = ref([])
const incomeCategories = ref([])
const noneCategories = ref([])
// 颜色配置
const categoryColors = [
'#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
'#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9'
]
// 计算属性
const datePickerType = computed(() => {
switch (currentPeriod.value) {
case 'week':
case 'month':
return 'year-month'
case 'year':
return 'year'
default:
return 'year-month'
}
})
// 获取周的开始日期(周一)
const getWeekStartDate = (date) => {
const target = new Date(date.valueOf())
const dayNr = (date.getDay() + 6) % 7 // 周一为0周日为6
target.setDate(target.getDate() - dayNr)
target.setHours(0, 0, 0, 0)
return target
}
// 格式化日期为字符串
const formatDateToString = (date) => {
const year = date.getFullYear()
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const day = date.getDate().toString().padStart(2, '0')
return `${year}-${month}-${day}`
}
// 加载统计数据
const loadStatistics = async () => {
if (loading.value && !refreshing.value) {
return // 防止重复加载
}
loading.value = !refreshing.value
try {
const year = currentDate.value.getFullYear()
const month = currentDate.value.getMonth() + 1
// 重置数据
monthlyStats.value = {
totalExpense: 0,
totalIncome: 0,
balance: 0,
expenseCount: 0,
incomeCount: 0
}
trendStats.value = []
expenseCategories.value = []
incomeCategories.value = []
noneCategories.value = []
// 根据时间段加载不同的数据
if (currentPeriod.value === 'month') {
await loadMonthlyData(year, month)
} else if (currentPeriod.value === 'year') {
await loadYearlyData(year)
} else if (currentPeriod.value === 'week') {
await loadWeeklyData()
}
// 加载分类统计
await loadCategoryStatistics(year, month)
} catch (error) {
console.error('加载统计数据失败:', error)
hasError.value = true
errorMessage.value = error.message || '网络连接异常,请检查网络后重试'
} finally {
loading.value = false
}
}
// 重试加载
const retryLoad = () => {
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
// 加载月度数据
const loadMonthlyData = async (year, month) => {
try {
// 月度统计
const monthlyResult = await getMonthlyStatistics({ year, month })
if (monthlyResult?.success && monthlyResult.data) {
monthlyStats.value = {
totalExpense: monthlyResult.data.totalExpense || 0,
totalIncome: monthlyResult.data.totalIncome || 0,
balance: (monthlyResult.data.totalIncome || 0) - (monthlyResult.data.totalExpense || 0),
expenseCount: monthlyResult.data.expenseCount || 0,
incomeCount: monthlyResult.data.incomeCount || 0
}
}
// 加载每日统计
const dailyResult = await getDailyStatistics({ year, month })
if (dailyResult?.success && dailyResult.data) {
trendStats.value = dailyResult.data.filter(item => item != null)
}
} catch (error) {
console.error('加载月度数据失败:', error)
}
}
// 加载年度数据
const loadYearlyData = async (year) => {
try {
// 年度统计 - 使用趋势接口获取12个月数据
const trendResult = await getTrendStatistics({ startYear: year, startMonth: 1, monthCount: 12 })
if (trendResult?.success && trendResult.data) {
// 计算年度汇总
const yearTotal = trendResult.data.reduce((acc, item) => {
const expense = item.expense || 0
const income = item.income || 0
return {
totalExpense: acc.totalExpense + expense,
totalIncome: acc.totalIncome + income,
balance: acc.balance + income - expense
}
}, { totalExpense: 0, totalIncome: 0, balance: 0 })
monthlyStats.value = {
...yearTotal,
expenseCount: 0,
incomeCount: 0
}
trendStats.value = trendResult.data.map(item => ({
date: `${item.year}-${item.month.toString().padStart(2, '0')}-01`,
amount: (item.income || 0) - (item.expense || 0),
count: 1
}))
}
} catch (error) {
console.error('加载年度数据失败:', error)
}
}
// 加载周度数据
const loadWeeklyData = async () => {
try {
// 周统计 - 计算当前周的开始和结束日期
const weekStart = getWeekStartDate(currentDate.value)
const weekEnd = new Date(weekStart)
weekEnd.setDate(weekStart.getDate() + 6)
// 获取周统计汇总
const weekSummaryResult = await getRangeStatistics({
startDate: formatDateToString(weekStart),
endDate: formatDateToString(weekEnd)
})
if (weekSummaryResult?.success && weekSummaryResult.data) {
monthlyStats.value = {
totalExpense: weekSummaryResult.data.totalExpense || 0,
totalIncome: weekSummaryResult.data.totalIncome || 0,
balance: (weekSummaryResult.data.totalIncome || 0) - (weekSummaryResult.data.totalExpense || 0),
expenseCount: weekSummaryResult.data.expenseCount || 0,
incomeCount: weekSummaryResult.data.incomeCount || 0
}
}
// 获取周内每日统计
const dailyResult = await getWeeklyStatistics({
startDate: formatDateToString(weekStart),
endDate: formatDateToString(weekEnd)
})
if (dailyResult?.success && dailyResult.data) {
// 转换数据格式以适配图表组件
trendStats.value = dailyResult.data.map(item => ({
date: item.date,
amount: (item.income || 0) - (item.expense || 0),
count: item.count || 0
}))
}
} catch (error) {
console.error('加载周度数据失败:', error)
}
}
// 加载分类统计
const loadCategoryStatistics = async (year, month) => {
try {
const categoryYear = year
const categoryMonth = month
// 对于周统计,使用日期范围进行分类统计
if (currentPeriod.value === 'week') {
const weekStart = getWeekStartDate(currentDate.value)
const weekEnd = new Date(weekStart)
weekEnd.setDate(weekStart.getDate() + 6)
weekEnd.setHours(23, 59, 59, 999)
const startDateStr = formatDateToString(weekStart)
const endDateStr = formatDateToString(weekEnd)
// 并发加载支出、收入和不计收支分类(使用日期范围)
const [expenseResult, incomeResult, noneResult] = await Promise.allSettled([
getCategoryStatisticsByDateRange({ startDate: startDateStr, endDate: endDateStr, type: 0 }),
getCategoryStatisticsByDateRange({ startDate: startDateStr, endDate: endDateStr, type: 1 }),
getCategoryStatisticsByDateRange({ startDate: startDateStr, endDate: endDateStr, type: 2 })
])
// 获取图表颜色配置
const getChartColors = () => [
getCssVar('--chart-color-1'),
getCssVar('--chart-color-2'),
getCssVar('--chart-color-3'),
getCssVar('--chart-color-4'),
getCssVar('--chart-color-5'),
getCssVar('--chart-color-6'),
getCssVar('--chart-color-7'),
getCssVar('--chart-color-8'),
getCssVar('--chart-color-9'),
getCssVar('--chart-color-10'),
getCssVar('--chart-color-11'),
getCssVar('--chart-color-12'),
getCssVar('--chart-color-13'),
getCssVar('--chart-color-14'),
getCssVar('--chart-color-15')
]
const currentColors = getChartColors()
// 处理支出分类结果
if (expenseResult.status === 'fulfilled' && expenseResult.value?.success && expenseResult.value.data) {
expenseCategories.value = expenseResult.value.data.map((item, index) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0,
color: currentColors[index % currentColors.length]
}))
}
// 处理收入分类结果
if (incomeResult.status === 'fulfilled' && incomeResult.value?.success && incomeResult.value.data) {
incomeCategories.value = incomeResult.value.data.map((item) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0
}))
}
// 处理不计收支分类结果
if (noneResult.status === 'fulfilled' && noneResult.value?.success && noneResult.value.data) {
noneCategories.value = noneResult.value.data.map((item) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0
}))
}
} else {
// 对于月度和年度统计,使用年月进行分类统计
// 并发加载支出、收入和不计收支分类
const [expenseResult, incomeResult, noneResult] = await Promise.allSettled([
getCategoryStatistics({ year: categoryYear, month: categoryMonth, type: 0 }),
getCategoryStatistics({ year: categoryYear, month: categoryMonth, type: 1 }),
getCategoryStatistics({ year: categoryYear, month: categoryMonth, type: 2 })
])
// 获取图表颜色配置
const getChartColors = () => [
getCssVar('--chart-color-1'),
getCssVar('--chart-color-2'),
getCssVar('--chart-color-3'),
getCssVar('--chart-color-4'),
getCssVar('--chart-color-5'),
getCssVar('--chart-color-6'),
getCssVar('--chart-color-7'),
getCssVar('--chart-color-8'),
getCssVar('--chart-color-9'),
getCssVar('--chart-color-10'),
getCssVar('--chart-color-11'),
getCssVar('--chart-color-12'),
getCssVar('--chart-color-13'),
getCssVar('--chart-color-14'),
getCssVar('--chart-color-15')
]
const currentColors = getChartColors()
// 处理支出分类结果
if (expenseResult.status === 'fulfilled' && expenseResult.value?.success && expenseResult.value.data) {
expenseCategories.value = expenseResult.value.data.map((item, index) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0,
color: currentColors[index % currentColors.length]
}))
}
// 处理收入分类结果
if (incomeResult.status === 'fulfilled' && incomeResult.value?.success && incomeResult.value.data) {
incomeCategories.value = incomeResult.value.data.map((item) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0
}))
}
// 处理不计收支分类结果
if (noneResult.status === 'fulfilled' && noneResult.value?.success && noneResult.value.data) {
noneCategories.value = noneResult.value.data.map((item) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0
}))
}
}
} catch (error) {
console.error('加载分类统计失败:', error)
}
}
// 处理时间段切换
const handlePeriodChange = (period) => {
currentPeriod.value = period
// 清除错误状态
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
// 切换时间周期
const handlePrevPeriod = () => {
const newDate = new Date(currentDate.value)
switch (currentPeriod.value) {
case 'week':
newDate.setDate(newDate.getDate() - 7)
break
case 'month':
newDate.setMonth(newDate.getMonth() - 1)
break
case 'year':
newDate.setFullYear(newDate.getFullYear() - 1)
break
}
currentDate.value = newDate
// 清除错误状态
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
const handleNextPeriod = () => {
// 检查是否已经是最后一个周期(当前周期)
if (isLastPeriod()) {
return
}
const newDate = new Date(currentDate.value)
switch (currentPeriod.value) {
case 'week':
newDate.setDate(newDate.getDate() + 7)
break
case 'month':
newDate.setMonth(newDate.getMonth() + 1)
break
case 'year':
newDate.setFullYear(newDate.getFullYear() + 1)
break
}
currentDate.value = newDate
// 清除错误状态
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
// 判断是否是最后一个周期(不能再往后切换)
const isLastPeriod = () => {
const now = new Date()
const current = new Date(currentDate.value)
switch (currentPeriod.value) {
case 'week': {
// 获取当前周的开始日期和当前时间所在周的开始日期
const currentWeekStart = getWeekStartDate(current)
const nowWeekStart = getWeekStartDate(now)
return currentWeekStart >= nowWeekStart
}
case 'month': {
// 比较年月
return current.getFullYear() === now.getFullYear() &&
current.getMonth() === now.getMonth()
}
case 'year': {
// 比较年份
return current.getFullYear() === now.getFullYear()
}
default:
return false
}
}
// 触摸事件处理
const handleTouchStart = (e) => {
touchStartX.value = e.touches[0].clientX
touchStartY.value = e.touches[0].clientY
}
const handleTouchMove = (e) => {
touchEndX.value = e.touches[0].clientX
touchEndY.value = e.touches[0].clientY
}
const handleTouchEnd = () => {
const deltaX = touchEndX.value - touchStartX.value
const deltaY = touchEndY.value - touchStartY.value
// 判断是否是水平滑动(水平距离大于垂直距离)
if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
if (deltaX > 0) {
// 右滑 - 上一个周期
handlePrevPeriod()
} else {
// 左滑 - 下一个周期
handleNextPeriod()
}
}
// 重置触摸位置
touchStartX.value = 0
touchStartY.value = 0
touchEndX.value = 0
touchEndY.value = 0
}
// 下拉刷新
const onRefresh = async () => {
// 清除错误状态
hasError.value = false
errorMessage.value = ''
await loadStatistics()
refreshing.value = false
}
// 日期选择确认
const onDateConfirm = ({ selectedValues }) => {
if (currentPeriod.value === 'year') {
const [year] = selectedValues
currentDate.value = new Date(year, 0, 1)
} else {
const [year, month] = selectedValues
currentDate.value = new Date(year, month - 1, 1)
}
showDatePicker.value = false
// 清除错误状态
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
// 跳转到分类账单
const goToCategoryBills = (classify, type) => {
selectedClassify.value = classify || ''
selectedType.value = type
billPopupVisible.value = true
}
// 切换到统计V1页面
const goToStatisticsV1 = () => {
router.push({ name: 'statistics' })
}
// 监听时间段变化,更新选中日期
watch(currentPeriod, () => {
if (currentPeriod.value === 'year') {
selectedDate.value = [currentDate.value.getFullYear()]
} else {
selectedDate.value = [
currentDate.value.getFullYear(),
currentDate.value.getMonth() + 1
]
}
})
// 初始化
onMounted(() => {
// 设置默认选中日期
selectedDate.value = [
currentDate.value.getFullYear(),
currentDate.value.getMonth() + 1
]
loadStatistics()
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
/* ========== 页面容器 ========== */
.statistics-v2-wrapper {
font-family: var(--font-primary);
color: var(--text-primary);
height: 100vh;
display: flex;
flex-direction: column;
}
.statistics-scroll-content {
flex: 1;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
overscroll-behavior: contain;
background-color: var(--bg-secondary);
/* 改善滚动性能 */
will-change: scroll-position;
/* 防止滚动卡顿 */
scroll-behavior: smooth;
}
.statistics-content {
padding: var(--spacing-md);
padding-bottom: calc(80px + env(safe-area-inset-bottom, 0px));
min-height: 100%;
/* 确保内容足够高以便滚动 */
display: flex;
flex-direction: column;
gap: var(--spacing-md);
}
.error-state {
padding: var(--spacing-3xl) var(--spacing-md);
text-align: center;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
/* 在移动设备上优化滚动体验 */
@media (max-width: 768px) {
.statistics-scroll-content {
/* iOS Safari 优化 */
-webkit-overflow-scrolling: touch;
/* 防止橡皮筋效果 */
overscroll-behavior-y: contain;
}
.statistics-content {
padding: var(--spacing-sm);
padding-bottom: calc(90px + env(safe-area-inset-bottom, 0px));
}
}
</style>

View File

@@ -0,0 +1,361 @@
<template>
<div class="daily-trend-card common-card">
<div class="card-header">
<h3 class="card-title">
{{ chartTitle }} (收支)
</h3>
</div>
<div
ref="chartRef"
class="trend-chart"
/>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useMessageStore } from '@/stores/message'
const props = defineProps({
data: {
type: Array,
default: () => []
},
period: {
type: String,
default: 'month'
},
currentDate: {
type: Date,
required: true
}
})
const messageStore = useMessageStore()
const chartRef = ref()
let chartInstance = null
// 计算图表标题
const chartTitle = computed(() => {
switch (props.period) {
case 'week':
return '每日趋势'
case 'month':
return '每日趋势'
case 'year':
return '每月趋势'
default:
return '趋势'
}
})
// 获取月份天数
const getDaysInMonth = (year, month) => {
return new Date(year, month, 0).getDate()
}
// 初始化图表
const initChart = async () => {
await nextTick()
if (!chartRef.value) {
console.warn('图表容器未找到')
return
}
// 销毁已存在的图表实例
if (chartInstance) {
chartInstance.dispose()
chartInstance = null
}
try {
chartInstance = echarts.init(chartRef.value)
updateChart()
} catch (error) {
console.error('初始化图表失败:', error)
}
}
// 更新图表
const updateChart = () => {
if (!chartInstance) {
console.warn('图表实例不存在')
return
}
// 验证数据
if (!Array.isArray(props.data)) {
console.warn('图表数据格式错误')
return
}
// 根据时间段类型和数据来生成图表
let chartData = []
let xAxisLabels = []
try {
if (props.period === 'week') {
// 周统计:直接使用传入的数据,按日期排序
chartData = [...props.data].sort((a, b) => new Date(a.date) - new Date(b.date))
xAxisLabels = chartData.map(item => {
const date = new Date(item.date)
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
return weekDays[date.getDay()]
})
} else if (props.period === 'month') {
// 月统计:生成完整的月份数据
const currentDate = props.currentDate
const year = currentDate.getFullYear()
const month = currentDate.getMonth() + 1
const daysInMonth = getDaysInMonth(year, month)
const allDays = Array.from({ length: daysInMonth }, (_, i) => {
const day = i + 1
const paddedDay = day.toString().padStart(2, '0')
return `${year}-${month.toString().padStart(2, '0')}-${paddedDay}`
})
// 创建完整的数据映射
const dataMap = new Map()
props.data.forEach(item => {
if (item && item.date) {
dataMap.set(item.date, item)
}
})
// 生成完整的数据序列
chartData = allDays.map(date => {
const dayData = dataMap.get(date)
return {
date,
amount: dayData?.amount || 0,
count: dayData?.count || 0
}
})
xAxisLabels = chartData.map((_, index) => (index + 1).toString())
} else if (props.period === 'year') {
// 年统计:直接使用数据,显示月份标签
chartData = [...props.data]
.filter(item => item && item.date)
.sort((a, b) => new Date(a.date) - new Date(b.date))
xAxisLabels = chartData.map(item => {
const date = new Date(item.date)
return `${date.getMonth() + 1}`
})
}
// 如果没有有效数据,显示空图表
if (chartData.length === 0) {
const option = {
backgroundColor: 'transparent',
graphic: [{
type: 'text',
left: 'center',
top: 'middle',
style: {
text: '暂无数据',
fontSize: 16,
fill: messageStore.isDarkMode ? '#9CA3AF' : '#6B7280'
}
}]
}
chartInstance.setOption(option)
return
}
// 准备图表数据
const expenseData = chartData.map(item => {
const amount = item.amount || 0
return amount < 0 ? Math.abs(amount) : 0
})
const incomeData = chartData.map(item => {
const amount = item.amount || 0
return amount > 0 ? amount : 0
})
const isDark = messageStore.isDarkMode
const option = {
backgroundColor: 'transparent',
grid: {
top: 20,
left: 10,
right: 10,
bottom: 20,
containLabel: false
},
xAxis: {
type: 'category',
data: xAxisLabels,
show: false
},
yAxis: {
type: 'value',
show: false
},
series: [
// 支出线
{
name: '支出',
type: 'line',
data: expenseData,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#ff6b6b',
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
{ offset: 1, color: 'rgba(255, 107, 107, 0.05)' }
]
}
}
},
// 收入线
{
name: '收入',
type: 'line',
data: incomeData,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#4ade80',
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(74, 222, 128, 0.3)' },
{ offset: 1, color: 'rgba(74, 222, 128, 0.05)' }
]
}
}
}
],
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'rgba(39, 39, 42, 0.95)' : 'rgba(255, 255, 255, 0.95)',
borderColor: isDark ? 'rgba(63, 63, 70, 0.8)' : 'rgba(229, 231, 235, 0.8)',
textStyle: {
color: isDark ? '#f4f4f5' : '#1a1a1a'
},
formatter: (params) => {
if (!params || params.length === 0 || !chartData[params[0].dataIndex]) {
return ''
}
const date = chartData[params[0].dataIndex].date
let content = ''
try {
if (props.period === 'week') {
const dateObj = new Date(date)
const month = dateObj.getMonth() + 1
const day = dateObj.getDate()
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
const weekDay = weekDays[dateObj.getDay()]
content = `${month}${day}日 (周${weekDay})<br/>`
} else if (props.period === 'month') {
const day = new Date(date).getDate()
content = `${props.currentDate.getMonth() + 1}${day}日<br/>`
} else if (props.period === 'year') {
const dateObj = new Date(date)
content = `${dateObj.getFullYear()}${dateObj.getMonth() + 1}月<br/>`
}
params.forEach((param) => {
if (param.value > 0) {
const color = param.seriesName === '支出' ? '#ff6b6b' : '#4ade80'
content += `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color}"></span>`
content += `${param.seriesName}: ¥${param.value.toFixed(2)}<br/>`
}
})
} catch (error) {
console.warn('格式化tooltip失败:', error)
content = '数据格式错误'
}
return content
}
}
}
chartInstance.setOption(option)
} catch (error) {
console.error('更新图表失败:', error)
}
}
// 监听数据变化
watch(() => props.data, () => {
if (chartInstance) {
updateChart()
}
}, { deep: true })
// 监听主题变化
watch(() => messageStore.isDarkMode, () => {
if (chartInstance) {
updateChart()
}
})
onMounted(() => {
initChart()
})
onBeforeUnmount(() => {
if (chartInstance) {
chartInstance.dispose()
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
.daily-trend-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
.trend-chart {
width: 100%;
height: 180px;
}
</style>

View File

@@ -0,0 +1,27 @@
<template>
<CategoryCard
title="支出分类"
:categories="categories"
:type="0"
tag-type="primary"
empty-description="本期暂无支出记录"
@category-click="handleCategoryClick"
/>
</template>
<script setup>
import CategoryCard from '@/components/Statistics/CategoryCard.vue'
defineProps({
categories: {
type: Array,
default: () => []
}
})
const emit = defineEmits(['category-click'])
const handleCategoryClick = (classify, type) => {
emit('category-click', classify, type)
}
</script>

View File

@@ -0,0 +1,407 @@
<template>
<!-- 支出分类统计 -->
<div
class="common-card"
style="padding-bottom: 10px;"
>
<div class="card-header">
<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 class="category-list">
<div
v-for="category in expenseCategoriesSimpView"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', 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="arrow"
class="category-arrow"
/>
</div>
<!-- 展开/收起按钮 -->
<div
v-if="expenseCategoriesView.length > 1"
class="expand-toggle"
@click="showAllExpense = !showAllExpense"
>
<van-icon :name="showAllExpense ? 'arrow-up' : 'arrow-down'" />
</div>
</div>
<ModernEmpty
v-if="!expenseCategoriesView || !expenseCategoriesView.length"
type="chart"
theme="blue"
title="暂无支出"
description="本期还没有支出记录"
size="small"
/>
</div>
</template>
<script setup>
import { ref, computed, onBeforeUnmount, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { getCssVar } from '@/utils/theme'
import ModernEmpty from '@/components/ModernEmpty.vue'
const props = defineProps({
categories: {
type: Array,
default: () => []
},
totalExpense: {
type: Number,
default: 0
},
colors: {
type: Array,
default: () => []
}
})
defineEmits(['category-click'])
const pieChartRef = ref(null)
let pieChartInstance = null
const showAllExpense = ref(false)
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 计算属性
const expenseCategoriesView = computed(() => {
const list = [...props.categories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
const expenseCategoriesSimpView = computed(() => {
const list = expenseCategoriesView.value
if (showAllExpense.value) {
return list
}
// 只展示未分类
const unclassified = list.filter((c) => c.classify === '未分类' || !c.classify)
if (unclassified.length > 0) {
return [...unclassified]
}
return []
})
// 渲染饼图
const renderPieChart = () => {
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)
}
// 使用 Top N + Other 的数据逻辑,确保图表不会太拥挤
const list = [...expenseCategoriesView.value]
let chartData = []
// 按照金额排序
list.sort((a, b) => b.amount - a.amount)
const MAX_SLICES = 8 // 最大显示扇区数,其余合并为"其他"
if (list.length > MAX_SLICES) {
const topList = list.slice(0, MAX_SLICES - 1)
const otherList = list.slice(MAX_SLICES - 1)
const otherAmount = otherList.reduce((sum, item) => sum + item.amount, 0)
chartData = topList.map((item, index) => ({
value: item.amount,
name: item.classify || '未分类',
itemStyle: { color: props.colors[index % props.colors.length] }
}))
chartData.push({
value: otherAmount,
name: '其他',
itemStyle: { color: getCssVar('--van-gray-6') } // 使用灰色表示其他
})
} else {
chartData = list.map((item, index) => ({
value: item.amount,
name: item.classify || '未分类',
itemStyle: { color: props.colors[index % props.colors.length] }
}))
}
const option = {
title: {
text: '¥' + formatMoney(props.totalExpense),
subtext: '总支出',
left: 'center',
top: 'center',
textStyle: {
color: getCssVar('--chart-text-muted'), // 适配深色模式
fontSize: 20,
fontWeight: 'bold'
},
subtextStyle: {
color: getCssVar('--chart-text-muted'),
fontSize: 13
}
},
tooltip: {
trigger: 'item',
formatter: (params) => {
return `${params.name}: ¥${formatMoney(params.value)} (${params.percent.toFixed(1)}%)`
}
},
series: [
{
name: '支出分类',
type: 'pie',
radius: ['50%', '80%'],
avoidLabelOverlap: true,
minAngle: 5, // 最小扇区角度,防止扇区太小看不见
itemStyle: {
borderRadius: 5,
borderColor: getCssVar('--van-background-2'),
borderWidth: 2
},
label: {
show: false
},
labelLine: {
show: false
},
data: chartData
}
]
}
pieChartInstance.setOption(option)
}
// 监听数据变化重新渲染图表
watch(() => [props.categories, props.totalExpense, props.colors], () => {
nextTick(() => {
renderPieChart()
})
}, { deep: true, immediate: true })
// 组件销毁时清理图表实例
onBeforeUnmount(() => {
if (pieChartInstance && !pieChartInstance.isDisposed()) {
pieChartInstance.dispose()
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
/* 环形图 */
.chart-container {
padding: 0;
}
.ring-chart {
position: relative;
width: 100%;
height: 200px;
margin: 0 auto;
}
/* 分类列表 */
.category-list {
padding: 0;
}
.category-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--van-border-color);
transition: background-color 0.2s;
gap: 12px;
}
.category-item:last-child {
border-bottom: none;
}
.category-item.clickable {
cursor: pointer;
}
.category-item.clickable:active {
background-color: var(--van-background);
}
.category-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 0;
}
.category-name-with-count {
display: flex;
align-items: center;
gap: 8px;
}
.category-color {
width: 12px;
height: 12px;
border-radius: 50%;
}
.category-name {
font-size: 14px;
color: var(--van-text-color);
}
.category-count {
font-size: 12px;
color: var(--van-text-color-3);
}
.category-stats {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.category-arrow {
margin-left: 8px;
color: var(--van-text-color-3);
font-size: 16px;
flex-shrink: 0;
}
.expand-toggle {
display: flex;
justify-content: center;
align-items: center;
padding-top: 0;
color: var(--van-text-color-3);
font-size: 20px;
cursor: pointer;
}
.expand-toggle:active {
opacity: 0.7;
}
.category-amount {
font-size: 15px;
font-weight: 600;
color: var(--van-text-color);
}
.category-percent {
font-size: 12px;
color: var(--van-text-color-3);
background: var(--van-background);
padding: 2px 8px;
border-radius: 10px;
}
</style>

View File

@@ -0,0 +1,93 @@
<template>
<div class="income-balance-card common-card">
<div class="stats-row">
<div class="stat-item">
<div class="stat-label">
本月收入
</div>
<div class="stat-amount income">
¥{{ formatMoney(income) }}
</div>
</div>
<div class="stat-item">
<div class="stat-label">
结余
</div>
<div
class="stat-amount"
:class="balanceClass"
>
¥{{ formatMoney(balance) }}
</div>
</div>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
import { formatMoney } from '@/utils/format'
const props = defineProps({
income: {
type: Number,
required: true
},
balance: {
type: Number,
required: true
}
})
const balanceClass = computed(() => ({
'positive': props.balance >= 0,
'negative': props.balance < 0
}))
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
.income-balance-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.stats-row {
display: flex;
gap: var(--spacing-3xl);
}
.stat-item {
flex: 1;
.stat-label {
font-size: var(--font-base);
color: var(--text-secondary);
margin-bottom: var(--spacing-md);
}
.stat-amount {
font-size: var(--font-xl);
font-weight: var(--font-semibold);
font-family: var(--font-display);
line-height: 1.2;
&.income {
color: var(--accent-success);
}
&.positive {
color: var(--accent-success);
}
&.negative {
color: var(--accent-danger);
}
}
}
</style>

View File

@@ -0,0 +1,27 @@
<template>
<CategoryCard
title="收入分类"
:categories="categories"
:type="1"
tag-type="success"
empty-description="本期暂无收入记录"
@category-click="handleCategoryClick"
/>
</template>
<script setup>
import CategoryCard from '@/components/Statistics/CategoryCard.vue'
defineProps({
categories: {
type: Array,
default: () => []
}
})
const emit = defineEmits(['category-click'])
const handleCategoryClick = (classify, type) => {
emit('category-click', classify, type)
}
</script>

View File

@@ -0,0 +1,272 @@
<template>
<!-- 收支和不计收支并列显示 -->
<div class="side-by-side-cards">
<!-- 收入分类统计 -->
<div class="common-card half-card">
<div class="card-header">
<h3 class="card-title">
收入
<span
class="income-text"
style="font-size: 13px; margin-left: 4px"
>
¥{{ formatMoney(totalIncome) }}
</span>
</h3>
<van-tag
type="success"
size="medium"
>
{{ incomeCategories.length }}
</van-tag>
</div>
<div
v-if="incomeCategories.length > 0"
class="category-list"
>
<div
v-for="category in incomeCategories"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 1)"
>
<div class="category-info">
<div class="category-color income-color" />
<span class="category-name text-ellipsis">{{ category.classify || '未分类' }}</span>
</div>
<div class="category-amount income-text">
¥{{ formatMoney(category.amount) }}
</div>
</div>
</div>
<ModernEmpty
v-else
type="finance"
theme="green"
title="暂无收入"
description="本期还没有收入记录"
size="small"
/>
</div>
<!-- 不计收支分类统计 -->
<div class="common-card half-card">
<div class="card-header">
<h3 class="card-title">
不计收支
</h3>
<van-tag
type="warning"
size="medium"
>
{{ noneCategories.length }}
</van-tag>
</div>
<div
v-if="noneCategories.length > 0"
class="category-list"
>
<div
v-for="category in noneCategories"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 2)"
>
<div class="category-info">
<div class="category-color none-color" />
<span class="category-name text-ellipsis">{{ category.classify || '未分类' }}</span>
</div>
<div class="category-amount none-text">
¥{{ formatMoney(category.amount) }}
</div>
</div>
</div>
<ModernEmpty
v-else
type="inbox"
theme="gray"
title="暂无数据"
description="本期没有不计收支记录"
size="small"
/>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
import ModernEmpty from '@/components/ModernEmpty.vue'
const props = defineProps({
incomeCategories: {
type: Array,
default: () => []
},
noneCategories: {
type: Array,
default: () => []
},
totalIncome: {
type: Number,
default: 0
}
})
defineEmits(['category-click'])
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 处理未分类排序
const incomeCategories = computed(() => {
const list = [...props.incomeCategories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
const noneCategories = computed(() => {
const list = [...props.noneCategories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
/* 并列显示卡片 */
.side-by-side-cards {
display: flex;
gap: 12px;
margin: 0 12px 16px;
}
.side-by-side-cards .common-card {
margin: 0;
flex: 1;
min-width: 0; /* 允许内部元素缩小 */
padding: 12px;
}
.card-header {
margin-bottom: 0;
}
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 13px;
}
/* 分类列表 */
.category-list {
padding: 0;
}
.category-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--van-border-color);
transition: background-color 0.2s;
gap: 12px;
}
.category-item:last-child {
border-bottom: none;
}
.category-item.clickable {
cursor: pointer;
}
.category-item.clickable:active {
background-color: var(--van-background);
}
.category-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 0;
}
.category-color {
width: 12px;
height: 12px;
border-radius: 50%;
}
.category-name {
font-size: 14px;
color: var(--van-text-color);
}
.category-amount {
font-size: 15px;
font-weight: 600;
color: var(--van-text-color);
flex-shrink: 0;
}
.income-color {
background-color: var(--van-success-color);
}
.income-text {
color: var(--van-success-color);
}
/* 不计收支颜色 */
.none-color {
background-color: var(--van-gray-6);
}
.none-text {
color: var(--van-gray-6);
}
</style>

View File

@@ -0,0 +1,504 @@
<template>
<div class="monthly-expense-card common-card">
<!-- 收支结余一行展示 -->
<div class="stats-row">
<div class="stat-item expense">
<div class="stat-label">
支出
</div>
<div class="stat-amount">
¥{{ formatMoney(amount) }}
</div>
</div>
<div class="stat-item income">
<div class="stat-label">
收入
</div>
<div class="stat-amount">
¥{{ formatMoney(income) }}
</div>
</div>
<div class="stat-item balance">
<div class="stat-label">
结余
</div>
<div
class="stat-amount"
:class="balanceClass"
>
¥{{ formatMoney(balance) }}
</div>
</div>
</div>
<!-- 趋势图 -->
<div class="trend-section">
<div
ref="chartRef"
class="trend-chart"
/>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { formatMoney } from '@/utils/format'
import { useMessageStore } from '@/stores/message'
const props = defineProps({
amount: {
type: Number,
required: true
},
income: {
type: Number,
default: 0
},
balance: {
type: Number,
default: 0
},
trendData: {
type: Array,
default: () => []
},
period: {
type: String,
default: 'month'
},
currentDate: {
type: Date,
required: true
}
})
const messageStore = useMessageStore()
const chartRef = ref()
let chartInstance = null
// 计算结余样式类
const balanceClass = computed(() => ({
'positive': props.balance >= 0,
'negative': props.balance < 0
}))
// 计算图表标题
const chartTitle = computed(() => {
switch (props.period) {
case 'week':
return '每日趋势'
case 'month':
return '每日趋势'
case 'year':
return '每月趋势'
default:
return '趋势'
}
})
// 获取月份天数
const getDaysInMonth = (year, month) => {
return new Date(year, month, 0).getDate()
}
// 初始化图表
const initChart = async () => {
await nextTick()
if (!chartRef.value) {
console.warn('图表容器未找到')
return
}
// 销毁已存在的图表实例
if (chartInstance) {
chartInstance.dispose()
chartInstance = null
}
try {
chartInstance = echarts.init(chartRef.value)
updateChart()
} catch (error) {
console.error('初始化图表失败:', error)
}
}
// 更新图表
const updateChart = () => {
if (!chartInstance) {
console.warn('图表实例不存在')
return
}
// 验证数据
if (!Array.isArray(props.trendData)) {
console.warn('图表数据格式错误')
return
}
// 根据时间段类型和数据来生成图表
let chartData = []
let xAxisLabels = []
try {
if (props.period === 'week') {
// 周统计:直接使用传入的数据,按日期排序
chartData = [...props.trendData].sort((a, b) => new Date(a.date) - new Date(b.date))
xAxisLabels = chartData.map(item => {
const date = new Date(item.date)
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
return weekDays[date.getDay()]
})
} else if (props.period === 'month') {
// 月统计:生成完整的月份数据
const currentDate = props.currentDate
const year = currentDate.getFullYear()
const month = currentDate.getMonth() + 1
const daysInMonth = getDaysInMonth(year, month)
const allDays = Array.from({ length: daysInMonth }, (_, i) => {
const day = i + 1
const paddedDay = day.toString().padStart(2, '0')
return `${year}-${month.toString().padStart(2, '0')}-${paddedDay}`
})
// 创建完整的数据映射
const dataMap = new Map()
props.trendData.forEach(item => {
if (item && item.date) {
dataMap.set(item.date, item)
}
})
// 生成完整的数据序列
chartData = allDays.map(date => {
const dayData = dataMap.get(date)
return {
date,
expense: dayData?.expense || 0,
income: dayData?.income || 0,
count: dayData?.count || 0
}
})
xAxisLabels = chartData.map((_, index) => (index + 1).toString())
} else if (props.period === 'year') {
// 年统计:直接使用数据,显示月份标签
chartData = [...props.trendData]
.filter(item => item && item.date)
.sort((a, b) => new Date(a.date) - new Date(b.date))
xAxisLabels = chartData.map(item => {
const date = new Date(item.date)
return `${date.getMonth() + 1}`
})
}
// 如果没有有效数据,显示空图表
if (chartData.length === 0) {
const option = {
backgroundColor: 'transparent',
graphic: [{
type: 'text',
left: 'center',
top: 'middle',
style: {
text: '暂无数据',
fontSize: 16,
fill: messageStore.isDarkMode ? '#9CA3AF' : '#6B7280'
}
}]
}
chartInstance.setOption(option)
return
}
// 准备图表数据 - 计算累计值
let cumulativeExpense = 0
let cumulativeIncome = 0
const expenseData = []
const incomeData = []
chartData.forEach(item => {
// 支持两种数据格式1) expense/income字段 2) amount字段兼容旧数据
let expense = 0
let income = 0
if (item.expense !== undefined || item.income !== undefined) {
expense = item.expense || 0
income = item.income || 0
} else {
const amount = item.amount || 0
if (amount < 0) {
expense = Math.abs(amount)
} else {
income = amount
}
}
// 累加计算
cumulativeExpense += expense
cumulativeIncome += income
expenseData.push(cumulativeExpense)
incomeData.push(cumulativeIncome)
})
const isDark = messageStore.isDarkMode
const option = {
backgroundColor: 'transparent',
grid: {
top: 20,
left: 10,
right: 10,
bottom: 20,
containLabel: false
},
xAxis: {
type: 'category',
data: xAxisLabels,
show: false
},
yAxis: {
type: 'value',
show: false
},
series: [
// 支出线
{
name: '支出',
type: 'line',
data: expenseData,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#ff6b6b',
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
{ offset: 1, color: 'rgba(255, 107, 107, 0.05)' }
]
}
}
},
// 收入线
{
name: '收入',
type: 'line',
data: incomeData,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#4ade80',
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(74, 222, 128, 0.3)' },
{ offset: 1, color: 'rgba(74, 222, 128, 0.05)' }
]
}
}
}
],
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'rgba(39, 39, 42, 0.95)' : 'rgba(255, 255, 255, 0.95)',
borderColor: isDark ? 'rgba(63, 63, 70, 0.8)' : 'rgba(229, 231, 235, 0.8)',
textStyle: {
color: isDark ? '#f4f4f5' : '#1a1a1a'
},
formatter: (params) => {
if (!params || params.length === 0 || !chartData[params[0].dataIndex]) {
return ''
}
const dataIndex = params[0].dataIndex
const date = chartData[dataIndex].date
const item = chartData[dataIndex]
let content = ''
try {
if (props.period === 'week') {
const dateObj = new Date(date)
const month = dateObj.getMonth() + 1
const day = dateObj.getDate()
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
const weekDay = weekDays[dateObj.getDay()]
content = `${month}${day}日 (周${weekDay})<br/>`
} else if (props.period === 'month') {
const day = new Date(date).getDate()
content = `${props.currentDate.getMonth() + 1}${day}日<br/>`
} else if (props.period === 'year') {
const dateObj = new Date(date)
content = `${dateObj.getFullYear()}${dateObj.getMonth() + 1}月<br/>`
}
// 计算当日值
let dailyExpense = 0
let dailyIncome = 0
if (item.expense !== undefined || item.income !== undefined) {
dailyExpense = item.expense || 0
dailyIncome = item.income || 0
} else {
const amount = item.amount || 0
if (amount < 0) {
dailyExpense = Math.abs(amount)
} else {
dailyIncome = amount
}
}
// 显示累计值和当日值
params.forEach((param) => {
const color = param.seriesName === '支出' ? '#ff6b6b' : '#4ade80'
const cumulativeValue = param.value
const dailyValue = param.seriesName === '支出' ? dailyExpense : dailyIncome
content += `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color}"></span>`
content += `${param.seriesName}累计: ¥${cumulativeValue.toFixed(2)}`
if (dailyValue > 0) {
content += ` (当日: ¥${dailyValue.toFixed(2)})`
}
content += '<br/>'
})
} catch (error) {
console.warn('格式化tooltip失败:', error)
content = '数据格式错误'
}
return content
}
}
}
chartInstance.setOption(option)
} catch (error) {
console.error('更新图表失败:', error)
}
}
// 监听数据变化
watch(() => props.trendData, () => {
if (chartInstance) {
updateChart()
}
}, { deep: true })
// 监听主题变化
watch(() => messageStore.isDarkMode, () => {
if (chartInstance) {
updateChart()
}
})
onMounted(() => {
initChart()
})
onBeforeUnmount(() => {
if (chartInstance) {
chartInstance.dispose()
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.monthly-expense-card {
display: flex;
flex-direction: column;
gap: var(--spacing-lg);
}
// 收支结余一行展示
.stats-row {
display: flex;
justify-content: space-between;
gap: var(--spacing-md);
padding-bottom: var(--spacing-md);
border-bottom: 1px solid var(--border-color);
}
.stat-item {
flex: 1;
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
text-align: center;
.stat-label {
color: var(--text-secondary);
font-family: var(--font-primary);
font-size: var(--font-sm);
font-weight: var(--font-medium);
}
.stat-amount {
font-family: var(--font-display);
font-size: var(--font-xl);
font-weight: var(--font-bold);
}
&.expense .stat-amount {
color: var(--accent-danger);
}
&.income .stat-amount {
color: var(--accent-success);
}
&.balance .stat-amount {
color: var(--accent-primary);
&.positive {
color: var(--accent-success);
}
&.negative {
color: var(--accent-danger);
}
}
}
// 趋势图部分
.trend-section {
display: flex;
flex-direction: column;
gap: var(--spacing-md);
}
.trend-chart {
width: 100%;
height: 180px;
}
</style>

View File

@@ -7,10 +7,8 @@ namespace WebApi.Controllers;
[Route("api/[controller]/[action]")]
public class TransactionRecordController(
ITransactionRecordRepository transactionRepository,
ITransactionStatisticsService transactionStatisticsService,
ISmartHandleService smartHandleService,
ILogger<TransactionRecordController> logger,
IConfigService configService
ILogger<TransactionRecordController> logger
) : ControllerBase
{
/// <summary>
@@ -262,147 +260,6 @@ public class TransactionRecordController(
}
}
/// <summary>
/// 获取累积余额统计数据(用于余额卡片图表)
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<BalanceStatisticsDto>>> GetBalanceStatisticsAsync(
[FromQuery] int year,
[FromQuery] int month
)
{
try
{
// 获取存款分类
var savingClassify = await configService.GetConfigByKeyAsync<string>("SavingsCategories");
// 获取每日统计数据
var statistics = await transactionStatisticsService.GetDailyStatisticsAsync(year, month, savingClassify);
// 按日期排序并计算累积余额
var sortedStats = statistics.OrderBy(s => s.Key).ToList();
var result = new List<BalanceStatisticsDto>();
decimal cumulativeBalance = 0;
foreach (var item in sortedStats)
{
var dailyBalance = item.Value.income - item.Value.expense;
cumulativeBalance += dailyBalance;
result.Add(new BalanceStatisticsDto(
item.Key,
cumulativeBalance
));
}
return result.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取累积余额统计失败,年份: {Year}, 月份: {Month}", year, month);
return $"获取累积余额统计失败: {ex.Message}".Fail<List<BalanceStatisticsDto>>();
}
}
/// <summary>
/// 获取指定月份每天的消费统计
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<DailyStatisticsDto>>> GetDailyStatisticsAsync(
[FromQuery] int year,
[FromQuery] int month
)
{
try
{
// 获取存款分类
var savingClassify = await configService.GetConfigByKeyAsync<string>("SavingsCategories");
var statistics = await transactionStatisticsService.GetDailyStatisticsAsync(year, month, savingClassify);
var result = statistics.Select(s => new DailyStatisticsDto(
s.Key,
s.Value.count,
s.Value.expense,
s.Value.income,
s.Value.saving
)).ToList();
return result.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取日历统计数据失败,年份: {Year}, 月份: {Month}", year, month);
return $"获取日历统计数据失败: {ex.Message}".Fail<List<DailyStatisticsDto>>();
}
}
/// <summary>
/// 获取月度统计数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<MonthlyStatistics>> GetMonthlyStatisticsAsync(
[FromQuery] int year,
[FromQuery] int month
)
{
try
{
var statistics = await transactionStatisticsService.GetMonthlyStatisticsAsync(year, month);
return statistics.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取月度统计数据失败,年份: {Year}, 月份: {Month}", year, month);
return $"获取月度统计数据失败: {ex.Message}".Fail<MonthlyStatistics>();
}
}
/// <summary>
/// 获取分类统计数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<CategoryStatistics>>> GetCategoryStatisticsAsync(
[FromQuery] int year,
[FromQuery] int month,
[FromQuery] TransactionType type
)
{
try
{
var statistics = await transactionStatisticsService.GetCategoryStatisticsAsync(year, month, type);
return statistics.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取分类统计数据失败,年份: {Year}, 月份: {Month}, 类型: {Type}", year, month, type);
return $"获取分类统计数据失败: {ex.Message}".Fail<List<CategoryStatistics>>();
}
}
/// <summary>
/// 获取趋势统计数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<TrendStatistics>>> GetTrendStatisticsAsync(
[FromQuery] int startYear,
[FromQuery] int startMonth,
[FromQuery] int monthCount = 6
)
{
try
{
var statistics = await transactionStatisticsService.GetTrendStatisticsAsync(startYear, startMonth, monthCount);
return statistics.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取趋势统计数据失败,开始年份: {Year}, 开始月份: {Month}, 月份数: {Count}", startYear, startMonth,
monthCount);
return $"获取趋势统计数据失败: {ex.Message}".Fail<List<TrendStatistics>>();
}
}
/// <summary>
/// 智能分析账单(流式输出)
@@ -627,30 +484,6 @@ public class TransactionRecordController(
}
}
/// <summary>
/// 获取按交易摘要分组的统计信息(支持分页)
/// </summary>
[HttpGet]
public async Task<PagedResponse<ReasonGroupDto>> GetReasonGroupsAsync(
[FromQuery] int pageIndex = 1,
[FromQuery] int pageSize = 20)
{
try
{
var (list, total) = await transactionStatisticsService.GetReasonGroupsAsync(pageIndex, pageSize);
return new PagedResponse<ReasonGroupDto>
{
Success = true,
Data = list.ToArray(),
Total = total
};
}
catch (Exception ex)
{
logger.LogError(ex, "获取交易摘要分组失败");
return PagedResponse<ReasonGroupDto>.Fail($"获取交易摘要分组失败: {ex.Message}");
}
}
/// <summary>
/// 按摘要批量更新分类
@@ -738,24 +571,7 @@ public record UpdateTransactionDto(
string? OccurredAt = null
);
/// <summary>
/// 日历统计响应DTO
/// </summary>
public record DailyStatisticsDto(
string Date,
int Count,
decimal Expense,
decimal Income,
decimal Balance
);
/// <summary>
/// 累积余额统计DTO
/// </summary>
public record BalanceStatisticsDto(
string Date,
decimal CumulativeBalance
);
/// <summary>
/// 智能分类请求DTO

View File

@@ -0,0 +1,315 @@
using Service.Transaction;
namespace WebApi.Controllers;
/// <summary>
/// 交易统计控制器
/// </summary>
[ApiController]
[Route("api/[controller]/[action]")]
public class TransactionStatisticsController(
ITransactionRecordRepository transactionRepository,
ITransactionStatisticsService transactionStatisticsService,
ILogger<TransactionStatisticsController> logger,
IConfigService configService
) : ControllerBase
{
/// <summary>
/// 获取累积余额统计数据(用于余额卡片图表)
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<BalanceStatisticsDto>>> GetBalanceStatisticsAsync(
[FromQuery] int year,
[FromQuery] int month
)
{
try
{
// 获取存款分类
var savingClassify = await configService.GetConfigByKeyAsync<string>("SavingsCategories");
// 获取每日统计数据
var statistics = await transactionStatisticsService.GetDailyStatisticsAsync(year, month, savingClassify);
// 按日期排序并计算累积余额
var sortedStats = statistics.OrderBy(s => s.Key).ToList();
var result = new List<BalanceStatisticsDto>();
decimal cumulativeBalance = 0;
foreach (var item in sortedStats)
{
var dailyBalance = item.Value.income - item.Value.expense;
cumulativeBalance += dailyBalance;
result.Add(new BalanceStatisticsDto(
item.Key,
cumulativeBalance
));
}
return result.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取累积余额统计失败,年份: {Year}, 月份: {Month}", year, month);
return $"获取累积余额统计失败: {ex.Message}".Fail<List<BalanceStatisticsDto>>();
}
}
/// <summary>
/// 获取指定月份每天的消费统计
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<DailyStatisticsDto>>> GetDailyStatisticsAsync(
[FromQuery] int year,
[FromQuery] int month
)
{
try
{
// 获取存款分类
var savingClassify = await configService.GetConfigByKeyAsync<string>("SavingsCategories");
var statistics = await transactionStatisticsService.GetDailyStatisticsAsync(year, month, savingClassify);
var result = statistics.Select(s => new DailyStatisticsDto(
s.Key,
s.Value.count,
s.Value.expense,
s.Value.income,
s.Value.saving
)).ToList();
return result.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取日历统计数据失败,年份: {Year}, 月份: {Month}", year, month);
return $"获取日历统计数据失败: {ex.Message}".Fail<List<DailyStatisticsDto>>();
}
}
/// <summary>
/// 获取周统计数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<DailyStatisticsDto>>> GetWeeklyStatisticsAsync(
[FromQuery] DateTime startDate,
[FromQuery] DateTime endDate
)
{
try
{
// 获取存款分类
var savingClassify = await configService.GetConfigByKeyAsync<string>("SavingsCategories");
var statistics = await transactionStatisticsService.GetDailyStatisticsByRangeAsync(startDate, endDate, savingClassify);
var result = statistics.Select(s => new DailyStatisticsDto(
s.Key,
s.Value.count,
s.Value.expense,
s.Value.income,
s.Value.saving
)).ToList();
return result.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取周统计数据失败,开始日期: {StartDate}, 结束日期: {EndDate}", startDate, endDate);
return $"获取周统计数据失败: {ex.Message}".Fail<List<DailyStatisticsDto>>();
}
}
/// <summary>
/// 获取指定日期范围的统计汇总数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<MonthlyStatistics>> GetRangeStatisticsAsync(
[FromQuery] DateTime startDate,
[FromQuery] DateTime endDate
)
{
try
{
// 通过日期范围查询数据
var records = await transactionRepository.QueryAsync(
startDate: startDate,
endDate: endDate,
pageSize: int.MaxValue);
var statistics = new MonthlyStatistics
{
Year = startDate.Year,
Month = startDate.Month
};
foreach (var record in records)
{
var amount = Math.Abs(record.Amount);
if (record.Type == TransactionType.Expense)
{
statistics.TotalExpense += amount;
statistics.ExpenseCount++;
}
else if (record.Type == TransactionType.Income)
{
statistics.TotalIncome += amount;
statistics.IncomeCount++;
}
}
statistics.Balance = statistics.TotalIncome - statistics.TotalExpense;
statistics.TotalCount = records.Count;
return statistics.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取时间范围统计数据失败,开始日期: {StartDate}, 结束日期: {EndDate}", startDate, endDate);
return $"获取时间范围统计数据失败: {ex.Message}".Fail<MonthlyStatistics>();
}
}
/// <summary>
/// 获取月度统计数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<MonthlyStatistics>> GetMonthlyStatisticsAsync(
[FromQuery] int year,
[FromQuery] int month
)
{
try
{
var statistics = await transactionStatisticsService.GetMonthlyStatisticsAsync(year, month);
return statistics.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取月度统计数据失败,年份: {Year}, 月份: {Month}", year, month);
return $"获取月度统计数据失败: {ex.Message}".Fail<MonthlyStatistics>();
}
}
/// <summary>
/// 获取分类统计数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<CategoryStatistics>>> GetCategoryStatisticsAsync(
[FromQuery] int year,
[FromQuery] int month,
[FromQuery] TransactionType type
)
{
try
{
var statistics = await transactionStatisticsService.GetCategoryStatisticsAsync(year, month, type);
return statistics.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取分类统计数据失败,年份: {Year}, 月份: {Month}, 类型: {Type}", year, month, type);
return $"获取分类统计数据失败: {ex.Message}".Fail<List<CategoryStatistics>>();
}
}
/// <summary>
/// 按日期范围获取分类统计数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<CategoryStatistics>>> GetCategoryStatisticsByDateRangeAsync(
[FromQuery] string startDate,
[FromQuery] string endDate,
[FromQuery] TransactionType type
)
{
try
{
if (!DateTime.TryParse(startDate, out var start))
{
return "开始日期格式错误".Fail<List<CategoryStatistics>>();
}
if (!DateTime.TryParse(endDate, out var end))
{
return "结束日期格式错误".Fail<List<CategoryStatistics>>();
}
var statistics = await transactionStatisticsService.GetCategoryStatisticsByDateRangeAsync(start, end, type);
return statistics.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取分类统计数据失败,开始日期: {StartDate}, 结束日期: {EndDate}, 类型: {Type}", startDate, endDate, type);
return $"获取分类统计数据失败: {ex.Message}".Fail<List<CategoryStatistics>>();
}
}
/// <summary>
/// 获取趋势统计数据
/// </summary>
[HttpGet]
public async Task<BaseResponse<List<TrendStatistics>>> GetTrendStatisticsAsync(
[FromQuery] int startYear,
[FromQuery] int startMonth,
[FromQuery] int monthCount = 6
)
{
try
{
var statistics = await transactionStatisticsService.GetTrendStatisticsAsync(startYear, startMonth, monthCount);
return statistics.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "获取趋势统计数据失败,开始年份: {Year}, 开始月份: {Month}, 月份数: {Count}", startYear, startMonth,
monthCount);
return $"获取趋势统计数据失败: {ex.Message}".Fail<List<TrendStatistics>>();
}
}
/// <summary>
/// 获取按交易摘要分组的统计信息(支持分页)
/// </summary>
[HttpGet]
public async Task<PagedResponse<ReasonGroupDto>> GetReasonGroupsAsync(
[FromQuery] int pageIndex = 1,
[FromQuery] int pageSize = 20)
{
try
{
var (list, total) = await transactionStatisticsService.GetReasonGroupsAsync(pageIndex, pageSize);
return new PagedResponse<ReasonGroupDto>
{
Success = true,
Data = list.ToArray(),
Total = total
};
}
catch (Exception ex)
{
logger.LogError(ex, "获取交易摘要分组失败");
return PagedResponse<ReasonGroupDto>.Fail($"获取交易摘要分组失败: {ex.Message}");
}
}
}
/// <summary>
/// 日历统计响应DTO
/// </summary>
public record DailyStatisticsDto(
string Date,
int Count,
decimal Expense,
decimal Income,
decimal Balance
);
/// <summary>
/// 累积余额统计DTO
/// </summary>
public record BalanceStatisticsDto(
string Date,
decimal CumulativeBalance
);