feat(ledger): 引入 latestPrice 字段与历史成本追踪,实装 P&L 盈亏计算引擎

This commit is contained in:
kennethcheng 2026-04-28 00:57:33 +08:00
parent 27c3b76bba
commit b9186d4699
6 changed files with 241 additions and 101 deletions

View File

@ -1,5 +1,6 @@
import { getAssets } from '@/actions/asset';
import { AddAssetDialog } from '@/components/assets/add-asset-dialog';
import { UpdatePriceDialog } from '@/components/assets/update-price-dialog';
import {
Table,
TableBody,
@ -15,33 +16,35 @@ export default async function AssetsPage() {
const typeLabels: Record<string, string> = {
STOCK: '股票',
CRYPTO: '加密货币',
CASH: '金',
CRYPTO: '加密貨幣',
CASH: '金',
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold"></h1>
<h1 className="text-2xl font-bold"></h1>
<AddAssetDialog />
</div>
<div className="rounded-md border">
<Table>
<TableCaption></TableCaption>
<TableCaption></TableCaption>
<TableHeader>
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead> (Latest Price)</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{assets.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="text-center text-muted-foreground">
"添加资产"
<TableCell colSpan={6} className="text-center text-muted-foreground">
"添加資產"
</TableCell>
</TableRow>
) : (
@ -50,11 +53,15 @@ export default async function AssetsPage() {
<TableCell className="font-medium">{asset.symbol}</TableCell>
<TableCell>{typeLabels[asset.type] || asset.type}</TableCell>
<TableCell>{asset.baseCurrency}</TableCell>
<TableCell>{asset.latestPrice}</TableCell>
<TableCell>
{asset.createdAt
? new Date(asset.createdAt).toLocaleString('zh-CN')
: '-'}
</TableCell>
<TableCell>
<UpdatePriceDialog assetId={asset.id} currentPrice={asset.latestPrice || '0'} />
</TableCell>
</TableRow>
))
)}

View File

@ -2,6 +2,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { getPortfolioSummary } from '@/actions/portfolio';
import { formatQuantity, formatAmount } from '@/lib/formatters';
import AllocationChart from '@/components/dashboard/allocation-chart';
import Big from 'big.js';
const CHART_COLORS = [
'#3b82f6',
@ -13,9 +14,11 @@ const CHART_COLORS = [
];
export default async function DashboardPage() {
const { positions, totalCnyValue, chartData } = await getPortfolioSummary();
const { positions, totalCnyValue, chartData, totalPnlCny } = await getPortfolioSummary();
const formattedTotal = formatAmount(totalCnyValue);
const formattedPnl = formatAmount(totalPnlCny);
const pnlIsPositive = new Big(totalPnlCny).gte(0);
const displayChartData = chartData.map((item) => ({
...item,
@ -42,6 +45,12 @@ export default async function DashboardPage() {
(CNY)
</span>
</div>
<div className="mt-2 flex items-center gap-2">
<span className="text-sm text-muted-foreground">:</span>
<span className={`text-lg font-semibold ${pnlIsPositive ? 'text-green-500' : 'text-red-500'}`}>
{pnlIsPositive ? '+' : ''}{formattedPnl}
</span>
</div>
</CardContent>
</Card>
@ -53,38 +62,56 @@ export default async function DashboardPage() {
</CardContent>
</Card>
) : (
positions.map((pos) => (
<Card key={pos.assetId}>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<span>{pos.symbol}</span>
<span className="text-sm font-normal text-muted-foreground">
{pos.type}
</span>
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-muted-foreground"></span>
<span className="font-medium">
{formatQuantity(pos.quantity, pos.type)}
positions.map((pos) => {
const posPnl = new Big(pos.pnlCny);
const posPnlPositive = posPnl.gte(0);
const formattedPosPnl = formatAmount(pos.pnlCny);
return (
<Card key={pos.assetId}>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<span>{pos.symbol}</span>
<span className="text-sm font-normal text-muted-foreground">
{pos.type}
</span>
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-muted-foreground"></span>
<span className="font-medium">
{formatQuantity(pos.quantity, pos.type)}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground"></span>
<span className="font-medium">{pos.baseCurrency}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">CNY </span>
<span className="font-medium text-green-600">
¥{formatAmount(pos.cnyValue)}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground"> (CNY)</span>
<span className="font-medium">
¥{formatAmount(pos.totalCostCny)}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground"></span>
<span className={`font-semibold ${posPnlPositive ? 'text-green-500' : 'text-red-500'}`}>
{posPnlPositive ? '+' : ''}{formattedPosPnl}
</span>
</div>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground"></span>
<span className="font-medium">{pos.baseCurrency}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">CNY </span>
<span className="font-medium text-green-600">
¥{formatAmount(pos.cnyValue)}
</span>
</div>
</div>
</CardContent>
</Card>
))
</CardContent>
</Card>
);
})
)}
</div>

View File

@ -2,6 +2,8 @@
import { db } from '@/db';
import { assets, assetTypeEnum } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { revalidatePath } from 'next/cache';
import { z } from 'zod';
const createAssetSchema = z.object({
@ -35,3 +37,23 @@ export async function createAsset(params: z.infer<typeof createAssetSchema>) {
export async function getAssets() {
return db.select().from(assets);
}
const updatePriceSchema = z.object({
assetId: z.string().min(1, 'Asset ID is required'),
newPrice: z.string().min(1, 'Price is required'),
});
export async function updateAssetPrice(params: z.infer<typeof updatePriceSchema>) {
const validation = updatePriceSchema.safeParse(params);
if (!validation.success) {
return { success: false, error: validation.error.issues[0].message };
}
try {
await db.update(assets).set({ latestPrice: params.newPrice }).where(eq(assets.id, params.assetId));
revalidatePath('/dashboard');
return { success: true };
} catch (error: unknown) {
throw error;
}
}

View File

@ -12,6 +12,8 @@ interface Position {
quantity: string;
baseCurrency: string;
cnyValue: string;
totalCostCny: string;
pnlCny: string;
}
interface RawRate {
@ -38,19 +40,21 @@ function getRate(
return null;
}
function calculateCnyValue(
function calculateCnyValueFromPrice(
quantity: Big,
latestPrice: string,
baseCurrency: string,
rateMap: Map<string, string>,
cryptoPrices: Map<string, string>
rateMap: Map<string, string>
): Big {
const price = new Big(latestPrice || '0');
if (baseCurrency === 'CNY') {
return quantity;
return quantity.times(price);
}
const directRate = getRate(rateMap, baseCurrency, 'CNY');
if (directRate) {
return quantity.times(directRate);
return quantity.times(price).times(directRate);
}
const usdToCny = getRate(rateMap, 'USD', 'CNY');
@ -58,17 +62,9 @@ function calculateCnyValue(
return new Big('0');
}
const priceKey = `${baseCurrency}_USD`;
const cryptoPrice = cryptoPrices.get(priceKey);
if (cryptoPrice) {
const usdValue = quantity.times(cryptoPrice);
return usdValue.times(usdToCny);
}
const usdRate = getRate(rateMap, baseCurrency, 'USD');
if (usdRate) {
const usdValue = quantity.times(usdRate);
return usdValue.times(usdToCny);
return quantity.times(price).times(usdRate).times(usdToCny);
}
return new Big('0');
@ -79,11 +75,13 @@ export async function getPortfolioPositions(): Promise<Position[]> {
.select({
txType: transactions.txType,
quantity: transactions.quantity,
price: transactions.price,
exchangeRate: transactions.exchangeRate,
assetId: transactions.assetId,
assetSymbol: assets.symbol,
assetType: assets.type,
assetBaseCurrency: assets.baseCurrency,
assetPrice: transactions.price,
assetLatestPrice: assets.latestPrice,
})
.from(transactions)
.leftJoin(assets, eq(assets.id, transactions.assetId))
@ -96,6 +94,7 @@ export async function getPortfolioPositions(): Promise<Position[]> {
quantity: Big;
baseCurrency: string;
latestPrice: string;
totalCostCny: Big;
}>();
for (const tx of allTransactions) {
@ -109,22 +108,28 @@ export async function getPortfolioPositions(): Promise<Position[]> {
type: tx.assetType || 'CASH',
quantity: new Big('0'),
baseCurrency: tx.assetBaseCurrency || '',
latestPrice: tx.assetPrice || '0',
latestPrice: tx.assetLatestPrice || '0',
totalCostCny: new Big('0'),
});
}
const holding = holdings.get(tx.assetId)!;
if (tx.txType === 'BUY' || tx.txType === 'AIRDROP') {
if (tx.txType === 'BUY') {
holding.quantity = holding.quantity.plus(tx.quantity);
const costPerUnit = tx.quantity.times(tx.price);
const costCny = costPerUnit.times(tx.exchangeRate || '1');
holding.totalCostCny = holding.totalCostCny.plus(costCny);
} else if (tx.txType === 'SELL') {
holding.quantity = holding.quantity.minus(tx.quantity);
} else if (tx.txType === 'AIRDROP') {
holding.quantity = holding.quantity.plus(tx.quantity);
} else if (tx.txType === 'DIVIDEND') {
holding.quantity = holding.quantity.plus(tx.quantity);
}
if (tx.assetPrice) {
holding.latestPrice = tx.assetPrice;
if (tx.assetLatestPrice) {
holding.latestPrice = tx.assetLatestPrice;
}
}
@ -136,56 +141,25 @@ export async function getPortfolioPositions(): Promise<Position[]> {
const rateMap = buildRateMap(rates);
const cryptoSymbols = new Set(['BTC', 'ETH', 'SOL', 'BNB', 'XRP', 'ADA', 'DOGE', 'AVAX', 'MATIC', 'DOT']);
const cryptoPrices = new Map<string, string>();
for (const [_, holding] of holdings) {
if (holding.type === 'CRYPTO' && cryptoSymbols.has(holding.symbol.toUpperCase())) {
const priceKey = `${holding.symbol}_USD`;
const usdRate = getRate(rateMap, holding.symbol, 'USD');
if (usdRate) {
cryptoPrices.set(priceKey, usdRate);
}
}
}
const result: Position[] = [];
let totalCnyValue = new Big('0');
let totalPnlCny = new Big('0');
for (const [_, holding] of holdings) {
if (holding.quantity.lte(0)) continue;
let cnyValue: Big;
if (holding.type === 'CRYPTO') {
const symbol = holding.symbol.toUpperCase();
const btcToUsd = getRate(rateMap, symbol, 'USD');
const usdToCny = getRate(rateMap, 'USD', 'CNY');
if (btcToUsd && usdToCny) {
const usdValue = holding.quantity.times(holding.latestPrice || '1');
cnyValue = usdValue.times(usdToCny);
} else {
cnyValue = new Big('0');
}
} else if (holding.baseCurrency === 'CNY') {
cnyValue = holding.quantity.times(holding.latestPrice || '1');
} else {
const directRate = getRate(rateMap, holding.baseCurrency, 'CNY');
if (directRate) {
cnyValue = holding.quantity.times(holding.latestPrice || '1').times(directRate);
} else {
const usdRate = getRate(rateMap, holding.baseCurrency, 'USD');
const usdToCny = getRate(rateMap, 'USD', 'CNY');
if (usdRate && usdToCny) {
cnyValue = holding.quantity.times(holding.latestPrice || '1').times(usdRate).times(usdToCny);
} else {
cnyValue = new Big('0');
}
}
}
const cnyValue = calculateCnyValueFromPrice(
holding.quantity,
holding.latestPrice,
holding.baseCurrency,
rateMap
);
totalCnyValue = totalCnyValue.plus(cnyValue);
const pnlCny = cnyValue.minus(holding.totalCostCny);
totalPnlCny = totalPnlCny.plus(pnlCny);
result.push({
assetId: holding.assetId,
symbol: holding.symbol,
@ -193,6 +167,8 @@ export async function getPortfolioPositions(): Promise<Position[]> {
quantity: holding.quantity.toString(),
baseCurrency: holding.baseCurrency,
cnyValue: cnyValue.toString(),
totalCostCny: holding.totalCostCny.toString(),
pnlCny: pnlCny.toString(),
});
}
@ -207,6 +183,11 @@ export async function getPortfolioSummary() {
new Big('0')
);
const totalPnlCny = positions.reduce(
(sum, pos) => sum.plus(new Big(pos.pnlCny)),
new Big('0')
);
const chartData = positions.map((pos, index) => ({
name: pos.symbol,
value: new Big(pos.cnyValue),
@ -223,6 +204,7 @@ export async function getPortfolioSummary() {
return {
positions,
totalCnyValue: totalCnyValue.toString(),
totalPnlCny: totalPnlCny.toString(),
chartData,
};
}

View File

@ -0,0 +1,101 @@
'use client';
import { useState, useTransition } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { useRouter } from 'next/navigation';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { RefreshCw } from 'lucide-react';
import { updateAssetPrice } from '@/actions/asset';
const updatePriceSchema = z.object({
newPrice: z.string().min(1, '價格不能為空'),
});
type UpdatePriceForm = z.infer<typeof updatePriceSchema>;
interface UpdatePriceDialogProps {
assetId: string;
currentPrice: string;
}
export function UpdatePriceDialog({ assetId, currentPrice }: UpdatePriceDialogProps) {
const [open, setOpen] = useState(false);
const [isPending, startTransition] = useTransition();
const router = useRouter();
const form = useForm<UpdatePriceForm>({
resolver: zodResolver(updatePriceSchema),
defaultValues: {
newPrice: currentPrice,
},
});
function onSubmit(values: UpdatePriceForm) {
startTransition(async () => {
await updateAssetPrice({ assetId, newPrice: values.newPrice });
setOpen(false);
router.refresh();
});
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm">
<RefreshCw className="h-3 w-3 mr-1" />
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="newPrice"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input placeholder="輸入價格數值" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<Button type="submit" disabled={isPending}>
{isPending ? '提交中...' : '確認更新'}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}

View File

@ -20,6 +20,7 @@ export const assets = pgTable("assets", {
symbol: varchar("symbol", { length: 20 }).notNull().unique(),
type: assetTypeEnum("type").notNull(),
baseCurrency: varchar("base_currency", { length: 10 }).notNull(),
latestPrice: numeric("latest_price", { precision: 36, scale: 18 }).default('0').notNull(),
createdAt: timestamp("created_at", { withTimezone: true, mode: "date" })
.defaultNow(),
});