chore: initial commit of HouseholdBudgetBook (backend, frontend, desktop)
This commit is contained in:
commit
4a5db3f1f9
167 files changed
+21732
No files matched your search
@@ -0,0 +1,36 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { api, ApiError } from './api'
|
||||
|
||||
describe('api.getTransactions', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('把 AbortSignal 传给 fetch', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ items: [], total: 0, page: 1, page_size: 20 }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const controller = new AbortController()
|
||||
|
||||
await api.getTransactions({ page: '2' }, controller.signal)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/transactions?page=2',
|
||||
expect.objectContaining({ signal: controller.signal }),
|
||||
)
|
||||
})
|
||||
|
||||
it('请求取消时保留 AbortError 而不包装为 ApiError', async () => {
|
||||
const abortError = new DOMException('已取消', 'AbortError')
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(abortError))
|
||||
|
||||
const request = api.getTransactions({}, new AbortController().signal)
|
||||
|
||||
await expect(request).rejects.toBe(abortError)
|
||||
await expect(request).rejects.not.toBeInstanceOf(ApiError)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,199 @@
|
||||
import type {
|
||||
Account, Category, CreateAccountRequest, CreateCategoryRequest,
|
||||
CreateMemberRequest, CreateTransactionRequest, DashboardSummary,
|
||||
Member, Transaction, TransactionListItem, TransactionListResponse,
|
||||
BudgetOverview, UpsertBudgetRequest, Budget, ReportOverview, CategoryRankingItem, TrendItem,
|
||||
Asset, AssetSnapshot, Liability, NetWorthSummary, Policy, LifecycleEvent,
|
||||
ImportTransactionsResult, ImportPreviewResult, ImportBatch, DeleteTransactionsResult,
|
||||
UpdateAccountRequest, UpdateCategoryRequest, UpdateMemberRequest,
|
||||
UpdateTransactionRequest, AccountReconciliation, BackupStatus, PolicyPayment,
|
||||
} from '@/types/index'
|
||||
|
||||
const BASE_URL = ''
|
||||
|
||||
class ApiError extends Error {
|
||||
status: number
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.status = status
|
||||
this.name = 'ApiError'
|
||||
}
|
||||
}
|
||||
|
||||
async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(BASE_URL + path, {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
...options,
|
||||
})
|
||||
} catch (e) {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') throw e
|
||||
throw new ApiError(e instanceof Error ? `网络请求失败:${e.message}` : '网络请求失败', 0)
|
||||
}
|
||||
|
||||
if (res.status === 204) return undefined as T
|
||||
|
||||
let data: { error?: string } | unknown = null
|
||||
try {
|
||||
data = await res.json()
|
||||
} catch {
|
||||
// 非 JSON 响应(如 502 网关返回 HTML),保持 data 为 null
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const msg = (data && typeof data === 'object' && 'error' in data ? (data as { error?: string }).error : null) || `请求失败 (${res.status})`
|
||||
throw new ApiError(msg, res.status)
|
||||
}
|
||||
|
||||
return data as T
|
||||
}
|
||||
|
||||
async function apiUpload<T>(path: string, formData: FormData): Promise<T> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(BASE_URL + path, { method: 'POST', body: formData })
|
||||
} catch (e) {
|
||||
throw new ApiError(e instanceof Error ? `网络请求失败:${e.message}` : '网络请求失败', 0)
|
||||
}
|
||||
|
||||
let data: { error?: string } | unknown = null
|
||||
try {
|
||||
data = await res.json()
|
||||
} catch {
|
||||
// 非 JSON 响应
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const msg = (data && typeof data === 'object' && 'error' in data ? (data as { error?: string }).error : null) || `请求失败 (${res.status})`
|
||||
throw new ApiError(msg, res.status)
|
||||
}
|
||||
|
||||
return data as T
|
||||
}
|
||||
|
||||
export const api = {
|
||||
// Members
|
||||
getMembers: () => apiFetch<Member[]>('/api/members'),
|
||||
createMember: (req: CreateMemberRequest) =>
|
||||
apiFetch<Member>('/api/members', { method: 'POST', body: JSON.stringify(req) }),
|
||||
updateMember: (id: number, req: UpdateMemberRequest) =>
|
||||
apiFetch<Member>(`/api/members/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deleteMember: (id: number) =>
|
||||
apiFetch<void>(`/api/members/${id}`, { method: 'DELETE' }),
|
||||
|
||||
// Categories
|
||||
getCategories: (type?: string) =>
|
||||
apiFetch<Category[]>(`/api/categories${type ? `?type=${type}` : ''}`),
|
||||
createCategory: (req: CreateCategoryRequest) =>
|
||||
apiFetch<Category>('/api/categories', { method: 'POST', body: JSON.stringify(req) }),
|
||||
updateCategory: (id: number, req: UpdateCategoryRequest) =>
|
||||
apiFetch<Category>(`/api/categories/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deleteCategory: (id: number) =>
|
||||
apiFetch<void>(`/api/categories/${id}`, { method: 'DELETE' }),
|
||||
|
||||
// Accounts
|
||||
getAccounts: () => apiFetch<Account[]>('/api/accounts'),
|
||||
createAccount: (req: CreateAccountRequest) =>
|
||||
apiFetch<Account>('/api/accounts', { method: 'POST', body: JSON.stringify(req) }),
|
||||
updateAccount: (id: number, req: UpdateAccountRequest) =>
|
||||
apiFetch<Account>(`/api/accounts/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deleteAccount: (id: number) =>
|
||||
apiFetch<void>(`/api/accounts/${id}`, { method: 'DELETE' }),
|
||||
reconcileAccount: (id: number, actual_balance: number, note = '', create_adjustment = true) =>
|
||||
apiFetch<AccountReconciliation>(`/api/accounts/${id}/reconcile`, { method: 'POST', body: JSON.stringify({ actual_balance, note, create_adjustment }) }),
|
||||
getAccountReconciliations: (id: number) => apiFetch<AccountReconciliation[]>(`/api/accounts/${id}/reconciliations`),
|
||||
|
||||
// Transactions
|
||||
getTransactions: (params: Record<string, string>, signal?: AbortSignal) => {
|
||||
const qs = new URLSearchParams(params).toString()
|
||||
return apiFetch<TransactionListResponse>(
|
||||
`/api/transactions${qs ? `?${qs}` : ''}`,
|
||||
{ signal },
|
||||
)
|
||||
},
|
||||
createTransaction: (req: CreateTransactionRequest) =>
|
||||
apiFetch<Transaction>('/api/transactions', { method: 'POST', body: JSON.stringify(req) }),
|
||||
previewImportTransactions: (formData: FormData) =>
|
||||
apiUpload<ImportPreviewResult>('/api/transactions/import/preview', formData),
|
||||
importTransactions: (formData: FormData) =>
|
||||
apiUpload<ImportTransactionsResult>('/api/transactions/import', formData),
|
||||
getImportBatches: () =>
|
||||
apiFetch<ImportBatch[]>('/api/transactions/import-batches'),
|
||||
deleteTransactionsBatch: (ids: number[]) =>
|
||||
apiFetch<DeleteTransactionsResult>('/api/transactions/batch-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
|
||||
deleteImportBatch: (id: number) =>
|
||||
apiFetch<DeleteTransactionsResult>(`/api/transactions/import-batches/${id}`, { method: 'DELETE' }),
|
||||
updateTransaction: (id: number, req: UpdateTransactionRequest) =>
|
||||
apiFetch<Transaction>(`/api/transactions/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deleteTransaction: (id: number) =>
|
||||
apiFetch<void>(`/api/transactions/${id}`, { method: 'DELETE' }),
|
||||
|
||||
// Dashboard
|
||||
getDashboardSummary: (year?: string, month?: string) => {
|
||||
const params = new URLSearchParams()
|
||||
if (year) params.set('year', year)
|
||||
if (month) params.set('month', month)
|
||||
const qs = params.toString()
|
||||
return apiFetch<DashboardSummary>(`/api/dashboard/summary${qs ? `?${qs}` : ''}`)
|
||||
},
|
||||
getDashboardRecent: (limit = 5) =>
|
||||
apiFetch<TransactionListItem[]>(`/api/dashboard/recent?limit=${limit}`),
|
||||
|
||||
// Budgets
|
||||
getBudgetOverview: (year: number, month: number) =>
|
||||
apiFetch<BudgetOverview>(`/api/budgets/${year}/${month}`),
|
||||
upsertBudget: (req: UpsertBudgetRequest) =>
|
||||
apiFetch<Budget>('/api/budgets', { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deleteBudget: (id: number) => apiFetch<void>(`/api/budgets/${id}`, { method: 'DELETE' }),
|
||||
|
||||
// Reports
|
||||
getReportOverview: (year: number, month: number, type: 'income' | 'expense' = 'expense') =>
|
||||
apiFetch<ReportOverview>(`/api/reports/overview?year=${year}&month=${month}&type=${type}`),
|
||||
getCategoryRanking: (year: number, month: number, type = 'expense') =>
|
||||
apiFetch<CategoryRankingItem[]>(`/api/reports/category-ranking?year=${year}&month=${month}&type=${type}`),
|
||||
getTrend: (year: number) =>
|
||||
apiFetch<TrendItem[]>(`/api/reports/trend?year=${year}`),
|
||||
|
||||
// Assets & liabilities
|
||||
getAssets: () => apiFetch<Asset[]>('/api/assets'),
|
||||
createAsset: (req: Partial<Asset>) =>
|
||||
apiFetch<Asset>('/api/assets', { method: 'POST', body: JSON.stringify(req) }),
|
||||
updateAsset: (id: number, req: Partial<Asset>) =>
|
||||
apiFetch<Asset>(`/api/assets/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deleteAsset: (id: number) => apiFetch<void>(`/api/assets/${id}`, { method: 'DELETE' }),
|
||||
getLiabilities: () => apiFetch<Liability[]>('/api/liabilities'),
|
||||
createLiability: (req: Partial<Liability>) =>
|
||||
apiFetch<Liability>('/api/liabilities', { method: 'POST', body: JSON.stringify(req) }),
|
||||
updateLiability: (id: number, req: Partial<Liability>) =>
|
||||
apiFetch<Liability>(`/api/liabilities/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deleteLiability: (id: number) => apiFetch<void>(`/api/liabilities/${id}`, { method: 'DELETE' }),
|
||||
getNetWorth: () => apiFetch<NetWorthSummary>('/api/assets/net-worth'),
|
||||
getAssetSnapshots: () => apiFetch<AssetSnapshot[]>('/api/assets/snapshots'),
|
||||
|
||||
// Policies
|
||||
getPolicies: () => apiFetch<Policy[]>('/api/policies'),
|
||||
getUpcomingPolicies: (days = 30) => apiFetch<Policy[]>(`/api/policies/upcoming?days=${days}`),
|
||||
createPolicy: (req: Partial<Policy>) =>
|
||||
apiFetch<Policy>('/api/policies', { method: 'POST', body: JSON.stringify(req) }),
|
||||
updatePolicy: (id: number, req: Partial<Policy>) =>
|
||||
apiFetch<Policy>(`/api/policies/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deletePolicy: (id: number) => apiFetch<void>(`/api/policies/${id}`, { method: 'DELETE' }),
|
||||
getPolicyPayments: (id: number) => apiFetch<PolicyPayment[]>(`/api/policies/${id}/payments`),
|
||||
createPolicyPayment: (id: number, req: Partial<PolicyPayment>) => apiFetch<PolicyPayment>(`/api/policies/${id}/payments`, { method: 'POST', body: JSON.stringify(req) }),
|
||||
updatePolicyPayment: (id: number, req: Partial<PolicyPayment>) => apiFetch<PolicyPayment>(`/api/policy-payments/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
|
||||
getBackupStatus: () => apiFetch<BackupStatus>('/api/backups/status'),
|
||||
createBackup: () => apiFetch<BackupStatus>('/api/backups', { method: 'POST' }),
|
||||
|
||||
// Lifecycle
|
||||
getLifecycleEvents: () => apiFetch<LifecycleEvent[]>('/api/lifecycle'),
|
||||
createLifecycleEvent: (req: Partial<LifecycleEvent>) =>
|
||||
apiFetch<LifecycleEvent>('/api/lifecycle/events', { method: 'POST', body: JSON.stringify(req) }),
|
||||
updateLifecycleEvent: (id: number, req: Partial<LifecycleEvent>) =>
|
||||
apiFetch<LifecycleEvent>(`/api/lifecycle/events/${id}`, { method: 'PUT', body: JSON.stringify(req) }),
|
||||
deleteLifecycleEvent: (id: number) => apiFetch<void>(`/api/lifecycle/events/${id}`, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
export type { Account, AccountReconciliation, BackupStatus, Category, CreateAccountRequest, CreateCategoryRequest, CreateMemberRequest, CreateTransactionRequest, DashboardSummary, Member, Transaction, TransactionListItem, TransactionListResponse, UpdateAccountRequest, UpdateCategoryRequest, UpdateMemberRequest, UpdateTransactionRequest, BudgetOverview, UpsertBudgetRequest, Budget, ReportOverview, CategoryRankingItem, TrendItem, Asset, AssetSnapshot, Liability, NetWorthSummary, Policy, PolicyPayment, LifecycleEvent, ImportTransactionsResult, ImportPreviewResult, ImportBatch, DeleteTransactionsResult }
|
||||
export { ApiError }
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { Category } from '@/lib/api'
|
||||
import type { TreeSelectNode } from '@/components/ui/tree-select'
|
||||
|
||||
export function buildCategoryTree(
|
||||
categories: Category[],
|
||||
config: { allowParentSelect: boolean },
|
||||
): TreeSelectNode[] {
|
||||
const typeRank = (t: string) => (t === 'expense' ? 0 : 1)
|
||||
const top = categories
|
||||
.filter((c) => c.parent_id === null)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
typeRank(a.type) - typeRank(b.type) ||
|
||||
a.sort_order - b.sort_order ||
|
||||
a.id - b.id,
|
||||
)
|
||||
const children = categories
|
||||
.filter((c) => c.parent_id !== null)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
typeRank(a.type) - typeRank(b.type) ||
|
||||
a.sort_order - b.sort_order ||
|
||||
a.id - b.id,
|
||||
)
|
||||
const orphanParentIds = new Set(
|
||||
children
|
||||
.filter((c) => !top.some((parent) => parent.id === c.parent_id))
|
||||
.map((c) => c.id),
|
||||
)
|
||||
const orphans = children.filter((c) => orphanParentIds.has(c.id))
|
||||
const tree: TreeSelectNode[] = top.map((parent) => {
|
||||
const kids = children.filter((c) => c.parent_id === parent.id)
|
||||
if (kids.length === 0) {
|
||||
return { id: String(parent.id), label: parent.name, selectable: true }
|
||||
}
|
||||
return {
|
||||
id: String(parent.id),
|
||||
label: parent.name,
|
||||
selectable: config.allowParentSelect,
|
||||
children: kids.map((child) => ({
|
||||
id: String(child.id),
|
||||
label: child.name,
|
||||
selectable: true,
|
||||
})),
|
||||
}
|
||||
})
|
||||
for (const orphan of orphans) {
|
||||
tree.push({ id: String(orphan.id), label: orphan.name, selectable: true })
|
||||
}
|
||||
return tree
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export type ImportSourceKind = 'cmb_debit' | 'cmb_credit' | 'alipay' | 'wechat'
|
||||
|
||||
export function importIsCSV(kind: string): boolean {
|
||||
return kind === 'alipay' || kind === 'wechat'
|
||||
}
|
||||
|
||||
export function sourceKindMatchesAccount(kind: string, accountType: string): boolean {
|
||||
switch (kind) {
|
||||
case 'cmb_debit':
|
||||
return accountType === 'debit_card' || accountType === 'bank_card'
|
||||
case 'cmb_credit':
|
||||
return accountType === 'credit_card'
|
||||
case 'alipay':
|
||||
return accountType === 'alipay'
|
||||
case 'wechat':
|
||||
return accountType === 'wechat'
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
accountMutationInvalidation,
|
||||
assetMutationInvalidation,
|
||||
invalidateKeys,
|
||||
transactionMutationInvalidation,
|
||||
} from './queryInvalidation'
|
||||
import { queryKeys } from './queryKeys'
|
||||
|
||||
describe('query invalidation', () => {
|
||||
it('defines hierarchical asset query keys', () => {
|
||||
expect(queryKeys.assets).toEqual({
|
||||
all: ['assets'],
|
||||
list: ['assets', 'list'],
|
||||
liabilities: ['assets', 'liabilities'],
|
||||
netWorth: ['assets', 'netWorth'],
|
||||
snapshots: ['assets', 'snapshots'],
|
||||
})
|
||||
})
|
||||
|
||||
it('invalidates only asset list and net worth for asset mutations', () => {
|
||||
expect(assetMutationInvalidation('asset')).toEqual([
|
||||
queryKeys.assets.list,
|
||||
queryKeys.assets.netWorth,
|
||||
])
|
||||
expect(assetMutationInvalidation('asset')).not.toContain(queryKeys.accounts)
|
||||
expect(assetMutationInvalidation('asset')).not.toContain(queryKeys.assets.snapshots)
|
||||
})
|
||||
|
||||
it('invalidates only liability list and net worth for liability mutations', () => {
|
||||
expect(assetMutationInvalidation('liability')).toEqual([
|
||||
queryKeys.assets.liabilities,
|
||||
queryKeys.assets.netWorth,
|
||||
])
|
||||
expect(assetMutationInvalidation('liability')).not.toContain(queryKeys.assets.list)
|
||||
})
|
||||
|
||||
it('invalidates only accounts and net worth for account mutations', () => {
|
||||
expect(accountMutationInvalidation()).toEqual([
|
||||
queryKeys.accounts,
|
||||
queryKeys.assets.netWorth,
|
||||
])
|
||||
expect(accountMutationInvalidation()).not.toContain(queryKeys.assets.list)
|
||||
expect(accountMutationInvalidation()).not.toContain(queryKeys.assets.snapshots)
|
||||
})
|
||||
|
||||
it('invalidates every transaction-dependent query root', () => {
|
||||
expect(transactionMutationInvalidation()).toEqual([
|
||||
queryKeys.transactions.all,
|
||||
queryKeys.importBatches,
|
||||
queryKeys.accounts,
|
||||
queryKeys.assets.netWorth,
|
||||
queryKeys.dashboard.all,
|
||||
queryKeys.budgets.all,
|
||||
queryKeys.reports.all,
|
||||
])
|
||||
})
|
||||
|
||||
it('invalidates every supplied query key', async () => {
|
||||
const queryClient = new QueryClient()
|
||||
const keys = [queryKeys.assets.list, queryKeys.assets.netWorth] as const
|
||||
|
||||
keys.forEach((queryKey) => queryClient.setQueryData(queryKey, 'cached'))
|
||||
|
||||
await invalidateKeys(queryClient, keys)
|
||||
|
||||
keys.forEach((queryKey) => {
|
||||
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { QueryClient, QueryKey } from '@tanstack/react-query'
|
||||
|
||||
import { queryKeys } from './queryKeys'
|
||||
|
||||
export type AssetMutationKind = 'asset' | 'liability'
|
||||
|
||||
export function assetMutationInvalidation(
|
||||
kind: AssetMutationKind,
|
||||
): readonly QueryKey[] {
|
||||
return [
|
||||
kind === 'asset' ? queryKeys.assets.list : queryKeys.assets.liabilities,
|
||||
queryKeys.assets.netWorth,
|
||||
]
|
||||
}
|
||||
|
||||
export function accountMutationInvalidation(): readonly QueryKey[] {
|
||||
return [queryKeys.accounts, queryKeys.assets.netWorth]
|
||||
}
|
||||
|
||||
export function transactionMutationInvalidation(): readonly QueryKey[] {
|
||||
return [
|
||||
queryKeys.transactions.all,
|
||||
queryKeys.importBatches,
|
||||
queryKeys.accounts,
|
||||
queryKeys.assets.netWorth,
|
||||
queryKeys.dashboard.all,
|
||||
queryKeys.budgets.all,
|
||||
queryKeys.reports.all,
|
||||
]
|
||||
}
|
||||
|
||||
export async function invalidateKeys(
|
||||
queryClient: QueryClient,
|
||||
keys: readonly QueryKey[],
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
keys.map((queryKey) => queryClient.invalidateQueries({ queryKey })),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
export const queryKeys = {
|
||||
categories: ['categories'] as const,
|
||||
accounts: ['accounts'] as const,
|
||||
members: ['members'] as const,
|
||||
importBatches: ['importBatches'] as const,
|
||||
transactions: {
|
||||
all: ['transactions'] as const,
|
||||
list: (params: Record<string, string>) => ['transactions', 'list', params] as const,
|
||||
},
|
||||
dashboard: {
|
||||
all: ['dashboard'] as const,
|
||||
summary: (year: string, month: string) => ['dashboard', 'summary', year, month] as const,
|
||||
recent: (limit: number) => ['dashboard', 'recent', limit] as const,
|
||||
},
|
||||
reports: {
|
||||
all: ['reports'] as const,
|
||||
overview: (year: number, month: number, type: string) =>
|
||||
['reports', 'overview', year, month, type] as const,
|
||||
},
|
||||
budgets: {
|
||||
all: ['budgets'] as const,
|
||||
month: (year: number, month: number) => ['budgets', year, month] as const,
|
||||
},
|
||||
assets: {
|
||||
all: ['assets'] as const,
|
||||
list: ['assets', 'list'] as const,
|
||||
liabilities: ['assets', 'liabilities'] as const,
|
||||
netWorth: ['assets', 'netWorth'] as const,
|
||||
snapshots: ['assets', 'snapshots'] as const,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateTransactionRequest } from '@/lib/api'
|
||||
|
||||
export const transactionFormSchema = z
|
||||
.object({
|
||||
amountYuan: z.string().refine((v) => {
|
||||
const n = parseFloat(v)
|
||||
return !isNaN(n) && n > 0 && /^\d+(\.\d{1,2})?$/.test(v)
|
||||
}, '请输入有效金额'),
|
||||
type: z.enum(['expense', 'income', 'transfer']),
|
||||
category_id: z.string().optional(),
|
||||
account_id: z.string().optional(),
|
||||
to_account_id: z.string().optional(),
|
||||
date: z.string().min(1, '请选择日期'),
|
||||
description: z.string().optional(),
|
||||
counterparty: z.string().optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.type === 'transfer') {
|
||||
if (!data.account_id) {
|
||||
ctx.addIssue({ code: 'custom', path: ['account_id'], message: '请选择转出账户' })
|
||||
}
|
||||
if (!data.to_account_id) {
|
||||
ctx.addIssue({ code: 'custom', path: ['to_account_id'], message: '请选择转入账户' })
|
||||
}
|
||||
if (data.account_id && data.to_account_id && data.account_id === data.to_account_id) {
|
||||
ctx.addIssue({ code: 'custom', path: ['to_account_id'], message: '转出与转入账户不能相同' })
|
||||
}
|
||||
} else if (!data.category_id) {
|
||||
ctx.addIssue({ code: 'custom', path: ['category_id'], message: '请选择分类' })
|
||||
}
|
||||
})
|
||||
|
||||
export type TransactionFormData = z.infer<typeof transactionFormSchema>
|
||||
|
||||
export function buildTransactionPayload(data: TransactionFormData): CreateTransactionRequest {
|
||||
const amount = Math.round(parseFloat(data.amountYuan) * 100)
|
||||
const isTransfer = data.type === 'transfer'
|
||||
return {
|
||||
type: data.type,
|
||||
amount,
|
||||
category_id: isTransfer ? null : data.category_id ? parseInt(data.category_id, 10) : null,
|
||||
account_id: data.account_id ? parseInt(data.account_id, 10) : null,
|
||||
to_account_id: isTransfer && data.to_account_id ? parseInt(data.to_account_id, 10) : null,
|
||||
date: data.date,
|
||||
description: data.description || '',
|
||||
counterparty: data.counterparty || '',
|
||||
}
|
||||
}
|
||||
|
||||
export const defaultTransactionFormValues: TransactionFormData = {
|
||||
type: 'expense',
|
||||
amountYuan: '',
|
||||
category_id: '',
|
||||
account_id: '',
|
||||
to_account_id: '',
|
||||
date: '',
|
||||
description: '',
|
||||
counterparty: '',
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { type ClassValue, clsx } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function formatCents(cents: number): string {
|
||||
const yuan = Math.abs(cents) / 100
|
||||
const sign = cents < 0 ? '-' : ''
|
||||
return sign + '¥' + yuan.toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})
|
||||
}
|
||||
|
||||
export function formatDate(dateStr: string): string {
|
||||
if (!dateStr) return ''
|
||||
const [y, m, d] = dateStr.split('-')
|
||||
return `${parseInt(y, 10)}年${parseInt(m, 10)}月${parseInt(d, 10)}日`
|
||||
}
|
||||
|
||||
export function formatMonth(dateStr: string): string {
|
||||
if (!dateStr) return ''
|
||||
const [y, m] = dateStr.split('-')
|
||||
return `${y}年${parseInt(m, 10)}月`
|
||||
}
|
||||
|
||||
export function formatLocalDate(date = new Date()): string {
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
Reference in new issue
Block a user