218 lines
8.7 KiB
TypeScript
218 lines
8.7 KiB
TypeScript
import { useState } from 'react'
|
|
import { useMutation } from '@tanstack/react-query'
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from '@/components/ui/dialog'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Input } from '@/components/ui/input'
|
|
import { api, ApiError, type Account, type ImportPreviewResult } from '@/lib/api'
|
|
import { formatDate } from '@/lib/utils'
|
|
import { importIsCSV, sourceKindMatchesAccount, type ImportSourceKind } from '@/lib/importUtils'
|
|
import { AmountDisplay } from '@/components/AmountDisplay'
|
|
import { useCategories } from '@/hooks/useCategories'
|
|
|
|
interface Props {
|
|
open: boolean
|
|
onOpenChange: (open: boolean) => void
|
|
accounts: Account[]
|
|
onImported: () => void
|
|
}
|
|
|
|
export function ImportDialog({ open, onOpenChange, accounts, onImported }: Props) {
|
|
const { categories } = useCategories()
|
|
const [importFile, setImportFile] = useState<File | null>(null)
|
|
const [importSourceKind, setImportSourceKind] = useState<ImportSourceKind>('cmb_debit')
|
|
const [importAccountID, setImportAccountID] = useState('')
|
|
const [preview, setPreview] = useState<ImportPreviewResult | null>(null)
|
|
const [importError, setImportError] = useState<string | null>(null)
|
|
const [importMessage, setImportMessage] = useState<string | null>(null)
|
|
const [categoryOverrides, setCategoryOverrides] = useState<Record<string, number>>({})
|
|
|
|
const resetState = () => {
|
|
setImportFile(null)
|
|
setPreview(null)
|
|
setImportError(null)
|
|
setImportMessage(null)
|
|
}
|
|
|
|
const buildFormData = () => {
|
|
const formData = new FormData()
|
|
if (!importFile) throw new Error('请选择文件')
|
|
formData.append('file', importFile)
|
|
formData.append('source_kind', importSourceKind)
|
|
if (importAccountID) formData.append('account_id', importAccountID)
|
|
if (Object.keys(categoryOverrides).length) formData.append('category_overrides', JSON.stringify(categoryOverrides))
|
|
return formData
|
|
}
|
|
|
|
const previewMutation = useMutation({
|
|
mutationFn: () => api.previewImportTransactions(buildFormData()),
|
|
onMutate: () => setImportError(null),
|
|
onSuccess: (data) => {
|
|
setPreview(data)
|
|
setImportMessage(null)
|
|
},
|
|
onError: (e) => {
|
|
setPreview(null)
|
|
setImportError(e instanceof ApiError ? e.message : '预览失败')
|
|
},
|
|
})
|
|
|
|
const importMutation = useMutation({
|
|
mutationFn: () => api.importTransactions(buildFormData()),
|
|
onMutate: () => {
|
|
setImportError(null)
|
|
setImportMessage(null)
|
|
},
|
|
onSuccess: (result) => {
|
|
setImportMessage(`导入成功:新增 ${result.imported_count} 条,跳过重复 ${result.skipped_count} 条`)
|
|
setPreview(null)
|
|
onImported()
|
|
},
|
|
onError: (e) => {
|
|
setImportError(e instanceof ApiError ? e.message : '导入失败')
|
|
},
|
|
})
|
|
|
|
const handleOpenChange = (next: boolean) => {
|
|
if (!next) resetState()
|
|
onOpenChange(next)
|
|
}
|
|
|
|
const handleFileChange = (file: File | null) => {
|
|
setImportFile(file)
|
|
setPreview(null)
|
|
setImportMessage(null)
|
|
setCategoryOverrides({})
|
|
setImportError(null)
|
|
}
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
|
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
|
|
<DialogHeader>
|
|
<DialogTitle>导入账单</DialogTitle>
|
|
</DialogHeader>
|
|
<div className="app-form">
|
|
<div>
|
|
<label className="app-form-label">导入来源</label>
|
|
<select
|
|
value={importSourceKind}
|
|
onChange={(e) => {
|
|
setImportSourceKind(e.target.value as ImportSourceKind)
|
|
handleFileChange(null)
|
|
}}
|
|
className="app-select mt-1 w-full"
|
|
>
|
|
<option value="cmb_debit">招商银行储蓄卡(PDF 流水)</option>
|
|
<option value="cmb_credit">招商银行信用卡(PDF 账单)</option>
|
|
<option value="alipay">支付宝(CSV 账单)</option>
|
|
<option value="wechat">微信支付(CSV 账单)</option>
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<label className="app-form-label">
|
|
{importIsCSV(importSourceKind) ? '账单 CSV' : '账单 PDF'}
|
|
</label>
|
|
<Input
|
|
key={importSourceKind}
|
|
type="file"
|
|
accept={importIsCSV(importSourceKind) ? '.csv,text/csv' : 'application/pdf,.pdf'}
|
|
className="h-9 text-sm mt-1"
|
|
onChange={(e) => handleFileChange(e.target.files?.[0] ?? null)}
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label className="app-form-label">导入账户</label>
|
|
<select
|
|
value={importAccountID}
|
|
onChange={(e) => setImportAccountID(e.target.value)}
|
|
className="app-select-muted mt-1 w-full"
|
|
>
|
|
<option value="">自动匹配或创建账户</option>
|
|
{accounts
|
|
.filter((a) => sourceKindMatchesAccount(importSourceKind, a.type))
|
|
.map((a) => (
|
|
<option key={a.id} value={a.id}>{a.name}</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
|
|
{preview && (
|
|
<div className="rounded-md border border-border/80 bg-[#0c1016]/60 p-3 space-y-2">
|
|
<p className="text-xs text-muted">
|
|
解析 {preview.total_count} 条 · 预计新增 {preview.new_count} 条 · 重复跳过 {preview.duplicate_count} 条
|
|
</p>
|
|
<p className="text-xs text-foreground">
|
|
目标账户:{preview.account_name}
|
|
{preview.will_create_account && (
|
|
<span className="ml-1 text-primary">(将自动创建)</span>
|
|
)}
|
|
</p>
|
|
{preview.items.length > 0 && (
|
|
<ul className="max-h-80 space-y-1.5 overflow-y-auto text-xs">
|
|
{preview.items.map((item, i) => (
|
|
<li key={i} className="flex items-start justify-between gap-2 border-b border-border/40 pb-1.5 last:border-0">
|
|
<div className="min-w-0">
|
|
<p className="truncate text-foreground">{item.description || item.counterparty || '—'}</p>
|
|
<p className="text-muted">
|
|
{formatDate(item.date)}
|
|
{item.status === 'duplicate_database' ? ' · 数据库已有' : item.status === 'duplicate_file' ? ' · 文件内重复' : ''}
|
|
</p>
|
|
{item.status === 'new' && (
|
|
<div className="mt-1 flex items-center gap-2">
|
|
<select
|
|
value={categoryOverrides[item.source_key] ?? item.category_id}
|
|
onChange={(e) => setCategoryOverrides(p => ({ ...p, [item.source_key]: Number(e.target.value) }))}
|
|
className="app-select-muted h-7 max-w-40 text-xs"
|
|
>
|
|
{categories.filter(c => c.type === item.type && c.parent_id !== null && c.is_active).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
|
</select>
|
|
<span className="text-[11px] text-muted">{item.category_reason}</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
<AmountDisplay cents={item.amount} type={item.type} />
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
{preview.total_count > preview.items.length && (
|
|
<p className="text-[11px] text-muted">
|
|
仅展示前 {preview.items.length} 条样本,确认后将处理全部 {preview.total_count} 条。
|
|
</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{importError && <p className="app-error">{importError}</p>}
|
|
{importMessage && <p className="app-success">{importMessage}</p>}
|
|
|
|
<div className="flex gap-2">
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
className="flex-1"
|
|
disabled={!importFile || previewMutation.isPending || importMutation.isPending}
|
|
onClick={() => previewMutation.mutate()}
|
|
>
|
|
{previewMutation.isPending ? '解析中...' : '预览'}
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
className="flex-1"
|
|
disabled={!importFile || !preview || preview.new_count === 0 || importMutation.isPending}
|
|
onClick={() => importMutation.mutate()}
|
|
>
|
|
{importMutation.isPending ? '导入中...' : `确认导入${preview ? ` (${preview.new_count})` : ''}`}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|