feat(ui): 增加历史价格批量导入解析功能与底层 Upsert 接口

This commit is contained in:
kennethcheng 2026-04-30 10:25:09 +08:00
parent 108023ae67
commit 209cdd3625
3 changed files with 181 additions and 15 deletions

View File

@ -126,4 +126,11 @@
- 資產卡片全新字段:現價、市值、持倉、攤薄/成本(合併為 `[dilutedCostNative] / [avgCostNative]` 格式)、浮動盈虧(帶百分比)、累計盈虧(帶百分比)、持倉天數。
- 盈虧顏色遵循中國市場慣例:大於 0 顯示紅色,小於 0 顯示綠色。
- 所有百分比保留 2 位小數0 值正常顯示 `0.00`
- 卡片佈局優化為響應式 `grid-cols-1 md:grid-cols-2 lg:grid-cols-3`
- 卡片佈局優化為響應式 `grid-cols-1 md:grid-cols-2 lg:grid-cols-3`
## 基於文本域粘貼的歷史價格批量導入功能 (Bulk Import, Task 49)
- 開發了基於文本域粘貼的歷史價格批量導入功能,支持從 Excel 快速複製錄入每日淨價。
- 在 `src/actions/market.ts` 中新增 `importHistoricalPrices(assetId, data)` Server Action遍歷數據數組對 `assetPricesHistory` 表執行批量 Upsert基於 `(assetId, date)` 聯合唯一索引的 `onConflictDoUpdate`),衝突時用新價格覆蓋舊價格。
- 前端 `app/dashboard/page.tsx` 的持倉明細表「操作」列與展開區域均新增【導入價格】按鈕。
- 點擊按鈕彈出 Dialog內含 `<textarea>` 文本域,支持用戶從 Excel 直接複製粘貼,格式為 `YYYY-MM-DD, 價格`(每行一條)。
- 前端按換行和逗號解析文本,生成 `{date, price}` 數組後調用 `importHistoricalPrices` Action導入完成後 Toast 提示成功/失敗條數並刷新頁面。

View File

