refactor: API 请求整合与 Bug 修复
前端重构: - 新增 api/ 目录统一管理所有 API 请求 - 所有 stores 和 pages 改为使用 api 模块 - 修复日期格式化函数,支持 Date 对象和 ISO 字符串 - 修复 TransactionItem 使用 CategoryIcon 组件 - 优化 ChartWrapper 区分 H5 和小程序环境 后端修复: - 修复 auth 中间件 PUBLIC_PATHS 缺少 demo-login - 修复备份工具命令注入漏洞,改用 execFile - 修复 stats 路由 type 参数验证 - 优化分类排序为批量 SQL 更新 - 合并迁移和删除为数据库事务原子操作 - 修复交易和统计日期返回格式 - 新增自动备份功能(启动时备份)
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { onLaunch } from '@dcloudio/uni-app'
|
||||
import { request } from '@/utils/request'
|
||||
import { wxLogin, demoLogin } from '@/api/auth'
|
||||
|
||||
onLaunch(() => {
|
||||
// #ifdef MP-WEIXIN
|
||||
@@ -9,11 +9,7 @@ onLaunch(() => {
|
||||
success: async (loginRes) => {
|
||||
if (loginRes.code) {
|
||||
try {
|
||||
const data = await request<{ token: string; userId: number }>({
|
||||
url: '/auth/login',
|
||||
method: 'POST',
|
||||
data: { code: loginRes.code }
|
||||
})
|
||||
const data = await wxLogin(loginRes.code)
|
||||
uni.setStorageSync('xc:token', data.token)
|
||||
uni.setStorageSync('xc:userId', data.userId)
|
||||
console.log('[Auth] Login success')
|
||||
@@ -29,10 +25,7 @@ onLaunch(() => {
|
||||
const token = uni.getStorageSync('xc:token')
|
||||
if (!token) {
|
||||
// 同步等待 token,避免页面首次请求因无 token 而 401
|
||||
request<{ token: string; userId: number }>({
|
||||
url: '/auth/demo-login',
|
||||
method: 'POST'
|
||||
}).then((data) => {
|
||||
demoLogin().then((data) => {
|
||||
uni.setStorageSync('xc:token', data.token)
|
||||
uni.setStorageSync('xc:userId', data.userId)
|
||||
console.log('[Auth] H5 demo login success')
|
||||
|
||||
17
client/src/api/auth.ts
Normal file
17
client/src/api/auth.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { request } from '@/utils/request'
|
||||
|
||||
/** 登录响应 */
|
||||
export interface LoginResult {
|
||||
token: string
|
||||
userId: number
|
||||
}
|
||||
|
||||
/** H5 演示登录 */
|
||||
export function demoLogin() {
|
||||
return request<LoginResult>({ url: '/auth/demo-login', method: 'POST' })
|
||||
}
|
||||
|
||||
/** 微信登录 */
|
||||
export function wxLogin(code: string) {
|
||||
return request<LoginResult>({ url: '/auth/login', method: 'POST', data: { code } })
|
||||
}
|
||||
18
client/src/api/budget.ts
Normal file
18
client/src/api/budget.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { request } from '@/utils/request'
|
||||
|
||||
/** 预算 */
|
||||
export interface Budget {
|
||||
id: number
|
||||
amount: number
|
||||
month: string
|
||||
}
|
||||
|
||||
/** 获取预算 */
|
||||
export function getBudget(month?: string) {
|
||||
return request<Budget | null>({ url: '/budget', data: month ? { month } : {} })
|
||||
}
|
||||
|
||||
/** 设置预算 */
|
||||
export function setBudget(amount: number, month: string) {
|
||||
return request<{ id: number }>({ url: '/budget', method: 'POST', data: { amount, month } })
|
||||
}
|
||||
52
client/src/api/category.ts
Normal file
52
client/src/api/category.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { request } from '@/utils/request'
|
||||
|
||||
/** 分类 */
|
||||
export interface Category {
|
||||
id: number
|
||||
name: string
|
||||
icon: string
|
||||
color: string
|
||||
type: 'expense' | 'income'
|
||||
sort_order: number
|
||||
is_custom: number
|
||||
}
|
||||
|
||||
/** 获取分类列表 */
|
||||
export function getCategories() {
|
||||
return request<Category[]>({ url: '/categories' })
|
||||
}
|
||||
|
||||
/** 创建分类 */
|
||||
export function createCategory(data: {
|
||||
name: string
|
||||
icon: string
|
||||
color: string
|
||||
type: 'expense' | 'income'
|
||||
}) {
|
||||
return request<{ id: number }>({ url: '/categories', method: 'POST', data })
|
||||
}
|
||||
|
||||
/** 更新分类 */
|
||||
export function updateCategory(id: number, data: { name: string; color: string }) {
|
||||
return request({ url: `/categories/${id}`, method: 'PUT', data })
|
||||
}
|
||||
|
||||
/** 删除分类 */
|
||||
export function deleteCategory(id: number) {
|
||||
return request({ url: `/categories/${id}`, method: 'DELETE' })
|
||||
}
|
||||
|
||||
/** 获取分类关联的交易数量 */
|
||||
export function getCategoryTransactionCount(id: number) {
|
||||
return request<{ count: number }>({ url: `/categories/${id}/transaction-count` })
|
||||
}
|
||||
|
||||
/** 迁移分类关联的交易并删除分类 */
|
||||
export function migrateCategory(fromId: number, targetId: number) {
|
||||
return request({ url: `/categories/${fromId}/migrate`, method: 'POST', data: { targetId } })
|
||||
}
|
||||
|
||||
/** 更新分类排序 */
|
||||
export function sortCategories(ids: number[]) {
|
||||
return request({ url: '/categories/sort', method: 'PUT', data: { ids } })
|
||||
}
|
||||
5
client/src/api/index.ts
Normal file
5
client/src/api/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export * from './auth'
|
||||
export * from './transaction'
|
||||
export * from './category'
|
||||
export * from './budget'
|
||||
export * from './stats'
|
||||
40
client/src/api/stats.ts
Normal file
40
client/src/api/stats.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { request } from '@/utils/request'
|
||||
|
||||
/** 概览数据 */
|
||||
export interface Overview {
|
||||
expense: number
|
||||
income: number
|
||||
count: number
|
||||
daily: number
|
||||
}
|
||||
|
||||
/** 分类统计 */
|
||||
export interface CategoryStat {
|
||||
id: number
|
||||
name: string
|
||||
icon: string
|
||||
color: string
|
||||
amount: number
|
||||
count: number
|
||||
}
|
||||
|
||||
/** 趋势数据点 */
|
||||
export interface TrendPoint {
|
||||
date: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
/** 获取概览数据 */
|
||||
export function getOverview(params?: { month?: string; startDate?: string; endDate?: string }) {
|
||||
return request<Overview>({ url: '/stats/overview', data: params })
|
||||
}
|
||||
|
||||
/** 获取分类统计 */
|
||||
export function getCategoryStats(month?: string, type: string = 'expense') {
|
||||
return request<CategoryStat[]>({ url: '/stats/category', data: { month, type } })
|
||||
}
|
||||
|
||||
/** 获取趋势数据 */
|
||||
export function getTrend(month?: string, type: string = 'expense') {
|
||||
return request<TrendPoint[]>({ url: '/stats/trend', data: { month, type } })
|
||||
}
|
||||
69
client/src/api/transaction.ts
Normal file
69
client/src/api/transaction.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { request } from '@/utils/request'
|
||||
|
||||
/** 交易记录 */
|
||||
export interface Transaction {
|
||||
id: number
|
||||
amount: number
|
||||
type: 'expense' | 'income'
|
||||
category_id: number
|
||||
note?: string
|
||||
date: string
|
||||
category_name?: string
|
||||
category_icon?: string
|
||||
category_color?: string
|
||||
}
|
||||
|
||||
/** 交易列表响应 */
|
||||
export interface TransactionList {
|
||||
list: Transaction[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** 获取交易列表参数 */
|
||||
export interface TransactionParams {
|
||||
page: number
|
||||
pageSize?: number
|
||||
type?: string
|
||||
startDate?: string
|
||||
endDate?: string
|
||||
sortBy?: string
|
||||
}
|
||||
|
||||
/** 获取交易列表 */
|
||||
export function getTransactions(params: TransactionParams) {
|
||||
return request<TransactionList>({ url: '/transactions', data: params })
|
||||
}
|
||||
|
||||
/** 获取单条交易记录 */
|
||||
export function getTransaction(id: number) {
|
||||
return request<Transaction>({ url: `/transactions/${id}` })
|
||||
}
|
||||
|
||||
/** 创建交易记录 */
|
||||
export function createTransaction(data: {
|
||||
amount: number
|
||||
type: 'expense' | 'income'
|
||||
category_id?: number
|
||||
note?: string
|
||||
date: string
|
||||
}) {
|
||||
return request<{ id: number }>({ url: '/transactions', method: 'POST', data })
|
||||
}
|
||||
|
||||
/** 更新交易记录 */
|
||||
export function updateTransaction(id: number, data: {
|
||||
amount: number
|
||||
type: 'expense' | 'income'
|
||||
category_id?: number
|
||||
note?: string
|
||||
date: string
|
||||
}) {
|
||||
return request({ url: `/transactions/${id}`, method: 'PUT', data })
|
||||
}
|
||||
|
||||
/** 删除交易记录 */
|
||||
export function deleteTransaction(id: number) {
|
||||
return request({ url: `/transactions/${id}`, method: 'DELETE' })
|
||||
}
|
||||
@@ -11,17 +11,17 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch, nextTick, getCurrentInstance } from 'vue'
|
||||
import { onMounted, watch, nextTick, getCurrentInstance } from 'vue'
|
||||
// @ts-ignore
|
||||
import uCharts from '@qiun/ucharts/u-charts.min.js'
|
||||
|
||||
const props = defineProps<{
|
||||
const props = withDefaults(defineProps<{
|
||||
canvasId: string
|
||||
type: 'pie' | 'line' | 'column'
|
||||
chartData: any
|
||||
width?: number
|
||||
height?: number
|
||||
}>()
|
||||
}>(), { width: 600, height: 400 })
|
||||
|
||||
const emit = defineEmits(['tap'])
|
||||
|
||||
@@ -30,34 +30,80 @@ let chartInstance: any = null
|
||||
function drawChart() {
|
||||
if (!props.chartData) return
|
||||
|
||||
const query = uni.createSelectorQuery().in(getCurrentInstance()?.proxy)
|
||||
query.select(`#${props.canvasId}`)
|
||||
.fields({ node: true, size: true })
|
||||
.exec((res) => {
|
||||
if (!res[0]) return
|
||||
// #ifdef H5
|
||||
drawChartH5()
|
||||
// #endif
|
||||
|
||||
const canvas = res[0].node
|
||||
const ctx = canvas.getContext('2d')
|
||||
// #ifdef MP-WEIXIN
|
||||
drawChartMP()
|
||||
// #endif
|
||||
}
|
||||
|
||||
const dpr = uni.getSystemInfoSync().pixelRatio
|
||||
canvas.width = res[0].width * dpr
|
||||
canvas.height = res[0].height * dpr
|
||||
ctx.scale(dpr, dpr)
|
||||
function drawChartH5() {
|
||||
try {
|
||||
const canvas = document.querySelector(`#${props.canvasId}`) as HTMLCanvasElement
|
||||
if (!canvas) return
|
||||
|
||||
const config: any = {
|
||||
context: ctx,
|
||||
canvas2d: true,
|
||||
pixelRatio: dpr,
|
||||
width: res[0].width,
|
||||
height: res[0].height,
|
||||
animation: true,
|
||||
background: '#FFFFFF',
|
||||
padding: [15, 15, 15, 15],
|
||||
...props.chartData
|
||||
}
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
chartInstance = new uCharts(config)
|
||||
})
|
||||
const dpr = window.devicePixelRatio || 1
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
canvas.width = rect.width * dpr
|
||||
canvas.height = rect.height * dpr
|
||||
ctx.scale(dpr, dpr)
|
||||
|
||||
const config: any = {
|
||||
context: ctx,
|
||||
canvas2d: true,
|
||||
pixelRatio: dpr,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
animation: true,
|
||||
background: '#FFFFFF',
|
||||
padding: [15, 15, 15, 15],
|
||||
...props.chartData
|
||||
}
|
||||
|
||||
chartInstance = new uCharts(config)
|
||||
} catch (e) {
|
||||
console.error('[Chart] H5 draw error:', e)
|
||||
}
|
||||
}
|
||||
|
||||
function drawChartMP() {
|
||||
try {
|
||||
const query = uni.createSelectorQuery().in(getCurrentInstance()?.proxy)
|
||||
query.select(`#${props.canvasId}`)
|
||||
.fields({ node: true, size: true })
|
||||
.exec((res) => {
|
||||
if (!res || !res[0]) return
|
||||
|
||||
const canvas = res[0].node
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
const dpr = uni.getSystemInfoSync().pixelRatio
|
||||
canvas.width = res[0].width * dpr
|
||||
canvas.height = res[0].height * dpr
|
||||
ctx.scale(dpr, dpr)
|
||||
|
||||
const config: any = {
|
||||
context: ctx,
|
||||
canvas2d: true,
|
||||
pixelRatio: dpr,
|
||||
width: res[0].width,
|
||||
height: res[0].height,
|
||||
animation: true,
|
||||
background: '#FFFFFF',
|
||||
padding: [15, 15, 15, 15],
|
||||
...props.chartData
|
||||
}
|
||||
|
||||
chartInstance = new uCharts(config)
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('[Chart] MP draw error:', e)
|
||||
}
|
||||
}
|
||||
|
||||
function onTap(e: any) {
|
||||
@@ -67,13 +113,13 @@ function onTap(e: any) {
|
||||
|
||||
onMounted(() => {
|
||||
nextTick(() => {
|
||||
setTimeout(drawChart, 100)
|
||||
setTimeout(drawChart, 300)
|
||||
})
|
||||
})
|
||||
|
||||
watch(() => props.chartData, () => {
|
||||
nextTick(() => {
|
||||
setTimeout(drawChart, 100)
|
||||
setTimeout(drawChart, 300)
|
||||
})
|
||||
}, { deep: true })
|
||||
</script>
|
||||
@@ -87,5 +133,6 @@ watch(() => props.chartData, () => {
|
||||
|
||||
.chart-canvas {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -8,9 +8,12 @@
|
||||
@touchmove="!disableSwipe && onTouchMove($event)"
|
||||
@touchend="!disableSwipe && onTouchEnd()"
|
||||
>
|
||||
<view class="icon-wrap" :style="{ background: item.category_color + '20' }">
|
||||
<text class="icon-text" :style="{ color: item.category_color }">{{ item.category_name?.[0] || '?' }}</text>
|
||||
</view>
|
||||
<CategoryIcon
|
||||
:label="item.category_name?.[0] || '?'"
|
||||
:color="item.category_color || '#BFB3B3'"
|
||||
:bg-color="(item.category_color || '#BFB3B3') + '20'"
|
||||
size="sm"
|
||||
/>
|
||||
<view class="info">
|
||||
<text class="name">{{ item.note || item.category_name || '未分类' }}</text>
|
||||
<text class="meta">{{ item.category_name || '未分类' }}{{ hideDate ? '' : ' · ' + formatDate(item.date) }}</text>
|
||||
@@ -27,6 +30,7 @@
|
||||
import { ref } from 'vue'
|
||||
import { formatAmount, formatDate } from '@/utils/format'
|
||||
import Icon from '@/components/Icon/Icon.vue'
|
||||
import CategoryIcon from '@/components/CategoryIcon/CategoryIcon.vue'
|
||||
|
||||
withDefaults(defineProps<{
|
||||
item: {
|
||||
@@ -84,7 +88,7 @@ function onTouchEnd() {
|
||||
.tx-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 28rpx 0;
|
||||
padding: 28rpx 24rpx;
|
||||
gap: 24rpx;
|
||||
border-radius: 20rpx;
|
||||
transition: transform 0.2s ease;
|
||||
@@ -117,21 +121,6 @@ function onTouchEnd() {
|
||||
}
|
||||
}
|
||||
|
||||
.icon-wrap {
|
||||
width: 80rpx;
|
||||
height: 80rpx;
|
||||
border-radius: 24rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.icon-text {
|
||||
font-size: 36rpx;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -20,51 +20,129 @@
|
||||
|
||||
<view class="cat-list">
|
||||
<view v-for="cat in currentCategories" :key="cat.id" class="cat-row">
|
||||
<view class="cat-info">
|
||||
<view class="cat-info" @tap="cat.is_custom && onEdit(cat)">
|
||||
<CategoryIcon :label="cat.name[0]" :color="cat.color" :bg-color="cat.color + '15'" size="sm" />
|
||||
<text class="cat-name">{{ cat.name }}</text>
|
||||
<text class="cat-badge" v-if="cat.is_custom">自定义</text>
|
||||
</view>
|
||||
<view class="cat-actions" v-if="cat.is_custom" @tap="onDelete(cat)">
|
||||
<Icon name="trash" :size="28" color="#FF6B6B" />
|
||||
<view class="cat-actions" v-if="cat.is_custom">
|
||||
<view class="action-btn" @tap="onEdit(cat)">
|
||||
<Icon name="edit" :size="24" color="#8B7E7E" />
|
||||
</view>
|
||||
<view class="action-btn" @tap="onDelete(cat)">
|
||||
<Icon name="trash" :size="24" color="#FF6B6B" />
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="add-section">
|
||||
<text class="add-title">添加自定义分类</text>
|
||||
<view class="add-form">
|
||||
<input class="add-input" v-model="newName" placeholder="分类名称" maxlength="10" />
|
||||
<!-- 浮动添加按钮 -->
|
||||
<view class="fab" @tap="showAddModal = true">
|
||||
<text class="fab-icon">+</text>
|
||||
</view>
|
||||
|
||||
<!-- 添加弹窗 -->
|
||||
<view class="modal-mask" v-if="showAddModal" @tap="showAddModal = false">
|
||||
<view class="modal" @tap.stop>
|
||||
<text class="modal-title">添加自定义分类</text>
|
||||
<input class="modal-input" v-model="newName" placeholder="分类名称" maxlength="10" />
|
||||
<view class="color-picker">
|
||||
<view
|
||||
v-for="c in colorOptions" :key="c"
|
||||
class="color-dot"
|
||||
:class="{ selected: selectedColor === c }"
|
||||
:style="{ background: c }"
|
||||
@tap="selectedColor = c"
|
||||
/>
|
||||
</view>
|
||||
<view class="modal-btns">
|
||||
<view class="modal-btn cancel" @tap="showAddModal = false">取消</view>
|
||||
<view class="modal-btn confirm" :class="{ disabled: !newName.trim() }" @tap="onAdd">添加</view>
|
||||
</view>
|
||||
</view>
|
||||
<view class="color-picker">
|
||||
<view
|
||||
v-for="c in colorOptions" :key="c"
|
||||
class="color-dot"
|
||||
:class="{ selected: selectedColor === c }"
|
||||
:style="{ background: c }"
|
||||
@tap="selectedColor = c"
|
||||
/>
|
||||
</view>
|
||||
|
||||
<!-- 编辑弹窗 -->
|
||||
<view class="modal-mask" v-if="showEditModal" @tap="showEditModal = false">
|
||||
<view class="modal" @tap.stop>
|
||||
<text class="modal-title">编辑分类</text>
|
||||
<input class="modal-input" v-model="editName" placeholder="分类名称" maxlength="10" />
|
||||
<view class="color-picker">
|
||||
<view
|
||||
v-for="c in colorOptions" :key="c"
|
||||
class="color-dot"
|
||||
:class="{ selected: editColor === c }"
|
||||
:style="{ background: c }"
|
||||
@tap="editColor = c"
|
||||
/>
|
||||
</view>
|
||||
<view class="modal-btns">
|
||||
<view class="modal-btn cancel" @tap="showEditModal = false">取消</view>
|
||||
<view class="modal-btn confirm" @tap="onEditConfirm">确定</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 迁移弹窗 -->
|
||||
<view class="modal-mask" v-if="showMigrateModal" @tap="showMigrateModal = false">
|
||||
<view class="modal" @tap.stop>
|
||||
<text class="modal-title">迁移记录</text>
|
||||
<text class="modal-desc">「{{ deletingCat?.name }}」下有 {{ migrateCount }} 条记录,请选择迁移到:</text>
|
||||
<scroll-view class="migrate-list" scroll-y>
|
||||
<view
|
||||
v-for="cat in migrateTargets"
|
||||
:key="cat.id"
|
||||
class="migrate-item"
|
||||
:class="{ selected: migrateTargetId === cat.id }"
|
||||
@tap="migrateTargetId = cat.id"
|
||||
>
|
||||
<CategoryIcon :label="cat.name[0]" :color="cat.color" :bg-color="cat.color + '15'" size="sm" />
|
||||
<text class="migrate-name">{{ cat.name }}</text>
|
||||
</view>
|
||||
</scroll-view>
|
||||
<view class="modal-btns">
|
||||
<view class="modal-btn cancel" @tap="showMigrateModal = false">取消</view>
|
||||
<view class="modal-btn confirm" :class="{ disabled: !migrateTargetId }" @tap="onMigrateConfirm">确认迁移并删除</view>
|
||||
</view>
|
||||
</view>
|
||||
<view class="add-btn" :class="{ disabled: !newName.trim() }" @tap="onAdd">添加</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useCategoryStore } from '@/stores/category'
|
||||
import { useCategoryStore, type Category } from '@/stores/category'
|
||||
import { getCategoryTransactionCount } from '@/api/category'
|
||||
import CategoryIcon from '@/components/CategoryIcon/CategoryIcon.vue'
|
||||
import Icon from '@/components/Icon/Icon.vue'
|
||||
import { statusBarHeight } from '@/utils/system'
|
||||
|
||||
const catStore = useCategoryStore()
|
||||
const tabType = ref<'expense' | 'income'>('expense')
|
||||
const showAddModal = ref(false)
|
||||
const newName = ref('')
|
||||
const colorOptions = ['#FF8C69', '#7BC67E', '#5B9BD5', '#FFD700', '#FF69B4', '#8B5CF6', '#F97316', '#06B6D4']
|
||||
const selectedColor = ref(colorOptions[0])
|
||||
|
||||
// 编辑相关
|
||||
const showEditModal = ref(false)
|
||||
const editingCat = ref<Category | null>(null)
|
||||
const editName = ref('')
|
||||
const editColor = ref('')
|
||||
|
||||
// 迁移相关
|
||||
const showMigrateModal = ref(false)
|
||||
const deletingCat = ref<Category | null>(null)
|
||||
const migrateCount = ref(0)
|
||||
const migrateTargetId = ref<number | null>(null)
|
||||
|
||||
const currentCategories = computed(() => catStore.getByType(tabType.value))
|
||||
|
||||
// 迁移目标列表(同类型且非当前删除的分类)
|
||||
const migrateTargets = computed(() => {
|
||||
return currentCategories.value.filter(c => c.id !== deletingCat.value?.id)
|
||||
})
|
||||
|
||||
onMounted(() => catStore.fetchCategories())
|
||||
|
||||
function goBack() {
|
||||
@@ -83,36 +161,66 @@ async function onAdd() {
|
||||
type: tabType.value
|
||||
})
|
||||
newName.value = ''
|
||||
showAddModal.value = false
|
||||
uni.showToast({ title: '添加成功', icon: 'success' })
|
||||
} catch {
|
||||
uni.showToast({ title: '添加失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
async function onDelete(cat: any) {
|
||||
function onEdit(cat: Category) {
|
||||
editingCat.value = cat
|
||||
editName.value = cat.name
|
||||
editColor.value = cat.color
|
||||
showEditModal.value = true
|
||||
}
|
||||
|
||||
async function onEditConfirm() {
|
||||
if (!editingCat.value) return
|
||||
const name = editName.value.trim()
|
||||
if (!name) {
|
||||
uni.showToast({ title: '请输入名称', icon: 'none' })
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// 查询关联记录数
|
||||
const { request: req } = await import('@/utils/request')
|
||||
const { count } = await req<{ count: number }>({ url: `/categories/${cat.id}/transaction-count` })
|
||||
const tip = count > 0
|
||||
? `该分类下有 ${count} 条记录,删除后会变为"未分类"。`
|
||||
: '删除后不可恢复。'
|
||||
uni.showModal({
|
||||
title: '删除分类',
|
||||
content: `确定删除「${cat.name}」?${tip}`,
|
||||
success: async (res) => {
|
||||
if (res.confirm) {
|
||||
try {
|
||||
await catStore.deleteCategory(cat.id)
|
||||
uni.showToast({ title: '已删除', icon: 'success' })
|
||||
} catch {
|
||||
uni.showToast({ title: '删除失败', icon: 'none' })
|
||||
await catStore.updateCategory(editingCat.value.id, { name, color: editColor.value })
|
||||
showEditModal.value = false
|
||||
uni.showToast({ title: '修改成功', icon: 'success' })
|
||||
} catch {
|
||||
uni.showToast({ title: '修改失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
async function onDelete(cat: Category) {
|
||||
try {
|
||||
const { count } = await getCategoryTransactionCount(cat.id)
|
||||
|
||||
if (count > 0) {
|
||||
// 有关联记录,需要迁移
|
||||
deletingCat.value = cat
|
||||
migrateCount.value = count
|
||||
migrateTargetId.value = null
|
||||
showMigrateModal.value = true
|
||||
} else {
|
||||
// 无关联记录,直接删除
|
||||
uni.showModal({
|
||||
title: '删除分类',
|
||||
content: `确定删除「${cat.name}」?删除后不可恢复。`,
|
||||
success: async (res) => {
|
||||
if (res.confirm) {
|
||||
try {
|
||||
await catStore.deleteCategory(cat.id)
|
||||
uni.showToast({ title: '已删除', icon: 'success' })
|
||||
} catch {
|
||||
uni.showToast({ title: '删除失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// 查询失败时仍允许删除
|
||||
// 查询失败时仍允许直接删除
|
||||
uni.showModal({
|
||||
title: '删除分类',
|
||||
content: `确定删除「${cat.name}」?`,
|
||||
@@ -129,6 +237,21 @@ async function onDelete(cat: any) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function onMigrateConfirm() {
|
||||
if (!deletingCat.value || !migrateTargetId.value) return
|
||||
|
||||
try {
|
||||
// 服务端原子操作:迁移记录 + 删除分类
|
||||
await catStore.migrateCategory(deletingCat.value.id, migrateTargetId.value)
|
||||
showMigrateModal.value = false
|
||||
// 刷新分类列表
|
||||
await catStore.fetchCategories()
|
||||
uni.showToast({ title: '已迁移并删除', icon: 'success' })
|
||||
} catch {
|
||||
uni.showToast({ title: '操作失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@@ -207,6 +330,7 @@ async function onDelete(cat: any) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16rpx;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.cat-name { font-size: 28rpx; color: #2D1B1B; font-weight: 500; }
|
||||
@@ -220,42 +344,43 @@ async function onDelete(cat: any) {
|
||||
}
|
||||
|
||||
.cat-actions {
|
||||
display: flex;
|
||||
gap: 8rpx;
|
||||
}
|
||||
|
||||
.action-btn {
|
||||
width: 64rpx;
|
||||
height: 64rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
|
||||
&:active { background: #F0E0D6; }
|
||||
}
|
||||
|
||||
.add-section {
|
||||
margin: 48rpx 40rpx 0;
|
||||
padding: 32rpx;
|
||||
background: #FFFFFF;
|
||||
border-radius: 32rpx;
|
||||
border: 2rpx solid #F0E0D6;
|
||||
}
|
||||
|
||||
.add-title {
|
||||
font-size: 28rpx;
|
||||
font-weight: 500;
|
||||
color: #2D1B1B;
|
||||
display: block;
|
||||
margin-bottom: 24rpx;
|
||||
}
|
||||
|
||||
.add-form {
|
||||
.fab {
|
||||
position: fixed;
|
||||
right: 40rpx;
|
||||
bottom: 120rpx;
|
||||
width: 112rpx;
|
||||
height: 112rpx;
|
||||
background: linear-gradient(135deg, #FF8C69, #E67355);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
gap: 16rpx;
|
||||
margin-bottom: 24rpx;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 8rpx 8rpx 24rpx rgba(255, 140, 105, 0.4);
|
||||
z-index: 50;
|
||||
|
||||
&:active { transform: scale(0.95); }
|
||||
}
|
||||
|
||||
.add-input {
|
||||
flex: 1;
|
||||
height: 88rpx;
|
||||
background: #FFF8F0;
|
||||
border-radius: 20rpx;
|
||||
padding: 0 24rpx;
|
||||
font-size: 28rpx;
|
||||
.fab-icon {
|
||||
font-size: 56rpx;
|
||||
color: #FFFFFF;
|
||||
font-weight: 300;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.color-picker {
|
||||
@@ -279,17 +404,100 @@ async function onDelete(cat: any) {
|
||||
&:active { opacity: 0.7; }
|
||||
}
|
||||
|
||||
.add-btn {
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
top: 0; left: 0; right: 0; bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 200;
|
||||
}
|
||||
|
||||
.modal {
|
||||
width: 600rpx;
|
||||
background: #FFFFFF;
|
||||
border-radius: 32rpx;
|
||||
padding: 48rpx;
|
||||
}
|
||||
|
||||
.modal-title {
|
||||
font-size: 32rpx;
|
||||
font-weight: 600;
|
||||
color: #2D1B1B;
|
||||
display: block;
|
||||
text-align: center;
|
||||
margin-bottom: 32rpx;
|
||||
}
|
||||
|
||||
.modal-desc {
|
||||
font-size: 28rpx;
|
||||
color: #8B7E7E;
|
||||
display: block;
|
||||
margin-bottom: 24rpx;
|
||||
}
|
||||
|
||||
.modal-input {
|
||||
width: 100%;
|
||||
height: 96rpx;
|
||||
background: #FFF8F0;
|
||||
border-radius: 24rpx;
|
||||
padding: 0 32rpx;
|
||||
font-size: 28rpx;
|
||||
margin-bottom: 24rpx;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.migrate-list {
|
||||
max-height: 400rpx;
|
||||
margin-bottom: 24rpx;
|
||||
}
|
||||
|
||||
.migrate-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16rpx;
|
||||
padding: 20rpx 16rpx;
|
||||
border-radius: 16rpx;
|
||||
margin-bottom: 8rpx;
|
||||
transition: background 0.2s;
|
||||
|
||||
&.selected {
|
||||
background: #FFE8E0;
|
||||
}
|
||||
&:active { background: #FFF0E6; }
|
||||
}
|
||||
|
||||
.migrate-name {
|
||||
font-size: 28rpx;
|
||||
color: #2D1B1B;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.modal-btns {
|
||||
display: flex;
|
||||
gap: 24rpx;
|
||||
}
|
||||
|
||||
.modal-btn {
|
||||
flex: 1;
|
||||
height: 88rpx;
|
||||
background: linear-gradient(135deg, #FF8C69, #E67355);
|
||||
border-radius: 20rpx;
|
||||
border-radius: 24rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 28rpx;
|
||||
font-weight: 600;
|
||||
color: #FFFFFF;
|
||||
|
||||
&.cancel {
|
||||
background: #FFF8F0;
|
||||
color: #8B7E7E;
|
||||
}
|
||||
|
||||
&.confirm {
|
||||
background: linear-gradient(135deg, #FF8C69, #E67355);
|
||||
color: #FFFFFF;
|
||||
}
|
||||
|
||||
&.disabled { opacity: 0.5; }
|
||||
&:active { opacity: 0.8; }
|
||||
|
||||
@@ -117,6 +117,7 @@ import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
|
||||
import { useTransactionStore } from '@/stores/transaction'
|
||||
import { useStatsStore } from '@/stores/stats'
|
||||
import { useBudgetStore } from '@/stores/budget'
|
||||
import { getOverview } from '@/api/stats'
|
||||
import { formatAmount, formatAmountRaw } from '@/utils/format'
|
||||
import { statusBarHeight } from '@/utils/system'
|
||||
import BudgetBar from '@/components/BudgetBar/BudgetBar.vue'
|
||||
@@ -173,8 +174,7 @@ async function loadData() {
|
||||
|
||||
async function fetchTodayData(today: string) {
|
||||
try {
|
||||
const { request } = await import('@/utils/request')
|
||||
const data = await request<any>({ url: '/stats/overview', data: { startDate: today, endDate: today } })
|
||||
const data = await getOverview({ startDate: today, endDate: today })
|
||||
todayExpense.value = data.expense || 0
|
||||
todayIncome.value = data.income || 0
|
||||
todayCount.value = data.count || 0
|
||||
|
||||
@@ -72,9 +72,9 @@ import { ref, onMounted } from 'vue'
|
||||
import { useTransactionStore } from '@/stores/transaction'
|
||||
import { useStatsStore } from '@/stores/stats'
|
||||
import { useBudgetStore } from '@/stores/budget'
|
||||
import { getTransactions } from '@/api/transaction'
|
||||
import { formatAmount } from '@/utils/format'
|
||||
import { statusBarHeight } from '@/utils/system'
|
||||
import { request } from '@/utils/request'
|
||||
import Icon from '@/components/Icon/Icon.vue'
|
||||
|
||||
const txStore = useTransactionStore()
|
||||
@@ -119,7 +119,7 @@ function getLocalDateStr(): string {
|
||||
async function exportData() {
|
||||
uni.showLoading({ title: '导出中...' })
|
||||
try {
|
||||
const data = await request<any>({ url: '/transactions', data: { page: 1, pageSize: 9999 } })
|
||||
const data = await getTransactions({ page: 1, pageSize: 9999 })
|
||||
const list = data.list
|
||||
if (!list || list.length === 0) {
|
||||
uni.showToast({ title: '暂无数据', icon: 'none' })
|
||||
|
||||
@@ -121,6 +121,8 @@
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import { onPullDownRefresh } from '@dcloudio/uni-app'
|
||||
import { useStatsStore } from '@/stores/stats'
|
||||
import { getTransactions } from '@/api/transaction'
|
||||
import { getOverview } from '@/api/stats'
|
||||
import { formatAmount, formatMonth, getCurrentMonth } from '@/utils/format'
|
||||
import { statusBarHeight } from '@/utils/system'
|
||||
import Icon from '@/components/Icon/Icon.vue'
|
||||
@@ -261,11 +263,7 @@ async function fetchMaxSingle() {
|
||||
const startDate = `${currentMonth.value}-01`
|
||||
const lastDay = new Date(y, m, 0).getDate()
|
||||
const endDate = `${currentMonth.value}-${String(lastDay).padStart(2, '0')}`
|
||||
const { request } = await import('@/utils/request')
|
||||
const data = await request<any>({
|
||||
url: '/transactions',
|
||||
data: { page: 1, pageSize: 1, type: tabType.value, startDate, endDate, sortBy: 'amount' }
|
||||
})
|
||||
const data = await getTransactions({ page: 1, pageSize: 1, type: tabType.value, startDate, endDate, sortBy: 'amount' })
|
||||
maxSingle.value = data.list?.[0]?.amount || 0
|
||||
} catch {
|
||||
maxSingle.value = 0
|
||||
@@ -276,11 +274,7 @@ async function fetchPrevMonthData() {
|
||||
try {
|
||||
const [y, m] = currentMonth.value.split('-').map(Number)
|
||||
const prevMonth = m === 1 ? `${y - 1}-12` : `${y}-${String(m - 1).padStart(2, '0')}`
|
||||
const { request } = await import('@/utils/request')
|
||||
const data = await request<any>({
|
||||
url: '/stats/overview',
|
||||
data: { month: prevMonth }
|
||||
})
|
||||
const data = await getOverview({ month: prevMonth })
|
||||
prevMonthData.value = data
|
||||
} catch {
|
||||
prevMonthData.value = null
|
||||
@@ -517,7 +511,7 @@ function getBarWidth(amount: number) {
|
||||
}
|
||||
|
||||
.trend-date {
|
||||
width: 48rpx;
|
||||
width: 52rpx;
|
||||
font-size: 24rpx;
|
||||
color: #8B7E7E;
|
||||
text-align: right;
|
||||
|
||||
@@ -1,25 +1,19 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { request } from '@/utils/request'
|
||||
import * as api from '@/api/budget'
|
||||
import { getCurrentMonth } from '@/utils/format'
|
||||
|
||||
export interface Budget {
|
||||
id: number
|
||||
amount: number
|
||||
month: string
|
||||
}
|
||||
// 重新导出类型以保持向后兼容
|
||||
export type Budget = api.Budget
|
||||
|
||||
export const useBudgetStore = defineStore('budget', () => {
|
||||
const budget = ref<Budget | null>(null)
|
||||
const budget = ref<api.Budget | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
async function fetchBudget(month?: string) {
|
||||
loading.value = true
|
||||
try {
|
||||
budget.value = await request<Budget>({
|
||||
url: '/budget',
|
||||
data: { month: month || getCurrentMonth() }
|
||||
})
|
||||
budget.value = await api.getBudget(month || getCurrentMonth())
|
||||
} catch {
|
||||
budget.value = null
|
||||
} finally {
|
||||
@@ -28,11 +22,7 @@ export const useBudgetStore = defineStore('budget', () => {
|
||||
}
|
||||
|
||||
async function setBudget(amount: number, month?: string) {
|
||||
await request({
|
||||
url: '/budget',
|
||||
method: 'POST',
|
||||
data: { amount, month: month || getCurrentMonth() }
|
||||
})
|
||||
await api.setBudget(amount, month || getCurrentMonth())
|
||||
await fetchBudget(month)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,18 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { request } from '@/utils/request'
|
||||
import * as api from '@/api/category'
|
||||
|
||||
export interface Category {
|
||||
id: number
|
||||
name: string
|
||||
icon: string
|
||||
color: string
|
||||
type: 'expense' | 'income'
|
||||
sort_order: number
|
||||
is_custom: number
|
||||
}
|
||||
// 重新导出类型以保持向后兼容
|
||||
export type Category = api.Category
|
||||
|
||||
export const useCategoryStore = defineStore('category', () => {
|
||||
const categories = ref<Category[]>([])
|
||||
const categories = ref<api.Category[]>([])
|
||||
const loading = ref(false)
|
||||
|
||||
async function fetchCategories() {
|
||||
loading.value = true
|
||||
try {
|
||||
categories.value = await request<Category[]>({ url: '/categories' })
|
||||
categories.value = await api.getCategories()
|
||||
} catch {
|
||||
categories.value = []
|
||||
} finally {
|
||||
@@ -36,19 +29,29 @@ export const useCategoryStore = defineStore('category', () => {
|
||||
}
|
||||
|
||||
async function addCategory(data: { name: string; icon: string; color: string; type: 'expense' | 'income' }) {
|
||||
const result = await request<{ id: number }>({
|
||||
url: '/categories',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
const result = await api.createCategory(data)
|
||||
await fetchCategories()
|
||||
return result.id
|
||||
}
|
||||
|
||||
async function deleteCategory(id: number) {
|
||||
await request({ url: `/categories/${id}`, method: 'DELETE' })
|
||||
async function updateCategory(id: number, data: { name: string; color: string }) {
|
||||
await api.updateCategory(id, data)
|
||||
await fetchCategories()
|
||||
}
|
||||
|
||||
return { categories, loading, fetchCategories, getByType, getById, addCategory, deleteCategory }
|
||||
async function deleteCategory(id: number) {
|
||||
await api.deleteCategory(id)
|
||||
await fetchCategories()
|
||||
}
|
||||
|
||||
async function migrateCategory(fromId: number, toId: number) {
|
||||
await api.migrateCategory(fromId, toId)
|
||||
}
|
||||
|
||||
async function sortCategories(ids: number[]) {
|
||||
await api.sortCategories(ids)
|
||||
await fetchCategories()
|
||||
}
|
||||
|
||||
return { categories, loading, fetchCategories, getByType, getById, addCategory, updateCategory, deleteCategory, migrateCategory, sortCategories }
|
||||
})
|
||||
|
||||
@@ -1,40 +1,21 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { request } from '@/utils/request'
|
||||
import * as api from '@/api/stats'
|
||||
import { getCurrentMonth } from '@/utils/format'
|
||||
|
||||
export interface Overview {
|
||||
expense: number
|
||||
income: number
|
||||
count: number
|
||||
daily: number
|
||||
}
|
||||
|
||||
export interface CategoryStat {
|
||||
id: number
|
||||
name: string
|
||||
icon: string
|
||||
color: string
|
||||
amount: number
|
||||
count: number
|
||||
}
|
||||
|
||||
export interface TrendPoint {
|
||||
date: string
|
||||
amount: number
|
||||
}
|
||||
// 重新导出类型以保持向后兼容
|
||||
export type Overview = api.Overview
|
||||
export type CategoryStat = api.CategoryStat
|
||||
export type TrendPoint = api.TrendPoint
|
||||
|
||||
export const useStatsStore = defineStore('stats', () => {
|
||||
const overview = ref<Overview>({ expense: 0, income: 0, count: 0, daily: 0 })
|
||||
const categoryStats = ref<CategoryStat[]>([])
|
||||
const trendData = ref<TrendPoint[]>([])
|
||||
const overview = ref<api.Overview>({ expense: 0, income: 0, count: 0, daily: 0 })
|
||||
const categoryStats = ref<api.CategoryStat[]>([])
|
||||
const trendData = ref<api.TrendPoint[]>([])
|
||||
|
||||
async function fetchOverview(month?: string) {
|
||||
try {
|
||||
overview.value = await request<Overview>({
|
||||
url: '/stats/overview',
|
||||
data: { month: month || getCurrentMonth() }
|
||||
})
|
||||
overview.value = await api.getOverview({ month: month || getCurrentMonth() })
|
||||
} catch {
|
||||
overview.value = { expense: 0, income: 0, count: 0, daily: 0 }
|
||||
}
|
||||
@@ -42,10 +23,7 @@ export const useStatsStore = defineStore('stats', () => {
|
||||
|
||||
async function fetchCategoryStats(month?: string, type: string = 'expense') {
|
||||
try {
|
||||
categoryStats.value = await request<CategoryStat[]>({
|
||||
url: '/stats/category',
|
||||
data: { month: month || getCurrentMonth(), type }
|
||||
})
|
||||
categoryStats.value = await api.getCategoryStats(month || getCurrentMonth(), type)
|
||||
} catch {
|
||||
categoryStats.value = []
|
||||
}
|
||||
@@ -53,10 +31,7 @@ export const useStatsStore = defineStore('stats', () => {
|
||||
|
||||
async function fetchTrend(month?: string, type: string = 'expense') {
|
||||
try {
|
||||
trendData.value = await request<TrendPoint[]>({
|
||||
url: '/stats/trend',
|
||||
data: { month: month || getCurrentMonth(), type }
|
||||
})
|
||||
trendData.value = await api.getTrend(month || getCurrentMonth(), type)
|
||||
} catch {
|
||||
trendData.value = []
|
||||
}
|
||||
|
||||
@@ -1,39 +1,17 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { request } from '@/utils/request'
|
||||
|
||||
export interface Transaction {
|
||||
id: number
|
||||
amount: number
|
||||
type: 'expense' | 'income'
|
||||
category_id: number
|
||||
note?: string
|
||||
date: string
|
||||
category_name?: string
|
||||
category_icon?: string
|
||||
category_color?: string
|
||||
}
|
||||
|
||||
export interface TransactionList {
|
||||
list: Transaction[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
import * as api from '@/api/transaction'
|
||||
|
||||
export const useTransactionStore = defineStore('transaction', () => {
|
||||
const transactions = ref<Transaction[]>([])
|
||||
const transactions = ref<api.Transaction[]>([])
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const currentPage = ref(1)
|
||||
|
||||
async function fetchTransactions(params?: { type?: string; startDate?: string; endDate?: string; page?: number; pageSize?: number }) {
|
||||
async function fetchTransactions(params?: api.TransactionParams) {
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await request<TransactionList>({
|
||||
url: '/transactions',
|
||||
data: params
|
||||
})
|
||||
const data = await api.getTransactions({ page: 1, ...params })
|
||||
transactions.value = data.list
|
||||
total.value = data.total
|
||||
currentPage.value = data.page
|
||||
@@ -45,26 +23,34 @@ export const useTransactionStore = defineStore('transaction', () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function addTransaction(data: { amount: number; type: string; category_id?: number; note?: string; date: string }) {
|
||||
const result = await request<{ id: number }>({
|
||||
url: '/transactions',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
async function addTransaction(data: {
|
||||
amount: number
|
||||
type: 'expense' | 'income'
|
||||
category_id?: number
|
||||
note?: string
|
||||
date: string
|
||||
}) {
|
||||
const result = await api.createTransaction(data)
|
||||
return result.id
|
||||
}
|
||||
|
||||
async function updateTransaction(id: number, data: { amount: number; type: string; category_id?: number; note?: string; date: string }) {
|
||||
await request({ url: `/transactions/${id}`, method: 'PUT', data })
|
||||
async function updateTransaction(id: number, data: {
|
||||
amount: number
|
||||
type: 'expense' | 'income'
|
||||
category_id?: number
|
||||
note?: string
|
||||
date: string
|
||||
}) {
|
||||
await api.updateTransaction(id, data)
|
||||
}
|
||||
|
||||
async function deleteTransaction(id: number) {
|
||||
await request({ url: `/transactions/${id}`, method: 'DELETE' })
|
||||
await api.deleteTransaction(id)
|
||||
}
|
||||
|
||||
async function fetchTransactionById(id: number): Promise<Transaction | undefined> {
|
||||
async function fetchTransactionById(id: number) {
|
||||
try {
|
||||
return await request<Transaction>({ url: `/transactions/${id}` })
|
||||
return await api.getTransaction(id)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -3,10 +3,29 @@ export function formatAmount(fen: number): string {
|
||||
return '¥ ' + yuan.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
}
|
||||
|
||||
export function formatDate(date: string): string {
|
||||
// Parse YYYY-MM-DD as local time to avoid timezone off-by-one
|
||||
const parts = date.split('-').map(Number)
|
||||
const d = new Date(parts[0], parts[1] - 1, parts[2])
|
||||
export function formatDate(date: string | Date): string {
|
||||
if (!date) return ''
|
||||
|
||||
// 处理 Date 对象或 ISO 字符串
|
||||
let d: Date
|
||||
if (date instanceof Date) {
|
||||
d = date
|
||||
} else if (typeof date === 'string') {
|
||||
// 处理 YYYY-MM-DD 格式
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
||||
const parts = date.split('-').map(Number)
|
||||
d = new Date(parts[0], parts[1] - 1, parts[2])
|
||||
} else {
|
||||
// 处理 ISO 字符串或其他格式
|
||||
d = new Date(date)
|
||||
}
|
||||
} else {
|
||||
return ''
|
||||
}
|
||||
|
||||
// 检查日期是否有效
|
||||
if (isNaN(d.getTime())) return ''
|
||||
|
||||
const now = new Date()
|
||||
// Reset time portion for accurate day diff
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
# Server
|
||||
PORT=3000
|
||||
|
||||
# Security
|
||||
TOKEN_SECRET=your_random_secret_here
|
||||
|
||||
# CORS (comma-separated origins, empty = allow all)
|
||||
CORS_ORIGINS=
|
||||
|
||||
# MySQL
|
||||
DB_HOST=your_mysql_host_here
|
||||
DB_USER=your_mysql_user_here
|
||||
DB_PASSWORD=your_mysql_password_here
|
||||
DB_NAME=your_mysql_name_here
|
||||
|
||||
# Backup
|
||||
BACKUP_DIR=/var/backups/xiaocai
|
||||
|
||||
# WeChat Mini Program
|
||||
WX_APPID=your_wx_appid_here
|
||||
WX_SECRET=your_wx_secret_here
|
||||
|
||||
@@ -10,6 +10,8 @@ import transactionRoutes from './routes/transaction'
|
||||
import statsRoutes from './routes/stats'
|
||||
import budgetRoutes from './routes/budget'
|
||||
import categoryRoutes from './routes/category'
|
||||
import backupRoutes from './routes/backup'
|
||||
import { backupDatabase } from './utils/backup'
|
||||
|
||||
// Warn if token secret is using default fallback
|
||||
if (!process.env.TOKEN_SECRET) {
|
||||
@@ -59,6 +61,7 @@ app.use('/api/transactions', apiLimiter, transactionRoutes)
|
||||
app.use('/api/stats', apiLimiter, statsRoutes)
|
||||
app.use('/api/budget', apiLimiter, budgetRoutes)
|
||||
app.use('/api/categories', apiLimiter, categoryRoutes)
|
||||
app.use('/api/backup', apiLimiter, backupRoutes)
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
try {
|
||||
@@ -71,7 +74,15 @@ app.get('/api/health', async (_req, res) => {
|
||||
|
||||
let server: any
|
||||
|
||||
initDatabase().then(() => {
|
||||
initDatabase().then(async () => {
|
||||
// 每次启动时自动备份数据库
|
||||
try {
|
||||
await backupDatabase()
|
||||
console.log('[Backup] 启动备份完成')
|
||||
} catch (err) {
|
||||
console.error('[Backup] 启动备份失败:', err)
|
||||
}
|
||||
|
||||
server = app.listen(PORT, () => {
|
||||
console.log(`Server running on port ${PORT}`)
|
||||
})
|
||||
|
||||
@@ -9,7 +9,7 @@ const TOKEN_SECRET = process.env.TOKEN_SECRET || 'xiaocai-token-secret-change-in
|
||||
const TOKEN_EXPIRY = 30 * 24 * 60 * 60 * 1000 // 30 days
|
||||
|
||||
// 不需要认证的路径
|
||||
const PUBLIC_PATHS = ['/api/auth/login', '/api/health']
|
||||
const PUBLIC_PATHS = ['/api/auth/login', '/api/auth/demo-login', '/api/health']
|
||||
|
||||
export function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
|
||||
// 公开路径跳过认证
|
||||
|
||||
29
server/src/routes/backup.ts
Normal file
29
server/src/routes/backup.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Router, Response } from 'express'
|
||||
import { AuthRequest } from '../middleware/auth'
|
||||
import { backupDatabase, getBackupList } from '../utils/backup'
|
||||
|
||||
const router = Router()
|
||||
|
||||
// 手动触发备份
|
||||
router.post('/', async (_req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const filepath = await backupDatabase()
|
||||
res.json({ code: 0, data: { filepath } })
|
||||
} catch (err) {
|
||||
console.error('[Backup] 手动备份失败:', err)
|
||||
res.status(500).json({ code: 50000, message: '备份失败' })
|
||||
}
|
||||
})
|
||||
|
||||
// 获取备份列表
|
||||
router.get('/', async (_req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const list = getBackupList()
|
||||
res.json({ code: 0, data: list })
|
||||
} catch (err) {
|
||||
console.error('[Backup] 获取列表失败:', err)
|
||||
res.status(500).json({ code: 50000, message: '获取备份列表失败' })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -38,6 +38,27 @@ router.post('/', async (req: AuthRequest, res: Response) => {
|
||||
}
|
||||
})
|
||||
|
||||
// 更新自定义分类
|
||||
router.put('/:id', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const { name, color } = req.body
|
||||
if (!name || !color) {
|
||||
return res.status(400).json({ code: 40001, message: '缺少必要参数' })
|
||||
}
|
||||
const [result] = await pool.query(
|
||||
'UPDATE categories SET name = ?, color = ? WHERE id = ? AND is_custom = 1 AND user_id = ?',
|
||||
[name, color, req.params.id, req.userId]
|
||||
)
|
||||
if ((result as any).affectedRows === 0) {
|
||||
return res.status(404).json({ code: 40400, message: '分类不存在' })
|
||||
}
|
||||
res.json({ code: 0 })
|
||||
} catch (err) {
|
||||
console.error('[Category] PUT error:', err)
|
||||
res.status(500).json({ code: 50000, message: '服务器错误' })
|
||||
}
|
||||
})
|
||||
|
||||
// 查询分类关联的记录数
|
||||
router.get('/:id/transaction-count', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
@@ -52,6 +73,72 @@ router.get('/:id/transaction-count', async (req: AuthRequest, res: Response) =>
|
||||
}
|
||||
})
|
||||
|
||||
// 迁移分类关联的记录到目标分类,并删除原分类(原子操作)
|
||||
router.post('/:id/migrate', async (req: AuthRequest, res: Response) => {
|
||||
const conn = await pool.getConnection()
|
||||
try {
|
||||
const { targetId } = req.body
|
||||
if (!targetId) {
|
||||
return res.status(400).json({ code: 40001, message: '缺少目标分类ID' })
|
||||
}
|
||||
|
||||
await conn.beginTransaction()
|
||||
|
||||
// 验证目标分类存在且属于当前用户或是默认分类
|
||||
const [targetRows] = await conn.query(
|
||||
'SELECT id FROM categories WHERE id = ? AND (user_id = 0 OR user_id = ?)',
|
||||
[targetId, req.userId]
|
||||
)
|
||||
if ((targetRows as any[]).length === 0) {
|
||||
await conn.rollback()
|
||||
return res.status(404).json({ code: 40400, message: '目标分类不存在' })
|
||||
}
|
||||
|
||||
// 迁移记录
|
||||
await conn.query(
|
||||
'UPDATE transactions SET category_id = ? WHERE category_id = ? AND user_id = ?',
|
||||
[targetId, req.params.id, req.userId]
|
||||
)
|
||||
|
||||
// 删除原分类
|
||||
await conn.query(
|
||||
'DELETE FROM categories WHERE id = ? AND is_custom = 1 AND user_id = ?',
|
||||
[req.params.id, req.userId]
|
||||
)
|
||||
|
||||
await conn.commit()
|
||||
res.json({ code: 0 })
|
||||
} catch (err) {
|
||||
await conn.rollback()
|
||||
console.error('[Category] migrate error:', err)
|
||||
res.status(500).json({ code: 50000, message: '服务器错误' })
|
||||
} finally {
|
||||
conn.release()
|
||||
}
|
||||
})
|
||||
|
||||
// 更新分类排序(批量更新,使用 CASE WHEN 一次完成)
|
||||
router.put('/sort', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const { ids } = req.body // [id1, id2, id3, ...]
|
||||
if (!Array.isArray(ids) || ids.length === 0) {
|
||||
return res.status(400).json({ code: 40001, message: '参数无效' })
|
||||
}
|
||||
|
||||
// 构建 CASE WHEN 语句批量更新
|
||||
const cases = ids.map((id: number, index: number) => `WHEN ${Number(id)} THEN ${index}`).join(' ')
|
||||
const idList = ids.map((id: number) => Number(id)).join(',')
|
||||
await pool.query(
|
||||
`UPDATE categories SET sort_order = CASE id ${cases} END WHERE id IN (${idList}) AND (user_id = 0 OR user_id = ?)`,
|
||||
[req.userId]
|
||||
)
|
||||
res.json({ code: 0 })
|
||||
} catch (err) {
|
||||
console.error('[Category] sort error:', err)
|
||||
res.status(500).json({ code: 50000, message: '服务器错误' })
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/:id', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const [result] = await pool.query(
|
||||
|
||||
@@ -4,6 +4,7 @@ import { AuthRequest } from '../middleware/auth'
|
||||
import { getCurrentMonth, getMonthRange } from '../utils/date'
|
||||
|
||||
const router = Router()
|
||||
const VALID_TYPES = ['expense', 'income']
|
||||
|
||||
router.get('/overview', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
@@ -54,6 +55,9 @@ router.get('/overview', async (req: AuthRequest, res: Response) => {
|
||||
router.get('/category', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const { month, type = 'expense' } = req.query
|
||||
if (!VALID_TYPES.includes(type as string)) {
|
||||
return res.status(400).json({ code: 40002, message: '类型无效' })
|
||||
}
|
||||
const m = (month as string) || getCurrentMonth()
|
||||
const range = getMonthRange(m)
|
||||
if (!range) return res.status(400).json({ code: 40001, message: '月份格式无效' })
|
||||
@@ -79,13 +83,16 @@ router.get('/category', async (req: AuthRequest, res: Response) => {
|
||||
router.get('/trend', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const { month, type = 'expense' } = req.query
|
||||
if (!VALID_TYPES.includes(type as string)) {
|
||||
return res.status(400).json({ code: 40002, message: '类型无效' })
|
||||
}
|
||||
const m = (month as string) || getCurrentMonth()
|
||||
const range = getMonthRange(m)
|
||||
if (!range) return res.status(400).json({ code: 40001, message: '月份格式无效' })
|
||||
const { startDate, endDate } = range
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT date, SUM(amount) as amount
|
||||
`SELECT DATE_FORMAT(date, '%Y-%m-%d') as date, SUM(amount) as amount
|
||||
FROM transactions
|
||||
WHERE user_id = ? AND type = ? AND date >= ? AND date <= ?
|
||||
GROUP BY date
|
||||
|
||||
@@ -16,7 +16,8 @@ function safeInt(val: any, fallback: number, min: number, max: number): number {
|
||||
router.get('/:id', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT t.*, c.name as category_name, c.icon as category_icon, c.color as category_color
|
||||
`SELECT t.id, t.user_id, t.amount, t.type, t.category_id, t.note, DATE_FORMAT(t.date, '%Y-%m-%d') as date, t.created_at, t.updated_at,
|
||||
c.name as category_name, c.icon as category_icon, c.color as category_color
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
WHERE t.id = ? AND t.user_id = ?`,
|
||||
@@ -56,7 +57,8 @@ router.get('/', async (req: AuthRequest, res: Response) => {
|
||||
const orderBy = sortBy === 'amount' ? 't.amount DESC' : 't.date DESC, t.created_at DESC'
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT t.*, c.name as category_name, c.icon as category_icon, c.color as category_color
|
||||
`SELECT t.id, t.user_id, t.amount, t.type, t.category_id, t.note, DATE_FORMAT(t.date, '%Y-%m-%d') as date, t.created_at, t.updated_at,
|
||||
c.name as category_name, c.icon as category_icon, c.color as category_color
|
||||
FROM transactions t
|
||||
LEFT JOIN categories c ON t.category_id = c.id
|
||||
${where}
|
||||
|
||||
100
server/src/utils/backup.ts
Normal file
100
server/src/utils/backup.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import zlib from 'zlib'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const gzipAsync = promisify(zlib.gzip)
|
||||
|
||||
const BACKUP_DIR = process.env.BACKUP_DIR || '/var/backups/xiaocai'
|
||||
const MAX_BACKUPS = 7 // 保留最近 7 天的备份
|
||||
|
||||
/**
|
||||
* 执行数据库备份
|
||||
* @returns 备份文件路径
|
||||
*/
|
||||
export async function backupDatabase(): Promise<string> {
|
||||
// 确保备份目录存在
|
||||
if (!fs.existsSync(BACKUP_DIR)) {
|
||||
fs.mkdirSync(BACKUP_DIR, { recursive: true })
|
||||
}
|
||||
|
||||
const date = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
|
||||
const filename = `xiaocai_${date}.sql.gz`
|
||||
const filepath = path.join(BACKUP_DIR, filename)
|
||||
|
||||
const dbHost = process.env.DB_HOST || 'localhost'
|
||||
const dbUser = process.env.DB_USER || 'root'
|
||||
const dbPassword = process.env.DB_PASSWORD || ''
|
||||
const dbName = process.env.DB_NAME || 'xiaocai'
|
||||
|
||||
try {
|
||||
// 使用 execFile 避免命令注入,参数通过数组传递
|
||||
const args = [
|
||||
`-h${dbHost}`,
|
||||
`-u${dbUser}`,
|
||||
...(dbPassword ? [`-p${dbPassword}`] : []),
|
||||
dbName
|
||||
]
|
||||
|
||||
const { stdout } = await execFileAsync('mysqldump', args, { maxBuffer: 50 * 1024 * 1024 })
|
||||
|
||||
// 使用 Node.js zlib 压缩
|
||||
const compressed = await gzipAsync(Buffer.from(stdout, 'utf-8'))
|
||||
fs.writeFileSync(filepath, compressed)
|
||||
|
||||
console.log(`[Backup] 完成: ${filename}`)
|
||||
|
||||
// 清理旧备份
|
||||
await cleanOldBackups()
|
||||
|
||||
return filepath
|
||||
} catch (err) {
|
||||
console.error('[Backup] 失败:', err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理过期的备份文件
|
||||
*/
|
||||
async function cleanOldBackups(): Promise<void> {
|
||||
try {
|
||||
if (!fs.existsSync(BACKUP_DIR)) return
|
||||
|
||||
const files = fs.readdirSync(BACKUP_DIR)
|
||||
.filter(f => f.startsWith('xiaocai_') && (f.endsWith('.sql.gz') || f.endsWith('.sql')))
|
||||
.sort()
|
||||
.reverse()
|
||||
|
||||
// 删除超出保留数量的文件
|
||||
for (let i = MAX_BACKUPS; i < files.length; i++) {
|
||||
const filepath = path.join(BACKUP_DIR, files[i])
|
||||
fs.unlinkSync(filepath)
|
||||
console.log(`[Backup] 清理旧备份: ${files[i]}`)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Backup] 清理失败:', err)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取备份列表
|
||||
*/
|
||||
export function getBackupList(): Array<{ name: string; size: number; date: string }> {
|
||||
if (!fs.existsSync(BACKUP_DIR)) return []
|
||||
|
||||
return fs.readdirSync(BACKUP_DIR)
|
||||
.filter(f => f.startsWith('xiaocai_') && (f.endsWith('.sql.gz') || f.endsWith('.sql')))
|
||||
.map(f => {
|
||||
const filepath = path.join(BACKUP_DIR, f)
|
||||
const stats = fs.statSync(filepath)
|
||||
return {
|
||||
name: f,
|
||||
size: stats.size,
|
||||
date: stats.mtime.toISOString()
|
||||
}
|
||||
})
|
||||
.sort((a, b) => b.date.localeCompare(a.date))
|
||||
}
|
||||
Reference in New Issue
Block a user