Compare commits
2 Commits
838bb0ef95
...
209cdd3625
| Author | SHA1 | Date | |
|---|---|---|---|
| 209cdd3625 | |||
| 108023ae67 |
10
Memory.md
10
Memory.md
@ -12,6 +12,7 @@
|
||||
- `assets` 表完成多次业务演进:新增 `latestPrice` (支持现价追踪)、`exchange` (显式交易所绑定) 以及 `name` (中文名称解析) 字段。
|
||||
- `exchange_rates` (汇率表) 已建立,支持联合主键与跨币种交叉汇率架构。
|
||||
- **引入 `portfolio_snapshots` 表**:用于每日记录投资组合快照,字段包括 `date` (唯一日期)、`total_value_cny` (当日总市值)、`total_cost_cny` (当日总投入本金),为历史净值走势图奠定底层数据结构。
|
||||
- **新增 `asset_prices_history` 表**:用于存储手动导入的每日标的价格,字段包括 `assetId` (关联资产)、`price` (当日收盘价/净值,numeric(36,18))、`date` (YYYY-MM-DD 格式)、`createdAt`,并对 `(assetId, date)` 建立联合唯一索引,为手动导入历史净值提供底层 Upsert 支持。
|
||||
|
||||
## 核心业务与服务端逻辑 (Server Actions)
|
||||
- 完成高精度交易流水与资产的 Server Actions 开发,成功实现字符串级别的高精度防腐层拦截(基于 Zod & Big.js)。
|
||||
@ -125,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 提示成功/失敗條數並刷新頁面。
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
10
drizzle/0004_glamorous_stranger.sql
Normal file
10
drizzle/0004_glamorous_stranger.sql
Normal file
@ -0,0 +1,10 @@
|
||||
CREATE TABLE "asset_prices_history" (
|
||||
"id" uuid PRIMARY KEY NOT NULL,
|
||||
"asset_id" uuid NOT NULL,
|
||||
"price" numeric(36, 18) NOT NULL,
|
||||
"date" date NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "asset_prices_history" ADD CONSTRAINT "asset_prices_history_asset_id_assets_id_fk" FOREIGN KEY ("asset_id") REFERENCES "public"."assets"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "asset_price_date_idx" ON "asset_prices_history" USING btree ("asset_id","date");
|
||||
455
drizzle/meta/0004_snapshot.json
Normal file
455
drizzle/meta/0004_snapshot.json
Normal file
@ -0,0 +1,455 @@
|
||||
{
|
||||
"id": "d95996ac-d802-4b08-83db-20ff0e9e64f7",
|
||||
"prevId": "26b392bf-03db-4f71-86d5-395d5c07fae5",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.asset_prices_history": {
|
||||
"name": "asset_prices_history",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"price": {
|
||||
"name": "price",
|
||||
"type": "numeric(36, 18)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"date": {
|
||||
"name": "date",
|
||||
"type": "date",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"asset_price_date_idx": {
|
||||
"name": "asset_price_date_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "asset_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "date",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"asset_prices_history_asset_id_assets_id_fk": {
|
||||
"name": "asset_prices_history_asset_id_assets_id_fk",
|
||||
"tableFrom": "asset_prices_history",
|
||||
"tableTo": "assets",
|
||||
"columnsFrom": [
|
||||
"asset_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.assets": {
|
||||
"name": "assets",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"symbol": {
|
||||
"name": "symbol",
|
||||
"type": "varchar(20)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "varchar(100)",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
"type": "asset_type_enum",
|
||||
"typeSchema": "public",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"exchange": {
|
||||
"name": "exchange",
|
||||
"type": "varchar(10)",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "'US'"
|
||||
},
|
||||
"base_currency": {
|
||||
"name": "base_currency",
|
||||
"type": "varchar(10)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"latest_price": {
|
||||
"name": "latest_price",
|
||||
"type": "numeric(36, 18)",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'0'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"assets_symbol_unique": {
|
||||
"name": "assets_symbol_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"symbol"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.exchange_rates": {
|
||||
"name": "exchange_rates",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"from_currency": {
|
||||
"name": "from_currency",
|
||||
"type": "varchar(10)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"to_currency": {
|
||||
"name": "to_currency",
|
||||
"type": "varchar(10)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"rate": {
|
||||
"name": "rate",
|
||||
"type": "numeric(20, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"currency_pair_idx": {
|
||||
"name": "currency_pair_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "from_currency",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "to_currency",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.portfolio_snapshots": {
|
||||
"name": "portfolio_snapshots",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"date": {
|
||||
"name": "date",
|
||||
"type": "date",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"total_value_cny": {
|
||||
"name": "total_value_cny",
|
||||
"type": "numeric(36, 18)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"total_cost_cny": {
|
||||
"name": "total_cost_cny",
|
||||
"type": "numeric(36, 18)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"portfolio_snapshots_date_unique": {
|
||||
"name": "portfolio_snapshots_date_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"date"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.transactions": {
|
||||
"name": "transactions",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"asset_id": {
|
||||
"name": "asset_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"tx_type": {
|
||||
"name": "tx_type",
|
||||
"type": "transaction_type_enum",
|
||||
"typeSchema": "public",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"quantity": {
|
||||
"name": "quantity",
|
||||
"type": "numeric(36, 18)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"price": {
|
||||
"name": "price",
|
||||
"type": "numeric(36, 18)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"fee": {
|
||||
"name": "fee",
|
||||
"type": "numeric(36, 18)",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'0'"
|
||||
},
|
||||
"tx_currency": {
|
||||
"name": "tx_currency",
|
||||
"type": "varchar(10)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"exchange_rate": {
|
||||
"name": "exchange_rate",
|
||||
"type": "numeric(20, 8)",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'1'"
|
||||
},
|
||||
"executed_at": {
|
||||
"name": "executed_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"transactions_asset_id_assets_id_fk": {
|
||||
"name": "transactions_asset_id_assets_id_fk",
|
||||
"tableFrom": "transactions",
|
||||
"tableTo": "assets",
|
||||
"columnsFrom": [
|
||||
"asset_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.users": {
|
||||
"name": "users",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"username": {
|
||||
"name": "username",
|
||||
"type": "varchar(50)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"password_hash": {
|
||||
"name": "password_hash",
|
||||
"type": "varchar(255)",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"users_username_unique": {
|
||||
"name": "users_username_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"username"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
}
|
||||
},
|
||||
"enums": {
|
||||
"public.asset_type_enum": {
|
||||
"name": "asset_type_enum",
|
||||
"schema": "public",
|
||||
"values": [
|
||||
"STOCK",
|
||||
"CRYPTO",
|
||||
"CASH"
|
||||
]
|
||||
},
|
||||
"public.transaction_type_enum": {
|
||||
"name": "transaction_type_enum",
|
||||
"schema": "public",
|
||||
"values": [
|
||||
"BUY",
|
||||
"SELL",
|
||||
"DIVIDEND",
|
||||
"AIRDROP",
|
||||
"FEE"
|
||||
]
|
||||
}
|
||||
},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"roles": {},
|
||||
"policies": {},
|
||||
"views": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@ -29,6 +29,13 @@
|
||||
"when": 1777433725731,
|
||||
"tag": "0003_watery_xorn",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1777514678798,
|
||||
"tag": "0004_glamorous_stranger",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@ -78,3 +78,17 @@ export const portfolioSnapshots = pgTable("portfolio_snapshots", {
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
});
|
||||
|
||||
export const assetPricesHistory = pgTable("asset_prices_history", {
|
||||
id: uuid("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
|
||||
assetId: uuid("asset_id")
|
||||
.notNull()
|
||||
.references(() => assets.id),
|
||||
price: numeric("price", { precision: 36, scale: 18 }).notNull(),
|
||||
date: date("date", { mode: "string" }).notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true, mode: "date" })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
}, (table) => [
|
||||
uniqueIndex("asset_price_date_idx").on(table.assetId, table.date),
|
||||
]);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user