feat: 完善项目架构并增强分析页面功能

- 新增项目文档和 Docker 配置
  - 添加 README.md 和 TODO.md 项目文档
  - 为各服务添加 Dockerfile 和 docker-compose 配置

- 重构后端架构
  - 新增 adapter 层(HTTP/Python 适配器)
  - 新增 repository 层(数据访问抽象)
  - 新增 router 模块统一管理路由
  - 新增账单处理 handler

- 扩展前端 UI 组件库
  - 新增 Calendar、DateRangePicker、Drawer、Popover 等组件
  - 集成 shadcn-svelte 组件库

- 增强分析页面功能
  - 添加时间范围筛选器(支持本月默认值)
  - 修复 DateRangePicker 默认值显示问题
  - 优化数据获取和展示逻辑

- 完善分析器服务
  - 新增 FastAPI 服务接口
  - 改进账单清理器实现
This commit is contained in:
2026-01-10 01:15:52 +08:00
parent 94f8ea12e6
commit 087ae027cc
96 changed files with 4301 additions and 482 deletions

View File

@@ -2,6 +2,7 @@
import '../app.css';
import { page } from '$app/stores';
import { onMount } from 'svelte';
import { checkHealth } from '$lib/api';
import * as Sidebar from '$lib/components/ui/sidebar';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import * as Avatar from '$lib/components/ui/avatar';
@@ -14,7 +15,6 @@
import BarChart3 from '@lucide/svelte/icons/bar-chart-3';
import Settings from '@lucide/svelte/icons/settings';
import HelpCircle from '@lucide/svelte/icons/help-circle';
import Search from '@lucide/svelte/icons/search';
import ChevronsUpDown from '@lucide/svelte/icons/chevrons-up-down';
import Wallet from '@lucide/svelte/icons/wallet';
import LogOut from '@lucide/svelte/icons/log-out';
@@ -35,16 +35,32 @@
let { children } = $props();
let themeMode = $state<ThemeMode>('system');
let serverOnline = $state(true);
let checkingHealth = $state(true);
async function checkServerHealth() {
checkingHealth = true;
serverOnline = await checkHealth();
checkingHealth = false;
}
onMount(() => {
themeMode = loadThemeFromStorage();
applyThemeToDocument(themeMode);
// 检查服务器状态
checkServerHealth();
// 每 30 秒检查一次
const healthInterval = setInterval(checkServerHealth, 30000);
// 监听系统主题变化
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => applyThemeToDocument(themeMode);
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
return () => {
mediaQuery.removeEventListener('change', handleChange);
clearInterval(healthInterval);
};
});
function cycleTheme() {
@@ -78,6 +94,18 @@
if (href === '/') return pathname === '/';
return pathname.startsWith(href);
}
// 根据路径获取页面标题
function getPageTitle(pathname: string): string {
const titles: Record<string, string> = {
'/': '上传账单',
'/review': '智能复核',
'/bills': '账单管理',
'/analysis': '数据分析',
'/settings': '设置',
'/help': '帮助'
};
return titles[pathname] || 'BillAI';
}
</script>
<Sidebar.Provider>
@@ -237,18 +265,32 @@
<header class="flex h-14 shrink-0 items-center gap-2 border-b px-4">
<Sidebar.Trigger class="-ml-1" />
<Separator orientation="vertical" class="mr-2 h-4" />
<div class="flex items-center gap-2">
<Search class="size-4 text-muted-foreground" />
<span class="text-sm text-muted-foreground">搜索...</span>
</div>
<div class="ml-auto flex items-center gap-2">
<div class="flex items-center gap-1.5 text-sm">
<span class="relative flex h-2 w-2">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
</span>
<span class="text-muted-foreground">服务运行中</span>
</div>
<h1 class="text-lg font-semibold">{getPageTitle($page.url.pathname)}</h1>
<div class="flex-1" />
<div class="flex items-center gap-3">
<button
class="flex items-center gap-1.5 text-sm hover:opacity-80 transition-opacity"
onclick={checkServerHealth}
title="点击刷新状态"
>
{#if checkingHealth}
<span class="relative flex h-2 w-2">
<span class="relative inline-flex rounded-full h-2 w-2 bg-gray-400 animate-pulse"></span>
</span>
<span class="text-muted-foreground">检查中...</span>
{:else if serverOnline}
<span class="relative flex h-2 w-2">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
</span>
<span class="text-muted-foreground">服务运行中</span>
{:else}
<span class="relative flex h-2 w-2">
<span class="relative inline-flex rounded-full h-2 w-2 bg-red-500"></span>
</span>
<span class="text-red-500">服务离线</span>
{/if}
</button>
</div>
</header>

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import { uploadBill, type UploadResponse } from '$lib/api';
import { uploadBill, type UploadResponse, type BillType } from '$lib/api';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
@@ -16,6 +16,7 @@
let isDragOver = $state(false);
let selectedFile: File | null = $state(null);
let selectedType: BillType = $state('alipay');
let isUploading = $state(false);
let uploadResult: UploadResponse | null = $state(null);
let errorMessage = $state('');
@@ -86,6 +87,14 @@
selectedFile = file;
errorMessage = '';
uploadResult = null;
// 根据文件名自动识别账单类型
const fileName = file.name.toLowerCase();
if (fileName.includes('支付宝') || fileName.includes('alipay')) {
selectedType = 'alipay';
} else if (fileName.includes('微信') || fileName.includes('wechat')) {
selectedType = 'wechat';
}
}
function clearFile() {
@@ -101,7 +110,7 @@
errorMessage = '';
try {
const result = await uploadBill(selectedFile);
const result = await uploadBill(selectedFile, selectedType);
if (result.result) {
uploadResult = result;
} else {
@@ -135,7 +144,7 @@
<!-- 统计卡片 -->
<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
{#each stats as stat}
<Card.Root>
<Card.Root class="transition-all duration-200 hover:shadow-lg hover:-translate-y-1 cursor-default">
<Card.Header class="flex flex-row items-center justify-between space-y-0 pb-2">
<Card.Title class="text-sm font-medium">{stat.title}</Card.Title>
{#if stat.trend === 'up'}
@@ -226,6 +235,27 @@
</div>
{/if}
<!-- 账单类型选择 -->
<div class="flex items-center gap-3">
<span class="text-sm font-medium">账单类型:</span>
<div class="flex gap-2">
<Button
variant={selectedType === 'alipay' ? 'default' : 'outline'}
size="sm"
onclick={() => selectedType = 'alipay'}
>
支付宝
</Button>
<Button
variant={selectedType === 'wechat' ? 'default' : 'outline'}
size="sm"
onclick={() => selectedType = 'wechat'}
>
微信
</Button>
</div>
</div>
<!-- 上传按钮 -->
<Button
class="w-full"
@@ -256,7 +286,7 @@
<CheckCircle class="h-5 w-5 text-green-600 dark:text-green-400" />
<div>
<p class="font-medium text-green-800 dark:text-green-200">处理成功</p>
<p class="text-sm text-green-600 dark:text-green-400">账单已分析完成</p>
<p class="text-sm text-green-600 dark:text-green-400">{uploadResult.message}</p>
</div>
</div>
@@ -267,6 +297,14 @@
{uploadResult.data?.bill_type === 'alipay' ? '支付宝' : '微信'}
</Badge>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-muted-foreground">原始记录数</span>
<span class="text-sm font-medium">{uploadResult.data?.raw_count ?? 0}</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-muted-foreground">清洗后记录数</span>
<span class="text-sm font-medium">{uploadResult.data?.cleaned_count ?? 0}</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-muted-foreground">输出文件</span>
<span class="text-sm font-medium">{uploadResult.data?.file_name}</span>
@@ -275,7 +313,7 @@
<div class="flex gap-3 pt-2">
<a
href={`http://localhost:8080${uploadResult.data?.file_url}`}
href={uploadResult.data?.file_url || '#'}
download
class="flex-1"
>

View File

@@ -1,11 +1,16 @@
<script lang="ts">
import { fetchBillContent, type BillRecord } from '$lib/api';
import { onMount } from 'svelte';
import { fetchBills, checkHealth, type CleanedBill } from '$lib/api';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { Input } from '$lib/components/ui/input';
import * as Card from '$lib/components/ui/card';
import { DateRangePicker } from '$lib/components/ui/date-range-picker';
import BarChart3 from '@lucide/svelte/icons/bar-chart-3';
import Loader2 from '@lucide/svelte/icons/loader-2';
import AlertCircle from '@lucide/svelte/icons/alert-circle';
import Activity from '@lucide/svelte/icons/activity';
import RefreshCw from '@lucide/svelte/icons/refresh-cw';
import Calendar from '@lucide/svelte/icons/calendar';
// 分析组件
import {
@@ -14,7 +19,6 @@
CategoryRanking,
MonthlyTrend,
TopExpenses,
EmptyState
} from '$lib/components/analysis';
// 数据处理服务
@@ -32,61 +36,119 @@
// 分类数据
import { categories as allCategories } from '$lib/data/categories';
// 计算默认日期范围(本月)
function getDefaultDates() {
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth();
const startDate = new Date(year, month, 1).toISOString().split('T')[0];
const endDate = today.toISOString().split('T')[0];
return { startDate, endDate };
}
const defaultDates = getDefaultDates();
// 状态
let fileName = $state('');
let isLoading = $state(false);
let errorMessage = $state('');
let records: BillRecord[] = $state([]);
let records: CleanedBill[] = $state([]);
let isDemo = $state(false);
let serverAvailable = $state(true);
// 派生数据
let categoryStats = $derived(calculateCategoryStats(records));
let monthlyStats = $derived(calculateMonthlyStats(records));
let dailyExpenseData = $derived(calculateDailyExpenseData(records));
let totalStats = $derived(calculateTotalStats(records));
// 时间范围筛选 - 初始化为默认值
let startDate: string = $state(defaultDates.startDate);
let endDate: string = $state(defaultDates.endDate);
// 将 CleanedBill 转换为分析服务需要的格式
function toAnalysisRecords(bills: CleanedBill[]) {
return bills.map(bill => ({
time: bill.time,
category: bill.category,
merchant: bill.merchant,
description: bill.description,
income_expense: bill.income_expense,
amount: String(bill.amount),
payment_method: bill.pay_method,
status: bill.status,
remark: bill.remark,
needs_review: bill.review_level,
}));
}
// 派生分析数据
let analysisRecords = $derived(isDemo ? demoRecords : toAnalysisRecords(records));
let categoryStats = $derived(calculateCategoryStats(analysisRecords));
let monthlyStats = $derived(calculateMonthlyStats(analysisRecords));
let dailyExpenseData = $derived(calculateDailyExpenseData(analysisRecords));
let totalStats = $derived(calculateTotalStats(analysisRecords));
let pieChartData = $derived(calculatePieChartData(categoryStats, totalStats.expense));
let topExpenses = $derived(getTopExpenses(records, 10));
let topExpenses = $derived(getTopExpenses(analysisRecords, 10));
// 分类列表按数据中出现次数排序(出现次数多的优先)
// 分类列表按数据中出现次数排序
let sortedCategories = $derived(() => {
// 统计每个分类的记录数量
const categoryCounts = new Map<string, number>();
for (const record of records) {
for (const record of analysisRecords) {
categoryCounts.set(record.category, (categoryCounts.get(record.category) || 0) + 1);
}
// 对分类进行排序:先按数据中的数量降序,未出现的分类按原顺序排在后面
return [...allCategories].sort((a, b) => {
const countA = categoryCounts.get(a) || 0;
const countB = categoryCounts.get(b) || 0;
// 数量大的排前面
if (countA !== countB) return countB - countA;
// 数量相同时保持原有顺序
return allCategories.indexOf(a) - allCategories.indexOf(b);
});
});
async function loadData() {
if (!fileName) return;
isLoading = true;
errorMessage = '';
isDemo = false;
try {
records = await fetchBillContent(fileName);
// 先检查服务器状态
serverAvailable = await checkHealth();
if (!serverAvailable) {
errorMessage = '服务器不可用';
return;
}
// 获取账单数据(带时间范围筛选)
const response = await fetchBills({
page_size: 10000,
start_date: startDate || undefined,
end_date: endDate || undefined,
});
if (response.result && response.data) {
records = response.data.bills || [];
if (records.length === 0) {
errorMessage = '暂无账单数据';
}
} else {
errorMessage = response.message || '加载失败';
}
} catch (err) {
errorMessage = err instanceof Error ? err.message : '加载失败';
serverAvailable = false;
} finally {
isLoading = false;
}
}
// 日期变化时重新加载
function onDateChange() {
if (!isDemo) {
loadData();
}
}
function loadDemoData() {
isDemo = true;
errorMessage = '';
records = demoRecords;
}
// 页面加载时自动获取数据
onMount(() => {
loadData();
});
</script>
<svelte:head>
@@ -95,55 +157,52 @@
<div class="space-y-6">
<!-- 页面标题 -->
<div class="flex items-center justify-between">
<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 class="text-2xl font-bold tracking-tight">数据分析</h1>
<p class="text-muted-foreground">可视化你的消费数据,洞察消费习惯</p>
</div>
{#if isDemo}
<Badge variant="secondary" class="text-xs">
📊 示例数据
</Badge>
{/if}
</div>
<!-- 搜索栏 -->
<div class="flex gap-3">
<div class="relative flex-1">
<BarChart3 class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
type="text"
placeholder="输入文件名..."
class="pl-10"
bind:value={fileName}
onkeydown={(e) => e.key === 'Enter' && loadData()}
/>
</div>
<Button onclick={loadData} disabled={isLoading}>
{#if isLoading}
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
分析中
<div class="flex items-center gap-3">
{#if isDemo}
<Badge variant="secondary" class="text-xs">
📊 示例数据
</Badge>
{:else}
<BarChart3 class="mr-2 h-4 w-4" />
分析
<!-- 时间范围筛选 -->
<DateRangePicker
bind:startDate
bind:endDate
onchange={onDateChange}
/>
{/if}
</Button>
<Button variant="outline" size="icon" onclick={loadData} disabled={isLoading} title="刷新数据">
<RefreshCw class="h-4 w-4 {isLoading ? 'animate-spin' : ''}" />
</Button>
</div>
</div>
<!-- 错误提示 -->
{#if errorMessage}
{#if errorMessage && !isDemo}
<div class="flex items-center gap-2 rounded-lg border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
<AlertCircle class="h-4 w-4" />
{errorMessage}
</div>
{/if}
{#if records.length > 0}
<!-- 加载中 -->
{#if isLoading}
<Card.Root>
<Card.Content class="flex flex-col items-center justify-center py-16">
<Loader2 class="h-16 w-16 text-muted-foreground mb-4 animate-spin" />
<p class="text-lg font-medium">正在加载数据...</p>
</Card.Content>
</Card.Root>
{:else if analysisRecords.length > 0}
<!-- 总览卡片 -->
<OverviewCards {totalStats} {records} />
<OverviewCards {totalStats} records={analysisRecords} />
<!-- 每日支出趋势图(按分类堆叠) -->
<DailyTrendChart bind:records categories={sortedCategories()} />
<DailyTrendChart records={analysisRecords} categories={sortedCategories()} />
<div class="grid gap-6 lg:grid-cols-2">
<!-- 分类支出排行 -->
@@ -151,7 +210,7 @@
{categoryStats}
{pieChartData}
totalExpense={totalStats.expense}
bind:records
records={analysisRecords}
categories={sortedCategories()}
/>
@@ -161,7 +220,30 @@
<!-- Top 10 支出 -->
<TopExpenses records={topExpenses} categories={sortedCategories()} />
{:else if !isLoading}
<EmptyState onLoadDemo={loadDemoData} />
{:else}
<!-- 空状态:服务器不可用或没有数据时显示示例按钮 -->
<Card.Root>
<Card.Content class="flex flex-col items-center justify-center py-16">
<BarChart3 class="h-16 w-16 text-muted-foreground mb-4" />
<p class="text-lg font-medium">
{#if !serverAvailable}
服务器不可用
{:else}
暂无账单数据
{/if}
</p>
<p class="text-sm text-muted-foreground mb-4">
{#if !serverAvailable}
请检查后端服务是否正常运行
{:else}
上传账单后可在此进行数据分析
{/if}
</p>
<Button variant="outline" onclick={loadDemoData}>
<Activity class="mr-2 h-4 w-4" />
查看示例数据
</Button>
</Card.Content>
</Card.Root>
{/if}
</div>

View File

@@ -0,0 +1,39 @@
import { env } from '$env/dynamic/private';
import type { RequestHandler } from './$types';
// 服务端使用 Docker 内部地址,默认使用 localhost
const API_URL = env.API_URL || 'http://localhost:8080';
export const GET: RequestHandler = async ({ params, url, fetch }) => {
const path = params.path;
const queryString = url.search;
const response = await fetch(`${API_URL}/api/${path}${queryString}`);
return new Response(response.body, {
status: response.status,
headers: {
'Content-Type': response.headers.get('Content-Type') || 'application/json',
},
});
};
export const POST: RequestHandler = async ({ params, request, fetch }) => {
const path = params.path;
// 转发原始请求体
const response = await fetch(`${API_URL}/api/${path}`, {
method: 'POST',
body: await request.arrayBuffer(),
headers: {
'Content-Type': request.headers.get('Content-Type') || 'application/octet-stream',
},
});
return new Response(response.body, {
status: response.status,
headers: {
'Content-Type': response.headers.get('Content-Type') || 'application/json',
},
});
};

View File

@@ -1,12 +1,13 @@
<script lang="ts">
import { fetchBillContent, type BillRecord } from '$lib/api';
import { onMount } from 'svelte';
import { fetchBills, type CleanedBill } from '$lib/api';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
import * as Table from '$lib/components/ui/table';
import FolderOpen from '@lucide/svelte/icons/folder-open';
import { DateRangePicker } from '$lib/components/ui/date-range-picker';
import Loader2 from '@lucide/svelte/icons/loader-2';
import AlertCircle from '@lucide/svelte/icons/alert-circle';
import Search from '@lucide/svelte/icons/search';
@@ -15,56 +16,124 @@
import TrendingUp from '@lucide/svelte/icons/trending-up';
import FileText from '@lucide/svelte/icons/file-text';
import Filter from '@lucide/svelte/icons/filter';
import ChevronLeft from '@lucide/svelte/icons/chevron-left';
import ChevronRight from '@lucide/svelte/icons/chevron-right';
import RefreshCw from '@lucide/svelte/icons/refresh-cw';
let fileName = $state('');
// 状态
let isLoading = $state(false);
let errorMessage = $state('');
let records: BillRecord[] = $state([]);
let filterCategory = $state('all');
let filterType = $state<'all' | '支出' | '收入'>('all');
let records: CleanedBill[] = $state([]);
// 分页
let currentPage = $state(1);
let pageSize = $state(20);
let totalRecords = $state(0);
let totalPages = $state(0);
// 聚合统计(所有筛选条件下的数据)
let totalExpense = $state(0);
let totalIncome = $state(0);
// 计算默认日期(当前月)
function getDefaultDates() {
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth();
const startDate = new Date(year, month, 1).toISOString().split('T')[0];
const endDate = today.toISOString().split('T')[0];
return { startDate, endDate };
}
const defaultDates = getDefaultDates();
// 筛选
let filterCategory = $state('');
let filterIncomeExpense = $state(''); // 收支类型
let filterBillType = $state(''); // 账单来源
let startDate = $state(defaultDates.startDate);
let endDate = $state(defaultDates.endDate);
let searchText = $state('');
async function loadBillData() {
if (!fileName) return;
// 分类列表(硬编码常用分类)
const categories = [
'餐饮美食', '交通出行', '生活服务', '日用百货',
'服饰美容', '医疗健康', '通讯话费', '住房缴费',
'文化娱乐', '金融理财', '教育培训', '人情往来', '其他'
];
async function loadBills() {
isLoading = true;
errorMessage = '';
try {
records = await fetchBillContent(fileName);
const response = await fetchBills({
page: currentPage,
page_size: pageSize,
start_date: startDate || undefined,
end_date: endDate || undefined,
category: filterCategory || undefined,
type: filterBillType || undefined,
income_expense: filterIncomeExpense || undefined,
});
if (response.result && response.data) {
records = response.data.bills || [];
totalRecords = response.data.total;
totalPages = response.data.pages;
totalExpense = response.data.total_expense || 0;
totalIncome = response.data.total_income || 0;
} else {
errorMessage = response.message || '加载失败';
records = [];
}
} catch (err) {
errorMessage = err instanceof Error ? err.message : '加载失败';
records = [];
} finally {
isLoading = false;
}
}
// 获取所有分类
let categories = $derived([...new Set(records.map(r => r.category))].sort());
// 切换页面
function goToPage(page: number) {
if (page >= 1 && page <= totalPages) {
currentPage = page;
loadBills();
}
}
// 过滤后的记录
let filteredRecords = $derived(
records.filter(r => {
if (filterCategory !== 'all' && r.category !== filterCategory) return false;
if (filterType !== 'all' && r.income_expense !== filterType) return false;
if (searchText) {
const text = searchText.toLowerCase();
return r.merchant.toLowerCase().includes(text) ||
r.description.toLowerCase().includes(text);
}
return true;
})
// 筛选变化时重置到第一页
function applyFilters() {
currentPage = 1;
loadBills();
}
// 清除筛选(恢复默认值)
function clearFilters() {
filterCategory = '';
filterIncomeExpense = '';
filterBillType = '';
startDate = defaultDates.startDate;
endDate = defaultDates.endDate;
searchText = '';
currentPage = 1;
loadBills();
}
// 本地搜索(在当前页数据中筛选)
let displayRecords = $derived(
searchText
? records.filter(r => {
const text = searchText.toLowerCase();
return r.merchant?.toLowerCase().includes(text) ||
r.description?.toLowerCase().includes(text);
})
: records
);
// 统计
let stats = $derived({
total: filteredRecords.length,
expense: filteredRecords
.filter(r => r.income_expense === '支出')
.reduce((sum, r) => sum + parseFloat(r.amount || '0'), 0),
income: filteredRecords
.filter(r => r.income_expense === '收入')
.reduce((sum, r) => sum + parseFloat(r.amount || '0'), 0),
// 页面加载时获取数据
onMount(() => {
loadBills();
});
</script>
@@ -74,31 +143,14 @@
<div class="space-y-6">
<!-- 页面标题 -->
<div>
<h1 class="text-2xl font-bold tracking-tight">账单列表</h1>
<p class="text-muted-foreground">查看和筛选已处理的账单记录</p>
</div>
<!-- 搜索栏 -->
<div class="flex gap-3">
<div class="relative flex-1">
<FolderOpen class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
type="text"
placeholder="输入文件名..."
class="pl-10"
bind:value={fileName}
onkeydown={(e) => e.key === 'Enter' && loadBillData()}
/>
<div class="flex items-center justify-between">
<div>
<h1 class="text-2xl font-bold tracking-tight">账单列表</h1>
<p class="text-muted-foreground">查看和筛选已处理的账单记录</p>
</div>
<Button onclick={loadBillData} disabled={isLoading}>
{#if isLoading}
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
加载中
{:else}
<FolderOpen class="mr-2 h-4 w-4" />
加载
{/if}
<Button variant="outline" onclick={loadBills} disabled={isLoading}>
<RefreshCw class="mr-2 h-4 w-4 {isLoading ? 'animate-spin' : ''}" />
刷新
</Button>
</div>
@@ -110,166 +162,235 @@
</div>
{/if}
{#if records.length > 0}
<!-- 统计概览 -->
<div class="grid gap-4 md:grid-cols-3">
<Card.Root>
<Card.Header class="flex flex-row items-center justify-between space-y-0 pb-2">
<Card.Title class="text-sm font-medium">交易笔数</Card.Title>
<Receipt class="h-4 w-4 text-muted-foreground" />
</Card.Header>
<Card.Content>
<div class="text-2xl font-bold">{stats.total}</div>
<p class="text-xs text-muted-foreground">符合筛选条件的记录</p>
</Card.Content>
</Card.Root>
<!-- 统计概览 -->
<div class="grid gap-4 md:grid-cols-3">
<Card.Root class="transition-all duration-200 hover:shadow-lg hover:-translate-y-1 cursor-default">
<Card.Header class="flex flex-row items-center justify-between space-y-0 pb-2">
<Card.Title class="text-sm font-medium">总交易笔数</Card.Title>
<Receipt class="h-4 w-4 text-muted-foreground" />
</Card.Header>
<Card.Content>
<div class="text-2xl font-bold">{totalRecords}</div>
<p class="text-xs text-muted-foreground">筛选条件下的账单总数</p>
</Card.Content>
</Card.Root>
<Card.Root class="border-red-200 dark:border-red-900">
<Card.Header class="flex flex-row items-center justify-between space-y-0 pb-2">
<Card.Title class="text-sm font-medium">总支出</Card.Title>
<TrendingDown class="h-4 w-4 text-red-500" />
</Card.Header>
<Card.Content>
<div class="text-2xl font-bold font-mono text-red-600 dark:text-red-400">
¥{stats.expense.toFixed(2)}
</div>
<p class="text-xs text-muted-foreground">支出金额汇总</p>
</Card.Content>
</Card.Root>
<Card.Root class="border-red-200 dark:border-red-900 transition-all duration-200 hover:shadow-lg hover:-translate-y-1 hover:border-red-300 dark:hover:border-red-800 cursor-default">
<Card.Header class="flex flex-row items-center justify-between space-y-0 pb-2">
<Card.Title class="text-sm font-medium">总支出</Card.Title>
<TrendingDown class="h-4 w-4 text-red-500" />
</Card.Header>
<Card.Content>
<div class="text-2xl font-bold font-mono text-red-600 dark:text-red-400">
¥{totalExpense.toFixed(2)}
</div>
<p class="text-xs text-muted-foreground">筛选条件下的支出汇总</p>
</Card.Content>
</Card.Root>
<Card.Root class="border-green-200 dark:border-green-900">
<Card.Header class="flex flex-row items-center justify-between space-y-0 pb-2">
<Card.Title class="text-sm font-medium">总收入</Card.Title>
<TrendingUp class="h-4 w-4 text-green-500" />
</Card.Header>
<Card.Content>
<div class="text-2xl font-bold font-mono text-green-600 dark:text-green-400">
¥{stats.income.toFixed(2)}
</div>
<p class="text-xs text-muted-foreground">收入金额汇总</p>
</Card.Content>
</Card.Root>
</div>
<Card.Root class="border-green-200 dark:border-green-900 transition-all duration-200 hover:shadow-lg hover:-translate-y-1 hover:border-green-300 dark:hover:border-green-800 cursor-default">
<Card.Header class="flex flex-row items-center justify-between space-y-0 pb-2">
<Card.Title class="text-sm font-medium">总收入</Card.Title>
<TrendingUp class="h-4 w-4 text-green-500" />
</Card.Header>
<Card.Content>
<div class="text-2xl font-bold font-mono text-green-600 dark:text-green-400">
¥{totalIncome.toFixed(2)}
</div>
<p class="text-xs text-muted-foreground">筛选条件下的收入汇总</p>
</Card.Content>
</Card.Root>
</div>
<!-- 筛选和表格 -->
<Card.Root>
<Card.Header>
<div class="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
<!-- 筛选和表格 -->
<Card.Root>
<Card.Header>
<div class="flex flex-col gap-4">
<div class="flex items-center justify-between">
<Card.Title class="flex items-center gap-2">
<Filter class="h-5 w-5" />
筛选条件
</Card.Title>
<div class="flex flex-wrap gap-4">
<div class="space-y-1.5">
<Label class="text-xs">分类</Label>
<select
class="h-9 rounded-md border border-input bg-background px-3 text-sm"
bind:value={filterCategory}
>
<option value="all">全部分类</option>
{#each categories as cat}
<option value={cat}>{cat}</option>
{/each}
</select>
</div>
<div class="space-y-1.5">
<Label class="text-xs">类型</Label>
<select
class="h-9 rounded-md border border-input bg-background px-3 text-sm"
bind:value={filterType}
>
<option value="all">全部</option>
<option value="支出">支出</option>
<option value="收入">收入</option>
</select>
</div>
<div class="space-y-1.5 flex-1 min-w-[200px]">
<Label class="text-xs">搜索</Label>
<div class="relative">
<Search class="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
type="text"
placeholder="商家/商品..."
class="pl-8"
bind:value={searchText}
/>
</div>
{#if filterCategory || filterIncomeExpense || filterBillType || startDate || endDate}
<Button variant="ghost" size="sm" onclick={clearFilters}>
清除筛选
</Button>
{/if}
</div>
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
<div class="space-y-1.5 col-span-2 sm:col-span-2">
<Label class="text-xs">日期范围</Label>
<DateRangePicker
{startDate}
{endDate}
onchange={(start, end) => {
startDate = start;
endDate = end;
applyFilters();
}}
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">分类</Label>
<select
class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
bind:value={filterCategory}
onchange={applyFilters}
>
<option value="">全部</option>
{#each categories as cat}
<option value={cat}>{cat}</option>
{/each}
</select>
</div>
<div class="space-y-1.5">
<Label class="text-xs">收/支</Label>
<select
class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
bind:value={filterIncomeExpense}
onchange={applyFilters}
>
<option value="">全部</option>
<option value="支出">支出</option>
<option value="收入">收入</option>
</select>
</div>
<div class="space-y-1.5">
<Label class="text-xs">来源</Label>
<select
class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
bind:value={filterBillType}
onchange={applyFilters}
>
<option value="">全部</option>
<option value="alipay">支付宝</option>
<option value="wechat">微信</option>
</select>
</div>
<div class="space-y-1.5 col-span-2 sm:col-span-1">
<Label class="text-xs">搜索</Label>
<div class="relative">
<Search class="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
type="text"
placeholder="商家/商品..."
class="pl-8"
bind:value={searchText}
/>
</div>
</div>
</div>
</Card.Header>
<Card.Content>
{#if filteredRecords.length > 0}
<div class="rounded-md border">
<Table.Root>
<Table.Header>
</div>
</Card.Header>
<Card.Content>
{#if isLoading}
<div class="flex flex-col items-center justify-center py-12">
<Loader2 class="h-8 w-8 animate-spin text-muted-foreground mb-4" />
<p class="text-muted-foreground">加载中...</p>
</div>
{:else if displayRecords.length > 0}
<div class="rounded-md border">
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head class="w-[100px] lg:w-[160px]">时间</Table.Head>
<Table.Head class="hidden xl:table-cell">来源</Table.Head>
<Table.Head>分类</Table.Head>
<Table.Head class="hidden sm:table-cell">交易对方</Table.Head>
<Table.Head class="hidden lg:table-cell">商品说明</Table.Head>
<Table.Head class="hidden min-[480px]:table-cell">收/支</Table.Head>
<Table.Head class="text-right">金额</Table.Head>
<Table.Head class="hidden xl:table-cell">支付方式</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each displayRecords as record}
<Table.Row>
<Table.Head class="w-[160px]">时间</Table.Head>
<Table.Head>分类</Table.Head>
<Table.Head>交易对方</Table.Head>
<Table.Head>商品说明</Table.Head>
<Table.Head>收/支</Table.Head>
<Table.Head class="text-right">金额</Table.Head>
<Table.Head>支付方式</Table.Head>
<Table.Head>状态</Table.Head>
<Table.Cell class="text-muted-foreground text-sm">
{record.time}
</Table.Cell>
<Table.Cell class="hidden xl:table-cell">
<Badge variant={record.bill_type === 'alipay' ? 'default' : 'secondary'}>
{record.bill_type === 'alipay' ? '支付宝' : '微信'}
</Badge>
</Table.Cell>
<Table.Cell>
<Badge variant="outline">{record.category}</Badge>
</Table.Cell>
<Table.Cell class="hidden sm:table-cell max-w-[100px] md:max-w-[150px] truncate" title={record.merchant}>
{record.merchant}
</Table.Cell>
<Table.Cell class="hidden lg:table-cell max-w-[150px] truncate text-muted-foreground" title={record.description}>
{record.description || '-'}
</Table.Cell>
<Table.Cell class="hidden min-[480px]:table-cell">
<span class={record.income_expense === '支出' ? 'text-red-500' : 'text-green-500'}>
{record.income_expense}
</span>
</Table.Cell>
<Table.Cell class="text-right font-mono font-medium">
¥{record.amount.toFixed(2)}
</Table.Cell>
<Table.Cell class="hidden xl:table-cell text-muted-foreground text-sm">
{record.pay_method || '-'}
</Table.Cell>
</Table.Row>
</Table.Header>
<Table.Body>
{#each filteredRecords.slice(0, 100) as record}
<Table.Row>
<Table.Cell class="text-muted-foreground text-sm">
{record.time}
</Table.Cell>
<Table.Cell>
<Badge variant="secondary">{record.category}</Badge>
</Table.Cell>
<Table.Cell class="max-w-[180px] truncate" title={record.merchant}>
{record.merchant}
</Table.Cell>
<Table.Cell class="max-w-[180px] truncate text-muted-foreground" title={record.description}>
{record.description || '-'}
</Table.Cell>
<Table.Cell>
<span class={record.income_expense === '支出' ? 'text-red-500' : 'text-green-500'}>
{record.income_expense}
</span>
</Table.Cell>
<Table.Cell class="text-right font-mono font-medium">
¥{record.amount}
</Table.Cell>
<Table.Cell class="text-muted-foreground text-sm">
{record.payment_method || '-'}
</Table.Cell>
<Table.Cell>
<Badge variant="outline" class="text-green-600 border-green-200">
{record.status || '已完成'}
</Badge>
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
{/each}
</Table.Body>
</Table.Root>
</div>
<!-- 分页控件 -->
<div class="flex items-center justify-between mt-4">
<p class="text-sm text-muted-foreground">
显示 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, totalRecords)} 条,共 {totalRecords}
</p>
<div class="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={currentPage <= 1}
onclick={() => goToPage(currentPage - 1)}
>
<ChevronLeft class="h-4 w-4" />
上一页
</Button>
<div class="flex items-center gap-1">
{#each Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
// 计算显示的页码范围
let start = Math.max(1, currentPage - 2);
let end = Math.min(totalPages, start + 4);
start = Math.max(1, end - 4);
return start + i;
}).filter(p => p <= totalPages) as page}
<Button
variant={page === currentPage ? 'default' : 'outline'}
size="sm"
class="w-9"
onclick={() => goToPage(page)}
>
{page}
</Button>
{/each}
</div>
<Button
variant="outline"
size="sm"
disabled={currentPage >= totalPages}
onclick={() => goToPage(currentPage + 1)}
>
下一页
<ChevronRight class="h-4 w-4" />
</Button>
</div>
{#if filteredRecords.length > 100}
<p class="text-center text-sm text-muted-foreground mt-4">
显示前 100 条记录,共 {filteredRecords.length}
</p>
{/if}
{:else}
<div class="flex flex-col items-center justify-center py-12 text-center">
<FileText class="h-12 w-12 text-muted-foreground mb-4" />
<p class="text-muted-foreground">没有匹配的记录</p>
</div>
{/if}
</Card.Content>
</Card.Root>
{:else if !isLoading}
<Card.Root>
<Card.Content class="flex flex-col items-center justify-center py-16">
<FileText class="h-16 w-16 text-muted-foreground mb-4" />
<p class="text-lg font-medium">输入文件名加载账单数据</p>
<p class="text-sm text-muted-foreground">上传账单后可在此查看完整记录</p>
</Card.Content>
</Card.Root>
{/if}
</div>
{:else}
<div class="flex flex-col items-center justify-center py-12 text-center">
<FileText class="h-12 w-12 text-muted-foreground mb-4" />
<p class="text-muted-foreground">没有找到账单记录</p>
<p class="text-sm text-muted-foreground mt-1">请先上传账单或调整筛选条件</p>
</div>
{/if}
</Card.Content>
</Card.Root>
</div>

View File

@@ -0,0 +1,19 @@
import { env } from '$env/dynamic/private';
import type { RequestHandler } from './$types';
// 服务端使用 Docker 内部地址
const API_URL = env.API_URL || 'http://localhost:8080';
export const GET: RequestHandler = async ({ params, fetch }) => {
const path = params.path;
const response = await fetch(`${API_URL}/download/${path}`);
return new Response(response.body, {
status: response.status,
headers: {
'Content-Type': response.headers.get('Content-Type') || 'text/csv',
'Content-Disposition': response.headers.get('Content-Disposition') || '',
},
});
};