Compare commits

...
4 Commits
5 changed files with 402 additions and 54 deletions
+248
View File
@@ -0,0 +1,248 @@
"use client"
import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
type AdminRecordItem = {
id: string
timestamp: string
sampleCount: number
duration: number
}
function toLocalInputValue(iso: string): string {
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return ''
const pad = (n: number) => n.toString().padStart(2, '0')
const year = d.getFullYear()
const month = pad(d.getMonth() + 1)
const day = pad(d.getDate())
const hour = pad(d.getHours())
const minute = pad(d.getMinutes())
const second = pad(d.getSeconds())
return `${year}-${month}-${day}T${hour}:${minute}:${second}`
}
export default function AdminClient({
initialData,
currentPage,
pageSize,
totalPages,
}: {
initialData: AdminRecordItem[]
currentPage: number
pageSize: number
totalPages: number
}) {
const router = useRouter()
const [data, setData] = useState(initialData)
const [selected, setSelected] = useState<Set<string>>(new Set())
const [editingTimes, setEditingTimes] = useState<Record<string, string>>(() => {
const initial: Record<string, string> = {}
for (const r of initialData) {
initial[r.id] = toLocalInputValue(r.timestamp)
}
return initial
})
const [dirty, setDirty] = useState<Record<string, boolean>>({})
function toggleSelect(id: string) {
setSelected((prev) => {
const next = new Set(prev)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
function selectAllCurrent() {
setSelected(new Set(data.map((d) => d.id)))
}
function clearSelection() {
setSelected(new Set())
}
async function handleBatchDelete() {
if (selected.size === 0) return
if (!confirm(`确定要删除选中的 ${selected.size} 条记录吗?`)) return
try {
const res = await fetch('/api/records/batch', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ action: 'delete', ids: Array.from(selected) }),
})
if (!res.ok) throw new Error('批量删除失败')
const j = await res.json()
const deletedIds: string[] = j.deletedIds || []
setData((prev) => prev.filter((r) => !deletedIds.includes(r.id)))
clearSelection()
} catch {
alert('批量删除失败')
}
}
function setNowFor(id: string) {
const now = new Date()
const isoLocal = toLocalInputValue(now.toISOString())
setEditingTimes((prev) => ({ ...prev, [id]: isoLocal }))
setDirty((prev) => ({ ...prev, [id]: true }))
}
function shiftMinutes(id: string, minutes: number) {
setEditingTimes((prev) => {
const current = prev[id]
const base = current ? new Date(current) : new Date()
if (Number.isNaN(base.getTime())) return prev
const shifted = new Date(base.getTime() + minutes * 60 * 1000)
const isoLocal = toLocalInputValue(shifted.toISOString())
return { ...prev, [id]: isoLocal }
})
setDirty((prev) => ({ ...prev, [id]: true }))
}
async function applyTime(id: string) {
const input = editingTimes[id]
if (!input) {
alert('请输入时间')
return
}
const dt = new Date(input)
if (Number.isNaN(dt.getTime())) {
alert('时间格式不正确')
return
}
try {
const res = await fetch('/api/records/batch', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ action: 'updateTimestamp', ids: [id], timestamp: dt.toISOString() }),
})
if (!res.ok) throw new Error('修改时间失败')
const j = await res.json()
const updated: { id: string; timestamp: string }[] = j.updated || []
if (!updated.length) return
const { timestamp } = updated[0]
setData((prev) => prev.map((r) => (r.id === id ? { ...r, timestamp } : r)))
setEditingTimes((prev) => ({ ...prev, [id]: toLocalInputValue(timestamp) }))
setDirty((prev) => ({ ...prev, [id]: false }))
} catch {
alert('修改时间失败')
}
}
function goToPage(page: number) {
const params = new URLSearchParams()
params.set('page', String(page))
params.set('pageSize', String(pageSize))
router.push(`/admin?${params.toString()}`)
}
return (
<div className="min-h-screen bg-zinc-50 text-zinc-900 dark:bg-black dark:text-zinc-100">
<div className="mx-auto max-w-6xl p-2 sm:p-6">
<header className="mb-4 flex items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-semibold">Admin 面板</h1>
<p className="mt-1 text-xs text-zinc-500">批量删除记录,批量修改时间等维护操作</p>
</div>
<Link href="/" className="rounded border px-3 py-1.5 text-sm">← 返回首页</Link>
</header>
<section className="mb-4 flex flex-wrap items-center gap-3 rounded border border-zinc-200 bg-white p-3 text-sm dark:border-zinc-800 dark:bg-zinc-950">
<div className="flex items-center gap-2">
<button onClick={selectAllCurrent} className="rounded border px-2 py-1">全选当前页</button>
<button onClick={clearSelection} className="rounded border px-2 py-1">清空选择</button>
<span className="text-xs text-zinc-500">已选 {selected.size} 条</span>
</div>
<div className="flex items-center gap-2">
<button onClick={handleBatchDelete} className="rounded bg-red-600 px-3 py-1 text-white disabled:opacity-50" disabled={selected.size === 0}>批量删除</button>
</div>
</section>
<section className="rounded border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950">
<div className="hidden items-center justify-between border-b px-3 py-2 text-xs text-zinc-500 dark:border-zinc-800 sm:flex">
<div className="flex items-center gap-2">
<span className="w-8 text-center">选中</span>
<span className="w-40">ID</span>
<span className="w-72">时间 / 编辑</span>
<span className="w-24 text-right">采样点数</span>
</div>
</div>
{data.length === 0 && (
<div className="px-3 py-3 text-sm text-zinc-500">暂无数据</div>
)}
<div className="divide-y text-sm dark:divide-zinc-800">
{data.map((r) => (
<div key={r.id} className="border-b px-3 py-2 text-xs last:border-b-0 dark:border-zinc-800">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<input
type="checkbox"
checked={selected.has(r.id)}
onChange={() => toggleSelect(r.id)}
className="h-4 w-4"
/>
<span className="max-w-[200px] truncate font-mono sm:w-40">{r.id}</span>
</div>
<div className="hidden items-center gap-2 sm:flex">
<span className="text-[11px] text-zinc-500">{new Date(r.timestamp).toLocaleString()}</span>
<span className="w-16 text-right text-[11px] text-zinc-500">{r.sampleCount}</span>
</div>
<Link href={`/records/${r.id}`} className="text-[11px] text-blue-600 hover:underline dark:text-blue-400">详情</Link>
</div>
<div className="mt-1 flex flex-col gap-1 sm:mt-1 sm:flex-row sm:items-center sm:gap-2">
<div
className={`flex flex-1 items-center gap-1 rounded border px-1 py-0.5 ${dirty[r.id] ? 'border-amber-400 bg-amber-50 dark:border-amber-500 dark:bg-amber-900/30' : 'border-zinc-300 bg-white dark:border-zinc-700 dark:bg-zinc-900'}`}
>
<input
type="datetime-local"
value={editingTimes[r.id] || ''}
onChange={(e) => {
const v = e.target.value
setEditingTimes((prev) => ({ ...prev, [r.id]: v }))
const original = toLocalInputValue(r.timestamp)
setDirty((prev) => ({ ...prev, [r.id]: v !== original }))
}}
className="w-full bg-transparent text-[11px] outline-none"
/>
</div>
<div className="mt-1 flex flex-wrap gap-1 sm:mt-0 sm:flex-none sm:justify-start justify-end">
<button
onClick={() => {
const original = toLocalInputValue(r.timestamp)
setEditingTimes((prev) => ({ ...prev, [r.id]: original }))
setDirty((prev) => ({ ...prev, [r.id]: false }))
}}
className="rounded border px-2 py-1 text-[11px]"
>重置</button>
<button onClick={() => setNowFor(r.id)} className="rounded border px-2 py-1 text-[11px]">现在</button>
<button onClick={() => shiftMinutes(r.id, 1)} className="rounded border px-2 py-1 text-[11px]">+1min</button>
<button onClick={() => shiftMinutes(r.id, 10)} className="rounded border px-2 py-1 text-[11px]">+10min</button>
<button onClick={() => applyTime(r.id)} className="rounded bg-zinc-900 px-3 py-1 text-[11px] text-white dark:bg-zinc-100 dark:text-black">应用</button>
</div>
</div>
<div className="mt-1 text-[11px] text-zinc-500 sm:hidden">
时长 {r.duration} · 点数 {r.sampleCount}
</div>
</div>
))}
</div>
<div className="flex items-center justify-center gap-4 border-t px-3 py-2 text-sm dark:border-zinc-800">
<button
className="rounded border px-3 py-1.5 disabled:opacity-50"
onClick={() => goToPage(Math.max(1, currentPage - 1))}
disabled={currentPage <= 1}
>上一页</button>
<div className="text-xs">{currentPage} / {totalPages}</div>
<button
className="rounded border px-3 py-1.5 disabled:opacity-50"
onClick={() => goToPage(Math.min(totalPages, currentPage + 1))}
disabled={currentPage >= totalPages}
>下一页</button>
</div>
</section>
</div>
</div>
)
}
+46
View File
@@ -0,0 +1,46 @@
import { prisma } from '@/src/lib/prisma'
import AdminClient from './AdminClient'
type AdminRecordItem = {
id: string
timestamp: string
sampleCount: number
duration: number
}
export default async function AdminPage({
searchParams,
}: {
searchParams: Promise<{ page?: string; pageSize?: string }>
}) {
const params = await searchParams
const page = Math.max(1, parseInt(params.page || '1', 10) || 1)
const pageSizeRaw = parseInt(params.pageSize || '50', 10) || 50
const pageSize = Math.min(100, Math.max(1, pageSizeRaw))
const [total, rows] = await Promise.all([
prisma.recording.count(),
prisma.recording.findMany({
orderBy: { timestamp: 'desc' },
skip: (page - 1) * pageSize,
take: pageSize,
select: {
id: true,
timestamp: true,
sample_count: true,
duration: true,
},
}),
])
const data: AdminRecordItem[] = rows.map((r) => ({
id: r.id,
timestamp: r.timestamp.toISOString(),
sampleCount: r.sample_count,
duration: r.duration,
}))
const totalPages = Math.max(1, Math.ceil(total / pageSize))
return <AdminClient initialData={data} currentPage={page} pageSize={pageSize} totalPages={totalPages} />
}
+9 -6
View File
@@ -48,20 +48,23 @@ export async function POST(req: NextRequest) {
})
}
// CSV
let csv = 'recordId,timestamp,index,timeSec,code,force\n'
// CSV(去掉 recordId、timestamp,timeSec 改为毫秒单位)
let csv = 'index,timeMs,code,force\n'
for (const r of rows) {
let step = r.sample_count > 0 ? r.duration / r.sample_count : 0
// 以毫秒为单位的步长
let stepMs = r.sample_count > 0 ? (r.duration * 1000) / r.sample_count : 0
if (r.rec_start_ms != null && r.rec_end_ms != null && r.sample_count > 0) {
const dtMs = Number((r.rec_end_ms as bigint) - (r.rec_start_ms as bigint))
if (Number.isFinite(dtMs) && dtMs > 0) step = dtMs / 1000 / r.sample_count
if (Number.isFinite(dtMs) && dtMs > 0) stepMs = dtMs / r.sample_count
}
// 采样溢出时强制 1ms 步长(与 16.384s/16384 对齐)
if (r.sample_count >= 16384) stepMs = 1
const hasFit = r.fit_a != null
for (let i = 0; i < r.code_data.length; i++) {
const t = (i * step).toFixed(6)
const t = (i * stepMs).toFixed(3)
const code = r.code_data[i]
const force = hasFit ? r.fit_a! * code + (r.fit_b ?? 0) : ''
csv += `${r.id},${new Date(r.timestamp).toISOString()},${i},${t},${code},${hasFit ? force : ''}\n`
csv += `${i},${t},${code},${hasFit ? force : ''}\n`
}
}
return new Response(csv, {
+50
View File
@@ -0,0 +1,50 @@
import { NextRequest } from 'next/server'
import { prisma } from '@/src/lib/prisma'
import { isAuthorizedDelete } from '@/src/lib/utils'
type BatchBody =
| { action: 'delete'; ids: string[] }
| { action: 'updateTimestamp'; ids: string[]; timestamp: string }
export async function POST(req: NextRequest) {
try {
if (!isAuthorizedDelete(req)) {
return Response.json({ error: 'unauthorized' }, { status: 401 })
}
const body = (await req.json()) as BatchBody
if (!body || !Array.isArray((body as any).ids) || (body as any).ids.length === 0) {
return Response.json({ error: 'ids required' }, { status: 400 })
}
const ids = (body as any).ids as string[]
if (body.action === 'delete') {
const result = await prisma.recording.deleteMany({ where: { id: { in: ids } } })
return Response.json({ success: true, deletedCount: result.count, deletedIds: ids })
}
if (body.action === 'updateTimestamp') {
const ts = new Date(body.timestamp)
if (Number.isNaN(ts.getTime())) {
return Response.json({ error: 'invalid timestamp' }, { status: 400 })
}
await prisma.recording.updateMany({ where: { id: { in: ids } }, data: { timestamp: ts } })
const updated = await prisma.recording.findMany({
where: { id: { in: ids } },
select: { id: true, timestamp: true },
})
return Response.json({
success: true,
updated: updated.map((r) => ({ id: r.id, timestamp: r.timestamp.toISOString() })),
})
}
return Response.json({ error: 'unsupported action' }, { status: 400 })
} catch (err) {
console.error(err)
return Response.json({ error: 'internal error' }, { status: 500 })
}
}
+28 -27
View File
@@ -45,15 +45,14 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
const [error, setError] = useState<string | null>(null)
const [rec, setRec] = useState<Detail | null>(null)
// 滤波相关状态
const [filterType, setFilterType] = useState<'none' | 'ema' | 'sg' | 'hampel_sg' | 'gauss'>('hampel_sg')
const [filterType, setFilterType] = useState<'none' | 'ema' | 'sg' | 'hampel_sg' | 'gauss'>('ema')
const [emaAlpha, setEmaAlpha] = useState(0.01)
const [sgWindow, setSgWindow] = useState(21)
const [sgOrder, setSgOrder] = useState<2 | 3>(3)
const [hampelWindow, setHampelWindow] = useState(11)
const [hampelK, setHampelK] = useState(2)
const [gaussSigma, setGaussSigma] = useState(5)
const [showOriginal, setShowOriginal] = useState(false)
const [showFiltered, setShowFiltered] = useState(true)
// 图例控制显示,不再使用自定义 checkbox;默认隐藏在数据集上配置
useEffect(() => {
const controller = new AbortController()
@@ -76,10 +75,7 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
return () => controller.abort()
}, [id])
// 若存在拟合,默认不显示滤波码值(仅在记录加载时初始化一次)
useEffect(() => {
if (rec?.fit) setShowFiltered(false)
}, [rec?.fit])
// 显示策略改由 Chart.js 图例控制,默认隐藏在数据集 hidden 字段中设置
// 侦测小屏(手机)以调整 Chart 布局
const [isSmall, setIsSmall] = useState(false)
@@ -121,7 +117,10 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
const timeAxis = useMemo(() => {
if (!rec) return [] as number[]
const step = rec.sampleCount > 0 ? (rec.duration * 1000) / rec.sampleCount : 0
// 使用秒为单位,保留3位小数;若采样溢出,固定为 16.384s
const overflow = rec.sampleCount >= 16384
const effectiveDuration = overflow ? 16.384 : rec.duration
const step = rec.sampleCount > 0 ? effectiveDuration / rec.sampleCount : 0
return Array.from({ length: rec.sampleCount }, (_, i) => +(i * step).toFixed(3))
}, [rec])
@@ -201,7 +200,23 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
</div>
<div className="rounded-lg border p-3 sm:p-4 dark:border-zinc-800">
<div className="text-sm text-zinc-500">采样</div>
<div className="mt-1 text-lg">{rec.sampleCount} 点 · {rec.duration.toFixed(3)} s · {(rec.sampleCount / rec.duration).toFixed(2)} Hz</div>
{(() => {
const overflow = rec.sampleCount >= 16384
const effectiveDuration = overflow ? 16.384 : rec.duration
const hz = effectiveDuration > 0 ? (rec.sampleCount / effectiveDuration) : 0
return (
<div className="mt-1 text-lg">
{rec.sampleCount} 点 ·{' '}
<span
className={overflow ? 'text-red-600 dark:text-red-400' : ''}
title={overflow ? '采样溢出,时间将不准确' : undefined}
>
{effectiveDuration.toFixed(3)} s
</span>
{' '}· {hz.toFixed(2)} Hz
</div>
)
})()}
</div>
<div className="rounded-lg border p-3 sm:p-4 dark:border-zinc-800">
<div className="text-sm text-zinc-500">拟合</div>
@@ -351,15 +366,7 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
</label>
)}
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" className="rounded" checked={showFiltered} onChange={(e) => setShowFiltered(e.target.checked)} />
<span>显示滤波码值</span>
</label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" className="rounded" checked={showOriginal} onChange={(e) => setShowOriginal(e.target.checked)} />
<span>叠加原始</span>
</label>
{/* 由 Chart.js 图例控制数据集显示,不再使用本地 checkbox */}
<span className="hidden text-xs text-zinc-500 sm:inline">按 Ctrl+滚轮 缩放,拖拽平移</span>
</div>
@@ -369,8 +376,6 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
data={{
labels: timeAxis,
datasets: [
...(showOriginal && rec
? [
{
type: 'line' as const,
label: '原始码值',
@@ -381,11 +386,8 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
borderWidth: 1,
yAxisID: 'yCode',
pointRadius: 0,
hidden: true, // 默认不显示原始
},
]
: []),
...(showFiltered
? [
{
type: 'line' as const,
label: '滤波码值',
@@ -395,9 +397,8 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
borderWidth: 1.5,
yAxisID: 'yCode',
pointRadius: 0,
hidden: Boolean(rec?.fit), // 存在拟合时默认不显示滤波码值
},
]
: []),
...(rec.fit && forceSeries
? [
{
@@ -431,7 +432,7 @@ export default function Page({ params }: { params: Promise<{ id: string }> }) {
},
},
scales: {
x: { title: { display: !isSmall, text: '时间 (ms)' }, ticks: { maxRotation: 0, font: { size: isSmall ? 10 : 12 } } },
x: { title: { display: !isSmall, text: '时间 (s)' }, ticks: { maxRotation: 0, font: { size: isSmall ? 10 : 12 } } },
yCode: { type: 'linear' as const, position: 'left' as const, title: { display: !isSmall, text: '码值' }, ticks: { font: { size: isSmall ? 10 : 12 } } },
yForce: { type: 'linear' as const, position: 'right' as const, title: { display: !isSmall, text: '力值 (mN)' }, grid: { drawOnChartArea: false }, ticks: { font: { size: isSmall ? 10 : 12 } } },
},