@ -30,7 +30,8 @@ import { SyncButton } from '@/components/assets/sync-button';
import { AddTransactionDialog } from '@/components/transactions/add-transaction-dialog';
import { UpdateTransactionDialog } from '@/components/transactions/update-transaction-dialog';
import { deleteTransaction } from '@/actions/transaction';
import { ChevronDown, ChevronUp, Plus, Edit3, Trash2 } from 'lucide-react';
import { importHistoricalPrices } from '@/actions/market';
import { ChevronDown, ChevronUp, Plus, Edit3, Trash2, Upload } from 'lucide-react';
import Big from 'big.js';
const txTypeMap: Record<string, string> = {
@ -87,6 +88,9 @@ export default function DashboardPage() {
const [updateTarget, setUpdateTarget] = useState<any>(null);
const [deleteTarget, setDeleteTarget] = useState<any>(null);
const [snapshots, setSnapshots] = useState<any[]>([]);
const [importDialogOpen, setImportDialogOpen] = useState(false);
const [importAssetId, setImportAssetId] = useState<string>('');
const [importText, setImportText] = useState('');
useEffect(() => {
async function loadData() {
@ -141,6 +145,46 @@ export default function DashboardPage() {
});
}
function handleOpenImportDialog(assetId: string) {
setImportAssetId(assetId);
setImportText('');
setImportDialogOpen(true);
}
function handleImportSubmit() {
startTransition(async () => {
const lines = importText.split('\n').filter(l => l.trim());
const data: Array<{ date: string; price: string }> = [];
for (const line of lines) {
const parts = line.split(',');
if (parts.length >= 2) {
const date = parts[0].trim();
const price = parts[1].trim();
if (date && price) {
data.push({ date, price });
}
}
}
if (data.length === 0) {
toast.error('未解析到有效數據,請檢查格式');
setImportDialogOpen(false);
return;
}
const result = await importHistoricalPrices(importAssetId, data);
if (result.success) {
toast.success(`成功導入 ${result.imported} 條價格記錄` + (result.errors ? `${result.errors} 條失敗` : ''));
setImportText('');
setImportDialogOpen(false);
window.location.reload();
} else {
toast.error(result.error || '導入失敗');
}
});
}
const formattedTotal = formatAmount(totalCnyValue);
const formattedTotalPnl = formatAmount(totalPnlCny);
const formattedUnrealized = formatAmount(unrealizedPnlCny);
@ -271,6 +315,18 @@ export default function DashboardPage() {
<Plus className="h-3 w-3 mr-1" />
</Button>
<Button
size="sm"
variant="ghost"
className="h-7 px-2 text-xs"
onClick={(e) => {
e.stopPropagation();
handleOpenImportDialog(pos.assetId);
}}
>
<Upload className="h-3 w-3 mr-1" />
</Button>
</div>
</TableCell>
</TableRow>
@ -281,18 +337,32 @@ export default function DashboardPage() {
<div className="space-y-2">
<div className="flex items-center justify-between pb-2 border-b border-border/50">
<span className="text-sm font-semibold text-foreground"></span>
<Button
size="sm"
variant="outline"
className="h-7 px-2 text-xs"
onClick={(e) => {
e.stopPropagation();
handleOpenDialog(pos.assetId);
}}
>
<Plus className="h-3 w-3 mr-1" />
</Button>
<div className="flex items-center gap-1">
<Button
size="sm"
variant="outline"
className="h-7 px-2 text-xs"
onClick={(e) => {
e.stopPropagation();
handleOpenDialog(pos.assetId);
}}
>
<Plus className="h-3 w-3 mr-1" />
</Button>
<Button
size="sm"
variant="outline"
className="h-7 px-2 text-xs"
onClick={(e) => {
e.stopPropagation();
handleOpenImportDialog(pos.assetId);
}}
>
<Upload className="h-3 w-3 mr-1" />
</Button>
</div>
</div>
{pos.transactions && pos.transactions.length > 0 ? (
<Table>
@ -437,6 +507,39 @@ export default function DashboardPage() {
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={importDialogOpen} onOpenChange={setImportDialogOpen}>
<DialogContent className="sm:max-w-[550px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
Excel ,
</DialogDescription>
</DialogHeader>
<div className="space-y-3 py-2">
<textarea
value={importText}
onChange={(e) => setImportText(e.target.value)}
placeholder={`2026-04-01, 150.5\n2026-04-02, 151.2\n2026-04-03, 149.8`}
className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring min-h-[180px] font-mono text-sm resize-y"
/>
<p className="text-xs text-muted-foreground">
Excel `日期, 價格` `YYYY-MM-DD`
</p>
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setImportDialogOpen(false)}>
</Button>
<Button
onClick={handleImportSubmit}
disabled={isPending || !importText.trim()}
>
{isPending ? '導入中...' : '開始導入'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -2,9 +2,10 @@
import { ProxyAgent, setGlobalDispatcher } from 'undici';
import { db } from '@/db';
import { assets } from '@/db/schema';
import { assets, assetPricesHistory } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { revalidatePath } from 'next/cache';
import { onConflictDoUpdate } from 'drizzle-orm/pg-core';
function getTencentSymbol(asset: { symbol: string; exchange: string | null }): string {
const cleanSymbol = asset.symbol.trim().toUpperCase().replace(/[^0-9A-Z]/g, '');
@ -80,3 +81,58 @@ export async function syncAllMarketPrices() {
return { success: true, count: successCount };
}
export async function importHistoricalPrices(
assetId: string,
data: Array<{ date: string; price: string }>
) {
if (!assetId || !data || data.length === 0) {
return { success: false, error: '參數不完整' };
}
let successCount = 0;
let errorCount = 0;
for (const row of data) {
try {
const parsedDate = row.date.trim();
const parsedPrice = row.price.trim();
if (!parsedDate || !parsedPrice) continue;
const priceNum = Number(parsedPrice);
if (isNaN(priceNum) || priceNum < 0) continue;
const dateMatch = parsedDate.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (!dateMatch) continue;
const normalizedDate = `${dateMatch[1]}-${dateMatch[2]}-${dateMatch[3]}`;
await db
.insert(assetPricesHistory)
.values({
assetId,
price: parsedPrice,
date: normalizedDate,
})
.onConflictDoUpdate({
target: [assetPricesHistory.assetId, assetPricesHistory.date],
set: { price: parsedPrice },
});
successCount++;
} catch (error) {
errorCount++;
console.warn(`[批量導入] 導入 ${row.date} 失敗:`, error);
}
}
revalidatePath('/dashboard');
revalidatePath('/dashboard/assets');
return {
success: true,
imported: successCount,
errors: errorCount,
};
}