feat(charge-points): add pricing mode for charge points with validation
feat(pricing): implement tariff management with peak, valley, and flat pricing feat(api): add tariff API for fetching and updating pricing configurations feat(tariff-schema): create database schema for tariff configuration feat(pricing-page): create UI for displaying and managing pricing tiers fix(sidebar): update sidebar to include pricing settings link
This commit is contained in:
@@ -78,6 +78,7 @@ type EditForm = {
|
||||
chargePointVendor: string;
|
||||
chargePointModel: string;
|
||||
registrationStatus: "Accepted" | "Pending" | "Rejected";
|
||||
pricingMode: "fixed" | "tou";
|
||||
feePerKwh: string;
|
||||
};
|
||||
|
||||
@@ -96,6 +97,7 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
chargePointVendor: "",
|
||||
chargePointModel: "",
|
||||
registrationStatus: "Pending",
|
||||
pricingMode: "fixed",
|
||||
feePerKwh: "0",
|
||||
});
|
||||
|
||||
@@ -121,6 +123,7 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
chargePointVendor: cp.chargePointVendor ?? "",
|
||||
chargePointModel: cp.chargePointModel ?? "",
|
||||
registrationStatus: cp.registrationStatus as EditForm["registrationStatus"],
|
||||
pricingMode: cp.pricingMode,
|
||||
feePerKwh: String(cp.feePerKwh),
|
||||
});
|
||||
setEditOpen(true);
|
||||
@@ -135,7 +138,8 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
chargePointVendor: editForm.chargePointVendor,
|
||||
chargePointModel: editForm.chargePointModel,
|
||||
registrationStatus: editForm.registrationStatus,
|
||||
feePerKwh: fee,
|
||||
pricingMode: editForm.pricingMode,
|
||||
feePerKwh: editForm.pricingMode === "fixed" ? fee : 0,
|
||||
});
|
||||
await cpQuery.refetch();
|
||||
setEditOpen(false);
|
||||
@@ -309,7 +313,9 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
<div className="flex items-center justify-between gap-4 py-2">
|
||||
<dt className="shrink-0 text-sm text-muted">电价</dt>
|
||||
<dd className="text-sm text-foreground">
|
||||
{cp.feePerKwh > 0 ? (
|
||||
{cp.pricingMode === "tou" ? (
|
||||
<span className="text-accent font-medium">峰谷电价</span>
|
||||
) : cp.feePerKwh > 0 ? (
|
||||
<span>
|
||||
{cp.feePerKwh} 分/kWh
|
||||
<span className="ml-1 text-xs text-muted">
|
||||
@@ -373,7 +379,9 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
<div className="flex items-center justify-between gap-4 py-2">
|
||||
<dt className="shrink-0 text-sm text-muted">单位电价</dt>
|
||||
<dd className="text-sm text-foreground">
|
||||
{cp.feePerKwh > 0 ? (
|
||||
{cp.pricingMode === "tou" ? (
|
||||
<span className="text-accent font-medium">峰谷电价</span>
|
||||
) : cp.feePerKwh > 0 ? (
|
||||
<span>
|
||||
<span className="font-semibold">¥{(cp.feePerKwh / 100).toFixed(2)}</span>
|
||||
<span className="ml-1 text-xs text-muted">/kWh</span>
|
||||
@@ -601,8 +609,33 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
</Select.Popover>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-sm font-medium">计费模式</Label>
|
||||
<Select
|
||||
fullWidth
|
||||
selectedKey={editForm.pricingMode}
|
||||
onSelectionChange={(key) =>
|
||||
setEditForm((f) => ({
|
||||
...f,
|
||||
pricingMode: String(key) as EditForm["pricingMode"],
|
||||
}))
|
||||
}
|
||||
>
|
||||
<Select.Trigger>
|
||||
<Select.Value />
|
||||
<Select.Indicator />
|
||||
</Select.Trigger>
|
||||
<Select.Popover>
|
||||
<ListBox>
|
||||
<ListBox.Item id="fixed">固定电价</ListBox.Item>
|
||||
<ListBox.Item id="tou">峰谷电价</ListBox.Item>
|
||||
</ListBox>
|
||||
</Select.Popover>
|
||||
</Select>
|
||||
</div>
|
||||
{editForm.pricingMode === "fixed" && (
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">电价(分/kWh)</Label>
|
||||
<Label className="text-sm font-medium">固定电价(分/kWh)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
@@ -612,6 +645,7 @@ export default function ChargePointDetailPage({ params }: { params: Promise<{ id
|
||||
onChange={(e) => setEditForm((f) => ({ ...f, feePerKwh: e.target.value }))}
|
||||
/>
|
||||
</TextField>
|
||||
)}
|
||||
</Modal.Body>
|
||||
<Modal.Footer className="flex justify-end gap-2">
|
||||
<Button variant="ghost" onPress={() => setEditOpen(false)}>
|
||||
|
||||
@@ -100,6 +100,7 @@ type FormData = {
|
||||
chargePointVendor: string;
|
||||
chargePointModel: string;
|
||||
registrationStatus: "Accepted" | "Pending" | "Rejected";
|
||||
pricingMode: "fixed" | "tou";
|
||||
feePerKwh: string;
|
||||
};
|
||||
|
||||
@@ -108,6 +109,7 @@ const EMPTY_FORM: FormData = {
|
||||
chargePointVendor: "",
|
||||
chargePointModel: "",
|
||||
registrationStatus: "Pending",
|
||||
pricingMode: "fixed",
|
||||
feePerKwh: "0",
|
||||
};
|
||||
|
||||
@@ -142,6 +144,7 @@ export default function ChargePointsPage() {
|
||||
chargePointVendor: cp.chargePointVendor ?? "",
|
||||
chargePointModel: cp.chargePointModel ?? "",
|
||||
registrationStatus: cp.registrationStatus as FormData["registrationStatus"],
|
||||
pricingMode: cp.pricingMode,
|
||||
feePerKwh: String(cp.feePerKwh),
|
||||
});
|
||||
setFormOpen(true);
|
||||
@@ -158,7 +161,8 @@ export default function ChargePointsPage() {
|
||||
chargePointVendor: formData.chargePointVendor,
|
||||
chargePointModel: formData.chargePointModel,
|
||||
registrationStatus: formData.registrationStatus,
|
||||
feePerKwh: fee,
|
||||
pricingMode: formData.pricingMode,
|
||||
feePerKwh: formData.pricingMode === "fixed" ? fee : 0,
|
||||
});
|
||||
} else {
|
||||
// Create
|
||||
@@ -167,7 +171,8 @@ export default function ChargePointsPage() {
|
||||
chargePointVendor: formData.chargePointVendor.trim() || undefined,
|
||||
chargePointModel: formData.chargePointModel.trim() || undefined,
|
||||
registrationStatus: formData.registrationStatus,
|
||||
feePerKwh: fee,
|
||||
pricingMode: formData.pricingMode,
|
||||
feePerKwh: formData.pricingMode === "fixed" ? fee : 0,
|
||||
});
|
||||
}
|
||||
await refetchList();
|
||||
@@ -300,17 +305,45 @@ export default function ChargePointsPage() {
|
||||
</Select.Popover>
|
||||
</Select>
|
||||
</div>
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">电价(分/kWh)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
placeholder="0"
|
||||
value={formData.feePerKwh}
|
||||
onChange={(e) => setFormData((f) => ({ ...f, feePerKwh: e.target.value }))}
|
||||
/>
|
||||
</TextField>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-sm font-medium">计费模式</Label>
|
||||
<Select
|
||||
fullWidth
|
||||
selectedKey={formData.pricingMode}
|
||||
onSelectionChange={(key) =>
|
||||
setFormData((f) => ({
|
||||
...f,
|
||||
pricingMode: String(key) as FormData["pricingMode"],
|
||||
}))
|
||||
}
|
||||
>
|
||||
<Select.Trigger>
|
||||
<Select.Value />
|
||||
<Select.Indicator />
|
||||
</Select.Trigger>
|
||||
<Select.Popover>
|
||||
<ListBox>
|
||||
<ListBox.Item id="fixed">固定电价</ListBox.Item>
|
||||
<ListBox.Item id="tou">峰谷电价</ListBox.Item>
|
||||
</ListBox>
|
||||
</Select.Popover>
|
||||
</Select>
|
||||
</div>
|
||||
{formData.pricingMode === "fixed" && (
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">固定电价(分/kWh)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
placeholder="0"
|
||||
value={formData.feePerKwh}
|
||||
onChange={(e) =>
|
||||
setFormData((f) => ({ ...f, feePerKwh: e.target.value }))
|
||||
}
|
||||
/>
|
||||
</TextField>
|
||||
)}
|
||||
{!isEdit && (
|
||||
<p className="text-xs text-muted">
|
||||
自动注册的充电桩默认状态为 Pending,需手动改为 Accepted 后才可正常上线。
|
||||
@@ -365,7 +398,7 @@ export default function ChargePointsPage() {
|
||||
.filter((c) => c.connectorId > 0)
|
||||
.sort((a, b) => a.connectorId - b.connectorId)
|
||||
.map((conn) => {
|
||||
const url = `${qrOrigin}/dashboard/charge?cpId=${qrTarget.id}&connector=${conn.connectorId}`;
|
||||
const url = `${qrOrigin}/charge?cpId=${qrTarget.id}&connector=${conn.connectorId}`;
|
||||
return (
|
||||
<div
|
||||
key={conn.id}
|
||||
@@ -401,7 +434,7 @@ export default function ChargePointsPage() {
|
||||
<Table.Column isRowHeader>标识符</Table.Column>
|
||||
{isAdmin && <Table.Column>品牌 / 型号</Table.Column>}
|
||||
{isAdmin && <Table.Column>注册状态</Table.Column>}
|
||||
<Table.Column>电价(分/kWh)</Table.Column>
|
||||
<Table.Column>计费模式</Table.Column>
|
||||
<Table.Column>最后发现</Table.Column>
|
||||
<Table.Column>状态</Table.Column>
|
||||
<Table.Column>接口</Table.Column>
|
||||
@@ -482,8 +515,10 @@ export default function ChargePointsPage() {
|
||||
</Chip>
|
||||
</Table.Cell>
|
||||
)}
|
||||
<Table.Cell className="tabular-nums">
|
||||
{cp.feePerKwh > 0 ? (
|
||||
<Table.Cell>
|
||||
{cp.pricingMode === "tou" ? (
|
||||
<span className="text-accent font-medium">峰谷电价</span>
|
||||
) : cp.feePerKwh > 0 ? (
|
||||
<span>
|
||||
{cp.feePerKwh} 分
|
||||
<span className="ml-1 text-xs text-muted">
|
||||
|
||||
@@ -11,6 +11,7 @@ import dayjs from "@/lib/dayjs";
|
||||
import { EvCharger, Plug } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { IdTagCard } from "@/components/id-tag-card";
|
||||
import router from "next/router";
|
||||
|
||||
// ── Status maps (same as charge-points page) ────────────────────────────────
|
||||
|
||||
@@ -333,12 +334,8 @@ function ChargePageContent() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-2xl font-bold text-foreground">充电指令已发送</h2>
|
||||
<p className="text-sm text-muted leading-relaxed">
|
||||
充电桩正在响应,充电将自动开始
|
||||
<br />
|
||||
可在「充电记录」中查看实时进度
|
||||
</p>
|
||||
<h2 className="text-2xl font-bold text-foreground">正在启动中</h2>
|
||||
<p className="text-sm text-muted leading-relaxed">充电桩正在响应,稍候将自动开始</p>
|
||||
</div>
|
||||
<div className="w-full max-w-xs rounded-2xl border border-border bg-surface p-4 text-left space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
@@ -354,10 +351,12 @@ function ChargePageContent() {
|
||||
<span className="font-mono font-medium text-foreground">{selectedIdTag}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button size="lg" onPress={resetAll} className="w-full max-w-xs">
|
||||
<ThunderboltFill className="size-4" />
|
||||
再次充电
|
||||
</Button>
|
||||
<Link href="/dashboard/transactions" className="w-full max-w-xs">
|
||||
<Button size="lg" className="w-full">
|
||||
<ThunderboltFill className="size-4" />
|
||||
充电记录
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -498,7 +497,9 @@ function ChargePageContent() {
|
||||
/{cp.connectors.length} 空闲
|
||||
</span>
|
||||
</span>
|
||||
{cp.feePerKwh > 0 ? (
|
||||
{cp.pricingMode === "tou" ? (
|
||||
<span className="text-sm font-medium text-accent">峰谷电价</span>
|
||||
) : cp.feePerKwh > 0 ? (
|
||||
<span className="text-sm font-medium text-foreground">
|
||||
¥{(cp.feePerKwh / 100).toFixed(2)}
|
||||
<span className="text-xs text-muted font-normal">/kWh</span>
|
||||
|
||||
233
apps/web/app/dashboard/pricing/page.tsx
Normal file
233
apps/web/app/dashboard/pricing/page.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Spinner } from "@heroui/react";
|
||||
import { TagDollar, ChartLine } from "@gravity-ui/icons";
|
||||
import { api, type PriceTier, type TariffConfig, type TariffSlot } from "@/lib/api";
|
||||
|
||||
// ── Tier meta (matches admin pricing editor colors) ───────────────────────────
|
||||
|
||||
const TIER_META: Record<
|
||||
PriceTier,
|
||||
{ label: string; sublabel: string; cellBg: string; text: string; border: string; dot: string }
|
||||
> = {
|
||||
peak: {
|
||||
label: "峰时",
|
||||
sublabel: "高峰时段",
|
||||
cellBg: "bg-orange-500/70",
|
||||
text: "text-orange-500",
|
||||
border: "border-orange-500/40",
|
||||
dot: "bg-orange-500",
|
||||
},
|
||||
flat: {
|
||||
label: "平时",
|
||||
sublabel: "肩峰时段",
|
||||
cellBg: "bg-neutral-400/45",
|
||||
text: "text-neutral-400",
|
||||
border: "border-neutral-400/40",
|
||||
dot: "bg-neutral-400",
|
||||
},
|
||||
valley: {
|
||||
label: "谷时",
|
||||
sublabel: "低谷时段",
|
||||
cellBg: "bg-blue-500/65",
|
||||
text: "text-blue-500",
|
||||
border: "border-blue-500/40",
|
||||
dot: "bg-blue-500",
|
||||
},
|
||||
};
|
||||
|
||||
// ── Slot cards ────────────────────────────────────────────────────────────────
|
||||
|
||||
function SlotCards({ tariff }: { tariff: TariffConfig }) {
|
||||
const sorted = [...tariff.slots].sort((a, b) => a.start - b.start);
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{sorted.map((slot: TariffSlot, i) => {
|
||||
const meta = TIER_META[slot.tier];
|
||||
const p = tariff.prices[slot.tier];
|
||||
const total = p.electricityPrice + p.serviceFee;
|
||||
return (
|
||||
<div key={i} className={`rounded-xl border bg-surface p-4 space-y-3 ${meta.border}`}>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`size-2.5 rounded-sm ${meta.cellBg}`} />
|
||||
<span className={`text-sm font-semibold ${meta.text}`}>{meta.label}</span>
|
||||
<span className="text-xs text-muted">{meta.sublabel}</span>
|
||||
</div>
|
||||
<span className="tabular-nums text-xs font-medium text-muted">
|
||||
{String(slot.start).padStart(2, "0")}:00 – {String(slot.end).padStart(2, "0")}:00
|
||||
</span>
|
||||
</div>
|
||||
{/* Prices */}
|
||||
<div className="divide-y divide-border rounded-lg border border-border overflow-hidden text-sm">
|
||||
<div className="flex divide-x divide-border">
|
||||
<div className="flex-1 flex items-center justify-between bg-surface-secondary px-3 py-2">
|
||||
<span className="text-muted">电费</span>
|
||||
<span className="tabular-nums font-medium text-foreground">
|
||||
¥{p.electricityPrice.toFixed(4)}
|
||||
<span className="text-xs text-muted font-normal">/kWh</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex-1 flex items-center justify-between bg-surface-secondary px-3 py-2">
|
||||
<span className="text-muted">服务费</span>
|
||||
<span className="tabular-nums font-medium text-foreground">
|
||||
¥{p.serviceFee.toFixed(4)}
|
||||
<span className="text-xs text-muted font-normal">/kWh</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between bg-surface px-3 py-2">
|
||||
<span className="font-semibold text-foreground">单价</span>
|
||||
<span className={`tabular-nums font-bold ${meta.text}`}>
|
||||
¥{total.toFixed(4)}
|
||||
<span className="text-xs font-normal">/kWh</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function PricingPage() {
|
||||
const {
|
||||
data: tariff,
|
||||
isLoading,
|
||||
isError,
|
||||
} = useQuery({
|
||||
queryKey: ["tariff"],
|
||||
queryFn: () => api.tariff.get(),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-9 items-center justify-center rounded-xl bg-accent/10">
|
||||
<TagDollar className="size-5 text-accent" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-foreground">电价标准</h1>
|
||||
<p className="text-sm text-muted">今日实行的电价标准</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading && (
|
||||
<div className="flex justify-center py-20">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isError && (
|
||||
<div className="rounded-xl border border-danger/30 bg-danger/5 px-4 py-3 text-sm text-danger">
|
||||
电价信息加载失败,请刷新页面重试。
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !isError && !tariff && (
|
||||
<div className="rounded-2xl border border-border bg-surface px-6 py-12 text-center">
|
||||
<TagDollar className="mx-auto mb-3 size-10 text-muted" />
|
||||
<p className="font-medium text-foreground">尚未配置峰谷电价</p>
|
||||
<p className="mt-1 text-sm text-muted">
|
||||
各充电桩使用独立固定电价,请查看充电桩详情页了解具体费率。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tariff && (
|
||||
<>
|
||||
{/* Timeline + legend */}
|
||||
<div className="rounded-xl border border-border bg-surface-secondary">
|
||||
<div className="flex items-center gap-3 border-b border-border px-5 py-4">
|
||||
<div className="flex size-9 items-center justify-center rounded-lg bg-accent/10">
|
||||
<ChartLine className="size-5 text-accent" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-foreground">24 小时时段分布</p>
|
||||
<p className="text-xs text-muted">实际扣费以交易完成时系统计算为准</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 px-5 py-5">
|
||||
{/* Tick labels */}
|
||||
<div className="relative h-4">
|
||||
{[0, 6, 12, 18, 24].map((h) => (
|
||||
<span
|
||||
key={h}
|
||||
className="absolute text-[10px] tabular-nums text-muted"
|
||||
style={{
|
||||
left: `${(h / 24) * 100}%`,
|
||||
transform:
|
||||
h === 24 ? "translateX(-100%)" : h > 0 ? "translateX(-50%)" : undefined,
|
||||
}}
|
||||
>
|
||||
{String(h).padStart(2, "0")}:00
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Colored bar */}
|
||||
<div className="flex h-12 overflow-hidden rounded-lg">
|
||||
{(() => {
|
||||
const hourTier: PriceTier[] = Array(24).fill("flat" as PriceTier);
|
||||
for (const slot of tariff.slots) {
|
||||
for (let h = slot.start; h < slot.end; h++) hourTier[h] = slot.tier;
|
||||
}
|
||||
return hourTier.map((tier, h) => (
|
||||
<div
|
||||
key={h}
|
||||
className={`flex-1 ${TIER_META[tier].cellBg} transition-opacity hover:opacity-100 opacity-90 flex items-center justify-center`}
|
||||
title={`${String(h).padStart(2, "0")}:00 — ${TIER_META[tier].label}`}
|
||||
>
|
||||
<span className="hidden text-[10px] font-semibold text-white drop-shadow lg:block">
|
||||
{String(h).padStart(2, "0")}
|
||||
</span>
|
||||
</div>
|
||||
));
|
||||
})()}
|
||||
</div>
|
||||
|
||||
{/* Legend */}
|
||||
<div className="flex flex-wrap items-center gap-3 gap-y-1 pt-0.5">
|
||||
{(["peak", "flat", "valley"] as PriceTier[]).map((tier) => {
|
||||
const meta = TIER_META[tier];
|
||||
const hours = tariff.slots
|
||||
.filter((s) => s.tier === tier)
|
||||
.reduce((acc, s) => acc + (s.end - s.start), 0);
|
||||
const total =
|
||||
tariff.prices[tier].electricityPrice + tariff.prices[tier].serviceFee;
|
||||
return (
|
||||
<div key={tier} className="flex items-center gap-1.5">
|
||||
<span className={`size-3 rounded-sm ${meta.cellBg}`} />
|
||||
<span className="text-xs text-muted">
|
||||
<span className={`font-semibold ${meta.text}`}>{meta.label}</span>
|
||||
<span className="ml-1 text-muted/70">
|
||||
{hours}h · ¥{total.toFixed(4)}/kWh
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Slot cards */}
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-foreground">各时段费率</h2>
|
||||
<SlotCards tariff={tariff} />
|
||||
<p className="text-xs text-muted">
|
||||
合计费率 = 电费 + 服务费。实际扣费以交易完成时系统计算为准。
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback, useEffect, useRef } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Button, Input, Label, Spinner, TextField, toast } from "@heroui/react";
|
||||
import { TagDollar, Lock, ArrowRotateRight, ChartLine } from "@gravity-ui/icons";
|
||||
// TagDollar is used in the page header badge
|
||||
import { useSession } from "@/lib/auth-client";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Types (designed for future backend API integration)
|
||||
@@ -155,6 +157,14 @@ const DEFAULT_PRICES: Record<PriceTier, TierPricing> = {
|
||||
export default function PricingPage() {
|
||||
const { data: session } = useSession();
|
||||
const isAdmin = session?.user?.role === "admin";
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Load current tariff from API
|
||||
const { data: remoteTariff, isLoading: loadingTariff } = useQuery({
|
||||
queryKey: ["tariff"],
|
||||
queryFn: () => api.tariff.get(),
|
||||
enabled: isAdmin,
|
||||
});
|
||||
|
||||
const [schedule, setSchedule] = useState<PriceTier[]>([...DEFAULT_SCHEDULE]);
|
||||
|
||||
@@ -176,6 +186,26 @@ export default function PricingPage() {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [showPayload, setShowPayload] = useState(false);
|
||||
|
||||
// Populate state once remote tariff loads
|
||||
useEffect(() => {
|
||||
if (!remoteTariff) return;
|
||||
// Reconstruct 24-element schedule from slots
|
||||
const s: PriceTier[] = [];
|
||||
for (let i = 0; i < 24; i++) s.push("flat");
|
||||
for (const slot of remoteTariff.slots) {
|
||||
for (let h = slot.start; h < slot.end; h++) s[h] = slot.tier as PriceTier;
|
||||
}
|
||||
setSchedule(s);
|
||||
const p = remoteTariff.prices as Record<PriceTier, TierPricing>;
|
||||
setPrices(p);
|
||||
setPriceStrings({
|
||||
peak: toStrings(p.peak),
|
||||
valley: toStrings(p.valley),
|
||||
flat: toStrings(p.flat),
|
||||
});
|
||||
setIsDirty(false);
|
||||
}, [remoteTariff]);
|
||||
|
||||
// ── Drag state via ref (avoids stale closures in global handler) ─────────
|
||||
const dragRef = useRef({
|
||||
active: false,
|
||||
@@ -239,14 +269,16 @@ export default function PricingPage() {
|
||||
setIsDirty(false);
|
||||
};
|
||||
|
||||
// ── Save (stub: simulates API call) ─────────────────────────────────────
|
||||
// ── Save ──────────────────────────────────────────────────────────────────────
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
// Future: await apiFetch("/api/tariff", { method: "PUT", body: JSON.stringify(apiPayload) })
|
||||
await new Promise<void>((r) => setTimeout(r, 700));
|
||||
await api.tariff.put({ slots, prices });
|
||||
setIsDirty(false);
|
||||
queryClient.invalidateQueries({ queryKey: ["tariff"] });
|
||||
toast.success("电价配置已保存");
|
||||
} catch {
|
||||
toast.warning("保存失败,请稍候重试");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -269,6 +301,14 @@ export default function PricingPage() {
|
||||
);
|
||||
}
|
||||
|
||||
if (loadingTariff) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-24">
|
||||
<Spinner size="lg" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6">
|
||||
{/* ── Page header ───────────────────────────────────────────────────── */}
|
||||
@@ -479,28 +519,6 @@ export default function PricingPage() {
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* ── API Payload preview ───────────────────────────────────────────── */}
|
||||
<div className="overflow-hidden rounded-xl border border-border bg-surface-secondary">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center justify-between px-5 py-4 text-left transition-colors hover:bg-surface-tertiary"
|
||||
onClick={() => setShowPayload((v) => !v)}
|
||||
>
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-foreground">API 载荷预览</p>
|
||||
<p className="text-xs text-muted">等效的后端 PUT /api/tariff 请求体</p>
|
||||
</div>
|
||||
<span className="shrink-0 text-xs text-muted">{showPayload ? "收起 ▲" : "展开 ▼"}</span>
|
||||
</button>
|
||||
{showPayload && (
|
||||
<div className="border-t border-border px-5 py-4">
|
||||
<pre className="overflow-x-auto rounded-lg bg-surface-tertiary p-4 text-xs leading-5 text-foreground">
|
||||
{JSON.stringify(apiPayload, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Actions ───────────────────────────────────────────────────────── */}
|
||||
<div className="flex items-center justify-between pb-2">
|
||||
<Button variant="danger-soft" size="sm" onPress={handleReset} isDisabled={saving}>
|
||||
|
||||
@@ -20,19 +20,20 @@ import { useSession } from "@/lib/auth-client";
|
||||
|
||||
const chargeItems = [
|
||||
{ href: "/dashboard/charge", label: "立即充电", icon: ThunderboltFill, adminOnly: false },
|
||||
{ href: "/dashboard/pricing", label: "电价标准", icon: TagDollar, adminOnly: false },
|
||||
];
|
||||
|
||||
const navItems = [
|
||||
{ href: "/dashboard", label: "概览", icon: Thunderbolt, exact: true, adminOnly: false },
|
||||
{ href: "/dashboard/charge-points", label: "充电桩", icon: PlugConnection, adminOnly: false },
|
||||
{ href: "/dashboard/transactions", label: "充电记录", icon: ListCheck, adminOnly: false },
|
||||
{ href: "/dashboard/id-tags", label: "储值卡", icon: CreditCard, adminOnly: false },
|
||||
{ href: "/dashboard/transactions", label: "充电记录", icon: ListCheck, adminOnly: false },
|
||||
{ href: "/dashboard/settings/pricing", label: "峰谷电价", icon: TagDollar, adminOnly: true },
|
||||
{ href: "/dashboard/users", label: "用户管理", icon: Person, adminOnly: true },
|
||||
];
|
||||
|
||||
const settingsItems = [
|
||||
{ href: "/dashboard/settings/user", label: "账号设置", icon: Gear, adminOnly: false },
|
||||
{ href: "/dashboard/settings/pricing", label: "峰谷电价", icon: TagDollar, adminOnly: true },
|
||||
];
|
||||
|
||||
function NavContent({
|
||||
@@ -114,27 +115,29 @@ function NavContent({
|
||||
<p className="mb-1 mt-3 px-2 text-[11px] font-semibold uppercase tracking-widest text-muted">
|
||||
设置
|
||||
</p>
|
||||
{settingsItems.filter((item) => !item.adminOnly || isAdmin).map((item) => {
|
||||
const isActive = pathname === item.href || pathname.startsWith(item.href + "/");
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
onClick={onNavigate}
|
||||
className={[
|
||||
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
|
||||
isActive
|
||||
? "bg-accent/10 text-accent"
|
||||
: "text-muted hover:bg-surface-tertiary hover:text-foreground",
|
||||
].join(" ")}
|
||||
>
|
||||
<Icon className="size-4 shrink-0" />
|
||||
<span>{item.label}</span>
|
||||
{isActive && <span className="ml-auto h-1.5 w-1.5 rounded-full bg-accent" />}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
{settingsItems
|
||||
.filter((item) => !item.adminOnly || isAdmin)
|
||||
.map((item) => {
|
||||
const isActive = pathname === item.href || pathname.startsWith(item.href + "/");
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
onClick={onNavigate}
|
||||
className={[
|
||||
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
|
||||
isActive
|
||||
? "bg-accent/10 text-accent"
|
||||
: "text-muted hover:bg-surface-tertiary hover:text-foreground",
|
||||
].join(" ")}
|
||||
>
|
||||
<Icon className="size-4 shrink-0" />
|
||||
<span>{item.label}</span>
|
||||
{isActive && <span className="ml-auto h-1.5 w-1.5 rounded-full bg-accent" />}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* Footer */}
|
||||
|
||||
@@ -77,6 +77,7 @@ export type ChargePoint = {
|
||||
lastHeartbeatAt: string | null;
|
||||
lastBootNotificationAt: string | null;
|
||||
feePerKwh: number;
|
||||
pricingMode: "fixed" | "tou";
|
||||
connectors: ConnectorSummary[];
|
||||
chargePointStatus: string | null;
|
||||
chargePointErrorCode: string | null;
|
||||
@@ -98,6 +99,7 @@ export type ChargePointDetail = {
|
||||
lastHeartbeatAt: string | null;
|
||||
lastBootNotificationAt: string | null;
|
||||
feePerKwh: number;
|
||||
pricingMode: "fixed" | "tou";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
connectors: ConnectorDetail[];
|
||||
@@ -121,6 +123,8 @@ export type Transaction = {
|
||||
stopIdTag: string | null;
|
||||
stopReason: string | null;
|
||||
chargeAmount: number | null;
|
||||
electricityFee: number | null;
|
||||
serviceFee: number | null;
|
||||
};
|
||||
|
||||
export type IdTag = {
|
||||
@@ -154,6 +158,29 @@ export type PaginatedTransactions = {
|
||||
totalPages: number;
|
||||
};
|
||||
|
||||
export type PriceTier = "peak" | "valley" | "flat";
|
||||
|
||||
export type TariffSlot = {
|
||||
start: number;
|
||||
end: number;
|
||||
tier: PriceTier;
|
||||
};
|
||||
|
||||
export type TierPricing = {
|
||||
/** 电价(元/kWh) */
|
||||
electricityPrice: number;
|
||||
/** 服务费(元/kWh) */
|
||||
serviceFee: number;
|
||||
};
|
||||
|
||||
export type TariffConfig = {
|
||||
id?: string;
|
||||
slots: TariffSlot[];
|
||||
prices: Record<PriceTier, TierPricing>;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
};
|
||||
|
||||
// ── API functions ──────────────────────────────────────────────────────────
|
||||
|
||||
export type ChartRange = "30d" | "7d" | "24h";
|
||||
@@ -181,6 +208,7 @@ export const api = {
|
||||
chargePointModel?: string;
|
||||
registrationStatus?: "Accepted" | "Pending" | "Rejected";
|
||||
feePerKwh?: number;
|
||||
pricingMode?: "fixed" | "tou";
|
||||
}) =>
|
||||
apiFetch<ChargePoint>("/api/charge-points", {
|
||||
method: "POST",
|
||||
@@ -190,6 +218,7 @@ export const api = {
|
||||
id: string,
|
||||
data: {
|
||||
feePerKwh?: number;
|
||||
pricingMode?: "fixed" | "tou";
|
||||
registrationStatus?: "Accepted" | "Pending" | "Rejected";
|
||||
chargePointVendor?: string;
|
||||
chargePointModel?: string;
|
||||
@@ -287,4 +316,9 @@ export const api = {
|
||||
create: (data: { name: string; email: string; username: string; password: string }) =>
|
||||
apiFetch<{ success: boolean }>("/api/setup", { method: "POST", body: JSON.stringify(data) }),
|
||||
},
|
||||
tariff: {
|
||||
get: () => apiFetch<TariffConfig | null>("/api/tariff"),
|
||||
put: (data: { slots: TariffSlot[]; prices: Record<PriceTier, TierPricing> }) =>
|
||||
apiFetch<TariffConfig>("/api/tariff", { method: "PUT", body: JSON.stringify(data) }),
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user